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 */
565 * little structure to keep track of outstanding WINDOW_ADJUSTs
573 * 2-3-4 tree storing channels.
576 Ssh ssh; /* pointer back to main context */
577 unsigned remoteid, localid;
579 /* True if we opened this channel but server hasn't confirmed. */
582 * In SSH-1, this value contains four bits:
584 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
585 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
586 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
587 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
589 * A channel is completely finished with when all four bits are set.
591 * In SSH-2, the four bits mean:
593 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
594 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
595 * 4 We have received SSH2_MSG_CHANNEL_EOF.
596 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
598 * A channel is completely finished with when we have both sent
599 * and received CLOSE.
601 * The symbolic constants below use the SSH-2 terminology, which
602 * is a bit confusing in SSH-1, but we have to use _something_.
604 #define CLOSES_SENT_EOF 1
605 #define CLOSES_SENT_CLOSE 2
606 #define CLOSES_RCVD_EOF 4
607 #define CLOSES_RCVD_CLOSE 8
611 * This flag indicates that an EOF is pending on the outgoing side
612 * of the channel: that is, wherever we're getting the data for
613 * this channel has sent us some data followed by EOF. We can't
614 * actually send the EOF until we've finished sending the data, so
615 * we set this flag instead to remind us to do so once our buffer
621 * True if this channel is causing the underlying connection to be
626 struct ssh2_data_channel {
628 unsigned remwindow, remmaxpkt;
629 /* locwindow is signed so we can cope with excess data. */
630 int locwindow, locmaxwin;
632 * remlocwin is the amount of local window that we think
633 * the remote end had available to it after it sent the
634 * last data packet or window adjust ack.
638 * These store the list of window adjusts that haven't
641 struct winadj *winadj_head, *winadj_tail;
642 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
646 struct ssh_agent_channel {
647 unsigned char *message;
648 unsigned char msglen[4];
649 unsigned lensofar, totallen;
651 struct ssh_x11_channel {
654 struct ssh_pfd_channel {
661 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
662 * use this structure in different ways, reflecting SSH-2's
663 * altogether saner approach to port forwarding.
665 * In SSH-1, you arrange a remote forwarding by sending the server
666 * the remote port number, and the local destination host:port.
667 * When a connection comes in, the server sends you back that
668 * host:port pair, and you connect to it. This is a ready-made
669 * security hole if you're not on the ball: a malicious server
670 * could send you back _any_ host:port pair, so if you trustingly
671 * connect to the address it gives you then you've just opened the
672 * entire inside of your corporate network just by connecting
673 * through it to a dodgy SSH server. Hence, we must store a list of
674 * host:port pairs we _are_ trying to forward to, and reject a
675 * connection request from the server if it's not in the list.
677 * In SSH-2, each side of the connection minds its own business and
678 * doesn't send unnecessary information to the other. You arrange a
679 * remote forwarding by sending the server just the remote port
680 * number. When a connection comes in, the server tells you which
681 * of its ports was connected to; and _you_ have to remember what
682 * local host:port pair went with that port number.
684 * Hence, in SSH-1 this structure is indexed by destination
685 * host:port pair, whereas in SSH-2 it is indexed by source port.
687 struct ssh_portfwd; /* forward declaration */
689 struct ssh_rportfwd {
690 unsigned sport, dport;
693 struct ssh_portfwd *pfrec;
695 #define free_rportfwd(pf) ( \
696 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
699 * Separately to the rportfwd tree (which is for looking up port
700 * open requests from the server), a tree of _these_ structures is
701 * used to keep track of all the currently open port forwardings,
702 * so that we can reconfigure in mid-session if the user requests
706 enum { DESTROY, KEEP, CREATE } status;
708 unsigned sport, dport;
711 struct ssh_rportfwd *remote;
715 #define free_portfwd(pf) ( \
716 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
717 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
720 long length; /* length of `data' actually used */
721 long forcepad; /* SSH-2: force padding to at least this length */
722 int type; /* only used for incoming packets */
723 unsigned long sequence; /* SSH-2 incoming sequence number */
724 unsigned char *data; /* allocated storage */
725 unsigned char *body; /* offset of payload within `data' */
726 long savedpos; /* temporary index into `data' (for strings) */
727 long maxlen; /* amount of storage allocated for `data' */
728 long encrypted_len; /* for SSH-2 total-size counting */
731 * State associated with packet logging
735 struct logblank_t *blanks;
738 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
739 struct Packet *pktin);
740 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
741 struct Packet *pktin);
742 static void ssh1_protocol_setup(Ssh ssh);
743 static void ssh2_protocol_setup(Ssh ssh);
744 static void ssh_size(void *handle, int width, int height);
745 static void ssh_special(void *handle, Telnet_Special);
746 static int ssh2_try_send(struct ssh_channel *c);
747 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
748 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
749 static void ssh2_set_window(struct ssh_channel *c, int newwin);
750 static int ssh_sendbuffer(void *handle);
751 static int ssh_do_close(Ssh ssh, int notify_exit);
752 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
753 static int ssh2_pkt_getbool(struct Packet *pkt);
754 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
755 static void ssh2_timer(void *ctx, long now);
756 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
757 struct Packet *pktin);
759 struct rdpkt1_state_tag {
760 long len, pad, biglen, to_read;
761 unsigned long realcrc, gotcrc;
765 struct Packet *pktin;
768 struct rdpkt2_state_tag {
769 long len, pad, payload, packetlen, maclen;
772 unsigned long incoming_sequence;
773 struct Packet *pktin;
776 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
777 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
779 struct queued_handler;
780 struct queued_handler {
782 chandler_fn_t handler;
784 struct queued_handler *next;
788 const struct plug_function_table *fn;
789 /* the above field _must_ be first in the structure */
799 unsigned char session_key[32];
801 int v1_remote_protoflags;
802 int v1_local_protoflags;
803 int agentfwd_enabled;
806 const struct ssh_cipher *cipher;
809 const struct ssh2_cipher *cscipher, *sccipher;
810 void *cs_cipher_ctx, *sc_cipher_ctx;
811 const struct ssh_mac *csmac, *scmac;
812 void *cs_mac_ctx, *sc_mac_ctx;
813 const struct ssh_compress *cscomp, *sccomp;
814 void *cs_comp_ctx, *sc_comp_ctx;
815 const struct ssh_kex *kex;
816 const struct ssh_signkey *hostkey;
817 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
818 int v2_session_id_len;
824 int echoing, editing;
828 int ospeed, ispeed; /* temporaries */
829 int term_width, term_height;
831 tree234 *channels; /* indexed by local id */
832 struct ssh_channel *mainchan; /* primary session channel */
833 int ncmode; /* is primary channel direct-tcpip? */
838 tree234 *rportfwds, *portfwds;
842 SSH_STATE_BEFORE_SIZE,
848 int size_needed, eof_needed;
849 int sent_console_eof;
850 int got_pty; /* affects EOF behaviour on main channel */
852 struct Packet **queue;
853 int queuelen, queuesize;
855 unsigned char *deferred_send_data;
856 int deferred_len, deferred_size;
859 * Gross hack: pscp will try to start SFTP but fall back to
860 * scp1 if that fails. This variable is the means by which
861 * scp.c can reach into the SSH code and find out which one it
866 bufchain banner; /* accumulates banners during do_ssh2_authconn */
871 struct X11Display *x11disp;
874 int conn_throttle_count;
877 int v1_stdout_throttling;
878 unsigned long v2_outgoing_sequence;
880 int ssh1_rdpkt_crstate;
881 int ssh2_rdpkt_crstate;
882 int do_ssh_init_crstate;
883 int ssh_gotdata_crstate;
884 int do_ssh1_login_crstate;
885 int do_ssh1_connection_crstate;
886 int do_ssh2_transport_crstate;
887 int do_ssh2_authconn_crstate;
889 void *do_ssh_init_state;
890 void *do_ssh1_login_state;
891 void *do_ssh2_transport_state;
892 void *do_ssh2_authconn_state;
894 struct rdpkt1_state_tag rdpkt1_state;
895 struct rdpkt2_state_tag rdpkt2_state;
897 /* SSH-1 and SSH-2 use this for different things, but both use it */
898 int protocol_initial_phase_done;
900 void (*protocol) (Ssh ssh, void *vin, int inlen,
902 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
905 * We maintain our own copy of a Conf structure here. That way,
906 * when we're passed a new one for reconfiguration, we can check
907 * the differences and potentially reconfigure port forwardings
908 * etc in mid-session.
913 * Values cached out of conf so as to avoid the tree234 lookup
914 * cost every time they're used.
919 * Dynamically allocated username string created during SSH
920 * login. Stored in here rather than in the coroutine state so
921 * that it'll be reliably freed if we shut down the SSH session
922 * at some unexpected moment.
927 * Used to transfer data back from async callbacks.
929 void *agent_response;
930 int agent_response_len;
934 * The SSH connection can be set as `frozen', meaning we are
935 * not currently accepting incoming data from the network. This
936 * is slightly more serious than setting the _socket_ as
937 * frozen, because we may already have had data passed to us
938 * from the network which we need to delay processing until
939 * after the freeze is lifted, so we also need a bufchain to
943 bufchain queued_incoming_data;
946 * Dispatch table for packet types that we may have to deal
949 handler_fn_t packet_dispatch[256];
952 * Queues of one-off handler functions for success/failure
953 * indications from a request.
955 struct queued_handler *qhead, *qtail;
958 * This module deals with sending keepalives.
963 * Track incoming and outgoing data sizes and time, for
966 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
967 unsigned long max_data_size;
969 long next_rekey, last_rekey;
970 char *deferred_rekey_reason; /* points to STATIC string; don't free */
973 * Fully qualified host name, which we need if doing GSSAPI.
979 * GSSAPI libraries for this session.
981 struct ssh_gss_liblist *gsslibs;
985 #define logevent(s) logevent(ssh->frontend, s)
987 /* logevent, only printf-formatted. */
988 static void logeventf(Ssh ssh, const char *fmt, ...)
994 buf = dupvprintf(fmt, ap);
1000 #define bombout(msg) \
1002 char *text = dupprintf msg; \
1003 ssh_do_close(ssh, FALSE); \
1005 connection_fatal(ssh->frontend, "%s", text); \
1009 /* Functions to leave bits out of the SSH packet log file. */
1011 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
1013 if (conf_get_int(ssh->conf, CONF_logomitpass))
1014 pkt->logmode = blanktype;
1017 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
1019 if (ssh->logomitdata)
1020 pkt->logmode = blanktype;
1023 static void end_log_omission(Ssh ssh, struct Packet *pkt)
1025 pkt->logmode = PKTLOG_EMIT;
1028 /* Helper function for common bits of parsing ttymodes. */
1029 static void parse_ttymodes(Ssh ssh,
1030 void (*do_mode)(void *data, char *mode, char *val),
1035 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
1037 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
1039 * val[0] is either 'V', indicating that an explicit value
1040 * follows it, or 'A' indicating that we should pass the
1041 * value through from the local environment via get_ttymode.
1044 val = get_ttymode(ssh->frontend, key);
1046 val++; /* skip the 'V' */
1048 do_mode(data, key, val);
1052 static int ssh_channelcmp(void *av, void *bv)
1054 struct ssh_channel *a = (struct ssh_channel *) av;
1055 struct ssh_channel *b = (struct ssh_channel *) bv;
1056 if (a->localid < b->localid)
1058 if (a->localid > b->localid)
1062 static int ssh_channelfind(void *av, void *bv)
1064 unsigned *a = (unsigned *) av;
1065 struct ssh_channel *b = (struct ssh_channel *) bv;
1066 if (*a < b->localid)
1068 if (*a > b->localid)
1073 static int ssh_rportcmp_ssh1(void *av, void *bv)
1075 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1076 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1078 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1079 return i < 0 ? -1 : +1;
1080 if (a->dport > b->dport)
1082 if (a->dport < b->dport)
1087 static int ssh_rportcmp_ssh2(void *av, void *bv)
1089 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1090 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1092 if (a->sport > b->sport)
1094 if (a->sport < b->sport)
1100 * Special form of strcmp which can cope with NULL inputs. NULL is
1101 * defined to sort before even the empty string.
1103 static int nullstrcmp(const char *a, const char *b)
1105 if (a == NULL && b == NULL)
1111 return strcmp(a, b);
1114 static int ssh_portcmp(void *av, void *bv)
1116 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1117 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1119 if (a->type > b->type)
1121 if (a->type < b->type)
1123 if (a->addressfamily > b->addressfamily)
1125 if (a->addressfamily < b->addressfamily)
1127 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1128 return i < 0 ? -1 : +1;
1129 if (a->sport > b->sport)
1131 if (a->sport < b->sport)
1133 if (a->type != 'D') {
1134 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1135 return i < 0 ? -1 : +1;
1136 if (a->dport > b->dport)
1138 if (a->dport < b->dport)
1144 static int alloc_channel_id(Ssh ssh)
1146 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1147 unsigned low, high, mid;
1149 struct ssh_channel *c;
1152 * First-fit allocation of channel numbers: always pick the
1153 * lowest unused one. To do this, binary-search using the
1154 * counted B-tree to find the largest channel ID which is in a
1155 * contiguous sequence from the beginning. (Precisely
1156 * everything in that sequence must have ID equal to its tree
1157 * index plus CHANNEL_NUMBER_OFFSET.)
1159 tsize = count234(ssh->channels);
1163 while (high - low > 1) {
1164 mid = (high + low) / 2;
1165 c = index234(ssh->channels, mid);
1166 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1167 low = mid; /* this one is fine */
1169 high = mid; /* this one is past it */
1172 * Now low points to either -1, or the tree index of the
1173 * largest ID in the initial sequence.
1176 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1177 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1179 return low + 1 + CHANNEL_NUMBER_OFFSET;
1182 static void c_write_stderr(int trusted, const char *buf, int len)
1185 for (i = 0; i < len; i++)
1186 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1187 fputc(buf[i], stderr);
1190 static void c_write(Ssh ssh, const char *buf, int len)
1192 if (flags & FLAG_STDERR)
1193 c_write_stderr(1, buf, len);
1195 from_backend(ssh->frontend, 1, buf, len);
1198 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1200 if (flags & FLAG_STDERR)
1201 c_write_stderr(0, buf, len);
1203 from_backend_untrusted(ssh->frontend, buf, len);
1206 static void c_write_str(Ssh ssh, const char *buf)
1208 c_write(ssh, buf, strlen(buf));
1211 static void ssh_free_packet(struct Packet *pkt)
1216 static struct Packet *ssh_new_packet(void)
1218 struct Packet *pkt = snew(struct Packet);
1220 pkt->body = pkt->data = NULL;
1222 pkt->logmode = PKTLOG_EMIT;
1230 * Collect incoming data in the incoming packet buffer.
1231 * Decipher and verify the packet when it is completely read.
1232 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1233 * Update the *data and *datalen variables.
1234 * Return a Packet structure when a packet is completed.
1236 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1238 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1240 crBegin(ssh->ssh1_rdpkt_crstate);
1242 st->pktin = ssh_new_packet();
1244 st->pktin->type = 0;
1245 st->pktin->length = 0;
1247 for (st->i = st->len = 0; st->i < 4; st->i++) {
1248 while ((*datalen) == 0)
1250 st->len = (st->len << 8) + **data;
1251 (*data)++, (*datalen)--;
1254 st->pad = 8 - (st->len % 8);
1255 st->biglen = st->len + st->pad;
1256 st->pktin->length = st->len - 5;
1258 if (st->biglen < 0) {
1259 bombout(("Extremely large packet length from server suggests"
1260 " data stream corruption"));
1261 ssh_free_packet(st->pktin);
1265 st->pktin->maxlen = st->biglen;
1266 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1268 st->to_read = st->biglen;
1269 st->p = st->pktin->data;
1270 while (st->to_read > 0) {
1271 st->chunk = st->to_read;
1272 while ((*datalen) == 0)
1274 if (st->chunk > (*datalen))
1275 st->chunk = (*datalen);
1276 memcpy(st->p, *data, st->chunk);
1278 *datalen -= st->chunk;
1280 st->to_read -= st->chunk;
1283 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1284 st->biglen, NULL)) {
1285 bombout(("Network attack (CRC compensation) detected!"));
1286 ssh_free_packet(st->pktin);
1291 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1293 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1294 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1295 if (st->gotcrc != st->realcrc) {
1296 bombout(("Incorrect CRC received on packet"));
1297 ssh_free_packet(st->pktin);
1301 st->pktin->body = st->pktin->data + st->pad + 1;
1302 st->pktin->savedpos = 0;
1304 if (ssh->v1_compressing) {
1305 unsigned char *decompblk;
1307 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1308 st->pktin->body - 1, st->pktin->length + 1,
1309 &decompblk, &decomplen)) {
1310 bombout(("Zlib decompression encountered invalid data"));
1311 ssh_free_packet(st->pktin);
1315 if (st->pktin->maxlen < st->pad + decomplen) {
1316 st->pktin->maxlen = st->pad + decomplen;
1317 st->pktin->data = sresize(st->pktin->data,
1318 st->pktin->maxlen + APIEXTRA,
1320 st->pktin->body = st->pktin->data + st->pad + 1;
1323 memcpy(st->pktin->body - 1, decompblk, decomplen);
1325 st->pktin->length = decomplen - 1;
1328 st->pktin->type = st->pktin->body[-1];
1331 * Log incoming packet, possibly omitting sensitive fields.
1335 struct logblank_t blank;
1336 if (ssh->logomitdata) {
1337 int do_blank = FALSE, blank_prefix = 0;
1338 /* "Session data" packets - omit the data field */
1339 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1340 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1341 do_blank = TRUE; blank_prefix = 4;
1342 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1343 do_blank = TRUE; blank_prefix = 8;
1346 blank.offset = blank_prefix;
1347 blank.len = st->pktin->length;
1348 blank.type = PKTLOG_OMIT;
1352 log_packet(ssh->logctx,
1353 PKT_INCOMING, st->pktin->type,
1354 ssh1_pkt_type(st->pktin->type),
1355 st->pktin->body, st->pktin->length,
1356 nblanks, &blank, NULL);
1359 crFinish(st->pktin);
1362 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1364 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1366 crBegin(ssh->ssh2_rdpkt_crstate);
1368 st->pktin = ssh_new_packet();
1370 st->pktin->type = 0;
1371 st->pktin->length = 0;
1373 st->cipherblk = ssh->sccipher->blksize;
1376 if (st->cipherblk < 8)
1378 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1380 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1383 * When dealing with a CBC-mode cipher, we want to avoid the
1384 * possibility of an attacker's tweaking the ciphertext stream
1385 * so as to cause us to feed the same block to the block
1386 * cipher more than once and thus leak information
1387 * (VU#958563). The way we do this is not to take any
1388 * decisions on the basis of anything we've decrypted until
1389 * we've verified it with a MAC. That includes the packet
1390 * length, so we just read data and check the MAC repeatedly,
1391 * and when the MAC passes, see if the length we've got is
1395 /* May as well allocate the whole lot now. */
1396 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1399 /* Read an amount corresponding to the MAC. */
1400 for (st->i = 0; st->i < st->maclen; st->i++) {
1401 while ((*datalen) == 0)
1403 st->pktin->data[st->i] = *(*data)++;
1409 unsigned char seq[4];
1410 ssh->scmac->start(ssh->sc_mac_ctx);
1411 PUT_32BIT(seq, st->incoming_sequence);
1412 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1415 for (;;) { /* Once around this loop per cipher block. */
1416 /* Read another cipher-block's worth, and tack it onto the end. */
1417 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1418 while ((*datalen) == 0)
1420 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1423 /* Decrypt one more block (a little further back in the stream). */
1424 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1425 st->pktin->data + st->packetlen,
1427 /* Feed that block to the MAC. */
1428 ssh->scmac->bytes(ssh->sc_mac_ctx,
1429 st->pktin->data + st->packetlen, st->cipherblk);
1430 st->packetlen += st->cipherblk;
1431 /* See if that gives us a valid packet. */
1432 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1433 st->pktin->data + st->packetlen) &&
1434 (st->len = GET_32BIT(st->pktin->data)) + 4 == st->packetlen)
1436 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1437 bombout(("No valid incoming packet found"));
1438 ssh_free_packet(st->pktin);
1442 st->pktin->maxlen = st->packetlen + st->maclen;
1443 st->pktin->data = sresize(st->pktin->data,
1444 st->pktin->maxlen + APIEXTRA,
1447 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1450 * Acquire and decrypt the first block of the packet. This will
1451 * contain the length and padding details.
1453 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1454 while ((*datalen) == 0)
1456 st->pktin->data[st->i] = *(*data)++;
1461 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1462 st->pktin->data, st->cipherblk);
1465 * Now get the length figure.
1467 st->len = GET_32BIT(st->pktin->data);
1470 * _Completely_ silly lengths should be stomped on before they
1471 * do us any more damage.
1473 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1474 (st->len + 4) % st->cipherblk != 0) {
1475 bombout(("Incoming packet was garbled on decryption"));
1476 ssh_free_packet(st->pktin);
1481 * So now we can work out the total packet length.
1483 st->packetlen = st->len + 4;
1486 * Allocate memory for the rest of the packet.
1488 st->pktin->maxlen = st->packetlen + st->maclen;
1489 st->pktin->data = sresize(st->pktin->data,
1490 st->pktin->maxlen + APIEXTRA,
1494 * Read and decrypt the remainder of the packet.
1496 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1498 while ((*datalen) == 0)
1500 st->pktin->data[st->i] = *(*data)++;
1503 /* Decrypt everything _except_ the MAC. */
1505 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1506 st->pktin->data + st->cipherblk,
1507 st->packetlen - st->cipherblk);
1513 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1514 st->len + 4, st->incoming_sequence)) {
1515 bombout(("Incorrect MAC received on packet"));
1516 ssh_free_packet(st->pktin);
1520 /* Get and sanity-check the amount of random padding. */
1521 st->pad = st->pktin->data[4];
1522 if (st->pad < 4 || st->len - st->pad < 1) {
1523 bombout(("Invalid padding length on received packet"));
1524 ssh_free_packet(st->pktin);
1528 * This enables us to deduce the payload length.
1530 st->payload = st->len - st->pad - 1;
1532 st->pktin->length = st->payload + 5;
1533 st->pktin->encrypted_len = st->packetlen;
1535 st->pktin->sequence = st->incoming_sequence++;
1538 * Decompress packet payload.
1541 unsigned char *newpayload;
1544 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1545 st->pktin->data + 5, st->pktin->length - 5,
1546 &newpayload, &newlen)) {
1547 if (st->pktin->maxlen < newlen + 5) {
1548 st->pktin->maxlen = newlen + 5;
1549 st->pktin->data = sresize(st->pktin->data,
1550 st->pktin->maxlen + APIEXTRA,
1553 st->pktin->length = 5 + newlen;
1554 memcpy(st->pktin->data + 5, newpayload, newlen);
1559 st->pktin->savedpos = 6;
1560 st->pktin->body = st->pktin->data;
1561 st->pktin->type = st->pktin->data[5];
1564 * Log incoming packet, possibly omitting sensitive fields.
1568 struct logblank_t blank;
1569 if (ssh->logomitdata) {
1570 int do_blank = FALSE, blank_prefix = 0;
1571 /* "Session data" packets - omit the data field */
1572 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1573 do_blank = TRUE; blank_prefix = 8;
1574 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1575 do_blank = TRUE; blank_prefix = 12;
1578 blank.offset = blank_prefix;
1579 blank.len = (st->pktin->length-6) - blank_prefix;
1580 blank.type = PKTLOG_OMIT;
1584 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1585 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1587 st->pktin->data+6, st->pktin->length-6,
1588 nblanks, &blank, &st->pktin->sequence);
1591 crFinish(st->pktin);
1594 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1596 int pad, biglen, i, pktoffs;
1600 * XXX various versions of SC (including 8.8.4) screw up the
1601 * register allocation in this function and use the same register
1602 * (D6) for len and as a temporary, with predictable results. The
1603 * following sledgehammer prevents this.
1610 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1611 ssh1_pkt_type(pkt->data[12]),
1612 pkt->body, pkt->length - (pkt->body - pkt->data),
1613 pkt->nblanks, pkt->blanks, NULL);
1614 sfree(pkt->blanks); pkt->blanks = NULL;
1617 if (ssh->v1_compressing) {
1618 unsigned char *compblk;
1620 zlib_compress_block(ssh->cs_comp_ctx,
1621 pkt->data + 12, pkt->length - 12,
1622 &compblk, &complen);
1623 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1624 memcpy(pkt->data + 12, compblk, complen);
1626 pkt->length = complen + 12;
1629 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1631 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1632 pad = 8 - (len % 8);
1634 biglen = len + pad; /* len(padding+type+data+CRC) */
1636 for (i = pktoffs; i < 4+8; i++)
1637 pkt->data[i] = random_byte();
1638 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1639 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1640 PUT_32BIT(pkt->data + pktoffs, len);
1643 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1644 pkt->data + pktoffs + 4, biglen);
1646 if (offset_p) *offset_p = pktoffs;
1647 return biglen + 4; /* len(length+padding+type+data+CRC) */
1650 static int s_write(Ssh ssh, void *data, int len)
1653 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1655 return sk_write(ssh->s, (char *)data, len);
1658 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1660 int len, backlog, offset;
1661 len = s_wrpkt_prepare(ssh, pkt, &offset);
1662 backlog = s_write(ssh, pkt->data + offset, len);
1663 if (backlog > SSH_MAX_BACKLOG)
1664 ssh_throttle_all(ssh, 1, backlog);
1665 ssh_free_packet(pkt);
1668 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1671 len = s_wrpkt_prepare(ssh, pkt, &offset);
1672 if (ssh->deferred_len + len > ssh->deferred_size) {
1673 ssh->deferred_size = ssh->deferred_len + len + 128;
1674 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1678 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1679 pkt->data + offset, len);
1680 ssh->deferred_len += len;
1681 ssh_free_packet(pkt);
1685 * Construct a SSH-1 packet with the specified contents.
1686 * (This all-at-once interface used to be the only one, but now SSH-1
1687 * packets can also be constructed incrementally.)
1689 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1695 pkt = ssh1_pkt_init(pkttype);
1697 while ((argtype = va_arg(ap, int)) != PKT_END) {
1698 unsigned char *argp, argchar;
1700 unsigned long argint;
1703 /* Actual fields in the packet */
1705 argint = va_arg(ap, int);
1706 ssh_pkt_adduint32(pkt, argint);
1709 argchar = (unsigned char) va_arg(ap, int);
1710 ssh_pkt_addbyte(pkt, argchar);
1713 argp = va_arg(ap, unsigned char *);
1714 arglen = va_arg(ap, int);
1715 ssh_pkt_adddata(pkt, argp, arglen);
1718 sargp = va_arg(ap, char *);
1719 ssh_pkt_addstring(pkt, sargp);
1722 bn = va_arg(ap, Bignum);
1723 ssh1_pkt_addmp(pkt, bn);
1725 /* Tokens for modifications to packet logging */
1727 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1730 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1733 end_log_omission(ssh, pkt);
1741 static void send_packet(Ssh ssh, int pkttype, ...)
1745 va_start(ap, pkttype);
1746 pkt = construct_packet(ssh, pkttype, ap);
1751 static void defer_packet(Ssh ssh, int pkttype, ...)
1755 va_start(ap, pkttype);
1756 pkt = construct_packet(ssh, pkttype, ap);
1758 s_wrpkt_defer(ssh, pkt);
1761 static int ssh_versioncmp(char *a, char *b)
1764 unsigned long av, bv;
1766 av = strtoul(a, &ae, 10);
1767 bv = strtoul(b, &be, 10);
1769 return (av < bv ? -1 : +1);
1774 av = strtoul(ae, &ae, 10);
1775 bv = strtoul(be, &be, 10);
1777 return (av < bv ? -1 : +1);
1782 * Utility routines for putting an SSH-protocol `string' and
1783 * `uint32' into a hash state.
1785 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1787 unsigned char lenblk[4];
1788 PUT_32BIT(lenblk, len);
1789 h->bytes(s, lenblk, 4);
1790 h->bytes(s, str, len);
1793 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1795 unsigned char intblk[4];
1796 PUT_32BIT(intblk, i);
1797 h->bytes(s, intblk, 4);
1801 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1803 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1805 if (pkt->maxlen < length) {
1806 unsigned char *body = pkt->body;
1807 int offset = body ? body - pkt->data : 0;
1808 pkt->maxlen = length + 256;
1809 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1810 if (body) pkt->body = pkt->data + offset;
1813 static void ssh_pkt_adddata(struct Packet *pkt, void *data, int len)
1815 if (pkt->logmode != PKTLOG_EMIT) {
1817 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1819 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1820 (pkt->body - pkt->data);
1821 pkt->blanks[pkt->nblanks-1].len = len;
1822 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1825 ssh_pkt_ensure(pkt, pkt->length);
1826 memcpy(pkt->data + pkt->length - len, data, len);
1828 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1830 ssh_pkt_adddata(pkt, &byte, 1);
1832 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1834 ssh_pkt_adddata(pkt, &value, 1);
1836 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1839 PUT_32BIT(x, value);
1840 ssh_pkt_adddata(pkt, x, 4);
1842 static void ssh_pkt_addstring_start(struct Packet *pkt)
1844 ssh_pkt_adduint32(pkt, 0);
1845 pkt->savedpos = pkt->length;
1847 static void ssh_pkt_addstring_str(struct Packet *pkt, char *data)
1849 ssh_pkt_adddata(pkt, data, strlen(data));
1850 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1852 static void ssh_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1854 ssh_pkt_adddata(pkt, data, len);
1855 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1857 static void ssh_pkt_addstring(struct Packet *pkt, char *data)
1859 ssh_pkt_addstring_start(pkt);
1860 ssh_pkt_addstring_str(pkt, data);
1862 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1864 int len = ssh1_bignum_length(b);
1865 unsigned char *data = snewn(len, unsigned char);
1866 (void) ssh1_write_bignum(data, b);
1867 ssh_pkt_adddata(pkt, data, len);
1870 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1873 int i, n = (bignum_bitcount(b) + 7) / 8;
1874 p = snewn(n + 1, unsigned char);
1876 for (i = 1; i <= n; i++)
1877 p[i] = bignum_byte(b, n - i);
1879 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1881 memmove(p, p + i, n + 1 - i);
1885 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1889 p = ssh2_mpint_fmt(b, &len);
1890 ssh_pkt_addstring_start(pkt);
1891 ssh_pkt_addstring_data(pkt, (char *)p, len);
1895 static struct Packet *ssh1_pkt_init(int pkt_type)
1897 struct Packet *pkt = ssh_new_packet();
1898 pkt->length = 4 + 8; /* space for length + max padding */
1899 ssh_pkt_addbyte(pkt, pkt_type);
1900 pkt->body = pkt->data + pkt->length;
1904 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1905 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1906 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1907 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1908 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1909 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1910 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1911 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1912 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1914 static struct Packet *ssh2_pkt_init(int pkt_type)
1916 struct Packet *pkt = ssh_new_packet();
1917 pkt->length = 5; /* space for packet length + padding length */
1919 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1920 pkt->body = pkt->data + pkt->length; /* after packet type */
1925 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1926 * put the MAC on it. Final packet, ready to be sent, is stored in
1927 * pkt->data. Total length is returned.
1929 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1931 int cipherblk, maclen, padding, i;
1934 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1935 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1936 pkt->body, pkt->length - (pkt->body - pkt->data),
1937 pkt->nblanks, pkt->blanks, &ssh->v2_outgoing_sequence);
1938 sfree(pkt->blanks); pkt->blanks = NULL;
1942 * Compress packet payload.
1945 unsigned char *newpayload;
1948 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1950 &newpayload, &newlen)) {
1952 ssh2_pkt_adddata(pkt, newpayload, newlen);
1958 * Add padding. At least four bytes, and must also bring total
1959 * length (minus MAC) up to a multiple of the block size.
1960 * If pkt->forcepad is set, make sure the packet is at least that size
1963 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1964 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1966 if (pkt->length + padding < pkt->forcepad)
1967 padding = pkt->forcepad - pkt->length;
1969 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1970 assert(padding <= 255);
1971 maclen = ssh->csmac ? ssh->csmac->len : 0;
1972 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1973 pkt->data[4] = padding;
1974 for (i = 0; i < padding; i++)
1975 pkt->data[pkt->length + i] = random_byte();
1976 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1978 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1979 pkt->length + padding,
1980 ssh->v2_outgoing_sequence);
1981 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1984 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1985 pkt->data, pkt->length + padding);
1987 pkt->encrypted_len = pkt->length + padding;
1989 /* Ready-to-send packet starts at pkt->data. We return length. */
1990 return pkt->length + padding + maclen;
1994 * Routines called from the main SSH code to send packets. There
1995 * are quite a few of these, because we have two separate
1996 * mechanisms for delaying the sending of packets:
1998 * - In order to send an IGNORE message and a password message in
1999 * a single fixed-length blob, we require the ability to
2000 * concatenate the encrypted forms of those two packets _into_ a
2001 * single blob and then pass it to our <network.h> transport
2002 * layer in one go. Hence, there's a deferment mechanism which
2003 * works after packet encryption.
2005 * - In order to avoid sending any connection-layer messages
2006 * during repeat key exchange, we have to queue up any such
2007 * outgoing messages _before_ they are encrypted (and in
2008 * particular before they're allocated sequence numbers), and
2009 * then send them once we've finished.
2011 * I call these mechanisms `defer' and `queue' respectively, so as
2012 * to distinguish them reasonably easily.
2014 * The functions send_noqueue() and defer_noqueue() free the packet
2015 * structure they are passed. Every outgoing packet goes through
2016 * precisely one of these functions in its life; packets passed to
2017 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2018 * these or get queued, and then when the queue is later emptied
2019 * the packets are all passed to defer_noqueue().
2021 * When using a CBC-mode cipher, it's necessary to ensure that an
2022 * attacker can't provide data to be encrypted using an IV that they
2023 * know. We ensure this by prefixing each packet that might contain
2024 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2025 * mechanism, so in this case send_noqueue() ends up redirecting to
2026 * defer_noqueue(). If you don't like this inefficiency, don't use
2030 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2031 static void ssh_pkt_defersend(Ssh);
2034 * Send an SSH-2 packet immediately, without queuing or deferring.
2036 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2040 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2041 /* We need to send two packets, so use the deferral mechanism. */
2042 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2043 ssh_pkt_defersend(ssh);
2046 len = ssh2_pkt_construct(ssh, pkt);
2047 backlog = s_write(ssh, pkt->data, len);
2048 if (backlog > SSH_MAX_BACKLOG)
2049 ssh_throttle_all(ssh, 1, backlog);
2051 ssh->outgoing_data_size += pkt->encrypted_len;
2052 if (!ssh->kex_in_progress &&
2053 ssh->max_data_size != 0 &&
2054 ssh->outgoing_data_size > ssh->max_data_size)
2055 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2057 ssh_free_packet(pkt);
2061 * Defer an SSH-2 packet.
2063 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2066 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2067 ssh->deferred_len == 0 && !noignore &&
2068 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2070 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2071 * get encrypted with a known IV.
2073 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2074 ssh2_pkt_addstring_start(ipkt);
2075 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2077 len = ssh2_pkt_construct(ssh, pkt);
2078 if (ssh->deferred_len + len > ssh->deferred_size) {
2079 ssh->deferred_size = ssh->deferred_len + len + 128;
2080 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2084 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
2085 ssh->deferred_len += len;
2086 ssh->deferred_data_size += pkt->encrypted_len;
2087 ssh_free_packet(pkt);
2091 * Queue an SSH-2 packet.
2093 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2095 assert(ssh->queueing);
2097 if (ssh->queuelen >= ssh->queuesize) {
2098 ssh->queuesize = ssh->queuelen + 32;
2099 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2102 ssh->queue[ssh->queuelen++] = pkt;
2106 * Either queue or send a packet, depending on whether queueing is
2109 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2112 ssh2_pkt_queue(ssh, pkt);
2114 ssh2_pkt_send_noqueue(ssh, pkt);
2118 * Either queue or defer a packet, depending on whether queueing is
2121 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2124 ssh2_pkt_queue(ssh, pkt);
2126 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2130 * Send the whole deferred data block constructed by
2131 * ssh2_pkt_defer() or SSH-1's defer_packet().
2133 * The expected use of the defer mechanism is that you call
2134 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2135 * not currently queueing, this simply sets up deferred_send_data
2136 * and then sends it. If we _are_ currently queueing, the calls to
2137 * ssh2_pkt_defer() put the deferred packets on to the queue
2138 * instead, and therefore ssh_pkt_defersend() has no deferred data
2139 * to send. Hence, there's no need to make it conditional on
2142 static void ssh_pkt_defersend(Ssh ssh)
2145 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2146 ssh->deferred_len = ssh->deferred_size = 0;
2147 sfree(ssh->deferred_send_data);
2148 ssh->deferred_send_data = NULL;
2149 if (backlog > SSH_MAX_BACKLOG)
2150 ssh_throttle_all(ssh, 1, backlog);
2152 ssh->outgoing_data_size += ssh->deferred_data_size;
2153 if (!ssh->kex_in_progress &&
2154 ssh->max_data_size != 0 &&
2155 ssh->outgoing_data_size > ssh->max_data_size)
2156 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2157 ssh->deferred_data_size = 0;
2161 * Send a packet whose length needs to be disguised (typically
2162 * passwords or keyboard-interactive responses).
2164 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2170 * The simplest way to do this is to adjust the
2171 * variable-length padding field in the outgoing packet.
2173 * Currently compiled out, because some Cisco SSH servers
2174 * don't like excessively padded packets (bah, why's it
2177 pkt->forcepad = padsize;
2178 ssh2_pkt_send(ssh, pkt);
2183 * If we can't do that, however, an alternative approach is
2184 * to use the pkt_defer mechanism to bundle the packet
2185 * tightly together with an SSH_MSG_IGNORE such that their
2186 * combined length is a constant. So first we construct the
2187 * final form of this packet and defer its sending.
2189 ssh2_pkt_defer(ssh, pkt);
2192 * Now construct an SSH_MSG_IGNORE which includes a string
2193 * that's an exact multiple of the cipher block size. (If
2194 * the cipher is NULL so that the block size is
2195 * unavailable, we don't do this trick at all, because we
2196 * gain nothing by it.)
2198 if (ssh->cscipher &&
2199 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2202 stringlen = (256 - ssh->deferred_len);
2203 stringlen += ssh->cscipher->blksize - 1;
2204 stringlen -= (stringlen % ssh->cscipher->blksize);
2207 * Temporarily disable actual compression, so we
2208 * can guarantee to get this string exactly the
2209 * length we want it. The compression-disabling
2210 * routine should return an integer indicating how
2211 * many bytes we should adjust our string length
2215 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2217 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2218 ssh2_pkt_addstring_start(pkt);
2219 for (i = 0; i < stringlen; i++) {
2220 char c = (char) random_byte();
2221 ssh2_pkt_addstring_data(pkt, &c, 1);
2223 ssh2_pkt_defer(ssh, pkt);
2225 ssh_pkt_defersend(ssh);
2230 * Send all queued SSH-2 packets. We send them by means of
2231 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2232 * packets that needed to be lumped together.
2234 static void ssh2_pkt_queuesend(Ssh ssh)
2238 assert(!ssh->queueing);
2240 for (i = 0; i < ssh->queuelen; i++)
2241 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2244 ssh_pkt_defersend(ssh);
2248 void bndebug(char *string, Bignum b)
2252 p = ssh2_mpint_fmt(b, &len);
2253 debug(("%s", string));
2254 for (i = 0; i < len; i++)
2255 debug((" %02x", p[i]));
2261 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2265 p = ssh2_mpint_fmt(b, &len);
2266 hash_string(h, s, p, len);
2271 * Packet decode functions for both SSH-1 and SSH-2.
2273 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2275 unsigned long value;
2276 if (pkt->length - pkt->savedpos < 4)
2277 return 0; /* arrgh, no way to decline (FIXME?) */
2278 value = GET_32BIT(pkt->body + pkt->savedpos);
2282 static int ssh2_pkt_getbool(struct Packet *pkt)
2284 unsigned long value;
2285 if (pkt->length - pkt->savedpos < 1)
2286 return 0; /* arrgh, no way to decline (FIXME?) */
2287 value = pkt->body[pkt->savedpos] != 0;
2291 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2296 if (pkt->length - pkt->savedpos < 4)
2298 len = GET_32BIT(pkt->body + pkt->savedpos);
2303 if (pkt->length - pkt->savedpos < *length)
2305 *p = (char *)(pkt->body + pkt->savedpos);
2306 pkt->savedpos += *length;
2308 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2310 if (pkt->length - pkt->savedpos < length)
2312 pkt->savedpos += length;
2313 return pkt->body + (pkt->savedpos - length);
2315 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2316 unsigned char **keystr)
2320 j = makekey(pkt->body + pkt->savedpos,
2321 pkt->length - pkt->savedpos,
2328 assert(pkt->savedpos < pkt->length);
2332 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2337 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2338 pkt->length - pkt->savedpos, &b);
2346 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2352 ssh_pkt_getstring(pkt, &p, &length);
2357 b = bignum_from_bytes((unsigned char *)p, length);
2362 * Helper function to add an SSH-2 signature blob to a packet.
2363 * Expects to be shown the public key blob as well as the signature
2364 * blob. Normally works just like ssh2_pkt_addstring, but will
2365 * fiddle with the signature packet if necessary for
2366 * BUG_SSH2_RSA_PADDING.
2368 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2369 void *pkblob_v, int pkblob_len,
2370 void *sigblob_v, int sigblob_len)
2372 unsigned char *pkblob = (unsigned char *)pkblob_v;
2373 unsigned char *sigblob = (unsigned char *)sigblob_v;
2375 /* dmemdump(pkblob, pkblob_len); */
2376 /* dmemdump(sigblob, sigblob_len); */
2379 * See if this is in fact an ssh-rsa signature and a buggy
2380 * server; otherwise we can just do this the easy way.
2382 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
2383 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2384 int pos, len, siglen;
2387 * Find the byte length of the modulus.
2390 pos = 4+7; /* skip over "ssh-rsa" */
2391 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
2392 len = GET_32BIT(pkblob+pos); /* find length of modulus */
2393 pos += 4; /* find modulus itself */
2394 while (len > 0 && pkblob[pos] == 0)
2396 /* debug(("modulus length is %d\n", len)); */
2399 * Now find the signature integer.
2401 pos = 4+7; /* skip over "ssh-rsa" */
2402 siglen = GET_32BIT(sigblob+pos);
2403 /* debug(("signature length is %d\n", siglen)); */
2405 if (len != siglen) {
2406 unsigned char newlen[4];
2407 ssh2_pkt_addstring_start(pkt);
2408 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2409 /* dmemdump(sigblob, pos); */
2410 pos += 4; /* point to start of actual sig */
2411 PUT_32BIT(newlen, len);
2412 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2413 /* dmemdump(newlen, 4); */
2415 while (len-- > siglen) {
2416 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2417 /* dmemdump(newlen, 1); */
2419 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2420 /* dmemdump(sigblob+pos, siglen); */
2424 /* Otherwise fall through and do it the easy way. */
2427 ssh2_pkt_addstring_start(pkt);
2428 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2432 * Examine the remote side's version string and compare it against
2433 * a list of known buggy implementations.
2435 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2437 char *imp; /* pointer to implementation part */
2439 imp += strcspn(imp, "-");
2441 imp += strcspn(imp, "-");
2444 ssh->remote_bugs = 0;
2447 * General notes on server version strings:
2448 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2449 * here -- in particular, we've heard of one that's perfectly happy
2450 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2451 * so we can't distinguish them.
2453 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2454 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2455 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2456 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2457 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2458 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2460 * These versions don't support SSH1_MSG_IGNORE, so we have
2461 * to use a different defence against password length
2464 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2465 logevent("We believe remote version has SSH-1 ignore bug");
2468 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2469 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2470 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2472 * These versions need a plain password sent; they can't
2473 * handle having a null and a random length of data after
2476 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2477 logevent("We believe remote version needs a plain SSH-1 password");
2480 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2481 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2482 (!strcmp(imp, "Cisco-1.25")))) {
2484 * These versions apparently have no clue whatever about
2485 * RSA authentication and will panic and die if they see
2486 * an AUTH_RSA message.
2488 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2489 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2492 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2493 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2494 !wc_match("* VShell", imp) &&
2495 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2496 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2497 wc_match("2.1 *", imp)))) {
2499 * These versions have the HMAC bug.
2501 ssh->remote_bugs |= BUG_SSH2_HMAC;
2502 logevent("We believe remote version has SSH-2 HMAC bug");
2505 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2506 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2507 !wc_match("* VShell", imp) &&
2508 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2510 * These versions have the key-derivation bug (failing to
2511 * include the literal shared secret in the hashes that
2512 * generate the keys).
2514 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2515 logevent("We believe remote version has SSH-2 key-derivation bug");
2518 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2519 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2520 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2521 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2523 * These versions have the SSH-2 RSA padding bug.
2525 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2526 logevent("We believe remote version has SSH-2 RSA padding bug");
2529 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2530 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2531 wc_match("OpenSSH_2.[0-2]*", imp))) {
2533 * These versions have the SSH-2 session-ID bug in
2534 * public-key authentication.
2536 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2537 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2540 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2541 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2542 (wc_match("DigiSSH_2.0", imp) ||
2543 wc_match("OpenSSH_2.[0-4]*", imp) ||
2544 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2545 wc_match("Sun_SSH_1.0", imp) ||
2546 wc_match("Sun_SSH_1.0.1", imp) ||
2547 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2548 wc_match("WeOnlyDo-*", imp)))) {
2550 * These versions have the SSH-2 rekey bug.
2552 ssh->remote_bugs |= BUG_SSH2_REKEY;
2553 logevent("We believe remote version has SSH-2 rekey bug");
2556 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2557 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2558 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2559 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2561 * This version ignores our makpkt and needs to be throttled.
2563 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2564 logevent("We believe remote version ignores SSH-2 maximum packet size");
2567 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2569 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2570 * none detected automatically.
2572 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2573 logevent("We believe remote version has SSH-2 ignore bug");
2578 * The `software version' part of an SSH version string is required
2579 * to contain no spaces or minus signs.
2581 static void ssh_fix_verstring(char *str)
2583 /* Eat "SSH-<protoversion>-". */
2584 assert(*str == 'S'); str++;
2585 assert(*str == 'S'); str++;
2586 assert(*str == 'H'); str++;
2587 assert(*str == '-'); str++;
2588 while (*str && *str != '-') str++;
2589 assert(*str == '-'); str++;
2591 /* Convert minus signs and spaces in the remaining string into
2594 if (*str == '-' || *str == ' ')
2601 * Send an appropriate SSH version string.
2603 static void ssh_send_verstring(Ssh ssh, char *svers)
2607 if (ssh->version == 2) {
2609 * Construct a v2 version string.
2611 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2614 * Construct a v1 version string.
2616 verstring = dupprintf("SSH-%s-%s\012",
2617 (ssh_versioncmp(svers, "1.5") <= 0 ?
2622 ssh_fix_verstring(verstring);
2624 if (ssh->version == 2) {
2627 * Record our version string.
2629 len = strcspn(verstring, "\015\012");
2630 ssh->v_c = snewn(len + 1, char);
2631 memcpy(ssh->v_c, verstring, len);
2635 logeventf(ssh, "We claim version: %.*s",
2636 strcspn(verstring, "\015\012"), verstring);
2637 s_write(ssh, verstring, strlen(verstring));
2641 static int do_ssh_init(Ssh ssh, unsigned char c)
2643 struct do_ssh_init_state {
2651 crState(do_ssh_init_state);
2653 crBegin(ssh->do_ssh_init_crstate);
2655 /* Search for a line beginning with the string "SSH-" in the input. */
2657 if (c != 'S') goto no;
2659 if (c != 'S') goto no;
2661 if (c != 'H') goto no;
2663 if (c != '-') goto no;
2672 s->vstring = snewn(s->vstrsize, char);
2673 strcpy(s->vstring, "SSH-");
2677 crReturn(1); /* get another char */
2678 if (s->vslen >= s->vstrsize - 1) {
2680 s->vstring = sresize(s->vstring, s->vstrsize, char);
2682 s->vstring[s->vslen++] = c;
2685 s->version[s->i] = '\0';
2687 } else if (s->i < sizeof(s->version) - 1)
2688 s->version[s->i++] = c;
2689 } else if (c == '\012')
2693 ssh->agentfwd_enabled = FALSE;
2694 ssh->rdpkt2_state.incoming_sequence = 0;
2696 s->vstring[s->vslen] = 0;
2697 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2698 logeventf(ssh, "Server version: %s", s->vstring);
2699 ssh_detect_bugs(ssh, s->vstring);
2702 * Decide which SSH protocol version to support.
2705 /* Anything strictly below "2.0" means protocol 1 is supported. */
2706 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2707 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2708 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2710 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2711 bombout(("SSH protocol version 1 required by user but not provided by server"));
2714 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2715 bombout(("SSH protocol version 2 required by user but not provided by server"));
2719 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2724 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2726 /* Send the version string, if we haven't already */
2727 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
2728 ssh_send_verstring(ssh, s->version);
2730 if (ssh->version == 2) {
2733 * Record their version string.
2735 len = strcspn(s->vstring, "\015\012");
2736 ssh->v_s = snewn(len + 1, char);
2737 memcpy(ssh->v_s, s->vstring, len);
2741 * Initialise SSH-2 protocol.
2743 ssh->protocol = ssh2_protocol;
2744 ssh2_protocol_setup(ssh);
2745 ssh->s_rdpkt = ssh2_rdpkt;
2748 * Initialise SSH-1 protocol.
2750 ssh->protocol = ssh1_protocol;
2751 ssh1_protocol_setup(ssh);
2752 ssh->s_rdpkt = ssh1_rdpkt;
2754 if (ssh->version == 2)
2755 do_ssh2_transport(ssh, NULL, -1, NULL);
2757 update_specials_menu(ssh->frontend);
2758 ssh->state = SSH_STATE_BEFORE_SIZE;
2759 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
2766 static void ssh_process_incoming_data(Ssh ssh,
2767 unsigned char **data, int *datalen)
2769 struct Packet *pktin;
2771 pktin = ssh->s_rdpkt(ssh, data, datalen);
2773 ssh->protocol(ssh, NULL, 0, pktin);
2774 ssh_free_packet(pktin);
2778 static void ssh_queue_incoming_data(Ssh ssh,
2779 unsigned char **data, int *datalen)
2781 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2786 static void ssh_process_queued_incoming_data(Ssh ssh)
2789 unsigned char *data;
2792 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2793 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2797 while (!ssh->frozen && len > 0)
2798 ssh_process_incoming_data(ssh, &data, &len);
2801 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2805 static void ssh_set_frozen(Ssh ssh, int frozen)
2808 sk_set_frozen(ssh->s, frozen);
2809 ssh->frozen = frozen;
2812 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2814 /* Log raw data, if we're in that mode. */
2816 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2819 crBegin(ssh->ssh_gotdata_crstate);
2822 * To begin with, feed the characters one by one to the
2823 * protocol initialisation / selection function do_ssh_init().
2824 * When that returns 0, we're done with the initial greeting
2825 * exchange and can move on to packet discipline.
2828 int ret; /* need not be kept across crReturn */
2830 crReturnV; /* more data please */
2831 ret = do_ssh_init(ssh, *data);
2839 * We emerge from that loop when the initial negotiation is
2840 * over and we have selected an s_rdpkt function. Now pass
2841 * everything to s_rdpkt, and then pass the resulting packets
2842 * to the proper protocol handler.
2846 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2848 ssh_queue_incoming_data(ssh, &data, &datalen);
2849 /* This uses up all data and cannot cause anything interesting
2850 * to happen; indeed, for anything to happen at all, we must
2851 * return, so break out. */
2853 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2854 /* This uses up some or all data, and may freeze the
2856 ssh_process_queued_incoming_data(ssh);
2858 /* This uses up some or all data, and may freeze the
2860 ssh_process_incoming_data(ssh, &data, &datalen);
2862 /* FIXME this is probably EBW. */
2863 if (ssh->state == SSH_STATE_CLOSED)
2866 /* We're out of data. Go and get some more. */
2872 static int ssh_do_close(Ssh ssh, int notify_exit)
2875 struct ssh_channel *c;
2877 ssh->state = SSH_STATE_CLOSED;
2878 expire_timer_context(ssh);
2883 notify_remote_exit(ssh->frontend);
2888 * Now we must shut down any port- and X-forwarded channels going
2889 * through this connection.
2891 if (ssh->channels) {
2892 while (NULL != (c = index234(ssh->channels, 0))) {
2895 x11_close(c->u.x11.s);
2898 case CHAN_SOCKDATA_DORMANT:
2899 pfd_close(c->u.pfd.s);
2902 del234(ssh->channels, c); /* moving next one to index 0 */
2903 if (ssh->version == 2)
2904 bufchain_clear(&c->v.v2.outbuffer);
2909 * Go through port-forwardings, and close any associated
2910 * listening sockets.
2912 if (ssh->portfwds) {
2913 struct ssh_portfwd *pf;
2914 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2915 /* Dispose of any listening socket. */
2917 pfd_terminate(pf->local);
2918 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2921 freetree234(ssh->portfwds);
2922 ssh->portfwds = NULL;
2928 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2929 const char *error_msg, int error_code)
2931 Ssh ssh = (Ssh) plug;
2932 char addrbuf[256], *msg;
2934 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2937 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2939 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2945 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2948 Ssh ssh = (Ssh) plug;
2949 int need_notify = ssh_do_close(ssh, FALSE);
2952 if (!ssh->close_expected)
2953 error_msg = "Server unexpectedly closed network connection";
2955 error_msg = "Server closed network connection";
2958 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
2962 notify_remote_exit(ssh->frontend);
2965 logevent(error_msg);
2966 if (!ssh->close_expected || !ssh->clean_exit)
2967 connection_fatal(ssh->frontend, "%s", error_msg);
2971 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2973 Ssh ssh = (Ssh) plug;
2974 ssh_gotdata(ssh, (unsigned char *)data, len);
2975 if (ssh->state == SSH_STATE_CLOSED) {
2976 ssh_do_close(ssh, TRUE);
2982 static void ssh_sent(Plug plug, int bufsize)
2984 Ssh ssh = (Ssh) plug;
2986 * If the send backlog on the SSH socket itself clears, we
2987 * should unthrottle the whole world if it was throttled.
2989 if (bufsize < SSH_MAX_BACKLOG)
2990 ssh_throttle_all(ssh, 0, bufsize);
2994 * Connect to specified host and port.
2995 * Returns an error message, or NULL on success.
2996 * Also places the canonical host name into `realhost'. It must be
2997 * freed by the caller.
2999 static const char *connect_to_host(Ssh ssh, char *host, int port,
3000 char **realhost, int nodelay, int keepalive)
3002 static const struct plug_function_table fn_table = {
3013 int addressfamily, sshprot;
3015 loghost = conf_get_str(ssh->conf, CONF_loghost);
3019 ssh->savedhost = dupstr(loghost);
3020 ssh->savedport = 22; /* default ssh port */
3023 * A colon suffix on savedhost also lets us affect
3026 * (FIXME: do something about IPv6 address literals here.)
3028 colon = strrchr(ssh->savedhost, ':');
3032 ssh->savedport = atoi(colon);
3035 ssh->savedhost = dupstr(host);
3037 port = 22; /* default ssh port */
3038 ssh->savedport = port;
3044 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3045 logeventf(ssh, "Looking up host \"%s\"%s", host,
3046 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3047 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3048 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3049 if ((err = sk_addr_error(addr)) != NULL) {
3053 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3058 ssh->fn = &fn_table;
3059 ssh->s = new_connection(addr, *realhost, port,
3060 0, 1, nodelay, keepalive, (Plug) ssh, ssh->conf);
3061 if ((err = sk_socket_error(ssh->s)) != NULL) {
3063 notify_remote_exit(ssh->frontend);
3068 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3069 * send the version string too.
3071 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3076 ssh_send_verstring(ssh, NULL);
3080 * loghost, if configured, overrides realhost.
3084 *realhost = dupstr(loghost);
3091 * Throttle or unthrottle the SSH connection.
3093 static void ssh_throttle_conn(Ssh ssh, int adjust)
3095 int old_count = ssh->conn_throttle_count;
3096 ssh->conn_throttle_count += adjust;
3097 assert(ssh->conn_throttle_count >= 0);
3098 if (ssh->conn_throttle_count && !old_count) {
3099 ssh_set_frozen(ssh, 1);
3100 } else if (!ssh->conn_throttle_count && old_count) {
3101 ssh_set_frozen(ssh, 0);
3106 * Throttle or unthrottle _all_ local data streams (for when sends
3107 * on the SSH connection itself back up).
3109 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3112 struct ssh_channel *c;
3114 if (enable == ssh->throttled_all)
3116 ssh->throttled_all = enable;
3117 ssh->overall_bufsize = bufsize;
3120 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3122 case CHAN_MAINSESSION:
3124 * This is treated separately, outside the switch.
3128 x11_override_throttle(c->u.x11.s, enable);
3131 /* Agent channels require no buffer management. */
3134 pfd_override_throttle(c->u.pfd.s, enable);
3140 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3142 Ssh ssh = (Ssh) sshv;
3144 ssh->agent_response = reply;
3145 ssh->agent_response_len = replylen;
3147 if (ssh->version == 1)
3148 do_ssh1_login(ssh, NULL, -1, NULL);
3150 do_ssh2_authconn(ssh, NULL, -1, NULL);
3153 static void ssh_dialog_callback(void *sshv, int ret)
3155 Ssh ssh = (Ssh) sshv;
3157 ssh->user_response = ret;
3159 if (ssh->version == 1)
3160 do_ssh1_login(ssh, NULL, -1, NULL);
3162 do_ssh2_transport(ssh, NULL, -1, NULL);
3165 * This may have unfrozen the SSH connection, so do a
3168 ssh_process_queued_incoming_data(ssh);
3171 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3173 struct ssh_channel *c = (struct ssh_channel *)cv;
3175 void *sentreply = reply;
3178 /* Fake SSH_AGENT_FAILURE. */
3179 sentreply = "\0\0\0\1\5";
3182 if (ssh->version == 2) {
3183 ssh2_add_channel_data(c, sentreply, replylen);
3186 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3187 PKT_INT, c->remoteid,
3190 PKT_DATA, sentreply, replylen,
3199 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3200 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3201 * => log `wire_reason'.
3203 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3204 int code, int clean_exit)
3208 client_reason = wire_reason;
3210 error = dupprintf("Disconnected: %s", client_reason);
3212 error = dupstr("Disconnected");
3214 if (ssh->version == 1) {
3215 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3217 } else if (ssh->version == 2) {
3218 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3219 ssh2_pkt_adduint32(pktout, code);
3220 ssh2_pkt_addstring(pktout, wire_reason);
3221 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3222 ssh2_pkt_send_noqueue(ssh, pktout);
3225 ssh->close_expected = TRUE;
3226 ssh->clean_exit = clean_exit;
3227 ssh_closing((Plug)ssh, error, 0, 0);
3232 * Handle the key exchange and user authentication phases.
3234 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3235 struct Packet *pktin)
3238 unsigned char cookie[8], *ptr;
3239 struct RSAKey servkey, hostkey;
3240 struct MD5Context md5c;
3241 struct do_ssh1_login_state {
3243 unsigned char *rsabuf, *keystr1, *keystr2;
3244 unsigned long supported_ciphers_mask, supported_auths_mask;
3245 int tried_publickey, tried_agent;
3246 int tis_auth_refused, ccard_auth_refused;
3247 unsigned char session_id[16];
3249 void *publickey_blob;
3250 int publickey_bloblen;
3251 char *publickey_comment;
3252 int publickey_encrypted;
3253 prompts_t *cur_prompt;
3256 unsigned char request[5], *response, *p;
3267 crState(do_ssh1_login_state);
3269 crBegin(ssh->do_ssh1_login_crstate);
3274 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3275 bombout(("Public key packet not received"));
3279 logevent("Received public keys");
3281 ptr = ssh_pkt_getdata(pktin, 8);
3283 bombout(("SSH-1 public key packet stopped before random cookie"));
3286 memcpy(cookie, ptr, 8);
3288 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
3289 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
3290 bombout(("Failed to read SSH-1 public keys from public key packet"));
3295 * Log the host key fingerprint.
3299 logevent("Host key fingerprint is:");
3300 strcpy(logmsg, " ");
3301 hostkey.comment = NULL;
3302 rsa_fingerprint(logmsg + strlen(logmsg),
3303 sizeof(logmsg) - strlen(logmsg), &hostkey);
3307 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3308 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3309 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3310 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3311 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3313 ssh->v1_local_protoflags =
3314 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3315 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3318 MD5Update(&md5c, s->keystr2, hostkey.bytes);
3319 MD5Update(&md5c, s->keystr1, servkey.bytes);
3320 MD5Update(&md5c, cookie, 8);
3321 MD5Final(s->session_id, &md5c);
3323 for (i = 0; i < 32; i++)
3324 ssh->session_key[i] = random_byte();
3327 * Verify that the `bits' and `bytes' parameters match.
3329 if (hostkey.bits > hostkey.bytes * 8 ||
3330 servkey.bits > servkey.bytes * 8) {
3331 bombout(("SSH-1 public keys were badly formatted"));
3335 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
3337 s->rsabuf = snewn(s->len, unsigned char);
3340 * Verify the host key.
3344 * First format the key into a string.
3346 int len = rsastr_len(&hostkey);
3347 char fingerprint[100];
3348 char *keystr = snewn(len, char);
3349 rsastr_fmt(keystr, &hostkey);
3350 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
3352 ssh_set_frozen(ssh, 1);
3353 s->dlgret = verify_ssh_host_key(ssh->frontend,
3354 ssh->savedhost, ssh->savedport,
3355 "rsa", keystr, fingerprint,
3356 ssh_dialog_callback, ssh);
3358 if (s->dlgret < 0) {
3362 bombout(("Unexpected data from server while waiting"
3363 " for user host key response"));
3366 } while (pktin || inlen > 0);
3367 s->dlgret = ssh->user_response;
3369 ssh_set_frozen(ssh, 0);
3371 if (s->dlgret == 0) {
3372 ssh_disconnect(ssh, "User aborted at host key verification",
3378 for (i = 0; i < 32; i++) {
3379 s->rsabuf[i] = ssh->session_key[i];
3381 s->rsabuf[i] ^= s->session_id[i];
3384 if (hostkey.bytes > servkey.bytes) {
3385 ret = rsaencrypt(s->rsabuf, 32, &servkey);
3387 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
3389 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
3391 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
3394 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3398 logevent("Encrypted session key");
3401 int cipher_chosen = 0, warn = 0;
3402 char *cipher_string = NULL;
3404 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3405 int next_cipher = conf_get_int_int(ssh->conf,
3406 CONF_ssh_cipherlist, i);
3407 if (next_cipher == CIPHER_WARN) {
3408 /* If/when we choose a cipher, warn about it */
3410 } else if (next_cipher == CIPHER_AES) {
3411 /* XXX Probably don't need to mention this. */
3412 logevent("AES not supported in SSH-1, skipping");
3414 switch (next_cipher) {
3415 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3416 cipher_string = "3DES"; break;
3417 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3418 cipher_string = "Blowfish"; break;
3419 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3420 cipher_string = "single-DES"; break;
3422 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3426 if (!cipher_chosen) {
3427 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3428 bombout(("Server violates SSH-1 protocol by not "
3429 "supporting 3DES encryption"));
3431 /* shouldn't happen */
3432 bombout(("No supported ciphers found"));
3436 /* Warn about chosen cipher if necessary. */
3438 ssh_set_frozen(ssh, 1);
3439 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3440 ssh_dialog_callback, ssh);
3441 if (s->dlgret < 0) {
3445 bombout(("Unexpected data from server while waiting"
3446 " for user response"));
3449 } while (pktin || inlen > 0);
3450 s->dlgret = ssh->user_response;
3452 ssh_set_frozen(ssh, 0);
3453 if (s->dlgret == 0) {
3454 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3461 switch (s->cipher_type) {
3462 case SSH_CIPHER_3DES:
3463 logevent("Using 3DES encryption");
3465 case SSH_CIPHER_DES:
3466 logevent("Using single-DES encryption");
3468 case SSH_CIPHER_BLOWFISH:
3469 logevent("Using Blowfish encryption");
3473 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3474 PKT_CHAR, s->cipher_type,
3475 PKT_DATA, cookie, 8,
3476 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3477 PKT_DATA, s->rsabuf, s->len,
3478 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3480 logevent("Trying to enable encryption...");
3484 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3485 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3487 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3488 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3489 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3491 ssh->crcda_ctx = crcda_make_context();
3492 logevent("Installing CRC compensation attack detector");
3494 if (servkey.modulus) {
3495 sfree(servkey.modulus);
3496 servkey.modulus = NULL;
3498 if (servkey.exponent) {
3499 sfree(servkey.exponent);
3500 servkey.exponent = NULL;
3502 if (hostkey.modulus) {
3503 sfree(hostkey.modulus);
3504 hostkey.modulus = NULL;
3506 if (hostkey.exponent) {
3507 sfree(hostkey.exponent);
3508 hostkey.exponent = NULL;
3512 if (pktin->type != SSH1_SMSG_SUCCESS) {
3513 bombout(("Encryption not successfully enabled"));
3517 logevent("Successfully started encryption");
3519 fflush(stdout); /* FIXME eh? */
3521 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
3522 int ret; /* need not be kept over crReturn */
3523 s->cur_prompt = new_prompts(ssh->frontend);
3524 s->cur_prompt->to_server = TRUE;
3525 s->cur_prompt->name = dupstr("SSH login name");
3526 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
3527 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3530 crWaitUntil(!pktin);
3531 ret = get_userpass_input(s->cur_prompt, in, inlen);
3536 * Failed to get a username. Terminate.
3538 free_prompts(s->cur_prompt);
3539 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3542 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
3543 free_prompts(s->cur_prompt);
3546 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
3548 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
3550 if (flags & FLAG_INTERACTIVE &&
3551 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3552 c_write_str(ssh, userlog);
3553 c_write_str(ssh, "\r\n");
3561 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3562 /* We must not attempt PK auth. Pretend we've already tried it. */
3563 s->tried_publickey = s->tried_agent = 1;
3565 s->tried_publickey = s->tried_agent = 0;
3567 s->tis_auth_refused = s->ccard_auth_refused = 0;
3569 * Load the public half of any configured keyfile for later use.
3571 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3572 if (!filename_is_null(s->keyfile)) {
3574 logeventf(ssh, "Reading private key file \"%.150s\"",
3575 filename_to_str(s->keyfile));
3576 keytype = key_type(s->keyfile);
3577 if (keytype == SSH_KEYTYPE_SSH1) {
3579 if (rsakey_pubblob(s->keyfile,
3580 &s->publickey_blob, &s->publickey_bloblen,
3581 &s->publickey_comment, &error)) {
3582 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
3586 logeventf(ssh, "Unable to load private key (%s)", error);
3587 msgbuf = dupprintf("Unable to load private key file "
3588 "\"%.150s\" (%s)\r\n",
3589 filename_to_str(s->keyfile),
3591 c_write_str(ssh, msgbuf);
3593 s->publickey_blob = NULL;
3597 logeventf(ssh, "Unable to use this key file (%s)",
3598 key_type_to_str(keytype));
3599 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3601 filename_to_str(s->keyfile),
3602 key_type_to_str(keytype));
3603 c_write_str(ssh, msgbuf);
3605 s->publickey_blob = NULL;
3608 s->publickey_blob = NULL;
3610 while (pktin->type == SSH1_SMSG_FAILURE) {
3611 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3613 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
3615 * Attempt RSA authentication using Pageant.
3621 logevent("Pageant is running. Requesting keys.");
3623 /* Request the keys held by the agent. */
3624 PUT_32BIT(s->request, 1);
3625 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3626 if (!agent_query(s->request, 5, &r, &s->responselen,
3627 ssh_agent_callback, ssh)) {
3631 bombout(("Unexpected data from server while waiting"
3632 " for agent response"));
3635 } while (pktin || inlen > 0);
3636 r = ssh->agent_response;
3637 s->responselen = ssh->agent_response_len;
3639 s->response = (unsigned char *) r;
3640 if (s->response && s->responselen >= 5 &&
3641 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3642 s->p = s->response + 5;
3643 s->nkeys = GET_32BIT(s->p);
3645 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3646 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3647 unsigned char *pkblob = s->p;
3651 do { /* do while (0) to make breaking easy */
3652 n = ssh1_read_bignum
3653 (s->p, s->responselen-(s->p-s->response),
3658 n = ssh1_read_bignum
3659 (s->p, s->responselen-(s->p-s->response),
3664 if (s->responselen - (s->p-s->response) < 4)
3666 s->commentlen = GET_32BIT(s->p);
3668 if (s->responselen - (s->p-s->response) <
3671 s->commentp = (char *)s->p;
3672 s->p += s->commentlen;
3676 logevent("Pageant key list packet was truncated");
3680 if (s->publickey_blob) {
3681 if (!memcmp(pkblob, s->publickey_blob,
3682 s->publickey_bloblen)) {
3683 logeventf(ssh, "Pageant key #%d matches "
3684 "configured key file", s->keyi);
3685 s->tried_publickey = 1;
3687 /* Skip non-configured key */
3690 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3691 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3692 PKT_BIGNUM, s->key.modulus, PKT_END);
3694 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3695 logevent("Key refused");
3698 logevent("Received RSA challenge");
3699 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3700 bombout(("Server's RSA challenge was badly formatted"));
3705 char *agentreq, *q, *ret;
3708 len = 1 + 4; /* message type, bit count */
3709 len += ssh1_bignum_length(s->key.exponent);
3710 len += ssh1_bignum_length(s->key.modulus);
3711 len += ssh1_bignum_length(s->challenge);
3712 len += 16; /* session id */
3713 len += 4; /* response format */
3714 agentreq = snewn(4 + len, char);
3715 PUT_32BIT(agentreq, len);
3717 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3718 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3720 q += ssh1_write_bignum(q, s->key.exponent);
3721 q += ssh1_write_bignum(q, s->key.modulus);
3722 q += ssh1_write_bignum(q, s->challenge);
3723 memcpy(q, s->session_id, 16);
3725 PUT_32BIT(q, 1); /* response format */
3726 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3727 ssh_agent_callback, ssh)) {
3732 bombout(("Unexpected data from server"
3733 " while waiting for agent"
3737 } while (pktin || inlen > 0);
3738 vret = ssh->agent_response;
3739 retlen = ssh->agent_response_len;
3744 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3745 logevent("Sending Pageant's response");
3746 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3747 PKT_DATA, ret + 5, 16,
3751 if (pktin->type == SSH1_SMSG_SUCCESS) {
3753 ("Pageant's response accepted");
3754 if (flags & FLAG_VERBOSE) {
3755 c_write_str(ssh, "Authenticated using"
3757 c_write(ssh, s->commentp,
3759 c_write_str(ssh, "\" from agent\r\n");
3764 ("Pageant's response not accepted");
3767 ("Pageant failed to answer challenge");
3771 logevent("No reply received from Pageant");
3774 freebn(s->key.exponent);
3775 freebn(s->key.modulus);
3776 freebn(s->challenge);
3781 if (s->publickey_blob && !s->tried_publickey)
3782 logevent("Configured key file not in Pageant");
3784 logevent("Failed to get reply from Pageant");
3789 if (s->publickey_blob && !s->tried_publickey) {
3791 * Try public key authentication with the specified
3794 int got_passphrase; /* need not be kept over crReturn */
3795 if (flags & FLAG_VERBOSE)
3796 c_write_str(ssh, "Trying public key authentication.\r\n");
3797 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3798 logeventf(ssh, "Trying public key \"%s\"",
3799 filename_to_str(s->keyfile));
3800 s->tried_publickey = 1;
3801 got_passphrase = FALSE;
3802 while (!got_passphrase) {
3804 * Get a passphrase, if necessary.
3806 char *passphrase = NULL; /* only written after crReturn */
3808 if (!s->publickey_encrypted) {
3809 if (flags & FLAG_VERBOSE)
3810 c_write_str(ssh, "No passphrase required.\r\n");
3813 int ret; /* need not be kept over crReturn */
3814 s->cur_prompt = new_prompts(ssh->frontend);
3815 s->cur_prompt->to_server = FALSE;
3816 s->cur_prompt->name = dupstr("SSH key passphrase");
3817 add_prompt(s->cur_prompt,
3818 dupprintf("Passphrase for key \"%.100s\": ",
3819 s->publickey_comment), FALSE);
3820 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3823 crWaitUntil(!pktin);
3824 ret = get_userpass_input(s->cur_prompt, in, inlen);
3828 /* Failed to get a passphrase. Terminate. */
3829 free_prompts(s->cur_prompt);
3830 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3834 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3835 free_prompts(s->cur_prompt);
3838 * Try decrypting key with passphrase.
3840 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3841 ret = loadrsakey(s->keyfile, &s->key, passphrase,
3844 memset(passphrase, 0, strlen(passphrase));
3848 /* Correct passphrase. */
3849 got_passphrase = TRUE;
3850 } else if (ret == 0) {
3851 c_write_str(ssh, "Couldn't load private key from ");
3852 c_write_str(ssh, filename_to_str(s->keyfile));
3853 c_write_str(ssh, " (");
3854 c_write_str(ssh, error);
3855 c_write_str(ssh, ").\r\n");
3856 got_passphrase = FALSE;
3857 break; /* go and try something else */
3858 } else if (ret == -1) {
3859 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3860 got_passphrase = FALSE;
3863 assert(0 && "unexpected return from loadrsakey()");
3864 got_passphrase = FALSE; /* placate optimisers */
3868 if (got_passphrase) {
3871 * Send a public key attempt.
3873 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3874 PKT_BIGNUM, s->key.modulus, PKT_END);
3877 if (pktin->type == SSH1_SMSG_FAILURE) {
3878 c_write_str(ssh, "Server refused our public key.\r\n");
3879 continue; /* go and try something else */
3881 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3882 bombout(("Bizarre response to offer of public key"));
3888 unsigned char buffer[32];
3889 Bignum challenge, response;
3891 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3892 bombout(("Server's RSA challenge was badly formatted"));
3895 response = rsadecrypt(challenge, &s->key);
3896 freebn(s->key.private_exponent);/* burn the evidence */
3898 for (i = 0; i < 32; i++) {
3899 buffer[i] = bignum_byte(response, 31 - i);
3903 MD5Update(&md5c, buffer, 32);
3904 MD5Update(&md5c, s->session_id, 16);
3905 MD5Final(buffer, &md5c);
3907 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3908 PKT_DATA, buffer, 16, PKT_END);
3915 if (pktin->type == SSH1_SMSG_FAILURE) {
3916 if (flags & FLAG_VERBOSE)
3917 c_write_str(ssh, "Failed to authenticate with"
3918 " our public key.\r\n");
3919 continue; /* go and try something else */
3920 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3921 bombout(("Bizarre response to RSA authentication response"));
3925 break; /* we're through! */
3931 * Otherwise, try various forms of password-like authentication.
3933 s->cur_prompt = new_prompts(ssh->frontend);
3935 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3936 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3937 !s->tis_auth_refused) {
3938 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3939 logevent("Requested TIS authentication");
3940 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3942 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3943 logevent("TIS authentication declined");
3944 if (flags & FLAG_INTERACTIVE)
3945 c_write_str(ssh, "TIS authentication refused.\r\n");
3946 s->tis_auth_refused = 1;
3951 char *instr_suf, *prompt;
3953 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3955 bombout(("TIS challenge packet was badly formed"));
3958 logevent("Received TIS challenge");
3959 s->cur_prompt->to_server = TRUE;
3960 s->cur_prompt->name = dupstr("SSH TIS authentication");
3961 /* Prompt heuristic comes from OpenSSH */
3962 if (memchr(challenge, '\n', challengelen)) {
3963 instr_suf = dupstr("");
3964 prompt = dupprintf("%.*s", challengelen, challenge);
3966 instr_suf = dupprintf("%.*s", challengelen, challenge);
3967 prompt = dupstr("Response: ");
3969 s->cur_prompt->instruction =
3970 dupprintf("Using TIS authentication.%s%s",
3971 (*instr_suf) ? "\n" : "",
3973 s->cur_prompt->instr_reqd = TRUE;
3974 add_prompt(s->cur_prompt, prompt, FALSE);
3978 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3979 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3980 !s->ccard_auth_refused) {
3981 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3982 logevent("Requested CryptoCard authentication");
3983 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3985 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3986 logevent("CryptoCard authentication declined");
3987 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3988 s->ccard_auth_refused = 1;
3993 char *instr_suf, *prompt;
3995 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3997 bombout(("CryptoCard challenge packet was badly formed"));
4000 logevent("Received CryptoCard challenge");
4001 s->cur_prompt->to_server = TRUE;
4002 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4003 s->cur_prompt->name_reqd = FALSE;
4004 /* Prompt heuristic comes from OpenSSH */
4005 if (memchr(challenge, '\n', challengelen)) {
4006 instr_suf = dupstr("");
4007 prompt = dupprintf("%.*s", challengelen, challenge);
4009 instr_suf = dupprintf("%.*s", challengelen, challenge);
4010 prompt = dupstr("Response: ");
4012 s->cur_prompt->instruction =
4013 dupprintf("Using CryptoCard authentication.%s%s",
4014 (*instr_suf) ? "\n" : "",
4016 s->cur_prompt->instr_reqd = TRUE;
4017 add_prompt(s->cur_prompt, prompt, FALSE);
4021 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4022 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4023 bombout(("No supported authentication methods available"));
4026 s->cur_prompt->to_server = TRUE;
4027 s->cur_prompt->name = dupstr("SSH password");
4028 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4029 ssh->username, ssh->savedhost),
4034 * Show password prompt, having first obtained it via a TIS
4035 * or CryptoCard exchange if we're doing TIS or CryptoCard
4039 int ret; /* need not be kept over crReturn */
4040 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4043 crWaitUntil(!pktin);
4044 ret = get_userpass_input(s->cur_prompt, in, inlen);
4049 * Failed to get a password (for example
4050 * because one was supplied on the command line
4051 * which has already failed to work). Terminate.
4053 free_prompts(s->cur_prompt);
4054 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4059 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4061 * Defence against traffic analysis: we send a
4062 * whole bunch of packets containing strings of
4063 * different lengths. One of these strings is the
4064 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4065 * The others are all random data in
4066 * SSH1_MSG_IGNORE packets. This way a passive
4067 * listener can't tell which is the password, and
4068 * hence can't deduce the password length.
4070 * Anybody with a password length greater than 16
4071 * bytes is going to have enough entropy in their
4072 * password that a listener won't find it _that_
4073 * much help to know how long it is. So what we'll
4076 * - if password length < 16, we send 15 packets
4077 * containing string lengths 1 through 15
4079 * - otherwise, we let N be the nearest multiple
4080 * of 8 below the password length, and send 8
4081 * packets containing string lengths N through
4082 * N+7. This won't obscure the order of
4083 * magnitude of the password length, but it will
4084 * introduce a bit of extra uncertainty.
4086 * A few servers can't deal with SSH1_MSG_IGNORE, at
4087 * least in this context. For these servers, we need
4088 * an alternative defence. We make use of the fact
4089 * that the password is interpreted as a C string:
4090 * so we can append a NUL, then some random data.
4092 * A few servers can deal with neither SSH1_MSG_IGNORE
4093 * here _nor_ a padded password string.
4094 * For these servers we are left with no defences
4095 * against password length sniffing.
4097 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4098 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4100 * The server can deal with SSH1_MSG_IGNORE, so
4101 * we can use the primary defence.
4103 int bottom, top, pwlen, i;
4106 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4108 bottom = 0; /* zero length passwords are OK! :-) */
4111 bottom = pwlen & ~7;
4115 assert(pwlen >= bottom && pwlen <= top);
4117 randomstr = snewn(top + 1, char);
4119 for (i = bottom; i <= top; i++) {
4121 defer_packet(ssh, s->pwpkt_type,
4122 PKTT_PASSWORD, PKT_STR,
4123 s->cur_prompt->prompts[0]->result,
4124 PKTT_OTHER, PKT_END);
4126 for (j = 0; j < i; j++) {
4128 randomstr[j] = random_byte();
4129 } while (randomstr[j] == '\0');
4131 randomstr[i] = '\0';
4132 defer_packet(ssh, SSH1_MSG_IGNORE,
4133 PKT_STR, randomstr, PKT_END);
4136 logevent("Sending password with camouflage packets");
4137 ssh_pkt_defersend(ssh);
4140 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4142 * The server can't deal with SSH1_MSG_IGNORE
4143 * but can deal with padded passwords, so we
4144 * can use the secondary defence.
4150 len = strlen(s->cur_prompt->prompts[0]->result);
4151 if (len < sizeof(string)) {
4153 strcpy(string, s->cur_prompt->prompts[0]->result);
4154 len++; /* cover the zero byte */
4155 while (len < sizeof(string)) {
4156 string[len++] = (char) random_byte();
4159 ss = s->cur_prompt->prompts[0]->result;
4161 logevent("Sending length-padded password");
4162 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4163 PKT_INT, len, PKT_DATA, ss, len,
4164 PKTT_OTHER, PKT_END);
4167 * The server is believed unable to cope with
4168 * any of our password camouflage methods.
4171 len = strlen(s->cur_prompt->prompts[0]->result);
4172 logevent("Sending unpadded password");
4173 send_packet(ssh, s->pwpkt_type,
4174 PKTT_PASSWORD, PKT_INT, len,
4175 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4176 PKTT_OTHER, PKT_END);
4179 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4180 PKT_STR, s->cur_prompt->prompts[0]->result,
4181 PKTT_OTHER, PKT_END);
4183 logevent("Sent password");
4184 free_prompts(s->cur_prompt);
4186 if (pktin->type == SSH1_SMSG_FAILURE) {
4187 if (flags & FLAG_VERBOSE)
4188 c_write_str(ssh, "Access denied\r\n");
4189 logevent("Authentication refused");
4190 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4191 bombout(("Strange packet received, type %d", pktin->type));
4197 if (s->publickey_blob) {
4198 sfree(s->publickey_blob);
4199 sfree(s->publickey_comment);
4202 logevent("Authentication successful");
4207 static void ssh_channel_try_eof(struct ssh_channel *c)
4210 assert(c->pending_eof); /* precondition for calling us */
4212 return; /* can't close: not even opened yet */
4213 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4214 return; /* can't send EOF: pending outgoing data */
4216 if (ssh->version == 1) {
4217 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4219 c->closes |= CLOSES_SENT_EOF;
4221 struct Packet *pktout;
4222 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4223 ssh2_pkt_adduint32(pktout, c->remoteid);
4224 ssh2_pkt_send(ssh, pktout);
4225 c->closes |= CLOSES_SENT_EOF;
4226 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes)) {
4228 * Also send MSG_CLOSE.
4230 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4231 ssh2_pkt_adduint32(pktout, c->remoteid);
4232 ssh2_pkt_send(ssh, pktout);
4233 c->closes |= CLOSES_SENT_CLOSE;
4236 c->pending_eof = FALSE; /* we've sent it now */
4239 void sshfwd_write_eof(struct ssh_channel *c)
4243 if (ssh->state == SSH_STATE_CLOSED)
4246 if (c->closes & CLOSES_SENT_EOF)
4249 c->pending_eof = TRUE;
4250 ssh_channel_try_eof(c);
4253 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4257 if (ssh->state == SSH_STATE_CLOSED)
4260 if (ssh->version == 1) {
4261 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4262 PKT_INT, c->remoteid,
4263 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
4264 PKTT_OTHER, PKT_END);
4266 * In SSH-1 we can return 0 here - implying that forwarded
4267 * connections are never individually throttled - because
4268 * the only circumstance that can cause throttling will be
4269 * the whole SSH connection backing up, in which case
4270 * _everything_ will be throttled as a whole.
4274 ssh2_add_channel_data(c, buf, len);
4275 return ssh2_try_send(c);
4279 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4284 if (ssh->state == SSH_STATE_CLOSED)
4287 if (ssh->version == 1) {
4288 buflimit = SSH1_BUFFER_LIMIT;
4290 buflimit = c->v.v2.locmaxwin;
4291 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4293 if (c->throttling_conn && bufsize <= buflimit) {
4294 c->throttling_conn = 0;
4295 ssh_throttle_conn(ssh, -1);
4299 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4301 struct queued_handler *qh = ssh->qhead;
4305 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4308 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4309 ssh->packet_dispatch[qh->msg1] = NULL;
4312 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4313 ssh->packet_dispatch[qh->msg2] = NULL;
4317 ssh->qhead = qh->next;
4319 if (ssh->qhead->msg1 > 0) {
4320 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
4321 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4323 if (ssh->qhead->msg2 > 0) {
4324 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
4325 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4328 ssh->qhead = ssh->qtail = NULL;
4329 ssh->packet_dispatch[pktin->type] = NULL;
4332 qh->handler(ssh, pktin, qh->ctx);
4337 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4338 chandler_fn_t handler, void *ctx)
4340 struct queued_handler *qh;
4342 qh = snew(struct queued_handler);
4345 qh->handler = handler;
4349 if (ssh->qtail == NULL) {
4353 assert(ssh->packet_dispatch[qh->msg1] == NULL);
4354 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4357 assert(ssh->packet_dispatch[qh->msg2] == NULL);
4358 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4361 ssh->qtail->next = qh;
4366 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4368 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4370 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4371 SSH2_MSG_REQUEST_SUCCESS)) {
4372 logeventf(ssh, "Remote port forwarding from %s enabled",
4375 logeventf(ssh, "Remote port forwarding from %s refused",
4378 rpf = del234(ssh->rportfwds, pf);
4380 pf->pfrec->remote = NULL;
4385 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4387 struct ssh_portfwd *epf;
4391 if (!ssh->portfwds) {
4392 ssh->portfwds = newtree234(ssh_portcmp);
4395 * Go through the existing port forwardings and tag them
4396 * with status==DESTROY. Any that we want to keep will be
4397 * re-enabled (status==KEEP) as we go through the
4398 * configuration and find out which bits are the same as
4401 struct ssh_portfwd *epf;
4403 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4404 epf->status = DESTROY;
4407 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
4409 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
4410 char *kp, *kp2, *vp, *vp2;
4411 char address_family, type;
4412 int sport,dport,sserv,dserv;
4413 char *sports, *dports, *saddr, *host;
4417 address_family = 'A';
4419 if (*kp == 'A' || *kp == '4' || *kp == '6')
4420 address_family = *kp++;
4421 if (*kp == 'L' || *kp == 'R')
4424 if ((kp2 = strchr(kp, ':')) != NULL) {
4426 * There's a colon in the middle of the source port
4427 * string, which means that the part before it is
4428 * actually a source address.
4430 saddr = dupprintf("%.*s", (int)(kp2 - kp), kp);
4436 sport = atoi(sports);
4440 sport = net_service_lookup(sports);
4442 logeventf(ssh, "Service lookup failed for source"
4443 " port \"%s\"", sports);
4447 if (type == 'L' && !strcmp(val, "D")) {
4448 /* dynamic forwarding */
4455 /* ordinary forwarding */
4457 vp2 = vp + strcspn(vp, ":");
4458 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
4462 dport = atoi(dports);
4466 dport = net_service_lookup(dports);
4468 logeventf(ssh, "Service lookup failed for destination"
4469 " port \"%s\"", dports);
4474 if (sport && dport) {
4475 /* Set up a description of the source port. */
4476 struct ssh_portfwd *pfrec, *epfrec;
4478 pfrec = snew(struct ssh_portfwd);
4480 pfrec->saddr = saddr;
4481 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4482 pfrec->sport = sport;
4483 pfrec->daddr = host;
4484 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4485 pfrec->dport = dport;
4486 pfrec->local = NULL;
4487 pfrec->remote = NULL;
4488 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4489 address_family == '6' ? ADDRTYPE_IPV6 :
4492 epfrec = add234(ssh->portfwds, pfrec);
4493 if (epfrec != pfrec) {
4494 if (epfrec->status == DESTROY) {
4496 * We already have a port forwarding up and running
4497 * with precisely these parameters. Hence, no need
4498 * to do anything; simply re-tag the existing one
4501 epfrec->status = KEEP;
4504 * Anything else indicates that there was a duplicate
4505 * in our input, which we'll silently ignore.
4507 free_portfwd(pfrec);
4509 pfrec->status = CREATE;
4518 * Now go through and destroy any port forwardings which were
4521 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4522 if (epf->status == DESTROY) {
4525 message = dupprintf("%s port forwarding from %s%s%d",
4526 epf->type == 'L' ? "local" :
4527 epf->type == 'R' ? "remote" : "dynamic",
4528 epf->saddr ? epf->saddr : "",
4529 epf->saddr ? ":" : "",
4532 if (epf->type != 'D') {
4533 char *msg2 = dupprintf("%s to %s:%d", message,
4534 epf->daddr, epf->dport);
4539 logeventf(ssh, "Cancelling %s", message);
4542 /* epf->remote or epf->local may be NULL if setting up a
4543 * forwarding failed. */
4545 struct ssh_rportfwd *rpf = epf->remote;
4546 struct Packet *pktout;
4549 * Cancel the port forwarding at the server
4552 if (ssh->version == 1) {
4554 * We cannot cancel listening ports on the
4555 * server side in SSH-1! There's no message
4556 * to support it. Instead, we simply remove
4557 * the rportfwd record from the local end
4558 * so that any connections the server tries
4559 * to make on it are rejected.
4562 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4563 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4564 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4566 ssh2_pkt_addstring(pktout, epf->saddr);
4567 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4568 /* XXX: rport_acceptall may not represent
4569 * what was used to open the original connection,
4570 * since it's reconfigurable. */
4571 ssh2_pkt_addstring(pktout, "0.0.0.0");
4573 ssh2_pkt_addstring(pktout, "127.0.0.1");
4575 ssh2_pkt_adduint32(pktout, epf->sport);
4576 ssh2_pkt_send(ssh, pktout);
4579 del234(ssh->rportfwds, rpf);
4581 } else if (epf->local) {
4582 pfd_terminate(epf->local);
4585 delpos234(ssh->portfwds, i);
4587 i--; /* so we don't skip one in the list */
4591 * And finally, set up any new port forwardings (status==CREATE).
4593 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4594 if (epf->status == CREATE) {
4595 char *sportdesc, *dportdesc;
4596 sportdesc = dupprintf("%s%s%s%s%d%s",
4597 epf->saddr ? epf->saddr : "",
4598 epf->saddr ? ":" : "",
4599 epf->sserv ? epf->sserv : "",
4600 epf->sserv ? "(" : "",
4602 epf->sserv ? ")" : "");
4603 if (epf->type == 'D') {
4606 dportdesc = dupprintf("%s:%s%s%d%s",
4608 epf->dserv ? epf->dserv : "",
4609 epf->dserv ? "(" : "",
4611 epf->dserv ? ")" : "");
4614 if (epf->type == 'L') {
4615 const char *err = pfd_addforward(epf->daddr, epf->dport,
4616 epf->saddr, epf->sport,
4619 epf->addressfamily);
4621 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4622 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4623 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4624 sportdesc, dportdesc,
4625 err ? " failed: " : "", err ? err : "");
4626 } else if (epf->type == 'D') {
4627 const char *err = pfd_addforward(NULL, -1,
4628 epf->saddr, epf->sport,
4631 epf->addressfamily);
4633 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4634 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4635 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4637 err ? " failed: " : "", err ? err : "");
4639 struct ssh_rportfwd *pf;
4642 * Ensure the remote port forwardings tree exists.
4644 if (!ssh->rportfwds) {
4645 if (ssh->version == 1)
4646 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4648 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4651 pf = snew(struct ssh_rportfwd);
4652 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4653 pf->dhost[lenof(pf->dhost)-1] = '\0';
4654 pf->dport = epf->dport;
4655 pf->sport = epf->sport;
4656 if (add234(ssh->rportfwds, pf) != pf) {
4657 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4658 epf->daddr, epf->dport);
4661 logeventf(ssh, "Requesting remote port %s"
4662 " forward to %s", sportdesc, dportdesc);
4664 pf->sportdesc = sportdesc;
4669 if (ssh->version == 1) {
4670 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4671 PKT_INT, epf->sport,
4672 PKT_STR, epf->daddr,
4673 PKT_INT, epf->dport,
4675 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4677 ssh_rportfwd_succfail, pf);
4679 struct Packet *pktout;
4680 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4681 ssh2_pkt_addstring(pktout, "tcpip-forward");
4682 ssh2_pkt_addbool(pktout, 1);/* want reply */
4684 ssh2_pkt_addstring(pktout, epf->saddr);
4685 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4686 ssh2_pkt_addstring(pktout, "0.0.0.0");
4688 ssh2_pkt_addstring(pktout, "127.0.0.1");
4690 ssh2_pkt_adduint32(pktout, epf->sport);
4691 ssh2_pkt_send(ssh, pktout);
4693 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4694 SSH2_MSG_REQUEST_FAILURE,
4695 ssh_rportfwd_succfail, pf);
4704 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4707 int stringlen, bufsize;
4709 ssh_pkt_getstring(pktin, &string, &stringlen);
4710 if (string == NULL) {
4711 bombout(("Incoming terminal data packet was badly formed"));
4715 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4717 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4718 ssh->v1_stdout_throttling = 1;
4719 ssh_throttle_conn(ssh, +1);
4723 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4725 /* Remote side is trying to open a channel to talk to our
4726 * X-Server. Give them back a local channel number. */
4727 struct ssh_channel *c;
4728 int remoteid = ssh_pkt_getuint32(pktin);
4730 logevent("Received X11 connect request");
4731 /* Refuse if X11 forwarding is disabled. */
4732 if (!ssh->X11_fwd_enabled) {
4733 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4734 PKT_INT, remoteid, PKT_END);
4735 logevent("Rejected X11 connect request");
4737 c = snew(struct ssh_channel);
4740 if (x11_init(&c->u.x11.s, ssh->x11disp, c,
4741 NULL, -1, ssh->conf) != NULL) {
4742 logevent("Opening X11 forward connection failed");
4744 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4745 PKT_INT, remoteid, PKT_END);
4748 ("Opening X11 forward connection succeeded");
4749 c->remoteid = remoteid;
4750 c->halfopen = FALSE;
4751 c->localid = alloc_channel_id(ssh);
4753 c->pending_eof = FALSE;
4754 c->throttling_conn = 0;
4755 c->type = CHAN_X11; /* identify channel type */
4756 add234(ssh->channels, c);
4757 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4758 PKT_INT, c->remoteid, PKT_INT,
4759 c->localid, PKT_END);
4760 logevent("Opened X11 forward channel");
4765 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4767 /* Remote side is trying to open a channel to talk to our
4768 * agent. Give them back a local channel number. */
4769 struct ssh_channel *c;
4770 int remoteid = ssh_pkt_getuint32(pktin);
4772 /* Refuse if agent forwarding is disabled. */
4773 if (!ssh->agentfwd_enabled) {
4774 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4775 PKT_INT, remoteid, PKT_END);
4777 c = snew(struct ssh_channel);
4779 c->remoteid = remoteid;
4780 c->halfopen = FALSE;
4781 c->localid = alloc_channel_id(ssh);
4783 c->pending_eof = FALSE;
4784 c->throttling_conn = 0;
4785 c->type = CHAN_AGENT; /* identify channel type */
4786 c->u.a.lensofar = 0;
4787 c->u.a.message = NULL;
4788 add234(ssh->channels, c);
4789 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4790 PKT_INT, c->remoteid, PKT_INT, c->localid,
4795 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4797 /* Remote side is trying to open a channel to talk to a
4798 * forwarded port. Give them back a local channel number. */
4799 struct ssh_channel *c;
4800 struct ssh_rportfwd pf, *pfp;
4805 c = snew(struct ssh_channel);
4808 remoteid = ssh_pkt_getuint32(pktin);
4809 ssh_pkt_getstring(pktin, &host, &hostsize);
4810 port = ssh_pkt_getuint32(pktin);
4812 if (hostsize >= lenof(pf.dhost))
4813 hostsize = lenof(pf.dhost)-1;
4814 memcpy(pf.dhost, host, hostsize);
4815 pf.dhost[hostsize] = '\0';
4817 pfp = find234(ssh->rportfwds, &pf, NULL);
4820 logeventf(ssh, "Rejected remote port open request for %s:%d",
4822 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4823 PKT_INT, remoteid, PKT_END);
4825 logeventf(ssh, "Received remote port open request for %s:%d",
4827 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4828 c, ssh->conf, pfp->pfrec->addressfamily);
4830 logeventf(ssh, "Port open failed: %s", e);
4832 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4833 PKT_INT, remoteid, PKT_END);
4835 c->remoteid = remoteid;
4836 c->halfopen = FALSE;
4837 c->localid = alloc_channel_id(ssh);
4839 c->pending_eof = FALSE;
4840 c->throttling_conn = 0;
4841 c->type = CHAN_SOCKDATA; /* identify channel type */
4842 add234(ssh->channels, c);
4843 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4844 PKT_INT, c->remoteid, PKT_INT,
4845 c->localid, PKT_END);
4846 logevent("Forwarded port opened successfully");
4851 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4853 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4854 unsigned int localid = ssh_pkt_getuint32(pktin);
4855 struct ssh_channel *c;
4857 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4858 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4859 c->remoteid = localid;
4860 c->halfopen = FALSE;
4861 c->type = CHAN_SOCKDATA;
4862 c->throttling_conn = 0;
4863 pfd_confirm(c->u.pfd.s);
4866 if (c && c->pending_eof) {
4868 * We have a pending close on this channel,
4869 * which we decided on before the server acked
4870 * the channel open. So now we know the
4871 * remoteid, we can close it again.
4873 ssh_channel_try_eof(c);
4877 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4879 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4880 struct ssh_channel *c;
4882 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4883 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4884 logevent("Forwarded connection refused by server");
4885 pfd_close(c->u.pfd.s);
4886 del234(ssh->channels, c);
4891 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4893 /* Remote side closes a channel. */
4894 unsigned i = ssh_pkt_getuint32(pktin);
4895 struct ssh_channel *c;
4896 c = find234(ssh->channels, &i, ssh_channelfind);
4897 if (c && !c->halfopen) {
4899 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
4900 !(c->closes & CLOSES_RCVD_EOF)) {
4902 * Received CHANNEL_CLOSE, which we translate into
4905 int send_close = FALSE;
4907 c->closes |= CLOSES_RCVD_EOF;
4912 x11_send_eof(c->u.x11.s);
4917 x11_send_eof(c->u.pfd.s);
4924 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
4925 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4927 c->closes |= CLOSES_SENT_EOF;
4931 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
4932 !(c->closes & CLOSES_RCVD_CLOSE)) {
4934 if (!(c->closes & CLOSES_SENT_EOF)) {
4935 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
4936 " for which we never sent CHANNEL_CLOSE\n", i));
4939 c->closes |= CLOSES_RCVD_CLOSE;
4942 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
4943 !(c->closes & CLOSES_SENT_CLOSE)) {
4944 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
4945 PKT_INT, c->remoteid, PKT_END);
4946 c->closes |= CLOSES_SENT_CLOSE;
4949 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
4950 ssh_channel_destroy(c);
4952 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4953 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4954 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4959 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4961 /* Data sent down one of our channels. */
4962 int i = ssh_pkt_getuint32(pktin);
4965 struct ssh_channel *c;
4967 ssh_pkt_getstring(pktin, &p, &len);
4969 c = find234(ssh->channels, &i, ssh_channelfind);
4974 bufsize = x11_send(c->u.x11.s, p, len);
4977 bufsize = pfd_send(c->u.pfd.s, p, len);
4980 /* Data for an agent message. Buffer it. */
4982 if (c->u.a.lensofar < 4) {
4983 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
4984 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4988 c->u.a.lensofar += l;
4990 if (c->u.a.lensofar == 4) {
4992 4 + GET_32BIT(c->u.a.msglen);
4993 c->u.a.message = snewn(c->u.a.totallen,
4995 memcpy(c->u.a.message, c->u.a.msglen, 4);
4997 if (c->u.a.lensofar >= 4 && len > 0) {
4999 min(c->u.a.totallen - c->u.a.lensofar,
5001 memcpy(c->u.a.message + c->u.a.lensofar, p,
5005 c->u.a.lensofar += l;
5007 if (c->u.a.lensofar == c->u.a.totallen) {
5010 if (agent_query(c->u.a.message,
5013 ssh_agentf_callback, c))
5014 ssh_agentf_callback(c, reply, replylen);
5015 sfree(c->u.a.message);
5016 c->u.a.lensofar = 0;
5019 bufsize = 0; /* agent channels never back up */
5022 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5023 c->throttling_conn = 1;
5024 ssh_throttle_conn(ssh, +1);
5029 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5031 ssh->exitcode = ssh_pkt_getuint32(pktin);
5032 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5033 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5035 * In case `helpful' firewalls or proxies tack
5036 * extra human-readable text on the end of the
5037 * session which we might mistake for another
5038 * encrypted packet, we close the session once
5039 * we've sent EXIT_CONFIRMATION.
5041 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5044 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5045 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5047 struct Packet *pktout = (struct Packet *)data;
5049 unsigned int arg = 0;
5050 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5051 if (i == lenof(ssh_ttymodes)) return;
5052 switch (ssh_ttymodes[i].type) {
5054 arg = ssh_tty_parse_specchar(val);
5057 arg = ssh_tty_parse_boolean(val);
5060 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5061 ssh2_pkt_addbyte(pktout, arg);
5065 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5066 struct Packet *pktin)
5068 crBegin(ssh->do_ssh1_connection_crstate);
5070 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5071 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5072 ssh1_smsg_stdout_stderr_data;
5074 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5075 ssh1_msg_channel_open_confirmation;
5076 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5077 ssh1_msg_channel_open_failure;
5078 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5079 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5080 ssh1_msg_channel_close;
5081 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5082 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5084 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
5085 logevent("Requesting agent forwarding");
5086 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5090 if (pktin->type != SSH1_SMSG_SUCCESS
5091 && pktin->type != SSH1_SMSG_FAILURE) {
5092 bombout(("Protocol confusion"));
5094 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5095 logevent("Agent forwarding refused");
5097 logevent("Agent forwarding enabled");
5098 ssh->agentfwd_enabled = TRUE;
5099 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5103 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
5104 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5105 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
5106 logevent("Requesting X11 forwarding");
5108 * Note that while we blank the X authentication data here, we don't
5109 * take any special action to blank the start of an X11 channel,
5110 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
5111 * without having session blanking enabled is likely to leak your
5112 * cookie into the log.
5114 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5115 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5116 PKT_STR, ssh->x11disp->remoteauthprotoname,
5118 PKT_STR, ssh->x11disp->remoteauthdatastring,
5120 PKT_INT, ssh->x11disp->screennum,
5123 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5124 PKT_STR, ssh->x11disp->remoteauthprotoname,
5126 PKT_STR, ssh->x11disp->remoteauthdatastring,
5133 if (pktin->type != SSH1_SMSG_SUCCESS
5134 && pktin->type != SSH1_SMSG_FAILURE) {
5135 bombout(("Protocol confusion"));
5137 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5138 logevent("X11 forwarding refused");
5140 logevent("X11 forwarding enabled");
5141 ssh->X11_fwd_enabled = TRUE;
5142 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5146 ssh_setup_portfwd(ssh, ssh->conf);
5147 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5149 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5151 /* Unpick the terminal-speed string. */
5152 /* XXX perhaps we should allow no speeds to be sent. */
5153 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5154 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5155 /* Send the pty request. */
5156 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5157 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5158 ssh_pkt_adduint32(pkt, ssh->term_height);
5159 ssh_pkt_adduint32(pkt, ssh->term_width);
5160 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5161 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5162 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5163 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5164 ssh_pkt_adduint32(pkt, ssh->ispeed);
5165 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5166 ssh_pkt_adduint32(pkt, ssh->ospeed);
5167 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5169 ssh->state = SSH_STATE_INTERMED;
5173 if (pktin->type != SSH1_SMSG_SUCCESS
5174 && pktin->type != SSH1_SMSG_FAILURE) {
5175 bombout(("Protocol confusion"));
5177 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5178 c_write_str(ssh, "Server refused to allocate pty\r\n");
5179 ssh->editing = ssh->echoing = 1;
5181 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5182 ssh->ospeed, ssh->ispeed);
5183 ssh->got_pty = TRUE;
5186 ssh->editing = ssh->echoing = 1;
5189 if (conf_get_int(ssh->conf, CONF_compression)) {
5190 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5194 if (pktin->type != SSH1_SMSG_SUCCESS
5195 && pktin->type != SSH1_SMSG_FAILURE) {
5196 bombout(("Protocol confusion"));
5198 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5199 c_write_str(ssh, "Server refused to compress\r\n");
5201 logevent("Started compression");
5202 ssh->v1_compressing = TRUE;
5203 ssh->cs_comp_ctx = zlib_compress_init();
5204 logevent("Initialised zlib (RFC1950) compression");
5205 ssh->sc_comp_ctx = zlib_decompress_init();
5206 logevent("Initialised zlib (RFC1950) decompression");
5210 * Start the shell or command.
5212 * Special case: if the first-choice command is an SSH-2
5213 * subsystem (hence not usable here) and the second choice
5214 * exists, we fall straight back to that.
5217 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5219 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5220 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5221 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5222 ssh->fallback_cmd = TRUE;
5225 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5227 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5228 logevent("Started session");
5231 ssh->state = SSH_STATE_SESSION;
5232 if (ssh->size_needed)
5233 ssh_size(ssh, ssh->term_width, ssh->term_height);
5234 if (ssh->eof_needed)
5235 ssh_special(ssh, TS_EOF);
5238 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5240 ssh->channels = newtree234(ssh_channelcmp);
5244 * By this point, most incoming packets are already being
5245 * handled by the dispatch table, and we need only pay
5246 * attention to the unusual ones.
5251 if (pktin->type == SSH1_SMSG_SUCCESS) {
5252 /* may be from EXEC_SHELL on some servers */
5253 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5254 /* may be from EXEC_SHELL on some servers
5255 * if no pty is available or in other odd cases. Ignore */
5257 bombout(("Strange packet received: type %d", pktin->type));
5262 int len = min(inlen, 512);
5263 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5264 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
5265 PKTT_OTHER, PKT_END);
5276 * Handle the top-level SSH-2 protocol.
5278 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5283 ssh_pkt_getstring(pktin, &msg, &msglen);
5284 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5287 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5289 /* log reason code in disconnect message */
5293 ssh_pkt_getstring(pktin, &msg, &msglen);
5294 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5297 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5299 /* Do nothing, because we're ignoring it! Duhh. */
5302 static void ssh1_protocol_setup(Ssh ssh)
5307 * Most messages are handled by the coroutines.
5309 for (i = 0; i < 256; i++)
5310 ssh->packet_dispatch[i] = NULL;
5313 * These special message types we install handlers for.
5315 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5316 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5317 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5320 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5321 struct Packet *pktin)
5323 unsigned char *in=(unsigned char*)vin;
5324 if (ssh->state == SSH_STATE_CLOSED)
5327 if (pktin && ssh->packet_dispatch[pktin->type]) {
5328 ssh->packet_dispatch[pktin->type](ssh, pktin);
5332 if (!ssh->protocol_initial_phase_done) {
5333 if (do_ssh1_login(ssh, in, inlen, pktin))
5334 ssh->protocol_initial_phase_done = TRUE;
5339 do_ssh1_connection(ssh, in, inlen, pktin);
5343 * Utility routine for decoding comma-separated strings in KEXINIT.
5345 static int in_commasep_string(char *needle, char *haystack, int haylen)
5348 if (!needle || !haystack) /* protect against null pointers */
5350 needlen = strlen(needle);
5353 * Is it at the start of the string?
5355 if (haylen >= needlen && /* haystack is long enough */
5356 !memcmp(needle, haystack, needlen) && /* initial match */
5357 (haylen == needlen || haystack[needlen] == ',')
5358 /* either , or EOS follows */
5362 * If not, search for the next comma and resume after that.
5363 * If no comma found, terminate.
5365 while (haylen > 0 && *haystack != ',')
5366 haylen--, haystack++;
5369 haylen--, haystack++; /* skip over comma itself */
5374 * Similar routine for checking whether we have the first string in a list.
5376 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5379 if (!needle || !haystack) /* protect against null pointers */
5381 needlen = strlen(needle);
5383 * Is it at the start of the string?
5385 if (haylen >= needlen && /* haystack is long enough */
5386 !memcmp(needle, haystack, needlen) && /* initial match */
5387 (haylen == needlen || haystack[needlen] == ',')
5388 /* either , or EOS follows */
5396 * SSH-2 key creation method.
5397 * (Currently assumes 2 lots of any hash are sufficient to generate
5398 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5400 #define SSH2_MKKEY_ITERS (2)
5401 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5402 unsigned char *keyspace)
5404 const struct ssh_hash *h = ssh->kex->hash;
5406 /* First hlen bytes. */
5408 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5409 hash_mpint(h, s, K);
5410 h->bytes(s, H, h->hlen);
5411 h->bytes(s, &chr, 1);
5412 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5413 h->final(s, keyspace);
5414 /* Next hlen bytes. */
5416 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5417 hash_mpint(h, s, K);
5418 h->bytes(s, H, h->hlen);
5419 h->bytes(s, keyspace, h->hlen);
5420 h->final(s, keyspace + h->hlen);
5424 * Handle the SSH-2 transport layer.
5426 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5427 struct Packet *pktin)
5429 unsigned char *in = (unsigned char *)vin;
5430 struct do_ssh2_transport_state {
5431 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5432 Bignum p, g, e, f, K;
5435 int kex_init_value, kex_reply_value;
5436 const struct ssh_mac **maclist;
5438 const struct ssh2_cipher *cscipher_tobe;
5439 const struct ssh2_cipher *sccipher_tobe;
5440 const struct ssh_mac *csmac_tobe;
5441 const struct ssh_mac *scmac_tobe;
5442 const struct ssh_compress *cscomp_tobe;
5443 const struct ssh_compress *sccomp_tobe;
5444 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5445 int hostkeylen, siglen, rsakeylen;
5446 void *hkey; /* actual host key */
5447 void *rsakey; /* for RSA kex */
5448 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5449 int n_preferred_kex;
5450 const struct ssh_kexes *preferred_kex[KEX_MAX];
5451 int n_preferred_ciphers;
5452 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5453 const struct ssh_compress *preferred_comp;
5454 int userauth_succeeded; /* for delayed compression */
5455 int pending_compression;
5456 int got_session_id, activated_authconn;
5457 struct Packet *pktout;
5462 crState(do_ssh2_transport_state);
5464 crBegin(ssh->do_ssh2_transport_crstate);
5466 s->cscipher_tobe = s->sccipher_tobe = NULL;
5467 s->csmac_tobe = s->scmac_tobe = NULL;
5468 s->cscomp_tobe = s->sccomp_tobe = NULL;
5470 s->got_session_id = s->activated_authconn = FALSE;
5471 s->userauth_succeeded = FALSE;
5472 s->pending_compression = FALSE;
5475 * Be prepared to work around the buggy MAC problem.
5477 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5478 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5480 s->maclist = macs, s->nmacs = lenof(macs);
5483 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5485 int i, j, commalist_started;
5488 * Set up the preferred key exchange. (NULL => warn below here)
5490 s->n_preferred_kex = 0;
5491 for (i = 0; i < KEX_MAX; i++) {
5492 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
5494 s->preferred_kex[s->n_preferred_kex++] =
5495 &ssh_diffiehellman_gex;
5498 s->preferred_kex[s->n_preferred_kex++] =
5499 &ssh_diffiehellman_group14;
5502 s->preferred_kex[s->n_preferred_kex++] =
5503 &ssh_diffiehellman_group1;
5506 s->preferred_kex[s->n_preferred_kex++] =
5510 /* Flag for later. Don't bother if it's the last in
5512 if (i < KEX_MAX - 1) {
5513 s->preferred_kex[s->n_preferred_kex++] = NULL;
5520 * Set up the preferred ciphers. (NULL => warn below here)
5522 s->n_preferred_ciphers = 0;
5523 for (i = 0; i < CIPHER_MAX; i++) {
5524 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
5525 case CIPHER_BLOWFISH:
5526 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5529 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
5530 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5534 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5537 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5539 case CIPHER_ARCFOUR:
5540 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5543 /* Flag for later. Don't bother if it's the last in
5545 if (i < CIPHER_MAX - 1) {
5546 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5553 * Set up preferred compression.
5555 if (conf_get_int(ssh->conf, CONF_compression))
5556 s->preferred_comp = &ssh_zlib;
5558 s->preferred_comp = &ssh_comp_none;
5561 * Enable queueing of outgoing auth- or connection-layer
5562 * packets while we are in the middle of a key exchange.
5564 ssh->queueing = TRUE;
5567 * Flag that KEX is in progress.
5569 ssh->kex_in_progress = TRUE;
5572 * Construct and send our key exchange packet.
5574 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5575 for (i = 0; i < 16; i++)
5576 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5577 /* List key exchange algorithms. */
5578 ssh2_pkt_addstring_start(s->pktout);
5579 commalist_started = 0;
5580 for (i = 0; i < s->n_preferred_kex; i++) {
5581 const struct ssh_kexes *k = s->preferred_kex[i];
5582 if (!k) continue; /* warning flag */
5583 for (j = 0; j < k->nkexes; j++) {
5584 if (commalist_started)
5585 ssh2_pkt_addstring_str(s->pktout, ",");
5586 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5587 commalist_started = 1;
5590 /* List server host key algorithms. */
5591 ssh2_pkt_addstring_start(s->pktout);
5592 for (i = 0; i < lenof(hostkey_algs); i++) {
5593 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5594 if (i < lenof(hostkey_algs) - 1)
5595 ssh2_pkt_addstring_str(s->pktout, ",");
5597 /* List client->server encryption algorithms. */
5598 ssh2_pkt_addstring_start(s->pktout);
5599 commalist_started = 0;
5600 for (i = 0; i < s->n_preferred_ciphers; i++) {
5601 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5602 if (!c) continue; /* warning flag */
5603 for (j = 0; j < c->nciphers; j++) {
5604 if (commalist_started)
5605 ssh2_pkt_addstring_str(s->pktout, ",");
5606 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5607 commalist_started = 1;
5610 /* List server->client encryption algorithms. */
5611 ssh2_pkt_addstring_start(s->pktout);
5612 commalist_started = 0;
5613 for (i = 0; i < s->n_preferred_ciphers; i++) {
5614 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5615 if (!c) continue; /* warning flag */
5616 for (j = 0; j < c->nciphers; j++) {
5617 if (commalist_started)
5618 ssh2_pkt_addstring_str(s->pktout, ",");
5619 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5620 commalist_started = 1;
5623 /* List client->server MAC algorithms. */
5624 ssh2_pkt_addstring_start(s->pktout);
5625 for (i = 0; i < s->nmacs; i++) {
5626 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5627 if (i < s->nmacs - 1)
5628 ssh2_pkt_addstring_str(s->pktout, ",");
5630 /* List server->client MAC algorithms. */
5631 ssh2_pkt_addstring_start(s->pktout);
5632 for (i = 0; i < s->nmacs; i++) {
5633 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5634 if (i < s->nmacs - 1)
5635 ssh2_pkt_addstring_str(s->pktout, ",");
5637 /* List client->server compression algorithms,
5638 * then server->client compression algorithms. (We use the
5639 * same set twice.) */
5640 for (j = 0; j < 2; j++) {
5641 ssh2_pkt_addstring_start(s->pktout);
5642 assert(lenof(compressions) > 1);
5643 /* Prefer non-delayed versions */
5644 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5645 /* We don't even list delayed versions of algorithms until
5646 * they're allowed to be used, to avoid a race. See the end of
5648 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
5649 ssh2_pkt_addstring_str(s->pktout, ",");
5650 ssh2_pkt_addstring_str(s->pktout,
5651 s->preferred_comp->delayed_name);
5653 for (i = 0; i < lenof(compressions); i++) {
5654 const struct ssh_compress *c = compressions[i];
5655 if (c != s->preferred_comp) {
5656 ssh2_pkt_addstring_str(s->pktout, ",");
5657 ssh2_pkt_addstring_str(s->pktout, c->name);
5658 if (s->userauth_succeeded && c->delayed_name) {
5659 ssh2_pkt_addstring_str(s->pktout, ",");
5660 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
5665 /* List client->server languages. Empty list. */
5666 ssh2_pkt_addstring_start(s->pktout);
5667 /* List server->client languages. Empty list. */
5668 ssh2_pkt_addstring_start(s->pktout);
5669 /* First KEX packet does _not_ follow, because we're not that brave. */
5670 ssh2_pkt_addbool(s->pktout, FALSE);
5672 ssh2_pkt_adduint32(s->pktout, 0);
5675 s->our_kexinitlen = s->pktout->length - 5;
5676 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5677 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5679 ssh2_pkt_send_noqueue(ssh, s->pktout);
5685 * Now examine the other side's KEXINIT to see what we're up
5689 char *str, *preferred;
5692 if (pktin->type != SSH2_MSG_KEXINIT) {
5693 bombout(("expected key exchange packet from server"));
5697 ssh->hostkey = NULL;
5698 s->cscipher_tobe = NULL;
5699 s->sccipher_tobe = NULL;
5700 s->csmac_tobe = NULL;
5701 s->scmac_tobe = NULL;
5702 s->cscomp_tobe = NULL;
5703 s->sccomp_tobe = NULL;
5704 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5706 pktin->savedpos += 16; /* skip garbage cookie */
5707 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5710 for (i = 0; i < s->n_preferred_kex; i++) {
5711 const struct ssh_kexes *k = s->preferred_kex[i];
5715 for (j = 0; j < k->nkexes; j++) {
5716 if (!preferred) preferred = k->list[j]->name;
5717 if (in_commasep_string(k->list[j]->name, str, len)) {
5718 ssh->kex = k->list[j];
5727 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5728 str ? str : "(null)"));
5732 * Note that the server's guess is considered wrong if it doesn't match
5733 * the first algorithm in our list, even if it's still the algorithm
5736 s->guessok = first_in_commasep_string(preferred, str, len);
5737 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5738 for (i = 0; i < lenof(hostkey_algs); i++) {
5739 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5740 ssh->hostkey = hostkey_algs[i];
5744 s->guessok = s->guessok &&
5745 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5746 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5747 for (i = 0; i < s->n_preferred_ciphers; i++) {
5748 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5750 s->warn_cscipher = TRUE;
5752 for (j = 0; j < c->nciphers; j++) {
5753 if (in_commasep_string(c->list[j]->name, str, len)) {
5754 s->cscipher_tobe = c->list[j];
5759 if (s->cscipher_tobe)
5762 if (!s->cscipher_tobe) {
5763 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5764 str ? str : "(null)"));
5768 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5769 for (i = 0; i < s->n_preferred_ciphers; i++) {
5770 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5772 s->warn_sccipher = TRUE;
5774 for (j = 0; j < c->nciphers; j++) {
5775 if (in_commasep_string(c->list[j]->name, str, len)) {
5776 s->sccipher_tobe = c->list[j];
5781 if (s->sccipher_tobe)
5784 if (!s->sccipher_tobe) {
5785 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5786 str ? str : "(null)"));
5790 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5791 for (i = 0; i < s->nmacs; i++) {
5792 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5793 s->csmac_tobe = s->maclist[i];
5797 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5798 for (i = 0; i < s->nmacs; i++) {
5799 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5800 s->scmac_tobe = s->maclist[i];
5804 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5805 for (i = 0; i < lenof(compressions) + 1; i++) {
5806 const struct ssh_compress *c =
5807 i == 0 ? s->preferred_comp : compressions[i - 1];
5808 if (in_commasep_string(c->name, str, len)) {
5811 } else if (in_commasep_string(c->delayed_name, str, len)) {
5812 if (s->userauth_succeeded) {
5816 s->pending_compression = TRUE; /* try this later */
5820 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5821 for (i = 0; i < lenof(compressions) + 1; i++) {
5822 const struct ssh_compress *c =
5823 i == 0 ? s->preferred_comp : compressions[i - 1];
5824 if (in_commasep_string(c->name, str, len)) {
5827 } else if (in_commasep_string(c->delayed_name, str, len)) {
5828 if (s->userauth_succeeded) {
5832 s->pending_compression = TRUE; /* try this later */
5836 if (s->pending_compression) {
5837 logevent("Server supports delayed compression; "
5838 "will try this later");
5840 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5841 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5842 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5845 ssh_set_frozen(ssh, 1);
5846 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5848 ssh_dialog_callback, ssh);
5849 if (s->dlgret < 0) {
5853 bombout(("Unexpected data from server while"
5854 " waiting for user response"));
5857 } while (pktin || inlen > 0);
5858 s->dlgret = ssh->user_response;
5860 ssh_set_frozen(ssh, 0);
5861 if (s->dlgret == 0) {
5862 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5868 if (s->warn_cscipher) {
5869 ssh_set_frozen(ssh, 1);
5870 s->dlgret = askalg(ssh->frontend,
5871 "client-to-server cipher",
5872 s->cscipher_tobe->name,
5873 ssh_dialog_callback, ssh);
5874 if (s->dlgret < 0) {
5878 bombout(("Unexpected data from server while"
5879 " waiting for user response"));
5882 } while (pktin || inlen > 0);
5883 s->dlgret = ssh->user_response;
5885 ssh_set_frozen(ssh, 0);
5886 if (s->dlgret == 0) {
5887 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5893 if (s->warn_sccipher) {
5894 ssh_set_frozen(ssh, 1);
5895 s->dlgret = askalg(ssh->frontend,
5896 "server-to-client cipher",
5897 s->sccipher_tobe->name,
5898 ssh_dialog_callback, ssh);
5899 if (s->dlgret < 0) {
5903 bombout(("Unexpected data from server while"
5904 " waiting for user response"));
5907 } while (pktin || inlen > 0);
5908 s->dlgret = ssh->user_response;
5910 ssh_set_frozen(ssh, 0);
5911 if (s->dlgret == 0) {
5912 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5918 ssh->exhash = ssh->kex->hash->init();
5919 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5920 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5921 hash_string(ssh->kex->hash, ssh->exhash,
5922 s->our_kexinit, s->our_kexinitlen);
5923 sfree(s->our_kexinit);
5924 if (pktin->length > 5)
5925 hash_string(ssh->kex->hash, ssh->exhash,
5926 pktin->data + 5, pktin->length - 5);
5928 if (s->ignorepkt) /* first_kex_packet_follows */
5929 crWaitUntil(pktin); /* Ignore packet */
5932 if (ssh->kex->main_type == KEXTYPE_DH) {
5934 * Work out the number of bits of key we will need from the
5935 * key exchange. We start with the maximum key length of
5941 csbits = s->cscipher_tobe->keylen;
5942 scbits = s->sccipher_tobe->keylen;
5943 s->nbits = (csbits > scbits ? csbits : scbits);
5945 /* The keys only have hlen-bit entropy, since they're based on
5946 * a hash. So cap the key size at hlen bits. */
5947 if (s->nbits > ssh->kex->hash->hlen * 8)
5948 s->nbits = ssh->kex->hash->hlen * 8;
5951 * If we're doing Diffie-Hellman group exchange, start by
5952 * requesting a group.
5954 if (!ssh->kex->pdata) {
5955 logevent("Doing Diffie-Hellman group exchange");
5956 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
5958 * Work out how big a DH group we will need to allow that
5961 s->pbits = 512 << ((s->nbits - 1) / 64);
5962 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5963 ssh2_pkt_adduint32(s->pktout, s->pbits);
5964 ssh2_pkt_send_noqueue(ssh, s->pktout);
5967 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5968 bombout(("expected key exchange group packet from server"));
5971 s->p = ssh2_pkt_getmp(pktin);
5972 s->g = ssh2_pkt_getmp(pktin);
5973 if (!s->p || !s->g) {
5974 bombout(("unable to read mp-ints from incoming group packet"));
5977 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5978 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5979 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5981 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
5982 ssh->kex_ctx = dh_setup_group(ssh->kex);
5983 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5984 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5985 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5986 ssh->kex->groupname);
5989 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
5990 ssh->kex->hash->text_name);
5992 * Now generate and send e for Diffie-Hellman.
5994 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
5995 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
5996 s->pktout = ssh2_pkt_init(s->kex_init_value);
5997 ssh2_pkt_addmp(s->pktout, s->e);
5998 ssh2_pkt_send_noqueue(ssh, s->pktout);
6000 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6002 if (pktin->type != s->kex_reply_value) {
6003 bombout(("expected key exchange reply packet from server"));
6006 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6007 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6008 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6009 s->f = ssh2_pkt_getmp(pktin);
6011 bombout(("unable to parse key exchange reply packet"));
6014 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6016 s->K = dh_find_K(ssh->kex_ctx, s->f);
6018 /* We assume everything from now on will be quick, and it might
6019 * involve user interaction. */
6020 set_busy_status(ssh->frontend, BUSY_NOT);
6022 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6023 if (!ssh->kex->pdata) {
6024 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6025 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6026 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6028 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6029 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6031 dh_cleanup(ssh->kex_ctx);
6033 if (!ssh->kex->pdata) {
6038 logeventf(ssh, "Doing RSA key exchange with hash %s",
6039 ssh->kex->hash->text_name);
6040 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6042 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6046 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6047 bombout(("expected RSA public key packet from server"));
6051 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6052 hash_string(ssh->kex->hash, ssh->exhash,
6053 s->hostkeydata, s->hostkeylen);
6054 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6058 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6059 s->rsakeydata = snewn(s->rsakeylen, char);
6060 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6063 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6065 sfree(s->rsakeydata);
6066 bombout(("unable to parse RSA public key from server"));
6070 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6073 * Next, set up a shared secret K, of precisely KLEN -
6074 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6075 * RSA key modulus and HLEN is the bit length of the hash
6079 int klen = ssh_rsakex_klen(s->rsakey);
6080 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6082 unsigned char *kstr1, *kstr2, *outstr;
6083 int kstr1len, kstr2len, outstrlen;
6085 s->K = bn_power_2(nbits - 1);
6087 for (i = 0; i < nbits; i++) {
6089 byte = random_byte();
6091 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6095 * Encode this as an mpint.
6097 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6098 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6099 PUT_32BIT(kstr2, kstr1len);
6100 memcpy(kstr2 + 4, kstr1, kstr1len);
6103 * Encrypt it with the given RSA key.
6105 outstrlen = (klen + 7) / 8;
6106 outstr = snewn(outstrlen, unsigned char);
6107 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6108 outstr, outstrlen, s->rsakey);
6111 * And send it off in a return packet.
6113 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6114 ssh2_pkt_addstring_start(s->pktout);
6115 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6116 ssh2_pkt_send_noqueue(ssh, s->pktout);
6118 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6125 ssh_rsakex_freekey(s->rsakey);
6128 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6129 sfree(s->rsakeydata);
6130 bombout(("expected signature packet from server"));
6134 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6136 sfree(s->rsakeydata);
6139 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6140 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6141 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6143 ssh->kex_ctx = NULL;
6146 debug(("Exchange hash is:\n"));
6147 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6151 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6152 (char *)s->exchange_hash,
6153 ssh->kex->hash->hlen)) {
6154 bombout(("Server's host key did not match the signature supplied"));
6159 * Authenticate remote host: verify host key. (We've already
6160 * checked the signature of the exchange hash.)
6162 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6163 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6164 ssh_set_frozen(ssh, 1);
6165 s->dlgret = verify_ssh_host_key(ssh->frontend,
6166 ssh->savedhost, ssh->savedport,
6167 ssh->hostkey->keytype, s->keystr,
6169 ssh_dialog_callback, ssh);
6170 if (s->dlgret < 0) {
6174 bombout(("Unexpected data from server while waiting"
6175 " for user host key response"));
6178 } while (pktin || inlen > 0);
6179 s->dlgret = ssh->user_response;
6181 ssh_set_frozen(ssh, 0);
6182 if (s->dlgret == 0) {
6183 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6187 if (!s->got_session_id) { /* don't bother logging this in rekeys */
6188 logevent("Host key fingerprint is:");
6189 logevent(s->fingerprint);
6191 sfree(s->fingerprint);
6193 ssh->hostkey->freekey(s->hkey);
6196 * The exchange hash from the very first key exchange is also
6197 * the session id, used in session key construction and
6200 if (!s->got_session_id) {
6201 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6202 memcpy(ssh->v2_session_id, s->exchange_hash,
6203 sizeof(s->exchange_hash));
6204 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6205 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6206 s->got_session_id = TRUE;
6210 * Send SSH2_MSG_NEWKEYS.
6212 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6213 ssh2_pkt_send_noqueue(ssh, s->pktout);
6214 ssh->outgoing_data_size = 0; /* start counting from here */
6217 * We've sent client NEWKEYS, so create and initialise
6218 * client-to-server session keys.
6220 if (ssh->cs_cipher_ctx)
6221 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6222 ssh->cscipher = s->cscipher_tobe;
6223 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6225 if (ssh->cs_mac_ctx)
6226 ssh->csmac->free_context(ssh->cs_mac_ctx);
6227 ssh->csmac = s->csmac_tobe;
6228 ssh->cs_mac_ctx = ssh->csmac->make_context();
6230 if (ssh->cs_comp_ctx)
6231 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6232 ssh->cscomp = s->cscomp_tobe;
6233 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6236 * Set IVs on client-to-server keys. Here we use the exchange
6237 * hash from the _first_ key exchange.
6240 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6241 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6242 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6243 assert((ssh->cscipher->keylen+7) / 8 <=
6244 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6245 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6246 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6247 assert(ssh->cscipher->blksize <=
6248 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6249 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6250 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6251 assert(ssh->csmac->len <=
6252 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6253 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6254 memset(keyspace, 0, sizeof(keyspace));
6257 logeventf(ssh, "Initialised %.200s client->server encryption",
6258 ssh->cscipher->text_name);
6259 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6260 ssh->csmac->text_name);
6261 if (ssh->cscomp->text_name)
6262 logeventf(ssh, "Initialised %s compression",
6263 ssh->cscomp->text_name);
6266 * Now our end of the key exchange is complete, we can send all
6267 * our queued higher-layer packets.
6269 ssh->queueing = FALSE;
6270 ssh2_pkt_queuesend(ssh);
6273 * Expect SSH2_MSG_NEWKEYS from server.
6276 if (pktin->type != SSH2_MSG_NEWKEYS) {
6277 bombout(("expected new-keys packet from server"));
6280 ssh->incoming_data_size = 0; /* start counting from here */
6283 * We've seen server NEWKEYS, so create and initialise
6284 * server-to-client session keys.
6286 if (ssh->sc_cipher_ctx)
6287 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6288 ssh->sccipher = s->sccipher_tobe;
6289 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6291 if (ssh->sc_mac_ctx)
6292 ssh->scmac->free_context(ssh->sc_mac_ctx);
6293 ssh->scmac = s->scmac_tobe;
6294 ssh->sc_mac_ctx = ssh->scmac->make_context();
6296 if (ssh->sc_comp_ctx)
6297 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6298 ssh->sccomp = s->sccomp_tobe;
6299 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6302 * Set IVs on server-to-client keys. Here we use the exchange
6303 * hash from the _first_ key exchange.
6306 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6307 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6308 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6309 assert((ssh->sccipher->keylen+7) / 8 <=
6310 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6311 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6312 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6313 assert(ssh->sccipher->blksize <=
6314 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6315 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6316 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6317 assert(ssh->scmac->len <=
6318 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6319 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6320 memset(keyspace, 0, sizeof(keyspace));
6322 logeventf(ssh, "Initialised %.200s server->client encryption",
6323 ssh->sccipher->text_name);
6324 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6325 ssh->scmac->text_name);
6326 if (ssh->sccomp->text_name)
6327 logeventf(ssh, "Initialised %s decompression",
6328 ssh->sccomp->text_name);
6331 * Free shared secret.
6336 * Key exchange is over. Loop straight back round if we have a
6337 * deferred rekey reason.
6339 if (ssh->deferred_rekey_reason) {
6340 logevent(ssh->deferred_rekey_reason);
6342 ssh->deferred_rekey_reason = NULL;
6343 goto begin_key_exchange;
6347 * Otherwise, schedule a timer for our next rekey.
6349 ssh->kex_in_progress = FALSE;
6350 ssh->last_rekey = GETTICKCOUNT();
6351 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
6352 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6356 * If this is the first key exchange phase, we must pass the
6357 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
6358 * wants to see it but because it will need time to initialise
6359 * itself before it sees an actual packet. In subsequent key
6360 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
6361 * it would only confuse the layer above.
6363 if (s->activated_authconn) {
6366 s->activated_authconn = TRUE;
6369 * Now we're encrypting. Begin returning 1 to the protocol main
6370 * function so that other things can run on top of the
6371 * transport. If we ever see a KEXINIT, we must go back to the
6374 * We _also_ go back to the start if we see pktin==NULL and
6375 * inlen negative, because this is a special signal meaning
6376 * `initiate client-driven rekey', and `in' contains a message
6377 * giving the reason for the rekey.
6379 * inlen==-1 means always initiate a rekey;
6380 * inlen==-2 means that userauth has completed successfully and
6381 * we should consider rekeying (for delayed compression).
6383 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6384 (!pktin && inlen < 0))) {
6389 logevent("Server initiated key re-exchange");
6393 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6394 * delayed compression, if it's available.
6396 * draft-miller-secsh-compression-delayed-00 says that you
6397 * negotiate delayed compression in the first key exchange, and
6398 * both sides start compressing when the server has sent
6399 * USERAUTH_SUCCESS. This has a race condition -- the server
6400 * can't know when the client has seen it, and thus which incoming
6401 * packets it should treat as compressed.
6403 * Instead, we do the initial key exchange without offering the
6404 * delayed methods, but note if the server offers them; when we
6405 * get here, if a delayed method was available that was higher
6406 * on our list than what we got, we initiate a rekey in which we
6407 * _do_ list the delayed methods (and hopefully get it as a
6408 * result). Subsequent rekeys will do the same.
6410 assert(!s->userauth_succeeded); /* should only happen once */
6411 s->userauth_succeeded = TRUE;
6412 if (!s->pending_compression)
6413 /* Can't see any point rekeying. */
6414 goto wait_for_rekey; /* this is utterly horrid */
6415 /* else fall through to rekey... */
6416 s->pending_compression = FALSE;
6419 * Now we've decided to rekey.
6421 * Special case: if the server bug is set that doesn't
6422 * allow rekeying, we give a different log message and
6423 * continue waiting. (If such a server _initiates_ a rekey,
6424 * we process it anyway!)
6426 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6427 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6429 /* Reset the counters, so that at least this message doesn't
6430 * hit the event log _too_ often. */
6431 ssh->outgoing_data_size = 0;
6432 ssh->incoming_data_size = 0;
6433 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
6435 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6438 goto wait_for_rekey; /* this is still utterly horrid */
6440 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6443 goto begin_key_exchange;
6449 * Add data to an SSH-2 channel output buffer.
6451 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6454 bufchain_add(&c->v.v2.outbuffer, buf, len);
6458 * Attempt to send data on an SSH-2 channel.
6460 static int ssh2_try_send(struct ssh_channel *c)
6463 struct Packet *pktout;
6466 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6469 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6470 if ((unsigned)len > c->v.v2.remwindow)
6471 len = c->v.v2.remwindow;
6472 if ((unsigned)len > c->v.v2.remmaxpkt)
6473 len = c->v.v2.remmaxpkt;
6474 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6475 ssh2_pkt_adduint32(pktout, c->remoteid);
6476 ssh2_pkt_addstring_start(pktout);
6477 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6478 ssh2_pkt_addstring_data(pktout, data, len);
6479 end_log_omission(ssh, pktout);
6480 ssh2_pkt_send(ssh, pktout);
6481 bufchain_consume(&c->v.v2.outbuffer, len);
6482 c->v.v2.remwindow -= len;
6486 * After having sent as much data as we can, return the amount
6489 ret = bufchain_size(&c->v.v2.outbuffer);
6492 * And if there's no data pending but we need to send an EOF, send
6495 if (!ret && c->pending_eof)
6496 ssh_channel_try_eof(c);
6501 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
6504 if (c->closes & CLOSES_SENT_EOF)
6505 return; /* don't send on channels we've EOFed */
6506 bufsize = ssh2_try_send(c);
6509 case CHAN_MAINSESSION:
6510 /* stdin need not receive an unthrottle
6511 * notification since it will be polled */
6514 x11_unthrottle(c->u.x11.s);
6517 /* agent sockets are request/response and need no
6518 * buffer management */
6521 pfd_unthrottle(c->u.pfd.s);
6528 * Set up most of a new ssh_channel for SSH-2.
6530 static void ssh2_channel_init(struct ssh_channel *c)
6533 c->localid = alloc_channel_id(ssh);
6535 c->pending_eof = FALSE;
6536 c->throttling_conn = FALSE;
6537 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6538 conf_get_int(ssh->conf, CONF_ssh_simple) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6539 c->v.v2.winadj_head = c->v.v2.winadj_tail = NULL;
6540 c->v.v2.throttle_state = UNTHROTTLED;
6541 bufchain_init(&c->v.v2.outbuffer);
6545 * Potentially enlarge the window on an SSH-2 channel.
6547 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6552 * Never send WINDOW_ADJUST for a channel that the remote side has
6553 * already sent EOF on; there's no point, since it won't be
6554 * sending any more data anyway. Ditto if _we've_ already sent
6557 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6561 * If the remote end has a habit of ignoring maxpkt, limit the
6562 * window so that it has no choice (assuming it doesn't ignore the
6565 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6566 newwin = OUR_V2_MAXPKT;
6570 * Only send a WINDOW_ADJUST if there's significantly more window
6571 * available than the other end thinks there is. This saves us
6572 * sending a WINDOW_ADJUST for every character in a shell session.
6574 * "Significant" is arbitrarily defined as half the window size.
6576 if (newwin / 2 >= c->v.v2.locwindow) {
6577 struct Packet *pktout;
6581 * In order to keep track of how much window the client
6582 * actually has available, we'd like it to acknowledge each
6583 * WINDOW_ADJUST. We can't do that directly, so we accompany
6584 * it with a CHANNEL_REQUEST that has to be acknowledged.
6586 * This is only necessary if we're opening the window wide.
6587 * If we're not, then throughput is being constrained by
6588 * something other than the maximum window size anyway.
6590 * We also only send this if the main channel has finished its
6591 * initial CHANNEL_REQUESTs and installed the default
6592 * CHANNEL_FAILURE handler, so as not to risk giving it
6593 * unexpected CHANNEL_FAILUREs.
6595 if (newwin == c->v.v2.locmaxwin &&
6596 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE]) {
6597 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6598 ssh2_pkt_adduint32(pktout, c->remoteid);
6599 ssh2_pkt_addstring(pktout, "winadj@putty.projects.tartarus.org");
6600 ssh2_pkt_addbool(pktout, TRUE);
6601 ssh2_pkt_send(ssh, pktout);
6604 * CHANNEL_FAILURE doesn't come with any indication of
6605 * what message caused it, so we have to keep track of the
6606 * outstanding CHANNEL_REQUESTs ourselves.
6608 wa = snew(struct winadj);
6609 wa->size = newwin - c->v.v2.locwindow;
6611 if (!c->v.v2.winadj_head)
6612 c->v.v2.winadj_head = wa;
6614 c->v.v2.winadj_tail->next = wa;
6615 c->v.v2.winadj_tail = wa;
6616 if (c->v.v2.throttle_state != UNTHROTTLED)
6617 c->v.v2.throttle_state = UNTHROTTLING;
6619 /* Pretend the WINDOW_ADJUST was acked immediately. */
6620 c->v.v2.remlocwin = newwin;
6621 c->v.v2.throttle_state = THROTTLED;
6623 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6624 ssh2_pkt_adduint32(pktout, c->remoteid);
6625 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6626 ssh2_pkt_send(ssh, pktout);
6627 c->v.v2.locwindow = newwin;
6632 * Find the channel associated with a message. If there's no channel,
6633 * or it's not properly open, make a noise about it and return NULL.
6635 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6637 unsigned localid = ssh_pkt_getuint32(pktin);
6638 struct ssh_channel *c;
6640 c = find234(ssh->channels, &localid, ssh_channelfind);
6642 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6643 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6644 char *buf = dupprintf("Received %s for %s channel %u",
6645 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6647 c ? "half-open" : "nonexistent", localid);
6648 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6655 static int ssh2_handle_winadj_response(struct ssh_channel *c)
6657 struct winadj *wa = c->v.v2.winadj_head;
6660 c->v.v2.winadj_head = wa->next;
6661 c->v.v2.remlocwin += wa->size;
6664 * winadj messages are only sent when the window is fully open, so
6665 * if we get an ack of one, we know any pending unthrottle is
6668 if (c->v.v2.throttle_state == UNTHROTTLING)
6669 c->v.v2.throttle_state = UNTHROTTLED;
6671 * We may now initiate channel-closing procedures, if that winadj
6672 * was the last thing outstanding before we send CHANNEL_CLOSE.
6674 ssh2_channel_check_close(c);
6678 static void ssh2_msg_channel_success(Ssh ssh, struct Packet *pktin)
6681 * This should never get called. All channel requests are either
6682 * sent with want_reply false, are sent before this handler gets
6683 * installed, or are "winadj@putty" requests, which servers should
6684 * never respond to with success.
6686 * However, at least one server ("boks_sshd") is known to return
6687 * SUCCESS for channel requests it's never heard of, such as
6688 * "winadj@putty". Raised with foxt.com as bug 090916-090424, but
6689 * for the sake of a quiet life, we handle it just the same as the
6692 struct ssh_channel *c;
6694 c = ssh2_channel_msg(ssh, pktin);
6697 if (!ssh2_handle_winadj_response(c))
6698 ssh_disconnect(ssh, NULL,
6699 "Received unsolicited SSH_MSG_CHANNEL_SUCCESS",
6700 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6703 static void ssh2_msg_channel_failure(Ssh ssh, struct Packet *pktin)
6706 * The only time this should get called is for "winadj@putty"
6707 * messages sent above. All other channel requests are either
6708 * sent with want_reply false or are sent before this handler gets
6711 struct ssh_channel *c;
6713 c = ssh2_channel_msg(ssh, pktin);
6716 if (!ssh2_handle_winadj_response(c))
6717 ssh_disconnect(ssh, NULL,
6718 "Received unsolicited SSH_MSG_CHANNEL_FAILURE",
6719 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6722 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6724 struct ssh_channel *c;
6725 c = ssh2_channel_msg(ssh, pktin);
6728 if (!(c->closes & CLOSES_SENT_EOF)) {
6729 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6730 ssh2_try_send_and_unthrottle(ssh, c);
6734 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6738 struct ssh_channel *c;
6739 c = ssh2_channel_msg(ssh, pktin);
6742 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6743 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6744 return; /* extended but not stderr */
6745 ssh_pkt_getstring(pktin, &data, &length);
6748 c->v.v2.locwindow -= length;
6749 c->v.v2.remlocwin -= length;
6751 case CHAN_MAINSESSION:
6753 from_backend(ssh->frontend, pktin->type ==
6754 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6758 bufsize = x11_send(c->u.x11.s, data, length);
6761 bufsize = pfd_send(c->u.pfd.s, data, length);
6764 while (length > 0) {
6765 if (c->u.a.lensofar < 4) {
6766 unsigned int l = min(4 - c->u.a.lensofar,
6768 memcpy(c->u.a.msglen + c->u.a.lensofar,
6772 c->u.a.lensofar += l;
6774 if (c->u.a.lensofar == 4) {
6776 4 + GET_32BIT(c->u.a.msglen);
6777 c->u.a.message = snewn(c->u.a.totallen,
6779 memcpy(c->u.a.message, c->u.a.msglen, 4);
6781 if (c->u.a.lensofar >= 4 && length > 0) {
6783 min(c->u.a.totallen - c->u.a.lensofar,
6785 memcpy(c->u.a.message + c->u.a.lensofar,
6789 c->u.a.lensofar += l;
6791 if (c->u.a.lensofar == c->u.a.totallen) {
6794 if (agent_query(c->u.a.message,
6797 ssh_agentf_callback, c))
6798 ssh_agentf_callback(c, reply, replylen);
6799 sfree(c->u.a.message);
6800 c->u.a.message = NULL;
6801 c->u.a.lensofar = 0;
6808 * If it looks like the remote end hit the end of its window,
6809 * and we didn't want it to do that, think about using a
6812 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6813 c->v.v2.locmaxwin < 0x40000000)
6814 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6816 * If we are not buffering too much data,
6817 * enlarge the window again at the remote side.
6818 * If we are buffering too much, we may still
6819 * need to adjust the window if the server's
6822 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6823 c->v.v2.locmaxwin - bufsize : 0);
6825 * If we're either buffering way too much data, or if we're
6826 * buffering anything at all and we're in "simple" mode,
6827 * throttle the whole channel.
6829 if ((bufsize > c->v.v2.locmaxwin ||
6830 (conf_get_int(ssh->conf, CONF_ssh_simple) && bufsize > 0)) &&
6831 !c->throttling_conn) {
6832 c->throttling_conn = 1;
6833 ssh_throttle_conn(ssh, +1);
6838 static void ssh_channel_destroy(struct ssh_channel *c)
6843 case CHAN_MAINSESSION:
6844 ssh->mainchan = NULL;
6845 update_specials_menu(ssh->frontend);
6848 if (c->u.x11.s != NULL)
6849 x11_close(c->u.x11.s);
6850 logevent("Forwarded X11 connection terminated");
6853 sfree(c->u.a.message);
6856 if (c->u.pfd.s != NULL)
6857 pfd_close(c->u.pfd.s);
6858 logevent("Forwarded port closed");
6862 del234(ssh->channels, c);
6863 if (ssh->version == 2)
6864 bufchain_clear(&c->v.v2.outbuffer);
6868 * See if that was the last channel left open.
6869 * (This is only our termination condition if we're
6870 * not running in -N mode.)
6872 if (ssh->version == 2 &&
6873 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
6874 count234(ssh->channels) == 0) {
6876 * We used to send SSH_MSG_DISCONNECT here,
6877 * because I'd believed that _every_ conforming
6878 * SSH-2 connection had to end with a disconnect
6879 * being sent by at least one side; apparently
6880 * I was wrong and it's perfectly OK to
6881 * unceremoniously slam the connection shut
6882 * when you're done, and indeed OpenSSH feels
6883 * this is more polite than sending a
6884 * DISCONNECT. So now we don't.
6886 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6890 static void ssh2_channel_check_close(struct ssh_channel *c)
6893 struct Packet *pktout;
6895 if ((c->closes & (CLOSES_SENT_EOF | CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6896 == (CLOSES_SENT_EOF | CLOSES_RCVD_EOF) && !c->v.v2.winadj_head) {
6898 * We have both sent and received EOF, and we have no
6899 * outstanding winadj channel requests, which means the
6900 * channel is in final wind-up. But we haven't sent CLOSE, so
6903 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6904 ssh2_pkt_adduint32(pktout, c->remoteid);
6905 ssh2_pkt_send(ssh, pktout);
6906 c->closes |= CLOSES_SENT_CLOSE;
6909 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
6911 * We have both sent and received CLOSE, which means we're
6912 * completely done with the channel.
6914 ssh_channel_destroy(c);
6918 static void ssh2_channel_got_eof(struct ssh_channel *c)
6920 if (c->closes & CLOSES_RCVD_EOF)
6921 return; /* already seen EOF */
6922 c->closes |= CLOSES_RCVD_EOF;
6924 if (c->type == CHAN_X11) {
6925 x11_send_eof(c->u.x11.s);
6926 } else if (c->type == CHAN_AGENT) {
6927 /* Manufacture an outgoing EOF in response to the incoming one. */
6928 sshfwd_write_eof(c);
6929 } else if (c->type == CHAN_SOCKDATA) {
6930 pfd_send_eof(c->u.pfd.s);
6931 } else if (c->type == CHAN_MAINSESSION) {
6934 if (!ssh->sent_console_eof &&
6935 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
6937 * Either from_backend_eof told us that the front end
6938 * wants us to close the outgoing side of the connection
6939 * as soon as we see EOF from the far end, or else we've
6940 * unilaterally decided to do that because we've allocated
6941 * a remote pty and hence EOF isn't a particularly
6942 * meaningful concept.
6944 sshfwd_write_eof(c);
6946 ssh->sent_console_eof = TRUE;
6949 ssh2_channel_check_close(c);
6952 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
6954 struct ssh_channel *c;
6956 c = ssh2_channel_msg(ssh, pktin);
6959 ssh2_channel_got_eof(c);
6962 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
6964 struct ssh_channel *c;
6966 c = ssh2_channel_msg(ssh, pktin);
6971 * When we receive CLOSE on a channel, we assume it comes with an
6972 * implied EOF if we haven't seen EOF yet.
6974 ssh2_channel_got_eof(c);
6977 * And we also send an outgoing EOF, if we haven't already, on the
6978 * assumption that CLOSE is a pretty forceful announcement that
6979 * the remote side is doing away with the entire channel. (If it
6980 * had wanted to send us EOF and continue receiving data from us,
6981 * it would have just sent CHANNEL_EOF.)
6983 if (!(c->closes & CLOSES_SENT_EOF)) {
6985 * Make sure we don't read any more from whatever our local
6986 * data source is for this channel.
6989 case CHAN_MAINSESSION:
6990 ssh->send_ok = 0; /* stop trying to read from stdin */
6993 x11_override_throttle(c->u.x11.s, 1);
6996 pfd_override_throttle(c->u.pfd.s, 1);
7001 * Send outgoing EOF.
7003 sshfwd_write_eof(ssh->mainchan);
7007 * Now process the actual close.
7009 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7010 c->closes |= CLOSES_RCVD_CLOSE;
7011 ssh2_channel_check_close(c);
7015 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7017 struct ssh_channel *c;
7019 c = ssh2_channel_msg(ssh, pktin);
7022 if (c->type != CHAN_SOCKDATA_DORMANT)
7023 return; /* dunno why they're confirming this */
7024 c->remoteid = ssh_pkt_getuint32(pktin);
7025 c->halfopen = FALSE;
7026 c->type = CHAN_SOCKDATA;
7027 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7028 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7030 pfd_confirm(c->u.pfd.s);
7032 ssh_channel_try_eof(c);
7035 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7037 static const char *const reasons[] = {
7038 "<unknown reason code>",
7039 "Administratively prohibited",
7041 "Unknown channel type",
7042 "Resource shortage",
7044 unsigned reason_code;
7045 char *reason_string;
7047 struct ssh_channel *c;
7048 c = ssh2_channel_msg(ssh, pktin);
7051 if (c->type != CHAN_SOCKDATA_DORMANT)
7052 return; /* dunno why they're failing this */
7054 reason_code = ssh_pkt_getuint32(pktin);
7055 if (reason_code >= lenof(reasons))
7056 reason_code = 0; /* ensure reasons[reason_code] in range */
7057 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7058 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7059 reasons[reason_code], reason_length, reason_string);
7061 pfd_close(c->u.pfd.s);
7063 del234(ssh->channels, c);
7067 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7070 int typelen, want_reply;
7071 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7072 struct ssh_channel *c;
7073 struct Packet *pktout;
7075 c = ssh2_channel_msg(ssh, pktin);
7078 ssh_pkt_getstring(pktin, &type, &typelen);
7079 want_reply = ssh2_pkt_getbool(pktin);
7082 * Having got the channel number, we now look at
7083 * the request type string to see if it's something
7086 if (c == ssh->mainchan) {
7088 * We recognise "exit-status" and "exit-signal" on
7089 * the primary channel.
7091 if (typelen == 11 &&
7092 !memcmp(type, "exit-status", 11)) {
7094 ssh->exitcode = ssh_pkt_getuint32(pktin);
7095 logeventf(ssh, "Server sent command exit status %d",
7097 reply = SSH2_MSG_CHANNEL_SUCCESS;
7099 } else if (typelen == 11 &&
7100 !memcmp(type, "exit-signal", 11)) {
7102 int is_plausible = TRUE, is_int = FALSE;
7103 char *fmt_sig = "", *fmt_msg = "";
7105 int msglen = 0, core = FALSE;
7106 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7107 * provide an `int' for the signal, despite its
7108 * having been a `string' in the drafts of RFC 4254 since at
7109 * least 2001. (Fixed in session.c 1.147.) Try to
7110 * infer which we can safely parse it as. */
7112 unsigned char *p = pktin->body +
7114 long len = pktin->length - pktin->savedpos;
7115 unsigned long num = GET_32BIT(p); /* what is it? */
7116 /* If it's 0, it hardly matters; assume string */
7120 int maybe_int = FALSE, maybe_str = FALSE;
7121 #define CHECK_HYPOTHESIS(offset, result) \
7124 if (q >= 0 && q+4 <= len) { \
7125 q = q + 4 + GET_32BIT(p+q); \
7126 if (q >= 0 && q+4 <= len && \
7127 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
7131 CHECK_HYPOTHESIS(4+1, maybe_int);
7132 CHECK_HYPOTHESIS(4+num+1, maybe_str);
7133 #undef CHECK_HYPOTHESIS
7134 if (maybe_int && !maybe_str)
7136 else if (!maybe_int && maybe_str)
7139 /* Crikey. Either or neither. Panic. */
7140 is_plausible = FALSE;
7143 ssh->exitcode = 128; /* means `unknown signal' */
7146 /* Old non-standard OpenSSH. */
7147 int signum = ssh_pkt_getuint32(pktin);
7148 fmt_sig = dupprintf(" %d", signum);
7149 ssh->exitcode = 128 + signum;
7151 /* As per RFC 4254. */
7154 ssh_pkt_getstring(pktin, &sig, &siglen);
7155 /* Signal name isn't supposed to be blank, but
7156 * let's cope gracefully if it is. */
7158 fmt_sig = dupprintf(" \"%.*s\"",
7163 * Really hideous method of translating the
7164 * signal description back into a locally
7165 * meaningful number.
7170 #define TRANSLATE_SIGNAL(s) \
7171 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7172 ssh->exitcode = 128 + SIG ## s
7174 TRANSLATE_SIGNAL(ABRT);
7177 TRANSLATE_SIGNAL(ALRM);
7180 TRANSLATE_SIGNAL(FPE);
7183 TRANSLATE_SIGNAL(HUP);
7186 TRANSLATE_SIGNAL(ILL);
7189 TRANSLATE_SIGNAL(INT);
7192 TRANSLATE_SIGNAL(KILL);
7195 TRANSLATE_SIGNAL(PIPE);
7198 TRANSLATE_SIGNAL(QUIT);
7201 TRANSLATE_SIGNAL(SEGV);
7204 TRANSLATE_SIGNAL(TERM);
7207 TRANSLATE_SIGNAL(USR1);
7210 TRANSLATE_SIGNAL(USR2);
7212 #undef TRANSLATE_SIGNAL
7214 ssh->exitcode = 128;
7216 core = ssh2_pkt_getbool(pktin);
7217 ssh_pkt_getstring(pktin, &msg, &msglen);
7219 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
7221 /* ignore lang tag */
7222 } /* else don't attempt to parse */
7223 logeventf(ssh, "Server exited on signal%s%s%s",
7224 fmt_sig, core ? " (core dumped)" : "",
7226 if (*fmt_sig) sfree(fmt_sig);
7227 if (*fmt_msg) sfree(fmt_msg);
7228 reply = SSH2_MSG_CHANNEL_SUCCESS;
7233 * This is a channel request we don't know
7234 * about, so we now either ignore the request
7235 * or respond with CHANNEL_FAILURE, depending
7238 reply = SSH2_MSG_CHANNEL_FAILURE;
7241 pktout = ssh2_pkt_init(reply);
7242 ssh2_pkt_adduint32(pktout, c->remoteid);
7243 ssh2_pkt_send(ssh, pktout);
7247 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7250 int typelen, want_reply;
7251 struct Packet *pktout;
7253 ssh_pkt_getstring(pktin, &type, &typelen);
7254 want_reply = ssh2_pkt_getbool(pktin);
7257 * We currently don't support any global requests
7258 * at all, so we either ignore the request or
7259 * respond with REQUEST_FAILURE, depending on
7263 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7264 ssh2_pkt_send(ssh, pktout);
7268 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7276 struct ssh_channel *c;
7277 unsigned remid, winsize, pktsize;
7278 struct Packet *pktout;
7280 ssh_pkt_getstring(pktin, &type, &typelen);
7281 c = snew(struct ssh_channel);
7284 remid = ssh_pkt_getuint32(pktin);
7285 winsize = ssh_pkt_getuint32(pktin);
7286 pktsize = ssh_pkt_getuint32(pktin);
7288 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7292 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7293 addrstr = snewn(peeraddrlen+1, char);
7294 memcpy(addrstr, peeraddr, peeraddrlen);
7295 addrstr[peeraddrlen] = '\0';
7296 peerport = ssh_pkt_getuint32(pktin);
7298 logeventf(ssh, "Received X11 connect request from %s:%d",
7301 if (!ssh->X11_fwd_enabled)
7302 error = "X11 forwarding is not enabled";
7303 else if ((x11err = x11_init(&c->u.x11.s, ssh->x11disp, c,
7304 addrstr, peerport, ssh->conf)) != NULL) {
7305 logeventf(ssh, "Local X11 connection failed: %s", x11err);
7306 error = "Unable to open an X11 connection";
7308 logevent("Opening X11 forward connection succeeded");
7313 } else if (typelen == 15 &&
7314 !memcmp(type, "forwarded-tcpip", 15)) {
7315 struct ssh_rportfwd pf, *realpf;
7318 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
7319 pf.sport = ssh_pkt_getuint32(pktin);
7320 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7321 peerport = ssh_pkt_getuint32(pktin);
7322 realpf = find234(ssh->rportfwds, &pf, NULL);
7323 logeventf(ssh, "Received remote port %d open request "
7324 "from %s:%d", pf.sport, peeraddr, peerport);
7325 if (realpf == NULL) {
7326 error = "Remote port is not recognised";
7328 const char *e = pfd_newconnect(&c->u.pfd.s,
7332 realpf->pfrec->addressfamily);
7333 logeventf(ssh, "Attempting to forward remote port to "
7334 "%s:%d", realpf->dhost, realpf->dport);
7336 logeventf(ssh, "Port open failed: %s", e);
7337 error = "Port open failed";
7339 logevent("Forwarded port opened successfully");
7340 c->type = CHAN_SOCKDATA;
7343 } else if (typelen == 22 &&
7344 !memcmp(type, "auth-agent@openssh.com", 22)) {
7345 if (!ssh->agentfwd_enabled)
7346 error = "Agent forwarding is not enabled";
7348 c->type = CHAN_AGENT; /* identify channel type */
7349 c->u.a.lensofar = 0;
7352 error = "Unsupported channel type requested";
7355 c->remoteid = remid;
7356 c->halfopen = FALSE;
7358 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7359 ssh2_pkt_adduint32(pktout, c->remoteid);
7360 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7361 ssh2_pkt_addstring(pktout, error);
7362 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7363 ssh2_pkt_send(ssh, pktout);
7364 logeventf(ssh, "Rejected channel open: %s", error);
7367 ssh2_channel_init(c);
7368 c->v.v2.remwindow = winsize;
7369 c->v.v2.remmaxpkt = pktsize;
7370 add234(ssh->channels, c);
7371 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7372 ssh2_pkt_adduint32(pktout, c->remoteid);
7373 ssh2_pkt_adduint32(pktout, c->localid);
7374 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7375 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7376 ssh2_pkt_send(ssh, pktout);
7381 * Buffer banner messages for later display at some convenient point,
7382 * if we're going to display them.
7384 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7386 /* Arbitrary limit to prevent unbounded inflation of buffer */
7387 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
7388 bufchain_size(&ssh->banner) <= 131072) {
7389 char *banner = NULL;
7391 ssh_pkt_getstring(pktin, &banner, &size);
7393 bufchain_add(&ssh->banner, banner, size);
7397 /* Helper function to deal with sending tty modes for "pty-req" */
7398 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7400 struct Packet *pktout = (struct Packet *)data;
7402 unsigned int arg = 0;
7403 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7404 if (i == lenof(ssh_ttymodes)) return;
7405 switch (ssh_ttymodes[i].type) {
7407 arg = ssh_tty_parse_specchar(val);
7410 arg = ssh_tty_parse_boolean(val);
7413 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7414 ssh2_pkt_adduint32(pktout, arg);
7418 * Handle the SSH-2 userauth and connection layers.
7420 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7421 struct Packet *pktin)
7423 struct do_ssh2_authconn_state {
7426 AUTH_TYPE_PUBLICKEY,
7427 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7428 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7430 AUTH_TYPE_GSSAPI, /* always QUIET */
7431 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7432 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7434 int done_service_req;
7435 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7436 int tried_pubkey_config, done_agent;
7441 int kbd_inter_refused;
7442 int we_are_in, userauth_success;
7443 prompts_t *cur_prompt;
7448 void *publickey_blob;
7449 int publickey_bloblen;
7450 int publickey_encrypted;
7451 char *publickey_algorithm;
7452 char *publickey_comment;
7453 unsigned char agent_request[5], *agent_response, *agentp;
7454 int agent_responselen;
7455 unsigned char *pkblob_in_agent;
7457 char *pkblob, *alg, *commentp;
7458 int pklen, alglen, commentlen;
7459 int siglen, retlen, len;
7460 char *q, *agentreq, *ret;
7462 int num_env, env_left, env_ok;
7463 struct Packet *pktout;
7466 struct ssh_gss_library *gsslib;
7467 Ssh_gss_ctx gss_ctx;
7468 Ssh_gss_buf gss_buf;
7469 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7470 Ssh_gss_name gss_srv_name;
7471 Ssh_gss_stat gss_stat;
7474 crState(do_ssh2_authconn_state);
7476 crBegin(ssh->do_ssh2_authconn_crstate);
7478 s->done_service_req = FALSE;
7479 s->we_are_in = s->userauth_success = FALSE;
7481 s->tried_gssapi = FALSE;
7484 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
7486 * Request userauth protocol, and await a response to it.
7488 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7489 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7490 ssh2_pkt_send(ssh, s->pktout);
7491 crWaitUntilV(pktin);
7492 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7493 s->done_service_req = TRUE;
7495 if (!s->done_service_req) {
7497 * Request connection protocol directly, without authentication.
7499 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7500 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7501 ssh2_pkt_send(ssh, s->pktout);
7502 crWaitUntilV(pktin);
7503 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7504 s->we_are_in = TRUE; /* no auth required */
7506 bombout(("Server refused service request"));
7511 /* Arrange to be able to deal with any BANNERs that come in.
7512 * (We do this now as packets may come in during the next bit.) */
7513 bufchain_init(&ssh->banner);
7514 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7515 ssh2_msg_userauth_banner;
7518 * Misc one-time setup for authentication.
7520 s->publickey_blob = NULL;
7521 if (!s->we_are_in) {
7524 * Load the public half of any configured public key file
7527 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
7528 if (!filename_is_null(s->keyfile)) {
7530 logeventf(ssh, "Reading private key file \"%.150s\"",
7531 filename_to_str(s->keyfile));
7532 keytype = key_type(s->keyfile);
7533 if (keytype == SSH_KEYTYPE_SSH2) {
7536 ssh2_userkey_loadpub(s->keyfile,
7537 &s->publickey_algorithm,
7538 &s->publickey_bloblen,
7539 &s->publickey_comment, &error);
7540 if (s->publickey_blob) {
7541 s->publickey_encrypted =
7542 ssh2_userkey_encrypted(s->keyfile, NULL);
7545 logeventf(ssh, "Unable to load private key (%s)",
7547 msgbuf = dupprintf("Unable to load private key file "
7548 "\"%.150s\" (%s)\r\n",
7549 filename_to_str(s->keyfile),
7551 c_write_str(ssh, msgbuf);
7556 logeventf(ssh, "Unable to use this key file (%s)",
7557 key_type_to_str(keytype));
7558 msgbuf = dupprintf("Unable to use key file \"%.150s\""
7560 filename_to_str(s->keyfile),
7561 key_type_to_str(keytype));
7562 c_write_str(ssh, msgbuf);
7564 s->publickey_blob = NULL;
7569 * Find out about any keys Pageant has (but if there's a
7570 * public key configured, filter out all others).
7573 s->agent_response = NULL;
7574 s->pkblob_in_agent = NULL;
7575 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
7579 logevent("Pageant is running. Requesting keys.");
7581 /* Request the keys held by the agent. */
7582 PUT_32BIT(s->agent_request, 1);
7583 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
7584 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
7585 ssh_agent_callback, ssh)) {
7589 bombout(("Unexpected data from server while"
7590 " waiting for agent response"));
7593 } while (pktin || inlen > 0);
7594 r = ssh->agent_response;
7595 s->agent_responselen = ssh->agent_response_len;
7597 s->agent_response = (unsigned char *) r;
7598 if (s->agent_response && s->agent_responselen >= 5 &&
7599 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
7602 p = s->agent_response + 5;
7603 s->nkeys = GET_32BIT(p);
7605 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
7606 if (s->publickey_blob) {
7607 /* See if configured key is in agent. */
7608 for (keyi = 0; keyi < s->nkeys; keyi++) {
7609 s->pklen = GET_32BIT(p);
7610 if (s->pklen == s->publickey_bloblen &&
7611 !memcmp(p+4, s->publickey_blob,
7612 s->publickey_bloblen)) {
7613 logeventf(ssh, "Pageant key #%d matches "
7614 "configured key file", keyi);
7616 s->pkblob_in_agent = p;
7620 p += GET_32BIT(p) + 4; /* comment */
7622 if (!s->pkblob_in_agent) {
7623 logevent("Configured key file not in Pageant");
7628 logevent("Failed to get reply from Pageant");
7635 * We repeat this whole loop, including the username prompt,
7636 * until we manage a successful authentication. If the user
7637 * types the wrong _password_, they can be sent back to the
7638 * beginning to try another username, if this is configured on.
7639 * (If they specify a username in the config, they are never
7640 * asked, even if they do give a wrong password.)
7642 * I think this best serves the needs of
7644 * - the people who have no configuration, no keys, and just
7645 * want to try repeated (username,password) pairs until they
7646 * type both correctly
7648 * - people who have keys and configuration but occasionally
7649 * need to fall back to passwords
7651 * - people with a key held in Pageant, who might not have
7652 * logged in to a particular machine before; so they want to
7653 * type a username, and then _either_ their key will be
7654 * accepted, _or_ they will type a password. If they mistype
7655 * the username they will want to be able to get back and
7658 s->got_username = FALSE;
7659 while (!s->we_are_in) {
7663 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
7665 * We got a username last time round this loop, and
7666 * with change_username turned off we don't try to get
7669 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
7670 int ret; /* need not be kept over crReturn */
7671 s->cur_prompt = new_prompts(ssh->frontend);
7672 s->cur_prompt->to_server = TRUE;
7673 s->cur_prompt->name = dupstr("SSH login name");
7674 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
7675 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7678 crWaitUntilV(!pktin);
7679 ret = get_userpass_input(s->cur_prompt, in, inlen);
7684 * get_userpass_input() failed to get a username.
7687 free_prompts(s->cur_prompt);
7688 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
7691 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
7692 free_prompts(s->cur_prompt);
7695 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7696 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
7697 c_write_str(ssh, stuff);
7701 s->got_username = TRUE;
7704 * Send an authentication request using method "none": (a)
7705 * just in case it succeeds, and (b) so that we know what
7706 * authentication methods we can usefully try next.
7708 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7710 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7711 ssh2_pkt_addstring(s->pktout, ssh->username);
7712 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
7713 ssh2_pkt_addstring(s->pktout, "none"); /* method */
7714 ssh2_pkt_send(ssh, s->pktout);
7715 s->type = AUTH_TYPE_NONE;
7717 s->we_are_in = FALSE;
7719 s->tried_pubkey_config = FALSE;
7720 s->kbd_inter_refused = FALSE;
7722 /* Reset agent request state. */
7723 s->done_agent = FALSE;
7724 if (s->agent_response) {
7725 if (s->pkblob_in_agent) {
7726 s->agentp = s->pkblob_in_agent;
7728 s->agentp = s->agent_response + 5 + 4;
7734 char *methods = NULL;
7738 * Wait for the result of the last authentication request.
7741 crWaitUntilV(pktin);
7743 * Now is a convenient point to spew any banner material
7744 * that we've accumulated. (This should ensure that when
7745 * we exit the auth loop, we haven't any left to deal
7749 int size = bufchain_size(&ssh->banner);
7751 * Don't show the banner if we're operating in
7752 * non-verbose non-interactive mode. (It's probably
7753 * a script, which means nobody will read the
7754 * banner _anyway_, and moreover the printing of
7755 * the banner will screw up processing on the
7756 * output of (say) plink.)
7758 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
7759 char *banner = snewn(size, char);
7760 bufchain_fetch(&ssh->banner, banner, size);
7761 c_write_untrusted(ssh, banner, size);
7764 bufchain_clear(&ssh->banner);
7766 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
7767 logevent("Access granted");
7768 s->we_are_in = s->userauth_success = TRUE;
7772 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
7773 bombout(("Strange packet received during authentication: "
7774 "type %d", pktin->type));
7781 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7782 * we can look at the string in it and know what we can
7783 * helpfully try next.
7785 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
7786 ssh_pkt_getstring(pktin, &methods, &methlen);
7787 if (!ssh2_pkt_getbool(pktin)) {
7789 * We have received an unequivocal Access
7790 * Denied. This can translate to a variety of
7791 * messages, or no message at all.
7793 * For forms of authentication which are attempted
7794 * implicitly, by which I mean without printing
7795 * anything in the window indicating that we're
7796 * trying them, we should never print 'Access
7799 * If we do print a message saying that we're
7800 * attempting some kind of authentication, it's OK
7801 * to print a followup message saying it failed -
7802 * but the message may sometimes be more specific
7803 * than simply 'Access denied'.
7805 * Additionally, if we'd just tried password
7806 * authentication, we should break out of this
7807 * whole loop so as to go back to the username
7808 * prompt (iff we're configured to allow
7809 * username change attempts).
7811 if (s->type == AUTH_TYPE_NONE) {
7813 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
7814 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
7815 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
7816 c_write_str(ssh, "Server refused our key\r\n");
7817 logevent("Server refused our key");
7818 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
7819 /* This _shouldn't_ happen except by a
7820 * protocol bug causing client and server to
7821 * disagree on what is a correct signature. */
7822 c_write_str(ssh, "Server refused public-key signature"
7823 " despite accepting key!\r\n");
7824 logevent("Server refused public-key signature"
7825 " despite accepting key!");
7826 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
7827 /* quiet, so no c_write */
7828 logevent("Server refused keyboard-interactive authentication");
7829 } else if (s->type==AUTH_TYPE_GSSAPI) {
7830 /* always quiet, so no c_write */
7831 /* also, the code down in the GSSAPI block has
7832 * already logged this in the Event Log */
7833 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
7834 logevent("Keyboard-interactive authentication failed");
7835 c_write_str(ssh, "Access denied\r\n");
7837 assert(s->type == AUTH_TYPE_PASSWORD);
7838 logevent("Password authentication failed");
7839 c_write_str(ssh, "Access denied\r\n");
7841 if (conf_get_int(ssh->conf, CONF_change_username)) {
7842 /* XXX perhaps we should allow
7843 * keyboard-interactive to do this too? */
7844 s->we_are_in = FALSE;
7849 c_write_str(ssh, "Further authentication required\r\n");
7850 logevent("Further authentication required");
7854 in_commasep_string("publickey", methods, methlen);
7856 in_commasep_string("password", methods, methlen);
7857 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
7858 in_commasep_string("keyboard-interactive", methods, methlen);
7861 ssh->gsslibs = ssh_gss_setup(ssh->conf);
7862 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
7863 in_commasep_string("gssapi-with-mic", methods, methlen) &&
7864 ssh->gsslibs->nlibraries > 0;
7868 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7870 if (s->can_pubkey && !s->done_agent && s->nkeys) {
7873 * Attempt public-key authentication using a key from Pageant.
7876 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7878 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
7880 /* Unpack key from agent response */
7881 s->pklen = GET_32BIT(s->agentp);
7883 s->pkblob = (char *)s->agentp;
7884 s->agentp += s->pklen;
7885 s->alglen = GET_32BIT(s->pkblob);
7886 s->alg = s->pkblob + 4;
7887 s->commentlen = GET_32BIT(s->agentp);
7889 s->commentp = (char *)s->agentp;
7890 s->agentp += s->commentlen;
7891 /* s->agentp now points at next key, if any */
7893 /* See if server will accept it */
7894 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7895 ssh2_pkt_addstring(s->pktout, ssh->username);
7896 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7897 /* service requested */
7898 ssh2_pkt_addstring(s->pktout, "publickey");
7900 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
7901 ssh2_pkt_addstring_start(s->pktout);
7902 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7903 ssh2_pkt_addstring_start(s->pktout);
7904 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7905 ssh2_pkt_send(ssh, s->pktout);
7906 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
7908 crWaitUntilV(pktin);
7909 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7911 /* Offer of key refused. */
7918 if (flags & FLAG_VERBOSE) {
7919 c_write_str(ssh, "Authenticating with "
7921 c_write(ssh, s->commentp, s->commentlen);
7922 c_write_str(ssh, "\" from agent\r\n");
7926 * Server is willing to accept the key.
7927 * Construct a SIGN_REQUEST.
7929 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7930 ssh2_pkt_addstring(s->pktout, ssh->username);
7931 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7932 /* service requested */
7933 ssh2_pkt_addstring(s->pktout, "publickey");
7935 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
7936 ssh2_pkt_addstring_start(s->pktout);
7937 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7938 ssh2_pkt_addstring_start(s->pktout);
7939 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7941 /* Ask agent for signature. */
7942 s->siglen = s->pktout->length - 5 + 4 +
7943 ssh->v2_session_id_len;
7944 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7946 s->len = 1; /* message type */
7947 s->len += 4 + s->pklen; /* key blob */
7948 s->len += 4 + s->siglen; /* data to sign */
7949 s->len += 4; /* flags */
7950 s->agentreq = snewn(4 + s->len, char);
7951 PUT_32BIT(s->agentreq, s->len);
7952 s->q = s->agentreq + 4;
7953 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
7954 PUT_32BIT(s->q, s->pklen);
7956 memcpy(s->q, s->pkblob, s->pklen);
7958 PUT_32BIT(s->q, s->siglen);
7960 /* Now the data to be signed... */
7961 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7962 PUT_32BIT(s->q, ssh->v2_session_id_len);
7965 memcpy(s->q, ssh->v2_session_id,
7966 ssh->v2_session_id_len);
7967 s->q += ssh->v2_session_id_len;
7968 memcpy(s->q, s->pktout->data + 5,
7969 s->pktout->length - 5);
7970 s->q += s->pktout->length - 5;
7971 /* And finally the (zero) flags word. */
7973 if (!agent_query(s->agentreq, s->len + 4,
7975 ssh_agent_callback, ssh)) {
7979 bombout(("Unexpected data from server"
7980 " while waiting for agent"
7984 } while (pktin || inlen > 0);
7985 vret = ssh->agent_response;
7986 s->retlen = ssh->agent_response_len;
7991 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
7992 logevent("Sending Pageant's response");
7993 ssh2_add_sigblob(ssh, s->pktout,
7994 s->pkblob, s->pklen,
7996 GET_32BIT(s->ret + 5));
7997 ssh2_pkt_send(ssh, s->pktout);
7998 s->type = AUTH_TYPE_PUBLICKEY;
8000 /* FIXME: less drastic response */
8001 bombout(("Pageant failed to answer challenge"));
8007 /* Do we have any keys left to try? */
8008 if (s->pkblob_in_agent) {
8009 s->done_agent = TRUE;
8010 s->tried_pubkey_config = TRUE;
8013 if (s->keyi >= s->nkeys)
8014 s->done_agent = TRUE;
8017 } else if (s->can_pubkey && s->publickey_blob &&
8018 !s->tried_pubkey_config) {
8020 struct ssh2_userkey *key; /* not live over crReturn */
8021 char *passphrase; /* not live over crReturn */
8023 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8025 s->tried_pubkey_config = TRUE;
8028 * Try the public key supplied in the configuration.
8030 * First, offer the public blob to see if the server is
8031 * willing to accept it.
8033 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8034 ssh2_pkt_addstring(s->pktout, ssh->username);
8035 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8036 /* service requested */
8037 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
8038 ssh2_pkt_addbool(s->pktout, FALSE);
8039 /* no signature included */
8040 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
8041 ssh2_pkt_addstring_start(s->pktout);
8042 ssh2_pkt_addstring_data(s->pktout,
8043 (char *)s->publickey_blob,
8044 s->publickey_bloblen);
8045 ssh2_pkt_send(ssh, s->pktout);
8046 logevent("Offered public key");
8048 crWaitUntilV(pktin);
8049 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8050 /* Key refused. Give up. */
8051 s->gotit = TRUE; /* reconsider message next loop */
8052 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
8053 continue; /* process this new message */
8055 logevent("Offer of public key accepted");
8058 * Actually attempt a serious authentication using
8061 if (flags & FLAG_VERBOSE) {
8062 c_write_str(ssh, "Authenticating with public key \"");
8063 c_write_str(ssh, s->publickey_comment);
8064 c_write_str(ssh, "\"\r\n");
8068 const char *error; /* not live over crReturn */
8069 if (s->publickey_encrypted) {
8071 * Get a passphrase from the user.
8073 int ret; /* need not be kept over crReturn */
8074 s->cur_prompt = new_prompts(ssh->frontend);
8075 s->cur_prompt->to_server = FALSE;
8076 s->cur_prompt->name = dupstr("SSH key passphrase");
8077 add_prompt(s->cur_prompt,
8078 dupprintf("Passphrase for key \"%.100s\": ",
8079 s->publickey_comment),
8081 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8084 crWaitUntilV(!pktin);
8085 ret = get_userpass_input(s->cur_prompt,
8090 /* Failed to get a passphrase. Terminate. */
8091 free_prompts(s->cur_prompt);
8092 ssh_disconnect(ssh, NULL,
8093 "Unable to authenticate",
8094 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8099 dupstr(s->cur_prompt->prompts[0]->result);
8100 free_prompts(s->cur_prompt);
8102 passphrase = NULL; /* no passphrase needed */
8106 * Try decrypting the key.
8108 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8109 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
8111 /* burn the evidence */
8112 memset(passphrase, 0, strlen(passphrase));
8115 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
8117 (key == SSH2_WRONG_PASSPHRASE)) {
8118 c_write_str(ssh, "Wrong passphrase\r\n");
8120 /* and loop again */
8122 c_write_str(ssh, "Unable to load private key (");
8123 c_write_str(ssh, error);
8124 c_write_str(ssh, ")\r\n");
8126 break; /* try something else */
8132 unsigned char *pkblob, *sigblob, *sigdata;
8133 int pkblob_len, sigblob_len, sigdata_len;
8137 * We have loaded the private key and the server
8138 * has announced that it's willing to accept it.
8139 * Hallelujah. Generate a signature and send it.
8141 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8142 ssh2_pkt_addstring(s->pktout, ssh->username);
8143 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8144 /* service requested */
8145 ssh2_pkt_addstring(s->pktout, "publickey");
8147 ssh2_pkt_addbool(s->pktout, TRUE);
8148 /* signature follows */
8149 ssh2_pkt_addstring(s->pktout, key->alg->name);
8150 pkblob = key->alg->public_blob(key->data,
8152 ssh2_pkt_addstring_start(s->pktout);
8153 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
8157 * The data to be signed is:
8161 * followed by everything so far placed in the
8164 sigdata_len = s->pktout->length - 5 + 4 +
8165 ssh->v2_session_id_len;
8166 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8168 sigdata = snewn(sigdata_len, unsigned char);
8170 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8171 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
8174 memcpy(sigdata+p, ssh->v2_session_id,
8175 ssh->v2_session_id_len);
8176 p += ssh->v2_session_id_len;
8177 memcpy(sigdata+p, s->pktout->data + 5,
8178 s->pktout->length - 5);
8179 p += s->pktout->length - 5;
8180 assert(p == sigdata_len);
8181 sigblob = key->alg->sign(key->data, (char *)sigdata,
8182 sigdata_len, &sigblob_len);
8183 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
8184 sigblob, sigblob_len);
8189 ssh2_pkt_send(ssh, s->pktout);
8190 logevent("Sent public key signature");
8191 s->type = AUTH_TYPE_PUBLICKEY;
8192 key->alg->freekey(key->data);
8196 } else if (s->can_gssapi && !s->tried_gssapi) {
8198 /* GSSAPI Authentication */
8203 s->type = AUTH_TYPE_GSSAPI;
8204 s->tried_gssapi = TRUE;
8206 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
8209 * Pick the highest GSS library on the preference
8215 for (i = 0; i < ngsslibs; i++) {
8216 int want_id = conf_get_int_int(ssh->conf,
8217 CONF_ssh_gsslist, i);
8218 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
8219 if (ssh->gsslibs->libraries[j].id == want_id) {
8220 s->gsslib = &ssh->gsslibs->libraries[j];
8221 goto got_gsslib; /* double break */
8226 * We always expect to have found something in
8227 * the above loop: we only came here if there
8228 * was at least one viable GSS library, and the
8229 * preference list should always mention
8230 * everything and only change the order.
8235 if (s->gsslib->gsslogmsg)
8236 logevent(s->gsslib->gsslogmsg);
8238 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8239 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8240 ssh2_pkt_addstring(s->pktout, ssh->username);
8241 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8242 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
8243 logevent("Attempting GSSAPI authentication");
8245 /* add mechanism info */
8246 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
8248 /* number of GSSAPI mechanisms */
8249 ssh2_pkt_adduint32(s->pktout,1);
8251 /* length of OID + 2 */
8252 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
8253 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
8256 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
8258 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
8260 ssh2_pkt_send(ssh, s->pktout);
8261 crWaitUntilV(pktin);
8262 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
8263 logevent("GSSAPI authentication request refused");
8267 /* check returned packet ... */
8269 ssh_pkt_getstring(pktin, &data, &len);
8270 s->gss_rcvtok.value = data;
8271 s->gss_rcvtok.length = len;
8272 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
8273 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
8274 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
8275 memcmp((char *)s->gss_rcvtok.value + 2,
8276 s->gss_buf.value,s->gss_buf.length) ) {
8277 logevent("GSSAPI authentication - wrong response from server");
8281 /* now start running */
8282 s->gss_stat = s->gsslib->import_name(s->gsslib,
8285 if (s->gss_stat != SSH_GSS_OK) {
8286 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
8287 logevent("GSSAPI import name failed - Bad service name");
8289 logevent("GSSAPI import name failed");
8293 /* fetch TGT into GSS engine */
8294 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
8296 if (s->gss_stat != SSH_GSS_OK) {
8297 logevent("GSSAPI authentication failed to get credentials");
8298 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8302 /* initial tokens are empty */
8303 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
8304 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
8306 /* now enter the loop */
8308 s->gss_stat = s->gsslib->init_sec_context
8312 conf_get_int(ssh->conf, CONF_gssapifwd),
8316 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
8317 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
8318 logevent("GSSAPI authentication initialisation failed");
8320 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
8321 &s->gss_buf) == SSH_GSS_OK) {
8322 logevent(s->gss_buf.value);
8323 sfree(s->gss_buf.value);
8328 logevent("GSSAPI authentication initialised");
8330 /* Client and server now exchange tokens until GSSAPI
8331 * no longer says CONTINUE_NEEDED */
8333 if (s->gss_sndtok.length != 0) {
8334 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8335 ssh_pkt_addstring_start(s->pktout);
8336 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
8337 ssh2_pkt_send(ssh, s->pktout);
8338 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
8341 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8342 crWaitUntilV(pktin);
8343 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8344 logevent("GSSAPI authentication - bad server response");
8345 s->gss_stat = SSH_GSS_FAILURE;
8348 ssh_pkt_getstring(pktin, &data, &len);
8349 s->gss_rcvtok.value = data;
8350 s->gss_rcvtok.length = len;
8352 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8354 if (s->gss_stat != SSH_GSS_OK) {
8355 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8356 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8359 logevent("GSSAPI authentication loop finished OK");
8361 /* Now send the MIC */
8363 s->pktout = ssh2_pkt_init(0);
8364 micoffset = s->pktout->length;
8365 ssh_pkt_addstring_start(s->pktout);
8366 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8367 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
8368 ssh_pkt_addstring(s->pktout, ssh->username);
8369 ssh_pkt_addstring(s->pktout, "ssh-connection");
8370 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8372 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8373 s->gss_buf.length = s->pktout->length - micoffset;
8375 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
8376 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8377 ssh_pkt_addstring_start(s->pktout);
8378 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
8379 ssh2_pkt_send(ssh, s->pktout);
8380 s->gsslib->free_mic(s->gsslib, &mic);
8384 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8385 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8388 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8391 * Keyboard-interactive authentication.
8394 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8396 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
8398 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8399 ssh2_pkt_addstring(s->pktout, ssh->username);
8400 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8401 /* service requested */
8402 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8404 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8405 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8406 ssh2_pkt_send(ssh, s->pktout);
8408 logevent("Attempting keyboard-interactive authentication");
8410 crWaitUntilV(pktin);
8411 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8412 /* Server is not willing to do keyboard-interactive
8413 * at all (or, bizarrely but legally, accepts the
8414 * user without actually issuing any prompts).
8415 * Give up on it entirely. */
8417 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8418 s->kbd_inter_refused = TRUE; /* don't try it again */
8423 * Loop while the server continues to send INFO_REQUESTs.
8425 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
8427 char *name, *inst, *lang;
8428 int name_len, inst_len, lang_len;
8432 * We've got a fresh USERAUTH_INFO_REQUEST.
8433 * Get the preamble and start building a prompt.
8435 ssh_pkt_getstring(pktin, &name, &name_len);
8436 ssh_pkt_getstring(pktin, &inst, &inst_len);
8437 ssh_pkt_getstring(pktin, &lang, &lang_len);
8438 s->cur_prompt = new_prompts(ssh->frontend);
8439 s->cur_prompt->to_server = TRUE;
8442 * Get any prompt(s) from the packet.
8444 s->num_prompts = ssh_pkt_getuint32(pktin);
8445 for (i = 0; i < s->num_prompts; i++) {
8449 static char noprompt[] =
8450 "<server failed to send prompt>: ";
8452 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8453 echo = ssh2_pkt_getbool(pktin);
8456 prompt_len = lenof(noprompt)-1;
8458 add_prompt(s->cur_prompt,
8459 dupprintf("%.*s", prompt_len, prompt),
8464 /* FIXME: better prefix to distinguish from
8466 s->cur_prompt->name =
8467 dupprintf("SSH server: %.*s", name_len, name);
8468 s->cur_prompt->name_reqd = TRUE;
8470 s->cur_prompt->name =
8471 dupstr("SSH server authentication");
8472 s->cur_prompt->name_reqd = FALSE;
8474 /* We add a prefix to try to make it clear that a prompt
8475 * has come from the server.
8476 * FIXME: ugly to print "Using..." in prompt _every_
8477 * time round. Can this be done more subtly? */
8478 /* Special case: for reasons best known to themselves,
8479 * some servers send k-i requests with no prompts and
8480 * nothing to display. Keep quiet in this case. */
8481 if (s->num_prompts || name_len || inst_len) {
8482 s->cur_prompt->instruction =
8483 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8484 inst_len ? "\n" : "", inst_len, inst);
8485 s->cur_prompt->instr_reqd = TRUE;
8487 s->cur_prompt->instr_reqd = FALSE;
8491 * Display any instructions, and get the user's
8495 int ret; /* not live over crReturn */
8496 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8499 crWaitUntilV(!pktin);
8500 ret = get_userpass_input(s->cur_prompt, in, inlen);
8505 * Failed to get responses. Terminate.
8507 free_prompts(s->cur_prompt);
8508 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8509 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8516 * Send the response(s) to the server.
8518 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
8519 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
8520 for (i=0; i < s->num_prompts; i++) {
8521 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8522 ssh2_pkt_addstring(s->pktout,
8523 s->cur_prompt->prompts[i]->result);
8524 end_log_omission(ssh, s->pktout);
8526 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8529 * Free the prompts structure from this iteration.
8530 * If there's another, a new one will be allocated
8531 * when we return to the top of this while loop.
8533 free_prompts(s->cur_prompt);
8536 * Get the next packet in case it's another
8539 crWaitUntilV(pktin);
8544 * We should have SUCCESS or FAILURE now.
8548 } else if (s->can_passwd) {
8551 * Plain old password authentication.
8553 int ret; /* not live over crReturn */
8554 int changereq_first_time; /* not live over crReturn */
8556 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
8558 s->cur_prompt = new_prompts(ssh->frontend);
8559 s->cur_prompt->to_server = TRUE;
8560 s->cur_prompt->name = dupstr("SSH password");
8561 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
8566 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8569 crWaitUntilV(!pktin);
8570 ret = get_userpass_input(s->cur_prompt, in, inlen);
8575 * Failed to get responses. Terminate.
8577 free_prompts(s->cur_prompt);
8578 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8579 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8584 * Squirrel away the password. (We may need it later if
8585 * asked to change it.)
8587 s->password = dupstr(s->cur_prompt->prompts[0]->result);
8588 free_prompts(s->cur_prompt);
8591 * Send the password packet.
8593 * We pad out the password packet to 256 bytes to make
8594 * it harder for an attacker to find the length of the
8597 * Anyone using a password longer than 256 bytes
8598 * probably doesn't have much to worry about from
8599 * people who find out how long their password is!
8601 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8602 ssh2_pkt_addstring(s->pktout, ssh->username);
8603 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8604 /* service requested */
8605 ssh2_pkt_addstring(s->pktout, "password");
8606 ssh2_pkt_addbool(s->pktout, FALSE);
8607 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8608 ssh2_pkt_addstring(s->pktout, s->password);
8609 end_log_omission(ssh, s->pktout);
8610 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8611 logevent("Sent password");
8612 s->type = AUTH_TYPE_PASSWORD;
8615 * Wait for next packet, in case it's a password change
8618 crWaitUntilV(pktin);
8619 changereq_first_time = TRUE;
8621 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
8624 * We're being asked for a new password
8625 * (perhaps not for the first time).
8626 * Loop until the server accepts it.
8629 int got_new = FALSE; /* not live over crReturn */
8630 char *prompt; /* not live over crReturn */
8631 int prompt_len; /* not live over crReturn */
8635 if (changereq_first_time)
8636 msg = "Server requested password change";
8638 msg = "Server rejected new password";
8640 c_write_str(ssh, msg);
8641 c_write_str(ssh, "\r\n");
8644 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8646 s->cur_prompt = new_prompts(ssh->frontend);
8647 s->cur_prompt->to_server = TRUE;
8648 s->cur_prompt->name = dupstr("New SSH password");
8649 s->cur_prompt->instruction =
8650 dupprintf("%.*s", prompt_len, prompt);
8651 s->cur_prompt->instr_reqd = TRUE;
8653 * There's no explicit requirement in the protocol
8654 * for the "old" passwords in the original and
8655 * password-change messages to be the same, and
8656 * apparently some Cisco kit supports password change
8657 * by the user entering a blank password originally
8658 * and the real password subsequently, so,
8659 * reluctantly, we prompt for the old password again.
8661 * (On the other hand, some servers don't even bother
8662 * to check this field.)
8664 add_prompt(s->cur_prompt,
8665 dupstr("Current password (blank for previously entered password): "),
8667 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
8669 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
8673 * Loop until the user manages to enter the same
8678 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8681 crWaitUntilV(!pktin);
8682 ret = get_userpass_input(s->cur_prompt, in, inlen);
8687 * Failed to get responses. Terminate.
8689 /* burn the evidence */
8690 free_prompts(s->cur_prompt);
8691 memset(s->password, 0, strlen(s->password));
8693 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8694 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8700 * If the user specified a new original password
8701 * (IYSWIM), overwrite any previously specified
8703 * (A side effect is that the user doesn't have to
8704 * re-enter it if they louse up the new password.)
8706 if (s->cur_prompt->prompts[0]->result[0]) {
8707 memset(s->password, 0, strlen(s->password));
8708 /* burn the evidence */
8711 dupstr(s->cur_prompt->prompts[0]->result);
8715 * Check the two new passwords match.
8717 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
8718 s->cur_prompt->prompts[2]->result)
8721 /* They don't. Silly user. */
8722 c_write_str(ssh, "Passwords do not match\r\n");
8727 * Send the new password (along with the old one).
8728 * (see above for padding rationale)
8730 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8731 ssh2_pkt_addstring(s->pktout, ssh->username);
8732 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8733 /* service requested */
8734 ssh2_pkt_addstring(s->pktout, "password");
8735 ssh2_pkt_addbool(s->pktout, TRUE);
8736 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8737 ssh2_pkt_addstring(s->pktout, s->password);
8738 ssh2_pkt_addstring(s->pktout,
8739 s->cur_prompt->prompts[1]->result);
8740 free_prompts(s->cur_prompt);
8741 end_log_omission(ssh, s->pktout);
8742 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8743 logevent("Sent new password");
8746 * Now see what the server has to say about it.
8747 * (If it's CHANGEREQ again, it's not happy with the
8750 crWaitUntilV(pktin);
8751 changereq_first_time = FALSE;
8756 * We need to reexamine the current pktin at the top
8757 * of the loop. Either:
8758 * - we weren't asked to change password at all, in
8759 * which case it's a SUCCESS or FAILURE with the
8761 * - we sent a new password, and the server was
8762 * either OK with it (SUCCESS or FAILURE w/partial
8763 * success) or unhappy with the _old_ password
8764 * (FAILURE w/o partial success)
8765 * In any of these cases, we go back to the top of
8766 * the loop and start again.
8771 * We don't need the old password any more, in any
8772 * case. Burn the evidence.
8774 memset(s->password, 0, strlen(s->password));
8778 char *str = dupprintf("No supported authentication methods available"
8779 " (server sent: %.*s)",
8782 ssh_disconnect(ssh, str,
8783 "No supported authentication methods available",
8784 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
8794 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
8796 /* Clear up various bits and pieces from authentication. */
8797 if (s->publickey_blob) {
8798 sfree(s->publickey_blob);
8799 sfree(s->publickey_comment);
8801 if (s->agent_response)
8802 sfree(s->agent_response);
8804 if (s->userauth_success) {
8806 * We've just received USERAUTH_SUCCESS, and we haven't sent any
8807 * packets since. Signal the transport layer to consider enacting
8808 * delayed compression.
8810 * (Relying on we_are_in is not sufficient, as
8811 * draft-miller-secsh-compression-delayed is quite clear that it
8812 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
8813 * become set for other reasons.)
8815 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
8819 * Now the connection protocol has started, one way or another.
8822 ssh->channels = newtree234(ssh_channelcmp);
8825 * Set up handlers for some connection protocol messages, so we
8826 * don't have to handle them repeatedly in this coroutine.
8828 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
8829 ssh2_msg_channel_window_adjust;
8830 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
8831 ssh2_msg_global_request;
8834 * Create the main session channel.
8836 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
8837 ssh->mainchan = NULL;
8838 } else if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
8840 * Just start a direct-tcpip channel and use it as the main
8843 ssh->mainchan = snew(struct ssh_channel);
8844 ssh->mainchan->ssh = ssh;
8845 ssh2_channel_init(ssh->mainchan);
8847 "Opening direct-tcpip channel to %s:%d in place of session",
8848 conf_get_str(ssh->conf, CONF_ssh_nc_host),
8849 conf_get_int(ssh->conf, CONF_ssh_nc_port));
8850 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8851 ssh2_pkt_addstring(s->pktout, "direct-tcpip");
8852 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8853 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8854 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8855 ssh2_pkt_addstring(s->pktout, conf_get_str(ssh->conf, CONF_ssh_nc_host));
8856 ssh2_pkt_adduint32(s->pktout, conf_get_int(ssh->conf, CONF_ssh_nc_port));
8858 * There's nothing meaningful to put in the originator
8859 * fields, but some servers insist on syntactically correct
8862 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
8863 ssh2_pkt_adduint32(s->pktout, 0);
8864 ssh2_pkt_send(ssh, s->pktout);
8866 crWaitUntilV(pktin);
8867 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8868 bombout(("Server refused to open a direct-tcpip channel"));
8870 /* FIXME: error data comes back in FAILURE packet */
8872 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8873 bombout(("Server's channel confirmation cited wrong channel"));
8876 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8877 ssh->mainchan->halfopen = FALSE;
8878 ssh->mainchan->type = CHAN_MAINSESSION;
8879 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8880 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8881 add234(ssh->channels, ssh->mainchan);
8882 update_specials_menu(ssh->frontend);
8883 logevent("Opened direct-tcpip channel");
8886 ssh->mainchan = snew(struct ssh_channel);
8887 ssh->mainchan->ssh = ssh;
8888 ssh2_channel_init(ssh->mainchan);
8889 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8890 ssh2_pkt_addstring(s->pktout, "session");
8891 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8892 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8893 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8894 ssh2_pkt_send(ssh, s->pktout);
8895 crWaitUntilV(pktin);
8896 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8897 bombout(("Server refused to open a session"));
8899 /* FIXME: error data comes back in FAILURE packet */
8901 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8902 bombout(("Server's channel confirmation cited wrong channel"));
8905 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8906 ssh->mainchan->halfopen = FALSE;
8907 ssh->mainchan->type = CHAN_MAINSESSION;
8908 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8909 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8910 add234(ssh->channels, ssh->mainchan);
8911 update_specials_menu(ssh->frontend);
8912 logevent("Opened channel for session");
8913 ssh->ncmode = FALSE;
8917 * Now we have a channel, make dispatch table entries for
8918 * general channel-based messages.
8920 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
8921 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
8922 ssh2_msg_channel_data;
8923 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
8924 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
8925 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
8926 ssh2_msg_channel_open_confirmation;
8927 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
8928 ssh2_msg_channel_open_failure;
8929 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
8930 ssh2_msg_channel_request;
8931 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
8932 ssh2_msg_channel_open;
8934 if (ssh->mainchan && conf_get_int(ssh->conf, CONF_ssh_simple)) {
8936 * This message indicates to the server that we promise
8937 * not to try to run any other channel in parallel with
8938 * this one, so it's safe for it to advertise a very large
8939 * window and leave the flow control to TCP.
8941 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8942 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8943 ssh2_pkt_addstring(s->pktout, "simple@putty.projects.tartarus.org");
8944 ssh2_pkt_addbool(s->pktout, 0); /* no reply */
8945 ssh2_pkt_send(ssh, s->pktout);
8949 * Potentially enable X11 forwarding.
8951 if (ssh->mainchan && !ssh->ncmode && conf_get_int(ssh->conf, CONF_x11_forward) &&
8952 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
8953 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
8954 logevent("Requesting X11 forwarding");
8955 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8956 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8957 ssh2_pkt_addstring(s->pktout, "x11-req");
8958 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8959 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
8960 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthprotoname);
8962 * Note that while we blank the X authentication data here, we don't
8963 * take any special action to blank the start of an X11 channel,
8964 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
8965 * without having session blanking enabled is likely to leak your
8966 * cookie into the log.
8968 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8969 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthdatastring);
8970 end_log_omission(ssh, s->pktout);
8971 ssh2_pkt_adduint32(s->pktout, ssh->x11disp->screennum);
8972 ssh2_pkt_send(ssh, s->pktout);
8974 crWaitUntilV(pktin);
8976 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8977 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8978 bombout(("Unexpected response to X11 forwarding request:"
8979 " packet type %d", pktin->type));
8982 logevent("X11 forwarding refused");
8984 logevent("X11 forwarding enabled");
8985 ssh->X11_fwd_enabled = TRUE;
8990 * Enable port forwardings.
8992 ssh_setup_portfwd(ssh, ssh->conf);
8995 * Potentially enable agent forwarding.
8997 if (ssh->mainchan && !ssh->ncmode && conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
8998 logevent("Requesting OpenSSH-style agent forwarding");
8999 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9000 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
9001 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
9002 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9003 ssh2_pkt_send(ssh, s->pktout);
9005 crWaitUntilV(pktin);
9007 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9008 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9009 bombout(("Unexpected response to agent forwarding request:"
9010 " packet type %d", pktin->type));
9013 logevent("Agent forwarding refused");
9015 logevent("Agent forwarding enabled");
9016 ssh->agentfwd_enabled = TRUE;
9021 * Now allocate a pty for the session.
9023 if (ssh->mainchan && !ssh->ncmode && !conf_get_int(ssh->conf, CONF_nopty)) {
9024 /* Unpick the terminal-speed string. */
9025 /* XXX perhaps we should allow no speeds to be sent. */
9026 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
9027 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
9028 /* Build the pty request. */
9029 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9030 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
9031 ssh2_pkt_addstring(s->pktout, "pty-req");
9032 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9033 ssh2_pkt_addstring(s->pktout, conf_get_str(ssh->conf, CONF_termtype));
9034 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
9035 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
9036 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
9037 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
9038 ssh2_pkt_addstring_start(s->pktout);
9039 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)s->pktout);
9040 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_ISPEED);
9041 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
9042 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_OSPEED);
9043 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
9044 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
9045 ssh2_pkt_send(ssh, s->pktout);
9046 ssh->state = SSH_STATE_INTERMED;
9048 crWaitUntilV(pktin);
9050 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9051 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9052 bombout(("Unexpected response to pty request:"
9053 " packet type %d", pktin->type));
9056 c_write_str(ssh, "Server refused to allocate pty\r\n");
9057 ssh->editing = ssh->echoing = 1;
9059 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9060 ssh->ospeed, ssh->ispeed);
9061 ssh->got_pty = TRUE;
9064 ssh->editing = ssh->echoing = 1;
9068 * Send environment variables.
9070 * Simplest thing here is to send all the requests at once, and
9071 * then wait for a whole bunch of successes or failures.
9073 if (ssh->mainchan && !ssh->ncmode) {
9078 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9080 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9081 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9082 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
9083 ssh2_pkt_addstring(s->pktout, "env");
9084 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9085 ssh2_pkt_addstring(s->pktout, key);
9086 ssh2_pkt_addstring(s->pktout, val);
9087 ssh2_pkt_send(ssh, s->pktout);
9093 logeventf(ssh, "Sent %d environment variables", s->num_env);
9096 s->env_left = s->num_env;
9098 while (s->env_left > 0) {
9099 crWaitUntilV(pktin);
9101 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9102 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9103 bombout(("Unexpected response to environment request:"
9104 " packet type %d", pktin->type));
9114 if (s->env_ok == s->num_env) {
9115 logevent("All environment variables successfully set");
9116 } else if (s->env_ok == 0) {
9117 logevent("All environment variables refused");
9118 c_write_str(ssh, "Server refused to set environment variables\r\n");
9120 logeventf(ssh, "%d environment variables refused",
9121 s->num_env - s->env_ok);
9122 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9128 * Start a shell or a remote command. We may have to attempt
9129 * this twice if the config data has provided a second choice
9132 if (ssh->mainchan && !ssh->ncmode) while (1) {
9136 if (ssh->fallback_cmd) {
9137 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
9138 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
9140 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
9141 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
9144 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9145 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
9147 ssh2_pkt_addstring(s->pktout, "subsystem");
9148 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9149 ssh2_pkt_addstring(s->pktout, cmd);
9151 ssh2_pkt_addstring(s->pktout, "exec");
9152 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9153 ssh2_pkt_addstring(s->pktout, cmd);
9155 ssh2_pkt_addstring(s->pktout, "shell");
9156 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9158 ssh2_pkt_send(ssh, s->pktout);
9160 crWaitUntilV(pktin);
9162 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9163 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9164 bombout(("Unexpected response to shell/command request:"
9165 " packet type %d", pktin->type));
9169 * We failed to start the command. If this is the
9170 * fallback command, we really are finished; if it's
9171 * not, and if the fallback command exists, try falling
9172 * back to it before complaining.
9174 if (!ssh->fallback_cmd &&
9175 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
9176 logevent("Primary command failed; attempting fallback");
9177 ssh->fallback_cmd = TRUE;
9180 bombout(("Server refused to start a shell/command"));
9183 logevent("Started a shell/command");
9188 ssh->state = SSH_STATE_SESSION;
9189 if (ssh->size_needed)
9190 ssh_size(ssh, ssh->term_width, ssh->term_height);
9191 if (ssh->eof_needed)
9192 ssh_special(ssh, TS_EOF);
9195 * All the initial channel requests are done, so install the default
9198 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_success;
9199 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_failure;
9205 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
9210 s->try_send = FALSE;
9214 * _All_ the connection-layer packets we expect to
9215 * receive are now handled by the dispatch table.
9216 * Anything that reaches here must be bogus.
9219 bombout(("Strange packet received: type %d", pktin->type));
9221 } else if (ssh->mainchan) {
9223 * We have spare data. Add it to the channel buffer.
9225 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
9230 struct ssh_channel *c;
9232 * Try to send data on all channels if we can.
9234 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
9235 ssh2_try_send_and_unthrottle(ssh, c);
9243 * Handlers for SSH-2 messages that might arrive at any moment.
9245 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
9247 /* log reason code in disconnect message */
9251 reason = ssh_pkt_getuint32(pktin);
9252 ssh_pkt_getstring(pktin, &msg, &msglen);
9254 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
9255 buf = dupprintf("Received disconnect message (%s)",
9256 ssh2_disconnect_reasons[reason]);
9258 buf = dupprintf("Received disconnect message (unknown"
9259 " type %d)", reason);
9263 buf = dupprintf("Disconnection message text: %.*s",
9266 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
9268 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
9269 ssh2_disconnect_reasons[reason] : "unknown",
9274 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
9276 /* log the debug message */
9280 /* XXX maybe we should actually take notice of the return value */
9281 ssh2_pkt_getbool(pktin);
9282 ssh_pkt_getstring(pktin, &msg, &msglen);
9284 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
9287 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
9289 struct Packet *pktout;
9290 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
9291 ssh2_pkt_adduint32(pktout, pktin->sequence);
9293 * UNIMPLEMENTED messages MUST appear in the same order as the
9294 * messages they respond to. Hence, never queue them.
9296 ssh2_pkt_send_noqueue(ssh, pktout);
9300 * Handle the top-level SSH-2 protocol.
9302 static void ssh2_protocol_setup(Ssh ssh)
9307 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9309 for (i = 0; i < 256; i++)
9310 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
9313 * Any message we actually understand, we set to NULL so that
9314 * the coroutines will get it.
9316 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
9317 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
9318 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
9319 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
9320 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
9321 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
9322 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
9323 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
9324 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
9325 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
9326 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
9327 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
9328 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
9329 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
9330 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
9331 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
9332 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
9333 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
9334 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
9335 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
9336 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
9337 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
9338 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
9339 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
9340 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
9341 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
9342 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
9343 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
9344 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
9345 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
9346 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
9347 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
9348 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
9351 * These special message types we install handlers for.
9353 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
9354 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
9355 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9358 static void ssh2_timer(void *ctx, long now)
9362 if (ssh->state == SSH_STATE_CLOSED)
9365 if (!ssh->kex_in_progress && conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
9366 now - ssh->next_rekey >= 0) {
9367 do_ssh2_transport(ssh, "timeout", -1, NULL);
9371 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
9372 struct Packet *pktin)
9374 unsigned char *in = (unsigned char *)vin;
9375 if (ssh->state == SSH_STATE_CLOSED)
9379 ssh->incoming_data_size += pktin->encrypted_len;
9380 if (!ssh->kex_in_progress &&
9381 ssh->max_data_size != 0 &&
9382 ssh->incoming_data_size > ssh->max_data_size)
9383 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9386 if (pktin && ssh->packet_dispatch[pktin->type]) {
9387 ssh->packet_dispatch[pktin->type](ssh, pktin);
9391 if (!ssh->protocol_initial_phase_done ||
9392 (pktin && pktin->type >= 20 && pktin->type < 50)) {
9393 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
9394 !ssh->protocol_initial_phase_done) {
9395 ssh->protocol_initial_phase_done = TRUE;
9397 * Allow authconn to initialise itself.
9399 do_ssh2_authconn(ssh, NULL, 0, NULL);
9402 do_ssh2_authconn(ssh, in, inlen, pktin);
9406 static void ssh_cache_conf_values(Ssh ssh)
9408 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
9412 * Called to set up the connection.
9414 * Returns an error message, or NULL on success.
9416 static const char *ssh_init(void *frontend_handle, void **backend_handle,
9417 Conf *conf, char *host, int port, char **realhost,
9418 int nodelay, int keepalive)
9423 ssh = snew(struct ssh_tag);
9424 ssh->conf = conf_copy(conf);
9425 ssh_cache_conf_values(ssh);
9426 ssh->version = 0; /* when not ready yet */
9429 ssh->v1_cipher_ctx = NULL;
9430 ssh->crcda_ctx = NULL;
9431 ssh->cscipher = NULL;
9432 ssh->cs_cipher_ctx = NULL;
9433 ssh->sccipher = NULL;
9434 ssh->sc_cipher_ctx = NULL;
9436 ssh->cs_mac_ctx = NULL;
9438 ssh->sc_mac_ctx = NULL;
9440 ssh->cs_comp_ctx = NULL;
9442 ssh->sc_comp_ctx = NULL;
9444 ssh->kex_ctx = NULL;
9445 ssh->hostkey = NULL;
9447 ssh->close_expected = FALSE;
9448 ssh->clean_exit = FALSE;
9449 ssh->state = SSH_STATE_PREPACKET;
9450 ssh->size_needed = FALSE;
9451 ssh->eof_needed = FALSE;
9454 ssh->deferred_send_data = NULL;
9455 ssh->deferred_len = 0;
9456 ssh->deferred_size = 0;
9457 ssh->fallback_cmd = 0;
9458 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9459 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9460 ssh->x11disp = NULL;
9461 ssh->v1_compressing = FALSE;
9462 ssh->v2_outgoing_sequence = 0;
9463 ssh->ssh1_rdpkt_crstate = 0;
9464 ssh->ssh2_rdpkt_crstate = 0;
9465 ssh->do_ssh_init_crstate = 0;
9466 ssh->ssh_gotdata_crstate = 0;
9467 ssh->do_ssh1_connection_crstate = 0;
9468 ssh->do_ssh1_login_crstate = 0;
9469 ssh->do_ssh2_transport_crstate = 0;
9470 ssh->do_ssh2_authconn_crstate = 0;
9471 ssh->do_ssh_init_state = NULL;
9472 ssh->do_ssh1_login_state = NULL;
9473 ssh->do_ssh2_transport_state = NULL;
9474 ssh->do_ssh2_authconn_state = NULL;
9477 ssh->mainchan = NULL;
9478 ssh->throttled_all = 0;
9479 ssh->v1_stdout_throttling = 0;
9481 ssh->queuelen = ssh->queuesize = 0;
9482 ssh->queueing = FALSE;
9483 ssh->qhead = ssh->qtail = NULL;
9484 ssh->deferred_rekey_reason = NULL;
9485 bufchain_init(&ssh->queued_incoming_data);
9486 ssh->frozen = FALSE;
9487 ssh->username = NULL;
9488 ssh->sent_console_eof = FALSE;
9489 ssh->got_pty = FALSE;
9491 *backend_handle = ssh;
9494 if (crypto_startup() == 0)
9495 return "Microsoft high encryption pack not installed!";
9498 ssh->frontend = frontend_handle;
9499 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
9500 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
9502 ssh->channels = NULL;
9503 ssh->rportfwds = NULL;
9504 ssh->portfwds = NULL;
9509 ssh->conn_throttle_count = 0;
9510 ssh->overall_bufsize = 0;
9511 ssh->fallback_cmd = 0;
9513 ssh->protocol = NULL;
9515 ssh->protocol_initial_phase_done = FALSE;
9519 ssh->incoming_data_size = ssh->outgoing_data_size =
9520 ssh->deferred_data_size = 0L;
9521 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9522 CONF_ssh_rekey_data));
9523 ssh->kex_in_progress = FALSE;
9526 ssh->gsslibs = NULL;
9529 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9538 static void ssh_free(void *handle)
9540 Ssh ssh = (Ssh) handle;
9541 struct ssh_channel *c;
9542 struct ssh_rportfwd *pf;
9544 if (ssh->v1_cipher_ctx)
9545 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9546 if (ssh->cs_cipher_ctx)
9547 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9548 if (ssh->sc_cipher_ctx)
9549 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9550 if (ssh->cs_mac_ctx)
9551 ssh->csmac->free_context(ssh->cs_mac_ctx);
9552 if (ssh->sc_mac_ctx)
9553 ssh->scmac->free_context(ssh->sc_mac_ctx);
9554 if (ssh->cs_comp_ctx) {
9556 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9558 zlib_compress_cleanup(ssh->cs_comp_ctx);
9560 if (ssh->sc_comp_ctx) {
9562 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9564 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9567 dh_cleanup(ssh->kex_ctx);
9568 sfree(ssh->savedhost);
9570 while (ssh->queuelen-- > 0)
9571 ssh_free_packet(ssh->queue[ssh->queuelen]);
9574 while (ssh->qhead) {
9575 struct queued_handler *qh = ssh->qhead;
9576 ssh->qhead = qh->next;
9579 ssh->qhead = ssh->qtail = NULL;
9581 if (ssh->channels) {
9582 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9585 if (c->u.x11.s != NULL)
9586 x11_close(c->u.x11.s);
9589 case CHAN_SOCKDATA_DORMANT:
9590 if (c->u.pfd.s != NULL)
9591 pfd_close(c->u.pfd.s);
9596 freetree234(ssh->channels);
9597 ssh->channels = NULL;
9600 if (ssh->rportfwds) {
9601 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9603 freetree234(ssh->rportfwds);
9604 ssh->rportfwds = NULL;
9606 sfree(ssh->deferred_send_data);
9608 x11_free_display(ssh->x11disp);
9609 sfree(ssh->do_ssh_init_state);
9610 sfree(ssh->do_ssh1_login_state);
9611 sfree(ssh->do_ssh2_transport_state);
9612 sfree(ssh->do_ssh2_authconn_state);
9615 sfree(ssh->fullhostname);
9616 if (ssh->crcda_ctx) {
9617 crcda_free_context(ssh->crcda_ctx);
9618 ssh->crcda_ctx = NULL;
9621 ssh_do_close(ssh, TRUE);
9622 expire_timer_context(ssh);
9624 pinger_free(ssh->pinger);
9625 bufchain_clear(&ssh->queued_incoming_data);
9626 sfree(ssh->username);
9627 conf_free(ssh->conf);
9630 ssh_gss_cleanup(ssh->gsslibs);
9638 * Reconfigure the SSH backend.
9640 static void ssh_reconfig(void *handle, Conf *conf)
9642 Ssh ssh = (Ssh) handle;
9643 char *rekeying = NULL, rekey_mandatory = FALSE;
9644 unsigned long old_max_data_size;
9647 pinger_reconfig(ssh->pinger, ssh->conf, conf);
9649 ssh_setup_portfwd(ssh, conf);
9651 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
9652 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
9654 long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
9655 long now = GETTICKCOUNT();
9657 if (new_next - now < 0) {
9658 rekeying = "timeout shortened";
9660 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
9664 old_max_data_size = ssh->max_data_size;
9665 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9666 CONF_ssh_rekey_data));
9667 if (old_max_data_size != ssh->max_data_size &&
9668 ssh->max_data_size != 0) {
9669 if (ssh->outgoing_data_size > ssh->max_data_size ||
9670 ssh->incoming_data_size > ssh->max_data_size)
9671 rekeying = "data limit lowered";
9674 if (conf_get_int(ssh->conf, CONF_compression) !=
9675 conf_get_int(conf, CONF_compression)) {
9676 rekeying = "compression setting changed";
9677 rekey_mandatory = TRUE;
9680 for (i = 0; i < CIPHER_MAX; i++)
9681 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
9682 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
9683 rekeying = "cipher settings changed";
9684 rekey_mandatory = TRUE;
9686 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
9687 conf_get_int(conf, CONF_ssh2_des_cbc)) {
9688 rekeying = "cipher settings changed";
9689 rekey_mandatory = TRUE;
9692 conf_free(ssh->conf);
9693 ssh->conf = conf_copy(conf);
9694 ssh_cache_conf_values(ssh);
9697 if (!ssh->kex_in_progress) {
9698 do_ssh2_transport(ssh, rekeying, -1, NULL);
9699 } else if (rekey_mandatory) {
9700 ssh->deferred_rekey_reason = rekeying;
9706 * Called to send data down the SSH connection.
9708 static int ssh_send(void *handle, char *buf, int len)
9710 Ssh ssh = (Ssh) handle;
9712 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9715 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
9717 return ssh_sendbuffer(ssh);
9721 * Called to query the current amount of buffered stdin data.
9723 static int ssh_sendbuffer(void *handle)
9725 Ssh ssh = (Ssh) handle;
9728 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9732 * If the SSH socket itself has backed up, add the total backup
9733 * size on that to any individual buffer on the stdin channel.
9736 if (ssh->throttled_all)
9737 override_value = ssh->overall_bufsize;
9739 if (ssh->version == 1) {
9740 return override_value;
9741 } else if (ssh->version == 2) {
9743 return override_value;
9745 return (override_value +
9746 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
9753 * Called to set the size of the window from SSH's POV.
9755 static void ssh_size(void *handle, int width, int height)
9757 Ssh ssh = (Ssh) handle;
9758 struct Packet *pktout;
9760 ssh->term_width = width;
9761 ssh->term_height = height;
9763 switch (ssh->state) {
9764 case SSH_STATE_BEFORE_SIZE:
9765 case SSH_STATE_PREPACKET:
9766 case SSH_STATE_CLOSED:
9767 break; /* do nothing */
9768 case SSH_STATE_INTERMED:
9769 ssh->size_needed = TRUE; /* buffer for later */
9771 case SSH_STATE_SESSION:
9772 if (!conf_get_int(ssh->conf, CONF_nopty)) {
9773 if (ssh->version == 1) {
9774 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
9775 PKT_INT, ssh->term_height,
9776 PKT_INT, ssh->term_width,
9777 PKT_INT, 0, PKT_INT, 0, PKT_END);
9778 } else if (ssh->mainchan) {
9779 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9780 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9781 ssh2_pkt_addstring(pktout, "window-change");
9782 ssh2_pkt_addbool(pktout, 0);
9783 ssh2_pkt_adduint32(pktout, ssh->term_width);
9784 ssh2_pkt_adduint32(pktout, ssh->term_height);
9785 ssh2_pkt_adduint32(pktout, 0);
9786 ssh2_pkt_adduint32(pktout, 0);
9787 ssh2_pkt_send(ssh, pktout);
9795 * Return a list of the special codes that make sense in this
9798 static const struct telnet_special *ssh_get_specials(void *handle)
9800 static const struct telnet_special ssh1_ignore_special[] = {
9801 {"IGNORE message", TS_NOP}
9803 static const struct telnet_special ssh2_ignore_special[] = {
9804 {"IGNORE message", TS_NOP},
9806 static const struct telnet_special ssh2_rekey_special[] = {
9807 {"Repeat key exchange", TS_REKEY},
9809 static const struct telnet_special ssh2_session_specials[] = {
9812 /* These are the signal names defined by RFC 4254.
9813 * They include all the ISO C signals, but are a subset of the POSIX
9814 * required signals. */
9815 {"SIGINT (Interrupt)", TS_SIGINT},
9816 {"SIGTERM (Terminate)", TS_SIGTERM},
9817 {"SIGKILL (Kill)", TS_SIGKILL},
9818 {"SIGQUIT (Quit)", TS_SIGQUIT},
9819 {"SIGHUP (Hangup)", TS_SIGHUP},
9820 {"More signals", TS_SUBMENU},
9821 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
9822 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
9823 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
9824 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
9827 static const struct telnet_special specials_end[] = {
9830 /* XXX review this length for any changes: */
9831 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
9832 lenof(ssh2_rekey_special) +
9833 lenof(ssh2_session_specials) +
9834 lenof(specials_end)];
9835 Ssh ssh = (Ssh) handle;
9837 #define ADD_SPECIALS(name) \
9839 assert((i + lenof(name)) <= lenof(ssh_specials)); \
9840 memcpy(&ssh_specials[i], name, sizeof name); \
9844 if (ssh->version == 1) {
9845 /* Don't bother offering IGNORE if we've decided the remote
9846 * won't cope with it, since we wouldn't bother sending it if
9848 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9849 ADD_SPECIALS(ssh1_ignore_special);
9850 } else if (ssh->version == 2) {
9851 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
9852 ADD_SPECIALS(ssh2_ignore_special);
9853 if (!(ssh->remote_bugs & BUG_SSH2_REKEY))
9854 ADD_SPECIALS(ssh2_rekey_special);
9856 ADD_SPECIALS(ssh2_session_specials);
9857 } /* else we're not ready yet */
9860 ADD_SPECIALS(specials_end);
9861 return ssh_specials;
9869 * Send special codes. TS_EOF is useful for `plink', so you
9870 * can send an EOF and collect resulting output (e.g. `plink
9873 static void ssh_special(void *handle, Telnet_Special code)
9875 Ssh ssh = (Ssh) handle;
9876 struct Packet *pktout;
9878 if (code == TS_EOF) {
9879 if (ssh->state != SSH_STATE_SESSION) {
9881 * Buffer the EOF in case we are pre-SESSION, so we can
9882 * send it as soon as we reach SESSION.
9885 ssh->eof_needed = TRUE;
9888 if (ssh->version == 1) {
9889 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
9890 } else if (ssh->mainchan) {
9891 sshfwd_write_eof(ssh->mainchan);
9892 ssh->send_ok = 0; /* now stop trying to read from stdin */
9894 logevent("Sent EOF message");
9895 } else if (code == TS_PING || code == TS_NOP) {
9896 if (ssh->state == SSH_STATE_CLOSED
9897 || ssh->state == SSH_STATE_PREPACKET) return;
9898 if (ssh->version == 1) {
9899 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9900 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
9902 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
9903 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
9904 ssh2_pkt_addstring_start(pktout);
9905 ssh2_pkt_send_noqueue(ssh, pktout);
9908 } else if (code == TS_REKEY) {
9909 if (!ssh->kex_in_progress && ssh->version == 2) {
9910 do_ssh2_transport(ssh, "at user request", -1, NULL);
9912 } else if (code == TS_BRK) {
9913 if (ssh->state == SSH_STATE_CLOSED
9914 || ssh->state == SSH_STATE_PREPACKET) return;
9915 if (ssh->version == 1) {
9916 logevent("Unable to send BREAK signal in SSH-1");
9917 } else if (ssh->mainchan) {
9918 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9919 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9920 ssh2_pkt_addstring(pktout, "break");
9921 ssh2_pkt_addbool(pktout, 0);
9922 ssh2_pkt_adduint32(pktout, 0); /* default break length */
9923 ssh2_pkt_send(ssh, pktout);
9926 /* Is is a POSIX signal? */
9927 char *signame = NULL;
9928 if (code == TS_SIGABRT) signame = "ABRT";
9929 if (code == TS_SIGALRM) signame = "ALRM";
9930 if (code == TS_SIGFPE) signame = "FPE";
9931 if (code == TS_SIGHUP) signame = "HUP";
9932 if (code == TS_SIGILL) signame = "ILL";
9933 if (code == TS_SIGINT) signame = "INT";
9934 if (code == TS_SIGKILL) signame = "KILL";
9935 if (code == TS_SIGPIPE) signame = "PIPE";
9936 if (code == TS_SIGQUIT) signame = "QUIT";
9937 if (code == TS_SIGSEGV) signame = "SEGV";
9938 if (code == TS_SIGTERM) signame = "TERM";
9939 if (code == TS_SIGUSR1) signame = "USR1";
9940 if (code == TS_SIGUSR2) signame = "USR2";
9941 /* The SSH-2 protocol does in principle support arbitrary named
9942 * signals, including signame@domain, but we don't support those. */
9944 /* It's a signal. */
9945 if (ssh->version == 2 && ssh->mainchan) {
9946 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9947 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9948 ssh2_pkt_addstring(pktout, "signal");
9949 ssh2_pkt_addbool(pktout, 0);
9950 ssh2_pkt_addstring(pktout, signame);
9951 ssh2_pkt_send(ssh, pktout);
9952 logeventf(ssh, "Sent signal SIG%s", signame);
9955 /* Never heard of it. Do nothing */
9960 void *new_sock_channel(void *handle, Socket s)
9962 Ssh ssh = (Ssh) handle;
9963 struct ssh_channel *c;
9964 c = snew(struct ssh_channel);
9967 ssh2_channel_init(c);
9969 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
9971 add234(ssh->channels, c);
9976 * This is called when stdout/stderr (the entity to which
9977 * from_backend sends data) manages to clear some backlog.
9979 static void ssh_unthrottle(void *handle, int bufsize)
9981 Ssh ssh = (Ssh) handle;
9984 if (ssh->version == 1) {
9985 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
9986 ssh->v1_stdout_throttling = 0;
9987 ssh_throttle_conn(ssh, -1);
9990 if (ssh->mainchan) {
9991 ssh2_set_window(ssh->mainchan,
9992 bufsize < ssh->mainchan->v.v2.locmaxwin ?
9993 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
9994 if (conf_get_int(ssh->conf, CONF_ssh_simple))
9997 buflimit = ssh->mainchan->v.v2.locmaxwin;
9998 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
9999 ssh->mainchan->throttling_conn = 0;
10000 ssh_throttle_conn(ssh, -1);
10006 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
10008 struct ssh_channel *c = (struct ssh_channel *)channel;
10010 struct Packet *pktout;
10012 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
10014 if (ssh->version == 1) {
10015 send_packet(ssh, SSH1_MSG_PORT_OPEN,
10016 PKT_INT, c->localid,
10019 /* PKT_STR, <org:orgport>, */
10022 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
10023 ssh2_pkt_addstring(pktout, "direct-tcpip");
10024 ssh2_pkt_adduint32(pktout, c->localid);
10025 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
10026 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
10027 ssh2_pkt_addstring(pktout, hostname);
10028 ssh2_pkt_adduint32(pktout, port);
10030 * We make up values for the originator data; partly it's
10031 * too much hassle to keep track, and partly I'm not
10032 * convinced the server should be told details like that
10033 * about my local network configuration.
10034 * The "originator IP address" is syntactically a numeric
10035 * IP address, and some servers (e.g., Tectia) get upset
10036 * if it doesn't match this syntax.
10038 ssh2_pkt_addstring(pktout, "0.0.0.0");
10039 ssh2_pkt_adduint32(pktout, 0);
10040 ssh2_pkt_send(ssh, pktout);
10044 static int ssh_connected(void *handle)
10046 Ssh ssh = (Ssh) handle;
10047 return ssh->s != NULL;
10050 static int ssh_sendok(void *handle)
10052 Ssh ssh = (Ssh) handle;
10053 return ssh->send_ok;
10056 static int ssh_ldisc(void *handle, int option)
10058 Ssh ssh = (Ssh) handle;
10059 if (option == LD_ECHO)
10060 return ssh->echoing;
10061 if (option == LD_EDIT)
10062 return ssh->editing;
10066 static void ssh_provide_ldisc(void *handle, void *ldisc)
10068 Ssh ssh = (Ssh) handle;
10069 ssh->ldisc = ldisc;
10072 static void ssh_provide_logctx(void *handle, void *logctx)
10074 Ssh ssh = (Ssh) handle;
10075 ssh->logctx = logctx;
10078 static int ssh_return_exitcode(void *handle)
10080 Ssh ssh = (Ssh) handle;
10081 if (ssh->s != NULL)
10084 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
10088 * cfg_info for SSH is the currently running version of the
10089 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
10091 static int ssh_cfg_info(void *handle)
10093 Ssh ssh = (Ssh) handle;
10094 return ssh->version;
10098 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
10099 * that fails. This variable is the means by which scp.c can reach
10100 * into the SSH code and find out which one it got.
10102 extern int ssh_fallback_cmd(void *handle)
10104 Ssh ssh = (Ssh) handle;
10105 return ssh->fallback_cmd;
10108 Backend ssh_backend = {
10118 ssh_return_exitcode,
10122 ssh_provide_logctx,