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 /* Maximum length of passwords/passphrases (arbitrary) */
521 #define SSH_MAX_PASSWORD_LEN 100
523 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
525 const static struct ssh_mac *macs[] = {
526 &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
528 const static struct ssh_mac *buggymacs[] = {
529 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
532 static void *ssh_comp_none_init(void)
536 static void ssh_comp_none_cleanup(void *handle)
539 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
540 unsigned char **outblock, int *outlen)
544 static int ssh_comp_none_disable(void *handle)
548 const static struct ssh_compress ssh_comp_none = {
550 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
551 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
552 ssh_comp_none_disable, NULL
554 extern const struct ssh_compress ssh_zlib;
555 const static struct ssh_compress *compressions[] = {
556 &ssh_zlib, &ssh_comp_none
559 enum { /* channel types */
564 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
568 * little structure to keep track of outstanding WINDOW_ADJUSTs
576 * 2-3-4 tree storing channels.
579 Ssh ssh; /* pointer back to main context */
580 unsigned remoteid, localid;
582 /* True if we opened this channel but server hasn't confirmed. */
585 * In SSH-1, this value contains four bits:
587 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
588 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
589 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
590 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
592 * A channel is completely finished with when all four bits are set.
594 * In SSH-2, the four bits mean:
596 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
597 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
598 * 4 We have received SSH2_MSG_CHANNEL_EOF.
599 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
601 * A channel is completely finished with when we have both sent
602 * and received CLOSE.
604 * The symbolic constants below use the SSH-2 terminology, which
605 * is a bit confusing in SSH-1, but we have to use _something_.
607 #define CLOSES_SENT_EOF 1
608 #define CLOSES_SENT_CLOSE 2
609 #define CLOSES_RCVD_EOF 4
610 #define CLOSES_RCVD_CLOSE 8
614 * This flag indicates that an EOF is pending on the outgoing side
615 * of the channel: that is, wherever we're getting the data for
616 * this channel has sent us some data followed by EOF. We can't
617 * actually send the EOF until we've finished sending the data, so
618 * we set this flag instead to remind us to do so once our buffer
624 * True if this channel is causing the underlying connection to be
629 struct ssh2_data_channel {
631 unsigned remwindow, remmaxpkt;
632 /* locwindow is signed so we can cope with excess data. */
633 int locwindow, locmaxwin;
635 * remlocwin is the amount of local window that we think
636 * the remote end had available to it after it sent the
637 * last data packet or window adjust ack.
641 * These store the list of window adjusts that haven't
644 struct winadj *winadj_head, *winadj_tail;
645 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
649 struct ssh_agent_channel {
650 unsigned char *message;
651 unsigned char msglen[4];
652 unsigned lensofar, totallen;
654 struct ssh_x11_channel {
657 struct ssh_pfd_channel {
664 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
665 * use this structure in different ways, reflecting SSH-2's
666 * altogether saner approach to port forwarding.
668 * In SSH-1, you arrange a remote forwarding by sending the server
669 * the remote port number, and the local destination host:port.
670 * When a connection comes in, the server sends you back that
671 * host:port pair, and you connect to it. This is a ready-made
672 * security hole if you're not on the ball: a malicious server
673 * could send you back _any_ host:port pair, so if you trustingly
674 * connect to the address it gives you then you've just opened the
675 * entire inside of your corporate network just by connecting
676 * through it to a dodgy SSH server. Hence, we must store a list of
677 * host:port pairs we _are_ trying to forward to, and reject a
678 * connection request from the server if it's not in the list.
680 * In SSH-2, each side of the connection minds its own business and
681 * doesn't send unnecessary information to the other. You arrange a
682 * remote forwarding by sending the server just the remote port
683 * number. When a connection comes in, the server tells you which
684 * of its ports was connected to; and _you_ have to remember what
685 * local host:port pair went with that port number.
687 * Hence, in SSH-1 this structure is indexed by destination
688 * host:port pair, whereas in SSH-2 it is indexed by source port.
690 struct ssh_portfwd; /* forward declaration */
692 struct ssh_rportfwd {
693 unsigned sport, dport;
696 struct ssh_portfwd *pfrec;
698 #define free_rportfwd(pf) ( \
699 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
702 * Separately to the rportfwd tree (which is for looking up port
703 * open requests from the server), a tree of _these_ structures is
704 * used to keep track of all the currently open port forwardings,
705 * so that we can reconfigure in mid-session if the user requests
709 enum { DESTROY, KEEP, CREATE } status;
711 unsigned sport, dport;
714 struct ssh_rportfwd *remote;
718 #define free_portfwd(pf) ( \
719 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
720 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
723 long length; /* length of `data' actually used */
724 long forcepad; /* SSH-2: force padding to at least this length */
725 int type; /* only used for incoming packets */
726 unsigned long sequence; /* SSH-2 incoming sequence number */
727 unsigned char *data; /* allocated storage */
728 unsigned char *body; /* offset of payload within `data' */
729 long savedpos; /* temporary index into `data' (for strings) */
730 long maxlen; /* amount of storage allocated for `data' */
731 long encrypted_len; /* for SSH-2 total-size counting */
734 * State associated with packet logging
738 struct logblank_t *blanks;
741 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
742 struct Packet *pktin);
743 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
744 struct Packet *pktin);
745 static void ssh1_protocol_setup(Ssh ssh);
746 static void ssh2_protocol_setup(Ssh ssh);
747 static void ssh_size(void *handle, int width, int height);
748 static void ssh_special(void *handle, Telnet_Special);
749 static int ssh2_try_send(struct ssh_channel *c);
750 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
751 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
752 static void ssh2_set_window(struct ssh_channel *c, int newwin);
753 static int ssh_sendbuffer(void *handle);
754 static int ssh_do_close(Ssh ssh, int notify_exit);
755 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
756 static int ssh2_pkt_getbool(struct Packet *pkt);
757 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
758 static void ssh2_timer(void *ctx, long now);
759 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
760 struct Packet *pktin);
762 struct rdpkt1_state_tag {
763 long len, pad, biglen, to_read;
764 unsigned long realcrc, gotcrc;
768 struct Packet *pktin;
771 struct rdpkt2_state_tag {
772 long len, pad, payload, packetlen, maclen;
775 unsigned long incoming_sequence;
776 struct Packet *pktin;
779 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
780 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
782 struct queued_handler;
783 struct queued_handler {
785 chandler_fn_t handler;
787 struct queued_handler *next;
791 const struct plug_function_table *fn;
792 /* the above field _must_ be first in the structure */
802 unsigned char session_key[32];
804 int v1_remote_protoflags;
805 int v1_local_protoflags;
806 int agentfwd_enabled;
809 const struct ssh_cipher *cipher;
812 const struct ssh2_cipher *cscipher, *sccipher;
813 void *cs_cipher_ctx, *sc_cipher_ctx;
814 const struct ssh_mac *csmac, *scmac;
815 void *cs_mac_ctx, *sc_mac_ctx;
816 const struct ssh_compress *cscomp, *sccomp;
817 void *cs_comp_ctx, *sc_comp_ctx;
818 const struct ssh_kex *kex;
819 const struct ssh_signkey *hostkey;
820 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
821 int v2_session_id_len;
827 int echoing, editing;
831 int ospeed, ispeed; /* temporaries */
832 int term_width, term_height;
834 tree234 *channels; /* indexed by local id */
835 struct ssh_channel *mainchan; /* primary session channel */
836 int ncmode; /* is primary channel direct-tcpip? */
841 tree234 *rportfwds, *portfwds;
845 SSH_STATE_BEFORE_SIZE,
851 int size_needed, eof_needed;
852 int sent_console_eof;
854 struct Packet **queue;
855 int queuelen, queuesize;
857 unsigned char *deferred_send_data;
858 int deferred_len, deferred_size;
861 * Gross hack: pscp will try to start SFTP but fall back to
862 * scp1 if that fails. This variable is the means by which
863 * scp.c can reach into the SSH code and find out which one it
868 bufchain banner; /* accumulates banners during do_ssh2_authconn */
873 struct X11Display *x11disp;
876 int conn_throttle_count;
879 int v1_stdout_throttling;
880 unsigned long v2_outgoing_sequence;
882 int ssh1_rdpkt_crstate;
883 int ssh2_rdpkt_crstate;
884 int do_ssh_init_crstate;
885 int ssh_gotdata_crstate;
886 int do_ssh1_login_crstate;
887 int do_ssh1_connection_crstate;
888 int do_ssh2_transport_crstate;
889 int do_ssh2_authconn_crstate;
891 void *do_ssh_init_state;
892 void *do_ssh1_login_state;
893 void *do_ssh2_transport_state;
894 void *do_ssh2_authconn_state;
896 struct rdpkt1_state_tag rdpkt1_state;
897 struct rdpkt2_state_tag rdpkt2_state;
899 /* SSH-1 and SSH-2 use this for different things, but both use it */
900 int protocol_initial_phase_done;
902 void (*protocol) (Ssh ssh, void *vin, int inlen,
904 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
907 * We maintain our own copy of a Conf structure here. That way,
908 * when we're passed a new one for reconfiguration, we can check
909 * the differences and potentially reconfigure port forwardings
910 * etc in mid-session.
915 * Values cached out of conf so as to avoid the tree234 lookup
916 * cost every time they're used.
921 * Dynamically allocated username string created during SSH
922 * login. Stored in here rather than in the coroutine state so
923 * that it'll be reliably freed if we shut down the SSH session
924 * at some unexpected moment.
929 * Used to transfer data back from async callbacks.
931 void *agent_response;
932 int agent_response_len;
936 * The SSH connection can be set as `frozen', meaning we are
937 * not currently accepting incoming data from the network. This
938 * is slightly more serious than setting the _socket_ as
939 * frozen, because we may already have had data passed to us
940 * from the network which we need to delay processing until
941 * after the freeze is lifted, so we also need a bufchain to
945 bufchain queued_incoming_data;
948 * Dispatch table for packet types that we may have to deal
951 handler_fn_t packet_dispatch[256];
954 * Queues of one-off handler functions for success/failure
955 * indications from a request.
957 struct queued_handler *qhead, *qtail;
960 * This module deals with sending keepalives.
965 * Track incoming and outgoing data sizes and time, for
968 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
969 unsigned long max_data_size;
971 long next_rekey, last_rekey;
972 char *deferred_rekey_reason; /* points to STATIC string; don't free */
975 * Fully qualified host name, which we need if doing GSSAPI.
981 * GSSAPI libraries for this session.
983 struct ssh_gss_liblist *gsslibs;
987 #define logevent(s) logevent(ssh->frontend, s)
989 /* logevent, only printf-formatted. */
990 static void logeventf(Ssh ssh, const char *fmt, ...)
996 buf = dupvprintf(fmt, ap);
1002 #define bombout(msg) \
1004 char *text = dupprintf msg; \
1005 ssh_do_close(ssh, FALSE); \
1007 connection_fatal(ssh->frontend, "%s", text); \
1011 /* Functions to leave bits out of the SSH packet log file. */
1013 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
1015 if (conf_get_int(ssh->conf, CONF_logomitpass))
1016 pkt->logmode = blanktype;
1019 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
1021 if (ssh->logomitdata)
1022 pkt->logmode = blanktype;
1025 static void end_log_omission(Ssh ssh, struct Packet *pkt)
1027 pkt->logmode = PKTLOG_EMIT;
1030 /* Helper function for common bits of parsing ttymodes. */
1031 static void parse_ttymodes(Ssh ssh,
1032 void (*do_mode)(void *data, char *mode, char *val),
1037 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
1039 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
1041 * val[0] is either 'V', indicating that an explicit value
1042 * follows it, or 'A' indicating that we should pass the
1043 * value through from the local environment via get_ttymode.
1046 val = get_ttymode(ssh->frontend, key);
1048 val++; /* skip the 'V' */
1050 do_mode(data, key, val);
1054 static int ssh_channelcmp(void *av, void *bv)
1056 struct ssh_channel *a = (struct ssh_channel *) av;
1057 struct ssh_channel *b = (struct ssh_channel *) bv;
1058 if (a->localid < b->localid)
1060 if (a->localid > b->localid)
1064 static int ssh_channelfind(void *av, void *bv)
1066 unsigned *a = (unsigned *) av;
1067 struct ssh_channel *b = (struct ssh_channel *) bv;
1068 if (*a < b->localid)
1070 if (*a > b->localid)
1075 static int ssh_rportcmp_ssh1(void *av, void *bv)
1077 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1078 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1080 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1081 return i < 0 ? -1 : +1;
1082 if (a->dport > b->dport)
1084 if (a->dport < b->dport)
1089 static int ssh_rportcmp_ssh2(void *av, void *bv)
1091 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1092 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1094 if (a->sport > b->sport)
1096 if (a->sport < b->sport)
1102 * Special form of strcmp which can cope with NULL inputs. NULL is
1103 * defined to sort before even the empty string.
1105 static int nullstrcmp(const char *a, const char *b)
1107 if (a == NULL && b == NULL)
1113 return strcmp(a, b);
1116 static int ssh_portcmp(void *av, void *bv)
1118 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1119 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1121 if (a->type > b->type)
1123 if (a->type < b->type)
1125 if (a->addressfamily > b->addressfamily)
1127 if (a->addressfamily < b->addressfamily)
1129 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1130 return i < 0 ? -1 : +1;
1131 if (a->sport > b->sport)
1133 if (a->sport < b->sport)
1135 if (a->type != 'D') {
1136 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1137 return i < 0 ? -1 : +1;
1138 if (a->dport > b->dport)
1140 if (a->dport < b->dport)
1146 static int alloc_channel_id(Ssh ssh)
1148 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1149 unsigned low, high, mid;
1151 struct ssh_channel *c;
1154 * First-fit allocation of channel numbers: always pick the
1155 * lowest unused one. To do this, binary-search using the
1156 * counted B-tree to find the largest channel ID which is in a
1157 * contiguous sequence from the beginning. (Precisely
1158 * everything in that sequence must have ID equal to its tree
1159 * index plus CHANNEL_NUMBER_OFFSET.)
1161 tsize = count234(ssh->channels);
1165 while (high - low > 1) {
1166 mid = (high + low) / 2;
1167 c = index234(ssh->channels, mid);
1168 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1169 low = mid; /* this one is fine */
1171 high = mid; /* this one is past it */
1174 * Now low points to either -1, or the tree index of the
1175 * largest ID in the initial sequence.
1178 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1179 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1181 return low + 1 + CHANNEL_NUMBER_OFFSET;
1184 static void c_write_stderr(int trusted, const char *buf, int len)
1187 for (i = 0; i < len; i++)
1188 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1189 fputc(buf[i], stderr);
1192 static void c_write(Ssh ssh, const char *buf, int len)
1194 if (flags & FLAG_STDERR)
1195 c_write_stderr(1, buf, len);
1197 from_backend(ssh->frontend, 1, buf, len);
1200 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1202 if (flags & FLAG_STDERR)
1203 c_write_stderr(0, buf, len);
1205 from_backend_untrusted(ssh->frontend, buf, len);
1208 static void c_write_str(Ssh ssh, const char *buf)
1210 c_write(ssh, buf, strlen(buf));
1213 static void ssh_free_packet(struct Packet *pkt)
1218 static struct Packet *ssh_new_packet(void)
1220 struct Packet *pkt = snew(struct Packet);
1222 pkt->body = pkt->data = NULL;
1224 pkt->logmode = PKTLOG_EMIT;
1232 * Collect incoming data in the incoming packet buffer.
1233 * Decipher and verify the packet when it is completely read.
1234 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1235 * Update the *data and *datalen variables.
1236 * Return a Packet structure when a packet is completed.
1238 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1240 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1242 crBegin(ssh->ssh1_rdpkt_crstate);
1244 st->pktin = ssh_new_packet();
1246 st->pktin->type = 0;
1247 st->pktin->length = 0;
1249 for (st->i = st->len = 0; st->i < 4; st->i++) {
1250 while ((*datalen) == 0)
1252 st->len = (st->len << 8) + **data;
1253 (*data)++, (*datalen)--;
1256 st->pad = 8 - (st->len % 8);
1257 st->biglen = st->len + st->pad;
1258 st->pktin->length = st->len - 5;
1260 if (st->biglen < 0) {
1261 bombout(("Extremely large packet length from server suggests"
1262 " data stream corruption"));
1263 ssh_free_packet(st->pktin);
1267 st->pktin->maxlen = st->biglen;
1268 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1270 st->to_read = st->biglen;
1271 st->p = st->pktin->data;
1272 while (st->to_read > 0) {
1273 st->chunk = st->to_read;
1274 while ((*datalen) == 0)
1276 if (st->chunk > (*datalen))
1277 st->chunk = (*datalen);
1278 memcpy(st->p, *data, st->chunk);
1280 *datalen -= st->chunk;
1282 st->to_read -= st->chunk;
1285 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1286 st->biglen, NULL)) {
1287 bombout(("Network attack (CRC compensation) detected!"));
1288 ssh_free_packet(st->pktin);
1293 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1295 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1296 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1297 if (st->gotcrc != st->realcrc) {
1298 bombout(("Incorrect CRC received on packet"));
1299 ssh_free_packet(st->pktin);
1303 st->pktin->body = st->pktin->data + st->pad + 1;
1304 st->pktin->savedpos = 0;
1306 if (ssh->v1_compressing) {
1307 unsigned char *decompblk;
1309 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1310 st->pktin->body - 1, st->pktin->length + 1,
1311 &decompblk, &decomplen)) {
1312 bombout(("Zlib decompression encountered invalid data"));
1313 ssh_free_packet(st->pktin);
1317 if (st->pktin->maxlen < st->pad + decomplen) {
1318 st->pktin->maxlen = st->pad + decomplen;
1319 st->pktin->data = sresize(st->pktin->data,
1320 st->pktin->maxlen + APIEXTRA,
1322 st->pktin->body = st->pktin->data + st->pad + 1;
1325 memcpy(st->pktin->body - 1, decompblk, decomplen);
1327 st->pktin->length = decomplen - 1;
1330 st->pktin->type = st->pktin->body[-1];
1333 * Log incoming packet, possibly omitting sensitive fields.
1337 struct logblank_t blank;
1338 if (ssh->logomitdata) {
1339 int do_blank = FALSE, blank_prefix = 0;
1340 /* "Session data" packets - omit the data field */
1341 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1342 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1343 do_blank = TRUE; blank_prefix = 4;
1344 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1345 do_blank = TRUE; blank_prefix = 8;
1348 blank.offset = blank_prefix;
1349 blank.len = st->pktin->length;
1350 blank.type = PKTLOG_OMIT;
1354 log_packet(ssh->logctx,
1355 PKT_INCOMING, st->pktin->type,
1356 ssh1_pkt_type(st->pktin->type),
1357 st->pktin->body, st->pktin->length,
1358 nblanks, &blank, NULL);
1361 crFinish(st->pktin);
1364 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1366 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1368 crBegin(ssh->ssh2_rdpkt_crstate);
1370 st->pktin = ssh_new_packet();
1372 st->pktin->type = 0;
1373 st->pktin->length = 0;
1375 st->cipherblk = ssh->sccipher->blksize;
1378 if (st->cipherblk < 8)
1380 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1382 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1385 * When dealing with a CBC-mode cipher, we want to avoid the
1386 * possibility of an attacker's tweaking the ciphertext stream
1387 * so as to cause us to feed the same block to the block
1388 * cipher more than once and thus leak information
1389 * (VU#958563). The way we do this is not to take any
1390 * decisions on the basis of anything we've decrypted until
1391 * we've verified it with a MAC. That includes the packet
1392 * length, so we just read data and check the MAC repeatedly,
1393 * and when the MAC passes, see if the length we've got is
1397 /* May as well allocate the whole lot now. */
1398 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1401 /* Read an amount corresponding to the MAC. */
1402 for (st->i = 0; st->i < st->maclen; st->i++) {
1403 while ((*datalen) == 0)
1405 st->pktin->data[st->i] = *(*data)++;
1411 unsigned char seq[4];
1412 ssh->scmac->start(ssh->sc_mac_ctx);
1413 PUT_32BIT(seq, st->incoming_sequence);
1414 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1417 for (;;) { /* Once around this loop per cipher block. */
1418 /* Read another cipher-block's worth, and tack it onto the end. */
1419 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1420 while ((*datalen) == 0)
1422 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1425 /* Decrypt one more block (a little further back in the stream). */
1426 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1427 st->pktin->data + st->packetlen,
1429 /* Feed that block to the MAC. */
1430 ssh->scmac->bytes(ssh->sc_mac_ctx,
1431 st->pktin->data + st->packetlen, st->cipherblk);
1432 st->packetlen += st->cipherblk;
1433 /* See if that gives us a valid packet. */
1434 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1435 st->pktin->data + st->packetlen) &&
1436 (st->len = GET_32BIT(st->pktin->data)) + 4 == st->packetlen)
1438 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1439 bombout(("No valid incoming packet found"));
1440 ssh_free_packet(st->pktin);
1444 st->pktin->maxlen = st->packetlen + st->maclen;
1445 st->pktin->data = sresize(st->pktin->data,
1446 st->pktin->maxlen + APIEXTRA,
1449 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1452 * Acquire and decrypt the first block of the packet. This will
1453 * contain the length and padding details.
1455 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1456 while ((*datalen) == 0)
1458 st->pktin->data[st->i] = *(*data)++;
1463 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1464 st->pktin->data, st->cipherblk);
1467 * Now get the length figure.
1469 st->len = GET_32BIT(st->pktin->data);
1472 * _Completely_ silly lengths should be stomped on before they
1473 * do us any more damage.
1475 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1476 (st->len + 4) % st->cipherblk != 0) {
1477 bombout(("Incoming packet was garbled on decryption"));
1478 ssh_free_packet(st->pktin);
1483 * So now we can work out the total packet length.
1485 st->packetlen = st->len + 4;
1488 * Allocate memory for the rest of the packet.
1490 st->pktin->maxlen = st->packetlen + st->maclen;
1491 st->pktin->data = sresize(st->pktin->data,
1492 st->pktin->maxlen + APIEXTRA,
1496 * Read and decrypt the remainder of the packet.
1498 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1500 while ((*datalen) == 0)
1502 st->pktin->data[st->i] = *(*data)++;
1505 /* Decrypt everything _except_ the MAC. */
1507 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1508 st->pktin->data + st->cipherblk,
1509 st->packetlen - st->cipherblk);
1515 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1516 st->len + 4, st->incoming_sequence)) {
1517 bombout(("Incorrect MAC received on packet"));
1518 ssh_free_packet(st->pktin);
1522 /* Get and sanity-check the amount of random padding. */
1523 st->pad = st->pktin->data[4];
1524 if (st->pad < 4 || st->len - st->pad < 1) {
1525 bombout(("Invalid padding length on received packet"));
1526 ssh_free_packet(st->pktin);
1530 * This enables us to deduce the payload length.
1532 st->payload = st->len - st->pad - 1;
1534 st->pktin->length = st->payload + 5;
1535 st->pktin->encrypted_len = st->packetlen;
1537 st->pktin->sequence = st->incoming_sequence++;
1540 * Decompress packet payload.
1543 unsigned char *newpayload;
1546 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1547 st->pktin->data + 5, st->pktin->length - 5,
1548 &newpayload, &newlen)) {
1549 if (st->pktin->maxlen < newlen + 5) {
1550 st->pktin->maxlen = newlen + 5;
1551 st->pktin->data = sresize(st->pktin->data,
1552 st->pktin->maxlen + APIEXTRA,
1555 st->pktin->length = 5 + newlen;
1556 memcpy(st->pktin->data + 5, newpayload, newlen);
1561 st->pktin->savedpos = 6;
1562 st->pktin->body = st->pktin->data;
1563 st->pktin->type = st->pktin->data[5];
1566 * Log incoming packet, possibly omitting sensitive fields.
1570 struct logblank_t blank;
1571 if (ssh->logomitdata) {
1572 int do_blank = FALSE, blank_prefix = 0;
1573 /* "Session data" packets - omit the data field */
1574 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1575 do_blank = TRUE; blank_prefix = 8;
1576 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1577 do_blank = TRUE; blank_prefix = 12;
1580 blank.offset = blank_prefix;
1581 blank.len = (st->pktin->length-6) - blank_prefix;
1582 blank.type = PKTLOG_OMIT;
1586 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1587 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1589 st->pktin->data+6, st->pktin->length-6,
1590 nblanks, &blank, &st->pktin->sequence);
1593 crFinish(st->pktin);
1596 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1598 int pad, biglen, i, pktoffs;
1602 * XXX various versions of SC (including 8.8.4) screw up the
1603 * register allocation in this function and use the same register
1604 * (D6) for len and as a temporary, with predictable results. The
1605 * following sledgehammer prevents this.
1612 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1613 ssh1_pkt_type(pkt->data[12]),
1614 pkt->body, pkt->length - (pkt->body - pkt->data),
1615 pkt->nblanks, pkt->blanks, NULL);
1616 sfree(pkt->blanks); pkt->blanks = NULL;
1619 if (ssh->v1_compressing) {
1620 unsigned char *compblk;
1622 zlib_compress_block(ssh->cs_comp_ctx,
1623 pkt->data + 12, pkt->length - 12,
1624 &compblk, &complen);
1625 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1626 memcpy(pkt->data + 12, compblk, complen);
1628 pkt->length = complen + 12;
1631 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1633 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1634 pad = 8 - (len % 8);
1636 biglen = len + pad; /* len(padding+type+data+CRC) */
1638 for (i = pktoffs; i < 4+8; i++)
1639 pkt->data[i] = random_byte();
1640 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1641 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1642 PUT_32BIT(pkt->data + pktoffs, len);
1645 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1646 pkt->data + pktoffs + 4, biglen);
1648 if (offset_p) *offset_p = pktoffs;
1649 return biglen + 4; /* len(length+padding+type+data+CRC) */
1652 static int s_write(Ssh ssh, void *data, int len)
1655 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1657 return sk_write(ssh->s, (char *)data, len);
1660 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1662 int len, backlog, offset;
1663 len = s_wrpkt_prepare(ssh, pkt, &offset);
1664 backlog = s_write(ssh, pkt->data + offset, len);
1665 if (backlog > SSH_MAX_BACKLOG)
1666 ssh_throttle_all(ssh, 1, backlog);
1667 ssh_free_packet(pkt);
1670 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1673 len = s_wrpkt_prepare(ssh, pkt, &offset);
1674 if (ssh->deferred_len + len > ssh->deferred_size) {
1675 ssh->deferred_size = ssh->deferred_len + len + 128;
1676 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1680 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1681 pkt->data + offset, len);
1682 ssh->deferred_len += len;
1683 ssh_free_packet(pkt);
1687 * Construct a SSH-1 packet with the specified contents.
1688 * (This all-at-once interface used to be the only one, but now SSH-1
1689 * packets can also be constructed incrementally.)
1691 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1697 pkt = ssh1_pkt_init(pkttype);
1699 while ((argtype = va_arg(ap, int)) != PKT_END) {
1700 unsigned char *argp, argchar;
1702 unsigned long argint;
1705 /* Actual fields in the packet */
1707 argint = va_arg(ap, int);
1708 ssh_pkt_adduint32(pkt, argint);
1711 argchar = (unsigned char) va_arg(ap, int);
1712 ssh_pkt_addbyte(pkt, argchar);
1715 argp = va_arg(ap, unsigned char *);
1716 arglen = va_arg(ap, int);
1717 ssh_pkt_adddata(pkt, argp, arglen);
1720 sargp = va_arg(ap, char *);
1721 ssh_pkt_addstring(pkt, sargp);
1724 bn = va_arg(ap, Bignum);
1725 ssh1_pkt_addmp(pkt, bn);
1727 /* Tokens for modifications to packet logging */
1729 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1732 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1735 end_log_omission(ssh, pkt);
1743 static void send_packet(Ssh ssh, int pkttype, ...)
1747 va_start(ap, pkttype);
1748 pkt = construct_packet(ssh, pkttype, ap);
1753 static void defer_packet(Ssh ssh, int pkttype, ...)
1757 va_start(ap, pkttype);
1758 pkt = construct_packet(ssh, pkttype, ap);
1760 s_wrpkt_defer(ssh, pkt);
1763 static int ssh_versioncmp(char *a, char *b)
1766 unsigned long av, bv;
1768 av = strtoul(a, &ae, 10);
1769 bv = strtoul(b, &be, 10);
1771 return (av < bv ? -1 : +1);
1776 av = strtoul(ae, &ae, 10);
1777 bv = strtoul(be, &be, 10);
1779 return (av < bv ? -1 : +1);
1784 * Utility routines for putting an SSH-protocol `string' and
1785 * `uint32' into a hash state.
1787 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1789 unsigned char lenblk[4];
1790 PUT_32BIT(lenblk, len);
1791 h->bytes(s, lenblk, 4);
1792 h->bytes(s, str, len);
1795 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1797 unsigned char intblk[4];
1798 PUT_32BIT(intblk, i);
1799 h->bytes(s, intblk, 4);
1803 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1805 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1807 if (pkt->maxlen < length) {
1808 unsigned char *body = pkt->body;
1809 int offset = body ? body - pkt->data : 0;
1810 pkt->maxlen = length + 256;
1811 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1812 if (body) pkt->body = pkt->data + offset;
1815 static void ssh_pkt_adddata(struct Packet *pkt, void *data, int len)
1817 if (pkt->logmode != PKTLOG_EMIT) {
1819 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1821 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1822 (pkt->body - pkt->data);
1823 pkt->blanks[pkt->nblanks-1].len = len;
1824 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1827 ssh_pkt_ensure(pkt, pkt->length);
1828 memcpy(pkt->data + pkt->length - len, data, len);
1830 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1832 ssh_pkt_adddata(pkt, &byte, 1);
1834 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1836 ssh_pkt_adddata(pkt, &value, 1);
1838 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1841 PUT_32BIT(x, value);
1842 ssh_pkt_adddata(pkt, x, 4);
1844 static void ssh_pkt_addstring_start(struct Packet *pkt)
1846 ssh_pkt_adduint32(pkt, 0);
1847 pkt->savedpos = pkt->length;
1849 static void ssh_pkt_addstring_str(struct Packet *pkt, char *data)
1851 ssh_pkt_adddata(pkt, data, strlen(data));
1852 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1854 static void ssh_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1856 ssh_pkt_adddata(pkt, data, len);
1857 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1859 static void ssh_pkt_addstring(struct Packet *pkt, char *data)
1861 ssh_pkt_addstring_start(pkt);
1862 ssh_pkt_addstring_str(pkt, data);
1864 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1866 int len = ssh1_bignum_length(b);
1867 unsigned char *data = snewn(len, unsigned char);
1868 (void) ssh1_write_bignum(data, b);
1869 ssh_pkt_adddata(pkt, data, len);
1872 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1875 int i, n = (bignum_bitcount(b) + 7) / 8;
1876 p = snewn(n + 1, unsigned char);
1878 for (i = 1; i <= n; i++)
1879 p[i] = bignum_byte(b, n - i);
1881 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1883 memmove(p, p + i, n + 1 - i);
1887 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1891 p = ssh2_mpint_fmt(b, &len);
1892 ssh_pkt_addstring_start(pkt);
1893 ssh_pkt_addstring_data(pkt, (char *)p, len);
1897 static struct Packet *ssh1_pkt_init(int pkt_type)
1899 struct Packet *pkt = ssh_new_packet();
1900 pkt->length = 4 + 8; /* space for length + max padding */
1901 ssh_pkt_addbyte(pkt, pkt_type);
1902 pkt->body = pkt->data + pkt->length;
1906 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1907 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1908 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1909 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1910 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1911 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1912 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1913 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1914 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1916 static struct Packet *ssh2_pkt_init(int pkt_type)
1918 struct Packet *pkt = ssh_new_packet();
1919 pkt->length = 5; /* space for packet length + padding length */
1921 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1922 pkt->body = pkt->data + pkt->length; /* after packet type */
1927 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1928 * put the MAC on it. Final packet, ready to be sent, is stored in
1929 * pkt->data. Total length is returned.
1931 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1933 int cipherblk, maclen, padding, i;
1936 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1937 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1938 pkt->body, pkt->length - (pkt->body - pkt->data),
1939 pkt->nblanks, pkt->blanks, &ssh->v2_outgoing_sequence);
1940 sfree(pkt->blanks); pkt->blanks = NULL;
1944 * Compress packet payload.
1947 unsigned char *newpayload;
1950 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1952 &newpayload, &newlen)) {
1954 ssh2_pkt_adddata(pkt, newpayload, newlen);
1960 * Add padding. At least four bytes, and must also bring total
1961 * length (minus MAC) up to a multiple of the block size.
1962 * If pkt->forcepad is set, make sure the packet is at least that size
1965 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1966 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1968 if (pkt->length + padding < pkt->forcepad)
1969 padding = pkt->forcepad - pkt->length;
1971 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1972 assert(padding <= 255);
1973 maclen = ssh->csmac ? ssh->csmac->len : 0;
1974 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1975 pkt->data[4] = padding;
1976 for (i = 0; i < padding; i++)
1977 pkt->data[pkt->length + i] = random_byte();
1978 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1980 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1981 pkt->length + padding,
1982 ssh->v2_outgoing_sequence);
1983 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1986 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1987 pkt->data, pkt->length + padding);
1989 pkt->encrypted_len = pkt->length + padding;
1991 /* Ready-to-send packet starts at pkt->data. We return length. */
1992 return pkt->length + padding + maclen;
1996 * Routines called from the main SSH code to send packets. There
1997 * are quite a few of these, because we have two separate
1998 * mechanisms for delaying the sending of packets:
2000 * - In order to send an IGNORE message and a password message in
2001 * a single fixed-length blob, we require the ability to
2002 * concatenate the encrypted forms of those two packets _into_ a
2003 * single blob and then pass it to our <network.h> transport
2004 * layer in one go. Hence, there's a deferment mechanism which
2005 * works after packet encryption.
2007 * - In order to avoid sending any connection-layer messages
2008 * during repeat key exchange, we have to queue up any such
2009 * outgoing messages _before_ they are encrypted (and in
2010 * particular before they're allocated sequence numbers), and
2011 * then send them once we've finished.
2013 * I call these mechanisms `defer' and `queue' respectively, so as
2014 * to distinguish them reasonably easily.
2016 * The functions send_noqueue() and defer_noqueue() free the packet
2017 * structure they are passed. Every outgoing packet goes through
2018 * precisely one of these functions in its life; packets passed to
2019 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2020 * these or get queued, and then when the queue is later emptied
2021 * the packets are all passed to defer_noqueue().
2023 * When using a CBC-mode cipher, it's necessary to ensure that an
2024 * attacker can't provide data to be encrypted using an IV that they
2025 * know. We ensure this by prefixing each packet that might contain
2026 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2027 * mechanism, so in this case send_noqueue() ends up redirecting to
2028 * defer_noqueue(). If you don't like this inefficiency, don't use
2032 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2033 static void ssh_pkt_defersend(Ssh);
2036 * Send an SSH-2 packet immediately, without queuing or deferring.
2038 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2042 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2043 /* We need to send two packets, so use the deferral mechanism. */
2044 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2045 ssh_pkt_defersend(ssh);
2048 len = ssh2_pkt_construct(ssh, pkt);
2049 backlog = s_write(ssh, pkt->data, len);
2050 if (backlog > SSH_MAX_BACKLOG)
2051 ssh_throttle_all(ssh, 1, backlog);
2053 ssh->outgoing_data_size += pkt->encrypted_len;
2054 if (!ssh->kex_in_progress &&
2055 ssh->max_data_size != 0 &&
2056 ssh->outgoing_data_size > ssh->max_data_size)
2057 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2059 ssh_free_packet(pkt);
2063 * Defer an SSH-2 packet.
2065 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2068 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2069 ssh->deferred_len == 0 && !noignore &&
2070 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2072 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2073 * get encrypted with a known IV.
2075 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2076 ssh2_pkt_addstring_start(ipkt);
2077 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2079 len = ssh2_pkt_construct(ssh, pkt);
2080 if (ssh->deferred_len + len > ssh->deferred_size) {
2081 ssh->deferred_size = ssh->deferred_len + len + 128;
2082 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2086 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
2087 ssh->deferred_len += len;
2088 ssh->deferred_data_size += pkt->encrypted_len;
2089 ssh_free_packet(pkt);
2093 * Queue an SSH-2 packet.
2095 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2097 assert(ssh->queueing);
2099 if (ssh->queuelen >= ssh->queuesize) {
2100 ssh->queuesize = ssh->queuelen + 32;
2101 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2104 ssh->queue[ssh->queuelen++] = pkt;
2108 * Either queue or send a packet, depending on whether queueing is
2111 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2114 ssh2_pkt_queue(ssh, pkt);
2116 ssh2_pkt_send_noqueue(ssh, pkt);
2120 * Either queue or defer a packet, depending on whether queueing is
2123 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2126 ssh2_pkt_queue(ssh, pkt);
2128 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2132 * Send the whole deferred data block constructed by
2133 * ssh2_pkt_defer() or SSH-1's defer_packet().
2135 * The expected use of the defer mechanism is that you call
2136 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2137 * not currently queueing, this simply sets up deferred_send_data
2138 * and then sends it. If we _are_ currently queueing, the calls to
2139 * ssh2_pkt_defer() put the deferred packets on to the queue
2140 * instead, and therefore ssh_pkt_defersend() has no deferred data
2141 * to send. Hence, there's no need to make it conditional on
2144 static void ssh_pkt_defersend(Ssh ssh)
2147 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2148 ssh->deferred_len = ssh->deferred_size = 0;
2149 sfree(ssh->deferred_send_data);
2150 ssh->deferred_send_data = NULL;
2151 if (backlog > SSH_MAX_BACKLOG)
2152 ssh_throttle_all(ssh, 1, backlog);
2154 ssh->outgoing_data_size += ssh->deferred_data_size;
2155 if (!ssh->kex_in_progress &&
2156 ssh->max_data_size != 0 &&
2157 ssh->outgoing_data_size > ssh->max_data_size)
2158 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2159 ssh->deferred_data_size = 0;
2163 * Send a packet whose length needs to be disguised (typically
2164 * passwords or keyboard-interactive responses).
2166 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2172 * The simplest way to do this is to adjust the
2173 * variable-length padding field in the outgoing packet.
2175 * Currently compiled out, because some Cisco SSH servers
2176 * don't like excessively padded packets (bah, why's it
2179 pkt->forcepad = padsize;
2180 ssh2_pkt_send(ssh, pkt);
2185 * If we can't do that, however, an alternative approach is
2186 * to use the pkt_defer mechanism to bundle the packet
2187 * tightly together with an SSH_MSG_IGNORE such that their
2188 * combined length is a constant. So first we construct the
2189 * final form of this packet and defer its sending.
2191 ssh2_pkt_defer(ssh, pkt);
2194 * Now construct an SSH_MSG_IGNORE which includes a string
2195 * that's an exact multiple of the cipher block size. (If
2196 * the cipher is NULL so that the block size is
2197 * unavailable, we don't do this trick at all, because we
2198 * gain nothing by it.)
2200 if (ssh->cscipher &&
2201 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2204 stringlen = (256 - ssh->deferred_len);
2205 stringlen += ssh->cscipher->blksize - 1;
2206 stringlen -= (stringlen % ssh->cscipher->blksize);
2209 * Temporarily disable actual compression, so we
2210 * can guarantee to get this string exactly the
2211 * length we want it. The compression-disabling
2212 * routine should return an integer indicating how
2213 * many bytes we should adjust our string length
2217 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2219 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2220 ssh2_pkt_addstring_start(pkt);
2221 for (i = 0; i < stringlen; i++) {
2222 char c = (char) random_byte();
2223 ssh2_pkt_addstring_data(pkt, &c, 1);
2225 ssh2_pkt_defer(ssh, pkt);
2227 ssh_pkt_defersend(ssh);
2232 * Send all queued SSH-2 packets. We send them by means of
2233 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2234 * packets that needed to be lumped together.
2236 static void ssh2_pkt_queuesend(Ssh ssh)
2240 assert(!ssh->queueing);
2242 for (i = 0; i < ssh->queuelen; i++)
2243 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2246 ssh_pkt_defersend(ssh);
2250 void bndebug(char *string, Bignum b)
2254 p = ssh2_mpint_fmt(b, &len);
2255 debug(("%s", string));
2256 for (i = 0; i < len; i++)
2257 debug((" %02x", p[i]));
2263 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2267 p = ssh2_mpint_fmt(b, &len);
2268 hash_string(h, s, p, len);
2273 * Packet decode functions for both SSH-1 and SSH-2.
2275 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2277 unsigned long value;
2278 if (pkt->length - pkt->savedpos < 4)
2279 return 0; /* arrgh, no way to decline (FIXME?) */
2280 value = GET_32BIT(pkt->body + pkt->savedpos);
2284 static int ssh2_pkt_getbool(struct Packet *pkt)
2286 unsigned long value;
2287 if (pkt->length - pkt->savedpos < 1)
2288 return 0; /* arrgh, no way to decline (FIXME?) */
2289 value = pkt->body[pkt->savedpos] != 0;
2293 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2298 if (pkt->length - pkt->savedpos < 4)
2300 len = GET_32BIT(pkt->body + pkt->savedpos);
2305 if (pkt->length - pkt->savedpos < *length)
2307 *p = (char *)(pkt->body + pkt->savedpos);
2308 pkt->savedpos += *length;
2310 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2312 if (pkt->length - pkt->savedpos < length)
2314 pkt->savedpos += length;
2315 return pkt->body + (pkt->savedpos - length);
2317 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2318 unsigned char **keystr)
2322 j = makekey(pkt->body + pkt->savedpos,
2323 pkt->length - pkt->savedpos,
2330 assert(pkt->savedpos < pkt->length);
2334 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2339 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2340 pkt->length - pkt->savedpos, &b);
2348 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2354 ssh_pkt_getstring(pkt, &p, &length);
2359 b = bignum_from_bytes((unsigned char *)p, length);
2364 * Helper function to add an SSH-2 signature blob to a packet.
2365 * Expects to be shown the public key blob as well as the signature
2366 * blob. Normally works just like ssh2_pkt_addstring, but will
2367 * fiddle with the signature packet if necessary for
2368 * BUG_SSH2_RSA_PADDING.
2370 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2371 void *pkblob_v, int pkblob_len,
2372 void *sigblob_v, int sigblob_len)
2374 unsigned char *pkblob = (unsigned char *)pkblob_v;
2375 unsigned char *sigblob = (unsigned char *)sigblob_v;
2377 /* dmemdump(pkblob, pkblob_len); */
2378 /* dmemdump(sigblob, sigblob_len); */
2381 * See if this is in fact an ssh-rsa signature and a buggy
2382 * server; otherwise we can just do this the easy way.
2384 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
2385 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2386 int pos, len, siglen;
2389 * Find the byte length of the modulus.
2392 pos = 4+7; /* skip over "ssh-rsa" */
2393 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
2394 len = GET_32BIT(pkblob+pos); /* find length of modulus */
2395 pos += 4; /* find modulus itself */
2396 while (len > 0 && pkblob[pos] == 0)
2398 /* debug(("modulus length is %d\n", len)); */
2401 * Now find the signature integer.
2403 pos = 4+7; /* skip over "ssh-rsa" */
2404 siglen = GET_32BIT(sigblob+pos);
2405 /* debug(("signature length is %d\n", siglen)); */
2407 if (len != siglen) {
2408 unsigned char newlen[4];
2409 ssh2_pkt_addstring_start(pkt);
2410 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2411 /* dmemdump(sigblob, pos); */
2412 pos += 4; /* point to start of actual sig */
2413 PUT_32BIT(newlen, len);
2414 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2415 /* dmemdump(newlen, 4); */
2417 while (len-- > siglen) {
2418 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2419 /* dmemdump(newlen, 1); */
2421 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2422 /* dmemdump(sigblob+pos, siglen); */
2426 /* Otherwise fall through and do it the easy way. */
2429 ssh2_pkt_addstring_start(pkt);
2430 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2434 * Examine the remote side's version string and compare it against
2435 * a list of known buggy implementations.
2437 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2439 char *imp; /* pointer to implementation part */
2441 imp += strcspn(imp, "-");
2443 imp += strcspn(imp, "-");
2446 ssh->remote_bugs = 0;
2449 * General notes on server version strings:
2450 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2451 * here -- in particular, we've heard of one that's perfectly happy
2452 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2453 * so we can't distinguish them.
2455 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2456 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2457 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2458 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2459 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2460 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2462 * These versions don't support SSH1_MSG_IGNORE, so we have
2463 * to use a different defence against password length
2466 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2467 logevent("We believe remote version has SSH-1 ignore bug");
2470 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2471 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2472 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2474 * These versions need a plain password sent; they can't
2475 * handle having a null and a random length of data after
2478 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2479 logevent("We believe remote version needs a plain SSH-1 password");
2482 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2483 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2484 (!strcmp(imp, "Cisco-1.25")))) {
2486 * These versions apparently have no clue whatever about
2487 * RSA authentication and will panic and die if they see
2488 * an AUTH_RSA message.
2490 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2491 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2494 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2495 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2496 !wc_match("* VShell", imp) &&
2497 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2498 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2499 wc_match("2.1 *", imp)))) {
2501 * These versions have the HMAC bug.
2503 ssh->remote_bugs |= BUG_SSH2_HMAC;
2504 logevent("We believe remote version has SSH-2 HMAC bug");
2507 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2508 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2509 !wc_match("* VShell", imp) &&
2510 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2512 * These versions have the key-derivation bug (failing to
2513 * include the literal shared secret in the hashes that
2514 * generate the keys).
2516 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2517 logevent("We believe remote version has SSH-2 key-derivation bug");
2520 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2521 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2522 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2523 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2525 * These versions have the SSH-2 RSA padding bug.
2527 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2528 logevent("We believe remote version has SSH-2 RSA padding bug");
2531 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2532 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2533 wc_match("OpenSSH_2.[0-2]*", imp))) {
2535 * These versions have the SSH-2 session-ID bug in
2536 * public-key authentication.
2538 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2539 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2542 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2543 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2544 (wc_match("DigiSSH_2.0", imp) ||
2545 wc_match("OpenSSH_2.[0-4]*", imp) ||
2546 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2547 wc_match("Sun_SSH_1.0", imp) ||
2548 wc_match("Sun_SSH_1.0.1", imp) ||
2549 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2550 wc_match("WeOnlyDo-*", imp)))) {
2552 * These versions have the SSH-2 rekey bug.
2554 ssh->remote_bugs |= BUG_SSH2_REKEY;
2555 logevent("We believe remote version has SSH-2 rekey bug");
2558 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2559 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2560 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2561 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2563 * This version ignores our makpkt and needs to be throttled.
2565 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2566 logevent("We believe remote version ignores SSH-2 maximum packet size");
2569 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2571 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2572 * none detected automatically.
2574 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2575 logevent("We believe remote version has SSH-2 ignore bug");
2580 * The `software version' part of an SSH version string is required
2581 * to contain no spaces or minus signs.
2583 static void ssh_fix_verstring(char *str)
2585 /* Eat "SSH-<protoversion>-". */
2586 assert(*str == 'S'); str++;
2587 assert(*str == 'S'); str++;
2588 assert(*str == 'H'); str++;
2589 assert(*str == '-'); str++;
2590 while (*str && *str != '-') str++;
2591 assert(*str == '-'); str++;
2593 /* Convert minus signs and spaces in the remaining string into
2596 if (*str == '-' || *str == ' ')
2603 * Send an appropriate SSH version string.
2605 static void ssh_send_verstring(Ssh ssh, char *svers)
2609 if (ssh->version == 2) {
2611 * Construct a v2 version string.
2613 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2616 * Construct a v1 version string.
2618 verstring = dupprintf("SSH-%s-%s\012",
2619 (ssh_versioncmp(svers, "1.5") <= 0 ?
2624 ssh_fix_verstring(verstring);
2626 if (ssh->version == 2) {
2629 * Record our version string.
2631 len = strcspn(verstring, "\015\012");
2632 ssh->v_c = snewn(len + 1, char);
2633 memcpy(ssh->v_c, verstring, len);
2637 logeventf(ssh, "We claim version: %.*s",
2638 strcspn(verstring, "\015\012"), verstring);
2639 s_write(ssh, verstring, strlen(verstring));
2643 static int do_ssh_init(Ssh ssh, unsigned char c)
2645 struct do_ssh_init_state {
2653 crState(do_ssh_init_state);
2655 crBegin(ssh->do_ssh_init_crstate);
2657 /* Search for a line beginning with the string "SSH-" in the input. */
2659 if (c != 'S') goto no;
2661 if (c != 'S') goto no;
2663 if (c != 'H') goto no;
2665 if (c != '-') goto no;
2674 s->vstring = snewn(s->vstrsize, char);
2675 strcpy(s->vstring, "SSH-");
2679 crReturn(1); /* get another char */
2680 if (s->vslen >= s->vstrsize - 1) {
2682 s->vstring = sresize(s->vstring, s->vstrsize, char);
2684 s->vstring[s->vslen++] = c;
2687 s->version[s->i] = '\0';
2689 } else if (s->i < sizeof(s->version) - 1)
2690 s->version[s->i++] = c;
2691 } else if (c == '\012')
2695 ssh->agentfwd_enabled = FALSE;
2696 ssh->rdpkt2_state.incoming_sequence = 0;
2698 s->vstring[s->vslen] = 0;
2699 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2700 logeventf(ssh, "Server version: %s", s->vstring);
2701 ssh_detect_bugs(ssh, s->vstring);
2704 * Decide which SSH protocol version to support.
2707 /* Anything strictly below "2.0" means protocol 1 is supported. */
2708 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2709 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2710 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2712 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2713 bombout(("SSH protocol version 1 required by user but not provided by server"));
2716 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2717 bombout(("SSH protocol version 2 required by user but not provided by server"));
2721 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2726 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2728 /* Send the version string, if we haven't already */
2729 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
2730 ssh_send_verstring(ssh, s->version);
2732 if (ssh->version == 2) {
2735 * Record their version string.
2737 len = strcspn(s->vstring, "\015\012");
2738 ssh->v_s = snewn(len + 1, char);
2739 memcpy(ssh->v_s, s->vstring, len);
2743 * Initialise SSH-2 protocol.
2745 ssh->protocol = ssh2_protocol;
2746 ssh2_protocol_setup(ssh);
2747 ssh->s_rdpkt = ssh2_rdpkt;
2750 * Initialise SSH-1 protocol.
2752 ssh->protocol = ssh1_protocol;
2753 ssh1_protocol_setup(ssh);
2754 ssh->s_rdpkt = ssh1_rdpkt;
2756 if (ssh->version == 2)
2757 do_ssh2_transport(ssh, NULL, -1, NULL);
2759 update_specials_menu(ssh->frontend);
2760 ssh->state = SSH_STATE_BEFORE_SIZE;
2761 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
2768 static void ssh_process_incoming_data(Ssh ssh,
2769 unsigned char **data, int *datalen)
2771 struct Packet *pktin;
2773 pktin = ssh->s_rdpkt(ssh, data, datalen);
2775 ssh->protocol(ssh, NULL, 0, pktin);
2776 ssh_free_packet(pktin);
2780 static void ssh_queue_incoming_data(Ssh ssh,
2781 unsigned char **data, int *datalen)
2783 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2788 static void ssh_process_queued_incoming_data(Ssh ssh)
2791 unsigned char *data;
2794 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2795 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2799 while (!ssh->frozen && len > 0)
2800 ssh_process_incoming_data(ssh, &data, &len);
2803 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2807 static void ssh_set_frozen(Ssh ssh, int frozen)
2810 sk_set_frozen(ssh->s, frozen);
2811 ssh->frozen = frozen;
2814 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2816 /* Log raw data, if we're in that mode. */
2818 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2821 crBegin(ssh->ssh_gotdata_crstate);
2824 * To begin with, feed the characters one by one to the
2825 * protocol initialisation / selection function do_ssh_init().
2826 * When that returns 0, we're done with the initial greeting
2827 * exchange and can move on to packet discipline.
2830 int ret; /* need not be kept across crReturn */
2832 crReturnV; /* more data please */
2833 ret = do_ssh_init(ssh, *data);
2841 * We emerge from that loop when the initial negotiation is
2842 * over and we have selected an s_rdpkt function. Now pass
2843 * everything to s_rdpkt, and then pass the resulting packets
2844 * to the proper protocol handler.
2848 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2850 ssh_queue_incoming_data(ssh, &data, &datalen);
2851 /* This uses up all data and cannot cause anything interesting
2852 * to happen; indeed, for anything to happen at all, we must
2853 * return, so break out. */
2855 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2856 /* This uses up some or all data, and may freeze the
2858 ssh_process_queued_incoming_data(ssh);
2860 /* This uses up some or all data, and may freeze the
2862 ssh_process_incoming_data(ssh, &data, &datalen);
2864 /* FIXME this is probably EBW. */
2865 if (ssh->state == SSH_STATE_CLOSED)
2868 /* We're out of data. Go and get some more. */
2874 static int ssh_do_close(Ssh ssh, int notify_exit)
2877 struct ssh_channel *c;
2879 ssh->state = SSH_STATE_CLOSED;
2880 expire_timer_context(ssh);
2885 notify_remote_exit(ssh->frontend);
2890 * Now we must shut down any port- and X-forwarded channels going
2891 * through this connection.
2893 if (ssh->channels) {
2894 while (NULL != (c = index234(ssh->channels, 0))) {
2897 x11_close(c->u.x11.s);
2900 case CHAN_SOCKDATA_DORMANT:
2901 pfd_close(c->u.pfd.s);
2904 del234(ssh->channels, c); /* moving next one to index 0 */
2905 if (ssh->version == 2)
2906 bufchain_clear(&c->v.v2.outbuffer);
2911 * Go through port-forwardings, and close any associated
2912 * listening sockets.
2914 if (ssh->portfwds) {
2915 struct ssh_portfwd *pf;
2916 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2917 /* Dispose of any listening socket. */
2919 pfd_terminate(pf->local);
2920 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2923 freetree234(ssh->portfwds);
2924 ssh->portfwds = NULL;
2930 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2931 const char *error_msg, int error_code)
2933 Ssh ssh = (Ssh) plug;
2934 char addrbuf[256], *msg;
2936 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2939 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2941 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2947 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2950 Ssh ssh = (Ssh) plug;
2951 int need_notify = ssh_do_close(ssh, FALSE);
2954 if (!ssh->close_expected)
2955 error_msg = "Server unexpectedly closed network connection";
2957 error_msg = "Server closed network connection";
2960 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
2964 notify_remote_exit(ssh->frontend);
2967 logevent(error_msg);
2968 if (!ssh->close_expected || !ssh->clean_exit)
2969 connection_fatal(ssh->frontend, "%s", error_msg);
2973 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2975 Ssh ssh = (Ssh) plug;
2976 ssh_gotdata(ssh, (unsigned char *)data, len);
2977 if (ssh->state == SSH_STATE_CLOSED) {
2978 ssh_do_close(ssh, TRUE);
2984 static void ssh_sent(Plug plug, int bufsize)
2986 Ssh ssh = (Ssh) plug;
2988 * If the send backlog on the SSH socket itself clears, we
2989 * should unthrottle the whole world if it was throttled.
2991 if (bufsize < SSH_MAX_BACKLOG)
2992 ssh_throttle_all(ssh, 0, bufsize);
2996 * Connect to specified host and port.
2997 * Returns an error message, or NULL on success.
2998 * Also places the canonical host name into `realhost'. It must be
2999 * freed by the caller.
3001 static const char *connect_to_host(Ssh ssh, char *host, int port,
3002 char **realhost, int nodelay, int keepalive)
3004 static const struct plug_function_table fn_table = {
3015 int addressfamily, sshprot;
3017 loghost = conf_get_str(ssh->conf, CONF_loghost);
3021 ssh->savedhost = dupstr(loghost);
3022 ssh->savedport = 22; /* default ssh port */
3025 * A colon suffix on savedhost also lets us affect
3028 * (FIXME: do something about IPv6 address literals here.)
3030 colon = strrchr(ssh->savedhost, ':');
3034 ssh->savedport = atoi(colon);
3037 ssh->savedhost = dupstr(host);
3039 port = 22; /* default ssh port */
3040 ssh->savedport = port;
3046 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3047 logeventf(ssh, "Looking up host \"%s\"%s", host,
3048 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3049 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3050 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3051 if ((err = sk_addr_error(addr)) != NULL) {
3055 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3060 ssh->fn = &fn_table;
3061 ssh->s = new_connection(addr, *realhost, port,
3062 0, 1, nodelay, keepalive, (Plug) ssh, ssh->conf);
3063 if ((err = sk_socket_error(ssh->s)) != NULL) {
3065 notify_remote_exit(ssh->frontend);
3070 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3071 * send the version string too.
3073 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3078 ssh_send_verstring(ssh, NULL);
3082 * loghost, if configured, overrides realhost.
3086 *realhost = dupstr(loghost);
3093 * Throttle or unthrottle the SSH connection.
3095 static void ssh_throttle_conn(Ssh ssh, int adjust)
3097 int old_count = ssh->conn_throttle_count;
3098 ssh->conn_throttle_count += adjust;
3099 assert(ssh->conn_throttle_count >= 0);
3100 if (ssh->conn_throttle_count && !old_count) {
3101 ssh_set_frozen(ssh, 1);
3102 } else if (!ssh->conn_throttle_count && old_count) {
3103 ssh_set_frozen(ssh, 0);
3108 * Throttle or unthrottle _all_ local data streams (for when sends
3109 * on the SSH connection itself back up).
3111 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3114 struct ssh_channel *c;
3116 if (enable == ssh->throttled_all)
3118 ssh->throttled_all = enable;
3119 ssh->overall_bufsize = bufsize;
3122 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3124 case CHAN_MAINSESSION:
3126 * This is treated separately, outside the switch.
3130 x11_override_throttle(c->u.x11.s, enable);
3133 /* Agent channels require no buffer management. */
3136 pfd_override_throttle(c->u.pfd.s, enable);
3142 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3144 Ssh ssh = (Ssh) sshv;
3146 ssh->agent_response = reply;
3147 ssh->agent_response_len = replylen;
3149 if (ssh->version == 1)
3150 do_ssh1_login(ssh, NULL, -1, NULL);
3152 do_ssh2_authconn(ssh, NULL, -1, NULL);
3155 static void ssh_dialog_callback(void *sshv, int ret)
3157 Ssh ssh = (Ssh) sshv;
3159 ssh->user_response = ret;
3161 if (ssh->version == 1)
3162 do_ssh1_login(ssh, NULL, -1, NULL);
3164 do_ssh2_transport(ssh, NULL, -1, NULL);
3167 * This may have unfrozen the SSH connection, so do a
3170 ssh_process_queued_incoming_data(ssh);
3173 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3175 struct ssh_channel *c = (struct ssh_channel *)cv;
3177 void *sentreply = reply;
3180 /* Fake SSH_AGENT_FAILURE. */
3181 sentreply = "\0\0\0\1\5";
3184 if (ssh->version == 2) {
3185 ssh2_add_channel_data(c, sentreply, replylen);
3188 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3189 PKT_INT, c->remoteid,
3192 PKT_DATA, sentreply, replylen,
3201 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3202 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3203 * => log `wire_reason'.
3205 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3206 int code, int clean_exit)
3210 client_reason = wire_reason;
3212 error = dupprintf("Disconnected: %s", client_reason);
3214 error = dupstr("Disconnected");
3216 if (ssh->version == 1) {
3217 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3219 } else if (ssh->version == 2) {
3220 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3221 ssh2_pkt_adduint32(pktout, code);
3222 ssh2_pkt_addstring(pktout, wire_reason);
3223 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3224 ssh2_pkt_send_noqueue(ssh, pktout);
3227 ssh->close_expected = TRUE;
3228 ssh->clean_exit = clean_exit;
3229 ssh_closing((Plug)ssh, error, 0, 0);
3234 * Handle the key exchange and user authentication phases.
3236 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3237 struct Packet *pktin)
3240 unsigned char cookie[8], *ptr;
3241 struct RSAKey servkey, hostkey;
3242 struct MD5Context md5c;
3243 struct do_ssh1_login_state {
3245 unsigned char *rsabuf, *keystr1, *keystr2;
3246 unsigned long supported_ciphers_mask, supported_auths_mask;
3247 int tried_publickey, tried_agent;
3248 int tis_auth_refused, ccard_auth_refused;
3249 unsigned char session_id[16];
3251 void *publickey_blob;
3252 int publickey_bloblen;
3253 char *publickey_comment;
3254 int publickey_encrypted;
3255 prompts_t *cur_prompt;
3258 unsigned char request[5], *response, *p;
3269 crState(do_ssh1_login_state);
3271 crBegin(ssh->do_ssh1_login_crstate);
3276 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3277 bombout(("Public key packet not received"));
3281 logevent("Received public keys");
3283 ptr = ssh_pkt_getdata(pktin, 8);
3285 bombout(("SSH-1 public key packet stopped before random cookie"));
3288 memcpy(cookie, ptr, 8);
3290 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
3291 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
3292 bombout(("Failed to read SSH-1 public keys from public key packet"));
3297 * Log the host key fingerprint.
3301 logevent("Host key fingerprint is:");
3302 strcpy(logmsg, " ");
3303 hostkey.comment = NULL;
3304 rsa_fingerprint(logmsg + strlen(logmsg),
3305 sizeof(logmsg) - strlen(logmsg), &hostkey);
3309 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3310 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3311 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3312 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3313 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3315 ssh->v1_local_protoflags =
3316 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3317 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3320 MD5Update(&md5c, s->keystr2, hostkey.bytes);
3321 MD5Update(&md5c, s->keystr1, servkey.bytes);
3322 MD5Update(&md5c, cookie, 8);
3323 MD5Final(s->session_id, &md5c);
3325 for (i = 0; i < 32; i++)
3326 ssh->session_key[i] = random_byte();
3329 * Verify that the `bits' and `bytes' parameters match.
3331 if (hostkey.bits > hostkey.bytes * 8 ||
3332 servkey.bits > servkey.bytes * 8) {
3333 bombout(("SSH-1 public keys were badly formatted"));
3337 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
3339 s->rsabuf = snewn(s->len, unsigned char);
3342 * Verify the host key.
3346 * First format the key into a string.
3348 int len = rsastr_len(&hostkey);
3349 char fingerprint[100];
3350 char *keystr = snewn(len, char);
3351 rsastr_fmt(keystr, &hostkey);
3352 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
3354 ssh_set_frozen(ssh, 1);
3355 s->dlgret = verify_ssh_host_key(ssh->frontend,
3356 ssh->savedhost, ssh->savedport,
3357 "rsa", keystr, fingerprint,
3358 ssh_dialog_callback, ssh);
3360 if (s->dlgret < 0) {
3364 bombout(("Unexpected data from server while waiting"
3365 " for user host key response"));
3368 } while (pktin || inlen > 0);
3369 s->dlgret = ssh->user_response;
3371 ssh_set_frozen(ssh, 0);
3373 if (s->dlgret == 0) {
3374 ssh_disconnect(ssh, "User aborted at host key verification",
3380 for (i = 0; i < 32; i++) {
3381 s->rsabuf[i] = ssh->session_key[i];
3383 s->rsabuf[i] ^= s->session_id[i];
3386 if (hostkey.bytes > servkey.bytes) {
3387 ret = rsaencrypt(s->rsabuf, 32, &servkey);
3389 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
3391 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
3393 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
3396 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3400 logevent("Encrypted session key");
3403 int cipher_chosen = 0, warn = 0;
3404 char *cipher_string = NULL;
3406 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3407 int next_cipher = conf_get_int_int(ssh->conf,
3408 CONF_ssh_cipherlist, i);
3409 if (next_cipher == CIPHER_WARN) {
3410 /* If/when we choose a cipher, warn about it */
3412 } else if (next_cipher == CIPHER_AES) {
3413 /* XXX Probably don't need to mention this. */
3414 logevent("AES not supported in SSH-1, skipping");
3416 switch (next_cipher) {
3417 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3418 cipher_string = "3DES"; break;
3419 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3420 cipher_string = "Blowfish"; break;
3421 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3422 cipher_string = "single-DES"; break;
3424 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3428 if (!cipher_chosen) {
3429 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3430 bombout(("Server violates SSH-1 protocol by not "
3431 "supporting 3DES encryption"));
3433 /* shouldn't happen */
3434 bombout(("No supported ciphers found"));
3438 /* Warn about chosen cipher if necessary. */
3440 ssh_set_frozen(ssh, 1);
3441 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3442 ssh_dialog_callback, ssh);
3443 if (s->dlgret < 0) {
3447 bombout(("Unexpected data from server while waiting"
3448 " for user response"));
3451 } while (pktin || inlen > 0);
3452 s->dlgret = ssh->user_response;
3454 ssh_set_frozen(ssh, 0);
3455 if (s->dlgret == 0) {
3456 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3463 switch (s->cipher_type) {
3464 case SSH_CIPHER_3DES:
3465 logevent("Using 3DES encryption");
3467 case SSH_CIPHER_DES:
3468 logevent("Using single-DES encryption");
3470 case SSH_CIPHER_BLOWFISH:
3471 logevent("Using Blowfish encryption");
3475 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3476 PKT_CHAR, s->cipher_type,
3477 PKT_DATA, cookie, 8,
3478 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3479 PKT_DATA, s->rsabuf, s->len,
3480 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3482 logevent("Trying to enable encryption...");
3486 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3487 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3489 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3490 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3491 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3493 ssh->crcda_ctx = crcda_make_context();
3494 logevent("Installing CRC compensation attack detector");
3496 if (servkey.modulus) {
3497 sfree(servkey.modulus);
3498 servkey.modulus = NULL;
3500 if (servkey.exponent) {
3501 sfree(servkey.exponent);
3502 servkey.exponent = NULL;
3504 if (hostkey.modulus) {
3505 sfree(hostkey.modulus);
3506 hostkey.modulus = NULL;
3508 if (hostkey.exponent) {
3509 sfree(hostkey.exponent);
3510 hostkey.exponent = NULL;
3514 if (pktin->type != SSH1_SMSG_SUCCESS) {
3515 bombout(("Encryption not successfully enabled"));
3519 logevent("Successfully started encryption");
3521 fflush(stdout); /* FIXME eh? */
3523 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
3524 int ret; /* need not be kept over crReturn */
3525 s->cur_prompt = new_prompts(ssh->frontend);
3526 s->cur_prompt->to_server = TRUE;
3527 s->cur_prompt->name = dupstr("SSH login name");
3528 /* 512 is an arbitrary upper limit on username size */
3529 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE, 512);
3530 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3533 crWaitUntil(!pktin);
3534 ret = get_userpass_input(s->cur_prompt, in, inlen);
3539 * Failed to get a username. Terminate.
3541 free_prompts(s->cur_prompt);
3542 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3545 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
3546 free_prompts(s->cur_prompt);
3549 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
3551 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
3553 if (flags & FLAG_INTERACTIVE &&
3554 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3555 c_write_str(ssh, userlog);
3556 c_write_str(ssh, "\r\n");
3564 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3565 /* We must not attempt PK auth. Pretend we've already tried it. */
3566 s->tried_publickey = s->tried_agent = 1;
3568 s->tried_publickey = s->tried_agent = 0;
3570 s->tis_auth_refused = s->ccard_auth_refused = 0;
3572 * Load the public half of any configured keyfile for later use.
3574 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3575 if (!filename_is_null(*s->keyfile)) {
3577 logeventf(ssh, "Reading private key file \"%.150s\"",
3578 filename_to_str(s->keyfile));
3579 keytype = key_type(s->keyfile);
3580 if (keytype == SSH_KEYTYPE_SSH1) {
3582 if (rsakey_pubblob(s->keyfile,
3583 &s->publickey_blob, &s->publickey_bloblen,
3584 &s->publickey_comment, &error)) {
3585 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
3589 logeventf(ssh, "Unable to load private key (%s)", error);
3590 msgbuf = dupprintf("Unable to load private key file "
3591 "\"%.150s\" (%s)\r\n",
3592 filename_to_str(s->keyfile),
3594 c_write_str(ssh, msgbuf);
3596 s->publickey_blob = NULL;
3600 logeventf(ssh, "Unable to use this key file (%s)",
3601 key_type_to_str(keytype));
3602 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3604 filename_to_str(s->keyfile),
3605 key_type_to_str(keytype));
3606 c_write_str(ssh, msgbuf);
3608 s->publickey_blob = NULL;
3611 s->publickey_blob = NULL;
3613 while (pktin->type == SSH1_SMSG_FAILURE) {
3614 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3616 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
3618 * Attempt RSA authentication using Pageant.
3624 logevent("Pageant is running. Requesting keys.");
3626 /* Request the keys held by the agent. */
3627 PUT_32BIT(s->request, 1);
3628 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3629 if (!agent_query(s->request, 5, &r, &s->responselen,
3630 ssh_agent_callback, ssh)) {
3634 bombout(("Unexpected data from server while waiting"
3635 " for agent response"));
3638 } while (pktin || inlen > 0);
3639 r = ssh->agent_response;
3640 s->responselen = ssh->agent_response_len;
3642 s->response = (unsigned char *) r;
3643 if (s->response && s->responselen >= 5 &&
3644 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3645 s->p = s->response + 5;
3646 s->nkeys = GET_32BIT(s->p);
3648 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3649 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3650 unsigned char *pkblob = s->p;
3654 do { /* do while (0) to make breaking easy */
3655 n = ssh1_read_bignum
3656 (s->p, s->responselen-(s->p-s->response),
3661 n = ssh1_read_bignum
3662 (s->p, s->responselen-(s->p-s->response),
3667 if (s->responselen - (s->p-s->response) < 4)
3669 s->commentlen = GET_32BIT(s->p);
3671 if (s->responselen - (s->p-s->response) <
3674 s->commentp = (char *)s->p;
3675 s->p += s->commentlen;
3679 logevent("Pageant key list packet was truncated");
3683 if (s->publickey_blob) {
3684 if (!memcmp(pkblob, s->publickey_blob,
3685 s->publickey_bloblen)) {
3686 logeventf(ssh, "Pageant key #%d matches "
3687 "configured key file", s->keyi);
3688 s->tried_publickey = 1;
3690 /* Skip non-configured key */
3693 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3694 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3695 PKT_BIGNUM, s->key.modulus, PKT_END);
3697 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3698 logevent("Key refused");
3701 logevent("Received RSA challenge");
3702 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3703 bombout(("Server's RSA challenge was badly formatted"));
3708 char *agentreq, *q, *ret;
3711 len = 1 + 4; /* message type, bit count */
3712 len += ssh1_bignum_length(s->key.exponent);
3713 len += ssh1_bignum_length(s->key.modulus);
3714 len += ssh1_bignum_length(s->challenge);
3715 len += 16; /* session id */
3716 len += 4; /* response format */
3717 agentreq = snewn(4 + len, char);
3718 PUT_32BIT(agentreq, len);
3720 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3721 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3723 q += ssh1_write_bignum(q, s->key.exponent);
3724 q += ssh1_write_bignum(q, s->key.modulus);
3725 q += ssh1_write_bignum(q, s->challenge);
3726 memcpy(q, s->session_id, 16);
3728 PUT_32BIT(q, 1); /* response format */
3729 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3730 ssh_agent_callback, ssh)) {
3735 bombout(("Unexpected data from server"
3736 " while waiting for agent"
3740 } while (pktin || inlen > 0);
3741 vret = ssh->agent_response;
3742 retlen = ssh->agent_response_len;
3747 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3748 logevent("Sending Pageant's response");
3749 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3750 PKT_DATA, ret + 5, 16,
3754 if (pktin->type == SSH1_SMSG_SUCCESS) {
3756 ("Pageant's response accepted");
3757 if (flags & FLAG_VERBOSE) {
3758 c_write_str(ssh, "Authenticated using"
3760 c_write(ssh, s->commentp,
3762 c_write_str(ssh, "\" from agent\r\n");
3767 ("Pageant's response not accepted");
3770 ("Pageant failed to answer challenge");
3774 logevent("No reply received from Pageant");
3777 freebn(s->key.exponent);
3778 freebn(s->key.modulus);
3779 freebn(s->challenge);
3784 if (s->publickey_blob && !s->tried_publickey)
3785 logevent("Configured key file not in Pageant");
3787 logevent("Failed to get reply from Pageant");
3792 if (s->publickey_blob && !s->tried_publickey) {
3794 * Try public key authentication with the specified
3797 int got_passphrase; /* need not be kept over crReturn */
3798 if (flags & FLAG_VERBOSE)
3799 c_write_str(ssh, "Trying public key authentication.\r\n");
3800 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3801 logeventf(ssh, "Trying public key \"%s\"",
3802 filename_to_str(s->keyfile));
3803 s->tried_publickey = 1;
3804 got_passphrase = FALSE;
3805 while (!got_passphrase) {
3807 * Get a passphrase, if necessary.
3809 char *passphrase = NULL; /* only written after crReturn */
3811 if (!s->publickey_encrypted) {
3812 if (flags & FLAG_VERBOSE)
3813 c_write_str(ssh, "No passphrase required.\r\n");
3816 int ret; /* need not be kept over crReturn */
3817 s->cur_prompt = new_prompts(ssh->frontend);
3818 s->cur_prompt->to_server = FALSE;
3819 s->cur_prompt->name = dupstr("SSH key passphrase");
3820 add_prompt(s->cur_prompt,
3821 dupprintf("Passphrase for key \"%.100s\": ",
3822 s->publickey_comment),
3823 FALSE, SSH_MAX_PASSWORD_LEN);
3824 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3827 crWaitUntil(!pktin);
3828 ret = get_userpass_input(s->cur_prompt, in, inlen);
3832 /* Failed to get a passphrase. Terminate. */
3833 free_prompts(s->cur_prompt);
3834 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3838 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3839 free_prompts(s->cur_prompt);
3842 * Try decrypting key with passphrase.
3844 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3845 ret = loadrsakey(s->keyfile, &s->key, passphrase,
3848 memset(passphrase, 0, strlen(passphrase));
3852 /* Correct passphrase. */
3853 got_passphrase = TRUE;
3854 } else if (ret == 0) {
3855 c_write_str(ssh, "Couldn't load private key from ");
3856 c_write_str(ssh, filename_to_str(s->keyfile));
3857 c_write_str(ssh, " (");
3858 c_write_str(ssh, error);
3859 c_write_str(ssh, ").\r\n");
3860 got_passphrase = FALSE;
3861 break; /* go and try something else */
3862 } else if (ret == -1) {
3863 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3864 got_passphrase = FALSE;
3867 assert(0 && "unexpected return from loadrsakey()");
3868 got_passphrase = FALSE; /* placate optimisers */
3872 if (got_passphrase) {
3875 * Send a public key attempt.
3877 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3878 PKT_BIGNUM, s->key.modulus, PKT_END);
3881 if (pktin->type == SSH1_SMSG_FAILURE) {
3882 c_write_str(ssh, "Server refused our public key.\r\n");
3883 continue; /* go and try something else */
3885 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3886 bombout(("Bizarre response to offer of public key"));
3892 unsigned char buffer[32];
3893 Bignum challenge, response;
3895 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3896 bombout(("Server's RSA challenge was badly formatted"));
3899 response = rsadecrypt(challenge, &s->key);
3900 freebn(s->key.private_exponent);/* burn the evidence */
3902 for (i = 0; i < 32; i++) {
3903 buffer[i] = bignum_byte(response, 31 - i);
3907 MD5Update(&md5c, buffer, 32);
3908 MD5Update(&md5c, s->session_id, 16);
3909 MD5Final(buffer, &md5c);
3911 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3912 PKT_DATA, buffer, 16, PKT_END);
3919 if (pktin->type == SSH1_SMSG_FAILURE) {
3920 if (flags & FLAG_VERBOSE)
3921 c_write_str(ssh, "Failed to authenticate with"
3922 " our public key.\r\n");
3923 continue; /* go and try something else */
3924 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3925 bombout(("Bizarre response to RSA authentication response"));
3929 break; /* we're through! */
3935 * Otherwise, try various forms of password-like authentication.
3937 s->cur_prompt = new_prompts(ssh->frontend);
3939 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3940 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3941 !s->tis_auth_refused) {
3942 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3943 logevent("Requested TIS authentication");
3944 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3946 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3947 logevent("TIS authentication declined");
3948 if (flags & FLAG_INTERACTIVE)
3949 c_write_str(ssh, "TIS authentication refused.\r\n");
3950 s->tis_auth_refused = 1;
3955 char *instr_suf, *prompt;
3957 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3959 bombout(("TIS challenge packet was badly formed"));
3962 logevent("Received TIS challenge");
3963 s->cur_prompt->to_server = TRUE;
3964 s->cur_prompt->name = dupstr("SSH TIS authentication");
3965 /* Prompt heuristic comes from OpenSSH */
3966 if (memchr(challenge, '\n', challengelen)) {
3967 instr_suf = dupstr("");
3968 prompt = dupprintf("%.*s", challengelen, challenge);
3970 instr_suf = dupprintf("%.*s", challengelen, challenge);
3971 prompt = dupstr("Response: ");
3973 s->cur_prompt->instruction =
3974 dupprintf("Using TIS authentication.%s%s",
3975 (*instr_suf) ? "\n" : "",
3977 s->cur_prompt->instr_reqd = TRUE;
3978 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3982 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3983 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3984 !s->ccard_auth_refused) {
3985 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3986 logevent("Requested CryptoCard authentication");
3987 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3989 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3990 logevent("CryptoCard authentication declined");
3991 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3992 s->ccard_auth_refused = 1;
3997 char *instr_suf, *prompt;
3999 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4001 bombout(("CryptoCard challenge packet was badly formed"));
4004 logevent("Received CryptoCard challenge");
4005 s->cur_prompt->to_server = TRUE;
4006 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4007 s->cur_prompt->name_reqd = FALSE;
4008 /* Prompt heuristic comes from OpenSSH */
4009 if (memchr(challenge, '\n', challengelen)) {
4010 instr_suf = dupstr("");
4011 prompt = dupprintf("%.*s", challengelen, challenge);
4013 instr_suf = dupprintf("%.*s", challengelen, challenge);
4014 prompt = dupstr("Response: ");
4016 s->cur_prompt->instruction =
4017 dupprintf("Using CryptoCard authentication.%s%s",
4018 (*instr_suf) ? "\n" : "",
4020 s->cur_prompt->instr_reqd = TRUE;
4021 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
4025 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4026 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4027 bombout(("No supported authentication methods available"));
4030 s->cur_prompt->to_server = TRUE;
4031 s->cur_prompt->name = dupstr("SSH password");
4032 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4033 ssh->username, ssh->savedhost),
4034 FALSE, SSH_MAX_PASSWORD_LEN);
4038 * Show password prompt, having first obtained it via a TIS
4039 * or CryptoCard exchange if we're doing TIS or CryptoCard
4043 int ret; /* need not be kept over crReturn */
4044 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4047 crWaitUntil(!pktin);
4048 ret = get_userpass_input(s->cur_prompt, in, inlen);
4053 * Failed to get a password (for example
4054 * because one was supplied on the command line
4055 * which has already failed to work). Terminate.
4057 free_prompts(s->cur_prompt);
4058 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4063 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4065 * Defence against traffic analysis: we send a
4066 * whole bunch of packets containing strings of
4067 * different lengths. One of these strings is the
4068 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4069 * The others are all random data in
4070 * SSH1_MSG_IGNORE packets. This way a passive
4071 * listener can't tell which is the password, and
4072 * hence can't deduce the password length.
4074 * Anybody with a password length greater than 16
4075 * bytes is going to have enough entropy in their
4076 * password that a listener won't find it _that_
4077 * much help to know how long it is. So what we'll
4080 * - if password length < 16, we send 15 packets
4081 * containing string lengths 1 through 15
4083 * - otherwise, we let N be the nearest multiple
4084 * of 8 below the password length, and send 8
4085 * packets containing string lengths N through
4086 * N+7. This won't obscure the order of
4087 * magnitude of the password length, but it will
4088 * introduce a bit of extra uncertainty.
4090 * A few servers can't deal with SSH1_MSG_IGNORE, at
4091 * least in this context. For these servers, we need
4092 * an alternative defence. We make use of the fact
4093 * that the password is interpreted as a C string:
4094 * so we can append a NUL, then some random data.
4096 * A few servers can deal with neither SSH1_MSG_IGNORE
4097 * here _nor_ a padded password string.
4098 * For these servers we are left with no defences
4099 * against password length sniffing.
4101 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4102 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4104 * The server can deal with SSH1_MSG_IGNORE, so
4105 * we can use the primary defence.
4107 int bottom, top, pwlen, i;
4110 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4112 bottom = 0; /* zero length passwords are OK! :-) */
4115 bottom = pwlen & ~7;
4119 assert(pwlen >= bottom && pwlen <= top);
4121 randomstr = snewn(top + 1, char);
4123 for (i = bottom; i <= top; i++) {
4125 defer_packet(ssh, s->pwpkt_type,
4126 PKTT_PASSWORD, PKT_STR,
4127 s->cur_prompt->prompts[0]->result,
4128 PKTT_OTHER, PKT_END);
4130 for (j = 0; j < i; j++) {
4132 randomstr[j] = random_byte();
4133 } while (randomstr[j] == '\0');
4135 randomstr[i] = '\0';
4136 defer_packet(ssh, SSH1_MSG_IGNORE,
4137 PKT_STR, randomstr, PKT_END);
4140 logevent("Sending password with camouflage packets");
4141 ssh_pkt_defersend(ssh);
4144 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4146 * The server can't deal with SSH1_MSG_IGNORE
4147 * but can deal with padded passwords, so we
4148 * can use the secondary defence.
4154 len = strlen(s->cur_prompt->prompts[0]->result);
4155 if (len < sizeof(string)) {
4157 strcpy(string, s->cur_prompt->prompts[0]->result);
4158 len++; /* cover the zero byte */
4159 while (len < sizeof(string)) {
4160 string[len++] = (char) random_byte();
4163 ss = s->cur_prompt->prompts[0]->result;
4165 logevent("Sending length-padded password");
4166 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4167 PKT_INT, len, PKT_DATA, ss, len,
4168 PKTT_OTHER, PKT_END);
4171 * The server is believed unable to cope with
4172 * any of our password camouflage methods.
4175 len = strlen(s->cur_prompt->prompts[0]->result);
4176 logevent("Sending unpadded password");
4177 send_packet(ssh, s->pwpkt_type,
4178 PKTT_PASSWORD, PKT_INT, len,
4179 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4180 PKTT_OTHER, PKT_END);
4183 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4184 PKT_STR, s->cur_prompt->prompts[0]->result,
4185 PKTT_OTHER, PKT_END);
4187 logevent("Sent password");
4188 free_prompts(s->cur_prompt);
4190 if (pktin->type == SSH1_SMSG_FAILURE) {
4191 if (flags & FLAG_VERBOSE)
4192 c_write_str(ssh, "Access denied\r\n");
4193 logevent("Authentication refused");
4194 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4195 bombout(("Strange packet received, type %d", pktin->type));
4201 if (s->publickey_blob) {
4202 sfree(s->publickey_blob);
4203 sfree(s->publickey_comment);
4206 logevent("Authentication successful");
4211 static void ssh_channel_try_eof(struct ssh_channel *c)
4214 assert(c->pending_eof); /* precondition for calling us */
4216 return; /* can't close: not even opened yet */
4217 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4218 return; /* can't send EOF: pending outgoing data */
4220 if (ssh->version == 1) {
4221 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4223 c->closes |= CLOSES_SENT_EOF;
4225 struct Packet *pktout;
4226 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4227 ssh2_pkt_adduint32(pktout, c->remoteid);
4228 ssh2_pkt_send(ssh, pktout);
4229 c->closes |= CLOSES_SENT_EOF;
4230 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes)) {
4232 * Also send MSG_CLOSE.
4234 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4235 ssh2_pkt_adduint32(pktout, c->remoteid);
4236 ssh2_pkt_send(ssh, pktout);
4237 c->closes |= CLOSES_SENT_CLOSE;
4240 c->pending_eof = FALSE; /* we've sent it now */
4243 void sshfwd_write_eof(struct ssh_channel *c)
4247 if (ssh->state == SSH_STATE_CLOSED)
4250 if (c->closes & CLOSES_SENT_EOF)
4253 c->pending_eof = TRUE;
4254 ssh_channel_try_eof(c);
4257 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4261 if (ssh->state == SSH_STATE_CLOSED)
4264 if (ssh->version == 1) {
4265 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4266 PKT_INT, c->remoteid,
4267 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
4268 PKTT_OTHER, PKT_END);
4270 * In SSH-1 we can return 0 here - implying that forwarded
4271 * connections are never individually throttled - because
4272 * the only circumstance that can cause throttling will be
4273 * the whole SSH connection backing up, in which case
4274 * _everything_ will be throttled as a whole.
4278 ssh2_add_channel_data(c, buf, len);
4279 return ssh2_try_send(c);
4283 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4288 if (ssh->state == SSH_STATE_CLOSED)
4291 if (ssh->version == 1) {
4292 buflimit = SSH1_BUFFER_LIMIT;
4294 buflimit = c->v.v2.locmaxwin;
4295 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4297 if (c->throttling_conn && bufsize <= buflimit) {
4298 c->throttling_conn = 0;
4299 ssh_throttle_conn(ssh, -1);
4303 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4305 struct queued_handler *qh = ssh->qhead;
4309 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4312 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4313 ssh->packet_dispatch[qh->msg1] = NULL;
4316 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4317 ssh->packet_dispatch[qh->msg2] = NULL;
4321 ssh->qhead = qh->next;
4323 if (ssh->qhead->msg1 > 0) {
4324 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
4325 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4327 if (ssh->qhead->msg2 > 0) {
4328 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
4329 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4332 ssh->qhead = ssh->qtail = NULL;
4333 ssh->packet_dispatch[pktin->type] = NULL;
4336 qh->handler(ssh, pktin, qh->ctx);
4341 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4342 chandler_fn_t handler, void *ctx)
4344 struct queued_handler *qh;
4346 qh = snew(struct queued_handler);
4349 qh->handler = handler;
4353 if (ssh->qtail == NULL) {
4357 assert(ssh->packet_dispatch[qh->msg1] == NULL);
4358 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4361 assert(ssh->packet_dispatch[qh->msg2] == NULL);
4362 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4365 ssh->qtail->next = qh;
4370 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4372 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4374 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4375 SSH2_MSG_REQUEST_SUCCESS)) {
4376 logeventf(ssh, "Remote port forwarding from %s enabled",
4379 logeventf(ssh, "Remote port forwarding from %s refused",
4382 rpf = del234(ssh->rportfwds, pf);
4384 pf->pfrec->remote = NULL;
4389 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4391 struct ssh_portfwd *epf;
4395 if (!ssh->portfwds) {
4396 ssh->portfwds = newtree234(ssh_portcmp);
4399 * Go through the existing port forwardings and tag them
4400 * with status==DESTROY. Any that we want to keep will be
4401 * re-enabled (status==KEEP) as we go through the
4402 * configuration and find out which bits are the same as
4405 struct ssh_portfwd *epf;
4407 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4408 epf->status = DESTROY;
4411 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
4413 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
4414 char *kp, *kp2, *vp, *vp2;
4415 char address_family, type;
4416 int sport,dport,sserv,dserv;
4417 char *sports, *dports, *saddr, *host;
4421 address_family = 'A';
4423 if (*kp == 'A' || *kp == '4' || *kp == '6')
4424 address_family = *kp++;
4425 if (*kp == 'L' || *kp == 'R')
4428 if ((kp2 = strchr(kp, ':')) != NULL) {
4430 * There's a colon in the middle of the source port
4431 * string, which means that the part before it is
4432 * actually a source address.
4434 saddr = dupprintf("%.*s", (int)(kp2 - kp), kp);
4440 sport = atoi(sports);
4444 sport = net_service_lookup(sports);
4446 logeventf(ssh, "Service lookup failed for source"
4447 " port \"%s\"", sports);
4451 if (type == 'L' && !strcmp(val, "D")) {
4452 /* dynamic forwarding */
4459 /* ordinary forwarding */
4461 vp2 = vp + strcspn(vp, ":");
4462 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
4466 dport = atoi(dports);
4470 dport = net_service_lookup(dports);
4472 logeventf(ssh, "Service lookup failed for destination"
4473 " port \"%s\"", dports);
4478 if (sport && dport) {
4479 /* Set up a description of the source port. */
4480 struct ssh_portfwd *pfrec, *epfrec;
4482 pfrec = snew(struct ssh_portfwd);
4484 pfrec->saddr = saddr;
4485 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4486 pfrec->sport = sport;
4487 pfrec->daddr = host;
4488 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4489 pfrec->dport = dport;
4490 pfrec->local = NULL;
4491 pfrec->remote = NULL;
4492 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4493 address_family == '6' ? ADDRTYPE_IPV6 :
4496 epfrec = add234(ssh->portfwds, pfrec);
4497 if (epfrec != pfrec) {
4498 if (epfrec->status == DESTROY) {
4500 * We already have a port forwarding up and running
4501 * with precisely these parameters. Hence, no need
4502 * to do anything; simply re-tag the existing one
4505 epfrec->status = KEEP;
4508 * Anything else indicates that there was a duplicate
4509 * in our input, which we'll silently ignore.
4511 free_portfwd(pfrec);
4513 pfrec->status = CREATE;
4522 * Now go through and destroy any port forwardings which were
4525 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4526 if (epf->status == DESTROY) {
4529 message = dupprintf("%s port forwarding from %s%s%d",
4530 epf->type == 'L' ? "local" :
4531 epf->type == 'R' ? "remote" : "dynamic",
4532 epf->saddr ? epf->saddr : "",
4533 epf->saddr ? ":" : "",
4536 if (epf->type != 'D') {
4537 char *msg2 = dupprintf("%s to %s:%d", message,
4538 epf->daddr, epf->dport);
4543 logeventf(ssh, "Cancelling %s", message);
4546 /* epf->remote or epf->local may be NULL if setting up a
4547 * forwarding failed. */
4549 struct ssh_rportfwd *rpf = epf->remote;
4550 struct Packet *pktout;
4553 * Cancel the port forwarding at the server
4556 if (ssh->version == 1) {
4558 * We cannot cancel listening ports on the
4559 * server side in SSH-1! There's no message
4560 * to support it. Instead, we simply remove
4561 * the rportfwd record from the local end
4562 * so that any connections the server tries
4563 * to make on it are rejected.
4566 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4567 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4568 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4570 ssh2_pkt_addstring(pktout, epf->saddr);
4571 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4572 /* XXX: rport_acceptall may not represent
4573 * what was used to open the original connection,
4574 * since it's reconfigurable. */
4575 ssh2_pkt_addstring(pktout, "0.0.0.0");
4577 ssh2_pkt_addstring(pktout, "127.0.0.1");
4579 ssh2_pkt_adduint32(pktout, epf->sport);
4580 ssh2_pkt_send(ssh, pktout);
4583 del234(ssh->rportfwds, rpf);
4585 } else if (epf->local) {
4586 pfd_terminate(epf->local);
4589 delpos234(ssh->portfwds, i);
4591 i--; /* so we don't skip one in the list */
4595 * And finally, set up any new port forwardings (status==CREATE).
4597 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4598 if (epf->status == CREATE) {
4599 char *sportdesc, *dportdesc;
4600 sportdesc = dupprintf("%s%s%s%s%d%s",
4601 epf->saddr ? epf->saddr : "",
4602 epf->saddr ? ":" : "",
4603 epf->sserv ? epf->sserv : "",
4604 epf->sserv ? "(" : "",
4606 epf->sserv ? ")" : "");
4607 if (epf->type == 'D') {
4610 dportdesc = dupprintf("%s:%s%s%d%s",
4612 epf->dserv ? epf->dserv : "",
4613 epf->dserv ? "(" : "",
4615 epf->dserv ? ")" : "");
4618 if (epf->type == 'L') {
4619 const char *err = pfd_addforward(epf->daddr, epf->dport,
4620 epf->saddr, epf->sport,
4623 epf->addressfamily);
4625 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4626 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4627 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4628 sportdesc, dportdesc,
4629 err ? " failed: " : "", err ? err : "");
4630 } else if (epf->type == 'D') {
4631 const char *err = pfd_addforward(NULL, -1,
4632 epf->saddr, epf->sport,
4635 epf->addressfamily);
4637 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4638 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4639 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4641 err ? " failed: " : "", err ? err : "");
4643 struct ssh_rportfwd *pf;
4646 * Ensure the remote port forwardings tree exists.
4648 if (!ssh->rportfwds) {
4649 if (ssh->version == 1)
4650 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4652 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4655 pf = snew(struct ssh_rportfwd);
4656 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4657 pf->dhost[lenof(pf->dhost)-1] = '\0';
4658 pf->dport = epf->dport;
4659 pf->sport = epf->sport;
4660 if (add234(ssh->rportfwds, pf) != pf) {
4661 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4662 epf->daddr, epf->dport);
4665 logeventf(ssh, "Requesting remote port %s"
4666 " forward to %s", sportdesc, dportdesc);
4668 pf->sportdesc = sportdesc;
4673 if (ssh->version == 1) {
4674 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4675 PKT_INT, epf->sport,
4676 PKT_STR, epf->daddr,
4677 PKT_INT, epf->dport,
4679 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4681 ssh_rportfwd_succfail, pf);
4683 struct Packet *pktout;
4684 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4685 ssh2_pkt_addstring(pktout, "tcpip-forward");
4686 ssh2_pkt_addbool(pktout, 1);/* want reply */
4688 ssh2_pkt_addstring(pktout, epf->saddr);
4689 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4690 ssh2_pkt_addstring(pktout, "0.0.0.0");
4692 ssh2_pkt_addstring(pktout, "127.0.0.1");
4694 ssh2_pkt_adduint32(pktout, epf->sport);
4695 ssh2_pkt_send(ssh, pktout);
4697 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4698 SSH2_MSG_REQUEST_FAILURE,
4699 ssh_rportfwd_succfail, pf);
4708 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4711 int stringlen, bufsize;
4713 ssh_pkt_getstring(pktin, &string, &stringlen);
4714 if (string == NULL) {
4715 bombout(("Incoming terminal data packet was badly formed"));
4719 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4721 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4722 ssh->v1_stdout_throttling = 1;
4723 ssh_throttle_conn(ssh, +1);
4727 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4729 /* Remote side is trying to open a channel to talk to our
4730 * X-Server. Give them back a local channel number. */
4731 struct ssh_channel *c;
4732 int remoteid = ssh_pkt_getuint32(pktin);
4734 logevent("Received X11 connect request");
4735 /* Refuse if X11 forwarding is disabled. */
4736 if (!ssh->X11_fwd_enabled) {
4737 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4738 PKT_INT, remoteid, PKT_END);
4739 logevent("Rejected X11 connect request");
4741 c = snew(struct ssh_channel);
4744 if (x11_init(&c->u.x11.s, ssh->x11disp, c,
4745 NULL, -1, ssh->conf) != NULL) {
4746 logevent("Opening X11 forward connection failed");
4748 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4749 PKT_INT, remoteid, PKT_END);
4752 ("Opening X11 forward connection succeeded");
4753 c->remoteid = remoteid;
4754 c->halfopen = FALSE;
4755 c->localid = alloc_channel_id(ssh);
4757 c->pending_eof = FALSE;
4758 c->throttling_conn = 0;
4759 c->type = CHAN_X11; /* identify channel type */
4760 add234(ssh->channels, c);
4761 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4762 PKT_INT, c->remoteid, PKT_INT,
4763 c->localid, PKT_END);
4764 logevent("Opened X11 forward channel");
4769 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4771 /* Remote side is trying to open a channel to talk to our
4772 * agent. Give them back a local channel number. */
4773 struct ssh_channel *c;
4774 int remoteid = ssh_pkt_getuint32(pktin);
4776 /* Refuse if agent forwarding is disabled. */
4777 if (!ssh->agentfwd_enabled) {
4778 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4779 PKT_INT, remoteid, PKT_END);
4781 c = snew(struct ssh_channel);
4783 c->remoteid = remoteid;
4784 c->halfopen = FALSE;
4785 c->localid = alloc_channel_id(ssh);
4787 c->pending_eof = FALSE;
4788 c->throttling_conn = 0;
4789 c->type = CHAN_AGENT; /* identify channel type */
4790 c->u.a.lensofar = 0;
4791 c->u.a.message = NULL;
4792 add234(ssh->channels, c);
4793 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4794 PKT_INT, c->remoteid, PKT_INT, c->localid,
4799 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4801 /* Remote side is trying to open a channel to talk to a
4802 * forwarded port. Give them back a local channel number. */
4803 struct ssh_channel *c;
4804 struct ssh_rportfwd pf, *pfp;
4809 c = snew(struct ssh_channel);
4812 remoteid = ssh_pkt_getuint32(pktin);
4813 ssh_pkt_getstring(pktin, &host, &hostsize);
4814 port = ssh_pkt_getuint32(pktin);
4816 if (hostsize >= lenof(pf.dhost))
4817 hostsize = lenof(pf.dhost)-1;
4818 memcpy(pf.dhost, host, hostsize);
4819 pf.dhost[hostsize] = '\0';
4821 pfp = find234(ssh->rportfwds, &pf, NULL);
4824 logeventf(ssh, "Rejected remote port open request for %s:%d",
4826 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4827 PKT_INT, remoteid, PKT_END);
4829 logeventf(ssh, "Received remote port open request for %s:%d",
4831 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4832 c, ssh->conf, pfp->pfrec->addressfamily);
4834 logeventf(ssh, "Port open failed: %s", e);
4836 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4837 PKT_INT, remoteid, PKT_END);
4839 c->remoteid = remoteid;
4840 c->halfopen = FALSE;
4841 c->localid = alloc_channel_id(ssh);
4843 c->pending_eof = FALSE;
4844 c->throttling_conn = 0;
4845 c->type = CHAN_SOCKDATA; /* identify channel type */
4846 add234(ssh->channels, c);
4847 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4848 PKT_INT, c->remoteid, PKT_INT,
4849 c->localid, PKT_END);
4850 logevent("Forwarded port opened successfully");
4855 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4857 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4858 unsigned int localid = ssh_pkt_getuint32(pktin);
4859 struct ssh_channel *c;
4861 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4862 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4863 c->remoteid = localid;
4864 c->halfopen = FALSE;
4865 c->type = CHAN_SOCKDATA;
4866 c->throttling_conn = 0;
4867 pfd_confirm(c->u.pfd.s);
4870 if (c && c->pending_eof) {
4872 * We have a pending close on this channel,
4873 * which we decided on before the server acked
4874 * the channel open. So now we know the
4875 * remoteid, we can close it again.
4877 ssh_channel_try_eof(c);
4881 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4883 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4884 struct ssh_channel *c;
4886 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4887 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4888 logevent("Forwarded connection refused by server");
4889 pfd_close(c->u.pfd.s);
4890 del234(ssh->channels, c);
4895 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4897 /* Remote side closes a channel. */
4898 unsigned i = ssh_pkt_getuint32(pktin);
4899 struct ssh_channel *c;
4900 c = find234(ssh->channels, &i, ssh_channelfind);
4901 if (c && !c->halfopen) {
4903 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
4904 !(c->closes & CLOSES_RCVD_EOF)) {
4906 * Received CHANNEL_CLOSE, which we translate into
4909 int send_close = FALSE;
4911 c->closes |= CLOSES_RCVD_EOF;
4916 x11_send_eof(c->u.x11.s);
4921 x11_send_eof(c->u.pfd.s);
4928 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
4929 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4931 c->closes |= CLOSES_SENT_EOF;
4935 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
4936 !(c->closes & CLOSES_RCVD_CLOSE)) {
4938 if (!(c->closes & CLOSES_SENT_EOF)) {
4939 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
4940 " for which we never sent CHANNEL_CLOSE\n", i));
4943 c->closes |= CLOSES_RCVD_CLOSE;
4946 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
4947 !(c->closes & CLOSES_SENT_CLOSE)) {
4948 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
4949 PKT_INT, c->remoteid, PKT_END);
4950 c->closes |= CLOSES_SENT_CLOSE;
4953 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
4954 ssh_channel_destroy(c);
4956 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4957 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4958 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4963 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4965 /* Data sent down one of our channels. */
4966 int i = ssh_pkt_getuint32(pktin);
4969 struct ssh_channel *c;
4971 ssh_pkt_getstring(pktin, &p, &len);
4973 c = find234(ssh->channels, &i, ssh_channelfind);
4978 bufsize = x11_send(c->u.x11.s, p, len);
4981 bufsize = pfd_send(c->u.pfd.s, p, len);
4984 /* Data for an agent message. Buffer it. */
4986 if (c->u.a.lensofar < 4) {
4987 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
4988 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4992 c->u.a.lensofar += l;
4994 if (c->u.a.lensofar == 4) {
4996 4 + GET_32BIT(c->u.a.msglen);
4997 c->u.a.message = snewn(c->u.a.totallen,
4999 memcpy(c->u.a.message, c->u.a.msglen, 4);
5001 if (c->u.a.lensofar >= 4 && len > 0) {
5003 min(c->u.a.totallen - c->u.a.lensofar,
5005 memcpy(c->u.a.message + c->u.a.lensofar, p,
5009 c->u.a.lensofar += l;
5011 if (c->u.a.lensofar == c->u.a.totallen) {
5014 if (agent_query(c->u.a.message,
5017 ssh_agentf_callback, c))
5018 ssh_agentf_callback(c, reply, replylen);
5019 sfree(c->u.a.message);
5020 c->u.a.lensofar = 0;
5023 bufsize = 0; /* agent channels never back up */
5026 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5027 c->throttling_conn = 1;
5028 ssh_throttle_conn(ssh, +1);
5033 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5035 ssh->exitcode = ssh_pkt_getuint32(pktin);
5036 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5037 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5039 * In case `helpful' firewalls or proxies tack
5040 * extra human-readable text on the end of the
5041 * session which we might mistake for another
5042 * encrypted packet, we close the session once
5043 * we've sent EXIT_CONFIRMATION.
5045 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5048 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5049 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5051 struct Packet *pktout = (struct Packet *)data;
5053 unsigned int arg = 0;
5054 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5055 if (i == lenof(ssh_ttymodes)) return;
5056 switch (ssh_ttymodes[i].type) {
5058 arg = ssh_tty_parse_specchar(val);
5061 arg = ssh_tty_parse_boolean(val);
5064 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5065 ssh2_pkt_addbyte(pktout, arg);
5069 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5070 struct Packet *pktin)
5072 crBegin(ssh->do_ssh1_connection_crstate);
5074 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5075 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5076 ssh1_smsg_stdout_stderr_data;
5078 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5079 ssh1_msg_channel_open_confirmation;
5080 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5081 ssh1_msg_channel_open_failure;
5082 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5083 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5084 ssh1_msg_channel_close;
5085 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5086 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5088 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
5089 logevent("Requesting agent forwarding");
5090 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5094 if (pktin->type != SSH1_SMSG_SUCCESS
5095 && pktin->type != SSH1_SMSG_FAILURE) {
5096 bombout(("Protocol confusion"));
5098 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5099 logevent("Agent forwarding refused");
5101 logevent("Agent forwarding enabled");
5102 ssh->agentfwd_enabled = TRUE;
5103 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5107 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
5108 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5109 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
5110 logevent("Requesting X11 forwarding");
5112 * Note that while we blank the X authentication data here, we don't
5113 * take any special action to blank the start of an X11 channel,
5114 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
5115 * without having session blanking enabled is likely to leak your
5116 * cookie into the log.
5118 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5119 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5120 PKT_STR, ssh->x11disp->remoteauthprotoname,
5122 PKT_STR, ssh->x11disp->remoteauthdatastring,
5124 PKT_INT, ssh->x11disp->screennum,
5127 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5128 PKT_STR, ssh->x11disp->remoteauthprotoname,
5130 PKT_STR, ssh->x11disp->remoteauthdatastring,
5137 if (pktin->type != SSH1_SMSG_SUCCESS
5138 && pktin->type != SSH1_SMSG_FAILURE) {
5139 bombout(("Protocol confusion"));
5141 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5142 logevent("X11 forwarding refused");
5144 logevent("X11 forwarding enabled");
5145 ssh->X11_fwd_enabled = TRUE;
5146 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5150 ssh_setup_portfwd(ssh, ssh->conf);
5151 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5153 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5155 /* Unpick the terminal-speed string. */
5156 /* XXX perhaps we should allow no speeds to be sent. */
5157 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5158 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5159 /* Send the pty request. */
5160 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5161 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5162 ssh_pkt_adduint32(pkt, ssh->term_height);
5163 ssh_pkt_adduint32(pkt, ssh->term_width);
5164 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5165 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5166 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5167 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5168 ssh_pkt_adduint32(pkt, ssh->ispeed);
5169 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5170 ssh_pkt_adduint32(pkt, ssh->ospeed);
5171 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5173 ssh->state = SSH_STATE_INTERMED;
5177 if (pktin->type != SSH1_SMSG_SUCCESS
5178 && pktin->type != SSH1_SMSG_FAILURE) {
5179 bombout(("Protocol confusion"));
5181 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5182 c_write_str(ssh, "Server refused to allocate pty\r\n");
5183 ssh->editing = ssh->echoing = 1;
5185 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5186 ssh->ospeed, ssh->ispeed);
5188 ssh->editing = ssh->echoing = 1;
5191 if (conf_get_int(ssh->conf, CONF_compression)) {
5192 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5196 if (pktin->type != SSH1_SMSG_SUCCESS
5197 && pktin->type != SSH1_SMSG_FAILURE) {
5198 bombout(("Protocol confusion"));
5200 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5201 c_write_str(ssh, "Server refused to compress\r\n");
5203 logevent("Started compression");
5204 ssh->v1_compressing = TRUE;
5205 ssh->cs_comp_ctx = zlib_compress_init();
5206 logevent("Initialised zlib (RFC1950) compression");
5207 ssh->sc_comp_ctx = zlib_decompress_init();
5208 logevent("Initialised zlib (RFC1950) decompression");
5212 * Start the shell or command.
5214 * Special case: if the first-choice command is an SSH-2
5215 * subsystem (hence not usable here) and the second choice
5216 * exists, we fall straight back to that.
5219 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5221 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5222 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5223 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5224 ssh->fallback_cmd = TRUE;
5227 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5229 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5230 logevent("Started session");
5233 ssh->state = SSH_STATE_SESSION;
5234 if (ssh->size_needed)
5235 ssh_size(ssh, ssh->term_width, ssh->term_height);
5236 if (ssh->eof_needed)
5237 ssh_special(ssh, TS_EOF);
5240 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5242 ssh->channels = newtree234(ssh_channelcmp);
5246 * By this point, most incoming packets are already being
5247 * handled by the dispatch table, and we need only pay
5248 * attention to the unusual ones.
5253 if (pktin->type == SSH1_SMSG_SUCCESS) {
5254 /* may be from EXEC_SHELL on some servers */
5255 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5256 /* may be from EXEC_SHELL on some servers
5257 * if no pty is available or in other odd cases. Ignore */
5259 bombout(("Strange packet received: type %d", pktin->type));
5264 int len = min(inlen, 512);
5265 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5266 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
5267 PKTT_OTHER, PKT_END);
5278 * Handle the top-level SSH-2 protocol.
5280 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5285 ssh_pkt_getstring(pktin, &msg, &msglen);
5286 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5289 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5291 /* log reason code in disconnect message */
5295 ssh_pkt_getstring(pktin, &msg, &msglen);
5296 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5299 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5301 /* Do nothing, because we're ignoring it! Duhh. */
5304 static void ssh1_protocol_setup(Ssh ssh)
5309 * Most messages are handled by the coroutines.
5311 for (i = 0; i < 256; i++)
5312 ssh->packet_dispatch[i] = NULL;
5315 * These special message types we install handlers for.
5317 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5318 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5319 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5322 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5323 struct Packet *pktin)
5325 unsigned char *in=(unsigned char*)vin;
5326 if (ssh->state == SSH_STATE_CLOSED)
5329 if (pktin && ssh->packet_dispatch[pktin->type]) {
5330 ssh->packet_dispatch[pktin->type](ssh, pktin);
5334 if (!ssh->protocol_initial_phase_done) {
5335 if (do_ssh1_login(ssh, in, inlen, pktin))
5336 ssh->protocol_initial_phase_done = TRUE;
5341 do_ssh1_connection(ssh, in, inlen, pktin);
5345 * Utility routine for decoding comma-separated strings in KEXINIT.
5347 static int in_commasep_string(char *needle, char *haystack, int haylen)
5350 if (!needle || !haystack) /* protect against null pointers */
5352 needlen = strlen(needle);
5355 * Is it at the start of the string?
5357 if (haylen >= needlen && /* haystack is long enough */
5358 !memcmp(needle, haystack, needlen) && /* initial match */
5359 (haylen == needlen || haystack[needlen] == ',')
5360 /* either , or EOS follows */
5364 * If not, search for the next comma and resume after that.
5365 * If no comma found, terminate.
5367 while (haylen > 0 && *haystack != ',')
5368 haylen--, haystack++;
5371 haylen--, haystack++; /* skip over comma itself */
5376 * Similar routine for checking whether we have the first string in a list.
5378 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5381 if (!needle || !haystack) /* protect against null pointers */
5383 needlen = strlen(needle);
5385 * Is it at the start of the string?
5387 if (haylen >= needlen && /* haystack is long enough */
5388 !memcmp(needle, haystack, needlen) && /* initial match */
5389 (haylen == needlen || haystack[needlen] == ',')
5390 /* either , or EOS follows */
5398 * SSH-2 key creation method.
5399 * (Currently assumes 2 lots of any hash are sufficient to generate
5400 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5402 #define SSH2_MKKEY_ITERS (2)
5403 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5404 unsigned char *keyspace)
5406 const struct ssh_hash *h = ssh->kex->hash;
5408 /* First hlen bytes. */
5410 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5411 hash_mpint(h, s, K);
5412 h->bytes(s, H, h->hlen);
5413 h->bytes(s, &chr, 1);
5414 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5415 h->final(s, keyspace);
5416 /* Next hlen bytes. */
5418 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5419 hash_mpint(h, s, K);
5420 h->bytes(s, H, h->hlen);
5421 h->bytes(s, keyspace, h->hlen);
5422 h->final(s, keyspace + h->hlen);
5426 * Handle the SSH-2 transport layer.
5428 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5429 struct Packet *pktin)
5431 unsigned char *in = (unsigned char *)vin;
5432 struct do_ssh2_transport_state {
5433 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5434 Bignum p, g, e, f, K;
5437 int kex_init_value, kex_reply_value;
5438 const struct ssh_mac **maclist;
5440 const struct ssh2_cipher *cscipher_tobe;
5441 const struct ssh2_cipher *sccipher_tobe;
5442 const struct ssh_mac *csmac_tobe;
5443 const struct ssh_mac *scmac_tobe;
5444 const struct ssh_compress *cscomp_tobe;
5445 const struct ssh_compress *sccomp_tobe;
5446 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5447 int hostkeylen, siglen, rsakeylen;
5448 void *hkey; /* actual host key */
5449 void *rsakey; /* for RSA kex */
5450 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5451 int n_preferred_kex;
5452 const struct ssh_kexes *preferred_kex[KEX_MAX];
5453 int n_preferred_ciphers;
5454 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5455 const struct ssh_compress *preferred_comp;
5456 int userauth_succeeded; /* for delayed compression */
5457 int pending_compression;
5458 int got_session_id, activated_authconn;
5459 struct Packet *pktout;
5464 crState(do_ssh2_transport_state);
5466 crBegin(ssh->do_ssh2_transport_crstate);
5468 s->cscipher_tobe = s->sccipher_tobe = NULL;
5469 s->csmac_tobe = s->scmac_tobe = NULL;
5470 s->cscomp_tobe = s->sccomp_tobe = NULL;
5472 s->got_session_id = s->activated_authconn = FALSE;
5473 s->userauth_succeeded = FALSE;
5474 s->pending_compression = FALSE;
5477 * Be prepared to work around the buggy MAC problem.
5479 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5480 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5482 s->maclist = macs, s->nmacs = lenof(macs);
5485 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5487 int i, j, commalist_started;
5490 * Set up the preferred key exchange. (NULL => warn below here)
5492 s->n_preferred_kex = 0;
5493 for (i = 0; i < KEX_MAX; i++) {
5494 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
5496 s->preferred_kex[s->n_preferred_kex++] =
5497 &ssh_diffiehellman_gex;
5500 s->preferred_kex[s->n_preferred_kex++] =
5501 &ssh_diffiehellman_group14;
5504 s->preferred_kex[s->n_preferred_kex++] =
5505 &ssh_diffiehellman_group1;
5508 s->preferred_kex[s->n_preferred_kex++] =
5512 /* Flag for later. Don't bother if it's the last in
5514 if (i < KEX_MAX - 1) {
5515 s->preferred_kex[s->n_preferred_kex++] = NULL;
5522 * Set up the preferred ciphers. (NULL => warn below here)
5524 s->n_preferred_ciphers = 0;
5525 for (i = 0; i < CIPHER_MAX; i++) {
5526 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
5527 case CIPHER_BLOWFISH:
5528 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5531 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
5532 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5536 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5539 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5541 case CIPHER_ARCFOUR:
5542 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5545 /* Flag for later. Don't bother if it's the last in
5547 if (i < CIPHER_MAX - 1) {
5548 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5555 * Set up preferred compression.
5557 if (conf_get_int(ssh->conf, CONF_compression))
5558 s->preferred_comp = &ssh_zlib;
5560 s->preferred_comp = &ssh_comp_none;
5563 * Enable queueing of outgoing auth- or connection-layer
5564 * packets while we are in the middle of a key exchange.
5566 ssh->queueing = TRUE;
5569 * Flag that KEX is in progress.
5571 ssh->kex_in_progress = TRUE;
5574 * Construct and send our key exchange packet.
5576 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5577 for (i = 0; i < 16; i++)
5578 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5579 /* List key exchange algorithms. */
5580 ssh2_pkt_addstring_start(s->pktout);
5581 commalist_started = 0;
5582 for (i = 0; i < s->n_preferred_kex; i++) {
5583 const struct ssh_kexes *k = s->preferred_kex[i];
5584 if (!k) continue; /* warning flag */
5585 for (j = 0; j < k->nkexes; j++) {
5586 if (commalist_started)
5587 ssh2_pkt_addstring_str(s->pktout, ",");
5588 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5589 commalist_started = 1;
5592 /* List server host key algorithms. */
5593 ssh2_pkt_addstring_start(s->pktout);
5594 for (i = 0; i < lenof(hostkey_algs); i++) {
5595 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5596 if (i < lenof(hostkey_algs) - 1)
5597 ssh2_pkt_addstring_str(s->pktout, ",");
5599 /* List client->server encryption algorithms. */
5600 ssh2_pkt_addstring_start(s->pktout);
5601 commalist_started = 0;
5602 for (i = 0; i < s->n_preferred_ciphers; i++) {
5603 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5604 if (!c) continue; /* warning flag */
5605 for (j = 0; j < c->nciphers; j++) {
5606 if (commalist_started)
5607 ssh2_pkt_addstring_str(s->pktout, ",");
5608 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5609 commalist_started = 1;
5612 /* List server->client encryption algorithms. */
5613 ssh2_pkt_addstring_start(s->pktout);
5614 commalist_started = 0;
5615 for (i = 0; i < s->n_preferred_ciphers; i++) {
5616 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5617 if (!c) continue; /* warning flag */
5618 for (j = 0; j < c->nciphers; j++) {
5619 if (commalist_started)
5620 ssh2_pkt_addstring_str(s->pktout, ",");
5621 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5622 commalist_started = 1;
5625 /* List client->server MAC algorithms. */
5626 ssh2_pkt_addstring_start(s->pktout);
5627 for (i = 0; i < s->nmacs; i++) {
5628 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5629 if (i < s->nmacs - 1)
5630 ssh2_pkt_addstring_str(s->pktout, ",");
5632 /* List server->client MAC algorithms. */
5633 ssh2_pkt_addstring_start(s->pktout);
5634 for (i = 0; i < s->nmacs; i++) {
5635 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5636 if (i < s->nmacs - 1)
5637 ssh2_pkt_addstring_str(s->pktout, ",");
5639 /* List client->server compression algorithms,
5640 * then server->client compression algorithms. (We use the
5641 * same set twice.) */
5642 for (j = 0; j < 2; j++) {
5643 ssh2_pkt_addstring_start(s->pktout);
5644 assert(lenof(compressions) > 1);
5645 /* Prefer non-delayed versions */
5646 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5647 /* We don't even list delayed versions of algorithms until
5648 * they're allowed to be used, to avoid a race. See the end of
5650 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
5651 ssh2_pkt_addstring_str(s->pktout, ",");
5652 ssh2_pkt_addstring_str(s->pktout,
5653 s->preferred_comp->delayed_name);
5655 for (i = 0; i < lenof(compressions); i++) {
5656 const struct ssh_compress *c = compressions[i];
5657 if (c != s->preferred_comp) {
5658 ssh2_pkt_addstring_str(s->pktout, ",");
5659 ssh2_pkt_addstring_str(s->pktout, c->name);
5660 if (s->userauth_succeeded && c->delayed_name) {
5661 ssh2_pkt_addstring_str(s->pktout, ",");
5662 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
5667 /* List client->server languages. Empty list. */
5668 ssh2_pkt_addstring_start(s->pktout);
5669 /* List server->client languages. Empty list. */
5670 ssh2_pkt_addstring_start(s->pktout);
5671 /* First KEX packet does _not_ follow, because we're not that brave. */
5672 ssh2_pkt_addbool(s->pktout, FALSE);
5674 ssh2_pkt_adduint32(s->pktout, 0);
5677 s->our_kexinitlen = s->pktout->length - 5;
5678 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5679 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5681 ssh2_pkt_send_noqueue(ssh, s->pktout);
5687 * Now examine the other side's KEXINIT to see what we're up
5691 char *str, *preferred;
5694 if (pktin->type != SSH2_MSG_KEXINIT) {
5695 bombout(("expected key exchange packet from server"));
5699 ssh->hostkey = NULL;
5700 s->cscipher_tobe = NULL;
5701 s->sccipher_tobe = NULL;
5702 s->csmac_tobe = NULL;
5703 s->scmac_tobe = NULL;
5704 s->cscomp_tobe = NULL;
5705 s->sccomp_tobe = NULL;
5706 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5708 pktin->savedpos += 16; /* skip garbage cookie */
5709 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5712 for (i = 0; i < s->n_preferred_kex; i++) {
5713 const struct ssh_kexes *k = s->preferred_kex[i];
5717 for (j = 0; j < k->nkexes; j++) {
5718 if (!preferred) preferred = k->list[j]->name;
5719 if (in_commasep_string(k->list[j]->name, str, len)) {
5720 ssh->kex = k->list[j];
5729 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5730 str ? str : "(null)"));
5734 * Note that the server's guess is considered wrong if it doesn't match
5735 * the first algorithm in our list, even if it's still the algorithm
5738 s->guessok = first_in_commasep_string(preferred, str, len);
5739 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5740 for (i = 0; i < lenof(hostkey_algs); i++) {
5741 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5742 ssh->hostkey = hostkey_algs[i];
5746 s->guessok = s->guessok &&
5747 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5748 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5749 for (i = 0; i < s->n_preferred_ciphers; i++) {
5750 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5752 s->warn_cscipher = TRUE;
5754 for (j = 0; j < c->nciphers; j++) {
5755 if (in_commasep_string(c->list[j]->name, str, len)) {
5756 s->cscipher_tobe = c->list[j];
5761 if (s->cscipher_tobe)
5764 if (!s->cscipher_tobe) {
5765 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5766 str ? str : "(null)"));
5770 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5771 for (i = 0; i < s->n_preferred_ciphers; i++) {
5772 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5774 s->warn_sccipher = TRUE;
5776 for (j = 0; j < c->nciphers; j++) {
5777 if (in_commasep_string(c->list[j]->name, str, len)) {
5778 s->sccipher_tobe = c->list[j];
5783 if (s->sccipher_tobe)
5786 if (!s->sccipher_tobe) {
5787 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5788 str ? str : "(null)"));
5792 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5793 for (i = 0; i < s->nmacs; i++) {
5794 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5795 s->csmac_tobe = s->maclist[i];
5799 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5800 for (i = 0; i < s->nmacs; i++) {
5801 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5802 s->scmac_tobe = s->maclist[i];
5806 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5807 for (i = 0; i < lenof(compressions) + 1; i++) {
5808 const struct ssh_compress *c =
5809 i == 0 ? s->preferred_comp : compressions[i - 1];
5810 if (in_commasep_string(c->name, str, len)) {
5813 } else if (in_commasep_string(c->delayed_name, str, len)) {
5814 if (s->userauth_succeeded) {
5818 s->pending_compression = TRUE; /* try this later */
5822 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5823 for (i = 0; i < lenof(compressions) + 1; i++) {
5824 const struct ssh_compress *c =
5825 i == 0 ? s->preferred_comp : compressions[i - 1];
5826 if (in_commasep_string(c->name, str, len)) {
5829 } else if (in_commasep_string(c->delayed_name, str, len)) {
5830 if (s->userauth_succeeded) {
5834 s->pending_compression = TRUE; /* try this later */
5838 if (s->pending_compression) {
5839 logevent("Server supports delayed compression; "
5840 "will try this later");
5842 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5843 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5844 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5847 ssh_set_frozen(ssh, 1);
5848 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5850 ssh_dialog_callback, ssh);
5851 if (s->dlgret < 0) {
5855 bombout(("Unexpected data from server while"
5856 " waiting for user response"));
5859 } while (pktin || inlen > 0);
5860 s->dlgret = ssh->user_response;
5862 ssh_set_frozen(ssh, 0);
5863 if (s->dlgret == 0) {
5864 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5870 if (s->warn_cscipher) {
5871 ssh_set_frozen(ssh, 1);
5872 s->dlgret = askalg(ssh->frontend,
5873 "client-to-server cipher",
5874 s->cscipher_tobe->name,
5875 ssh_dialog_callback, ssh);
5876 if (s->dlgret < 0) {
5880 bombout(("Unexpected data from server while"
5881 " waiting for user response"));
5884 } while (pktin || inlen > 0);
5885 s->dlgret = ssh->user_response;
5887 ssh_set_frozen(ssh, 0);
5888 if (s->dlgret == 0) {
5889 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5895 if (s->warn_sccipher) {
5896 ssh_set_frozen(ssh, 1);
5897 s->dlgret = askalg(ssh->frontend,
5898 "server-to-client cipher",
5899 s->sccipher_tobe->name,
5900 ssh_dialog_callback, ssh);
5901 if (s->dlgret < 0) {
5905 bombout(("Unexpected data from server while"
5906 " waiting for user response"));
5909 } while (pktin || inlen > 0);
5910 s->dlgret = ssh->user_response;
5912 ssh_set_frozen(ssh, 0);
5913 if (s->dlgret == 0) {
5914 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5920 ssh->exhash = ssh->kex->hash->init();
5921 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5922 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5923 hash_string(ssh->kex->hash, ssh->exhash,
5924 s->our_kexinit, s->our_kexinitlen);
5925 sfree(s->our_kexinit);
5926 if (pktin->length > 5)
5927 hash_string(ssh->kex->hash, ssh->exhash,
5928 pktin->data + 5, pktin->length - 5);
5930 if (s->ignorepkt) /* first_kex_packet_follows */
5931 crWaitUntil(pktin); /* Ignore packet */
5934 if (ssh->kex->main_type == KEXTYPE_DH) {
5936 * Work out the number of bits of key we will need from the
5937 * key exchange. We start with the maximum key length of
5943 csbits = s->cscipher_tobe->keylen;
5944 scbits = s->sccipher_tobe->keylen;
5945 s->nbits = (csbits > scbits ? csbits : scbits);
5947 /* The keys only have hlen-bit entropy, since they're based on
5948 * a hash. So cap the key size at hlen bits. */
5949 if (s->nbits > ssh->kex->hash->hlen * 8)
5950 s->nbits = ssh->kex->hash->hlen * 8;
5953 * If we're doing Diffie-Hellman group exchange, start by
5954 * requesting a group.
5956 if (!ssh->kex->pdata) {
5957 logevent("Doing Diffie-Hellman group exchange");
5958 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
5960 * Work out how big a DH group we will need to allow that
5963 s->pbits = 512 << ((s->nbits - 1) / 64);
5964 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5965 ssh2_pkt_adduint32(s->pktout, s->pbits);
5966 ssh2_pkt_send_noqueue(ssh, s->pktout);
5969 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5970 bombout(("expected key exchange group packet from server"));
5973 s->p = ssh2_pkt_getmp(pktin);
5974 s->g = ssh2_pkt_getmp(pktin);
5975 if (!s->p || !s->g) {
5976 bombout(("unable to read mp-ints from incoming group packet"));
5979 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5980 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5981 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5983 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
5984 ssh->kex_ctx = dh_setup_group(ssh->kex);
5985 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5986 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5987 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5988 ssh->kex->groupname);
5991 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
5992 ssh->kex->hash->text_name);
5994 * Now generate and send e for Diffie-Hellman.
5996 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
5997 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
5998 s->pktout = ssh2_pkt_init(s->kex_init_value);
5999 ssh2_pkt_addmp(s->pktout, s->e);
6000 ssh2_pkt_send_noqueue(ssh, s->pktout);
6002 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6004 if (pktin->type != s->kex_reply_value) {
6005 bombout(("expected key exchange reply packet from server"));
6008 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6009 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6010 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6011 s->f = ssh2_pkt_getmp(pktin);
6013 bombout(("unable to parse key exchange reply packet"));
6016 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6018 s->K = dh_find_K(ssh->kex_ctx, s->f);
6020 /* We assume everything from now on will be quick, and it might
6021 * involve user interaction. */
6022 set_busy_status(ssh->frontend, BUSY_NOT);
6024 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6025 if (!ssh->kex->pdata) {
6026 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6027 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6028 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6030 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6031 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6033 dh_cleanup(ssh->kex_ctx);
6035 if (!ssh->kex->pdata) {
6040 logeventf(ssh, "Doing RSA key exchange with hash %s",
6041 ssh->kex->hash->text_name);
6042 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6044 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6048 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6049 bombout(("expected RSA public key packet from server"));
6053 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6054 hash_string(ssh->kex->hash, ssh->exhash,
6055 s->hostkeydata, s->hostkeylen);
6056 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6060 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6061 s->rsakeydata = snewn(s->rsakeylen, char);
6062 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6065 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6067 sfree(s->rsakeydata);
6068 bombout(("unable to parse RSA public key from server"));
6072 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6075 * Next, set up a shared secret K, of precisely KLEN -
6076 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6077 * RSA key modulus and HLEN is the bit length of the hash
6081 int klen = ssh_rsakex_klen(s->rsakey);
6082 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6084 unsigned char *kstr1, *kstr2, *outstr;
6085 int kstr1len, kstr2len, outstrlen;
6087 s->K = bn_power_2(nbits - 1);
6089 for (i = 0; i < nbits; i++) {
6091 byte = random_byte();
6093 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6097 * Encode this as an mpint.
6099 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6100 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6101 PUT_32BIT(kstr2, kstr1len);
6102 memcpy(kstr2 + 4, kstr1, kstr1len);
6105 * Encrypt it with the given RSA key.
6107 outstrlen = (klen + 7) / 8;
6108 outstr = snewn(outstrlen, unsigned char);
6109 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6110 outstr, outstrlen, s->rsakey);
6113 * And send it off in a return packet.
6115 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6116 ssh2_pkt_addstring_start(s->pktout);
6117 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6118 ssh2_pkt_send_noqueue(ssh, s->pktout);
6120 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6127 ssh_rsakex_freekey(s->rsakey);
6130 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6131 sfree(s->rsakeydata);
6132 bombout(("expected signature packet from server"));
6136 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6138 sfree(s->rsakeydata);
6141 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6142 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6143 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6145 ssh->kex_ctx = NULL;
6148 debug(("Exchange hash is:\n"));
6149 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6153 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6154 (char *)s->exchange_hash,
6155 ssh->kex->hash->hlen)) {
6156 bombout(("Server's host key did not match the signature supplied"));
6161 * Authenticate remote host: verify host key. (We've already
6162 * checked the signature of the exchange hash.)
6164 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6165 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6166 ssh_set_frozen(ssh, 1);
6167 s->dlgret = verify_ssh_host_key(ssh->frontend,
6168 ssh->savedhost, ssh->savedport,
6169 ssh->hostkey->keytype, s->keystr,
6171 ssh_dialog_callback, ssh);
6172 if (s->dlgret < 0) {
6176 bombout(("Unexpected data from server while waiting"
6177 " for user host key response"));
6180 } while (pktin || inlen > 0);
6181 s->dlgret = ssh->user_response;
6183 ssh_set_frozen(ssh, 0);
6184 if (s->dlgret == 0) {
6185 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6189 if (!s->got_session_id) { /* don't bother logging this in rekeys */
6190 logevent("Host key fingerprint is:");
6191 logevent(s->fingerprint);
6193 sfree(s->fingerprint);
6195 ssh->hostkey->freekey(s->hkey);
6198 * The exchange hash from the very first key exchange is also
6199 * the session id, used in session key construction and
6202 if (!s->got_session_id) {
6203 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6204 memcpy(ssh->v2_session_id, s->exchange_hash,
6205 sizeof(s->exchange_hash));
6206 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6207 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6208 s->got_session_id = TRUE;
6212 * Send SSH2_MSG_NEWKEYS.
6214 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6215 ssh2_pkt_send_noqueue(ssh, s->pktout);
6216 ssh->outgoing_data_size = 0; /* start counting from here */
6219 * We've sent client NEWKEYS, so create and initialise
6220 * client-to-server session keys.
6222 if (ssh->cs_cipher_ctx)
6223 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6224 ssh->cscipher = s->cscipher_tobe;
6225 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6227 if (ssh->cs_mac_ctx)
6228 ssh->csmac->free_context(ssh->cs_mac_ctx);
6229 ssh->csmac = s->csmac_tobe;
6230 ssh->cs_mac_ctx = ssh->csmac->make_context();
6232 if (ssh->cs_comp_ctx)
6233 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6234 ssh->cscomp = s->cscomp_tobe;
6235 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6238 * Set IVs on client-to-server keys. Here we use the exchange
6239 * hash from the _first_ key exchange.
6242 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6243 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6244 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6245 assert((ssh->cscipher->keylen+7) / 8 <=
6246 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6247 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6248 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6249 assert(ssh->cscipher->blksize <=
6250 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6251 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6252 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6253 assert(ssh->csmac->len <=
6254 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6255 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6256 memset(keyspace, 0, sizeof(keyspace));
6259 logeventf(ssh, "Initialised %.200s client->server encryption",
6260 ssh->cscipher->text_name);
6261 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6262 ssh->csmac->text_name);
6263 if (ssh->cscomp->text_name)
6264 logeventf(ssh, "Initialised %s compression",
6265 ssh->cscomp->text_name);
6268 * Now our end of the key exchange is complete, we can send all
6269 * our queued higher-layer packets.
6271 ssh->queueing = FALSE;
6272 ssh2_pkt_queuesend(ssh);
6275 * Expect SSH2_MSG_NEWKEYS from server.
6278 if (pktin->type != SSH2_MSG_NEWKEYS) {
6279 bombout(("expected new-keys packet from server"));
6282 ssh->incoming_data_size = 0; /* start counting from here */
6285 * We've seen server NEWKEYS, so create and initialise
6286 * server-to-client session keys.
6288 if (ssh->sc_cipher_ctx)
6289 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6290 ssh->sccipher = s->sccipher_tobe;
6291 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6293 if (ssh->sc_mac_ctx)
6294 ssh->scmac->free_context(ssh->sc_mac_ctx);
6295 ssh->scmac = s->scmac_tobe;
6296 ssh->sc_mac_ctx = ssh->scmac->make_context();
6298 if (ssh->sc_comp_ctx)
6299 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6300 ssh->sccomp = s->sccomp_tobe;
6301 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6304 * Set IVs on server-to-client keys. Here we use the exchange
6305 * hash from the _first_ key exchange.
6308 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6309 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6310 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6311 assert((ssh->sccipher->keylen+7) / 8 <=
6312 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6313 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6314 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6315 assert(ssh->sccipher->blksize <=
6316 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6317 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6318 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6319 assert(ssh->scmac->len <=
6320 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6321 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6322 memset(keyspace, 0, sizeof(keyspace));
6324 logeventf(ssh, "Initialised %.200s server->client encryption",
6325 ssh->sccipher->text_name);
6326 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6327 ssh->scmac->text_name);
6328 if (ssh->sccomp->text_name)
6329 logeventf(ssh, "Initialised %s decompression",
6330 ssh->sccomp->text_name);
6333 * Free shared secret.
6338 * Key exchange is over. Loop straight back round if we have a
6339 * deferred rekey reason.
6341 if (ssh->deferred_rekey_reason) {
6342 logevent(ssh->deferred_rekey_reason);
6344 ssh->deferred_rekey_reason = NULL;
6345 goto begin_key_exchange;
6349 * Otherwise, schedule a timer for our next rekey.
6351 ssh->kex_in_progress = FALSE;
6352 ssh->last_rekey = GETTICKCOUNT();
6353 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
6354 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6358 * If this is the first key exchange phase, we must pass the
6359 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
6360 * wants to see it but because it will need time to initialise
6361 * itself before it sees an actual packet. In subsequent key
6362 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
6363 * it would only confuse the layer above.
6365 if (s->activated_authconn) {
6368 s->activated_authconn = TRUE;
6371 * Now we're encrypting. Begin returning 1 to the protocol main
6372 * function so that other things can run on top of the
6373 * transport. If we ever see a KEXINIT, we must go back to the
6376 * We _also_ go back to the start if we see pktin==NULL and
6377 * inlen negative, because this is a special signal meaning
6378 * `initiate client-driven rekey', and `in' contains a message
6379 * giving the reason for the rekey.
6381 * inlen==-1 means always initiate a rekey;
6382 * inlen==-2 means that userauth has completed successfully and
6383 * we should consider rekeying (for delayed compression).
6385 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6386 (!pktin && inlen < 0))) {
6391 logevent("Server initiated key re-exchange");
6395 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6396 * delayed compression, if it's available.
6398 * draft-miller-secsh-compression-delayed-00 says that you
6399 * negotiate delayed compression in the first key exchange, and
6400 * both sides start compressing when the server has sent
6401 * USERAUTH_SUCCESS. This has a race condition -- the server
6402 * can't know when the client has seen it, and thus which incoming
6403 * packets it should treat as compressed.
6405 * Instead, we do the initial key exchange without offering the
6406 * delayed methods, but note if the server offers them; when we
6407 * get here, if a delayed method was available that was higher
6408 * on our list than what we got, we initiate a rekey in which we
6409 * _do_ list the delayed methods (and hopefully get it as a
6410 * result). Subsequent rekeys will do the same.
6412 assert(!s->userauth_succeeded); /* should only happen once */
6413 s->userauth_succeeded = TRUE;
6414 if (!s->pending_compression)
6415 /* Can't see any point rekeying. */
6416 goto wait_for_rekey; /* this is utterly horrid */
6417 /* else fall through to rekey... */
6418 s->pending_compression = FALSE;
6421 * Now we've decided to rekey.
6423 * Special case: if the server bug is set that doesn't
6424 * allow rekeying, we give a different log message and
6425 * continue waiting. (If such a server _initiates_ a rekey,
6426 * we process it anyway!)
6428 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6429 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6431 /* Reset the counters, so that at least this message doesn't
6432 * hit the event log _too_ often. */
6433 ssh->outgoing_data_size = 0;
6434 ssh->incoming_data_size = 0;
6435 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
6437 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6440 goto wait_for_rekey; /* this is still utterly horrid */
6442 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6445 goto begin_key_exchange;
6451 * Add data to an SSH-2 channel output buffer.
6453 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6456 bufchain_add(&c->v.v2.outbuffer, buf, len);
6460 * Attempt to send data on an SSH-2 channel.
6462 static int ssh2_try_send(struct ssh_channel *c)
6465 struct Packet *pktout;
6468 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6471 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6472 if ((unsigned)len > c->v.v2.remwindow)
6473 len = c->v.v2.remwindow;
6474 if ((unsigned)len > c->v.v2.remmaxpkt)
6475 len = c->v.v2.remmaxpkt;
6476 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6477 ssh2_pkt_adduint32(pktout, c->remoteid);
6478 ssh2_pkt_addstring_start(pktout);
6479 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6480 ssh2_pkt_addstring_data(pktout, data, len);
6481 end_log_omission(ssh, pktout);
6482 ssh2_pkt_send(ssh, pktout);
6483 bufchain_consume(&c->v.v2.outbuffer, len);
6484 c->v.v2.remwindow -= len;
6488 * After having sent as much data as we can, return the amount
6491 ret = bufchain_size(&c->v.v2.outbuffer);
6494 * And if there's no data pending but we need to send an EOF, send
6497 if (!ret && c->pending_eof)
6498 ssh_channel_try_eof(c);
6503 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
6506 if (c->closes & CLOSES_SENT_EOF)
6507 return; /* don't send on channels we've EOFed */
6508 bufsize = ssh2_try_send(c);
6511 case CHAN_MAINSESSION:
6512 /* stdin need not receive an unthrottle
6513 * notification since it will be polled */
6516 x11_unthrottle(c->u.x11.s);
6519 /* agent sockets are request/response and need no
6520 * buffer management */
6523 pfd_unthrottle(c->u.pfd.s);
6530 * Set up most of a new ssh_channel for SSH-2.
6532 static void ssh2_channel_init(struct ssh_channel *c)
6535 c->localid = alloc_channel_id(ssh);
6537 c->pending_eof = FALSE;
6538 c->throttling_conn = FALSE;
6539 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6540 conf_get_int(ssh->conf, CONF_ssh_simple) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6541 c->v.v2.winadj_head = c->v.v2.winadj_tail = NULL;
6542 c->v.v2.throttle_state = UNTHROTTLED;
6543 bufchain_init(&c->v.v2.outbuffer);
6547 * Potentially enlarge the window on an SSH-2 channel.
6549 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6554 * Never send WINDOW_ADJUST for a channel that the remote side has
6555 * already sent EOF on; there's no point, since it won't be
6556 * sending any more data anyway.
6558 if (c->closes & CLOSES_RCVD_EOF)
6562 * If the remote end has a habit of ignoring maxpkt, limit the
6563 * window so that it has no choice (assuming it doesn't ignore the
6566 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6567 newwin = OUR_V2_MAXPKT;
6571 * Only send a WINDOW_ADJUST if there's significantly more window
6572 * available than the other end thinks there is. This saves us
6573 * sending a WINDOW_ADJUST for every character in a shell session.
6575 * "Significant" is arbitrarily defined as half the window size.
6577 if (newwin / 2 >= c->v.v2.locwindow) {
6578 struct Packet *pktout;
6582 * In order to keep track of how much window the client
6583 * actually has available, we'd like it to acknowledge each
6584 * WINDOW_ADJUST. We can't do that directly, so we accompany
6585 * it with a CHANNEL_REQUEST that has to be acknowledged.
6587 * This is only necessary if we're opening the window wide.
6588 * If we're not, then throughput is being constrained by
6589 * something other than the maximum window size anyway.
6591 * We also only send this if the main channel has finished its
6592 * initial CHANNEL_REQUESTs and installed the default
6593 * CHANNEL_FAILURE handler, so as not to risk giving it
6594 * unexpected CHANNEL_FAILUREs.
6596 if (newwin == c->v.v2.locmaxwin &&
6597 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE]) {
6598 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6599 ssh2_pkt_adduint32(pktout, c->remoteid);
6600 ssh2_pkt_addstring(pktout, "winadj@putty.projects.tartarus.org");
6601 ssh2_pkt_addbool(pktout, TRUE);
6602 ssh2_pkt_send(ssh, pktout);
6605 * CHANNEL_FAILURE doesn't come with any indication of
6606 * what message caused it, so we have to keep track of the
6607 * outstanding CHANNEL_REQUESTs ourselves.
6609 wa = snew(struct winadj);
6610 wa->size = newwin - c->v.v2.locwindow;
6612 if (!c->v.v2.winadj_head)
6613 c->v.v2.winadj_head = wa;
6615 c->v.v2.winadj_tail->next = wa;
6616 c->v.v2.winadj_tail = wa;
6617 if (c->v.v2.throttle_state != UNTHROTTLED)
6618 c->v.v2.throttle_state = UNTHROTTLING;
6620 /* Pretend the WINDOW_ADJUST was acked immediately. */
6621 c->v.v2.remlocwin = newwin;
6622 c->v.v2.throttle_state = THROTTLED;
6624 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6625 ssh2_pkt_adduint32(pktout, c->remoteid);
6626 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6627 ssh2_pkt_send(ssh, pktout);
6628 c->v.v2.locwindow = newwin;
6633 * Find the channel associated with a message. If there's no channel,
6634 * or it's not properly open, make a noise about it and return NULL.
6636 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6638 unsigned localid = ssh_pkt_getuint32(pktin);
6639 struct ssh_channel *c;
6641 c = find234(ssh->channels, &localid, ssh_channelfind);
6643 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6644 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6645 char *buf = dupprintf("Received %s for %s channel %u",
6646 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6648 c ? "half-open" : "nonexistent", localid);
6649 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6656 static int ssh2_handle_winadj_response(struct ssh_channel *c)
6658 struct winadj *wa = c->v.v2.winadj_head;
6661 c->v.v2.winadj_head = wa->next;
6662 c->v.v2.remlocwin += wa->size;
6665 * winadj messages are only sent when the window is fully open, so
6666 * if we get an ack of one, we know any pending unthrottle is
6669 if (c->v.v2.throttle_state == UNTHROTTLING)
6670 c->v.v2.throttle_state = UNTHROTTLED;
6672 * We may now initiate channel-closing procedures, if that winadj
6673 * was the last thing outstanding before we send CHANNEL_CLOSE.
6675 ssh2_channel_check_close(c);
6679 static void ssh2_msg_channel_success(Ssh ssh, struct Packet *pktin)
6682 * This should never get called. All channel requests are either
6683 * sent with want_reply false, are sent before this handler gets
6684 * installed, or are "winadj@putty" requests, which servers should
6685 * never respond to with success.
6687 * However, at least one server ("boks_sshd") is known to return
6688 * SUCCESS for channel requests it's never heard of, such as
6689 * "winadj@putty". Raised with foxt.com as bug 090916-090424, but
6690 * for the sake of a quiet life, we handle it just the same as the
6693 struct ssh_channel *c;
6695 c = ssh2_channel_msg(ssh, pktin);
6698 if (!ssh2_handle_winadj_response(c))
6699 ssh_disconnect(ssh, NULL,
6700 "Received unsolicited SSH_MSG_CHANNEL_SUCCESS",
6701 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6704 static void ssh2_msg_channel_failure(Ssh ssh, struct Packet *pktin)
6707 * The only time this should get called is for "winadj@putty"
6708 * messages sent above. All other channel requests are either
6709 * sent with want_reply false or are sent before this handler gets
6712 struct ssh_channel *c;
6714 c = ssh2_channel_msg(ssh, pktin);
6717 if (!ssh2_handle_winadj_response(c))
6718 ssh_disconnect(ssh, NULL,
6719 "Received unsolicited SSH_MSG_CHANNEL_FAILURE",
6720 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6723 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6725 struct ssh_channel *c;
6726 c = ssh2_channel_msg(ssh, pktin);
6729 if (!(c->closes & CLOSES_SENT_EOF)) {
6730 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6731 ssh2_try_send_and_unthrottle(ssh, c);
6735 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6739 struct ssh_channel *c;
6740 c = ssh2_channel_msg(ssh, pktin);
6743 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6744 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6745 return; /* extended but not stderr */
6746 ssh_pkt_getstring(pktin, &data, &length);
6749 c->v.v2.locwindow -= length;
6750 c->v.v2.remlocwin -= length;
6752 case CHAN_MAINSESSION:
6754 from_backend(ssh->frontend, pktin->type ==
6755 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6759 bufsize = x11_send(c->u.x11.s, data, length);
6762 bufsize = pfd_send(c->u.pfd.s, data, length);
6765 while (length > 0) {
6766 if (c->u.a.lensofar < 4) {
6767 unsigned int l = min(4 - c->u.a.lensofar,
6769 memcpy(c->u.a.msglen + c->u.a.lensofar,
6773 c->u.a.lensofar += l;
6775 if (c->u.a.lensofar == 4) {
6777 4 + GET_32BIT(c->u.a.msglen);
6778 c->u.a.message = snewn(c->u.a.totallen,
6780 memcpy(c->u.a.message, c->u.a.msglen, 4);
6782 if (c->u.a.lensofar >= 4 && length > 0) {
6784 min(c->u.a.totallen - c->u.a.lensofar,
6786 memcpy(c->u.a.message + c->u.a.lensofar,
6790 c->u.a.lensofar += l;
6792 if (c->u.a.lensofar == c->u.a.totallen) {
6795 if (agent_query(c->u.a.message,
6798 ssh_agentf_callback, c))
6799 ssh_agentf_callback(c, reply, replylen);
6800 sfree(c->u.a.message);
6801 c->u.a.message = NULL;
6802 c->u.a.lensofar = 0;
6809 * If it looks like the remote end hit the end of its window,
6810 * and we didn't want it to do that, think about using a
6813 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6814 c->v.v2.locmaxwin < 0x40000000)
6815 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6817 * If we are not buffering too much data,
6818 * enlarge the window again at the remote side.
6819 * If we are buffering too much, we may still
6820 * need to adjust the window if the server's
6823 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6824 c->v.v2.locmaxwin - bufsize : 0);
6826 * If we're either buffering way too much data, or if we're
6827 * buffering anything at all and we're in "simple" mode,
6828 * throttle the whole channel.
6830 if ((bufsize > c->v.v2.locmaxwin ||
6831 (conf_get_int(ssh->conf, CONF_ssh_simple) && bufsize > 0)) &&
6832 !c->throttling_conn) {
6833 c->throttling_conn = 1;
6834 ssh_throttle_conn(ssh, +1);
6839 static void ssh_channel_destroy(struct ssh_channel *c)
6844 case CHAN_MAINSESSION:
6845 ssh->mainchan = NULL;
6846 update_specials_menu(ssh->frontend);
6849 if (c->u.x11.s != NULL)
6850 x11_close(c->u.x11.s);
6851 logevent("Forwarded X11 connection terminated");
6854 sfree(c->u.a.message);
6857 if (c->u.pfd.s != NULL)
6858 pfd_close(c->u.pfd.s);
6859 logevent("Forwarded port closed");
6863 del234(ssh->channels, c);
6864 if (ssh->version == 2)
6865 bufchain_clear(&c->v.v2.outbuffer);
6869 * See if that was the last channel left open.
6870 * (This is only our termination condition if we're
6871 * not running in -N mode.)
6873 if (ssh->version == 2 &&
6874 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
6875 count234(ssh->channels) == 0) {
6877 * We used to send SSH_MSG_DISCONNECT here,
6878 * because I'd believed that _every_ conforming
6879 * SSH-2 connection had to end with a disconnect
6880 * being sent by at least one side; apparently
6881 * I was wrong and it's perfectly OK to
6882 * unceremoniously slam the connection shut
6883 * when you're done, and indeed OpenSSH feels
6884 * this is more polite than sending a
6885 * DISCONNECT. So now we don't.
6887 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6891 static void ssh2_channel_check_close(struct ssh_channel *c)
6894 struct Packet *pktout;
6896 if ((c->closes & (CLOSES_SENT_EOF | CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6897 == (CLOSES_SENT_EOF | CLOSES_RCVD_EOF) && !c->v.v2.winadj_head) {
6899 * We have both sent and received EOF, and we have no
6900 * outstanding winadj channel requests, which means the
6901 * channel is in final wind-up. But we haven't sent CLOSE, so
6904 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6905 ssh2_pkt_adduint32(pktout, c->remoteid);
6906 ssh2_pkt_send(ssh, pktout);
6907 c->closes |= CLOSES_SENT_CLOSE;
6910 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
6912 * We have both sent and received CLOSE, which means we're
6913 * completely done with the channel.
6915 ssh_channel_destroy(c);
6919 static void ssh2_channel_got_eof(struct ssh_channel *c)
6921 if (c->closes & CLOSES_RCVD_EOF)
6922 return; /* already seen EOF */
6923 c->closes |= CLOSES_RCVD_EOF;
6925 if (c->type == CHAN_X11) {
6926 x11_send_eof(c->u.x11.s);
6927 } else if (c->type == CHAN_AGENT) {
6928 /* Manufacture an outgoing EOF in response to the incoming one. */
6929 sshfwd_write_eof(c);
6930 } else if (c->type == CHAN_SOCKDATA) {
6931 pfd_send_eof(c->u.pfd.s);
6932 } else if (c->type == CHAN_MAINSESSION) {
6935 if (!ssh->sent_console_eof && from_backend_eof(ssh->frontend)) {
6937 * The front end wants us to close the outgoing side of the
6938 * connection as soon as we see EOF from the far end.
6940 sshfwd_write_eof(c);
6942 ssh->sent_console_eof = TRUE;
6945 ssh2_channel_check_close(c);
6948 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
6950 struct ssh_channel *c;
6952 c = ssh2_channel_msg(ssh, pktin);
6955 ssh2_channel_got_eof(c);
6958 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
6960 struct ssh_channel *c;
6962 c = ssh2_channel_msg(ssh, pktin);
6967 * When we receive CLOSE on a channel, we assume it comes with an
6968 * implied EOF if we haven't seen EOF yet.
6970 ssh2_channel_got_eof(c);
6973 * Now process the actual close.
6975 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
6976 c->closes |= CLOSES_RCVD_CLOSE;
6977 ssh2_channel_check_close(c);
6981 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
6983 struct ssh_channel *c;
6985 c = ssh2_channel_msg(ssh, pktin);
6988 if (c->type != CHAN_SOCKDATA_DORMANT)
6989 return; /* dunno why they're confirming this */
6990 c->remoteid = ssh_pkt_getuint32(pktin);
6991 c->halfopen = FALSE;
6992 c->type = CHAN_SOCKDATA;
6993 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
6994 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
6996 pfd_confirm(c->u.pfd.s);
6998 ssh_channel_try_eof(c);
7001 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7003 static const char *const reasons[] = {
7004 "<unknown reason code>",
7005 "Administratively prohibited",
7007 "Unknown channel type",
7008 "Resource shortage",
7010 unsigned reason_code;
7011 char *reason_string;
7013 struct ssh_channel *c;
7014 c = ssh2_channel_msg(ssh, pktin);
7017 if (c->type != CHAN_SOCKDATA_DORMANT)
7018 return; /* dunno why they're failing this */
7020 reason_code = ssh_pkt_getuint32(pktin);
7021 if (reason_code >= lenof(reasons))
7022 reason_code = 0; /* ensure reasons[reason_code] in range */
7023 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7024 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7025 reasons[reason_code], reason_length, reason_string);
7027 pfd_close(c->u.pfd.s);
7029 del234(ssh->channels, c);
7033 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7036 int typelen, want_reply;
7037 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7038 struct ssh_channel *c;
7039 struct Packet *pktout;
7041 c = ssh2_channel_msg(ssh, pktin);
7044 ssh_pkt_getstring(pktin, &type, &typelen);
7045 want_reply = ssh2_pkt_getbool(pktin);
7048 * Having got the channel number, we now look at
7049 * the request type string to see if it's something
7052 if (c == ssh->mainchan) {
7054 * We recognise "exit-status" and "exit-signal" on
7055 * the primary channel.
7057 if (typelen == 11 &&
7058 !memcmp(type, "exit-status", 11)) {
7060 ssh->exitcode = ssh_pkt_getuint32(pktin);
7061 logeventf(ssh, "Server sent command exit status %d",
7063 reply = SSH2_MSG_CHANNEL_SUCCESS;
7065 } else if (typelen == 11 &&
7066 !memcmp(type, "exit-signal", 11)) {
7068 int is_plausible = TRUE, is_int = FALSE;
7069 char *fmt_sig = "", *fmt_msg = "";
7071 int msglen = 0, core = FALSE;
7072 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7073 * provide an `int' for the signal, despite its
7074 * having been a `string' in the drafts of RFC 4254 since at
7075 * least 2001. (Fixed in session.c 1.147.) Try to
7076 * infer which we can safely parse it as. */
7078 unsigned char *p = pktin->body +
7080 long len = pktin->length - pktin->savedpos;
7081 unsigned long num = GET_32BIT(p); /* what is it? */
7082 /* If it's 0, it hardly matters; assume string */
7086 int maybe_int = FALSE, maybe_str = FALSE;
7087 #define CHECK_HYPOTHESIS(offset, result) \
7090 if (q >= 0 && q+4 <= len) { \
7091 q = q + 4 + GET_32BIT(p+q); \
7092 if (q >= 0 && q+4 <= len && \
7093 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
7097 CHECK_HYPOTHESIS(4+1, maybe_int);
7098 CHECK_HYPOTHESIS(4+num+1, maybe_str);
7099 #undef CHECK_HYPOTHESIS
7100 if (maybe_int && !maybe_str)
7102 else if (!maybe_int && maybe_str)
7105 /* Crikey. Either or neither. Panic. */
7106 is_plausible = FALSE;
7109 ssh->exitcode = 128; /* means `unknown signal' */
7112 /* Old non-standard OpenSSH. */
7113 int signum = ssh_pkt_getuint32(pktin);
7114 fmt_sig = dupprintf(" %d", signum);
7115 ssh->exitcode = 128 + signum;
7117 /* As per RFC 4254. */
7120 ssh_pkt_getstring(pktin, &sig, &siglen);
7121 /* Signal name isn't supposed to be blank, but
7122 * let's cope gracefully if it is. */
7124 fmt_sig = dupprintf(" \"%.*s\"",
7129 * Really hideous method of translating the
7130 * signal description back into a locally
7131 * meaningful number.
7136 #define TRANSLATE_SIGNAL(s) \
7137 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7138 ssh->exitcode = 128 + SIG ## s
7140 TRANSLATE_SIGNAL(ABRT);
7143 TRANSLATE_SIGNAL(ALRM);
7146 TRANSLATE_SIGNAL(FPE);
7149 TRANSLATE_SIGNAL(HUP);
7152 TRANSLATE_SIGNAL(ILL);
7155 TRANSLATE_SIGNAL(INT);
7158 TRANSLATE_SIGNAL(KILL);
7161 TRANSLATE_SIGNAL(PIPE);
7164 TRANSLATE_SIGNAL(QUIT);
7167 TRANSLATE_SIGNAL(SEGV);
7170 TRANSLATE_SIGNAL(TERM);
7173 TRANSLATE_SIGNAL(USR1);
7176 TRANSLATE_SIGNAL(USR2);
7178 #undef TRANSLATE_SIGNAL
7180 ssh->exitcode = 128;
7182 core = ssh2_pkt_getbool(pktin);
7183 ssh_pkt_getstring(pktin, &msg, &msglen);
7185 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
7187 /* ignore lang tag */
7188 } /* else don't attempt to parse */
7189 logeventf(ssh, "Server exited on signal%s%s%s",
7190 fmt_sig, core ? " (core dumped)" : "",
7192 if (*fmt_sig) sfree(fmt_sig);
7193 if (*fmt_msg) sfree(fmt_msg);
7194 reply = SSH2_MSG_CHANNEL_SUCCESS;
7199 * This is a channel request we don't know
7200 * about, so we now either ignore the request
7201 * or respond with CHANNEL_FAILURE, depending
7204 reply = SSH2_MSG_CHANNEL_FAILURE;
7207 pktout = ssh2_pkt_init(reply);
7208 ssh2_pkt_adduint32(pktout, c->remoteid);
7209 ssh2_pkt_send(ssh, pktout);
7213 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7216 int typelen, want_reply;
7217 struct Packet *pktout;
7219 ssh_pkt_getstring(pktin, &type, &typelen);
7220 want_reply = ssh2_pkt_getbool(pktin);
7223 * We currently don't support any global requests
7224 * at all, so we either ignore the request or
7225 * respond with REQUEST_FAILURE, depending on
7229 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7230 ssh2_pkt_send(ssh, pktout);
7234 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7242 struct ssh_channel *c;
7243 unsigned remid, winsize, pktsize;
7244 struct Packet *pktout;
7246 ssh_pkt_getstring(pktin, &type, &typelen);
7247 c = snew(struct ssh_channel);
7250 remid = ssh_pkt_getuint32(pktin);
7251 winsize = ssh_pkt_getuint32(pktin);
7252 pktsize = ssh_pkt_getuint32(pktin);
7254 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7258 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7259 addrstr = snewn(peeraddrlen+1, char);
7260 memcpy(addrstr, peeraddr, peeraddrlen);
7261 addrstr[peeraddrlen] = '\0';
7262 peerport = ssh_pkt_getuint32(pktin);
7264 logeventf(ssh, "Received X11 connect request from %s:%d",
7267 if (!ssh->X11_fwd_enabled)
7268 error = "X11 forwarding is not enabled";
7269 else if ((x11err = x11_init(&c->u.x11.s, ssh->x11disp, c,
7270 addrstr, peerport, ssh->conf)) != NULL) {
7271 logeventf(ssh, "Local X11 connection failed: %s", x11err);
7272 error = "Unable to open an X11 connection";
7274 logevent("Opening X11 forward connection succeeded");
7279 } else if (typelen == 15 &&
7280 !memcmp(type, "forwarded-tcpip", 15)) {
7281 struct ssh_rportfwd pf, *realpf;
7284 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
7285 pf.sport = ssh_pkt_getuint32(pktin);
7286 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7287 peerport = ssh_pkt_getuint32(pktin);
7288 realpf = find234(ssh->rportfwds, &pf, NULL);
7289 logeventf(ssh, "Received remote port %d open request "
7290 "from %s:%d", pf.sport, peeraddr, peerport);
7291 if (realpf == NULL) {
7292 error = "Remote port is not recognised";
7294 const char *e = pfd_newconnect(&c->u.pfd.s,
7298 realpf->pfrec->addressfamily);
7299 logeventf(ssh, "Attempting to forward remote port to "
7300 "%s:%d", realpf->dhost, realpf->dport);
7302 logeventf(ssh, "Port open failed: %s", e);
7303 error = "Port open failed";
7305 logevent("Forwarded port opened successfully");
7306 c->type = CHAN_SOCKDATA;
7309 } else if (typelen == 22 &&
7310 !memcmp(type, "auth-agent@openssh.com", 22)) {
7311 if (!ssh->agentfwd_enabled)
7312 error = "Agent forwarding is not enabled";
7314 c->type = CHAN_AGENT; /* identify channel type */
7315 c->u.a.lensofar = 0;
7318 error = "Unsupported channel type requested";
7321 c->remoteid = remid;
7322 c->halfopen = FALSE;
7324 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7325 ssh2_pkt_adduint32(pktout, c->remoteid);
7326 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7327 ssh2_pkt_addstring(pktout, error);
7328 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7329 ssh2_pkt_send(ssh, pktout);
7330 logeventf(ssh, "Rejected channel open: %s", error);
7333 ssh2_channel_init(c);
7334 c->v.v2.remwindow = winsize;
7335 c->v.v2.remmaxpkt = pktsize;
7336 add234(ssh->channels, c);
7337 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7338 ssh2_pkt_adduint32(pktout, c->remoteid);
7339 ssh2_pkt_adduint32(pktout, c->localid);
7340 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7341 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7342 ssh2_pkt_send(ssh, pktout);
7347 * Buffer banner messages for later display at some convenient point,
7348 * if we're going to display them.
7350 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7352 /* Arbitrary limit to prevent unbounded inflation of buffer */
7353 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
7354 bufchain_size(&ssh->banner) <= 131072) {
7355 char *banner = NULL;
7357 ssh_pkt_getstring(pktin, &banner, &size);
7359 bufchain_add(&ssh->banner, banner, size);
7363 /* Helper function to deal with sending tty modes for "pty-req" */
7364 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7366 struct Packet *pktout = (struct Packet *)data;
7368 unsigned int arg = 0;
7369 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7370 if (i == lenof(ssh_ttymodes)) return;
7371 switch (ssh_ttymodes[i].type) {
7373 arg = ssh_tty_parse_specchar(val);
7376 arg = ssh_tty_parse_boolean(val);
7379 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7380 ssh2_pkt_adduint32(pktout, arg);
7384 * Handle the SSH-2 userauth and connection layers.
7386 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7387 struct Packet *pktin)
7389 struct do_ssh2_authconn_state {
7392 AUTH_TYPE_PUBLICKEY,
7393 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7394 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7396 AUTH_TYPE_GSSAPI, /* always QUIET */
7397 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7398 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7400 int done_service_req;
7401 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7402 int tried_pubkey_config, done_agent;
7407 int kbd_inter_refused;
7408 int we_are_in, userauth_success;
7409 prompts_t *cur_prompt;
7414 void *publickey_blob;
7415 int publickey_bloblen;
7416 int publickey_encrypted;
7417 char *publickey_algorithm;
7418 char *publickey_comment;
7419 unsigned char agent_request[5], *agent_response, *agentp;
7420 int agent_responselen;
7421 unsigned char *pkblob_in_agent;
7423 char *pkblob, *alg, *commentp;
7424 int pklen, alglen, commentlen;
7425 int siglen, retlen, len;
7426 char *q, *agentreq, *ret;
7428 int num_env, env_left, env_ok;
7429 struct Packet *pktout;
7432 struct ssh_gss_library *gsslib;
7433 Ssh_gss_ctx gss_ctx;
7434 Ssh_gss_buf gss_buf;
7435 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7436 Ssh_gss_name gss_srv_name;
7437 Ssh_gss_stat gss_stat;
7440 crState(do_ssh2_authconn_state);
7442 crBegin(ssh->do_ssh2_authconn_crstate);
7444 s->done_service_req = FALSE;
7445 s->we_are_in = s->userauth_success = FALSE;
7447 s->tried_gssapi = FALSE;
7450 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
7452 * Request userauth protocol, and await a response to it.
7454 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7455 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7456 ssh2_pkt_send(ssh, s->pktout);
7457 crWaitUntilV(pktin);
7458 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7459 s->done_service_req = TRUE;
7461 if (!s->done_service_req) {
7463 * Request connection protocol directly, without authentication.
7465 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7466 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7467 ssh2_pkt_send(ssh, s->pktout);
7468 crWaitUntilV(pktin);
7469 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7470 s->we_are_in = TRUE; /* no auth required */
7472 bombout(("Server refused service request"));
7477 /* Arrange to be able to deal with any BANNERs that come in.
7478 * (We do this now as packets may come in during the next bit.) */
7479 bufchain_init(&ssh->banner);
7480 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7481 ssh2_msg_userauth_banner;
7484 * Misc one-time setup for authentication.
7486 s->publickey_blob = NULL;
7487 if (!s->we_are_in) {
7490 * Load the public half of any configured public key file
7493 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
7494 if (!filename_is_null(*s->keyfile)) {
7496 logeventf(ssh, "Reading private key file \"%.150s\"",
7497 filename_to_str(s->keyfile));
7498 keytype = key_type(s->keyfile);
7499 if (keytype == SSH_KEYTYPE_SSH2) {
7502 ssh2_userkey_loadpub(s->keyfile,
7503 &s->publickey_algorithm,
7504 &s->publickey_bloblen,
7505 &s->publickey_comment, &error);
7506 if (s->publickey_blob) {
7507 s->publickey_encrypted =
7508 ssh2_userkey_encrypted(s->keyfile, NULL);
7511 logeventf(ssh, "Unable to load private key (%s)",
7513 msgbuf = dupprintf("Unable to load private key file "
7514 "\"%.150s\" (%s)\r\n",
7515 filename_to_str(s->keyfile),
7517 c_write_str(ssh, msgbuf);
7522 logeventf(ssh, "Unable to use this key file (%s)",
7523 key_type_to_str(keytype));
7524 msgbuf = dupprintf("Unable to use key file \"%.150s\""
7526 filename_to_str(s->keyfile),
7527 key_type_to_str(keytype));
7528 c_write_str(ssh, msgbuf);
7530 s->publickey_blob = NULL;
7535 * Find out about any keys Pageant has (but if there's a
7536 * public key configured, filter out all others).
7539 s->agent_response = NULL;
7540 s->pkblob_in_agent = NULL;
7541 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
7545 logevent("Pageant is running. Requesting keys.");
7547 /* Request the keys held by the agent. */
7548 PUT_32BIT(s->agent_request, 1);
7549 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
7550 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
7551 ssh_agent_callback, ssh)) {
7555 bombout(("Unexpected data from server while"
7556 " waiting for agent response"));
7559 } while (pktin || inlen > 0);
7560 r = ssh->agent_response;
7561 s->agent_responselen = ssh->agent_response_len;
7563 s->agent_response = (unsigned char *) r;
7564 if (s->agent_response && s->agent_responselen >= 5 &&
7565 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
7568 p = s->agent_response + 5;
7569 s->nkeys = GET_32BIT(p);
7571 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
7572 if (s->publickey_blob) {
7573 /* See if configured key is in agent. */
7574 for (keyi = 0; keyi < s->nkeys; keyi++) {
7575 s->pklen = GET_32BIT(p);
7576 if (s->pklen == s->publickey_bloblen &&
7577 !memcmp(p+4, s->publickey_blob,
7578 s->publickey_bloblen)) {
7579 logeventf(ssh, "Pageant key #%d matches "
7580 "configured key file", keyi);
7582 s->pkblob_in_agent = p;
7586 p += GET_32BIT(p) + 4; /* comment */
7588 if (!s->pkblob_in_agent) {
7589 logevent("Configured key file not in Pageant");
7594 logevent("Failed to get reply from Pageant");
7601 * We repeat this whole loop, including the username prompt,
7602 * until we manage a successful authentication. If the user
7603 * types the wrong _password_, they can be sent back to the
7604 * beginning to try another username, if this is configured on.
7605 * (If they specify a username in the config, they are never
7606 * asked, even if they do give a wrong password.)
7608 * I think this best serves the needs of
7610 * - the people who have no configuration, no keys, and just
7611 * want to try repeated (username,password) pairs until they
7612 * type both correctly
7614 * - people who have keys and configuration but occasionally
7615 * need to fall back to passwords
7617 * - people with a key held in Pageant, who might not have
7618 * logged in to a particular machine before; so they want to
7619 * type a username, and then _either_ their key will be
7620 * accepted, _or_ they will type a password. If they mistype
7621 * the username they will want to be able to get back and
7624 s->got_username = FALSE;
7625 while (!s->we_are_in) {
7629 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
7631 * We got a username last time round this loop, and
7632 * with change_username turned off we don't try to get
7635 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
7636 int ret; /* need not be kept over crReturn */
7637 s->cur_prompt = new_prompts(ssh->frontend);
7638 s->cur_prompt->to_server = TRUE;
7639 s->cur_prompt->name = dupstr("SSH login name");
7640 /* 512 is an arbitrary limit :-( */
7641 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE, 512);
7642 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7645 crWaitUntilV(!pktin);
7646 ret = get_userpass_input(s->cur_prompt, in, inlen);
7651 * get_userpass_input() failed to get a username.
7654 free_prompts(s->cur_prompt);
7655 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
7658 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
7659 free_prompts(s->cur_prompt);
7662 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7663 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
7664 c_write_str(ssh, stuff);
7668 s->got_username = TRUE;
7671 * Send an authentication request using method "none": (a)
7672 * just in case it succeeds, and (b) so that we know what
7673 * authentication methods we can usefully try next.
7675 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7677 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7678 ssh2_pkt_addstring(s->pktout, ssh->username);
7679 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
7680 ssh2_pkt_addstring(s->pktout, "none"); /* method */
7681 ssh2_pkt_send(ssh, s->pktout);
7682 s->type = AUTH_TYPE_NONE;
7684 s->we_are_in = FALSE;
7686 s->tried_pubkey_config = FALSE;
7687 s->kbd_inter_refused = FALSE;
7689 /* Reset agent request state. */
7690 s->done_agent = FALSE;
7691 if (s->agent_response) {
7692 if (s->pkblob_in_agent) {
7693 s->agentp = s->pkblob_in_agent;
7695 s->agentp = s->agent_response + 5 + 4;
7701 char *methods = NULL;
7705 * Wait for the result of the last authentication request.
7708 crWaitUntilV(pktin);
7710 * Now is a convenient point to spew any banner material
7711 * that we've accumulated. (This should ensure that when
7712 * we exit the auth loop, we haven't any left to deal
7716 int size = bufchain_size(&ssh->banner);
7718 * Don't show the banner if we're operating in
7719 * non-verbose non-interactive mode. (It's probably
7720 * a script, which means nobody will read the
7721 * banner _anyway_, and moreover the printing of
7722 * the banner will screw up processing on the
7723 * output of (say) plink.)
7725 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
7726 char *banner = snewn(size, char);
7727 bufchain_fetch(&ssh->banner, banner, size);
7728 c_write_untrusted(ssh, banner, size);
7731 bufchain_clear(&ssh->banner);
7733 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
7734 logevent("Access granted");
7735 s->we_are_in = s->userauth_success = TRUE;
7739 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
7740 bombout(("Strange packet received during authentication: "
7741 "type %d", pktin->type));
7748 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7749 * we can look at the string in it and know what we can
7750 * helpfully try next.
7752 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
7753 ssh_pkt_getstring(pktin, &methods, &methlen);
7754 if (!ssh2_pkt_getbool(pktin)) {
7756 * We have received an unequivocal Access
7757 * Denied. This can translate to a variety of
7758 * messages, or no message at all.
7760 * For forms of authentication which are attempted
7761 * implicitly, by which I mean without printing
7762 * anything in the window indicating that we're
7763 * trying them, we should never print 'Access
7766 * If we do print a message saying that we're
7767 * attempting some kind of authentication, it's OK
7768 * to print a followup message saying it failed -
7769 * but the message may sometimes be more specific
7770 * than simply 'Access denied'.
7772 * Additionally, if we'd just tried password
7773 * authentication, we should break out of this
7774 * whole loop so as to go back to the username
7775 * prompt (iff we're configured to allow
7776 * username change attempts).
7778 if (s->type == AUTH_TYPE_NONE) {
7780 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
7781 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
7782 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
7783 c_write_str(ssh, "Server refused our key\r\n");
7784 logevent("Server refused our key");
7785 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
7786 /* This _shouldn't_ happen except by a
7787 * protocol bug causing client and server to
7788 * disagree on what is a correct signature. */
7789 c_write_str(ssh, "Server refused public-key signature"
7790 " despite accepting key!\r\n");
7791 logevent("Server refused public-key signature"
7792 " despite accepting key!");
7793 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
7794 /* quiet, so no c_write */
7795 logevent("Server refused keyboard-interactive authentication");
7796 } else if (s->type==AUTH_TYPE_GSSAPI) {
7797 /* always quiet, so no c_write */
7798 /* also, the code down in the GSSAPI block has
7799 * already logged this in the Event Log */
7800 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
7801 logevent("Keyboard-interactive authentication failed");
7802 c_write_str(ssh, "Access denied\r\n");
7804 assert(s->type == AUTH_TYPE_PASSWORD);
7805 logevent("Password authentication failed");
7806 c_write_str(ssh, "Access denied\r\n");
7808 if (conf_get_int(ssh->conf, CONF_change_username)) {
7809 /* XXX perhaps we should allow
7810 * keyboard-interactive to do this too? */
7811 s->we_are_in = FALSE;
7816 c_write_str(ssh, "Further authentication required\r\n");
7817 logevent("Further authentication required");
7821 in_commasep_string("publickey", methods, methlen);
7823 in_commasep_string("password", methods, methlen);
7824 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
7825 in_commasep_string("keyboard-interactive", methods, methlen);
7828 ssh->gsslibs = ssh_gss_setup(ssh->conf);
7829 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
7830 in_commasep_string("gssapi-with-mic", methods, methlen) &&
7831 ssh->gsslibs->nlibraries > 0;
7835 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7837 if (s->can_pubkey && !s->done_agent && s->nkeys) {
7840 * Attempt public-key authentication using a key from Pageant.
7843 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7845 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
7847 /* Unpack key from agent response */
7848 s->pklen = GET_32BIT(s->agentp);
7850 s->pkblob = (char *)s->agentp;
7851 s->agentp += s->pklen;
7852 s->alglen = GET_32BIT(s->pkblob);
7853 s->alg = s->pkblob + 4;
7854 s->commentlen = GET_32BIT(s->agentp);
7856 s->commentp = (char *)s->agentp;
7857 s->agentp += s->commentlen;
7858 /* s->agentp now points at next key, if any */
7860 /* See if server will accept it */
7861 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7862 ssh2_pkt_addstring(s->pktout, ssh->username);
7863 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7864 /* service requested */
7865 ssh2_pkt_addstring(s->pktout, "publickey");
7867 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
7868 ssh2_pkt_addstring_start(s->pktout);
7869 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7870 ssh2_pkt_addstring_start(s->pktout);
7871 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7872 ssh2_pkt_send(ssh, s->pktout);
7873 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
7875 crWaitUntilV(pktin);
7876 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7878 /* Offer of key refused. */
7885 if (flags & FLAG_VERBOSE) {
7886 c_write_str(ssh, "Authenticating with "
7888 c_write(ssh, s->commentp, s->commentlen);
7889 c_write_str(ssh, "\" from agent\r\n");
7893 * Server is willing to accept the key.
7894 * Construct a SIGN_REQUEST.
7896 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7897 ssh2_pkt_addstring(s->pktout, ssh->username);
7898 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7899 /* service requested */
7900 ssh2_pkt_addstring(s->pktout, "publickey");
7902 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
7903 ssh2_pkt_addstring_start(s->pktout);
7904 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7905 ssh2_pkt_addstring_start(s->pktout);
7906 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7908 /* Ask agent for signature. */
7909 s->siglen = s->pktout->length - 5 + 4 +
7910 ssh->v2_session_id_len;
7911 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7913 s->len = 1; /* message type */
7914 s->len += 4 + s->pklen; /* key blob */
7915 s->len += 4 + s->siglen; /* data to sign */
7916 s->len += 4; /* flags */
7917 s->agentreq = snewn(4 + s->len, char);
7918 PUT_32BIT(s->agentreq, s->len);
7919 s->q = s->agentreq + 4;
7920 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
7921 PUT_32BIT(s->q, s->pklen);
7923 memcpy(s->q, s->pkblob, s->pklen);
7925 PUT_32BIT(s->q, s->siglen);
7927 /* Now the data to be signed... */
7928 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7929 PUT_32BIT(s->q, ssh->v2_session_id_len);
7932 memcpy(s->q, ssh->v2_session_id,
7933 ssh->v2_session_id_len);
7934 s->q += ssh->v2_session_id_len;
7935 memcpy(s->q, s->pktout->data + 5,
7936 s->pktout->length - 5);
7937 s->q += s->pktout->length - 5;
7938 /* And finally the (zero) flags word. */
7940 if (!agent_query(s->agentreq, s->len + 4,
7942 ssh_agent_callback, ssh)) {
7946 bombout(("Unexpected data from server"
7947 " while waiting for agent"
7951 } while (pktin || inlen > 0);
7952 vret = ssh->agent_response;
7953 s->retlen = ssh->agent_response_len;
7958 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
7959 logevent("Sending Pageant's response");
7960 ssh2_add_sigblob(ssh, s->pktout,
7961 s->pkblob, s->pklen,
7963 GET_32BIT(s->ret + 5));
7964 ssh2_pkt_send(ssh, s->pktout);
7965 s->type = AUTH_TYPE_PUBLICKEY;
7967 /* FIXME: less drastic response */
7968 bombout(("Pageant failed to answer challenge"));
7974 /* Do we have any keys left to try? */
7975 if (s->pkblob_in_agent) {
7976 s->done_agent = TRUE;
7977 s->tried_pubkey_config = TRUE;
7980 if (s->keyi >= s->nkeys)
7981 s->done_agent = TRUE;
7984 } else if (s->can_pubkey && s->publickey_blob &&
7985 !s->tried_pubkey_config) {
7987 struct ssh2_userkey *key; /* not live over crReturn */
7988 char *passphrase; /* not live over crReturn */
7990 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7992 s->tried_pubkey_config = TRUE;
7995 * Try the public key supplied in the configuration.
7997 * First, offer the public blob to see if the server is
7998 * willing to accept it.
8000 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8001 ssh2_pkt_addstring(s->pktout, ssh->username);
8002 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8003 /* service requested */
8004 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
8005 ssh2_pkt_addbool(s->pktout, FALSE);
8006 /* no signature included */
8007 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
8008 ssh2_pkt_addstring_start(s->pktout);
8009 ssh2_pkt_addstring_data(s->pktout,
8010 (char *)s->publickey_blob,
8011 s->publickey_bloblen);
8012 ssh2_pkt_send(ssh, s->pktout);
8013 logevent("Offered public key");
8015 crWaitUntilV(pktin);
8016 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8017 /* Key refused. Give up. */
8018 s->gotit = TRUE; /* reconsider message next loop */
8019 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
8020 continue; /* process this new message */
8022 logevent("Offer of public key accepted");
8025 * Actually attempt a serious authentication using
8028 if (flags & FLAG_VERBOSE) {
8029 c_write_str(ssh, "Authenticating with public key \"");
8030 c_write_str(ssh, s->publickey_comment);
8031 c_write_str(ssh, "\"\r\n");
8035 const char *error; /* not live over crReturn */
8036 if (s->publickey_encrypted) {
8038 * Get a passphrase from the user.
8040 int ret; /* need not be kept over crReturn */
8041 s->cur_prompt = new_prompts(ssh->frontend);
8042 s->cur_prompt->to_server = FALSE;
8043 s->cur_prompt->name = dupstr("SSH key passphrase");
8044 add_prompt(s->cur_prompt,
8045 dupprintf("Passphrase for key \"%.100s\": ",
8046 s->publickey_comment),
8047 FALSE, SSH_MAX_PASSWORD_LEN);
8048 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8051 crWaitUntilV(!pktin);
8052 ret = get_userpass_input(s->cur_prompt,
8057 /* Failed to get a passphrase. Terminate. */
8058 free_prompts(s->cur_prompt);
8059 ssh_disconnect(ssh, NULL,
8060 "Unable to authenticate",
8061 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8066 dupstr(s->cur_prompt->prompts[0]->result);
8067 free_prompts(s->cur_prompt);
8069 passphrase = NULL; /* no passphrase needed */
8073 * Try decrypting the key.
8075 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8076 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
8078 /* burn the evidence */
8079 memset(passphrase, 0, strlen(passphrase));
8082 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
8084 (key == SSH2_WRONG_PASSPHRASE)) {
8085 c_write_str(ssh, "Wrong passphrase\r\n");
8087 /* and loop again */
8089 c_write_str(ssh, "Unable to load private key (");
8090 c_write_str(ssh, error);
8091 c_write_str(ssh, ")\r\n");
8093 break; /* try something else */
8099 unsigned char *pkblob, *sigblob, *sigdata;
8100 int pkblob_len, sigblob_len, sigdata_len;
8104 * We have loaded the private key and the server
8105 * has announced that it's willing to accept it.
8106 * Hallelujah. Generate a signature and send it.
8108 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8109 ssh2_pkt_addstring(s->pktout, ssh->username);
8110 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8111 /* service requested */
8112 ssh2_pkt_addstring(s->pktout, "publickey");
8114 ssh2_pkt_addbool(s->pktout, TRUE);
8115 /* signature follows */
8116 ssh2_pkt_addstring(s->pktout, key->alg->name);
8117 pkblob = key->alg->public_blob(key->data,
8119 ssh2_pkt_addstring_start(s->pktout);
8120 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
8124 * The data to be signed is:
8128 * followed by everything so far placed in the
8131 sigdata_len = s->pktout->length - 5 + 4 +
8132 ssh->v2_session_id_len;
8133 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8135 sigdata = snewn(sigdata_len, unsigned char);
8137 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8138 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
8141 memcpy(sigdata+p, ssh->v2_session_id,
8142 ssh->v2_session_id_len);
8143 p += ssh->v2_session_id_len;
8144 memcpy(sigdata+p, s->pktout->data + 5,
8145 s->pktout->length - 5);
8146 p += s->pktout->length - 5;
8147 assert(p == sigdata_len);
8148 sigblob = key->alg->sign(key->data, (char *)sigdata,
8149 sigdata_len, &sigblob_len);
8150 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
8151 sigblob, sigblob_len);
8156 ssh2_pkt_send(ssh, s->pktout);
8157 logevent("Sent public key signature");
8158 s->type = AUTH_TYPE_PUBLICKEY;
8159 key->alg->freekey(key->data);
8163 } else if (s->can_gssapi && !s->tried_gssapi) {
8165 /* GSSAPI Authentication */
8170 s->type = AUTH_TYPE_GSSAPI;
8171 s->tried_gssapi = TRUE;
8173 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
8176 * Pick the highest GSS library on the preference
8182 for (i = 0; i < ngsslibs; i++) {
8183 int want_id = conf_get_int_int(ssh->conf,
8184 CONF_ssh_gsslist, i);
8185 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
8186 if (ssh->gsslibs->libraries[j].id == want_id) {
8187 s->gsslib = &ssh->gsslibs->libraries[j];
8188 goto got_gsslib; /* double break */
8193 * We always expect to have found something in
8194 * the above loop: we only came here if there
8195 * was at least one viable GSS library, and the
8196 * preference list should always mention
8197 * everything and only change the order.
8202 if (s->gsslib->gsslogmsg)
8203 logevent(s->gsslib->gsslogmsg);
8205 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8206 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8207 ssh2_pkt_addstring(s->pktout, ssh->username);
8208 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8209 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
8210 logevent("Attempting GSSAPI authentication");
8212 /* add mechanism info */
8213 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
8215 /* number of GSSAPI mechanisms */
8216 ssh2_pkt_adduint32(s->pktout,1);
8218 /* length of OID + 2 */
8219 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
8220 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
8223 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
8225 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
8227 ssh2_pkt_send(ssh, s->pktout);
8228 crWaitUntilV(pktin);
8229 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
8230 logevent("GSSAPI authentication request refused");
8234 /* check returned packet ... */
8236 ssh_pkt_getstring(pktin, &data, &len);
8237 s->gss_rcvtok.value = data;
8238 s->gss_rcvtok.length = len;
8239 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
8240 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
8241 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
8242 memcmp((char *)s->gss_rcvtok.value + 2,
8243 s->gss_buf.value,s->gss_buf.length) ) {
8244 logevent("GSSAPI authentication - wrong response from server");
8248 /* now start running */
8249 s->gss_stat = s->gsslib->import_name(s->gsslib,
8252 if (s->gss_stat != SSH_GSS_OK) {
8253 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
8254 logevent("GSSAPI import name failed - Bad service name");
8256 logevent("GSSAPI import name failed");
8260 /* fetch TGT into GSS engine */
8261 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
8263 if (s->gss_stat != SSH_GSS_OK) {
8264 logevent("GSSAPI authentication failed to get credentials");
8265 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8269 /* initial tokens are empty */
8270 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
8271 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
8273 /* now enter the loop */
8275 s->gss_stat = s->gsslib->init_sec_context
8279 conf_get_int(ssh->conf, CONF_gssapifwd),
8283 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
8284 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
8285 logevent("GSSAPI authentication initialisation failed");
8287 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
8288 &s->gss_buf) == SSH_GSS_OK) {
8289 logevent(s->gss_buf.value);
8290 sfree(s->gss_buf.value);
8295 logevent("GSSAPI authentication initialised");
8297 /* Client and server now exchange tokens until GSSAPI
8298 * no longer says CONTINUE_NEEDED */
8300 if (s->gss_sndtok.length != 0) {
8301 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8302 ssh_pkt_addstring_start(s->pktout);
8303 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
8304 ssh2_pkt_send(ssh, s->pktout);
8305 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
8308 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8309 crWaitUntilV(pktin);
8310 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8311 logevent("GSSAPI authentication - bad server response");
8312 s->gss_stat = SSH_GSS_FAILURE;
8315 ssh_pkt_getstring(pktin, &data, &len);
8316 s->gss_rcvtok.value = data;
8317 s->gss_rcvtok.length = len;
8319 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8321 if (s->gss_stat != SSH_GSS_OK) {
8322 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8323 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8326 logevent("GSSAPI authentication loop finished OK");
8328 /* Now send the MIC */
8330 s->pktout = ssh2_pkt_init(0);
8331 micoffset = s->pktout->length;
8332 ssh_pkt_addstring_start(s->pktout);
8333 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8334 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
8335 ssh_pkt_addstring(s->pktout, ssh->username);
8336 ssh_pkt_addstring(s->pktout, "ssh-connection");
8337 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8339 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8340 s->gss_buf.length = s->pktout->length - micoffset;
8342 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
8343 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8344 ssh_pkt_addstring_start(s->pktout);
8345 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
8346 ssh2_pkt_send(ssh, s->pktout);
8347 s->gsslib->free_mic(s->gsslib, &mic);
8351 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8352 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8355 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8358 * Keyboard-interactive authentication.
8361 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8363 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
8365 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8366 ssh2_pkt_addstring(s->pktout, ssh->username);
8367 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8368 /* service requested */
8369 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8371 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8372 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8373 ssh2_pkt_send(ssh, s->pktout);
8375 logevent("Attempting keyboard-interactive authentication");
8377 crWaitUntilV(pktin);
8378 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8379 /* Server is not willing to do keyboard-interactive
8380 * at all (or, bizarrely but legally, accepts the
8381 * user without actually issuing any prompts).
8382 * Give up on it entirely. */
8384 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8385 s->kbd_inter_refused = TRUE; /* don't try it again */
8390 * Loop while the server continues to send INFO_REQUESTs.
8392 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
8394 char *name, *inst, *lang;
8395 int name_len, inst_len, lang_len;
8399 * We've got a fresh USERAUTH_INFO_REQUEST.
8400 * Get the preamble and start building a prompt.
8402 ssh_pkt_getstring(pktin, &name, &name_len);
8403 ssh_pkt_getstring(pktin, &inst, &inst_len);
8404 ssh_pkt_getstring(pktin, &lang, &lang_len);
8405 s->cur_prompt = new_prompts(ssh->frontend);
8406 s->cur_prompt->to_server = TRUE;
8409 * Get any prompt(s) from the packet.
8411 s->num_prompts = ssh_pkt_getuint32(pktin);
8412 for (i = 0; i < s->num_prompts; i++) {
8416 static char noprompt[] =
8417 "<server failed to send prompt>: ";
8419 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8420 echo = ssh2_pkt_getbool(pktin);
8423 prompt_len = lenof(noprompt)-1;
8425 add_prompt(s->cur_prompt,
8426 dupprintf("%.*s", prompt_len, prompt),
8427 echo, SSH_MAX_PASSWORD_LEN);
8431 /* FIXME: better prefix to distinguish from
8433 s->cur_prompt->name =
8434 dupprintf("SSH server: %.*s", name_len, name);
8435 s->cur_prompt->name_reqd = TRUE;
8437 s->cur_prompt->name =
8438 dupstr("SSH server authentication");
8439 s->cur_prompt->name_reqd = FALSE;
8441 /* We add a prefix to try to make it clear that a prompt
8442 * has come from the server.
8443 * FIXME: ugly to print "Using..." in prompt _every_
8444 * time round. Can this be done more subtly? */
8445 /* Special case: for reasons best known to themselves,
8446 * some servers send k-i requests with no prompts and
8447 * nothing to display. Keep quiet in this case. */
8448 if (s->num_prompts || name_len || inst_len) {
8449 s->cur_prompt->instruction =
8450 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8451 inst_len ? "\n" : "", inst_len, inst);
8452 s->cur_prompt->instr_reqd = TRUE;
8454 s->cur_prompt->instr_reqd = FALSE;
8458 * Display any instructions, and get the user's
8462 int ret; /* not live over crReturn */
8463 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8466 crWaitUntilV(!pktin);
8467 ret = get_userpass_input(s->cur_prompt, in, inlen);
8472 * Failed to get responses. Terminate.
8474 free_prompts(s->cur_prompt);
8475 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8476 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8483 * Send the response(s) to the server.
8485 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
8486 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
8487 for (i=0; i < s->num_prompts; i++) {
8488 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8489 ssh2_pkt_addstring(s->pktout,
8490 s->cur_prompt->prompts[i]->result);
8491 end_log_omission(ssh, s->pktout);
8493 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8496 * Get the next packet in case it's another
8499 crWaitUntilV(pktin);
8504 * We should have SUCCESS or FAILURE now.
8508 } else if (s->can_passwd) {
8511 * Plain old password authentication.
8513 int ret; /* not live over crReturn */
8514 int changereq_first_time; /* not live over crReturn */
8516 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
8518 s->cur_prompt = new_prompts(ssh->frontend);
8519 s->cur_prompt->to_server = TRUE;
8520 s->cur_prompt->name = dupstr("SSH password");
8521 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
8524 FALSE, SSH_MAX_PASSWORD_LEN);
8526 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8529 crWaitUntilV(!pktin);
8530 ret = get_userpass_input(s->cur_prompt, in, inlen);
8535 * Failed to get responses. Terminate.
8537 free_prompts(s->cur_prompt);
8538 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8539 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8544 * Squirrel away the password. (We may need it later if
8545 * asked to change it.)
8547 s->password = dupstr(s->cur_prompt->prompts[0]->result);
8548 free_prompts(s->cur_prompt);
8551 * Send the password packet.
8553 * We pad out the password packet to 256 bytes to make
8554 * it harder for an attacker to find the length of the
8557 * Anyone using a password longer than 256 bytes
8558 * probably doesn't have much to worry about from
8559 * people who find out how long their password is!
8561 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8562 ssh2_pkt_addstring(s->pktout, ssh->username);
8563 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8564 /* service requested */
8565 ssh2_pkt_addstring(s->pktout, "password");
8566 ssh2_pkt_addbool(s->pktout, FALSE);
8567 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8568 ssh2_pkt_addstring(s->pktout, s->password);
8569 end_log_omission(ssh, s->pktout);
8570 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8571 logevent("Sent password");
8572 s->type = AUTH_TYPE_PASSWORD;
8575 * Wait for next packet, in case it's a password change
8578 crWaitUntilV(pktin);
8579 changereq_first_time = TRUE;
8581 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
8584 * We're being asked for a new password
8585 * (perhaps not for the first time).
8586 * Loop until the server accepts it.
8589 int got_new = FALSE; /* not live over crReturn */
8590 char *prompt; /* not live over crReturn */
8591 int prompt_len; /* not live over crReturn */
8595 if (changereq_first_time)
8596 msg = "Server requested password change";
8598 msg = "Server rejected new password";
8600 c_write_str(ssh, msg);
8601 c_write_str(ssh, "\r\n");
8604 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8606 s->cur_prompt = new_prompts(ssh->frontend);
8607 s->cur_prompt->to_server = TRUE;
8608 s->cur_prompt->name = dupstr("New SSH password");
8609 s->cur_prompt->instruction =
8610 dupprintf("%.*s", prompt_len, prompt);
8611 s->cur_prompt->instr_reqd = TRUE;
8613 * There's no explicit requirement in the protocol
8614 * for the "old" passwords in the original and
8615 * password-change messages to be the same, and
8616 * apparently some Cisco kit supports password change
8617 * by the user entering a blank password originally
8618 * and the real password subsequently, so,
8619 * reluctantly, we prompt for the old password again.
8621 * (On the other hand, some servers don't even bother
8622 * to check this field.)
8624 add_prompt(s->cur_prompt,
8625 dupstr("Current password (blank for previously entered password): "),
8626 FALSE, SSH_MAX_PASSWORD_LEN);
8627 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
8628 FALSE, SSH_MAX_PASSWORD_LEN);
8629 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
8630 FALSE, SSH_MAX_PASSWORD_LEN);
8633 * Loop until the user manages to enter the same
8638 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8641 crWaitUntilV(!pktin);
8642 ret = get_userpass_input(s->cur_prompt, in, inlen);
8647 * Failed to get responses. Terminate.
8649 /* burn the evidence */
8650 free_prompts(s->cur_prompt);
8651 memset(s->password, 0, strlen(s->password));
8653 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8654 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8660 * If the user specified a new original password
8661 * (IYSWIM), overwrite any previously specified
8663 * (A side effect is that the user doesn't have to
8664 * re-enter it if they louse up the new password.)
8666 if (s->cur_prompt->prompts[0]->result[0]) {
8667 memset(s->password, 0, strlen(s->password));
8668 /* burn the evidence */
8671 dupstr(s->cur_prompt->prompts[0]->result);
8675 * Check the two new passwords match.
8677 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
8678 s->cur_prompt->prompts[2]->result)
8681 /* They don't. Silly user. */
8682 c_write_str(ssh, "Passwords do not match\r\n");
8687 * Send the new password (along with the old one).
8688 * (see above for padding rationale)
8690 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8691 ssh2_pkt_addstring(s->pktout, ssh->username);
8692 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8693 /* service requested */
8694 ssh2_pkt_addstring(s->pktout, "password");
8695 ssh2_pkt_addbool(s->pktout, TRUE);
8696 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8697 ssh2_pkt_addstring(s->pktout, s->password);
8698 ssh2_pkt_addstring(s->pktout,
8699 s->cur_prompt->prompts[1]->result);
8700 free_prompts(s->cur_prompt);
8701 end_log_omission(ssh, s->pktout);
8702 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8703 logevent("Sent new password");
8706 * Now see what the server has to say about it.
8707 * (If it's CHANGEREQ again, it's not happy with the
8710 crWaitUntilV(pktin);
8711 changereq_first_time = FALSE;
8716 * We need to reexamine the current pktin at the top
8717 * of the loop. Either:
8718 * - we weren't asked to change password at all, in
8719 * which case it's a SUCCESS or FAILURE with the
8721 * - we sent a new password, and the server was
8722 * either OK with it (SUCCESS or FAILURE w/partial
8723 * success) or unhappy with the _old_ password
8724 * (FAILURE w/o partial success)
8725 * In any of these cases, we go back to the top of
8726 * the loop and start again.
8731 * We don't need the old password any more, in any
8732 * case. Burn the evidence.
8734 memset(s->password, 0, strlen(s->password));
8738 char *str = dupprintf("No supported authentication methods available"
8739 " (server sent: %.*s)",
8742 ssh_disconnect(ssh, str,
8743 "No supported authentication methods available",
8744 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
8754 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
8756 /* Clear up various bits and pieces from authentication. */
8757 if (s->publickey_blob) {
8758 sfree(s->publickey_blob);
8759 sfree(s->publickey_comment);
8761 if (s->agent_response)
8762 sfree(s->agent_response);
8764 if (s->userauth_success) {
8766 * We've just received USERAUTH_SUCCESS, and we haven't sent any
8767 * packets since. Signal the transport layer to consider enacting
8768 * delayed compression.
8770 * (Relying on we_are_in is not sufficient, as
8771 * draft-miller-secsh-compression-delayed is quite clear that it
8772 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
8773 * become set for other reasons.)
8775 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
8779 * Now the connection protocol has started, one way or another.
8782 ssh->channels = newtree234(ssh_channelcmp);
8785 * Set up handlers for some connection protocol messages, so we
8786 * don't have to handle them repeatedly in this coroutine.
8788 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
8789 ssh2_msg_channel_window_adjust;
8790 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
8791 ssh2_msg_global_request;
8794 * Create the main session channel.
8796 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
8797 ssh->mainchan = NULL;
8798 } else if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
8800 * Just start a direct-tcpip channel and use it as the main
8803 ssh->mainchan = snew(struct ssh_channel);
8804 ssh->mainchan->ssh = ssh;
8805 ssh2_channel_init(ssh->mainchan);
8807 "Opening direct-tcpip channel to %s:%d in place of session",
8808 conf_get_str(ssh->conf, CONF_ssh_nc_host),
8809 conf_get_int(ssh->conf, CONF_ssh_nc_port));
8810 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8811 ssh2_pkt_addstring(s->pktout, "direct-tcpip");
8812 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8813 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8814 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8815 ssh2_pkt_addstring(s->pktout, conf_get_str(ssh->conf, CONF_ssh_nc_host));
8816 ssh2_pkt_adduint32(s->pktout, conf_get_int(ssh->conf, CONF_ssh_nc_port));
8818 * There's nothing meaningful to put in the originator
8819 * fields, but some servers insist on syntactically correct
8822 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
8823 ssh2_pkt_adduint32(s->pktout, 0);
8824 ssh2_pkt_send(ssh, s->pktout);
8826 crWaitUntilV(pktin);
8827 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8828 bombout(("Server refused to open a direct-tcpip channel"));
8830 /* FIXME: error data comes back in FAILURE packet */
8832 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8833 bombout(("Server's channel confirmation cited wrong channel"));
8836 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8837 ssh->mainchan->halfopen = FALSE;
8838 ssh->mainchan->type = CHAN_MAINSESSION;
8839 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8840 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8841 add234(ssh->channels, ssh->mainchan);
8842 update_specials_menu(ssh->frontend);
8843 logevent("Opened direct-tcpip channel");
8846 ssh->mainchan = snew(struct ssh_channel);
8847 ssh->mainchan->ssh = ssh;
8848 ssh2_channel_init(ssh->mainchan);
8849 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8850 ssh2_pkt_addstring(s->pktout, "session");
8851 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8852 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8853 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8854 ssh2_pkt_send(ssh, s->pktout);
8855 crWaitUntilV(pktin);
8856 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8857 bombout(("Server refused to open a session"));
8859 /* FIXME: error data comes back in FAILURE packet */
8861 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8862 bombout(("Server's channel confirmation cited wrong channel"));
8865 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8866 ssh->mainchan->halfopen = FALSE;
8867 ssh->mainchan->type = CHAN_MAINSESSION;
8868 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8869 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8870 add234(ssh->channels, ssh->mainchan);
8871 update_specials_menu(ssh->frontend);
8872 logevent("Opened channel for session");
8873 ssh->ncmode = FALSE;
8877 * Now we have a channel, make dispatch table entries for
8878 * general channel-based messages.
8880 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
8881 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
8882 ssh2_msg_channel_data;
8883 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
8884 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
8885 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
8886 ssh2_msg_channel_open_confirmation;
8887 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
8888 ssh2_msg_channel_open_failure;
8889 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
8890 ssh2_msg_channel_request;
8891 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
8892 ssh2_msg_channel_open;
8894 if (ssh->mainchan && conf_get_int(ssh->conf, CONF_ssh_simple)) {
8896 * This message indicates to the server that we promise
8897 * not to try to run any other channel in parallel with
8898 * this one, so it's safe for it to advertise a very large
8899 * window and leave the flow control to TCP.
8901 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8902 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8903 ssh2_pkt_addstring(s->pktout, "simple@putty.projects.tartarus.org");
8904 ssh2_pkt_addbool(s->pktout, 0); /* no reply */
8905 ssh2_pkt_send(ssh, s->pktout);
8909 * Potentially enable X11 forwarding.
8911 if (ssh->mainchan && !ssh->ncmode && conf_get_int(ssh->conf, CONF_x11_forward) &&
8912 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
8913 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
8914 logevent("Requesting X11 forwarding");
8915 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8916 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8917 ssh2_pkt_addstring(s->pktout, "x11-req");
8918 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8919 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
8920 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthprotoname);
8922 * Note that while we blank the X authentication data here, we don't
8923 * take any special action to blank the start of an X11 channel,
8924 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
8925 * without having session blanking enabled is likely to leak your
8926 * cookie into the log.
8928 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8929 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthdatastring);
8930 end_log_omission(ssh, s->pktout);
8931 ssh2_pkt_adduint32(s->pktout, ssh->x11disp->screennum);
8932 ssh2_pkt_send(ssh, s->pktout);
8934 crWaitUntilV(pktin);
8936 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8937 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8938 bombout(("Unexpected response to X11 forwarding request:"
8939 " packet type %d", pktin->type));
8942 logevent("X11 forwarding refused");
8944 logevent("X11 forwarding enabled");
8945 ssh->X11_fwd_enabled = TRUE;
8950 * Enable port forwardings.
8952 ssh_setup_portfwd(ssh, ssh->conf);
8955 * Potentially enable agent forwarding.
8957 if (ssh->mainchan && !ssh->ncmode && conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
8958 logevent("Requesting OpenSSH-style agent forwarding");
8959 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8960 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8961 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
8962 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8963 ssh2_pkt_send(ssh, s->pktout);
8965 crWaitUntilV(pktin);
8967 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8968 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8969 bombout(("Unexpected response to agent forwarding request:"
8970 " packet type %d", pktin->type));
8973 logevent("Agent forwarding refused");
8975 logevent("Agent forwarding enabled");
8976 ssh->agentfwd_enabled = TRUE;
8981 * Now allocate a pty for the session.
8983 if (ssh->mainchan && !ssh->ncmode && !conf_get_int(ssh->conf, CONF_nopty)) {
8984 /* Unpick the terminal-speed string. */
8985 /* XXX perhaps we should allow no speeds to be sent. */
8986 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8987 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8988 /* Build the pty request. */
8989 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8990 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
8991 ssh2_pkt_addstring(s->pktout, "pty-req");
8992 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8993 ssh2_pkt_addstring(s->pktout, conf_get_str(ssh->conf, CONF_termtype));
8994 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
8995 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
8996 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
8997 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
8998 ssh2_pkt_addstring_start(s->pktout);
8999 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)s->pktout);
9000 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_ISPEED);
9001 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
9002 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_OSPEED);
9003 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
9004 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
9005 ssh2_pkt_send(ssh, s->pktout);
9006 ssh->state = SSH_STATE_INTERMED;
9008 crWaitUntilV(pktin);
9010 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9011 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9012 bombout(("Unexpected response to pty request:"
9013 " packet type %d", pktin->type));
9016 c_write_str(ssh, "Server refused to allocate pty\r\n");
9017 ssh->editing = ssh->echoing = 1;
9019 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9020 ssh->ospeed, ssh->ispeed);
9023 ssh->editing = ssh->echoing = 1;
9027 * Send environment variables.
9029 * Simplest thing here is to send all the requests at once, and
9030 * then wait for a whole bunch of successes or failures.
9032 if (ssh->mainchan && !ssh->ncmode) {
9037 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9039 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9040 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9041 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
9042 ssh2_pkt_addstring(s->pktout, "env");
9043 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9044 ssh2_pkt_addstring(s->pktout, key);
9045 ssh2_pkt_addstring(s->pktout, val);
9046 ssh2_pkt_send(ssh, s->pktout);
9052 logeventf(ssh, "Sent %d environment variables", s->num_env);
9055 s->env_left = s->num_env;
9057 while (s->env_left > 0) {
9058 crWaitUntilV(pktin);
9060 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9061 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9062 bombout(("Unexpected response to environment request:"
9063 " packet type %d", pktin->type));
9073 if (s->env_ok == s->num_env) {
9074 logevent("All environment variables successfully set");
9075 } else if (s->env_ok == 0) {
9076 logevent("All environment variables refused");
9077 c_write_str(ssh, "Server refused to set environment variables\r\n");
9079 logeventf(ssh, "%d environment variables refused",
9080 s->num_env - s->env_ok);
9081 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9087 * Start a shell or a remote command. We may have to attempt
9088 * this twice if the config data has provided a second choice
9091 if (ssh->mainchan && !ssh->ncmode) while (1) {
9095 if (ssh->fallback_cmd) {
9096 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
9097 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
9099 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
9100 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
9103 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9104 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
9106 ssh2_pkt_addstring(s->pktout, "subsystem");
9107 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9108 ssh2_pkt_addstring(s->pktout, cmd);
9110 ssh2_pkt_addstring(s->pktout, "exec");
9111 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9112 ssh2_pkt_addstring(s->pktout, cmd);
9114 ssh2_pkt_addstring(s->pktout, "shell");
9115 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9117 ssh2_pkt_send(ssh, s->pktout);
9119 crWaitUntilV(pktin);
9121 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9122 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9123 bombout(("Unexpected response to shell/command request:"
9124 " packet type %d", pktin->type));
9128 * We failed to start the command. If this is the
9129 * fallback command, we really are finished; if it's
9130 * not, and if the fallback command exists, try falling
9131 * back to it before complaining.
9133 if (!ssh->fallback_cmd &&
9134 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
9135 logevent("Primary command failed; attempting fallback");
9136 ssh->fallback_cmd = TRUE;
9139 bombout(("Server refused to start a shell/command"));
9142 logevent("Started a shell/command");
9147 ssh->state = SSH_STATE_SESSION;
9148 if (ssh->size_needed)
9149 ssh_size(ssh, ssh->term_width, ssh->term_height);
9150 if (ssh->eof_needed)
9151 ssh_special(ssh, TS_EOF);
9154 * All the initial channel requests are done, so install the default
9157 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_success;
9158 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_failure;
9164 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
9169 s->try_send = FALSE;
9173 * _All_ the connection-layer packets we expect to
9174 * receive are now handled by the dispatch table.
9175 * Anything that reaches here must be bogus.
9178 bombout(("Strange packet received: type %d", pktin->type));
9180 } else if (ssh->mainchan) {
9182 * We have spare data. Add it to the channel buffer.
9184 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
9189 struct ssh_channel *c;
9191 * Try to send data on all channels if we can.
9193 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
9194 ssh2_try_send_and_unthrottle(ssh, c);
9202 * Handlers for SSH-2 messages that might arrive at any moment.
9204 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
9206 /* log reason code in disconnect message */
9210 reason = ssh_pkt_getuint32(pktin);
9211 ssh_pkt_getstring(pktin, &msg, &msglen);
9213 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
9214 buf = dupprintf("Received disconnect message (%s)",
9215 ssh2_disconnect_reasons[reason]);
9217 buf = dupprintf("Received disconnect message (unknown"
9218 " type %d)", reason);
9222 buf = dupprintf("Disconnection message text: %.*s",
9225 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
9227 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
9228 ssh2_disconnect_reasons[reason] : "unknown",
9233 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
9235 /* log the debug message */
9239 /* XXX maybe we should actually take notice of the return value */
9240 ssh2_pkt_getbool(pktin);
9241 ssh_pkt_getstring(pktin, &msg, &msglen);
9243 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
9246 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
9248 struct Packet *pktout;
9249 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
9250 ssh2_pkt_adduint32(pktout, pktin->sequence);
9252 * UNIMPLEMENTED messages MUST appear in the same order as the
9253 * messages they respond to. Hence, never queue them.
9255 ssh2_pkt_send_noqueue(ssh, pktout);
9259 * Handle the top-level SSH-2 protocol.
9261 static void ssh2_protocol_setup(Ssh ssh)
9266 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9268 for (i = 0; i < 256; i++)
9269 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
9272 * Any message we actually understand, we set to NULL so that
9273 * the coroutines will get it.
9275 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
9276 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
9277 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
9278 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
9279 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
9280 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
9281 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
9282 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
9283 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
9284 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
9285 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
9286 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
9287 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
9288 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
9289 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
9290 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
9291 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
9292 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
9293 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
9294 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
9295 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
9296 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
9297 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
9298 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
9299 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
9300 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
9301 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
9302 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
9303 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
9304 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
9305 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
9306 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
9307 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
9310 * These special message types we install handlers for.
9312 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
9313 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
9314 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9317 static void ssh2_timer(void *ctx, long now)
9321 if (ssh->state == SSH_STATE_CLOSED)
9324 if (!ssh->kex_in_progress && conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
9325 now - ssh->next_rekey >= 0) {
9326 do_ssh2_transport(ssh, "timeout", -1, NULL);
9330 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
9331 struct Packet *pktin)
9333 unsigned char *in = (unsigned char *)vin;
9334 if (ssh->state == SSH_STATE_CLOSED)
9338 ssh->incoming_data_size += pktin->encrypted_len;
9339 if (!ssh->kex_in_progress &&
9340 ssh->max_data_size != 0 &&
9341 ssh->incoming_data_size > ssh->max_data_size)
9342 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9345 if (pktin && ssh->packet_dispatch[pktin->type]) {
9346 ssh->packet_dispatch[pktin->type](ssh, pktin);
9350 if (!ssh->protocol_initial_phase_done ||
9351 (pktin && pktin->type >= 20 && pktin->type < 50)) {
9352 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
9353 !ssh->protocol_initial_phase_done) {
9354 ssh->protocol_initial_phase_done = TRUE;
9356 * Allow authconn to initialise itself.
9358 do_ssh2_authconn(ssh, NULL, 0, NULL);
9361 do_ssh2_authconn(ssh, in, inlen, pktin);
9365 static void ssh_cache_conf_values(Ssh ssh)
9367 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
9371 * Called to set up the connection.
9373 * Returns an error message, or NULL on success.
9375 static const char *ssh_init(void *frontend_handle, void **backend_handle,
9376 Conf *conf, char *host, int port, char **realhost,
9377 int nodelay, int keepalive)
9382 ssh = snew(struct ssh_tag);
9383 ssh->conf = conf_copy(conf);
9384 ssh_cache_conf_values(ssh);
9385 ssh->version = 0; /* when not ready yet */
9388 ssh->v1_cipher_ctx = NULL;
9389 ssh->crcda_ctx = NULL;
9390 ssh->cscipher = NULL;
9391 ssh->cs_cipher_ctx = NULL;
9392 ssh->sccipher = NULL;
9393 ssh->sc_cipher_ctx = NULL;
9395 ssh->cs_mac_ctx = NULL;
9397 ssh->sc_mac_ctx = NULL;
9399 ssh->cs_comp_ctx = NULL;
9401 ssh->sc_comp_ctx = NULL;
9403 ssh->kex_ctx = NULL;
9404 ssh->hostkey = NULL;
9406 ssh->close_expected = FALSE;
9407 ssh->clean_exit = FALSE;
9408 ssh->state = SSH_STATE_PREPACKET;
9409 ssh->size_needed = FALSE;
9410 ssh->eof_needed = FALSE;
9413 ssh->deferred_send_data = NULL;
9414 ssh->deferred_len = 0;
9415 ssh->deferred_size = 0;
9416 ssh->fallback_cmd = 0;
9417 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9418 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9419 ssh->x11disp = NULL;
9420 ssh->v1_compressing = FALSE;
9421 ssh->v2_outgoing_sequence = 0;
9422 ssh->ssh1_rdpkt_crstate = 0;
9423 ssh->ssh2_rdpkt_crstate = 0;
9424 ssh->do_ssh_init_crstate = 0;
9425 ssh->ssh_gotdata_crstate = 0;
9426 ssh->do_ssh1_connection_crstate = 0;
9427 ssh->do_ssh1_login_crstate = 0;
9428 ssh->do_ssh2_transport_crstate = 0;
9429 ssh->do_ssh2_authconn_crstate = 0;
9430 ssh->do_ssh_init_state = NULL;
9431 ssh->do_ssh1_login_state = NULL;
9432 ssh->do_ssh2_transport_state = NULL;
9433 ssh->do_ssh2_authconn_state = NULL;
9436 ssh->mainchan = NULL;
9437 ssh->throttled_all = 0;
9438 ssh->v1_stdout_throttling = 0;
9440 ssh->queuelen = ssh->queuesize = 0;
9441 ssh->queueing = FALSE;
9442 ssh->qhead = ssh->qtail = NULL;
9443 ssh->deferred_rekey_reason = NULL;
9444 bufchain_init(&ssh->queued_incoming_data);
9445 ssh->frozen = FALSE;
9446 ssh->username = NULL;
9447 ssh->sent_console_eof = FALSE;
9449 *backend_handle = ssh;
9452 if (crypto_startup() == 0)
9453 return "Microsoft high encryption pack not installed!";
9456 ssh->frontend = frontend_handle;
9457 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
9458 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
9460 ssh->channels = NULL;
9461 ssh->rportfwds = NULL;
9462 ssh->portfwds = NULL;
9467 ssh->conn_throttle_count = 0;
9468 ssh->overall_bufsize = 0;
9469 ssh->fallback_cmd = 0;
9471 ssh->protocol = NULL;
9473 ssh->protocol_initial_phase_done = FALSE;
9477 ssh->incoming_data_size = ssh->outgoing_data_size =
9478 ssh->deferred_data_size = 0L;
9479 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9480 CONF_ssh_rekey_data));
9481 ssh->kex_in_progress = FALSE;
9484 ssh->gsslibs = NULL;
9487 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9496 static void ssh_free(void *handle)
9498 Ssh ssh = (Ssh) handle;
9499 struct ssh_channel *c;
9500 struct ssh_rportfwd *pf;
9502 if (ssh->v1_cipher_ctx)
9503 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9504 if (ssh->cs_cipher_ctx)
9505 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9506 if (ssh->sc_cipher_ctx)
9507 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9508 if (ssh->cs_mac_ctx)
9509 ssh->csmac->free_context(ssh->cs_mac_ctx);
9510 if (ssh->sc_mac_ctx)
9511 ssh->scmac->free_context(ssh->sc_mac_ctx);
9512 if (ssh->cs_comp_ctx) {
9514 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9516 zlib_compress_cleanup(ssh->cs_comp_ctx);
9518 if (ssh->sc_comp_ctx) {
9520 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9522 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9525 dh_cleanup(ssh->kex_ctx);
9526 sfree(ssh->savedhost);
9528 while (ssh->queuelen-- > 0)
9529 ssh_free_packet(ssh->queue[ssh->queuelen]);
9532 while (ssh->qhead) {
9533 struct queued_handler *qh = ssh->qhead;
9534 ssh->qhead = qh->next;
9537 ssh->qhead = ssh->qtail = NULL;
9539 if (ssh->channels) {
9540 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9543 if (c->u.x11.s != NULL)
9544 x11_close(c->u.x11.s);
9547 case CHAN_SOCKDATA_DORMANT:
9548 if (c->u.pfd.s != NULL)
9549 pfd_close(c->u.pfd.s);
9554 freetree234(ssh->channels);
9555 ssh->channels = NULL;
9558 if (ssh->rportfwds) {
9559 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9561 freetree234(ssh->rportfwds);
9562 ssh->rportfwds = NULL;
9564 sfree(ssh->deferred_send_data);
9566 x11_free_display(ssh->x11disp);
9567 sfree(ssh->do_ssh_init_state);
9568 sfree(ssh->do_ssh1_login_state);
9569 sfree(ssh->do_ssh2_transport_state);
9570 sfree(ssh->do_ssh2_authconn_state);
9573 sfree(ssh->fullhostname);
9574 if (ssh->crcda_ctx) {
9575 crcda_free_context(ssh->crcda_ctx);
9576 ssh->crcda_ctx = NULL;
9579 ssh_do_close(ssh, TRUE);
9580 expire_timer_context(ssh);
9582 pinger_free(ssh->pinger);
9583 bufchain_clear(&ssh->queued_incoming_data);
9584 sfree(ssh->username);
9585 conf_free(ssh->conf);
9588 ssh_gss_cleanup(ssh->gsslibs);
9596 * Reconfigure the SSH backend.
9598 static void ssh_reconfig(void *handle, Conf *conf)
9600 Ssh ssh = (Ssh) handle;
9601 char *rekeying = NULL, rekey_mandatory = FALSE;
9602 unsigned long old_max_data_size;
9605 pinger_reconfig(ssh->pinger, ssh->conf, conf);
9607 ssh_setup_portfwd(ssh, conf);
9609 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
9610 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
9612 long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
9613 long now = GETTICKCOUNT();
9615 if (new_next - now < 0) {
9616 rekeying = "timeout shortened";
9618 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
9622 old_max_data_size = ssh->max_data_size;
9623 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9624 CONF_ssh_rekey_data));
9625 if (old_max_data_size != ssh->max_data_size &&
9626 ssh->max_data_size != 0) {
9627 if (ssh->outgoing_data_size > ssh->max_data_size ||
9628 ssh->incoming_data_size > ssh->max_data_size)
9629 rekeying = "data limit lowered";
9632 if (conf_get_int(ssh->conf, CONF_compression) !=
9633 conf_get_int(conf, CONF_compression)) {
9634 rekeying = "compression setting changed";
9635 rekey_mandatory = TRUE;
9638 for (i = 0; i < CIPHER_MAX; i++)
9639 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
9640 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
9641 rekeying = "cipher settings changed";
9642 rekey_mandatory = TRUE;
9644 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
9645 conf_get_int(conf, CONF_ssh2_des_cbc)) {
9646 rekeying = "cipher settings changed";
9647 rekey_mandatory = TRUE;
9650 conf_free(ssh->conf);
9651 ssh->conf = conf_copy(conf);
9652 ssh_cache_conf_values(ssh);
9655 if (!ssh->kex_in_progress) {
9656 do_ssh2_transport(ssh, rekeying, -1, NULL);
9657 } else if (rekey_mandatory) {
9658 ssh->deferred_rekey_reason = rekeying;
9664 * Called to send data down the SSH connection.
9666 static int ssh_send(void *handle, char *buf, int len)
9668 Ssh ssh = (Ssh) handle;
9670 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9673 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
9675 return ssh_sendbuffer(ssh);
9679 * Called to query the current amount of buffered stdin data.
9681 static int ssh_sendbuffer(void *handle)
9683 Ssh ssh = (Ssh) handle;
9686 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9690 * If the SSH socket itself has backed up, add the total backup
9691 * size on that to any individual buffer on the stdin channel.
9694 if (ssh->throttled_all)
9695 override_value = ssh->overall_bufsize;
9697 if (ssh->version == 1) {
9698 return override_value;
9699 } else if (ssh->version == 2) {
9701 return override_value;
9703 return (override_value +
9704 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
9711 * Called to set the size of the window from SSH's POV.
9713 static void ssh_size(void *handle, int width, int height)
9715 Ssh ssh = (Ssh) handle;
9716 struct Packet *pktout;
9718 ssh->term_width = width;
9719 ssh->term_height = height;
9721 switch (ssh->state) {
9722 case SSH_STATE_BEFORE_SIZE:
9723 case SSH_STATE_PREPACKET:
9724 case SSH_STATE_CLOSED:
9725 break; /* do nothing */
9726 case SSH_STATE_INTERMED:
9727 ssh->size_needed = TRUE; /* buffer for later */
9729 case SSH_STATE_SESSION:
9730 if (!conf_get_int(ssh->conf, CONF_nopty)) {
9731 if (ssh->version == 1) {
9732 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
9733 PKT_INT, ssh->term_height,
9734 PKT_INT, ssh->term_width,
9735 PKT_INT, 0, PKT_INT, 0, PKT_END);
9736 } else if (ssh->mainchan) {
9737 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9738 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9739 ssh2_pkt_addstring(pktout, "window-change");
9740 ssh2_pkt_addbool(pktout, 0);
9741 ssh2_pkt_adduint32(pktout, ssh->term_width);
9742 ssh2_pkt_adduint32(pktout, ssh->term_height);
9743 ssh2_pkt_adduint32(pktout, 0);
9744 ssh2_pkt_adduint32(pktout, 0);
9745 ssh2_pkt_send(ssh, pktout);
9753 * Return a list of the special codes that make sense in this
9756 static const struct telnet_special *ssh_get_specials(void *handle)
9758 static const struct telnet_special ssh1_ignore_special[] = {
9759 {"IGNORE message", TS_NOP}
9761 static const struct telnet_special ssh2_ignore_special[] = {
9762 {"IGNORE message", TS_NOP},
9764 static const struct telnet_special ssh2_rekey_special[] = {
9765 {"Repeat key exchange", TS_REKEY},
9767 static const struct telnet_special ssh2_session_specials[] = {
9770 /* These are the signal names defined by RFC 4254.
9771 * They include all the ISO C signals, but are a subset of the POSIX
9772 * required signals. */
9773 {"SIGINT (Interrupt)", TS_SIGINT},
9774 {"SIGTERM (Terminate)", TS_SIGTERM},
9775 {"SIGKILL (Kill)", TS_SIGKILL},
9776 {"SIGQUIT (Quit)", TS_SIGQUIT},
9777 {"SIGHUP (Hangup)", TS_SIGHUP},
9778 {"More signals", TS_SUBMENU},
9779 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
9780 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
9781 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
9782 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
9785 static const struct telnet_special specials_end[] = {
9788 /* XXX review this length for any changes: */
9789 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
9790 lenof(ssh2_rekey_special) +
9791 lenof(ssh2_session_specials) +
9792 lenof(specials_end)];
9793 Ssh ssh = (Ssh) handle;
9795 #define ADD_SPECIALS(name) \
9797 assert((i + lenof(name)) <= lenof(ssh_specials)); \
9798 memcpy(&ssh_specials[i], name, sizeof name); \
9802 if (ssh->version == 1) {
9803 /* Don't bother offering IGNORE if we've decided the remote
9804 * won't cope with it, since we wouldn't bother sending it if
9806 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9807 ADD_SPECIALS(ssh1_ignore_special);
9808 } else if (ssh->version == 2) {
9809 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
9810 ADD_SPECIALS(ssh2_ignore_special);
9811 if (!(ssh->remote_bugs & BUG_SSH2_REKEY))
9812 ADD_SPECIALS(ssh2_rekey_special);
9814 ADD_SPECIALS(ssh2_session_specials);
9815 } /* else we're not ready yet */
9818 ADD_SPECIALS(specials_end);
9819 return ssh_specials;
9827 * Send special codes. TS_EOF is useful for `plink', so you
9828 * can send an EOF and collect resulting output (e.g. `plink
9831 static void ssh_special(void *handle, Telnet_Special code)
9833 Ssh ssh = (Ssh) handle;
9834 struct Packet *pktout;
9836 if (code == TS_EOF) {
9837 if (ssh->state != SSH_STATE_SESSION) {
9839 * Buffer the EOF in case we are pre-SESSION, so we can
9840 * send it as soon as we reach SESSION.
9843 ssh->eof_needed = TRUE;
9846 if (ssh->version == 1) {
9847 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
9848 } else if (ssh->mainchan) {
9849 sshfwd_write_eof(ssh->mainchan);
9850 ssh->send_ok = 0; /* now stop trying to read from stdin */
9852 logevent("Sent EOF message");
9853 } else if (code == TS_PING || code == TS_NOP) {
9854 if (ssh->state == SSH_STATE_CLOSED
9855 || ssh->state == SSH_STATE_PREPACKET) return;
9856 if (ssh->version == 1) {
9857 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9858 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
9860 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
9861 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
9862 ssh2_pkt_addstring_start(pktout);
9863 ssh2_pkt_send_noqueue(ssh, pktout);
9866 } else if (code == TS_REKEY) {
9867 if (!ssh->kex_in_progress && ssh->version == 2) {
9868 do_ssh2_transport(ssh, "at user request", -1, NULL);
9870 } else if (code == TS_BRK) {
9871 if (ssh->state == SSH_STATE_CLOSED
9872 || ssh->state == SSH_STATE_PREPACKET) return;
9873 if (ssh->version == 1) {
9874 logevent("Unable to send BREAK signal in SSH-1");
9875 } else if (ssh->mainchan) {
9876 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9877 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9878 ssh2_pkt_addstring(pktout, "break");
9879 ssh2_pkt_addbool(pktout, 0);
9880 ssh2_pkt_adduint32(pktout, 0); /* default break length */
9881 ssh2_pkt_send(ssh, pktout);
9884 /* Is is a POSIX signal? */
9885 char *signame = NULL;
9886 if (code == TS_SIGABRT) signame = "ABRT";
9887 if (code == TS_SIGALRM) signame = "ALRM";
9888 if (code == TS_SIGFPE) signame = "FPE";
9889 if (code == TS_SIGHUP) signame = "HUP";
9890 if (code == TS_SIGILL) signame = "ILL";
9891 if (code == TS_SIGINT) signame = "INT";
9892 if (code == TS_SIGKILL) signame = "KILL";
9893 if (code == TS_SIGPIPE) signame = "PIPE";
9894 if (code == TS_SIGQUIT) signame = "QUIT";
9895 if (code == TS_SIGSEGV) signame = "SEGV";
9896 if (code == TS_SIGTERM) signame = "TERM";
9897 if (code == TS_SIGUSR1) signame = "USR1";
9898 if (code == TS_SIGUSR2) signame = "USR2";
9899 /* The SSH-2 protocol does in principle support arbitrary named
9900 * signals, including signame@domain, but we don't support those. */
9902 /* It's a signal. */
9903 if (ssh->version == 2 && ssh->mainchan) {
9904 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9905 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9906 ssh2_pkt_addstring(pktout, "signal");
9907 ssh2_pkt_addbool(pktout, 0);
9908 ssh2_pkt_addstring(pktout, signame);
9909 ssh2_pkt_send(ssh, pktout);
9910 logeventf(ssh, "Sent signal SIG%s", signame);
9913 /* Never heard of it. Do nothing */
9918 void *new_sock_channel(void *handle, Socket s)
9920 Ssh ssh = (Ssh) handle;
9921 struct ssh_channel *c;
9922 c = snew(struct ssh_channel);
9925 ssh2_channel_init(c);
9927 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
9929 add234(ssh->channels, c);
9934 * This is called when stdout/stderr (the entity to which
9935 * from_backend sends data) manages to clear some backlog.
9937 static void ssh_unthrottle(void *handle, int bufsize)
9939 Ssh ssh = (Ssh) handle;
9942 if (ssh->version == 1) {
9943 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
9944 ssh->v1_stdout_throttling = 0;
9945 ssh_throttle_conn(ssh, -1);
9948 if (ssh->mainchan) {
9949 ssh2_set_window(ssh->mainchan,
9950 bufsize < ssh->mainchan->v.v2.locmaxwin ?
9951 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
9952 if (conf_get_int(ssh->conf, CONF_ssh_simple))
9955 buflimit = ssh->mainchan->v.v2.locmaxwin;
9956 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
9957 ssh->mainchan->throttling_conn = 0;
9958 ssh_throttle_conn(ssh, -1);
9964 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
9966 struct ssh_channel *c = (struct ssh_channel *)channel;
9968 struct Packet *pktout;
9970 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
9972 if (ssh->version == 1) {
9973 send_packet(ssh, SSH1_MSG_PORT_OPEN,
9974 PKT_INT, c->localid,
9977 /* PKT_STR, <org:orgport>, */
9980 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
9981 ssh2_pkt_addstring(pktout, "direct-tcpip");
9982 ssh2_pkt_adduint32(pktout, c->localid);
9983 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
9984 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
9985 ssh2_pkt_addstring(pktout, hostname);
9986 ssh2_pkt_adduint32(pktout, port);
9988 * We make up values for the originator data; partly it's
9989 * too much hassle to keep track, and partly I'm not
9990 * convinced the server should be told details like that
9991 * about my local network configuration.
9992 * The "originator IP address" is syntactically a numeric
9993 * IP address, and some servers (e.g., Tectia) get upset
9994 * if it doesn't match this syntax.
9996 ssh2_pkt_addstring(pktout, "0.0.0.0");
9997 ssh2_pkt_adduint32(pktout, 0);
9998 ssh2_pkt_send(ssh, pktout);
10002 static int ssh_connected(void *handle)
10004 Ssh ssh = (Ssh) handle;
10005 return ssh->s != NULL;
10008 static int ssh_sendok(void *handle)
10010 Ssh ssh = (Ssh) handle;
10011 return ssh->send_ok;
10014 static int ssh_ldisc(void *handle, int option)
10016 Ssh ssh = (Ssh) handle;
10017 if (option == LD_ECHO)
10018 return ssh->echoing;
10019 if (option == LD_EDIT)
10020 return ssh->editing;
10024 static void ssh_provide_ldisc(void *handle, void *ldisc)
10026 Ssh ssh = (Ssh) handle;
10027 ssh->ldisc = ldisc;
10030 static void ssh_provide_logctx(void *handle, void *logctx)
10032 Ssh ssh = (Ssh) handle;
10033 ssh->logctx = logctx;
10036 static int ssh_return_exitcode(void *handle)
10038 Ssh ssh = (Ssh) handle;
10039 if (ssh->s != NULL)
10042 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
10046 * cfg_info for SSH is the currently running version of the
10047 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
10049 static int ssh_cfg_info(void *handle)
10051 Ssh ssh = (Ssh) handle;
10052 return ssh->version;
10056 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
10057 * that fails. This variable is the means by which scp.c can reach
10058 * into the SSH code and find out which one it got.
10060 extern int ssh_fallback_cmd(void *handle)
10062 Ssh ssh = (Ssh) handle;
10063 return ssh->fallback_cmd;
10066 Backend ssh_backend = {
10076 ssh_return_exitcode,
10080 ssh_provide_logctx,