27 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
28 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
29 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
30 #define SSH1_CMSG_USER 4 /* 0x4 */
31 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
32 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
33 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
34 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
35 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
36 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
37 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
38 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
39 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
40 #define SSH1_SMSG_FAILURE 15 /* 0xf */
41 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
42 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
43 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
44 #define SSH1_CMSG_EOF 19 /* 0x13 */
45 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
46 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
47 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
48 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
49 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
50 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
51 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
52 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
53 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
54 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
55 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
56 #define SSH1_MSG_IGNORE 32 /* 0x20 */
57 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
58 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
59 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
60 #define SSH1_MSG_DEBUG 36 /* 0x24 */
61 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
62 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
63 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
64 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
65 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
66 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
67 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
69 #define SSH1_AUTH_RHOSTS 1 /* 0x1 */
70 #define SSH1_AUTH_RSA 2 /* 0x2 */
71 #define SSH1_AUTH_PASSWORD 3 /* 0x3 */
72 #define SSH1_AUTH_RHOSTS_RSA 4 /* 0x4 */
73 #define SSH1_AUTH_TIS 5 /* 0x5 */
74 #define SSH1_AUTH_CCARD 16 /* 0x10 */
76 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
77 /* Mask for protoflags we will echo back to server if seen */
78 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
80 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
81 #define SSH2_MSG_IGNORE 2 /* 0x2 */
82 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
83 #define SSH2_MSG_DEBUG 4 /* 0x4 */
84 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
85 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
86 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
87 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
88 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
89 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
90 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
91 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
92 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
93 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
94 #define SSH2_MSG_KEXRSA_PUBKEY 30 /* 0x1e */
95 #define SSH2_MSG_KEXRSA_SECRET 31 /* 0x1f */
96 #define SSH2_MSG_KEXRSA_DONE 32 /* 0x20 */
97 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
98 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
99 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
100 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
101 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
102 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
103 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
104 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
105 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
106 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
107 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
108 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
109 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
110 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
111 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
112 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
113 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
114 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
115 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
116 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
117 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
118 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
119 #define SSH2_MSG_USERAUTH_GSSAPI_RESPONSE 60
120 #define SSH2_MSG_USERAUTH_GSSAPI_TOKEN 61
121 #define SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE 63
122 #define SSH2_MSG_USERAUTH_GSSAPI_ERROR 64
123 #define SSH2_MSG_USERAUTH_GSSAPI_ERRTOK 65
124 #define SSH2_MSG_USERAUTH_GSSAPI_MIC 66
127 * Packet type contexts, so that ssh2_pkt_type can correctly decode
128 * the ambiguous type numbers back into the correct type strings.
138 SSH2_PKTCTX_PUBLICKEY,
139 SSH2_PKTCTX_PASSWORD,
144 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
145 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
146 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
147 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
148 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
149 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
150 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
151 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
152 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
153 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
154 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
155 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
156 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
157 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
158 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
160 static const char *const ssh2_disconnect_reasons[] = {
162 "host not allowed to connect",
164 "key exchange failed",
165 "host authentication failed",
168 "service not available",
169 "protocol version not supported",
170 "host key not verifiable",
173 "too many connections",
174 "auth cancelled by user",
175 "no more auth methods available",
179 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
180 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
181 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
182 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
184 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
187 * Various remote-bug flags.
189 #define BUG_CHOKES_ON_SSH1_IGNORE 1
190 #define BUG_SSH2_HMAC 2
191 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
192 #define BUG_CHOKES_ON_RSA 8
193 #define BUG_SSH2_RSA_PADDING 16
194 #define BUG_SSH2_DERIVEKEY 32
195 #define BUG_SSH2_REKEY 64
196 #define BUG_SSH2_PK_SESSIONID 128
197 #define BUG_SSH2_MAXPKT 256
198 #define BUG_CHOKES_ON_SSH2_IGNORE 512
201 * Codes for terminal modes.
202 * Most of these are the same in SSH-1 and SSH-2.
203 * This list is derived from RFC 4254 and
206 static const struct {
207 const char* const mode;
209 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
211 /* "V" prefix discarded for special characters relative to SSH specs */
212 { "INTR", 1, TTY_OP_CHAR },
213 { "QUIT", 2, TTY_OP_CHAR },
214 { "ERASE", 3, TTY_OP_CHAR },
215 { "KILL", 4, TTY_OP_CHAR },
216 { "EOF", 5, TTY_OP_CHAR },
217 { "EOL", 6, TTY_OP_CHAR },
218 { "EOL2", 7, TTY_OP_CHAR },
219 { "START", 8, TTY_OP_CHAR },
220 { "STOP", 9, TTY_OP_CHAR },
221 { "SUSP", 10, TTY_OP_CHAR },
222 { "DSUSP", 11, TTY_OP_CHAR },
223 { "REPRINT", 12, TTY_OP_CHAR },
224 { "WERASE", 13, TTY_OP_CHAR },
225 { "LNEXT", 14, TTY_OP_CHAR },
226 { "FLUSH", 15, TTY_OP_CHAR },
227 { "SWTCH", 16, TTY_OP_CHAR },
228 { "STATUS", 17, TTY_OP_CHAR },
229 { "DISCARD", 18, TTY_OP_CHAR },
230 { "IGNPAR", 30, TTY_OP_BOOL },
231 { "PARMRK", 31, TTY_OP_BOOL },
232 { "INPCK", 32, TTY_OP_BOOL },
233 { "ISTRIP", 33, TTY_OP_BOOL },
234 { "INLCR", 34, TTY_OP_BOOL },
235 { "IGNCR", 35, TTY_OP_BOOL },
236 { "ICRNL", 36, TTY_OP_BOOL },
237 { "IUCLC", 37, TTY_OP_BOOL },
238 { "IXON", 38, TTY_OP_BOOL },
239 { "IXANY", 39, TTY_OP_BOOL },
240 { "IXOFF", 40, TTY_OP_BOOL },
241 { "IMAXBEL", 41, TTY_OP_BOOL },
242 { "ISIG", 50, TTY_OP_BOOL },
243 { "ICANON", 51, TTY_OP_BOOL },
244 { "XCASE", 52, TTY_OP_BOOL },
245 { "ECHO", 53, TTY_OP_BOOL },
246 { "ECHOE", 54, TTY_OP_BOOL },
247 { "ECHOK", 55, TTY_OP_BOOL },
248 { "ECHONL", 56, TTY_OP_BOOL },
249 { "NOFLSH", 57, TTY_OP_BOOL },
250 { "TOSTOP", 58, TTY_OP_BOOL },
251 { "IEXTEN", 59, TTY_OP_BOOL },
252 { "ECHOCTL", 60, TTY_OP_BOOL },
253 { "ECHOKE", 61, TTY_OP_BOOL },
254 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
255 { "OPOST", 70, TTY_OP_BOOL },
256 { "OLCUC", 71, TTY_OP_BOOL },
257 { "ONLCR", 72, TTY_OP_BOOL },
258 { "OCRNL", 73, TTY_OP_BOOL },
259 { "ONOCR", 74, TTY_OP_BOOL },
260 { "ONLRET", 75, TTY_OP_BOOL },
261 { "CS7", 90, TTY_OP_BOOL },
262 { "CS8", 91, TTY_OP_BOOL },
263 { "PARENB", 92, TTY_OP_BOOL },
264 { "PARODD", 93, TTY_OP_BOOL }
267 /* Miscellaneous other tty-related constants. */
268 #define SSH_TTY_OP_END 0
269 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
270 #define SSH1_TTY_OP_ISPEED 192
271 #define SSH1_TTY_OP_OSPEED 193
272 #define SSH2_TTY_OP_ISPEED 128
273 #define SSH2_TTY_OP_OSPEED 129
275 /* Helper functions for parsing tty-related config. */
276 static unsigned int ssh_tty_parse_specchar(char *s)
281 ret = ctrlparse(s, &next);
282 if (!next) ret = s[0];
284 ret = 255; /* special value meaning "don't set" */
288 static unsigned int ssh_tty_parse_boolean(char *s)
290 if (stricmp(s, "yes") == 0 ||
291 stricmp(s, "on") == 0 ||
292 stricmp(s, "true") == 0 ||
293 stricmp(s, "+") == 0)
295 else if (stricmp(s, "no") == 0 ||
296 stricmp(s, "off") == 0 ||
297 stricmp(s, "false") == 0 ||
298 stricmp(s, "-") == 0)
299 return 0; /* false */
301 return (atoi(s) != 0);
304 #define translate(x) if (type == x) return #x
305 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
306 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
307 static char *ssh1_pkt_type(int type)
309 translate(SSH1_MSG_DISCONNECT);
310 translate(SSH1_SMSG_PUBLIC_KEY);
311 translate(SSH1_CMSG_SESSION_KEY);
312 translate(SSH1_CMSG_USER);
313 translate(SSH1_CMSG_AUTH_RSA);
314 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
315 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
316 translate(SSH1_CMSG_AUTH_PASSWORD);
317 translate(SSH1_CMSG_REQUEST_PTY);
318 translate(SSH1_CMSG_WINDOW_SIZE);
319 translate(SSH1_CMSG_EXEC_SHELL);
320 translate(SSH1_CMSG_EXEC_CMD);
321 translate(SSH1_SMSG_SUCCESS);
322 translate(SSH1_SMSG_FAILURE);
323 translate(SSH1_CMSG_STDIN_DATA);
324 translate(SSH1_SMSG_STDOUT_DATA);
325 translate(SSH1_SMSG_STDERR_DATA);
326 translate(SSH1_CMSG_EOF);
327 translate(SSH1_SMSG_EXIT_STATUS);
328 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
329 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
330 translate(SSH1_MSG_CHANNEL_DATA);
331 translate(SSH1_MSG_CHANNEL_CLOSE);
332 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
333 translate(SSH1_SMSG_X11_OPEN);
334 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
335 translate(SSH1_MSG_PORT_OPEN);
336 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
337 translate(SSH1_SMSG_AGENT_OPEN);
338 translate(SSH1_MSG_IGNORE);
339 translate(SSH1_CMSG_EXIT_CONFIRMATION);
340 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
341 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
342 translate(SSH1_MSG_DEBUG);
343 translate(SSH1_CMSG_REQUEST_COMPRESSION);
344 translate(SSH1_CMSG_AUTH_TIS);
345 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
346 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
347 translate(SSH1_CMSG_AUTH_CCARD);
348 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
349 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
352 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
354 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
355 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
356 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
357 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
358 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
359 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
360 translate(SSH2_MSG_DISCONNECT);
361 translate(SSH2_MSG_IGNORE);
362 translate(SSH2_MSG_UNIMPLEMENTED);
363 translate(SSH2_MSG_DEBUG);
364 translate(SSH2_MSG_SERVICE_REQUEST);
365 translate(SSH2_MSG_SERVICE_ACCEPT);
366 translate(SSH2_MSG_KEXINIT);
367 translate(SSH2_MSG_NEWKEYS);
368 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
369 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
370 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
371 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
372 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
373 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
374 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
375 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
376 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
377 translate(SSH2_MSG_USERAUTH_REQUEST);
378 translate(SSH2_MSG_USERAUTH_FAILURE);
379 translate(SSH2_MSG_USERAUTH_SUCCESS);
380 translate(SSH2_MSG_USERAUTH_BANNER);
381 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
382 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
383 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
384 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
385 translate(SSH2_MSG_GLOBAL_REQUEST);
386 translate(SSH2_MSG_REQUEST_SUCCESS);
387 translate(SSH2_MSG_REQUEST_FAILURE);
388 translate(SSH2_MSG_CHANNEL_OPEN);
389 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
390 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
391 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
392 translate(SSH2_MSG_CHANNEL_DATA);
393 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
394 translate(SSH2_MSG_CHANNEL_EOF);
395 translate(SSH2_MSG_CHANNEL_CLOSE);
396 translate(SSH2_MSG_CHANNEL_REQUEST);
397 translate(SSH2_MSG_CHANNEL_SUCCESS);
398 translate(SSH2_MSG_CHANNEL_FAILURE);
404 /* Enumeration values for fields in SSH-1 packets */
406 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
407 /* These values are for communicating relevant semantics of
408 * fields to the packet logging code. */
409 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
413 * Coroutine mechanics for the sillier bits of the code. If these
414 * macros look impenetrable to you, you might find it helpful to
417 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
419 * which explains the theory behind these macros.
421 * In particular, if you are getting `case expression not constant'
422 * errors when building with MS Visual Studio, this is because MS's
423 * Edit and Continue debugging feature causes their compiler to
424 * violate ANSI C. To disable Edit and Continue debugging:
426 * - right-click ssh.c in the FileView
428 * - select the C/C++ tab and the General category
429 * - under `Debug info:', select anything _other_ than `Program
430 * Database for Edit and Continue'.
432 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
435 if (!ssh->t) ssh->t = snew(struct t); \
437 #define crFinish(z) } *crLine = 0; return (z); }
438 #define crFinishV } *crLine = 0; return; }
439 #define crReturn(z) \
441 *crLine =__LINE__; return (z); case __LINE__:;\
445 *crLine=__LINE__; return; case __LINE__:;\
447 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
448 #define crStopV do{ *crLine = 0; return; }while(0)
449 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
450 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
452 typedef struct ssh_tag *Ssh;
455 static struct Packet *ssh1_pkt_init(int pkt_type);
456 static struct Packet *ssh2_pkt_init(int pkt_type);
457 static void ssh_pkt_ensure(struct Packet *, int length);
458 static void ssh_pkt_adddata(struct Packet *, void *data, int len);
459 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
460 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
461 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
462 static void ssh_pkt_addstring_start(struct Packet *);
463 static void ssh_pkt_addstring_str(struct Packet *, char *data);
464 static void ssh_pkt_addstring_data(struct Packet *, char *data, int len);
465 static void ssh_pkt_addstring(struct Packet *, char *data);
466 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
467 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
468 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
469 static int ssh2_pkt_construct(Ssh, struct Packet *);
470 static void ssh2_pkt_send(Ssh, struct Packet *);
471 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
472 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
473 struct Packet *pktin);
474 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
475 struct Packet *pktin);
476 static void ssh2_channel_check_close(struct ssh_channel *c);
477 static void ssh_channel_destroy(struct ssh_channel *c);
480 * Buffer management constants. There are several of these for
481 * various different purposes:
483 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
484 * on a local data stream before we throttle the whole SSH
485 * connection (in SSH-1 only). Throttling the whole connection is
486 * pretty drastic so we set this high in the hope it won't
489 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
490 * on the SSH connection itself before we defensively throttle
491 * _all_ local data streams. This is pretty drastic too (though
492 * thankfully unlikely in SSH-2 since the window mechanism should
493 * ensure that the server never has any need to throttle its end
494 * of the connection), so we set this high as well.
496 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
499 * - OUR_V2_BIGWIN is the window size we advertise for the only
500 * channel in a simple connection. It must be <= INT_MAX.
502 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
503 * to the remote side. This actually has nothing to do with the
504 * size of the _packet_, but is instead a limit on the amount
505 * of data we're willing to receive in a single SSH2 channel
508 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
509 * _packet_ we're prepared to cope with. It must be a multiple
510 * of the cipher block size, and must be at least 35000.
513 #define SSH1_BUFFER_LIMIT 32768
514 #define SSH_MAX_BACKLOG 32768
515 #define OUR_V2_WINSIZE 16384
516 #define OUR_V2_BIGWIN 0x7fffffff
517 #define OUR_V2_MAXPKT 0x4000UL
518 #define OUR_V2_PACKETLIMIT 0x9000UL
520 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
522 const static struct ssh_mac *macs[] = {
523 &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
525 const static struct ssh_mac *buggymacs[] = {
526 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
529 static void *ssh_comp_none_init(void)
533 static void ssh_comp_none_cleanup(void *handle)
536 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
537 unsigned char **outblock, int *outlen)
541 static int ssh_comp_none_disable(void *handle)
545 const static struct ssh_compress ssh_comp_none = {
547 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
548 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
549 ssh_comp_none_disable, NULL
551 extern const struct ssh_compress ssh_zlib;
552 const static struct ssh_compress *compressions[] = {
553 &ssh_zlib, &ssh_comp_none
556 enum { /* channel types */
561 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
563 * CHAN_ZOMBIE is used to indicate a channel for which we've
564 * already destroyed the local data source: for instance, if a
565 * forwarded port experiences a socket error on the local side, we
566 * immediately destroy its local socket and turn the SSH channel
573 * little structure to keep track of outstanding WINDOW_ADJUSTs
581 * 2-3-4 tree storing channels.
584 Ssh ssh; /* pointer back to main context */
585 unsigned remoteid, localid;
587 /* True if we opened this channel but server hasn't confirmed. */
590 * In SSH-1, this value contains four bits:
592 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
593 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
594 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
595 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
597 * A channel is completely finished with when all four bits are set.
599 * In SSH-2, the four bits mean:
601 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
602 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
603 * 4 We have received SSH2_MSG_CHANNEL_EOF.
604 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
606 * A channel is completely finished with when we have both sent
607 * and received CLOSE.
609 * The symbolic constants below use the SSH-2 terminology, which
610 * is a bit confusing in SSH-1, but we have to use _something_.
612 #define CLOSES_SENT_EOF 1
613 #define CLOSES_SENT_CLOSE 2
614 #define CLOSES_RCVD_EOF 4
615 #define CLOSES_RCVD_CLOSE 8
619 * This flag indicates that an EOF is pending on the outgoing side
620 * of the channel: that is, wherever we're getting the data for
621 * this channel has sent us some data followed by EOF. We can't
622 * actually send the EOF until we've finished sending the data, so
623 * we set this flag instead to remind us to do so once our buffer
629 * True if this channel is causing the underlying connection to be
634 struct ssh2_data_channel {
636 unsigned remwindow, remmaxpkt;
637 /* locwindow is signed so we can cope with excess data. */
638 int locwindow, locmaxwin;
640 * remlocwin is the amount of local window that we think
641 * the remote end had available to it after it sent the
642 * last data packet or window adjust ack.
646 * These store the list of window adjusts that haven't
649 struct winadj *winadj_head, *winadj_tail;
650 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
654 struct ssh_agent_channel {
655 unsigned char *message;
656 unsigned char msglen[4];
657 unsigned lensofar, totallen;
659 struct ssh_x11_channel {
662 struct ssh_pfd_channel {
669 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
670 * use this structure in different ways, reflecting SSH-2's
671 * altogether saner approach to port forwarding.
673 * In SSH-1, you arrange a remote forwarding by sending the server
674 * the remote port number, and the local destination host:port.
675 * When a connection comes in, the server sends you back that
676 * host:port pair, and you connect to it. This is a ready-made
677 * security hole if you're not on the ball: a malicious server
678 * could send you back _any_ host:port pair, so if you trustingly
679 * connect to the address it gives you then you've just opened the
680 * entire inside of your corporate network just by connecting
681 * through it to a dodgy SSH server. Hence, we must store a list of
682 * host:port pairs we _are_ trying to forward to, and reject a
683 * connection request from the server if it's not in the list.
685 * In SSH-2, each side of the connection minds its own business and
686 * doesn't send unnecessary information to the other. You arrange a
687 * remote forwarding by sending the server just the remote port
688 * number. When a connection comes in, the server tells you which
689 * of its ports was connected to; and _you_ have to remember what
690 * local host:port pair went with that port number.
692 * Hence, in SSH-1 this structure is indexed by destination
693 * host:port pair, whereas in SSH-2 it is indexed by source port.
695 struct ssh_portfwd; /* forward declaration */
697 struct ssh_rportfwd {
698 unsigned sport, dport;
701 struct ssh_portfwd *pfrec;
703 #define free_rportfwd(pf) ( \
704 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
707 * Separately to the rportfwd tree (which is for looking up port
708 * open requests from the server), a tree of _these_ structures is
709 * used to keep track of all the currently open port forwardings,
710 * so that we can reconfigure in mid-session if the user requests
714 enum { DESTROY, KEEP, CREATE } status;
716 unsigned sport, dport;
719 struct ssh_rportfwd *remote;
723 #define free_portfwd(pf) ( \
724 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
725 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
728 long length; /* length of `data' actually used */
729 long forcepad; /* SSH-2: force padding to at least this length */
730 int type; /* only used for incoming packets */
731 unsigned long sequence; /* SSH-2 incoming sequence number */
732 unsigned char *data; /* allocated storage */
733 unsigned char *body; /* offset of payload within `data' */
734 long savedpos; /* temporary index into `data' (for strings) */
735 long maxlen; /* amount of storage allocated for `data' */
736 long encrypted_len; /* for SSH-2 total-size counting */
739 * State associated with packet logging
743 struct logblank_t *blanks;
746 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
747 struct Packet *pktin);
748 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
749 struct Packet *pktin);
750 static void ssh1_protocol_setup(Ssh ssh);
751 static void ssh2_protocol_setup(Ssh ssh);
752 static void ssh_size(void *handle, int width, int height);
753 static void ssh_special(void *handle, Telnet_Special);
754 static int ssh2_try_send(struct ssh_channel *c);
755 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
756 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
757 static void ssh2_set_window(struct ssh_channel *c, int newwin);
758 static int ssh_sendbuffer(void *handle);
759 static int ssh_do_close(Ssh ssh, int notify_exit);
760 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
761 static int ssh2_pkt_getbool(struct Packet *pkt);
762 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
763 static void ssh2_timer(void *ctx, long now);
764 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
765 struct Packet *pktin);
767 struct rdpkt1_state_tag {
768 long len, pad, biglen, to_read;
769 unsigned long realcrc, gotcrc;
773 struct Packet *pktin;
776 struct rdpkt2_state_tag {
777 long len, pad, payload, packetlen, maclen;
780 unsigned long incoming_sequence;
781 struct Packet *pktin;
784 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
785 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
787 struct queued_handler;
788 struct queued_handler {
790 chandler_fn_t handler;
792 struct queued_handler *next;
796 const struct plug_function_table *fn;
797 /* the above field _must_ be first in the structure */
807 unsigned char session_key[32];
809 int v1_remote_protoflags;
810 int v1_local_protoflags;
811 int agentfwd_enabled;
814 const struct ssh_cipher *cipher;
817 const struct ssh2_cipher *cscipher, *sccipher;
818 void *cs_cipher_ctx, *sc_cipher_ctx;
819 const struct ssh_mac *csmac, *scmac;
820 void *cs_mac_ctx, *sc_mac_ctx;
821 const struct ssh_compress *cscomp, *sccomp;
822 void *cs_comp_ctx, *sc_comp_ctx;
823 const struct ssh_kex *kex;
824 const struct ssh_signkey *hostkey;
825 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
826 int v2_session_id_len;
832 int echoing, editing;
836 int ospeed, ispeed; /* temporaries */
837 int term_width, term_height;
839 tree234 *channels; /* indexed by local id */
840 struct ssh_channel *mainchan; /* primary session channel */
841 int ncmode; /* is primary channel direct-tcpip? */
846 tree234 *rportfwds, *portfwds;
850 SSH_STATE_BEFORE_SIZE,
856 int size_needed, eof_needed;
857 int sent_console_eof;
858 int got_pty; /* affects EOF behaviour on main channel */
860 struct Packet **queue;
861 int queuelen, queuesize;
863 unsigned char *deferred_send_data;
864 int deferred_len, deferred_size;
867 * Gross hack: pscp will try to start SFTP but fall back to
868 * scp1 if that fails. This variable is the means by which
869 * scp.c can reach into the SSH code and find out which one it
874 bufchain banner; /* accumulates banners during do_ssh2_authconn */
879 struct X11Display *x11disp;
882 int conn_throttle_count;
885 int v1_stdout_throttling;
886 unsigned long v2_outgoing_sequence;
888 int ssh1_rdpkt_crstate;
889 int ssh2_rdpkt_crstate;
890 int do_ssh_init_crstate;
891 int ssh_gotdata_crstate;
892 int do_ssh1_login_crstate;
893 int do_ssh1_connection_crstate;
894 int do_ssh2_transport_crstate;
895 int do_ssh2_authconn_crstate;
897 void *do_ssh_init_state;
898 void *do_ssh1_login_state;
899 void *do_ssh2_transport_state;
900 void *do_ssh2_authconn_state;
902 struct rdpkt1_state_tag rdpkt1_state;
903 struct rdpkt2_state_tag rdpkt2_state;
905 /* SSH-1 and SSH-2 use this for different things, but both use it */
906 int protocol_initial_phase_done;
908 void (*protocol) (Ssh ssh, void *vin, int inlen,
910 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
913 * We maintain our own copy of a Conf structure here. That way,
914 * when we're passed a new one for reconfiguration, we can check
915 * the differences and potentially reconfigure port forwardings
916 * etc in mid-session.
921 * Values cached out of conf so as to avoid the tree234 lookup
922 * cost every time they're used.
927 * Dynamically allocated username string created during SSH
928 * login. Stored in here rather than in the coroutine state so
929 * that it'll be reliably freed if we shut down the SSH session
930 * at some unexpected moment.
935 * Used to transfer data back from async callbacks.
937 void *agent_response;
938 int agent_response_len;
942 * The SSH connection can be set as `frozen', meaning we are
943 * not currently accepting incoming data from the network. This
944 * is slightly more serious than setting the _socket_ as
945 * frozen, because we may already have had data passed to us
946 * from the network which we need to delay processing until
947 * after the freeze is lifted, so we also need a bufchain to
951 bufchain queued_incoming_data;
954 * Dispatch table for packet types that we may have to deal
957 handler_fn_t packet_dispatch[256];
960 * Queues of one-off handler functions for success/failure
961 * indications from a request.
963 struct queued_handler *qhead, *qtail;
966 * This module deals with sending keepalives.
971 * Track incoming and outgoing data sizes and time, for
974 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
975 unsigned long max_data_size;
977 long next_rekey, last_rekey;
978 char *deferred_rekey_reason; /* points to STATIC string; don't free */
981 * Fully qualified host name, which we need if doing GSSAPI.
987 * GSSAPI libraries for this session.
989 struct ssh_gss_liblist *gsslibs;
993 #define logevent(s) logevent(ssh->frontend, s)
995 /* logevent, only printf-formatted. */
996 static void logeventf(Ssh ssh, const char *fmt, ...)
1002 buf = dupvprintf(fmt, ap);
1008 #define bombout(msg) \
1010 char *text = dupprintf msg; \
1011 ssh_do_close(ssh, FALSE); \
1013 connection_fatal(ssh->frontend, "%s", text); \
1017 /* Functions to leave bits out of the SSH packet log file. */
1019 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
1021 if (conf_get_int(ssh->conf, CONF_logomitpass))
1022 pkt->logmode = blanktype;
1025 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
1027 if (ssh->logomitdata)
1028 pkt->logmode = blanktype;
1031 static void end_log_omission(Ssh ssh, struct Packet *pkt)
1033 pkt->logmode = PKTLOG_EMIT;
1036 /* Helper function for common bits of parsing ttymodes. */
1037 static void parse_ttymodes(Ssh ssh,
1038 void (*do_mode)(void *data, char *mode, char *val),
1043 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
1045 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
1047 * val[0] is either 'V', indicating that an explicit value
1048 * follows it, or 'A' indicating that we should pass the
1049 * value through from the local environment via get_ttymode.
1052 val = get_ttymode(ssh->frontend, key);
1054 val++; /* skip the 'V' */
1056 do_mode(data, key, val);
1060 static int ssh_channelcmp(void *av, void *bv)
1062 struct ssh_channel *a = (struct ssh_channel *) av;
1063 struct ssh_channel *b = (struct ssh_channel *) bv;
1064 if (a->localid < b->localid)
1066 if (a->localid > b->localid)
1070 static int ssh_channelfind(void *av, void *bv)
1072 unsigned *a = (unsigned *) av;
1073 struct ssh_channel *b = (struct ssh_channel *) bv;
1074 if (*a < b->localid)
1076 if (*a > b->localid)
1081 static int ssh_rportcmp_ssh1(void *av, void *bv)
1083 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1084 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1086 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1087 return i < 0 ? -1 : +1;
1088 if (a->dport > b->dport)
1090 if (a->dport < b->dport)
1095 static int ssh_rportcmp_ssh2(void *av, void *bv)
1097 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1098 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1100 if (a->sport > b->sport)
1102 if (a->sport < b->sport)
1108 * Special form of strcmp which can cope with NULL inputs. NULL is
1109 * defined to sort before even the empty string.
1111 static int nullstrcmp(const char *a, const char *b)
1113 if (a == NULL && b == NULL)
1119 return strcmp(a, b);
1122 static int ssh_portcmp(void *av, void *bv)
1124 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1125 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1127 if (a->type > b->type)
1129 if (a->type < b->type)
1131 if (a->addressfamily > b->addressfamily)
1133 if (a->addressfamily < b->addressfamily)
1135 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1136 return i < 0 ? -1 : +1;
1137 if (a->sport > b->sport)
1139 if (a->sport < b->sport)
1141 if (a->type != 'D') {
1142 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1143 return i < 0 ? -1 : +1;
1144 if (a->dport > b->dport)
1146 if (a->dport < b->dport)
1152 static int alloc_channel_id(Ssh ssh)
1154 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1155 unsigned low, high, mid;
1157 struct ssh_channel *c;
1160 * First-fit allocation of channel numbers: always pick the
1161 * lowest unused one. To do this, binary-search using the
1162 * counted B-tree to find the largest channel ID which is in a
1163 * contiguous sequence from the beginning. (Precisely
1164 * everything in that sequence must have ID equal to its tree
1165 * index plus CHANNEL_NUMBER_OFFSET.)
1167 tsize = count234(ssh->channels);
1171 while (high - low > 1) {
1172 mid = (high + low) / 2;
1173 c = index234(ssh->channels, mid);
1174 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1175 low = mid; /* this one is fine */
1177 high = mid; /* this one is past it */
1180 * Now low points to either -1, or the tree index of the
1181 * largest ID in the initial sequence.
1184 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1185 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1187 return low + 1 + CHANNEL_NUMBER_OFFSET;
1190 static void c_write_stderr(int trusted, const char *buf, int len)
1193 for (i = 0; i < len; i++)
1194 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1195 fputc(buf[i], stderr);
1198 static void c_write(Ssh ssh, const char *buf, int len)
1200 if (flags & FLAG_STDERR)
1201 c_write_stderr(1, buf, len);
1203 from_backend(ssh->frontend, 1, buf, len);
1206 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1208 if (flags & FLAG_STDERR)
1209 c_write_stderr(0, buf, len);
1211 from_backend_untrusted(ssh->frontend, buf, len);
1214 static void c_write_str(Ssh ssh, const char *buf)
1216 c_write(ssh, buf, strlen(buf));
1219 static void ssh_free_packet(struct Packet *pkt)
1224 static struct Packet *ssh_new_packet(void)
1226 struct Packet *pkt = snew(struct Packet);
1228 pkt->body = pkt->data = NULL;
1230 pkt->logmode = PKTLOG_EMIT;
1238 * Collect incoming data in the incoming packet buffer.
1239 * Decipher and verify the packet when it is completely read.
1240 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1241 * Update the *data and *datalen variables.
1242 * Return a Packet structure when a packet is completed.
1244 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1246 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1248 crBegin(ssh->ssh1_rdpkt_crstate);
1250 st->pktin = ssh_new_packet();
1252 st->pktin->type = 0;
1253 st->pktin->length = 0;
1255 for (st->i = st->len = 0; st->i < 4; st->i++) {
1256 while ((*datalen) == 0)
1258 st->len = (st->len << 8) + **data;
1259 (*data)++, (*datalen)--;
1262 st->pad = 8 - (st->len % 8);
1263 st->biglen = st->len + st->pad;
1264 st->pktin->length = st->len - 5;
1266 if (st->biglen < 0) {
1267 bombout(("Extremely large packet length from server suggests"
1268 " data stream corruption"));
1269 ssh_free_packet(st->pktin);
1273 st->pktin->maxlen = st->biglen;
1274 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1276 st->to_read = st->biglen;
1277 st->p = st->pktin->data;
1278 while (st->to_read > 0) {
1279 st->chunk = st->to_read;
1280 while ((*datalen) == 0)
1282 if (st->chunk > (*datalen))
1283 st->chunk = (*datalen);
1284 memcpy(st->p, *data, st->chunk);
1286 *datalen -= st->chunk;
1288 st->to_read -= st->chunk;
1291 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1292 st->biglen, NULL)) {
1293 bombout(("Network attack (CRC compensation) detected!"));
1294 ssh_free_packet(st->pktin);
1299 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1301 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1302 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1303 if (st->gotcrc != st->realcrc) {
1304 bombout(("Incorrect CRC received on packet"));
1305 ssh_free_packet(st->pktin);
1309 st->pktin->body = st->pktin->data + st->pad + 1;
1310 st->pktin->savedpos = 0;
1312 if (ssh->v1_compressing) {
1313 unsigned char *decompblk;
1315 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1316 st->pktin->body - 1, st->pktin->length + 1,
1317 &decompblk, &decomplen)) {
1318 bombout(("Zlib decompression encountered invalid data"));
1319 ssh_free_packet(st->pktin);
1323 if (st->pktin->maxlen < st->pad + decomplen) {
1324 st->pktin->maxlen = st->pad + decomplen;
1325 st->pktin->data = sresize(st->pktin->data,
1326 st->pktin->maxlen + APIEXTRA,
1328 st->pktin->body = st->pktin->data + st->pad + 1;
1331 memcpy(st->pktin->body - 1, decompblk, decomplen);
1333 st->pktin->length = decomplen - 1;
1336 st->pktin->type = st->pktin->body[-1];
1339 * Log incoming packet, possibly omitting sensitive fields.
1343 struct logblank_t blank;
1344 if (ssh->logomitdata) {
1345 int do_blank = FALSE, blank_prefix = 0;
1346 /* "Session data" packets - omit the data field */
1347 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1348 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1349 do_blank = TRUE; blank_prefix = 4;
1350 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1351 do_blank = TRUE; blank_prefix = 8;
1354 blank.offset = blank_prefix;
1355 blank.len = st->pktin->length;
1356 blank.type = PKTLOG_OMIT;
1360 log_packet(ssh->logctx,
1361 PKT_INCOMING, st->pktin->type,
1362 ssh1_pkt_type(st->pktin->type),
1363 st->pktin->body, st->pktin->length,
1364 nblanks, &blank, NULL);
1367 crFinish(st->pktin);
1370 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1372 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1374 crBegin(ssh->ssh2_rdpkt_crstate);
1376 st->pktin = ssh_new_packet();
1378 st->pktin->type = 0;
1379 st->pktin->length = 0;
1381 st->cipherblk = ssh->sccipher->blksize;
1384 if (st->cipherblk < 8)
1386 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1388 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1391 * When dealing with a CBC-mode cipher, we want to avoid the
1392 * possibility of an attacker's tweaking the ciphertext stream
1393 * so as to cause us to feed the same block to the block
1394 * cipher more than once and thus leak information
1395 * (VU#958563). The way we do this is not to take any
1396 * decisions on the basis of anything we've decrypted until
1397 * we've verified it with a MAC. That includes the packet
1398 * length, so we just read data and check the MAC repeatedly,
1399 * and when the MAC passes, see if the length we've got is
1403 /* May as well allocate the whole lot now. */
1404 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1407 /* Read an amount corresponding to the MAC. */
1408 for (st->i = 0; st->i < st->maclen; st->i++) {
1409 while ((*datalen) == 0)
1411 st->pktin->data[st->i] = *(*data)++;
1417 unsigned char seq[4];
1418 ssh->scmac->start(ssh->sc_mac_ctx);
1419 PUT_32BIT(seq, st->incoming_sequence);
1420 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1423 for (;;) { /* Once around this loop per cipher block. */
1424 /* Read another cipher-block's worth, and tack it onto the end. */
1425 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1426 while ((*datalen) == 0)
1428 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1431 /* Decrypt one more block (a little further back in the stream). */
1432 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1433 st->pktin->data + st->packetlen,
1435 /* Feed that block to the MAC. */
1436 ssh->scmac->bytes(ssh->sc_mac_ctx,
1437 st->pktin->data + st->packetlen, st->cipherblk);
1438 st->packetlen += st->cipherblk;
1439 /* See if that gives us a valid packet. */
1440 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1441 st->pktin->data + st->packetlen) &&
1442 (st->len = GET_32BIT(st->pktin->data)) + 4 == st->packetlen)
1444 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1445 bombout(("No valid incoming packet found"));
1446 ssh_free_packet(st->pktin);
1450 st->pktin->maxlen = st->packetlen + st->maclen;
1451 st->pktin->data = sresize(st->pktin->data,
1452 st->pktin->maxlen + APIEXTRA,
1455 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1458 * Acquire and decrypt the first block of the packet. This will
1459 * contain the length and padding details.
1461 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1462 while ((*datalen) == 0)
1464 st->pktin->data[st->i] = *(*data)++;
1469 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1470 st->pktin->data, st->cipherblk);
1473 * Now get the length figure.
1475 st->len = GET_32BIT(st->pktin->data);
1478 * _Completely_ silly lengths should be stomped on before they
1479 * do us any more damage.
1481 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1482 (st->len + 4) % st->cipherblk != 0) {
1483 bombout(("Incoming packet was garbled on decryption"));
1484 ssh_free_packet(st->pktin);
1489 * So now we can work out the total packet length.
1491 st->packetlen = st->len + 4;
1494 * Allocate memory for the rest of the packet.
1496 st->pktin->maxlen = st->packetlen + st->maclen;
1497 st->pktin->data = sresize(st->pktin->data,
1498 st->pktin->maxlen + APIEXTRA,
1502 * Read and decrypt the remainder of the packet.
1504 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1506 while ((*datalen) == 0)
1508 st->pktin->data[st->i] = *(*data)++;
1511 /* Decrypt everything _except_ the MAC. */
1513 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1514 st->pktin->data + st->cipherblk,
1515 st->packetlen - st->cipherblk);
1521 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1522 st->len + 4, st->incoming_sequence)) {
1523 bombout(("Incorrect MAC received on packet"));
1524 ssh_free_packet(st->pktin);
1528 /* Get and sanity-check the amount of random padding. */
1529 st->pad = st->pktin->data[4];
1530 if (st->pad < 4 || st->len - st->pad < 1) {
1531 bombout(("Invalid padding length on received packet"));
1532 ssh_free_packet(st->pktin);
1536 * This enables us to deduce the payload length.
1538 st->payload = st->len - st->pad - 1;
1540 st->pktin->length = st->payload + 5;
1541 st->pktin->encrypted_len = st->packetlen;
1543 st->pktin->sequence = st->incoming_sequence++;
1546 * Decompress packet payload.
1549 unsigned char *newpayload;
1552 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1553 st->pktin->data + 5, st->pktin->length - 5,
1554 &newpayload, &newlen)) {
1555 if (st->pktin->maxlen < newlen + 5) {
1556 st->pktin->maxlen = newlen + 5;
1557 st->pktin->data = sresize(st->pktin->data,
1558 st->pktin->maxlen + APIEXTRA,
1561 st->pktin->length = 5 + newlen;
1562 memcpy(st->pktin->data + 5, newpayload, newlen);
1567 st->pktin->savedpos = 6;
1568 st->pktin->body = st->pktin->data;
1569 st->pktin->type = st->pktin->data[5];
1572 * Log incoming packet, possibly omitting sensitive fields.
1576 struct logblank_t blank;
1577 if (ssh->logomitdata) {
1578 int do_blank = FALSE, blank_prefix = 0;
1579 /* "Session data" packets - omit the data field */
1580 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1581 do_blank = TRUE; blank_prefix = 8;
1582 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1583 do_blank = TRUE; blank_prefix = 12;
1586 blank.offset = blank_prefix;
1587 blank.len = (st->pktin->length-6) - blank_prefix;
1588 blank.type = PKTLOG_OMIT;
1592 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1593 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1595 st->pktin->data+6, st->pktin->length-6,
1596 nblanks, &blank, &st->pktin->sequence);
1599 crFinish(st->pktin);
1602 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1604 int pad, biglen, i, pktoffs;
1608 * XXX various versions of SC (including 8.8.4) screw up the
1609 * register allocation in this function and use the same register
1610 * (D6) for len and as a temporary, with predictable results. The
1611 * following sledgehammer prevents this.
1618 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1619 ssh1_pkt_type(pkt->data[12]),
1620 pkt->body, pkt->length - (pkt->body - pkt->data),
1621 pkt->nblanks, pkt->blanks, NULL);
1622 sfree(pkt->blanks); pkt->blanks = NULL;
1625 if (ssh->v1_compressing) {
1626 unsigned char *compblk;
1628 zlib_compress_block(ssh->cs_comp_ctx,
1629 pkt->data + 12, pkt->length - 12,
1630 &compblk, &complen);
1631 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1632 memcpy(pkt->data + 12, compblk, complen);
1634 pkt->length = complen + 12;
1637 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1639 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1640 pad = 8 - (len % 8);
1642 biglen = len + pad; /* len(padding+type+data+CRC) */
1644 for (i = pktoffs; i < 4+8; i++)
1645 pkt->data[i] = random_byte();
1646 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1647 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1648 PUT_32BIT(pkt->data + pktoffs, len);
1651 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1652 pkt->data + pktoffs + 4, biglen);
1654 if (offset_p) *offset_p = pktoffs;
1655 return biglen + 4; /* len(length+padding+type+data+CRC) */
1658 static int s_write(Ssh ssh, void *data, int len)
1661 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1663 return sk_write(ssh->s, (char *)data, len);
1666 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1668 int len, backlog, offset;
1669 len = s_wrpkt_prepare(ssh, pkt, &offset);
1670 backlog = s_write(ssh, pkt->data + offset, len);
1671 if (backlog > SSH_MAX_BACKLOG)
1672 ssh_throttle_all(ssh, 1, backlog);
1673 ssh_free_packet(pkt);
1676 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1679 len = s_wrpkt_prepare(ssh, pkt, &offset);
1680 if (ssh->deferred_len + len > ssh->deferred_size) {
1681 ssh->deferred_size = ssh->deferred_len + len + 128;
1682 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1686 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1687 pkt->data + offset, len);
1688 ssh->deferred_len += len;
1689 ssh_free_packet(pkt);
1693 * Construct a SSH-1 packet with the specified contents.
1694 * (This all-at-once interface used to be the only one, but now SSH-1
1695 * packets can also be constructed incrementally.)
1697 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1703 pkt = ssh1_pkt_init(pkttype);
1705 while ((argtype = va_arg(ap, int)) != PKT_END) {
1706 unsigned char *argp, argchar;
1708 unsigned long argint;
1711 /* Actual fields in the packet */
1713 argint = va_arg(ap, int);
1714 ssh_pkt_adduint32(pkt, argint);
1717 argchar = (unsigned char) va_arg(ap, int);
1718 ssh_pkt_addbyte(pkt, argchar);
1721 argp = va_arg(ap, unsigned char *);
1722 arglen = va_arg(ap, int);
1723 ssh_pkt_adddata(pkt, argp, arglen);
1726 sargp = va_arg(ap, char *);
1727 ssh_pkt_addstring(pkt, sargp);
1730 bn = va_arg(ap, Bignum);
1731 ssh1_pkt_addmp(pkt, bn);
1733 /* Tokens for modifications to packet logging */
1735 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1738 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1741 end_log_omission(ssh, pkt);
1749 static void send_packet(Ssh ssh, int pkttype, ...)
1753 va_start(ap, pkttype);
1754 pkt = construct_packet(ssh, pkttype, ap);
1759 static void defer_packet(Ssh ssh, int pkttype, ...)
1763 va_start(ap, pkttype);
1764 pkt = construct_packet(ssh, pkttype, ap);
1766 s_wrpkt_defer(ssh, pkt);
1769 static int ssh_versioncmp(char *a, char *b)
1772 unsigned long av, bv;
1774 av = strtoul(a, &ae, 10);
1775 bv = strtoul(b, &be, 10);
1777 return (av < bv ? -1 : +1);
1782 av = strtoul(ae, &ae, 10);
1783 bv = strtoul(be, &be, 10);
1785 return (av < bv ? -1 : +1);
1790 * Utility routines for putting an SSH-protocol `string' and
1791 * `uint32' into a hash state.
1793 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1795 unsigned char lenblk[4];
1796 PUT_32BIT(lenblk, len);
1797 h->bytes(s, lenblk, 4);
1798 h->bytes(s, str, len);
1801 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1803 unsigned char intblk[4];
1804 PUT_32BIT(intblk, i);
1805 h->bytes(s, intblk, 4);
1809 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1811 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1813 if (pkt->maxlen < length) {
1814 unsigned char *body = pkt->body;
1815 int offset = body ? body - pkt->data : 0;
1816 pkt->maxlen = length + 256;
1817 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1818 if (body) pkt->body = pkt->data + offset;
1821 static void ssh_pkt_adddata(struct Packet *pkt, void *data, int len)
1823 if (pkt->logmode != PKTLOG_EMIT) {
1825 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1827 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1828 (pkt->body - pkt->data);
1829 pkt->blanks[pkt->nblanks-1].len = len;
1830 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1833 ssh_pkt_ensure(pkt, pkt->length);
1834 memcpy(pkt->data + pkt->length - len, data, len);
1836 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1838 ssh_pkt_adddata(pkt, &byte, 1);
1840 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1842 ssh_pkt_adddata(pkt, &value, 1);
1844 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1847 PUT_32BIT(x, value);
1848 ssh_pkt_adddata(pkt, x, 4);
1850 static void ssh_pkt_addstring_start(struct Packet *pkt)
1852 ssh_pkt_adduint32(pkt, 0);
1853 pkt->savedpos = pkt->length;
1855 static void ssh_pkt_addstring_str(struct Packet *pkt, char *data)
1857 ssh_pkt_adddata(pkt, data, strlen(data));
1858 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1860 static void ssh_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1862 ssh_pkt_adddata(pkt, data, len);
1863 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1865 static void ssh_pkt_addstring(struct Packet *pkt, char *data)
1867 ssh_pkt_addstring_start(pkt);
1868 ssh_pkt_addstring_str(pkt, data);
1870 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1872 int len = ssh1_bignum_length(b);
1873 unsigned char *data = snewn(len, unsigned char);
1874 (void) ssh1_write_bignum(data, b);
1875 ssh_pkt_adddata(pkt, data, len);
1878 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1881 int i, n = (bignum_bitcount(b) + 7) / 8;
1882 p = snewn(n + 1, unsigned char);
1884 for (i = 1; i <= n; i++)
1885 p[i] = bignum_byte(b, n - i);
1887 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1889 memmove(p, p + i, n + 1 - i);
1893 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1897 p = ssh2_mpint_fmt(b, &len);
1898 ssh_pkt_addstring_start(pkt);
1899 ssh_pkt_addstring_data(pkt, (char *)p, len);
1903 static struct Packet *ssh1_pkt_init(int pkt_type)
1905 struct Packet *pkt = ssh_new_packet();
1906 pkt->length = 4 + 8; /* space for length + max padding */
1907 ssh_pkt_addbyte(pkt, pkt_type);
1908 pkt->body = pkt->data + pkt->length;
1912 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1913 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1914 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1915 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1916 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1917 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1918 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1919 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1920 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1922 static struct Packet *ssh2_pkt_init(int pkt_type)
1924 struct Packet *pkt = ssh_new_packet();
1925 pkt->length = 5; /* space for packet length + padding length */
1927 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1928 pkt->body = pkt->data + pkt->length; /* after packet type */
1933 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1934 * put the MAC on it. Final packet, ready to be sent, is stored in
1935 * pkt->data. Total length is returned.
1937 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1939 int cipherblk, maclen, padding, i;
1942 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1943 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1944 pkt->body, pkt->length - (pkt->body - pkt->data),
1945 pkt->nblanks, pkt->blanks, &ssh->v2_outgoing_sequence);
1946 sfree(pkt->blanks); pkt->blanks = NULL;
1950 * Compress packet payload.
1953 unsigned char *newpayload;
1956 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1958 &newpayload, &newlen)) {
1960 ssh2_pkt_adddata(pkt, newpayload, newlen);
1966 * Add padding. At least four bytes, and must also bring total
1967 * length (minus MAC) up to a multiple of the block size.
1968 * If pkt->forcepad is set, make sure the packet is at least that size
1971 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1972 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1974 if (pkt->length + padding < pkt->forcepad)
1975 padding = pkt->forcepad - pkt->length;
1977 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1978 assert(padding <= 255);
1979 maclen = ssh->csmac ? ssh->csmac->len : 0;
1980 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1981 pkt->data[4] = padding;
1982 for (i = 0; i < padding; i++)
1983 pkt->data[pkt->length + i] = random_byte();
1984 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1986 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1987 pkt->length + padding,
1988 ssh->v2_outgoing_sequence);
1989 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1992 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1993 pkt->data, pkt->length + padding);
1995 pkt->encrypted_len = pkt->length + padding;
1997 /* Ready-to-send packet starts at pkt->data. We return length. */
1998 return pkt->length + padding + maclen;
2002 * Routines called from the main SSH code to send packets. There
2003 * are quite a few of these, because we have two separate
2004 * mechanisms for delaying the sending of packets:
2006 * - In order to send an IGNORE message and a password message in
2007 * a single fixed-length blob, we require the ability to
2008 * concatenate the encrypted forms of those two packets _into_ a
2009 * single blob and then pass it to our <network.h> transport
2010 * layer in one go. Hence, there's a deferment mechanism which
2011 * works after packet encryption.
2013 * - In order to avoid sending any connection-layer messages
2014 * during repeat key exchange, we have to queue up any such
2015 * outgoing messages _before_ they are encrypted (and in
2016 * particular before they're allocated sequence numbers), and
2017 * then send them once we've finished.
2019 * I call these mechanisms `defer' and `queue' respectively, so as
2020 * to distinguish them reasonably easily.
2022 * The functions send_noqueue() and defer_noqueue() free the packet
2023 * structure they are passed. Every outgoing packet goes through
2024 * precisely one of these functions in its life; packets passed to
2025 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2026 * these or get queued, and then when the queue is later emptied
2027 * the packets are all passed to defer_noqueue().
2029 * When using a CBC-mode cipher, it's necessary to ensure that an
2030 * attacker can't provide data to be encrypted using an IV that they
2031 * know. We ensure this by prefixing each packet that might contain
2032 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2033 * mechanism, so in this case send_noqueue() ends up redirecting to
2034 * defer_noqueue(). If you don't like this inefficiency, don't use
2038 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2039 static void ssh_pkt_defersend(Ssh);
2042 * Send an SSH-2 packet immediately, without queuing or deferring.
2044 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2048 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2049 /* We need to send two packets, so use the deferral mechanism. */
2050 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2051 ssh_pkt_defersend(ssh);
2054 len = ssh2_pkt_construct(ssh, pkt);
2055 backlog = s_write(ssh, pkt->data, len);
2056 if (backlog > SSH_MAX_BACKLOG)
2057 ssh_throttle_all(ssh, 1, backlog);
2059 ssh->outgoing_data_size += pkt->encrypted_len;
2060 if (!ssh->kex_in_progress &&
2061 ssh->max_data_size != 0 &&
2062 ssh->outgoing_data_size > ssh->max_data_size)
2063 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2065 ssh_free_packet(pkt);
2069 * Defer an SSH-2 packet.
2071 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2074 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2075 ssh->deferred_len == 0 && !noignore &&
2076 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2078 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2079 * get encrypted with a known IV.
2081 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2082 ssh2_pkt_addstring_start(ipkt);
2083 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2085 len = ssh2_pkt_construct(ssh, pkt);
2086 if (ssh->deferred_len + len > ssh->deferred_size) {
2087 ssh->deferred_size = ssh->deferred_len + len + 128;
2088 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2092 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
2093 ssh->deferred_len += len;
2094 ssh->deferred_data_size += pkt->encrypted_len;
2095 ssh_free_packet(pkt);
2099 * Queue an SSH-2 packet.
2101 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2103 assert(ssh->queueing);
2105 if (ssh->queuelen >= ssh->queuesize) {
2106 ssh->queuesize = ssh->queuelen + 32;
2107 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2110 ssh->queue[ssh->queuelen++] = pkt;
2114 * Either queue or send a packet, depending on whether queueing is
2117 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2120 ssh2_pkt_queue(ssh, pkt);
2122 ssh2_pkt_send_noqueue(ssh, pkt);
2126 * Either queue or defer a packet, depending on whether queueing is
2129 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2132 ssh2_pkt_queue(ssh, pkt);
2134 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2138 * Send the whole deferred data block constructed by
2139 * ssh2_pkt_defer() or SSH-1's defer_packet().
2141 * The expected use of the defer mechanism is that you call
2142 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2143 * not currently queueing, this simply sets up deferred_send_data
2144 * and then sends it. If we _are_ currently queueing, the calls to
2145 * ssh2_pkt_defer() put the deferred packets on to the queue
2146 * instead, and therefore ssh_pkt_defersend() has no deferred data
2147 * to send. Hence, there's no need to make it conditional on
2150 static void ssh_pkt_defersend(Ssh ssh)
2153 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2154 ssh->deferred_len = ssh->deferred_size = 0;
2155 sfree(ssh->deferred_send_data);
2156 ssh->deferred_send_data = NULL;
2157 if (backlog > SSH_MAX_BACKLOG)
2158 ssh_throttle_all(ssh, 1, backlog);
2160 ssh->outgoing_data_size += ssh->deferred_data_size;
2161 if (!ssh->kex_in_progress &&
2162 ssh->max_data_size != 0 &&
2163 ssh->outgoing_data_size > ssh->max_data_size)
2164 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2165 ssh->deferred_data_size = 0;
2169 * Send a packet whose length needs to be disguised (typically
2170 * passwords or keyboard-interactive responses).
2172 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2178 * The simplest way to do this is to adjust the
2179 * variable-length padding field in the outgoing packet.
2181 * Currently compiled out, because some Cisco SSH servers
2182 * don't like excessively padded packets (bah, why's it
2185 pkt->forcepad = padsize;
2186 ssh2_pkt_send(ssh, pkt);
2191 * If we can't do that, however, an alternative approach is
2192 * to use the pkt_defer mechanism to bundle the packet
2193 * tightly together with an SSH_MSG_IGNORE such that their
2194 * combined length is a constant. So first we construct the
2195 * final form of this packet and defer its sending.
2197 ssh2_pkt_defer(ssh, pkt);
2200 * Now construct an SSH_MSG_IGNORE which includes a string
2201 * that's an exact multiple of the cipher block size. (If
2202 * the cipher is NULL so that the block size is
2203 * unavailable, we don't do this trick at all, because we
2204 * gain nothing by it.)
2206 if (ssh->cscipher &&
2207 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2210 stringlen = (256 - ssh->deferred_len);
2211 stringlen += ssh->cscipher->blksize - 1;
2212 stringlen -= (stringlen % ssh->cscipher->blksize);
2215 * Temporarily disable actual compression, so we
2216 * can guarantee to get this string exactly the
2217 * length we want it. The compression-disabling
2218 * routine should return an integer indicating how
2219 * many bytes we should adjust our string length
2223 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2225 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2226 ssh2_pkt_addstring_start(pkt);
2227 for (i = 0; i < stringlen; i++) {
2228 char c = (char) random_byte();
2229 ssh2_pkt_addstring_data(pkt, &c, 1);
2231 ssh2_pkt_defer(ssh, pkt);
2233 ssh_pkt_defersend(ssh);
2238 * Send all queued SSH-2 packets. We send them by means of
2239 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2240 * packets that needed to be lumped together.
2242 static void ssh2_pkt_queuesend(Ssh ssh)
2246 assert(!ssh->queueing);
2248 for (i = 0; i < ssh->queuelen; i++)
2249 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2252 ssh_pkt_defersend(ssh);
2256 void bndebug(char *string, Bignum b)
2260 p = ssh2_mpint_fmt(b, &len);
2261 debug(("%s", string));
2262 for (i = 0; i < len; i++)
2263 debug((" %02x", p[i]));
2269 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2273 p = ssh2_mpint_fmt(b, &len);
2274 hash_string(h, s, p, len);
2279 * Packet decode functions for both SSH-1 and SSH-2.
2281 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2283 unsigned long value;
2284 if (pkt->length - pkt->savedpos < 4)
2285 return 0; /* arrgh, no way to decline (FIXME?) */
2286 value = GET_32BIT(pkt->body + pkt->savedpos);
2290 static int ssh2_pkt_getbool(struct Packet *pkt)
2292 unsigned long value;
2293 if (pkt->length - pkt->savedpos < 1)
2294 return 0; /* arrgh, no way to decline (FIXME?) */
2295 value = pkt->body[pkt->savedpos] != 0;
2299 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2304 if (pkt->length - pkt->savedpos < 4)
2306 len = GET_32BIT(pkt->body + pkt->savedpos);
2311 if (pkt->length - pkt->savedpos < *length)
2313 *p = (char *)(pkt->body + pkt->savedpos);
2314 pkt->savedpos += *length;
2316 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2318 if (pkt->length - pkt->savedpos < length)
2320 pkt->savedpos += length;
2321 return pkt->body + (pkt->savedpos - length);
2323 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2324 unsigned char **keystr)
2328 j = makekey(pkt->body + pkt->savedpos,
2329 pkt->length - pkt->savedpos,
2336 assert(pkt->savedpos < pkt->length);
2340 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2345 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2346 pkt->length - pkt->savedpos, &b);
2354 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2360 ssh_pkt_getstring(pkt, &p, &length);
2365 b = bignum_from_bytes((unsigned char *)p, length);
2370 * Helper function to add an SSH-2 signature blob to a packet.
2371 * Expects to be shown the public key blob as well as the signature
2372 * blob. Normally works just like ssh2_pkt_addstring, but will
2373 * fiddle with the signature packet if necessary for
2374 * BUG_SSH2_RSA_PADDING.
2376 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2377 void *pkblob_v, int pkblob_len,
2378 void *sigblob_v, int sigblob_len)
2380 unsigned char *pkblob = (unsigned char *)pkblob_v;
2381 unsigned char *sigblob = (unsigned char *)sigblob_v;
2383 /* dmemdump(pkblob, pkblob_len); */
2384 /* dmemdump(sigblob, sigblob_len); */
2387 * See if this is in fact an ssh-rsa signature and a buggy
2388 * server; otherwise we can just do this the easy way.
2390 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
2391 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2392 int pos, len, siglen;
2395 * Find the byte length of the modulus.
2398 pos = 4+7; /* skip over "ssh-rsa" */
2399 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
2400 len = GET_32BIT(pkblob+pos); /* find length of modulus */
2401 pos += 4; /* find modulus itself */
2402 while (len > 0 && pkblob[pos] == 0)
2404 /* debug(("modulus length is %d\n", len)); */
2407 * Now find the signature integer.
2409 pos = 4+7; /* skip over "ssh-rsa" */
2410 siglen = GET_32BIT(sigblob+pos);
2411 /* debug(("signature length is %d\n", siglen)); */
2413 if (len != siglen) {
2414 unsigned char newlen[4];
2415 ssh2_pkt_addstring_start(pkt);
2416 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2417 /* dmemdump(sigblob, pos); */
2418 pos += 4; /* point to start of actual sig */
2419 PUT_32BIT(newlen, len);
2420 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2421 /* dmemdump(newlen, 4); */
2423 while (len-- > siglen) {
2424 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2425 /* dmemdump(newlen, 1); */
2427 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2428 /* dmemdump(sigblob+pos, siglen); */
2432 /* Otherwise fall through and do it the easy way. */
2435 ssh2_pkt_addstring_start(pkt);
2436 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2440 * Examine the remote side's version string and compare it against
2441 * a list of known buggy implementations.
2443 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2445 char *imp; /* pointer to implementation part */
2447 imp += strcspn(imp, "-");
2449 imp += strcspn(imp, "-");
2452 ssh->remote_bugs = 0;
2455 * General notes on server version strings:
2456 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2457 * here -- in particular, we've heard of one that's perfectly happy
2458 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2459 * so we can't distinguish them.
2461 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2462 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2463 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2464 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2465 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2466 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2468 * These versions don't support SSH1_MSG_IGNORE, so we have
2469 * to use a different defence against password length
2472 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2473 logevent("We believe remote version has SSH-1 ignore bug");
2476 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2477 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2478 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2480 * These versions need a plain password sent; they can't
2481 * handle having a null and a random length of data after
2484 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2485 logevent("We believe remote version needs a plain SSH-1 password");
2488 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2489 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2490 (!strcmp(imp, "Cisco-1.25")))) {
2492 * These versions apparently have no clue whatever about
2493 * RSA authentication and will panic and die if they see
2494 * an AUTH_RSA message.
2496 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2497 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2500 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2501 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2502 !wc_match("* VShell", imp) &&
2503 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2504 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2505 wc_match("2.1 *", imp)))) {
2507 * These versions have the HMAC bug.
2509 ssh->remote_bugs |= BUG_SSH2_HMAC;
2510 logevent("We believe remote version has SSH-2 HMAC bug");
2513 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2514 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2515 !wc_match("* VShell", imp) &&
2516 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2518 * These versions have the key-derivation bug (failing to
2519 * include the literal shared secret in the hashes that
2520 * generate the keys).
2522 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2523 logevent("We believe remote version has SSH-2 key-derivation bug");
2526 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2527 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2528 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2529 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2531 * These versions have the SSH-2 RSA padding bug.
2533 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2534 logevent("We believe remote version has SSH-2 RSA padding bug");
2537 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2538 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2539 wc_match("OpenSSH_2.[0-2]*", imp))) {
2541 * These versions have the SSH-2 session-ID bug in
2542 * public-key authentication.
2544 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2545 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2548 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2549 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2550 (wc_match("DigiSSH_2.0", imp) ||
2551 wc_match("OpenSSH_2.[0-4]*", imp) ||
2552 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2553 wc_match("Sun_SSH_1.0", imp) ||
2554 wc_match("Sun_SSH_1.0.1", imp) ||
2555 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2556 wc_match("WeOnlyDo-*", imp)))) {
2558 * These versions have the SSH-2 rekey bug.
2560 ssh->remote_bugs |= BUG_SSH2_REKEY;
2561 logevent("We believe remote version has SSH-2 rekey bug");
2564 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2565 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2566 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2567 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2569 * This version ignores our makpkt and needs to be throttled.
2571 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2572 logevent("We believe remote version ignores SSH-2 maximum packet size");
2575 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2577 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2578 * none detected automatically.
2580 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2581 logevent("We believe remote version has SSH-2 ignore bug");
2586 * The `software version' part of an SSH version string is required
2587 * to contain no spaces or minus signs.
2589 static void ssh_fix_verstring(char *str)
2591 /* Eat "SSH-<protoversion>-". */
2592 assert(*str == 'S'); str++;
2593 assert(*str == 'S'); str++;
2594 assert(*str == 'H'); str++;
2595 assert(*str == '-'); str++;
2596 while (*str && *str != '-') str++;
2597 assert(*str == '-'); str++;
2599 /* Convert minus signs and spaces in the remaining string into
2602 if (*str == '-' || *str == ' ')
2609 * Send an appropriate SSH version string.
2611 static void ssh_send_verstring(Ssh ssh, char *svers)
2615 if (ssh->version == 2) {
2617 * Construct a v2 version string.
2619 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2622 * Construct a v1 version string.
2624 verstring = dupprintf("SSH-%s-%s\012",
2625 (ssh_versioncmp(svers, "1.5") <= 0 ?
2630 ssh_fix_verstring(verstring);
2632 if (ssh->version == 2) {
2635 * Record our version string.
2637 len = strcspn(verstring, "\015\012");
2638 ssh->v_c = snewn(len + 1, char);
2639 memcpy(ssh->v_c, verstring, len);
2643 logeventf(ssh, "We claim version: %.*s",
2644 strcspn(verstring, "\015\012"), verstring);
2645 s_write(ssh, verstring, strlen(verstring));
2649 static int do_ssh_init(Ssh ssh, unsigned char c)
2651 struct do_ssh_init_state {
2659 crState(do_ssh_init_state);
2661 crBegin(ssh->do_ssh_init_crstate);
2663 /* Search for a line beginning with the string "SSH-" in the input. */
2665 if (c != 'S') goto no;
2667 if (c != 'S') goto no;
2669 if (c != 'H') goto no;
2671 if (c != '-') goto no;
2680 s->vstring = snewn(s->vstrsize, char);
2681 strcpy(s->vstring, "SSH-");
2685 crReturn(1); /* get another char */
2686 if (s->vslen >= s->vstrsize - 1) {
2688 s->vstring = sresize(s->vstring, s->vstrsize, char);
2690 s->vstring[s->vslen++] = c;
2693 s->version[s->i] = '\0';
2695 } else if (s->i < sizeof(s->version) - 1)
2696 s->version[s->i++] = c;
2697 } else if (c == '\012')
2701 ssh->agentfwd_enabled = FALSE;
2702 ssh->rdpkt2_state.incoming_sequence = 0;
2704 s->vstring[s->vslen] = 0;
2705 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2706 logeventf(ssh, "Server version: %s", s->vstring);
2707 ssh_detect_bugs(ssh, s->vstring);
2710 * Decide which SSH protocol version to support.
2713 /* Anything strictly below "2.0" means protocol 1 is supported. */
2714 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2715 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2716 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2718 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2719 bombout(("SSH protocol version 1 required by user but not provided by server"));
2722 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2723 bombout(("SSH protocol version 2 required by user but not provided by server"));
2727 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2732 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2734 /* Send the version string, if we haven't already */
2735 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
2736 ssh_send_verstring(ssh, s->version);
2738 if (ssh->version == 2) {
2741 * Record their version string.
2743 len = strcspn(s->vstring, "\015\012");
2744 ssh->v_s = snewn(len + 1, char);
2745 memcpy(ssh->v_s, s->vstring, len);
2749 * Initialise SSH-2 protocol.
2751 ssh->protocol = ssh2_protocol;
2752 ssh2_protocol_setup(ssh);
2753 ssh->s_rdpkt = ssh2_rdpkt;
2756 * Initialise SSH-1 protocol.
2758 ssh->protocol = ssh1_protocol;
2759 ssh1_protocol_setup(ssh);
2760 ssh->s_rdpkt = ssh1_rdpkt;
2762 if (ssh->version == 2)
2763 do_ssh2_transport(ssh, NULL, -1, NULL);
2765 update_specials_menu(ssh->frontend);
2766 ssh->state = SSH_STATE_BEFORE_SIZE;
2767 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
2774 static void ssh_process_incoming_data(Ssh ssh,
2775 unsigned char **data, int *datalen)
2777 struct Packet *pktin;
2779 pktin = ssh->s_rdpkt(ssh, data, datalen);
2781 ssh->protocol(ssh, NULL, 0, pktin);
2782 ssh_free_packet(pktin);
2786 static void ssh_queue_incoming_data(Ssh ssh,
2787 unsigned char **data, int *datalen)
2789 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2794 static void ssh_process_queued_incoming_data(Ssh ssh)
2797 unsigned char *data;
2800 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2801 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2805 while (!ssh->frozen && len > 0)
2806 ssh_process_incoming_data(ssh, &data, &len);
2809 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2813 static void ssh_set_frozen(Ssh ssh, int frozen)
2816 sk_set_frozen(ssh->s, frozen);
2817 ssh->frozen = frozen;
2820 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2822 /* Log raw data, if we're in that mode. */
2824 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2827 crBegin(ssh->ssh_gotdata_crstate);
2830 * To begin with, feed the characters one by one to the
2831 * protocol initialisation / selection function do_ssh_init().
2832 * When that returns 0, we're done with the initial greeting
2833 * exchange and can move on to packet discipline.
2836 int ret; /* need not be kept across crReturn */
2838 crReturnV; /* more data please */
2839 ret = do_ssh_init(ssh, *data);
2847 * We emerge from that loop when the initial negotiation is
2848 * over and we have selected an s_rdpkt function. Now pass
2849 * everything to s_rdpkt, and then pass the resulting packets
2850 * to the proper protocol handler.
2854 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2856 ssh_queue_incoming_data(ssh, &data, &datalen);
2857 /* This uses up all data and cannot cause anything interesting
2858 * to happen; indeed, for anything to happen at all, we must
2859 * return, so break out. */
2861 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2862 /* This uses up some or all data, and may freeze the
2864 ssh_process_queued_incoming_data(ssh);
2866 /* This uses up some or all data, and may freeze the
2868 ssh_process_incoming_data(ssh, &data, &datalen);
2870 /* FIXME this is probably EBW. */
2871 if (ssh->state == SSH_STATE_CLOSED)
2874 /* We're out of data. Go and get some more. */
2880 static int ssh_do_close(Ssh ssh, int notify_exit)
2883 struct ssh_channel *c;
2885 ssh->state = SSH_STATE_CLOSED;
2886 expire_timer_context(ssh);
2891 notify_remote_exit(ssh->frontend);
2896 * Now we must shut down any port- and X-forwarded channels going
2897 * through this connection.
2899 if (ssh->channels) {
2900 while (NULL != (c = index234(ssh->channels, 0))) {
2903 x11_close(c->u.x11.s);
2906 case CHAN_SOCKDATA_DORMANT:
2907 pfd_close(c->u.pfd.s);
2910 del234(ssh->channels, c); /* moving next one to index 0 */
2911 if (ssh->version == 2)
2912 bufchain_clear(&c->v.v2.outbuffer);
2917 * Go through port-forwardings, and close any associated
2918 * listening sockets.
2920 if (ssh->portfwds) {
2921 struct ssh_portfwd *pf;
2922 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2923 /* Dispose of any listening socket. */
2925 pfd_terminate(pf->local);
2926 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2929 freetree234(ssh->portfwds);
2930 ssh->portfwds = NULL;
2936 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2937 const char *error_msg, int error_code)
2939 Ssh ssh = (Ssh) plug;
2940 char addrbuf[256], *msg;
2942 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2945 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2947 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2953 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2956 Ssh ssh = (Ssh) plug;
2957 int need_notify = ssh_do_close(ssh, FALSE);
2960 if (!ssh->close_expected)
2961 error_msg = "Server unexpectedly closed network connection";
2963 error_msg = "Server closed network connection";
2966 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
2970 notify_remote_exit(ssh->frontend);
2973 logevent(error_msg);
2974 if (!ssh->close_expected || !ssh->clean_exit)
2975 connection_fatal(ssh->frontend, "%s", error_msg);
2979 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2981 Ssh ssh = (Ssh) plug;
2982 ssh_gotdata(ssh, (unsigned char *)data, len);
2983 if (ssh->state == SSH_STATE_CLOSED) {
2984 ssh_do_close(ssh, TRUE);
2990 static void ssh_sent(Plug plug, int bufsize)
2992 Ssh ssh = (Ssh) plug;
2994 * If the send backlog on the SSH socket itself clears, we
2995 * should unthrottle the whole world if it was throttled.
2997 if (bufsize < SSH_MAX_BACKLOG)
2998 ssh_throttle_all(ssh, 0, bufsize);
3002 * Connect to specified host and port.
3003 * Returns an error message, or NULL on success.
3004 * Also places the canonical host name into `realhost'. It must be
3005 * freed by the caller.
3007 static const char *connect_to_host(Ssh ssh, char *host, int port,
3008 char **realhost, int nodelay, int keepalive)
3010 static const struct plug_function_table fn_table = {
3021 int addressfamily, sshprot;
3023 loghost = conf_get_str(ssh->conf, CONF_loghost);
3027 ssh->savedhost = dupstr(loghost);
3028 ssh->savedport = 22; /* default ssh port */
3031 * A colon suffix on savedhost also lets us affect
3034 * (FIXME: do something about IPv6 address literals here.)
3036 colon = strrchr(ssh->savedhost, ':');
3040 ssh->savedport = atoi(colon);
3043 ssh->savedhost = dupstr(host);
3045 port = 22; /* default ssh port */
3046 ssh->savedport = port;
3052 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3053 logeventf(ssh, "Looking up host \"%s\"%s", host,
3054 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3055 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3056 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3057 if ((err = sk_addr_error(addr)) != NULL) {
3061 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3066 ssh->fn = &fn_table;
3067 ssh->s = new_connection(addr, *realhost, port,
3068 0, 1, nodelay, keepalive, (Plug) ssh, ssh->conf);
3069 if ((err = sk_socket_error(ssh->s)) != NULL) {
3071 notify_remote_exit(ssh->frontend);
3076 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3077 * send the version string too.
3079 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3084 ssh_send_verstring(ssh, NULL);
3088 * loghost, if configured, overrides realhost.
3092 *realhost = dupstr(loghost);
3099 * Throttle or unthrottle the SSH connection.
3101 static void ssh_throttle_conn(Ssh ssh, int adjust)
3103 int old_count = ssh->conn_throttle_count;
3104 ssh->conn_throttle_count += adjust;
3105 assert(ssh->conn_throttle_count >= 0);
3106 if (ssh->conn_throttle_count && !old_count) {
3107 ssh_set_frozen(ssh, 1);
3108 } else if (!ssh->conn_throttle_count && old_count) {
3109 ssh_set_frozen(ssh, 0);
3114 * Throttle or unthrottle _all_ local data streams (for when sends
3115 * on the SSH connection itself back up).
3117 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3120 struct ssh_channel *c;
3122 if (enable == ssh->throttled_all)
3124 ssh->throttled_all = enable;
3125 ssh->overall_bufsize = bufsize;
3128 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3130 case CHAN_MAINSESSION:
3132 * This is treated separately, outside the switch.
3136 x11_override_throttle(c->u.x11.s, enable);
3139 /* Agent channels require no buffer management. */
3142 pfd_override_throttle(c->u.pfd.s, enable);
3148 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3150 Ssh ssh = (Ssh) sshv;
3152 ssh->agent_response = reply;
3153 ssh->agent_response_len = replylen;
3155 if (ssh->version == 1)
3156 do_ssh1_login(ssh, NULL, -1, NULL);
3158 do_ssh2_authconn(ssh, NULL, -1, NULL);
3161 static void ssh_dialog_callback(void *sshv, int ret)
3163 Ssh ssh = (Ssh) sshv;
3165 ssh->user_response = ret;
3167 if (ssh->version == 1)
3168 do_ssh1_login(ssh, NULL, -1, NULL);
3170 do_ssh2_transport(ssh, NULL, -1, NULL);
3173 * This may have unfrozen the SSH connection, so do a
3176 ssh_process_queued_incoming_data(ssh);
3179 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3181 struct ssh_channel *c = (struct ssh_channel *)cv;
3183 void *sentreply = reply;
3186 /* Fake SSH_AGENT_FAILURE. */
3187 sentreply = "\0\0\0\1\5";
3190 if (ssh->version == 2) {
3191 ssh2_add_channel_data(c, sentreply, replylen);
3194 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3195 PKT_INT, c->remoteid,
3198 PKT_DATA, sentreply, replylen,
3207 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3208 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3209 * => log `wire_reason'.
3211 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3212 int code, int clean_exit)
3216 client_reason = wire_reason;
3218 error = dupprintf("Disconnected: %s", client_reason);
3220 error = dupstr("Disconnected");
3222 if (ssh->version == 1) {
3223 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3225 } else if (ssh->version == 2) {
3226 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3227 ssh2_pkt_adduint32(pktout, code);
3228 ssh2_pkt_addstring(pktout, wire_reason);
3229 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3230 ssh2_pkt_send_noqueue(ssh, pktout);
3233 ssh->close_expected = TRUE;
3234 ssh->clean_exit = clean_exit;
3235 ssh_closing((Plug)ssh, error, 0, 0);
3240 * Handle the key exchange and user authentication phases.
3242 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3243 struct Packet *pktin)
3246 unsigned char cookie[8], *ptr;
3247 struct RSAKey servkey, hostkey;
3248 struct MD5Context md5c;
3249 struct do_ssh1_login_state {
3251 unsigned char *rsabuf, *keystr1, *keystr2;
3252 unsigned long supported_ciphers_mask, supported_auths_mask;
3253 int tried_publickey, tried_agent;
3254 int tis_auth_refused, ccard_auth_refused;
3255 unsigned char session_id[16];
3257 void *publickey_blob;
3258 int publickey_bloblen;
3259 char *publickey_comment;
3260 int publickey_encrypted;
3261 prompts_t *cur_prompt;
3264 unsigned char request[5], *response, *p;
3275 crState(do_ssh1_login_state);
3277 crBegin(ssh->do_ssh1_login_crstate);
3282 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3283 bombout(("Public key packet not received"));
3287 logevent("Received public keys");
3289 ptr = ssh_pkt_getdata(pktin, 8);
3291 bombout(("SSH-1 public key packet stopped before random cookie"));
3294 memcpy(cookie, ptr, 8);
3296 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
3297 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
3298 bombout(("Failed to read SSH-1 public keys from public key packet"));
3303 * Log the host key fingerprint.
3307 logevent("Host key fingerprint is:");
3308 strcpy(logmsg, " ");
3309 hostkey.comment = NULL;
3310 rsa_fingerprint(logmsg + strlen(logmsg),
3311 sizeof(logmsg) - strlen(logmsg), &hostkey);
3315 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3316 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3317 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3318 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3319 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3321 ssh->v1_local_protoflags =
3322 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3323 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3326 MD5Update(&md5c, s->keystr2, hostkey.bytes);
3327 MD5Update(&md5c, s->keystr1, servkey.bytes);
3328 MD5Update(&md5c, cookie, 8);
3329 MD5Final(s->session_id, &md5c);
3331 for (i = 0; i < 32; i++)
3332 ssh->session_key[i] = random_byte();
3335 * Verify that the `bits' and `bytes' parameters match.
3337 if (hostkey.bits > hostkey.bytes * 8 ||
3338 servkey.bits > servkey.bytes * 8) {
3339 bombout(("SSH-1 public keys were badly formatted"));
3343 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
3345 s->rsabuf = snewn(s->len, unsigned char);
3348 * Verify the host key.
3352 * First format the key into a string.
3354 int len = rsastr_len(&hostkey);
3355 char fingerprint[100];
3356 char *keystr = snewn(len, char);
3357 rsastr_fmt(keystr, &hostkey);
3358 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
3360 ssh_set_frozen(ssh, 1);
3361 s->dlgret = verify_ssh_host_key(ssh->frontend,
3362 ssh->savedhost, ssh->savedport,
3363 "rsa", keystr, fingerprint,
3364 ssh_dialog_callback, ssh);
3366 if (s->dlgret < 0) {
3370 bombout(("Unexpected data from server while waiting"
3371 " for user host key response"));
3374 } while (pktin || inlen > 0);
3375 s->dlgret = ssh->user_response;
3377 ssh_set_frozen(ssh, 0);
3379 if (s->dlgret == 0) {
3380 ssh_disconnect(ssh, "User aborted at host key verification",
3386 for (i = 0; i < 32; i++) {
3387 s->rsabuf[i] = ssh->session_key[i];
3389 s->rsabuf[i] ^= s->session_id[i];
3392 if (hostkey.bytes > servkey.bytes) {
3393 ret = rsaencrypt(s->rsabuf, 32, &servkey);
3395 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
3397 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
3399 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
3402 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3406 logevent("Encrypted session key");
3409 int cipher_chosen = 0, warn = 0;
3410 char *cipher_string = NULL;
3412 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3413 int next_cipher = conf_get_int_int(ssh->conf,
3414 CONF_ssh_cipherlist, i);
3415 if (next_cipher == CIPHER_WARN) {
3416 /* If/when we choose a cipher, warn about it */
3418 } else if (next_cipher == CIPHER_AES) {
3419 /* XXX Probably don't need to mention this. */
3420 logevent("AES not supported in SSH-1, skipping");
3422 switch (next_cipher) {
3423 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3424 cipher_string = "3DES"; break;
3425 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3426 cipher_string = "Blowfish"; break;
3427 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3428 cipher_string = "single-DES"; break;
3430 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3434 if (!cipher_chosen) {
3435 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3436 bombout(("Server violates SSH-1 protocol by not "
3437 "supporting 3DES encryption"));
3439 /* shouldn't happen */
3440 bombout(("No supported ciphers found"));
3444 /* Warn about chosen cipher if necessary. */
3446 ssh_set_frozen(ssh, 1);
3447 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3448 ssh_dialog_callback, ssh);
3449 if (s->dlgret < 0) {
3453 bombout(("Unexpected data from server while waiting"
3454 " for user response"));
3457 } while (pktin || inlen > 0);
3458 s->dlgret = ssh->user_response;
3460 ssh_set_frozen(ssh, 0);
3461 if (s->dlgret == 0) {
3462 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3469 switch (s->cipher_type) {
3470 case SSH_CIPHER_3DES:
3471 logevent("Using 3DES encryption");
3473 case SSH_CIPHER_DES:
3474 logevent("Using single-DES encryption");
3476 case SSH_CIPHER_BLOWFISH:
3477 logevent("Using Blowfish encryption");
3481 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3482 PKT_CHAR, s->cipher_type,
3483 PKT_DATA, cookie, 8,
3484 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3485 PKT_DATA, s->rsabuf, s->len,
3486 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3488 logevent("Trying to enable encryption...");
3492 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3493 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3495 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3496 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3497 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3499 ssh->crcda_ctx = crcda_make_context();
3500 logevent("Installing CRC compensation attack detector");
3502 if (servkey.modulus) {
3503 sfree(servkey.modulus);
3504 servkey.modulus = NULL;
3506 if (servkey.exponent) {
3507 sfree(servkey.exponent);
3508 servkey.exponent = NULL;
3510 if (hostkey.modulus) {
3511 sfree(hostkey.modulus);
3512 hostkey.modulus = NULL;
3514 if (hostkey.exponent) {
3515 sfree(hostkey.exponent);
3516 hostkey.exponent = NULL;
3520 if (pktin->type != SSH1_SMSG_SUCCESS) {
3521 bombout(("Encryption not successfully enabled"));
3525 logevent("Successfully started encryption");
3527 fflush(stdout); /* FIXME eh? */
3529 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
3530 int ret; /* need not be kept over crReturn */
3531 s->cur_prompt = new_prompts(ssh->frontend);
3532 s->cur_prompt->to_server = TRUE;
3533 s->cur_prompt->name = dupstr("SSH login name");
3534 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
3535 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3538 crWaitUntil(!pktin);
3539 ret = get_userpass_input(s->cur_prompt, in, inlen);
3544 * Failed to get a username. Terminate.
3546 free_prompts(s->cur_prompt);
3547 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3550 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
3551 free_prompts(s->cur_prompt);
3554 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
3556 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
3558 if (flags & FLAG_INTERACTIVE &&
3559 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3560 c_write_str(ssh, userlog);
3561 c_write_str(ssh, "\r\n");
3569 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3570 /* We must not attempt PK auth. Pretend we've already tried it. */
3571 s->tried_publickey = s->tried_agent = 1;
3573 s->tried_publickey = s->tried_agent = 0;
3575 s->tis_auth_refused = s->ccard_auth_refused = 0;
3577 * Load the public half of any configured keyfile for later use.
3579 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3580 if (!filename_is_null(s->keyfile)) {
3582 logeventf(ssh, "Reading private key file \"%.150s\"",
3583 filename_to_str(s->keyfile));
3584 keytype = key_type(s->keyfile);
3585 if (keytype == SSH_KEYTYPE_SSH1) {
3587 if (rsakey_pubblob(s->keyfile,
3588 &s->publickey_blob, &s->publickey_bloblen,
3589 &s->publickey_comment, &error)) {
3590 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
3594 logeventf(ssh, "Unable to load private key (%s)", error);
3595 msgbuf = dupprintf("Unable to load private key file "
3596 "\"%.150s\" (%s)\r\n",
3597 filename_to_str(s->keyfile),
3599 c_write_str(ssh, msgbuf);
3601 s->publickey_blob = NULL;
3605 logeventf(ssh, "Unable to use this key file (%s)",
3606 key_type_to_str(keytype));
3607 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3609 filename_to_str(s->keyfile),
3610 key_type_to_str(keytype));
3611 c_write_str(ssh, msgbuf);
3613 s->publickey_blob = NULL;
3616 s->publickey_blob = NULL;
3618 while (pktin->type == SSH1_SMSG_FAILURE) {
3619 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3621 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
3623 * Attempt RSA authentication using Pageant.
3629 logevent("Pageant is running. Requesting keys.");
3631 /* Request the keys held by the agent. */
3632 PUT_32BIT(s->request, 1);
3633 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3634 if (!agent_query(s->request, 5, &r, &s->responselen,
3635 ssh_agent_callback, ssh)) {
3639 bombout(("Unexpected data from server while waiting"
3640 " for agent response"));
3643 } while (pktin || inlen > 0);
3644 r = ssh->agent_response;
3645 s->responselen = ssh->agent_response_len;
3647 s->response = (unsigned char *) r;
3648 if (s->response && s->responselen >= 5 &&
3649 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3650 s->p = s->response + 5;
3651 s->nkeys = GET_32BIT(s->p);
3653 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3654 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3655 unsigned char *pkblob = s->p;
3659 do { /* do while (0) to make breaking easy */
3660 n = ssh1_read_bignum
3661 (s->p, s->responselen-(s->p-s->response),
3666 n = ssh1_read_bignum
3667 (s->p, s->responselen-(s->p-s->response),
3672 if (s->responselen - (s->p-s->response) < 4)
3674 s->commentlen = GET_32BIT(s->p);
3676 if (s->responselen - (s->p-s->response) <
3679 s->commentp = (char *)s->p;
3680 s->p += s->commentlen;
3684 logevent("Pageant key list packet was truncated");
3688 if (s->publickey_blob) {
3689 if (!memcmp(pkblob, s->publickey_blob,
3690 s->publickey_bloblen)) {
3691 logeventf(ssh, "Pageant key #%d matches "
3692 "configured key file", s->keyi);
3693 s->tried_publickey = 1;
3695 /* Skip non-configured key */
3698 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3699 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3700 PKT_BIGNUM, s->key.modulus, PKT_END);
3702 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3703 logevent("Key refused");
3706 logevent("Received RSA challenge");
3707 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3708 bombout(("Server's RSA challenge was badly formatted"));
3713 char *agentreq, *q, *ret;
3716 len = 1 + 4; /* message type, bit count */
3717 len += ssh1_bignum_length(s->key.exponent);
3718 len += ssh1_bignum_length(s->key.modulus);
3719 len += ssh1_bignum_length(s->challenge);
3720 len += 16; /* session id */
3721 len += 4; /* response format */
3722 agentreq = snewn(4 + len, char);
3723 PUT_32BIT(agentreq, len);
3725 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3726 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3728 q += ssh1_write_bignum(q, s->key.exponent);
3729 q += ssh1_write_bignum(q, s->key.modulus);
3730 q += ssh1_write_bignum(q, s->challenge);
3731 memcpy(q, s->session_id, 16);
3733 PUT_32BIT(q, 1); /* response format */
3734 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3735 ssh_agent_callback, ssh)) {
3740 bombout(("Unexpected data from server"
3741 " while waiting for agent"
3745 } while (pktin || inlen > 0);
3746 vret = ssh->agent_response;
3747 retlen = ssh->agent_response_len;
3752 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3753 logevent("Sending Pageant's response");
3754 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3755 PKT_DATA, ret + 5, 16,
3759 if (pktin->type == SSH1_SMSG_SUCCESS) {
3761 ("Pageant's response accepted");
3762 if (flags & FLAG_VERBOSE) {
3763 c_write_str(ssh, "Authenticated using"
3765 c_write(ssh, s->commentp,
3767 c_write_str(ssh, "\" from agent\r\n");
3772 ("Pageant's response not accepted");
3775 ("Pageant failed to answer challenge");
3779 logevent("No reply received from Pageant");
3782 freebn(s->key.exponent);
3783 freebn(s->key.modulus);
3784 freebn(s->challenge);
3789 if (s->publickey_blob && !s->tried_publickey)
3790 logevent("Configured key file not in Pageant");
3792 logevent("Failed to get reply from Pageant");
3797 if (s->publickey_blob && !s->tried_publickey) {
3799 * Try public key authentication with the specified
3802 int got_passphrase; /* need not be kept over crReturn */
3803 if (flags & FLAG_VERBOSE)
3804 c_write_str(ssh, "Trying public key authentication.\r\n");
3805 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3806 logeventf(ssh, "Trying public key \"%s\"",
3807 filename_to_str(s->keyfile));
3808 s->tried_publickey = 1;
3809 got_passphrase = FALSE;
3810 while (!got_passphrase) {
3812 * Get a passphrase, if necessary.
3814 char *passphrase = NULL; /* only written after crReturn */
3816 if (!s->publickey_encrypted) {
3817 if (flags & FLAG_VERBOSE)
3818 c_write_str(ssh, "No passphrase required.\r\n");
3821 int ret; /* need not be kept over crReturn */
3822 s->cur_prompt = new_prompts(ssh->frontend);
3823 s->cur_prompt->to_server = FALSE;
3824 s->cur_prompt->name = dupstr("SSH key passphrase");
3825 add_prompt(s->cur_prompt,
3826 dupprintf("Passphrase for key \"%.100s\": ",
3827 s->publickey_comment), FALSE);
3828 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3831 crWaitUntil(!pktin);
3832 ret = get_userpass_input(s->cur_prompt, in, inlen);
3836 /* Failed to get a passphrase. Terminate. */
3837 free_prompts(s->cur_prompt);
3838 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3842 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3843 free_prompts(s->cur_prompt);
3846 * Try decrypting key with passphrase.
3848 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3849 ret = loadrsakey(s->keyfile, &s->key, passphrase,
3852 memset(passphrase, 0, strlen(passphrase));
3856 /* Correct passphrase. */
3857 got_passphrase = TRUE;
3858 } else if (ret == 0) {
3859 c_write_str(ssh, "Couldn't load private key from ");
3860 c_write_str(ssh, filename_to_str(s->keyfile));
3861 c_write_str(ssh, " (");
3862 c_write_str(ssh, error);
3863 c_write_str(ssh, ").\r\n");
3864 got_passphrase = FALSE;
3865 break; /* go and try something else */
3866 } else if (ret == -1) {
3867 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3868 got_passphrase = FALSE;
3871 assert(0 && "unexpected return from loadrsakey()");
3872 got_passphrase = FALSE; /* placate optimisers */
3876 if (got_passphrase) {
3879 * Send a public key attempt.
3881 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3882 PKT_BIGNUM, s->key.modulus, PKT_END);
3885 if (pktin->type == SSH1_SMSG_FAILURE) {
3886 c_write_str(ssh, "Server refused our public key.\r\n");
3887 continue; /* go and try something else */
3889 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3890 bombout(("Bizarre response to offer of public key"));
3896 unsigned char buffer[32];
3897 Bignum challenge, response;
3899 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3900 bombout(("Server's RSA challenge was badly formatted"));
3903 response = rsadecrypt(challenge, &s->key);
3904 freebn(s->key.private_exponent);/* burn the evidence */
3906 for (i = 0; i < 32; i++) {
3907 buffer[i] = bignum_byte(response, 31 - i);
3911 MD5Update(&md5c, buffer, 32);
3912 MD5Update(&md5c, s->session_id, 16);
3913 MD5Final(buffer, &md5c);
3915 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3916 PKT_DATA, buffer, 16, PKT_END);
3923 if (pktin->type == SSH1_SMSG_FAILURE) {
3924 if (flags & FLAG_VERBOSE)
3925 c_write_str(ssh, "Failed to authenticate with"
3926 " our public key.\r\n");
3927 continue; /* go and try something else */
3928 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3929 bombout(("Bizarre response to RSA authentication response"));
3933 break; /* we're through! */
3939 * Otherwise, try various forms of password-like authentication.
3941 s->cur_prompt = new_prompts(ssh->frontend);
3943 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3944 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3945 !s->tis_auth_refused) {
3946 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3947 logevent("Requested TIS authentication");
3948 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3950 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3951 logevent("TIS authentication declined");
3952 if (flags & FLAG_INTERACTIVE)
3953 c_write_str(ssh, "TIS authentication refused.\r\n");
3954 s->tis_auth_refused = 1;
3959 char *instr_suf, *prompt;
3961 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3963 bombout(("TIS challenge packet was badly formed"));
3966 logevent("Received TIS challenge");
3967 s->cur_prompt->to_server = TRUE;
3968 s->cur_prompt->name = dupstr("SSH TIS authentication");
3969 /* Prompt heuristic comes from OpenSSH */
3970 if (memchr(challenge, '\n', challengelen)) {
3971 instr_suf = dupstr("");
3972 prompt = dupprintf("%.*s", challengelen, challenge);
3974 instr_suf = dupprintf("%.*s", challengelen, challenge);
3975 prompt = dupstr("Response: ");
3977 s->cur_prompt->instruction =
3978 dupprintf("Using TIS authentication.%s%s",
3979 (*instr_suf) ? "\n" : "",
3981 s->cur_prompt->instr_reqd = TRUE;
3982 add_prompt(s->cur_prompt, prompt, FALSE);
3986 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3987 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3988 !s->ccard_auth_refused) {
3989 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3990 logevent("Requested CryptoCard authentication");
3991 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3993 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3994 logevent("CryptoCard authentication declined");
3995 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3996 s->ccard_auth_refused = 1;
4001 char *instr_suf, *prompt;
4003 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4005 bombout(("CryptoCard challenge packet was badly formed"));
4008 logevent("Received CryptoCard challenge");
4009 s->cur_prompt->to_server = TRUE;
4010 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4011 s->cur_prompt->name_reqd = FALSE;
4012 /* Prompt heuristic comes from OpenSSH */
4013 if (memchr(challenge, '\n', challengelen)) {
4014 instr_suf = dupstr("");
4015 prompt = dupprintf("%.*s", challengelen, challenge);
4017 instr_suf = dupprintf("%.*s", challengelen, challenge);
4018 prompt = dupstr("Response: ");
4020 s->cur_prompt->instruction =
4021 dupprintf("Using CryptoCard authentication.%s%s",
4022 (*instr_suf) ? "\n" : "",
4024 s->cur_prompt->instr_reqd = TRUE;
4025 add_prompt(s->cur_prompt, prompt, FALSE);
4029 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4030 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4031 bombout(("No supported authentication methods available"));
4034 s->cur_prompt->to_server = TRUE;
4035 s->cur_prompt->name = dupstr("SSH password");
4036 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4037 ssh->username, ssh->savedhost),
4042 * Show password prompt, having first obtained it via a TIS
4043 * or CryptoCard exchange if we're doing TIS or CryptoCard
4047 int ret; /* need not be kept over crReturn */
4048 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4051 crWaitUntil(!pktin);
4052 ret = get_userpass_input(s->cur_prompt, in, inlen);
4057 * Failed to get a password (for example
4058 * because one was supplied on the command line
4059 * which has already failed to work). Terminate.
4061 free_prompts(s->cur_prompt);
4062 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4067 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4069 * Defence against traffic analysis: we send a
4070 * whole bunch of packets containing strings of
4071 * different lengths. One of these strings is the
4072 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4073 * The others are all random data in
4074 * SSH1_MSG_IGNORE packets. This way a passive
4075 * listener can't tell which is the password, and
4076 * hence can't deduce the password length.
4078 * Anybody with a password length greater than 16
4079 * bytes is going to have enough entropy in their
4080 * password that a listener won't find it _that_
4081 * much help to know how long it is. So what we'll
4084 * - if password length < 16, we send 15 packets
4085 * containing string lengths 1 through 15
4087 * - otherwise, we let N be the nearest multiple
4088 * of 8 below the password length, and send 8
4089 * packets containing string lengths N through
4090 * N+7. This won't obscure the order of
4091 * magnitude of the password length, but it will
4092 * introduce a bit of extra uncertainty.
4094 * A few servers can't deal with SSH1_MSG_IGNORE, at
4095 * least in this context. For these servers, we need
4096 * an alternative defence. We make use of the fact
4097 * that the password is interpreted as a C string:
4098 * so we can append a NUL, then some random data.
4100 * A few servers can deal with neither SSH1_MSG_IGNORE
4101 * here _nor_ a padded password string.
4102 * For these servers we are left with no defences
4103 * against password length sniffing.
4105 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4106 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4108 * The server can deal with SSH1_MSG_IGNORE, so
4109 * we can use the primary defence.
4111 int bottom, top, pwlen, i;
4114 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4116 bottom = 0; /* zero length passwords are OK! :-) */
4119 bottom = pwlen & ~7;
4123 assert(pwlen >= bottom && pwlen <= top);
4125 randomstr = snewn(top + 1, char);
4127 for (i = bottom; i <= top; i++) {
4129 defer_packet(ssh, s->pwpkt_type,
4130 PKTT_PASSWORD, PKT_STR,
4131 s->cur_prompt->prompts[0]->result,
4132 PKTT_OTHER, PKT_END);
4134 for (j = 0; j < i; j++) {
4136 randomstr[j] = random_byte();
4137 } while (randomstr[j] == '\0');
4139 randomstr[i] = '\0';
4140 defer_packet(ssh, SSH1_MSG_IGNORE,
4141 PKT_STR, randomstr, PKT_END);
4144 logevent("Sending password with camouflage packets");
4145 ssh_pkt_defersend(ssh);
4148 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4150 * The server can't deal with SSH1_MSG_IGNORE
4151 * but can deal with padded passwords, so we
4152 * can use the secondary defence.
4158 len = strlen(s->cur_prompt->prompts[0]->result);
4159 if (len < sizeof(string)) {
4161 strcpy(string, s->cur_prompt->prompts[0]->result);
4162 len++; /* cover the zero byte */
4163 while (len < sizeof(string)) {
4164 string[len++] = (char) random_byte();
4167 ss = s->cur_prompt->prompts[0]->result;
4169 logevent("Sending length-padded password");
4170 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4171 PKT_INT, len, PKT_DATA, ss, len,
4172 PKTT_OTHER, PKT_END);
4175 * The server is believed unable to cope with
4176 * any of our password camouflage methods.
4179 len = strlen(s->cur_prompt->prompts[0]->result);
4180 logevent("Sending unpadded password");
4181 send_packet(ssh, s->pwpkt_type,
4182 PKTT_PASSWORD, PKT_INT, len,
4183 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4184 PKTT_OTHER, PKT_END);
4187 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4188 PKT_STR, s->cur_prompt->prompts[0]->result,
4189 PKTT_OTHER, PKT_END);
4191 logevent("Sent password");
4192 free_prompts(s->cur_prompt);
4194 if (pktin->type == SSH1_SMSG_FAILURE) {
4195 if (flags & FLAG_VERBOSE)
4196 c_write_str(ssh, "Access denied\r\n");
4197 logevent("Authentication refused");
4198 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4199 bombout(("Strange packet received, type %d", pktin->type));
4205 if (s->publickey_blob) {
4206 sfree(s->publickey_blob);
4207 sfree(s->publickey_comment);
4210 logevent("Authentication successful");
4215 static void ssh_channel_try_eof(struct ssh_channel *c)
4218 assert(c->pending_eof); /* precondition for calling us */
4220 return; /* can't close: not even opened yet */
4221 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4222 return; /* can't send EOF: pending outgoing data */
4224 if (ssh->version == 1) {
4225 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4227 c->closes |= CLOSES_SENT_EOF;
4229 struct Packet *pktout;
4230 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4231 ssh2_pkt_adduint32(pktout, c->remoteid);
4232 ssh2_pkt_send(ssh, pktout);
4233 c->closes |= CLOSES_SENT_EOF;
4234 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes)) {
4236 * Also send MSG_CLOSE.
4238 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4239 ssh2_pkt_adduint32(pktout, c->remoteid);
4240 ssh2_pkt_send(ssh, pktout);
4241 c->closes |= CLOSES_SENT_CLOSE;
4244 c->pending_eof = FALSE; /* we've sent it now */
4247 void sshfwd_write_eof(struct ssh_channel *c)
4251 if (ssh->state == SSH_STATE_CLOSED)
4254 if (c->closes & CLOSES_SENT_EOF)
4257 c->pending_eof = TRUE;
4258 ssh_channel_try_eof(c);
4261 void sshfwd_unclean_close(struct ssh_channel *c)
4264 struct Packet *pktout;
4266 if (ssh->state == SSH_STATE_CLOSED)
4269 if (!(c->closes & CLOSES_SENT_CLOSE)) {
4270 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4271 ssh2_pkt_adduint32(pktout, c->remoteid);
4272 ssh2_pkt_send(ssh, pktout);
4273 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
4278 x11_close(c->u.x11.s);
4281 case CHAN_SOCKDATA_DORMANT:
4282 pfd_close(c->u.pfd.s);
4285 c->type = CHAN_ZOMBIE;
4287 ssh2_channel_check_close(c);
4290 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4294 if (ssh->state == SSH_STATE_CLOSED)
4297 if (ssh->version == 1) {
4298 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4299 PKT_INT, c->remoteid,
4300 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
4301 PKTT_OTHER, PKT_END);
4303 * In SSH-1 we can return 0 here - implying that forwarded
4304 * connections are never individually throttled - because
4305 * the only circumstance that can cause throttling will be
4306 * the whole SSH connection backing up, in which case
4307 * _everything_ will be throttled as a whole.
4311 ssh2_add_channel_data(c, buf, len);
4312 return ssh2_try_send(c);
4316 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4321 if (ssh->state == SSH_STATE_CLOSED)
4324 if (ssh->version == 1) {
4325 buflimit = SSH1_BUFFER_LIMIT;
4327 buflimit = c->v.v2.locmaxwin;
4328 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4330 if (c->throttling_conn && bufsize <= buflimit) {
4331 c->throttling_conn = 0;
4332 ssh_throttle_conn(ssh, -1);
4336 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4338 struct queued_handler *qh = ssh->qhead;
4342 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4345 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4346 ssh->packet_dispatch[qh->msg1] = NULL;
4349 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4350 ssh->packet_dispatch[qh->msg2] = NULL;
4354 ssh->qhead = qh->next;
4356 if (ssh->qhead->msg1 > 0) {
4357 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
4358 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4360 if (ssh->qhead->msg2 > 0) {
4361 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
4362 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4365 ssh->qhead = ssh->qtail = NULL;
4366 ssh->packet_dispatch[pktin->type] = NULL;
4369 qh->handler(ssh, pktin, qh->ctx);
4374 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4375 chandler_fn_t handler, void *ctx)
4377 struct queued_handler *qh;
4379 qh = snew(struct queued_handler);
4382 qh->handler = handler;
4386 if (ssh->qtail == NULL) {
4390 assert(ssh->packet_dispatch[qh->msg1] == NULL);
4391 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4394 assert(ssh->packet_dispatch[qh->msg2] == NULL);
4395 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4398 ssh->qtail->next = qh;
4403 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4405 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4407 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4408 SSH2_MSG_REQUEST_SUCCESS)) {
4409 logeventf(ssh, "Remote port forwarding from %s enabled",
4412 logeventf(ssh, "Remote port forwarding from %s refused",
4415 rpf = del234(ssh->rportfwds, pf);
4417 pf->pfrec->remote = NULL;
4422 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4424 struct ssh_portfwd *epf;
4428 if (!ssh->portfwds) {
4429 ssh->portfwds = newtree234(ssh_portcmp);
4432 * Go through the existing port forwardings and tag them
4433 * with status==DESTROY. Any that we want to keep will be
4434 * re-enabled (status==KEEP) as we go through the
4435 * configuration and find out which bits are the same as
4438 struct ssh_portfwd *epf;
4440 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4441 epf->status = DESTROY;
4444 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
4446 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
4447 char *kp, *kp2, *vp, *vp2;
4448 char address_family, type;
4449 int sport,dport,sserv,dserv;
4450 char *sports, *dports, *saddr, *host;
4454 address_family = 'A';
4456 if (*kp == 'A' || *kp == '4' || *kp == '6')
4457 address_family = *kp++;
4458 if (*kp == 'L' || *kp == 'R')
4461 if ((kp2 = strchr(kp, ':')) != NULL) {
4463 * There's a colon in the middle of the source port
4464 * string, which means that the part before it is
4465 * actually a source address.
4467 saddr = dupprintf("%.*s", (int)(kp2 - kp), kp);
4473 sport = atoi(sports);
4477 sport = net_service_lookup(sports);
4479 logeventf(ssh, "Service lookup failed for source"
4480 " port \"%s\"", sports);
4484 if (type == 'L' && !strcmp(val, "D")) {
4485 /* dynamic forwarding */
4492 /* ordinary forwarding */
4494 vp2 = vp + strcspn(vp, ":");
4495 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
4499 dport = atoi(dports);
4503 dport = net_service_lookup(dports);
4505 logeventf(ssh, "Service lookup failed for destination"
4506 " port \"%s\"", dports);
4511 if (sport && dport) {
4512 /* Set up a description of the source port. */
4513 struct ssh_portfwd *pfrec, *epfrec;
4515 pfrec = snew(struct ssh_portfwd);
4517 pfrec->saddr = saddr;
4518 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4519 pfrec->sport = sport;
4520 pfrec->daddr = host;
4521 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4522 pfrec->dport = dport;
4523 pfrec->local = NULL;
4524 pfrec->remote = NULL;
4525 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4526 address_family == '6' ? ADDRTYPE_IPV6 :
4529 epfrec = add234(ssh->portfwds, pfrec);
4530 if (epfrec != pfrec) {
4531 if (epfrec->status == DESTROY) {
4533 * We already have a port forwarding up and running
4534 * with precisely these parameters. Hence, no need
4535 * to do anything; simply re-tag the existing one
4538 epfrec->status = KEEP;
4541 * Anything else indicates that there was a duplicate
4542 * in our input, which we'll silently ignore.
4544 free_portfwd(pfrec);
4546 pfrec->status = CREATE;
4555 * Now go through and destroy any port forwardings which were
4558 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4559 if (epf->status == DESTROY) {
4562 message = dupprintf("%s port forwarding from %s%s%d",
4563 epf->type == 'L' ? "local" :
4564 epf->type == 'R' ? "remote" : "dynamic",
4565 epf->saddr ? epf->saddr : "",
4566 epf->saddr ? ":" : "",
4569 if (epf->type != 'D') {
4570 char *msg2 = dupprintf("%s to %s:%d", message,
4571 epf->daddr, epf->dport);
4576 logeventf(ssh, "Cancelling %s", message);
4579 /* epf->remote or epf->local may be NULL if setting up a
4580 * forwarding failed. */
4582 struct ssh_rportfwd *rpf = epf->remote;
4583 struct Packet *pktout;
4586 * Cancel the port forwarding at the server
4589 if (ssh->version == 1) {
4591 * We cannot cancel listening ports on the
4592 * server side in SSH-1! There's no message
4593 * to support it. Instead, we simply remove
4594 * the rportfwd record from the local end
4595 * so that any connections the server tries
4596 * to make on it are rejected.
4599 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4600 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4601 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4603 ssh2_pkt_addstring(pktout, epf->saddr);
4604 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4605 /* XXX: rport_acceptall may not represent
4606 * what was used to open the original connection,
4607 * since it's reconfigurable. */
4608 ssh2_pkt_addstring(pktout, "0.0.0.0");
4610 ssh2_pkt_addstring(pktout, "127.0.0.1");
4612 ssh2_pkt_adduint32(pktout, epf->sport);
4613 ssh2_pkt_send(ssh, pktout);
4616 del234(ssh->rportfwds, rpf);
4618 } else if (epf->local) {
4619 pfd_terminate(epf->local);
4622 delpos234(ssh->portfwds, i);
4624 i--; /* so we don't skip one in the list */
4628 * And finally, set up any new port forwardings (status==CREATE).
4630 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4631 if (epf->status == CREATE) {
4632 char *sportdesc, *dportdesc;
4633 sportdesc = dupprintf("%s%s%s%s%d%s",
4634 epf->saddr ? epf->saddr : "",
4635 epf->saddr ? ":" : "",
4636 epf->sserv ? epf->sserv : "",
4637 epf->sserv ? "(" : "",
4639 epf->sserv ? ")" : "");
4640 if (epf->type == 'D') {
4643 dportdesc = dupprintf("%s:%s%s%d%s",
4645 epf->dserv ? epf->dserv : "",
4646 epf->dserv ? "(" : "",
4648 epf->dserv ? ")" : "");
4651 if (epf->type == 'L') {
4652 const char *err = pfd_addforward(epf->daddr, epf->dport,
4653 epf->saddr, epf->sport,
4656 epf->addressfamily);
4658 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4659 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4660 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4661 sportdesc, dportdesc,
4662 err ? " failed: " : "", err ? err : "");
4663 } else if (epf->type == 'D') {
4664 const char *err = pfd_addforward(NULL, -1,
4665 epf->saddr, epf->sport,
4668 epf->addressfamily);
4670 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4671 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4672 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4674 err ? " failed: " : "", err ? err : "");
4676 struct ssh_rportfwd *pf;
4679 * Ensure the remote port forwardings tree exists.
4681 if (!ssh->rportfwds) {
4682 if (ssh->version == 1)
4683 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4685 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4688 pf = snew(struct ssh_rportfwd);
4689 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4690 pf->dhost[lenof(pf->dhost)-1] = '\0';
4691 pf->dport = epf->dport;
4692 pf->sport = epf->sport;
4693 if (add234(ssh->rportfwds, pf) != pf) {
4694 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4695 epf->daddr, epf->dport);
4698 logeventf(ssh, "Requesting remote port %s"
4699 " forward to %s", sportdesc, dportdesc);
4701 pf->sportdesc = sportdesc;
4706 if (ssh->version == 1) {
4707 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4708 PKT_INT, epf->sport,
4709 PKT_STR, epf->daddr,
4710 PKT_INT, epf->dport,
4712 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4714 ssh_rportfwd_succfail, pf);
4716 struct Packet *pktout;
4717 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4718 ssh2_pkt_addstring(pktout, "tcpip-forward");
4719 ssh2_pkt_addbool(pktout, 1);/* want reply */
4721 ssh2_pkt_addstring(pktout, epf->saddr);
4722 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4723 ssh2_pkt_addstring(pktout, "0.0.0.0");
4725 ssh2_pkt_addstring(pktout, "127.0.0.1");
4727 ssh2_pkt_adduint32(pktout, epf->sport);
4728 ssh2_pkt_send(ssh, pktout);
4730 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4731 SSH2_MSG_REQUEST_FAILURE,
4732 ssh_rportfwd_succfail, pf);
4741 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4744 int stringlen, bufsize;
4746 ssh_pkt_getstring(pktin, &string, &stringlen);
4747 if (string == NULL) {
4748 bombout(("Incoming terminal data packet was badly formed"));
4752 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4754 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4755 ssh->v1_stdout_throttling = 1;
4756 ssh_throttle_conn(ssh, +1);
4760 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4762 /* Remote side is trying to open a channel to talk to our
4763 * X-Server. Give them back a local channel number. */
4764 struct ssh_channel *c;
4765 int remoteid = ssh_pkt_getuint32(pktin);
4767 logevent("Received X11 connect request");
4768 /* Refuse if X11 forwarding is disabled. */
4769 if (!ssh->X11_fwd_enabled) {
4770 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4771 PKT_INT, remoteid, PKT_END);
4772 logevent("Rejected X11 connect request");
4774 c = snew(struct ssh_channel);
4777 if (x11_init(&c->u.x11.s, ssh->x11disp, c,
4778 NULL, -1, ssh->conf) != NULL) {
4779 logevent("Opening X11 forward connection failed");
4781 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4782 PKT_INT, remoteid, PKT_END);
4785 ("Opening X11 forward connection succeeded");
4786 c->remoteid = remoteid;
4787 c->halfopen = FALSE;
4788 c->localid = alloc_channel_id(ssh);
4790 c->pending_eof = FALSE;
4791 c->throttling_conn = 0;
4792 c->type = CHAN_X11; /* identify channel type */
4793 add234(ssh->channels, c);
4794 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4795 PKT_INT, c->remoteid, PKT_INT,
4796 c->localid, PKT_END);
4797 logevent("Opened X11 forward channel");
4802 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4804 /* Remote side is trying to open a channel to talk to our
4805 * agent. Give them back a local channel number. */
4806 struct ssh_channel *c;
4807 int remoteid = ssh_pkt_getuint32(pktin);
4809 /* Refuse if agent forwarding is disabled. */
4810 if (!ssh->agentfwd_enabled) {
4811 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4812 PKT_INT, remoteid, PKT_END);
4814 c = snew(struct ssh_channel);
4816 c->remoteid = remoteid;
4817 c->halfopen = FALSE;
4818 c->localid = alloc_channel_id(ssh);
4820 c->pending_eof = FALSE;
4821 c->throttling_conn = 0;
4822 c->type = CHAN_AGENT; /* identify channel type */
4823 c->u.a.lensofar = 0;
4824 c->u.a.message = NULL;
4825 add234(ssh->channels, c);
4826 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4827 PKT_INT, c->remoteid, PKT_INT, c->localid,
4832 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4834 /* Remote side is trying to open a channel to talk to a
4835 * forwarded port. Give them back a local channel number. */
4836 struct ssh_channel *c;
4837 struct ssh_rportfwd pf, *pfp;
4842 c = snew(struct ssh_channel);
4845 remoteid = ssh_pkt_getuint32(pktin);
4846 ssh_pkt_getstring(pktin, &host, &hostsize);
4847 port = ssh_pkt_getuint32(pktin);
4849 if (hostsize >= lenof(pf.dhost))
4850 hostsize = lenof(pf.dhost)-1;
4851 memcpy(pf.dhost, host, hostsize);
4852 pf.dhost[hostsize] = '\0';
4854 pfp = find234(ssh->rportfwds, &pf, NULL);
4857 logeventf(ssh, "Rejected remote port open request for %s:%d",
4859 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4860 PKT_INT, remoteid, PKT_END);
4862 logeventf(ssh, "Received remote port open request for %s:%d",
4864 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4865 c, ssh->conf, pfp->pfrec->addressfamily);
4867 logeventf(ssh, "Port open failed: %s", e);
4869 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4870 PKT_INT, remoteid, PKT_END);
4872 c->remoteid = remoteid;
4873 c->halfopen = FALSE;
4874 c->localid = alloc_channel_id(ssh);
4876 c->pending_eof = FALSE;
4877 c->throttling_conn = 0;
4878 c->type = CHAN_SOCKDATA; /* identify channel type */
4879 add234(ssh->channels, c);
4880 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4881 PKT_INT, c->remoteid, PKT_INT,
4882 c->localid, PKT_END);
4883 logevent("Forwarded port opened successfully");
4888 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4890 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4891 unsigned int localid = ssh_pkt_getuint32(pktin);
4892 struct ssh_channel *c;
4894 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4895 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4896 c->remoteid = localid;
4897 c->halfopen = FALSE;
4898 c->type = CHAN_SOCKDATA;
4899 c->throttling_conn = 0;
4900 pfd_confirm(c->u.pfd.s);
4903 if (c && c->pending_eof) {
4905 * We have a pending close on this channel,
4906 * which we decided on before the server acked
4907 * the channel open. So now we know the
4908 * remoteid, we can close it again.
4910 ssh_channel_try_eof(c);
4914 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4916 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4917 struct ssh_channel *c;
4919 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4920 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4921 logevent("Forwarded connection refused by server");
4922 pfd_close(c->u.pfd.s);
4923 del234(ssh->channels, c);
4928 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4930 /* Remote side closes a channel. */
4931 unsigned i = ssh_pkt_getuint32(pktin);
4932 struct ssh_channel *c;
4933 c = find234(ssh->channels, &i, ssh_channelfind);
4934 if (c && !c->halfopen) {
4936 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
4937 !(c->closes & CLOSES_RCVD_EOF)) {
4939 * Received CHANNEL_CLOSE, which we translate into
4942 int send_close = FALSE;
4944 c->closes |= CLOSES_RCVD_EOF;
4949 x11_send_eof(c->u.x11.s);
4954 x11_send_eof(c->u.pfd.s);
4961 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
4962 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4964 c->closes |= CLOSES_SENT_EOF;
4968 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
4969 !(c->closes & CLOSES_RCVD_CLOSE)) {
4971 if (!(c->closes & CLOSES_SENT_EOF)) {
4972 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
4973 " for which we never sent CHANNEL_CLOSE\n", i));
4976 c->closes |= CLOSES_RCVD_CLOSE;
4979 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
4980 !(c->closes & CLOSES_SENT_CLOSE)) {
4981 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
4982 PKT_INT, c->remoteid, PKT_END);
4983 c->closes |= CLOSES_SENT_CLOSE;
4986 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
4987 ssh_channel_destroy(c);
4989 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4990 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4991 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4996 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4998 /* Data sent down one of our channels. */
4999 int i = ssh_pkt_getuint32(pktin);
5002 struct ssh_channel *c;
5004 ssh_pkt_getstring(pktin, &p, &len);
5006 c = find234(ssh->channels, &i, ssh_channelfind);
5011 bufsize = x11_send(c->u.x11.s, p, len);
5014 bufsize = pfd_send(c->u.pfd.s, p, len);
5017 /* Data for an agent message. Buffer it. */
5019 if (c->u.a.lensofar < 4) {
5020 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5021 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5025 c->u.a.lensofar += l;
5027 if (c->u.a.lensofar == 4) {
5029 4 + GET_32BIT(c->u.a.msglen);
5030 c->u.a.message = snewn(c->u.a.totallen,
5032 memcpy(c->u.a.message, c->u.a.msglen, 4);
5034 if (c->u.a.lensofar >= 4 && len > 0) {
5036 min(c->u.a.totallen - c->u.a.lensofar,
5038 memcpy(c->u.a.message + c->u.a.lensofar, p,
5042 c->u.a.lensofar += l;
5044 if (c->u.a.lensofar == c->u.a.totallen) {
5047 if (agent_query(c->u.a.message,
5050 ssh_agentf_callback, c))
5051 ssh_agentf_callback(c, reply, replylen);
5052 sfree(c->u.a.message);
5053 c->u.a.lensofar = 0;
5056 bufsize = 0; /* agent channels never back up */
5059 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5060 c->throttling_conn = 1;
5061 ssh_throttle_conn(ssh, +1);
5066 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5068 ssh->exitcode = ssh_pkt_getuint32(pktin);
5069 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5070 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5072 * In case `helpful' firewalls or proxies tack
5073 * extra human-readable text on the end of the
5074 * session which we might mistake for another
5075 * encrypted packet, we close the session once
5076 * we've sent EXIT_CONFIRMATION.
5078 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5081 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5082 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5084 struct Packet *pktout = (struct Packet *)data;
5086 unsigned int arg = 0;
5087 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5088 if (i == lenof(ssh_ttymodes)) return;
5089 switch (ssh_ttymodes[i].type) {
5091 arg = ssh_tty_parse_specchar(val);
5094 arg = ssh_tty_parse_boolean(val);
5097 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5098 ssh2_pkt_addbyte(pktout, arg);
5102 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5103 struct Packet *pktin)
5105 crBegin(ssh->do_ssh1_connection_crstate);
5107 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5108 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5109 ssh1_smsg_stdout_stderr_data;
5111 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5112 ssh1_msg_channel_open_confirmation;
5113 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5114 ssh1_msg_channel_open_failure;
5115 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5116 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5117 ssh1_msg_channel_close;
5118 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5119 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5121 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
5122 logevent("Requesting agent forwarding");
5123 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5127 if (pktin->type != SSH1_SMSG_SUCCESS
5128 && pktin->type != SSH1_SMSG_FAILURE) {
5129 bombout(("Protocol confusion"));
5131 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5132 logevent("Agent forwarding refused");
5134 logevent("Agent forwarding enabled");
5135 ssh->agentfwd_enabled = TRUE;
5136 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5140 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
5141 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5142 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
5143 logevent("Requesting X11 forwarding");
5145 * Note that while we blank the X authentication data here, we don't
5146 * take any special action to blank the start of an X11 channel,
5147 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
5148 * without having session blanking enabled is likely to leak your
5149 * cookie into the log.
5151 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5152 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5153 PKT_STR, ssh->x11disp->remoteauthprotoname,
5155 PKT_STR, ssh->x11disp->remoteauthdatastring,
5157 PKT_INT, ssh->x11disp->screennum,
5160 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5161 PKT_STR, ssh->x11disp->remoteauthprotoname,
5163 PKT_STR, ssh->x11disp->remoteauthdatastring,
5170 if (pktin->type != SSH1_SMSG_SUCCESS
5171 && pktin->type != SSH1_SMSG_FAILURE) {
5172 bombout(("Protocol confusion"));
5174 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5175 logevent("X11 forwarding refused");
5177 logevent("X11 forwarding enabled");
5178 ssh->X11_fwd_enabled = TRUE;
5179 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5183 ssh_setup_portfwd(ssh, ssh->conf);
5184 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5186 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5188 /* Unpick the terminal-speed string. */
5189 /* XXX perhaps we should allow no speeds to be sent. */
5190 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5191 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5192 /* Send the pty request. */
5193 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5194 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5195 ssh_pkt_adduint32(pkt, ssh->term_height);
5196 ssh_pkt_adduint32(pkt, ssh->term_width);
5197 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5198 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5199 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5200 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5201 ssh_pkt_adduint32(pkt, ssh->ispeed);
5202 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5203 ssh_pkt_adduint32(pkt, ssh->ospeed);
5204 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5206 ssh->state = SSH_STATE_INTERMED;
5210 if (pktin->type != SSH1_SMSG_SUCCESS
5211 && pktin->type != SSH1_SMSG_FAILURE) {
5212 bombout(("Protocol confusion"));
5214 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5215 c_write_str(ssh, "Server refused to allocate pty\r\n");
5216 ssh->editing = ssh->echoing = 1;
5218 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5219 ssh->ospeed, ssh->ispeed);
5220 ssh->got_pty = TRUE;
5223 ssh->editing = ssh->echoing = 1;
5226 if (conf_get_int(ssh->conf, CONF_compression)) {
5227 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5231 if (pktin->type != SSH1_SMSG_SUCCESS
5232 && pktin->type != SSH1_SMSG_FAILURE) {
5233 bombout(("Protocol confusion"));
5235 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5236 c_write_str(ssh, "Server refused to compress\r\n");
5238 logevent("Started compression");
5239 ssh->v1_compressing = TRUE;
5240 ssh->cs_comp_ctx = zlib_compress_init();
5241 logevent("Initialised zlib (RFC1950) compression");
5242 ssh->sc_comp_ctx = zlib_decompress_init();
5243 logevent("Initialised zlib (RFC1950) decompression");
5247 * Start the shell or command.
5249 * Special case: if the first-choice command is an SSH-2
5250 * subsystem (hence not usable here) and the second choice
5251 * exists, we fall straight back to that.
5254 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5256 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5257 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5258 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5259 ssh->fallback_cmd = TRUE;
5262 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5264 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5265 logevent("Started session");
5268 ssh->state = SSH_STATE_SESSION;
5269 if (ssh->size_needed)
5270 ssh_size(ssh, ssh->term_width, ssh->term_height);
5271 if (ssh->eof_needed)
5272 ssh_special(ssh, TS_EOF);
5275 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5277 ssh->channels = newtree234(ssh_channelcmp);
5281 * By this point, most incoming packets are already being
5282 * handled by the dispatch table, and we need only pay
5283 * attention to the unusual ones.
5288 if (pktin->type == SSH1_SMSG_SUCCESS) {
5289 /* may be from EXEC_SHELL on some servers */
5290 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5291 /* may be from EXEC_SHELL on some servers
5292 * if no pty is available or in other odd cases. Ignore */
5294 bombout(("Strange packet received: type %d", pktin->type));
5299 int len = min(inlen, 512);
5300 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5301 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
5302 PKTT_OTHER, PKT_END);
5313 * Handle the top-level SSH-2 protocol.
5315 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5320 ssh_pkt_getstring(pktin, &msg, &msglen);
5321 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5324 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5326 /* log reason code in disconnect message */
5330 ssh_pkt_getstring(pktin, &msg, &msglen);
5331 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5334 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5336 /* Do nothing, because we're ignoring it! Duhh. */
5339 static void ssh1_protocol_setup(Ssh ssh)
5344 * Most messages are handled by the coroutines.
5346 for (i = 0; i < 256; i++)
5347 ssh->packet_dispatch[i] = NULL;
5350 * These special message types we install handlers for.
5352 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5353 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5354 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5357 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5358 struct Packet *pktin)
5360 unsigned char *in=(unsigned char*)vin;
5361 if (ssh->state == SSH_STATE_CLOSED)
5364 if (pktin && ssh->packet_dispatch[pktin->type]) {
5365 ssh->packet_dispatch[pktin->type](ssh, pktin);
5369 if (!ssh->protocol_initial_phase_done) {
5370 if (do_ssh1_login(ssh, in, inlen, pktin))
5371 ssh->protocol_initial_phase_done = TRUE;
5376 do_ssh1_connection(ssh, in, inlen, pktin);
5380 * Utility routine for decoding comma-separated strings in KEXINIT.
5382 static int in_commasep_string(char *needle, char *haystack, int haylen)
5385 if (!needle || !haystack) /* protect against null pointers */
5387 needlen = strlen(needle);
5390 * Is it at the start of the string?
5392 if (haylen >= needlen && /* haystack is long enough */
5393 !memcmp(needle, haystack, needlen) && /* initial match */
5394 (haylen == needlen || haystack[needlen] == ',')
5395 /* either , or EOS follows */
5399 * If not, search for the next comma and resume after that.
5400 * If no comma found, terminate.
5402 while (haylen > 0 && *haystack != ',')
5403 haylen--, haystack++;
5406 haylen--, haystack++; /* skip over comma itself */
5411 * Similar routine for checking whether we have the first string in a list.
5413 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5416 if (!needle || !haystack) /* protect against null pointers */
5418 needlen = strlen(needle);
5420 * Is it at the start of the string?
5422 if (haylen >= needlen && /* haystack is long enough */
5423 !memcmp(needle, haystack, needlen) && /* initial match */
5424 (haylen == needlen || haystack[needlen] == ',')
5425 /* either , or EOS follows */
5433 * SSH-2 key creation method.
5434 * (Currently assumes 2 lots of any hash are sufficient to generate
5435 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5437 #define SSH2_MKKEY_ITERS (2)
5438 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5439 unsigned char *keyspace)
5441 const struct ssh_hash *h = ssh->kex->hash;
5443 /* First hlen bytes. */
5445 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5446 hash_mpint(h, s, K);
5447 h->bytes(s, H, h->hlen);
5448 h->bytes(s, &chr, 1);
5449 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5450 h->final(s, keyspace);
5451 /* Next hlen bytes. */
5453 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5454 hash_mpint(h, s, K);
5455 h->bytes(s, H, h->hlen);
5456 h->bytes(s, keyspace, h->hlen);
5457 h->final(s, keyspace + h->hlen);
5461 * Handle the SSH-2 transport layer.
5463 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5464 struct Packet *pktin)
5466 unsigned char *in = (unsigned char *)vin;
5467 struct do_ssh2_transport_state {
5468 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5469 Bignum p, g, e, f, K;
5472 int kex_init_value, kex_reply_value;
5473 const struct ssh_mac **maclist;
5475 const struct ssh2_cipher *cscipher_tobe;
5476 const struct ssh2_cipher *sccipher_tobe;
5477 const struct ssh_mac *csmac_tobe;
5478 const struct ssh_mac *scmac_tobe;
5479 const struct ssh_compress *cscomp_tobe;
5480 const struct ssh_compress *sccomp_tobe;
5481 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5482 int hostkeylen, siglen, rsakeylen;
5483 void *hkey; /* actual host key */
5484 void *rsakey; /* for RSA kex */
5485 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5486 int n_preferred_kex;
5487 const struct ssh_kexes *preferred_kex[KEX_MAX];
5488 int n_preferred_ciphers;
5489 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5490 const struct ssh_compress *preferred_comp;
5491 int userauth_succeeded; /* for delayed compression */
5492 int pending_compression;
5493 int got_session_id, activated_authconn;
5494 struct Packet *pktout;
5499 crState(do_ssh2_transport_state);
5501 crBegin(ssh->do_ssh2_transport_crstate);
5503 s->cscipher_tobe = s->sccipher_tobe = NULL;
5504 s->csmac_tobe = s->scmac_tobe = NULL;
5505 s->cscomp_tobe = s->sccomp_tobe = NULL;
5507 s->got_session_id = s->activated_authconn = FALSE;
5508 s->userauth_succeeded = FALSE;
5509 s->pending_compression = FALSE;
5512 * Be prepared to work around the buggy MAC problem.
5514 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5515 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5517 s->maclist = macs, s->nmacs = lenof(macs);
5520 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5522 int i, j, commalist_started;
5525 * Set up the preferred key exchange. (NULL => warn below here)
5527 s->n_preferred_kex = 0;
5528 for (i = 0; i < KEX_MAX; i++) {
5529 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
5531 s->preferred_kex[s->n_preferred_kex++] =
5532 &ssh_diffiehellman_gex;
5535 s->preferred_kex[s->n_preferred_kex++] =
5536 &ssh_diffiehellman_group14;
5539 s->preferred_kex[s->n_preferred_kex++] =
5540 &ssh_diffiehellman_group1;
5543 s->preferred_kex[s->n_preferred_kex++] =
5547 /* Flag for later. Don't bother if it's the last in
5549 if (i < KEX_MAX - 1) {
5550 s->preferred_kex[s->n_preferred_kex++] = NULL;
5557 * Set up the preferred ciphers. (NULL => warn below here)
5559 s->n_preferred_ciphers = 0;
5560 for (i = 0; i < CIPHER_MAX; i++) {
5561 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
5562 case CIPHER_BLOWFISH:
5563 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5566 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
5567 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5571 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5574 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5576 case CIPHER_ARCFOUR:
5577 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5580 /* Flag for later. Don't bother if it's the last in
5582 if (i < CIPHER_MAX - 1) {
5583 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5590 * Set up preferred compression.
5592 if (conf_get_int(ssh->conf, CONF_compression))
5593 s->preferred_comp = &ssh_zlib;
5595 s->preferred_comp = &ssh_comp_none;
5598 * Enable queueing of outgoing auth- or connection-layer
5599 * packets while we are in the middle of a key exchange.
5601 ssh->queueing = TRUE;
5604 * Flag that KEX is in progress.
5606 ssh->kex_in_progress = TRUE;
5609 * Construct and send our key exchange packet.
5611 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5612 for (i = 0; i < 16; i++)
5613 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5614 /* List key exchange algorithms. */
5615 ssh2_pkt_addstring_start(s->pktout);
5616 commalist_started = 0;
5617 for (i = 0; i < s->n_preferred_kex; i++) {
5618 const struct ssh_kexes *k = s->preferred_kex[i];
5619 if (!k) continue; /* warning flag */
5620 for (j = 0; j < k->nkexes; j++) {
5621 if (commalist_started)
5622 ssh2_pkt_addstring_str(s->pktout, ",");
5623 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5624 commalist_started = 1;
5627 /* List server host key algorithms. */
5628 ssh2_pkt_addstring_start(s->pktout);
5629 for (i = 0; i < lenof(hostkey_algs); i++) {
5630 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5631 if (i < lenof(hostkey_algs) - 1)
5632 ssh2_pkt_addstring_str(s->pktout, ",");
5634 /* List client->server encryption algorithms. */
5635 ssh2_pkt_addstring_start(s->pktout);
5636 commalist_started = 0;
5637 for (i = 0; i < s->n_preferred_ciphers; i++) {
5638 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5639 if (!c) continue; /* warning flag */
5640 for (j = 0; j < c->nciphers; j++) {
5641 if (commalist_started)
5642 ssh2_pkt_addstring_str(s->pktout, ",");
5643 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5644 commalist_started = 1;
5647 /* List server->client encryption algorithms. */
5648 ssh2_pkt_addstring_start(s->pktout);
5649 commalist_started = 0;
5650 for (i = 0; i < s->n_preferred_ciphers; i++) {
5651 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5652 if (!c) continue; /* warning flag */
5653 for (j = 0; j < c->nciphers; j++) {
5654 if (commalist_started)
5655 ssh2_pkt_addstring_str(s->pktout, ",");
5656 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5657 commalist_started = 1;
5660 /* List client->server MAC algorithms. */
5661 ssh2_pkt_addstring_start(s->pktout);
5662 for (i = 0; i < s->nmacs; i++) {
5663 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5664 if (i < s->nmacs - 1)
5665 ssh2_pkt_addstring_str(s->pktout, ",");
5667 /* List server->client MAC algorithms. */
5668 ssh2_pkt_addstring_start(s->pktout);
5669 for (i = 0; i < s->nmacs; i++) {
5670 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5671 if (i < s->nmacs - 1)
5672 ssh2_pkt_addstring_str(s->pktout, ",");
5674 /* List client->server compression algorithms,
5675 * then server->client compression algorithms. (We use the
5676 * same set twice.) */
5677 for (j = 0; j < 2; j++) {
5678 ssh2_pkt_addstring_start(s->pktout);
5679 assert(lenof(compressions) > 1);
5680 /* Prefer non-delayed versions */
5681 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5682 /* We don't even list delayed versions of algorithms until
5683 * they're allowed to be used, to avoid a race. See the end of
5685 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
5686 ssh2_pkt_addstring_str(s->pktout, ",");
5687 ssh2_pkt_addstring_str(s->pktout,
5688 s->preferred_comp->delayed_name);
5690 for (i = 0; i < lenof(compressions); i++) {
5691 const struct ssh_compress *c = compressions[i];
5692 if (c != s->preferred_comp) {
5693 ssh2_pkt_addstring_str(s->pktout, ",");
5694 ssh2_pkt_addstring_str(s->pktout, c->name);
5695 if (s->userauth_succeeded && c->delayed_name) {
5696 ssh2_pkt_addstring_str(s->pktout, ",");
5697 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
5702 /* List client->server languages. Empty list. */
5703 ssh2_pkt_addstring_start(s->pktout);
5704 /* List server->client languages. Empty list. */
5705 ssh2_pkt_addstring_start(s->pktout);
5706 /* First KEX packet does _not_ follow, because we're not that brave. */
5707 ssh2_pkt_addbool(s->pktout, FALSE);
5709 ssh2_pkt_adduint32(s->pktout, 0);
5712 s->our_kexinitlen = s->pktout->length - 5;
5713 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5714 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5716 ssh2_pkt_send_noqueue(ssh, s->pktout);
5722 * Now examine the other side's KEXINIT to see what we're up
5726 char *str, *preferred;
5729 if (pktin->type != SSH2_MSG_KEXINIT) {
5730 bombout(("expected key exchange packet from server"));
5734 ssh->hostkey = NULL;
5735 s->cscipher_tobe = NULL;
5736 s->sccipher_tobe = NULL;
5737 s->csmac_tobe = NULL;
5738 s->scmac_tobe = NULL;
5739 s->cscomp_tobe = NULL;
5740 s->sccomp_tobe = NULL;
5741 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5743 pktin->savedpos += 16; /* skip garbage cookie */
5744 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5747 for (i = 0; i < s->n_preferred_kex; i++) {
5748 const struct ssh_kexes *k = s->preferred_kex[i];
5752 for (j = 0; j < k->nkexes; j++) {
5753 if (!preferred) preferred = k->list[j]->name;
5754 if (in_commasep_string(k->list[j]->name, str, len)) {
5755 ssh->kex = k->list[j];
5764 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5765 str ? str : "(null)"));
5769 * Note that the server's guess is considered wrong if it doesn't match
5770 * the first algorithm in our list, even if it's still the algorithm
5773 s->guessok = first_in_commasep_string(preferred, str, len);
5774 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5775 for (i = 0; i < lenof(hostkey_algs); i++) {
5776 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5777 ssh->hostkey = hostkey_algs[i];
5781 s->guessok = s->guessok &&
5782 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5783 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5784 for (i = 0; i < s->n_preferred_ciphers; i++) {
5785 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5787 s->warn_cscipher = TRUE;
5789 for (j = 0; j < c->nciphers; j++) {
5790 if (in_commasep_string(c->list[j]->name, str, len)) {
5791 s->cscipher_tobe = c->list[j];
5796 if (s->cscipher_tobe)
5799 if (!s->cscipher_tobe) {
5800 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5801 str ? str : "(null)"));
5805 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5806 for (i = 0; i < s->n_preferred_ciphers; i++) {
5807 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5809 s->warn_sccipher = TRUE;
5811 for (j = 0; j < c->nciphers; j++) {
5812 if (in_commasep_string(c->list[j]->name, str, len)) {
5813 s->sccipher_tobe = c->list[j];
5818 if (s->sccipher_tobe)
5821 if (!s->sccipher_tobe) {
5822 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5823 str ? str : "(null)"));
5827 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5828 for (i = 0; i < s->nmacs; i++) {
5829 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5830 s->csmac_tobe = s->maclist[i];
5834 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5835 for (i = 0; i < s->nmacs; i++) {
5836 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5837 s->scmac_tobe = s->maclist[i];
5841 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5842 for (i = 0; i < lenof(compressions) + 1; i++) {
5843 const struct ssh_compress *c =
5844 i == 0 ? s->preferred_comp : compressions[i - 1];
5845 if (in_commasep_string(c->name, str, len)) {
5848 } else if (in_commasep_string(c->delayed_name, str, len)) {
5849 if (s->userauth_succeeded) {
5853 s->pending_compression = TRUE; /* try this later */
5857 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5858 for (i = 0; i < lenof(compressions) + 1; i++) {
5859 const struct ssh_compress *c =
5860 i == 0 ? s->preferred_comp : compressions[i - 1];
5861 if (in_commasep_string(c->name, str, len)) {
5864 } else if (in_commasep_string(c->delayed_name, str, len)) {
5865 if (s->userauth_succeeded) {
5869 s->pending_compression = TRUE; /* try this later */
5873 if (s->pending_compression) {
5874 logevent("Server supports delayed compression; "
5875 "will try this later");
5877 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5878 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5879 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5882 ssh_set_frozen(ssh, 1);
5883 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5885 ssh_dialog_callback, ssh);
5886 if (s->dlgret < 0) {
5890 bombout(("Unexpected data from server while"
5891 " waiting for user response"));
5894 } while (pktin || inlen > 0);
5895 s->dlgret = ssh->user_response;
5897 ssh_set_frozen(ssh, 0);
5898 if (s->dlgret == 0) {
5899 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5905 if (s->warn_cscipher) {
5906 ssh_set_frozen(ssh, 1);
5907 s->dlgret = askalg(ssh->frontend,
5908 "client-to-server cipher",
5909 s->cscipher_tobe->name,
5910 ssh_dialog_callback, ssh);
5911 if (s->dlgret < 0) {
5915 bombout(("Unexpected data from server while"
5916 " waiting for user response"));
5919 } while (pktin || inlen > 0);
5920 s->dlgret = ssh->user_response;
5922 ssh_set_frozen(ssh, 0);
5923 if (s->dlgret == 0) {
5924 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5930 if (s->warn_sccipher) {
5931 ssh_set_frozen(ssh, 1);
5932 s->dlgret = askalg(ssh->frontend,
5933 "server-to-client cipher",
5934 s->sccipher_tobe->name,
5935 ssh_dialog_callback, ssh);
5936 if (s->dlgret < 0) {
5940 bombout(("Unexpected data from server while"
5941 " waiting for user response"));
5944 } while (pktin || inlen > 0);
5945 s->dlgret = ssh->user_response;
5947 ssh_set_frozen(ssh, 0);
5948 if (s->dlgret == 0) {
5949 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5955 ssh->exhash = ssh->kex->hash->init();
5956 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5957 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5958 hash_string(ssh->kex->hash, ssh->exhash,
5959 s->our_kexinit, s->our_kexinitlen);
5960 sfree(s->our_kexinit);
5961 if (pktin->length > 5)
5962 hash_string(ssh->kex->hash, ssh->exhash,
5963 pktin->data + 5, pktin->length - 5);
5965 if (s->ignorepkt) /* first_kex_packet_follows */
5966 crWaitUntil(pktin); /* Ignore packet */
5969 if (ssh->kex->main_type == KEXTYPE_DH) {
5971 * Work out the number of bits of key we will need from the
5972 * key exchange. We start with the maximum key length of
5978 csbits = s->cscipher_tobe->keylen;
5979 scbits = s->sccipher_tobe->keylen;
5980 s->nbits = (csbits > scbits ? csbits : scbits);
5982 /* The keys only have hlen-bit entropy, since they're based on
5983 * a hash. So cap the key size at hlen bits. */
5984 if (s->nbits > ssh->kex->hash->hlen * 8)
5985 s->nbits = ssh->kex->hash->hlen * 8;
5988 * If we're doing Diffie-Hellman group exchange, start by
5989 * requesting a group.
5991 if (!ssh->kex->pdata) {
5992 logevent("Doing Diffie-Hellman group exchange");
5993 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
5995 * Work out how big a DH group we will need to allow that
5998 s->pbits = 512 << ((s->nbits - 1) / 64);
5999 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6000 ssh2_pkt_adduint32(s->pktout, s->pbits);
6001 ssh2_pkt_send_noqueue(ssh, s->pktout);
6004 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6005 bombout(("expected key exchange group packet from server"));
6008 s->p = ssh2_pkt_getmp(pktin);
6009 s->g = ssh2_pkt_getmp(pktin);
6010 if (!s->p || !s->g) {
6011 bombout(("unable to read mp-ints from incoming group packet"));
6014 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6015 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6016 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6018 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6019 ssh->kex_ctx = dh_setup_group(ssh->kex);
6020 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6021 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6022 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6023 ssh->kex->groupname);
6026 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6027 ssh->kex->hash->text_name);
6029 * Now generate and send e for Diffie-Hellman.
6031 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6032 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6033 s->pktout = ssh2_pkt_init(s->kex_init_value);
6034 ssh2_pkt_addmp(s->pktout, s->e);
6035 ssh2_pkt_send_noqueue(ssh, s->pktout);
6037 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6039 if (pktin->type != s->kex_reply_value) {
6040 bombout(("expected key exchange reply packet from server"));
6043 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6044 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6045 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6046 s->f = ssh2_pkt_getmp(pktin);
6048 bombout(("unable to parse key exchange reply packet"));
6051 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6053 s->K = dh_find_K(ssh->kex_ctx, s->f);
6055 /* We assume everything from now on will be quick, and it might
6056 * involve user interaction. */
6057 set_busy_status(ssh->frontend, BUSY_NOT);
6059 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6060 if (!ssh->kex->pdata) {
6061 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6062 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6063 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6065 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6066 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6068 dh_cleanup(ssh->kex_ctx);
6070 if (!ssh->kex->pdata) {
6075 logeventf(ssh, "Doing RSA key exchange with hash %s",
6076 ssh->kex->hash->text_name);
6077 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6079 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6083 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6084 bombout(("expected RSA public key packet from server"));
6088 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6089 hash_string(ssh->kex->hash, ssh->exhash,
6090 s->hostkeydata, s->hostkeylen);
6091 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6095 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6096 s->rsakeydata = snewn(s->rsakeylen, char);
6097 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6100 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6102 sfree(s->rsakeydata);
6103 bombout(("unable to parse RSA public key from server"));
6107 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6110 * Next, set up a shared secret K, of precisely KLEN -
6111 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6112 * RSA key modulus and HLEN is the bit length of the hash
6116 int klen = ssh_rsakex_klen(s->rsakey);
6117 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6119 unsigned char *kstr1, *kstr2, *outstr;
6120 int kstr1len, kstr2len, outstrlen;
6122 s->K = bn_power_2(nbits - 1);
6124 for (i = 0; i < nbits; i++) {
6126 byte = random_byte();
6128 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6132 * Encode this as an mpint.
6134 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6135 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6136 PUT_32BIT(kstr2, kstr1len);
6137 memcpy(kstr2 + 4, kstr1, kstr1len);
6140 * Encrypt it with the given RSA key.
6142 outstrlen = (klen + 7) / 8;
6143 outstr = snewn(outstrlen, unsigned char);
6144 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6145 outstr, outstrlen, s->rsakey);
6148 * And send it off in a return packet.
6150 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6151 ssh2_pkt_addstring_start(s->pktout);
6152 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6153 ssh2_pkt_send_noqueue(ssh, s->pktout);
6155 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6162 ssh_rsakex_freekey(s->rsakey);
6165 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6166 sfree(s->rsakeydata);
6167 bombout(("expected signature packet from server"));
6171 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6173 sfree(s->rsakeydata);
6176 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6177 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6178 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6180 ssh->kex_ctx = NULL;
6183 debug(("Exchange hash is:\n"));
6184 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6188 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6189 (char *)s->exchange_hash,
6190 ssh->kex->hash->hlen)) {
6191 bombout(("Server's host key did not match the signature supplied"));
6196 * Authenticate remote host: verify host key. (We've already
6197 * checked the signature of the exchange hash.)
6199 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6200 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6201 ssh_set_frozen(ssh, 1);
6202 s->dlgret = verify_ssh_host_key(ssh->frontend,
6203 ssh->savedhost, ssh->savedport,
6204 ssh->hostkey->keytype, s->keystr,
6206 ssh_dialog_callback, ssh);
6207 if (s->dlgret < 0) {
6211 bombout(("Unexpected data from server while waiting"
6212 " for user host key response"));
6215 } while (pktin || inlen > 0);
6216 s->dlgret = ssh->user_response;
6218 ssh_set_frozen(ssh, 0);
6219 if (s->dlgret == 0) {
6220 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6224 if (!s->got_session_id) { /* don't bother logging this in rekeys */
6225 logevent("Host key fingerprint is:");
6226 logevent(s->fingerprint);
6228 sfree(s->fingerprint);
6230 ssh->hostkey->freekey(s->hkey);
6233 * The exchange hash from the very first key exchange is also
6234 * the session id, used in session key construction and
6237 if (!s->got_session_id) {
6238 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6239 memcpy(ssh->v2_session_id, s->exchange_hash,
6240 sizeof(s->exchange_hash));
6241 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6242 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6243 s->got_session_id = TRUE;
6247 * Send SSH2_MSG_NEWKEYS.
6249 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6250 ssh2_pkt_send_noqueue(ssh, s->pktout);
6251 ssh->outgoing_data_size = 0; /* start counting from here */
6254 * We've sent client NEWKEYS, so create and initialise
6255 * client-to-server session keys.
6257 if (ssh->cs_cipher_ctx)
6258 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6259 ssh->cscipher = s->cscipher_tobe;
6260 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6262 if (ssh->cs_mac_ctx)
6263 ssh->csmac->free_context(ssh->cs_mac_ctx);
6264 ssh->csmac = s->csmac_tobe;
6265 ssh->cs_mac_ctx = ssh->csmac->make_context();
6267 if (ssh->cs_comp_ctx)
6268 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6269 ssh->cscomp = s->cscomp_tobe;
6270 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6273 * Set IVs on client-to-server keys. Here we use the exchange
6274 * hash from the _first_ key exchange.
6277 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6278 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6279 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6280 assert((ssh->cscipher->keylen+7) / 8 <=
6281 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6282 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6283 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6284 assert(ssh->cscipher->blksize <=
6285 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6286 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6287 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6288 assert(ssh->csmac->len <=
6289 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6290 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6291 memset(keyspace, 0, sizeof(keyspace));
6294 logeventf(ssh, "Initialised %.200s client->server encryption",
6295 ssh->cscipher->text_name);
6296 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6297 ssh->csmac->text_name);
6298 if (ssh->cscomp->text_name)
6299 logeventf(ssh, "Initialised %s compression",
6300 ssh->cscomp->text_name);
6303 * Now our end of the key exchange is complete, we can send all
6304 * our queued higher-layer packets.
6306 ssh->queueing = FALSE;
6307 ssh2_pkt_queuesend(ssh);
6310 * Expect SSH2_MSG_NEWKEYS from server.
6313 if (pktin->type != SSH2_MSG_NEWKEYS) {
6314 bombout(("expected new-keys packet from server"));
6317 ssh->incoming_data_size = 0; /* start counting from here */
6320 * We've seen server NEWKEYS, so create and initialise
6321 * server-to-client session keys.
6323 if (ssh->sc_cipher_ctx)
6324 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6325 ssh->sccipher = s->sccipher_tobe;
6326 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6328 if (ssh->sc_mac_ctx)
6329 ssh->scmac->free_context(ssh->sc_mac_ctx);
6330 ssh->scmac = s->scmac_tobe;
6331 ssh->sc_mac_ctx = ssh->scmac->make_context();
6333 if (ssh->sc_comp_ctx)
6334 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6335 ssh->sccomp = s->sccomp_tobe;
6336 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6339 * Set IVs on server-to-client keys. Here we use the exchange
6340 * hash from the _first_ key exchange.
6343 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6344 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6345 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6346 assert((ssh->sccipher->keylen+7) / 8 <=
6347 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6348 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6349 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6350 assert(ssh->sccipher->blksize <=
6351 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6352 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6353 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6354 assert(ssh->scmac->len <=
6355 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6356 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6357 memset(keyspace, 0, sizeof(keyspace));
6359 logeventf(ssh, "Initialised %.200s server->client encryption",
6360 ssh->sccipher->text_name);
6361 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6362 ssh->scmac->text_name);
6363 if (ssh->sccomp->text_name)
6364 logeventf(ssh, "Initialised %s decompression",
6365 ssh->sccomp->text_name);
6368 * Free shared secret.
6373 * Key exchange is over. Loop straight back round if we have a
6374 * deferred rekey reason.
6376 if (ssh->deferred_rekey_reason) {
6377 logevent(ssh->deferred_rekey_reason);
6379 ssh->deferred_rekey_reason = NULL;
6380 goto begin_key_exchange;
6384 * Otherwise, schedule a timer for our next rekey.
6386 ssh->kex_in_progress = FALSE;
6387 ssh->last_rekey = GETTICKCOUNT();
6388 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
6389 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6393 * If this is the first key exchange phase, we must pass the
6394 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
6395 * wants to see it but because it will need time to initialise
6396 * itself before it sees an actual packet. In subsequent key
6397 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
6398 * it would only confuse the layer above.
6400 if (s->activated_authconn) {
6403 s->activated_authconn = TRUE;
6406 * Now we're encrypting. Begin returning 1 to the protocol main
6407 * function so that other things can run on top of the
6408 * transport. If we ever see a KEXINIT, we must go back to the
6411 * We _also_ go back to the start if we see pktin==NULL and
6412 * inlen negative, because this is a special signal meaning
6413 * `initiate client-driven rekey', and `in' contains a message
6414 * giving the reason for the rekey.
6416 * inlen==-1 means always initiate a rekey;
6417 * inlen==-2 means that userauth has completed successfully and
6418 * we should consider rekeying (for delayed compression).
6420 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6421 (!pktin && inlen < 0))) {
6426 logevent("Server initiated key re-exchange");
6430 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6431 * delayed compression, if it's available.
6433 * draft-miller-secsh-compression-delayed-00 says that you
6434 * negotiate delayed compression in the first key exchange, and
6435 * both sides start compressing when the server has sent
6436 * USERAUTH_SUCCESS. This has a race condition -- the server
6437 * can't know when the client has seen it, and thus which incoming
6438 * packets it should treat as compressed.
6440 * Instead, we do the initial key exchange without offering the
6441 * delayed methods, but note if the server offers them; when we
6442 * get here, if a delayed method was available that was higher
6443 * on our list than what we got, we initiate a rekey in which we
6444 * _do_ list the delayed methods (and hopefully get it as a
6445 * result). Subsequent rekeys will do the same.
6447 assert(!s->userauth_succeeded); /* should only happen once */
6448 s->userauth_succeeded = TRUE;
6449 if (!s->pending_compression)
6450 /* Can't see any point rekeying. */
6451 goto wait_for_rekey; /* this is utterly horrid */
6452 /* else fall through to rekey... */
6453 s->pending_compression = FALSE;
6456 * Now we've decided to rekey.
6458 * Special case: if the server bug is set that doesn't
6459 * allow rekeying, we give a different log message and
6460 * continue waiting. (If such a server _initiates_ a rekey,
6461 * we process it anyway!)
6463 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6464 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6466 /* Reset the counters, so that at least this message doesn't
6467 * hit the event log _too_ often. */
6468 ssh->outgoing_data_size = 0;
6469 ssh->incoming_data_size = 0;
6470 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
6472 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6475 goto wait_for_rekey; /* this is still utterly horrid */
6477 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6480 goto begin_key_exchange;
6486 * Add data to an SSH-2 channel output buffer.
6488 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6491 bufchain_add(&c->v.v2.outbuffer, buf, len);
6495 * Attempt to send data on an SSH-2 channel.
6497 static int ssh2_try_send(struct ssh_channel *c)
6500 struct Packet *pktout;
6503 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6506 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6507 if ((unsigned)len > c->v.v2.remwindow)
6508 len = c->v.v2.remwindow;
6509 if ((unsigned)len > c->v.v2.remmaxpkt)
6510 len = c->v.v2.remmaxpkt;
6511 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6512 ssh2_pkt_adduint32(pktout, c->remoteid);
6513 ssh2_pkt_addstring_start(pktout);
6514 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6515 ssh2_pkt_addstring_data(pktout, data, len);
6516 end_log_omission(ssh, pktout);
6517 ssh2_pkt_send(ssh, pktout);
6518 bufchain_consume(&c->v.v2.outbuffer, len);
6519 c->v.v2.remwindow -= len;
6523 * After having sent as much data as we can, return the amount
6526 ret = bufchain_size(&c->v.v2.outbuffer);
6529 * And if there's no data pending but we need to send an EOF, send
6532 if (!ret && c->pending_eof)
6533 ssh_channel_try_eof(c);
6538 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
6541 if (c->closes & CLOSES_SENT_EOF)
6542 return; /* don't send on channels we've EOFed */
6543 bufsize = ssh2_try_send(c);
6546 case CHAN_MAINSESSION:
6547 /* stdin need not receive an unthrottle
6548 * notification since it will be polled */
6551 x11_unthrottle(c->u.x11.s);
6554 /* agent sockets are request/response and need no
6555 * buffer management */
6558 pfd_unthrottle(c->u.pfd.s);
6565 * Set up most of a new ssh_channel for SSH-2.
6567 static void ssh2_channel_init(struct ssh_channel *c)
6570 c->localid = alloc_channel_id(ssh);
6572 c->pending_eof = FALSE;
6573 c->throttling_conn = FALSE;
6574 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6575 conf_get_int(ssh->conf, CONF_ssh_simple) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6576 c->v.v2.winadj_head = c->v.v2.winadj_tail = NULL;
6577 c->v.v2.throttle_state = UNTHROTTLED;
6578 bufchain_init(&c->v.v2.outbuffer);
6582 * Potentially enlarge the window on an SSH-2 channel.
6584 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6589 * Never send WINDOW_ADJUST for a channel that the remote side has
6590 * already sent EOF on; there's no point, since it won't be
6591 * sending any more data anyway. Ditto if _we've_ already sent
6594 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6598 * If the remote end has a habit of ignoring maxpkt, limit the
6599 * window so that it has no choice (assuming it doesn't ignore the
6602 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6603 newwin = OUR_V2_MAXPKT;
6606 * Only send a WINDOW_ADJUST if there's significantly more window
6607 * available than the other end thinks there is. This saves us
6608 * sending a WINDOW_ADJUST for every character in a shell session.
6610 * "Significant" is arbitrarily defined as half the window size.
6612 if (newwin / 2 >= c->v.v2.locwindow) {
6613 struct Packet *pktout;
6617 * In order to keep track of how much window the client
6618 * actually has available, we'd like it to acknowledge each
6619 * WINDOW_ADJUST. We can't do that directly, so we accompany
6620 * it with a CHANNEL_REQUEST that has to be acknowledged.
6622 * This is only necessary if we're opening the window wide.
6623 * If we're not, then throughput is being constrained by
6624 * something other than the maximum window size anyway.
6626 * We also only send this if the main channel has finished its
6627 * initial CHANNEL_REQUESTs and installed the default
6628 * CHANNEL_FAILURE handler, so as not to risk giving it
6629 * unexpected CHANNEL_FAILUREs.
6631 if (newwin == c->v.v2.locmaxwin &&
6632 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE]) {
6633 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6634 ssh2_pkt_adduint32(pktout, c->remoteid);
6635 ssh2_pkt_addstring(pktout, "winadj@putty.projects.tartarus.org");
6636 ssh2_pkt_addbool(pktout, TRUE);
6637 ssh2_pkt_send(ssh, pktout);
6640 * CHANNEL_FAILURE doesn't come with any indication of
6641 * what message caused it, so we have to keep track of the
6642 * outstanding CHANNEL_REQUESTs ourselves.
6644 wa = snew(struct winadj);
6645 wa->size = newwin - c->v.v2.locwindow;
6647 if (!c->v.v2.winadj_head)
6648 c->v.v2.winadj_head = wa;
6650 c->v.v2.winadj_tail->next = wa;
6651 c->v.v2.winadj_tail = wa;
6652 if (c->v.v2.throttle_state != UNTHROTTLED)
6653 c->v.v2.throttle_state = UNTHROTTLING;
6655 /* Pretend the WINDOW_ADJUST was acked immediately. */
6656 c->v.v2.remlocwin = newwin;
6657 c->v.v2.throttle_state = THROTTLED;
6659 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6660 ssh2_pkt_adduint32(pktout, c->remoteid);
6661 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6662 ssh2_pkt_send(ssh, pktout);
6663 c->v.v2.locwindow = newwin;
6668 * Find the channel associated with a message. If there's no channel,
6669 * or it's not properly open, make a noise about it and return NULL.
6671 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6673 unsigned localid = ssh_pkt_getuint32(pktin);
6674 struct ssh_channel *c;
6676 c = find234(ssh->channels, &localid, ssh_channelfind);
6678 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6679 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6680 char *buf = dupprintf("Received %s for %s channel %u",
6681 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6683 c ? "half-open" : "nonexistent", localid);
6684 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6691 static int ssh2_handle_winadj_response(struct ssh_channel *c)
6693 struct winadj *wa = c->v.v2.winadj_head;
6696 c->v.v2.winadj_head = wa->next;
6697 c->v.v2.remlocwin += wa->size;
6700 * winadj messages are only sent when the window is fully open, so
6701 * if we get an ack of one, we know any pending unthrottle is
6704 if (c->v.v2.throttle_state == UNTHROTTLING)
6705 c->v.v2.throttle_state = UNTHROTTLED;
6707 * We may now initiate channel-closing procedures, if that winadj
6708 * was the last thing outstanding before we send CHANNEL_CLOSE.
6710 ssh2_channel_check_close(c);
6714 static void ssh2_msg_channel_success(Ssh ssh, struct Packet *pktin)
6717 * This should never get called. All channel requests are either
6718 * sent with want_reply false, are sent before this handler gets
6719 * installed, or are "winadj@putty" requests, which servers should
6720 * never respond to with success.
6722 * However, at least one server ("boks_sshd") is known to return
6723 * SUCCESS for channel requests it's never heard of, such as
6724 * "winadj@putty". Raised with foxt.com as bug 090916-090424, but
6725 * for the sake of a quiet life, we handle it just the same as the
6728 struct ssh_channel *c;
6730 c = ssh2_channel_msg(ssh, pktin);
6733 if (!ssh2_handle_winadj_response(c))
6734 ssh_disconnect(ssh, NULL,
6735 "Received unsolicited SSH_MSG_CHANNEL_SUCCESS",
6736 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6739 static void ssh2_msg_channel_failure(Ssh ssh, struct Packet *pktin)
6742 * The only time this should get called is for "winadj@putty"
6743 * messages sent above. All other channel requests are either
6744 * sent with want_reply false or are sent before this handler gets
6747 struct ssh_channel *c;
6749 c = ssh2_channel_msg(ssh, pktin);
6752 if (!ssh2_handle_winadj_response(c))
6753 ssh_disconnect(ssh, NULL,
6754 "Received unsolicited SSH_MSG_CHANNEL_FAILURE",
6755 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6758 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6760 struct ssh_channel *c;
6761 c = ssh2_channel_msg(ssh, pktin);
6764 if (!(c->closes & CLOSES_SENT_EOF)) {
6765 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6766 ssh2_try_send_and_unthrottle(ssh, c);
6770 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6774 struct ssh_channel *c;
6775 c = ssh2_channel_msg(ssh, pktin);
6778 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6779 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6780 return; /* extended but not stderr */
6781 ssh_pkt_getstring(pktin, &data, &length);
6784 c->v.v2.locwindow -= length;
6785 c->v.v2.remlocwin -= length;
6787 case CHAN_MAINSESSION:
6789 from_backend(ssh->frontend, pktin->type ==
6790 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6794 bufsize = x11_send(c->u.x11.s, data, length);
6797 bufsize = pfd_send(c->u.pfd.s, data, length);
6800 while (length > 0) {
6801 if (c->u.a.lensofar < 4) {
6802 unsigned int l = min(4 - c->u.a.lensofar,
6804 memcpy(c->u.a.msglen + c->u.a.lensofar,
6808 c->u.a.lensofar += l;
6810 if (c->u.a.lensofar == 4) {
6812 4 + GET_32BIT(c->u.a.msglen);
6813 c->u.a.message = snewn(c->u.a.totallen,
6815 memcpy(c->u.a.message, c->u.a.msglen, 4);
6817 if (c->u.a.lensofar >= 4 && length > 0) {
6819 min(c->u.a.totallen - c->u.a.lensofar,
6821 memcpy(c->u.a.message + c->u.a.lensofar,
6825 c->u.a.lensofar += l;
6827 if (c->u.a.lensofar == c->u.a.totallen) {
6830 if (agent_query(c->u.a.message,
6833 ssh_agentf_callback, c))
6834 ssh_agentf_callback(c, reply, replylen);
6835 sfree(c->u.a.message);
6836 c->u.a.message = NULL;
6837 c->u.a.lensofar = 0;
6844 * If it looks like the remote end hit the end of its window,
6845 * and we didn't want it to do that, think about using a
6848 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6849 c->v.v2.locmaxwin < 0x40000000)
6850 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6852 * If we are not buffering too much data,
6853 * enlarge the window again at the remote side.
6854 * If we are buffering too much, we may still
6855 * need to adjust the window if the server's
6858 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6859 c->v.v2.locmaxwin - bufsize : 0);
6861 * If we're either buffering way too much data, or if we're
6862 * buffering anything at all and we're in "simple" mode,
6863 * throttle the whole channel.
6865 if ((bufsize > c->v.v2.locmaxwin ||
6866 (conf_get_int(ssh->conf, CONF_ssh_simple) && bufsize > 0)) &&
6867 !c->throttling_conn) {
6868 c->throttling_conn = 1;
6869 ssh_throttle_conn(ssh, +1);
6874 static void ssh_channel_destroy(struct ssh_channel *c)
6879 case CHAN_MAINSESSION:
6880 ssh->mainchan = NULL;
6881 update_specials_menu(ssh->frontend);
6884 if (c->u.x11.s != NULL)
6885 x11_close(c->u.x11.s);
6886 logevent("Forwarded X11 connection terminated");
6889 sfree(c->u.a.message);
6892 if (c->u.pfd.s != NULL)
6893 pfd_close(c->u.pfd.s);
6894 logevent("Forwarded port closed");
6898 del234(ssh->channels, c);
6899 if (ssh->version == 2)
6900 bufchain_clear(&c->v.v2.outbuffer);
6904 * See if that was the last channel left open.
6905 * (This is only our termination condition if we're
6906 * not running in -N mode.)
6908 if (ssh->version == 2 &&
6909 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
6910 count234(ssh->channels) == 0) {
6912 * We used to send SSH_MSG_DISCONNECT here,
6913 * because I'd believed that _every_ conforming
6914 * SSH-2 connection had to end with a disconnect
6915 * being sent by at least one side; apparently
6916 * I was wrong and it's perfectly OK to
6917 * unceremoniously slam the connection shut
6918 * when you're done, and indeed OpenSSH feels
6919 * this is more polite than sending a
6920 * DISCONNECT. So now we don't.
6922 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6926 static void ssh2_channel_check_close(struct ssh_channel *c)
6929 struct Packet *pktout;
6931 if ((c->closes & (CLOSES_SENT_EOF | CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6932 == (CLOSES_SENT_EOF | CLOSES_RCVD_EOF) && !c->v.v2.winadj_head) {
6934 * We have both sent and received EOF, and we have no
6935 * outstanding winadj channel requests, which means the
6936 * channel is in final wind-up. But we haven't sent CLOSE, so
6939 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6940 ssh2_pkt_adduint32(pktout, c->remoteid);
6941 ssh2_pkt_send(ssh, pktout);
6942 c->closes |= CLOSES_SENT_CLOSE;
6945 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
6947 * We have both sent and received CLOSE, which means we're
6948 * completely done with the channel.
6950 ssh_channel_destroy(c);
6954 static void ssh2_channel_got_eof(struct ssh_channel *c)
6956 if (c->closes & CLOSES_RCVD_EOF)
6957 return; /* already seen EOF */
6958 c->closes |= CLOSES_RCVD_EOF;
6960 if (c->type == CHAN_X11) {
6961 x11_send_eof(c->u.x11.s);
6962 } else if (c->type == CHAN_AGENT) {
6963 /* Manufacture an outgoing EOF in response to the incoming one. */
6964 sshfwd_write_eof(c);
6965 } else if (c->type == CHAN_SOCKDATA) {
6966 pfd_send_eof(c->u.pfd.s);
6967 } else if (c->type == CHAN_MAINSESSION) {
6970 if (!ssh->sent_console_eof &&
6971 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
6973 * Either from_backend_eof told us that the front end
6974 * wants us to close the outgoing side of the connection
6975 * as soon as we see EOF from the far end, or else we've
6976 * unilaterally decided to do that because we've allocated
6977 * a remote pty and hence EOF isn't a particularly
6978 * meaningful concept.
6980 sshfwd_write_eof(c);
6982 ssh->sent_console_eof = TRUE;
6985 ssh2_channel_check_close(c);
6988 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
6990 struct ssh_channel *c;
6992 c = ssh2_channel_msg(ssh, pktin);
6995 ssh2_channel_got_eof(c);
6998 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7000 struct ssh_channel *c;
7002 c = ssh2_channel_msg(ssh, pktin);
7007 * When we receive CLOSE on a channel, we assume it comes with an
7008 * implied EOF if we haven't seen EOF yet.
7010 ssh2_channel_got_eof(c);
7013 * And we also send an outgoing EOF, if we haven't already, on the
7014 * assumption that CLOSE is a pretty forceful announcement that
7015 * the remote side is doing away with the entire channel. (If it
7016 * had wanted to send us EOF and continue receiving data from us,
7017 * it would have just sent CHANNEL_EOF.)
7019 if (!(c->closes & CLOSES_SENT_EOF)) {
7021 * Make sure we don't read any more from whatever our local
7022 * data source is for this channel.
7025 case CHAN_MAINSESSION:
7026 ssh->send_ok = 0; /* stop trying to read from stdin */
7029 x11_override_throttle(c->u.x11.s, 1);
7032 pfd_override_throttle(c->u.pfd.s, 1);
7037 * Send outgoing EOF.
7039 sshfwd_write_eof(c);
7043 * Now process the actual close.
7045 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7046 c->closes |= CLOSES_RCVD_CLOSE;
7047 ssh2_channel_check_close(c);
7051 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7053 struct ssh_channel *c;
7055 c = ssh2_channel_msg(ssh, pktin);
7058 if (c->type != CHAN_SOCKDATA_DORMANT)
7059 return; /* dunno why they're confirming this */
7060 c->remoteid = ssh_pkt_getuint32(pktin);
7061 c->halfopen = FALSE;
7062 c->type = CHAN_SOCKDATA;
7063 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7064 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7066 pfd_confirm(c->u.pfd.s);
7068 ssh_channel_try_eof(c);
7071 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7073 static const char *const reasons[] = {
7074 "<unknown reason code>",
7075 "Administratively prohibited",
7077 "Unknown channel type",
7078 "Resource shortage",
7080 unsigned reason_code;
7081 char *reason_string;
7083 struct ssh_channel *c;
7084 c = ssh2_channel_msg(ssh, pktin);
7087 if (c->type != CHAN_SOCKDATA_DORMANT)
7088 return; /* dunno why they're failing this */
7090 reason_code = ssh_pkt_getuint32(pktin);
7091 if (reason_code >= lenof(reasons))
7092 reason_code = 0; /* ensure reasons[reason_code] in range */
7093 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7094 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7095 reasons[reason_code], reason_length, reason_string);
7097 pfd_close(c->u.pfd.s);
7099 del234(ssh->channels, c);
7103 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7106 int typelen, want_reply;
7107 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7108 struct ssh_channel *c;
7109 struct Packet *pktout;
7111 c = ssh2_channel_msg(ssh, pktin);
7114 ssh_pkt_getstring(pktin, &type, &typelen);
7115 want_reply = ssh2_pkt_getbool(pktin);
7118 * Having got the channel number, we now look at
7119 * the request type string to see if it's something
7122 if (c == ssh->mainchan) {
7124 * We recognise "exit-status" and "exit-signal" on
7125 * the primary channel.
7127 if (typelen == 11 &&
7128 !memcmp(type, "exit-status", 11)) {
7130 ssh->exitcode = ssh_pkt_getuint32(pktin);
7131 logeventf(ssh, "Server sent command exit status %d",
7133 reply = SSH2_MSG_CHANNEL_SUCCESS;
7135 } else if (typelen == 11 &&
7136 !memcmp(type, "exit-signal", 11)) {
7138 int is_plausible = TRUE, is_int = FALSE;
7139 char *fmt_sig = "", *fmt_msg = "";
7141 int msglen = 0, core = FALSE;
7142 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7143 * provide an `int' for the signal, despite its
7144 * having been a `string' in the drafts of RFC 4254 since at
7145 * least 2001. (Fixed in session.c 1.147.) Try to
7146 * infer which we can safely parse it as. */
7148 unsigned char *p = pktin->body +
7150 long len = pktin->length - pktin->savedpos;
7151 unsigned long num = GET_32BIT(p); /* what is it? */
7152 /* If it's 0, it hardly matters; assume string */
7156 int maybe_int = FALSE, maybe_str = FALSE;
7157 #define CHECK_HYPOTHESIS(offset, result) \
7160 if (q >= 0 && q+4 <= len) { \
7161 q = q + 4 + GET_32BIT(p+q); \
7162 if (q >= 0 && q+4 <= len && \
7163 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
7167 CHECK_HYPOTHESIS(4+1, maybe_int);
7168 CHECK_HYPOTHESIS(4+num+1, maybe_str);
7169 #undef CHECK_HYPOTHESIS
7170 if (maybe_int && !maybe_str)
7172 else if (!maybe_int && maybe_str)
7175 /* Crikey. Either or neither. Panic. */
7176 is_plausible = FALSE;
7179 ssh->exitcode = 128; /* means `unknown signal' */
7182 /* Old non-standard OpenSSH. */
7183 int signum = ssh_pkt_getuint32(pktin);
7184 fmt_sig = dupprintf(" %d", signum);
7185 ssh->exitcode = 128 + signum;
7187 /* As per RFC 4254. */
7190 ssh_pkt_getstring(pktin, &sig, &siglen);
7191 /* Signal name isn't supposed to be blank, but
7192 * let's cope gracefully if it is. */
7194 fmt_sig = dupprintf(" \"%.*s\"",
7199 * Really hideous method of translating the
7200 * signal description back into a locally
7201 * meaningful number.
7206 #define TRANSLATE_SIGNAL(s) \
7207 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7208 ssh->exitcode = 128 + SIG ## s
7210 TRANSLATE_SIGNAL(ABRT);
7213 TRANSLATE_SIGNAL(ALRM);
7216 TRANSLATE_SIGNAL(FPE);
7219 TRANSLATE_SIGNAL(HUP);
7222 TRANSLATE_SIGNAL(ILL);
7225 TRANSLATE_SIGNAL(INT);
7228 TRANSLATE_SIGNAL(KILL);
7231 TRANSLATE_SIGNAL(PIPE);
7234 TRANSLATE_SIGNAL(QUIT);
7237 TRANSLATE_SIGNAL(SEGV);
7240 TRANSLATE_SIGNAL(TERM);
7243 TRANSLATE_SIGNAL(USR1);
7246 TRANSLATE_SIGNAL(USR2);
7248 #undef TRANSLATE_SIGNAL
7250 ssh->exitcode = 128;
7252 core = ssh2_pkt_getbool(pktin);
7253 ssh_pkt_getstring(pktin, &msg, &msglen);
7255 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
7257 /* ignore lang tag */
7258 } /* else don't attempt to parse */
7259 logeventf(ssh, "Server exited on signal%s%s%s",
7260 fmt_sig, core ? " (core dumped)" : "",
7262 if (*fmt_sig) sfree(fmt_sig);
7263 if (*fmt_msg) sfree(fmt_msg);
7264 reply = SSH2_MSG_CHANNEL_SUCCESS;
7269 * This is a channel request we don't know
7270 * about, so we now either ignore the request
7271 * or respond with CHANNEL_FAILURE, depending
7274 reply = SSH2_MSG_CHANNEL_FAILURE;
7277 pktout = ssh2_pkt_init(reply);
7278 ssh2_pkt_adduint32(pktout, c->remoteid);
7279 ssh2_pkt_send(ssh, pktout);
7283 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7286 int typelen, want_reply;
7287 struct Packet *pktout;
7289 ssh_pkt_getstring(pktin, &type, &typelen);
7290 want_reply = ssh2_pkt_getbool(pktin);
7293 * We currently don't support any global requests
7294 * at all, so we either ignore the request or
7295 * respond with REQUEST_FAILURE, depending on
7299 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7300 ssh2_pkt_send(ssh, pktout);
7304 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7312 struct ssh_channel *c;
7313 unsigned remid, winsize, pktsize;
7314 struct Packet *pktout;
7316 ssh_pkt_getstring(pktin, &type, &typelen);
7317 c = snew(struct ssh_channel);
7320 remid = ssh_pkt_getuint32(pktin);
7321 winsize = ssh_pkt_getuint32(pktin);
7322 pktsize = ssh_pkt_getuint32(pktin);
7324 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7328 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7329 addrstr = snewn(peeraddrlen+1, char);
7330 memcpy(addrstr, peeraddr, peeraddrlen);
7331 addrstr[peeraddrlen] = '\0';
7332 peerport = ssh_pkt_getuint32(pktin);
7334 logeventf(ssh, "Received X11 connect request from %s:%d",
7337 if (!ssh->X11_fwd_enabled)
7338 error = "X11 forwarding is not enabled";
7339 else if ((x11err = x11_init(&c->u.x11.s, ssh->x11disp, c,
7340 addrstr, peerport, ssh->conf)) != NULL) {
7341 logeventf(ssh, "Local X11 connection failed: %s", x11err);
7342 error = "Unable to open an X11 connection";
7344 logevent("Opening X11 forward connection succeeded");
7349 } else if (typelen == 15 &&
7350 !memcmp(type, "forwarded-tcpip", 15)) {
7351 struct ssh_rportfwd pf, *realpf;
7354 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
7355 pf.sport = ssh_pkt_getuint32(pktin);
7356 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7357 peerport = ssh_pkt_getuint32(pktin);
7358 realpf = find234(ssh->rportfwds, &pf, NULL);
7359 logeventf(ssh, "Received remote port %d open request "
7360 "from %s:%d", pf.sport, peeraddr, peerport);
7361 if (realpf == NULL) {
7362 error = "Remote port is not recognised";
7364 const char *e = pfd_newconnect(&c->u.pfd.s,
7368 realpf->pfrec->addressfamily);
7369 logeventf(ssh, "Attempting to forward remote port to "
7370 "%s:%d", realpf->dhost, realpf->dport);
7372 logeventf(ssh, "Port open failed: %s", e);
7373 error = "Port open failed";
7375 logevent("Forwarded port opened successfully");
7376 c->type = CHAN_SOCKDATA;
7379 } else if (typelen == 22 &&
7380 !memcmp(type, "auth-agent@openssh.com", 22)) {
7381 if (!ssh->agentfwd_enabled)
7382 error = "Agent forwarding is not enabled";
7384 c->type = CHAN_AGENT; /* identify channel type */
7385 c->u.a.lensofar = 0;
7388 error = "Unsupported channel type requested";
7391 c->remoteid = remid;
7392 c->halfopen = FALSE;
7394 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7395 ssh2_pkt_adduint32(pktout, c->remoteid);
7396 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7397 ssh2_pkt_addstring(pktout, error);
7398 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7399 ssh2_pkt_send(ssh, pktout);
7400 logeventf(ssh, "Rejected channel open: %s", error);
7403 ssh2_channel_init(c);
7404 c->v.v2.remwindow = winsize;
7405 c->v.v2.remmaxpkt = pktsize;
7406 add234(ssh->channels, c);
7407 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7408 ssh2_pkt_adduint32(pktout, c->remoteid);
7409 ssh2_pkt_adduint32(pktout, c->localid);
7410 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7411 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7412 ssh2_pkt_send(ssh, pktout);
7417 * Buffer banner messages for later display at some convenient point,
7418 * if we're going to display them.
7420 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7422 /* Arbitrary limit to prevent unbounded inflation of buffer */
7423 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
7424 bufchain_size(&ssh->banner) <= 131072) {
7425 char *banner = NULL;
7427 ssh_pkt_getstring(pktin, &banner, &size);
7429 bufchain_add(&ssh->banner, banner, size);
7433 /* Helper function to deal with sending tty modes for "pty-req" */
7434 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7436 struct Packet *pktout = (struct Packet *)data;
7438 unsigned int arg = 0;
7439 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7440 if (i == lenof(ssh_ttymodes)) return;
7441 switch (ssh_ttymodes[i].type) {
7443 arg = ssh_tty_parse_specchar(val);
7446 arg = ssh_tty_parse_boolean(val);
7449 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7450 ssh2_pkt_adduint32(pktout, arg);
7454 * Handle the SSH-2 userauth and connection layers.
7456 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7457 struct Packet *pktin)
7459 struct do_ssh2_authconn_state {
7462 AUTH_TYPE_PUBLICKEY,
7463 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7464 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7466 AUTH_TYPE_GSSAPI, /* always QUIET */
7467 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7468 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7470 int done_service_req;
7471 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7472 int tried_pubkey_config, done_agent;
7477 int kbd_inter_refused;
7478 int we_are_in, userauth_success;
7479 prompts_t *cur_prompt;
7484 void *publickey_blob;
7485 int publickey_bloblen;
7486 int publickey_encrypted;
7487 char *publickey_algorithm;
7488 char *publickey_comment;
7489 unsigned char agent_request[5], *agent_response, *agentp;
7490 int agent_responselen;
7491 unsigned char *pkblob_in_agent;
7493 char *pkblob, *alg, *commentp;
7494 int pklen, alglen, commentlen;
7495 int siglen, retlen, len;
7496 char *q, *agentreq, *ret;
7498 int num_env, env_left, env_ok;
7499 struct Packet *pktout;
7502 struct ssh_gss_library *gsslib;
7503 Ssh_gss_ctx gss_ctx;
7504 Ssh_gss_buf gss_buf;
7505 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7506 Ssh_gss_name gss_srv_name;
7507 Ssh_gss_stat gss_stat;
7510 crState(do_ssh2_authconn_state);
7512 crBegin(ssh->do_ssh2_authconn_crstate);
7514 s->done_service_req = FALSE;
7515 s->we_are_in = s->userauth_success = FALSE;
7517 s->tried_gssapi = FALSE;
7520 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
7522 * Request userauth protocol, and await a response to it.
7524 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7525 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7526 ssh2_pkt_send(ssh, s->pktout);
7527 crWaitUntilV(pktin);
7528 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7529 s->done_service_req = TRUE;
7531 if (!s->done_service_req) {
7533 * Request connection protocol directly, without authentication.
7535 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7536 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7537 ssh2_pkt_send(ssh, s->pktout);
7538 crWaitUntilV(pktin);
7539 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7540 s->we_are_in = TRUE; /* no auth required */
7542 bombout(("Server refused service request"));
7547 /* Arrange to be able to deal with any BANNERs that come in.
7548 * (We do this now as packets may come in during the next bit.) */
7549 bufchain_init(&ssh->banner);
7550 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7551 ssh2_msg_userauth_banner;
7554 * Misc one-time setup for authentication.
7556 s->publickey_blob = NULL;
7557 if (!s->we_are_in) {
7560 * Load the public half of any configured public key file
7563 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
7564 if (!filename_is_null(s->keyfile)) {
7566 logeventf(ssh, "Reading private key file \"%.150s\"",
7567 filename_to_str(s->keyfile));
7568 keytype = key_type(s->keyfile);
7569 if (keytype == SSH_KEYTYPE_SSH2) {
7572 ssh2_userkey_loadpub(s->keyfile,
7573 &s->publickey_algorithm,
7574 &s->publickey_bloblen,
7575 &s->publickey_comment, &error);
7576 if (s->publickey_blob) {
7577 s->publickey_encrypted =
7578 ssh2_userkey_encrypted(s->keyfile, NULL);
7581 logeventf(ssh, "Unable to load private key (%s)",
7583 msgbuf = dupprintf("Unable to load private key file "
7584 "\"%.150s\" (%s)\r\n",
7585 filename_to_str(s->keyfile),
7587 c_write_str(ssh, msgbuf);
7592 logeventf(ssh, "Unable to use this key file (%s)",
7593 key_type_to_str(keytype));
7594 msgbuf = dupprintf("Unable to use key file \"%.150s\""
7596 filename_to_str(s->keyfile),
7597 key_type_to_str(keytype));
7598 c_write_str(ssh, msgbuf);
7600 s->publickey_blob = NULL;
7605 * Find out about any keys Pageant has (but if there's a
7606 * public key configured, filter out all others).
7609 s->agent_response = NULL;
7610 s->pkblob_in_agent = NULL;
7611 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
7615 logevent("Pageant is running. Requesting keys.");
7617 /* Request the keys held by the agent. */
7618 PUT_32BIT(s->agent_request, 1);
7619 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
7620 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
7621 ssh_agent_callback, ssh)) {
7625 bombout(("Unexpected data from server while"
7626 " waiting for agent response"));
7629 } while (pktin || inlen > 0);
7630 r = ssh->agent_response;
7631 s->agent_responselen = ssh->agent_response_len;
7633 s->agent_response = (unsigned char *) r;
7634 if (s->agent_response && s->agent_responselen >= 5 &&
7635 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
7638 p = s->agent_response + 5;
7639 s->nkeys = GET_32BIT(p);
7641 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
7642 if (s->publickey_blob) {
7643 /* See if configured key is in agent. */
7644 for (keyi = 0; keyi < s->nkeys; keyi++) {
7645 s->pklen = GET_32BIT(p);
7646 if (s->pklen == s->publickey_bloblen &&
7647 !memcmp(p+4, s->publickey_blob,
7648 s->publickey_bloblen)) {
7649 logeventf(ssh, "Pageant key #%d matches "
7650 "configured key file", keyi);
7652 s->pkblob_in_agent = p;
7656 p += GET_32BIT(p) + 4; /* comment */
7658 if (!s->pkblob_in_agent) {
7659 logevent("Configured key file not in Pageant");
7664 logevent("Failed to get reply from Pageant");
7671 * We repeat this whole loop, including the username prompt,
7672 * until we manage a successful authentication. If the user
7673 * types the wrong _password_, they can be sent back to the
7674 * beginning to try another username, if this is configured on.
7675 * (If they specify a username in the config, they are never
7676 * asked, even if they do give a wrong password.)
7678 * I think this best serves the needs of
7680 * - the people who have no configuration, no keys, and just
7681 * want to try repeated (username,password) pairs until they
7682 * type both correctly
7684 * - people who have keys and configuration but occasionally
7685 * need to fall back to passwords
7687 * - people with a key held in Pageant, who might not have
7688 * logged in to a particular machine before; so they want to
7689 * type a username, and then _either_ their key will be
7690 * accepted, _or_ they will type a password. If they mistype
7691 * the username they will want to be able to get back and
7694 s->got_username = FALSE;
7695 while (!s->we_are_in) {
7699 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
7701 * We got a username last time round this loop, and
7702 * with change_username turned off we don't try to get
7705 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
7706 int ret; /* need not be kept over crReturn */
7707 s->cur_prompt = new_prompts(ssh->frontend);
7708 s->cur_prompt->to_server = TRUE;
7709 s->cur_prompt->name = dupstr("SSH login name");
7710 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
7711 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7714 crWaitUntilV(!pktin);
7715 ret = get_userpass_input(s->cur_prompt, in, inlen);
7720 * get_userpass_input() failed to get a username.
7723 free_prompts(s->cur_prompt);
7724 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
7727 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
7728 free_prompts(s->cur_prompt);
7731 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7732 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
7733 c_write_str(ssh, stuff);
7737 s->got_username = TRUE;
7740 * Send an authentication request using method "none": (a)
7741 * just in case it succeeds, and (b) so that we know what
7742 * authentication methods we can usefully try next.
7744 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7746 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7747 ssh2_pkt_addstring(s->pktout, ssh->username);
7748 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
7749 ssh2_pkt_addstring(s->pktout, "none"); /* method */
7750 ssh2_pkt_send(ssh, s->pktout);
7751 s->type = AUTH_TYPE_NONE;
7753 s->we_are_in = FALSE;
7755 s->tried_pubkey_config = FALSE;
7756 s->kbd_inter_refused = FALSE;
7758 /* Reset agent request state. */
7759 s->done_agent = FALSE;
7760 if (s->agent_response) {
7761 if (s->pkblob_in_agent) {
7762 s->agentp = s->pkblob_in_agent;
7764 s->agentp = s->agent_response + 5 + 4;
7770 char *methods = NULL;
7774 * Wait for the result of the last authentication request.
7777 crWaitUntilV(pktin);
7779 * Now is a convenient point to spew any banner material
7780 * that we've accumulated. (This should ensure that when
7781 * we exit the auth loop, we haven't any left to deal
7785 int size = bufchain_size(&ssh->banner);
7787 * Don't show the banner if we're operating in
7788 * non-verbose non-interactive mode. (It's probably
7789 * a script, which means nobody will read the
7790 * banner _anyway_, and moreover the printing of
7791 * the banner will screw up processing on the
7792 * output of (say) plink.)
7794 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
7795 char *banner = snewn(size, char);
7796 bufchain_fetch(&ssh->banner, banner, size);
7797 c_write_untrusted(ssh, banner, size);
7800 bufchain_clear(&ssh->banner);
7802 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
7803 logevent("Access granted");
7804 s->we_are_in = s->userauth_success = TRUE;
7808 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
7809 bombout(("Strange packet received during authentication: "
7810 "type %d", pktin->type));
7817 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7818 * we can look at the string in it and know what we can
7819 * helpfully try next.
7821 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
7822 ssh_pkt_getstring(pktin, &methods, &methlen);
7823 if (!ssh2_pkt_getbool(pktin)) {
7825 * We have received an unequivocal Access
7826 * Denied. This can translate to a variety of
7827 * messages, or no message at all.
7829 * For forms of authentication which are attempted
7830 * implicitly, by which I mean without printing
7831 * anything in the window indicating that we're
7832 * trying them, we should never print 'Access
7835 * If we do print a message saying that we're
7836 * attempting some kind of authentication, it's OK
7837 * to print a followup message saying it failed -
7838 * but the message may sometimes be more specific
7839 * than simply 'Access denied'.
7841 * Additionally, if we'd just tried password
7842 * authentication, we should break out of this
7843 * whole loop so as to go back to the username
7844 * prompt (iff we're configured to allow
7845 * username change attempts).
7847 if (s->type == AUTH_TYPE_NONE) {
7849 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
7850 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
7851 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
7852 c_write_str(ssh, "Server refused our key\r\n");
7853 logevent("Server refused our key");
7854 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
7855 /* This _shouldn't_ happen except by a
7856 * protocol bug causing client and server to
7857 * disagree on what is a correct signature. */
7858 c_write_str(ssh, "Server refused public-key signature"
7859 " despite accepting key!\r\n");
7860 logevent("Server refused public-key signature"
7861 " despite accepting key!");
7862 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
7863 /* quiet, so no c_write */
7864 logevent("Server refused keyboard-interactive authentication");
7865 } else if (s->type==AUTH_TYPE_GSSAPI) {
7866 /* always quiet, so no c_write */
7867 /* also, the code down in the GSSAPI block has
7868 * already logged this in the Event Log */
7869 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
7870 logevent("Keyboard-interactive authentication failed");
7871 c_write_str(ssh, "Access denied\r\n");
7873 assert(s->type == AUTH_TYPE_PASSWORD);
7874 logevent("Password authentication failed");
7875 c_write_str(ssh, "Access denied\r\n");
7877 if (conf_get_int(ssh->conf, CONF_change_username)) {
7878 /* XXX perhaps we should allow
7879 * keyboard-interactive to do this too? */
7880 s->we_are_in = FALSE;
7885 c_write_str(ssh, "Further authentication required\r\n");
7886 logevent("Further authentication required");
7890 in_commasep_string("publickey", methods, methlen);
7892 in_commasep_string("password", methods, methlen);
7893 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
7894 in_commasep_string("keyboard-interactive", methods, methlen);
7897 ssh->gsslibs = ssh_gss_setup(ssh->conf);
7898 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
7899 in_commasep_string("gssapi-with-mic", methods, methlen) &&
7900 ssh->gsslibs->nlibraries > 0;
7904 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7906 if (s->can_pubkey && !s->done_agent && s->nkeys) {
7909 * Attempt public-key authentication using a key from Pageant.
7912 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7914 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
7916 /* Unpack key from agent response */
7917 s->pklen = GET_32BIT(s->agentp);
7919 s->pkblob = (char *)s->agentp;
7920 s->agentp += s->pklen;
7921 s->alglen = GET_32BIT(s->pkblob);
7922 s->alg = s->pkblob + 4;
7923 s->commentlen = GET_32BIT(s->agentp);
7925 s->commentp = (char *)s->agentp;
7926 s->agentp += s->commentlen;
7927 /* s->agentp now points at next key, if any */
7929 /* See if server will accept it */
7930 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7931 ssh2_pkt_addstring(s->pktout, ssh->username);
7932 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7933 /* service requested */
7934 ssh2_pkt_addstring(s->pktout, "publickey");
7936 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
7937 ssh2_pkt_addstring_start(s->pktout);
7938 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7939 ssh2_pkt_addstring_start(s->pktout);
7940 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7941 ssh2_pkt_send(ssh, s->pktout);
7942 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
7944 crWaitUntilV(pktin);
7945 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7947 /* Offer of key refused. */
7954 if (flags & FLAG_VERBOSE) {
7955 c_write_str(ssh, "Authenticating with "
7957 c_write(ssh, s->commentp, s->commentlen);
7958 c_write_str(ssh, "\" from agent\r\n");
7962 * Server is willing to accept the key.
7963 * Construct a SIGN_REQUEST.
7965 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7966 ssh2_pkt_addstring(s->pktout, ssh->username);
7967 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7968 /* service requested */
7969 ssh2_pkt_addstring(s->pktout, "publickey");
7971 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
7972 ssh2_pkt_addstring_start(s->pktout);
7973 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7974 ssh2_pkt_addstring_start(s->pktout);
7975 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7977 /* Ask agent for signature. */
7978 s->siglen = s->pktout->length - 5 + 4 +
7979 ssh->v2_session_id_len;
7980 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7982 s->len = 1; /* message type */
7983 s->len += 4 + s->pklen; /* key blob */
7984 s->len += 4 + s->siglen; /* data to sign */
7985 s->len += 4; /* flags */
7986 s->agentreq = snewn(4 + s->len, char);
7987 PUT_32BIT(s->agentreq, s->len);
7988 s->q = s->agentreq + 4;
7989 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
7990 PUT_32BIT(s->q, s->pklen);
7992 memcpy(s->q, s->pkblob, s->pklen);
7994 PUT_32BIT(s->q, s->siglen);
7996 /* Now the data to be signed... */
7997 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7998 PUT_32BIT(s->q, ssh->v2_session_id_len);
8001 memcpy(s->q, ssh->v2_session_id,
8002 ssh->v2_session_id_len);
8003 s->q += ssh->v2_session_id_len;
8004 memcpy(s->q, s->pktout->data + 5,
8005 s->pktout->length - 5);
8006 s->q += s->pktout->length - 5;
8007 /* And finally the (zero) flags word. */
8009 if (!agent_query(s->agentreq, s->len + 4,
8011 ssh_agent_callback, ssh)) {
8015 bombout(("Unexpected data from server"
8016 " while waiting for agent"
8020 } while (pktin || inlen > 0);
8021 vret = ssh->agent_response;
8022 s->retlen = ssh->agent_response_len;
8027 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
8028 logevent("Sending Pageant's response");
8029 ssh2_add_sigblob(ssh, s->pktout,
8030 s->pkblob, s->pklen,
8032 GET_32BIT(s->ret + 5));
8033 ssh2_pkt_send(ssh, s->pktout);
8034 s->type = AUTH_TYPE_PUBLICKEY;
8036 /* FIXME: less drastic response */
8037 bombout(("Pageant failed to answer challenge"));
8043 /* Do we have any keys left to try? */
8044 if (s->pkblob_in_agent) {
8045 s->done_agent = TRUE;
8046 s->tried_pubkey_config = TRUE;
8049 if (s->keyi >= s->nkeys)
8050 s->done_agent = TRUE;
8053 } else if (s->can_pubkey && s->publickey_blob &&
8054 !s->tried_pubkey_config) {
8056 struct ssh2_userkey *key; /* not live over crReturn */
8057 char *passphrase; /* not live over crReturn */
8059 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8061 s->tried_pubkey_config = TRUE;
8064 * Try the public key supplied in the configuration.
8066 * First, offer the public blob to see if the server is
8067 * willing to accept it.
8069 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8070 ssh2_pkt_addstring(s->pktout, ssh->username);
8071 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8072 /* service requested */
8073 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
8074 ssh2_pkt_addbool(s->pktout, FALSE);
8075 /* no signature included */
8076 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
8077 ssh2_pkt_addstring_start(s->pktout);
8078 ssh2_pkt_addstring_data(s->pktout,
8079 (char *)s->publickey_blob,
8080 s->publickey_bloblen);
8081 ssh2_pkt_send(ssh, s->pktout);
8082 logevent("Offered public key");
8084 crWaitUntilV(pktin);
8085 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8086 /* Key refused. Give up. */
8087 s->gotit = TRUE; /* reconsider message next loop */
8088 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
8089 continue; /* process this new message */
8091 logevent("Offer of public key accepted");
8094 * Actually attempt a serious authentication using
8097 if (flags & FLAG_VERBOSE) {
8098 c_write_str(ssh, "Authenticating with public key \"");
8099 c_write_str(ssh, s->publickey_comment);
8100 c_write_str(ssh, "\"\r\n");
8104 const char *error; /* not live over crReturn */
8105 if (s->publickey_encrypted) {
8107 * Get a passphrase from the user.
8109 int ret; /* need not be kept over crReturn */
8110 s->cur_prompt = new_prompts(ssh->frontend);
8111 s->cur_prompt->to_server = FALSE;
8112 s->cur_prompt->name = dupstr("SSH key passphrase");
8113 add_prompt(s->cur_prompt,
8114 dupprintf("Passphrase for key \"%.100s\": ",
8115 s->publickey_comment),
8117 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8120 crWaitUntilV(!pktin);
8121 ret = get_userpass_input(s->cur_prompt,
8126 /* Failed to get a passphrase. Terminate. */
8127 free_prompts(s->cur_prompt);
8128 ssh_disconnect(ssh, NULL,
8129 "Unable to authenticate",
8130 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8135 dupstr(s->cur_prompt->prompts[0]->result);
8136 free_prompts(s->cur_prompt);
8138 passphrase = NULL; /* no passphrase needed */
8142 * Try decrypting the key.
8144 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8145 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
8147 /* burn the evidence */
8148 memset(passphrase, 0, strlen(passphrase));
8151 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
8153 (key == SSH2_WRONG_PASSPHRASE)) {
8154 c_write_str(ssh, "Wrong passphrase\r\n");
8156 /* and loop again */
8158 c_write_str(ssh, "Unable to load private key (");
8159 c_write_str(ssh, error);
8160 c_write_str(ssh, ")\r\n");
8162 break; /* try something else */
8168 unsigned char *pkblob, *sigblob, *sigdata;
8169 int pkblob_len, sigblob_len, sigdata_len;
8173 * We have loaded the private key and the server
8174 * has announced that it's willing to accept it.
8175 * Hallelujah. Generate a signature and send it.
8177 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8178 ssh2_pkt_addstring(s->pktout, ssh->username);
8179 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8180 /* service requested */
8181 ssh2_pkt_addstring(s->pktout, "publickey");
8183 ssh2_pkt_addbool(s->pktout, TRUE);
8184 /* signature follows */
8185 ssh2_pkt_addstring(s->pktout, key->alg->name);
8186 pkblob = key->alg->public_blob(key->data,
8188 ssh2_pkt_addstring_start(s->pktout);
8189 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
8193 * The data to be signed is:
8197 * followed by everything so far placed in the
8200 sigdata_len = s->pktout->length - 5 + 4 +
8201 ssh->v2_session_id_len;
8202 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8204 sigdata = snewn(sigdata_len, unsigned char);
8206 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8207 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
8210 memcpy(sigdata+p, ssh->v2_session_id,
8211 ssh->v2_session_id_len);
8212 p += ssh->v2_session_id_len;
8213 memcpy(sigdata+p, s->pktout->data + 5,
8214 s->pktout->length - 5);
8215 p += s->pktout->length - 5;
8216 assert(p == sigdata_len);
8217 sigblob = key->alg->sign(key->data, (char *)sigdata,
8218 sigdata_len, &sigblob_len);
8219 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
8220 sigblob, sigblob_len);
8225 ssh2_pkt_send(ssh, s->pktout);
8226 logevent("Sent public key signature");
8227 s->type = AUTH_TYPE_PUBLICKEY;
8228 key->alg->freekey(key->data);
8232 } else if (s->can_gssapi && !s->tried_gssapi) {
8234 /* GSSAPI Authentication */
8239 s->type = AUTH_TYPE_GSSAPI;
8240 s->tried_gssapi = TRUE;
8242 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
8245 * Pick the highest GSS library on the preference
8251 for (i = 0; i < ngsslibs; i++) {
8252 int want_id = conf_get_int_int(ssh->conf,
8253 CONF_ssh_gsslist, i);
8254 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
8255 if (ssh->gsslibs->libraries[j].id == want_id) {
8256 s->gsslib = &ssh->gsslibs->libraries[j];
8257 goto got_gsslib; /* double break */
8262 * We always expect to have found something in
8263 * the above loop: we only came here if there
8264 * was at least one viable GSS library, and the
8265 * preference list should always mention
8266 * everything and only change the order.
8271 if (s->gsslib->gsslogmsg)
8272 logevent(s->gsslib->gsslogmsg);
8274 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8275 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8276 ssh2_pkt_addstring(s->pktout, ssh->username);
8277 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8278 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
8279 logevent("Attempting GSSAPI authentication");
8281 /* add mechanism info */
8282 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
8284 /* number of GSSAPI mechanisms */
8285 ssh2_pkt_adduint32(s->pktout,1);
8287 /* length of OID + 2 */
8288 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
8289 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
8292 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
8294 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
8296 ssh2_pkt_send(ssh, s->pktout);
8297 crWaitUntilV(pktin);
8298 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
8299 logevent("GSSAPI authentication request refused");
8303 /* check returned packet ... */
8305 ssh_pkt_getstring(pktin, &data, &len);
8306 s->gss_rcvtok.value = data;
8307 s->gss_rcvtok.length = len;
8308 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
8309 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
8310 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
8311 memcmp((char *)s->gss_rcvtok.value + 2,
8312 s->gss_buf.value,s->gss_buf.length) ) {
8313 logevent("GSSAPI authentication - wrong response from server");
8317 /* now start running */
8318 s->gss_stat = s->gsslib->import_name(s->gsslib,
8321 if (s->gss_stat != SSH_GSS_OK) {
8322 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
8323 logevent("GSSAPI import name failed - Bad service name");
8325 logevent("GSSAPI import name failed");
8329 /* fetch TGT into GSS engine */
8330 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
8332 if (s->gss_stat != SSH_GSS_OK) {
8333 logevent("GSSAPI authentication failed to get credentials");
8334 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8338 /* initial tokens are empty */
8339 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
8340 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
8342 /* now enter the loop */
8344 s->gss_stat = s->gsslib->init_sec_context
8348 conf_get_int(ssh->conf, CONF_gssapifwd),
8352 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
8353 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
8354 logevent("GSSAPI authentication initialisation failed");
8356 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
8357 &s->gss_buf) == SSH_GSS_OK) {
8358 logevent(s->gss_buf.value);
8359 sfree(s->gss_buf.value);
8364 logevent("GSSAPI authentication initialised");
8366 /* Client and server now exchange tokens until GSSAPI
8367 * no longer says CONTINUE_NEEDED */
8369 if (s->gss_sndtok.length != 0) {
8370 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8371 ssh_pkt_addstring_start(s->pktout);
8372 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
8373 ssh2_pkt_send(ssh, s->pktout);
8374 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
8377 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8378 crWaitUntilV(pktin);
8379 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8380 logevent("GSSAPI authentication - bad server response");
8381 s->gss_stat = SSH_GSS_FAILURE;
8384 ssh_pkt_getstring(pktin, &data, &len);
8385 s->gss_rcvtok.value = data;
8386 s->gss_rcvtok.length = len;
8388 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8390 if (s->gss_stat != SSH_GSS_OK) {
8391 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8392 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8395 logevent("GSSAPI authentication loop finished OK");
8397 /* Now send the MIC */
8399 s->pktout = ssh2_pkt_init(0);
8400 micoffset = s->pktout->length;
8401 ssh_pkt_addstring_start(s->pktout);
8402 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8403 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
8404 ssh_pkt_addstring(s->pktout, ssh->username);
8405 ssh_pkt_addstring(s->pktout, "ssh-connection");
8406 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8408 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8409 s->gss_buf.length = s->pktout->length - micoffset;
8411 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
8412 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8413 ssh_pkt_addstring_start(s->pktout);
8414 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
8415 ssh2_pkt_send(ssh, s->pktout);
8416 s->gsslib->free_mic(s->gsslib, &mic);
8420 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8421 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8424 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8427 * Keyboard-interactive authentication.
8430 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8432 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
8434 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8435 ssh2_pkt_addstring(s->pktout, ssh->username);
8436 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8437 /* service requested */
8438 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8440 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8441 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8442 ssh2_pkt_send(ssh, s->pktout);
8444 logevent("Attempting keyboard-interactive authentication");
8446 crWaitUntilV(pktin);
8447 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8448 /* Server is not willing to do keyboard-interactive
8449 * at all (or, bizarrely but legally, accepts the
8450 * user without actually issuing any prompts).
8451 * Give up on it entirely. */
8453 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8454 s->kbd_inter_refused = TRUE; /* don't try it again */
8459 * Loop while the server continues to send INFO_REQUESTs.
8461 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
8463 char *name, *inst, *lang;
8464 int name_len, inst_len, lang_len;
8468 * We've got a fresh USERAUTH_INFO_REQUEST.
8469 * Get the preamble and start building a prompt.
8471 ssh_pkt_getstring(pktin, &name, &name_len);
8472 ssh_pkt_getstring(pktin, &inst, &inst_len);
8473 ssh_pkt_getstring(pktin, &lang, &lang_len);
8474 s->cur_prompt = new_prompts(ssh->frontend);
8475 s->cur_prompt->to_server = TRUE;
8478 * Get any prompt(s) from the packet.
8480 s->num_prompts = ssh_pkt_getuint32(pktin);
8481 for (i = 0; i < s->num_prompts; i++) {
8485 static char noprompt[] =
8486 "<server failed to send prompt>: ";
8488 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8489 echo = ssh2_pkt_getbool(pktin);
8492 prompt_len = lenof(noprompt)-1;
8494 add_prompt(s->cur_prompt,
8495 dupprintf("%.*s", prompt_len, prompt),
8500 /* FIXME: better prefix to distinguish from
8502 s->cur_prompt->name =
8503 dupprintf("SSH server: %.*s", name_len, name);
8504 s->cur_prompt->name_reqd = TRUE;
8506 s->cur_prompt->name =
8507 dupstr("SSH server authentication");
8508 s->cur_prompt->name_reqd = FALSE;
8510 /* We add a prefix to try to make it clear that a prompt
8511 * has come from the server.
8512 * FIXME: ugly to print "Using..." in prompt _every_
8513 * time round. Can this be done more subtly? */
8514 /* Special case: for reasons best known to themselves,
8515 * some servers send k-i requests with no prompts and
8516 * nothing to display. Keep quiet in this case. */
8517 if (s->num_prompts || name_len || inst_len) {
8518 s->cur_prompt->instruction =
8519 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8520 inst_len ? "\n" : "", inst_len, inst);
8521 s->cur_prompt->instr_reqd = TRUE;
8523 s->cur_prompt->instr_reqd = FALSE;
8527 * Display any instructions, and get the user's
8531 int ret; /* not live over crReturn */
8532 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8535 crWaitUntilV(!pktin);
8536 ret = get_userpass_input(s->cur_prompt, in, inlen);
8541 * Failed to get responses. Terminate.
8543 free_prompts(s->cur_prompt);
8544 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8545 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8552 * Send the response(s) to the server.
8554 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
8555 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
8556 for (i=0; i < s->num_prompts; i++) {
8557 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8558 ssh2_pkt_addstring(s->pktout,
8559 s->cur_prompt->prompts[i]->result);
8560 end_log_omission(ssh, s->pktout);
8562 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8565 * Free the prompts structure from this iteration.
8566 * If there's another, a new one will be allocated
8567 * when we return to the top of this while loop.
8569 free_prompts(s->cur_prompt);
8572 * Get the next packet in case it's another
8575 crWaitUntilV(pktin);
8580 * We should have SUCCESS or FAILURE now.
8584 } else if (s->can_passwd) {
8587 * Plain old password authentication.
8589 int ret; /* not live over crReturn */
8590 int changereq_first_time; /* not live over crReturn */
8592 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
8594 s->cur_prompt = new_prompts(ssh->frontend);
8595 s->cur_prompt->to_server = TRUE;
8596 s->cur_prompt->name = dupstr("SSH password");
8597 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
8602 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8605 crWaitUntilV(!pktin);
8606 ret = get_userpass_input(s->cur_prompt, in, inlen);
8611 * Failed to get responses. Terminate.
8613 free_prompts(s->cur_prompt);
8614 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8615 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8620 * Squirrel away the password. (We may need it later if
8621 * asked to change it.)
8623 s->password = dupstr(s->cur_prompt->prompts[0]->result);
8624 free_prompts(s->cur_prompt);
8627 * Send the password packet.
8629 * We pad out the password packet to 256 bytes to make
8630 * it harder for an attacker to find the length of the
8633 * Anyone using a password longer than 256 bytes
8634 * probably doesn't have much to worry about from
8635 * people who find out how long their password is!
8637 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8638 ssh2_pkt_addstring(s->pktout, ssh->username);
8639 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8640 /* service requested */
8641 ssh2_pkt_addstring(s->pktout, "password");
8642 ssh2_pkt_addbool(s->pktout, FALSE);
8643 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8644 ssh2_pkt_addstring(s->pktout, s->password);
8645 end_log_omission(ssh, s->pktout);
8646 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8647 logevent("Sent password");
8648 s->type = AUTH_TYPE_PASSWORD;
8651 * Wait for next packet, in case it's a password change
8654 crWaitUntilV(pktin);
8655 changereq_first_time = TRUE;
8657 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
8660 * We're being asked for a new password
8661 * (perhaps not for the first time).
8662 * Loop until the server accepts it.
8665 int got_new = FALSE; /* not live over crReturn */
8666 char *prompt; /* not live over crReturn */
8667 int prompt_len; /* not live over crReturn */
8671 if (changereq_first_time)
8672 msg = "Server requested password change";
8674 msg = "Server rejected new password";
8676 c_write_str(ssh, msg);
8677 c_write_str(ssh, "\r\n");
8680 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8682 s->cur_prompt = new_prompts(ssh->frontend);
8683 s->cur_prompt->to_server = TRUE;
8684 s->cur_prompt->name = dupstr("New SSH password");
8685 s->cur_prompt->instruction =
8686 dupprintf("%.*s", prompt_len, prompt);
8687 s->cur_prompt->instr_reqd = TRUE;
8689 * There's no explicit requirement in the protocol
8690 * for the "old" passwords in the original and
8691 * password-change messages to be the same, and
8692 * apparently some Cisco kit supports password change
8693 * by the user entering a blank password originally
8694 * and the real password subsequently, so,
8695 * reluctantly, we prompt for the old password again.
8697 * (On the other hand, some servers don't even bother
8698 * to check this field.)
8700 add_prompt(s->cur_prompt,
8701 dupstr("Current password (blank for previously entered password): "),
8703 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
8705 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
8709 * Loop until the user manages to enter the same
8714 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8717 crWaitUntilV(!pktin);
8718 ret = get_userpass_input(s->cur_prompt, in, inlen);
8723 * Failed to get responses. Terminate.
8725 /* burn the evidence */
8726 free_prompts(s->cur_prompt);
8727 memset(s->password, 0, strlen(s->password));
8729 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8730 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8736 * If the user specified a new original password
8737 * (IYSWIM), overwrite any previously specified
8739 * (A side effect is that the user doesn't have to
8740 * re-enter it if they louse up the new password.)
8742 if (s->cur_prompt->prompts[0]->result[0]) {
8743 memset(s->password, 0, strlen(s->password));
8744 /* burn the evidence */
8747 dupstr(s->cur_prompt->prompts[0]->result);
8751 * Check the two new passwords match.
8753 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
8754 s->cur_prompt->prompts[2]->result)
8757 /* They don't. Silly user. */
8758 c_write_str(ssh, "Passwords do not match\r\n");
8763 * Send the new password (along with the old one).
8764 * (see above for padding rationale)
8766 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8767 ssh2_pkt_addstring(s->pktout, ssh->username);
8768 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8769 /* service requested */
8770 ssh2_pkt_addstring(s->pktout, "password");
8771 ssh2_pkt_addbool(s->pktout, TRUE);
8772 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8773 ssh2_pkt_addstring(s->pktout, s->password);
8774 ssh2_pkt_addstring(s->pktout,
8775 s->cur_prompt->prompts[1]->result);
8776 free_prompts(s->cur_prompt);
8777 end_log_omission(ssh, s->pktout);
8778 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8779 logevent("Sent new password");
8782 * Now see what the server has to say about it.
8783 * (If it's CHANGEREQ again, it's not happy with the
8786 crWaitUntilV(pktin);
8787 changereq_first_time = FALSE;
8792 * We need to reexamine the current pktin at the top
8793 * of the loop. Either:
8794 * - we weren't asked to change password at all, in
8795 * which case it's a SUCCESS or FAILURE with the
8797 * - we sent a new password, and the server was
8798 * either OK with it (SUCCESS or FAILURE w/partial
8799 * success) or unhappy with the _old_ password
8800 * (FAILURE w/o partial success)
8801 * In any of these cases, we go back to the top of
8802 * the loop and start again.
8807 * We don't need the old password any more, in any
8808 * case. Burn the evidence.
8810 memset(s->password, 0, strlen(s->password));
8814 char *str = dupprintf("No supported authentication methods available"
8815 " (server sent: %.*s)",
8818 ssh_disconnect(ssh, str,
8819 "No supported authentication methods available",
8820 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
8830 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
8832 /* Clear up various bits and pieces from authentication. */
8833 if (s->publickey_blob) {
8834 sfree(s->publickey_blob);
8835 sfree(s->publickey_comment);
8837 if (s->agent_response)
8838 sfree(s->agent_response);
8840 if (s->userauth_success) {
8842 * We've just received USERAUTH_SUCCESS, and we haven't sent any
8843 * packets since. Signal the transport layer to consider enacting
8844 * delayed compression.
8846 * (Relying on we_are_in is not sufficient, as
8847 * draft-miller-secsh-compression-delayed is quite clear that it
8848 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
8849 * become set for other reasons.)
8851 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
8855 * Now the connection protocol has started, one way or another.
8858 ssh->channels = newtree234(ssh_channelcmp);
8861 * Set up handlers for some connection protocol messages, so we
8862 * don't have to handle them repeatedly in this coroutine.
8864 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
8865 ssh2_msg_channel_window_adjust;
8866 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
8867 ssh2_msg_global_request;
8870 * Create the main session channel.
8872 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
8873 ssh->mainchan = NULL;
8874 } else if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
8876 * Just start a direct-tcpip channel and use it as the main
8879 ssh->mainchan = snew(struct ssh_channel);
8880 ssh->mainchan->ssh = ssh;
8881 ssh2_channel_init(ssh->mainchan);
8883 "Opening direct-tcpip channel to %s:%d in place of session",
8884 conf_get_str(ssh->conf, CONF_ssh_nc_host),
8885 conf_get_int(ssh->conf, CONF_ssh_nc_port));
8886 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8887 ssh2_pkt_addstring(s->pktout, "direct-tcpip");
8888 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8889 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8890 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8891 ssh2_pkt_addstring(s->pktout, conf_get_str(ssh->conf, CONF_ssh_nc_host));
8892 ssh2_pkt_adduint32(s->pktout, conf_get_int(ssh->conf, CONF_ssh_nc_port));
8894 * There's nothing meaningful to put in the originator
8895 * fields, but some servers insist on syntactically correct
8898 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
8899 ssh2_pkt_adduint32(s->pktout, 0);
8900 ssh2_pkt_send(ssh, s->pktout);
8902 crWaitUntilV(pktin);
8903 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8904 bombout(("Server refused to open a direct-tcpip channel"));
8906 /* FIXME: error data comes back in FAILURE packet */
8908 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8909 bombout(("Server's channel confirmation cited wrong channel"));
8912 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8913 ssh->mainchan->halfopen = FALSE;
8914 ssh->mainchan->type = CHAN_MAINSESSION;
8915 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8916 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8917 add234(ssh->channels, ssh->mainchan);
8918 update_specials_menu(ssh->frontend);
8919 logevent("Opened direct-tcpip channel");
8922 ssh->mainchan = snew(struct ssh_channel);
8923 ssh->mainchan->ssh = ssh;
8924 ssh2_channel_init(ssh->mainchan);
8925 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8926 ssh2_pkt_addstring(s->pktout, "session");
8927 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8928 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8929 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8930 ssh2_pkt_send(ssh, s->pktout);
8931 crWaitUntilV(pktin);
8932 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8933 bombout(("Server refused to open a session"));
8935 /* FIXME: error data comes back in FAILURE packet */
8937 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8938 bombout(("Server's channel confirmation cited wrong channel"));
8941 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8942 ssh->mainchan->halfopen = FALSE;
8943 ssh->mainchan->type = CHAN_MAINSESSION;
8944 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8945 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8946 add234(ssh->channels, ssh->mainchan);
8947 update_specials_menu(ssh->frontend);
8948 logevent("Opened channel for session");
8949 ssh->ncmode = FALSE;
8953 * Now we have a channel, make dispatch table entries for
8954 * general channel-based messages.
8956 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
8957 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
8958 ssh2_msg_channel_data;
8959 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
8960 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
8961 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
8962 ssh2_msg_channel_open_confirmation;
8963 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
8964 ssh2_msg_channel_open_failure;
8965 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
8966 ssh2_msg_channel_request;
8967 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
8968 ssh2_msg_channel_open;
8970 if (ssh->mainchan && conf_get_int(ssh->conf, CONF_ssh_simple)) {
8972 * This message indicates to the server that we promise
8973 * not to try to run any other channel in parallel with
8974 * this one, so it's safe for it to advertise a very large
8975 * window and leave the flow control to TCP.
8977 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8978 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8979 ssh2_pkt_addstring(s->pktout, "simple@putty.projects.tartarus.org");
8980 ssh2_pkt_addbool(s->pktout, 0); /* no reply */
8981 ssh2_pkt_send(ssh, s->pktout);
8985 * Potentially enable X11 forwarding.
8987 if (ssh->mainchan && !ssh->ncmode && conf_get_int(ssh->conf, CONF_x11_forward) &&
8988 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
8989 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
8990 logevent("Requesting X11 forwarding");
8991 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8992 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8993 ssh2_pkt_addstring(s->pktout, "x11-req");
8994 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8995 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
8996 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthprotoname);
8998 * Note that while we blank the X authentication data here, we don't
8999 * take any special action to blank the start of an X11 channel,
9000 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
9001 * without having session blanking enabled is likely to leak your
9002 * cookie into the log.
9004 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
9005 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthdatastring);
9006 end_log_omission(ssh, s->pktout);
9007 ssh2_pkt_adduint32(s->pktout, ssh->x11disp->screennum);
9008 ssh2_pkt_send(ssh, s->pktout);
9010 crWaitUntilV(pktin);
9012 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9013 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9014 bombout(("Unexpected response to X11 forwarding request:"
9015 " packet type %d", pktin->type));
9018 logevent("X11 forwarding refused");
9020 logevent("X11 forwarding enabled");
9021 ssh->X11_fwd_enabled = TRUE;
9026 * Enable port forwardings.
9028 ssh_setup_portfwd(ssh, ssh->conf);
9031 * Potentially enable agent forwarding.
9033 if (ssh->mainchan && !ssh->ncmode && conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
9034 logevent("Requesting OpenSSH-style agent forwarding");
9035 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9036 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
9037 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
9038 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9039 ssh2_pkt_send(ssh, s->pktout);
9041 crWaitUntilV(pktin);
9043 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9044 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9045 bombout(("Unexpected response to agent forwarding request:"
9046 " packet type %d", pktin->type));
9049 logevent("Agent forwarding refused");
9051 logevent("Agent forwarding enabled");
9052 ssh->agentfwd_enabled = TRUE;
9057 * Now allocate a pty for the session.
9059 if (ssh->mainchan && !ssh->ncmode && !conf_get_int(ssh->conf, CONF_nopty)) {
9060 /* Unpick the terminal-speed string. */
9061 /* XXX perhaps we should allow no speeds to be sent. */
9062 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
9063 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
9064 /* Build the pty request. */
9065 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9066 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
9067 ssh2_pkt_addstring(s->pktout, "pty-req");
9068 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9069 ssh2_pkt_addstring(s->pktout, conf_get_str(ssh->conf, CONF_termtype));
9070 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
9071 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
9072 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
9073 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
9074 ssh2_pkt_addstring_start(s->pktout);
9075 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)s->pktout);
9076 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_ISPEED);
9077 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
9078 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_OSPEED);
9079 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
9080 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
9081 ssh2_pkt_send(ssh, s->pktout);
9082 ssh->state = SSH_STATE_INTERMED;
9084 crWaitUntilV(pktin);
9086 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9087 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9088 bombout(("Unexpected response to pty request:"
9089 " packet type %d", pktin->type));
9092 c_write_str(ssh, "Server refused to allocate pty\r\n");
9093 ssh->editing = ssh->echoing = 1;
9095 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9096 ssh->ospeed, ssh->ispeed);
9097 ssh->got_pty = TRUE;
9100 ssh->editing = ssh->echoing = 1;
9104 * Send environment variables.
9106 * Simplest thing here is to send all the requests at once, and
9107 * then wait for a whole bunch of successes or failures.
9109 if (ssh->mainchan && !ssh->ncmode) {
9114 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9116 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9117 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9118 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
9119 ssh2_pkt_addstring(s->pktout, "env");
9120 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9121 ssh2_pkt_addstring(s->pktout, key);
9122 ssh2_pkt_addstring(s->pktout, val);
9123 ssh2_pkt_send(ssh, s->pktout);
9129 logeventf(ssh, "Sent %d environment variables", s->num_env);
9132 s->env_left = s->num_env;
9134 while (s->env_left > 0) {
9135 crWaitUntilV(pktin);
9137 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9138 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9139 bombout(("Unexpected response to environment request:"
9140 " packet type %d", pktin->type));
9150 if (s->env_ok == s->num_env) {
9151 logevent("All environment variables successfully set");
9152 } else if (s->env_ok == 0) {
9153 logevent("All environment variables refused");
9154 c_write_str(ssh, "Server refused to set environment variables\r\n");
9156 logeventf(ssh, "%d environment variables refused",
9157 s->num_env - s->env_ok);
9158 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9164 * Start a shell or a remote command. We may have to attempt
9165 * this twice if the config data has provided a second choice
9168 if (ssh->mainchan && !ssh->ncmode) while (1) {
9172 if (ssh->fallback_cmd) {
9173 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
9174 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
9176 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
9177 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
9180 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9181 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
9183 ssh2_pkt_addstring(s->pktout, "subsystem");
9184 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9185 ssh2_pkt_addstring(s->pktout, cmd);
9187 ssh2_pkt_addstring(s->pktout, "exec");
9188 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9189 ssh2_pkt_addstring(s->pktout, cmd);
9191 ssh2_pkt_addstring(s->pktout, "shell");
9192 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9194 ssh2_pkt_send(ssh, s->pktout);
9196 crWaitUntilV(pktin);
9198 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9199 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9200 bombout(("Unexpected response to shell/command request:"
9201 " packet type %d", pktin->type));
9205 * We failed to start the command. If this is the
9206 * fallback command, we really are finished; if it's
9207 * not, and if the fallback command exists, try falling
9208 * back to it before complaining.
9210 if (!ssh->fallback_cmd &&
9211 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
9212 logevent("Primary command failed; attempting fallback");
9213 ssh->fallback_cmd = TRUE;
9216 bombout(("Server refused to start a shell/command"));
9219 logevent("Started a shell/command");
9224 ssh->state = SSH_STATE_SESSION;
9225 if (ssh->size_needed)
9226 ssh_size(ssh, ssh->term_width, ssh->term_height);
9227 if (ssh->eof_needed)
9228 ssh_special(ssh, TS_EOF);
9231 * All the initial channel requests are done, so install the default
9234 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_success;
9235 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_failure;
9241 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
9246 s->try_send = FALSE;
9250 * _All_ the connection-layer packets we expect to
9251 * receive are now handled by the dispatch table.
9252 * Anything that reaches here must be bogus.
9255 bombout(("Strange packet received: type %d", pktin->type));
9257 } else if (ssh->mainchan) {
9259 * We have spare data. Add it to the channel buffer.
9261 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
9266 struct ssh_channel *c;
9268 * Try to send data on all channels if we can.
9270 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
9271 ssh2_try_send_and_unthrottle(ssh, c);
9279 * Handlers for SSH-2 messages that might arrive at any moment.
9281 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
9283 /* log reason code in disconnect message */
9287 reason = ssh_pkt_getuint32(pktin);
9288 ssh_pkt_getstring(pktin, &msg, &msglen);
9290 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
9291 buf = dupprintf("Received disconnect message (%s)",
9292 ssh2_disconnect_reasons[reason]);
9294 buf = dupprintf("Received disconnect message (unknown"
9295 " type %d)", reason);
9299 buf = dupprintf("Disconnection message text: %.*s",
9302 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
9304 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
9305 ssh2_disconnect_reasons[reason] : "unknown",
9310 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
9312 /* log the debug message */
9316 /* XXX maybe we should actually take notice of the return value */
9317 ssh2_pkt_getbool(pktin);
9318 ssh_pkt_getstring(pktin, &msg, &msglen);
9320 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
9323 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
9325 struct Packet *pktout;
9326 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
9327 ssh2_pkt_adduint32(pktout, pktin->sequence);
9329 * UNIMPLEMENTED messages MUST appear in the same order as the
9330 * messages they respond to. Hence, never queue them.
9332 ssh2_pkt_send_noqueue(ssh, pktout);
9336 * Handle the top-level SSH-2 protocol.
9338 static void ssh2_protocol_setup(Ssh ssh)
9343 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9345 for (i = 0; i < 256; i++)
9346 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
9349 * Any message we actually understand, we set to NULL so that
9350 * the coroutines will get it.
9352 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
9353 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
9354 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
9355 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
9356 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
9357 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
9358 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
9359 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
9360 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
9361 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
9362 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
9363 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
9364 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
9365 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
9366 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
9367 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
9368 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
9369 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
9370 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
9371 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
9372 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
9373 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
9374 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
9375 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
9376 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
9377 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
9378 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
9379 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
9380 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
9381 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
9382 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
9383 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
9384 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
9387 * These special message types we install handlers for.
9389 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
9390 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
9391 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9394 static void ssh2_timer(void *ctx, long now)
9398 if (ssh->state == SSH_STATE_CLOSED)
9401 if (!ssh->kex_in_progress && conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
9402 now - ssh->next_rekey >= 0) {
9403 do_ssh2_transport(ssh, "timeout", -1, NULL);
9407 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
9408 struct Packet *pktin)
9410 unsigned char *in = (unsigned char *)vin;
9411 if (ssh->state == SSH_STATE_CLOSED)
9415 ssh->incoming_data_size += pktin->encrypted_len;
9416 if (!ssh->kex_in_progress &&
9417 ssh->max_data_size != 0 &&
9418 ssh->incoming_data_size > ssh->max_data_size)
9419 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9422 if (pktin && ssh->packet_dispatch[pktin->type]) {
9423 ssh->packet_dispatch[pktin->type](ssh, pktin);
9427 if (!ssh->protocol_initial_phase_done ||
9428 (pktin && pktin->type >= 20 && pktin->type < 50)) {
9429 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
9430 !ssh->protocol_initial_phase_done) {
9431 ssh->protocol_initial_phase_done = TRUE;
9433 * Allow authconn to initialise itself.
9435 do_ssh2_authconn(ssh, NULL, 0, NULL);
9438 do_ssh2_authconn(ssh, in, inlen, pktin);
9442 static void ssh_cache_conf_values(Ssh ssh)
9444 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
9448 * Called to set up the connection.
9450 * Returns an error message, or NULL on success.
9452 static const char *ssh_init(void *frontend_handle, void **backend_handle,
9453 Conf *conf, char *host, int port, char **realhost,
9454 int nodelay, int keepalive)
9459 ssh = snew(struct ssh_tag);
9460 ssh->conf = conf_copy(conf);
9461 ssh_cache_conf_values(ssh);
9462 ssh->version = 0; /* when not ready yet */
9465 ssh->v1_cipher_ctx = NULL;
9466 ssh->crcda_ctx = NULL;
9467 ssh->cscipher = NULL;
9468 ssh->cs_cipher_ctx = NULL;
9469 ssh->sccipher = NULL;
9470 ssh->sc_cipher_ctx = NULL;
9472 ssh->cs_mac_ctx = NULL;
9474 ssh->sc_mac_ctx = NULL;
9476 ssh->cs_comp_ctx = NULL;
9478 ssh->sc_comp_ctx = NULL;
9480 ssh->kex_ctx = NULL;
9481 ssh->hostkey = NULL;
9483 ssh->close_expected = FALSE;
9484 ssh->clean_exit = FALSE;
9485 ssh->state = SSH_STATE_PREPACKET;
9486 ssh->size_needed = FALSE;
9487 ssh->eof_needed = FALSE;
9490 ssh->deferred_send_data = NULL;
9491 ssh->deferred_len = 0;
9492 ssh->deferred_size = 0;
9493 ssh->fallback_cmd = 0;
9494 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9495 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9496 ssh->x11disp = NULL;
9497 ssh->v1_compressing = FALSE;
9498 ssh->v2_outgoing_sequence = 0;
9499 ssh->ssh1_rdpkt_crstate = 0;
9500 ssh->ssh2_rdpkt_crstate = 0;
9501 ssh->do_ssh_init_crstate = 0;
9502 ssh->ssh_gotdata_crstate = 0;
9503 ssh->do_ssh1_connection_crstate = 0;
9504 ssh->do_ssh1_login_crstate = 0;
9505 ssh->do_ssh2_transport_crstate = 0;
9506 ssh->do_ssh2_authconn_crstate = 0;
9507 ssh->do_ssh_init_state = NULL;
9508 ssh->do_ssh1_login_state = NULL;
9509 ssh->do_ssh2_transport_state = NULL;
9510 ssh->do_ssh2_authconn_state = NULL;
9513 ssh->mainchan = NULL;
9514 ssh->throttled_all = 0;
9515 ssh->v1_stdout_throttling = 0;
9517 ssh->queuelen = ssh->queuesize = 0;
9518 ssh->queueing = FALSE;
9519 ssh->qhead = ssh->qtail = NULL;
9520 ssh->deferred_rekey_reason = NULL;
9521 bufchain_init(&ssh->queued_incoming_data);
9522 ssh->frozen = FALSE;
9523 ssh->username = NULL;
9524 ssh->sent_console_eof = FALSE;
9525 ssh->got_pty = FALSE;
9527 *backend_handle = ssh;
9530 if (crypto_startup() == 0)
9531 return "Microsoft high encryption pack not installed!";
9534 ssh->frontend = frontend_handle;
9535 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
9536 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
9538 ssh->channels = NULL;
9539 ssh->rportfwds = NULL;
9540 ssh->portfwds = NULL;
9545 ssh->conn_throttle_count = 0;
9546 ssh->overall_bufsize = 0;
9547 ssh->fallback_cmd = 0;
9549 ssh->protocol = NULL;
9551 ssh->protocol_initial_phase_done = FALSE;
9555 ssh->incoming_data_size = ssh->outgoing_data_size =
9556 ssh->deferred_data_size = 0L;
9557 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9558 CONF_ssh_rekey_data));
9559 ssh->kex_in_progress = FALSE;
9562 ssh->gsslibs = NULL;
9565 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9574 static void ssh_free(void *handle)
9576 Ssh ssh = (Ssh) handle;
9577 struct ssh_channel *c;
9578 struct ssh_rportfwd *pf;
9580 if (ssh->v1_cipher_ctx)
9581 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9582 if (ssh->cs_cipher_ctx)
9583 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9584 if (ssh->sc_cipher_ctx)
9585 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9586 if (ssh->cs_mac_ctx)
9587 ssh->csmac->free_context(ssh->cs_mac_ctx);
9588 if (ssh->sc_mac_ctx)
9589 ssh->scmac->free_context(ssh->sc_mac_ctx);
9590 if (ssh->cs_comp_ctx) {
9592 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9594 zlib_compress_cleanup(ssh->cs_comp_ctx);
9596 if (ssh->sc_comp_ctx) {
9598 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9600 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9603 dh_cleanup(ssh->kex_ctx);
9604 sfree(ssh->savedhost);
9606 while (ssh->queuelen-- > 0)
9607 ssh_free_packet(ssh->queue[ssh->queuelen]);
9610 while (ssh->qhead) {
9611 struct queued_handler *qh = ssh->qhead;
9612 ssh->qhead = qh->next;
9615 ssh->qhead = ssh->qtail = NULL;
9617 if (ssh->channels) {
9618 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9621 if (c->u.x11.s != NULL)
9622 x11_close(c->u.x11.s);
9625 case CHAN_SOCKDATA_DORMANT:
9626 if (c->u.pfd.s != NULL)
9627 pfd_close(c->u.pfd.s);
9632 freetree234(ssh->channels);
9633 ssh->channels = NULL;
9636 if (ssh->rportfwds) {
9637 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9639 freetree234(ssh->rportfwds);
9640 ssh->rportfwds = NULL;
9642 sfree(ssh->deferred_send_data);
9644 x11_free_display(ssh->x11disp);
9645 sfree(ssh->do_ssh_init_state);
9646 sfree(ssh->do_ssh1_login_state);
9647 sfree(ssh->do_ssh2_transport_state);
9648 sfree(ssh->do_ssh2_authconn_state);
9651 sfree(ssh->fullhostname);
9652 if (ssh->crcda_ctx) {
9653 crcda_free_context(ssh->crcda_ctx);
9654 ssh->crcda_ctx = NULL;
9657 ssh_do_close(ssh, TRUE);
9658 expire_timer_context(ssh);
9660 pinger_free(ssh->pinger);
9661 bufchain_clear(&ssh->queued_incoming_data);
9662 sfree(ssh->username);
9663 conf_free(ssh->conf);
9666 ssh_gss_cleanup(ssh->gsslibs);
9674 * Reconfigure the SSH backend.
9676 static void ssh_reconfig(void *handle, Conf *conf)
9678 Ssh ssh = (Ssh) handle;
9679 char *rekeying = NULL, rekey_mandatory = FALSE;
9680 unsigned long old_max_data_size;
9683 pinger_reconfig(ssh->pinger, ssh->conf, conf);
9685 ssh_setup_portfwd(ssh, conf);
9687 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
9688 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
9690 long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
9691 long now = GETTICKCOUNT();
9693 if (new_next - now < 0) {
9694 rekeying = "timeout shortened";
9696 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
9700 old_max_data_size = ssh->max_data_size;
9701 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9702 CONF_ssh_rekey_data));
9703 if (old_max_data_size != ssh->max_data_size &&
9704 ssh->max_data_size != 0) {
9705 if (ssh->outgoing_data_size > ssh->max_data_size ||
9706 ssh->incoming_data_size > ssh->max_data_size)
9707 rekeying = "data limit lowered";
9710 if (conf_get_int(ssh->conf, CONF_compression) !=
9711 conf_get_int(conf, CONF_compression)) {
9712 rekeying = "compression setting changed";
9713 rekey_mandatory = TRUE;
9716 for (i = 0; i < CIPHER_MAX; i++)
9717 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
9718 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
9719 rekeying = "cipher settings changed";
9720 rekey_mandatory = TRUE;
9722 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
9723 conf_get_int(conf, CONF_ssh2_des_cbc)) {
9724 rekeying = "cipher settings changed";
9725 rekey_mandatory = TRUE;
9728 conf_free(ssh->conf);
9729 ssh->conf = conf_copy(conf);
9730 ssh_cache_conf_values(ssh);
9733 if (!ssh->kex_in_progress) {
9734 do_ssh2_transport(ssh, rekeying, -1, NULL);
9735 } else if (rekey_mandatory) {
9736 ssh->deferred_rekey_reason = rekeying;
9742 * Called to send data down the SSH connection.
9744 static int ssh_send(void *handle, char *buf, int len)
9746 Ssh ssh = (Ssh) handle;
9748 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9751 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
9753 return ssh_sendbuffer(ssh);
9757 * Called to query the current amount of buffered stdin data.
9759 static int ssh_sendbuffer(void *handle)
9761 Ssh ssh = (Ssh) handle;
9764 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9768 * If the SSH socket itself has backed up, add the total backup
9769 * size on that to any individual buffer on the stdin channel.
9772 if (ssh->throttled_all)
9773 override_value = ssh->overall_bufsize;
9775 if (ssh->version == 1) {
9776 return override_value;
9777 } else if (ssh->version == 2) {
9779 return override_value;
9781 return (override_value +
9782 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
9789 * Called to set the size of the window from SSH's POV.
9791 static void ssh_size(void *handle, int width, int height)
9793 Ssh ssh = (Ssh) handle;
9794 struct Packet *pktout;
9796 ssh->term_width = width;
9797 ssh->term_height = height;
9799 switch (ssh->state) {
9800 case SSH_STATE_BEFORE_SIZE:
9801 case SSH_STATE_PREPACKET:
9802 case SSH_STATE_CLOSED:
9803 break; /* do nothing */
9804 case SSH_STATE_INTERMED:
9805 ssh->size_needed = TRUE; /* buffer for later */
9807 case SSH_STATE_SESSION:
9808 if (!conf_get_int(ssh->conf, CONF_nopty)) {
9809 if (ssh->version == 1) {
9810 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
9811 PKT_INT, ssh->term_height,
9812 PKT_INT, ssh->term_width,
9813 PKT_INT, 0, PKT_INT, 0, PKT_END);
9814 } else if (ssh->mainchan) {
9815 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9816 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9817 ssh2_pkt_addstring(pktout, "window-change");
9818 ssh2_pkt_addbool(pktout, 0);
9819 ssh2_pkt_adduint32(pktout, ssh->term_width);
9820 ssh2_pkt_adduint32(pktout, ssh->term_height);
9821 ssh2_pkt_adduint32(pktout, 0);
9822 ssh2_pkt_adduint32(pktout, 0);
9823 ssh2_pkt_send(ssh, pktout);
9831 * Return a list of the special codes that make sense in this
9834 static const struct telnet_special *ssh_get_specials(void *handle)
9836 static const struct telnet_special ssh1_ignore_special[] = {
9837 {"IGNORE message", TS_NOP}
9839 static const struct telnet_special ssh2_ignore_special[] = {
9840 {"IGNORE message", TS_NOP},
9842 static const struct telnet_special ssh2_rekey_special[] = {
9843 {"Repeat key exchange", TS_REKEY},
9845 static const struct telnet_special ssh2_session_specials[] = {
9848 /* These are the signal names defined by RFC 4254.
9849 * They include all the ISO C signals, but are a subset of the POSIX
9850 * required signals. */
9851 {"SIGINT (Interrupt)", TS_SIGINT},
9852 {"SIGTERM (Terminate)", TS_SIGTERM},
9853 {"SIGKILL (Kill)", TS_SIGKILL},
9854 {"SIGQUIT (Quit)", TS_SIGQUIT},
9855 {"SIGHUP (Hangup)", TS_SIGHUP},
9856 {"More signals", TS_SUBMENU},
9857 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
9858 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
9859 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
9860 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
9863 static const struct telnet_special specials_end[] = {
9866 /* XXX review this length for any changes: */
9867 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
9868 lenof(ssh2_rekey_special) +
9869 lenof(ssh2_session_specials) +
9870 lenof(specials_end)];
9871 Ssh ssh = (Ssh) handle;
9873 #define ADD_SPECIALS(name) \
9875 assert((i + lenof(name)) <= lenof(ssh_specials)); \
9876 memcpy(&ssh_specials[i], name, sizeof name); \
9880 if (ssh->version == 1) {
9881 /* Don't bother offering IGNORE if we've decided the remote
9882 * won't cope with it, since we wouldn't bother sending it if
9884 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9885 ADD_SPECIALS(ssh1_ignore_special);
9886 } else if (ssh->version == 2) {
9887 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
9888 ADD_SPECIALS(ssh2_ignore_special);
9889 if (!(ssh->remote_bugs & BUG_SSH2_REKEY))
9890 ADD_SPECIALS(ssh2_rekey_special);
9892 ADD_SPECIALS(ssh2_session_specials);
9893 } /* else we're not ready yet */
9896 ADD_SPECIALS(specials_end);
9897 return ssh_specials;
9905 * Send special codes. TS_EOF is useful for `plink', so you
9906 * can send an EOF and collect resulting output (e.g. `plink
9909 static void ssh_special(void *handle, Telnet_Special code)
9911 Ssh ssh = (Ssh) handle;
9912 struct Packet *pktout;
9914 if (code == TS_EOF) {
9915 if (ssh->state != SSH_STATE_SESSION) {
9917 * Buffer the EOF in case we are pre-SESSION, so we can
9918 * send it as soon as we reach SESSION.
9921 ssh->eof_needed = TRUE;
9924 if (ssh->version == 1) {
9925 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
9926 } else if (ssh->mainchan) {
9927 sshfwd_write_eof(ssh->mainchan);
9928 ssh->send_ok = 0; /* now stop trying to read from stdin */
9930 logevent("Sent EOF message");
9931 } else if (code == TS_PING || code == TS_NOP) {
9932 if (ssh->state == SSH_STATE_CLOSED
9933 || ssh->state == SSH_STATE_PREPACKET) return;
9934 if (ssh->version == 1) {
9935 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9936 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
9938 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
9939 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
9940 ssh2_pkt_addstring_start(pktout);
9941 ssh2_pkt_send_noqueue(ssh, pktout);
9944 } else if (code == TS_REKEY) {
9945 if (!ssh->kex_in_progress && ssh->version == 2) {
9946 do_ssh2_transport(ssh, "at user request", -1, NULL);
9948 } else if (code == TS_BRK) {
9949 if (ssh->state == SSH_STATE_CLOSED
9950 || ssh->state == SSH_STATE_PREPACKET) return;
9951 if (ssh->version == 1) {
9952 logevent("Unable to send BREAK signal in SSH-1");
9953 } else if (ssh->mainchan) {
9954 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9955 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9956 ssh2_pkt_addstring(pktout, "break");
9957 ssh2_pkt_addbool(pktout, 0);
9958 ssh2_pkt_adduint32(pktout, 0); /* default break length */
9959 ssh2_pkt_send(ssh, pktout);
9962 /* Is is a POSIX signal? */
9963 char *signame = NULL;
9964 if (code == TS_SIGABRT) signame = "ABRT";
9965 if (code == TS_SIGALRM) signame = "ALRM";
9966 if (code == TS_SIGFPE) signame = "FPE";
9967 if (code == TS_SIGHUP) signame = "HUP";
9968 if (code == TS_SIGILL) signame = "ILL";
9969 if (code == TS_SIGINT) signame = "INT";
9970 if (code == TS_SIGKILL) signame = "KILL";
9971 if (code == TS_SIGPIPE) signame = "PIPE";
9972 if (code == TS_SIGQUIT) signame = "QUIT";
9973 if (code == TS_SIGSEGV) signame = "SEGV";
9974 if (code == TS_SIGTERM) signame = "TERM";
9975 if (code == TS_SIGUSR1) signame = "USR1";
9976 if (code == TS_SIGUSR2) signame = "USR2";
9977 /* The SSH-2 protocol does in principle support arbitrary named
9978 * signals, including signame@domain, but we don't support those. */
9980 /* It's a signal. */
9981 if (ssh->version == 2 && ssh->mainchan) {
9982 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9983 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9984 ssh2_pkt_addstring(pktout, "signal");
9985 ssh2_pkt_addbool(pktout, 0);
9986 ssh2_pkt_addstring(pktout, signame);
9987 ssh2_pkt_send(ssh, pktout);
9988 logeventf(ssh, "Sent signal SIG%s", signame);
9991 /* Never heard of it. Do nothing */
9996 void *new_sock_channel(void *handle, Socket s)
9998 Ssh ssh = (Ssh) handle;
9999 struct ssh_channel *c;
10000 c = snew(struct ssh_channel);
10003 ssh2_channel_init(c);
10004 c->halfopen = TRUE;
10005 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
10007 add234(ssh->channels, c);
10012 * This is called when stdout/stderr (the entity to which
10013 * from_backend sends data) manages to clear some backlog.
10015 static void ssh_unthrottle(void *handle, int bufsize)
10017 Ssh ssh = (Ssh) handle;
10020 if (ssh->version == 1) {
10021 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
10022 ssh->v1_stdout_throttling = 0;
10023 ssh_throttle_conn(ssh, -1);
10026 if (ssh->mainchan) {
10027 ssh2_set_window(ssh->mainchan,
10028 bufsize < ssh->mainchan->v.v2.locmaxwin ?
10029 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
10030 if (conf_get_int(ssh->conf, CONF_ssh_simple))
10033 buflimit = ssh->mainchan->v.v2.locmaxwin;
10034 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
10035 ssh->mainchan->throttling_conn = 0;
10036 ssh_throttle_conn(ssh, -1);
10042 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
10044 struct ssh_channel *c = (struct ssh_channel *)channel;
10046 struct Packet *pktout;
10048 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
10050 if (ssh->version == 1) {
10051 send_packet(ssh, SSH1_MSG_PORT_OPEN,
10052 PKT_INT, c->localid,
10055 /* PKT_STR, <org:orgport>, */
10058 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
10059 ssh2_pkt_addstring(pktout, "direct-tcpip");
10060 ssh2_pkt_adduint32(pktout, c->localid);
10061 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
10062 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
10063 ssh2_pkt_addstring(pktout, hostname);
10064 ssh2_pkt_adduint32(pktout, port);
10066 * We make up values for the originator data; partly it's
10067 * too much hassle to keep track, and partly I'm not
10068 * convinced the server should be told details like that
10069 * about my local network configuration.
10070 * The "originator IP address" is syntactically a numeric
10071 * IP address, and some servers (e.g., Tectia) get upset
10072 * if it doesn't match this syntax.
10074 ssh2_pkt_addstring(pktout, "0.0.0.0");
10075 ssh2_pkt_adduint32(pktout, 0);
10076 ssh2_pkt_send(ssh, pktout);
10080 static int ssh_connected(void *handle)
10082 Ssh ssh = (Ssh) handle;
10083 return ssh->s != NULL;
10086 static int ssh_sendok(void *handle)
10088 Ssh ssh = (Ssh) handle;
10089 return ssh->send_ok;
10092 static int ssh_ldisc(void *handle, int option)
10094 Ssh ssh = (Ssh) handle;
10095 if (option == LD_ECHO)
10096 return ssh->echoing;
10097 if (option == LD_EDIT)
10098 return ssh->editing;
10102 static void ssh_provide_ldisc(void *handle, void *ldisc)
10104 Ssh ssh = (Ssh) handle;
10105 ssh->ldisc = ldisc;
10108 static void ssh_provide_logctx(void *handle, void *logctx)
10110 Ssh ssh = (Ssh) handle;
10111 ssh->logctx = logctx;
10114 static int ssh_return_exitcode(void *handle)
10116 Ssh ssh = (Ssh) handle;
10117 if (ssh->s != NULL)
10120 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
10124 * cfg_info for SSH is the currently running version of the
10125 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
10127 static int ssh_cfg_info(void *handle)
10129 Ssh ssh = (Ssh) handle;
10130 return ssh->version;
10134 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
10135 * that fails. This variable is the means by which scp.c can reach
10136 * into the SSH code and find out which one it got.
10138 extern int ssh_fallback_cmd(void *handle)
10140 Ssh ssh = (Ssh) handle;
10141 return ssh->fallback_cmd;
10144 Backend ssh_backend = {
10154 ssh_return_exitcode,
10158 ssh_provide_logctx,