Changed my mind about the EOF policy in SSH mode: I think the SSH
[u/mdw/putty] / ssh.c
1 /*
2 * SSH backend.
3 */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdarg.h>
8 #include <assert.h>
9 #include <limits.h>
10 #include <signal.h>
11
12 #include "putty.h"
13 #include "tree234.h"
14 #include "ssh.h"
15 #ifndef NO_GSSAPI
16 #include "sshgssc.h"
17 #include "sshgss.h"
18 #endif
19
20 #ifndef FALSE
21 #define FALSE 0
22 #endif
23 #ifndef TRUE
24 #define TRUE 1
25 #endif
26
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 */
68
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 */
75
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 */
79
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
125
126 /*
127 * Packet type contexts, so that ssh2_pkt_type can correctly decode
128 * the ambiguous type numbers back into the correct type strings.
129 */
130 typedef enum {
131 SSH2_PKTCTX_NOKEX,
132 SSH2_PKTCTX_DHGROUP,
133 SSH2_PKTCTX_DHGEX,
134 SSH2_PKTCTX_RSAKEX
135 } Pkt_KCtx;
136 typedef enum {
137 SSH2_PKTCTX_NOAUTH,
138 SSH2_PKTCTX_PUBLICKEY,
139 SSH2_PKTCTX_PASSWORD,
140 SSH2_PKTCTX_GSSAPI,
141 SSH2_PKTCTX_KBDINTER
142 } Pkt_ACtx;
143
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 */
159
160 static const char *const ssh2_disconnect_reasons[] = {
161 NULL,
162 "host not allowed to connect",
163 "protocol error",
164 "key exchange failed",
165 "host authentication failed",
166 "MAC error",
167 "compression error",
168 "service not available",
169 "protocol version not supported",
170 "host key not verifiable",
171 "connection lost",
172 "by application",
173 "too many connections",
174 "auth cancelled by user",
175 "no more auth methods available",
176 "illegal user name",
177 };
178
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 */
183
184 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
185
186 /*
187 * Various remote-bug flags.
188 */
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
200 /*
201 * Codes for terminal modes.
202 * Most of these are the same in SSH-1 and SSH-2.
203 * This list is derived from RFC 4254 and
204 * SSH-1 RFC-1.2.31.
205 */
206 static const struct {
207 const char* const mode;
208 int opcode;
209 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
210 } ssh_ttymodes[] = {
211 /* "V" prefix discarded for special characters relative to SSH specs */
212 { "INTR", 1, TTY_OP_CHAR },
213 { "QUIT", 2, TTY_OP_CHAR },
214 { "ERASE", 3, TTY_OP_CHAR },
215 { "KILL", 4, TTY_OP_CHAR },
216 { "EOF", 5, TTY_OP_CHAR },
217 { "EOL", 6, TTY_OP_CHAR },
218 { "EOL2", 7, TTY_OP_CHAR },
219 { "START", 8, TTY_OP_CHAR },
220 { "STOP", 9, TTY_OP_CHAR },
221 { "SUSP", 10, TTY_OP_CHAR },
222 { "DSUSP", 11, TTY_OP_CHAR },
223 { "REPRINT", 12, TTY_OP_CHAR },
224 { "WERASE", 13, TTY_OP_CHAR },
225 { "LNEXT", 14, TTY_OP_CHAR },
226 { "FLUSH", 15, TTY_OP_CHAR },
227 { "SWTCH", 16, TTY_OP_CHAR },
228 { "STATUS", 17, TTY_OP_CHAR },
229 { "DISCARD", 18, TTY_OP_CHAR },
230 { "IGNPAR", 30, TTY_OP_BOOL },
231 { "PARMRK", 31, TTY_OP_BOOL },
232 { "INPCK", 32, TTY_OP_BOOL },
233 { "ISTRIP", 33, TTY_OP_BOOL },
234 { "INLCR", 34, TTY_OP_BOOL },
235 { "IGNCR", 35, TTY_OP_BOOL },
236 { "ICRNL", 36, TTY_OP_BOOL },
237 { "IUCLC", 37, TTY_OP_BOOL },
238 { "IXON", 38, TTY_OP_BOOL },
239 { "IXANY", 39, TTY_OP_BOOL },
240 { "IXOFF", 40, TTY_OP_BOOL },
241 { "IMAXBEL", 41, TTY_OP_BOOL },
242 { "ISIG", 50, TTY_OP_BOOL },
243 { "ICANON", 51, TTY_OP_BOOL },
244 { "XCASE", 52, TTY_OP_BOOL },
245 { "ECHO", 53, TTY_OP_BOOL },
246 { "ECHOE", 54, TTY_OP_BOOL },
247 { "ECHOK", 55, TTY_OP_BOOL },
248 { "ECHONL", 56, TTY_OP_BOOL },
249 { "NOFLSH", 57, TTY_OP_BOOL },
250 { "TOSTOP", 58, TTY_OP_BOOL },
251 { "IEXTEN", 59, TTY_OP_BOOL },
252 { "ECHOCTL", 60, TTY_OP_BOOL },
253 { "ECHOKE", 61, TTY_OP_BOOL },
254 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
255 { "OPOST", 70, TTY_OP_BOOL },
256 { "OLCUC", 71, TTY_OP_BOOL },
257 { "ONLCR", 72, TTY_OP_BOOL },
258 { "OCRNL", 73, TTY_OP_BOOL },
259 { "ONOCR", 74, TTY_OP_BOOL },
260 { "ONLRET", 75, TTY_OP_BOOL },
261 { "CS7", 90, TTY_OP_BOOL },
262 { "CS8", 91, TTY_OP_BOOL },
263 { "PARENB", 92, TTY_OP_BOOL },
264 { "PARODD", 93, TTY_OP_BOOL }
265 };
266
267 /* Miscellaneous other tty-related constants. */
268 #define SSH_TTY_OP_END 0
269 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
270 #define SSH1_TTY_OP_ISPEED 192
271 #define SSH1_TTY_OP_OSPEED 193
272 #define SSH2_TTY_OP_ISPEED 128
273 #define SSH2_TTY_OP_OSPEED 129
274
275 /* Helper functions for parsing tty-related config. */
276 static unsigned int ssh_tty_parse_specchar(char *s)
277 {
278 unsigned int ret;
279 if (*s) {
280 char *next = NULL;
281 ret = ctrlparse(s, &next);
282 if (!next) ret = s[0];
283 } else {
284 ret = 255; /* special value meaning "don't set" */
285 }
286 return ret;
287 }
288 static unsigned int ssh_tty_parse_boolean(char *s)
289 {
290 if (stricmp(s, "yes") == 0 ||
291 stricmp(s, "on") == 0 ||
292 stricmp(s, "true") == 0 ||
293 stricmp(s, "+") == 0)
294 return 1; /* true */
295 else if (stricmp(s, "no") == 0 ||
296 stricmp(s, "off") == 0 ||
297 stricmp(s, "false") == 0 ||
298 stricmp(s, "-") == 0)
299 return 0; /* false */
300 else
301 return (atoi(s) != 0);
302 }
303
304 #define translate(x) if (type == x) return #x
305 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
306 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
307 static char *ssh1_pkt_type(int type)
308 {
309 translate(SSH1_MSG_DISCONNECT);
310 translate(SSH1_SMSG_PUBLIC_KEY);
311 translate(SSH1_CMSG_SESSION_KEY);
312 translate(SSH1_CMSG_USER);
313 translate(SSH1_CMSG_AUTH_RSA);
314 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
315 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
316 translate(SSH1_CMSG_AUTH_PASSWORD);
317 translate(SSH1_CMSG_REQUEST_PTY);
318 translate(SSH1_CMSG_WINDOW_SIZE);
319 translate(SSH1_CMSG_EXEC_SHELL);
320 translate(SSH1_CMSG_EXEC_CMD);
321 translate(SSH1_SMSG_SUCCESS);
322 translate(SSH1_SMSG_FAILURE);
323 translate(SSH1_CMSG_STDIN_DATA);
324 translate(SSH1_SMSG_STDOUT_DATA);
325 translate(SSH1_SMSG_STDERR_DATA);
326 translate(SSH1_CMSG_EOF);
327 translate(SSH1_SMSG_EXIT_STATUS);
328 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
329 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
330 translate(SSH1_MSG_CHANNEL_DATA);
331 translate(SSH1_MSG_CHANNEL_CLOSE);
332 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
333 translate(SSH1_SMSG_X11_OPEN);
334 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
335 translate(SSH1_MSG_PORT_OPEN);
336 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
337 translate(SSH1_SMSG_AGENT_OPEN);
338 translate(SSH1_MSG_IGNORE);
339 translate(SSH1_CMSG_EXIT_CONFIRMATION);
340 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
341 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
342 translate(SSH1_MSG_DEBUG);
343 translate(SSH1_CMSG_REQUEST_COMPRESSION);
344 translate(SSH1_CMSG_AUTH_TIS);
345 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
346 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
347 translate(SSH1_CMSG_AUTH_CCARD);
348 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
349 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
350 return "unknown";
351 }
352 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
353 {
354 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
355 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
356 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
357 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
358 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
359 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
360 translate(SSH2_MSG_DISCONNECT);
361 translate(SSH2_MSG_IGNORE);
362 translate(SSH2_MSG_UNIMPLEMENTED);
363 translate(SSH2_MSG_DEBUG);
364 translate(SSH2_MSG_SERVICE_REQUEST);
365 translate(SSH2_MSG_SERVICE_ACCEPT);
366 translate(SSH2_MSG_KEXINIT);
367 translate(SSH2_MSG_NEWKEYS);
368 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
369 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
370 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
371 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
372 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
373 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
374 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
375 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
376 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
377 translate(SSH2_MSG_USERAUTH_REQUEST);
378 translate(SSH2_MSG_USERAUTH_FAILURE);
379 translate(SSH2_MSG_USERAUTH_SUCCESS);
380 translate(SSH2_MSG_USERAUTH_BANNER);
381 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
382 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
383 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
384 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
385 translate(SSH2_MSG_GLOBAL_REQUEST);
386 translate(SSH2_MSG_REQUEST_SUCCESS);
387 translate(SSH2_MSG_REQUEST_FAILURE);
388 translate(SSH2_MSG_CHANNEL_OPEN);
389 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
390 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
391 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
392 translate(SSH2_MSG_CHANNEL_DATA);
393 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
394 translate(SSH2_MSG_CHANNEL_EOF);
395 translate(SSH2_MSG_CHANNEL_CLOSE);
396 translate(SSH2_MSG_CHANNEL_REQUEST);
397 translate(SSH2_MSG_CHANNEL_SUCCESS);
398 translate(SSH2_MSG_CHANNEL_FAILURE);
399 return "unknown";
400 }
401 #undef translate
402 #undef translatec
403
404 /* Enumeration values for fields in SSH-1 packets */
405 enum {
406 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
407 /* These values are for communicating relevant semantics of
408 * fields to the packet logging code. */
409 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
410 };
411
412 /*
413 * Coroutine mechanics for the sillier bits of the code. If these
414 * macros look impenetrable to you, you might find it helpful to
415 * read
416 *
417 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
418 *
419 * which explains the theory behind these macros.
420 *
421 * In particular, if you are getting `case expression not constant'
422 * errors when building with MS Visual Studio, this is because MS's
423 * Edit and Continue debugging feature causes their compiler to
424 * violate ANSI C. To disable Edit and Continue debugging:
425 *
426 * - right-click ssh.c in the FileView
427 * - click Settings
428 * - select the C/C++ tab and the General category
429 * - under `Debug info:', select anything _other_ than `Program
430 * Database for Edit and Continue'.
431 */
432 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
433 #define crState(t) \
434 struct t *s; \
435 if (!ssh->t) ssh->t = snew(struct t); \
436 s = ssh->t;
437 #define crFinish(z) } *crLine = 0; return (z); }
438 #define crFinishV } *crLine = 0; return; }
439 #define crReturn(z) \
440 do {\
441 *crLine =__LINE__; return (z); case __LINE__:;\
442 } while (0)
443 #define crReturnV \
444 do {\
445 *crLine=__LINE__; return; case __LINE__:;\
446 } while (0)
447 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
448 #define crStopV do{ *crLine = 0; return; }while(0)
449 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
450 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
451
452 typedef struct ssh_tag *Ssh;
453 struct Packet;
454
455 static struct Packet *ssh1_pkt_init(int pkt_type);
456 static struct Packet *ssh2_pkt_init(int pkt_type);
457 static void ssh_pkt_ensure(struct Packet *, int length);
458 static void ssh_pkt_adddata(struct Packet *, void *data, int len);
459 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
460 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
461 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
462 static void ssh_pkt_addstring_start(struct Packet *);
463 static void ssh_pkt_addstring_str(struct Packet *, char *data);
464 static void ssh_pkt_addstring_data(struct Packet *, char *data, int len);
465 static void ssh_pkt_addstring(struct Packet *, char *data);
466 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
467 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
468 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
469 static int ssh2_pkt_construct(Ssh, struct Packet *);
470 static void ssh2_pkt_send(Ssh, struct Packet *);
471 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
472 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
473 struct Packet *pktin);
474 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
475 struct Packet *pktin);
476 static void ssh2_channel_check_close(struct ssh_channel *c);
477 static void ssh_channel_destroy(struct ssh_channel *c);
478
479 /*
480 * Buffer management constants. There are several of these for
481 * various different purposes:
482 *
483 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
484 * on a local data stream before we throttle the whole SSH
485 * connection (in SSH-1 only). Throttling the whole connection is
486 * pretty drastic so we set this high in the hope it won't
487 * happen very often.
488 *
489 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
490 * on the SSH connection itself before we defensively throttle
491 * _all_ local data streams. This is pretty drastic too (though
492 * thankfully unlikely in SSH-2 since the window mechanism should
493 * ensure that the server never has any need to throttle its end
494 * of the connection), so we set this high as well.
495 *
496 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
497 * channels.
498 *
499 * - OUR_V2_BIGWIN is the window size we advertise for the only
500 * channel in a simple connection. It must be <= INT_MAX.
501 *
502 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
503 * to the remote side. This actually has nothing to do with the
504 * size of the _packet_, but is instead a limit on the amount
505 * of data we're willing to receive in a single SSH2 channel
506 * data message.
507 *
508 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
509 * _packet_ we're prepared to cope with. It must be a multiple
510 * of the cipher block size, and must be at least 35000.
511 */
512
513 #define SSH1_BUFFER_LIMIT 32768
514 #define SSH_MAX_BACKLOG 32768
515 #define OUR_V2_WINSIZE 16384
516 #define OUR_V2_BIGWIN 0x7fffffff
517 #define OUR_V2_MAXPKT 0x4000UL
518 #define OUR_V2_PACKETLIMIT 0x9000UL
519
520 /* Maximum length of passwords/passphrases (arbitrary) */
521 #define SSH_MAX_PASSWORD_LEN 100
522
523 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
524
525 const static struct ssh_mac *macs[] = {
526 &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
527 };
528 const static struct ssh_mac *buggymacs[] = {
529 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
530 };
531
532 static void *ssh_comp_none_init(void)
533 {
534 return NULL;
535 }
536 static void ssh_comp_none_cleanup(void *handle)
537 {
538 }
539 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
540 unsigned char **outblock, int *outlen)
541 {
542 return 0;
543 }
544 static int ssh_comp_none_disable(void *handle)
545 {
546 return 0;
547 }
548 const static struct ssh_compress ssh_comp_none = {
549 "none", NULL,
550 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
551 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
552 ssh_comp_none_disable, NULL
553 };
554 extern const struct ssh_compress ssh_zlib;
555 const static struct ssh_compress *compressions[] = {
556 &ssh_zlib, &ssh_comp_none
557 };
558
559 enum { /* channel types */
560 CHAN_MAINSESSION,
561 CHAN_X11,
562 CHAN_AGENT,
563 CHAN_SOCKDATA,
564 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
565 };
566
567 /*
568 * little structure to keep track of outstanding WINDOW_ADJUSTs
569 */
570 struct winadj {
571 struct winadj *next;
572 unsigned size;
573 };
574
575 /*
576 * 2-3-4 tree storing channels.
577 */
578 struct ssh_channel {
579 Ssh ssh; /* pointer back to main context */
580 unsigned remoteid, localid;
581 int type;
582 /* True if we opened this channel but server hasn't confirmed. */
583 int halfopen;
584 /*
585 * In SSH-1, this value contains four bits:
586 *
587 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
588 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
589 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
590 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
591 *
592 * A channel is completely finished with when all four bits are set.
593 *
594 * In SSH-2, the four bits mean:
595 *
596 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
597 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
598 * 4 We have received SSH2_MSG_CHANNEL_EOF.
599 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
600 *
601 * A channel is completely finished with when we have both sent
602 * and received CLOSE.
603 *
604 * The symbolic constants below use the SSH-2 terminology, which
605 * is a bit confusing in SSH-1, but we have to use _something_.
606 */
607 #define CLOSES_SENT_EOF 1
608 #define CLOSES_SENT_CLOSE 2
609 #define CLOSES_RCVD_EOF 4
610 #define CLOSES_RCVD_CLOSE 8
611 int closes;
612
613 /*
614 * This flag indicates that an EOF is pending on the outgoing side
615 * of the channel: that is, wherever we're getting the data for
616 * this channel has sent us some data followed by EOF. We can't
617 * actually send the EOF until we've finished sending the data, so
618 * we set this flag instead to remind us to do so once our buffer
619 * is clear.
620 */
621 int pending_eof;
622
623 /*
624 * True if this channel is causing the underlying connection to be
625 * throttled.
626 */
627 int throttling_conn;
628 union {
629 struct ssh2_data_channel {
630 bufchain outbuffer;
631 unsigned remwindow, remmaxpkt;
632 /* locwindow is signed so we can cope with excess data. */
633 int locwindow, locmaxwin;
634 /*
635 * remlocwin is the amount of local window that we think
636 * the remote end had available to it after it sent the
637 * last data packet or window adjust ack.
638 */
639 int remlocwin;
640 /*
641 * These store the list of window adjusts that haven't
642 * been acked.
643 */
644 struct winadj *winadj_head, *winadj_tail;
645 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
646 } v2;
647 } v;
648 union {
649 struct ssh_agent_channel {
650 unsigned char *message;
651 unsigned char msglen[4];
652 unsigned lensofar, totallen;
653 } a;
654 struct ssh_x11_channel {
655 Socket s;
656 } x11;
657 struct ssh_pfd_channel {
658 Socket s;
659 } pfd;
660 } u;
661 };
662
663 /*
664 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
665 * use this structure in different ways, reflecting SSH-2's
666 * altogether saner approach to port forwarding.
667 *
668 * In SSH-1, you arrange a remote forwarding by sending the server
669 * the remote port number, and the local destination host:port.
670 * When a connection comes in, the server sends you back that
671 * host:port pair, and you connect to it. This is a ready-made
672 * security hole if you're not on the ball: a malicious server
673 * could send you back _any_ host:port pair, so if you trustingly
674 * connect to the address it gives you then you've just opened the
675 * entire inside of your corporate network just by connecting
676 * through it to a dodgy SSH server. Hence, we must store a list of
677 * host:port pairs we _are_ trying to forward to, and reject a
678 * connection request from the server if it's not in the list.
679 *
680 * In SSH-2, each side of the connection minds its own business and
681 * doesn't send unnecessary information to the other. You arrange a
682 * remote forwarding by sending the server just the remote port
683 * number. When a connection comes in, the server tells you which
684 * of its ports was connected to; and _you_ have to remember what
685 * local host:port pair went with that port number.
686 *
687 * Hence, in SSH-1 this structure is indexed by destination
688 * host:port pair, whereas in SSH-2 it is indexed by source port.
689 */
690 struct ssh_portfwd; /* forward declaration */
691
692 struct ssh_rportfwd {
693 unsigned sport, dport;
694 char dhost[256];
695 char *sportdesc;
696 struct ssh_portfwd *pfrec;
697 };
698 #define free_rportfwd(pf) ( \
699 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
700
701 /*
702 * Separately to the rportfwd tree (which is for looking up port
703 * open requests from the server), a tree of _these_ structures is
704 * used to keep track of all the currently open port forwardings,
705 * so that we can reconfigure in mid-session if the user requests
706 * it.
707 */
708 struct ssh_portfwd {
709 enum { DESTROY, KEEP, CREATE } status;
710 int type;
711 unsigned sport, dport;
712 char *saddr, *daddr;
713 char *sserv, *dserv;
714 struct ssh_rportfwd *remote;
715 int addressfamily;
716 void *local;
717 };
718 #define free_portfwd(pf) ( \
719 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
720 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
721
722 struct Packet {
723 long length; /* length of `data' actually used */
724 long forcepad; /* SSH-2: force padding to at least this length */
725 int type; /* only used for incoming packets */
726 unsigned long sequence; /* SSH-2 incoming sequence number */
727 unsigned char *data; /* allocated storage */
728 unsigned char *body; /* offset of payload within `data' */
729 long savedpos; /* temporary index into `data' (for strings) */
730 long maxlen; /* amount of storage allocated for `data' */
731 long encrypted_len; /* for SSH-2 total-size counting */
732
733 /*
734 * State associated with packet logging
735 */
736 int logmode;
737 int nblanks;
738 struct logblank_t *blanks;
739 };
740
741 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
742 struct Packet *pktin);
743 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
744 struct Packet *pktin);
745 static void ssh1_protocol_setup(Ssh ssh);
746 static void ssh2_protocol_setup(Ssh ssh);
747 static void ssh_size(void *handle, int width, int height);
748 static void ssh_special(void *handle, Telnet_Special);
749 static int ssh2_try_send(struct ssh_channel *c);
750 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
751 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
752 static void ssh2_set_window(struct ssh_channel *c, int newwin);
753 static int ssh_sendbuffer(void *handle);
754 static int ssh_do_close(Ssh ssh, int notify_exit);
755 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
756 static int ssh2_pkt_getbool(struct Packet *pkt);
757 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
758 static void ssh2_timer(void *ctx, long now);
759 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
760 struct Packet *pktin);
761
762 struct rdpkt1_state_tag {
763 long len, pad, biglen, to_read;
764 unsigned long realcrc, gotcrc;
765 unsigned char *p;
766 int i;
767 int chunk;
768 struct Packet *pktin;
769 };
770
771 struct rdpkt2_state_tag {
772 long len, pad, payload, packetlen, maclen;
773 int i;
774 int cipherblk;
775 unsigned long incoming_sequence;
776 struct Packet *pktin;
777 };
778
779 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
780 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
781
782 struct queued_handler;
783 struct queued_handler {
784 int msg1, msg2;
785 chandler_fn_t handler;
786 void *ctx;
787 struct queued_handler *next;
788 };
789
790 struct ssh_tag {
791 const struct plug_function_table *fn;
792 /* the above field _must_ be first in the structure */
793
794 char *v_c, *v_s;
795 void *exhash;
796
797 Socket s;
798
799 void *ldisc;
800 void *logctx;
801
802 unsigned char session_key[32];
803 int v1_compressing;
804 int v1_remote_protoflags;
805 int v1_local_protoflags;
806 int agentfwd_enabled;
807 int X11_fwd_enabled;
808 int remote_bugs;
809 const struct ssh_cipher *cipher;
810 void *v1_cipher_ctx;
811 void *crcda_ctx;
812 const struct ssh2_cipher *cscipher, *sccipher;
813 void *cs_cipher_ctx, *sc_cipher_ctx;
814 const struct ssh_mac *csmac, *scmac;
815 void *cs_mac_ctx, *sc_mac_ctx;
816 const struct ssh_compress *cscomp, *sccomp;
817 void *cs_comp_ctx, *sc_comp_ctx;
818 const struct ssh_kex *kex;
819 const struct ssh_signkey *hostkey;
820 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
821 int v2_session_id_len;
822 void *kex_ctx;
823
824 char *savedhost;
825 int savedport;
826 int send_ok;
827 int echoing, editing;
828
829 void *frontend;
830
831 int ospeed, ispeed; /* temporaries */
832 int term_width, term_height;
833
834 tree234 *channels; /* indexed by local id */
835 struct ssh_channel *mainchan; /* primary session channel */
836 int ncmode; /* is primary channel direct-tcpip? */
837 int exitcode;
838 int close_expected;
839 int clean_exit;
840
841 tree234 *rportfwds, *portfwds;
842
843 enum {
844 SSH_STATE_PREPACKET,
845 SSH_STATE_BEFORE_SIZE,
846 SSH_STATE_INTERMED,
847 SSH_STATE_SESSION,
848 SSH_STATE_CLOSED
849 } state;
850
851 int size_needed, eof_needed;
852 int sent_console_eof;
853 int got_pty; /* affects EOF behaviour on main channel */
854
855 struct Packet **queue;
856 int queuelen, queuesize;
857 int queueing;
858 unsigned char *deferred_send_data;
859 int deferred_len, deferred_size;
860
861 /*
862 * Gross hack: pscp will try to start SFTP but fall back to
863 * scp1 if that fails. This variable is the means by which
864 * scp.c can reach into the SSH code and find out which one it
865 * got.
866 */
867 int fallback_cmd;
868
869 bufchain banner; /* accumulates banners during do_ssh2_authconn */
870
871 Pkt_KCtx pkt_kctx;
872 Pkt_ACtx pkt_actx;
873
874 struct X11Display *x11disp;
875
876 int version;
877 int conn_throttle_count;
878 int overall_bufsize;
879 int throttled_all;
880 int v1_stdout_throttling;
881 unsigned long v2_outgoing_sequence;
882
883 int ssh1_rdpkt_crstate;
884 int ssh2_rdpkt_crstate;
885 int do_ssh_init_crstate;
886 int ssh_gotdata_crstate;
887 int do_ssh1_login_crstate;
888 int do_ssh1_connection_crstate;
889 int do_ssh2_transport_crstate;
890 int do_ssh2_authconn_crstate;
891
892 void *do_ssh_init_state;
893 void *do_ssh1_login_state;
894 void *do_ssh2_transport_state;
895 void *do_ssh2_authconn_state;
896
897 struct rdpkt1_state_tag rdpkt1_state;
898 struct rdpkt2_state_tag rdpkt2_state;
899
900 /* SSH-1 and SSH-2 use this for different things, but both use it */
901 int protocol_initial_phase_done;
902
903 void (*protocol) (Ssh ssh, void *vin, int inlen,
904 struct Packet *pkt);
905 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
906
907 /*
908 * We maintain our own copy of a Conf structure here. That way,
909 * when we're passed a new one for reconfiguration, we can check
910 * the differences and potentially reconfigure port forwardings
911 * etc in mid-session.
912 */
913 Conf *conf;
914
915 /*
916 * Values cached out of conf so as to avoid the tree234 lookup
917 * cost every time they're used.
918 */
919 int logomitdata;
920
921 /*
922 * Dynamically allocated username string created during SSH
923 * login. Stored in here rather than in the coroutine state so
924 * that it'll be reliably freed if we shut down the SSH session
925 * at some unexpected moment.
926 */
927 char *username;
928
929 /*
930 * Used to transfer data back from async callbacks.
931 */
932 void *agent_response;
933 int agent_response_len;
934 int user_response;
935
936 /*
937 * The SSH connection can be set as `frozen', meaning we are
938 * not currently accepting incoming data from the network. This
939 * is slightly more serious than setting the _socket_ as
940 * frozen, because we may already have had data passed to us
941 * from the network which we need to delay processing until
942 * after the freeze is lifted, so we also need a bufchain to
943 * store that data.
944 */
945 int frozen;
946 bufchain queued_incoming_data;
947
948 /*
949 * Dispatch table for packet types that we may have to deal
950 * with at any time.
951 */
952 handler_fn_t packet_dispatch[256];
953
954 /*
955 * Queues of one-off handler functions for success/failure
956 * indications from a request.
957 */
958 struct queued_handler *qhead, *qtail;
959
960 /*
961 * This module deals with sending keepalives.
962 */
963 Pinger pinger;
964
965 /*
966 * Track incoming and outgoing data sizes and time, for
967 * size-based rekeys.
968 */
969 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
970 unsigned long max_data_size;
971 int kex_in_progress;
972 long next_rekey, last_rekey;
973 char *deferred_rekey_reason; /* points to STATIC string; don't free */
974
975 /*
976 * Fully qualified host name, which we need if doing GSSAPI.
977 */
978 char *fullhostname;
979
980 #ifndef NO_GSSAPI
981 /*
982 * GSSAPI libraries for this session.
983 */
984 struct ssh_gss_liblist *gsslibs;
985 #endif
986 };
987
988 #define logevent(s) logevent(ssh->frontend, s)
989
990 /* logevent, only printf-formatted. */
991 static void logeventf(Ssh ssh, const char *fmt, ...)
992 {
993 va_list ap;
994 char *buf;
995
996 va_start(ap, fmt);
997 buf = dupvprintf(fmt, ap);
998 va_end(ap);
999 logevent(buf);
1000 sfree(buf);
1001 }
1002
1003 #define bombout(msg) \
1004 do { \
1005 char *text = dupprintf msg; \
1006 ssh_do_close(ssh, FALSE); \
1007 logevent(text); \
1008 connection_fatal(ssh->frontend, "%s", text); \
1009 sfree(text); \
1010 } while (0)
1011
1012 /* Functions to leave bits out of the SSH packet log file. */
1013
1014 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
1015 {
1016 if (conf_get_int(ssh->conf, CONF_logomitpass))
1017 pkt->logmode = blanktype;
1018 }
1019
1020 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
1021 {
1022 if (ssh->logomitdata)
1023 pkt->logmode = blanktype;
1024 }
1025
1026 static void end_log_omission(Ssh ssh, struct Packet *pkt)
1027 {
1028 pkt->logmode = PKTLOG_EMIT;
1029 }
1030
1031 /* Helper function for common bits of parsing ttymodes. */
1032 static void parse_ttymodes(Ssh ssh,
1033 void (*do_mode)(void *data, char *mode, char *val),
1034 void *data)
1035 {
1036 char *key, *val;
1037
1038 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
1039 val != NULL;
1040 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
1041 /*
1042 * val[0] is either 'V', indicating that an explicit value
1043 * follows it, or 'A' indicating that we should pass the
1044 * value through from the local environment via get_ttymode.
1045 */
1046 if (val[0] == 'A')
1047 val = get_ttymode(ssh->frontend, key);
1048 else
1049 val++; /* skip the 'V' */
1050 if (val)
1051 do_mode(data, key, val);
1052 }
1053 }
1054
1055 static int ssh_channelcmp(void *av, void *bv)
1056 {
1057 struct ssh_channel *a = (struct ssh_channel *) av;
1058 struct ssh_channel *b = (struct ssh_channel *) bv;
1059 if (a->localid < b->localid)
1060 return -1;
1061 if (a->localid > b->localid)
1062 return +1;
1063 return 0;
1064 }
1065 static int ssh_channelfind(void *av, void *bv)
1066 {
1067 unsigned *a = (unsigned *) av;
1068 struct ssh_channel *b = (struct ssh_channel *) bv;
1069 if (*a < b->localid)
1070 return -1;
1071 if (*a > b->localid)
1072 return +1;
1073 return 0;
1074 }
1075
1076 static int ssh_rportcmp_ssh1(void *av, void *bv)
1077 {
1078 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1079 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1080 int i;
1081 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1082 return i < 0 ? -1 : +1;
1083 if (a->dport > b->dport)
1084 return +1;
1085 if (a->dport < b->dport)
1086 return -1;
1087 return 0;
1088 }
1089
1090 static int ssh_rportcmp_ssh2(void *av, void *bv)
1091 {
1092 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1093 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1094
1095 if (a->sport > b->sport)
1096 return +1;
1097 if (a->sport < b->sport)
1098 return -1;
1099 return 0;
1100 }
1101
1102 /*
1103 * Special form of strcmp which can cope with NULL inputs. NULL is
1104 * defined to sort before even the empty string.
1105 */
1106 static int nullstrcmp(const char *a, const char *b)
1107 {
1108 if (a == NULL && b == NULL)
1109 return 0;
1110 if (a == NULL)
1111 return -1;
1112 if (b == NULL)
1113 return +1;
1114 return strcmp(a, b);
1115 }
1116
1117 static int ssh_portcmp(void *av, void *bv)
1118 {
1119 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1120 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1121 int i;
1122 if (a->type > b->type)
1123 return +1;
1124 if (a->type < b->type)
1125 return -1;
1126 if (a->addressfamily > b->addressfamily)
1127 return +1;
1128 if (a->addressfamily < b->addressfamily)
1129 return -1;
1130 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1131 return i < 0 ? -1 : +1;
1132 if (a->sport > b->sport)
1133 return +1;
1134 if (a->sport < b->sport)
1135 return -1;
1136 if (a->type != 'D') {
1137 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1138 return i < 0 ? -1 : +1;
1139 if (a->dport > b->dport)
1140 return +1;
1141 if (a->dport < b->dport)
1142 return -1;
1143 }
1144 return 0;
1145 }
1146
1147 static int alloc_channel_id(Ssh ssh)
1148 {
1149 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1150 unsigned low, high, mid;
1151 int tsize;
1152 struct ssh_channel *c;
1153
1154 /*
1155 * First-fit allocation of channel numbers: always pick the
1156 * lowest unused one. To do this, binary-search using the
1157 * counted B-tree to find the largest channel ID which is in a
1158 * contiguous sequence from the beginning. (Precisely
1159 * everything in that sequence must have ID equal to its tree
1160 * index plus CHANNEL_NUMBER_OFFSET.)
1161 */
1162 tsize = count234(ssh->channels);
1163
1164 low = -1;
1165 high = tsize;
1166 while (high - low > 1) {
1167 mid = (high + low) / 2;
1168 c = index234(ssh->channels, mid);
1169 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1170 low = mid; /* this one is fine */
1171 else
1172 high = mid; /* this one is past it */
1173 }
1174 /*
1175 * Now low points to either -1, or the tree index of the
1176 * largest ID in the initial sequence.
1177 */
1178 {
1179 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1180 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1181 }
1182 return low + 1 + CHANNEL_NUMBER_OFFSET;
1183 }
1184
1185 static void c_write_stderr(int trusted, const char *buf, int len)
1186 {
1187 int i;
1188 for (i = 0; i < len; i++)
1189 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1190 fputc(buf[i], stderr);
1191 }
1192
1193 static void c_write(Ssh ssh, const char *buf, int len)
1194 {
1195 if (flags & FLAG_STDERR)
1196 c_write_stderr(1, buf, len);
1197 else
1198 from_backend(ssh->frontend, 1, buf, len);
1199 }
1200
1201 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1202 {
1203 if (flags & FLAG_STDERR)
1204 c_write_stderr(0, buf, len);
1205 else
1206 from_backend_untrusted(ssh->frontend, buf, len);
1207 }
1208
1209 static void c_write_str(Ssh ssh, const char *buf)
1210 {
1211 c_write(ssh, buf, strlen(buf));
1212 }
1213
1214 static void ssh_free_packet(struct Packet *pkt)
1215 {
1216 sfree(pkt->data);
1217 sfree(pkt);
1218 }
1219 static struct Packet *ssh_new_packet(void)
1220 {
1221 struct Packet *pkt = snew(struct Packet);
1222
1223 pkt->body = pkt->data = NULL;
1224 pkt->maxlen = 0;
1225 pkt->logmode = PKTLOG_EMIT;
1226 pkt->nblanks = 0;
1227 pkt->blanks = NULL;
1228
1229 return pkt;
1230 }
1231
1232 /*
1233 * Collect incoming data in the incoming packet buffer.
1234 * Decipher and verify the packet when it is completely read.
1235 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1236 * Update the *data and *datalen variables.
1237 * Return a Packet structure when a packet is completed.
1238 */
1239 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1240 {
1241 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1242
1243 crBegin(ssh->ssh1_rdpkt_crstate);
1244
1245 st->pktin = ssh_new_packet();
1246
1247 st->pktin->type = 0;
1248 st->pktin->length = 0;
1249
1250 for (st->i = st->len = 0; st->i < 4; st->i++) {
1251 while ((*datalen) == 0)
1252 crReturn(NULL);
1253 st->len = (st->len << 8) + **data;
1254 (*data)++, (*datalen)--;
1255 }
1256
1257 st->pad = 8 - (st->len % 8);
1258 st->biglen = st->len + st->pad;
1259 st->pktin->length = st->len - 5;
1260
1261 if (st->biglen < 0) {
1262 bombout(("Extremely large packet length from server suggests"
1263 " data stream corruption"));
1264 ssh_free_packet(st->pktin);
1265 crStop(NULL);
1266 }
1267
1268 st->pktin->maxlen = st->biglen;
1269 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1270
1271 st->to_read = st->biglen;
1272 st->p = st->pktin->data;
1273 while (st->to_read > 0) {
1274 st->chunk = st->to_read;
1275 while ((*datalen) == 0)
1276 crReturn(NULL);
1277 if (st->chunk > (*datalen))
1278 st->chunk = (*datalen);
1279 memcpy(st->p, *data, st->chunk);
1280 *data += st->chunk;
1281 *datalen -= st->chunk;
1282 st->p += st->chunk;
1283 st->to_read -= st->chunk;
1284 }
1285
1286 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1287 st->biglen, NULL)) {
1288 bombout(("Network attack (CRC compensation) detected!"));
1289 ssh_free_packet(st->pktin);
1290 crStop(NULL);
1291 }
1292
1293 if (ssh->cipher)
1294 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1295
1296 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1297 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1298 if (st->gotcrc != st->realcrc) {
1299 bombout(("Incorrect CRC received on packet"));
1300 ssh_free_packet(st->pktin);
1301 crStop(NULL);
1302 }
1303
1304 st->pktin->body = st->pktin->data + st->pad + 1;
1305 st->pktin->savedpos = 0;
1306
1307 if (ssh->v1_compressing) {
1308 unsigned char *decompblk;
1309 int decomplen;
1310 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1311 st->pktin->body - 1, st->pktin->length + 1,
1312 &decompblk, &decomplen)) {
1313 bombout(("Zlib decompression encountered invalid data"));
1314 ssh_free_packet(st->pktin);
1315 crStop(NULL);
1316 }
1317
1318 if (st->pktin->maxlen < st->pad + decomplen) {
1319 st->pktin->maxlen = st->pad + decomplen;
1320 st->pktin->data = sresize(st->pktin->data,
1321 st->pktin->maxlen + APIEXTRA,
1322 unsigned char);
1323 st->pktin->body = st->pktin->data + st->pad + 1;
1324 }
1325
1326 memcpy(st->pktin->body - 1, decompblk, decomplen);
1327 sfree(decompblk);
1328 st->pktin->length = decomplen - 1;
1329 }
1330
1331 st->pktin->type = st->pktin->body[-1];
1332
1333 /*
1334 * Log incoming packet, possibly omitting sensitive fields.
1335 */
1336 if (ssh->logctx) {
1337 int nblanks = 0;
1338 struct logblank_t blank;
1339 if (ssh->logomitdata) {
1340 int do_blank = FALSE, blank_prefix = 0;
1341 /* "Session data" packets - omit the data field */
1342 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1343 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1344 do_blank = TRUE; blank_prefix = 4;
1345 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1346 do_blank = TRUE; blank_prefix = 8;
1347 }
1348 if (do_blank) {
1349 blank.offset = blank_prefix;
1350 blank.len = st->pktin->length;
1351 blank.type = PKTLOG_OMIT;
1352 nblanks = 1;
1353 }
1354 }
1355 log_packet(ssh->logctx,
1356 PKT_INCOMING, st->pktin->type,
1357 ssh1_pkt_type(st->pktin->type),
1358 st->pktin->body, st->pktin->length,
1359 nblanks, &blank, NULL);
1360 }
1361
1362 crFinish(st->pktin);
1363 }
1364
1365 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1366 {
1367 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1368
1369 crBegin(ssh->ssh2_rdpkt_crstate);
1370
1371 st->pktin = ssh_new_packet();
1372
1373 st->pktin->type = 0;
1374 st->pktin->length = 0;
1375 if (ssh->sccipher)
1376 st->cipherblk = ssh->sccipher->blksize;
1377 else
1378 st->cipherblk = 8;
1379 if (st->cipherblk < 8)
1380 st->cipherblk = 8;
1381 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1382
1383 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1384 ssh->scmac) {
1385 /*
1386 * When dealing with a CBC-mode cipher, we want to avoid the
1387 * possibility of an attacker's tweaking the ciphertext stream
1388 * so as to cause us to feed the same block to the block
1389 * cipher more than once and thus leak information
1390 * (VU#958563). The way we do this is not to take any
1391 * decisions on the basis of anything we've decrypted until
1392 * we've verified it with a MAC. That includes the packet
1393 * length, so we just read data and check the MAC repeatedly,
1394 * and when the MAC passes, see if the length we've got is
1395 * plausible.
1396 */
1397
1398 /* May as well allocate the whole lot now. */
1399 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1400 unsigned char);
1401
1402 /* Read an amount corresponding to the MAC. */
1403 for (st->i = 0; st->i < st->maclen; st->i++) {
1404 while ((*datalen) == 0)
1405 crReturn(NULL);
1406 st->pktin->data[st->i] = *(*data)++;
1407 (*datalen)--;
1408 }
1409
1410 st->packetlen = 0;
1411 {
1412 unsigned char seq[4];
1413 ssh->scmac->start(ssh->sc_mac_ctx);
1414 PUT_32BIT(seq, st->incoming_sequence);
1415 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1416 }
1417
1418 for (;;) { /* Once around this loop per cipher block. */
1419 /* Read another cipher-block's worth, and tack it onto the end. */
1420 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1421 while ((*datalen) == 0)
1422 crReturn(NULL);
1423 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1424 (*datalen)--;
1425 }
1426 /* Decrypt one more block (a little further back in the stream). */
1427 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1428 st->pktin->data + st->packetlen,
1429 st->cipherblk);
1430 /* Feed that block to the MAC. */
1431 ssh->scmac->bytes(ssh->sc_mac_ctx,
1432 st->pktin->data + st->packetlen, st->cipherblk);
1433 st->packetlen += st->cipherblk;
1434 /* See if that gives us a valid packet. */
1435 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1436 st->pktin->data + st->packetlen) &&
1437 (st->len = GET_32BIT(st->pktin->data)) + 4 == st->packetlen)
1438 break;
1439 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1440 bombout(("No valid incoming packet found"));
1441 ssh_free_packet(st->pktin);
1442 crStop(NULL);
1443 }
1444 }
1445 st->pktin->maxlen = st->packetlen + st->maclen;
1446 st->pktin->data = sresize(st->pktin->data,
1447 st->pktin->maxlen + APIEXTRA,
1448 unsigned char);
1449 } else {
1450 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1451
1452 /*
1453 * Acquire and decrypt the first block of the packet. This will
1454 * contain the length and padding details.
1455 */
1456 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1457 while ((*datalen) == 0)
1458 crReturn(NULL);
1459 st->pktin->data[st->i] = *(*data)++;
1460 (*datalen)--;
1461 }
1462
1463 if (ssh->sccipher)
1464 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1465 st->pktin->data, st->cipherblk);
1466
1467 /*
1468 * Now get the length figure.
1469 */
1470 st->len = GET_32BIT(st->pktin->data);
1471
1472 /*
1473 * _Completely_ silly lengths should be stomped on before they
1474 * do us any more damage.
1475 */
1476 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1477 (st->len + 4) % st->cipherblk != 0) {
1478 bombout(("Incoming packet was garbled on decryption"));
1479 ssh_free_packet(st->pktin);
1480 crStop(NULL);
1481 }
1482
1483 /*
1484 * So now we can work out the total packet length.
1485 */
1486 st->packetlen = st->len + 4;
1487
1488 /*
1489 * Allocate memory for the rest of the packet.
1490 */
1491 st->pktin->maxlen = st->packetlen + st->maclen;
1492 st->pktin->data = sresize(st->pktin->data,
1493 st->pktin->maxlen + APIEXTRA,
1494 unsigned char);
1495
1496 /*
1497 * Read and decrypt the remainder of the packet.
1498 */
1499 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1500 st->i++) {
1501 while ((*datalen) == 0)
1502 crReturn(NULL);
1503 st->pktin->data[st->i] = *(*data)++;
1504 (*datalen)--;
1505 }
1506 /* Decrypt everything _except_ the MAC. */
1507 if (ssh->sccipher)
1508 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1509 st->pktin->data + st->cipherblk,
1510 st->packetlen - st->cipherblk);
1511
1512 /*
1513 * Check the MAC.
1514 */
1515 if (ssh->scmac
1516 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1517 st->len + 4, st->incoming_sequence)) {
1518 bombout(("Incorrect MAC received on packet"));
1519 ssh_free_packet(st->pktin);
1520 crStop(NULL);
1521 }
1522 }
1523 /* Get and sanity-check the amount of random padding. */
1524 st->pad = st->pktin->data[4];
1525 if (st->pad < 4 || st->len - st->pad < 1) {
1526 bombout(("Invalid padding length on received packet"));
1527 ssh_free_packet(st->pktin);
1528 crStop(NULL);
1529 }
1530 /*
1531 * This enables us to deduce the payload length.
1532 */
1533 st->payload = st->len - st->pad - 1;
1534
1535 st->pktin->length = st->payload + 5;
1536 st->pktin->encrypted_len = st->packetlen;
1537
1538 st->pktin->sequence = st->incoming_sequence++;
1539
1540 /*
1541 * Decompress packet payload.
1542 */
1543 {
1544 unsigned char *newpayload;
1545 int newlen;
1546 if (ssh->sccomp &&
1547 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1548 st->pktin->data + 5, st->pktin->length - 5,
1549 &newpayload, &newlen)) {
1550 if (st->pktin->maxlen < newlen + 5) {
1551 st->pktin->maxlen = newlen + 5;
1552 st->pktin->data = sresize(st->pktin->data,
1553 st->pktin->maxlen + APIEXTRA,
1554 unsigned char);
1555 }
1556 st->pktin->length = 5 + newlen;
1557 memcpy(st->pktin->data + 5, newpayload, newlen);
1558 sfree(newpayload);
1559 }
1560 }
1561
1562 st->pktin->savedpos = 6;
1563 st->pktin->body = st->pktin->data;
1564 st->pktin->type = st->pktin->data[5];
1565
1566 /*
1567 * Log incoming packet, possibly omitting sensitive fields.
1568 */
1569 if (ssh->logctx) {
1570 int nblanks = 0;
1571 struct logblank_t blank;
1572 if (ssh->logomitdata) {
1573 int do_blank = FALSE, blank_prefix = 0;
1574 /* "Session data" packets - omit the data field */
1575 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1576 do_blank = TRUE; blank_prefix = 8;
1577 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1578 do_blank = TRUE; blank_prefix = 12;
1579 }
1580 if (do_blank) {
1581 blank.offset = blank_prefix;
1582 blank.len = (st->pktin->length-6) - blank_prefix;
1583 blank.type = PKTLOG_OMIT;
1584 nblanks = 1;
1585 }
1586 }
1587 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1588 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1589 st->pktin->type),
1590 st->pktin->data+6, st->pktin->length-6,
1591 nblanks, &blank, &st->pktin->sequence);
1592 }
1593
1594 crFinish(st->pktin);
1595 }
1596
1597 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1598 {
1599 int pad, biglen, i, pktoffs;
1600 unsigned long crc;
1601 #ifdef __SC__
1602 /*
1603 * XXX various versions of SC (including 8.8.4) screw up the
1604 * register allocation in this function and use the same register
1605 * (D6) for len and as a temporary, with predictable results. The
1606 * following sledgehammer prevents this.
1607 */
1608 volatile
1609 #endif
1610 int len;
1611
1612 if (ssh->logctx)
1613 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1614 ssh1_pkt_type(pkt->data[12]),
1615 pkt->body, pkt->length - (pkt->body - pkt->data),
1616 pkt->nblanks, pkt->blanks, NULL);
1617 sfree(pkt->blanks); pkt->blanks = NULL;
1618 pkt->nblanks = 0;
1619
1620 if (ssh->v1_compressing) {
1621 unsigned char *compblk;
1622 int complen;
1623 zlib_compress_block(ssh->cs_comp_ctx,
1624 pkt->data + 12, pkt->length - 12,
1625 &compblk, &complen);
1626 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1627 memcpy(pkt->data + 12, compblk, complen);
1628 sfree(compblk);
1629 pkt->length = complen + 12;
1630 }
1631
1632 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1633 pkt->length += 4;
1634 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1635 pad = 8 - (len % 8);
1636 pktoffs = 8 - pad;
1637 biglen = len + pad; /* len(padding+type+data+CRC) */
1638
1639 for (i = pktoffs; i < 4+8; i++)
1640 pkt->data[i] = random_byte();
1641 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1642 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1643 PUT_32BIT(pkt->data + pktoffs, len);
1644
1645 if (ssh->cipher)
1646 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1647 pkt->data + pktoffs + 4, biglen);
1648
1649 if (offset_p) *offset_p = pktoffs;
1650 return biglen + 4; /* len(length+padding+type+data+CRC) */
1651 }
1652
1653 static int s_write(Ssh ssh, void *data, int len)
1654 {
1655 if (ssh->logctx)
1656 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1657 0, NULL, NULL);
1658 return sk_write(ssh->s, (char *)data, len);
1659 }
1660
1661 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1662 {
1663 int len, backlog, offset;
1664 len = s_wrpkt_prepare(ssh, pkt, &offset);
1665 backlog = s_write(ssh, pkt->data + offset, len);
1666 if (backlog > SSH_MAX_BACKLOG)
1667 ssh_throttle_all(ssh, 1, backlog);
1668 ssh_free_packet(pkt);
1669 }
1670
1671 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1672 {
1673 int len, offset;
1674 len = s_wrpkt_prepare(ssh, pkt, &offset);
1675 if (ssh->deferred_len + len > ssh->deferred_size) {
1676 ssh->deferred_size = ssh->deferred_len + len + 128;
1677 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1678 ssh->deferred_size,
1679 unsigned char);
1680 }
1681 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1682 pkt->data + offset, len);
1683 ssh->deferred_len += len;
1684 ssh_free_packet(pkt);
1685 }
1686
1687 /*
1688 * Construct a SSH-1 packet with the specified contents.
1689 * (This all-at-once interface used to be the only one, but now SSH-1
1690 * packets can also be constructed incrementally.)
1691 */
1692 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1693 {
1694 int argtype;
1695 Bignum bn;
1696 struct Packet *pkt;
1697
1698 pkt = ssh1_pkt_init(pkttype);
1699
1700 while ((argtype = va_arg(ap, int)) != PKT_END) {
1701 unsigned char *argp, argchar;
1702 char *sargp;
1703 unsigned long argint;
1704 int arglen;
1705 switch (argtype) {
1706 /* Actual fields in the packet */
1707 case PKT_INT:
1708 argint = va_arg(ap, int);
1709 ssh_pkt_adduint32(pkt, argint);
1710 break;
1711 case PKT_CHAR:
1712 argchar = (unsigned char) va_arg(ap, int);
1713 ssh_pkt_addbyte(pkt, argchar);
1714 break;
1715 case PKT_DATA:
1716 argp = va_arg(ap, unsigned char *);
1717 arglen = va_arg(ap, int);
1718 ssh_pkt_adddata(pkt, argp, arglen);
1719 break;
1720 case PKT_STR:
1721 sargp = va_arg(ap, char *);
1722 ssh_pkt_addstring(pkt, sargp);
1723 break;
1724 case PKT_BIGNUM:
1725 bn = va_arg(ap, Bignum);
1726 ssh1_pkt_addmp(pkt, bn);
1727 break;
1728 /* Tokens for modifications to packet logging */
1729 case PKTT_PASSWORD:
1730 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1731 break;
1732 case PKTT_DATA:
1733 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1734 break;
1735 case PKTT_OTHER:
1736 end_log_omission(ssh, pkt);
1737 break;
1738 }
1739 }
1740
1741 return pkt;
1742 }
1743
1744 static void send_packet(Ssh ssh, int pkttype, ...)
1745 {
1746 struct Packet *pkt;
1747 va_list ap;
1748 va_start(ap, pkttype);
1749 pkt = construct_packet(ssh, pkttype, ap);
1750 va_end(ap);
1751 s_wrpkt(ssh, pkt);
1752 }
1753
1754 static void defer_packet(Ssh ssh, int pkttype, ...)
1755 {
1756 struct Packet *pkt;
1757 va_list ap;
1758 va_start(ap, pkttype);
1759 pkt = construct_packet(ssh, pkttype, ap);
1760 va_end(ap);
1761 s_wrpkt_defer(ssh, pkt);
1762 }
1763
1764 static int ssh_versioncmp(char *a, char *b)
1765 {
1766 char *ae, *be;
1767 unsigned long av, bv;
1768
1769 av = strtoul(a, &ae, 10);
1770 bv = strtoul(b, &be, 10);
1771 if (av != bv)
1772 return (av < bv ? -1 : +1);
1773 if (*ae == '.')
1774 ae++;
1775 if (*be == '.')
1776 be++;
1777 av = strtoul(ae, &ae, 10);
1778 bv = strtoul(be, &be, 10);
1779 if (av != bv)
1780 return (av < bv ? -1 : +1);
1781 return 0;
1782 }
1783
1784 /*
1785 * Utility routines for putting an SSH-protocol `string' and
1786 * `uint32' into a hash state.
1787 */
1788 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1789 {
1790 unsigned char lenblk[4];
1791 PUT_32BIT(lenblk, len);
1792 h->bytes(s, lenblk, 4);
1793 h->bytes(s, str, len);
1794 }
1795
1796 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1797 {
1798 unsigned char intblk[4];
1799 PUT_32BIT(intblk, i);
1800 h->bytes(s, intblk, 4);
1801 }
1802
1803 /*
1804 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1805 */
1806 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1807 {
1808 if (pkt->maxlen < length) {
1809 unsigned char *body = pkt->body;
1810 int offset = body ? body - pkt->data : 0;
1811 pkt->maxlen = length + 256;
1812 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1813 if (body) pkt->body = pkt->data + offset;
1814 }
1815 }
1816 static void ssh_pkt_adddata(struct Packet *pkt, void *data, int len)
1817 {
1818 if (pkt->logmode != PKTLOG_EMIT) {
1819 pkt->nblanks++;
1820 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1821 assert(pkt->body);
1822 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1823 (pkt->body - pkt->data);
1824 pkt->blanks[pkt->nblanks-1].len = len;
1825 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1826 }
1827 pkt->length += len;
1828 ssh_pkt_ensure(pkt, pkt->length);
1829 memcpy(pkt->data + pkt->length - len, data, len);
1830 }
1831 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1832 {
1833 ssh_pkt_adddata(pkt, &byte, 1);
1834 }
1835 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1836 {
1837 ssh_pkt_adddata(pkt, &value, 1);
1838 }
1839 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1840 {
1841 unsigned char x[4];
1842 PUT_32BIT(x, value);
1843 ssh_pkt_adddata(pkt, x, 4);
1844 }
1845 static void ssh_pkt_addstring_start(struct Packet *pkt)
1846 {
1847 ssh_pkt_adduint32(pkt, 0);
1848 pkt->savedpos = pkt->length;
1849 }
1850 static void ssh_pkt_addstring_str(struct Packet *pkt, char *data)
1851 {
1852 ssh_pkt_adddata(pkt, data, strlen(data));
1853 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1854 }
1855 static void ssh_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1856 {
1857 ssh_pkt_adddata(pkt, data, len);
1858 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1859 }
1860 static void ssh_pkt_addstring(struct Packet *pkt, char *data)
1861 {
1862 ssh_pkt_addstring_start(pkt);
1863 ssh_pkt_addstring_str(pkt, data);
1864 }
1865 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1866 {
1867 int len = ssh1_bignum_length(b);
1868 unsigned char *data = snewn(len, unsigned char);
1869 (void) ssh1_write_bignum(data, b);
1870 ssh_pkt_adddata(pkt, data, len);
1871 sfree(data);
1872 }
1873 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1874 {
1875 unsigned char *p;
1876 int i, n = (bignum_bitcount(b) + 7) / 8;
1877 p = snewn(n + 1, unsigned char);
1878 p[0] = 0;
1879 for (i = 1; i <= n; i++)
1880 p[i] = bignum_byte(b, n - i);
1881 i = 0;
1882 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1883 i++;
1884 memmove(p, p + i, n + 1 - i);
1885 *len = n + 1 - i;
1886 return p;
1887 }
1888 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1889 {
1890 unsigned char *p;
1891 int len;
1892 p = ssh2_mpint_fmt(b, &len);
1893 ssh_pkt_addstring_start(pkt);
1894 ssh_pkt_addstring_data(pkt, (char *)p, len);
1895 sfree(p);
1896 }
1897
1898 static struct Packet *ssh1_pkt_init(int pkt_type)
1899 {
1900 struct Packet *pkt = ssh_new_packet();
1901 pkt->length = 4 + 8; /* space for length + max padding */
1902 ssh_pkt_addbyte(pkt, pkt_type);
1903 pkt->body = pkt->data + pkt->length;
1904 return pkt;
1905 }
1906
1907 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1908 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1909 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1910 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1911 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1912 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1913 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1914 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1915 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1916
1917 static struct Packet *ssh2_pkt_init(int pkt_type)
1918 {
1919 struct Packet *pkt = ssh_new_packet();
1920 pkt->length = 5; /* space for packet length + padding length */
1921 pkt->forcepad = 0;
1922 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1923 pkt->body = pkt->data + pkt->length; /* after packet type */
1924 return pkt;
1925 }
1926
1927 /*
1928 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1929 * put the MAC on it. Final packet, ready to be sent, is stored in
1930 * pkt->data. Total length is returned.
1931 */
1932 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1933 {
1934 int cipherblk, maclen, padding, i;
1935
1936 if (ssh->logctx)
1937 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1938 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1939 pkt->body, pkt->length - (pkt->body - pkt->data),
1940 pkt->nblanks, pkt->blanks, &ssh->v2_outgoing_sequence);
1941 sfree(pkt->blanks); pkt->blanks = NULL;
1942 pkt->nblanks = 0;
1943
1944 /*
1945 * Compress packet payload.
1946 */
1947 {
1948 unsigned char *newpayload;
1949 int newlen;
1950 if (ssh->cscomp &&
1951 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1952 pkt->length - 5,
1953 &newpayload, &newlen)) {
1954 pkt->length = 5;
1955 ssh2_pkt_adddata(pkt, newpayload, newlen);
1956 sfree(newpayload);
1957 }
1958 }
1959
1960 /*
1961 * Add padding. At least four bytes, and must also bring total
1962 * length (minus MAC) up to a multiple of the block size.
1963 * If pkt->forcepad is set, make sure the packet is at least that size
1964 * after padding.
1965 */
1966 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1967 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1968 padding = 4;
1969 if (pkt->length + padding < pkt->forcepad)
1970 padding = pkt->forcepad - pkt->length;
1971 padding +=
1972 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1973 assert(padding <= 255);
1974 maclen = ssh->csmac ? ssh->csmac->len : 0;
1975 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1976 pkt->data[4] = padding;
1977 for (i = 0; i < padding; i++)
1978 pkt->data[pkt->length + i] = random_byte();
1979 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1980 if (ssh->csmac)
1981 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1982 pkt->length + padding,
1983 ssh->v2_outgoing_sequence);
1984 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1985
1986 if (ssh->cscipher)
1987 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1988 pkt->data, pkt->length + padding);
1989
1990 pkt->encrypted_len = pkt->length + padding;
1991
1992 /* Ready-to-send packet starts at pkt->data. We return length. */
1993 return pkt->length + padding + maclen;
1994 }
1995
1996 /*
1997 * Routines called from the main SSH code to send packets. There
1998 * are quite a few of these, because we have two separate
1999 * mechanisms for delaying the sending of packets:
2000 *
2001 * - In order to send an IGNORE message and a password message in
2002 * a single fixed-length blob, we require the ability to
2003 * concatenate the encrypted forms of those two packets _into_ a
2004 * single blob and then pass it to our <network.h> transport
2005 * layer in one go. Hence, there's a deferment mechanism which
2006 * works after packet encryption.
2007 *
2008 * - In order to avoid sending any connection-layer messages
2009 * during repeat key exchange, we have to queue up any such
2010 * outgoing messages _before_ they are encrypted (and in
2011 * particular before they're allocated sequence numbers), and
2012 * then send them once we've finished.
2013 *
2014 * I call these mechanisms `defer' and `queue' respectively, so as
2015 * to distinguish them reasonably easily.
2016 *
2017 * The functions send_noqueue() and defer_noqueue() free the packet
2018 * structure they are passed. Every outgoing packet goes through
2019 * precisely one of these functions in its life; packets passed to
2020 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2021 * these or get queued, and then when the queue is later emptied
2022 * the packets are all passed to defer_noqueue().
2023 *
2024 * When using a CBC-mode cipher, it's necessary to ensure that an
2025 * attacker can't provide data to be encrypted using an IV that they
2026 * know. We ensure this by prefixing each packet that might contain
2027 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2028 * mechanism, so in this case send_noqueue() ends up redirecting to
2029 * defer_noqueue(). If you don't like this inefficiency, don't use
2030 * CBC.
2031 */
2032
2033 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2034 static void ssh_pkt_defersend(Ssh);
2035
2036 /*
2037 * Send an SSH-2 packet immediately, without queuing or deferring.
2038 */
2039 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2040 {
2041 int len;
2042 int backlog;
2043 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2044 /* We need to send two packets, so use the deferral mechanism. */
2045 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2046 ssh_pkt_defersend(ssh);
2047 return;
2048 }
2049 len = ssh2_pkt_construct(ssh, pkt);
2050 backlog = s_write(ssh, pkt->data, len);
2051 if (backlog > SSH_MAX_BACKLOG)
2052 ssh_throttle_all(ssh, 1, backlog);
2053
2054 ssh->outgoing_data_size += pkt->encrypted_len;
2055 if (!ssh->kex_in_progress &&
2056 ssh->max_data_size != 0 &&
2057 ssh->outgoing_data_size > ssh->max_data_size)
2058 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2059
2060 ssh_free_packet(pkt);
2061 }
2062
2063 /*
2064 * Defer an SSH-2 packet.
2065 */
2066 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2067 {
2068 int len;
2069 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2070 ssh->deferred_len == 0 && !noignore &&
2071 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2072 /*
2073 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2074 * get encrypted with a known IV.
2075 */
2076 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2077 ssh2_pkt_addstring_start(ipkt);
2078 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2079 }
2080 len = ssh2_pkt_construct(ssh, pkt);
2081 if (ssh->deferred_len + len > ssh->deferred_size) {
2082 ssh->deferred_size = ssh->deferred_len + len + 128;
2083 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2084 ssh->deferred_size,
2085 unsigned char);
2086 }
2087 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
2088 ssh->deferred_len += len;
2089 ssh->deferred_data_size += pkt->encrypted_len;
2090 ssh_free_packet(pkt);
2091 }
2092
2093 /*
2094 * Queue an SSH-2 packet.
2095 */
2096 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2097 {
2098 assert(ssh->queueing);
2099
2100 if (ssh->queuelen >= ssh->queuesize) {
2101 ssh->queuesize = ssh->queuelen + 32;
2102 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2103 }
2104
2105 ssh->queue[ssh->queuelen++] = pkt;
2106 }
2107
2108 /*
2109 * Either queue or send a packet, depending on whether queueing is
2110 * set.
2111 */
2112 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2113 {
2114 if (ssh->queueing)
2115 ssh2_pkt_queue(ssh, pkt);
2116 else
2117 ssh2_pkt_send_noqueue(ssh, pkt);
2118 }
2119
2120 /*
2121 * Either queue or defer a packet, depending on whether queueing is
2122 * set.
2123 */
2124 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2125 {
2126 if (ssh->queueing)
2127 ssh2_pkt_queue(ssh, pkt);
2128 else
2129 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2130 }
2131
2132 /*
2133 * Send the whole deferred data block constructed by
2134 * ssh2_pkt_defer() or SSH-1's defer_packet().
2135 *
2136 * The expected use of the defer mechanism is that you call
2137 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2138 * not currently queueing, this simply sets up deferred_send_data
2139 * and then sends it. If we _are_ currently queueing, the calls to
2140 * ssh2_pkt_defer() put the deferred packets on to the queue
2141 * instead, and therefore ssh_pkt_defersend() has no deferred data
2142 * to send. Hence, there's no need to make it conditional on
2143 * ssh->queueing.
2144 */
2145 static void ssh_pkt_defersend(Ssh ssh)
2146 {
2147 int backlog;
2148 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2149 ssh->deferred_len = ssh->deferred_size = 0;
2150 sfree(ssh->deferred_send_data);
2151 ssh->deferred_send_data = NULL;
2152 if (backlog > SSH_MAX_BACKLOG)
2153 ssh_throttle_all(ssh, 1, backlog);
2154
2155 ssh->outgoing_data_size += ssh->deferred_data_size;
2156 if (!ssh->kex_in_progress &&
2157 ssh->max_data_size != 0 &&
2158 ssh->outgoing_data_size > ssh->max_data_size)
2159 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2160 ssh->deferred_data_size = 0;
2161 }
2162
2163 /*
2164 * Send a packet whose length needs to be disguised (typically
2165 * passwords or keyboard-interactive responses).
2166 */
2167 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2168 int padsize)
2169 {
2170 #if 0
2171 if (0) {
2172 /*
2173 * The simplest way to do this is to adjust the
2174 * variable-length padding field in the outgoing packet.
2175 *
2176 * Currently compiled out, because some Cisco SSH servers
2177 * don't like excessively padded packets (bah, why's it
2178 * always Cisco?)
2179 */
2180 pkt->forcepad = padsize;
2181 ssh2_pkt_send(ssh, pkt);
2182 } else
2183 #endif
2184 {
2185 /*
2186 * If we can't do that, however, an alternative approach is
2187 * to use the pkt_defer mechanism to bundle the packet
2188 * tightly together with an SSH_MSG_IGNORE such that their
2189 * combined length is a constant. So first we construct the
2190 * final form of this packet and defer its sending.
2191 */
2192 ssh2_pkt_defer(ssh, pkt);
2193
2194 /*
2195 * Now construct an SSH_MSG_IGNORE which includes a string
2196 * that's an exact multiple of the cipher block size. (If
2197 * the cipher is NULL so that the block size is
2198 * unavailable, we don't do this trick at all, because we
2199 * gain nothing by it.)
2200 */
2201 if (ssh->cscipher &&
2202 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2203 int stringlen, i;
2204
2205 stringlen = (256 - ssh->deferred_len);
2206 stringlen += ssh->cscipher->blksize - 1;
2207 stringlen -= (stringlen % ssh->cscipher->blksize);
2208 if (ssh->cscomp) {
2209 /*
2210 * Temporarily disable actual compression, so we
2211 * can guarantee to get this string exactly the
2212 * length we want it. The compression-disabling
2213 * routine should return an integer indicating how
2214 * many bytes we should adjust our string length
2215 * by.
2216 */
2217 stringlen -=
2218 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2219 }
2220 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2221 ssh2_pkt_addstring_start(pkt);
2222 for (i = 0; i < stringlen; i++) {
2223 char c = (char) random_byte();
2224 ssh2_pkt_addstring_data(pkt, &c, 1);
2225 }
2226 ssh2_pkt_defer(ssh, pkt);
2227 }
2228 ssh_pkt_defersend(ssh);
2229 }
2230 }
2231
2232 /*
2233 * Send all queued SSH-2 packets. We send them by means of
2234 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2235 * packets that needed to be lumped together.
2236 */
2237 static void ssh2_pkt_queuesend(Ssh ssh)
2238 {
2239 int i;
2240
2241 assert(!ssh->queueing);
2242
2243 for (i = 0; i < ssh->queuelen; i++)
2244 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2245 ssh->queuelen = 0;
2246
2247 ssh_pkt_defersend(ssh);
2248 }
2249
2250 #if 0
2251 void bndebug(char *string, Bignum b)
2252 {
2253 unsigned char *p;
2254 int i, len;
2255 p = ssh2_mpint_fmt(b, &len);
2256 debug(("%s", string));
2257 for (i = 0; i < len; i++)
2258 debug((" %02x", p[i]));
2259 debug(("\n"));
2260 sfree(p);
2261 }
2262 #endif
2263
2264 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2265 {
2266 unsigned char *p;
2267 int len;
2268 p = ssh2_mpint_fmt(b, &len);
2269 hash_string(h, s, p, len);
2270 sfree(p);
2271 }
2272
2273 /*
2274 * Packet decode functions for both SSH-1 and SSH-2.
2275 */
2276 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2277 {
2278 unsigned long value;
2279 if (pkt->length - pkt->savedpos < 4)
2280 return 0; /* arrgh, no way to decline (FIXME?) */
2281 value = GET_32BIT(pkt->body + pkt->savedpos);
2282 pkt->savedpos += 4;
2283 return value;
2284 }
2285 static int ssh2_pkt_getbool(struct Packet *pkt)
2286 {
2287 unsigned long value;
2288 if (pkt->length - pkt->savedpos < 1)
2289 return 0; /* arrgh, no way to decline (FIXME?) */
2290 value = pkt->body[pkt->savedpos] != 0;
2291 pkt->savedpos++;
2292 return value;
2293 }
2294 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2295 {
2296 int len;
2297 *p = NULL;
2298 *length = 0;
2299 if (pkt->length - pkt->savedpos < 4)
2300 return;
2301 len = GET_32BIT(pkt->body + pkt->savedpos);
2302 if (len < 0)
2303 return;
2304 *length = len;
2305 pkt->savedpos += 4;
2306 if (pkt->length - pkt->savedpos < *length)
2307 return;
2308 *p = (char *)(pkt->body + pkt->savedpos);
2309 pkt->savedpos += *length;
2310 }
2311 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2312 {
2313 if (pkt->length - pkt->savedpos < length)
2314 return NULL;
2315 pkt->savedpos += length;
2316 return pkt->body + (pkt->savedpos - length);
2317 }
2318 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2319 unsigned char **keystr)
2320 {
2321 int j;
2322
2323 j = makekey(pkt->body + pkt->savedpos,
2324 pkt->length - pkt->savedpos,
2325 key, keystr, 0);
2326
2327 if (j < 0)
2328 return FALSE;
2329
2330 pkt->savedpos += j;
2331 assert(pkt->savedpos < pkt->length);
2332
2333 return TRUE;
2334 }
2335 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2336 {
2337 int j;
2338 Bignum b;
2339
2340 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2341 pkt->length - pkt->savedpos, &b);
2342
2343 if (j < 0)
2344 return NULL;
2345
2346 pkt->savedpos += j;
2347 return b;
2348 }
2349 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2350 {
2351 char *p;
2352 int length;
2353 Bignum b;
2354
2355 ssh_pkt_getstring(pkt, &p, &length);
2356 if (!p)
2357 return NULL;
2358 if (p[0] & 0x80)
2359 return NULL;
2360 b = bignum_from_bytes((unsigned char *)p, length);
2361 return b;
2362 }
2363
2364 /*
2365 * Helper function to add an SSH-2 signature blob to a packet.
2366 * Expects to be shown the public key blob as well as the signature
2367 * blob. Normally works just like ssh2_pkt_addstring, but will
2368 * fiddle with the signature packet if necessary for
2369 * BUG_SSH2_RSA_PADDING.
2370 */
2371 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2372 void *pkblob_v, int pkblob_len,
2373 void *sigblob_v, int sigblob_len)
2374 {
2375 unsigned char *pkblob = (unsigned char *)pkblob_v;
2376 unsigned char *sigblob = (unsigned char *)sigblob_v;
2377
2378 /* dmemdump(pkblob, pkblob_len); */
2379 /* dmemdump(sigblob, sigblob_len); */
2380
2381 /*
2382 * See if this is in fact an ssh-rsa signature and a buggy
2383 * server; otherwise we can just do this the easy way.
2384 */
2385 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
2386 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2387 int pos, len, siglen;
2388
2389 /*
2390 * Find the byte length of the modulus.
2391 */
2392
2393 pos = 4+7; /* skip over "ssh-rsa" */
2394 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
2395 len = GET_32BIT(pkblob+pos); /* find length of modulus */
2396 pos += 4; /* find modulus itself */
2397 while (len > 0 && pkblob[pos] == 0)
2398 len--, pos++;
2399 /* debug(("modulus length is %d\n", len)); */
2400
2401 /*
2402 * Now find the signature integer.
2403 */
2404 pos = 4+7; /* skip over "ssh-rsa" */
2405 siglen = GET_32BIT(sigblob+pos);
2406 /* debug(("signature length is %d\n", siglen)); */
2407
2408 if (len != siglen) {
2409 unsigned char newlen[4];
2410 ssh2_pkt_addstring_start(pkt);
2411 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2412 /* dmemdump(sigblob, pos); */
2413 pos += 4; /* point to start of actual sig */
2414 PUT_32BIT(newlen, len);
2415 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2416 /* dmemdump(newlen, 4); */
2417 newlen[0] = 0;
2418 while (len-- > siglen) {
2419 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2420 /* dmemdump(newlen, 1); */
2421 }
2422 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2423 /* dmemdump(sigblob+pos, siglen); */
2424 return;
2425 }
2426
2427 /* Otherwise fall through and do it the easy way. */
2428 }
2429
2430 ssh2_pkt_addstring_start(pkt);
2431 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2432 }
2433
2434 /*
2435 * Examine the remote side's version string and compare it against
2436 * a list of known buggy implementations.
2437 */
2438 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2439 {
2440 char *imp; /* pointer to implementation part */
2441 imp = vstring;
2442 imp += strcspn(imp, "-");
2443 if (*imp) imp++;
2444 imp += strcspn(imp, "-");
2445 if (*imp) imp++;
2446
2447 ssh->remote_bugs = 0;
2448
2449 /*
2450 * General notes on server version strings:
2451 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2452 * here -- in particular, we've heard of one that's perfectly happy
2453 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2454 * so we can't distinguish them.
2455 */
2456 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2457 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2458 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2459 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2460 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2461 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2462 /*
2463 * These versions don't support SSH1_MSG_IGNORE, so we have
2464 * to use a different defence against password length
2465 * sniffing.
2466 */
2467 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2468 logevent("We believe remote version has SSH-1 ignore bug");
2469 }
2470
2471 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2472 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2473 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2474 /*
2475 * These versions need a plain password sent; they can't
2476 * handle having a null and a random length of data after
2477 * the password.
2478 */
2479 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2480 logevent("We believe remote version needs a plain SSH-1 password");
2481 }
2482
2483 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2484 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2485 (!strcmp(imp, "Cisco-1.25")))) {
2486 /*
2487 * These versions apparently have no clue whatever about
2488 * RSA authentication and will panic and die if they see
2489 * an AUTH_RSA message.
2490 */
2491 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2492 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2493 }
2494
2495 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2496 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2497 !wc_match("* VShell", imp) &&
2498 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2499 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2500 wc_match("2.1 *", imp)))) {
2501 /*
2502 * These versions have the HMAC bug.
2503 */
2504 ssh->remote_bugs |= BUG_SSH2_HMAC;
2505 logevent("We believe remote version has SSH-2 HMAC bug");
2506 }
2507
2508 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2509 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2510 !wc_match("* VShell", imp) &&
2511 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2512 /*
2513 * These versions have the key-derivation bug (failing to
2514 * include the literal shared secret in the hashes that
2515 * generate the keys).
2516 */
2517 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2518 logevent("We believe remote version has SSH-2 key-derivation bug");
2519 }
2520
2521 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2522 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2523 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2524 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2525 /*
2526 * These versions have the SSH-2 RSA padding bug.
2527 */
2528 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2529 logevent("We believe remote version has SSH-2 RSA padding bug");
2530 }
2531
2532 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2533 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2534 wc_match("OpenSSH_2.[0-2]*", imp))) {
2535 /*
2536 * These versions have the SSH-2 session-ID bug in
2537 * public-key authentication.
2538 */
2539 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2540 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2541 }
2542
2543 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2544 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2545 (wc_match("DigiSSH_2.0", imp) ||
2546 wc_match("OpenSSH_2.[0-4]*", imp) ||
2547 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2548 wc_match("Sun_SSH_1.0", imp) ||
2549 wc_match("Sun_SSH_1.0.1", imp) ||
2550 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2551 wc_match("WeOnlyDo-*", imp)))) {
2552 /*
2553 * These versions have the SSH-2 rekey bug.
2554 */
2555 ssh->remote_bugs |= BUG_SSH2_REKEY;
2556 logevent("We believe remote version has SSH-2 rekey bug");
2557 }
2558
2559 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2560 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2561 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2562 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2563 /*
2564 * This version ignores our makpkt and needs to be throttled.
2565 */
2566 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2567 logevent("We believe remote version ignores SSH-2 maximum packet size");
2568 }
2569
2570 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2571 /*
2572 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2573 * none detected automatically.
2574 */
2575 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2576 logevent("We believe remote version has SSH-2 ignore bug");
2577 }
2578 }
2579
2580 /*
2581 * The `software version' part of an SSH version string is required
2582 * to contain no spaces or minus signs.
2583 */
2584 static void ssh_fix_verstring(char *str)
2585 {
2586 /* Eat "SSH-<protoversion>-". */
2587 assert(*str == 'S'); str++;
2588 assert(*str == 'S'); str++;
2589 assert(*str == 'H'); str++;
2590 assert(*str == '-'); str++;
2591 while (*str && *str != '-') str++;
2592 assert(*str == '-'); str++;
2593
2594 /* Convert minus signs and spaces in the remaining string into
2595 * underscores. */
2596 while (*str) {
2597 if (*str == '-' || *str == ' ')
2598 *str = '_';
2599 str++;
2600 }
2601 }
2602
2603 /*
2604 * Send an appropriate SSH version string.
2605 */
2606 static void ssh_send_verstring(Ssh ssh, char *svers)
2607 {
2608 char *verstring;
2609
2610 if (ssh->version == 2) {
2611 /*
2612 * Construct a v2 version string.
2613 */
2614 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2615 } else {
2616 /*
2617 * Construct a v1 version string.
2618 */
2619 verstring = dupprintf("SSH-%s-%s\012",
2620 (ssh_versioncmp(svers, "1.5") <= 0 ?
2621 svers : "1.5"),
2622 sshver);
2623 }
2624
2625 ssh_fix_verstring(verstring);
2626
2627 if (ssh->version == 2) {
2628 size_t len;
2629 /*
2630 * Record our version string.
2631 */
2632 len = strcspn(verstring, "\015\012");
2633 ssh->v_c = snewn(len + 1, char);
2634 memcpy(ssh->v_c, verstring, len);
2635 ssh->v_c[len] = 0;
2636 }
2637
2638 logeventf(ssh, "We claim version: %.*s",
2639 strcspn(verstring, "\015\012"), verstring);
2640 s_write(ssh, verstring, strlen(verstring));
2641 sfree(verstring);
2642 }
2643
2644 static int do_ssh_init(Ssh ssh, unsigned char c)
2645 {
2646 struct do_ssh_init_state {
2647 int vslen;
2648 char version[10];
2649 char *vstring;
2650 int vstrsize;
2651 int i;
2652 int proto1, proto2;
2653 };
2654 crState(do_ssh_init_state);
2655
2656 crBegin(ssh->do_ssh_init_crstate);
2657
2658 /* Search for a line beginning with the string "SSH-" in the input. */
2659 for (;;) {
2660 if (c != 'S') goto no;
2661 crReturn(1);
2662 if (c != 'S') goto no;
2663 crReturn(1);
2664 if (c != 'H') goto no;
2665 crReturn(1);
2666 if (c != '-') goto no;
2667 break;
2668 no:
2669 while (c != '\012')
2670 crReturn(1);
2671 crReturn(1);
2672 }
2673
2674 s->vstrsize = 16;
2675 s->vstring = snewn(s->vstrsize, char);
2676 strcpy(s->vstring, "SSH-");
2677 s->vslen = 4;
2678 s->i = 0;
2679 while (1) {
2680 crReturn(1); /* get another char */
2681 if (s->vslen >= s->vstrsize - 1) {
2682 s->vstrsize += 16;
2683 s->vstring = sresize(s->vstring, s->vstrsize, char);
2684 }
2685 s->vstring[s->vslen++] = c;
2686 if (s->i >= 0) {
2687 if (c == '-') {
2688 s->version[s->i] = '\0';
2689 s->i = -1;
2690 } else if (s->i < sizeof(s->version) - 1)
2691 s->version[s->i++] = c;
2692 } else if (c == '\012')
2693 break;
2694 }
2695
2696 ssh->agentfwd_enabled = FALSE;
2697 ssh->rdpkt2_state.incoming_sequence = 0;
2698
2699 s->vstring[s->vslen] = 0;
2700 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2701 logeventf(ssh, "Server version: %s", s->vstring);
2702 ssh_detect_bugs(ssh, s->vstring);
2703
2704 /*
2705 * Decide which SSH protocol version to support.
2706 */
2707
2708 /* Anything strictly below "2.0" means protocol 1 is supported. */
2709 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2710 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2711 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2712
2713 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2714 bombout(("SSH protocol version 1 required by user but not provided by server"));
2715 crStop(0);
2716 }
2717 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2718 bombout(("SSH protocol version 2 required by user but not provided by server"));
2719 crStop(0);
2720 }
2721
2722 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2723 ssh->version = 2;
2724 else
2725 ssh->version = 1;
2726
2727 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2728
2729 /* Send the version string, if we haven't already */
2730 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
2731 ssh_send_verstring(ssh, s->version);
2732
2733 if (ssh->version == 2) {
2734 size_t len;
2735 /*
2736 * Record their version string.
2737 */
2738 len = strcspn(s->vstring, "\015\012");
2739 ssh->v_s = snewn(len + 1, char);
2740 memcpy(ssh->v_s, s->vstring, len);
2741 ssh->v_s[len] = 0;
2742
2743 /*
2744 * Initialise SSH-2 protocol.
2745 */
2746 ssh->protocol = ssh2_protocol;
2747 ssh2_protocol_setup(ssh);
2748 ssh->s_rdpkt = ssh2_rdpkt;
2749 } else {
2750 /*
2751 * Initialise SSH-1 protocol.
2752 */
2753 ssh->protocol = ssh1_protocol;
2754 ssh1_protocol_setup(ssh);
2755 ssh->s_rdpkt = ssh1_rdpkt;
2756 }
2757 if (ssh->version == 2)
2758 do_ssh2_transport(ssh, NULL, -1, NULL);
2759
2760 update_specials_menu(ssh->frontend);
2761 ssh->state = SSH_STATE_BEFORE_SIZE;
2762 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
2763
2764 sfree(s->vstring);
2765
2766 crFinish(0);
2767 }
2768
2769 static void ssh_process_incoming_data(Ssh ssh,
2770 unsigned char **data, int *datalen)
2771 {
2772 struct Packet *pktin;
2773
2774 pktin = ssh->s_rdpkt(ssh, data, datalen);
2775 if (pktin) {
2776 ssh->protocol(ssh, NULL, 0, pktin);
2777 ssh_free_packet(pktin);
2778 }
2779 }
2780
2781 static void ssh_queue_incoming_data(Ssh ssh,
2782 unsigned char **data, int *datalen)
2783 {
2784 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2785 *data += *datalen;
2786 *datalen = 0;
2787 }
2788
2789 static void ssh_process_queued_incoming_data(Ssh ssh)
2790 {
2791 void *vdata;
2792 unsigned char *data;
2793 int len, origlen;
2794
2795 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2796 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2797 data = vdata;
2798 origlen = len;
2799
2800 while (!ssh->frozen && len > 0)
2801 ssh_process_incoming_data(ssh, &data, &len);
2802
2803 if (origlen > len)
2804 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2805 }
2806 }
2807
2808 static void ssh_set_frozen(Ssh ssh, int frozen)
2809 {
2810 if (ssh->s)
2811 sk_set_frozen(ssh->s, frozen);
2812 ssh->frozen = frozen;
2813 }
2814
2815 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2816 {
2817 /* Log raw data, if we're in that mode. */
2818 if (ssh->logctx)
2819 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2820 0, NULL, NULL);
2821
2822 crBegin(ssh->ssh_gotdata_crstate);
2823
2824 /*
2825 * To begin with, feed the characters one by one to the
2826 * protocol initialisation / selection function do_ssh_init().
2827 * When that returns 0, we're done with the initial greeting
2828 * exchange and can move on to packet discipline.
2829 */
2830 while (1) {
2831 int ret; /* need not be kept across crReturn */
2832 if (datalen == 0)
2833 crReturnV; /* more data please */
2834 ret = do_ssh_init(ssh, *data);
2835 data++;
2836 datalen--;
2837 if (ret == 0)
2838 break;
2839 }
2840
2841 /*
2842 * We emerge from that loop when the initial negotiation is
2843 * over and we have selected an s_rdpkt function. Now pass
2844 * everything to s_rdpkt, and then pass the resulting packets
2845 * to the proper protocol handler.
2846 */
2847
2848 while (1) {
2849 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2850 if (ssh->frozen) {
2851 ssh_queue_incoming_data(ssh, &data, &datalen);
2852 /* This uses up all data and cannot cause anything interesting
2853 * to happen; indeed, for anything to happen at all, we must
2854 * return, so break out. */
2855 break;
2856 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2857 /* This uses up some or all data, and may freeze the
2858 * session. */
2859 ssh_process_queued_incoming_data(ssh);
2860 } else {
2861 /* This uses up some or all data, and may freeze the
2862 * session. */
2863 ssh_process_incoming_data(ssh, &data, &datalen);
2864 }
2865 /* FIXME this is probably EBW. */
2866 if (ssh->state == SSH_STATE_CLOSED)
2867 return;
2868 }
2869 /* We're out of data. Go and get some more. */
2870 crReturnV;
2871 }
2872 crFinishV;
2873 }
2874
2875 static int ssh_do_close(Ssh ssh, int notify_exit)
2876 {
2877 int ret = 0;
2878 struct ssh_channel *c;
2879
2880 ssh->state = SSH_STATE_CLOSED;
2881 expire_timer_context(ssh);
2882 if (ssh->s) {
2883 sk_close(ssh->s);
2884 ssh->s = NULL;
2885 if (notify_exit)
2886 notify_remote_exit(ssh->frontend);
2887 else
2888 ret = 1;
2889 }
2890 /*
2891 * Now we must shut down any port- and X-forwarded channels going
2892 * through this connection.
2893 */
2894 if (ssh->channels) {
2895 while (NULL != (c = index234(ssh->channels, 0))) {
2896 switch (c->type) {
2897 case CHAN_X11:
2898 x11_close(c->u.x11.s);
2899 break;
2900 case CHAN_SOCKDATA:
2901 case CHAN_SOCKDATA_DORMANT:
2902 pfd_close(c->u.pfd.s);
2903 break;
2904 }
2905 del234(ssh->channels, c); /* moving next one to index 0 */
2906 if (ssh->version == 2)
2907 bufchain_clear(&c->v.v2.outbuffer);
2908 sfree(c);
2909 }
2910 }
2911 /*
2912 * Go through port-forwardings, and close any associated
2913 * listening sockets.
2914 */
2915 if (ssh->portfwds) {
2916 struct ssh_portfwd *pf;
2917 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2918 /* Dispose of any listening socket. */
2919 if (pf->local)
2920 pfd_terminate(pf->local);
2921 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2922 free_portfwd(pf);
2923 }
2924 freetree234(ssh->portfwds);
2925 ssh->portfwds = NULL;
2926 }
2927
2928 return ret;
2929 }
2930
2931 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2932 const char *error_msg, int error_code)
2933 {
2934 Ssh ssh = (Ssh) plug;
2935 char addrbuf[256], *msg;
2936
2937 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2938
2939 if (type == 0)
2940 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2941 else
2942 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2943
2944 logevent(msg);
2945 sfree(msg);
2946 }
2947
2948 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2949 int calling_back)
2950 {
2951 Ssh ssh = (Ssh) plug;
2952 int need_notify = ssh_do_close(ssh, FALSE);
2953
2954 if (!error_msg) {
2955 if (!ssh->close_expected)
2956 error_msg = "Server unexpectedly closed network connection";
2957 else
2958 error_msg = "Server closed network connection";
2959 }
2960
2961 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
2962 ssh->exitcode = 0;
2963
2964 if (need_notify)
2965 notify_remote_exit(ssh->frontend);
2966
2967 if (error_msg)
2968 logevent(error_msg);
2969 if (!ssh->close_expected || !ssh->clean_exit)
2970 connection_fatal(ssh->frontend, "%s", error_msg);
2971 return 0;
2972 }
2973
2974 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2975 {
2976 Ssh ssh = (Ssh) plug;
2977 ssh_gotdata(ssh, (unsigned char *)data, len);
2978 if (ssh->state == SSH_STATE_CLOSED) {
2979 ssh_do_close(ssh, TRUE);
2980 return 0;
2981 }
2982 return 1;
2983 }
2984
2985 static void ssh_sent(Plug plug, int bufsize)
2986 {
2987 Ssh ssh = (Ssh) plug;
2988 /*
2989 * If the send backlog on the SSH socket itself clears, we
2990 * should unthrottle the whole world if it was throttled.
2991 */
2992 if (bufsize < SSH_MAX_BACKLOG)
2993 ssh_throttle_all(ssh, 0, bufsize);
2994 }
2995
2996 /*
2997 * Connect to specified host and port.
2998 * Returns an error message, or NULL on success.
2999 * Also places the canonical host name into `realhost'. It must be
3000 * freed by the caller.
3001 */
3002 static const char *connect_to_host(Ssh ssh, char *host, int port,
3003 char **realhost, int nodelay, int keepalive)
3004 {
3005 static const struct plug_function_table fn_table = {
3006 ssh_log,
3007 ssh_closing,
3008 ssh_receive,
3009 ssh_sent,
3010 NULL
3011 };
3012
3013 SockAddr addr;
3014 const char *err;
3015 char *loghost;
3016 int addressfamily, sshprot;
3017
3018 loghost = conf_get_str(ssh->conf, CONF_loghost);
3019 if (*loghost) {
3020 char *colon;
3021
3022 ssh->savedhost = dupstr(loghost);
3023 ssh->savedport = 22; /* default ssh port */
3024
3025 /*
3026 * A colon suffix on savedhost also lets us affect
3027 * savedport.
3028 *
3029 * (FIXME: do something about IPv6 address literals here.)
3030 */
3031 colon = strrchr(ssh->savedhost, ':');
3032 if (colon) {
3033 *colon++ = '\0';
3034 if (*colon)
3035 ssh->savedport = atoi(colon);
3036 }
3037 } else {
3038 ssh->savedhost = dupstr(host);
3039 if (port < 0)
3040 port = 22; /* default ssh port */
3041 ssh->savedport = port;
3042 }
3043
3044 /*
3045 * Try to find host.
3046 */
3047 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3048 logeventf(ssh, "Looking up host \"%s\"%s", host,
3049 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3050 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3051 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3052 if ((err = sk_addr_error(addr)) != NULL) {
3053 sk_addr_free(addr);
3054 return err;
3055 }
3056 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3057
3058 /*
3059 * Open socket.
3060 */
3061 ssh->fn = &fn_table;
3062 ssh->s = new_connection(addr, *realhost, port,
3063 0, 1, nodelay, keepalive, (Plug) ssh, ssh->conf);
3064 if ((err = sk_socket_error(ssh->s)) != NULL) {
3065 ssh->s = NULL;
3066 notify_remote_exit(ssh->frontend);
3067 return err;
3068 }
3069
3070 /*
3071 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3072 * send the version string too.
3073 */
3074 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3075 if (sshprot == 0)
3076 ssh->version = 1;
3077 if (sshprot == 3) {
3078 ssh->version = 2;
3079 ssh_send_verstring(ssh, NULL);
3080 }
3081
3082 /*
3083 * loghost, if configured, overrides realhost.
3084 */
3085 if (*loghost) {
3086 sfree(*realhost);
3087 *realhost = dupstr(loghost);
3088 }
3089
3090 return NULL;
3091 }
3092
3093 /*
3094 * Throttle or unthrottle the SSH connection.
3095 */
3096 static void ssh_throttle_conn(Ssh ssh, int adjust)
3097 {
3098 int old_count = ssh->conn_throttle_count;
3099 ssh->conn_throttle_count += adjust;
3100 assert(ssh->conn_throttle_count >= 0);
3101 if (ssh->conn_throttle_count && !old_count) {
3102 ssh_set_frozen(ssh, 1);
3103 } else if (!ssh->conn_throttle_count && old_count) {
3104 ssh_set_frozen(ssh, 0);
3105 }
3106 }
3107
3108 /*
3109 * Throttle or unthrottle _all_ local data streams (for when sends
3110 * on the SSH connection itself back up).
3111 */
3112 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3113 {
3114 int i;
3115 struct ssh_channel *c;
3116
3117 if (enable == ssh->throttled_all)
3118 return;
3119 ssh->throttled_all = enable;
3120 ssh->overall_bufsize = bufsize;
3121 if (!ssh->channels)
3122 return;
3123 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3124 switch (c->type) {
3125 case CHAN_MAINSESSION:
3126 /*
3127 * This is treated separately, outside the switch.
3128 */
3129 break;
3130 case CHAN_X11:
3131 x11_override_throttle(c->u.x11.s, enable);
3132 break;
3133 case CHAN_AGENT:
3134 /* Agent channels require no buffer management. */
3135 break;
3136 case CHAN_SOCKDATA:
3137 pfd_override_throttle(c->u.pfd.s, enable);
3138 break;
3139 }
3140 }
3141 }
3142
3143 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3144 {
3145 Ssh ssh = (Ssh) sshv;
3146
3147 ssh->agent_response = reply;
3148 ssh->agent_response_len = replylen;
3149
3150 if (ssh->version == 1)
3151 do_ssh1_login(ssh, NULL, -1, NULL);
3152 else
3153 do_ssh2_authconn(ssh, NULL, -1, NULL);
3154 }
3155
3156 static void ssh_dialog_callback(void *sshv, int ret)
3157 {
3158 Ssh ssh = (Ssh) sshv;
3159
3160 ssh->user_response = ret;
3161
3162 if (ssh->version == 1)
3163 do_ssh1_login(ssh, NULL, -1, NULL);
3164 else
3165 do_ssh2_transport(ssh, NULL, -1, NULL);
3166
3167 /*
3168 * This may have unfrozen the SSH connection, so do a
3169 * queued-data run.
3170 */
3171 ssh_process_queued_incoming_data(ssh);
3172 }
3173
3174 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3175 {
3176 struct ssh_channel *c = (struct ssh_channel *)cv;
3177 Ssh ssh = c->ssh;
3178 void *sentreply = reply;
3179
3180 if (!sentreply) {
3181 /* Fake SSH_AGENT_FAILURE. */
3182 sentreply = "\0\0\0\1\5";
3183 replylen = 5;
3184 }
3185 if (ssh->version == 2) {
3186 ssh2_add_channel_data(c, sentreply, replylen);
3187 ssh2_try_send(c);
3188 } else {
3189 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3190 PKT_INT, c->remoteid,
3191 PKT_INT, replylen,
3192 PKTT_DATA,
3193 PKT_DATA, sentreply, replylen,
3194 PKTT_OTHER,
3195 PKT_END);
3196 }
3197 if (reply)
3198 sfree(reply);
3199 }
3200
3201 /*
3202 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3203 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3204 * => log `wire_reason'.
3205 */
3206 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3207 int code, int clean_exit)
3208 {
3209 char *error;
3210 if (!client_reason)
3211 client_reason = wire_reason;
3212 if (client_reason)
3213 error = dupprintf("Disconnected: %s", client_reason);
3214 else
3215 error = dupstr("Disconnected");
3216 if (wire_reason) {
3217 if (ssh->version == 1) {
3218 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3219 PKT_END);
3220 } else if (ssh->version == 2) {
3221 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3222 ssh2_pkt_adduint32(pktout, code);
3223 ssh2_pkt_addstring(pktout, wire_reason);
3224 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3225 ssh2_pkt_send_noqueue(ssh, pktout);
3226 }
3227 }
3228 ssh->close_expected = TRUE;
3229 ssh->clean_exit = clean_exit;
3230 ssh_closing((Plug)ssh, error, 0, 0);
3231 sfree(error);
3232 }
3233
3234 /*
3235 * Handle the key exchange and user authentication phases.
3236 */
3237 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3238 struct Packet *pktin)
3239 {
3240 int i, j, ret;
3241 unsigned char cookie[8], *ptr;
3242 struct RSAKey servkey, hostkey;
3243 struct MD5Context md5c;
3244 struct do_ssh1_login_state {
3245 int len;
3246 unsigned char *rsabuf, *keystr1, *keystr2;
3247 unsigned long supported_ciphers_mask, supported_auths_mask;
3248 int tried_publickey, tried_agent;
3249 int tis_auth_refused, ccard_auth_refused;
3250 unsigned char session_id[16];
3251 int cipher_type;
3252 void *publickey_blob;
3253 int publickey_bloblen;
3254 char *publickey_comment;
3255 int publickey_encrypted;
3256 prompts_t *cur_prompt;
3257 char c;
3258 int pwpkt_type;
3259 unsigned char request[5], *response, *p;
3260 int responselen;
3261 int keyi, nkeys;
3262 int authed;
3263 struct RSAKey key;
3264 Bignum challenge;
3265 char *commentp;
3266 int commentlen;
3267 int dlgret;
3268 Filename *keyfile;
3269 };
3270 crState(do_ssh1_login_state);
3271
3272 crBegin(ssh->do_ssh1_login_crstate);
3273
3274 if (!pktin)
3275 crWaitUntil(pktin);
3276
3277 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3278 bombout(("Public key packet not received"));
3279 crStop(0);
3280 }
3281
3282 logevent("Received public keys");
3283
3284 ptr = ssh_pkt_getdata(pktin, 8);
3285 if (!ptr) {
3286 bombout(("SSH-1 public key packet stopped before random cookie"));
3287 crStop(0);
3288 }
3289 memcpy(cookie, ptr, 8);
3290
3291 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
3292 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
3293 bombout(("Failed to read SSH-1 public keys from public key packet"));
3294 crStop(0);
3295 }
3296
3297 /*
3298 * Log the host key fingerprint.
3299 */
3300 {
3301 char logmsg[80];
3302 logevent("Host key fingerprint is:");
3303 strcpy(logmsg, " ");
3304 hostkey.comment = NULL;
3305 rsa_fingerprint(logmsg + strlen(logmsg),
3306 sizeof(logmsg) - strlen(logmsg), &hostkey);
3307 logevent(logmsg);
3308 }
3309
3310 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3311 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3312 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3313 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3314 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3315
3316 ssh->v1_local_protoflags =
3317 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3318 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3319
3320 MD5Init(&md5c);
3321 MD5Update(&md5c, s->keystr2, hostkey.bytes);
3322 MD5Update(&md5c, s->keystr1, servkey.bytes);
3323 MD5Update(&md5c, cookie, 8);
3324 MD5Final(s->session_id, &md5c);
3325
3326 for (i = 0; i < 32; i++)
3327 ssh->session_key[i] = random_byte();
3328
3329 /*
3330 * Verify that the `bits' and `bytes' parameters match.
3331 */
3332 if (hostkey.bits > hostkey.bytes * 8 ||
3333 servkey.bits > servkey.bytes * 8) {
3334 bombout(("SSH-1 public keys were badly formatted"));
3335 crStop(0);
3336 }
3337
3338 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
3339
3340 s->rsabuf = snewn(s->len, unsigned char);
3341
3342 /*
3343 * Verify the host key.
3344 */
3345 {
3346 /*
3347 * First format the key into a string.
3348 */
3349 int len = rsastr_len(&hostkey);
3350 char fingerprint[100];
3351 char *keystr = snewn(len, char);
3352 rsastr_fmt(keystr, &hostkey);
3353 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
3354
3355 ssh_set_frozen(ssh, 1);
3356 s->dlgret = verify_ssh_host_key(ssh->frontend,
3357 ssh->savedhost, ssh->savedport,
3358 "rsa", keystr, fingerprint,
3359 ssh_dialog_callback, ssh);
3360 sfree(keystr);
3361 if (s->dlgret < 0) {
3362 do {
3363 crReturn(0);
3364 if (pktin) {
3365 bombout(("Unexpected data from server while waiting"
3366 " for user host key response"));
3367 crStop(0);
3368 }
3369 } while (pktin || inlen > 0);
3370 s->dlgret = ssh->user_response;
3371 }
3372 ssh_set_frozen(ssh, 0);
3373
3374 if (s->dlgret == 0) {
3375 ssh_disconnect(ssh, "User aborted at host key verification",
3376 NULL, 0, TRUE);
3377 crStop(0);
3378 }
3379 }
3380
3381 for (i = 0; i < 32; i++) {
3382 s->rsabuf[i] = ssh->session_key[i];
3383 if (i < 16)
3384 s->rsabuf[i] ^= s->session_id[i];
3385 }
3386
3387 if (hostkey.bytes > servkey.bytes) {
3388 ret = rsaencrypt(s->rsabuf, 32, &servkey);
3389 if (ret)
3390 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
3391 } else {
3392 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
3393 if (ret)
3394 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
3395 }
3396 if (!ret) {
3397 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3398 crStop(0);
3399 }
3400
3401 logevent("Encrypted session key");
3402
3403 {
3404 int cipher_chosen = 0, warn = 0;
3405 char *cipher_string = NULL;
3406 int i;
3407 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3408 int next_cipher = conf_get_int_int(ssh->conf,
3409 CONF_ssh_cipherlist, i);
3410 if (next_cipher == CIPHER_WARN) {
3411 /* If/when we choose a cipher, warn about it */
3412 warn = 1;
3413 } else if (next_cipher == CIPHER_AES) {
3414 /* XXX Probably don't need to mention this. */
3415 logevent("AES not supported in SSH-1, skipping");
3416 } else {
3417 switch (next_cipher) {
3418 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3419 cipher_string = "3DES"; break;
3420 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3421 cipher_string = "Blowfish"; break;
3422 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3423 cipher_string = "single-DES"; break;
3424 }
3425 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3426 cipher_chosen = 1;
3427 }
3428 }
3429 if (!cipher_chosen) {
3430 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3431 bombout(("Server violates SSH-1 protocol by not "
3432 "supporting 3DES encryption"));
3433 else
3434 /* shouldn't happen */
3435 bombout(("No supported ciphers found"));
3436 crStop(0);
3437 }
3438
3439 /* Warn about chosen cipher if necessary. */
3440 if (warn) {
3441 ssh_set_frozen(ssh, 1);
3442 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3443 ssh_dialog_callback, ssh);
3444 if (s->dlgret < 0) {
3445 do {
3446 crReturn(0);
3447 if (pktin) {
3448 bombout(("Unexpected data from server while waiting"
3449 " for user response"));
3450 crStop(0);
3451 }
3452 } while (pktin || inlen > 0);
3453 s->dlgret = ssh->user_response;
3454 }
3455 ssh_set_frozen(ssh, 0);
3456 if (s->dlgret == 0) {
3457 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3458 0, TRUE);
3459 crStop(0);
3460 }
3461 }
3462 }
3463
3464 switch (s->cipher_type) {
3465 case SSH_CIPHER_3DES:
3466 logevent("Using 3DES encryption");
3467 break;
3468 case SSH_CIPHER_DES:
3469 logevent("Using single-DES encryption");
3470 break;
3471 case SSH_CIPHER_BLOWFISH:
3472 logevent("Using Blowfish encryption");
3473 break;
3474 }
3475
3476 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3477 PKT_CHAR, s->cipher_type,
3478 PKT_DATA, cookie, 8,
3479 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3480 PKT_DATA, s->rsabuf, s->len,
3481 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3482
3483 logevent("Trying to enable encryption...");
3484
3485 sfree(s->rsabuf);
3486
3487 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3488 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3489 &ssh_3des);
3490 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3491 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3492 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3493
3494 ssh->crcda_ctx = crcda_make_context();
3495 logevent("Installing CRC compensation attack detector");
3496
3497 if (servkey.modulus) {
3498 sfree(servkey.modulus);
3499 servkey.modulus = NULL;
3500 }
3501 if (servkey.exponent) {
3502 sfree(servkey.exponent);
3503 servkey.exponent = NULL;
3504 }
3505 if (hostkey.modulus) {
3506 sfree(hostkey.modulus);
3507 hostkey.modulus = NULL;
3508 }
3509 if (hostkey.exponent) {
3510 sfree(hostkey.exponent);
3511 hostkey.exponent = NULL;
3512 }
3513 crWaitUntil(pktin);
3514
3515 if (pktin->type != SSH1_SMSG_SUCCESS) {
3516 bombout(("Encryption not successfully enabled"));
3517 crStop(0);
3518 }
3519
3520 logevent("Successfully started encryption");
3521
3522 fflush(stdout); /* FIXME eh? */
3523 {
3524 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
3525 int ret; /* need not be kept over crReturn */
3526 s->cur_prompt = new_prompts(ssh->frontend);
3527 s->cur_prompt->to_server = TRUE;
3528 s->cur_prompt->name = dupstr("SSH login name");
3529 /* 512 is an arbitrary upper limit on username size */
3530 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE, 512);
3531 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3532 while (ret < 0) {
3533 ssh->send_ok = 1;
3534 crWaitUntil(!pktin);
3535 ret = get_userpass_input(s->cur_prompt, in, inlen);
3536 ssh->send_ok = 0;
3537 }
3538 if (!ret) {
3539 /*
3540 * Failed to get a username. Terminate.
3541 */
3542 free_prompts(s->cur_prompt);
3543 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3544 crStop(0);
3545 }
3546 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
3547 free_prompts(s->cur_prompt);
3548 }
3549
3550 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
3551 {
3552 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
3553 logevent(userlog);
3554 if (flags & FLAG_INTERACTIVE &&
3555 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3556 c_write_str(ssh, userlog);
3557 c_write_str(ssh, "\r\n");
3558 }
3559 sfree(userlog);
3560 }
3561 }
3562
3563 crWaitUntil(pktin);
3564
3565 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3566 /* We must not attempt PK auth. Pretend we've already tried it. */
3567 s->tried_publickey = s->tried_agent = 1;
3568 } else {
3569 s->tried_publickey = s->tried_agent = 0;
3570 }
3571 s->tis_auth_refused = s->ccard_auth_refused = 0;
3572 /*
3573 * Load the public half of any configured keyfile for later use.
3574 */
3575 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3576 if (!filename_is_null(*s->keyfile)) {
3577 int keytype;
3578 logeventf(ssh, "Reading private key file \"%.150s\"",
3579 filename_to_str(s->keyfile));
3580 keytype = key_type(s->keyfile);
3581 if (keytype == SSH_KEYTYPE_SSH1) {
3582 const char *error;
3583 if (rsakey_pubblob(s->keyfile,
3584 &s->publickey_blob, &s->publickey_bloblen,
3585 &s->publickey_comment, &error)) {
3586 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
3587 NULL);
3588 } else {
3589 char *msgbuf;
3590 logeventf(ssh, "Unable to load private key (%s)", error);
3591 msgbuf = dupprintf("Unable to load private key file "
3592 "\"%.150s\" (%s)\r\n",
3593 filename_to_str(s->keyfile),
3594 error);
3595 c_write_str(ssh, msgbuf);
3596 sfree(msgbuf);
3597 s->publickey_blob = NULL;
3598 }
3599 } else {
3600 char *msgbuf;
3601 logeventf(ssh, "Unable to use this key file (%s)",
3602 key_type_to_str(keytype));
3603 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3604 " (%s)\r\n",
3605 filename_to_str(s->keyfile),
3606 key_type_to_str(keytype));
3607 c_write_str(ssh, msgbuf);
3608 sfree(msgbuf);
3609 s->publickey_blob = NULL;
3610 }
3611 } else
3612 s->publickey_blob = NULL;
3613
3614 while (pktin->type == SSH1_SMSG_FAILURE) {
3615 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3616
3617 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
3618 /*
3619 * Attempt RSA authentication using Pageant.
3620 */
3621 void *r;
3622
3623 s->authed = FALSE;
3624 s->tried_agent = 1;
3625 logevent("Pageant is running. Requesting keys.");
3626
3627 /* Request the keys held by the agent. */
3628 PUT_32BIT(s->request, 1);
3629 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3630 if (!agent_query(s->request, 5, &r, &s->responselen,
3631 ssh_agent_callback, ssh)) {
3632 do {
3633 crReturn(0);
3634 if (pktin) {
3635 bombout(("Unexpected data from server while waiting"
3636 " for agent response"));
3637 crStop(0);
3638 }
3639 } while (pktin || inlen > 0);
3640 r = ssh->agent_response;
3641 s->responselen = ssh->agent_response_len;
3642 }
3643 s->response = (unsigned char *) r;
3644 if (s->response && s->responselen >= 5 &&
3645 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3646 s->p = s->response + 5;
3647 s->nkeys = GET_32BIT(s->p);
3648 s->p += 4;
3649 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3650 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3651 unsigned char *pkblob = s->p;
3652 s->p += 4;
3653 {
3654 int n, ok = FALSE;
3655 do { /* do while (0) to make breaking easy */
3656 n = ssh1_read_bignum
3657 (s->p, s->responselen-(s->p-s->response),
3658 &s->key.exponent);
3659 if (n < 0)
3660 break;
3661 s->p += n;
3662 n = ssh1_read_bignum
3663 (s->p, s->responselen-(s->p-s->response),
3664 &s->key.modulus);
3665 if (n < 0)
3666 break;
3667 s->p += n;
3668 if (s->responselen - (s->p-s->response) < 4)
3669 break;
3670 s->commentlen = GET_32BIT(s->p);
3671 s->p += 4;
3672 if (s->responselen - (s->p-s->response) <
3673 s->commentlen)
3674 break;
3675 s->commentp = (char *)s->p;
3676 s->p += s->commentlen;
3677 ok = TRUE;
3678 } while (0);
3679 if (!ok) {
3680 logevent("Pageant key list packet was truncated");
3681 break;
3682 }
3683 }
3684 if (s->publickey_blob) {
3685 if (!memcmp(pkblob, s->publickey_blob,
3686 s->publickey_bloblen)) {
3687 logeventf(ssh, "Pageant key #%d matches "
3688 "configured key file", s->keyi);
3689 s->tried_publickey = 1;
3690 } else
3691 /* Skip non-configured key */
3692 continue;
3693 }
3694 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3695 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3696 PKT_BIGNUM, s->key.modulus, PKT_END);
3697 crWaitUntil(pktin);
3698 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3699 logevent("Key refused");
3700 continue;
3701 }
3702 logevent("Received RSA challenge");
3703 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3704 bombout(("Server's RSA challenge was badly formatted"));
3705 crStop(0);
3706 }
3707
3708 {
3709 char *agentreq, *q, *ret;
3710 void *vret;
3711 int len, retlen;
3712 len = 1 + 4; /* message type, bit count */
3713 len += ssh1_bignum_length(s->key.exponent);
3714 len += ssh1_bignum_length(s->key.modulus);
3715 len += ssh1_bignum_length(s->challenge);
3716 len += 16; /* session id */
3717 len += 4; /* response format */
3718 agentreq = snewn(4 + len, char);
3719 PUT_32BIT(agentreq, len);
3720 q = agentreq + 4;
3721 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3722 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3723 q += 4;
3724 q += ssh1_write_bignum(q, s->key.exponent);
3725 q += ssh1_write_bignum(q, s->key.modulus);
3726 q += ssh1_write_bignum(q, s->challenge);
3727 memcpy(q, s->session_id, 16);
3728 q += 16;
3729 PUT_32BIT(q, 1); /* response format */
3730 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3731 ssh_agent_callback, ssh)) {
3732 sfree(agentreq);
3733 do {
3734 crReturn(0);
3735 if (pktin) {
3736 bombout(("Unexpected data from server"
3737 " while waiting for agent"
3738 " response"));
3739 crStop(0);
3740 }
3741 } while (pktin || inlen > 0);
3742 vret = ssh->agent_response;
3743 retlen = ssh->agent_response_len;
3744 } else
3745 sfree(agentreq);
3746 ret = vret;
3747 if (ret) {
3748 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3749 logevent("Sending Pageant's response");
3750 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3751 PKT_DATA, ret + 5, 16,
3752 PKT_END);
3753 sfree(ret);
3754 crWaitUntil(pktin);
3755 if (pktin->type == SSH1_SMSG_SUCCESS) {
3756 logevent
3757 ("Pageant's response accepted");
3758 if (flags & FLAG_VERBOSE) {
3759 c_write_str(ssh, "Authenticated using"
3760 " RSA key \"");
3761 c_write(ssh, s->commentp,
3762 s->commentlen);
3763 c_write_str(ssh, "\" from agent\r\n");
3764 }
3765 s->authed = TRUE;
3766 } else
3767 logevent
3768 ("Pageant's response not accepted");
3769 } else {
3770 logevent
3771 ("Pageant failed to answer challenge");
3772 sfree(ret);
3773 }
3774 } else {
3775 logevent("No reply received from Pageant");
3776 }
3777 }
3778 freebn(s->key.exponent);
3779 freebn(s->key.modulus);
3780 freebn(s->challenge);
3781 if (s->authed)
3782 break;
3783 }
3784 sfree(s->response);
3785 if (s->publickey_blob && !s->tried_publickey)
3786 logevent("Configured key file not in Pageant");
3787 } else {
3788 logevent("Failed to get reply from Pageant");
3789 }
3790 if (s->authed)
3791 break;
3792 }
3793 if (s->publickey_blob && !s->tried_publickey) {
3794 /*
3795 * Try public key authentication with the specified
3796 * key file.
3797 */
3798 int got_passphrase; /* need not be kept over crReturn */
3799 if (flags & FLAG_VERBOSE)
3800 c_write_str(ssh, "Trying public key authentication.\r\n");
3801 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3802 logeventf(ssh, "Trying public key \"%s\"",
3803 filename_to_str(s->keyfile));
3804 s->tried_publickey = 1;
3805 got_passphrase = FALSE;
3806 while (!got_passphrase) {
3807 /*
3808 * Get a passphrase, if necessary.
3809 */
3810 char *passphrase = NULL; /* only written after crReturn */
3811 const char *error;
3812 if (!s->publickey_encrypted) {
3813 if (flags & FLAG_VERBOSE)
3814 c_write_str(ssh, "No passphrase required.\r\n");
3815 passphrase = NULL;
3816 } else {
3817 int ret; /* need not be kept over crReturn */
3818 s->cur_prompt = new_prompts(ssh->frontend);
3819 s->cur_prompt->to_server = FALSE;
3820 s->cur_prompt->name = dupstr("SSH key passphrase");
3821 add_prompt(s->cur_prompt,
3822 dupprintf("Passphrase for key \"%.100s\": ",
3823 s->publickey_comment),
3824 FALSE, SSH_MAX_PASSWORD_LEN);
3825 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3826 while (ret < 0) {
3827 ssh->send_ok = 1;
3828 crWaitUntil(!pktin);
3829 ret = get_userpass_input(s->cur_prompt, in, inlen);
3830 ssh->send_ok = 0;
3831 }
3832 if (!ret) {
3833 /* Failed to get a passphrase. Terminate. */
3834 free_prompts(s->cur_prompt);
3835 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3836 0, TRUE);
3837 crStop(0);
3838 }
3839 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3840 free_prompts(s->cur_prompt);
3841 }
3842 /*
3843 * Try decrypting key with passphrase.
3844 */
3845 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3846 ret = loadrsakey(s->keyfile, &s->key, passphrase,
3847 &error);
3848 if (passphrase) {
3849 memset(passphrase, 0, strlen(passphrase));
3850 sfree(passphrase);
3851 }
3852 if (ret == 1) {
3853 /* Correct passphrase. */
3854 got_passphrase = TRUE;
3855 } else if (ret == 0) {
3856 c_write_str(ssh, "Couldn't load private key from ");
3857 c_write_str(ssh, filename_to_str(s->keyfile));
3858 c_write_str(ssh, " (");
3859 c_write_str(ssh, error);
3860 c_write_str(ssh, ").\r\n");
3861 got_passphrase = FALSE;
3862 break; /* go and try something else */
3863 } else if (ret == -1) {
3864 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3865 got_passphrase = FALSE;
3866 /* and try again */
3867 } else {
3868 assert(0 && "unexpected return from loadrsakey()");
3869 got_passphrase = FALSE; /* placate optimisers */
3870 }
3871 }
3872
3873 if (got_passphrase) {
3874
3875 /*
3876 * Send a public key attempt.
3877 */
3878 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3879 PKT_BIGNUM, s->key.modulus, PKT_END);
3880
3881 crWaitUntil(pktin);
3882 if (pktin->type == SSH1_SMSG_FAILURE) {
3883 c_write_str(ssh, "Server refused our public key.\r\n");
3884 continue; /* go and try something else */
3885 }
3886 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3887 bombout(("Bizarre response to offer of public key"));
3888 crStop(0);
3889 }
3890
3891 {
3892 int i;
3893 unsigned char buffer[32];
3894 Bignum challenge, response;
3895
3896 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3897 bombout(("Server's RSA challenge was badly formatted"));
3898 crStop(0);
3899 }
3900 response = rsadecrypt(challenge, &s->key);
3901 freebn(s->key.private_exponent);/* burn the evidence */
3902
3903 for (i = 0; i < 32; i++) {
3904 buffer[i] = bignum_byte(response, 31 - i);
3905 }
3906
3907 MD5Init(&md5c);
3908 MD5Update(&md5c, buffer, 32);
3909 MD5Update(&md5c, s->session_id, 16);
3910 MD5Final(buffer, &md5c);
3911
3912 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3913 PKT_DATA, buffer, 16, PKT_END);
3914
3915 freebn(challenge);
3916 freebn(response);
3917 }
3918
3919 crWaitUntil(pktin);
3920 if (pktin->type == SSH1_SMSG_FAILURE) {
3921 if (flags & FLAG_VERBOSE)
3922 c_write_str(ssh, "Failed to authenticate with"
3923 " our public key.\r\n");
3924 continue; /* go and try something else */
3925 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3926 bombout(("Bizarre response to RSA authentication response"));
3927 crStop(0);
3928 }
3929
3930 break; /* we're through! */
3931 }
3932
3933 }
3934
3935 /*
3936 * Otherwise, try various forms of password-like authentication.
3937 */
3938 s->cur_prompt = new_prompts(ssh->frontend);
3939
3940 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3941 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3942 !s->tis_auth_refused) {
3943 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3944 logevent("Requested TIS authentication");
3945 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3946 crWaitUntil(pktin);
3947 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3948 logevent("TIS authentication declined");
3949 if (flags & FLAG_INTERACTIVE)
3950 c_write_str(ssh, "TIS authentication refused.\r\n");
3951 s->tis_auth_refused = 1;
3952 continue;
3953 } else {
3954 char *challenge;
3955 int challengelen;
3956 char *instr_suf, *prompt;
3957
3958 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3959 if (!challenge) {
3960 bombout(("TIS challenge packet was badly formed"));
3961 crStop(0);
3962 }
3963 logevent("Received TIS challenge");
3964 s->cur_prompt->to_server = TRUE;
3965 s->cur_prompt->name = dupstr("SSH TIS authentication");
3966 /* Prompt heuristic comes from OpenSSH */
3967 if (memchr(challenge, '\n', challengelen)) {
3968 instr_suf = dupstr("");
3969 prompt = dupprintf("%.*s", challengelen, challenge);
3970 } else {
3971 instr_suf = dupprintf("%.*s", challengelen, challenge);
3972 prompt = dupstr("Response: ");
3973 }
3974 s->cur_prompt->instruction =
3975 dupprintf("Using TIS authentication.%s%s",
3976 (*instr_suf) ? "\n" : "",
3977 instr_suf);
3978 s->cur_prompt->instr_reqd = TRUE;
3979 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3980 sfree(instr_suf);
3981 }
3982 }
3983 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3984 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3985 !s->ccard_auth_refused) {
3986 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3987 logevent("Requested CryptoCard authentication");
3988 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3989 crWaitUntil(pktin);
3990 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3991 logevent("CryptoCard authentication declined");
3992 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3993 s->ccard_auth_refused = 1;
3994 continue;
3995 } else {
3996 char *challenge;
3997 int challengelen;
3998 char *instr_suf, *prompt;
3999
4000 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4001 if (!challenge) {
4002 bombout(("CryptoCard challenge packet was badly formed"));
4003 crStop(0);
4004 }
4005 logevent("Received CryptoCard challenge");
4006 s->cur_prompt->to_server = TRUE;
4007 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4008 s->cur_prompt->name_reqd = FALSE;
4009 /* Prompt heuristic comes from OpenSSH */
4010 if (memchr(challenge, '\n', challengelen)) {
4011 instr_suf = dupstr("");
4012 prompt = dupprintf("%.*s", challengelen, challenge);
4013 } else {
4014 instr_suf = dupprintf("%.*s", challengelen, challenge);
4015 prompt = dupstr("Response: ");
4016 }
4017 s->cur_prompt->instruction =
4018 dupprintf("Using CryptoCard authentication.%s%s",
4019 (*instr_suf) ? "\n" : "",
4020 instr_suf);
4021 s->cur_prompt->instr_reqd = TRUE;
4022 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
4023 sfree(instr_suf);
4024 }
4025 }
4026 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4027 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4028 bombout(("No supported authentication methods available"));
4029 crStop(0);
4030 }
4031 s->cur_prompt->to_server = TRUE;
4032 s->cur_prompt->name = dupstr("SSH password");
4033 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4034 ssh->username, ssh->savedhost),
4035 FALSE, SSH_MAX_PASSWORD_LEN);
4036 }
4037
4038 /*
4039 * Show password prompt, having first obtained it via a TIS
4040 * or CryptoCard exchange if we're doing TIS or CryptoCard
4041 * authentication.
4042 */
4043 {
4044 int ret; /* need not be kept over crReturn */
4045 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4046 while (ret < 0) {
4047 ssh->send_ok = 1;
4048 crWaitUntil(!pktin);
4049 ret = get_userpass_input(s->cur_prompt, in, inlen);
4050 ssh->send_ok = 0;
4051 }
4052 if (!ret) {
4053 /*
4054 * Failed to get a password (for example
4055 * because one was supplied on the command line
4056 * which has already failed to work). Terminate.
4057 */
4058 free_prompts(s->cur_prompt);
4059 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4060 crStop(0);
4061 }
4062 }
4063
4064 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4065 /*
4066 * Defence against traffic analysis: we send a
4067 * whole bunch of packets containing strings of
4068 * different lengths. One of these strings is the
4069 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4070 * The others are all random data in
4071 * SSH1_MSG_IGNORE packets. This way a passive
4072 * listener can't tell which is the password, and
4073 * hence can't deduce the password length.
4074 *
4075 * Anybody with a password length greater than 16
4076 * bytes is going to have enough entropy in their
4077 * password that a listener won't find it _that_
4078 * much help to know how long it is. So what we'll
4079 * do is:
4080 *
4081 * - if password length < 16, we send 15 packets
4082 * containing string lengths 1 through 15
4083 *
4084 * - otherwise, we let N be the nearest multiple
4085 * of 8 below the password length, and send 8
4086 * packets containing string lengths N through
4087 * N+7. This won't obscure the order of
4088 * magnitude of the password length, but it will
4089 * introduce a bit of extra uncertainty.
4090 *
4091 * A few servers can't deal with SSH1_MSG_IGNORE, at
4092 * least in this context. For these servers, we need
4093 * an alternative defence. We make use of the fact
4094 * that the password is interpreted as a C string:
4095 * so we can append a NUL, then some random data.
4096 *
4097 * A few servers can deal with neither SSH1_MSG_IGNORE
4098 * here _nor_ a padded password string.
4099 * For these servers we are left with no defences
4100 * against password length sniffing.
4101 */
4102 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4103 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4104 /*
4105 * The server can deal with SSH1_MSG_IGNORE, so
4106 * we can use the primary defence.
4107 */
4108 int bottom, top, pwlen, i;
4109 char *randomstr;
4110
4111 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4112 if (pwlen < 16) {
4113 bottom = 0; /* zero length passwords are OK! :-) */
4114 top = 15;
4115 } else {
4116 bottom = pwlen & ~7;
4117 top = bottom + 7;
4118 }
4119
4120 assert(pwlen >= bottom && pwlen <= top);
4121
4122 randomstr = snewn(top + 1, char);
4123
4124 for (i = bottom; i <= top; i++) {
4125 if (i == pwlen) {
4126 defer_packet(ssh, s->pwpkt_type,
4127 PKTT_PASSWORD, PKT_STR,
4128 s->cur_prompt->prompts[0]->result,
4129 PKTT_OTHER, PKT_END);
4130 } else {
4131 for (j = 0; j < i; j++) {
4132 do {
4133 randomstr[j] = random_byte();
4134 } while (randomstr[j] == '\0');
4135 }
4136 randomstr[i] = '\0';
4137 defer_packet(ssh, SSH1_MSG_IGNORE,
4138 PKT_STR, randomstr, PKT_END);
4139 }
4140 }
4141 logevent("Sending password with camouflage packets");
4142 ssh_pkt_defersend(ssh);
4143 sfree(randomstr);
4144 }
4145 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4146 /*
4147 * The server can't deal with SSH1_MSG_IGNORE
4148 * but can deal with padded passwords, so we
4149 * can use the secondary defence.
4150 */
4151 char string[64];
4152 char *ss;
4153 int len;
4154
4155 len = strlen(s->cur_prompt->prompts[0]->result);
4156 if (len < sizeof(string)) {
4157 ss = string;
4158 strcpy(string, s->cur_prompt->prompts[0]->result);
4159 len++; /* cover the zero byte */
4160 while (len < sizeof(string)) {
4161 string[len++] = (char) random_byte();
4162 }
4163 } else {
4164 ss = s->cur_prompt->prompts[0]->result;
4165 }
4166 logevent("Sending length-padded password");
4167 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4168 PKT_INT, len, PKT_DATA, ss, len,
4169 PKTT_OTHER, PKT_END);
4170 } else {
4171 /*
4172 * The server is believed unable to cope with
4173 * any of our password camouflage methods.
4174 */
4175 int len;
4176 len = strlen(s->cur_prompt->prompts[0]->result);
4177 logevent("Sending unpadded password");
4178 send_packet(ssh, s->pwpkt_type,
4179 PKTT_PASSWORD, PKT_INT, len,
4180 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4181 PKTT_OTHER, PKT_END);
4182 }
4183 } else {
4184 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4185 PKT_STR, s->cur_prompt->prompts[0]->result,
4186 PKTT_OTHER, PKT_END);
4187 }
4188 logevent("Sent password");
4189 free_prompts(s->cur_prompt);
4190 crWaitUntil(pktin);
4191 if (pktin->type == SSH1_SMSG_FAILURE) {
4192 if (flags & FLAG_VERBOSE)
4193 c_write_str(ssh, "Access denied\r\n");
4194 logevent("Authentication refused");
4195 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4196 bombout(("Strange packet received, type %d", pktin->type));
4197 crStop(0);
4198 }
4199 }
4200
4201 /* Clear up */
4202 if (s->publickey_blob) {
4203 sfree(s->publickey_blob);
4204 sfree(s->publickey_comment);
4205 }
4206
4207 logevent("Authentication successful");
4208
4209 crFinish(1);
4210 }
4211
4212 static void ssh_channel_try_eof(struct ssh_channel *c)
4213 {
4214 Ssh ssh = c->ssh;
4215 assert(c->pending_eof); /* precondition for calling us */
4216 if (c->halfopen)
4217 return; /* can't close: not even opened yet */
4218 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4219 return; /* can't send EOF: pending outgoing data */
4220
4221 if (ssh->version == 1) {
4222 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4223 PKT_END);
4224 c->closes |= CLOSES_SENT_EOF;
4225 } else {
4226 struct Packet *pktout;
4227 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4228 ssh2_pkt_adduint32(pktout, c->remoteid);
4229 ssh2_pkt_send(ssh, pktout);
4230 c->closes |= CLOSES_SENT_EOF;
4231 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes)) {
4232 /*
4233 * Also send MSG_CLOSE.
4234 */
4235 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4236 ssh2_pkt_adduint32(pktout, c->remoteid);
4237 ssh2_pkt_send(ssh, pktout);
4238 c->closes |= CLOSES_SENT_CLOSE;
4239 }
4240 }
4241 c->pending_eof = FALSE; /* we've sent it now */
4242 }
4243
4244 void sshfwd_write_eof(struct ssh_channel *c)
4245 {
4246 Ssh ssh = c->ssh;
4247
4248 if (ssh->state == SSH_STATE_CLOSED)
4249 return;
4250
4251 if (c->closes & CLOSES_SENT_EOF)
4252 return;
4253
4254 c->pending_eof = TRUE;
4255 ssh_channel_try_eof(c);
4256 }
4257
4258 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4259 {
4260 Ssh ssh = c->ssh;
4261
4262 if (ssh->state == SSH_STATE_CLOSED)
4263 return 0;
4264
4265 if (ssh->version == 1) {
4266 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4267 PKT_INT, c->remoteid,
4268 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
4269 PKTT_OTHER, PKT_END);
4270 /*
4271 * In SSH-1 we can return 0 here - implying that forwarded
4272 * connections are never individually throttled - because
4273 * the only circumstance that can cause throttling will be
4274 * the whole SSH connection backing up, in which case
4275 * _everything_ will be throttled as a whole.
4276 */
4277 return 0;
4278 } else {
4279 ssh2_add_channel_data(c, buf, len);
4280 return ssh2_try_send(c);
4281 }
4282 }
4283
4284 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4285 {
4286 Ssh ssh = c->ssh;
4287 int buflimit;
4288
4289 if (ssh->state == SSH_STATE_CLOSED)
4290 return;
4291
4292 if (ssh->version == 1) {
4293 buflimit = SSH1_BUFFER_LIMIT;
4294 } else {
4295 buflimit = c->v.v2.locmaxwin;
4296 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4297 }
4298 if (c->throttling_conn && bufsize <= buflimit) {
4299 c->throttling_conn = 0;
4300 ssh_throttle_conn(ssh, -1);
4301 }
4302 }
4303
4304 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4305 {
4306 struct queued_handler *qh = ssh->qhead;
4307
4308 assert(qh != NULL);
4309
4310 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4311
4312 if (qh->msg1 > 0) {
4313 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4314 ssh->packet_dispatch[qh->msg1] = NULL;
4315 }
4316 if (qh->msg2 > 0) {
4317 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4318 ssh->packet_dispatch[qh->msg2] = NULL;
4319 }
4320
4321 if (qh->next) {
4322 ssh->qhead = qh->next;
4323
4324 if (ssh->qhead->msg1 > 0) {
4325 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
4326 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4327 }
4328 if (ssh->qhead->msg2 > 0) {
4329 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
4330 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4331 }
4332 } else {
4333 ssh->qhead = ssh->qtail = NULL;
4334 ssh->packet_dispatch[pktin->type] = NULL;
4335 }
4336
4337 qh->handler(ssh, pktin, qh->ctx);
4338
4339 sfree(qh);
4340 }
4341
4342 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4343 chandler_fn_t handler, void *ctx)
4344 {
4345 struct queued_handler *qh;
4346
4347 qh = snew(struct queued_handler);
4348 qh->msg1 = msg1;
4349 qh->msg2 = msg2;
4350 qh->handler = handler;
4351 qh->ctx = ctx;
4352 qh->next = NULL;
4353
4354 if (ssh->qtail == NULL) {
4355 ssh->qhead = qh;
4356
4357 if (qh->msg1 > 0) {
4358 assert(ssh->packet_dispatch[qh->msg1] == NULL);
4359 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4360 }
4361 if (qh->msg2 > 0) {
4362 assert(ssh->packet_dispatch[qh->msg2] == NULL);
4363 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4364 }
4365 } else {
4366 ssh->qtail->next = qh;
4367 }
4368 ssh->qtail = qh;
4369 }
4370
4371 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4372 {
4373 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4374
4375 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4376 SSH2_MSG_REQUEST_SUCCESS)) {
4377 logeventf(ssh, "Remote port forwarding from %s enabled",
4378 pf->sportdesc);
4379 } else {
4380 logeventf(ssh, "Remote port forwarding from %s refused",
4381 pf->sportdesc);
4382
4383 rpf = del234(ssh->rportfwds, pf);
4384 assert(rpf == pf);
4385 pf->pfrec->remote = NULL;
4386 free_rportfwd(pf);
4387 }
4388 }
4389
4390 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4391 {
4392 struct ssh_portfwd *epf;
4393 int i;
4394 char *key, *val;
4395
4396 if (!ssh->portfwds) {
4397 ssh->portfwds = newtree234(ssh_portcmp);
4398 } else {
4399 /*
4400 * Go through the existing port forwardings and tag them
4401 * with status==DESTROY. Any that we want to keep will be
4402 * re-enabled (status==KEEP) as we go through the
4403 * configuration and find out which bits are the same as
4404 * they were before.
4405 */
4406 struct ssh_portfwd *epf;
4407 int i;
4408 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4409 epf->status = DESTROY;
4410 }
4411
4412 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
4413 val != NULL;
4414 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
4415 char *kp, *kp2, *vp, *vp2;
4416 char address_family, type;
4417 int sport,dport,sserv,dserv;
4418 char *sports, *dports, *saddr, *host;
4419
4420 kp = key;
4421
4422 address_family = 'A';
4423 type = 'L';
4424 if (*kp == 'A' || *kp == '4' || *kp == '6')
4425 address_family = *kp++;
4426 if (*kp == 'L' || *kp == 'R')
4427 type = *kp++;
4428
4429 if ((kp2 = strchr(kp, ':')) != NULL) {
4430 /*
4431 * There's a colon in the middle of the source port
4432 * string, which means that the part before it is
4433 * actually a source address.
4434 */
4435 saddr = dupprintf("%.*s", (int)(kp2 - kp), kp);
4436 sports = kp2+1;
4437 } else {
4438 saddr = NULL;
4439 sports = kp;
4440 }
4441 sport = atoi(sports);
4442 sserv = 0;
4443 if (sport == 0) {
4444 sserv = 1;
4445 sport = net_service_lookup(sports);
4446 if (!sport) {
4447 logeventf(ssh, "Service lookup failed for source"
4448 " port \"%s\"", sports);
4449 }
4450 }
4451
4452 if (type == 'L' && !strcmp(val, "D")) {
4453 /* dynamic forwarding */
4454 host = NULL;
4455 dports = NULL;
4456 dport = -1;
4457 dserv = 0;
4458 type = 'D';
4459 } else {
4460 /* ordinary forwarding */
4461 vp = val;
4462 vp2 = vp + strcspn(vp, ":");
4463 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
4464 if (vp2)
4465 vp2++;
4466 dports = vp2;
4467 dport = atoi(dports);
4468 dserv = 0;
4469 if (dport == 0) {
4470 dserv = 1;
4471 dport = net_service_lookup(dports);
4472 if (!dport) {
4473 logeventf(ssh, "Service lookup failed for destination"
4474 " port \"%s\"", dports);
4475 }
4476 }
4477 }
4478
4479 if (sport && dport) {
4480 /* Set up a description of the source port. */
4481 struct ssh_portfwd *pfrec, *epfrec;
4482
4483 pfrec = snew(struct ssh_portfwd);
4484 pfrec->type = type;
4485 pfrec->saddr = saddr;
4486 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4487 pfrec->sport = sport;
4488 pfrec->daddr = host;
4489 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4490 pfrec->dport = dport;
4491 pfrec->local = NULL;
4492 pfrec->remote = NULL;
4493 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4494 address_family == '6' ? ADDRTYPE_IPV6 :
4495 ADDRTYPE_UNSPEC);
4496
4497 epfrec = add234(ssh->portfwds, pfrec);
4498 if (epfrec != pfrec) {
4499 if (epfrec->status == DESTROY) {
4500 /*
4501 * We already have a port forwarding up and running
4502 * with precisely these parameters. Hence, no need
4503 * to do anything; simply re-tag the existing one
4504 * as KEEP.
4505 */
4506 epfrec->status = KEEP;
4507 }
4508 /*
4509 * Anything else indicates that there was a duplicate
4510 * in our input, which we'll silently ignore.
4511 */
4512 free_portfwd(pfrec);
4513 } else {
4514 pfrec->status = CREATE;
4515 }
4516 } else {
4517 sfree(saddr);
4518 sfree(host);
4519 }
4520 }
4521
4522 /*
4523 * Now go through and destroy any port forwardings which were
4524 * not re-enabled.
4525 */
4526 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4527 if (epf->status == DESTROY) {
4528 char *message;
4529
4530 message = dupprintf("%s port forwarding from %s%s%d",
4531 epf->type == 'L' ? "local" :
4532 epf->type == 'R' ? "remote" : "dynamic",
4533 epf->saddr ? epf->saddr : "",
4534 epf->saddr ? ":" : "",
4535 epf->sport);
4536
4537 if (epf->type != 'D') {
4538 char *msg2 = dupprintf("%s to %s:%d", message,
4539 epf->daddr, epf->dport);
4540 sfree(message);
4541 message = msg2;
4542 }
4543
4544 logeventf(ssh, "Cancelling %s", message);
4545 sfree(message);
4546
4547 /* epf->remote or epf->local may be NULL if setting up a
4548 * forwarding failed. */
4549 if (epf->remote) {
4550 struct ssh_rportfwd *rpf = epf->remote;
4551 struct Packet *pktout;
4552
4553 /*
4554 * Cancel the port forwarding at the server
4555 * end.
4556 */
4557 if (ssh->version == 1) {
4558 /*
4559 * We cannot cancel listening ports on the
4560 * server side in SSH-1! There's no message
4561 * to support it. Instead, we simply remove
4562 * the rportfwd record from the local end
4563 * so that any connections the server tries
4564 * to make on it are rejected.
4565 */
4566 } else {
4567 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4568 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4569 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4570 if (epf->saddr) {
4571 ssh2_pkt_addstring(pktout, epf->saddr);
4572 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4573 /* XXX: rport_acceptall may not represent
4574 * what was used to open the original connection,
4575 * since it's reconfigurable. */
4576 ssh2_pkt_addstring(pktout, "0.0.0.0");
4577 } else {
4578 ssh2_pkt_addstring(pktout, "127.0.0.1");
4579 }
4580 ssh2_pkt_adduint32(pktout, epf->sport);
4581 ssh2_pkt_send(ssh, pktout);
4582 }
4583
4584 del234(ssh->rportfwds, rpf);
4585 free_rportfwd(rpf);
4586 } else if (epf->local) {
4587 pfd_terminate(epf->local);
4588 }
4589
4590 delpos234(ssh->portfwds, i);
4591 free_portfwd(epf);
4592 i--; /* so we don't skip one in the list */
4593 }
4594
4595 /*
4596 * And finally, set up any new port forwardings (status==CREATE).
4597 */
4598 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4599 if (epf->status == CREATE) {
4600 char *sportdesc, *dportdesc;
4601 sportdesc = dupprintf("%s%s%s%s%d%s",
4602 epf->saddr ? epf->saddr : "",
4603 epf->saddr ? ":" : "",
4604 epf->sserv ? epf->sserv : "",
4605 epf->sserv ? "(" : "",
4606 epf->sport,
4607 epf->sserv ? ")" : "");
4608 if (epf->type == 'D') {
4609 dportdesc = NULL;
4610 } else {
4611 dportdesc = dupprintf("%s:%s%s%d%s",
4612 epf->daddr,
4613 epf->dserv ? epf->dserv : "",
4614 epf->dserv ? "(" : "",
4615 epf->dport,
4616 epf->dserv ? ")" : "");
4617 }
4618
4619 if (epf->type == 'L') {
4620 const char *err = pfd_addforward(epf->daddr, epf->dport,
4621 epf->saddr, epf->sport,
4622 ssh, conf,
4623 &epf->local,
4624 epf->addressfamily);
4625
4626 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4627 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4628 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4629 sportdesc, dportdesc,
4630 err ? " failed: " : "", err ? err : "");
4631 } else if (epf->type == 'D') {
4632 const char *err = pfd_addforward(NULL, -1,
4633 epf->saddr, epf->sport,
4634 ssh, conf,
4635 &epf->local,
4636 epf->addressfamily);
4637
4638 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4639 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4640 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4641 sportdesc,
4642 err ? " failed: " : "", err ? err : "");
4643 } else {
4644 struct ssh_rportfwd *pf;
4645
4646 /*
4647 * Ensure the remote port forwardings tree exists.
4648 */
4649 if (!ssh->rportfwds) {
4650 if (ssh->version == 1)
4651 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4652 else
4653 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4654 }
4655
4656 pf = snew(struct ssh_rportfwd);
4657 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4658 pf->dhost[lenof(pf->dhost)-1] = '\0';
4659 pf->dport = epf->dport;
4660 pf->sport = epf->sport;
4661 if (add234(ssh->rportfwds, pf) != pf) {
4662 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4663 epf->daddr, epf->dport);
4664 sfree(pf);
4665 } else {
4666 logeventf(ssh, "Requesting remote port %s"
4667 " forward to %s", sportdesc, dportdesc);
4668
4669 pf->sportdesc = sportdesc;
4670 sportdesc = NULL;
4671 epf->remote = pf;
4672 pf->pfrec = epf;
4673
4674 if (ssh->version == 1) {
4675 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4676 PKT_INT, epf->sport,
4677 PKT_STR, epf->daddr,
4678 PKT_INT, epf->dport,
4679 PKT_END);
4680 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4681 SSH1_SMSG_FAILURE,
4682 ssh_rportfwd_succfail, pf);
4683 } else {
4684 struct Packet *pktout;
4685 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4686 ssh2_pkt_addstring(pktout, "tcpip-forward");
4687 ssh2_pkt_addbool(pktout, 1);/* want reply */
4688 if (epf->saddr) {
4689 ssh2_pkt_addstring(pktout, epf->saddr);
4690 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4691 ssh2_pkt_addstring(pktout, "0.0.0.0");
4692 } else {
4693 ssh2_pkt_addstring(pktout, "127.0.0.1");
4694 }
4695 ssh2_pkt_adduint32(pktout, epf->sport);
4696 ssh2_pkt_send(ssh, pktout);
4697
4698 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4699 SSH2_MSG_REQUEST_FAILURE,
4700 ssh_rportfwd_succfail, pf);
4701 }
4702 }
4703 }
4704 sfree(sportdesc);
4705 sfree(dportdesc);
4706 }
4707 }
4708
4709 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4710 {
4711 char *string;
4712 int stringlen, bufsize;
4713
4714 ssh_pkt_getstring(pktin, &string, &stringlen);
4715 if (string == NULL) {
4716 bombout(("Incoming terminal data packet was badly formed"));
4717 return;
4718 }
4719
4720 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4721 string, stringlen);
4722 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4723 ssh->v1_stdout_throttling = 1;
4724 ssh_throttle_conn(ssh, +1);
4725 }
4726 }
4727
4728 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4729 {
4730 /* Remote side is trying to open a channel to talk to our
4731 * X-Server. Give them back a local channel number. */
4732 struct ssh_channel *c;
4733 int remoteid = ssh_pkt_getuint32(pktin);
4734
4735 logevent("Received X11 connect request");
4736 /* Refuse if X11 forwarding is disabled. */
4737 if (!ssh->X11_fwd_enabled) {
4738 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4739 PKT_INT, remoteid, PKT_END);
4740 logevent("Rejected X11 connect request");
4741 } else {
4742 c = snew(struct ssh_channel);
4743 c->ssh = ssh;
4744
4745 if (x11_init(&c->u.x11.s, ssh->x11disp, c,
4746 NULL, -1, ssh->conf) != NULL) {
4747 logevent("Opening X11 forward connection failed");
4748 sfree(c);
4749 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4750 PKT_INT, remoteid, PKT_END);
4751 } else {
4752 logevent
4753 ("Opening X11 forward connection succeeded");
4754 c->remoteid = remoteid;
4755 c->halfopen = FALSE;
4756 c->localid = alloc_channel_id(ssh);
4757 c->closes = 0;
4758 c->pending_eof = FALSE;
4759 c->throttling_conn = 0;
4760 c->type = CHAN_X11; /* identify channel type */
4761 add234(ssh->channels, c);
4762 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4763 PKT_INT, c->remoteid, PKT_INT,
4764 c->localid, PKT_END);
4765 logevent("Opened X11 forward channel");
4766 }
4767 }
4768 }
4769
4770 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4771 {
4772 /* Remote side is trying to open a channel to talk to our
4773 * agent. Give them back a local channel number. */
4774 struct ssh_channel *c;
4775 int remoteid = ssh_pkt_getuint32(pktin);
4776
4777 /* Refuse if agent forwarding is disabled. */
4778 if (!ssh->agentfwd_enabled) {
4779 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4780 PKT_INT, remoteid, PKT_END);
4781 } else {
4782 c = snew(struct ssh_channel);
4783 c->ssh = ssh;
4784 c->remoteid = remoteid;
4785 c->halfopen = FALSE;
4786 c->localid = alloc_channel_id(ssh);
4787 c->closes = 0;
4788 c->pending_eof = FALSE;
4789 c->throttling_conn = 0;
4790 c->type = CHAN_AGENT; /* identify channel type */
4791 c->u.a.lensofar = 0;
4792 c->u.a.message = NULL;
4793 add234(ssh->channels, c);
4794 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4795 PKT_INT, c->remoteid, PKT_INT, c->localid,
4796 PKT_END);
4797 }
4798 }
4799
4800 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4801 {
4802 /* Remote side is trying to open a channel to talk to a
4803 * forwarded port. Give them back a local channel number. */
4804 struct ssh_channel *c;
4805 struct ssh_rportfwd pf, *pfp;
4806 int remoteid;
4807 int hostsize, port;
4808 char *host;
4809 const char *e;
4810 c = snew(struct ssh_channel);
4811 c->ssh = ssh;
4812
4813 remoteid = ssh_pkt_getuint32(pktin);
4814 ssh_pkt_getstring(pktin, &host, &hostsize);
4815 port = ssh_pkt_getuint32(pktin);
4816
4817 if (hostsize >= lenof(pf.dhost))
4818 hostsize = lenof(pf.dhost)-1;
4819 memcpy(pf.dhost, host, hostsize);
4820 pf.dhost[hostsize] = '\0';
4821 pf.dport = port;
4822 pfp = find234(ssh->rportfwds, &pf, NULL);
4823
4824 if (pfp == NULL) {
4825 logeventf(ssh, "Rejected remote port open request for %s:%d",
4826 pf.dhost, port);
4827 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4828 PKT_INT, remoteid, PKT_END);
4829 } else {
4830 logeventf(ssh, "Received remote port open request for %s:%d",
4831 pf.dhost, port);
4832 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4833 c, ssh->conf, pfp->pfrec->addressfamily);
4834 if (e != NULL) {
4835 logeventf(ssh, "Port open failed: %s", e);
4836 sfree(c);
4837 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4838 PKT_INT, remoteid, PKT_END);
4839 } else {
4840 c->remoteid = remoteid;
4841 c->halfopen = FALSE;
4842 c->localid = alloc_channel_id(ssh);
4843 c->closes = 0;
4844 c->pending_eof = FALSE;
4845 c->throttling_conn = 0;
4846 c->type = CHAN_SOCKDATA; /* identify channel type */
4847 add234(ssh->channels, c);
4848 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4849 PKT_INT, c->remoteid, PKT_INT,
4850 c->localid, PKT_END);
4851 logevent("Forwarded port opened successfully");
4852 }
4853 }
4854 }
4855
4856 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4857 {
4858 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4859 unsigned int localid = ssh_pkt_getuint32(pktin);
4860 struct ssh_channel *c;
4861
4862 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4863 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4864 c->remoteid = localid;
4865 c->halfopen = FALSE;
4866 c->type = CHAN_SOCKDATA;
4867 c->throttling_conn = 0;
4868 pfd_confirm(c->u.pfd.s);
4869 }
4870
4871 if (c && c->pending_eof) {
4872 /*
4873 * We have a pending close on this channel,
4874 * which we decided on before the server acked
4875 * the channel open. So now we know the
4876 * remoteid, we can close it again.
4877 */
4878 ssh_channel_try_eof(c);
4879 }
4880 }
4881
4882 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4883 {
4884 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4885 struct ssh_channel *c;
4886
4887 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4888 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4889 logevent("Forwarded connection refused by server");
4890 pfd_close(c->u.pfd.s);
4891 del234(ssh->channels, c);
4892 sfree(c);
4893 }
4894 }
4895
4896 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4897 {
4898 /* Remote side closes a channel. */
4899 unsigned i = ssh_pkt_getuint32(pktin);
4900 struct ssh_channel *c;
4901 c = find234(ssh->channels, &i, ssh_channelfind);
4902 if (c && !c->halfopen) {
4903
4904 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
4905 !(c->closes & CLOSES_RCVD_EOF)) {
4906 /*
4907 * Received CHANNEL_CLOSE, which we translate into
4908 * outgoing EOF.
4909 */
4910 int send_close = FALSE;
4911
4912 c->closes |= CLOSES_RCVD_EOF;
4913
4914 switch (c->type) {
4915 case CHAN_X11:
4916 if (c->u.x11.s)
4917 x11_send_eof(c->u.x11.s);
4918 else
4919 send_close = TRUE;
4920 case CHAN_SOCKDATA:
4921 if (c->u.pfd.s)
4922 x11_send_eof(c->u.pfd.s);
4923 else
4924 send_close = TRUE;
4925 case CHAN_AGENT:
4926 send_close = TRUE;
4927 }
4928
4929 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
4930 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4931 PKT_END);
4932 c->closes |= CLOSES_SENT_EOF;
4933 }
4934 }
4935
4936 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
4937 !(c->closes & CLOSES_RCVD_CLOSE)) {
4938
4939 if (!(c->closes & CLOSES_SENT_EOF)) {
4940 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
4941 " for which we never sent CHANNEL_CLOSE\n", i));
4942 }
4943
4944 c->closes |= CLOSES_RCVD_CLOSE;
4945 }
4946
4947 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
4948 !(c->closes & CLOSES_SENT_CLOSE)) {
4949 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
4950 PKT_INT, c->remoteid, PKT_END);
4951 c->closes |= CLOSES_SENT_CLOSE;
4952 }
4953
4954 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
4955 ssh_channel_destroy(c);
4956 } else {
4957 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4958 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4959 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4960 i));
4961 }
4962 }
4963
4964 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4965 {
4966 /* Data sent down one of our channels. */
4967 int i = ssh_pkt_getuint32(pktin);
4968 char *p;
4969 int len;
4970 struct ssh_channel *c;
4971
4972 ssh_pkt_getstring(pktin, &p, &len);
4973
4974 c = find234(ssh->channels, &i, ssh_channelfind);
4975 if (c) {
4976 int bufsize = 0;
4977 switch (c->type) {
4978 case CHAN_X11:
4979 bufsize = x11_send(c->u.x11.s, p, len);
4980 break;
4981 case CHAN_SOCKDATA:
4982 bufsize = pfd_send(c->u.pfd.s, p, len);
4983 break;
4984 case CHAN_AGENT:
4985 /* Data for an agent message. Buffer it. */
4986 while (len > 0) {
4987 if (c->u.a.lensofar < 4) {
4988 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
4989 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4990 l);
4991 p += l;
4992 len -= l;
4993 c->u.a.lensofar += l;
4994 }
4995 if (c->u.a.lensofar == 4) {
4996 c->u.a.totallen =
4997 4 + GET_32BIT(c->u.a.msglen);
4998 c->u.a.message = snewn(c->u.a.totallen,
4999 unsigned char);
5000 memcpy(c->u.a.message, c->u.a.msglen, 4);
5001 }
5002 if (c->u.a.lensofar >= 4 && len > 0) {
5003 unsigned int l =
5004 min(c->u.a.totallen - c->u.a.lensofar,
5005 (unsigned)len);
5006 memcpy(c->u.a.message + c->u.a.lensofar, p,
5007 l);
5008 p += l;
5009 len -= l;
5010 c->u.a.lensofar += l;
5011 }
5012 if (c->u.a.lensofar == c->u.a.totallen) {
5013 void *reply;
5014 int replylen;
5015 if (agent_query(c->u.a.message,
5016 c->u.a.totallen,
5017 &reply, &replylen,
5018 ssh_agentf_callback, c))
5019 ssh_agentf_callback(c, reply, replylen);
5020 sfree(c->u.a.message);
5021 c->u.a.lensofar = 0;
5022 }
5023 }
5024 bufsize = 0; /* agent channels never back up */
5025 break;
5026 }
5027 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5028 c->throttling_conn = 1;
5029 ssh_throttle_conn(ssh, +1);
5030 }
5031 }
5032 }
5033
5034 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5035 {
5036 ssh->exitcode = ssh_pkt_getuint32(pktin);
5037 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5038 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5039 /*
5040 * In case `helpful' firewalls or proxies tack
5041 * extra human-readable text on the end of the
5042 * session which we might mistake for another
5043 * encrypted packet, we close the session once
5044 * we've sent EXIT_CONFIRMATION.
5045 */
5046 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5047 }
5048
5049 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5050 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5051 {
5052 struct Packet *pktout = (struct Packet *)data;
5053 int i = 0;
5054 unsigned int arg = 0;
5055 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5056 if (i == lenof(ssh_ttymodes)) return;
5057 switch (ssh_ttymodes[i].type) {
5058 case TTY_OP_CHAR:
5059 arg = ssh_tty_parse_specchar(val);
5060 break;
5061 case TTY_OP_BOOL:
5062 arg = ssh_tty_parse_boolean(val);
5063 break;
5064 }
5065 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5066 ssh2_pkt_addbyte(pktout, arg);
5067 }
5068
5069
5070 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5071 struct Packet *pktin)
5072 {
5073 crBegin(ssh->do_ssh1_connection_crstate);
5074
5075 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5076 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5077 ssh1_smsg_stdout_stderr_data;
5078
5079 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5080 ssh1_msg_channel_open_confirmation;
5081 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5082 ssh1_msg_channel_open_failure;
5083 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5084 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5085 ssh1_msg_channel_close;
5086 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5087 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5088
5089 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
5090 logevent("Requesting agent forwarding");
5091 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5092 do {
5093 crReturnV;
5094 } while (!pktin);
5095 if (pktin->type != SSH1_SMSG_SUCCESS
5096 && pktin->type != SSH1_SMSG_FAILURE) {
5097 bombout(("Protocol confusion"));
5098 crStopV;
5099 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5100 logevent("Agent forwarding refused");
5101 } else {
5102 logevent("Agent forwarding enabled");
5103 ssh->agentfwd_enabled = TRUE;
5104 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5105 }
5106 }
5107
5108 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
5109 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5110 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
5111 logevent("Requesting X11 forwarding");
5112 /*
5113 * Note that while we blank the X authentication data here, we don't
5114 * take any special action to blank the start of an X11 channel,
5115 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
5116 * without having session blanking enabled is likely to leak your
5117 * cookie into the log.
5118 */
5119 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5120 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5121 PKT_STR, ssh->x11disp->remoteauthprotoname,
5122 PKTT_PASSWORD,
5123 PKT_STR, ssh->x11disp->remoteauthdatastring,
5124 PKTT_OTHER,
5125 PKT_INT, ssh->x11disp->screennum,
5126 PKT_END);
5127 } else {
5128 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5129 PKT_STR, ssh->x11disp->remoteauthprotoname,
5130 PKTT_PASSWORD,
5131 PKT_STR, ssh->x11disp->remoteauthdatastring,
5132 PKTT_OTHER,
5133 PKT_END);
5134 }
5135 do {
5136 crReturnV;
5137 } while (!pktin);
5138 if (pktin->type != SSH1_SMSG_SUCCESS
5139 && pktin->type != SSH1_SMSG_FAILURE) {
5140 bombout(("Protocol confusion"));
5141 crStopV;
5142 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5143 logevent("X11 forwarding refused");
5144 } else {
5145 logevent("X11 forwarding enabled");
5146 ssh->X11_fwd_enabled = TRUE;
5147 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5148 }
5149 }
5150
5151 ssh_setup_portfwd(ssh, ssh->conf);
5152 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5153
5154 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5155 struct Packet *pkt;
5156 /* Unpick the terminal-speed string. */
5157 /* XXX perhaps we should allow no speeds to be sent. */
5158 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5159 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5160 /* Send the pty request. */
5161 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5162 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5163 ssh_pkt_adduint32(pkt, ssh->term_height);
5164 ssh_pkt_adduint32(pkt, ssh->term_width);
5165 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5166 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5167 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5168 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5169 ssh_pkt_adduint32(pkt, ssh->ispeed);
5170 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5171 ssh_pkt_adduint32(pkt, ssh->ospeed);
5172 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5173 s_wrpkt(ssh, pkt);
5174 ssh->state = SSH_STATE_INTERMED;
5175 do {
5176 crReturnV;
5177 } while (!pktin);
5178 if (pktin->type != SSH1_SMSG_SUCCESS
5179 && pktin->type != SSH1_SMSG_FAILURE) {
5180 bombout(("Protocol confusion"));
5181 crStopV;
5182 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5183 c_write_str(ssh, "Server refused to allocate pty\r\n");
5184 ssh->editing = ssh->echoing = 1;
5185 } else {
5186 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5187 ssh->ospeed, ssh->ispeed);
5188 ssh->got_pty = TRUE;
5189 }
5190 } else {
5191 ssh->editing = ssh->echoing = 1;
5192 }
5193
5194 if (conf_get_int(ssh->conf, CONF_compression)) {
5195 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5196 do {
5197 crReturnV;
5198 } while (!pktin);
5199 if (pktin->type != SSH1_SMSG_SUCCESS
5200 && pktin->type != SSH1_SMSG_FAILURE) {
5201 bombout(("Protocol confusion"));
5202 crStopV;
5203 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5204 c_write_str(ssh, "Server refused to compress\r\n");
5205 }
5206 logevent("Started compression");
5207 ssh->v1_compressing = TRUE;
5208 ssh->cs_comp_ctx = zlib_compress_init();
5209 logevent("Initialised zlib (RFC1950) compression");
5210 ssh->sc_comp_ctx = zlib_decompress_init();
5211 logevent("Initialised zlib (RFC1950) decompression");
5212 }
5213
5214 /*
5215 * Start the shell or command.
5216 *
5217 * Special case: if the first-choice command is an SSH-2
5218 * subsystem (hence not usable here) and the second choice
5219 * exists, we fall straight back to that.
5220 */
5221 {
5222 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5223
5224 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5225 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5226 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5227 ssh->fallback_cmd = TRUE;
5228 }
5229 if (*cmd)
5230 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5231 else
5232 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5233 logevent("Started session");
5234 }
5235
5236 ssh->state = SSH_STATE_SESSION;
5237 if (ssh->size_needed)
5238 ssh_size(ssh, ssh->term_width, ssh->term_height);
5239 if (ssh->eof_needed)
5240 ssh_special(ssh, TS_EOF);
5241
5242 if (ssh->ldisc)
5243 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5244 ssh->send_ok = 1;
5245 ssh->channels = newtree234(ssh_channelcmp);
5246 while (1) {
5247
5248 /*
5249 * By this point, most incoming packets are already being
5250 * handled by the dispatch table, and we need only pay
5251 * attention to the unusual ones.
5252 */
5253
5254 crReturnV;
5255 if (pktin) {
5256 if (pktin->type == SSH1_SMSG_SUCCESS) {
5257 /* may be from EXEC_SHELL on some servers */
5258 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5259 /* may be from EXEC_SHELL on some servers
5260 * if no pty is available or in other odd cases. Ignore */
5261 } else {
5262 bombout(("Strange packet received: type %d", pktin->type));
5263 crStopV;
5264 }
5265 } else {
5266 while (inlen > 0) {
5267 int len = min(inlen, 512);
5268 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5269 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
5270 PKTT_OTHER, PKT_END);
5271 in += len;
5272 inlen -= len;
5273 }
5274 }
5275 }
5276
5277 crFinishV;
5278 }
5279
5280 /*
5281 * Handle the top-level SSH-2 protocol.
5282 */
5283 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5284 {
5285 char *msg;
5286 int msglen;
5287
5288 ssh_pkt_getstring(pktin, &msg, &msglen);
5289 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5290 }
5291
5292 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5293 {
5294 /* log reason code in disconnect message */
5295 char *msg;
5296 int msglen;
5297
5298 ssh_pkt_getstring(pktin, &msg, &msglen);
5299 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5300 }
5301
5302 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5303 {
5304 /* Do nothing, because we're ignoring it! Duhh. */
5305 }
5306
5307 static void ssh1_protocol_setup(Ssh ssh)
5308 {
5309 int i;
5310
5311 /*
5312 * Most messages are handled by the coroutines.
5313 */
5314 for (i = 0; i < 256; i++)
5315 ssh->packet_dispatch[i] = NULL;
5316
5317 /*
5318 * These special message types we install handlers for.
5319 */
5320 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5321 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5322 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5323 }
5324
5325 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5326 struct Packet *pktin)
5327 {
5328 unsigned char *in=(unsigned char*)vin;
5329 if (ssh->state == SSH_STATE_CLOSED)
5330 return;
5331
5332 if (pktin && ssh->packet_dispatch[pktin->type]) {
5333 ssh->packet_dispatch[pktin->type](ssh, pktin);
5334 return;
5335 }
5336
5337 if (!ssh->protocol_initial_phase_done) {
5338 if (do_ssh1_login(ssh, in, inlen, pktin))
5339 ssh->protocol_initial_phase_done = TRUE;
5340 else
5341 return;
5342 }
5343
5344 do_ssh1_connection(ssh, in, inlen, pktin);
5345 }
5346
5347 /*
5348 * Utility routine for decoding comma-separated strings in KEXINIT.
5349 */
5350 static int in_commasep_string(char *needle, char *haystack, int haylen)
5351 {
5352 int needlen;
5353 if (!needle || !haystack) /* protect against null pointers */
5354 return 0;
5355 needlen = strlen(needle);
5356 while (1) {
5357 /*
5358 * Is it at the start of the string?
5359 */
5360 if (haylen >= needlen && /* haystack is long enough */
5361 !memcmp(needle, haystack, needlen) && /* initial match */
5362 (haylen == needlen || haystack[needlen] == ',')
5363 /* either , or EOS follows */
5364 )
5365 return 1;
5366 /*
5367 * If not, search for the next comma and resume after that.
5368 * If no comma found, terminate.
5369 */
5370 while (haylen > 0 && *haystack != ',')
5371 haylen--, haystack++;
5372 if (haylen == 0)
5373 return 0;
5374 haylen--, haystack++; /* skip over comma itself */
5375 }
5376 }
5377
5378 /*
5379 * Similar routine for checking whether we have the first string in a list.
5380 */
5381 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5382 {
5383 int needlen;
5384 if (!needle || !haystack) /* protect against null pointers */
5385 return 0;
5386 needlen = strlen(needle);
5387 /*
5388 * Is it at the start of the string?
5389 */
5390 if (haylen >= needlen && /* haystack is long enough */
5391 !memcmp(needle, haystack, needlen) && /* initial match */
5392 (haylen == needlen || haystack[needlen] == ',')
5393 /* either , or EOS follows */
5394 )
5395 return 1;
5396 return 0;
5397 }
5398
5399
5400 /*
5401 * SSH-2 key creation method.
5402 * (Currently assumes 2 lots of any hash are sufficient to generate
5403 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5404 */
5405 #define SSH2_MKKEY_ITERS (2)
5406 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5407 unsigned char *keyspace)
5408 {
5409 const struct ssh_hash *h = ssh->kex->hash;
5410 void *s;
5411 /* First hlen bytes. */
5412 s = h->init();
5413 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5414 hash_mpint(h, s, K);
5415 h->bytes(s, H, h->hlen);
5416 h->bytes(s, &chr, 1);
5417 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5418 h->final(s, keyspace);
5419 /* Next hlen bytes. */
5420 s = h->init();
5421 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5422 hash_mpint(h, s, K);
5423 h->bytes(s, H, h->hlen);
5424 h->bytes(s, keyspace, h->hlen);
5425 h->final(s, keyspace + h->hlen);
5426 }
5427
5428 /*
5429 * Handle the SSH-2 transport layer.
5430 */
5431 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5432 struct Packet *pktin)
5433 {
5434 unsigned char *in = (unsigned char *)vin;
5435 struct do_ssh2_transport_state {
5436 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5437 Bignum p, g, e, f, K;
5438 void *our_kexinit;
5439 int our_kexinitlen;
5440 int kex_init_value, kex_reply_value;
5441 const struct ssh_mac **maclist;
5442 int nmacs;
5443 const struct ssh2_cipher *cscipher_tobe;
5444 const struct ssh2_cipher *sccipher_tobe;
5445 const struct ssh_mac *csmac_tobe;
5446 const struct ssh_mac *scmac_tobe;
5447 const struct ssh_compress *cscomp_tobe;
5448 const struct ssh_compress *sccomp_tobe;
5449 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5450 int hostkeylen, siglen, rsakeylen;
5451 void *hkey; /* actual host key */
5452 void *rsakey; /* for RSA kex */
5453 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5454 int n_preferred_kex;
5455 const struct ssh_kexes *preferred_kex[KEX_MAX];
5456 int n_preferred_ciphers;
5457 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5458 const struct ssh_compress *preferred_comp;
5459 int userauth_succeeded; /* for delayed compression */
5460 int pending_compression;
5461 int got_session_id, activated_authconn;
5462 struct Packet *pktout;
5463 int dlgret;
5464 int guessok;
5465 int ignorepkt;
5466 };
5467 crState(do_ssh2_transport_state);
5468
5469 crBegin(ssh->do_ssh2_transport_crstate);
5470
5471 s->cscipher_tobe = s->sccipher_tobe = NULL;
5472 s->csmac_tobe = s->scmac_tobe = NULL;
5473 s->cscomp_tobe = s->sccomp_tobe = NULL;
5474
5475 s->got_session_id = s->activated_authconn = FALSE;
5476 s->userauth_succeeded = FALSE;
5477 s->pending_compression = FALSE;
5478
5479 /*
5480 * Be prepared to work around the buggy MAC problem.
5481 */
5482 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5483 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5484 else
5485 s->maclist = macs, s->nmacs = lenof(macs);
5486
5487 begin_key_exchange:
5488 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5489 {
5490 int i, j, commalist_started;
5491
5492 /*
5493 * Set up the preferred key exchange. (NULL => warn below here)
5494 */
5495 s->n_preferred_kex = 0;
5496 for (i = 0; i < KEX_MAX; i++) {
5497 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
5498 case KEX_DHGEX:
5499 s->preferred_kex[s->n_preferred_kex++] =
5500 &ssh_diffiehellman_gex;
5501 break;
5502 case KEX_DHGROUP14:
5503 s->preferred_kex[s->n_preferred_kex++] =
5504 &ssh_diffiehellman_group14;
5505 break;
5506 case KEX_DHGROUP1:
5507 s->preferred_kex[s->n_preferred_kex++] =
5508 &ssh_diffiehellman_group1;
5509 break;
5510 case KEX_RSA:
5511 s->preferred_kex[s->n_preferred_kex++] =
5512 &ssh_rsa_kex;
5513 break;
5514 case KEX_WARN:
5515 /* Flag for later. Don't bother if it's the last in
5516 * the list. */
5517 if (i < KEX_MAX - 1) {
5518 s->preferred_kex[s->n_preferred_kex++] = NULL;
5519 }
5520 break;
5521 }
5522 }
5523
5524 /*
5525 * Set up the preferred ciphers. (NULL => warn below here)
5526 */
5527 s->n_preferred_ciphers = 0;
5528 for (i = 0; i < CIPHER_MAX; i++) {
5529 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
5530 case CIPHER_BLOWFISH:
5531 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5532 break;
5533 case CIPHER_DES:
5534 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
5535 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5536 }
5537 break;
5538 case CIPHER_3DES:
5539 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5540 break;
5541 case CIPHER_AES:
5542 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5543 break;
5544 case CIPHER_ARCFOUR:
5545 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5546 break;
5547 case CIPHER_WARN:
5548 /* Flag for later. Don't bother if it's the last in
5549 * the list. */
5550 if (i < CIPHER_MAX - 1) {
5551 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5552 }
5553 break;
5554 }
5555 }
5556
5557 /*
5558 * Set up preferred compression.
5559 */
5560 if (conf_get_int(ssh->conf, CONF_compression))
5561 s->preferred_comp = &ssh_zlib;
5562 else
5563 s->preferred_comp = &ssh_comp_none;
5564
5565 /*
5566 * Enable queueing of outgoing auth- or connection-layer
5567 * packets while we are in the middle of a key exchange.
5568 */
5569 ssh->queueing = TRUE;
5570
5571 /*
5572 * Flag that KEX is in progress.
5573 */
5574 ssh->kex_in_progress = TRUE;
5575
5576 /*
5577 * Construct and send our key exchange packet.
5578 */
5579 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5580 for (i = 0; i < 16; i++)
5581 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5582 /* List key exchange algorithms. */
5583 ssh2_pkt_addstring_start(s->pktout);
5584 commalist_started = 0;
5585 for (i = 0; i < s->n_preferred_kex; i++) {
5586 const struct ssh_kexes *k = s->preferred_kex[i];
5587 if (!k) continue; /* warning flag */
5588 for (j = 0; j < k->nkexes; j++) {
5589 if (commalist_started)
5590 ssh2_pkt_addstring_str(s->pktout, ",");
5591 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5592 commalist_started = 1;
5593 }
5594 }
5595 /* List server host key algorithms. */
5596 ssh2_pkt_addstring_start(s->pktout);
5597 for (i = 0; i < lenof(hostkey_algs); i++) {
5598 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5599 if (i < lenof(hostkey_algs) - 1)
5600 ssh2_pkt_addstring_str(s->pktout, ",");
5601 }
5602 /* List client->server encryption algorithms. */
5603 ssh2_pkt_addstring_start(s->pktout);
5604 commalist_started = 0;
5605 for (i = 0; i < s->n_preferred_ciphers; i++) {
5606 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5607 if (!c) continue; /* warning flag */
5608 for (j = 0; j < c->nciphers; j++) {
5609 if (commalist_started)
5610 ssh2_pkt_addstring_str(s->pktout, ",");
5611 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5612 commalist_started = 1;
5613 }
5614 }
5615 /* List server->client encryption algorithms. */
5616 ssh2_pkt_addstring_start(s->pktout);
5617 commalist_started = 0;
5618 for (i = 0; i < s->n_preferred_ciphers; i++) {
5619 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5620 if (!c) continue; /* warning flag */
5621 for (j = 0; j < c->nciphers; j++) {
5622 if (commalist_started)
5623 ssh2_pkt_addstring_str(s->pktout, ",");
5624 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5625 commalist_started = 1;
5626 }
5627 }
5628 /* List client->server MAC algorithms. */
5629 ssh2_pkt_addstring_start(s->pktout);
5630 for (i = 0; i < s->nmacs; i++) {
5631 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5632 if (i < s->nmacs - 1)
5633 ssh2_pkt_addstring_str(s->pktout, ",");
5634 }
5635 /* List server->client MAC algorithms. */
5636 ssh2_pkt_addstring_start(s->pktout);
5637 for (i = 0; i < s->nmacs; i++) {
5638 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5639 if (i < s->nmacs - 1)
5640 ssh2_pkt_addstring_str(s->pktout, ",");
5641 }
5642 /* List client->server compression algorithms,
5643 * then server->client compression algorithms. (We use the
5644 * same set twice.) */
5645 for (j = 0; j < 2; j++) {
5646 ssh2_pkt_addstring_start(s->pktout);
5647 assert(lenof(compressions) > 1);
5648 /* Prefer non-delayed versions */
5649 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5650 /* We don't even list delayed versions of algorithms until
5651 * they're allowed to be used, to avoid a race. See the end of
5652 * this function. */
5653 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
5654 ssh2_pkt_addstring_str(s->pktout, ",");
5655 ssh2_pkt_addstring_str(s->pktout,
5656 s->preferred_comp->delayed_name);
5657 }
5658 for (i = 0; i < lenof(compressions); i++) {
5659 const struct ssh_compress *c = compressions[i];
5660 if (c != s->preferred_comp) {
5661 ssh2_pkt_addstring_str(s->pktout, ",");
5662 ssh2_pkt_addstring_str(s->pktout, c->name);
5663 if (s->userauth_succeeded && c->delayed_name) {
5664 ssh2_pkt_addstring_str(s->pktout, ",");
5665 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
5666 }
5667 }
5668 }
5669 }
5670 /* List client->server languages. Empty list. */
5671 ssh2_pkt_addstring_start(s->pktout);
5672 /* List server->client languages. Empty list. */
5673 ssh2_pkt_addstring_start(s->pktout);
5674 /* First KEX packet does _not_ follow, because we're not that brave. */
5675 ssh2_pkt_addbool(s->pktout, FALSE);
5676 /* Reserved. */
5677 ssh2_pkt_adduint32(s->pktout, 0);
5678 }
5679
5680 s->our_kexinitlen = s->pktout->length - 5;
5681 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5682 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5683
5684 ssh2_pkt_send_noqueue(ssh, s->pktout);
5685
5686 if (!pktin)
5687 crWaitUntil(pktin);
5688
5689 /*
5690 * Now examine the other side's KEXINIT to see what we're up
5691 * to.
5692 */
5693 {
5694 char *str, *preferred;
5695 int i, j, len;
5696
5697 if (pktin->type != SSH2_MSG_KEXINIT) {
5698 bombout(("expected key exchange packet from server"));
5699 crStop(0);
5700 }
5701 ssh->kex = NULL;
5702 ssh->hostkey = NULL;
5703 s->cscipher_tobe = NULL;
5704 s->sccipher_tobe = NULL;
5705 s->csmac_tobe = NULL;
5706 s->scmac_tobe = NULL;
5707 s->cscomp_tobe = NULL;
5708 s->sccomp_tobe = NULL;
5709 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5710
5711 pktin->savedpos += 16; /* skip garbage cookie */
5712 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5713
5714 preferred = NULL;
5715 for (i = 0; i < s->n_preferred_kex; i++) {
5716 const struct ssh_kexes *k = s->preferred_kex[i];
5717 if (!k) {
5718 s->warn_kex = TRUE;
5719 } else {
5720 for (j = 0; j < k->nkexes; j++) {
5721 if (!preferred) preferred = k->list[j]->name;
5722 if (in_commasep_string(k->list[j]->name, str, len)) {
5723 ssh->kex = k->list[j];
5724 break;
5725 }
5726 }
5727 }
5728 if (ssh->kex)
5729 break;
5730 }
5731 if (!ssh->kex) {
5732 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5733 str ? str : "(null)"));
5734 crStop(0);
5735 }
5736 /*
5737 * Note that the server's guess is considered wrong if it doesn't match
5738 * the first algorithm in our list, even if it's still the algorithm
5739 * we end up using.
5740 */
5741 s->guessok = first_in_commasep_string(preferred, str, len);
5742 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5743 for (i = 0; i < lenof(hostkey_algs); i++) {
5744 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5745 ssh->hostkey = hostkey_algs[i];
5746 break;
5747 }
5748 }
5749 s->guessok = s->guessok &&
5750 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5751 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5752 for (i = 0; i < s->n_preferred_ciphers; i++) {
5753 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5754 if (!c) {
5755 s->warn_cscipher = TRUE;
5756 } else {
5757 for (j = 0; j < c->nciphers; j++) {
5758 if (in_commasep_string(c->list[j]->name, str, len)) {
5759 s->cscipher_tobe = c->list[j];
5760 break;
5761 }
5762 }
5763 }
5764 if (s->cscipher_tobe)
5765 break;
5766 }
5767 if (!s->cscipher_tobe) {
5768 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5769 str ? str : "(null)"));
5770 crStop(0);
5771 }
5772
5773 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5774 for (i = 0; i < s->n_preferred_ciphers; i++) {
5775 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5776 if (!c) {
5777 s->warn_sccipher = TRUE;
5778 } else {
5779 for (j = 0; j < c->nciphers; j++) {
5780 if (in_commasep_string(c->list[j]->name, str, len)) {
5781 s->sccipher_tobe = c->list[j];
5782 break;
5783 }
5784 }
5785 }
5786 if (s->sccipher_tobe)
5787 break;
5788 }
5789 if (!s->sccipher_tobe) {
5790 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5791 str ? str : "(null)"));
5792 crStop(0);
5793 }
5794
5795 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5796 for (i = 0; i < s->nmacs; i++) {
5797 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5798 s->csmac_tobe = s->maclist[i];
5799 break;
5800 }
5801 }
5802 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5803 for (i = 0; i < s->nmacs; i++) {
5804 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5805 s->scmac_tobe = s->maclist[i];
5806 break;
5807 }
5808 }
5809 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5810 for (i = 0; i < lenof(compressions) + 1; i++) {
5811 const struct ssh_compress *c =
5812 i == 0 ? s->preferred_comp : compressions[i - 1];
5813 if (in_commasep_string(c->name, str, len)) {
5814 s->cscomp_tobe = c;
5815 break;
5816 } else if (in_commasep_string(c->delayed_name, str, len)) {
5817 if (s->userauth_succeeded) {
5818 s->cscomp_tobe = c;
5819 break;
5820 } else {
5821 s->pending_compression = TRUE; /* try this later */
5822 }
5823 }
5824 }
5825 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5826 for (i = 0; i < lenof(compressions) + 1; i++) {
5827 const struct ssh_compress *c =
5828 i == 0 ? s->preferred_comp : compressions[i - 1];
5829 if (in_commasep_string(c->name, str, len)) {
5830 s->sccomp_tobe = c;
5831 break;
5832 } else if (in_commasep_string(c->delayed_name, str, len)) {
5833 if (s->userauth_succeeded) {
5834 s->sccomp_tobe = c;
5835 break;
5836 } else {
5837 s->pending_compression = TRUE; /* try this later */
5838 }
5839 }
5840 }
5841 if (s->pending_compression) {
5842 logevent("Server supports delayed compression; "
5843 "will try this later");
5844 }
5845 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5846 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5847 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5848
5849 if (s->warn_kex) {
5850 ssh_set_frozen(ssh, 1);
5851 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5852 ssh->kex->name,
5853 ssh_dialog_callback, ssh);
5854 if (s->dlgret < 0) {
5855 do {
5856 crReturn(0);
5857 if (pktin) {
5858 bombout(("Unexpected data from server while"
5859 " waiting for user response"));
5860 crStop(0);
5861 }
5862 } while (pktin || inlen > 0);
5863 s->dlgret = ssh->user_response;
5864 }
5865 ssh_set_frozen(ssh, 0);
5866 if (s->dlgret == 0) {
5867 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5868 0, TRUE);
5869 crStop(0);
5870 }
5871 }
5872
5873 if (s->warn_cscipher) {
5874 ssh_set_frozen(ssh, 1);
5875 s->dlgret = askalg(ssh->frontend,
5876 "client-to-server cipher",
5877 s->cscipher_tobe->name,
5878 ssh_dialog_callback, ssh);
5879 if (s->dlgret < 0) {
5880 do {
5881 crReturn(0);
5882 if (pktin) {
5883 bombout(("Unexpected data from server while"
5884 " waiting for user response"));
5885 crStop(0);
5886 }
5887 } while (pktin || inlen > 0);
5888 s->dlgret = ssh->user_response;
5889 }
5890 ssh_set_frozen(ssh, 0);
5891 if (s->dlgret == 0) {
5892 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5893 0, TRUE);
5894 crStop(0);
5895 }
5896 }
5897
5898 if (s->warn_sccipher) {
5899 ssh_set_frozen(ssh, 1);
5900 s->dlgret = askalg(ssh->frontend,
5901 "server-to-client cipher",
5902 s->sccipher_tobe->name,
5903 ssh_dialog_callback, ssh);
5904 if (s->dlgret < 0) {
5905 do {
5906 crReturn(0);
5907 if (pktin) {
5908 bombout(("Unexpected data from server while"
5909 " waiting for user response"));
5910 crStop(0);
5911 }
5912 } while (pktin || inlen > 0);
5913 s->dlgret = ssh->user_response;
5914 }
5915 ssh_set_frozen(ssh, 0);
5916 if (s->dlgret == 0) {
5917 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5918 0, TRUE);
5919 crStop(0);
5920 }
5921 }
5922
5923 ssh->exhash = ssh->kex->hash->init();
5924 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5925 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5926 hash_string(ssh->kex->hash, ssh->exhash,
5927 s->our_kexinit, s->our_kexinitlen);
5928 sfree(s->our_kexinit);
5929 if (pktin->length > 5)
5930 hash_string(ssh->kex->hash, ssh->exhash,
5931 pktin->data + 5, pktin->length - 5);
5932
5933 if (s->ignorepkt) /* first_kex_packet_follows */
5934 crWaitUntil(pktin); /* Ignore packet */
5935 }
5936
5937 if (ssh->kex->main_type == KEXTYPE_DH) {
5938 /*
5939 * Work out the number of bits of key we will need from the
5940 * key exchange. We start with the maximum key length of
5941 * either cipher...
5942 */
5943 {
5944 int csbits, scbits;
5945
5946 csbits = s->cscipher_tobe->keylen;
5947 scbits = s->sccipher_tobe->keylen;
5948 s->nbits = (csbits > scbits ? csbits : scbits);
5949 }
5950 /* The keys only have hlen-bit entropy, since they're based on
5951 * a hash. So cap the key size at hlen bits. */
5952 if (s->nbits > ssh->kex->hash->hlen * 8)
5953 s->nbits = ssh->kex->hash->hlen * 8;
5954
5955 /*
5956 * If we're doing Diffie-Hellman group exchange, start by
5957 * requesting a group.
5958 */
5959 if (!ssh->kex->pdata) {
5960 logevent("Doing Diffie-Hellman group exchange");
5961 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
5962 /*
5963 * Work out how big a DH group we will need to allow that
5964 * much data.
5965 */
5966 s->pbits = 512 << ((s->nbits - 1) / 64);
5967 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5968 ssh2_pkt_adduint32(s->pktout, s->pbits);
5969 ssh2_pkt_send_noqueue(ssh, s->pktout);
5970
5971 crWaitUntil(pktin);
5972 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5973 bombout(("expected key exchange group packet from server"));
5974 crStop(0);
5975 }
5976 s->p = ssh2_pkt_getmp(pktin);
5977 s->g = ssh2_pkt_getmp(pktin);
5978 if (!s->p || !s->g) {
5979 bombout(("unable to read mp-ints from incoming group packet"));
5980 crStop(0);
5981 }
5982 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5983 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5984 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5985 } else {
5986 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
5987 ssh->kex_ctx = dh_setup_group(ssh->kex);
5988 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5989 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5990 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5991 ssh->kex->groupname);
5992 }
5993
5994 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
5995 ssh->kex->hash->text_name);
5996 /*
5997 * Now generate and send e for Diffie-Hellman.
5998 */
5999 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6000 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6001 s->pktout = ssh2_pkt_init(s->kex_init_value);
6002 ssh2_pkt_addmp(s->pktout, s->e);
6003 ssh2_pkt_send_noqueue(ssh, s->pktout);
6004
6005 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6006 crWaitUntil(pktin);
6007 if (pktin->type != s->kex_reply_value) {
6008 bombout(("expected key exchange reply packet from server"));
6009 crStop(0);
6010 }
6011 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6012 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6013 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6014 s->f = ssh2_pkt_getmp(pktin);
6015 if (!s->f) {
6016 bombout(("unable to parse key exchange reply packet"));
6017 crStop(0);
6018 }
6019 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6020
6021 s->K = dh_find_K(ssh->kex_ctx, s->f);
6022
6023 /* We assume everything from now on will be quick, and it might
6024 * involve user interaction. */
6025 set_busy_status(ssh->frontend, BUSY_NOT);
6026
6027 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6028 if (!ssh->kex->pdata) {
6029 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6030 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6031 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6032 }
6033 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6034 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6035
6036 dh_cleanup(ssh->kex_ctx);
6037 freebn(s->f);
6038 if (!ssh->kex->pdata) {
6039 freebn(s->g);
6040 freebn(s->p);
6041 }
6042 } else {
6043 logeventf(ssh, "Doing RSA key exchange with hash %s",
6044 ssh->kex->hash->text_name);
6045 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6046 /*
6047 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6048 * from the server.
6049 */
6050 crWaitUntil(pktin);
6051 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6052 bombout(("expected RSA public key packet from server"));
6053 crStop(0);
6054 }
6055
6056 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6057 hash_string(ssh->kex->hash, ssh->exhash,
6058 s->hostkeydata, s->hostkeylen);
6059 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6060
6061 {
6062 char *keydata;
6063 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6064 s->rsakeydata = snewn(s->rsakeylen, char);
6065 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6066 }
6067
6068 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6069 if (!s->rsakey) {
6070 sfree(s->rsakeydata);
6071 bombout(("unable to parse RSA public key from server"));
6072 crStop(0);
6073 }
6074
6075 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6076
6077 /*
6078 * Next, set up a shared secret K, of precisely KLEN -
6079 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6080 * RSA key modulus and HLEN is the bit length of the hash
6081 * we're using.
6082 */
6083 {
6084 int klen = ssh_rsakex_klen(s->rsakey);
6085 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6086 int i, byte = 0;
6087 unsigned char *kstr1, *kstr2, *outstr;
6088 int kstr1len, kstr2len, outstrlen;
6089
6090 s->K = bn_power_2(nbits - 1);
6091
6092 for (i = 0; i < nbits; i++) {
6093 if ((i & 7) == 0) {
6094 byte = random_byte();
6095 }
6096 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6097 }
6098
6099 /*
6100 * Encode this as an mpint.
6101 */
6102 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6103 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6104 PUT_32BIT(kstr2, kstr1len);
6105 memcpy(kstr2 + 4, kstr1, kstr1len);
6106
6107 /*
6108 * Encrypt it with the given RSA key.
6109 */
6110 outstrlen = (klen + 7) / 8;
6111 outstr = snewn(outstrlen, unsigned char);
6112 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6113 outstr, outstrlen, s->rsakey);
6114
6115 /*
6116 * And send it off in a return packet.
6117 */
6118 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6119 ssh2_pkt_addstring_start(s->pktout);
6120 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6121 ssh2_pkt_send_noqueue(ssh, s->pktout);
6122
6123 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6124
6125 sfree(kstr2);
6126 sfree(kstr1);
6127 sfree(outstr);
6128 }
6129
6130 ssh_rsakex_freekey(s->rsakey);
6131
6132 crWaitUntil(pktin);
6133 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6134 sfree(s->rsakeydata);
6135 bombout(("expected signature packet from server"));
6136 crStop(0);
6137 }
6138
6139 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6140
6141 sfree(s->rsakeydata);
6142 }
6143
6144 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6145 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6146 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6147
6148 ssh->kex_ctx = NULL;
6149
6150 #if 0
6151 debug(("Exchange hash is:\n"));
6152 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6153 #endif
6154
6155 if (!s->hkey ||
6156 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6157 (char *)s->exchange_hash,
6158 ssh->kex->hash->hlen)) {
6159 bombout(("Server's host key did not match the signature supplied"));
6160 crStop(0);
6161 }
6162
6163 /*
6164 * Authenticate remote host: verify host key. (We've already
6165 * checked the signature of the exchange hash.)
6166 */
6167 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6168 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6169 ssh_set_frozen(ssh, 1);
6170 s->dlgret = verify_ssh_host_key(ssh->frontend,
6171 ssh->savedhost, ssh->savedport,
6172 ssh->hostkey->keytype, s->keystr,
6173 s->fingerprint,
6174 ssh_dialog_callback, ssh);
6175 if (s->dlgret < 0) {
6176 do {
6177 crReturn(0);
6178 if (pktin) {
6179 bombout(("Unexpected data from server while waiting"
6180 " for user host key response"));
6181 crStop(0);
6182 }
6183 } while (pktin || inlen > 0);
6184 s->dlgret = ssh->user_response;
6185 }
6186 ssh_set_frozen(ssh, 0);
6187 if (s->dlgret == 0) {
6188 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6189 0, TRUE);
6190 crStop(0);
6191 }
6192 if (!s->got_session_id) { /* don't bother logging this in rekeys */
6193 logevent("Host key fingerprint is:");
6194 logevent(s->fingerprint);
6195 }
6196 sfree(s->fingerprint);
6197 sfree(s->keystr);
6198 ssh->hostkey->freekey(s->hkey);
6199
6200 /*
6201 * The exchange hash from the very first key exchange is also
6202 * the session id, used in session key construction and
6203 * authentication.
6204 */
6205 if (!s->got_session_id) {
6206 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6207 memcpy(ssh->v2_session_id, s->exchange_hash,
6208 sizeof(s->exchange_hash));
6209 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6210 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6211 s->got_session_id = TRUE;
6212 }
6213
6214 /*
6215 * Send SSH2_MSG_NEWKEYS.
6216 */
6217 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6218 ssh2_pkt_send_noqueue(ssh, s->pktout);
6219 ssh->outgoing_data_size = 0; /* start counting from here */
6220
6221 /*
6222 * We've sent client NEWKEYS, so create and initialise
6223 * client-to-server session keys.
6224 */
6225 if (ssh->cs_cipher_ctx)
6226 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6227 ssh->cscipher = s->cscipher_tobe;
6228 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6229
6230 if (ssh->cs_mac_ctx)
6231 ssh->csmac->free_context(ssh->cs_mac_ctx);
6232 ssh->csmac = s->csmac_tobe;
6233 ssh->cs_mac_ctx = ssh->csmac->make_context();
6234
6235 if (ssh->cs_comp_ctx)
6236 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6237 ssh->cscomp = s->cscomp_tobe;
6238 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6239
6240 /*
6241 * Set IVs on client-to-server keys. Here we use the exchange
6242 * hash from the _first_ key exchange.
6243 */
6244 {
6245 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6246 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6247 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6248 assert((ssh->cscipher->keylen+7) / 8 <=
6249 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6250 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6251 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6252 assert(ssh->cscipher->blksize <=
6253 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6254 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6255 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6256 assert(ssh->csmac->len <=
6257 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6258 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6259 memset(keyspace, 0, sizeof(keyspace));
6260 }
6261
6262 logeventf(ssh, "Initialised %.200s client->server encryption",
6263 ssh->cscipher->text_name);
6264 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6265 ssh->csmac->text_name);
6266 if (ssh->cscomp->text_name)
6267 logeventf(ssh, "Initialised %s compression",
6268 ssh->cscomp->text_name);
6269
6270 /*
6271 * Now our end of the key exchange is complete, we can send all
6272 * our queued higher-layer packets.
6273 */
6274 ssh->queueing = FALSE;
6275 ssh2_pkt_queuesend(ssh);
6276
6277 /*
6278 * Expect SSH2_MSG_NEWKEYS from server.
6279 */
6280 crWaitUntil(pktin);
6281 if (pktin->type != SSH2_MSG_NEWKEYS) {
6282 bombout(("expected new-keys packet from server"));
6283 crStop(0);
6284 }
6285 ssh->incoming_data_size = 0; /* start counting from here */
6286
6287 /*
6288 * We've seen server NEWKEYS, so create and initialise
6289 * server-to-client session keys.
6290 */
6291 if (ssh->sc_cipher_ctx)
6292 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6293 ssh->sccipher = s->sccipher_tobe;
6294 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6295
6296 if (ssh->sc_mac_ctx)
6297 ssh->scmac->free_context(ssh->sc_mac_ctx);
6298 ssh->scmac = s->scmac_tobe;
6299 ssh->sc_mac_ctx = ssh->scmac->make_context();
6300
6301 if (ssh->sc_comp_ctx)
6302 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6303 ssh->sccomp = s->sccomp_tobe;
6304 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6305
6306 /*
6307 * Set IVs on server-to-client keys. Here we use the exchange
6308 * hash from the _first_ key exchange.
6309 */
6310 {
6311 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6312 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6313 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6314 assert((ssh->sccipher->keylen+7) / 8 <=
6315 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6316 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6317 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6318 assert(ssh->sccipher->blksize <=
6319 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6320 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6321 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6322 assert(ssh->scmac->len <=
6323 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6324 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6325 memset(keyspace, 0, sizeof(keyspace));
6326 }
6327 logeventf(ssh, "Initialised %.200s server->client encryption",
6328 ssh->sccipher->text_name);
6329 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6330 ssh->scmac->text_name);
6331 if (ssh->sccomp->text_name)
6332 logeventf(ssh, "Initialised %s decompression",
6333 ssh->sccomp->text_name);
6334
6335 /*
6336 * Free shared secret.
6337 */
6338 freebn(s->K);
6339
6340 /*
6341 * Key exchange is over. Loop straight back round if we have a
6342 * deferred rekey reason.
6343 */
6344 if (ssh->deferred_rekey_reason) {
6345 logevent(ssh->deferred_rekey_reason);
6346 pktin = NULL;
6347 ssh->deferred_rekey_reason = NULL;
6348 goto begin_key_exchange;
6349 }
6350
6351 /*
6352 * Otherwise, schedule a timer for our next rekey.
6353 */
6354 ssh->kex_in_progress = FALSE;
6355 ssh->last_rekey = GETTICKCOUNT();
6356 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
6357 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6358 ssh2_timer, ssh);
6359
6360 /*
6361 * If this is the first key exchange phase, we must pass the
6362 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
6363 * wants to see it but because it will need time to initialise
6364 * itself before it sees an actual packet. In subsequent key
6365 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
6366 * it would only confuse the layer above.
6367 */
6368 if (s->activated_authconn) {
6369 crReturn(0);
6370 }
6371 s->activated_authconn = TRUE;
6372
6373 /*
6374 * Now we're encrypting. Begin returning 1 to the protocol main
6375 * function so that other things can run on top of the
6376 * transport. If we ever see a KEXINIT, we must go back to the
6377 * start.
6378 *
6379 * We _also_ go back to the start if we see pktin==NULL and
6380 * inlen negative, because this is a special signal meaning
6381 * `initiate client-driven rekey', and `in' contains a message
6382 * giving the reason for the rekey.
6383 *
6384 * inlen==-1 means always initiate a rekey;
6385 * inlen==-2 means that userauth has completed successfully and
6386 * we should consider rekeying (for delayed compression).
6387 */
6388 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6389 (!pktin && inlen < 0))) {
6390 wait_for_rekey:
6391 crReturn(1);
6392 }
6393 if (pktin) {
6394 logevent("Server initiated key re-exchange");
6395 } else {
6396 if (inlen == -2) {
6397 /*
6398 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6399 * delayed compression, if it's available.
6400 *
6401 * draft-miller-secsh-compression-delayed-00 says that you
6402 * negotiate delayed compression in the first key exchange, and
6403 * both sides start compressing when the server has sent
6404 * USERAUTH_SUCCESS. This has a race condition -- the server
6405 * can't know when the client has seen it, and thus which incoming
6406 * packets it should treat as compressed.
6407 *
6408 * Instead, we do the initial key exchange without offering the
6409 * delayed methods, but note if the server offers them; when we
6410 * get here, if a delayed method was available that was higher
6411 * on our list than what we got, we initiate a rekey in which we
6412 * _do_ list the delayed methods (and hopefully get it as a
6413 * result). Subsequent rekeys will do the same.
6414 */
6415 assert(!s->userauth_succeeded); /* should only happen once */
6416 s->userauth_succeeded = TRUE;
6417 if (!s->pending_compression)
6418 /* Can't see any point rekeying. */
6419 goto wait_for_rekey; /* this is utterly horrid */
6420 /* else fall through to rekey... */
6421 s->pending_compression = FALSE;
6422 }
6423 /*
6424 * Now we've decided to rekey.
6425 *
6426 * Special case: if the server bug is set that doesn't
6427 * allow rekeying, we give a different log message and
6428 * continue waiting. (If such a server _initiates_ a rekey,
6429 * we process it anyway!)
6430 */
6431 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6432 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6433 (char *)in);
6434 /* Reset the counters, so that at least this message doesn't
6435 * hit the event log _too_ often. */
6436 ssh->outgoing_data_size = 0;
6437 ssh->incoming_data_size = 0;
6438 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
6439 ssh->next_rekey =
6440 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6441 ssh2_timer, ssh);
6442 }
6443 goto wait_for_rekey; /* this is still utterly horrid */
6444 } else {
6445 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6446 }
6447 }
6448 goto begin_key_exchange;
6449
6450 crFinish(1);
6451 }
6452
6453 /*
6454 * Add data to an SSH-2 channel output buffer.
6455 */
6456 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6457 int len)
6458 {
6459 bufchain_add(&c->v.v2.outbuffer, buf, len);
6460 }
6461
6462 /*
6463 * Attempt to send data on an SSH-2 channel.
6464 */
6465 static int ssh2_try_send(struct ssh_channel *c)
6466 {
6467 Ssh ssh = c->ssh;
6468 struct Packet *pktout;
6469 int ret;
6470
6471 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6472 int len;
6473 void *data;
6474 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6475 if ((unsigned)len > c->v.v2.remwindow)
6476 len = c->v.v2.remwindow;
6477 if ((unsigned)len > c->v.v2.remmaxpkt)
6478 len = c->v.v2.remmaxpkt;
6479 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6480 ssh2_pkt_adduint32(pktout, c->remoteid);
6481 ssh2_pkt_addstring_start(pktout);
6482 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6483 ssh2_pkt_addstring_data(pktout, data, len);
6484 end_log_omission(ssh, pktout);
6485 ssh2_pkt_send(ssh, pktout);
6486 bufchain_consume(&c->v.v2.outbuffer, len);
6487 c->v.v2.remwindow -= len;
6488 }
6489
6490 /*
6491 * After having sent as much data as we can, return the amount
6492 * still buffered.
6493 */
6494 ret = bufchain_size(&c->v.v2.outbuffer);
6495
6496 /*
6497 * And if there's no data pending but we need to send an EOF, send
6498 * it.
6499 */
6500 if (!ret && c->pending_eof)
6501 ssh_channel_try_eof(c);
6502
6503 return ret;
6504 }
6505
6506 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
6507 {
6508 int bufsize;
6509 if (c->closes & CLOSES_SENT_EOF)
6510 return; /* don't send on channels we've EOFed */
6511 bufsize = ssh2_try_send(c);
6512 if (bufsize == 0) {
6513 switch (c->type) {
6514 case CHAN_MAINSESSION:
6515 /* stdin need not receive an unthrottle
6516 * notification since it will be polled */
6517 break;
6518 case CHAN_X11:
6519 x11_unthrottle(c->u.x11.s);
6520 break;
6521 case CHAN_AGENT:
6522 /* agent sockets are request/response and need no
6523 * buffer management */
6524 break;
6525 case CHAN_SOCKDATA:
6526 pfd_unthrottle(c->u.pfd.s);
6527 break;
6528 }
6529 }
6530 }
6531
6532 /*
6533 * Set up most of a new ssh_channel for SSH-2.
6534 */
6535 static void ssh2_channel_init(struct ssh_channel *c)
6536 {
6537 Ssh ssh = c->ssh;
6538 c->localid = alloc_channel_id(ssh);
6539 c->closes = 0;
6540 c->pending_eof = FALSE;
6541 c->throttling_conn = FALSE;
6542 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6543 conf_get_int(ssh->conf, CONF_ssh_simple) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6544 c->v.v2.winadj_head = c->v.v2.winadj_tail = NULL;
6545 c->v.v2.throttle_state = UNTHROTTLED;
6546 bufchain_init(&c->v.v2.outbuffer);
6547 }
6548
6549 /*
6550 * Potentially enlarge the window on an SSH-2 channel.
6551 */
6552 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6553 {
6554 Ssh ssh = c->ssh;
6555
6556 /*
6557 * Never send WINDOW_ADJUST for a channel that the remote side has
6558 * already sent EOF on; there's no point, since it won't be
6559 * sending any more data anyway.
6560 */
6561 if (c->closes & CLOSES_RCVD_EOF)
6562 return;
6563
6564 /*
6565 * If the remote end has a habit of ignoring maxpkt, limit the
6566 * window so that it has no choice (assuming it doesn't ignore the
6567 * window as well).
6568 */
6569 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6570 newwin = OUR_V2_MAXPKT;
6571
6572
6573 /*
6574 * Only send a WINDOW_ADJUST if there's significantly more window
6575 * available than the other end thinks there is. This saves us
6576 * sending a WINDOW_ADJUST for every character in a shell session.
6577 *
6578 * "Significant" is arbitrarily defined as half the window size.
6579 */
6580 if (newwin / 2 >= c->v.v2.locwindow) {
6581 struct Packet *pktout;
6582 struct winadj *wa;
6583
6584 /*
6585 * In order to keep track of how much window the client
6586 * actually has available, we'd like it to acknowledge each
6587 * WINDOW_ADJUST. We can't do that directly, so we accompany
6588 * it with a CHANNEL_REQUEST that has to be acknowledged.
6589 *
6590 * This is only necessary if we're opening the window wide.
6591 * If we're not, then throughput is being constrained by
6592 * something other than the maximum window size anyway.
6593 *
6594 * We also only send this if the main channel has finished its
6595 * initial CHANNEL_REQUESTs and installed the default
6596 * CHANNEL_FAILURE handler, so as not to risk giving it
6597 * unexpected CHANNEL_FAILUREs.
6598 */
6599 if (newwin == c->v.v2.locmaxwin &&
6600 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE]) {
6601 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6602 ssh2_pkt_adduint32(pktout, c->remoteid);
6603 ssh2_pkt_addstring(pktout, "winadj@putty.projects.tartarus.org");
6604 ssh2_pkt_addbool(pktout, TRUE);
6605 ssh2_pkt_send(ssh, pktout);
6606
6607 /*
6608 * CHANNEL_FAILURE doesn't come with any indication of
6609 * what message caused it, so we have to keep track of the
6610 * outstanding CHANNEL_REQUESTs ourselves.
6611 */
6612 wa = snew(struct winadj);
6613 wa->size = newwin - c->v.v2.locwindow;
6614 wa->next = NULL;
6615 if (!c->v.v2.winadj_head)
6616 c->v.v2.winadj_head = wa;
6617 else
6618 c->v.v2.winadj_tail->next = wa;
6619 c->v.v2.winadj_tail = wa;
6620 if (c->v.v2.throttle_state != UNTHROTTLED)
6621 c->v.v2.throttle_state = UNTHROTTLING;
6622 } else {
6623 /* Pretend the WINDOW_ADJUST was acked immediately. */
6624 c->v.v2.remlocwin = newwin;
6625 c->v.v2.throttle_state = THROTTLED;
6626 }
6627 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6628 ssh2_pkt_adduint32(pktout, c->remoteid);
6629 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6630 ssh2_pkt_send(ssh, pktout);
6631 c->v.v2.locwindow = newwin;
6632 }
6633 }
6634
6635 /*
6636 * Find the channel associated with a message. If there's no channel,
6637 * or it's not properly open, make a noise about it and return NULL.
6638 */
6639 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6640 {
6641 unsigned localid = ssh_pkt_getuint32(pktin);
6642 struct ssh_channel *c;
6643
6644 c = find234(ssh->channels, &localid, ssh_channelfind);
6645 if (!c ||
6646 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6647 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6648 char *buf = dupprintf("Received %s for %s channel %u",
6649 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6650 pktin->type),
6651 c ? "half-open" : "nonexistent", localid);
6652 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6653 sfree(buf);
6654 return NULL;
6655 }
6656 return c;
6657 }
6658
6659 static int ssh2_handle_winadj_response(struct ssh_channel *c)
6660 {
6661 struct winadj *wa = c->v.v2.winadj_head;
6662 if (!wa)
6663 return FALSE;
6664 c->v.v2.winadj_head = wa->next;
6665 c->v.v2.remlocwin += wa->size;
6666 sfree(wa);
6667 /*
6668 * winadj messages are only sent when the window is fully open, so
6669 * if we get an ack of one, we know any pending unthrottle is
6670 * complete.
6671 */
6672 if (c->v.v2.throttle_state == UNTHROTTLING)
6673 c->v.v2.throttle_state = UNTHROTTLED;
6674 /*
6675 * We may now initiate channel-closing procedures, if that winadj
6676 * was the last thing outstanding before we send CHANNEL_CLOSE.
6677 */
6678 ssh2_channel_check_close(c);
6679 return TRUE;
6680 }
6681
6682 static void ssh2_msg_channel_success(Ssh ssh, struct Packet *pktin)
6683 {
6684 /*
6685 * This should never get called. All channel requests are either
6686 * sent with want_reply false, are sent before this handler gets
6687 * installed, or are "winadj@putty" requests, which servers should
6688 * never respond to with success.
6689 *
6690 * However, at least one server ("boks_sshd") is known to return
6691 * SUCCESS for channel requests it's never heard of, such as
6692 * "winadj@putty". Raised with foxt.com as bug 090916-090424, but
6693 * for the sake of a quiet life, we handle it just the same as the
6694 * expected FAILURE.
6695 */
6696 struct ssh_channel *c;
6697
6698 c = ssh2_channel_msg(ssh, pktin);
6699 if (!c)
6700 return;
6701 if (!ssh2_handle_winadj_response(c))
6702 ssh_disconnect(ssh, NULL,
6703 "Received unsolicited SSH_MSG_CHANNEL_SUCCESS",
6704 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6705 }
6706
6707 static void ssh2_msg_channel_failure(Ssh ssh, struct Packet *pktin)
6708 {
6709 /*
6710 * The only time this should get called is for "winadj@putty"
6711 * messages sent above. All other channel requests are either
6712 * sent with want_reply false or are sent before this handler gets
6713 * installed.
6714 */
6715 struct ssh_channel *c;
6716
6717 c = ssh2_channel_msg(ssh, pktin);
6718 if (!c)
6719 return;
6720 if (!ssh2_handle_winadj_response(c))
6721 ssh_disconnect(ssh, NULL,
6722 "Received unsolicited SSH_MSG_CHANNEL_FAILURE",
6723 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6724 }
6725
6726 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6727 {
6728 struct ssh_channel *c;
6729 c = ssh2_channel_msg(ssh, pktin);
6730 if (!c)
6731 return;
6732 if (!(c->closes & CLOSES_SENT_EOF)) {
6733 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6734 ssh2_try_send_and_unthrottle(ssh, c);
6735 }
6736 }
6737
6738 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6739 {
6740 char *data;
6741 int length;
6742 struct ssh_channel *c;
6743 c = ssh2_channel_msg(ssh, pktin);
6744 if (!c)
6745 return;
6746 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6747 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6748 return; /* extended but not stderr */
6749 ssh_pkt_getstring(pktin, &data, &length);
6750 if (data) {
6751 int bufsize = 0;
6752 c->v.v2.locwindow -= length;
6753 c->v.v2.remlocwin -= length;
6754 switch (c->type) {
6755 case CHAN_MAINSESSION:
6756 bufsize =
6757 from_backend(ssh->frontend, pktin->type ==
6758 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6759 data, length);
6760 break;
6761 case CHAN_X11:
6762 bufsize = x11_send(c->u.x11.s, data, length);
6763 break;
6764 case CHAN_SOCKDATA:
6765 bufsize = pfd_send(c->u.pfd.s, data, length);
6766 break;
6767 case CHAN_AGENT:
6768 while (length > 0) {
6769 if (c->u.a.lensofar < 4) {
6770 unsigned int l = min(4 - c->u.a.lensofar,
6771 (unsigned)length);
6772 memcpy(c->u.a.msglen + c->u.a.lensofar,
6773 data, l);
6774 data += l;
6775 length -= l;
6776 c->u.a.lensofar += l;
6777 }
6778 if (c->u.a.lensofar == 4) {
6779 c->u.a.totallen =
6780 4 + GET_32BIT(c->u.a.msglen);
6781 c->u.a.message = snewn(c->u.a.totallen,
6782 unsigned char);
6783 memcpy(c->u.a.message, c->u.a.msglen, 4);
6784 }
6785 if (c->u.a.lensofar >= 4 && length > 0) {
6786 unsigned int l =
6787 min(c->u.a.totallen - c->u.a.lensofar,
6788 (unsigned)length);
6789 memcpy(c->u.a.message + c->u.a.lensofar,
6790 data, l);
6791 data += l;
6792 length -= l;
6793 c->u.a.lensofar += l;
6794 }
6795 if (c->u.a.lensofar == c->u.a.totallen) {
6796 void *reply;
6797 int replylen;
6798 if (agent_query(c->u.a.message,
6799 c->u.a.totallen,
6800 &reply, &replylen,
6801 ssh_agentf_callback, c))
6802 ssh_agentf_callback(c, reply, replylen);
6803 sfree(c->u.a.message);
6804 c->u.a.message = NULL;
6805 c->u.a.lensofar = 0;
6806 }
6807 }
6808 bufsize = 0;
6809 break;
6810 }
6811 /*
6812 * If it looks like the remote end hit the end of its window,
6813 * and we didn't want it to do that, think about using a
6814 * larger window.
6815 */
6816 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6817 c->v.v2.locmaxwin < 0x40000000)
6818 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6819 /*
6820 * If we are not buffering too much data,
6821 * enlarge the window again at the remote side.
6822 * If we are buffering too much, we may still
6823 * need to adjust the window if the server's
6824 * sent excess data.
6825 */
6826 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6827 c->v.v2.locmaxwin - bufsize : 0);
6828 /*
6829 * If we're either buffering way too much data, or if we're
6830 * buffering anything at all and we're in "simple" mode,
6831 * throttle the whole channel.
6832 */
6833 if ((bufsize > c->v.v2.locmaxwin ||
6834 (conf_get_int(ssh->conf, CONF_ssh_simple) && bufsize > 0)) &&
6835 !c->throttling_conn) {
6836 c->throttling_conn = 1;
6837 ssh_throttle_conn(ssh, +1);
6838 }
6839 }
6840 }
6841
6842 static void ssh_channel_destroy(struct ssh_channel *c)
6843 {
6844 Ssh ssh = c->ssh;
6845
6846 switch (c->type) {
6847 case CHAN_MAINSESSION:
6848 ssh->mainchan = NULL;
6849 update_specials_menu(ssh->frontend);
6850 break;
6851 case CHAN_X11:
6852 if (c->u.x11.s != NULL)
6853 x11_close(c->u.x11.s);
6854 logevent("Forwarded X11 connection terminated");
6855 break;
6856 case CHAN_AGENT:
6857 sfree(c->u.a.message);
6858 break;
6859 case CHAN_SOCKDATA:
6860 if (c->u.pfd.s != NULL)
6861 pfd_close(c->u.pfd.s);
6862 logevent("Forwarded port closed");
6863 break;
6864 }
6865
6866 del234(ssh->channels, c);
6867 if (ssh->version == 2)
6868 bufchain_clear(&c->v.v2.outbuffer);
6869 sfree(c);
6870
6871 /*
6872 * See if that was the last channel left open.
6873 * (This is only our termination condition if we're
6874 * not running in -N mode.)
6875 */
6876 if (ssh->version == 2 &&
6877 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
6878 count234(ssh->channels) == 0) {
6879 /*
6880 * We used to send SSH_MSG_DISCONNECT here,
6881 * because I'd believed that _every_ conforming
6882 * SSH-2 connection had to end with a disconnect
6883 * being sent by at least one side; apparently
6884 * I was wrong and it's perfectly OK to
6885 * unceremoniously slam the connection shut
6886 * when you're done, and indeed OpenSSH feels
6887 * this is more polite than sending a
6888 * DISCONNECT. So now we don't.
6889 */
6890 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6891 }
6892 }
6893
6894 static void ssh2_channel_check_close(struct ssh_channel *c)
6895 {
6896 Ssh ssh = c->ssh;
6897 struct Packet *pktout;
6898
6899 if ((c->closes & (CLOSES_SENT_EOF | CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6900 == (CLOSES_SENT_EOF | CLOSES_RCVD_EOF) && !c->v.v2.winadj_head) {
6901 /*
6902 * We have both sent and received EOF, and we have no
6903 * outstanding winadj channel requests, which means the
6904 * channel is in final wind-up. But we haven't sent CLOSE, so
6905 * let's do so now.
6906 */
6907 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6908 ssh2_pkt_adduint32(pktout, c->remoteid);
6909 ssh2_pkt_send(ssh, pktout);
6910 c->closes |= CLOSES_SENT_CLOSE;
6911 }
6912
6913 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
6914 /*
6915 * We have both sent and received CLOSE, which means we're
6916 * completely done with the channel.
6917 */
6918 ssh_channel_destroy(c);
6919 }
6920 }
6921
6922 static void ssh2_channel_got_eof(struct ssh_channel *c)
6923 {
6924 if (c->closes & CLOSES_RCVD_EOF)
6925 return; /* already seen EOF */
6926 c->closes |= CLOSES_RCVD_EOF;
6927
6928 if (c->type == CHAN_X11) {
6929 x11_send_eof(c->u.x11.s);
6930 } else if (c->type == CHAN_AGENT) {
6931 /* Manufacture an outgoing EOF in response to the incoming one. */
6932 sshfwd_write_eof(c);
6933 } else if (c->type == CHAN_SOCKDATA) {
6934 pfd_send_eof(c->u.pfd.s);
6935 } else if (c->type == CHAN_MAINSESSION) {
6936 Ssh ssh = c->ssh;
6937
6938 if (!ssh->sent_console_eof &&
6939 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
6940 /*
6941 * Either from_backend_eof told us that the front end
6942 * wants us to close the outgoing side of the connection
6943 * as soon as we see EOF from the far end, or else we've
6944 * unilaterally decided to do that because we've allocated
6945 * a remote pty and hence EOF isn't a particularly
6946 * meaningful concept.
6947 */
6948 sshfwd_write_eof(c);
6949 }
6950 ssh->sent_console_eof = TRUE;
6951 }
6952
6953 ssh2_channel_check_close(c);
6954 }
6955
6956 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
6957 {
6958 struct ssh_channel *c;
6959
6960 c = ssh2_channel_msg(ssh, pktin);
6961 if (!c)
6962 return;
6963 ssh2_channel_got_eof(c);
6964 }
6965
6966 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
6967 {
6968 struct ssh_channel *c;
6969
6970 c = ssh2_channel_msg(ssh, pktin);
6971 if (!c)
6972 return;
6973
6974 /*
6975 * When we receive CLOSE on a channel, we assume it comes with an
6976 * implied EOF if we haven't seen EOF yet.
6977 */
6978 ssh2_channel_got_eof(c);
6979
6980 /*
6981 * Now process the actual close.
6982 */
6983 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
6984 c->closes |= CLOSES_RCVD_CLOSE;
6985 ssh2_channel_check_close(c);
6986 }
6987 }
6988
6989 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
6990 {
6991 struct ssh_channel *c;
6992
6993 c = ssh2_channel_msg(ssh, pktin);
6994 if (!c)
6995 return;
6996 if (c->type != CHAN_SOCKDATA_DORMANT)
6997 return; /* dunno why they're confirming this */
6998 c->remoteid = ssh_pkt_getuint32(pktin);
6999 c->halfopen = FALSE;
7000 c->type = CHAN_SOCKDATA;
7001 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7002 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7003 if (c->u.pfd.s)
7004 pfd_confirm(c->u.pfd.s);
7005 if (c->pending_eof)
7006 ssh_channel_try_eof(c);
7007 }
7008
7009 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7010 {
7011 static const char *const reasons[] = {
7012 "<unknown reason code>",
7013 "Administratively prohibited",
7014 "Connect failed",
7015 "Unknown channel type",
7016 "Resource shortage",
7017 };
7018 unsigned reason_code;
7019 char *reason_string;
7020 int reason_length;
7021 struct ssh_channel *c;
7022 c = ssh2_channel_msg(ssh, pktin);
7023 if (!c)
7024 return;
7025 if (c->type != CHAN_SOCKDATA_DORMANT)
7026 return; /* dunno why they're failing this */
7027
7028 reason_code = ssh_pkt_getuint32(pktin);
7029 if (reason_code >= lenof(reasons))
7030 reason_code = 0; /* ensure reasons[reason_code] in range */
7031 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7032 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7033 reasons[reason_code], reason_length, reason_string);
7034
7035 pfd_close(c->u.pfd.s);
7036
7037 del234(ssh->channels, c);
7038 sfree(c);
7039 }
7040
7041 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7042 {
7043 char *type;
7044 int typelen, want_reply;
7045 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7046 struct ssh_channel *c;
7047 struct Packet *pktout;
7048
7049 c = ssh2_channel_msg(ssh, pktin);
7050 if (!c)
7051 return;
7052 ssh_pkt_getstring(pktin, &type, &typelen);
7053 want_reply = ssh2_pkt_getbool(pktin);
7054
7055 /*
7056 * Having got the channel number, we now look at
7057 * the request type string to see if it's something
7058 * we recognise.
7059 */
7060 if (c == ssh->mainchan) {
7061 /*
7062 * We recognise "exit-status" and "exit-signal" on
7063 * the primary channel.
7064 */
7065 if (typelen == 11 &&
7066 !memcmp(type, "exit-status", 11)) {
7067
7068 ssh->exitcode = ssh_pkt_getuint32(pktin);
7069 logeventf(ssh, "Server sent command exit status %d",
7070 ssh->exitcode);
7071 reply = SSH2_MSG_CHANNEL_SUCCESS;
7072
7073 } else if (typelen == 11 &&
7074 !memcmp(type, "exit-signal", 11)) {
7075
7076 int is_plausible = TRUE, is_int = FALSE;
7077 char *fmt_sig = "", *fmt_msg = "";
7078 char *msg;
7079 int msglen = 0, core = FALSE;
7080 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7081 * provide an `int' for the signal, despite its
7082 * having been a `string' in the drafts of RFC 4254 since at
7083 * least 2001. (Fixed in session.c 1.147.) Try to
7084 * infer which we can safely parse it as. */
7085 {
7086 unsigned char *p = pktin->body +
7087 pktin->savedpos;
7088 long len = pktin->length - pktin->savedpos;
7089 unsigned long num = GET_32BIT(p); /* what is it? */
7090 /* If it's 0, it hardly matters; assume string */
7091 if (num == 0) {
7092 is_int = FALSE;
7093 } else {
7094 int maybe_int = FALSE, maybe_str = FALSE;
7095 #define CHECK_HYPOTHESIS(offset, result) \
7096 do { \
7097 long q = offset; \
7098 if (q >= 0 && q+4 <= len) { \
7099 q = q + 4 + GET_32BIT(p+q); \
7100 if (q >= 0 && q+4 <= len && \
7101 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
7102 result = TRUE; \
7103 } \
7104 } while(0)
7105 CHECK_HYPOTHESIS(4+1, maybe_int);
7106 CHECK_HYPOTHESIS(4+num+1, maybe_str);
7107 #undef CHECK_HYPOTHESIS
7108 if (maybe_int && !maybe_str)
7109 is_int = TRUE;
7110 else if (!maybe_int && maybe_str)
7111 is_int = FALSE;
7112 else
7113 /* Crikey. Either or neither. Panic. */
7114 is_plausible = FALSE;
7115 }
7116 }
7117 ssh->exitcode = 128; /* means `unknown signal' */
7118 if (is_plausible) {
7119 if (is_int) {
7120 /* Old non-standard OpenSSH. */
7121 int signum = ssh_pkt_getuint32(pktin);
7122 fmt_sig = dupprintf(" %d", signum);
7123 ssh->exitcode = 128 + signum;
7124 } else {
7125 /* As per RFC 4254. */
7126 char *sig;
7127 int siglen;
7128 ssh_pkt_getstring(pktin, &sig, &siglen);
7129 /* Signal name isn't supposed to be blank, but
7130 * let's cope gracefully if it is. */
7131 if (siglen) {
7132 fmt_sig = dupprintf(" \"%.*s\"",
7133 siglen, sig);
7134 }
7135
7136 /*
7137 * Really hideous method of translating the
7138 * signal description back into a locally
7139 * meaningful number.
7140 */
7141
7142 if (0)
7143 ;
7144 #define TRANSLATE_SIGNAL(s) \
7145 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7146 ssh->exitcode = 128 + SIG ## s
7147 #ifdef SIGABRT
7148 TRANSLATE_SIGNAL(ABRT);
7149 #endif
7150 #ifdef SIGALRM
7151 TRANSLATE_SIGNAL(ALRM);
7152 #endif
7153 #ifdef SIGFPE
7154 TRANSLATE_SIGNAL(FPE);
7155 #endif
7156 #ifdef SIGHUP
7157 TRANSLATE_SIGNAL(HUP);
7158 #endif
7159 #ifdef SIGILL
7160 TRANSLATE_SIGNAL(ILL);
7161 #endif
7162 #ifdef SIGINT
7163 TRANSLATE_SIGNAL(INT);
7164 #endif
7165 #ifdef SIGKILL
7166 TRANSLATE_SIGNAL(KILL);
7167 #endif
7168 #ifdef SIGPIPE
7169 TRANSLATE_SIGNAL(PIPE);
7170 #endif
7171 #ifdef SIGQUIT
7172 TRANSLATE_SIGNAL(QUIT);
7173 #endif
7174 #ifdef SIGSEGV
7175 TRANSLATE_SIGNAL(SEGV);
7176 #endif
7177 #ifdef SIGTERM
7178 TRANSLATE_SIGNAL(TERM);
7179 #endif
7180 #ifdef SIGUSR1
7181 TRANSLATE_SIGNAL(USR1);
7182 #endif
7183 #ifdef SIGUSR2
7184 TRANSLATE_SIGNAL(USR2);
7185 #endif
7186 #undef TRANSLATE_SIGNAL
7187 else
7188 ssh->exitcode = 128;
7189 }
7190 core = ssh2_pkt_getbool(pktin);
7191 ssh_pkt_getstring(pktin, &msg, &msglen);
7192 if (msglen) {
7193 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
7194 }
7195 /* ignore lang tag */
7196 } /* else don't attempt to parse */
7197 logeventf(ssh, "Server exited on signal%s%s%s",
7198 fmt_sig, core ? " (core dumped)" : "",
7199 fmt_msg);
7200 if (*fmt_sig) sfree(fmt_sig);
7201 if (*fmt_msg) sfree(fmt_msg);
7202 reply = SSH2_MSG_CHANNEL_SUCCESS;
7203
7204 }
7205 } else {
7206 /*
7207 * This is a channel request we don't know
7208 * about, so we now either ignore the request
7209 * or respond with CHANNEL_FAILURE, depending
7210 * on want_reply.
7211 */
7212 reply = SSH2_MSG_CHANNEL_FAILURE;
7213 }
7214 if (want_reply) {
7215 pktout = ssh2_pkt_init(reply);
7216 ssh2_pkt_adduint32(pktout, c->remoteid);
7217 ssh2_pkt_send(ssh, pktout);
7218 }
7219 }
7220
7221 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7222 {
7223 char *type;
7224 int typelen, want_reply;
7225 struct Packet *pktout;
7226
7227 ssh_pkt_getstring(pktin, &type, &typelen);
7228 want_reply = ssh2_pkt_getbool(pktin);
7229
7230 /*
7231 * We currently don't support any global requests
7232 * at all, so we either ignore the request or
7233 * respond with REQUEST_FAILURE, depending on
7234 * want_reply.
7235 */
7236 if (want_reply) {
7237 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7238 ssh2_pkt_send(ssh, pktout);
7239 }
7240 }
7241
7242 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7243 {
7244 char *type;
7245 int typelen;
7246 char *peeraddr;
7247 int peeraddrlen;
7248 int peerport;
7249 char *error = NULL;
7250 struct ssh_channel *c;
7251 unsigned remid, winsize, pktsize;
7252 struct Packet *pktout;
7253
7254 ssh_pkt_getstring(pktin, &type, &typelen);
7255 c = snew(struct ssh_channel);
7256 c->ssh = ssh;
7257
7258 remid = ssh_pkt_getuint32(pktin);
7259 winsize = ssh_pkt_getuint32(pktin);
7260 pktsize = ssh_pkt_getuint32(pktin);
7261
7262 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7263 char *addrstr;
7264 const char *x11err;
7265
7266 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7267 addrstr = snewn(peeraddrlen+1, char);
7268 memcpy(addrstr, peeraddr, peeraddrlen);
7269 addrstr[peeraddrlen] = '\0';
7270 peerport = ssh_pkt_getuint32(pktin);
7271
7272 logeventf(ssh, "Received X11 connect request from %s:%d",
7273 addrstr, peerport);
7274
7275 if (!ssh->X11_fwd_enabled)
7276 error = "X11 forwarding is not enabled";
7277 else if ((x11err = x11_init(&c->u.x11.s, ssh->x11disp, c,
7278 addrstr, peerport, ssh->conf)) != NULL) {
7279 logeventf(ssh, "Local X11 connection failed: %s", x11err);
7280 error = "Unable to open an X11 connection";
7281 } else {
7282 logevent("Opening X11 forward connection succeeded");
7283 c->type = CHAN_X11;
7284 }
7285
7286 sfree(addrstr);
7287 } else if (typelen == 15 &&
7288 !memcmp(type, "forwarded-tcpip", 15)) {
7289 struct ssh_rportfwd pf, *realpf;
7290 char *dummy;
7291 int dummylen;
7292 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
7293 pf.sport = ssh_pkt_getuint32(pktin);
7294 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7295 peerport = ssh_pkt_getuint32(pktin);
7296 realpf = find234(ssh->rportfwds, &pf, NULL);
7297 logeventf(ssh, "Received remote port %d open request "
7298 "from %s:%d", pf.sport, peeraddr, peerport);
7299 if (realpf == NULL) {
7300 error = "Remote port is not recognised";
7301 } else {
7302 const char *e = pfd_newconnect(&c->u.pfd.s,
7303 realpf->dhost,
7304 realpf->dport, c,
7305 ssh->conf,
7306 realpf->pfrec->addressfamily);
7307 logeventf(ssh, "Attempting to forward remote port to "
7308 "%s:%d", realpf->dhost, realpf->dport);
7309 if (e != NULL) {
7310 logeventf(ssh, "Port open failed: %s", e);
7311 error = "Port open failed";
7312 } else {
7313 logevent("Forwarded port opened successfully");
7314 c->type = CHAN_SOCKDATA;
7315 }
7316 }
7317 } else if (typelen == 22 &&
7318 !memcmp(type, "auth-agent@openssh.com", 22)) {
7319 if (!ssh->agentfwd_enabled)
7320 error = "Agent forwarding is not enabled";
7321 else {
7322 c->type = CHAN_AGENT; /* identify channel type */
7323 c->u.a.lensofar = 0;
7324 }
7325 } else {
7326 error = "Unsupported channel type requested";
7327 }
7328
7329 c->remoteid = remid;
7330 c->halfopen = FALSE;
7331 if (error) {
7332 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7333 ssh2_pkt_adduint32(pktout, c->remoteid);
7334 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7335 ssh2_pkt_addstring(pktout, error);
7336 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7337 ssh2_pkt_send(ssh, pktout);
7338 logeventf(ssh, "Rejected channel open: %s", error);
7339 sfree(c);
7340 } else {
7341 ssh2_channel_init(c);
7342 c->v.v2.remwindow = winsize;
7343 c->v.v2.remmaxpkt = pktsize;
7344 add234(ssh->channels, c);
7345 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7346 ssh2_pkt_adduint32(pktout, c->remoteid);
7347 ssh2_pkt_adduint32(pktout, c->localid);
7348 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7349 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7350 ssh2_pkt_send(ssh, pktout);
7351 }
7352 }
7353
7354 /*
7355 * Buffer banner messages for later display at some convenient point,
7356 * if we're going to display them.
7357 */
7358 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7359 {
7360 /* Arbitrary limit to prevent unbounded inflation of buffer */
7361 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
7362 bufchain_size(&ssh->banner) <= 131072) {
7363 char *banner = NULL;
7364 int size = 0;
7365 ssh_pkt_getstring(pktin, &banner, &size);
7366 if (banner)
7367 bufchain_add(&ssh->banner, banner, size);
7368 }
7369 }
7370
7371 /* Helper function to deal with sending tty modes for "pty-req" */
7372 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7373 {
7374 struct Packet *pktout = (struct Packet *)data;
7375 int i = 0;
7376 unsigned int arg = 0;
7377 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7378 if (i == lenof(ssh_ttymodes)) return;
7379 switch (ssh_ttymodes[i].type) {
7380 case TTY_OP_CHAR:
7381 arg = ssh_tty_parse_specchar(val);
7382 break;
7383 case TTY_OP_BOOL:
7384 arg = ssh_tty_parse_boolean(val);
7385 break;
7386 }
7387 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7388 ssh2_pkt_adduint32(pktout, arg);
7389 }
7390
7391 /*
7392 * Handle the SSH-2 userauth and connection layers.
7393 */
7394 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7395 struct Packet *pktin)
7396 {
7397 struct do_ssh2_authconn_state {
7398 enum {
7399 AUTH_TYPE_NONE,
7400 AUTH_TYPE_PUBLICKEY,
7401 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7402 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7403 AUTH_TYPE_PASSWORD,
7404 AUTH_TYPE_GSSAPI, /* always QUIET */
7405 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7406 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7407 } type;
7408 int done_service_req;
7409 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7410 int tried_pubkey_config, done_agent;
7411 #ifndef NO_GSSAPI
7412 int can_gssapi;
7413 int tried_gssapi;
7414 #endif
7415 int kbd_inter_refused;
7416 int we_are_in, userauth_success;
7417 prompts_t *cur_prompt;
7418 int num_prompts;
7419 char *username;
7420 char *password;
7421 int got_username;
7422 void *publickey_blob;
7423 int publickey_bloblen;
7424 int publickey_encrypted;
7425 char *publickey_algorithm;
7426 char *publickey_comment;
7427 unsigned char agent_request[5], *agent_response, *agentp;
7428 int agent_responselen;
7429 unsigned char *pkblob_in_agent;
7430 int keyi, nkeys;
7431 char *pkblob, *alg, *commentp;
7432 int pklen, alglen, commentlen;
7433 int siglen, retlen, len;
7434 char *q, *agentreq, *ret;
7435 int try_send;
7436 int num_env, env_left, env_ok;
7437 struct Packet *pktout;
7438 Filename *keyfile;
7439 #ifndef NO_GSSAPI
7440 struct ssh_gss_library *gsslib;
7441 Ssh_gss_ctx gss_ctx;
7442 Ssh_gss_buf gss_buf;
7443 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7444 Ssh_gss_name gss_srv_name;
7445 Ssh_gss_stat gss_stat;
7446 #endif
7447 };
7448 crState(do_ssh2_authconn_state);
7449
7450 crBegin(ssh->do_ssh2_authconn_crstate);
7451
7452 s->done_service_req = FALSE;
7453 s->we_are_in = s->userauth_success = FALSE;
7454 #ifndef NO_GSSAPI
7455 s->tried_gssapi = FALSE;
7456 #endif
7457
7458 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
7459 /*
7460 * Request userauth protocol, and await a response to it.
7461 */
7462 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7463 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7464 ssh2_pkt_send(ssh, s->pktout);
7465 crWaitUntilV(pktin);
7466 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7467 s->done_service_req = TRUE;
7468 }
7469 if (!s->done_service_req) {
7470 /*
7471 * Request connection protocol directly, without authentication.
7472 */
7473 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7474 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7475 ssh2_pkt_send(ssh, s->pktout);
7476 crWaitUntilV(pktin);
7477 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7478 s->we_are_in = TRUE; /* no auth required */
7479 } else {
7480 bombout(("Server refused service request"));
7481 crStopV;
7482 }
7483 }
7484
7485 /* Arrange to be able to deal with any BANNERs that come in.
7486 * (We do this now as packets may come in during the next bit.) */
7487 bufchain_init(&ssh->banner);
7488 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7489 ssh2_msg_userauth_banner;
7490
7491 /*
7492 * Misc one-time setup for authentication.
7493 */
7494 s->publickey_blob = NULL;
7495 if (!s->we_are_in) {
7496
7497 /*
7498 * Load the public half of any configured public key file
7499 * for later use.
7500 */
7501 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
7502 if (!filename_is_null(*s->keyfile)) {
7503 int keytype;
7504 logeventf(ssh, "Reading private key file \"%.150s\"",
7505 filename_to_str(s->keyfile));
7506 keytype = key_type(s->keyfile);
7507 if (keytype == SSH_KEYTYPE_SSH2) {
7508 const char *error;
7509 s->publickey_blob =
7510 ssh2_userkey_loadpub(s->keyfile,
7511 &s->publickey_algorithm,
7512 &s->publickey_bloblen,
7513 &s->publickey_comment, &error);
7514 if (s->publickey_blob) {
7515 s->publickey_encrypted =
7516 ssh2_userkey_encrypted(s->keyfile, NULL);
7517 } else {
7518 char *msgbuf;
7519 logeventf(ssh, "Unable to load private key (%s)",
7520 error);
7521 msgbuf = dupprintf("Unable to load private key file "
7522 "\"%.150s\" (%s)\r\n",
7523 filename_to_str(s->keyfile),
7524 error);
7525 c_write_str(ssh, msgbuf);
7526 sfree(msgbuf);
7527 }
7528 } else {
7529 char *msgbuf;
7530 logeventf(ssh, "Unable to use this key file (%s)",
7531 key_type_to_str(keytype));
7532 msgbuf = dupprintf("Unable to use key file \"%.150s\""
7533 " (%s)\r\n",
7534 filename_to_str(s->keyfile),
7535 key_type_to_str(keytype));
7536 c_write_str(ssh, msgbuf);
7537 sfree(msgbuf);
7538 s->publickey_blob = NULL;
7539 }
7540 }
7541
7542 /*
7543 * Find out about any keys Pageant has (but if there's a
7544 * public key configured, filter out all others).
7545 */
7546 s->nkeys = 0;
7547 s->agent_response = NULL;
7548 s->pkblob_in_agent = NULL;
7549 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
7550
7551 void *r;
7552
7553 logevent("Pageant is running. Requesting keys.");
7554
7555 /* Request the keys held by the agent. */
7556 PUT_32BIT(s->agent_request, 1);
7557 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
7558 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
7559 ssh_agent_callback, ssh)) {
7560 do {
7561 crReturnV;
7562 if (pktin) {
7563 bombout(("Unexpected data from server while"
7564 " waiting for agent response"));
7565 crStopV;
7566 }
7567 } while (pktin || inlen > 0);
7568 r = ssh->agent_response;
7569 s->agent_responselen = ssh->agent_response_len;
7570 }
7571 s->agent_response = (unsigned char *) r;
7572 if (s->agent_response && s->agent_responselen >= 5 &&
7573 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
7574 int keyi;
7575 unsigned char *p;
7576 p = s->agent_response + 5;
7577 s->nkeys = GET_32BIT(p);
7578 p += 4;
7579 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
7580 if (s->publickey_blob) {
7581 /* See if configured key is in agent. */
7582 for (keyi = 0; keyi < s->nkeys; keyi++) {
7583 s->pklen = GET_32BIT(p);
7584 if (s->pklen == s->publickey_bloblen &&
7585 !memcmp(p+4, s->publickey_blob,
7586 s->publickey_bloblen)) {
7587 logeventf(ssh, "Pageant key #%d matches "
7588 "configured key file", keyi);
7589 s->keyi = keyi;
7590 s->pkblob_in_agent = p;
7591 break;
7592 }
7593 p += 4 + s->pklen;
7594 p += GET_32BIT(p) + 4; /* comment */
7595 }
7596 if (!s->pkblob_in_agent) {
7597 logevent("Configured key file not in Pageant");
7598 s->nkeys = 0;
7599 }
7600 }
7601 } else {
7602 logevent("Failed to get reply from Pageant");
7603 }
7604 }
7605
7606 }
7607
7608 /*
7609 * We repeat this whole loop, including the username prompt,
7610 * until we manage a successful authentication. If the user
7611 * types the wrong _password_, they can be sent back to the
7612 * beginning to try another username, if this is configured on.
7613 * (If they specify a username in the config, they are never
7614 * asked, even if they do give a wrong password.)
7615 *
7616 * I think this best serves the needs of
7617 *
7618 * - the people who have no configuration, no keys, and just
7619 * want to try repeated (username,password) pairs until they
7620 * type both correctly
7621 *
7622 * - people who have keys and configuration but occasionally
7623 * need to fall back to passwords
7624 *
7625 * - people with a key held in Pageant, who might not have
7626 * logged in to a particular machine before; so they want to
7627 * type a username, and then _either_ their key will be
7628 * accepted, _or_ they will type a password. If they mistype
7629 * the username they will want to be able to get back and
7630 * retype it!
7631 */
7632 s->got_username = FALSE;
7633 while (!s->we_are_in) {
7634 /*
7635 * Get a username.
7636 */
7637 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
7638 /*
7639 * We got a username last time round this loop, and
7640 * with change_username turned off we don't try to get
7641 * it again.
7642 */
7643 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
7644 int ret; /* need not be kept over crReturn */
7645 s->cur_prompt = new_prompts(ssh->frontend);
7646 s->cur_prompt->to_server = TRUE;
7647 s->cur_prompt->name = dupstr("SSH login name");
7648 /* 512 is an arbitrary limit :-( */
7649 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE, 512);
7650 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7651 while (ret < 0) {
7652 ssh->send_ok = 1;
7653 crWaitUntilV(!pktin);
7654 ret = get_userpass_input(s->cur_prompt, in, inlen);
7655 ssh->send_ok = 0;
7656 }
7657 if (!ret) {
7658 /*
7659 * get_userpass_input() failed to get a username.
7660 * Terminate.
7661 */
7662 free_prompts(s->cur_prompt);
7663 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
7664 crStopV;
7665 }
7666 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
7667 free_prompts(s->cur_prompt);
7668 } else {
7669 char *stuff;
7670 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7671 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
7672 c_write_str(ssh, stuff);
7673 sfree(stuff);
7674 }
7675 }
7676 s->got_username = TRUE;
7677
7678 /*
7679 * Send an authentication request using method "none": (a)
7680 * just in case it succeeds, and (b) so that we know what
7681 * authentication methods we can usefully try next.
7682 */
7683 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7684
7685 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7686 ssh2_pkt_addstring(s->pktout, ssh->username);
7687 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
7688 ssh2_pkt_addstring(s->pktout, "none"); /* method */
7689 ssh2_pkt_send(ssh, s->pktout);
7690 s->type = AUTH_TYPE_NONE;
7691 s->gotit = FALSE;
7692 s->we_are_in = FALSE;
7693
7694 s->tried_pubkey_config = FALSE;
7695 s->kbd_inter_refused = FALSE;
7696
7697 /* Reset agent request state. */
7698 s->done_agent = FALSE;
7699 if (s->agent_response) {
7700 if (s->pkblob_in_agent) {
7701 s->agentp = s->pkblob_in_agent;
7702 } else {
7703 s->agentp = s->agent_response + 5 + 4;
7704 s->keyi = 0;
7705 }
7706 }
7707
7708 while (1) {
7709 char *methods = NULL;
7710 int methlen = 0;
7711
7712 /*
7713 * Wait for the result of the last authentication request.
7714 */
7715 if (!s->gotit)
7716 crWaitUntilV(pktin);
7717 /*
7718 * Now is a convenient point to spew any banner material
7719 * that we've accumulated. (This should ensure that when
7720 * we exit the auth loop, we haven't any left to deal
7721 * with.)
7722 */
7723 {
7724 int size = bufchain_size(&ssh->banner);
7725 /*
7726 * Don't show the banner if we're operating in
7727 * non-verbose non-interactive mode. (It's probably
7728 * a script, which means nobody will read the
7729 * banner _anyway_, and moreover the printing of
7730 * the banner will screw up processing on the
7731 * output of (say) plink.)
7732 */
7733 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
7734 char *banner = snewn(size, char);
7735 bufchain_fetch(&ssh->banner, banner, size);
7736 c_write_untrusted(ssh, banner, size);
7737 sfree(banner);
7738 }
7739 bufchain_clear(&ssh->banner);
7740 }
7741 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
7742 logevent("Access granted");
7743 s->we_are_in = s->userauth_success = TRUE;
7744 break;
7745 }
7746
7747 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
7748 bombout(("Strange packet received during authentication: "
7749 "type %d", pktin->type));
7750 crStopV;
7751 }
7752
7753 s->gotit = FALSE;
7754
7755 /*
7756 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7757 * we can look at the string in it and know what we can
7758 * helpfully try next.
7759 */
7760 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
7761 ssh_pkt_getstring(pktin, &methods, &methlen);
7762 if (!ssh2_pkt_getbool(pktin)) {
7763 /*
7764 * We have received an unequivocal Access
7765 * Denied. This can translate to a variety of
7766 * messages, or no message at all.
7767 *
7768 * For forms of authentication which are attempted
7769 * implicitly, by which I mean without printing
7770 * anything in the window indicating that we're
7771 * trying them, we should never print 'Access
7772 * denied'.
7773 *
7774 * If we do print a message saying that we're
7775 * attempting some kind of authentication, it's OK
7776 * to print a followup message saying it failed -
7777 * but the message may sometimes be more specific
7778 * than simply 'Access denied'.
7779 *
7780 * Additionally, if we'd just tried password
7781 * authentication, we should break out of this
7782 * whole loop so as to go back to the username
7783 * prompt (iff we're configured to allow
7784 * username change attempts).
7785 */
7786 if (s->type == AUTH_TYPE_NONE) {
7787 /* do nothing */
7788 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
7789 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
7790 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
7791 c_write_str(ssh, "Server refused our key\r\n");
7792 logevent("Server refused our key");
7793 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
7794 /* This _shouldn't_ happen except by a
7795 * protocol bug causing client and server to
7796 * disagree on what is a correct signature. */
7797 c_write_str(ssh, "Server refused public-key signature"
7798 " despite accepting key!\r\n");
7799 logevent("Server refused public-key signature"
7800 " despite accepting key!");
7801 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
7802 /* quiet, so no c_write */
7803 logevent("Server refused keyboard-interactive authentication");
7804 } else if (s->type==AUTH_TYPE_GSSAPI) {
7805 /* always quiet, so no c_write */
7806 /* also, the code down in the GSSAPI block has
7807 * already logged this in the Event Log */
7808 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
7809 logevent("Keyboard-interactive authentication failed");
7810 c_write_str(ssh, "Access denied\r\n");
7811 } else {
7812 assert(s->type == AUTH_TYPE_PASSWORD);
7813 logevent("Password authentication failed");
7814 c_write_str(ssh, "Access denied\r\n");
7815
7816 if (conf_get_int(ssh->conf, CONF_change_username)) {
7817 /* XXX perhaps we should allow
7818 * keyboard-interactive to do this too? */
7819 s->we_are_in = FALSE;
7820 break;
7821 }
7822 }
7823 } else {
7824 c_write_str(ssh, "Further authentication required\r\n");
7825 logevent("Further authentication required");
7826 }
7827
7828 s->can_pubkey =
7829 in_commasep_string("publickey", methods, methlen);
7830 s->can_passwd =
7831 in_commasep_string("password", methods, methlen);
7832 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
7833 in_commasep_string("keyboard-interactive", methods, methlen);
7834 #ifndef NO_GSSAPI
7835 if (!ssh->gsslibs)
7836 ssh->gsslibs = ssh_gss_setup(ssh->conf);
7837 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
7838 in_commasep_string("gssapi-with-mic", methods, methlen) &&
7839 ssh->gsslibs->nlibraries > 0;
7840 #endif
7841 }
7842
7843 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7844
7845 if (s->can_pubkey && !s->done_agent && s->nkeys) {
7846
7847 /*
7848 * Attempt public-key authentication using a key from Pageant.
7849 */
7850
7851 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7852
7853 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
7854
7855 /* Unpack key from agent response */
7856 s->pklen = GET_32BIT(s->agentp);
7857 s->agentp += 4;
7858 s->pkblob = (char *)s->agentp;
7859 s->agentp += s->pklen;
7860 s->alglen = GET_32BIT(s->pkblob);
7861 s->alg = s->pkblob + 4;
7862 s->commentlen = GET_32BIT(s->agentp);
7863 s->agentp += 4;
7864 s->commentp = (char *)s->agentp;
7865 s->agentp += s->commentlen;
7866 /* s->agentp now points at next key, if any */
7867
7868 /* See if server will accept it */
7869 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7870 ssh2_pkt_addstring(s->pktout, ssh->username);
7871 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7872 /* service requested */
7873 ssh2_pkt_addstring(s->pktout, "publickey");
7874 /* method */
7875 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
7876 ssh2_pkt_addstring_start(s->pktout);
7877 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7878 ssh2_pkt_addstring_start(s->pktout);
7879 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7880 ssh2_pkt_send(ssh, s->pktout);
7881 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
7882
7883 crWaitUntilV(pktin);
7884 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7885
7886 /* Offer of key refused. */
7887 s->gotit = TRUE;
7888
7889 } else {
7890
7891 void *vret;
7892
7893 if (flags & FLAG_VERBOSE) {
7894 c_write_str(ssh, "Authenticating with "
7895 "public key \"");
7896 c_write(ssh, s->commentp, s->commentlen);
7897 c_write_str(ssh, "\" from agent\r\n");
7898 }
7899
7900 /*
7901 * Server is willing to accept the key.
7902 * Construct a SIGN_REQUEST.
7903 */
7904 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7905 ssh2_pkt_addstring(s->pktout, ssh->username);
7906 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7907 /* service requested */
7908 ssh2_pkt_addstring(s->pktout, "publickey");
7909 /* method */
7910 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
7911 ssh2_pkt_addstring_start(s->pktout);
7912 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7913 ssh2_pkt_addstring_start(s->pktout);
7914 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7915
7916 /* Ask agent for signature. */
7917 s->siglen = s->pktout->length - 5 + 4 +
7918 ssh->v2_session_id_len;
7919 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7920 s->siglen -= 4;
7921 s->len = 1; /* message type */
7922 s->len += 4 + s->pklen; /* key blob */
7923 s->len += 4 + s->siglen; /* data to sign */
7924 s->len += 4; /* flags */
7925 s->agentreq = snewn(4 + s->len, char);
7926 PUT_32BIT(s->agentreq, s->len);
7927 s->q = s->agentreq + 4;
7928 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
7929 PUT_32BIT(s->q, s->pklen);
7930 s->q += 4;
7931 memcpy(s->q, s->pkblob, s->pklen);
7932 s->q += s->pklen;
7933 PUT_32BIT(s->q, s->siglen);
7934 s->q += 4;
7935 /* Now the data to be signed... */
7936 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7937 PUT_32BIT(s->q, ssh->v2_session_id_len);
7938 s->q += 4;
7939 }
7940 memcpy(s->q, ssh->v2_session_id,
7941 ssh->v2_session_id_len);
7942 s->q += ssh->v2_session_id_len;
7943 memcpy(s->q, s->pktout->data + 5,
7944 s->pktout->length - 5);
7945 s->q += s->pktout->length - 5;
7946 /* And finally the (zero) flags word. */
7947 PUT_32BIT(s->q, 0);
7948 if (!agent_query(s->agentreq, s->len + 4,
7949 &vret, &s->retlen,
7950 ssh_agent_callback, ssh)) {
7951 do {
7952 crReturnV;
7953 if (pktin) {
7954 bombout(("Unexpected data from server"
7955 " while waiting for agent"
7956 " response"));
7957 crStopV;
7958 }
7959 } while (pktin || inlen > 0);
7960 vret = ssh->agent_response;
7961 s->retlen = ssh->agent_response_len;
7962 }
7963 s->ret = vret;
7964 sfree(s->agentreq);
7965 if (s->ret) {
7966 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
7967 logevent("Sending Pageant's response");
7968 ssh2_add_sigblob(ssh, s->pktout,
7969 s->pkblob, s->pklen,
7970 s->ret + 9,
7971 GET_32BIT(s->ret + 5));
7972 ssh2_pkt_send(ssh, s->pktout);
7973 s->type = AUTH_TYPE_PUBLICKEY;
7974 } else {
7975 /* FIXME: less drastic response */
7976 bombout(("Pageant failed to answer challenge"));
7977 crStopV;
7978 }
7979 }
7980 }
7981
7982 /* Do we have any keys left to try? */
7983 if (s->pkblob_in_agent) {
7984 s->done_agent = TRUE;
7985 s->tried_pubkey_config = TRUE;
7986 } else {
7987 s->keyi++;
7988 if (s->keyi >= s->nkeys)
7989 s->done_agent = TRUE;
7990 }
7991
7992 } else if (s->can_pubkey && s->publickey_blob &&
7993 !s->tried_pubkey_config) {
7994
7995 struct ssh2_userkey *key; /* not live over crReturn */
7996 char *passphrase; /* not live over crReturn */
7997
7998 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7999
8000 s->tried_pubkey_config = TRUE;
8001
8002 /*
8003 * Try the public key supplied in the configuration.
8004 *
8005 * First, offer the public blob to see if the server is
8006 * willing to accept it.
8007 */
8008 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8009 ssh2_pkt_addstring(s->pktout, ssh->username);
8010 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8011 /* service requested */
8012 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
8013 ssh2_pkt_addbool(s->pktout, FALSE);
8014 /* no signature included */
8015 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
8016 ssh2_pkt_addstring_start(s->pktout);
8017 ssh2_pkt_addstring_data(s->pktout,
8018 (char *)s->publickey_blob,
8019 s->publickey_bloblen);
8020 ssh2_pkt_send(ssh, s->pktout);
8021 logevent("Offered public key");
8022
8023 crWaitUntilV(pktin);
8024 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8025 /* Key refused. Give up. */
8026 s->gotit = TRUE; /* reconsider message next loop */
8027 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
8028 continue; /* process this new message */
8029 }
8030 logevent("Offer of public key accepted");
8031
8032 /*
8033 * Actually attempt a serious authentication using
8034 * the key.
8035 */
8036 if (flags & FLAG_VERBOSE) {
8037 c_write_str(ssh, "Authenticating with public key \"");
8038 c_write_str(ssh, s->publickey_comment);
8039 c_write_str(ssh, "\"\r\n");
8040 }
8041 key = NULL;
8042 while (!key) {
8043 const char *error; /* not live over crReturn */
8044 if (s->publickey_encrypted) {
8045 /*
8046 * Get a passphrase from the user.
8047 */
8048 int ret; /* need not be kept over crReturn */
8049 s->cur_prompt = new_prompts(ssh->frontend);
8050 s->cur_prompt->to_server = FALSE;
8051 s->cur_prompt->name = dupstr("SSH key passphrase");
8052 add_prompt(s->cur_prompt,
8053 dupprintf("Passphrase for key \"%.100s\": ",
8054 s->publickey_comment),
8055 FALSE, SSH_MAX_PASSWORD_LEN);
8056 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8057 while (ret < 0) {
8058 ssh->send_ok = 1;
8059 crWaitUntilV(!pktin);
8060 ret = get_userpass_input(s->cur_prompt,
8061 in, inlen);
8062 ssh->send_ok = 0;
8063 }
8064 if (!ret) {
8065 /* Failed to get a passphrase. Terminate. */
8066 free_prompts(s->cur_prompt);
8067 ssh_disconnect(ssh, NULL,
8068 "Unable to authenticate",
8069 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8070 TRUE);
8071 crStopV;
8072 }
8073 passphrase =
8074 dupstr(s->cur_prompt->prompts[0]->result);
8075 free_prompts(s->cur_prompt);
8076 } else {
8077 passphrase = NULL; /* no passphrase needed */
8078 }
8079
8080 /*
8081 * Try decrypting the key.
8082 */
8083 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8084 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
8085 if (passphrase) {
8086 /* burn the evidence */
8087 memset(passphrase, 0, strlen(passphrase));
8088 sfree(passphrase);
8089 }
8090 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
8091 if (passphrase &&
8092 (key == SSH2_WRONG_PASSPHRASE)) {
8093 c_write_str(ssh, "Wrong passphrase\r\n");
8094 key = NULL;
8095 /* and loop again */
8096 } else {
8097 c_write_str(ssh, "Unable to load private key (");
8098 c_write_str(ssh, error);
8099 c_write_str(ssh, ")\r\n");
8100 key = NULL;
8101 break; /* try something else */
8102 }
8103 }
8104 }
8105
8106 if (key) {
8107 unsigned char *pkblob, *sigblob, *sigdata;
8108 int pkblob_len, sigblob_len, sigdata_len;
8109 int p;
8110
8111 /*
8112 * We have loaded the private key and the server
8113 * has announced that it's willing to accept it.
8114 * Hallelujah. Generate a signature and send it.
8115 */
8116 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8117 ssh2_pkt_addstring(s->pktout, ssh->username);
8118 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8119 /* service requested */
8120 ssh2_pkt_addstring(s->pktout, "publickey");
8121 /* method */
8122 ssh2_pkt_addbool(s->pktout, TRUE);
8123 /* signature follows */
8124 ssh2_pkt_addstring(s->pktout, key->alg->name);
8125 pkblob = key->alg->public_blob(key->data,
8126 &pkblob_len);
8127 ssh2_pkt_addstring_start(s->pktout);
8128 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
8129 pkblob_len);
8130
8131 /*
8132 * The data to be signed is:
8133 *
8134 * string session-id
8135 *
8136 * followed by everything so far placed in the
8137 * outgoing packet.
8138 */
8139 sigdata_len = s->pktout->length - 5 + 4 +
8140 ssh->v2_session_id_len;
8141 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8142 sigdata_len -= 4;
8143 sigdata = snewn(sigdata_len, unsigned char);
8144 p = 0;
8145 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8146 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
8147 p += 4;
8148 }
8149 memcpy(sigdata+p, ssh->v2_session_id,
8150 ssh->v2_session_id_len);
8151 p += ssh->v2_session_id_len;
8152 memcpy(sigdata+p, s->pktout->data + 5,
8153 s->pktout->length - 5);
8154 p += s->pktout->length - 5;
8155 assert(p == sigdata_len);
8156 sigblob = key->alg->sign(key->data, (char *)sigdata,
8157 sigdata_len, &sigblob_len);
8158 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
8159 sigblob, sigblob_len);
8160 sfree(pkblob);
8161 sfree(sigblob);
8162 sfree(sigdata);
8163
8164 ssh2_pkt_send(ssh, s->pktout);
8165 logevent("Sent public key signature");
8166 s->type = AUTH_TYPE_PUBLICKEY;
8167 key->alg->freekey(key->data);
8168 }
8169
8170 #ifndef NO_GSSAPI
8171 } else if (s->can_gssapi && !s->tried_gssapi) {
8172
8173 /* GSSAPI Authentication */
8174
8175 int micoffset, len;
8176 char *data;
8177 Ssh_gss_buf mic;
8178 s->type = AUTH_TYPE_GSSAPI;
8179 s->tried_gssapi = TRUE;
8180 s->gotit = TRUE;
8181 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
8182
8183 /*
8184 * Pick the highest GSS library on the preference
8185 * list.
8186 */
8187 {
8188 int i, j;
8189 s->gsslib = NULL;
8190 for (i = 0; i < ngsslibs; i++) {
8191 int want_id = conf_get_int_int(ssh->conf,
8192 CONF_ssh_gsslist, i);
8193 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
8194 if (ssh->gsslibs->libraries[j].id == want_id) {
8195 s->gsslib = &ssh->gsslibs->libraries[j];
8196 goto got_gsslib; /* double break */
8197 }
8198 }
8199 got_gsslib:
8200 /*
8201 * We always expect to have found something in
8202 * the above loop: we only came here if there
8203 * was at least one viable GSS library, and the
8204 * preference list should always mention
8205 * everything and only change the order.
8206 */
8207 assert(s->gsslib);
8208 }
8209
8210 if (s->gsslib->gsslogmsg)
8211 logevent(s->gsslib->gsslogmsg);
8212
8213 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8214 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8215 ssh2_pkt_addstring(s->pktout, ssh->username);
8216 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8217 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
8218 logevent("Attempting GSSAPI authentication");
8219
8220 /* add mechanism info */
8221 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
8222
8223 /* number of GSSAPI mechanisms */
8224 ssh2_pkt_adduint32(s->pktout,1);
8225
8226 /* length of OID + 2 */
8227 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
8228 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
8229
8230 /* length of OID */
8231 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
8232
8233 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
8234 s->gss_buf.length);
8235 ssh2_pkt_send(ssh, s->pktout);
8236 crWaitUntilV(pktin);
8237 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
8238 logevent("GSSAPI authentication request refused");
8239 continue;
8240 }
8241
8242 /* check returned packet ... */
8243
8244 ssh_pkt_getstring(pktin, &data, &len);
8245 s->gss_rcvtok.value = data;
8246 s->gss_rcvtok.length = len;
8247 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
8248 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
8249 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
8250 memcmp((char *)s->gss_rcvtok.value + 2,
8251 s->gss_buf.value,s->gss_buf.length) ) {
8252 logevent("GSSAPI authentication - wrong response from server");
8253 continue;
8254 }
8255
8256 /* now start running */
8257 s->gss_stat = s->gsslib->import_name(s->gsslib,
8258 ssh->fullhostname,
8259 &s->gss_srv_name);
8260 if (s->gss_stat != SSH_GSS_OK) {
8261 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
8262 logevent("GSSAPI import name failed - Bad service name");
8263 else
8264 logevent("GSSAPI import name failed");
8265 continue;
8266 }
8267
8268 /* fetch TGT into GSS engine */
8269 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
8270
8271 if (s->gss_stat != SSH_GSS_OK) {
8272 logevent("GSSAPI authentication failed to get credentials");
8273 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8274 continue;
8275 }
8276
8277 /* initial tokens are empty */
8278 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
8279 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
8280
8281 /* now enter the loop */
8282 do {
8283 s->gss_stat = s->gsslib->init_sec_context
8284 (s->gsslib,
8285 &s->gss_ctx,
8286 s->gss_srv_name,
8287 conf_get_int(ssh->conf, CONF_gssapifwd),
8288 &s->gss_rcvtok,
8289 &s->gss_sndtok);
8290
8291 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
8292 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
8293 logevent("GSSAPI authentication initialisation failed");
8294
8295 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
8296 &s->gss_buf) == SSH_GSS_OK) {
8297 logevent(s->gss_buf.value);
8298 sfree(s->gss_buf.value);
8299 }
8300
8301 break;
8302 }
8303 logevent("GSSAPI authentication initialised");
8304
8305 /* Client and server now exchange tokens until GSSAPI
8306 * no longer says CONTINUE_NEEDED */
8307
8308 if (s->gss_sndtok.length != 0) {
8309 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8310 ssh_pkt_addstring_start(s->pktout);
8311 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
8312 ssh2_pkt_send(ssh, s->pktout);
8313 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
8314 }
8315
8316 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8317 crWaitUntilV(pktin);
8318 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8319 logevent("GSSAPI authentication - bad server response");
8320 s->gss_stat = SSH_GSS_FAILURE;
8321 break;
8322 }
8323 ssh_pkt_getstring(pktin, &data, &len);
8324 s->gss_rcvtok.value = data;
8325 s->gss_rcvtok.length = len;
8326 }
8327 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8328
8329 if (s->gss_stat != SSH_GSS_OK) {
8330 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8331 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8332 continue;
8333 }
8334 logevent("GSSAPI authentication loop finished OK");
8335
8336 /* Now send the MIC */
8337
8338 s->pktout = ssh2_pkt_init(0);
8339 micoffset = s->pktout->length;
8340 ssh_pkt_addstring_start(s->pktout);
8341 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8342 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
8343 ssh_pkt_addstring(s->pktout, ssh->username);
8344 ssh_pkt_addstring(s->pktout, "ssh-connection");
8345 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8346
8347 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8348 s->gss_buf.length = s->pktout->length - micoffset;
8349
8350 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
8351 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8352 ssh_pkt_addstring_start(s->pktout);
8353 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
8354 ssh2_pkt_send(ssh, s->pktout);
8355 s->gsslib->free_mic(s->gsslib, &mic);
8356
8357 s->gotit = FALSE;
8358
8359 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8360 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8361 continue;
8362 #endif
8363 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8364
8365 /*
8366 * Keyboard-interactive authentication.
8367 */
8368
8369 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8370
8371 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
8372
8373 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8374 ssh2_pkt_addstring(s->pktout, ssh->username);
8375 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8376 /* service requested */
8377 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8378 /* method */
8379 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8380 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8381 ssh2_pkt_send(ssh, s->pktout);
8382
8383 logevent("Attempting keyboard-interactive authentication");
8384
8385 crWaitUntilV(pktin);
8386 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8387 /* Server is not willing to do keyboard-interactive
8388 * at all (or, bizarrely but legally, accepts the
8389 * user without actually issuing any prompts).
8390 * Give up on it entirely. */
8391 s->gotit = TRUE;
8392 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8393 s->kbd_inter_refused = TRUE; /* don't try it again */
8394 continue;
8395 }
8396
8397 /*
8398 * Loop while the server continues to send INFO_REQUESTs.
8399 */
8400 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
8401
8402 char *name, *inst, *lang;
8403 int name_len, inst_len, lang_len;
8404 int i;
8405
8406 /*
8407 * We've got a fresh USERAUTH_INFO_REQUEST.
8408 * Get the preamble and start building a prompt.
8409 */
8410 ssh_pkt_getstring(pktin, &name, &name_len);
8411 ssh_pkt_getstring(pktin, &inst, &inst_len);
8412 ssh_pkt_getstring(pktin, &lang, &lang_len);
8413 s->cur_prompt = new_prompts(ssh->frontend);
8414 s->cur_prompt->to_server = TRUE;
8415
8416 /*
8417 * Get any prompt(s) from the packet.
8418 */
8419 s->num_prompts = ssh_pkt_getuint32(pktin);
8420 for (i = 0; i < s->num_prompts; i++) {
8421 char *prompt;
8422 int prompt_len;
8423 int echo;
8424 static char noprompt[] =
8425 "<server failed to send prompt>: ";
8426
8427 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8428 echo = ssh2_pkt_getbool(pktin);
8429 if (!prompt_len) {
8430 prompt = noprompt;
8431 prompt_len = lenof(noprompt)-1;
8432 }
8433 add_prompt(s->cur_prompt,
8434 dupprintf("%.*s", prompt_len, prompt),
8435 echo, SSH_MAX_PASSWORD_LEN);
8436 }
8437
8438 if (name_len) {
8439 /* FIXME: better prefix to distinguish from
8440 * local prompts? */
8441 s->cur_prompt->name =
8442 dupprintf("SSH server: %.*s", name_len, name);
8443 s->cur_prompt->name_reqd = TRUE;
8444 } else {
8445 s->cur_prompt->name =
8446 dupstr("SSH server authentication");
8447 s->cur_prompt->name_reqd = FALSE;
8448 }
8449 /* We add a prefix to try to make it clear that a prompt
8450 * has come from the server.
8451 * FIXME: ugly to print "Using..." in prompt _every_
8452 * time round. Can this be done more subtly? */
8453 /* Special case: for reasons best known to themselves,
8454 * some servers send k-i requests with no prompts and
8455 * nothing to display. Keep quiet in this case. */
8456 if (s->num_prompts || name_len || inst_len) {
8457 s->cur_prompt->instruction =
8458 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8459 inst_len ? "\n" : "", inst_len, inst);
8460 s->cur_prompt->instr_reqd = TRUE;
8461 } else {
8462 s->cur_prompt->instr_reqd = FALSE;
8463 }
8464
8465 /*
8466 * Display any instructions, and get the user's
8467 * response(s).
8468 */
8469 {
8470 int ret; /* not live over crReturn */
8471 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8472 while (ret < 0) {
8473 ssh->send_ok = 1;
8474 crWaitUntilV(!pktin);
8475 ret = get_userpass_input(s->cur_prompt, in, inlen);
8476 ssh->send_ok = 0;
8477 }
8478 if (!ret) {
8479 /*
8480 * Failed to get responses. Terminate.
8481 */
8482 free_prompts(s->cur_prompt);
8483 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8484 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8485 TRUE);
8486 crStopV;
8487 }
8488 }
8489
8490 /*
8491 * Send the response(s) to the server.
8492 */
8493 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
8494 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
8495 for (i=0; i < s->num_prompts; i++) {
8496 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8497 ssh2_pkt_addstring(s->pktout,
8498 s->cur_prompt->prompts[i]->result);
8499 end_log_omission(ssh, s->pktout);
8500 }
8501 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8502
8503 /*
8504 * Get the next packet in case it's another
8505 * INFO_REQUEST.
8506 */
8507 crWaitUntilV(pktin);
8508
8509 }
8510
8511 /*
8512 * We should have SUCCESS or FAILURE now.
8513 */
8514 s->gotit = TRUE;
8515
8516 } else if (s->can_passwd) {
8517
8518 /*
8519 * Plain old password authentication.
8520 */
8521 int ret; /* not live over crReturn */
8522 int changereq_first_time; /* not live over crReturn */
8523
8524 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
8525
8526 s->cur_prompt = new_prompts(ssh->frontend);
8527 s->cur_prompt->to_server = TRUE;
8528 s->cur_prompt->name = dupstr("SSH password");
8529 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
8530 ssh->username,
8531 ssh->savedhost),
8532 FALSE, SSH_MAX_PASSWORD_LEN);
8533
8534 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8535 while (ret < 0) {
8536 ssh->send_ok = 1;
8537 crWaitUntilV(!pktin);
8538 ret = get_userpass_input(s->cur_prompt, in, inlen);
8539 ssh->send_ok = 0;
8540 }
8541 if (!ret) {
8542 /*
8543 * Failed to get responses. Terminate.
8544 */
8545 free_prompts(s->cur_prompt);
8546 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8547 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8548 TRUE);
8549 crStopV;
8550 }
8551 /*
8552 * Squirrel away the password. (We may need it later if
8553 * asked to change it.)
8554 */
8555 s->password = dupstr(s->cur_prompt->prompts[0]->result);
8556 free_prompts(s->cur_prompt);
8557
8558 /*
8559 * Send the password packet.
8560 *
8561 * We pad out the password packet to 256 bytes to make
8562 * it harder for an attacker to find the length of the
8563 * user's password.
8564 *
8565 * Anyone using a password longer than 256 bytes
8566 * probably doesn't have much to worry about from
8567 * people who find out how long their password is!
8568 */
8569 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8570 ssh2_pkt_addstring(s->pktout, ssh->username);
8571 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8572 /* service requested */
8573 ssh2_pkt_addstring(s->pktout, "password");
8574 ssh2_pkt_addbool(s->pktout, FALSE);
8575 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8576 ssh2_pkt_addstring(s->pktout, s->password);
8577 end_log_omission(ssh, s->pktout);
8578 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8579 logevent("Sent password");
8580 s->type = AUTH_TYPE_PASSWORD;
8581
8582 /*
8583 * Wait for next packet, in case it's a password change
8584 * request.
8585 */
8586 crWaitUntilV(pktin);
8587 changereq_first_time = TRUE;
8588
8589 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
8590
8591 /*
8592 * We're being asked for a new password
8593 * (perhaps not for the first time).
8594 * Loop until the server accepts it.
8595 */
8596
8597 int got_new = FALSE; /* not live over crReturn */
8598 char *prompt; /* not live over crReturn */
8599 int prompt_len; /* not live over crReturn */
8600
8601 {
8602 char *msg;
8603 if (changereq_first_time)
8604 msg = "Server requested password change";
8605 else
8606 msg = "Server rejected new password";
8607 logevent(msg);
8608 c_write_str(ssh, msg);
8609 c_write_str(ssh, "\r\n");
8610 }
8611
8612 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8613
8614 s->cur_prompt = new_prompts(ssh->frontend);
8615 s->cur_prompt->to_server = TRUE;
8616 s->cur_prompt->name = dupstr("New SSH password");
8617 s->cur_prompt->instruction =
8618 dupprintf("%.*s", prompt_len, prompt);
8619 s->cur_prompt->instr_reqd = TRUE;
8620 /*
8621 * There's no explicit requirement in the protocol
8622 * for the "old" passwords in the original and
8623 * password-change messages to be the same, and
8624 * apparently some Cisco kit supports password change
8625 * by the user entering a blank password originally
8626 * and the real password subsequently, so,
8627 * reluctantly, we prompt for the old password again.
8628 *
8629 * (On the other hand, some servers don't even bother
8630 * to check this field.)
8631 */
8632 add_prompt(s->cur_prompt,
8633 dupstr("Current password (blank for previously entered password): "),
8634 FALSE, SSH_MAX_PASSWORD_LEN);
8635 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
8636 FALSE, SSH_MAX_PASSWORD_LEN);
8637 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
8638 FALSE, SSH_MAX_PASSWORD_LEN);
8639
8640 /*
8641 * Loop until the user manages to enter the same
8642 * password twice.
8643 */
8644 while (!got_new) {
8645
8646 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8647 while (ret < 0) {
8648 ssh->send_ok = 1;
8649 crWaitUntilV(!pktin);
8650 ret = get_userpass_input(s->cur_prompt, in, inlen);
8651 ssh->send_ok = 0;
8652 }
8653 if (!ret) {
8654 /*
8655 * Failed to get responses. Terminate.
8656 */
8657 /* burn the evidence */
8658 free_prompts(s->cur_prompt);
8659 memset(s->password, 0, strlen(s->password));
8660 sfree(s->password);
8661 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8662 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8663 TRUE);
8664 crStopV;
8665 }
8666
8667 /*
8668 * If the user specified a new original password
8669 * (IYSWIM), overwrite any previously specified
8670 * one.
8671 * (A side effect is that the user doesn't have to
8672 * re-enter it if they louse up the new password.)
8673 */
8674 if (s->cur_prompt->prompts[0]->result[0]) {
8675 memset(s->password, 0, strlen(s->password));
8676 /* burn the evidence */
8677 sfree(s->password);
8678 s->password =
8679 dupstr(s->cur_prompt->prompts[0]->result);
8680 }
8681
8682 /*
8683 * Check the two new passwords match.
8684 */
8685 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
8686 s->cur_prompt->prompts[2]->result)
8687 == 0);
8688 if (!got_new)
8689 /* They don't. Silly user. */
8690 c_write_str(ssh, "Passwords do not match\r\n");
8691
8692 }
8693
8694 /*
8695 * Send the new password (along with the old one).
8696 * (see above for padding rationale)
8697 */
8698 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8699 ssh2_pkt_addstring(s->pktout, ssh->username);
8700 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8701 /* service requested */
8702 ssh2_pkt_addstring(s->pktout, "password");
8703 ssh2_pkt_addbool(s->pktout, TRUE);
8704 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8705 ssh2_pkt_addstring(s->pktout, s->password);
8706 ssh2_pkt_addstring(s->pktout,
8707 s->cur_prompt->prompts[1]->result);
8708 free_prompts(s->cur_prompt);
8709 end_log_omission(ssh, s->pktout);
8710 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8711 logevent("Sent new password");
8712
8713 /*
8714 * Now see what the server has to say about it.
8715 * (If it's CHANGEREQ again, it's not happy with the
8716 * new password.)
8717 */
8718 crWaitUntilV(pktin);
8719 changereq_first_time = FALSE;
8720
8721 }
8722
8723 /*
8724 * We need to reexamine the current pktin at the top
8725 * of the loop. Either:
8726 * - we weren't asked to change password at all, in
8727 * which case it's a SUCCESS or FAILURE with the
8728 * usual meaning
8729 * - we sent a new password, and the server was
8730 * either OK with it (SUCCESS or FAILURE w/partial
8731 * success) or unhappy with the _old_ password
8732 * (FAILURE w/o partial success)
8733 * In any of these cases, we go back to the top of
8734 * the loop and start again.
8735 */
8736 s->gotit = TRUE;
8737
8738 /*
8739 * We don't need the old password any more, in any
8740 * case. Burn the evidence.
8741 */
8742 memset(s->password, 0, strlen(s->password));
8743 sfree(s->password);
8744
8745 } else {
8746 char *str = dupprintf("No supported authentication methods available"
8747 " (server sent: %.*s)",
8748 methlen, methods);
8749
8750 ssh_disconnect(ssh, str,
8751 "No supported authentication methods available",
8752 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
8753 FALSE);
8754 sfree(str);
8755
8756 crStopV;
8757
8758 }
8759
8760 }
8761 }
8762 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
8763
8764 /* Clear up various bits and pieces from authentication. */
8765 if (s->publickey_blob) {
8766 sfree(s->publickey_blob);
8767 sfree(s->publickey_comment);
8768 }
8769 if (s->agent_response)
8770 sfree(s->agent_response);
8771
8772 if (s->userauth_success) {
8773 /*
8774 * We've just received USERAUTH_SUCCESS, and we haven't sent any
8775 * packets since. Signal the transport layer to consider enacting
8776 * delayed compression.
8777 *
8778 * (Relying on we_are_in is not sufficient, as
8779 * draft-miller-secsh-compression-delayed is quite clear that it
8780 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
8781 * become set for other reasons.)
8782 */
8783 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
8784 }
8785
8786 /*
8787 * Now the connection protocol has started, one way or another.
8788 */
8789
8790 ssh->channels = newtree234(ssh_channelcmp);
8791
8792 /*
8793 * Set up handlers for some connection protocol messages, so we
8794 * don't have to handle them repeatedly in this coroutine.
8795 */
8796 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
8797 ssh2_msg_channel_window_adjust;
8798 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
8799 ssh2_msg_global_request;
8800
8801 /*
8802 * Create the main session channel.
8803 */
8804 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
8805 ssh->mainchan = NULL;
8806 } else if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
8807 /*
8808 * Just start a direct-tcpip channel and use it as the main
8809 * channel.
8810 */
8811 ssh->mainchan = snew(struct ssh_channel);
8812 ssh->mainchan->ssh = ssh;
8813 ssh2_channel_init(ssh->mainchan);
8814 logeventf(ssh,
8815 "Opening direct-tcpip channel to %s:%d in place of session",
8816 conf_get_str(ssh->conf, CONF_ssh_nc_host),
8817 conf_get_int(ssh->conf, CONF_ssh_nc_port));
8818 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8819 ssh2_pkt_addstring(s->pktout, "direct-tcpip");
8820 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8821 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8822 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8823 ssh2_pkt_addstring(s->pktout, conf_get_str(ssh->conf, CONF_ssh_nc_host));
8824 ssh2_pkt_adduint32(s->pktout, conf_get_int(ssh->conf, CONF_ssh_nc_port));
8825 /*
8826 * There's nothing meaningful to put in the originator
8827 * fields, but some servers insist on syntactically correct
8828 * information.
8829 */
8830 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
8831 ssh2_pkt_adduint32(s->pktout, 0);
8832 ssh2_pkt_send(ssh, s->pktout);
8833
8834 crWaitUntilV(pktin);
8835 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8836 bombout(("Server refused to open a direct-tcpip channel"));
8837 crStopV;
8838 /* FIXME: error data comes back in FAILURE packet */
8839 }
8840 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8841 bombout(("Server's channel confirmation cited wrong channel"));
8842 crStopV;
8843 }
8844 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8845 ssh->mainchan->halfopen = FALSE;
8846 ssh->mainchan->type = CHAN_MAINSESSION;
8847 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8848 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8849 add234(ssh->channels, ssh->mainchan);
8850 update_specials_menu(ssh->frontend);
8851 logevent("Opened direct-tcpip channel");
8852 ssh->ncmode = TRUE;
8853 } else {
8854 ssh->mainchan = snew(struct ssh_channel);
8855 ssh->mainchan->ssh = ssh;
8856 ssh2_channel_init(ssh->mainchan);
8857 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8858 ssh2_pkt_addstring(s->pktout, "session");
8859 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8860 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8861 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8862 ssh2_pkt_send(ssh, s->pktout);
8863 crWaitUntilV(pktin);
8864 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8865 bombout(("Server refused to open a session"));
8866 crStopV;
8867 /* FIXME: error data comes back in FAILURE packet */
8868 }
8869 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8870 bombout(("Server's channel confirmation cited wrong channel"));
8871 crStopV;
8872 }
8873 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8874 ssh->mainchan->halfopen = FALSE;
8875 ssh->mainchan->type = CHAN_MAINSESSION;
8876 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8877 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8878 add234(ssh->channels, ssh->mainchan);
8879 update_specials_menu(ssh->frontend);
8880 logevent("Opened channel for session");
8881 ssh->ncmode = FALSE;
8882 }
8883
8884 /*
8885 * Now we have a channel, make dispatch table entries for
8886 * general channel-based messages.
8887 */
8888 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
8889 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
8890 ssh2_msg_channel_data;
8891 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
8892 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
8893 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
8894 ssh2_msg_channel_open_confirmation;
8895 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
8896 ssh2_msg_channel_open_failure;
8897 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
8898 ssh2_msg_channel_request;
8899 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
8900 ssh2_msg_channel_open;
8901
8902 if (ssh->mainchan && conf_get_int(ssh->conf, CONF_ssh_simple)) {
8903 /*
8904 * This message indicates to the server that we promise
8905 * not to try to run any other channel in parallel with
8906 * this one, so it's safe for it to advertise a very large
8907 * window and leave the flow control to TCP.
8908 */
8909 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8910 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8911 ssh2_pkt_addstring(s->pktout, "simple@putty.projects.tartarus.org");
8912 ssh2_pkt_addbool(s->pktout, 0); /* no reply */
8913 ssh2_pkt_send(ssh, s->pktout);
8914 }
8915
8916 /*
8917 * Potentially enable X11 forwarding.
8918 */
8919 if (ssh->mainchan && !ssh->ncmode && conf_get_int(ssh->conf, CONF_x11_forward) &&
8920 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
8921 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
8922 logevent("Requesting X11 forwarding");
8923 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8924 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8925 ssh2_pkt_addstring(s->pktout, "x11-req");
8926 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8927 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
8928 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthprotoname);
8929 /*
8930 * Note that while we blank the X authentication data here, we don't
8931 * take any special action to blank the start of an X11 channel,
8932 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
8933 * without having session blanking enabled is likely to leak your
8934 * cookie into the log.
8935 */
8936 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8937 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthdatastring);
8938 end_log_omission(ssh, s->pktout);
8939 ssh2_pkt_adduint32(s->pktout, ssh->x11disp->screennum);
8940 ssh2_pkt_send(ssh, s->pktout);
8941
8942 crWaitUntilV(pktin);
8943
8944 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8945 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8946 bombout(("Unexpected response to X11 forwarding request:"
8947 " packet type %d", pktin->type));
8948 crStopV;
8949 }
8950 logevent("X11 forwarding refused");
8951 } else {
8952 logevent("X11 forwarding enabled");
8953 ssh->X11_fwd_enabled = TRUE;
8954 }
8955 }
8956
8957 /*
8958 * Enable port forwardings.
8959 */
8960 ssh_setup_portfwd(ssh, ssh->conf);
8961
8962 /*
8963 * Potentially enable agent forwarding.
8964 */
8965 if (ssh->mainchan && !ssh->ncmode && conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
8966 logevent("Requesting OpenSSH-style agent forwarding");
8967 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8968 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8969 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
8970 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8971 ssh2_pkt_send(ssh, s->pktout);
8972
8973 crWaitUntilV(pktin);
8974
8975 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8976 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8977 bombout(("Unexpected response to agent forwarding request:"
8978 " packet type %d", pktin->type));
8979 crStopV;
8980 }
8981 logevent("Agent forwarding refused");
8982 } else {
8983 logevent("Agent forwarding enabled");
8984 ssh->agentfwd_enabled = TRUE;
8985 }
8986 }
8987
8988 /*
8989 * Now allocate a pty for the session.
8990 */
8991 if (ssh->mainchan && !ssh->ncmode && !conf_get_int(ssh->conf, CONF_nopty)) {
8992 /* Unpick the terminal-speed string. */
8993 /* XXX perhaps we should allow no speeds to be sent. */
8994 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8995 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8996 /* Build the pty request. */
8997 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8998 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
8999 ssh2_pkt_addstring(s->pktout, "pty-req");
9000 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9001 ssh2_pkt_addstring(s->pktout, conf_get_str(ssh->conf, CONF_termtype));
9002 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
9003 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
9004 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
9005 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
9006 ssh2_pkt_addstring_start(s->pktout);
9007 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)s->pktout);
9008 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_ISPEED);
9009 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
9010 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_OSPEED);
9011 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
9012 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
9013 ssh2_pkt_send(ssh, s->pktout);
9014 ssh->state = SSH_STATE_INTERMED;
9015
9016 crWaitUntilV(pktin);
9017
9018 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9019 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9020 bombout(("Unexpected response to pty request:"
9021 " packet type %d", pktin->type));
9022 crStopV;
9023 }
9024 c_write_str(ssh, "Server refused to allocate pty\r\n");
9025 ssh->editing = ssh->echoing = 1;
9026 } else {
9027 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9028 ssh->ospeed, ssh->ispeed);
9029 ssh->got_pty = TRUE;
9030 }
9031 } else {
9032 ssh->editing = ssh->echoing = 1;
9033 }
9034
9035 /*
9036 * Send environment variables.
9037 *
9038 * Simplest thing here is to send all the requests at once, and
9039 * then wait for a whole bunch of successes or failures.
9040 */
9041 if (ssh->mainchan && !ssh->ncmode) {
9042 char *key, *val;
9043
9044 s->num_env = 0;
9045
9046 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9047 val != NULL;
9048 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9049 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9050 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
9051 ssh2_pkt_addstring(s->pktout, "env");
9052 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9053 ssh2_pkt_addstring(s->pktout, key);
9054 ssh2_pkt_addstring(s->pktout, val);
9055 ssh2_pkt_send(ssh, s->pktout);
9056
9057 s->num_env++;
9058 }
9059
9060 if (s->num_env) {
9061 logeventf(ssh, "Sent %d environment variables", s->num_env);
9062
9063 s->env_ok = 0;
9064 s->env_left = s->num_env;
9065
9066 while (s->env_left > 0) {
9067 crWaitUntilV(pktin);
9068
9069 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9070 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9071 bombout(("Unexpected response to environment request:"
9072 " packet type %d", pktin->type));
9073 crStopV;
9074 }
9075 } else {
9076 s->env_ok++;
9077 }
9078
9079 s->env_left--;
9080 }
9081
9082 if (s->env_ok == s->num_env) {
9083 logevent("All environment variables successfully set");
9084 } else if (s->env_ok == 0) {
9085 logevent("All environment variables refused");
9086 c_write_str(ssh, "Server refused to set environment variables\r\n");
9087 } else {
9088 logeventf(ssh, "%d environment variables refused",
9089 s->num_env - s->env_ok);
9090 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9091 }
9092 }
9093 }
9094
9095 /*
9096 * Start a shell or a remote command. We may have to attempt
9097 * this twice if the config data has provided a second choice
9098 * of command.
9099 */
9100 if (ssh->mainchan && !ssh->ncmode) while (1) {
9101 int subsys;
9102 char *cmd;
9103
9104 if (ssh->fallback_cmd) {
9105 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
9106 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
9107 } else {
9108 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
9109 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
9110 }
9111
9112 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9113 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
9114 if (subsys) {
9115 ssh2_pkt_addstring(s->pktout, "subsystem");
9116 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9117 ssh2_pkt_addstring(s->pktout, cmd);
9118 } else if (*cmd) {
9119 ssh2_pkt_addstring(s->pktout, "exec");
9120 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9121 ssh2_pkt_addstring(s->pktout, cmd);
9122 } else {
9123 ssh2_pkt_addstring(s->pktout, "shell");
9124 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9125 }
9126 ssh2_pkt_send(ssh, s->pktout);
9127
9128 crWaitUntilV(pktin);
9129
9130 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9131 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9132 bombout(("Unexpected response to shell/command request:"
9133 " packet type %d", pktin->type));
9134 crStopV;
9135 }
9136 /*
9137 * We failed to start the command. If this is the
9138 * fallback command, we really are finished; if it's
9139 * not, and if the fallback command exists, try falling
9140 * back to it before complaining.
9141 */
9142 if (!ssh->fallback_cmd &&
9143 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
9144 logevent("Primary command failed; attempting fallback");
9145 ssh->fallback_cmd = TRUE;
9146 continue;
9147 }
9148 bombout(("Server refused to start a shell/command"));
9149 crStopV;
9150 } else {
9151 logevent("Started a shell/command");
9152 }
9153 break;
9154 }
9155
9156 ssh->state = SSH_STATE_SESSION;
9157 if (ssh->size_needed)
9158 ssh_size(ssh, ssh->term_width, ssh->term_height);
9159 if (ssh->eof_needed)
9160 ssh_special(ssh, TS_EOF);
9161
9162 /*
9163 * All the initial channel requests are done, so install the default
9164 * failure handler.
9165 */
9166 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_success;
9167 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_failure;
9168
9169 /*
9170 * Transfer data!
9171 */
9172 if (ssh->ldisc)
9173 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
9174 if (ssh->mainchan)
9175 ssh->send_ok = 1;
9176 while (1) {
9177 crReturnV;
9178 s->try_send = FALSE;
9179 if (pktin) {
9180
9181 /*
9182 * _All_ the connection-layer packets we expect to
9183 * receive are now handled by the dispatch table.
9184 * Anything that reaches here must be bogus.
9185 */
9186
9187 bombout(("Strange packet received: type %d", pktin->type));
9188 crStopV;
9189 } else if (ssh->mainchan) {
9190 /*
9191 * We have spare data. Add it to the channel buffer.
9192 */
9193 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
9194 s->try_send = TRUE;
9195 }
9196 if (s->try_send) {
9197 int i;
9198 struct ssh_channel *c;
9199 /*
9200 * Try to send data on all channels if we can.
9201 */
9202 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
9203 ssh2_try_send_and_unthrottle(ssh, c);
9204 }
9205 }
9206
9207 crFinishV;
9208 }
9209
9210 /*
9211 * Handlers for SSH-2 messages that might arrive at any moment.
9212 */
9213 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
9214 {
9215 /* log reason code in disconnect message */
9216 char *buf, *msg;
9217 int reason, msglen;
9218
9219 reason = ssh_pkt_getuint32(pktin);
9220 ssh_pkt_getstring(pktin, &msg, &msglen);
9221
9222 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
9223 buf = dupprintf("Received disconnect message (%s)",
9224 ssh2_disconnect_reasons[reason]);
9225 } else {
9226 buf = dupprintf("Received disconnect message (unknown"
9227 " type %d)", reason);
9228 }
9229 logevent(buf);
9230 sfree(buf);
9231 buf = dupprintf("Disconnection message text: %.*s",
9232 msglen, msg);
9233 logevent(buf);
9234 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
9235 reason,
9236 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
9237 ssh2_disconnect_reasons[reason] : "unknown",
9238 msglen, msg));
9239 sfree(buf);
9240 }
9241
9242 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
9243 {
9244 /* log the debug message */
9245 char *msg;
9246 int msglen;
9247
9248 /* XXX maybe we should actually take notice of the return value */
9249 ssh2_pkt_getbool(pktin);
9250 ssh_pkt_getstring(pktin, &msg, &msglen);
9251
9252 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
9253 }
9254
9255 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
9256 {
9257 struct Packet *pktout;
9258 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
9259 ssh2_pkt_adduint32(pktout, pktin->sequence);
9260 /*
9261 * UNIMPLEMENTED messages MUST appear in the same order as the
9262 * messages they respond to. Hence, never queue them.
9263 */
9264 ssh2_pkt_send_noqueue(ssh, pktout);
9265 }
9266
9267 /*
9268 * Handle the top-level SSH-2 protocol.
9269 */
9270 static void ssh2_protocol_setup(Ssh ssh)
9271 {
9272 int i;
9273
9274 /*
9275 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9276 */
9277 for (i = 0; i < 256; i++)
9278 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
9279
9280 /*
9281 * Any message we actually understand, we set to NULL so that
9282 * the coroutines will get it.
9283 */
9284 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
9285 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
9286 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
9287 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
9288 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
9289 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
9290 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
9291 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
9292 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
9293 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
9294 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
9295 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
9296 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
9297 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
9298 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
9299 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
9300 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
9301 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
9302 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
9303 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
9304 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
9305 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
9306 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
9307 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
9308 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
9309 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
9310 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
9311 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
9312 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
9313 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
9314 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
9315 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
9316 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
9317
9318 /*
9319 * These special message types we install handlers for.
9320 */
9321 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
9322 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
9323 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9324 }
9325
9326 static void ssh2_timer(void *ctx, long now)
9327 {
9328 Ssh ssh = (Ssh)ctx;
9329
9330 if (ssh->state == SSH_STATE_CLOSED)
9331 return;
9332
9333 if (!ssh->kex_in_progress && conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
9334 now - ssh->next_rekey >= 0) {
9335 do_ssh2_transport(ssh, "timeout", -1, NULL);
9336 }
9337 }
9338
9339 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
9340 struct Packet *pktin)
9341 {
9342 unsigned char *in = (unsigned char *)vin;
9343 if (ssh->state == SSH_STATE_CLOSED)
9344 return;
9345
9346 if (pktin) {
9347 ssh->incoming_data_size += pktin->encrypted_len;
9348 if (!ssh->kex_in_progress &&
9349 ssh->max_data_size != 0 &&
9350 ssh->incoming_data_size > ssh->max_data_size)
9351 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9352 }
9353
9354 if (pktin && ssh->packet_dispatch[pktin->type]) {
9355 ssh->packet_dispatch[pktin->type](ssh, pktin);
9356 return;
9357 }
9358
9359 if (!ssh->protocol_initial_phase_done ||
9360 (pktin && pktin->type >= 20 && pktin->type < 50)) {
9361 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
9362 !ssh->protocol_initial_phase_done) {
9363 ssh->protocol_initial_phase_done = TRUE;
9364 /*
9365 * Allow authconn to initialise itself.
9366 */
9367 do_ssh2_authconn(ssh, NULL, 0, NULL);
9368 }
9369 } else {
9370 do_ssh2_authconn(ssh, in, inlen, pktin);
9371 }
9372 }
9373
9374 static void ssh_cache_conf_values(Ssh ssh)
9375 {
9376 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
9377 }
9378
9379 /*
9380 * Called to set up the connection.
9381 *
9382 * Returns an error message, or NULL on success.
9383 */
9384 static const char *ssh_init(void *frontend_handle, void **backend_handle,
9385 Conf *conf, char *host, int port, char **realhost,
9386 int nodelay, int keepalive)
9387 {
9388 const char *p;
9389 Ssh ssh;
9390
9391 ssh = snew(struct ssh_tag);
9392 ssh->conf = conf_copy(conf);
9393 ssh_cache_conf_values(ssh);
9394 ssh->version = 0; /* when not ready yet */
9395 ssh->s = NULL;
9396 ssh->cipher = NULL;
9397 ssh->v1_cipher_ctx = NULL;
9398 ssh->crcda_ctx = NULL;
9399 ssh->cscipher = NULL;
9400 ssh->cs_cipher_ctx = NULL;
9401 ssh->sccipher = NULL;
9402 ssh->sc_cipher_ctx = NULL;
9403 ssh->csmac = NULL;
9404 ssh->cs_mac_ctx = NULL;
9405 ssh->scmac = NULL;
9406 ssh->sc_mac_ctx = NULL;
9407 ssh->cscomp = NULL;
9408 ssh->cs_comp_ctx = NULL;
9409 ssh->sccomp = NULL;
9410 ssh->sc_comp_ctx = NULL;
9411 ssh->kex = NULL;
9412 ssh->kex_ctx = NULL;
9413 ssh->hostkey = NULL;
9414 ssh->exitcode = -1;
9415 ssh->close_expected = FALSE;
9416 ssh->clean_exit = FALSE;
9417 ssh->state = SSH_STATE_PREPACKET;
9418 ssh->size_needed = FALSE;
9419 ssh->eof_needed = FALSE;
9420 ssh->ldisc = NULL;
9421 ssh->logctx = NULL;
9422 ssh->deferred_send_data = NULL;
9423 ssh->deferred_len = 0;
9424 ssh->deferred_size = 0;
9425 ssh->fallback_cmd = 0;
9426 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9427 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9428 ssh->x11disp = NULL;
9429 ssh->v1_compressing = FALSE;
9430 ssh->v2_outgoing_sequence = 0;
9431 ssh->ssh1_rdpkt_crstate = 0;
9432 ssh->ssh2_rdpkt_crstate = 0;
9433 ssh->do_ssh_init_crstate = 0;
9434 ssh->ssh_gotdata_crstate = 0;
9435 ssh->do_ssh1_connection_crstate = 0;
9436 ssh->do_ssh1_login_crstate = 0;
9437 ssh->do_ssh2_transport_crstate = 0;
9438 ssh->do_ssh2_authconn_crstate = 0;
9439 ssh->do_ssh_init_state = NULL;
9440 ssh->do_ssh1_login_state = NULL;
9441 ssh->do_ssh2_transport_state = NULL;
9442 ssh->do_ssh2_authconn_state = NULL;
9443 ssh->v_c = NULL;
9444 ssh->v_s = NULL;
9445 ssh->mainchan = NULL;
9446 ssh->throttled_all = 0;
9447 ssh->v1_stdout_throttling = 0;
9448 ssh->queue = NULL;
9449 ssh->queuelen = ssh->queuesize = 0;
9450 ssh->queueing = FALSE;
9451 ssh->qhead = ssh->qtail = NULL;
9452 ssh->deferred_rekey_reason = NULL;
9453 bufchain_init(&ssh->queued_incoming_data);
9454 ssh->frozen = FALSE;
9455 ssh->username = NULL;
9456 ssh->sent_console_eof = FALSE;
9457 ssh->got_pty = FALSE;
9458
9459 *backend_handle = ssh;
9460
9461 #ifdef MSCRYPTOAPI
9462 if (crypto_startup() == 0)
9463 return "Microsoft high encryption pack not installed!";
9464 #endif
9465
9466 ssh->frontend = frontend_handle;
9467 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
9468 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
9469
9470 ssh->channels = NULL;
9471 ssh->rportfwds = NULL;
9472 ssh->portfwds = NULL;
9473
9474 ssh->send_ok = 0;
9475 ssh->editing = 0;
9476 ssh->echoing = 0;
9477 ssh->conn_throttle_count = 0;
9478 ssh->overall_bufsize = 0;
9479 ssh->fallback_cmd = 0;
9480
9481 ssh->protocol = NULL;
9482
9483 ssh->protocol_initial_phase_done = FALSE;
9484
9485 ssh->pinger = NULL;
9486
9487 ssh->incoming_data_size = ssh->outgoing_data_size =
9488 ssh->deferred_data_size = 0L;
9489 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9490 CONF_ssh_rekey_data));
9491 ssh->kex_in_progress = FALSE;
9492
9493 #ifndef NO_GSSAPI
9494 ssh->gsslibs = NULL;
9495 #endif
9496
9497 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9498 if (p != NULL)
9499 return p;
9500
9501 random_ref();
9502
9503 return NULL;
9504 }
9505
9506 static void ssh_free(void *handle)
9507 {
9508 Ssh ssh = (Ssh) handle;
9509 struct ssh_channel *c;
9510 struct ssh_rportfwd *pf;
9511
9512 if (ssh->v1_cipher_ctx)
9513 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9514 if (ssh->cs_cipher_ctx)
9515 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9516 if (ssh->sc_cipher_ctx)
9517 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9518 if (ssh->cs_mac_ctx)
9519 ssh->csmac->free_context(ssh->cs_mac_ctx);
9520 if (ssh->sc_mac_ctx)
9521 ssh->scmac->free_context(ssh->sc_mac_ctx);
9522 if (ssh->cs_comp_ctx) {
9523 if (ssh->cscomp)
9524 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9525 else
9526 zlib_compress_cleanup(ssh->cs_comp_ctx);
9527 }
9528 if (ssh->sc_comp_ctx) {
9529 if (ssh->sccomp)
9530 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9531 else
9532 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9533 }
9534 if (ssh->kex_ctx)
9535 dh_cleanup(ssh->kex_ctx);
9536 sfree(ssh->savedhost);
9537
9538 while (ssh->queuelen-- > 0)
9539 ssh_free_packet(ssh->queue[ssh->queuelen]);
9540 sfree(ssh->queue);
9541
9542 while (ssh->qhead) {
9543 struct queued_handler *qh = ssh->qhead;
9544 ssh->qhead = qh->next;
9545 sfree(ssh->qhead);
9546 }
9547 ssh->qhead = ssh->qtail = NULL;
9548
9549 if (ssh->channels) {
9550 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9551 switch (c->type) {
9552 case CHAN_X11:
9553 if (c->u.x11.s != NULL)
9554 x11_close(c->u.x11.s);
9555 break;
9556 case CHAN_SOCKDATA:
9557 case CHAN_SOCKDATA_DORMANT:
9558 if (c->u.pfd.s != NULL)
9559 pfd_close(c->u.pfd.s);
9560 break;
9561 }
9562 sfree(c);
9563 }
9564 freetree234(ssh->channels);
9565 ssh->channels = NULL;
9566 }
9567
9568 if (ssh->rportfwds) {
9569 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9570 free_rportfwd(pf);
9571 freetree234(ssh->rportfwds);
9572 ssh->rportfwds = NULL;
9573 }
9574 sfree(ssh->deferred_send_data);
9575 if (ssh->x11disp)
9576 x11_free_display(ssh->x11disp);
9577 sfree(ssh->do_ssh_init_state);
9578 sfree(ssh->do_ssh1_login_state);
9579 sfree(ssh->do_ssh2_transport_state);
9580 sfree(ssh->do_ssh2_authconn_state);
9581 sfree(ssh->v_c);
9582 sfree(ssh->v_s);
9583 sfree(ssh->fullhostname);
9584 if (ssh->crcda_ctx) {
9585 crcda_free_context(ssh->crcda_ctx);
9586 ssh->crcda_ctx = NULL;
9587 }
9588 if (ssh->s)
9589 ssh_do_close(ssh, TRUE);
9590 expire_timer_context(ssh);
9591 if (ssh->pinger)
9592 pinger_free(ssh->pinger);
9593 bufchain_clear(&ssh->queued_incoming_data);
9594 sfree(ssh->username);
9595 conf_free(ssh->conf);
9596 #ifndef NO_GSSAPI
9597 if (ssh->gsslibs)
9598 ssh_gss_cleanup(ssh->gsslibs);
9599 #endif
9600 sfree(ssh);
9601
9602 random_unref();
9603 }
9604
9605 /*
9606 * Reconfigure the SSH backend.
9607 */
9608 static void ssh_reconfig(void *handle, Conf *conf)
9609 {
9610 Ssh ssh = (Ssh) handle;
9611 char *rekeying = NULL, rekey_mandatory = FALSE;
9612 unsigned long old_max_data_size;
9613 int i, rekey_time;
9614
9615 pinger_reconfig(ssh->pinger, ssh->conf, conf);
9616 if (ssh->portfwds)
9617 ssh_setup_portfwd(ssh, conf);
9618
9619 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
9620 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
9621 rekey_time != 0) {
9622 long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
9623 long now = GETTICKCOUNT();
9624
9625 if (new_next - now < 0) {
9626 rekeying = "timeout shortened";
9627 } else {
9628 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
9629 }
9630 }
9631
9632 old_max_data_size = ssh->max_data_size;
9633 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9634 CONF_ssh_rekey_data));
9635 if (old_max_data_size != ssh->max_data_size &&
9636 ssh->max_data_size != 0) {
9637 if (ssh->outgoing_data_size > ssh->max_data_size ||
9638 ssh->incoming_data_size > ssh->max_data_size)
9639 rekeying = "data limit lowered";
9640 }
9641
9642 if (conf_get_int(ssh->conf, CONF_compression) !=
9643 conf_get_int(conf, CONF_compression)) {
9644 rekeying = "compression setting changed";
9645 rekey_mandatory = TRUE;
9646 }
9647
9648 for (i = 0; i < CIPHER_MAX; i++)
9649 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
9650 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
9651 rekeying = "cipher settings changed";
9652 rekey_mandatory = TRUE;
9653 }
9654 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
9655 conf_get_int(conf, CONF_ssh2_des_cbc)) {
9656 rekeying = "cipher settings changed";
9657 rekey_mandatory = TRUE;
9658 }
9659
9660 conf_free(ssh->conf);
9661 ssh->conf = conf_copy(conf);
9662 ssh_cache_conf_values(ssh);
9663
9664 if (rekeying) {
9665 if (!ssh->kex_in_progress) {
9666 do_ssh2_transport(ssh, rekeying, -1, NULL);
9667 } else if (rekey_mandatory) {
9668 ssh->deferred_rekey_reason = rekeying;
9669 }
9670 }
9671 }
9672
9673 /*
9674 * Called to send data down the SSH connection.
9675 */
9676 static int ssh_send(void *handle, char *buf, int len)
9677 {
9678 Ssh ssh = (Ssh) handle;
9679
9680 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9681 return 0;
9682
9683 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
9684
9685 return ssh_sendbuffer(ssh);
9686 }
9687
9688 /*
9689 * Called to query the current amount of buffered stdin data.
9690 */
9691 static int ssh_sendbuffer(void *handle)
9692 {
9693 Ssh ssh = (Ssh) handle;
9694 int override_value;
9695
9696 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9697 return 0;
9698
9699 /*
9700 * If the SSH socket itself has backed up, add the total backup
9701 * size on that to any individual buffer on the stdin channel.
9702 */
9703 override_value = 0;
9704 if (ssh->throttled_all)
9705 override_value = ssh->overall_bufsize;
9706
9707 if (ssh->version == 1) {
9708 return override_value;
9709 } else if (ssh->version == 2) {
9710 if (!ssh->mainchan)
9711 return override_value;
9712 else
9713 return (override_value +
9714 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
9715 }
9716
9717 return 0;
9718 }
9719
9720 /*
9721 * Called to set the size of the window from SSH's POV.
9722 */
9723 static void ssh_size(void *handle, int width, int height)
9724 {
9725 Ssh ssh = (Ssh) handle;
9726 struct Packet *pktout;
9727
9728 ssh->term_width = width;
9729 ssh->term_height = height;
9730
9731 switch (ssh->state) {
9732 case SSH_STATE_BEFORE_SIZE:
9733 case SSH_STATE_PREPACKET:
9734 case SSH_STATE_CLOSED:
9735 break; /* do nothing */
9736 case SSH_STATE_INTERMED:
9737 ssh->size_needed = TRUE; /* buffer for later */
9738 break;
9739 case SSH_STATE_SESSION:
9740 if (!conf_get_int(ssh->conf, CONF_nopty)) {
9741 if (ssh->version == 1) {
9742 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
9743 PKT_INT, ssh->term_height,
9744 PKT_INT, ssh->term_width,
9745 PKT_INT, 0, PKT_INT, 0, PKT_END);
9746 } else if (ssh->mainchan) {
9747 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9748 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9749 ssh2_pkt_addstring(pktout, "window-change");
9750 ssh2_pkt_addbool(pktout, 0);
9751 ssh2_pkt_adduint32(pktout, ssh->term_width);
9752 ssh2_pkt_adduint32(pktout, ssh->term_height);
9753 ssh2_pkt_adduint32(pktout, 0);
9754 ssh2_pkt_adduint32(pktout, 0);
9755 ssh2_pkt_send(ssh, pktout);
9756 }
9757 }
9758 break;
9759 }
9760 }
9761
9762 /*
9763 * Return a list of the special codes that make sense in this
9764 * protocol.
9765 */
9766 static const struct telnet_special *ssh_get_specials(void *handle)
9767 {
9768 static const struct telnet_special ssh1_ignore_special[] = {
9769 {"IGNORE message", TS_NOP}
9770 };
9771 static const struct telnet_special ssh2_ignore_special[] = {
9772 {"IGNORE message", TS_NOP},
9773 };
9774 static const struct telnet_special ssh2_rekey_special[] = {
9775 {"Repeat key exchange", TS_REKEY},
9776 };
9777 static const struct telnet_special ssh2_session_specials[] = {
9778 {NULL, TS_SEP},
9779 {"Break", TS_BRK},
9780 /* These are the signal names defined by RFC 4254.
9781 * They include all the ISO C signals, but are a subset of the POSIX
9782 * required signals. */
9783 {"SIGINT (Interrupt)", TS_SIGINT},
9784 {"SIGTERM (Terminate)", TS_SIGTERM},
9785 {"SIGKILL (Kill)", TS_SIGKILL},
9786 {"SIGQUIT (Quit)", TS_SIGQUIT},
9787 {"SIGHUP (Hangup)", TS_SIGHUP},
9788 {"More signals", TS_SUBMENU},
9789 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
9790 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
9791 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
9792 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
9793 {NULL, TS_EXITMENU}
9794 };
9795 static const struct telnet_special specials_end[] = {
9796 {NULL, TS_EXITMENU}
9797 };
9798 /* XXX review this length for any changes: */
9799 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
9800 lenof(ssh2_rekey_special) +
9801 lenof(ssh2_session_specials) +
9802 lenof(specials_end)];
9803 Ssh ssh = (Ssh) handle;
9804 int i = 0;
9805 #define ADD_SPECIALS(name) \
9806 do { \
9807 assert((i + lenof(name)) <= lenof(ssh_specials)); \
9808 memcpy(&ssh_specials[i], name, sizeof name); \
9809 i += lenof(name); \
9810 } while(0)
9811
9812 if (ssh->version == 1) {
9813 /* Don't bother offering IGNORE if we've decided the remote
9814 * won't cope with it, since we wouldn't bother sending it if
9815 * asked anyway. */
9816 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9817 ADD_SPECIALS(ssh1_ignore_special);
9818 } else if (ssh->version == 2) {
9819 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
9820 ADD_SPECIALS(ssh2_ignore_special);
9821 if (!(ssh->remote_bugs & BUG_SSH2_REKEY))
9822 ADD_SPECIALS(ssh2_rekey_special);
9823 if (ssh->mainchan)
9824 ADD_SPECIALS(ssh2_session_specials);
9825 } /* else we're not ready yet */
9826
9827 if (i) {
9828 ADD_SPECIALS(specials_end);
9829 return ssh_specials;
9830 } else {
9831 return NULL;
9832 }
9833 #undef ADD_SPECIALS
9834 }
9835
9836 /*
9837 * Send special codes. TS_EOF is useful for `plink', so you
9838 * can send an EOF and collect resulting output (e.g. `plink
9839 * hostname sort').
9840 */
9841 static void ssh_special(void *handle, Telnet_Special code)
9842 {
9843 Ssh ssh = (Ssh) handle;
9844 struct Packet *pktout;
9845
9846 if (code == TS_EOF) {
9847 if (ssh->state != SSH_STATE_SESSION) {
9848 /*
9849 * Buffer the EOF in case we are pre-SESSION, so we can
9850 * send it as soon as we reach SESSION.
9851 */
9852 if (code == TS_EOF)
9853 ssh->eof_needed = TRUE;
9854 return;
9855 }
9856 if (ssh->version == 1) {
9857 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
9858 } else if (ssh->mainchan) {
9859 sshfwd_write_eof(ssh->mainchan);
9860 ssh->send_ok = 0; /* now stop trying to read from stdin */
9861 }
9862 logevent("Sent EOF message");
9863 } else if (code == TS_PING || code == TS_NOP) {
9864 if (ssh->state == SSH_STATE_CLOSED
9865 || ssh->state == SSH_STATE_PREPACKET) return;
9866 if (ssh->version == 1) {
9867 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9868 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
9869 } else {
9870 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
9871 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
9872 ssh2_pkt_addstring_start(pktout);
9873 ssh2_pkt_send_noqueue(ssh, pktout);
9874 }
9875 }
9876 } else if (code == TS_REKEY) {
9877 if (!ssh->kex_in_progress && ssh->version == 2) {
9878 do_ssh2_transport(ssh, "at user request", -1, NULL);
9879 }
9880 } else if (code == TS_BRK) {
9881 if (ssh->state == SSH_STATE_CLOSED
9882 || ssh->state == SSH_STATE_PREPACKET) return;
9883 if (ssh->version == 1) {
9884 logevent("Unable to send BREAK signal in SSH-1");
9885 } else if (ssh->mainchan) {
9886 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9887 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9888 ssh2_pkt_addstring(pktout, "break");
9889 ssh2_pkt_addbool(pktout, 0);
9890 ssh2_pkt_adduint32(pktout, 0); /* default break length */
9891 ssh2_pkt_send(ssh, pktout);
9892 }
9893 } else {
9894 /* Is is a POSIX signal? */
9895 char *signame = NULL;
9896 if (code == TS_SIGABRT) signame = "ABRT";
9897 if (code == TS_SIGALRM) signame = "ALRM";
9898 if (code == TS_SIGFPE) signame = "FPE";
9899 if (code == TS_SIGHUP) signame = "HUP";
9900 if (code == TS_SIGILL) signame = "ILL";
9901 if (code == TS_SIGINT) signame = "INT";
9902 if (code == TS_SIGKILL) signame = "KILL";
9903 if (code == TS_SIGPIPE) signame = "PIPE";
9904 if (code == TS_SIGQUIT) signame = "QUIT";
9905 if (code == TS_SIGSEGV) signame = "SEGV";
9906 if (code == TS_SIGTERM) signame = "TERM";
9907 if (code == TS_SIGUSR1) signame = "USR1";
9908 if (code == TS_SIGUSR2) signame = "USR2";
9909 /* The SSH-2 protocol does in principle support arbitrary named
9910 * signals, including signame@domain, but we don't support those. */
9911 if (signame) {
9912 /* It's a signal. */
9913 if (ssh->version == 2 && ssh->mainchan) {
9914 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9915 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9916 ssh2_pkt_addstring(pktout, "signal");
9917 ssh2_pkt_addbool(pktout, 0);
9918 ssh2_pkt_addstring(pktout, signame);
9919 ssh2_pkt_send(ssh, pktout);
9920 logeventf(ssh, "Sent signal SIG%s", signame);
9921 }
9922 } else {
9923 /* Never heard of it. Do nothing */
9924 }
9925 }
9926 }
9927
9928 void *new_sock_channel(void *handle, Socket s)
9929 {
9930 Ssh ssh = (Ssh) handle;
9931 struct ssh_channel *c;
9932 c = snew(struct ssh_channel);
9933
9934 c->ssh = ssh;
9935 ssh2_channel_init(c);
9936 c->halfopen = TRUE;
9937 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
9938 c->u.pfd.s = s;
9939 add234(ssh->channels, c);
9940 return c;
9941 }
9942
9943 /*
9944 * This is called when stdout/stderr (the entity to which
9945 * from_backend sends data) manages to clear some backlog.
9946 */
9947 static void ssh_unthrottle(void *handle, int bufsize)
9948 {
9949 Ssh ssh = (Ssh) handle;
9950 int buflimit;
9951
9952 if (ssh->version == 1) {
9953 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
9954 ssh->v1_stdout_throttling = 0;
9955 ssh_throttle_conn(ssh, -1);
9956 }
9957 } else {
9958 if (ssh->mainchan) {
9959 ssh2_set_window(ssh->mainchan,
9960 bufsize < ssh->mainchan->v.v2.locmaxwin ?
9961 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
9962 if (conf_get_int(ssh->conf, CONF_ssh_simple))
9963 buflimit = 0;
9964 else
9965 buflimit = ssh->mainchan->v.v2.locmaxwin;
9966 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
9967 ssh->mainchan->throttling_conn = 0;
9968 ssh_throttle_conn(ssh, -1);
9969 }
9970 }
9971 }
9972 }
9973
9974 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
9975 {
9976 struct ssh_channel *c = (struct ssh_channel *)channel;
9977 Ssh ssh = c->ssh;
9978 struct Packet *pktout;
9979
9980 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
9981
9982 if (ssh->version == 1) {
9983 send_packet(ssh, SSH1_MSG_PORT_OPEN,
9984 PKT_INT, c->localid,
9985 PKT_STR, hostname,
9986 PKT_INT, port,
9987 /* PKT_STR, <org:orgport>, */
9988 PKT_END);
9989 } else {
9990 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
9991 ssh2_pkt_addstring(pktout, "direct-tcpip");
9992 ssh2_pkt_adduint32(pktout, c->localid);
9993 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
9994 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
9995 ssh2_pkt_addstring(pktout, hostname);
9996 ssh2_pkt_adduint32(pktout, port);
9997 /*
9998 * We make up values for the originator data; partly it's
9999 * too much hassle to keep track, and partly I'm not
10000 * convinced the server should be told details like that
10001 * about my local network configuration.
10002 * The "originator IP address" is syntactically a numeric
10003 * IP address, and some servers (e.g., Tectia) get upset
10004 * if it doesn't match this syntax.
10005 */
10006 ssh2_pkt_addstring(pktout, "0.0.0.0");
10007 ssh2_pkt_adduint32(pktout, 0);
10008 ssh2_pkt_send(ssh, pktout);
10009 }
10010 }
10011
10012 static int ssh_connected(void *handle)
10013 {
10014 Ssh ssh = (Ssh) handle;
10015 return ssh->s != NULL;
10016 }
10017
10018 static int ssh_sendok(void *handle)
10019 {
10020 Ssh ssh = (Ssh) handle;
10021 return ssh->send_ok;
10022 }
10023
10024 static int ssh_ldisc(void *handle, int option)
10025 {
10026 Ssh ssh = (Ssh) handle;
10027 if (option == LD_ECHO)
10028 return ssh->echoing;
10029 if (option == LD_EDIT)
10030 return ssh->editing;
10031 return FALSE;
10032 }
10033
10034 static void ssh_provide_ldisc(void *handle, void *ldisc)
10035 {
10036 Ssh ssh = (Ssh) handle;
10037 ssh->ldisc = ldisc;
10038 }
10039
10040 static void ssh_provide_logctx(void *handle, void *logctx)
10041 {
10042 Ssh ssh = (Ssh) handle;
10043 ssh->logctx = logctx;
10044 }
10045
10046 static int ssh_return_exitcode(void *handle)
10047 {
10048 Ssh ssh = (Ssh) handle;
10049 if (ssh->s != NULL)
10050 return -1;
10051 else
10052 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
10053 }
10054
10055 /*
10056 * cfg_info for SSH is the currently running version of the
10057 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
10058 */
10059 static int ssh_cfg_info(void *handle)
10060 {
10061 Ssh ssh = (Ssh) handle;
10062 return ssh->version;
10063 }
10064
10065 /*
10066 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
10067 * that fails. This variable is the means by which scp.c can reach
10068 * into the SSH code and find out which one it got.
10069 */
10070 extern int ssh_fallback_cmd(void *handle)
10071 {
10072 Ssh ssh = (Ssh) handle;
10073 return ssh->fallback_cmd;
10074 }
10075
10076 Backend ssh_backend = {
10077 ssh_init,
10078 ssh_free,
10079 ssh_reconfig,
10080 ssh_send,
10081 ssh_sendbuffer,
10082 ssh_size,
10083 ssh_special,
10084 ssh_get_specials,
10085 ssh_connected,
10086 ssh_return_exitcode,
10087 ssh_sendok,
10088 ssh_ldisc,
10089 ssh_provide_ldisc,
10090 ssh_provide_logctx,
10091 ssh_unthrottle,
10092 ssh_cfg_info,
10093 "ssh",
10094 PROT_SSH,
10095 22
10096 };