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
199 #define BUG_CHOKES_ON_WINADJ 1024
202 * Codes for terminal modes.
203 * Most of these are the same in SSH-1 and SSH-2.
204 * This list is derived from RFC 4254 and
207 static const struct {
208 const char* const mode;
210 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
212 /* "V" prefix discarded for special characters relative to SSH specs */
213 { "INTR", 1, TTY_OP_CHAR },
214 { "QUIT", 2, TTY_OP_CHAR },
215 { "ERASE", 3, TTY_OP_CHAR },
216 { "KILL", 4, TTY_OP_CHAR },
217 { "EOF", 5, TTY_OP_CHAR },
218 { "EOL", 6, TTY_OP_CHAR },
219 { "EOL2", 7, TTY_OP_CHAR },
220 { "START", 8, TTY_OP_CHAR },
221 { "STOP", 9, TTY_OP_CHAR },
222 { "SUSP", 10, TTY_OP_CHAR },
223 { "DSUSP", 11, TTY_OP_CHAR },
224 { "REPRINT", 12, TTY_OP_CHAR },
225 { "WERASE", 13, TTY_OP_CHAR },
226 { "LNEXT", 14, TTY_OP_CHAR },
227 { "FLUSH", 15, TTY_OP_CHAR },
228 { "SWTCH", 16, TTY_OP_CHAR },
229 { "STATUS", 17, TTY_OP_CHAR },
230 { "DISCARD", 18, TTY_OP_CHAR },
231 { "IGNPAR", 30, TTY_OP_BOOL },
232 { "PARMRK", 31, TTY_OP_BOOL },
233 { "INPCK", 32, TTY_OP_BOOL },
234 { "ISTRIP", 33, TTY_OP_BOOL },
235 { "INLCR", 34, TTY_OP_BOOL },
236 { "IGNCR", 35, TTY_OP_BOOL },
237 { "ICRNL", 36, TTY_OP_BOOL },
238 { "IUCLC", 37, TTY_OP_BOOL },
239 { "IXON", 38, TTY_OP_BOOL },
240 { "IXANY", 39, TTY_OP_BOOL },
241 { "IXOFF", 40, TTY_OP_BOOL },
242 { "IMAXBEL", 41, TTY_OP_BOOL },
243 { "ISIG", 50, TTY_OP_BOOL },
244 { "ICANON", 51, TTY_OP_BOOL },
245 { "XCASE", 52, TTY_OP_BOOL },
246 { "ECHO", 53, TTY_OP_BOOL },
247 { "ECHOE", 54, TTY_OP_BOOL },
248 { "ECHOK", 55, TTY_OP_BOOL },
249 { "ECHONL", 56, TTY_OP_BOOL },
250 { "NOFLSH", 57, TTY_OP_BOOL },
251 { "TOSTOP", 58, TTY_OP_BOOL },
252 { "IEXTEN", 59, TTY_OP_BOOL },
253 { "ECHOCTL", 60, TTY_OP_BOOL },
254 { "ECHOKE", 61, TTY_OP_BOOL },
255 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
256 { "OPOST", 70, TTY_OP_BOOL },
257 { "OLCUC", 71, TTY_OP_BOOL },
258 { "ONLCR", 72, TTY_OP_BOOL },
259 { "OCRNL", 73, TTY_OP_BOOL },
260 { "ONOCR", 74, TTY_OP_BOOL },
261 { "ONLRET", 75, TTY_OP_BOOL },
262 { "CS7", 90, TTY_OP_BOOL },
263 { "CS8", 91, TTY_OP_BOOL },
264 { "PARENB", 92, TTY_OP_BOOL },
265 { "PARODD", 93, TTY_OP_BOOL }
268 /* Miscellaneous other tty-related constants. */
269 #define SSH_TTY_OP_END 0
270 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
271 #define SSH1_TTY_OP_ISPEED 192
272 #define SSH1_TTY_OP_OSPEED 193
273 #define SSH2_TTY_OP_ISPEED 128
274 #define SSH2_TTY_OP_OSPEED 129
276 /* Helper functions for parsing tty-related config. */
277 static unsigned int ssh_tty_parse_specchar(char *s)
282 ret = ctrlparse(s, &next);
283 if (!next) ret = s[0];
285 ret = 255; /* special value meaning "don't set" */
289 static unsigned int ssh_tty_parse_boolean(char *s)
291 if (stricmp(s, "yes") == 0 ||
292 stricmp(s, "on") == 0 ||
293 stricmp(s, "true") == 0 ||
294 stricmp(s, "+") == 0)
296 else if (stricmp(s, "no") == 0 ||
297 stricmp(s, "off") == 0 ||
298 stricmp(s, "false") == 0 ||
299 stricmp(s, "-") == 0)
300 return 0; /* false */
302 return (atoi(s) != 0);
305 #define translate(x) if (type == x) return #x
306 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
307 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
308 static char *ssh1_pkt_type(int type)
310 translate(SSH1_MSG_DISCONNECT);
311 translate(SSH1_SMSG_PUBLIC_KEY);
312 translate(SSH1_CMSG_SESSION_KEY);
313 translate(SSH1_CMSG_USER);
314 translate(SSH1_CMSG_AUTH_RSA);
315 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
316 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
317 translate(SSH1_CMSG_AUTH_PASSWORD);
318 translate(SSH1_CMSG_REQUEST_PTY);
319 translate(SSH1_CMSG_WINDOW_SIZE);
320 translate(SSH1_CMSG_EXEC_SHELL);
321 translate(SSH1_CMSG_EXEC_CMD);
322 translate(SSH1_SMSG_SUCCESS);
323 translate(SSH1_SMSG_FAILURE);
324 translate(SSH1_CMSG_STDIN_DATA);
325 translate(SSH1_SMSG_STDOUT_DATA);
326 translate(SSH1_SMSG_STDERR_DATA);
327 translate(SSH1_CMSG_EOF);
328 translate(SSH1_SMSG_EXIT_STATUS);
329 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
330 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
331 translate(SSH1_MSG_CHANNEL_DATA);
332 translate(SSH1_MSG_CHANNEL_CLOSE);
333 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
334 translate(SSH1_SMSG_X11_OPEN);
335 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
336 translate(SSH1_MSG_PORT_OPEN);
337 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
338 translate(SSH1_SMSG_AGENT_OPEN);
339 translate(SSH1_MSG_IGNORE);
340 translate(SSH1_CMSG_EXIT_CONFIRMATION);
341 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
342 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
343 translate(SSH1_MSG_DEBUG);
344 translate(SSH1_CMSG_REQUEST_COMPRESSION);
345 translate(SSH1_CMSG_AUTH_TIS);
346 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
347 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
348 translate(SSH1_CMSG_AUTH_CCARD);
349 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
350 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
353 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
355 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
356 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
357 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
358 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
359 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
360 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
361 translate(SSH2_MSG_DISCONNECT);
362 translate(SSH2_MSG_IGNORE);
363 translate(SSH2_MSG_UNIMPLEMENTED);
364 translate(SSH2_MSG_DEBUG);
365 translate(SSH2_MSG_SERVICE_REQUEST);
366 translate(SSH2_MSG_SERVICE_ACCEPT);
367 translate(SSH2_MSG_KEXINIT);
368 translate(SSH2_MSG_NEWKEYS);
369 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
370 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
371 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
372 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
373 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
374 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
375 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
376 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
377 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
378 translate(SSH2_MSG_USERAUTH_REQUEST);
379 translate(SSH2_MSG_USERAUTH_FAILURE);
380 translate(SSH2_MSG_USERAUTH_SUCCESS);
381 translate(SSH2_MSG_USERAUTH_BANNER);
382 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
383 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
384 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
385 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
386 translate(SSH2_MSG_GLOBAL_REQUEST);
387 translate(SSH2_MSG_REQUEST_SUCCESS);
388 translate(SSH2_MSG_REQUEST_FAILURE);
389 translate(SSH2_MSG_CHANNEL_OPEN);
390 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
391 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
392 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
393 translate(SSH2_MSG_CHANNEL_DATA);
394 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
395 translate(SSH2_MSG_CHANNEL_EOF);
396 translate(SSH2_MSG_CHANNEL_CLOSE);
397 translate(SSH2_MSG_CHANNEL_REQUEST);
398 translate(SSH2_MSG_CHANNEL_SUCCESS);
399 translate(SSH2_MSG_CHANNEL_FAILURE);
405 /* Enumeration values for fields in SSH-1 packets */
407 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
408 /* These values are for communicating relevant semantics of
409 * fields to the packet logging code. */
410 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
414 * Coroutine mechanics for the sillier bits of the code. If these
415 * macros look impenetrable to you, you might find it helpful to
418 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
420 * which explains the theory behind these macros.
422 * In particular, if you are getting `case expression not constant'
423 * errors when building with MS Visual Studio, this is because MS's
424 * Edit and Continue debugging feature causes their compiler to
425 * violate ANSI C. To disable Edit and Continue debugging:
427 * - right-click ssh.c in the FileView
429 * - select the C/C++ tab and the General category
430 * - under `Debug info:', select anything _other_ than `Program
431 * Database for Edit and Continue'.
433 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
434 #define crBeginState crBegin(s->crLine)
435 #define crStateP(t, v) \
437 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
439 #define crState(t) crStateP(t, ssh->t)
440 #define crFinish(z) } *crLine = 0; return (z); }
441 #define crFinishV } *crLine = 0; return; }
442 #define crFinishFree(z) } sfree(s); return (z); }
443 #define crFinishFreeV } sfree(s); return; }
444 #define crReturn(z) \
446 *crLine =__LINE__; return (z); case __LINE__:;\
450 *crLine=__LINE__; return; case __LINE__:;\
452 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
453 #define crStopV do{ *crLine = 0; return; }while(0)
454 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
455 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
457 typedef struct ssh_tag *Ssh;
460 static struct Packet *ssh1_pkt_init(int pkt_type);
461 static struct Packet *ssh2_pkt_init(int pkt_type);
462 static void ssh_pkt_ensure(struct Packet *, int length);
463 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
464 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
465 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
466 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
467 static void ssh_pkt_addstring_start(struct Packet *);
468 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
469 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
470 static void ssh_pkt_addstring(struct Packet *, const char *data);
471 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
472 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
473 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
474 static int ssh2_pkt_construct(Ssh, struct Packet *);
475 static void ssh2_pkt_send(Ssh, struct Packet *);
476 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
477 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
478 struct Packet *pktin);
479 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
480 struct Packet *pktin);
481 static void ssh2_channel_check_close(struct ssh_channel *c);
482 static void ssh_channel_destroy(struct ssh_channel *c);
485 * Buffer management constants. There are several of these for
486 * various different purposes:
488 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
489 * on a local data stream before we throttle the whole SSH
490 * connection (in SSH-1 only). Throttling the whole connection is
491 * pretty drastic so we set this high in the hope it won't
494 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
495 * on the SSH connection itself before we defensively throttle
496 * _all_ local data streams. This is pretty drastic too (though
497 * thankfully unlikely in SSH-2 since the window mechanism should
498 * ensure that the server never has any need to throttle its end
499 * of the connection), so we set this high as well.
501 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
504 * - OUR_V2_BIGWIN is the window size we advertise for the only
505 * channel in a simple connection. It must be <= INT_MAX.
507 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
508 * to the remote side. This actually has nothing to do with the
509 * size of the _packet_, but is instead a limit on the amount
510 * of data we're willing to receive in a single SSH2 channel
513 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
514 * _packet_ we're prepared to cope with. It must be a multiple
515 * of the cipher block size, and must be at least 35000.
518 #define SSH1_BUFFER_LIMIT 32768
519 #define SSH_MAX_BACKLOG 32768
520 #define OUR_V2_WINSIZE 16384
521 #define OUR_V2_BIGWIN 0x7fffffff
522 #define OUR_V2_MAXPKT 0x4000UL
523 #define OUR_V2_PACKETLIMIT 0x9000UL
525 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
527 const static struct ssh_mac *macs[] = {
528 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
530 const static struct ssh_mac *buggymacs[] = {
531 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
534 static void *ssh_comp_none_init(void)
538 static void ssh_comp_none_cleanup(void *handle)
541 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
542 unsigned char **outblock, int *outlen)
546 static int ssh_comp_none_disable(void *handle)
550 const static struct ssh_compress ssh_comp_none = {
552 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
553 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
554 ssh_comp_none_disable, NULL
556 extern const struct ssh_compress ssh_zlib;
557 const static struct ssh_compress *compressions[] = {
558 &ssh_zlib, &ssh_comp_none
561 enum { /* channel types */
566 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
568 * CHAN_ZOMBIE is used to indicate a channel for which we've
569 * already destroyed the local data source: for instance, if a
570 * forwarded port experiences a socket error on the local side, we
571 * immediately destroy its local socket and turn the SSH channel
577 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
578 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
579 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
582 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
585 struct outstanding_channel_request {
586 cchandler_fn_t handler;
588 struct outstanding_channel_request *next;
592 * 2-3-4 tree storing channels.
595 Ssh ssh; /* pointer back to main context */
596 unsigned remoteid, localid;
598 /* True if we opened this channel but server hasn't confirmed. */
601 * In SSH-1, this value contains four bits:
603 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
604 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
605 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
606 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
608 * A channel is completely finished with when all four bits are set.
610 * In SSH-2, the four bits mean:
612 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
613 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
614 * 4 We have received SSH2_MSG_CHANNEL_EOF.
615 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
617 * A channel is completely finished with when we have both sent
618 * and received CLOSE.
620 * The symbolic constants below use the SSH-2 terminology, which
621 * is a bit confusing in SSH-1, but we have to use _something_.
623 #define CLOSES_SENT_EOF 1
624 #define CLOSES_SENT_CLOSE 2
625 #define CLOSES_RCVD_EOF 4
626 #define CLOSES_RCVD_CLOSE 8
630 * This flag indicates that an EOF is pending on the outgoing side
631 * of the channel: that is, wherever we're getting the data for
632 * this channel has sent us some data followed by EOF. We can't
633 * actually send the EOF until we've finished sending the data, so
634 * we set this flag instead to remind us to do so once our buffer
640 * True if this channel is causing the underlying connection to be
645 struct ssh2_data_channel {
647 unsigned remwindow, remmaxpkt;
648 /* locwindow is signed so we can cope with excess data. */
649 int locwindow, locmaxwin;
651 * remlocwin is the amount of local window that we think
652 * the remote end had available to it after it sent the
653 * last data packet or window adjust ack.
657 * These store the list of channel requests that haven't
660 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
661 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
665 struct ssh_agent_channel {
666 unsigned char *message;
667 unsigned char msglen[4];
668 unsigned lensofar, totallen;
669 int outstanding_requests;
671 struct ssh_x11_channel {
674 struct ssh_pfd_channel {
681 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
682 * use this structure in different ways, reflecting SSH-2's
683 * altogether saner approach to port forwarding.
685 * In SSH-1, you arrange a remote forwarding by sending the server
686 * the remote port number, and the local destination host:port.
687 * When a connection comes in, the server sends you back that
688 * host:port pair, and you connect to it. This is a ready-made
689 * security hole if you're not on the ball: a malicious server
690 * could send you back _any_ host:port pair, so if you trustingly
691 * connect to the address it gives you then you've just opened the
692 * entire inside of your corporate network just by connecting
693 * through it to a dodgy SSH server. Hence, we must store a list of
694 * host:port pairs we _are_ trying to forward to, and reject a
695 * connection request from the server if it's not in the list.
697 * In SSH-2, each side of the connection minds its own business and
698 * doesn't send unnecessary information to the other. You arrange a
699 * remote forwarding by sending the server just the remote port
700 * number. When a connection comes in, the server tells you which
701 * of its ports was connected to; and _you_ have to remember what
702 * local host:port pair went with that port number.
704 * Hence, in SSH-1 this structure is indexed by destination
705 * host:port pair, whereas in SSH-2 it is indexed by source port.
707 struct ssh_portfwd; /* forward declaration */
709 struct ssh_rportfwd {
710 unsigned sport, dport;
713 struct ssh_portfwd *pfrec;
715 #define free_rportfwd(pf) ( \
716 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
719 * Separately to the rportfwd tree (which is for looking up port
720 * open requests from the server), a tree of _these_ structures is
721 * used to keep track of all the currently open port forwardings,
722 * so that we can reconfigure in mid-session if the user requests
726 enum { DESTROY, KEEP, CREATE } status;
728 unsigned sport, dport;
731 struct ssh_rportfwd *remote;
735 #define free_portfwd(pf) ( \
736 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
737 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
740 long length; /* length of `data' actually used */
741 long forcepad; /* SSH-2: force padding to at least this length */
742 int type; /* only used for incoming packets */
743 unsigned long sequence; /* SSH-2 incoming sequence number */
744 unsigned char *data; /* allocated storage */
745 unsigned char *body; /* offset of payload within `data' */
746 long savedpos; /* temporary index into `data' (for strings) */
747 long maxlen; /* amount of storage allocated for `data' */
748 long encrypted_len; /* for SSH-2 total-size counting */
751 * State associated with packet logging
755 struct logblank_t *blanks;
758 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
759 struct Packet *pktin);
760 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
761 struct Packet *pktin);
762 static void ssh1_protocol_setup(Ssh ssh);
763 static void ssh2_protocol_setup(Ssh ssh);
764 static void ssh_size(void *handle, int width, int height);
765 static void ssh_special(void *handle, Telnet_Special);
766 static int ssh2_try_send(struct ssh_channel *c);
767 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
768 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
769 static void ssh2_set_window(struct ssh_channel *c, int newwin);
770 static int ssh_sendbuffer(void *handle);
771 static int ssh_do_close(Ssh ssh, int notify_exit);
772 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
773 static int ssh2_pkt_getbool(struct Packet *pkt);
774 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
775 static void ssh2_timer(void *ctx, unsigned long now);
776 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
777 struct Packet *pktin);
778 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
780 struct rdpkt1_state_tag {
781 long len, pad, biglen, to_read;
782 unsigned long realcrc, gotcrc;
786 struct Packet *pktin;
789 struct rdpkt2_state_tag {
790 long len, pad, payload, packetlen, maclen;
793 unsigned long incoming_sequence;
794 struct Packet *pktin;
797 struct queued_handler;
798 struct queued_handler {
800 chandler_fn_t handler;
802 struct queued_handler *next;
806 const struct plug_function_table *fn;
807 /* the above field _must_ be first in the structure */
817 unsigned char session_key[32];
819 int v1_remote_protoflags;
820 int v1_local_protoflags;
821 int agentfwd_enabled;
824 const struct ssh_cipher *cipher;
827 const struct ssh2_cipher *cscipher, *sccipher;
828 void *cs_cipher_ctx, *sc_cipher_ctx;
829 const struct ssh_mac *csmac, *scmac;
830 void *cs_mac_ctx, *sc_mac_ctx;
831 const struct ssh_compress *cscomp, *sccomp;
832 void *cs_comp_ctx, *sc_comp_ctx;
833 const struct ssh_kex *kex;
834 const struct ssh_signkey *hostkey;
835 char *hostkey_str; /* string representation, for easy checking in rekeys */
836 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
837 int v2_session_id_len;
843 int echoing, editing;
847 int ospeed, ispeed; /* temporaries */
848 int term_width, term_height;
850 tree234 *channels; /* indexed by local id */
851 struct ssh_channel *mainchan; /* primary session channel */
852 int ncmode; /* is primary channel direct-tcpip? */
857 tree234 *rportfwds, *portfwds;
861 SSH_STATE_BEFORE_SIZE,
867 int size_needed, eof_needed;
868 int sent_console_eof;
869 int got_pty; /* affects EOF behaviour on main channel */
871 struct Packet **queue;
872 int queuelen, queuesize;
874 unsigned char *deferred_send_data;
875 int deferred_len, deferred_size;
878 * Gross hack: pscp will try to start SFTP but fall back to
879 * scp1 if that fails. This variable is the means by which
880 * scp.c can reach into the SSH code and find out which one it
885 bufchain banner; /* accumulates banners during do_ssh2_authconn */
890 struct X11Display *x11disp;
893 int conn_throttle_count;
896 int v1_stdout_throttling;
897 unsigned long v2_outgoing_sequence;
899 int ssh1_rdpkt_crstate;
900 int ssh2_rdpkt_crstate;
901 int ssh_gotdata_crstate;
902 int do_ssh1_connection_crstate;
904 void *do_ssh_init_state;
905 void *do_ssh1_login_state;
906 void *do_ssh2_transport_state;
907 void *do_ssh2_authconn_state;
909 struct rdpkt1_state_tag rdpkt1_state;
910 struct rdpkt2_state_tag rdpkt2_state;
912 /* SSH-1 and SSH-2 use this for different things, but both use it */
913 int protocol_initial_phase_done;
915 void (*protocol) (Ssh ssh, void *vin, int inlen,
917 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
920 * We maintain our own copy of a Conf structure here. That way,
921 * when we're passed a new one for reconfiguration, we can check
922 * the differences and potentially reconfigure port forwardings
923 * etc in mid-session.
928 * Values cached out of conf so as to avoid the tree234 lookup
929 * cost every time they're used.
934 * Dynamically allocated username string created during SSH
935 * login. Stored in here rather than in the coroutine state so
936 * that it'll be reliably freed if we shut down the SSH session
937 * at some unexpected moment.
942 * Used to transfer data back from async callbacks.
944 void *agent_response;
945 int agent_response_len;
949 * The SSH connection can be set as `frozen', meaning we are
950 * not currently accepting incoming data from the network. This
951 * is slightly more serious than setting the _socket_ as
952 * frozen, because we may already have had data passed to us
953 * from the network which we need to delay processing until
954 * after the freeze is lifted, so we also need a bufchain to
958 bufchain queued_incoming_data;
961 * Dispatch table for packet types that we may have to deal
964 handler_fn_t packet_dispatch[256];
967 * Queues of one-off handler functions for success/failure
968 * indications from a request.
970 struct queued_handler *qhead, *qtail;
971 handler_fn_t q_saved_handler1, q_saved_handler2;
974 * This module deals with sending keepalives.
979 * Track incoming and outgoing data sizes and time, for
982 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
983 unsigned long max_data_size;
985 unsigned long next_rekey, last_rekey;
986 char *deferred_rekey_reason; /* points to STATIC string; don't free */
989 * Fully qualified host name, which we need if doing GSSAPI.
995 * GSSAPI libraries for this session.
997 struct ssh_gss_liblist *gsslibs;
1001 #define logevent(s) logevent(ssh->frontend, s)
1003 /* logevent, only printf-formatted. */
1004 static void logeventf(Ssh ssh, const char *fmt, ...)
1010 buf = dupvprintf(fmt, ap);
1016 static void bomb_out(Ssh ssh, char *text)
1018 ssh_do_close(ssh, FALSE);
1020 connection_fatal(ssh->frontend, "%s", text);
1024 #define bombout(msg) bomb_out(ssh, dupprintf msg)
1026 /* Functions to leave bits out of the SSH packet log file. */
1028 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
1030 if (conf_get_int(ssh->conf, CONF_logomitpass))
1031 pkt->logmode = blanktype;
1034 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
1036 if (ssh->logomitdata)
1037 pkt->logmode = blanktype;
1040 static void end_log_omission(Ssh ssh, struct Packet *pkt)
1042 pkt->logmode = PKTLOG_EMIT;
1045 /* Helper function for common bits of parsing ttymodes. */
1046 static void parse_ttymodes(Ssh ssh,
1047 void (*do_mode)(void *data, char *mode, char *val),
1052 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
1054 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
1056 * val[0] is either 'V', indicating that an explicit value
1057 * follows it, or 'A' indicating that we should pass the
1058 * value through from the local environment via get_ttymode.
1060 if (val[0] == 'A') {
1061 val = get_ttymode(ssh->frontend, key);
1063 do_mode(data, key, val);
1067 do_mode(data, key, val + 1); /* skip the 'V' */
1071 static int ssh_channelcmp(void *av, void *bv)
1073 struct ssh_channel *a = (struct ssh_channel *) av;
1074 struct ssh_channel *b = (struct ssh_channel *) bv;
1075 if (a->localid < b->localid)
1077 if (a->localid > b->localid)
1081 static int ssh_channelfind(void *av, void *bv)
1083 unsigned *a = (unsigned *) av;
1084 struct ssh_channel *b = (struct ssh_channel *) bv;
1085 if (*a < b->localid)
1087 if (*a > b->localid)
1092 static int ssh_rportcmp_ssh1(void *av, void *bv)
1094 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1095 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1097 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1098 return i < 0 ? -1 : +1;
1099 if (a->dport > b->dport)
1101 if (a->dport < b->dport)
1106 static int ssh_rportcmp_ssh2(void *av, void *bv)
1108 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1109 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1111 if (a->sport > b->sport)
1113 if (a->sport < b->sport)
1119 * Special form of strcmp which can cope with NULL inputs. NULL is
1120 * defined to sort before even the empty string.
1122 static int nullstrcmp(const char *a, const char *b)
1124 if (a == NULL && b == NULL)
1130 return strcmp(a, b);
1133 static int ssh_portcmp(void *av, void *bv)
1135 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1136 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1138 if (a->type > b->type)
1140 if (a->type < b->type)
1142 if (a->addressfamily > b->addressfamily)
1144 if (a->addressfamily < b->addressfamily)
1146 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1147 return i < 0 ? -1 : +1;
1148 if (a->sport > b->sport)
1150 if (a->sport < b->sport)
1152 if (a->type != 'D') {
1153 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1154 return i < 0 ? -1 : +1;
1155 if (a->dport > b->dport)
1157 if (a->dport < b->dport)
1163 static int alloc_channel_id(Ssh ssh)
1165 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1166 unsigned low, high, mid;
1168 struct ssh_channel *c;
1171 * First-fit allocation of channel numbers: always pick the
1172 * lowest unused one. To do this, binary-search using the
1173 * counted B-tree to find the largest channel ID which is in a
1174 * contiguous sequence from the beginning. (Precisely
1175 * everything in that sequence must have ID equal to its tree
1176 * index plus CHANNEL_NUMBER_OFFSET.)
1178 tsize = count234(ssh->channels);
1182 while (high - low > 1) {
1183 mid = (high + low) / 2;
1184 c = index234(ssh->channels, mid);
1185 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1186 low = mid; /* this one is fine */
1188 high = mid; /* this one is past it */
1191 * Now low points to either -1, or the tree index of the
1192 * largest ID in the initial sequence.
1195 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1196 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1198 return low + 1 + CHANNEL_NUMBER_OFFSET;
1201 static void c_write_stderr(int trusted, const char *buf, int len)
1204 for (i = 0; i < len; i++)
1205 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1206 fputc(buf[i], stderr);
1209 static void c_write(Ssh ssh, const char *buf, int len)
1211 if (flags & FLAG_STDERR)
1212 c_write_stderr(1, buf, len);
1214 from_backend(ssh->frontend, 1, buf, len);
1217 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1219 if (flags & FLAG_STDERR)
1220 c_write_stderr(0, buf, len);
1222 from_backend_untrusted(ssh->frontend, buf, len);
1225 static void c_write_str(Ssh ssh, const char *buf)
1227 c_write(ssh, buf, strlen(buf));
1230 static void ssh_free_packet(struct Packet *pkt)
1235 static struct Packet *ssh_new_packet(void)
1237 struct Packet *pkt = snew(struct Packet);
1239 pkt->body = pkt->data = NULL;
1241 pkt->logmode = PKTLOG_EMIT;
1249 * Collect incoming data in the incoming packet buffer.
1250 * Decipher and verify the packet when it is completely read.
1251 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1252 * Update the *data and *datalen variables.
1253 * Return a Packet structure when a packet is completed.
1255 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1257 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1259 crBegin(ssh->ssh1_rdpkt_crstate);
1261 st->pktin = ssh_new_packet();
1263 st->pktin->type = 0;
1264 st->pktin->length = 0;
1266 for (st->i = st->len = 0; st->i < 4; st->i++) {
1267 while ((*datalen) == 0)
1269 st->len = (st->len << 8) + **data;
1270 (*data)++, (*datalen)--;
1273 st->pad = 8 - (st->len % 8);
1274 st->biglen = st->len + st->pad;
1275 st->pktin->length = st->len - 5;
1277 if (st->biglen < 0) {
1278 bombout(("Extremely large packet length from server suggests"
1279 " data stream corruption"));
1280 ssh_free_packet(st->pktin);
1284 st->pktin->maxlen = st->biglen;
1285 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1287 st->to_read = st->biglen;
1288 st->p = st->pktin->data;
1289 while (st->to_read > 0) {
1290 st->chunk = st->to_read;
1291 while ((*datalen) == 0)
1293 if (st->chunk > (*datalen))
1294 st->chunk = (*datalen);
1295 memcpy(st->p, *data, st->chunk);
1297 *datalen -= st->chunk;
1299 st->to_read -= st->chunk;
1302 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1303 st->biglen, NULL)) {
1304 bombout(("Network attack (CRC compensation) detected!"));
1305 ssh_free_packet(st->pktin);
1310 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1312 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1313 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1314 if (st->gotcrc != st->realcrc) {
1315 bombout(("Incorrect CRC received on packet"));
1316 ssh_free_packet(st->pktin);
1320 st->pktin->body = st->pktin->data + st->pad + 1;
1321 st->pktin->savedpos = 0;
1323 if (ssh->v1_compressing) {
1324 unsigned char *decompblk;
1326 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1327 st->pktin->body - 1, st->pktin->length + 1,
1328 &decompblk, &decomplen)) {
1329 bombout(("Zlib decompression encountered invalid data"));
1330 ssh_free_packet(st->pktin);
1334 if (st->pktin->maxlen < st->pad + decomplen) {
1335 st->pktin->maxlen = st->pad + decomplen;
1336 st->pktin->data = sresize(st->pktin->data,
1337 st->pktin->maxlen + APIEXTRA,
1339 st->pktin->body = st->pktin->data + st->pad + 1;
1342 memcpy(st->pktin->body - 1, decompblk, decomplen);
1344 st->pktin->length = decomplen - 1;
1347 st->pktin->type = st->pktin->body[-1];
1350 * Log incoming packet, possibly omitting sensitive fields.
1354 struct logblank_t blank;
1355 if (ssh->logomitdata) {
1356 int do_blank = FALSE, blank_prefix = 0;
1357 /* "Session data" packets - omit the data field */
1358 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1359 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1360 do_blank = TRUE; blank_prefix = 4;
1361 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1362 do_blank = TRUE; blank_prefix = 8;
1365 blank.offset = blank_prefix;
1366 blank.len = st->pktin->length;
1367 blank.type = PKTLOG_OMIT;
1371 log_packet(ssh->logctx,
1372 PKT_INCOMING, st->pktin->type,
1373 ssh1_pkt_type(st->pktin->type),
1374 st->pktin->body, st->pktin->length,
1375 nblanks, &blank, NULL);
1378 crFinish(st->pktin);
1381 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1383 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1385 crBegin(ssh->ssh2_rdpkt_crstate);
1387 st->pktin = ssh_new_packet();
1389 st->pktin->type = 0;
1390 st->pktin->length = 0;
1392 st->cipherblk = ssh->sccipher->blksize;
1395 if (st->cipherblk < 8)
1397 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1399 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1402 * When dealing with a CBC-mode cipher, we want to avoid the
1403 * possibility of an attacker's tweaking the ciphertext stream
1404 * so as to cause us to feed the same block to the block
1405 * cipher more than once and thus leak information
1406 * (VU#958563). The way we do this is not to take any
1407 * decisions on the basis of anything we've decrypted until
1408 * we've verified it with a MAC. That includes the packet
1409 * length, so we just read data and check the MAC repeatedly,
1410 * and when the MAC passes, see if the length we've got is
1414 /* May as well allocate the whole lot now. */
1415 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1418 /* Read an amount corresponding to the MAC. */
1419 for (st->i = 0; st->i < st->maclen; st->i++) {
1420 while ((*datalen) == 0)
1422 st->pktin->data[st->i] = *(*data)++;
1428 unsigned char seq[4];
1429 ssh->scmac->start(ssh->sc_mac_ctx);
1430 PUT_32BIT(seq, st->incoming_sequence);
1431 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1434 for (;;) { /* Once around this loop per cipher block. */
1435 /* Read another cipher-block's worth, and tack it onto the end. */
1436 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1437 while ((*datalen) == 0)
1439 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1442 /* Decrypt one more block (a little further back in the stream). */
1443 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1444 st->pktin->data + st->packetlen,
1446 /* Feed that block to the MAC. */
1447 ssh->scmac->bytes(ssh->sc_mac_ctx,
1448 st->pktin->data + st->packetlen, st->cipherblk);
1449 st->packetlen += st->cipherblk;
1450 /* See if that gives us a valid packet. */
1451 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1452 st->pktin->data + st->packetlen) &&
1453 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1456 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1457 bombout(("No valid incoming packet found"));
1458 ssh_free_packet(st->pktin);
1462 st->pktin->maxlen = st->packetlen + st->maclen;
1463 st->pktin->data = sresize(st->pktin->data,
1464 st->pktin->maxlen + APIEXTRA,
1467 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1470 * Acquire and decrypt the first block of the packet. This will
1471 * contain the length and padding details.
1473 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1474 while ((*datalen) == 0)
1476 st->pktin->data[st->i] = *(*data)++;
1481 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1482 st->pktin->data, st->cipherblk);
1485 * Now get the length figure.
1487 st->len = toint(GET_32BIT(st->pktin->data));
1490 * _Completely_ silly lengths should be stomped on before they
1491 * do us any more damage.
1493 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1494 (st->len + 4) % st->cipherblk != 0) {
1495 bombout(("Incoming packet was garbled on decryption"));
1496 ssh_free_packet(st->pktin);
1501 * So now we can work out the total packet length.
1503 st->packetlen = st->len + 4;
1506 * Allocate memory for the rest of the packet.
1508 st->pktin->maxlen = st->packetlen + st->maclen;
1509 st->pktin->data = sresize(st->pktin->data,
1510 st->pktin->maxlen + APIEXTRA,
1514 * Read and decrypt the remainder of the packet.
1516 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1518 while ((*datalen) == 0)
1520 st->pktin->data[st->i] = *(*data)++;
1523 /* Decrypt everything _except_ the MAC. */
1525 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1526 st->pktin->data + st->cipherblk,
1527 st->packetlen - st->cipherblk);
1533 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1534 st->len + 4, st->incoming_sequence)) {
1535 bombout(("Incorrect MAC received on packet"));
1536 ssh_free_packet(st->pktin);
1540 /* Get and sanity-check the amount of random padding. */
1541 st->pad = st->pktin->data[4];
1542 if (st->pad < 4 || st->len - st->pad < 1) {
1543 bombout(("Invalid padding length on received packet"));
1544 ssh_free_packet(st->pktin);
1548 * This enables us to deduce the payload length.
1550 st->payload = st->len - st->pad - 1;
1552 st->pktin->length = st->payload + 5;
1553 st->pktin->encrypted_len = st->packetlen;
1555 st->pktin->sequence = st->incoming_sequence++;
1558 * Decompress packet payload.
1561 unsigned char *newpayload;
1564 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1565 st->pktin->data + 5, st->pktin->length - 5,
1566 &newpayload, &newlen)) {
1567 if (st->pktin->maxlen < newlen + 5) {
1568 st->pktin->maxlen = newlen + 5;
1569 st->pktin->data = sresize(st->pktin->data,
1570 st->pktin->maxlen + APIEXTRA,
1573 st->pktin->length = 5 + newlen;
1574 memcpy(st->pktin->data + 5, newpayload, newlen);
1579 st->pktin->savedpos = 6;
1580 st->pktin->body = st->pktin->data;
1581 st->pktin->type = st->pktin->data[5];
1584 * Log incoming packet, possibly omitting sensitive fields.
1588 struct logblank_t blank;
1589 if (ssh->logomitdata) {
1590 int do_blank = FALSE, blank_prefix = 0;
1591 /* "Session data" packets - omit the data field */
1592 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1593 do_blank = TRUE; blank_prefix = 8;
1594 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1595 do_blank = TRUE; blank_prefix = 12;
1598 blank.offset = blank_prefix;
1599 blank.len = (st->pktin->length-6) - blank_prefix;
1600 blank.type = PKTLOG_OMIT;
1604 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1605 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1607 st->pktin->data+6, st->pktin->length-6,
1608 nblanks, &blank, &st->pktin->sequence);
1611 crFinish(st->pktin);
1614 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1616 int pad, biglen, i, pktoffs;
1620 * XXX various versions of SC (including 8.8.4) screw up the
1621 * register allocation in this function and use the same register
1622 * (D6) for len and as a temporary, with predictable results. The
1623 * following sledgehammer prevents this.
1630 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1631 ssh1_pkt_type(pkt->data[12]),
1632 pkt->body, pkt->length - (pkt->body - pkt->data),
1633 pkt->nblanks, pkt->blanks, NULL);
1634 sfree(pkt->blanks); pkt->blanks = NULL;
1637 if (ssh->v1_compressing) {
1638 unsigned char *compblk;
1640 zlib_compress_block(ssh->cs_comp_ctx,
1641 pkt->data + 12, pkt->length - 12,
1642 &compblk, &complen);
1643 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1644 memcpy(pkt->data + 12, compblk, complen);
1646 pkt->length = complen + 12;
1649 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1651 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1652 pad = 8 - (len % 8);
1654 biglen = len + pad; /* len(padding+type+data+CRC) */
1656 for (i = pktoffs; i < 4+8; i++)
1657 pkt->data[i] = random_byte();
1658 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1659 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1660 PUT_32BIT(pkt->data + pktoffs, len);
1663 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1664 pkt->data + pktoffs + 4, biglen);
1666 if (offset_p) *offset_p = pktoffs;
1667 return biglen + 4; /* len(length+padding+type+data+CRC) */
1670 static int s_write(Ssh ssh, void *data, int len)
1673 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1675 return sk_write(ssh->s, (char *)data, len);
1678 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1680 int len, backlog, offset;
1681 len = s_wrpkt_prepare(ssh, pkt, &offset);
1682 backlog = s_write(ssh, pkt->data + offset, len);
1683 if (backlog > SSH_MAX_BACKLOG)
1684 ssh_throttle_all(ssh, 1, backlog);
1685 ssh_free_packet(pkt);
1688 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1691 len = s_wrpkt_prepare(ssh, pkt, &offset);
1692 if (ssh->deferred_len + len > ssh->deferred_size) {
1693 ssh->deferred_size = ssh->deferred_len + len + 128;
1694 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1698 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1699 pkt->data + offset, len);
1700 ssh->deferred_len += len;
1701 ssh_free_packet(pkt);
1705 * Construct a SSH-1 packet with the specified contents.
1706 * (This all-at-once interface used to be the only one, but now SSH-1
1707 * packets can also be constructed incrementally.)
1709 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1715 pkt = ssh1_pkt_init(pkttype);
1717 while ((argtype = va_arg(ap, int)) != PKT_END) {
1718 unsigned char *argp, argchar;
1720 unsigned long argint;
1723 /* Actual fields in the packet */
1725 argint = va_arg(ap, int);
1726 ssh_pkt_adduint32(pkt, argint);
1729 argchar = (unsigned char) va_arg(ap, int);
1730 ssh_pkt_addbyte(pkt, argchar);
1733 argp = va_arg(ap, unsigned char *);
1734 arglen = va_arg(ap, int);
1735 ssh_pkt_adddata(pkt, argp, arglen);
1738 sargp = va_arg(ap, char *);
1739 ssh_pkt_addstring(pkt, sargp);
1742 bn = va_arg(ap, Bignum);
1743 ssh1_pkt_addmp(pkt, bn);
1745 /* Tokens for modifications to packet logging */
1747 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1750 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1753 end_log_omission(ssh, pkt);
1761 static void send_packet(Ssh ssh, int pkttype, ...)
1765 va_start(ap, pkttype);
1766 pkt = construct_packet(ssh, pkttype, ap);
1771 static void defer_packet(Ssh ssh, int pkttype, ...)
1775 va_start(ap, pkttype);
1776 pkt = construct_packet(ssh, pkttype, ap);
1778 s_wrpkt_defer(ssh, pkt);
1781 static int ssh_versioncmp(char *a, char *b)
1784 unsigned long av, bv;
1786 av = strtoul(a, &ae, 10);
1787 bv = strtoul(b, &be, 10);
1789 return (av < bv ? -1 : +1);
1794 av = strtoul(ae, &ae, 10);
1795 bv = strtoul(be, &be, 10);
1797 return (av < bv ? -1 : +1);
1802 * Utility routines for putting an SSH-protocol `string' and
1803 * `uint32' into a hash state.
1805 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1807 unsigned char lenblk[4];
1808 PUT_32BIT(lenblk, len);
1809 h->bytes(s, lenblk, 4);
1810 h->bytes(s, str, len);
1813 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1815 unsigned char intblk[4];
1816 PUT_32BIT(intblk, i);
1817 h->bytes(s, intblk, 4);
1821 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1823 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1825 if (pkt->maxlen < length) {
1826 unsigned char *body = pkt->body;
1827 int offset = body ? body - pkt->data : 0;
1828 pkt->maxlen = length + 256;
1829 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1830 if (body) pkt->body = pkt->data + offset;
1833 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
1835 if (pkt->logmode != PKTLOG_EMIT) {
1837 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1839 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1840 (pkt->body - pkt->data);
1841 pkt->blanks[pkt->nblanks-1].len = len;
1842 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1845 ssh_pkt_ensure(pkt, pkt->length);
1846 memcpy(pkt->data + pkt->length - len, data, len);
1848 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1850 ssh_pkt_adddata(pkt, &byte, 1);
1852 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1854 ssh_pkt_adddata(pkt, &value, 1);
1856 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1859 PUT_32BIT(x, value);
1860 ssh_pkt_adddata(pkt, x, 4);
1862 static void ssh_pkt_addstring_start(struct Packet *pkt)
1864 ssh_pkt_adduint32(pkt, 0);
1865 pkt->savedpos = pkt->length;
1867 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
1869 ssh_pkt_adddata(pkt, data, strlen(data));
1870 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1872 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
1875 ssh_pkt_adddata(pkt, data, len);
1876 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1878 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
1880 ssh_pkt_addstring_start(pkt);
1881 ssh_pkt_addstring_str(pkt, data);
1883 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1885 int len = ssh1_bignum_length(b);
1886 unsigned char *data = snewn(len, unsigned char);
1887 (void) ssh1_write_bignum(data, b);
1888 ssh_pkt_adddata(pkt, data, len);
1891 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1894 int i, n = (bignum_bitcount(b) + 7) / 8;
1895 p = snewn(n + 1, unsigned char);
1897 for (i = 1; i <= n; i++)
1898 p[i] = bignum_byte(b, n - i);
1900 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1902 memmove(p, p + i, n + 1 - i);
1906 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1910 p = ssh2_mpint_fmt(b, &len);
1911 ssh_pkt_addstring_start(pkt);
1912 ssh_pkt_addstring_data(pkt, (char *)p, len);
1916 static struct Packet *ssh1_pkt_init(int pkt_type)
1918 struct Packet *pkt = ssh_new_packet();
1919 pkt->length = 4 + 8; /* space for length + max padding */
1920 ssh_pkt_addbyte(pkt, pkt_type);
1921 pkt->body = pkt->data + pkt->length;
1925 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1926 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1927 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1928 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1929 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1930 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1931 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1932 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1933 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1935 static struct Packet *ssh2_pkt_init(int pkt_type)
1937 struct Packet *pkt = ssh_new_packet();
1938 pkt->length = 5; /* space for packet length + padding length */
1940 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1941 pkt->body = pkt->data + pkt->length; /* after packet type */
1946 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1947 * put the MAC on it. Final packet, ready to be sent, is stored in
1948 * pkt->data. Total length is returned.
1950 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1952 int cipherblk, maclen, padding, i;
1955 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1956 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1957 pkt->body, pkt->length - (pkt->body - pkt->data),
1958 pkt->nblanks, pkt->blanks, &ssh->v2_outgoing_sequence);
1959 sfree(pkt->blanks); pkt->blanks = NULL;
1963 * Compress packet payload.
1966 unsigned char *newpayload;
1969 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1971 &newpayload, &newlen)) {
1973 ssh2_pkt_adddata(pkt, newpayload, newlen);
1979 * Add padding. At least four bytes, and must also bring total
1980 * length (minus MAC) up to a multiple of the block size.
1981 * If pkt->forcepad is set, make sure the packet is at least that size
1984 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1985 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1987 if (pkt->length + padding < pkt->forcepad)
1988 padding = pkt->forcepad - pkt->length;
1990 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1991 assert(padding <= 255);
1992 maclen = ssh->csmac ? ssh->csmac->len : 0;
1993 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1994 pkt->data[4] = padding;
1995 for (i = 0; i < padding; i++)
1996 pkt->data[pkt->length + i] = random_byte();
1997 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1999 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2000 pkt->length + padding,
2001 ssh->v2_outgoing_sequence);
2002 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2005 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2006 pkt->data, pkt->length + padding);
2008 pkt->encrypted_len = pkt->length + padding;
2010 /* Ready-to-send packet starts at pkt->data. We return length. */
2011 return pkt->length + padding + maclen;
2015 * Routines called from the main SSH code to send packets. There
2016 * are quite a few of these, because we have two separate
2017 * mechanisms for delaying the sending of packets:
2019 * - In order to send an IGNORE message and a password message in
2020 * a single fixed-length blob, we require the ability to
2021 * concatenate the encrypted forms of those two packets _into_ a
2022 * single blob and then pass it to our <network.h> transport
2023 * layer in one go. Hence, there's a deferment mechanism which
2024 * works after packet encryption.
2026 * - In order to avoid sending any connection-layer messages
2027 * during repeat key exchange, we have to queue up any such
2028 * outgoing messages _before_ they are encrypted (and in
2029 * particular before they're allocated sequence numbers), and
2030 * then send them once we've finished.
2032 * I call these mechanisms `defer' and `queue' respectively, so as
2033 * to distinguish them reasonably easily.
2035 * The functions send_noqueue() and defer_noqueue() free the packet
2036 * structure they are passed. Every outgoing packet goes through
2037 * precisely one of these functions in its life; packets passed to
2038 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2039 * these or get queued, and then when the queue is later emptied
2040 * the packets are all passed to defer_noqueue().
2042 * When using a CBC-mode cipher, it's necessary to ensure that an
2043 * attacker can't provide data to be encrypted using an IV that they
2044 * know. We ensure this by prefixing each packet that might contain
2045 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2046 * mechanism, so in this case send_noqueue() ends up redirecting to
2047 * defer_noqueue(). If you don't like this inefficiency, don't use
2051 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2052 static void ssh_pkt_defersend(Ssh);
2055 * Send an SSH-2 packet immediately, without queuing or deferring.
2057 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2061 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2062 /* We need to send two packets, so use the deferral mechanism. */
2063 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2064 ssh_pkt_defersend(ssh);
2067 len = ssh2_pkt_construct(ssh, pkt);
2068 backlog = s_write(ssh, pkt->data, len);
2069 if (backlog > SSH_MAX_BACKLOG)
2070 ssh_throttle_all(ssh, 1, backlog);
2072 ssh->outgoing_data_size += pkt->encrypted_len;
2073 if (!ssh->kex_in_progress &&
2074 ssh->max_data_size != 0 &&
2075 ssh->outgoing_data_size > ssh->max_data_size)
2076 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2078 ssh_free_packet(pkt);
2082 * Defer an SSH-2 packet.
2084 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2087 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2088 ssh->deferred_len == 0 && !noignore &&
2089 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2091 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2092 * get encrypted with a known IV.
2094 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2095 ssh2_pkt_addstring_start(ipkt);
2096 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2098 len = ssh2_pkt_construct(ssh, pkt);
2099 if (ssh->deferred_len + len > ssh->deferred_size) {
2100 ssh->deferred_size = ssh->deferred_len + len + 128;
2101 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2105 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
2106 ssh->deferred_len += len;
2107 ssh->deferred_data_size += pkt->encrypted_len;
2108 ssh_free_packet(pkt);
2112 * Queue an SSH-2 packet.
2114 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2116 assert(ssh->queueing);
2118 if (ssh->queuelen >= ssh->queuesize) {
2119 ssh->queuesize = ssh->queuelen + 32;
2120 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2123 ssh->queue[ssh->queuelen++] = pkt;
2127 * Either queue or send a packet, depending on whether queueing is
2130 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2133 ssh2_pkt_queue(ssh, pkt);
2135 ssh2_pkt_send_noqueue(ssh, pkt);
2139 * Either queue or defer a packet, depending on whether queueing is
2142 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2145 ssh2_pkt_queue(ssh, pkt);
2147 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2151 * Send the whole deferred data block constructed by
2152 * ssh2_pkt_defer() or SSH-1's defer_packet().
2154 * The expected use of the defer mechanism is that you call
2155 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2156 * not currently queueing, this simply sets up deferred_send_data
2157 * and then sends it. If we _are_ currently queueing, the calls to
2158 * ssh2_pkt_defer() put the deferred packets on to the queue
2159 * instead, and therefore ssh_pkt_defersend() has no deferred data
2160 * to send. Hence, there's no need to make it conditional on
2163 static void ssh_pkt_defersend(Ssh ssh)
2166 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2167 ssh->deferred_len = ssh->deferred_size = 0;
2168 sfree(ssh->deferred_send_data);
2169 ssh->deferred_send_data = NULL;
2170 if (backlog > SSH_MAX_BACKLOG)
2171 ssh_throttle_all(ssh, 1, backlog);
2173 ssh->outgoing_data_size += ssh->deferred_data_size;
2174 if (!ssh->kex_in_progress &&
2175 ssh->max_data_size != 0 &&
2176 ssh->outgoing_data_size > ssh->max_data_size)
2177 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2178 ssh->deferred_data_size = 0;
2182 * Send a packet whose length needs to be disguised (typically
2183 * passwords or keyboard-interactive responses).
2185 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2191 * The simplest way to do this is to adjust the
2192 * variable-length padding field in the outgoing packet.
2194 * Currently compiled out, because some Cisco SSH servers
2195 * don't like excessively padded packets (bah, why's it
2198 pkt->forcepad = padsize;
2199 ssh2_pkt_send(ssh, pkt);
2204 * If we can't do that, however, an alternative approach is
2205 * to use the pkt_defer mechanism to bundle the packet
2206 * tightly together with an SSH_MSG_IGNORE such that their
2207 * combined length is a constant. So first we construct the
2208 * final form of this packet and defer its sending.
2210 ssh2_pkt_defer(ssh, pkt);
2213 * Now construct an SSH_MSG_IGNORE which includes a string
2214 * that's an exact multiple of the cipher block size. (If
2215 * the cipher is NULL so that the block size is
2216 * unavailable, we don't do this trick at all, because we
2217 * gain nothing by it.)
2219 if (ssh->cscipher &&
2220 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2223 stringlen = (256 - ssh->deferred_len);
2224 stringlen += ssh->cscipher->blksize - 1;
2225 stringlen -= (stringlen % ssh->cscipher->blksize);
2228 * Temporarily disable actual compression, so we
2229 * can guarantee to get this string exactly the
2230 * length we want it. The compression-disabling
2231 * routine should return an integer indicating how
2232 * many bytes we should adjust our string length
2236 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2238 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2239 ssh2_pkt_addstring_start(pkt);
2240 for (i = 0; i < stringlen; i++) {
2241 char c = (char) random_byte();
2242 ssh2_pkt_addstring_data(pkt, &c, 1);
2244 ssh2_pkt_defer(ssh, pkt);
2246 ssh_pkt_defersend(ssh);
2251 * Send all queued SSH-2 packets. We send them by means of
2252 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2253 * packets that needed to be lumped together.
2255 static void ssh2_pkt_queuesend(Ssh ssh)
2259 assert(!ssh->queueing);
2261 for (i = 0; i < ssh->queuelen; i++)
2262 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2265 ssh_pkt_defersend(ssh);
2269 void bndebug(char *string, Bignum b)
2273 p = ssh2_mpint_fmt(b, &len);
2274 debug(("%s", string));
2275 for (i = 0; i < len; i++)
2276 debug((" %02x", p[i]));
2282 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2286 p = ssh2_mpint_fmt(b, &len);
2287 hash_string(h, s, p, len);
2292 * Packet decode functions for both SSH-1 and SSH-2.
2294 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2296 unsigned long value;
2297 if (pkt->length - pkt->savedpos < 4)
2298 return 0; /* arrgh, no way to decline (FIXME?) */
2299 value = GET_32BIT(pkt->body + pkt->savedpos);
2303 static int ssh2_pkt_getbool(struct Packet *pkt)
2305 unsigned long value;
2306 if (pkt->length - pkt->savedpos < 1)
2307 return 0; /* arrgh, no way to decline (FIXME?) */
2308 value = pkt->body[pkt->savedpos] != 0;
2312 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2317 if (pkt->length - pkt->savedpos < 4)
2319 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2324 if (pkt->length - pkt->savedpos < *length)
2326 *p = (char *)(pkt->body + pkt->savedpos);
2327 pkt->savedpos += *length;
2329 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2331 if (pkt->length - pkt->savedpos < length)
2333 pkt->savedpos += length;
2334 return pkt->body + (pkt->savedpos - length);
2336 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2337 unsigned char **keystr)
2341 j = makekey(pkt->body + pkt->savedpos,
2342 pkt->length - pkt->savedpos,
2349 assert(pkt->savedpos < pkt->length);
2353 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2358 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2359 pkt->length - pkt->savedpos, &b);
2367 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2373 ssh_pkt_getstring(pkt, &p, &length);
2378 b = bignum_from_bytes((unsigned char *)p, length);
2383 * Helper function to add an SSH-2 signature blob to a packet.
2384 * Expects to be shown the public key blob as well as the signature
2385 * blob. Normally works just like ssh2_pkt_addstring, but will
2386 * fiddle with the signature packet if necessary for
2387 * BUG_SSH2_RSA_PADDING.
2389 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2390 void *pkblob_v, int pkblob_len,
2391 void *sigblob_v, int sigblob_len)
2393 unsigned char *pkblob = (unsigned char *)pkblob_v;
2394 unsigned char *sigblob = (unsigned char *)sigblob_v;
2396 /* dmemdump(pkblob, pkblob_len); */
2397 /* dmemdump(sigblob, sigblob_len); */
2400 * See if this is in fact an ssh-rsa signature and a buggy
2401 * server; otherwise we can just do this the easy way.
2403 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2404 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2405 int pos, len, siglen;
2408 * Find the byte length of the modulus.
2411 pos = 4+7; /* skip over "ssh-rsa" */
2412 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2413 if (len < 0 || len > pkblob_len - pos - 4)
2415 pos += 4 + len; /* skip over exponent */
2416 if (pkblob_len - pos < 4)
2418 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2419 if (len < 0 || len > pkblob_len - pos - 4)
2421 pos += 4; /* find modulus itself */
2422 while (len > 0 && pkblob[pos] == 0)
2424 /* debug(("modulus length is %d\n", len)); */
2427 * Now find the signature integer.
2429 pos = 4+7; /* skip over "ssh-rsa" */
2430 if (sigblob_len < pos+4)
2432 siglen = toint(GET_32BIT(sigblob+pos));
2433 if (siglen != sigblob_len - pos - 4)
2435 /* debug(("signature length is %d\n", siglen)); */
2437 if (len != siglen) {
2438 unsigned char newlen[4];
2439 ssh2_pkt_addstring_start(pkt);
2440 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2441 /* dmemdump(sigblob, pos); */
2442 pos += 4; /* point to start of actual sig */
2443 PUT_32BIT(newlen, len);
2444 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2445 /* dmemdump(newlen, 4); */
2447 while (len-- > siglen) {
2448 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2449 /* dmemdump(newlen, 1); */
2451 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2452 /* dmemdump(sigblob+pos, siglen); */
2456 /* Otherwise fall through and do it the easy way. We also come
2457 * here as a fallback if we discover above that the key blob
2458 * is misformatted in some way. */
2462 ssh2_pkt_addstring_start(pkt);
2463 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2467 * Examine the remote side's version string and compare it against
2468 * a list of known buggy implementations.
2470 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2472 char *imp; /* pointer to implementation part */
2474 imp += strcspn(imp, "-");
2476 imp += strcspn(imp, "-");
2479 ssh->remote_bugs = 0;
2482 * General notes on server version strings:
2483 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2484 * here -- in particular, we've heard of one that's perfectly happy
2485 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2486 * so we can't distinguish them.
2488 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2489 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2490 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2491 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2492 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2493 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2495 * These versions don't support SSH1_MSG_IGNORE, so we have
2496 * to use a different defence against password length
2499 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2500 logevent("We believe remote version has SSH-1 ignore bug");
2503 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2504 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2505 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2507 * These versions need a plain password sent; they can't
2508 * handle having a null and a random length of data after
2511 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2512 logevent("We believe remote version needs a plain SSH-1 password");
2515 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2516 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2517 (!strcmp(imp, "Cisco-1.25")))) {
2519 * These versions apparently have no clue whatever about
2520 * RSA authentication and will panic and die if they see
2521 * an AUTH_RSA message.
2523 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2524 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2527 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2528 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2529 !wc_match("* VShell", imp) &&
2530 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2531 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2532 wc_match("2.1 *", imp)))) {
2534 * These versions have the HMAC bug.
2536 ssh->remote_bugs |= BUG_SSH2_HMAC;
2537 logevent("We believe remote version has SSH-2 HMAC bug");
2540 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2541 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2542 !wc_match("* VShell", imp) &&
2543 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2545 * These versions have the key-derivation bug (failing to
2546 * include the literal shared secret in the hashes that
2547 * generate the keys).
2549 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2550 logevent("We believe remote version has SSH-2 key-derivation bug");
2553 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2554 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2555 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2556 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2558 * These versions have the SSH-2 RSA padding bug.
2560 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2561 logevent("We believe remote version has SSH-2 RSA padding bug");
2564 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2565 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2566 wc_match("OpenSSH_2.[0-2]*", imp))) {
2568 * These versions have the SSH-2 session-ID bug in
2569 * public-key authentication.
2571 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2572 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2575 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2576 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2577 (wc_match("DigiSSH_2.0", imp) ||
2578 wc_match("OpenSSH_2.[0-4]*", imp) ||
2579 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2580 wc_match("Sun_SSH_1.0", imp) ||
2581 wc_match("Sun_SSH_1.0.1", imp) ||
2582 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2583 wc_match("WeOnlyDo-*", imp)))) {
2585 * These versions have the SSH-2 rekey bug.
2587 ssh->remote_bugs |= BUG_SSH2_REKEY;
2588 logevent("We believe remote version has SSH-2 rekey bug");
2591 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2592 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2593 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2594 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2596 * This version ignores our makpkt and needs to be throttled.
2598 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2599 logevent("We believe remote version ignores SSH-2 maximum packet size");
2602 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2604 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2605 * none detected automatically.
2607 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2608 logevent("We believe remote version has SSH-2 ignore bug");
2611 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2613 * Servers that don't support our winadj request for one
2614 * reason or another. Currently, none detected automatically.
2616 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2617 logevent("We believe remote version has winadj bug");
2622 * The `software version' part of an SSH version string is required
2623 * to contain no spaces or minus signs.
2625 static void ssh_fix_verstring(char *str)
2627 /* Eat "SSH-<protoversion>-". */
2628 assert(*str == 'S'); str++;
2629 assert(*str == 'S'); str++;
2630 assert(*str == 'H'); str++;
2631 assert(*str == '-'); str++;
2632 while (*str && *str != '-') str++;
2633 assert(*str == '-'); str++;
2635 /* Convert minus signs and spaces in the remaining string into
2638 if (*str == '-' || *str == ' ')
2645 * Send an appropriate SSH version string.
2647 static void ssh_send_verstring(Ssh ssh, char *svers)
2651 if (ssh->version == 2) {
2653 * Construct a v2 version string.
2655 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2658 * Construct a v1 version string.
2660 verstring = dupprintf("SSH-%s-%s\012",
2661 (ssh_versioncmp(svers, "1.5") <= 0 ?
2666 ssh_fix_verstring(verstring);
2668 if (ssh->version == 2) {
2671 * Record our version string.
2673 len = strcspn(verstring, "\015\012");
2674 ssh->v_c = snewn(len + 1, char);
2675 memcpy(ssh->v_c, verstring, len);
2679 logeventf(ssh, "We claim version: %.*s",
2680 strcspn(verstring, "\015\012"), verstring);
2681 s_write(ssh, verstring, strlen(verstring));
2685 static int do_ssh_init(Ssh ssh, unsigned char c)
2687 struct do_ssh_init_state {
2696 crState(do_ssh_init_state);
2700 /* Search for a line beginning with the string "SSH-" in the input. */
2702 if (c != 'S') goto no;
2704 if (c != 'S') goto no;
2706 if (c != 'H') goto no;
2708 if (c != '-') goto no;
2717 s->vstring = snewn(s->vstrsize, char);
2718 strcpy(s->vstring, "SSH-");
2722 crReturn(1); /* get another char */
2723 if (s->vslen >= s->vstrsize - 1) {
2725 s->vstring = sresize(s->vstring, s->vstrsize, char);
2727 s->vstring[s->vslen++] = c;
2730 s->version[s->i] = '\0';
2732 } else if (s->i < sizeof(s->version) - 1)
2733 s->version[s->i++] = c;
2734 } else if (c == '\012')
2738 ssh->agentfwd_enabled = FALSE;
2739 ssh->rdpkt2_state.incoming_sequence = 0;
2741 s->vstring[s->vslen] = 0;
2742 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2743 logeventf(ssh, "Server version: %s", s->vstring);
2744 ssh_detect_bugs(ssh, s->vstring);
2747 * Decide which SSH protocol version to support.
2750 /* Anything strictly below "2.0" means protocol 1 is supported. */
2751 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2752 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2753 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2755 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2756 bombout(("SSH protocol version 1 required by user but not provided by server"));
2759 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2760 bombout(("SSH protocol version 2 required by user but not provided by server"));
2764 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2769 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2771 /* Send the version string, if we haven't already */
2772 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
2773 ssh_send_verstring(ssh, s->version);
2775 if (ssh->version == 2) {
2778 * Record their version string.
2780 len = strcspn(s->vstring, "\015\012");
2781 ssh->v_s = snewn(len + 1, char);
2782 memcpy(ssh->v_s, s->vstring, len);
2786 * Initialise SSH-2 protocol.
2788 ssh->protocol = ssh2_protocol;
2789 ssh2_protocol_setup(ssh);
2790 ssh->s_rdpkt = ssh2_rdpkt;
2793 * Initialise SSH-1 protocol.
2795 ssh->protocol = ssh1_protocol;
2796 ssh1_protocol_setup(ssh);
2797 ssh->s_rdpkt = ssh1_rdpkt;
2799 if (ssh->version == 2)
2800 do_ssh2_transport(ssh, NULL, -1, NULL);
2802 update_specials_menu(ssh->frontend);
2803 ssh->state = SSH_STATE_BEFORE_SIZE;
2804 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
2811 static void ssh_process_incoming_data(Ssh ssh,
2812 unsigned char **data, int *datalen)
2814 struct Packet *pktin;
2816 pktin = ssh->s_rdpkt(ssh, data, datalen);
2818 ssh->protocol(ssh, NULL, 0, pktin);
2819 ssh_free_packet(pktin);
2823 static void ssh_queue_incoming_data(Ssh ssh,
2824 unsigned char **data, int *datalen)
2826 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2831 static void ssh_process_queued_incoming_data(Ssh ssh)
2834 unsigned char *data;
2837 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2838 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2842 while (!ssh->frozen && len > 0)
2843 ssh_process_incoming_data(ssh, &data, &len);
2846 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2850 static void ssh_set_frozen(Ssh ssh, int frozen)
2853 sk_set_frozen(ssh->s, frozen);
2854 ssh->frozen = frozen;
2857 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2859 /* Log raw data, if we're in that mode. */
2861 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2864 crBegin(ssh->ssh_gotdata_crstate);
2867 * To begin with, feed the characters one by one to the
2868 * protocol initialisation / selection function do_ssh_init().
2869 * When that returns 0, we're done with the initial greeting
2870 * exchange and can move on to packet discipline.
2873 int ret; /* need not be kept across crReturn */
2875 crReturnV; /* more data please */
2876 ret = do_ssh_init(ssh, *data);
2884 * We emerge from that loop when the initial negotiation is
2885 * over and we have selected an s_rdpkt function. Now pass
2886 * everything to s_rdpkt, and then pass the resulting packets
2887 * to the proper protocol handler.
2891 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2893 ssh_queue_incoming_data(ssh, &data, &datalen);
2894 /* This uses up all data and cannot cause anything interesting
2895 * to happen; indeed, for anything to happen at all, we must
2896 * return, so break out. */
2898 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2899 /* This uses up some or all data, and may freeze the
2901 ssh_process_queued_incoming_data(ssh);
2903 /* This uses up some or all data, and may freeze the
2905 ssh_process_incoming_data(ssh, &data, &datalen);
2907 /* FIXME this is probably EBW. */
2908 if (ssh->state == SSH_STATE_CLOSED)
2911 /* We're out of data. Go and get some more. */
2917 static int ssh_do_close(Ssh ssh, int notify_exit)
2920 struct ssh_channel *c;
2922 ssh->state = SSH_STATE_CLOSED;
2923 expire_timer_context(ssh);
2928 notify_remote_exit(ssh->frontend);
2933 * Now we must shut down any port- and X-forwarded channels going
2934 * through this connection.
2936 if (ssh->channels) {
2937 while (NULL != (c = index234(ssh->channels, 0))) {
2940 x11_close(c->u.x11.s);
2943 case CHAN_SOCKDATA_DORMANT:
2944 pfd_close(c->u.pfd.s);
2947 del234(ssh->channels, c); /* moving next one to index 0 */
2948 if (ssh->version == 2)
2949 bufchain_clear(&c->v.v2.outbuffer);
2954 * Go through port-forwardings, and close any associated
2955 * listening sockets.
2957 if (ssh->portfwds) {
2958 struct ssh_portfwd *pf;
2959 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2960 /* Dispose of any listening socket. */
2962 pfd_terminate(pf->local);
2963 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2966 freetree234(ssh->portfwds);
2967 ssh->portfwds = NULL;
2973 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2974 const char *error_msg, int error_code)
2976 Ssh ssh = (Ssh) plug;
2977 char addrbuf[256], *msg;
2979 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2982 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2984 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2990 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2993 Ssh ssh = (Ssh) plug;
2994 int need_notify = ssh_do_close(ssh, FALSE);
2997 if (!ssh->close_expected)
2998 error_msg = "Server unexpectedly closed network connection";
3000 error_msg = "Server closed network connection";
3003 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3007 notify_remote_exit(ssh->frontend);
3010 logevent(error_msg);
3011 if (!ssh->close_expected || !ssh->clean_exit)
3012 connection_fatal(ssh->frontend, "%s", error_msg);
3016 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3018 Ssh ssh = (Ssh) plug;
3019 ssh_gotdata(ssh, (unsigned char *)data, len);
3020 if (ssh->state == SSH_STATE_CLOSED) {
3021 ssh_do_close(ssh, TRUE);
3027 static void ssh_sent(Plug plug, int bufsize)
3029 Ssh ssh = (Ssh) plug;
3031 * If the send backlog on the SSH socket itself clears, we
3032 * should unthrottle the whole world if it was throttled.
3034 if (bufsize < SSH_MAX_BACKLOG)
3035 ssh_throttle_all(ssh, 0, bufsize);
3039 * Connect to specified host and port.
3040 * Returns an error message, or NULL on success.
3041 * Also places the canonical host name into `realhost'. It must be
3042 * freed by the caller.
3044 static const char *connect_to_host(Ssh ssh, char *host, int port,
3045 char **realhost, int nodelay, int keepalive)
3047 static const struct plug_function_table fn_table = {
3058 int addressfamily, sshprot;
3060 loghost = conf_get_str(ssh->conf, CONF_loghost);
3064 ssh->savedhost = dupstr(loghost);
3065 ssh->savedport = 22; /* default ssh port */
3068 * A colon suffix on savedhost also lets us affect
3071 * (FIXME: do something about IPv6 address literals here.)
3073 colon = strrchr(ssh->savedhost, ':');
3077 ssh->savedport = atoi(colon);
3080 ssh->savedhost = dupstr(host);
3082 port = 22; /* default ssh port */
3083 ssh->savedport = port;
3089 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3090 logeventf(ssh, "Looking up host \"%s\"%s", host,
3091 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3092 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3093 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3094 if ((err = sk_addr_error(addr)) != NULL) {
3098 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3103 ssh->fn = &fn_table;
3104 ssh->s = new_connection(addr, *realhost, port,
3105 0, 1, nodelay, keepalive, (Plug) ssh, ssh->conf);
3106 if ((err = sk_socket_error(ssh->s)) != NULL) {
3108 notify_remote_exit(ssh->frontend);
3113 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3114 * send the version string too.
3116 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3121 ssh_send_verstring(ssh, NULL);
3125 * loghost, if configured, overrides realhost.
3129 *realhost = dupstr(loghost);
3136 * Throttle or unthrottle the SSH connection.
3138 static void ssh_throttle_conn(Ssh ssh, int adjust)
3140 int old_count = ssh->conn_throttle_count;
3141 ssh->conn_throttle_count += adjust;
3142 assert(ssh->conn_throttle_count >= 0);
3143 if (ssh->conn_throttle_count && !old_count) {
3144 ssh_set_frozen(ssh, 1);
3145 } else if (!ssh->conn_throttle_count && old_count) {
3146 ssh_set_frozen(ssh, 0);
3151 * Throttle or unthrottle _all_ local data streams (for when sends
3152 * on the SSH connection itself back up).
3154 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3157 struct ssh_channel *c;
3159 if (enable == ssh->throttled_all)
3161 ssh->throttled_all = enable;
3162 ssh->overall_bufsize = bufsize;
3165 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3167 case CHAN_MAINSESSION:
3169 * This is treated separately, outside the switch.
3173 x11_override_throttle(c->u.x11.s, enable);
3176 /* Agent channels require no buffer management. */
3179 pfd_override_throttle(c->u.pfd.s, enable);
3185 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3187 Ssh ssh = (Ssh) sshv;
3189 ssh->agent_response = reply;
3190 ssh->agent_response_len = replylen;
3192 if (ssh->version == 1)
3193 do_ssh1_login(ssh, NULL, -1, NULL);
3195 do_ssh2_authconn(ssh, NULL, -1, NULL);
3198 static void ssh_dialog_callback(void *sshv, int ret)
3200 Ssh ssh = (Ssh) sshv;
3202 ssh->user_response = ret;
3204 if (ssh->version == 1)
3205 do_ssh1_login(ssh, NULL, -1, NULL);
3207 do_ssh2_transport(ssh, NULL, -1, NULL);
3210 * This may have unfrozen the SSH connection, so do a
3213 ssh_process_queued_incoming_data(ssh);
3216 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3218 struct ssh_channel *c = (struct ssh_channel *)cv;
3220 void *sentreply = reply;
3222 c->u.a.outstanding_requests--;
3224 /* Fake SSH_AGENT_FAILURE. */
3225 sentreply = "\0\0\0\1\5";
3228 if (ssh->version == 2) {
3229 ssh2_add_channel_data(c, sentreply, replylen);
3232 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3233 PKT_INT, c->remoteid,
3236 PKT_DATA, sentreply, replylen,
3243 * If we've already seen an incoming EOF but haven't sent an
3244 * outgoing one, this may be the moment to send it.
3246 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3247 sshfwd_write_eof(c);
3251 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3252 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3253 * => log `wire_reason'.
3255 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3256 int code, int clean_exit)
3260 client_reason = wire_reason;
3262 error = dupprintf("Disconnected: %s", client_reason);
3264 error = dupstr("Disconnected");
3266 if (ssh->version == 1) {
3267 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3269 } else if (ssh->version == 2) {
3270 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3271 ssh2_pkt_adduint32(pktout, code);
3272 ssh2_pkt_addstring(pktout, wire_reason);
3273 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3274 ssh2_pkt_send_noqueue(ssh, pktout);
3277 ssh->close_expected = TRUE;
3278 ssh->clean_exit = clean_exit;
3279 ssh_closing((Plug)ssh, error, 0, 0);
3284 * Handle the key exchange and user authentication phases.
3286 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3287 struct Packet *pktin)
3290 unsigned char cookie[8], *ptr;
3291 struct MD5Context md5c;
3292 struct do_ssh1_login_state {
3295 unsigned char *rsabuf, *keystr1, *keystr2;
3296 unsigned long supported_ciphers_mask, supported_auths_mask;
3297 int tried_publickey, tried_agent;
3298 int tis_auth_refused, ccard_auth_refused;
3299 unsigned char session_id[16];
3301 void *publickey_blob;
3302 int publickey_bloblen;
3303 char *publickey_comment;
3304 int publickey_encrypted;
3305 prompts_t *cur_prompt;
3308 unsigned char request[5], *response, *p;
3318 struct RSAKey servkey, hostkey;
3320 crState(do_ssh1_login_state);
3327 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3328 bombout(("Public key packet not received"));
3332 logevent("Received public keys");
3334 ptr = ssh_pkt_getdata(pktin, 8);
3336 bombout(("SSH-1 public key packet stopped before random cookie"));
3339 memcpy(cookie, ptr, 8);
3341 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3342 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3343 bombout(("Failed to read SSH-1 public keys from public key packet"));
3348 * Log the host key fingerprint.
3352 logevent("Host key fingerprint is:");
3353 strcpy(logmsg, " ");
3354 s->hostkey.comment = NULL;
3355 rsa_fingerprint(logmsg + strlen(logmsg),
3356 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3360 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3361 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3362 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3363 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3364 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3366 ssh->v1_local_protoflags =
3367 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3368 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3371 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
3372 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
3373 MD5Update(&md5c, cookie, 8);
3374 MD5Final(s->session_id, &md5c);
3376 for (i = 0; i < 32; i++)
3377 ssh->session_key[i] = random_byte();
3380 * Verify that the `bits' and `bytes' parameters match.
3382 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
3383 s->servkey.bits > s->servkey.bytes * 8) {
3384 bombout(("SSH-1 public keys were badly formatted"));
3388 s->len = (s->hostkey.bytes > s->servkey.bytes ?
3389 s->hostkey.bytes : s->servkey.bytes);
3391 s->rsabuf = snewn(s->len, unsigned char);
3394 * Verify the host key.
3398 * First format the key into a string.
3400 int len = rsastr_len(&s->hostkey);
3401 char fingerprint[100];
3402 char *keystr = snewn(len, char);
3403 rsastr_fmt(keystr, &s->hostkey);
3404 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
3406 ssh_set_frozen(ssh, 1);
3407 s->dlgret = verify_ssh_host_key(ssh->frontend,
3408 ssh->savedhost, ssh->savedport,
3409 "rsa", keystr, fingerprint,
3410 ssh_dialog_callback, ssh);
3412 if (s->dlgret < 0) {
3416 bombout(("Unexpected data from server while waiting"
3417 " for user host key response"));
3420 } while (pktin || inlen > 0);
3421 s->dlgret = ssh->user_response;
3423 ssh_set_frozen(ssh, 0);
3425 if (s->dlgret == 0) {
3426 ssh_disconnect(ssh, "User aborted at host key verification",
3432 for (i = 0; i < 32; i++) {
3433 s->rsabuf[i] = ssh->session_key[i];
3435 s->rsabuf[i] ^= s->session_id[i];
3438 if (s->hostkey.bytes > s->servkey.bytes) {
3439 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
3441 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
3443 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
3445 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
3448 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3452 logevent("Encrypted session key");
3455 int cipher_chosen = 0, warn = 0;
3456 char *cipher_string = NULL;
3458 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3459 int next_cipher = conf_get_int_int(ssh->conf,
3460 CONF_ssh_cipherlist, i);
3461 if (next_cipher == CIPHER_WARN) {
3462 /* If/when we choose a cipher, warn about it */
3464 } else if (next_cipher == CIPHER_AES) {
3465 /* XXX Probably don't need to mention this. */
3466 logevent("AES not supported in SSH-1, skipping");
3468 switch (next_cipher) {
3469 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3470 cipher_string = "3DES"; break;
3471 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3472 cipher_string = "Blowfish"; break;
3473 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3474 cipher_string = "single-DES"; break;
3476 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3480 if (!cipher_chosen) {
3481 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3482 bombout(("Server violates SSH-1 protocol by not "
3483 "supporting 3DES encryption"));
3485 /* shouldn't happen */
3486 bombout(("No supported ciphers found"));
3490 /* Warn about chosen cipher if necessary. */
3492 ssh_set_frozen(ssh, 1);
3493 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3494 ssh_dialog_callback, ssh);
3495 if (s->dlgret < 0) {
3499 bombout(("Unexpected data from server while waiting"
3500 " for user response"));
3503 } while (pktin || inlen > 0);
3504 s->dlgret = ssh->user_response;
3506 ssh_set_frozen(ssh, 0);
3507 if (s->dlgret == 0) {
3508 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3515 switch (s->cipher_type) {
3516 case SSH_CIPHER_3DES:
3517 logevent("Using 3DES encryption");
3519 case SSH_CIPHER_DES:
3520 logevent("Using single-DES encryption");
3522 case SSH_CIPHER_BLOWFISH:
3523 logevent("Using Blowfish encryption");
3527 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3528 PKT_CHAR, s->cipher_type,
3529 PKT_DATA, cookie, 8,
3530 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3531 PKT_DATA, s->rsabuf, s->len,
3532 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3534 logevent("Trying to enable encryption...");
3538 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3539 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3541 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3542 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3543 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3545 ssh->crcda_ctx = crcda_make_context();
3546 logevent("Installing CRC compensation attack detector");
3548 if (s->servkey.modulus) {
3549 sfree(s->servkey.modulus);
3550 s->servkey.modulus = NULL;
3552 if (s->servkey.exponent) {
3553 sfree(s->servkey.exponent);
3554 s->servkey.exponent = NULL;
3556 if (s->hostkey.modulus) {
3557 sfree(s->hostkey.modulus);
3558 s->hostkey.modulus = NULL;
3560 if (s->hostkey.exponent) {
3561 sfree(s->hostkey.exponent);
3562 s->hostkey.exponent = NULL;
3566 if (pktin->type != SSH1_SMSG_SUCCESS) {
3567 bombout(("Encryption not successfully enabled"));
3571 logevent("Successfully started encryption");
3573 fflush(stdout); /* FIXME eh? */
3575 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
3576 int ret; /* need not be kept over crReturn */
3577 s->cur_prompt = new_prompts(ssh->frontend);
3578 s->cur_prompt->to_server = TRUE;
3579 s->cur_prompt->name = dupstr("SSH login name");
3580 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
3581 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3584 crWaitUntil(!pktin);
3585 ret = get_userpass_input(s->cur_prompt, in, inlen);
3590 * Failed to get a username. Terminate.
3592 free_prompts(s->cur_prompt);
3593 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3596 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
3597 free_prompts(s->cur_prompt);
3600 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
3602 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
3604 if (flags & FLAG_INTERACTIVE &&
3605 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3606 c_write_str(ssh, userlog);
3607 c_write_str(ssh, "\r\n");
3615 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3616 /* We must not attempt PK auth. Pretend we've already tried it. */
3617 s->tried_publickey = s->tried_agent = 1;
3619 s->tried_publickey = s->tried_agent = 0;
3621 s->tis_auth_refused = s->ccard_auth_refused = 0;
3623 * Load the public half of any configured keyfile for later use.
3625 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3626 if (!filename_is_null(s->keyfile)) {
3628 logeventf(ssh, "Reading private key file \"%.150s\"",
3629 filename_to_str(s->keyfile));
3630 keytype = key_type(s->keyfile);
3631 if (keytype == SSH_KEYTYPE_SSH1) {
3633 if (rsakey_pubblob(s->keyfile,
3634 &s->publickey_blob, &s->publickey_bloblen,
3635 &s->publickey_comment, &error)) {
3636 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
3640 logeventf(ssh, "Unable to load private key (%s)", error);
3641 msgbuf = dupprintf("Unable to load private key file "
3642 "\"%.150s\" (%s)\r\n",
3643 filename_to_str(s->keyfile),
3645 c_write_str(ssh, msgbuf);
3647 s->publickey_blob = NULL;
3651 logeventf(ssh, "Unable to use this key file (%s)",
3652 key_type_to_str(keytype));
3653 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3655 filename_to_str(s->keyfile),
3656 key_type_to_str(keytype));
3657 c_write_str(ssh, msgbuf);
3659 s->publickey_blob = NULL;
3662 s->publickey_blob = NULL;
3664 while (pktin->type == SSH1_SMSG_FAILURE) {
3665 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3667 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
3669 * Attempt RSA authentication using Pageant.
3675 logevent("Pageant is running. Requesting keys.");
3677 /* Request the keys held by the agent. */
3678 PUT_32BIT(s->request, 1);
3679 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3680 if (!agent_query(s->request, 5, &r, &s->responselen,
3681 ssh_agent_callback, ssh)) {
3685 bombout(("Unexpected data from server while waiting"
3686 " for agent response"));
3689 } while (pktin || inlen > 0);
3690 r = ssh->agent_response;
3691 s->responselen = ssh->agent_response_len;
3693 s->response = (unsigned char *) r;
3694 if (s->response && s->responselen >= 5 &&
3695 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3696 s->p = s->response + 5;
3697 s->nkeys = toint(GET_32BIT(s->p));
3699 logeventf(ssh, "Pageant reported negative key count %d",
3704 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3705 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3706 unsigned char *pkblob = s->p;
3710 do { /* do while (0) to make breaking easy */
3711 n = ssh1_read_bignum
3712 (s->p, toint(s->responselen-(s->p-s->response)),
3717 n = ssh1_read_bignum
3718 (s->p, toint(s->responselen-(s->p-s->response)),
3723 if (s->responselen - (s->p-s->response) < 4)
3725 s->commentlen = toint(GET_32BIT(s->p));
3727 if (s->commentlen < 0 ||
3728 toint(s->responselen - (s->p-s->response)) <
3731 s->commentp = (char *)s->p;
3732 s->p += s->commentlen;
3736 logevent("Pageant key list packet was truncated");
3740 if (s->publickey_blob) {
3741 if (!memcmp(pkblob, s->publickey_blob,
3742 s->publickey_bloblen)) {
3743 logeventf(ssh, "Pageant key #%d matches "
3744 "configured key file", s->keyi);
3745 s->tried_publickey = 1;
3747 /* Skip non-configured key */
3750 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3751 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3752 PKT_BIGNUM, s->key.modulus, PKT_END);
3754 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3755 logevent("Key refused");
3758 logevent("Received RSA challenge");
3759 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3760 bombout(("Server's RSA challenge was badly formatted"));
3765 char *agentreq, *q, *ret;
3768 len = 1 + 4; /* message type, bit count */
3769 len += ssh1_bignum_length(s->key.exponent);
3770 len += ssh1_bignum_length(s->key.modulus);
3771 len += ssh1_bignum_length(s->challenge);
3772 len += 16; /* session id */
3773 len += 4; /* response format */
3774 agentreq = snewn(4 + len, char);
3775 PUT_32BIT(agentreq, len);
3777 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3778 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3780 q += ssh1_write_bignum(q, s->key.exponent);
3781 q += ssh1_write_bignum(q, s->key.modulus);
3782 q += ssh1_write_bignum(q, s->challenge);
3783 memcpy(q, s->session_id, 16);
3785 PUT_32BIT(q, 1); /* response format */
3786 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3787 ssh_agent_callback, ssh)) {
3792 bombout(("Unexpected data from server"
3793 " while waiting for agent"
3797 } while (pktin || inlen > 0);
3798 vret = ssh->agent_response;
3799 retlen = ssh->agent_response_len;
3804 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3805 logevent("Sending Pageant's response");
3806 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3807 PKT_DATA, ret + 5, 16,
3811 if (pktin->type == SSH1_SMSG_SUCCESS) {
3813 ("Pageant's response accepted");
3814 if (flags & FLAG_VERBOSE) {
3815 c_write_str(ssh, "Authenticated using"
3817 c_write(ssh, s->commentp,
3819 c_write_str(ssh, "\" from agent\r\n");
3824 ("Pageant's response not accepted");
3827 ("Pageant failed to answer challenge");
3831 logevent("No reply received from Pageant");
3834 freebn(s->key.exponent);
3835 freebn(s->key.modulus);
3836 freebn(s->challenge);
3841 if (s->publickey_blob && !s->tried_publickey)
3842 logevent("Configured key file not in Pageant");
3844 logevent("Failed to get reply from Pageant");
3849 if (s->publickey_blob && !s->tried_publickey) {
3851 * Try public key authentication with the specified
3854 int got_passphrase; /* need not be kept over crReturn */
3855 if (flags & FLAG_VERBOSE)
3856 c_write_str(ssh, "Trying public key authentication.\r\n");
3857 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3858 logeventf(ssh, "Trying public key \"%s\"",
3859 filename_to_str(s->keyfile));
3860 s->tried_publickey = 1;
3861 got_passphrase = FALSE;
3862 while (!got_passphrase) {
3864 * Get a passphrase, if necessary.
3866 char *passphrase = NULL; /* only written after crReturn */
3868 if (!s->publickey_encrypted) {
3869 if (flags & FLAG_VERBOSE)
3870 c_write_str(ssh, "No passphrase required.\r\n");
3873 int ret; /* need not be kept over crReturn */
3874 s->cur_prompt = new_prompts(ssh->frontend);
3875 s->cur_prompt->to_server = FALSE;
3876 s->cur_prompt->name = dupstr("SSH key passphrase");
3877 add_prompt(s->cur_prompt,
3878 dupprintf("Passphrase for key \"%.100s\": ",
3879 s->publickey_comment), FALSE);
3880 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3883 crWaitUntil(!pktin);
3884 ret = get_userpass_input(s->cur_prompt, in, inlen);
3888 /* Failed to get a passphrase. Terminate. */
3889 free_prompts(s->cur_prompt);
3890 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3894 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3895 free_prompts(s->cur_prompt);
3898 * Try decrypting key with passphrase.
3900 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3901 ret = loadrsakey(s->keyfile, &s->key, passphrase,
3904 smemclr(passphrase, strlen(passphrase));
3908 /* Correct passphrase. */
3909 got_passphrase = TRUE;
3910 } else if (ret == 0) {
3911 c_write_str(ssh, "Couldn't load private key from ");
3912 c_write_str(ssh, filename_to_str(s->keyfile));
3913 c_write_str(ssh, " (");
3914 c_write_str(ssh, error);
3915 c_write_str(ssh, ").\r\n");
3916 got_passphrase = FALSE;
3917 break; /* go and try something else */
3918 } else if (ret == -1) {
3919 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3920 got_passphrase = FALSE;
3923 assert(0 && "unexpected return from loadrsakey()");
3924 got_passphrase = FALSE; /* placate optimisers */
3928 if (got_passphrase) {
3931 * Send a public key attempt.
3933 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3934 PKT_BIGNUM, s->key.modulus, PKT_END);
3937 if (pktin->type == SSH1_SMSG_FAILURE) {
3938 c_write_str(ssh, "Server refused our public key.\r\n");
3939 continue; /* go and try something else */
3941 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3942 bombout(("Bizarre response to offer of public key"));
3948 unsigned char buffer[32];
3949 Bignum challenge, response;
3951 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3952 bombout(("Server's RSA challenge was badly formatted"));
3955 response = rsadecrypt(challenge, &s->key);
3956 freebn(s->key.private_exponent);/* burn the evidence */
3958 for (i = 0; i < 32; i++) {
3959 buffer[i] = bignum_byte(response, 31 - i);
3963 MD5Update(&md5c, buffer, 32);
3964 MD5Update(&md5c, s->session_id, 16);
3965 MD5Final(buffer, &md5c);
3967 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3968 PKT_DATA, buffer, 16, PKT_END);
3975 if (pktin->type == SSH1_SMSG_FAILURE) {
3976 if (flags & FLAG_VERBOSE)
3977 c_write_str(ssh, "Failed to authenticate with"
3978 " our public key.\r\n");
3979 continue; /* go and try something else */
3980 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3981 bombout(("Bizarre response to RSA authentication response"));
3985 break; /* we're through! */
3991 * Otherwise, try various forms of password-like authentication.
3993 s->cur_prompt = new_prompts(ssh->frontend);
3995 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3996 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3997 !s->tis_auth_refused) {
3998 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3999 logevent("Requested TIS authentication");
4000 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4002 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4003 logevent("TIS authentication declined");
4004 if (flags & FLAG_INTERACTIVE)
4005 c_write_str(ssh, "TIS authentication refused.\r\n");
4006 s->tis_auth_refused = 1;
4011 char *instr_suf, *prompt;
4013 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4015 bombout(("TIS challenge packet was badly formed"));
4018 logevent("Received TIS challenge");
4019 s->cur_prompt->to_server = TRUE;
4020 s->cur_prompt->name = dupstr("SSH TIS authentication");
4021 /* Prompt heuristic comes from OpenSSH */
4022 if (memchr(challenge, '\n', challengelen)) {
4023 instr_suf = dupstr("");
4024 prompt = dupprintf("%.*s", challengelen, challenge);
4026 instr_suf = dupprintf("%.*s", challengelen, challenge);
4027 prompt = dupstr("Response: ");
4029 s->cur_prompt->instruction =
4030 dupprintf("Using TIS authentication.%s%s",
4031 (*instr_suf) ? "\n" : "",
4033 s->cur_prompt->instr_reqd = TRUE;
4034 add_prompt(s->cur_prompt, prompt, FALSE);
4038 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4039 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4040 !s->ccard_auth_refused) {
4041 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4042 logevent("Requested CryptoCard authentication");
4043 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4045 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4046 logevent("CryptoCard authentication declined");
4047 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4048 s->ccard_auth_refused = 1;
4053 char *instr_suf, *prompt;
4055 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4057 bombout(("CryptoCard challenge packet was badly formed"));
4060 logevent("Received CryptoCard challenge");
4061 s->cur_prompt->to_server = TRUE;
4062 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4063 s->cur_prompt->name_reqd = FALSE;
4064 /* Prompt heuristic comes from OpenSSH */
4065 if (memchr(challenge, '\n', challengelen)) {
4066 instr_suf = dupstr("");
4067 prompt = dupprintf("%.*s", challengelen, challenge);
4069 instr_suf = dupprintf("%.*s", challengelen, challenge);
4070 prompt = dupstr("Response: ");
4072 s->cur_prompt->instruction =
4073 dupprintf("Using CryptoCard authentication.%s%s",
4074 (*instr_suf) ? "\n" : "",
4076 s->cur_prompt->instr_reqd = TRUE;
4077 add_prompt(s->cur_prompt, prompt, FALSE);
4081 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4082 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4083 bombout(("No supported authentication methods available"));
4086 s->cur_prompt->to_server = TRUE;
4087 s->cur_prompt->name = dupstr("SSH password");
4088 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4089 ssh->username, ssh->savedhost),
4094 * Show password prompt, having first obtained it via a TIS
4095 * or CryptoCard exchange if we're doing TIS or CryptoCard
4099 int ret; /* need not be kept over crReturn */
4100 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4103 crWaitUntil(!pktin);
4104 ret = get_userpass_input(s->cur_prompt, in, inlen);
4109 * Failed to get a password (for example
4110 * because one was supplied on the command line
4111 * which has already failed to work). Terminate.
4113 free_prompts(s->cur_prompt);
4114 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4119 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4121 * Defence against traffic analysis: we send a
4122 * whole bunch of packets containing strings of
4123 * different lengths. One of these strings is the
4124 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4125 * The others are all random data in
4126 * SSH1_MSG_IGNORE packets. This way a passive
4127 * listener can't tell which is the password, and
4128 * hence can't deduce the password length.
4130 * Anybody with a password length greater than 16
4131 * bytes is going to have enough entropy in their
4132 * password that a listener won't find it _that_
4133 * much help to know how long it is. So what we'll
4136 * - if password length < 16, we send 15 packets
4137 * containing string lengths 1 through 15
4139 * - otherwise, we let N be the nearest multiple
4140 * of 8 below the password length, and send 8
4141 * packets containing string lengths N through
4142 * N+7. This won't obscure the order of
4143 * magnitude of the password length, but it will
4144 * introduce a bit of extra uncertainty.
4146 * A few servers can't deal with SSH1_MSG_IGNORE, at
4147 * least in this context. For these servers, we need
4148 * an alternative defence. We make use of the fact
4149 * that the password is interpreted as a C string:
4150 * so we can append a NUL, then some random data.
4152 * A few servers can deal with neither SSH1_MSG_IGNORE
4153 * here _nor_ a padded password string.
4154 * For these servers we are left with no defences
4155 * against password length sniffing.
4157 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4158 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4160 * The server can deal with SSH1_MSG_IGNORE, so
4161 * we can use the primary defence.
4163 int bottom, top, pwlen, i;
4166 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4168 bottom = 0; /* zero length passwords are OK! :-) */
4171 bottom = pwlen & ~7;
4175 assert(pwlen >= bottom && pwlen <= top);
4177 randomstr = snewn(top + 1, char);
4179 for (i = bottom; i <= top; i++) {
4181 defer_packet(ssh, s->pwpkt_type,
4182 PKTT_PASSWORD, PKT_STR,
4183 s->cur_prompt->prompts[0]->result,
4184 PKTT_OTHER, PKT_END);
4186 for (j = 0; j < i; j++) {
4188 randomstr[j] = random_byte();
4189 } while (randomstr[j] == '\0');
4191 randomstr[i] = '\0';
4192 defer_packet(ssh, SSH1_MSG_IGNORE,
4193 PKT_STR, randomstr, PKT_END);
4196 logevent("Sending password with camouflage packets");
4197 ssh_pkt_defersend(ssh);
4200 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4202 * The server can't deal with SSH1_MSG_IGNORE
4203 * but can deal with padded passwords, so we
4204 * can use the secondary defence.
4210 len = strlen(s->cur_prompt->prompts[0]->result);
4211 if (len < sizeof(string)) {
4213 strcpy(string, s->cur_prompt->prompts[0]->result);
4214 len++; /* cover the zero byte */
4215 while (len < sizeof(string)) {
4216 string[len++] = (char) random_byte();
4219 ss = s->cur_prompt->prompts[0]->result;
4221 logevent("Sending length-padded password");
4222 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4223 PKT_INT, len, PKT_DATA, ss, len,
4224 PKTT_OTHER, PKT_END);
4227 * The server is believed unable to cope with
4228 * any of our password camouflage methods.
4231 len = strlen(s->cur_prompt->prompts[0]->result);
4232 logevent("Sending unpadded password");
4233 send_packet(ssh, s->pwpkt_type,
4234 PKTT_PASSWORD, PKT_INT, len,
4235 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4236 PKTT_OTHER, PKT_END);
4239 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4240 PKT_STR, s->cur_prompt->prompts[0]->result,
4241 PKTT_OTHER, PKT_END);
4243 logevent("Sent password");
4244 free_prompts(s->cur_prompt);
4246 if (pktin->type == SSH1_SMSG_FAILURE) {
4247 if (flags & FLAG_VERBOSE)
4248 c_write_str(ssh, "Access denied\r\n");
4249 logevent("Authentication refused");
4250 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4251 bombout(("Strange packet received, type %d", pktin->type));
4257 if (s->publickey_blob) {
4258 sfree(s->publickey_blob);
4259 sfree(s->publickey_comment);
4262 logevent("Authentication successful");
4267 static void ssh_channel_try_eof(struct ssh_channel *c)
4270 assert(c->pending_eof); /* precondition for calling us */
4272 return; /* can't close: not even opened yet */
4273 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4274 return; /* can't send EOF: pending outgoing data */
4276 c->pending_eof = FALSE; /* we're about to send it */
4277 if (ssh->version == 1) {
4278 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4280 c->closes |= CLOSES_SENT_EOF;
4282 struct Packet *pktout;
4283 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4284 ssh2_pkt_adduint32(pktout, c->remoteid);
4285 ssh2_pkt_send(ssh, pktout);
4286 c->closes |= CLOSES_SENT_EOF;
4287 ssh2_channel_check_close(c);
4291 void sshfwd_write_eof(struct ssh_channel *c)
4295 if (ssh->state == SSH_STATE_CLOSED)
4298 if (c->closes & CLOSES_SENT_EOF)
4301 c->pending_eof = TRUE;
4302 ssh_channel_try_eof(c);
4305 void sshfwd_unclean_close(struct ssh_channel *c)
4309 if (ssh->state == SSH_STATE_CLOSED)
4314 x11_close(c->u.x11.s);
4315 logevent("Forwarded X11 connection terminated due to local error");
4318 case CHAN_SOCKDATA_DORMANT:
4319 pfd_close(c->u.pfd.s);
4320 logevent("Forwarded port closed due to local error");
4323 c->type = CHAN_ZOMBIE;
4325 ssh2_channel_check_close(c);
4328 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4332 if (ssh->state == SSH_STATE_CLOSED)
4335 if (ssh->version == 1) {
4336 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4337 PKT_INT, c->remoteid,
4338 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
4339 PKTT_OTHER, PKT_END);
4341 * In SSH-1 we can return 0 here - implying that forwarded
4342 * connections are never individually throttled - because
4343 * the only circumstance that can cause throttling will be
4344 * the whole SSH connection backing up, in which case
4345 * _everything_ will be throttled as a whole.
4349 ssh2_add_channel_data(c, buf, len);
4350 return ssh2_try_send(c);
4354 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4359 if (ssh->state == SSH_STATE_CLOSED)
4362 if (ssh->version == 1) {
4363 buflimit = SSH1_BUFFER_LIMIT;
4365 buflimit = c->v.v2.locmaxwin;
4366 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4368 if (c->throttling_conn && bufsize <= buflimit) {
4369 c->throttling_conn = 0;
4370 ssh_throttle_conn(ssh, -1);
4374 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4376 struct queued_handler *qh = ssh->qhead;
4380 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4383 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4384 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
4387 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4388 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
4392 ssh->qhead = qh->next;
4394 if (ssh->qhead->msg1 > 0) {
4395 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4396 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4398 if (ssh->qhead->msg2 > 0) {
4399 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4400 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4403 ssh->qhead = ssh->qtail = NULL;
4406 qh->handler(ssh, pktin, qh->ctx);
4411 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4412 chandler_fn_t handler, void *ctx)
4414 struct queued_handler *qh;
4416 qh = snew(struct queued_handler);
4419 qh->handler = handler;
4423 if (ssh->qtail == NULL) {
4427 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4428 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4431 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4432 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4435 ssh->qtail->next = qh;
4440 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4442 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4444 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4445 SSH2_MSG_REQUEST_SUCCESS)) {
4446 logeventf(ssh, "Remote port forwarding from %s enabled",
4449 logeventf(ssh, "Remote port forwarding from %s refused",
4452 rpf = del234(ssh->rportfwds, pf);
4454 pf->pfrec->remote = NULL;
4459 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4461 struct ssh_portfwd *epf;
4465 if (!ssh->portfwds) {
4466 ssh->portfwds = newtree234(ssh_portcmp);
4469 * Go through the existing port forwardings and tag them
4470 * with status==DESTROY. Any that we want to keep will be
4471 * re-enabled (status==KEEP) as we go through the
4472 * configuration and find out which bits are the same as
4475 struct ssh_portfwd *epf;
4477 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4478 epf->status = DESTROY;
4481 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
4483 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
4484 char *kp, *kp2, *vp, *vp2;
4485 char address_family, type;
4486 int sport,dport,sserv,dserv;
4487 char *sports, *dports, *saddr, *host;
4491 address_family = 'A';
4493 if (*kp == 'A' || *kp == '4' || *kp == '6')
4494 address_family = *kp++;
4495 if (*kp == 'L' || *kp == 'R')
4498 if ((kp2 = strchr(kp, ':')) != NULL) {
4500 * There's a colon in the middle of the source port
4501 * string, which means that the part before it is
4502 * actually a source address.
4504 saddr = dupprintf("%.*s", (int)(kp2 - kp), kp);
4510 sport = atoi(sports);
4514 sport = net_service_lookup(sports);
4516 logeventf(ssh, "Service lookup failed for source"
4517 " port \"%s\"", sports);
4521 if (type == 'L' && !strcmp(val, "D")) {
4522 /* dynamic forwarding */
4529 /* ordinary forwarding */
4531 vp2 = vp + strcspn(vp, ":");
4532 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
4536 dport = atoi(dports);
4540 dport = net_service_lookup(dports);
4542 logeventf(ssh, "Service lookup failed for destination"
4543 " port \"%s\"", dports);
4548 if (sport && dport) {
4549 /* Set up a description of the source port. */
4550 struct ssh_portfwd *pfrec, *epfrec;
4552 pfrec = snew(struct ssh_portfwd);
4554 pfrec->saddr = saddr;
4555 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4556 pfrec->sport = sport;
4557 pfrec->daddr = host;
4558 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4559 pfrec->dport = dport;
4560 pfrec->local = NULL;
4561 pfrec->remote = NULL;
4562 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4563 address_family == '6' ? ADDRTYPE_IPV6 :
4566 epfrec = add234(ssh->portfwds, pfrec);
4567 if (epfrec != pfrec) {
4568 if (epfrec->status == DESTROY) {
4570 * We already have a port forwarding up and running
4571 * with precisely these parameters. Hence, no need
4572 * to do anything; simply re-tag the existing one
4575 epfrec->status = KEEP;
4578 * Anything else indicates that there was a duplicate
4579 * in our input, which we'll silently ignore.
4581 free_portfwd(pfrec);
4583 pfrec->status = CREATE;
4592 * Now go through and destroy any port forwardings which were
4595 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4596 if (epf->status == DESTROY) {
4599 message = dupprintf("%s port forwarding from %s%s%d",
4600 epf->type == 'L' ? "local" :
4601 epf->type == 'R' ? "remote" : "dynamic",
4602 epf->saddr ? epf->saddr : "",
4603 epf->saddr ? ":" : "",
4606 if (epf->type != 'D') {
4607 char *msg2 = dupprintf("%s to %s:%d", message,
4608 epf->daddr, epf->dport);
4613 logeventf(ssh, "Cancelling %s", message);
4616 /* epf->remote or epf->local may be NULL if setting up a
4617 * forwarding failed. */
4619 struct ssh_rportfwd *rpf = epf->remote;
4620 struct Packet *pktout;
4623 * Cancel the port forwarding at the server
4626 if (ssh->version == 1) {
4628 * We cannot cancel listening ports on the
4629 * server side in SSH-1! There's no message
4630 * to support it. Instead, we simply remove
4631 * the rportfwd record from the local end
4632 * so that any connections the server tries
4633 * to make on it are rejected.
4636 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4637 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4638 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4640 ssh2_pkt_addstring(pktout, epf->saddr);
4641 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4642 /* XXX: rport_acceptall may not represent
4643 * what was used to open the original connection,
4644 * since it's reconfigurable. */
4645 ssh2_pkt_addstring(pktout, "");
4647 ssh2_pkt_addstring(pktout, "localhost");
4649 ssh2_pkt_adduint32(pktout, epf->sport);
4650 ssh2_pkt_send(ssh, pktout);
4653 del234(ssh->rportfwds, rpf);
4655 } else if (epf->local) {
4656 pfd_terminate(epf->local);
4659 delpos234(ssh->portfwds, i);
4661 i--; /* so we don't skip one in the list */
4665 * And finally, set up any new port forwardings (status==CREATE).
4667 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4668 if (epf->status == CREATE) {
4669 char *sportdesc, *dportdesc;
4670 sportdesc = dupprintf("%s%s%s%s%d%s",
4671 epf->saddr ? epf->saddr : "",
4672 epf->saddr ? ":" : "",
4673 epf->sserv ? epf->sserv : "",
4674 epf->sserv ? "(" : "",
4676 epf->sserv ? ")" : "");
4677 if (epf->type == 'D') {
4680 dportdesc = dupprintf("%s:%s%s%d%s",
4682 epf->dserv ? epf->dserv : "",
4683 epf->dserv ? "(" : "",
4685 epf->dserv ? ")" : "");
4688 if (epf->type == 'L') {
4689 const char *err = pfd_addforward(epf->daddr, epf->dport,
4690 epf->saddr, epf->sport,
4693 epf->addressfamily);
4695 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4696 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4697 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4698 sportdesc, dportdesc,
4699 err ? " failed: " : "", err ? err : "");
4700 } else if (epf->type == 'D') {
4701 const char *err = pfd_addforward(NULL, -1,
4702 epf->saddr, epf->sport,
4705 epf->addressfamily);
4707 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4708 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4709 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4711 err ? " failed: " : "", err ? err : "");
4713 struct ssh_rportfwd *pf;
4716 * Ensure the remote port forwardings tree exists.
4718 if (!ssh->rportfwds) {
4719 if (ssh->version == 1)
4720 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4722 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4725 pf = snew(struct ssh_rportfwd);
4726 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4727 pf->dhost[lenof(pf->dhost)-1] = '\0';
4728 pf->dport = epf->dport;
4729 pf->sport = epf->sport;
4730 if (add234(ssh->rportfwds, pf) != pf) {
4731 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4732 epf->daddr, epf->dport);
4735 logeventf(ssh, "Requesting remote port %s"
4736 " forward to %s", sportdesc, dportdesc);
4738 pf->sportdesc = sportdesc;
4743 if (ssh->version == 1) {
4744 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4745 PKT_INT, epf->sport,
4746 PKT_STR, epf->daddr,
4747 PKT_INT, epf->dport,
4749 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4751 ssh_rportfwd_succfail, pf);
4753 struct Packet *pktout;
4754 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4755 ssh2_pkt_addstring(pktout, "tcpip-forward");
4756 ssh2_pkt_addbool(pktout, 1);/* want reply */
4758 ssh2_pkt_addstring(pktout, epf->saddr);
4759 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4760 ssh2_pkt_addstring(pktout, "");
4762 ssh2_pkt_addstring(pktout, "localhost");
4764 ssh2_pkt_adduint32(pktout, epf->sport);
4765 ssh2_pkt_send(ssh, pktout);
4767 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4768 SSH2_MSG_REQUEST_FAILURE,
4769 ssh_rportfwd_succfail, pf);
4778 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4781 int stringlen, bufsize;
4783 ssh_pkt_getstring(pktin, &string, &stringlen);
4784 if (string == NULL) {
4785 bombout(("Incoming terminal data packet was badly formed"));
4789 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4791 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4792 ssh->v1_stdout_throttling = 1;
4793 ssh_throttle_conn(ssh, +1);
4797 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4799 /* Remote side is trying to open a channel to talk to our
4800 * X-Server. Give them back a local channel number. */
4801 struct ssh_channel *c;
4802 int remoteid = ssh_pkt_getuint32(pktin);
4804 logevent("Received X11 connect request");
4805 /* Refuse if X11 forwarding is disabled. */
4806 if (!ssh->X11_fwd_enabled) {
4807 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4808 PKT_INT, remoteid, PKT_END);
4809 logevent("Rejected X11 connect request");
4811 c = snew(struct ssh_channel);
4814 if (x11_init(&c->u.x11.s, ssh->x11disp, c,
4815 NULL, -1, ssh->conf) != NULL) {
4816 logevent("Opening X11 forward connection failed");
4818 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4819 PKT_INT, remoteid, PKT_END);
4822 ("Opening X11 forward connection succeeded");
4823 c->remoteid = remoteid;
4824 c->halfopen = FALSE;
4825 c->localid = alloc_channel_id(ssh);
4827 c->pending_eof = FALSE;
4828 c->throttling_conn = 0;
4829 c->type = CHAN_X11; /* identify channel type */
4830 add234(ssh->channels, c);
4831 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4832 PKT_INT, c->remoteid, PKT_INT,
4833 c->localid, PKT_END);
4834 logevent("Opened X11 forward channel");
4839 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4841 /* Remote side is trying to open a channel to talk to our
4842 * agent. Give them back a local channel number. */
4843 struct ssh_channel *c;
4844 int remoteid = ssh_pkt_getuint32(pktin);
4846 /* Refuse if agent forwarding is disabled. */
4847 if (!ssh->agentfwd_enabled) {
4848 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4849 PKT_INT, remoteid, PKT_END);
4851 c = snew(struct ssh_channel);
4853 c->remoteid = remoteid;
4854 c->halfopen = FALSE;
4855 c->localid = alloc_channel_id(ssh);
4857 c->pending_eof = FALSE;
4858 c->throttling_conn = 0;
4859 c->type = CHAN_AGENT; /* identify channel type */
4860 c->u.a.lensofar = 0;
4861 c->u.a.message = NULL;
4862 c->u.a.outstanding_requests = 0;
4863 add234(ssh->channels, c);
4864 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4865 PKT_INT, c->remoteid, PKT_INT, c->localid,
4870 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4872 /* Remote side is trying to open a channel to talk to a
4873 * forwarded port. Give them back a local channel number. */
4874 struct ssh_rportfwd pf, *pfp;
4880 remoteid = ssh_pkt_getuint32(pktin);
4881 ssh_pkt_getstring(pktin, &host, &hostsize);
4882 port = ssh_pkt_getuint32(pktin);
4884 if (hostsize >= lenof(pf.dhost))
4885 hostsize = lenof(pf.dhost)-1;
4886 memcpy(pf.dhost, host, hostsize);
4887 pf.dhost[hostsize] = '\0';
4889 pfp = find234(ssh->rportfwds, &pf, NULL);
4892 logeventf(ssh, "Rejected remote port open request for %s:%d",
4894 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4895 PKT_INT, remoteid, PKT_END);
4897 struct ssh_channel *c = snew(struct ssh_channel);
4900 logeventf(ssh, "Received remote port open request for %s:%d",
4902 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4903 c, ssh->conf, pfp->pfrec->addressfamily);
4905 logeventf(ssh, "Port open failed: %s", e);
4907 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4908 PKT_INT, remoteid, PKT_END);
4910 c->remoteid = remoteid;
4911 c->halfopen = FALSE;
4912 c->localid = alloc_channel_id(ssh);
4914 c->pending_eof = FALSE;
4915 c->throttling_conn = 0;
4916 c->type = CHAN_SOCKDATA; /* identify channel type */
4917 add234(ssh->channels, c);
4918 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4919 PKT_INT, c->remoteid, PKT_INT,
4920 c->localid, PKT_END);
4921 logevent("Forwarded port opened successfully");
4926 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4928 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4929 unsigned int localid = ssh_pkt_getuint32(pktin);
4930 struct ssh_channel *c;
4932 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4933 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4934 c->remoteid = localid;
4935 c->halfopen = FALSE;
4936 c->type = CHAN_SOCKDATA;
4937 c->throttling_conn = 0;
4938 pfd_confirm(c->u.pfd.s);
4941 if (c && c->pending_eof) {
4943 * We have a pending close on this channel,
4944 * which we decided on before the server acked
4945 * the channel open. So now we know the
4946 * remoteid, we can close it again.
4948 ssh_channel_try_eof(c);
4952 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4954 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4955 struct ssh_channel *c;
4957 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4958 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4959 logevent("Forwarded connection refused by server");
4960 pfd_close(c->u.pfd.s);
4961 del234(ssh->channels, c);
4966 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4968 /* Remote side closes a channel. */
4969 unsigned i = ssh_pkt_getuint32(pktin);
4970 struct ssh_channel *c;
4971 c = find234(ssh->channels, &i, ssh_channelfind);
4972 if (c && !c->halfopen) {
4974 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
4975 !(c->closes & CLOSES_RCVD_EOF)) {
4977 * Received CHANNEL_CLOSE, which we translate into
4980 int send_close = FALSE;
4982 c->closes |= CLOSES_RCVD_EOF;
4987 x11_send_eof(c->u.x11.s);
4993 pfd_send_eof(c->u.pfd.s);
5002 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5003 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5005 c->closes |= CLOSES_SENT_EOF;
5009 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5010 !(c->closes & CLOSES_RCVD_CLOSE)) {
5012 if (!(c->closes & CLOSES_SENT_EOF)) {
5013 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5014 " for which we never sent CHANNEL_CLOSE\n", i));
5017 c->closes |= CLOSES_RCVD_CLOSE;
5020 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5021 !(c->closes & CLOSES_SENT_CLOSE)) {
5022 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5023 PKT_INT, c->remoteid, PKT_END);
5024 c->closes |= CLOSES_SENT_CLOSE;
5027 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5028 ssh_channel_destroy(c);
5030 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5031 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5032 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5037 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5039 /* Data sent down one of our channels. */
5040 int i = ssh_pkt_getuint32(pktin);
5043 struct ssh_channel *c;
5045 ssh_pkt_getstring(pktin, &p, &len);
5047 c = find234(ssh->channels, &i, ssh_channelfind);
5052 bufsize = x11_send(c->u.x11.s, p, len);
5055 bufsize = pfd_send(c->u.pfd.s, p, len);
5058 /* Data for an agent message. Buffer it. */
5060 if (c->u.a.lensofar < 4) {
5061 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5062 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5066 c->u.a.lensofar += l;
5068 if (c->u.a.lensofar == 4) {
5070 4 + GET_32BIT(c->u.a.msglen);
5071 c->u.a.message = snewn(c->u.a.totallen,
5073 memcpy(c->u.a.message, c->u.a.msglen, 4);
5075 if (c->u.a.lensofar >= 4 && len > 0) {
5077 min(c->u.a.totallen - c->u.a.lensofar,
5079 memcpy(c->u.a.message + c->u.a.lensofar, p,
5083 c->u.a.lensofar += l;
5085 if (c->u.a.lensofar == c->u.a.totallen) {
5088 c->u.a.outstanding_requests++;
5089 if (agent_query(c->u.a.message,
5092 ssh_agentf_callback, c))
5093 ssh_agentf_callback(c, reply, replylen);
5094 sfree(c->u.a.message);
5095 c->u.a.lensofar = 0;
5098 bufsize = 0; /* agent channels never back up */
5101 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5102 c->throttling_conn = 1;
5103 ssh_throttle_conn(ssh, +1);
5108 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5110 ssh->exitcode = ssh_pkt_getuint32(pktin);
5111 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5112 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5114 * In case `helpful' firewalls or proxies tack
5115 * extra human-readable text on the end of the
5116 * session which we might mistake for another
5117 * encrypted packet, we close the session once
5118 * we've sent EXIT_CONFIRMATION.
5120 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5123 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5124 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5126 struct Packet *pktout = (struct Packet *)data;
5128 unsigned int arg = 0;
5129 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5130 if (i == lenof(ssh_ttymodes)) return;
5131 switch (ssh_ttymodes[i].type) {
5133 arg = ssh_tty_parse_specchar(val);
5136 arg = ssh_tty_parse_boolean(val);
5139 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5140 ssh2_pkt_addbyte(pktout, arg);
5144 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5145 struct Packet *pktin)
5147 crBegin(ssh->do_ssh1_connection_crstate);
5149 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5150 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5151 ssh1_smsg_stdout_stderr_data;
5153 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5154 ssh1_msg_channel_open_confirmation;
5155 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5156 ssh1_msg_channel_open_failure;
5157 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5158 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5159 ssh1_msg_channel_close;
5160 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5161 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5163 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
5164 logevent("Requesting agent forwarding");
5165 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5169 if (pktin->type != SSH1_SMSG_SUCCESS
5170 && pktin->type != SSH1_SMSG_FAILURE) {
5171 bombout(("Protocol confusion"));
5173 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5174 logevent("Agent forwarding refused");
5176 logevent("Agent forwarding enabled");
5177 ssh->agentfwd_enabled = TRUE;
5178 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5182 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
5183 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5184 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
5185 logevent("Requesting X11 forwarding");
5187 * Note that while we blank the X authentication data here, we don't
5188 * take any special action to blank the start of an X11 channel,
5189 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
5190 * without having session blanking enabled is likely to leak your
5191 * cookie into the log.
5193 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5194 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5195 PKT_STR, ssh->x11disp->remoteauthprotoname,
5197 PKT_STR, ssh->x11disp->remoteauthdatastring,
5199 PKT_INT, ssh->x11disp->screennum,
5202 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5203 PKT_STR, ssh->x11disp->remoteauthprotoname,
5205 PKT_STR, ssh->x11disp->remoteauthdatastring,
5212 if (pktin->type != SSH1_SMSG_SUCCESS
5213 && pktin->type != SSH1_SMSG_FAILURE) {
5214 bombout(("Protocol confusion"));
5216 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5217 logevent("X11 forwarding refused");
5219 logevent("X11 forwarding enabled");
5220 ssh->X11_fwd_enabled = TRUE;
5221 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5225 ssh_setup_portfwd(ssh, ssh->conf);
5226 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5228 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5230 /* Unpick the terminal-speed string. */
5231 /* XXX perhaps we should allow no speeds to be sent. */
5232 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5233 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5234 /* Send the pty request. */
5235 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5236 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5237 ssh_pkt_adduint32(pkt, ssh->term_height);
5238 ssh_pkt_adduint32(pkt, ssh->term_width);
5239 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5240 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5241 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5242 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5243 ssh_pkt_adduint32(pkt, ssh->ispeed);
5244 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5245 ssh_pkt_adduint32(pkt, ssh->ospeed);
5246 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5248 ssh->state = SSH_STATE_INTERMED;
5252 if (pktin->type != SSH1_SMSG_SUCCESS
5253 && pktin->type != SSH1_SMSG_FAILURE) {
5254 bombout(("Protocol confusion"));
5256 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5257 c_write_str(ssh, "Server refused to allocate pty\r\n");
5258 ssh->editing = ssh->echoing = 1;
5260 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5261 ssh->ospeed, ssh->ispeed);
5262 ssh->got_pty = TRUE;
5265 ssh->editing = ssh->echoing = 1;
5268 if (conf_get_int(ssh->conf, CONF_compression)) {
5269 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5273 if (pktin->type != SSH1_SMSG_SUCCESS
5274 && pktin->type != SSH1_SMSG_FAILURE) {
5275 bombout(("Protocol confusion"));
5277 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5278 c_write_str(ssh, "Server refused to compress\r\n");
5280 logevent("Started compression");
5281 ssh->v1_compressing = TRUE;
5282 ssh->cs_comp_ctx = zlib_compress_init();
5283 logevent("Initialised zlib (RFC1950) compression");
5284 ssh->sc_comp_ctx = zlib_decompress_init();
5285 logevent("Initialised zlib (RFC1950) decompression");
5289 * Start the shell or command.
5291 * Special case: if the first-choice command is an SSH-2
5292 * subsystem (hence not usable here) and the second choice
5293 * exists, we fall straight back to that.
5296 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5298 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5299 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5300 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5301 ssh->fallback_cmd = TRUE;
5304 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5306 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5307 logevent("Started session");
5310 ssh->state = SSH_STATE_SESSION;
5311 if (ssh->size_needed)
5312 ssh_size(ssh, ssh->term_width, ssh->term_height);
5313 if (ssh->eof_needed)
5314 ssh_special(ssh, TS_EOF);
5317 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5319 ssh->channels = newtree234(ssh_channelcmp);
5323 * By this point, most incoming packets are already being
5324 * handled by the dispatch table, and we need only pay
5325 * attention to the unusual ones.
5330 if (pktin->type == SSH1_SMSG_SUCCESS) {
5331 /* may be from EXEC_SHELL on some servers */
5332 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5333 /* may be from EXEC_SHELL on some servers
5334 * if no pty is available or in other odd cases. Ignore */
5336 bombout(("Strange packet received: type %d", pktin->type));
5341 int len = min(inlen, 512);
5342 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5343 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
5344 PKTT_OTHER, PKT_END);
5355 * Handle the top-level SSH-2 protocol.
5357 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5362 ssh_pkt_getstring(pktin, &msg, &msglen);
5363 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5366 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5368 /* log reason code in disconnect message */
5372 ssh_pkt_getstring(pktin, &msg, &msglen);
5373 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5376 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5378 /* Do nothing, because we're ignoring it! Duhh. */
5381 static void ssh1_protocol_setup(Ssh ssh)
5386 * Most messages are handled by the coroutines.
5388 for (i = 0; i < 256; i++)
5389 ssh->packet_dispatch[i] = NULL;
5392 * These special message types we install handlers for.
5394 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5395 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5396 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5399 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5400 struct Packet *pktin)
5402 unsigned char *in=(unsigned char*)vin;
5403 if (ssh->state == SSH_STATE_CLOSED)
5406 if (pktin && ssh->packet_dispatch[pktin->type]) {
5407 ssh->packet_dispatch[pktin->type](ssh, pktin);
5411 if (!ssh->protocol_initial_phase_done) {
5412 if (do_ssh1_login(ssh, in, inlen, pktin))
5413 ssh->protocol_initial_phase_done = TRUE;
5418 do_ssh1_connection(ssh, in, inlen, pktin);
5422 * Utility routine for decoding comma-separated strings in KEXINIT.
5424 static int in_commasep_string(char *needle, char *haystack, int haylen)
5427 if (!needle || !haystack) /* protect against null pointers */
5429 needlen = strlen(needle);
5432 * Is it at the start of the string?
5434 if (haylen >= needlen && /* haystack is long enough */
5435 !memcmp(needle, haystack, needlen) && /* initial match */
5436 (haylen == needlen || haystack[needlen] == ',')
5437 /* either , or EOS follows */
5441 * If not, search for the next comma and resume after that.
5442 * If no comma found, terminate.
5444 while (haylen > 0 && *haystack != ',')
5445 haylen--, haystack++;
5448 haylen--, haystack++; /* skip over comma itself */
5453 * Similar routine for checking whether we have the first string in a list.
5455 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5458 if (!needle || !haystack) /* protect against null pointers */
5460 needlen = strlen(needle);
5462 * Is it at the start of the string?
5464 if (haylen >= needlen && /* haystack is long enough */
5465 !memcmp(needle, haystack, needlen) && /* initial match */
5466 (haylen == needlen || haystack[needlen] == ',')
5467 /* either , or EOS follows */
5475 * SSH-2 key creation method.
5476 * (Currently assumes 2 lots of any hash are sufficient to generate
5477 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5479 #define SSH2_MKKEY_ITERS (2)
5480 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5481 unsigned char *keyspace)
5483 const struct ssh_hash *h = ssh->kex->hash;
5485 /* First hlen bytes. */
5487 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5488 hash_mpint(h, s, K);
5489 h->bytes(s, H, h->hlen);
5490 h->bytes(s, &chr, 1);
5491 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5492 h->final(s, keyspace);
5493 /* Next hlen bytes. */
5495 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5496 hash_mpint(h, s, K);
5497 h->bytes(s, H, h->hlen);
5498 h->bytes(s, keyspace, h->hlen);
5499 h->final(s, keyspace + h->hlen);
5503 * Handle the SSH-2 transport layer.
5505 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5506 struct Packet *pktin)
5508 unsigned char *in = (unsigned char *)vin;
5509 struct do_ssh2_transport_state {
5511 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5512 Bignum p, g, e, f, K;
5515 int kex_init_value, kex_reply_value;
5516 const struct ssh_mac **maclist;
5518 const struct ssh2_cipher *cscipher_tobe;
5519 const struct ssh2_cipher *sccipher_tobe;
5520 const struct ssh_mac *csmac_tobe;
5521 const struct ssh_mac *scmac_tobe;
5522 const struct ssh_compress *cscomp_tobe;
5523 const struct ssh_compress *sccomp_tobe;
5524 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5525 int hostkeylen, siglen, rsakeylen;
5526 void *hkey; /* actual host key */
5527 void *rsakey; /* for RSA kex */
5528 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5529 int n_preferred_kex;
5530 const struct ssh_kexes *preferred_kex[KEX_MAX];
5531 int n_preferred_ciphers;
5532 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5533 const struct ssh_compress *preferred_comp;
5534 int userauth_succeeded; /* for delayed compression */
5535 int pending_compression;
5536 int got_session_id, activated_authconn;
5537 struct Packet *pktout;
5542 crState(do_ssh2_transport_state);
5546 s->cscipher_tobe = s->sccipher_tobe = NULL;
5547 s->csmac_tobe = s->scmac_tobe = NULL;
5548 s->cscomp_tobe = s->sccomp_tobe = NULL;
5550 s->got_session_id = s->activated_authconn = FALSE;
5551 s->userauth_succeeded = FALSE;
5552 s->pending_compression = FALSE;
5555 * Be prepared to work around the buggy MAC problem.
5557 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5558 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5560 s->maclist = macs, s->nmacs = lenof(macs);
5563 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5565 int i, j, k, commalist_started;
5568 * Set up the preferred key exchange. (NULL => warn below here)
5570 s->n_preferred_kex = 0;
5571 for (i = 0; i < KEX_MAX; i++) {
5572 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
5574 s->preferred_kex[s->n_preferred_kex++] =
5575 &ssh_diffiehellman_gex;
5578 s->preferred_kex[s->n_preferred_kex++] =
5579 &ssh_diffiehellman_group14;
5582 s->preferred_kex[s->n_preferred_kex++] =
5583 &ssh_diffiehellman_group1;
5586 s->preferred_kex[s->n_preferred_kex++] =
5590 /* Flag for later. Don't bother if it's the last in
5592 if (i < KEX_MAX - 1) {
5593 s->preferred_kex[s->n_preferred_kex++] = NULL;
5600 * Set up the preferred ciphers. (NULL => warn below here)
5602 s->n_preferred_ciphers = 0;
5603 for (i = 0; i < CIPHER_MAX; i++) {
5604 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
5605 case CIPHER_BLOWFISH:
5606 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5609 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
5610 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5614 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5617 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5619 case CIPHER_ARCFOUR:
5620 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5623 /* Flag for later. Don't bother if it's the last in
5625 if (i < CIPHER_MAX - 1) {
5626 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5633 * Set up preferred compression.
5635 if (conf_get_int(ssh->conf, CONF_compression))
5636 s->preferred_comp = &ssh_zlib;
5638 s->preferred_comp = &ssh_comp_none;
5641 * Enable queueing of outgoing auth- or connection-layer
5642 * packets while we are in the middle of a key exchange.
5644 ssh->queueing = TRUE;
5647 * Flag that KEX is in progress.
5649 ssh->kex_in_progress = TRUE;
5652 * Construct and send our key exchange packet.
5654 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5655 for (i = 0; i < 16; i++)
5656 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5657 /* List key exchange algorithms. */
5658 ssh2_pkt_addstring_start(s->pktout);
5659 commalist_started = 0;
5660 for (i = 0; i < s->n_preferred_kex; i++) {
5661 const struct ssh_kexes *k = s->preferred_kex[i];
5662 if (!k) continue; /* warning flag */
5663 for (j = 0; j < k->nkexes; j++) {
5664 if (commalist_started)
5665 ssh2_pkt_addstring_str(s->pktout, ",");
5666 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5667 commalist_started = 1;
5670 /* List server host key algorithms. */
5671 if (!s->got_session_id) {
5673 * In the first key exchange, we list all the algorithms
5674 * we're prepared to cope with.
5676 ssh2_pkt_addstring_start(s->pktout);
5677 for (i = 0; i < lenof(hostkey_algs); i++) {
5678 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5679 if (i < lenof(hostkey_algs) - 1)
5680 ssh2_pkt_addstring_str(s->pktout, ",");
5684 * In subsequent key exchanges, we list only the kex
5685 * algorithm that was selected in the first key exchange,
5686 * so that we keep getting the same host key and hence
5687 * don't have to interrupt the user's session to ask for
5691 ssh2_pkt_addstring(s->pktout, ssh->hostkey->name);
5693 /* List encryption algorithms (client->server then server->client). */
5694 for (k = 0; k < 2; k++) {
5695 ssh2_pkt_addstring_start(s->pktout);
5696 commalist_started = 0;
5697 for (i = 0; i < s->n_preferred_ciphers; i++) {
5698 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5699 if (!c) continue; /* warning flag */
5700 for (j = 0; j < c->nciphers; j++) {
5701 if (commalist_started)
5702 ssh2_pkt_addstring_str(s->pktout, ",");
5703 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5704 commalist_started = 1;
5708 /* List MAC algorithms (client->server then server->client). */
5709 for (j = 0; j < 2; j++) {
5710 ssh2_pkt_addstring_start(s->pktout);
5711 for (i = 0; i < s->nmacs; i++) {
5712 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5713 if (i < s->nmacs - 1)
5714 ssh2_pkt_addstring_str(s->pktout, ",");
5717 /* List client->server compression algorithms,
5718 * then server->client compression algorithms. (We use the
5719 * same set twice.) */
5720 for (j = 0; j < 2; j++) {
5721 ssh2_pkt_addstring_start(s->pktout);
5722 assert(lenof(compressions) > 1);
5723 /* Prefer non-delayed versions */
5724 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5725 /* We don't even list delayed versions of algorithms until
5726 * they're allowed to be used, to avoid a race. See the end of
5728 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
5729 ssh2_pkt_addstring_str(s->pktout, ",");
5730 ssh2_pkt_addstring_str(s->pktout,
5731 s->preferred_comp->delayed_name);
5733 for (i = 0; i < lenof(compressions); i++) {
5734 const struct ssh_compress *c = compressions[i];
5735 if (c != s->preferred_comp) {
5736 ssh2_pkt_addstring_str(s->pktout, ",");
5737 ssh2_pkt_addstring_str(s->pktout, c->name);
5738 if (s->userauth_succeeded && c->delayed_name) {
5739 ssh2_pkt_addstring_str(s->pktout, ",");
5740 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
5745 /* List client->server languages. Empty list. */
5746 ssh2_pkt_addstring_start(s->pktout);
5747 /* List server->client languages. Empty list. */
5748 ssh2_pkt_addstring_start(s->pktout);
5749 /* First KEX packet does _not_ follow, because we're not that brave. */
5750 ssh2_pkt_addbool(s->pktout, FALSE);
5752 ssh2_pkt_adduint32(s->pktout, 0);
5755 s->our_kexinitlen = s->pktout->length - 5;
5756 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5757 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5759 ssh2_pkt_send_noqueue(ssh, s->pktout);
5762 crWaitUntilV(pktin);
5765 * Now examine the other side's KEXINIT to see what we're up
5769 char *str, *preferred;
5772 if (pktin->type != SSH2_MSG_KEXINIT) {
5773 bombout(("expected key exchange packet from server"));
5777 ssh->hostkey = NULL;
5778 s->cscipher_tobe = NULL;
5779 s->sccipher_tobe = NULL;
5780 s->csmac_tobe = NULL;
5781 s->scmac_tobe = NULL;
5782 s->cscomp_tobe = NULL;
5783 s->sccomp_tobe = NULL;
5784 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5786 pktin->savedpos += 16; /* skip garbage cookie */
5787 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5790 for (i = 0; i < s->n_preferred_kex; i++) {
5791 const struct ssh_kexes *k = s->preferred_kex[i];
5795 for (j = 0; j < k->nkexes; j++) {
5796 if (!preferred) preferred = k->list[j]->name;
5797 if (in_commasep_string(k->list[j]->name, str, len)) {
5798 ssh->kex = k->list[j];
5807 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5808 str ? str : "(null)"));
5812 * Note that the server's guess is considered wrong if it doesn't match
5813 * the first algorithm in our list, even if it's still the algorithm
5816 s->guessok = first_in_commasep_string(preferred, str, len);
5817 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5818 for (i = 0; i < lenof(hostkey_algs); i++) {
5819 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5820 ssh->hostkey = hostkey_algs[i];
5824 if (!ssh->hostkey) {
5825 bombout(("Couldn't agree a host key algorithm (available: %s)",
5826 str ? str : "(null)"));
5830 s->guessok = s->guessok &&
5831 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5832 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5833 for (i = 0; i < s->n_preferred_ciphers; i++) {
5834 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5836 s->warn_cscipher = TRUE;
5838 for (j = 0; j < c->nciphers; j++) {
5839 if (in_commasep_string(c->list[j]->name, str, len)) {
5840 s->cscipher_tobe = c->list[j];
5845 if (s->cscipher_tobe)
5848 if (!s->cscipher_tobe) {
5849 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5850 str ? str : "(null)"));
5854 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5855 for (i = 0; i < s->n_preferred_ciphers; i++) {
5856 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5858 s->warn_sccipher = TRUE;
5860 for (j = 0; j < c->nciphers; j++) {
5861 if (in_commasep_string(c->list[j]->name, str, len)) {
5862 s->sccipher_tobe = c->list[j];
5867 if (s->sccipher_tobe)
5870 if (!s->sccipher_tobe) {
5871 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5872 str ? str : "(null)"));
5876 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5877 for (i = 0; i < s->nmacs; i++) {
5878 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5879 s->csmac_tobe = s->maclist[i];
5883 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5884 for (i = 0; i < s->nmacs; i++) {
5885 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5886 s->scmac_tobe = s->maclist[i];
5890 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5891 for (i = 0; i < lenof(compressions) + 1; i++) {
5892 const struct ssh_compress *c =
5893 i == 0 ? s->preferred_comp : compressions[i - 1];
5894 if (in_commasep_string(c->name, str, len)) {
5897 } else if (in_commasep_string(c->delayed_name, str, len)) {
5898 if (s->userauth_succeeded) {
5902 s->pending_compression = TRUE; /* try this later */
5906 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5907 for (i = 0; i < lenof(compressions) + 1; i++) {
5908 const struct ssh_compress *c =
5909 i == 0 ? s->preferred_comp : compressions[i - 1];
5910 if (in_commasep_string(c->name, str, len)) {
5913 } else if (in_commasep_string(c->delayed_name, str, len)) {
5914 if (s->userauth_succeeded) {
5918 s->pending_compression = TRUE; /* try this later */
5922 if (s->pending_compression) {
5923 logevent("Server supports delayed compression; "
5924 "will try this later");
5926 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5927 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5928 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5930 ssh->exhash = ssh->kex->hash->init();
5931 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5932 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5933 hash_string(ssh->kex->hash, ssh->exhash,
5934 s->our_kexinit, s->our_kexinitlen);
5935 sfree(s->our_kexinit);
5936 if (pktin->length > 5)
5937 hash_string(ssh->kex->hash, ssh->exhash,
5938 pktin->data + 5, pktin->length - 5);
5941 ssh_set_frozen(ssh, 1);
5942 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5944 ssh_dialog_callback, ssh);
5945 if (s->dlgret < 0) {
5949 bombout(("Unexpected data from server while"
5950 " waiting for user response"));
5953 } while (pktin || inlen > 0);
5954 s->dlgret = ssh->user_response;
5956 ssh_set_frozen(ssh, 0);
5957 if (s->dlgret == 0) {
5958 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5964 if (s->warn_cscipher) {
5965 ssh_set_frozen(ssh, 1);
5966 s->dlgret = askalg(ssh->frontend,
5967 "client-to-server cipher",
5968 s->cscipher_tobe->name,
5969 ssh_dialog_callback, ssh);
5970 if (s->dlgret < 0) {
5974 bombout(("Unexpected data from server while"
5975 " waiting for user response"));
5978 } while (pktin || inlen > 0);
5979 s->dlgret = ssh->user_response;
5981 ssh_set_frozen(ssh, 0);
5982 if (s->dlgret == 0) {
5983 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5989 if (s->warn_sccipher) {
5990 ssh_set_frozen(ssh, 1);
5991 s->dlgret = askalg(ssh->frontend,
5992 "server-to-client cipher",
5993 s->sccipher_tobe->name,
5994 ssh_dialog_callback, ssh);
5995 if (s->dlgret < 0) {
5999 bombout(("Unexpected data from server while"
6000 " waiting for user response"));
6003 } while (pktin || inlen > 0);
6004 s->dlgret = ssh->user_response;
6006 ssh_set_frozen(ssh, 0);
6007 if (s->dlgret == 0) {
6008 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6014 if (s->ignorepkt) /* first_kex_packet_follows */
6015 crWaitUntilV(pktin); /* Ignore packet */
6018 if (ssh->kex->main_type == KEXTYPE_DH) {
6020 * Work out the number of bits of key we will need from the
6021 * key exchange. We start with the maximum key length of
6027 csbits = s->cscipher_tobe->keylen;
6028 scbits = s->sccipher_tobe->keylen;
6029 s->nbits = (csbits > scbits ? csbits : scbits);
6031 /* The keys only have hlen-bit entropy, since they're based on
6032 * a hash. So cap the key size at hlen bits. */
6033 if (s->nbits > ssh->kex->hash->hlen * 8)
6034 s->nbits = ssh->kex->hash->hlen * 8;
6037 * If we're doing Diffie-Hellman group exchange, start by
6038 * requesting a group.
6040 if (!ssh->kex->pdata) {
6041 logevent("Doing Diffie-Hellman group exchange");
6042 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6044 * Work out how big a DH group we will need to allow that
6047 s->pbits = 512 << ((s->nbits - 1) / 64);
6048 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6049 ssh2_pkt_adduint32(s->pktout, s->pbits);
6050 ssh2_pkt_send_noqueue(ssh, s->pktout);
6052 crWaitUntilV(pktin);
6053 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6054 bombout(("expected key exchange group packet from server"));
6057 s->p = ssh2_pkt_getmp(pktin);
6058 s->g = ssh2_pkt_getmp(pktin);
6059 if (!s->p || !s->g) {
6060 bombout(("unable to read mp-ints from incoming group packet"));
6063 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6064 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6065 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6067 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6068 ssh->kex_ctx = dh_setup_group(ssh->kex);
6069 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6070 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6071 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6072 ssh->kex->groupname);
6075 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6076 ssh->kex->hash->text_name);
6078 * Now generate and send e for Diffie-Hellman.
6080 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6081 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6082 s->pktout = ssh2_pkt_init(s->kex_init_value);
6083 ssh2_pkt_addmp(s->pktout, s->e);
6084 ssh2_pkt_send_noqueue(ssh, s->pktout);
6086 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6087 crWaitUntilV(pktin);
6088 if (pktin->type != s->kex_reply_value) {
6089 bombout(("expected key exchange reply packet from server"));
6092 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6093 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6094 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6095 s->f = ssh2_pkt_getmp(pktin);
6097 bombout(("unable to parse key exchange reply packet"));
6100 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6102 s->K = dh_find_K(ssh->kex_ctx, s->f);
6104 /* We assume everything from now on will be quick, and it might
6105 * involve user interaction. */
6106 set_busy_status(ssh->frontend, BUSY_NOT);
6108 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6109 if (!ssh->kex->pdata) {
6110 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6111 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6112 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6114 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6115 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6117 dh_cleanup(ssh->kex_ctx);
6119 if (!ssh->kex->pdata) {
6124 logeventf(ssh, "Doing RSA key exchange with hash %s",
6125 ssh->kex->hash->text_name);
6126 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6128 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6131 crWaitUntilV(pktin);
6132 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6133 bombout(("expected RSA public key packet from server"));
6137 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6138 hash_string(ssh->kex->hash, ssh->exhash,
6139 s->hostkeydata, s->hostkeylen);
6140 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6144 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6145 s->rsakeydata = snewn(s->rsakeylen, char);
6146 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6149 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6151 sfree(s->rsakeydata);
6152 bombout(("unable to parse RSA public key from server"));
6156 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6159 * Next, set up a shared secret K, of precisely KLEN -
6160 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6161 * RSA key modulus and HLEN is the bit length of the hash
6165 int klen = ssh_rsakex_klen(s->rsakey);
6166 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6168 unsigned char *kstr1, *kstr2, *outstr;
6169 int kstr1len, kstr2len, outstrlen;
6171 s->K = bn_power_2(nbits - 1);
6173 for (i = 0; i < nbits; i++) {
6175 byte = random_byte();
6177 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6181 * Encode this as an mpint.
6183 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6184 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6185 PUT_32BIT(kstr2, kstr1len);
6186 memcpy(kstr2 + 4, kstr1, kstr1len);
6189 * Encrypt it with the given RSA key.
6191 outstrlen = (klen + 7) / 8;
6192 outstr = snewn(outstrlen, unsigned char);
6193 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6194 outstr, outstrlen, s->rsakey);
6197 * And send it off in a return packet.
6199 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6200 ssh2_pkt_addstring_start(s->pktout);
6201 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6202 ssh2_pkt_send_noqueue(ssh, s->pktout);
6204 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6211 ssh_rsakex_freekey(s->rsakey);
6213 crWaitUntilV(pktin);
6214 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6215 sfree(s->rsakeydata);
6216 bombout(("expected signature packet from server"));
6220 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6222 sfree(s->rsakeydata);
6225 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6226 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6227 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6229 ssh->kex_ctx = NULL;
6232 debug(("Exchange hash is:\n"));
6233 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6237 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6238 (char *)s->exchange_hash,
6239 ssh->kex->hash->hlen)) {
6240 bombout(("Server's host key did not match the signature supplied"));
6244 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6245 if (!s->got_session_id) {
6247 * Authenticate remote host: verify host key. (We've already
6248 * checked the signature of the exchange hash.)
6250 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6251 ssh_set_frozen(ssh, 1);
6252 s->dlgret = verify_ssh_host_key(ssh->frontend,
6253 ssh->savedhost, ssh->savedport,
6254 ssh->hostkey->keytype, s->keystr,
6256 ssh_dialog_callback, ssh);
6257 if (s->dlgret < 0) {
6261 bombout(("Unexpected data from server while waiting"
6262 " for user host key response"));
6265 } while (pktin || inlen > 0);
6266 s->dlgret = ssh->user_response;
6268 ssh_set_frozen(ssh, 0);
6269 if (s->dlgret == 0) {
6270 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6274 logevent("Host key fingerprint is:");
6275 logevent(s->fingerprint);
6276 sfree(s->fingerprint);
6278 * Save this host key, to check against the one presented in
6279 * subsequent rekeys.
6281 ssh->hostkey_str = s->keystr;
6284 * In a rekey, we never present an interactive host key
6285 * verification request to the user. Instead, we simply
6286 * enforce that the key we're seeing this time is identical to
6287 * the one we saw before.
6289 if (strcmp(ssh->hostkey_str, s->keystr)) {
6290 bombout(("Host key was different in repeat key exchange"));
6295 ssh->hostkey->freekey(s->hkey);
6298 * The exchange hash from the very first key exchange is also
6299 * the session id, used in session key construction and
6302 if (!s->got_session_id) {
6303 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6304 memcpy(ssh->v2_session_id, s->exchange_hash,
6305 sizeof(s->exchange_hash));
6306 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6307 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6308 s->got_session_id = TRUE;
6312 * Send SSH2_MSG_NEWKEYS.
6314 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6315 ssh2_pkt_send_noqueue(ssh, s->pktout);
6316 ssh->outgoing_data_size = 0; /* start counting from here */
6319 * We've sent client NEWKEYS, so create and initialise
6320 * client-to-server session keys.
6322 if (ssh->cs_cipher_ctx)
6323 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6324 ssh->cscipher = s->cscipher_tobe;
6325 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6327 if (ssh->cs_mac_ctx)
6328 ssh->csmac->free_context(ssh->cs_mac_ctx);
6329 ssh->csmac = s->csmac_tobe;
6330 ssh->cs_mac_ctx = ssh->csmac->make_context();
6332 if (ssh->cs_comp_ctx)
6333 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6334 ssh->cscomp = s->cscomp_tobe;
6335 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6338 * Set IVs on client-to-server keys. Here we use the exchange
6339 * hash from the _first_ key exchange.
6342 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6343 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6344 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6345 assert((ssh->cscipher->keylen+7) / 8 <=
6346 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6347 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6348 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6349 assert(ssh->cscipher->blksize <=
6350 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6351 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6352 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6353 assert(ssh->csmac->len <=
6354 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6355 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6356 smemclr(keyspace, sizeof(keyspace));
6359 logeventf(ssh, "Initialised %.200s client->server encryption",
6360 ssh->cscipher->text_name);
6361 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6362 ssh->csmac->text_name);
6363 if (ssh->cscomp->text_name)
6364 logeventf(ssh, "Initialised %s compression",
6365 ssh->cscomp->text_name);
6368 * Now our end of the key exchange is complete, we can send all
6369 * our queued higher-layer packets.
6371 ssh->queueing = FALSE;
6372 ssh2_pkt_queuesend(ssh);
6375 * Expect SSH2_MSG_NEWKEYS from server.
6377 crWaitUntilV(pktin);
6378 if (pktin->type != SSH2_MSG_NEWKEYS) {
6379 bombout(("expected new-keys packet from server"));
6382 ssh->incoming_data_size = 0; /* start counting from here */
6385 * We've seen server NEWKEYS, so create and initialise
6386 * server-to-client session keys.
6388 if (ssh->sc_cipher_ctx)
6389 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6390 ssh->sccipher = s->sccipher_tobe;
6391 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6393 if (ssh->sc_mac_ctx)
6394 ssh->scmac->free_context(ssh->sc_mac_ctx);
6395 ssh->scmac = s->scmac_tobe;
6396 ssh->sc_mac_ctx = ssh->scmac->make_context();
6398 if (ssh->sc_comp_ctx)
6399 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6400 ssh->sccomp = s->sccomp_tobe;
6401 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6404 * Set IVs on server-to-client keys. Here we use the exchange
6405 * hash from the _first_ key exchange.
6408 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6409 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6410 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6411 assert((ssh->sccipher->keylen+7) / 8 <=
6412 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6413 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6414 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6415 assert(ssh->sccipher->blksize <=
6416 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6417 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6418 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6419 assert(ssh->scmac->len <=
6420 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6421 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6422 smemclr(keyspace, sizeof(keyspace));
6424 logeventf(ssh, "Initialised %.200s server->client encryption",
6425 ssh->sccipher->text_name);
6426 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6427 ssh->scmac->text_name);
6428 if (ssh->sccomp->text_name)
6429 logeventf(ssh, "Initialised %s decompression",
6430 ssh->sccomp->text_name);
6433 * Free shared secret.
6438 * Key exchange is over. Loop straight back round if we have a
6439 * deferred rekey reason.
6441 if (ssh->deferred_rekey_reason) {
6442 logevent(ssh->deferred_rekey_reason);
6444 ssh->deferred_rekey_reason = NULL;
6445 goto begin_key_exchange;
6449 * Otherwise, schedule a timer for our next rekey.
6451 ssh->kex_in_progress = FALSE;
6452 ssh->last_rekey = GETTICKCOUNT();
6453 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
6454 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6458 * Now we're encrypting. Begin returning 1 to the protocol main
6459 * function so that other things can run on top of the
6460 * transport. If we ever see a KEXINIT, we must go back to the
6463 * We _also_ go back to the start if we see pktin==NULL and
6464 * inlen negative, because this is a special signal meaning
6465 * `initiate client-driven rekey', and `in' contains a message
6466 * giving the reason for the rekey.
6468 * inlen==-1 means always initiate a rekey;
6469 * inlen==-2 means that userauth has completed successfully and
6470 * we should consider rekeying (for delayed compression).
6472 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6473 (!pktin && inlen < 0))) {
6475 if (!ssh->protocol_initial_phase_done) {
6476 ssh->protocol_initial_phase_done = TRUE;
6478 * Allow authconn to initialise itself.
6480 do_ssh2_authconn(ssh, NULL, 0, NULL);
6485 logevent("Server initiated key re-exchange");
6489 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6490 * delayed compression, if it's available.
6492 * draft-miller-secsh-compression-delayed-00 says that you
6493 * negotiate delayed compression in the first key exchange, and
6494 * both sides start compressing when the server has sent
6495 * USERAUTH_SUCCESS. This has a race condition -- the server
6496 * can't know when the client has seen it, and thus which incoming
6497 * packets it should treat as compressed.
6499 * Instead, we do the initial key exchange without offering the
6500 * delayed methods, but note if the server offers them; when we
6501 * get here, if a delayed method was available that was higher
6502 * on our list than what we got, we initiate a rekey in which we
6503 * _do_ list the delayed methods (and hopefully get it as a
6504 * result). Subsequent rekeys will do the same.
6506 assert(!s->userauth_succeeded); /* should only happen once */
6507 s->userauth_succeeded = TRUE;
6508 if (!s->pending_compression)
6509 /* Can't see any point rekeying. */
6510 goto wait_for_rekey; /* this is utterly horrid */
6511 /* else fall through to rekey... */
6512 s->pending_compression = FALSE;
6515 * Now we've decided to rekey.
6517 * Special case: if the server bug is set that doesn't
6518 * allow rekeying, we give a different log message and
6519 * continue waiting. (If such a server _initiates_ a rekey,
6520 * we process it anyway!)
6522 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6523 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6525 /* Reset the counters, so that at least this message doesn't
6526 * hit the event log _too_ often. */
6527 ssh->outgoing_data_size = 0;
6528 ssh->incoming_data_size = 0;
6529 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
6531 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6534 goto wait_for_rekey; /* this is still utterly horrid */
6536 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6539 goto begin_key_exchange;
6545 * Add data to an SSH-2 channel output buffer.
6547 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6550 bufchain_add(&c->v.v2.outbuffer, buf, len);
6554 * Attempt to send data on an SSH-2 channel.
6556 static int ssh2_try_send(struct ssh_channel *c)
6559 struct Packet *pktout;
6562 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6565 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6566 if ((unsigned)len > c->v.v2.remwindow)
6567 len = c->v.v2.remwindow;
6568 if ((unsigned)len > c->v.v2.remmaxpkt)
6569 len = c->v.v2.remmaxpkt;
6570 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6571 ssh2_pkt_adduint32(pktout, c->remoteid);
6572 ssh2_pkt_addstring_start(pktout);
6573 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6574 ssh2_pkt_addstring_data(pktout, data, len);
6575 end_log_omission(ssh, pktout);
6576 ssh2_pkt_send(ssh, pktout);
6577 bufchain_consume(&c->v.v2.outbuffer, len);
6578 c->v.v2.remwindow -= len;
6582 * After having sent as much data as we can, return the amount
6585 ret = bufchain_size(&c->v.v2.outbuffer);
6588 * And if there's no data pending but we need to send an EOF, send
6591 if (!ret && c->pending_eof)
6592 ssh_channel_try_eof(c);
6597 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
6600 if (c->closes & CLOSES_SENT_EOF)
6601 return; /* don't send on channels we've EOFed */
6602 bufsize = ssh2_try_send(c);
6605 case CHAN_MAINSESSION:
6606 /* stdin need not receive an unthrottle
6607 * notification since it will be polled */
6610 x11_unthrottle(c->u.x11.s);
6613 /* agent sockets are request/response and need no
6614 * buffer management */
6617 pfd_unthrottle(c->u.pfd.s);
6624 * Set up most of a new ssh_channel for SSH-2.
6626 static void ssh2_channel_init(struct ssh_channel *c)
6629 c->localid = alloc_channel_id(ssh);
6631 c->pending_eof = FALSE;
6632 c->throttling_conn = FALSE;
6633 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6634 conf_get_int(ssh->conf, CONF_ssh_simple) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6635 c->v.v2.chanreq_head = NULL;
6636 c->v.v2.throttle_state = UNTHROTTLED;
6637 bufchain_init(&c->v.v2.outbuffer);
6641 * Construct the common parts of a CHANNEL_OPEN.
6643 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c, char *type)
6645 struct Packet *pktout;
6647 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
6648 ssh2_pkt_addstring(pktout, type);
6649 ssh2_pkt_adduint32(pktout, c->localid);
6650 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
6651 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
6656 * CHANNEL_FAILURE doesn't come with any indication of what message
6657 * caused it, so we have to keep track of the outstanding
6658 * CHANNEL_REQUESTs ourselves.
6660 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
6661 cchandler_fn_t handler, void *ctx)
6663 struct outstanding_channel_request *ocr =
6664 snew(struct outstanding_channel_request);
6666 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
6667 ocr->handler = handler;
6670 if (!c->v.v2.chanreq_head)
6671 c->v.v2.chanreq_head = ocr;
6673 c->v.v2.chanreq_tail->next = ocr;
6674 c->v.v2.chanreq_tail = ocr;
6678 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
6679 * NULL then a reply will be requested and the handler will be called
6680 * when it arrives. The returned packet is ready to have any
6681 * request-specific data added and be sent. Note that if a handler is
6682 * provided, it's essential that the request actually be sent.
6684 * The handler will usually be passed the response packet in pktin.
6685 * If pktin is NULL, this means that no reply will ever be forthcoming
6686 * (e.g. because the entire connection is being destroyed) and the
6687 * handler should free any storage it's holding.
6689 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c, char *type,
6690 cchandler_fn_t handler, void *ctx)
6692 struct Packet *pktout;
6694 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
6695 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6696 ssh2_pkt_adduint32(pktout, c->remoteid);
6697 ssh2_pkt_addstring(pktout, type);
6698 ssh2_pkt_addbool(pktout, handler != NULL);
6699 if (handler != NULL)
6700 ssh2_queue_chanreq_handler(c, handler, ctx);
6705 * Potentially enlarge the window on an SSH-2 channel.
6707 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
6709 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6714 * Never send WINDOW_ADJUST for a channel that the remote side has
6715 * already sent EOF on; there's no point, since it won't be
6716 * sending any more data anyway. Ditto if _we've_ already sent
6719 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6723 * If the remote end has a habit of ignoring maxpkt, limit the
6724 * window so that it has no choice (assuming it doesn't ignore the
6727 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6728 newwin = OUR_V2_MAXPKT;
6731 * Only send a WINDOW_ADJUST if there's significantly more window
6732 * available than the other end thinks there is. This saves us
6733 * sending a WINDOW_ADJUST for every character in a shell session.
6735 * "Significant" is arbitrarily defined as half the window size.
6737 if (newwin / 2 >= c->v.v2.locwindow) {
6738 struct Packet *pktout;
6742 * In order to keep track of how much window the client
6743 * actually has available, we'd like it to acknowledge each
6744 * WINDOW_ADJUST. We can't do that directly, so we accompany
6745 * it with a CHANNEL_REQUEST that has to be acknowledged.
6747 * This is only necessary if we're opening the window wide.
6748 * If we're not, then throughput is being constrained by
6749 * something other than the maximum window size anyway.
6751 if (newwin == c->v.v2.locmaxwin &&
6752 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
6753 up = snew(unsigned);
6754 *up = newwin - c->v.v2.locwindow;
6755 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
6756 ssh2_handle_winadj_response, up);
6757 ssh2_pkt_send(ssh, pktout);
6759 if (c->v.v2.throttle_state != UNTHROTTLED)
6760 c->v.v2.throttle_state = UNTHROTTLING;
6762 /* Pretend the WINDOW_ADJUST was acked immediately. */
6763 c->v.v2.remlocwin = newwin;
6764 c->v.v2.throttle_state = THROTTLED;
6766 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6767 ssh2_pkt_adduint32(pktout, c->remoteid);
6768 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6769 ssh2_pkt_send(ssh, pktout);
6770 c->v.v2.locwindow = newwin;
6775 * Find the channel associated with a message. If there's no channel,
6776 * or it's not properly open, make a noise about it and return NULL.
6778 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6780 unsigned localid = ssh_pkt_getuint32(pktin);
6781 struct ssh_channel *c;
6783 c = find234(ssh->channels, &localid, ssh_channelfind);
6785 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6786 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6787 char *buf = dupprintf("Received %s for %s channel %u",
6788 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6790 c ? "half-open" : "nonexistent", localid);
6791 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6798 static void ssh2_handle_winadj_response(struct ssh_channel *c,
6799 struct Packet *pktin, void *ctx)
6801 unsigned *sizep = ctx;
6804 * Winadj responses should always be failures. However, at least
6805 * one server ("boks_sshd") is known to return SUCCESS for channel
6806 * requests it's never heard of, such as "winadj@putty". Raised
6807 * with foxt.com as bug 090916-090424, but for the sake of a quiet
6808 * life, we don't worry about what kind of response we got.
6811 c->v.v2.remlocwin += *sizep;
6814 * winadj messages are only sent when the window is fully open, so
6815 * if we get an ack of one, we know any pending unthrottle is
6818 if (c->v.v2.throttle_state == UNTHROTTLING)
6819 c->v.v2.throttle_state = UNTHROTTLED;
6822 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
6824 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
6825 struct outstanding_channel_request *ocr;
6828 ocr = c->v.v2.chanreq_head;
6830 ssh2_msg_unexpected(ssh, pktin);
6833 ocr->handler(c, pktin, ocr->ctx);
6834 c->v.v2.chanreq_head = ocr->next;
6837 * We may now initiate channel-closing procedures, if that
6838 * CHANNEL_REQUEST was the last thing outstanding before we send
6841 ssh2_channel_check_close(c);
6844 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6846 struct ssh_channel *c;
6847 c = ssh2_channel_msg(ssh, pktin);
6850 if (!(c->closes & CLOSES_SENT_EOF)) {
6851 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6852 ssh2_try_send_and_unthrottle(ssh, c);
6856 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6860 struct ssh_channel *c;
6861 c = ssh2_channel_msg(ssh, pktin);
6864 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6865 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6866 return; /* extended but not stderr */
6867 ssh_pkt_getstring(pktin, &data, &length);
6870 c->v.v2.locwindow -= length;
6871 c->v.v2.remlocwin -= length;
6873 case CHAN_MAINSESSION:
6875 from_backend(ssh->frontend, pktin->type ==
6876 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6880 bufsize = x11_send(c->u.x11.s, data, length);
6883 bufsize = pfd_send(c->u.pfd.s, data, length);
6886 while (length > 0) {
6887 if (c->u.a.lensofar < 4) {
6888 unsigned int l = min(4 - c->u.a.lensofar,
6890 memcpy(c->u.a.msglen + c->u.a.lensofar,
6894 c->u.a.lensofar += l;
6896 if (c->u.a.lensofar == 4) {
6898 4 + GET_32BIT(c->u.a.msglen);
6899 c->u.a.message = snewn(c->u.a.totallen,
6901 memcpy(c->u.a.message, c->u.a.msglen, 4);
6903 if (c->u.a.lensofar >= 4 && length > 0) {
6905 min(c->u.a.totallen - c->u.a.lensofar,
6907 memcpy(c->u.a.message + c->u.a.lensofar,
6911 c->u.a.lensofar += l;
6913 if (c->u.a.lensofar == c->u.a.totallen) {
6916 c->u.a.outstanding_requests++;
6917 if (agent_query(c->u.a.message,
6920 ssh_agentf_callback, c))
6921 ssh_agentf_callback(c, reply, replylen);
6922 sfree(c->u.a.message);
6923 c->u.a.message = NULL;
6924 c->u.a.lensofar = 0;
6931 * If it looks like the remote end hit the end of its window,
6932 * and we didn't want it to do that, think about using a
6935 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6936 c->v.v2.locmaxwin < 0x40000000)
6937 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6939 * If we are not buffering too much data,
6940 * enlarge the window again at the remote side.
6941 * If we are buffering too much, we may still
6942 * need to adjust the window if the server's
6945 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6946 c->v.v2.locmaxwin - bufsize : 0);
6948 * If we're either buffering way too much data, or if we're
6949 * buffering anything at all and we're in "simple" mode,
6950 * throttle the whole channel.
6952 if ((bufsize > c->v.v2.locmaxwin ||
6953 (conf_get_int(ssh->conf, CONF_ssh_simple) && bufsize > 0)) &&
6954 !c->throttling_conn) {
6955 c->throttling_conn = 1;
6956 ssh_throttle_conn(ssh, +1);
6961 static void ssh_channel_destroy(struct ssh_channel *c)
6966 case CHAN_MAINSESSION:
6967 ssh->mainchan = NULL;
6968 update_specials_menu(ssh->frontend);
6971 if (c->u.x11.s != NULL)
6972 x11_close(c->u.x11.s);
6973 logevent("Forwarded X11 connection terminated");
6976 sfree(c->u.a.message);
6979 if (c->u.pfd.s != NULL)
6980 pfd_close(c->u.pfd.s);
6981 logevent("Forwarded port closed");
6985 del234(ssh->channels, c);
6986 if (ssh->version == 2) {
6987 bufchain_clear(&c->v.v2.outbuffer);
6988 assert(c->v.v2.chanreq_head == NULL);
6993 * See if that was the last channel left open.
6994 * (This is only our termination condition if we're
6995 * not running in -N mode.)
6997 if (ssh->version == 2 &&
6998 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
6999 count234(ssh->channels) == 0) {
7001 * We used to send SSH_MSG_DISCONNECT here,
7002 * because I'd believed that _every_ conforming
7003 * SSH-2 connection had to end with a disconnect
7004 * being sent by at least one side; apparently
7005 * I was wrong and it's perfectly OK to
7006 * unceremoniously slam the connection shut
7007 * when you're done, and indeed OpenSSH feels
7008 * this is more polite than sending a
7009 * DISCONNECT. So now we don't.
7011 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7015 static void ssh2_channel_check_close(struct ssh_channel *c)
7018 struct Packet *pktout;
7020 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
7021 c->type == CHAN_ZOMBIE) &&
7022 !c->v.v2.chanreq_head &&
7023 !(c->closes & CLOSES_SENT_CLOSE)) {
7025 * We have both sent and received EOF (or the channel is a
7026 * zombie), and we have no outstanding channel requests, which
7027 * means the channel is in final wind-up. But we haven't sent
7028 * CLOSE, so let's do so now.
7030 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
7031 ssh2_pkt_adduint32(pktout, c->remoteid);
7032 ssh2_pkt_send(ssh, pktout);
7033 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
7036 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
7037 assert(c->v.v2.chanreq_head == NULL);
7039 * We have both sent and received CLOSE, which means we're
7040 * completely done with the channel.
7042 ssh_channel_destroy(c);
7046 static void ssh2_channel_got_eof(struct ssh_channel *c)
7048 if (c->closes & CLOSES_RCVD_EOF)
7049 return; /* already seen EOF */
7050 c->closes |= CLOSES_RCVD_EOF;
7052 if (c->type == CHAN_X11) {
7053 x11_send_eof(c->u.x11.s);
7054 } else if (c->type == CHAN_AGENT) {
7055 if (c->u.a.outstanding_requests == 0) {
7056 /* Manufacture an outgoing EOF in response to the incoming one. */
7057 sshfwd_write_eof(c);
7059 } else if (c->type == CHAN_SOCKDATA) {
7060 pfd_send_eof(c->u.pfd.s);
7061 } else if (c->type == CHAN_MAINSESSION) {
7064 if (!ssh->sent_console_eof &&
7065 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
7067 * Either from_backend_eof told us that the front end
7068 * wants us to close the outgoing side of the connection
7069 * as soon as we see EOF from the far end, or else we've
7070 * unilaterally decided to do that because we've allocated
7071 * a remote pty and hence EOF isn't a particularly
7072 * meaningful concept.
7074 sshfwd_write_eof(c);
7076 ssh->sent_console_eof = TRUE;
7079 ssh2_channel_check_close(c);
7082 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
7084 struct ssh_channel *c;
7086 c = ssh2_channel_msg(ssh, pktin);
7089 ssh2_channel_got_eof(c);
7092 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7094 struct ssh_channel *c;
7096 c = ssh2_channel_msg(ssh, pktin);
7101 * When we receive CLOSE on a channel, we assume it comes with an
7102 * implied EOF if we haven't seen EOF yet.
7104 ssh2_channel_got_eof(c);
7107 * And we also send an outgoing EOF, if we haven't already, on the
7108 * assumption that CLOSE is a pretty forceful announcement that
7109 * the remote side is doing away with the entire channel. (If it
7110 * had wanted to send us EOF and continue receiving data from us,
7111 * it would have just sent CHANNEL_EOF.)
7113 if (!(c->closes & CLOSES_SENT_EOF)) {
7115 * Make sure we don't read any more from whatever our local
7116 * data source is for this channel.
7119 case CHAN_MAINSESSION:
7120 ssh->send_ok = 0; /* stop trying to read from stdin */
7123 x11_override_throttle(c->u.x11.s, 1);
7126 pfd_override_throttle(c->u.pfd.s, 1);
7131 * Abandon any buffered data we still wanted to send to this
7132 * channel. Receiving a CHANNEL_CLOSE is an indication that
7133 * the server really wants to get on and _destroy_ this
7134 * channel, and it isn't going to send us any further
7135 * WINDOW_ADJUSTs to permit us to send pending stuff.
7137 bufchain_clear(&c->v.v2.outbuffer);
7140 * Send outgoing EOF.
7142 sshfwd_write_eof(c);
7146 * Now process the actual close.
7148 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7149 c->closes |= CLOSES_RCVD_CLOSE;
7150 ssh2_channel_check_close(c);
7154 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7156 struct ssh_channel *c;
7158 c = ssh2_channel_msg(ssh, pktin);
7161 if (c->type != CHAN_SOCKDATA_DORMANT)
7162 return; /* dunno why they're confirming this */
7163 c->remoteid = ssh_pkt_getuint32(pktin);
7164 c->halfopen = FALSE;
7165 c->type = CHAN_SOCKDATA;
7166 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7167 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7169 pfd_confirm(c->u.pfd.s);
7171 ssh_channel_try_eof(c);
7174 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7176 static const char *const reasons[] = {
7177 "<unknown reason code>",
7178 "Administratively prohibited",
7180 "Unknown channel type",
7181 "Resource shortage",
7183 unsigned reason_code;
7184 char *reason_string;
7186 struct ssh_channel *c;
7187 c = ssh2_channel_msg(ssh, pktin);
7190 if (c->type != CHAN_SOCKDATA_DORMANT)
7191 return; /* dunno why they're failing this */
7193 reason_code = ssh_pkt_getuint32(pktin);
7194 if (reason_code >= lenof(reasons))
7195 reason_code = 0; /* ensure reasons[reason_code] in range */
7196 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7197 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7198 reasons[reason_code], reason_length, reason_string);
7200 pfd_close(c->u.pfd.s);
7202 del234(ssh->channels, c);
7206 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7209 int typelen, want_reply;
7210 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7211 struct ssh_channel *c;
7212 struct Packet *pktout;
7214 c = ssh2_channel_msg(ssh, pktin);
7217 ssh_pkt_getstring(pktin, &type, &typelen);
7218 want_reply = ssh2_pkt_getbool(pktin);
7221 * Having got the channel number, we now look at
7222 * the request type string to see if it's something
7225 if (c == ssh->mainchan) {
7227 * We recognise "exit-status" and "exit-signal" on
7228 * the primary channel.
7230 if (typelen == 11 &&
7231 !memcmp(type, "exit-status", 11)) {
7233 ssh->exitcode = ssh_pkt_getuint32(pktin);
7234 logeventf(ssh, "Server sent command exit status %d",
7236 reply = SSH2_MSG_CHANNEL_SUCCESS;
7238 } else if (typelen == 11 &&
7239 !memcmp(type, "exit-signal", 11)) {
7241 int is_plausible = TRUE, is_int = FALSE;
7242 char *fmt_sig = "", *fmt_msg = "";
7244 int msglen = 0, core = FALSE;
7245 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7246 * provide an `int' for the signal, despite its
7247 * having been a `string' in the drafts of RFC 4254 since at
7248 * least 2001. (Fixed in session.c 1.147.) Try to
7249 * infer which we can safely parse it as. */
7251 unsigned char *p = pktin->body +
7253 long len = pktin->length - pktin->savedpos;
7254 unsigned long num = GET_32BIT(p); /* what is it? */
7255 /* If it's 0, it hardly matters; assume string */
7259 int maybe_int = FALSE, maybe_str = FALSE;
7260 #define CHECK_HYPOTHESIS(offset, result) \
7263 int q = toint(offset); \
7264 if (q >= 0 && q+4 <= len) { \
7265 q = toint(q + 4 + GET_32BIT(p+q)); \
7266 if (q >= 0 && q+4 <= len && \
7267 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
7272 CHECK_HYPOTHESIS(4+1, maybe_int);
7273 CHECK_HYPOTHESIS(4+num+1, maybe_str);
7274 #undef CHECK_HYPOTHESIS
7275 if (maybe_int && !maybe_str)
7277 else if (!maybe_int && maybe_str)
7280 /* Crikey. Either or neither. Panic. */
7281 is_plausible = FALSE;
7284 ssh->exitcode = 128; /* means `unknown signal' */
7287 /* Old non-standard OpenSSH. */
7288 int signum = ssh_pkt_getuint32(pktin);
7289 fmt_sig = dupprintf(" %d", signum);
7290 ssh->exitcode = 128 + signum;
7292 /* As per RFC 4254. */
7295 ssh_pkt_getstring(pktin, &sig, &siglen);
7296 /* Signal name isn't supposed to be blank, but
7297 * let's cope gracefully if it is. */
7299 fmt_sig = dupprintf(" \"%.*s\"",
7304 * Really hideous method of translating the
7305 * signal description back into a locally
7306 * meaningful number.
7311 #define TRANSLATE_SIGNAL(s) \
7312 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7313 ssh->exitcode = 128 + SIG ## s
7315 TRANSLATE_SIGNAL(ABRT);
7318 TRANSLATE_SIGNAL(ALRM);
7321 TRANSLATE_SIGNAL(FPE);
7324 TRANSLATE_SIGNAL(HUP);
7327 TRANSLATE_SIGNAL(ILL);
7330 TRANSLATE_SIGNAL(INT);
7333 TRANSLATE_SIGNAL(KILL);
7336 TRANSLATE_SIGNAL(PIPE);
7339 TRANSLATE_SIGNAL(QUIT);
7342 TRANSLATE_SIGNAL(SEGV);
7345 TRANSLATE_SIGNAL(TERM);
7348 TRANSLATE_SIGNAL(USR1);
7351 TRANSLATE_SIGNAL(USR2);
7353 #undef TRANSLATE_SIGNAL
7355 ssh->exitcode = 128;
7357 core = ssh2_pkt_getbool(pktin);
7358 ssh_pkt_getstring(pktin, &msg, &msglen);
7360 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
7362 /* ignore lang tag */
7363 } /* else don't attempt to parse */
7364 logeventf(ssh, "Server exited on signal%s%s%s",
7365 fmt_sig, core ? " (core dumped)" : "",
7367 if (*fmt_sig) sfree(fmt_sig);
7368 if (*fmt_msg) sfree(fmt_msg);
7369 reply = SSH2_MSG_CHANNEL_SUCCESS;
7374 * This is a channel request we don't know
7375 * about, so we now either ignore the request
7376 * or respond with CHANNEL_FAILURE, depending
7379 reply = SSH2_MSG_CHANNEL_FAILURE;
7382 pktout = ssh2_pkt_init(reply);
7383 ssh2_pkt_adduint32(pktout, c->remoteid);
7384 ssh2_pkt_send(ssh, pktout);
7388 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7391 int typelen, want_reply;
7392 struct Packet *pktout;
7394 ssh_pkt_getstring(pktin, &type, &typelen);
7395 want_reply = ssh2_pkt_getbool(pktin);
7398 * We currently don't support any global requests
7399 * at all, so we either ignore the request or
7400 * respond with REQUEST_FAILURE, depending on
7404 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7405 ssh2_pkt_send(ssh, pktout);
7409 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7417 struct ssh_channel *c;
7418 unsigned remid, winsize, pktsize;
7419 struct Packet *pktout;
7421 ssh_pkt_getstring(pktin, &type, &typelen);
7422 c = snew(struct ssh_channel);
7425 remid = ssh_pkt_getuint32(pktin);
7426 winsize = ssh_pkt_getuint32(pktin);
7427 pktsize = ssh_pkt_getuint32(pktin);
7429 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7433 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7434 addrstr = snewn(peeraddrlen+1, char);
7435 memcpy(addrstr, peeraddr, peeraddrlen);
7436 addrstr[peeraddrlen] = '\0';
7437 peerport = ssh_pkt_getuint32(pktin);
7439 logeventf(ssh, "Received X11 connect request from %s:%d",
7442 if (!ssh->X11_fwd_enabled)
7443 error = "X11 forwarding is not enabled";
7444 else if ((x11err = x11_init(&c->u.x11.s, ssh->x11disp, c,
7445 addrstr, peerport, ssh->conf)) != NULL) {
7446 logeventf(ssh, "Local X11 connection failed: %s", x11err);
7447 error = "Unable to open an X11 connection";
7449 logevent("Opening X11 forward connection succeeded");
7454 } else if (typelen == 15 &&
7455 !memcmp(type, "forwarded-tcpip", 15)) {
7456 struct ssh_rportfwd pf, *realpf;
7459 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
7460 pf.sport = ssh_pkt_getuint32(pktin);
7461 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7462 peerport = ssh_pkt_getuint32(pktin);
7463 realpf = find234(ssh->rportfwds, &pf, NULL);
7464 logeventf(ssh, "Received remote port %d open request "
7465 "from %s:%d", pf.sport, peeraddr, peerport);
7466 if (realpf == NULL) {
7467 error = "Remote port is not recognised";
7469 const char *e = pfd_newconnect(&c->u.pfd.s,
7473 realpf->pfrec->addressfamily);
7474 logeventf(ssh, "Attempting to forward remote port to "
7475 "%s:%d", realpf->dhost, realpf->dport);
7477 logeventf(ssh, "Port open failed: %s", e);
7478 error = "Port open failed";
7480 logevent("Forwarded port opened successfully");
7481 c->type = CHAN_SOCKDATA;
7484 } else if (typelen == 22 &&
7485 !memcmp(type, "auth-agent@openssh.com", 22)) {
7486 if (!ssh->agentfwd_enabled)
7487 error = "Agent forwarding is not enabled";
7489 c->type = CHAN_AGENT; /* identify channel type */
7490 c->u.a.lensofar = 0;
7491 c->u.a.message = NULL;
7492 c->u.a.outstanding_requests = 0;
7495 error = "Unsupported channel type requested";
7498 c->remoteid = remid;
7499 c->halfopen = FALSE;
7501 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7502 ssh2_pkt_adduint32(pktout, c->remoteid);
7503 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7504 ssh2_pkt_addstring(pktout, error);
7505 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7506 ssh2_pkt_send(ssh, pktout);
7507 logeventf(ssh, "Rejected channel open: %s", error);
7510 ssh2_channel_init(c);
7511 c->v.v2.remwindow = winsize;
7512 c->v.v2.remmaxpkt = pktsize;
7513 add234(ssh->channels, c);
7514 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7515 ssh2_pkt_adduint32(pktout, c->remoteid);
7516 ssh2_pkt_adduint32(pktout, c->localid);
7517 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7518 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7519 ssh2_pkt_send(ssh, pktout);
7524 * Buffer banner messages for later display at some convenient point,
7525 * if we're going to display them.
7527 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7529 /* Arbitrary limit to prevent unbounded inflation of buffer */
7530 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
7531 bufchain_size(&ssh->banner) <= 131072) {
7532 char *banner = NULL;
7534 ssh_pkt_getstring(pktin, &banner, &size);
7536 bufchain_add(&ssh->banner, banner, size);
7540 /* Helper function to deal with sending tty modes for "pty-req" */
7541 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7543 struct Packet *pktout = (struct Packet *)data;
7545 unsigned int arg = 0;
7546 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7547 if (i == lenof(ssh_ttymodes)) return;
7548 switch (ssh_ttymodes[i].type) {
7550 arg = ssh_tty_parse_specchar(val);
7553 arg = ssh_tty_parse_boolean(val);
7556 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7557 ssh2_pkt_adduint32(pktout, arg);
7560 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
7563 struct ssh2_setup_x11_state {
7567 struct Packet *pktout;
7568 crStateP(ssh2_setup_x11_state, ctx);
7572 logevent("Requesting X11 forwarding");
7573 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
7575 ssh2_pkt_addbool(pktout, 0); /* many connections */
7576 ssh2_pkt_addstring(pktout, ssh->x11disp->remoteauthprotoname);
7578 * Note that while we blank the X authentication data here, we don't
7579 * take any special action to blank the start of an X11 channel,
7580 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
7581 * without having session blanking enabled is likely to leak your
7582 * cookie into the log.
7584 dont_log_password(ssh, pktout, PKTLOG_BLANK);
7585 ssh2_pkt_addstring(pktout, ssh->x11disp->remoteauthdatastring);
7586 end_log_omission(ssh, pktout);
7587 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
7588 ssh2_pkt_send(ssh, pktout);
7590 /* Wait to be called back with either a response packet, or NULL
7591 * meaning clean up and free our data */
7595 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7596 logevent("X11 forwarding enabled");
7597 ssh->X11_fwd_enabled = TRUE;
7599 logevent("X11 forwarding refused");
7605 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
7608 struct ssh2_setup_agent_state {
7612 struct Packet *pktout;
7613 crStateP(ssh2_setup_agent_state, ctx);
7617 logevent("Requesting OpenSSH-style agent forwarding");
7618 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
7619 ssh2_setup_agent, s);
7620 ssh2_pkt_send(ssh, pktout);
7622 /* Wait to be called back with either a response packet, or NULL
7623 * meaning clean up and free our data */
7627 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7628 logevent("Agent forwarding enabled");
7629 ssh->agentfwd_enabled = TRUE;
7631 logevent("Agent forwarding refused");
7637 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
7640 struct ssh2_setup_pty_state {
7644 struct Packet *pktout;
7645 crStateP(ssh2_setup_pty_state, ctx);
7649 /* Unpick the terminal-speed string. */
7650 /* XXX perhaps we should allow no speeds to be sent. */
7651 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
7652 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
7653 /* Build the pty request. */
7654 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
7656 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
7657 ssh2_pkt_adduint32(pktout, ssh->term_width);
7658 ssh2_pkt_adduint32(pktout, ssh->term_height);
7659 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
7660 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
7661 ssh2_pkt_addstring_start(pktout);
7662 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
7663 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
7664 ssh2_pkt_adduint32(pktout, ssh->ispeed);
7665 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
7666 ssh2_pkt_adduint32(pktout, ssh->ospeed);
7667 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
7668 ssh2_pkt_send(ssh, pktout);
7669 ssh->state = SSH_STATE_INTERMED;
7671 /* Wait to be called back with either a response packet, or NULL
7672 * meaning clean up and free our data */
7676 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7677 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
7678 ssh->ospeed, ssh->ispeed);
7679 ssh->got_pty = TRUE;
7681 c_write_str(ssh, "Server refused to allocate pty\r\n");
7682 ssh->editing = ssh->echoing = 1;
7689 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
7692 struct ssh2_setup_env_state {
7694 int num_env, env_left, env_ok;
7697 struct Packet *pktout;
7698 crStateP(ssh2_setup_env_state, ctx);
7703 * Send environment variables.
7705 * Simplest thing here is to send all the requests at once, and
7706 * then wait for a whole bunch of successes or failures.
7712 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
7714 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
7715 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
7716 ssh2_pkt_addstring(pktout, key);
7717 ssh2_pkt_addstring(pktout, val);
7718 ssh2_pkt_send(ssh, pktout);
7723 logeventf(ssh, "Sent %d environment variables", s->num_env);
7728 s->env_left = s->num_env;
7730 while (s->env_left > 0) {
7731 /* Wait to be called back with either a response packet,
7732 * or NULL meaning clean up and free our data */
7734 if (!pktin) goto out;
7735 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
7740 if (s->env_ok == s->num_env) {
7741 logevent("All environment variables successfully set");
7742 } else if (s->env_ok == 0) {
7743 logevent("All environment variables refused");
7744 c_write_str(ssh, "Server refused to set environment variables\r\n");
7746 logeventf(ssh, "%d environment variables refused",
7747 s->num_env - s->env_ok);
7748 c_write_str(ssh, "Server refused to set all environment variables\r\n");
7756 * Handle the SSH-2 userauth and connection layers.
7758 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
7760 do_ssh2_authconn(ssh, NULL, 0, pktin);
7763 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
7766 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
7769 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7770 struct Packet *pktin)
7772 struct do_ssh2_authconn_state {
7776 AUTH_TYPE_PUBLICKEY,
7777 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7778 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7780 AUTH_TYPE_GSSAPI, /* always QUIET */
7781 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7782 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7784 int done_service_req;
7785 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7786 int tried_pubkey_config, done_agent;
7791 int kbd_inter_refused;
7792 int we_are_in, userauth_success;
7793 prompts_t *cur_prompt;
7798 void *publickey_blob;
7799 int publickey_bloblen;
7800 int publickey_encrypted;
7801 char *publickey_algorithm;
7802 char *publickey_comment;
7803 unsigned char agent_request[5], *agent_response, *agentp;
7804 int agent_responselen;
7805 unsigned char *pkblob_in_agent;
7807 char *pkblob, *alg, *commentp;
7808 int pklen, alglen, commentlen;
7809 int siglen, retlen, len;
7810 char *q, *agentreq, *ret;
7812 struct Packet *pktout;
7815 struct ssh_gss_library *gsslib;
7816 Ssh_gss_ctx gss_ctx;
7817 Ssh_gss_buf gss_buf;
7818 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7819 Ssh_gss_name gss_srv_name;
7820 Ssh_gss_stat gss_stat;
7823 crState(do_ssh2_authconn_state);
7827 /* Register as a handler for all the messages this coroutine handles. */
7828 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
7829 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
7830 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
7831 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
7832 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
7833 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
7834 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
7835 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
7836 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
7837 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
7838 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
7839 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
7840 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
7841 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
7842 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
7843 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
7844 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
7845 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
7846 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
7847 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
7849 s->done_service_req = FALSE;
7850 s->we_are_in = s->userauth_success = FALSE;
7852 s->tried_gssapi = FALSE;
7855 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
7857 * Request userauth protocol, and await a response to it.
7859 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7860 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7861 ssh2_pkt_send(ssh, s->pktout);
7862 crWaitUntilV(pktin);
7863 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7864 s->done_service_req = TRUE;
7866 if (!s->done_service_req) {
7868 * Request connection protocol directly, without authentication.
7870 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7871 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7872 ssh2_pkt_send(ssh, s->pktout);
7873 crWaitUntilV(pktin);
7874 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7875 s->we_are_in = TRUE; /* no auth required */
7877 bombout(("Server refused service request"));
7882 /* Arrange to be able to deal with any BANNERs that come in.
7883 * (We do this now as packets may come in during the next bit.) */
7884 bufchain_init(&ssh->banner);
7885 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7886 ssh2_msg_userauth_banner;
7889 * Misc one-time setup for authentication.
7891 s->publickey_blob = NULL;
7892 if (!s->we_are_in) {
7895 * Load the public half of any configured public key file
7898 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
7899 if (!filename_is_null(s->keyfile)) {
7901 logeventf(ssh, "Reading private key file \"%.150s\"",
7902 filename_to_str(s->keyfile));
7903 keytype = key_type(s->keyfile);
7904 if (keytype == SSH_KEYTYPE_SSH2) {
7907 ssh2_userkey_loadpub(s->keyfile,
7908 &s->publickey_algorithm,
7909 &s->publickey_bloblen,
7910 &s->publickey_comment, &error);
7911 if (s->publickey_blob) {
7912 s->publickey_encrypted =
7913 ssh2_userkey_encrypted(s->keyfile, NULL);
7916 logeventf(ssh, "Unable to load private key (%s)",
7918 msgbuf = dupprintf("Unable to load private key file "
7919 "\"%.150s\" (%s)\r\n",
7920 filename_to_str(s->keyfile),
7922 c_write_str(ssh, msgbuf);
7927 logeventf(ssh, "Unable to use this key file (%s)",
7928 key_type_to_str(keytype));
7929 msgbuf = dupprintf("Unable to use key file \"%.150s\""
7931 filename_to_str(s->keyfile),
7932 key_type_to_str(keytype));
7933 c_write_str(ssh, msgbuf);
7935 s->publickey_blob = NULL;
7940 * Find out about any keys Pageant has (but if there's a
7941 * public key configured, filter out all others).
7944 s->agent_response = NULL;
7945 s->pkblob_in_agent = NULL;
7946 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
7950 logevent("Pageant is running. Requesting keys.");
7952 /* Request the keys held by the agent. */
7953 PUT_32BIT(s->agent_request, 1);
7954 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
7955 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
7956 ssh_agent_callback, ssh)) {
7960 bombout(("Unexpected data from server while"
7961 " waiting for agent response"));
7964 } while (pktin || inlen > 0);
7965 r = ssh->agent_response;
7966 s->agent_responselen = ssh->agent_response_len;
7968 s->agent_response = (unsigned char *) r;
7969 if (s->agent_response && s->agent_responselen >= 5 &&
7970 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
7973 p = s->agent_response + 5;
7974 s->nkeys = toint(GET_32BIT(p));
7977 * Vet the Pageant response to ensure that the key
7978 * count and blob lengths make sense.
7981 logeventf(ssh, "Pageant response contained a negative"
7982 " key count %d", s->nkeys);
7984 goto done_agent_query;
7986 unsigned char *q = p + 4;
7987 int lenleft = s->agent_responselen - 5 - 4;
7989 for (keyi = 0; keyi < s->nkeys; keyi++) {
7990 int bloblen, commentlen;
7992 logeventf(ssh, "Pageant response was truncated");
7994 goto done_agent_query;
7996 bloblen = toint(GET_32BIT(q));
7997 if (bloblen < 0 || bloblen > lenleft) {
7998 logeventf(ssh, "Pageant response was truncated");
8000 goto done_agent_query;
8002 lenleft -= 4 + bloblen;
8004 commentlen = toint(GET_32BIT(q));
8005 if (commentlen < 0 || commentlen > lenleft) {
8006 logeventf(ssh, "Pageant response was truncated");
8008 goto done_agent_query;
8010 lenleft -= 4 + commentlen;
8011 q += 4 + commentlen;
8016 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
8017 if (s->publickey_blob) {
8018 /* See if configured key is in agent. */
8019 for (keyi = 0; keyi < s->nkeys; keyi++) {
8020 s->pklen = toint(GET_32BIT(p));
8021 if (s->pklen == s->publickey_bloblen &&
8022 !memcmp(p+4, s->publickey_blob,
8023 s->publickey_bloblen)) {
8024 logeventf(ssh, "Pageant key #%d matches "
8025 "configured key file", keyi);
8027 s->pkblob_in_agent = p;
8031 p += toint(GET_32BIT(p)) + 4; /* comment */
8033 if (!s->pkblob_in_agent) {
8034 logevent("Configured key file not in Pageant");
8039 logevent("Failed to get reply from Pageant");
8047 * We repeat this whole loop, including the username prompt,
8048 * until we manage a successful authentication. If the user
8049 * types the wrong _password_, they can be sent back to the
8050 * beginning to try another username, if this is configured on.
8051 * (If they specify a username in the config, they are never
8052 * asked, even if they do give a wrong password.)
8054 * I think this best serves the needs of
8056 * - the people who have no configuration, no keys, and just
8057 * want to try repeated (username,password) pairs until they
8058 * type both correctly
8060 * - people who have keys and configuration but occasionally
8061 * need to fall back to passwords
8063 * - people with a key held in Pageant, who might not have
8064 * logged in to a particular machine before; so they want to
8065 * type a username, and then _either_ their key will be
8066 * accepted, _or_ they will type a password. If they mistype
8067 * the username they will want to be able to get back and
8070 s->got_username = FALSE;
8071 while (!s->we_are_in) {
8075 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
8077 * We got a username last time round this loop, and
8078 * with change_username turned off we don't try to get
8081 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
8082 int ret; /* need not be kept over crReturn */
8083 s->cur_prompt = new_prompts(ssh->frontend);
8084 s->cur_prompt->to_server = TRUE;
8085 s->cur_prompt->name = dupstr("SSH login name");
8086 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
8087 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8090 crWaitUntilV(!pktin);
8091 ret = get_userpass_input(s->cur_prompt, in, inlen);
8096 * get_userpass_input() failed to get a username.
8099 free_prompts(s->cur_prompt);
8100 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
8103 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
8104 free_prompts(s->cur_prompt);
8107 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
8108 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
8109 c_write_str(ssh, stuff);
8113 s->got_username = TRUE;
8116 * Send an authentication request using method "none": (a)
8117 * just in case it succeeds, and (b) so that we know what
8118 * authentication methods we can usefully try next.
8120 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8122 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8123 ssh2_pkt_addstring(s->pktout, ssh->username);
8124 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
8125 ssh2_pkt_addstring(s->pktout, "none"); /* method */
8126 ssh2_pkt_send(ssh, s->pktout);
8127 s->type = AUTH_TYPE_NONE;
8129 s->we_are_in = FALSE;
8131 s->tried_pubkey_config = FALSE;
8132 s->kbd_inter_refused = FALSE;
8134 /* Reset agent request state. */
8135 s->done_agent = FALSE;
8136 if (s->agent_response) {
8137 if (s->pkblob_in_agent) {
8138 s->agentp = s->pkblob_in_agent;
8140 s->agentp = s->agent_response + 5 + 4;
8146 char *methods = NULL;
8150 * Wait for the result of the last authentication request.
8153 crWaitUntilV(pktin);
8155 * Now is a convenient point to spew any banner material
8156 * that we've accumulated. (This should ensure that when
8157 * we exit the auth loop, we haven't any left to deal
8161 int size = bufchain_size(&ssh->banner);
8163 * Don't show the banner if we're operating in
8164 * non-verbose non-interactive mode. (It's probably
8165 * a script, which means nobody will read the
8166 * banner _anyway_, and moreover the printing of
8167 * the banner will screw up processing on the
8168 * output of (say) plink.)
8170 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
8171 char *banner = snewn(size, char);
8172 bufchain_fetch(&ssh->banner, banner, size);
8173 c_write_untrusted(ssh, banner, size);
8176 bufchain_clear(&ssh->banner);
8178 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
8179 logevent("Access granted");
8180 s->we_are_in = s->userauth_success = TRUE;
8184 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
8185 bombout(("Strange packet received during authentication: "
8186 "type %d", pktin->type));
8193 * OK, we're now sitting on a USERAUTH_FAILURE message, so
8194 * we can look at the string in it and know what we can
8195 * helpfully try next.
8197 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
8198 ssh_pkt_getstring(pktin, &methods, &methlen);
8199 if (!ssh2_pkt_getbool(pktin)) {
8201 * We have received an unequivocal Access
8202 * Denied. This can translate to a variety of
8203 * messages, or no message at all.
8205 * For forms of authentication which are attempted
8206 * implicitly, by which I mean without printing
8207 * anything in the window indicating that we're
8208 * trying them, we should never print 'Access
8211 * If we do print a message saying that we're
8212 * attempting some kind of authentication, it's OK
8213 * to print a followup message saying it failed -
8214 * but the message may sometimes be more specific
8215 * than simply 'Access denied'.
8217 * Additionally, if we'd just tried password
8218 * authentication, we should break out of this
8219 * whole loop so as to go back to the username
8220 * prompt (iff we're configured to allow
8221 * username change attempts).
8223 if (s->type == AUTH_TYPE_NONE) {
8225 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
8226 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
8227 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
8228 c_write_str(ssh, "Server refused our key\r\n");
8229 logevent("Server refused our key");
8230 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
8231 /* This _shouldn't_ happen except by a
8232 * protocol bug causing client and server to
8233 * disagree on what is a correct signature. */
8234 c_write_str(ssh, "Server refused public-key signature"
8235 " despite accepting key!\r\n");
8236 logevent("Server refused public-key signature"
8237 " despite accepting key!");
8238 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
8239 /* quiet, so no c_write */
8240 logevent("Server refused keyboard-interactive authentication");
8241 } else if (s->type==AUTH_TYPE_GSSAPI) {
8242 /* always quiet, so no c_write */
8243 /* also, the code down in the GSSAPI block has
8244 * already logged this in the Event Log */
8245 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
8246 logevent("Keyboard-interactive authentication failed");
8247 c_write_str(ssh, "Access denied\r\n");
8249 assert(s->type == AUTH_TYPE_PASSWORD);
8250 logevent("Password authentication failed");
8251 c_write_str(ssh, "Access denied\r\n");
8253 if (conf_get_int(ssh->conf, CONF_change_username)) {
8254 /* XXX perhaps we should allow
8255 * keyboard-interactive to do this too? */
8256 s->we_are_in = FALSE;
8261 c_write_str(ssh, "Further authentication required\r\n");
8262 logevent("Further authentication required");
8266 in_commasep_string("publickey", methods, methlen);
8268 in_commasep_string("password", methods, methlen);
8269 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
8270 in_commasep_string("keyboard-interactive", methods, methlen);
8273 ssh->gsslibs = ssh_gss_setup(ssh->conf);
8274 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
8275 in_commasep_string("gssapi-with-mic", methods, methlen) &&
8276 ssh->gsslibs->nlibraries > 0;
8280 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8282 if (s->can_pubkey && !s->done_agent && s->nkeys) {
8285 * Attempt public-key authentication using a key from Pageant.
8288 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8290 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
8292 /* Unpack key from agent response */
8293 s->pklen = toint(GET_32BIT(s->agentp));
8295 s->pkblob = (char *)s->agentp;
8296 s->agentp += s->pklen;
8297 s->alglen = toint(GET_32BIT(s->pkblob));
8298 s->alg = s->pkblob + 4;
8299 s->commentlen = toint(GET_32BIT(s->agentp));
8301 s->commentp = (char *)s->agentp;
8302 s->agentp += s->commentlen;
8303 /* s->agentp now points at next key, if any */
8305 /* See if server will accept it */
8306 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8307 ssh2_pkt_addstring(s->pktout, ssh->username);
8308 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8309 /* service requested */
8310 ssh2_pkt_addstring(s->pktout, "publickey");
8312 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
8313 ssh2_pkt_addstring_start(s->pktout);
8314 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
8315 ssh2_pkt_addstring_start(s->pktout);
8316 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
8317 ssh2_pkt_send(ssh, s->pktout);
8318 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
8320 crWaitUntilV(pktin);
8321 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8323 /* Offer of key refused. */
8330 if (flags & FLAG_VERBOSE) {
8331 c_write_str(ssh, "Authenticating with "
8333 c_write(ssh, s->commentp, s->commentlen);
8334 c_write_str(ssh, "\" from agent\r\n");
8338 * Server is willing to accept the key.
8339 * Construct a SIGN_REQUEST.
8341 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8342 ssh2_pkt_addstring(s->pktout, ssh->username);
8343 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8344 /* service requested */
8345 ssh2_pkt_addstring(s->pktout, "publickey");
8347 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
8348 ssh2_pkt_addstring_start(s->pktout);
8349 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
8350 ssh2_pkt_addstring_start(s->pktout);
8351 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
8353 /* Ask agent for signature. */
8354 s->siglen = s->pktout->length - 5 + 4 +
8355 ssh->v2_session_id_len;
8356 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8358 s->len = 1; /* message type */
8359 s->len += 4 + s->pklen; /* key blob */
8360 s->len += 4 + s->siglen; /* data to sign */
8361 s->len += 4; /* flags */
8362 s->agentreq = snewn(4 + s->len, char);
8363 PUT_32BIT(s->agentreq, s->len);
8364 s->q = s->agentreq + 4;
8365 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
8366 PUT_32BIT(s->q, s->pklen);
8368 memcpy(s->q, s->pkblob, s->pklen);
8370 PUT_32BIT(s->q, s->siglen);
8372 /* Now the data to be signed... */
8373 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8374 PUT_32BIT(s->q, ssh->v2_session_id_len);
8377 memcpy(s->q, ssh->v2_session_id,
8378 ssh->v2_session_id_len);
8379 s->q += ssh->v2_session_id_len;
8380 memcpy(s->q, s->pktout->data + 5,
8381 s->pktout->length - 5);
8382 s->q += s->pktout->length - 5;
8383 /* And finally the (zero) flags word. */
8385 if (!agent_query(s->agentreq, s->len + 4,
8387 ssh_agent_callback, ssh)) {
8391 bombout(("Unexpected data from server"
8392 " while waiting for agent"
8396 } while (pktin || inlen > 0);
8397 vret = ssh->agent_response;
8398 s->retlen = ssh->agent_response_len;
8403 if (s->retlen >= 9 &&
8404 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
8405 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
8406 logevent("Sending Pageant's response");
8407 ssh2_add_sigblob(ssh, s->pktout,
8408 s->pkblob, s->pklen,
8410 GET_32BIT(s->ret + 5));
8411 ssh2_pkt_send(ssh, s->pktout);
8412 s->type = AUTH_TYPE_PUBLICKEY;
8414 /* FIXME: less drastic response */
8415 bombout(("Pageant failed to answer challenge"));
8421 /* Do we have any keys left to try? */
8422 if (s->pkblob_in_agent) {
8423 s->done_agent = TRUE;
8424 s->tried_pubkey_config = TRUE;
8427 if (s->keyi >= s->nkeys)
8428 s->done_agent = TRUE;
8431 } else if (s->can_pubkey && s->publickey_blob &&
8432 !s->tried_pubkey_config) {
8434 struct ssh2_userkey *key; /* not live over crReturn */
8435 char *passphrase; /* not live over crReturn */
8437 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8439 s->tried_pubkey_config = TRUE;
8442 * Try the public key supplied in the configuration.
8444 * First, offer the public blob to see if the server is
8445 * willing to accept it.
8447 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8448 ssh2_pkt_addstring(s->pktout, ssh->username);
8449 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8450 /* service requested */
8451 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
8452 ssh2_pkt_addbool(s->pktout, FALSE);
8453 /* no signature included */
8454 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
8455 ssh2_pkt_addstring_start(s->pktout);
8456 ssh2_pkt_addstring_data(s->pktout,
8457 (char *)s->publickey_blob,
8458 s->publickey_bloblen);
8459 ssh2_pkt_send(ssh, s->pktout);
8460 logevent("Offered public key");
8462 crWaitUntilV(pktin);
8463 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8464 /* Key refused. Give up. */
8465 s->gotit = TRUE; /* reconsider message next loop */
8466 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
8467 continue; /* process this new message */
8469 logevent("Offer of public key accepted");
8472 * Actually attempt a serious authentication using
8475 if (flags & FLAG_VERBOSE) {
8476 c_write_str(ssh, "Authenticating with public key \"");
8477 c_write_str(ssh, s->publickey_comment);
8478 c_write_str(ssh, "\"\r\n");
8482 const char *error; /* not live over crReturn */
8483 if (s->publickey_encrypted) {
8485 * Get a passphrase from the user.
8487 int ret; /* need not be kept over crReturn */
8488 s->cur_prompt = new_prompts(ssh->frontend);
8489 s->cur_prompt->to_server = FALSE;
8490 s->cur_prompt->name = dupstr("SSH key passphrase");
8491 add_prompt(s->cur_prompt,
8492 dupprintf("Passphrase for key \"%.100s\": ",
8493 s->publickey_comment),
8495 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8498 crWaitUntilV(!pktin);
8499 ret = get_userpass_input(s->cur_prompt,
8504 /* Failed to get a passphrase. Terminate. */
8505 free_prompts(s->cur_prompt);
8506 ssh_disconnect(ssh, NULL,
8507 "Unable to authenticate",
8508 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8513 dupstr(s->cur_prompt->prompts[0]->result);
8514 free_prompts(s->cur_prompt);
8516 passphrase = NULL; /* no passphrase needed */
8520 * Try decrypting the key.
8522 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8523 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
8525 /* burn the evidence */
8526 smemclr(passphrase, strlen(passphrase));
8529 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
8531 (key == SSH2_WRONG_PASSPHRASE)) {
8532 c_write_str(ssh, "Wrong passphrase\r\n");
8534 /* and loop again */
8536 c_write_str(ssh, "Unable to load private key (");
8537 c_write_str(ssh, error);
8538 c_write_str(ssh, ")\r\n");
8540 break; /* try something else */
8546 unsigned char *pkblob, *sigblob, *sigdata;
8547 int pkblob_len, sigblob_len, sigdata_len;
8551 * We have loaded the private key and the server
8552 * has announced that it's willing to accept it.
8553 * Hallelujah. Generate a signature and send it.
8555 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8556 ssh2_pkt_addstring(s->pktout, ssh->username);
8557 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8558 /* service requested */
8559 ssh2_pkt_addstring(s->pktout, "publickey");
8561 ssh2_pkt_addbool(s->pktout, TRUE);
8562 /* signature follows */
8563 ssh2_pkt_addstring(s->pktout, key->alg->name);
8564 pkblob = key->alg->public_blob(key->data,
8566 ssh2_pkt_addstring_start(s->pktout);
8567 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
8571 * The data to be signed is:
8575 * followed by everything so far placed in the
8578 sigdata_len = s->pktout->length - 5 + 4 +
8579 ssh->v2_session_id_len;
8580 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8582 sigdata = snewn(sigdata_len, unsigned char);
8584 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8585 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
8588 memcpy(sigdata+p, ssh->v2_session_id,
8589 ssh->v2_session_id_len);
8590 p += ssh->v2_session_id_len;
8591 memcpy(sigdata+p, s->pktout->data + 5,
8592 s->pktout->length - 5);
8593 p += s->pktout->length - 5;
8594 assert(p == sigdata_len);
8595 sigblob = key->alg->sign(key->data, (char *)sigdata,
8596 sigdata_len, &sigblob_len);
8597 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
8598 sigblob, sigblob_len);
8603 ssh2_pkt_send(ssh, s->pktout);
8604 logevent("Sent public key signature");
8605 s->type = AUTH_TYPE_PUBLICKEY;
8606 key->alg->freekey(key->data);
8610 } else if (s->can_gssapi && !s->tried_gssapi) {
8612 /* GSSAPI Authentication */
8617 s->type = AUTH_TYPE_GSSAPI;
8618 s->tried_gssapi = TRUE;
8620 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
8623 * Pick the highest GSS library on the preference
8629 for (i = 0; i < ngsslibs; i++) {
8630 int want_id = conf_get_int_int(ssh->conf,
8631 CONF_ssh_gsslist, i);
8632 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
8633 if (ssh->gsslibs->libraries[j].id == want_id) {
8634 s->gsslib = &ssh->gsslibs->libraries[j];
8635 goto got_gsslib; /* double break */
8640 * We always expect to have found something in
8641 * the above loop: we only came here if there
8642 * was at least one viable GSS library, and the
8643 * preference list should always mention
8644 * everything and only change the order.
8649 if (s->gsslib->gsslogmsg)
8650 logevent(s->gsslib->gsslogmsg);
8652 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8653 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8654 ssh2_pkt_addstring(s->pktout, ssh->username);
8655 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8656 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
8657 logevent("Attempting GSSAPI authentication");
8659 /* add mechanism info */
8660 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
8662 /* number of GSSAPI mechanisms */
8663 ssh2_pkt_adduint32(s->pktout,1);
8665 /* length of OID + 2 */
8666 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
8667 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
8670 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
8672 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
8674 ssh2_pkt_send(ssh, s->pktout);
8675 crWaitUntilV(pktin);
8676 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
8677 logevent("GSSAPI authentication request refused");
8681 /* check returned packet ... */
8683 ssh_pkt_getstring(pktin, &data, &len);
8684 s->gss_rcvtok.value = data;
8685 s->gss_rcvtok.length = len;
8686 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
8687 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
8688 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
8689 memcmp((char *)s->gss_rcvtok.value + 2,
8690 s->gss_buf.value,s->gss_buf.length) ) {
8691 logevent("GSSAPI authentication - wrong response from server");
8695 /* now start running */
8696 s->gss_stat = s->gsslib->import_name(s->gsslib,
8699 if (s->gss_stat != SSH_GSS_OK) {
8700 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
8701 logevent("GSSAPI import name failed - Bad service name");
8703 logevent("GSSAPI import name failed");
8707 /* fetch TGT into GSS engine */
8708 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
8710 if (s->gss_stat != SSH_GSS_OK) {
8711 logevent("GSSAPI authentication failed to get credentials");
8712 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8716 /* initial tokens are empty */
8717 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
8718 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
8720 /* now enter the loop */
8722 s->gss_stat = s->gsslib->init_sec_context
8726 conf_get_int(ssh->conf, CONF_gssapifwd),
8730 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
8731 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
8732 logevent("GSSAPI authentication initialisation failed");
8734 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
8735 &s->gss_buf) == SSH_GSS_OK) {
8736 logevent(s->gss_buf.value);
8737 sfree(s->gss_buf.value);
8742 logevent("GSSAPI authentication initialised");
8744 /* Client and server now exchange tokens until GSSAPI
8745 * no longer says CONTINUE_NEEDED */
8747 if (s->gss_sndtok.length != 0) {
8748 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8749 ssh_pkt_addstring_start(s->pktout);
8750 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
8751 ssh2_pkt_send(ssh, s->pktout);
8752 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
8755 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8756 crWaitUntilV(pktin);
8757 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8758 logevent("GSSAPI authentication - bad server response");
8759 s->gss_stat = SSH_GSS_FAILURE;
8762 ssh_pkt_getstring(pktin, &data, &len);
8763 s->gss_rcvtok.value = data;
8764 s->gss_rcvtok.length = len;
8766 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8768 if (s->gss_stat != SSH_GSS_OK) {
8769 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8770 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8773 logevent("GSSAPI authentication loop finished OK");
8775 /* Now send the MIC */
8777 s->pktout = ssh2_pkt_init(0);
8778 micoffset = s->pktout->length;
8779 ssh_pkt_addstring_start(s->pktout);
8780 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8781 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
8782 ssh_pkt_addstring(s->pktout, ssh->username);
8783 ssh_pkt_addstring(s->pktout, "ssh-connection");
8784 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8786 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8787 s->gss_buf.length = s->pktout->length - micoffset;
8789 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
8790 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8791 ssh_pkt_addstring_start(s->pktout);
8792 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
8793 ssh2_pkt_send(ssh, s->pktout);
8794 s->gsslib->free_mic(s->gsslib, &mic);
8798 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8799 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8802 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8805 * Keyboard-interactive authentication.
8808 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8810 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
8812 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8813 ssh2_pkt_addstring(s->pktout, ssh->username);
8814 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8815 /* service requested */
8816 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8818 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8819 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8820 ssh2_pkt_send(ssh, s->pktout);
8822 logevent("Attempting keyboard-interactive authentication");
8824 crWaitUntilV(pktin);
8825 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8826 /* Server is not willing to do keyboard-interactive
8827 * at all (or, bizarrely but legally, accepts the
8828 * user without actually issuing any prompts).
8829 * Give up on it entirely. */
8831 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8832 s->kbd_inter_refused = TRUE; /* don't try it again */
8837 * Loop while the server continues to send INFO_REQUESTs.
8839 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
8841 char *name, *inst, *lang;
8842 int name_len, inst_len, lang_len;
8846 * We've got a fresh USERAUTH_INFO_REQUEST.
8847 * Get the preamble and start building a prompt.
8849 ssh_pkt_getstring(pktin, &name, &name_len);
8850 ssh_pkt_getstring(pktin, &inst, &inst_len);
8851 ssh_pkt_getstring(pktin, &lang, &lang_len);
8852 s->cur_prompt = new_prompts(ssh->frontend);
8853 s->cur_prompt->to_server = TRUE;
8856 * Get any prompt(s) from the packet.
8858 s->num_prompts = ssh_pkt_getuint32(pktin);
8859 for (i = 0; i < s->num_prompts; i++) {
8863 static char noprompt[] =
8864 "<server failed to send prompt>: ";
8866 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8867 echo = ssh2_pkt_getbool(pktin);
8870 prompt_len = lenof(noprompt)-1;
8872 add_prompt(s->cur_prompt,
8873 dupprintf("%.*s", prompt_len, prompt),
8878 /* FIXME: better prefix to distinguish from
8880 s->cur_prompt->name =
8881 dupprintf("SSH server: %.*s", name_len, name);
8882 s->cur_prompt->name_reqd = TRUE;
8884 s->cur_prompt->name =
8885 dupstr("SSH server authentication");
8886 s->cur_prompt->name_reqd = FALSE;
8888 /* We add a prefix to try to make it clear that a prompt
8889 * has come from the server.
8890 * FIXME: ugly to print "Using..." in prompt _every_
8891 * time round. Can this be done more subtly? */
8892 /* Special case: for reasons best known to themselves,
8893 * some servers send k-i requests with no prompts and
8894 * nothing to display. Keep quiet in this case. */
8895 if (s->num_prompts || name_len || inst_len) {
8896 s->cur_prompt->instruction =
8897 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8898 inst_len ? "\n" : "", inst_len, inst);
8899 s->cur_prompt->instr_reqd = TRUE;
8901 s->cur_prompt->instr_reqd = FALSE;
8905 * Display any instructions, and get the user's
8909 int ret; /* not live over crReturn */
8910 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8913 crWaitUntilV(!pktin);
8914 ret = get_userpass_input(s->cur_prompt, in, inlen);
8919 * Failed to get responses. Terminate.
8921 free_prompts(s->cur_prompt);
8922 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8923 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8930 * Send the response(s) to the server.
8932 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
8933 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
8934 for (i=0; i < s->num_prompts; i++) {
8935 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8936 ssh2_pkt_addstring(s->pktout,
8937 s->cur_prompt->prompts[i]->result);
8938 end_log_omission(ssh, s->pktout);
8940 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8943 * Free the prompts structure from this iteration.
8944 * If there's another, a new one will be allocated
8945 * when we return to the top of this while loop.
8947 free_prompts(s->cur_prompt);
8950 * Get the next packet in case it's another
8953 crWaitUntilV(pktin);
8958 * We should have SUCCESS or FAILURE now.
8962 } else if (s->can_passwd) {
8965 * Plain old password authentication.
8967 int ret; /* not live over crReturn */
8968 int changereq_first_time; /* not live over crReturn */
8970 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
8972 s->cur_prompt = new_prompts(ssh->frontend);
8973 s->cur_prompt->to_server = TRUE;
8974 s->cur_prompt->name = dupstr("SSH password");
8975 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
8980 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8983 crWaitUntilV(!pktin);
8984 ret = get_userpass_input(s->cur_prompt, in, inlen);
8989 * Failed to get responses. Terminate.
8991 free_prompts(s->cur_prompt);
8992 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8993 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8998 * Squirrel away the password. (We may need it later if
8999 * asked to change it.)
9001 s->password = dupstr(s->cur_prompt->prompts[0]->result);
9002 free_prompts(s->cur_prompt);
9005 * Send the password packet.
9007 * We pad out the password packet to 256 bytes to make
9008 * it harder for an attacker to find the length of the
9011 * Anyone using a password longer than 256 bytes
9012 * probably doesn't have much to worry about from
9013 * people who find out how long their password is!
9015 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9016 ssh2_pkt_addstring(s->pktout, ssh->username);
9017 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9018 /* service requested */
9019 ssh2_pkt_addstring(s->pktout, "password");
9020 ssh2_pkt_addbool(s->pktout, FALSE);
9021 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
9022 ssh2_pkt_addstring(s->pktout, s->password);
9023 end_log_omission(ssh, s->pktout);
9024 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9025 logevent("Sent password");
9026 s->type = AUTH_TYPE_PASSWORD;
9029 * Wait for next packet, in case it's a password change
9032 crWaitUntilV(pktin);
9033 changereq_first_time = TRUE;
9035 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
9038 * We're being asked for a new password
9039 * (perhaps not for the first time).
9040 * Loop until the server accepts it.
9043 int got_new = FALSE; /* not live over crReturn */
9044 char *prompt; /* not live over crReturn */
9045 int prompt_len; /* not live over crReturn */
9049 if (changereq_first_time)
9050 msg = "Server requested password change";
9052 msg = "Server rejected new password";
9054 c_write_str(ssh, msg);
9055 c_write_str(ssh, "\r\n");
9058 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9060 s->cur_prompt = new_prompts(ssh->frontend);
9061 s->cur_prompt->to_server = TRUE;
9062 s->cur_prompt->name = dupstr("New SSH password");
9063 s->cur_prompt->instruction =
9064 dupprintf("%.*s", prompt_len, prompt);
9065 s->cur_prompt->instr_reqd = TRUE;
9067 * There's no explicit requirement in the protocol
9068 * for the "old" passwords in the original and
9069 * password-change messages to be the same, and
9070 * apparently some Cisco kit supports password change
9071 * by the user entering a blank password originally
9072 * and the real password subsequently, so,
9073 * reluctantly, we prompt for the old password again.
9075 * (On the other hand, some servers don't even bother
9076 * to check this field.)
9078 add_prompt(s->cur_prompt,
9079 dupstr("Current password (blank for previously entered password): "),
9081 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
9083 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
9087 * Loop until the user manages to enter the same
9092 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9095 crWaitUntilV(!pktin);
9096 ret = get_userpass_input(s->cur_prompt, in, inlen);
9101 * Failed to get responses. Terminate.
9103 /* burn the evidence */
9104 free_prompts(s->cur_prompt);
9105 smemclr(s->password, strlen(s->password));
9107 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9108 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9114 * If the user specified a new original password
9115 * (IYSWIM), overwrite any previously specified
9117 * (A side effect is that the user doesn't have to
9118 * re-enter it if they louse up the new password.)
9120 if (s->cur_prompt->prompts[0]->result[0]) {
9121 smemclr(s->password, strlen(s->password));
9122 /* burn the evidence */
9125 dupstr(s->cur_prompt->prompts[0]->result);
9129 * Check the two new passwords match.
9131 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
9132 s->cur_prompt->prompts[2]->result)
9135 /* They don't. Silly user. */
9136 c_write_str(ssh, "Passwords do not match\r\n");
9141 * Send the new password (along with the old one).
9142 * (see above for padding rationale)
9144 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9145 ssh2_pkt_addstring(s->pktout, ssh->username);
9146 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9147 /* service requested */
9148 ssh2_pkt_addstring(s->pktout, "password");
9149 ssh2_pkt_addbool(s->pktout, TRUE);
9150 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
9151 ssh2_pkt_addstring(s->pktout, s->password);
9152 ssh2_pkt_addstring(s->pktout,
9153 s->cur_prompt->prompts[1]->result);
9154 free_prompts(s->cur_prompt);
9155 end_log_omission(ssh, s->pktout);
9156 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9157 logevent("Sent new password");
9160 * Now see what the server has to say about it.
9161 * (If it's CHANGEREQ again, it's not happy with the
9164 crWaitUntilV(pktin);
9165 changereq_first_time = FALSE;
9170 * We need to reexamine the current pktin at the top
9171 * of the loop. Either:
9172 * - we weren't asked to change password at all, in
9173 * which case it's a SUCCESS or FAILURE with the
9175 * - we sent a new password, and the server was
9176 * either OK with it (SUCCESS or FAILURE w/partial
9177 * success) or unhappy with the _old_ password
9178 * (FAILURE w/o partial success)
9179 * In any of these cases, we go back to the top of
9180 * the loop and start again.
9185 * We don't need the old password any more, in any
9186 * case. Burn the evidence.
9188 smemclr(s->password, strlen(s->password));
9192 char *str = dupprintf("No supported authentication methods available"
9193 " (server sent: %.*s)",
9196 ssh_disconnect(ssh, str,
9197 "No supported authentication methods available",
9198 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
9208 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
9210 /* Clear up various bits and pieces from authentication. */
9211 if (s->publickey_blob) {
9212 sfree(s->publickey_blob);
9213 sfree(s->publickey_comment);
9215 if (s->agent_response)
9216 sfree(s->agent_response);
9218 if (s->userauth_success) {
9220 * We've just received USERAUTH_SUCCESS, and we haven't sent any
9221 * packets since. Signal the transport layer to consider enacting
9222 * delayed compression.
9224 * (Relying on we_are_in is not sufficient, as
9225 * draft-miller-secsh-compression-delayed is quite clear that it
9226 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
9227 * become set for other reasons.)
9229 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
9233 * Now the connection protocol has started, one way or another.
9236 ssh->channels = newtree234(ssh_channelcmp);
9239 * Set up handlers for some connection protocol messages, so we
9240 * don't have to handle them repeatedly in this coroutine.
9242 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
9243 ssh2_msg_channel_window_adjust;
9244 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
9245 ssh2_msg_global_request;
9248 * Create the main session channel.
9250 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
9251 ssh->mainchan = NULL;
9253 ssh->mainchan = snew(struct ssh_channel);
9254 ssh->mainchan->ssh = ssh;
9255 ssh2_channel_init(ssh->mainchan);
9257 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
9259 * Just start a direct-tcpip channel and use it as the main
9262 ssh_send_port_open(ssh->mainchan,
9263 conf_get_str(ssh->conf, CONF_ssh_nc_host),
9264 conf_get_int(ssh->conf, CONF_ssh_nc_port),
9268 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
9269 logevent("Opening session as main channel");
9270 ssh2_pkt_send(ssh, s->pktout);
9271 ssh->ncmode = FALSE;
9273 crWaitUntilV(pktin);
9274 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
9275 bombout(("Server refused to open channel"));
9277 /* FIXME: error data comes back in FAILURE packet */
9279 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
9280 bombout(("Server's channel confirmation cited wrong channel"));
9283 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
9284 ssh->mainchan->halfopen = FALSE;
9285 ssh->mainchan->type = CHAN_MAINSESSION;
9286 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
9287 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
9288 add234(ssh->channels, ssh->mainchan);
9289 update_specials_menu(ssh->frontend);
9290 logevent("Opened main channel");
9294 * Now we have a channel, make dispatch table entries for
9295 * general channel-based messages.
9297 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
9298 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
9299 ssh2_msg_channel_data;
9300 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
9301 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
9302 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
9303 ssh2_msg_channel_open_confirmation;
9304 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
9305 ssh2_msg_channel_open_failure;
9306 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
9307 ssh2_msg_channel_request;
9308 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
9309 ssh2_msg_channel_open;
9310 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
9311 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
9314 if (ssh->mainchan && conf_get_int(ssh->conf, CONF_ssh_simple)) {
9316 * This message indicates to the server that we promise
9317 * not to try to run any other channel in parallel with
9318 * this one, so it's safe for it to advertise a very large
9319 * window and leave the flow control to TCP.
9321 s->pktout = ssh2_chanreq_init(ssh->mainchan,
9322 "simple@putty.projects.tartarus.org",
9324 ssh2_pkt_send(ssh, s->pktout);
9328 * Enable port forwardings.
9330 ssh_setup_portfwd(ssh, ssh->conf);
9332 if (ssh->mainchan && !ssh->ncmode) {
9334 * Send the CHANNEL_REQUESTS for the main session channel.
9335 * Each one is handled by its own little asynchronous
9339 /* Potentially enable X11 forwarding. */
9340 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
9342 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
9343 conf_get_int(ssh->conf, CONF_x11_auth),
9345 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
9347 /* Potentially enable agent forwarding. */
9348 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists())
9349 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
9351 /* Now allocate a pty for the session. */
9352 if (!conf_get_int(ssh->conf, CONF_nopty))
9353 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
9355 /* Send environment variables. */
9356 ssh2_setup_env(ssh->mainchan, NULL, NULL);
9359 * Start a shell or a remote command. We may have to attempt
9360 * this twice if the config data has provided a second choice
9367 if (ssh->fallback_cmd) {
9368 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
9369 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
9371 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
9372 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
9376 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
9377 ssh2_response_authconn, NULL);
9378 ssh2_pkt_addstring(s->pktout, cmd);
9380 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
9381 ssh2_response_authconn, NULL);
9382 ssh2_pkt_addstring(s->pktout, cmd);
9384 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
9385 ssh2_response_authconn, NULL);
9387 ssh2_pkt_send(ssh, s->pktout);
9389 crWaitUntilV(pktin);
9391 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9392 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9393 bombout(("Unexpected response to shell/command request:"
9394 " packet type %d", pktin->type));
9398 * We failed to start the command. If this is the
9399 * fallback command, we really are finished; if it's
9400 * not, and if the fallback command exists, try falling
9401 * back to it before complaining.
9403 if (!ssh->fallback_cmd &&
9404 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
9405 logevent("Primary command failed; attempting fallback");
9406 ssh->fallback_cmd = TRUE;
9409 bombout(("Server refused to start a shell/command"));
9412 logevent("Started a shell/command");
9417 ssh->editing = ssh->echoing = TRUE;
9420 ssh->state = SSH_STATE_SESSION;
9421 if (ssh->size_needed)
9422 ssh_size(ssh, ssh->term_width, ssh->term_height);
9423 if (ssh->eof_needed)
9424 ssh_special(ssh, TS_EOF);
9430 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
9435 s->try_send = FALSE;
9439 * _All_ the connection-layer packets we expect to
9440 * receive are now handled by the dispatch table.
9441 * Anything that reaches here must be bogus.
9444 bombout(("Strange packet received: type %d", pktin->type));
9446 } else if (ssh->mainchan) {
9448 * We have spare data. Add it to the channel buffer.
9450 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
9455 struct ssh_channel *c;
9457 * Try to send data on all channels if we can.
9459 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
9460 ssh2_try_send_and_unthrottle(ssh, c);
9468 * Handlers for SSH-2 messages that might arrive at any moment.
9470 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
9472 /* log reason code in disconnect message */
9476 reason = ssh_pkt_getuint32(pktin);
9477 ssh_pkt_getstring(pktin, &msg, &msglen);
9479 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
9480 buf = dupprintf("Received disconnect message (%s)",
9481 ssh2_disconnect_reasons[reason]);
9483 buf = dupprintf("Received disconnect message (unknown"
9484 " type %d)", reason);
9488 buf = dupprintf("Disconnection message text: %.*s",
9491 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
9493 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
9494 ssh2_disconnect_reasons[reason] : "unknown",
9499 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
9501 /* log the debug message */
9505 /* XXX maybe we should actually take notice of the return value */
9506 ssh2_pkt_getbool(pktin);
9507 ssh_pkt_getstring(pktin, &msg, &msglen);
9509 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
9512 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
9514 do_ssh2_transport(ssh, NULL, 0, pktin);
9518 * Called if we receive a packet that isn't allowed by the protocol.
9519 * This only applies to packets whose meaning PuTTY understands.
9520 * Entirely unknown packets are handled below.
9522 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
9524 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
9525 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
9527 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
9531 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
9533 struct Packet *pktout;
9534 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
9535 ssh2_pkt_adduint32(pktout, pktin->sequence);
9537 * UNIMPLEMENTED messages MUST appear in the same order as the
9538 * messages they respond to. Hence, never queue them.
9540 ssh2_pkt_send_noqueue(ssh, pktout);
9544 * Handle the top-level SSH-2 protocol.
9546 static void ssh2_protocol_setup(Ssh ssh)
9551 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9553 for (i = 0; i < 256; i++)
9554 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
9557 * Initially, we only accept transport messages (and a few generic
9558 * ones). do_ssh2_authconn will add more when it starts.
9559 * Messages that are understood but not currently acceptable go to
9560 * ssh2_msg_unexpected.
9562 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
9563 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
9564 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
9565 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
9566 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
9567 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
9568 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
9569 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
9570 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
9571 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
9572 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
9573 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
9574 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
9575 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
9576 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
9577 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
9578 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
9579 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
9580 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
9581 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
9582 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
9583 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
9584 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
9585 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
9586 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
9587 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
9588 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
9589 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
9590 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
9591 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
9592 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
9593 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
9594 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
9597 * These messages have a special handler from the start.
9599 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
9600 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
9601 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9604 static void ssh2_timer(void *ctx, unsigned long now)
9608 if (ssh->state == SSH_STATE_CLOSED)
9611 if (!ssh->kex_in_progress && conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
9612 now == ssh->next_rekey) {
9613 do_ssh2_transport(ssh, "timeout", -1, NULL);
9617 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
9618 struct Packet *pktin)
9620 unsigned char *in = (unsigned char *)vin;
9621 if (ssh->state == SSH_STATE_CLOSED)
9625 ssh->incoming_data_size += pktin->encrypted_len;
9626 if (!ssh->kex_in_progress &&
9627 ssh->max_data_size != 0 &&
9628 ssh->incoming_data_size > ssh->max_data_size)
9629 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9633 ssh->packet_dispatch[pktin->type](ssh, pktin);
9634 else if (!ssh->protocol_initial_phase_done)
9635 do_ssh2_transport(ssh, in, inlen, pktin);
9637 do_ssh2_authconn(ssh, in, inlen, pktin);
9640 static void ssh_cache_conf_values(Ssh ssh)
9642 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
9646 * Called to set up the connection.
9648 * Returns an error message, or NULL on success.
9650 static const char *ssh_init(void *frontend_handle, void **backend_handle,
9651 Conf *conf, char *host, int port, char **realhost,
9652 int nodelay, int keepalive)
9657 ssh = snew(struct ssh_tag);
9658 ssh->conf = conf_copy(conf);
9659 ssh_cache_conf_values(ssh);
9660 ssh->version = 0; /* when not ready yet */
9663 ssh->v1_cipher_ctx = NULL;
9664 ssh->crcda_ctx = NULL;
9665 ssh->cscipher = NULL;
9666 ssh->cs_cipher_ctx = NULL;
9667 ssh->sccipher = NULL;
9668 ssh->sc_cipher_ctx = NULL;
9670 ssh->cs_mac_ctx = NULL;
9672 ssh->sc_mac_ctx = NULL;
9674 ssh->cs_comp_ctx = NULL;
9676 ssh->sc_comp_ctx = NULL;
9678 ssh->kex_ctx = NULL;
9679 ssh->hostkey = NULL;
9680 ssh->hostkey_str = NULL;
9682 ssh->close_expected = FALSE;
9683 ssh->clean_exit = FALSE;
9684 ssh->state = SSH_STATE_PREPACKET;
9685 ssh->size_needed = FALSE;
9686 ssh->eof_needed = FALSE;
9689 ssh->deferred_send_data = NULL;
9690 ssh->deferred_len = 0;
9691 ssh->deferred_size = 0;
9692 ssh->fallback_cmd = 0;
9693 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9694 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9695 ssh->x11disp = NULL;
9696 ssh->v1_compressing = FALSE;
9697 ssh->v2_outgoing_sequence = 0;
9698 ssh->ssh1_rdpkt_crstate = 0;
9699 ssh->ssh2_rdpkt_crstate = 0;
9700 ssh->ssh_gotdata_crstate = 0;
9701 ssh->do_ssh1_connection_crstate = 0;
9702 ssh->do_ssh_init_state = NULL;
9703 ssh->do_ssh1_login_state = NULL;
9704 ssh->do_ssh2_transport_state = NULL;
9705 ssh->do_ssh2_authconn_state = NULL;
9708 ssh->mainchan = NULL;
9709 ssh->throttled_all = 0;
9710 ssh->v1_stdout_throttling = 0;
9712 ssh->queuelen = ssh->queuesize = 0;
9713 ssh->queueing = FALSE;
9714 ssh->qhead = ssh->qtail = NULL;
9715 ssh->deferred_rekey_reason = NULL;
9716 bufchain_init(&ssh->queued_incoming_data);
9717 ssh->frozen = FALSE;
9718 ssh->username = NULL;
9719 ssh->sent_console_eof = FALSE;
9720 ssh->got_pty = FALSE;
9722 *backend_handle = ssh;
9725 if (crypto_startup() == 0)
9726 return "Microsoft high encryption pack not installed!";
9729 ssh->frontend = frontend_handle;
9730 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
9731 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
9733 ssh->channels = NULL;
9734 ssh->rportfwds = NULL;
9735 ssh->portfwds = NULL;
9740 ssh->conn_throttle_count = 0;
9741 ssh->overall_bufsize = 0;
9742 ssh->fallback_cmd = 0;
9744 ssh->protocol = NULL;
9746 ssh->protocol_initial_phase_done = FALSE;
9750 ssh->incoming_data_size = ssh->outgoing_data_size =
9751 ssh->deferred_data_size = 0L;
9752 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9753 CONF_ssh_rekey_data));
9754 ssh->kex_in_progress = FALSE;
9757 ssh->gsslibs = NULL;
9760 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9769 static void ssh_free(void *handle)
9771 Ssh ssh = (Ssh) handle;
9772 struct ssh_channel *c;
9773 struct ssh_rportfwd *pf;
9775 if (ssh->v1_cipher_ctx)
9776 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9777 if (ssh->cs_cipher_ctx)
9778 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9779 if (ssh->sc_cipher_ctx)
9780 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9781 if (ssh->cs_mac_ctx)
9782 ssh->csmac->free_context(ssh->cs_mac_ctx);
9783 if (ssh->sc_mac_ctx)
9784 ssh->scmac->free_context(ssh->sc_mac_ctx);
9785 if (ssh->cs_comp_ctx) {
9787 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9789 zlib_compress_cleanup(ssh->cs_comp_ctx);
9791 if (ssh->sc_comp_ctx) {
9793 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9795 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9798 dh_cleanup(ssh->kex_ctx);
9799 sfree(ssh->savedhost);
9801 while (ssh->queuelen-- > 0)
9802 ssh_free_packet(ssh->queue[ssh->queuelen]);
9805 while (ssh->qhead) {
9806 struct queued_handler *qh = ssh->qhead;
9807 ssh->qhead = qh->next;
9810 ssh->qhead = ssh->qtail = NULL;
9812 if (ssh->channels) {
9813 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9816 if (c->u.x11.s != NULL)
9817 x11_close(c->u.x11.s);
9820 case CHAN_SOCKDATA_DORMANT:
9821 if (c->u.pfd.s != NULL)
9822 pfd_close(c->u.pfd.s);
9825 if (ssh->version == 2) {
9826 struct outstanding_channel_request *ocr, *nocr;
9827 ocr = c->v.v2.chanreq_head;
9829 ocr->handler(c, NULL, ocr->ctx);
9834 bufchain_clear(&c->v.v2.outbuffer);
9838 freetree234(ssh->channels);
9839 ssh->channels = NULL;
9842 if (ssh->rportfwds) {
9843 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9845 freetree234(ssh->rportfwds);
9846 ssh->rportfwds = NULL;
9848 sfree(ssh->deferred_send_data);
9850 x11_free_display(ssh->x11disp);
9851 sfree(ssh->do_ssh_init_state);
9852 sfree(ssh->do_ssh1_login_state);
9853 sfree(ssh->do_ssh2_transport_state);
9854 sfree(ssh->do_ssh2_authconn_state);
9857 sfree(ssh->fullhostname);
9858 sfree(ssh->hostkey_str);
9859 if (ssh->crcda_ctx) {
9860 crcda_free_context(ssh->crcda_ctx);
9861 ssh->crcda_ctx = NULL;
9864 ssh_do_close(ssh, TRUE);
9865 expire_timer_context(ssh);
9867 pinger_free(ssh->pinger);
9868 bufchain_clear(&ssh->queued_incoming_data);
9869 sfree(ssh->username);
9870 conf_free(ssh->conf);
9873 ssh_gss_cleanup(ssh->gsslibs);
9881 * Reconfigure the SSH backend.
9883 static void ssh_reconfig(void *handle, Conf *conf)
9885 Ssh ssh = (Ssh) handle;
9886 char *rekeying = NULL, rekey_mandatory = FALSE;
9887 unsigned long old_max_data_size;
9890 pinger_reconfig(ssh->pinger, ssh->conf, conf);
9892 ssh_setup_portfwd(ssh, conf);
9894 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
9895 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
9897 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
9898 unsigned long now = GETTICKCOUNT();
9900 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
9901 rekeying = "timeout shortened";
9903 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
9907 old_max_data_size = ssh->max_data_size;
9908 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9909 CONF_ssh_rekey_data));
9910 if (old_max_data_size != ssh->max_data_size &&
9911 ssh->max_data_size != 0) {
9912 if (ssh->outgoing_data_size > ssh->max_data_size ||
9913 ssh->incoming_data_size > ssh->max_data_size)
9914 rekeying = "data limit lowered";
9917 if (conf_get_int(ssh->conf, CONF_compression) !=
9918 conf_get_int(conf, CONF_compression)) {
9919 rekeying = "compression setting changed";
9920 rekey_mandatory = TRUE;
9923 for (i = 0; i < CIPHER_MAX; i++)
9924 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
9925 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
9926 rekeying = "cipher settings changed";
9927 rekey_mandatory = TRUE;
9929 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
9930 conf_get_int(conf, CONF_ssh2_des_cbc)) {
9931 rekeying = "cipher settings changed";
9932 rekey_mandatory = TRUE;
9935 conf_free(ssh->conf);
9936 ssh->conf = conf_copy(conf);
9937 ssh_cache_conf_values(ssh);
9940 if (!ssh->kex_in_progress) {
9941 do_ssh2_transport(ssh, rekeying, -1, NULL);
9942 } else if (rekey_mandatory) {
9943 ssh->deferred_rekey_reason = rekeying;
9949 * Called to send data down the SSH connection.
9951 static int ssh_send(void *handle, char *buf, int len)
9953 Ssh ssh = (Ssh) handle;
9955 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9958 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
9960 return ssh_sendbuffer(ssh);
9964 * Called to query the current amount of buffered stdin data.
9966 static int ssh_sendbuffer(void *handle)
9968 Ssh ssh = (Ssh) handle;
9971 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9975 * If the SSH socket itself has backed up, add the total backup
9976 * size on that to any individual buffer on the stdin channel.
9979 if (ssh->throttled_all)
9980 override_value = ssh->overall_bufsize;
9982 if (ssh->version == 1) {
9983 return override_value;
9984 } else if (ssh->version == 2) {
9986 return override_value;
9988 return (override_value +
9989 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
9996 * Called to set the size of the window from SSH's POV.
9998 static void ssh_size(void *handle, int width, int height)
10000 Ssh ssh = (Ssh) handle;
10001 struct Packet *pktout;
10003 ssh->term_width = width;
10004 ssh->term_height = height;
10006 switch (ssh->state) {
10007 case SSH_STATE_BEFORE_SIZE:
10008 case SSH_STATE_PREPACKET:
10009 case SSH_STATE_CLOSED:
10010 break; /* do nothing */
10011 case SSH_STATE_INTERMED:
10012 ssh->size_needed = TRUE; /* buffer for later */
10014 case SSH_STATE_SESSION:
10015 if (!conf_get_int(ssh->conf, CONF_nopty)) {
10016 if (ssh->version == 1) {
10017 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
10018 PKT_INT, ssh->term_height,
10019 PKT_INT, ssh->term_width,
10020 PKT_INT, 0, PKT_INT, 0, PKT_END);
10021 } else if (ssh->mainchan) {
10022 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
10024 ssh2_pkt_adduint32(pktout, ssh->term_width);
10025 ssh2_pkt_adduint32(pktout, ssh->term_height);
10026 ssh2_pkt_adduint32(pktout, 0);
10027 ssh2_pkt_adduint32(pktout, 0);
10028 ssh2_pkt_send(ssh, pktout);
10036 * Return a list of the special codes that make sense in this
10039 static const struct telnet_special *ssh_get_specials(void *handle)
10041 static const struct telnet_special ssh1_ignore_special[] = {
10042 {"IGNORE message", TS_NOP}
10044 static const struct telnet_special ssh2_ignore_special[] = {
10045 {"IGNORE message", TS_NOP},
10047 static const struct telnet_special ssh2_rekey_special[] = {
10048 {"Repeat key exchange", TS_REKEY},
10050 static const struct telnet_special ssh2_session_specials[] = {
10053 /* These are the signal names defined by RFC 4254.
10054 * They include all the ISO C signals, but are a subset of the POSIX
10055 * required signals. */
10056 {"SIGINT (Interrupt)", TS_SIGINT},
10057 {"SIGTERM (Terminate)", TS_SIGTERM},
10058 {"SIGKILL (Kill)", TS_SIGKILL},
10059 {"SIGQUIT (Quit)", TS_SIGQUIT},
10060 {"SIGHUP (Hangup)", TS_SIGHUP},
10061 {"More signals", TS_SUBMENU},
10062 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
10063 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
10064 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
10065 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
10066 {NULL, TS_EXITMENU}
10068 static const struct telnet_special specials_end[] = {
10069 {NULL, TS_EXITMENU}
10071 /* XXX review this length for any changes: */
10072 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
10073 lenof(ssh2_rekey_special) +
10074 lenof(ssh2_session_specials) +
10075 lenof(specials_end)];
10076 Ssh ssh = (Ssh) handle;
10078 #define ADD_SPECIALS(name) \
10080 assert((i + lenof(name)) <= lenof(ssh_specials)); \
10081 memcpy(&ssh_specials[i], name, sizeof name); \
10082 i += lenof(name); \
10085 if (ssh->version == 1) {
10086 /* Don't bother offering IGNORE if we've decided the remote
10087 * won't cope with it, since we wouldn't bother sending it if
10089 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10090 ADD_SPECIALS(ssh1_ignore_special);
10091 } else if (ssh->version == 2) {
10092 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
10093 ADD_SPECIALS(ssh2_ignore_special);
10094 if (!(ssh->remote_bugs & BUG_SSH2_REKEY))
10095 ADD_SPECIALS(ssh2_rekey_special);
10097 ADD_SPECIALS(ssh2_session_specials);
10098 } /* else we're not ready yet */
10101 ADD_SPECIALS(specials_end);
10102 return ssh_specials;
10106 #undef ADD_SPECIALS
10110 * Send special codes. TS_EOF is useful for `plink', so you
10111 * can send an EOF and collect resulting output (e.g. `plink
10114 static void ssh_special(void *handle, Telnet_Special code)
10116 Ssh ssh = (Ssh) handle;
10117 struct Packet *pktout;
10119 if (code == TS_EOF) {
10120 if (ssh->state != SSH_STATE_SESSION) {
10122 * Buffer the EOF in case we are pre-SESSION, so we can
10123 * send it as soon as we reach SESSION.
10125 if (code == TS_EOF)
10126 ssh->eof_needed = TRUE;
10129 if (ssh->version == 1) {
10130 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
10131 } else if (ssh->mainchan) {
10132 sshfwd_write_eof(ssh->mainchan);
10133 ssh->send_ok = 0; /* now stop trying to read from stdin */
10135 logevent("Sent EOF message");
10136 } else if (code == TS_PING || code == TS_NOP) {
10137 if (ssh->state == SSH_STATE_CLOSED
10138 || ssh->state == SSH_STATE_PREPACKET) return;
10139 if (ssh->version == 1) {
10140 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10141 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
10143 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
10144 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
10145 ssh2_pkt_addstring_start(pktout);
10146 ssh2_pkt_send_noqueue(ssh, pktout);
10149 } else if (code == TS_REKEY) {
10150 if (!ssh->kex_in_progress && ssh->version == 2) {
10151 do_ssh2_transport(ssh, "at user request", -1, NULL);
10153 } else if (code == TS_BRK) {
10154 if (ssh->state == SSH_STATE_CLOSED
10155 || ssh->state == SSH_STATE_PREPACKET) return;
10156 if (ssh->version == 1) {
10157 logevent("Unable to send BREAK signal in SSH-1");
10158 } else if (ssh->mainchan) {
10159 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
10160 ssh2_pkt_adduint32(pktout, 0); /* default break length */
10161 ssh2_pkt_send(ssh, pktout);
10164 /* Is is a POSIX signal? */
10165 char *signame = NULL;
10166 if (code == TS_SIGABRT) signame = "ABRT";
10167 if (code == TS_SIGALRM) signame = "ALRM";
10168 if (code == TS_SIGFPE) signame = "FPE";
10169 if (code == TS_SIGHUP) signame = "HUP";
10170 if (code == TS_SIGILL) signame = "ILL";
10171 if (code == TS_SIGINT) signame = "INT";
10172 if (code == TS_SIGKILL) signame = "KILL";
10173 if (code == TS_SIGPIPE) signame = "PIPE";
10174 if (code == TS_SIGQUIT) signame = "QUIT";
10175 if (code == TS_SIGSEGV) signame = "SEGV";
10176 if (code == TS_SIGTERM) signame = "TERM";
10177 if (code == TS_SIGUSR1) signame = "USR1";
10178 if (code == TS_SIGUSR2) signame = "USR2";
10179 /* The SSH-2 protocol does in principle support arbitrary named
10180 * signals, including signame@domain, but we don't support those. */
10182 /* It's a signal. */
10183 if (ssh->version == 2 && ssh->mainchan) {
10184 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
10185 ssh2_pkt_addstring(pktout, signame);
10186 ssh2_pkt_send(ssh, pktout);
10187 logeventf(ssh, "Sent signal SIG%s", signame);
10190 /* Never heard of it. Do nothing */
10195 void *new_sock_channel(void *handle, Socket s)
10197 Ssh ssh = (Ssh) handle;
10198 struct ssh_channel *c;
10199 c = snew(struct ssh_channel);
10202 ssh2_channel_init(c);
10203 c->halfopen = TRUE;
10204 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
10206 add234(ssh->channels, c);
10211 * This is called when stdout/stderr (the entity to which
10212 * from_backend sends data) manages to clear some backlog.
10214 static void ssh_unthrottle(void *handle, int bufsize)
10216 Ssh ssh = (Ssh) handle;
10219 if (ssh->version == 1) {
10220 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
10221 ssh->v1_stdout_throttling = 0;
10222 ssh_throttle_conn(ssh, -1);
10225 if (ssh->mainchan) {
10226 ssh2_set_window(ssh->mainchan,
10227 bufsize < ssh->mainchan->v.v2.locmaxwin ?
10228 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
10229 if (conf_get_int(ssh->conf, CONF_ssh_simple))
10232 buflimit = ssh->mainchan->v.v2.locmaxwin;
10233 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
10234 ssh->mainchan->throttling_conn = 0;
10235 ssh_throttle_conn(ssh, -1);
10241 * Now process any SSH connection data that was stashed in our
10242 * queue while we were frozen.
10244 ssh_process_queued_incoming_data(ssh);
10247 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
10249 struct ssh_channel *c = (struct ssh_channel *)channel;
10251 struct Packet *pktout;
10253 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
10255 if (ssh->version == 1) {
10256 send_packet(ssh, SSH1_MSG_PORT_OPEN,
10257 PKT_INT, c->localid,
10260 /* PKT_STR, <org:orgport>, */
10263 pktout = ssh2_chanopen_init(c, "direct-tcpip");
10264 ssh2_pkt_addstring(pktout, hostname);
10265 ssh2_pkt_adduint32(pktout, port);
10267 * We make up values for the originator data; partly it's
10268 * too much hassle to keep track, and partly I'm not
10269 * convinced the server should be told details like that
10270 * about my local network configuration.
10271 * The "originator IP address" is syntactically a numeric
10272 * IP address, and some servers (e.g., Tectia) get upset
10273 * if it doesn't match this syntax.
10275 ssh2_pkt_addstring(pktout, "0.0.0.0");
10276 ssh2_pkt_adduint32(pktout, 0);
10277 ssh2_pkt_send(ssh, pktout);
10281 static int ssh_connected(void *handle)
10283 Ssh ssh = (Ssh) handle;
10284 return ssh->s != NULL;
10287 static int ssh_sendok(void *handle)
10289 Ssh ssh = (Ssh) handle;
10290 return ssh->send_ok;
10293 static int ssh_ldisc(void *handle, int option)
10295 Ssh ssh = (Ssh) handle;
10296 if (option == LD_ECHO)
10297 return ssh->echoing;
10298 if (option == LD_EDIT)
10299 return ssh->editing;
10303 static void ssh_provide_ldisc(void *handle, void *ldisc)
10305 Ssh ssh = (Ssh) handle;
10306 ssh->ldisc = ldisc;
10309 static void ssh_provide_logctx(void *handle, void *logctx)
10311 Ssh ssh = (Ssh) handle;
10312 ssh->logctx = logctx;
10315 static int ssh_return_exitcode(void *handle)
10317 Ssh ssh = (Ssh) handle;
10318 if (ssh->s != NULL)
10321 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
10325 * cfg_info for SSH is the currently running version of the
10326 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
10328 static int ssh_cfg_info(void *handle)
10330 Ssh ssh = (Ssh) handle;
10331 return ssh->version;
10335 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
10336 * that fails. This variable is the means by which scp.c can reach
10337 * into the SSH code and find out which one it got.
10339 extern int ssh_fallback_cmd(void *handle)
10341 Ssh ssh = (Ssh) handle;
10342 return ssh->fallback_cmd;
10345 Backend ssh_backend = {
10355 ssh_return_exitcode,
10359 ssh_provide_logctx,