24 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
25 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
26 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
27 #define SSH1_CMSG_USER 4 /* 0x4 */
28 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
29 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
30 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
31 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
32 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
33 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
34 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
35 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
36 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
37 #define SSH1_SMSG_FAILURE 15 /* 0xf */
38 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
39 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
40 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
41 #define SSH1_CMSG_EOF 19 /* 0x13 */
42 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
43 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
44 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
45 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
46 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
47 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
48 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
49 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
50 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
51 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
52 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
53 #define SSH1_MSG_IGNORE 32 /* 0x20 */
54 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
55 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
56 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
57 #define SSH1_MSG_DEBUG 36 /* 0x24 */
58 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
59 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
60 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
61 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
62 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
63 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
64 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
66 #define SSH1_AUTH_RHOSTS 1 /* 0x1 */
67 #define SSH1_AUTH_RSA 2 /* 0x2 */
68 #define SSH1_AUTH_PASSWORD 3 /* 0x3 */
69 #define SSH1_AUTH_RHOSTS_RSA 4 /* 0x4 */
70 #define SSH1_AUTH_TIS 5 /* 0x5 */
71 #define SSH1_AUTH_CCARD 16 /* 0x10 */
73 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
74 /* Mask for protoflags we will echo back to server if seen */
75 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
77 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
78 #define SSH2_MSG_IGNORE 2 /* 0x2 */
79 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
80 #define SSH2_MSG_DEBUG 4 /* 0x4 */
81 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
82 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
83 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
84 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
85 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
86 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
87 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
88 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
89 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
90 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
91 #define SSH2_MSG_KEXRSA_PUBKEY 30 /* 0x1e */
92 #define SSH2_MSG_KEXRSA_SECRET 31 /* 0x1f */
93 #define SSH2_MSG_KEXRSA_DONE 32 /* 0x20 */
94 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
95 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
96 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
97 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
98 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
99 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
100 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
101 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
102 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
103 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
104 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
105 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
106 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
107 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
108 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
109 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
110 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
111 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
112 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
113 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
114 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
115 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
116 #define SSH2_MSG_USERAUTH_GSSAPI_RESPONSE 60
117 #define SSH2_MSG_USERAUTH_GSSAPI_TOKEN 61
118 #define SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE 63
119 #define SSH2_MSG_USERAUTH_GSSAPI_ERROR 64
120 #define SSH2_MSG_USERAUTH_GSSAPI_ERRTOK 65
121 #define SSH2_MSG_USERAUTH_GSSAPI_MIC 66
124 * Packet type contexts, so that ssh2_pkt_type can correctly decode
125 * the ambiguous type numbers back into the correct type strings.
135 SSH2_PKTCTX_PUBLICKEY
,
136 SSH2_PKTCTX_PASSWORD
,
141 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
142 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
143 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
144 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
145 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
146 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
147 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
148 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
149 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
150 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
151 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
152 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
153 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
154 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
155 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
157 static const char *const ssh2_disconnect_reasons
[] = {
159 "host not allowed to connect",
161 "key exchange failed",
162 "host authentication failed",
165 "service not available",
166 "protocol version not supported",
167 "host key not verifiable",
170 "too many connections",
171 "auth cancelled by user",
172 "no more auth methods available",
176 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
177 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
178 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
179 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
181 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
184 * Various remote-bug flags.
186 #define BUG_CHOKES_ON_SSH1_IGNORE 1
187 #define BUG_SSH2_HMAC 2
188 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
189 #define BUG_CHOKES_ON_RSA 8
190 #define BUG_SSH2_RSA_PADDING 16
191 #define BUG_SSH2_DERIVEKEY 32
192 #define BUG_SSH2_REKEY 64
193 #define BUG_SSH2_PK_SESSIONID 128
194 #define BUG_SSH2_MAXPKT 256
197 * Codes for terminal modes.
198 * Most of these are the same in SSH-1 and SSH-2.
199 * This list is derived from RFC 4254 and
202 static const struct {
203 const char* const mode
;
205 enum { TTY_OP_CHAR
, TTY_OP_BOOL
} type
;
207 /* "V" prefix discarded for special characters relative to SSH specs */
208 { "INTR", 1, TTY_OP_CHAR
},
209 { "QUIT", 2, TTY_OP_CHAR
},
210 { "ERASE", 3, TTY_OP_CHAR
},
211 { "KILL", 4, TTY_OP_CHAR
},
212 { "EOF", 5, TTY_OP_CHAR
},
213 { "EOL", 6, TTY_OP_CHAR
},
214 { "EOL2", 7, TTY_OP_CHAR
},
215 { "START", 8, TTY_OP_CHAR
},
216 { "STOP", 9, TTY_OP_CHAR
},
217 { "SUSP", 10, TTY_OP_CHAR
},
218 { "DSUSP", 11, TTY_OP_CHAR
},
219 { "REPRINT", 12, TTY_OP_CHAR
},
220 { "WERASE", 13, TTY_OP_CHAR
},
221 { "LNEXT", 14, TTY_OP_CHAR
},
222 { "FLUSH", 15, TTY_OP_CHAR
},
223 { "SWTCH", 16, TTY_OP_CHAR
},
224 { "STATUS", 17, TTY_OP_CHAR
},
225 { "DISCARD", 18, TTY_OP_CHAR
},
226 { "IGNPAR", 30, TTY_OP_BOOL
},
227 { "PARMRK", 31, TTY_OP_BOOL
},
228 { "INPCK", 32, TTY_OP_BOOL
},
229 { "ISTRIP", 33, TTY_OP_BOOL
},
230 { "INLCR", 34, TTY_OP_BOOL
},
231 { "IGNCR", 35, TTY_OP_BOOL
},
232 { "ICRNL", 36, TTY_OP_BOOL
},
233 { "IUCLC", 37, TTY_OP_BOOL
},
234 { "IXON", 38, TTY_OP_BOOL
},
235 { "IXANY", 39, TTY_OP_BOOL
},
236 { "IXOFF", 40, TTY_OP_BOOL
},
237 { "IMAXBEL", 41, TTY_OP_BOOL
},
238 { "ISIG", 50, TTY_OP_BOOL
},
239 { "ICANON", 51, TTY_OP_BOOL
},
240 { "XCASE", 52, TTY_OP_BOOL
},
241 { "ECHO", 53, TTY_OP_BOOL
},
242 { "ECHOE", 54, TTY_OP_BOOL
},
243 { "ECHOK", 55, TTY_OP_BOOL
},
244 { "ECHONL", 56, TTY_OP_BOOL
},
245 { "NOFLSH", 57, TTY_OP_BOOL
},
246 { "TOSTOP", 58, TTY_OP_BOOL
},
247 { "IEXTEN", 59, TTY_OP_BOOL
},
248 { "ECHOCTL", 60, TTY_OP_BOOL
},
249 { "ECHOKE", 61, TTY_OP_BOOL
},
250 { "PENDIN", 62, TTY_OP_BOOL
}, /* XXX is this a real mode? */
251 { "OPOST", 70, TTY_OP_BOOL
},
252 { "OLCUC", 71, TTY_OP_BOOL
},
253 { "ONLCR", 72, TTY_OP_BOOL
},
254 { "OCRNL", 73, TTY_OP_BOOL
},
255 { "ONOCR", 74, TTY_OP_BOOL
},
256 { "ONLRET", 75, TTY_OP_BOOL
},
257 { "CS7", 90, TTY_OP_BOOL
},
258 { "CS8", 91, TTY_OP_BOOL
},
259 { "PARENB", 92, TTY_OP_BOOL
},
260 { "PARODD", 93, TTY_OP_BOOL
}
263 /* Miscellaneous other tty-related constants. */
264 #define SSH_TTY_OP_END 0
265 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
266 #define SSH1_TTY_OP_ISPEED 192
267 #define SSH1_TTY_OP_OSPEED 193
268 #define SSH2_TTY_OP_ISPEED 128
269 #define SSH2_TTY_OP_OSPEED 129
271 /* Helper functions for parsing tty-related config. */
272 static unsigned int ssh_tty_parse_specchar(char *s
)
277 ret
= ctrlparse(s
, &next
);
278 if (!next
) ret
= s
[0];
280 ret
= 255; /* special value meaning "don't set" */
284 static unsigned int ssh_tty_parse_boolean(char *s
)
286 if (stricmp(s
, "yes") == 0 ||
287 stricmp(s
, "on") == 0 ||
288 stricmp(s
, "true") == 0 ||
289 stricmp(s
, "+") == 0)
291 else if (stricmp(s
, "no") == 0 ||
292 stricmp(s
, "off") == 0 ||
293 stricmp(s
, "false") == 0 ||
294 stricmp(s
, "-") == 0)
295 return 0; /* false */
297 return (atoi(s
) != 0);
300 #define translate(x) if (type == x) return #x
301 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
302 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
303 static char *ssh1_pkt_type(int type
)
305 translate(SSH1_MSG_DISCONNECT
);
306 translate(SSH1_SMSG_PUBLIC_KEY
);
307 translate(SSH1_CMSG_SESSION_KEY
);
308 translate(SSH1_CMSG_USER
);
309 translate(SSH1_CMSG_AUTH_RSA
);
310 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE
);
311 translate(SSH1_CMSG_AUTH_RSA_RESPONSE
);
312 translate(SSH1_CMSG_AUTH_PASSWORD
);
313 translate(SSH1_CMSG_REQUEST_PTY
);
314 translate(SSH1_CMSG_WINDOW_SIZE
);
315 translate(SSH1_CMSG_EXEC_SHELL
);
316 translate(SSH1_CMSG_EXEC_CMD
);
317 translate(SSH1_SMSG_SUCCESS
);
318 translate(SSH1_SMSG_FAILURE
);
319 translate(SSH1_CMSG_STDIN_DATA
);
320 translate(SSH1_SMSG_STDOUT_DATA
);
321 translate(SSH1_SMSG_STDERR_DATA
);
322 translate(SSH1_CMSG_EOF
);
323 translate(SSH1_SMSG_EXIT_STATUS
);
324 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
);
325 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE
);
326 translate(SSH1_MSG_CHANNEL_DATA
);
327 translate(SSH1_MSG_CHANNEL_CLOSE
);
328 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
);
329 translate(SSH1_SMSG_X11_OPEN
);
330 translate(SSH1_CMSG_PORT_FORWARD_REQUEST
);
331 translate(SSH1_MSG_PORT_OPEN
);
332 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING
);
333 translate(SSH1_SMSG_AGENT_OPEN
);
334 translate(SSH1_MSG_IGNORE
);
335 translate(SSH1_CMSG_EXIT_CONFIRMATION
);
336 translate(SSH1_CMSG_X11_REQUEST_FORWARDING
);
337 translate(SSH1_CMSG_AUTH_RHOSTS_RSA
);
338 translate(SSH1_MSG_DEBUG
);
339 translate(SSH1_CMSG_REQUEST_COMPRESSION
);
340 translate(SSH1_CMSG_AUTH_TIS
);
341 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE
);
342 translate(SSH1_CMSG_AUTH_TIS_RESPONSE
);
343 translate(SSH1_CMSG_AUTH_CCARD
);
344 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE
);
345 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE
);
348 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx
, Pkt_ACtx pkt_actx
, int type
)
350 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE
,SSH2_PKTCTX_GSSAPI
);
351 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN
,SSH2_PKTCTX_GSSAPI
);
352 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE
,SSH2_PKTCTX_GSSAPI
);
353 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR
,SSH2_PKTCTX_GSSAPI
);
354 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK
,SSH2_PKTCTX_GSSAPI
);
355 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC
, SSH2_PKTCTX_GSSAPI
);
356 translate(SSH2_MSG_DISCONNECT
);
357 translate(SSH2_MSG_IGNORE
);
358 translate(SSH2_MSG_UNIMPLEMENTED
);
359 translate(SSH2_MSG_DEBUG
);
360 translate(SSH2_MSG_SERVICE_REQUEST
);
361 translate(SSH2_MSG_SERVICE_ACCEPT
);
362 translate(SSH2_MSG_KEXINIT
);
363 translate(SSH2_MSG_NEWKEYS
);
364 translatek(SSH2_MSG_KEXDH_INIT
, SSH2_PKTCTX_DHGROUP
);
365 translatek(SSH2_MSG_KEXDH_REPLY
, SSH2_PKTCTX_DHGROUP
);
366 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST
, SSH2_PKTCTX_DHGEX
);
367 translatek(SSH2_MSG_KEX_DH_GEX_GROUP
, SSH2_PKTCTX_DHGEX
);
368 translatek(SSH2_MSG_KEX_DH_GEX_INIT
, SSH2_PKTCTX_DHGEX
);
369 translatek(SSH2_MSG_KEX_DH_GEX_REPLY
, SSH2_PKTCTX_DHGEX
);
370 translatek(SSH2_MSG_KEXRSA_PUBKEY
, SSH2_PKTCTX_RSAKEX
);
371 translatek(SSH2_MSG_KEXRSA_SECRET
, SSH2_PKTCTX_RSAKEX
);
372 translatek(SSH2_MSG_KEXRSA_DONE
, SSH2_PKTCTX_RSAKEX
);
373 translate(SSH2_MSG_USERAUTH_REQUEST
);
374 translate(SSH2_MSG_USERAUTH_FAILURE
);
375 translate(SSH2_MSG_USERAUTH_SUCCESS
);
376 translate(SSH2_MSG_USERAUTH_BANNER
);
377 translatea(SSH2_MSG_USERAUTH_PK_OK
, SSH2_PKTCTX_PUBLICKEY
);
378 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
, SSH2_PKTCTX_PASSWORD
);
379 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST
, SSH2_PKTCTX_KBDINTER
);
380 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE
, SSH2_PKTCTX_KBDINTER
);
381 translate(SSH2_MSG_GLOBAL_REQUEST
);
382 translate(SSH2_MSG_REQUEST_SUCCESS
);
383 translate(SSH2_MSG_REQUEST_FAILURE
);
384 translate(SSH2_MSG_CHANNEL_OPEN
);
385 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
386 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
387 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
388 translate(SSH2_MSG_CHANNEL_DATA
);
389 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA
);
390 translate(SSH2_MSG_CHANNEL_EOF
);
391 translate(SSH2_MSG_CHANNEL_CLOSE
);
392 translate(SSH2_MSG_CHANNEL_REQUEST
);
393 translate(SSH2_MSG_CHANNEL_SUCCESS
);
394 translate(SSH2_MSG_CHANNEL_FAILURE
);
400 /* Enumeration values for fields in SSH-1 packets */
402 PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
,
403 /* These values are for communicating relevant semantics of
404 * fields to the packet logging code. */
405 PKTT_OTHER
, PKTT_PASSWORD
, PKTT_DATA
409 * Coroutine mechanics for the sillier bits of the code. If these
410 * macros look impenetrable to you, you might find it helpful to
413 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
415 * which explains the theory behind these macros.
417 * In particular, if you are getting `case expression not constant'
418 * errors when building with MS Visual Studio, this is because MS's
419 * Edit and Continue debugging feature causes their compiler to
420 * violate ANSI C. To disable Edit and Continue debugging:
422 * - right-click ssh.c in the FileView
424 * - select the C/C++ tab and the General category
425 * - under `Debug info:', select anything _other_ than `Program
426 * Database for Edit and Continue'.
428 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
431 if (!ssh->t) ssh->t = snew(struct t); \
433 #define crFinish(z) } *crLine = 0; return (z); }
434 #define crFinishV } *crLine = 0; return; }
435 #define crReturn(z) \
437 *crLine =__LINE__; return (z); case __LINE__:;\
441 *crLine=__LINE__; return; case __LINE__:;\
443 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
444 #define crStopV do{ *crLine = 0; return; }while(0)
445 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
446 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
448 typedef struct ssh_tag
*Ssh
;
451 static struct Packet
*ssh1_pkt_init(int pkt_type
);
452 static struct Packet
*ssh2_pkt_init(int pkt_type
);
453 static void ssh_pkt_ensure(struct Packet
*, int length
);
454 static void ssh_pkt_adddata(struct Packet
*, void *data
, int len
);
455 static void ssh_pkt_addbyte(struct Packet
*, unsigned char value
);
456 static void ssh2_pkt_addbool(struct Packet
*, unsigned char value
);
457 static void ssh_pkt_adduint32(struct Packet
*, unsigned long value
);
458 static void ssh_pkt_addstring_start(struct Packet
*);
459 static void ssh_pkt_addstring_str(struct Packet
*, char *data
);
460 static void ssh_pkt_addstring_data(struct Packet
*, char *data
, int len
);
461 static void ssh_pkt_addstring(struct Packet
*, char *data
);
462 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
);
463 static void ssh1_pkt_addmp(struct Packet
*, Bignum b
);
464 static void ssh2_pkt_addmp(struct Packet
*, Bignum b
);
465 static int ssh2_pkt_construct(Ssh
, struct Packet
*);
466 static void ssh2_pkt_send(Ssh
, struct Packet
*);
467 static void ssh2_pkt_send_noqueue(Ssh
, struct Packet
*);
468 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
,
469 struct Packet
*pktin
);
470 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
,
471 struct Packet
*pktin
);
474 * Buffer management constants. There are several of these for
475 * various different purposes:
477 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
478 * on a local data stream before we throttle the whole SSH
479 * connection (in SSH-1 only). Throttling the whole connection is
480 * pretty drastic so we set this high in the hope it won't
483 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
484 * on the SSH connection itself before we defensively throttle
485 * _all_ local data streams. This is pretty drastic too (though
486 * thankfully unlikely in SSH-2 since the window mechanism should
487 * ensure that the server never has any need to throttle its end
488 * of the connection), so we set this high as well.
490 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
493 * - OUR_V2_BIGWIN is the window size we advertise for the only
494 * channel in a simple connection. It must be <= INT_MAX.
497 #define SSH1_BUFFER_LIMIT 32768
498 #define SSH_MAX_BACKLOG 32768
499 #define OUR_V2_WINSIZE 16384
500 #define OUR_V2_BIGWIN 0x7fffffff
501 #define OUR_V2_MAXPKT 0x4000UL
503 /* Maximum length of passwords/passphrases (arbitrary) */
504 #define SSH_MAX_PASSWORD_LEN 100
506 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
508 const static struct ssh_mac
*macs
[] = {
509 &ssh_hmac_sha1
, &ssh_hmac_sha1_96
, &ssh_hmac_md5
511 const static struct ssh_mac
*buggymacs
[] = {
512 &ssh_hmac_sha1_buggy
, &ssh_hmac_sha1_96_buggy
, &ssh_hmac_md5
515 static void *ssh_comp_none_init(void)
519 static void ssh_comp_none_cleanup(void *handle
)
522 static int ssh_comp_none_block(void *handle
, unsigned char *block
, int len
,
523 unsigned char **outblock
, int *outlen
)
527 static int ssh_comp_none_disable(void *handle
)
531 const static struct ssh_compress ssh_comp_none
= {
533 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
534 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
535 ssh_comp_none_disable
, NULL
537 extern const struct ssh_compress ssh_zlib
;
538 const static struct ssh_compress
*compressions
[] = {
539 &ssh_zlib
, &ssh_comp_none
542 enum { /* channel types */
547 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
551 * little structure to keep track of outstanding WINDOW_ADJUSTs
559 * 2-3-4 tree storing channels.
562 Ssh ssh
; /* pointer back to main context */
563 unsigned remoteid
, localid
;
565 /* True if we opened this channel but server hasn't confirmed. */
568 * In SSH-1, this value contains four bits:
570 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
571 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
572 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
573 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
575 * A channel is completely finished with when all four bits are set.
579 * True if this channel is causing the underlying connection to be
584 struct ssh2_data_channel
{
586 unsigned remwindow
, remmaxpkt
;
587 /* locwindow is signed so we can cope with excess data. */
588 int locwindow
, locmaxwin
;
590 * remlocwin is the amount of local window that we think
591 * the remote end had available to it after it sent the
592 * last data packet or window adjust ack.
596 * These store the list of window adjusts that haven't
599 struct winadj
*winadj_head
, *winadj_tail
;
600 enum { THROTTLED
, UNTHROTTLING
, UNTHROTTLED
} throttle_state
;
604 struct ssh_agent_channel
{
605 unsigned char *message
;
606 unsigned char msglen
[4];
607 unsigned lensofar
, totallen
;
609 struct ssh_x11_channel
{
612 struct ssh_pfd_channel
{
619 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
620 * use this structure in different ways, reflecting SSH-2's
621 * altogether saner approach to port forwarding.
623 * In SSH-1, you arrange a remote forwarding by sending the server
624 * the remote port number, and the local destination host:port.
625 * When a connection comes in, the server sends you back that
626 * host:port pair, and you connect to it. This is a ready-made
627 * security hole if you're not on the ball: a malicious server
628 * could send you back _any_ host:port pair, so if you trustingly
629 * connect to the address it gives you then you've just opened the
630 * entire inside of your corporate network just by connecting
631 * through it to a dodgy SSH server. Hence, we must store a list of
632 * host:port pairs we _are_ trying to forward to, and reject a
633 * connection request from the server if it's not in the list.
635 * In SSH-2, each side of the connection minds its own business and
636 * doesn't send unnecessary information to the other. You arrange a
637 * remote forwarding by sending the server just the remote port
638 * number. When a connection comes in, the server tells you which
639 * of its ports was connected to; and _you_ have to remember what
640 * local host:port pair went with that port number.
642 * Hence, in SSH-1 this structure is indexed by destination
643 * host:port pair, whereas in SSH-2 it is indexed by source port.
645 struct ssh_portfwd
; /* forward declaration */
647 struct ssh_rportfwd
{
648 unsigned sport
, dport
;
651 struct ssh_portfwd
*pfrec
;
653 #define free_rportfwd(pf) ( \
654 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
657 * Separately to the rportfwd tree (which is for looking up port
658 * open requests from the server), a tree of _these_ structures is
659 * used to keep track of all the currently open port forwardings,
660 * so that we can reconfigure in mid-session if the user requests
664 enum { DESTROY
, KEEP
, CREATE
} status
;
666 unsigned sport
, dport
;
669 struct ssh_rportfwd
*remote
;
673 #define free_portfwd(pf) ( \
674 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
675 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
678 long length
; /* length of `data' actually used */
679 long forcepad
; /* SSH-2: force padding to at least this length */
680 int type
; /* only used for incoming packets */
681 unsigned long sequence
; /* SSH-2 incoming sequence number */
682 unsigned char *data
; /* allocated storage */
683 unsigned char *body
; /* offset of payload within `data' */
684 long savedpos
; /* temporary index into `data' (for strings) */
685 long maxlen
; /* amount of storage allocated for `data' */
686 long encrypted_len
; /* for SSH-2 total-size counting */
689 * State associated with packet logging
693 struct logblank_t
*blanks
;
696 static void ssh1_protocol(Ssh ssh
, void *vin
, int inlen
,
697 struct Packet
*pktin
);
698 static void ssh2_protocol(Ssh ssh
, void *vin
, int inlen
,
699 struct Packet
*pktin
);
700 static void ssh1_protocol_setup(Ssh ssh
);
701 static void ssh2_protocol_setup(Ssh ssh
);
702 static void ssh_size(void *handle
, int width
, int height
);
703 static void ssh_special(void *handle
, Telnet_Special
);
704 static int ssh2_try_send(struct ssh_channel
*c
);
705 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
);
706 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
);
707 static void ssh2_set_window(struct ssh_channel
*c
, int newwin
);
708 static int ssh_sendbuffer(void *handle
);
709 static int ssh_do_close(Ssh ssh
, int notify_exit
);
710 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
);
711 static int ssh2_pkt_getbool(struct Packet
*pkt
);
712 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
);
713 static void ssh2_timer(void *ctx
, long now
);
714 static int do_ssh2_transport(Ssh ssh
, void *vin
, int inlen
,
715 struct Packet
*pktin
);
717 struct rdpkt1_state_tag
{
718 long len
, pad
, biglen
, to_read
;
719 unsigned long realcrc
, gotcrc
;
723 struct Packet
*pktin
;
726 struct rdpkt2_state_tag
{
727 long len
, pad
, payload
, packetlen
, maclen
;
730 unsigned long incoming_sequence
;
731 struct Packet
*pktin
;
734 typedef void (*handler_fn_t
)(Ssh ssh
, struct Packet
*pktin
);
735 typedef void (*chandler_fn_t
)(Ssh ssh
, struct Packet
*pktin
, void *ctx
);
737 struct queued_handler
;
738 struct queued_handler
{
740 chandler_fn_t handler
;
742 struct queued_handler
*next
;
746 const struct plug_function_table
*fn
;
747 /* the above field _must_ be first in the structure */
757 unsigned char session_key
[32];
759 int v1_remote_protoflags
;
760 int v1_local_protoflags
;
761 int agentfwd_enabled
;
764 const struct ssh_cipher
*cipher
;
767 const struct ssh2_cipher
*cscipher
, *sccipher
;
768 void *cs_cipher_ctx
, *sc_cipher_ctx
;
769 const struct ssh_mac
*csmac
, *scmac
;
770 void *cs_mac_ctx
, *sc_mac_ctx
;
771 const struct ssh_compress
*cscomp
, *sccomp
;
772 void *cs_comp_ctx
, *sc_comp_ctx
;
773 const struct ssh_kex
*kex
;
774 const struct ssh_signkey
*hostkey
;
775 unsigned char v2_session_id
[SSH2_KEX_MAX_HASH_LEN
];
776 int v2_session_id_len
;
782 int echoing
, editing
;
786 int ospeed
, ispeed
; /* temporaries */
787 int term_width
, term_height
;
789 tree234
*channels
; /* indexed by local id */
790 struct ssh_channel
*mainchan
; /* primary session channel */
791 int ncmode
; /* is primary channel direct-tcpip? */
796 tree234
*rportfwds
, *portfwds
;
800 SSH_STATE_BEFORE_SIZE
,
806 int size_needed
, eof_needed
;
808 struct Packet
**queue
;
809 int queuelen
, queuesize
;
811 unsigned char *deferred_send_data
;
812 int deferred_len
, deferred_size
;
815 * Gross hack: pscp will try to start SFTP but fall back to
816 * scp1 if that fails. This variable is the means by which
817 * scp.c can reach into the SSH code and find out which one it
822 bufchain banner
; /* accumulates banners during do_ssh2_authconn */
830 int conn_throttle_count
;
833 int v1_stdout_throttling
;
834 unsigned long v2_outgoing_sequence
;
836 int ssh1_rdpkt_crstate
;
837 int ssh2_rdpkt_crstate
;
838 int do_ssh_init_crstate
;
839 int ssh_gotdata_crstate
;
840 int do_ssh1_login_crstate
;
841 int do_ssh1_connection_crstate
;
842 int do_ssh2_transport_crstate
;
843 int do_ssh2_authconn_crstate
;
845 void *do_ssh_init_state
;
846 void *do_ssh1_login_state
;
847 void *do_ssh2_transport_state
;
848 void *do_ssh2_authconn_state
;
850 struct rdpkt1_state_tag rdpkt1_state
;
851 struct rdpkt2_state_tag rdpkt2_state
;
853 /* SSH-1 and SSH-2 use this for different things, but both use it */
854 int protocol_initial_phase_done
;
856 void (*protocol
) (Ssh ssh
, void *vin
, int inlen
,
858 struct Packet
*(*s_rdpkt
) (Ssh ssh
, unsigned char **data
, int *datalen
);
861 * We maintain a full _copy_ of a Config structure here, not
862 * merely a pointer to it. That way, when we're passed a new
863 * one for reconfiguration, we can check the differences and
864 * potentially reconfigure port forwardings etc in mid-session.
869 * Used to transfer data back from async callbacks.
871 void *agent_response
;
872 int agent_response_len
;
876 * The SSH connection can be set as `frozen', meaning we are
877 * not currently accepting incoming data from the network. This
878 * is slightly more serious than setting the _socket_ as
879 * frozen, because we may already have had data passed to us
880 * from the network which we need to delay processing until
881 * after the freeze is lifted, so we also need a bufchain to
885 bufchain queued_incoming_data
;
888 * Dispatch table for packet types that we may have to deal
891 handler_fn_t packet_dispatch
[256];
894 * Queues of one-off handler functions for success/failure
895 * indications from a request.
897 struct queued_handler
*qhead
, *qtail
;
900 * This module deals with sending keepalives.
905 * Track incoming and outgoing data sizes and time, for
908 unsigned long incoming_data_size
, outgoing_data_size
, deferred_data_size
;
909 unsigned long max_data_size
;
911 long next_rekey
, last_rekey
;
912 char *deferred_rekey_reason
; /* points to STATIC string; don't free */
915 * Fully qualified host name, which we need if doing GSSAPI.
920 #define logevent(s) logevent(ssh->frontend, s)
922 /* logevent, only printf-formatted. */
923 static void logeventf(Ssh ssh
, const char *fmt
, ...)
929 buf
= dupvprintf(fmt
, ap
);
935 #define bombout(msg) \
937 char *text = dupprintf msg; \
938 ssh_do_close(ssh, FALSE); \
940 connection_fatal(ssh->frontend, "%s", text); \
944 /* Functions to leave bits out of the SSH packet log file. */
946 static void dont_log_password(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
948 if (ssh
->cfg
.logomitpass
)
949 pkt
->logmode
= blanktype
;
952 static void dont_log_data(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
954 if (ssh
->cfg
.logomitdata
)
955 pkt
->logmode
= blanktype
;
958 static void end_log_omission(Ssh ssh
, struct Packet
*pkt
)
960 pkt
->logmode
= PKTLOG_EMIT
;
963 /* Helper function for common bits of parsing cfg.ttymodes. */
964 static void parse_ttymodes(Ssh ssh
, char *modes
,
965 void (*do_mode
)(void *data
, char *mode
, char *val
),
969 char *t
= strchr(modes
, '\t');
970 char *m
= snewn(t
-modes
+1, char);
972 strncpy(m
, modes
, t
-modes
);
975 val
= get_ttymode(ssh
->frontend
, m
);
979 do_mode(data
, m
, val
);
982 modes
+= strlen(modes
) + 1;
986 static int ssh_channelcmp(void *av
, void *bv
)
988 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
989 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
990 if (a
->localid
< b
->localid
)
992 if (a
->localid
> b
->localid
)
996 static int ssh_channelfind(void *av
, void *bv
)
998 unsigned *a
= (unsigned *) av
;
999 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
1000 if (*a
< b
->localid
)
1002 if (*a
> b
->localid
)
1007 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
1009 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
1010 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
1012 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
1013 return i
< 0 ?
-1 : +1;
1014 if (a
->dport
> b
->dport
)
1016 if (a
->dport
< b
->dport
)
1021 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
1023 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
1024 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
1026 if (a
->sport
> b
->sport
)
1028 if (a
->sport
< b
->sport
)
1034 * Special form of strcmp which can cope with NULL inputs. NULL is
1035 * defined to sort before even the empty string.
1037 static int nullstrcmp(const char *a
, const char *b
)
1039 if (a
== NULL
&& b
== NULL
)
1045 return strcmp(a
, b
);
1048 static int ssh_portcmp(void *av
, void *bv
)
1050 struct ssh_portfwd
*a
= (struct ssh_portfwd
*) av
;
1051 struct ssh_portfwd
*b
= (struct ssh_portfwd
*) bv
;
1053 if (a
->type
> b
->type
)
1055 if (a
->type
< b
->type
)
1057 if (a
->addressfamily
> b
->addressfamily
)
1059 if (a
->addressfamily
< b
->addressfamily
)
1061 if ( (i
= nullstrcmp(a
->saddr
, b
->saddr
)) != 0)
1062 return i
< 0 ?
-1 : +1;
1063 if (a
->sport
> b
->sport
)
1065 if (a
->sport
< b
->sport
)
1067 if (a
->type
!= 'D') {
1068 if ( (i
= nullstrcmp(a
->daddr
, b
->daddr
)) != 0)
1069 return i
< 0 ?
-1 : +1;
1070 if (a
->dport
> b
->dport
)
1072 if (a
->dport
< b
->dport
)
1078 static int alloc_channel_id(Ssh ssh
)
1080 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
1081 unsigned low
, high
, mid
;
1083 struct ssh_channel
*c
;
1086 * First-fit allocation of channel numbers: always pick the
1087 * lowest unused one. To do this, binary-search using the
1088 * counted B-tree to find the largest channel ID which is in a
1089 * contiguous sequence from the beginning. (Precisely
1090 * everything in that sequence must have ID equal to its tree
1091 * index plus CHANNEL_NUMBER_OFFSET.)
1093 tsize
= count234(ssh
->channels
);
1097 while (high
- low
> 1) {
1098 mid
= (high
+ low
) / 2;
1099 c
= index234(ssh
->channels
, mid
);
1100 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
1101 low
= mid
; /* this one is fine */
1103 high
= mid
; /* this one is past it */
1106 * Now low points to either -1, or the tree index of the
1107 * largest ID in the initial sequence.
1110 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
1111 assert(NULL
== find234(ssh
->channels
, &i
, ssh_channelfind
));
1113 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
1116 static void c_write_stderr(int trusted
, const char *buf
, int len
)
1119 for (i
= 0; i
< len
; i
++)
1120 if (buf
[i
] != '\r' && (trusted
|| buf
[i
] == '\n' || (buf
[i
] & 0x60)))
1121 fputc(buf
[i
], stderr
);
1124 static void c_write(Ssh ssh
, const char *buf
, int len
)
1126 if (flags
& FLAG_STDERR
)
1127 c_write_stderr(1, buf
, len
);
1129 from_backend(ssh
->frontend
, 1, buf
, len
);
1132 static void c_write_untrusted(Ssh ssh
, const char *buf
, int len
)
1134 if (flags
& FLAG_STDERR
)
1135 c_write_stderr(0, buf
, len
);
1137 from_backend_untrusted(ssh
->frontend
, buf
, len
);
1140 static void c_write_str(Ssh ssh
, const char *buf
)
1142 c_write(ssh
, buf
, strlen(buf
));
1145 static void ssh_free_packet(struct Packet
*pkt
)
1150 static struct Packet
*ssh_new_packet(void)
1152 struct Packet
*pkt
= snew(struct Packet
);
1154 pkt
->body
= pkt
->data
= NULL
;
1156 pkt
->logmode
= PKTLOG_EMIT
;
1164 * Collect incoming data in the incoming packet buffer.
1165 * Decipher and verify the packet when it is completely read.
1166 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1167 * Update the *data and *datalen variables.
1168 * Return a Packet structure when a packet is completed.
1170 static struct Packet
*ssh1_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
1172 struct rdpkt1_state_tag
*st
= &ssh
->rdpkt1_state
;
1174 crBegin(ssh
->ssh1_rdpkt_crstate
);
1176 st
->pktin
= ssh_new_packet();
1178 st
->pktin
->type
= 0;
1179 st
->pktin
->length
= 0;
1181 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
1182 while ((*datalen
) == 0)
1184 st
->len
= (st
->len
<< 8) + **data
;
1185 (*data
)++, (*datalen
)--;
1188 st
->pad
= 8 - (st
->len
% 8);
1189 st
->biglen
= st
->len
+ st
->pad
;
1190 st
->pktin
->length
= st
->len
- 5;
1192 if (st
->biglen
< 0) {
1193 bombout(("Extremely large packet length from server suggests"
1194 " data stream corruption"));
1195 ssh_free_packet(st
->pktin
);
1199 st
->pktin
->maxlen
= st
->biglen
;
1200 st
->pktin
->data
= snewn(st
->biglen
+ APIEXTRA
, unsigned char);
1202 st
->to_read
= st
->biglen
;
1203 st
->p
= st
->pktin
->data
;
1204 while (st
->to_read
> 0) {
1205 st
->chunk
= st
->to_read
;
1206 while ((*datalen
) == 0)
1208 if (st
->chunk
> (*datalen
))
1209 st
->chunk
= (*datalen
);
1210 memcpy(st
->p
, *data
, st
->chunk
);
1212 *datalen
-= st
->chunk
;
1214 st
->to_read
-= st
->chunk
;
1217 if (ssh
->cipher
&& detect_attack(ssh
->crcda_ctx
, st
->pktin
->data
,
1218 st
->biglen
, NULL
)) {
1219 bombout(("Network attack (CRC compensation) detected!"));
1220 ssh_free_packet(st
->pktin
);
1225 ssh
->cipher
->decrypt(ssh
->v1_cipher_ctx
, st
->pktin
->data
, st
->biglen
);
1227 st
->realcrc
= crc32_compute(st
->pktin
->data
, st
->biglen
- 4);
1228 st
->gotcrc
= GET_32BIT(st
->pktin
->data
+ st
->biglen
- 4);
1229 if (st
->gotcrc
!= st
->realcrc
) {
1230 bombout(("Incorrect CRC received on packet"));
1231 ssh_free_packet(st
->pktin
);
1235 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
1236 st
->pktin
->savedpos
= 0;
1238 if (ssh
->v1_compressing
) {
1239 unsigned char *decompblk
;
1241 if (!zlib_decompress_block(ssh
->sc_comp_ctx
,
1242 st
->pktin
->body
- 1, st
->pktin
->length
+ 1,
1243 &decompblk
, &decomplen
)) {
1244 bombout(("Zlib decompression encountered invalid data"));
1245 ssh_free_packet(st
->pktin
);
1249 if (st
->pktin
->maxlen
< st
->pad
+ decomplen
) {
1250 st
->pktin
->maxlen
= st
->pad
+ decomplen
;
1251 st
->pktin
->data
= sresize(st
->pktin
->data
,
1252 st
->pktin
->maxlen
+ APIEXTRA
,
1254 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
1257 memcpy(st
->pktin
->body
- 1, decompblk
, decomplen
);
1259 st
->pktin
->length
= decomplen
- 1;
1262 st
->pktin
->type
= st
->pktin
->body
[-1];
1265 * Log incoming packet, possibly omitting sensitive fields.
1269 struct logblank_t blank
;
1270 if (ssh
->cfg
.logomitdata
) {
1271 int do_blank
= FALSE
, blank_prefix
= 0;
1272 /* "Session data" packets - omit the data field */
1273 if ((st
->pktin
->type
== SSH1_SMSG_STDOUT_DATA
) ||
1274 (st
->pktin
->type
== SSH1_SMSG_STDERR_DATA
)) {
1275 do_blank
= TRUE
; blank_prefix
= 4;
1276 } else if (st
->pktin
->type
== SSH1_MSG_CHANNEL_DATA
) {
1277 do_blank
= TRUE
; blank_prefix
= 8;
1280 blank
.offset
= blank_prefix
;
1281 blank
.len
= st
->pktin
->length
;
1282 blank
.type
= PKTLOG_OMIT
;
1286 log_packet(ssh
->logctx
,
1287 PKT_INCOMING
, st
->pktin
->type
,
1288 ssh1_pkt_type(st
->pktin
->type
),
1289 st
->pktin
->body
, st
->pktin
->length
,
1293 crFinish(st
->pktin
);
1296 static struct Packet
*ssh2_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
1298 struct rdpkt2_state_tag
*st
= &ssh
->rdpkt2_state
;
1300 crBegin(ssh
->ssh2_rdpkt_crstate
);
1302 st
->pktin
= ssh_new_packet();
1304 st
->pktin
->type
= 0;
1305 st
->pktin
->length
= 0;
1307 st
->cipherblk
= ssh
->sccipher
->blksize
;
1310 if (st
->cipherblk
< 8)
1313 st
->pktin
->data
= snewn(st
->cipherblk
+ APIEXTRA
, unsigned char);
1316 * Acquire and decrypt the first block of the packet. This will
1317 * contain the length and padding details.
1319 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
1320 while ((*datalen
) == 0)
1322 st
->pktin
->data
[st
->i
] = *(*data
)++;
1327 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1328 st
->pktin
->data
, st
->cipherblk
);
1331 * Now get the length and padding figures.
1333 st
->len
= GET_32BIT(st
->pktin
->data
);
1334 st
->pad
= st
->pktin
->data
[4];
1337 * _Completely_ silly lengths should be stomped on before they
1338 * do us any more damage.
1340 if (st
->len
< 0 || st
->len
> 35000 || st
->pad
< 4 ||
1341 st
->len
- st
->pad
< 1 || (st
->len
+ 4) % st
->cipherblk
!= 0) {
1342 bombout(("Incoming packet was garbled on decryption"));
1343 ssh_free_packet(st
->pktin
);
1348 * This enables us to deduce the payload length.
1350 st
->payload
= st
->len
- st
->pad
- 1;
1352 st
->pktin
->length
= st
->payload
+ 5;
1355 * So now we can work out the total packet length.
1357 st
->packetlen
= st
->len
+ 4;
1358 st
->maclen
= ssh
->scmac ? ssh
->scmac
->len
: 0;
1361 * Allocate memory for the rest of the packet.
1363 st
->pktin
->maxlen
= st
->packetlen
+ st
->maclen
;
1364 st
->pktin
->data
= sresize(st
->pktin
->data
,
1365 st
->pktin
->maxlen
+ APIEXTRA
,
1369 * Read and decrypt the remainder of the packet.
1371 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
1373 while ((*datalen
) == 0)
1375 st
->pktin
->data
[st
->i
] = *(*data
)++;
1378 /* Decrypt everything _except_ the MAC. */
1380 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1381 st
->pktin
->data
+ st
->cipherblk
,
1382 st
->packetlen
- st
->cipherblk
);
1384 st
->pktin
->encrypted_len
= st
->packetlen
;
1390 && !ssh
->scmac
->verify(ssh
->sc_mac_ctx
, st
->pktin
->data
, st
->len
+ 4,
1391 st
->incoming_sequence
)) {
1392 bombout(("Incorrect MAC received on packet"));
1393 ssh_free_packet(st
->pktin
);
1397 st
->pktin
->sequence
= st
->incoming_sequence
++;
1400 * Decompress packet payload.
1403 unsigned char *newpayload
;
1406 ssh
->sccomp
->decompress(ssh
->sc_comp_ctx
,
1407 st
->pktin
->data
+ 5, st
->pktin
->length
- 5,
1408 &newpayload
, &newlen
)) {
1409 if (st
->pktin
->maxlen
< newlen
+ 5) {
1410 st
->pktin
->maxlen
= newlen
+ 5;
1411 st
->pktin
->data
= sresize(st
->pktin
->data
,
1412 st
->pktin
->maxlen
+ APIEXTRA
,
1415 st
->pktin
->length
= 5 + newlen
;
1416 memcpy(st
->pktin
->data
+ 5, newpayload
, newlen
);
1421 st
->pktin
->savedpos
= 6;
1422 st
->pktin
->body
= st
->pktin
->data
;
1423 st
->pktin
->type
= st
->pktin
->data
[5];
1426 * Log incoming packet, possibly omitting sensitive fields.
1430 struct logblank_t blank
;
1431 if (ssh
->cfg
.logomitdata
) {
1432 int do_blank
= FALSE
, blank_prefix
= 0;
1433 /* "Session data" packets - omit the data field */
1434 if (st
->pktin
->type
== SSH2_MSG_CHANNEL_DATA
) {
1435 do_blank
= TRUE
; blank_prefix
= 8;
1436 } else if (st
->pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
1437 do_blank
= TRUE
; blank_prefix
= 12;
1440 blank
.offset
= blank_prefix
;
1441 blank
.len
= (st
->pktin
->length
-6) - blank_prefix
;
1442 blank
.type
= PKTLOG_OMIT
;
1446 log_packet(ssh
->logctx
, PKT_INCOMING
, st
->pktin
->type
,
1447 ssh2_pkt_type(ssh
->pkt_kctx
, ssh
->pkt_actx
,
1449 st
->pktin
->data
+6, st
->pktin
->length
-6,
1453 crFinish(st
->pktin
);
1456 static int s_wrpkt_prepare(Ssh ssh
, struct Packet
*pkt
, int *offset_p
)
1458 int pad
, biglen
, i
, pktoffs
;
1462 * XXX various versions of SC (including 8.8.4) screw up the
1463 * register allocation in this function and use the same register
1464 * (D6) for len and as a temporary, with predictable results. The
1465 * following sledgehammer prevents this.
1472 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->data
[12],
1473 ssh1_pkt_type(pkt
->data
[12]),
1474 pkt
->body
, pkt
->length
- (pkt
->body
- pkt
->data
),
1475 pkt
->nblanks
, pkt
->blanks
);
1476 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1479 if (ssh
->v1_compressing
) {
1480 unsigned char *compblk
;
1482 zlib_compress_block(ssh
->cs_comp_ctx
,
1483 pkt
->data
+ 12, pkt
->length
- 12,
1484 &compblk
, &complen
);
1485 ssh_pkt_ensure(pkt
, complen
+ 2); /* just in case it's got bigger */
1486 memcpy(pkt
->data
+ 12, compblk
, complen
);
1488 pkt
->length
= complen
+ 12;
1491 ssh_pkt_ensure(pkt
, pkt
->length
+ 4); /* space for CRC */
1493 len
= pkt
->length
- 4 - 8; /* len(type+data+CRC) */
1494 pad
= 8 - (len
% 8);
1496 biglen
= len
+ pad
; /* len(padding+type+data+CRC) */
1498 for (i
= pktoffs
; i
< 4+8; i
++)
1499 pkt
->data
[i
] = random_byte();
1500 crc
= crc32_compute(pkt
->data
+ pktoffs
+ 4, biglen
- 4); /* all ex len */
1501 PUT_32BIT(pkt
->data
+ pktoffs
+ 4 + biglen
- 4, crc
);
1502 PUT_32BIT(pkt
->data
+ pktoffs
, len
);
1505 ssh
->cipher
->encrypt(ssh
->v1_cipher_ctx
,
1506 pkt
->data
+ pktoffs
+ 4, biglen
);
1508 if (offset_p
) *offset_p
= pktoffs
;
1509 return biglen
+ 4; /* len(length+padding+type+data+CRC) */
1512 static int s_write(Ssh ssh
, void *data
, int len
)
1515 log_packet(ssh
->logctx
, PKT_OUTGOING
, -1, NULL
, data
, len
, 0, NULL
);
1516 return sk_write(ssh
->s
, (char *)data
, len
);
1519 static void s_wrpkt(Ssh ssh
, struct Packet
*pkt
)
1521 int len
, backlog
, offset
;
1522 len
= s_wrpkt_prepare(ssh
, pkt
, &offset
);
1523 backlog
= s_write(ssh
, pkt
->data
+ offset
, len
);
1524 if (backlog
> SSH_MAX_BACKLOG
)
1525 ssh_throttle_all(ssh
, 1, backlog
);
1526 ssh_free_packet(pkt
);
1529 static void s_wrpkt_defer(Ssh ssh
, struct Packet
*pkt
)
1532 len
= s_wrpkt_prepare(ssh
, pkt
, &offset
);
1533 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1534 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1535 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
1539 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
,
1540 pkt
->data
+ offset
, len
);
1541 ssh
->deferred_len
+= len
;
1542 ssh_free_packet(pkt
);
1546 * Construct a SSH-1 packet with the specified contents.
1547 * (This all-at-once interface used to be the only one, but now SSH-1
1548 * packets can also be constructed incrementally.)
1550 static struct Packet
*construct_packet(Ssh ssh
, int pkttype
, va_list ap
)
1556 pkt
= ssh1_pkt_init(pkttype
);
1558 while ((argtype
= va_arg(ap
, int)) != PKT_END
) {
1559 unsigned char *argp
, argchar
;
1561 unsigned long argint
;
1564 /* Actual fields in the packet */
1566 argint
= va_arg(ap
, int);
1567 ssh_pkt_adduint32(pkt
, argint
);
1570 argchar
= (unsigned char) va_arg(ap
, int);
1571 ssh_pkt_addbyte(pkt
, argchar
);
1574 argp
= va_arg(ap
, unsigned char *);
1575 arglen
= va_arg(ap
, int);
1576 ssh_pkt_adddata(pkt
, argp
, arglen
);
1579 sargp
= va_arg(ap
, char *);
1580 ssh_pkt_addstring(pkt
, sargp
);
1583 bn
= va_arg(ap
, Bignum
);
1584 ssh1_pkt_addmp(pkt
, bn
);
1586 /* Tokens for modifications to packet logging */
1588 dont_log_password(ssh
, pkt
, PKTLOG_BLANK
);
1591 dont_log_data(ssh
, pkt
, PKTLOG_OMIT
);
1594 end_log_omission(ssh
, pkt
);
1602 static void send_packet(Ssh ssh
, int pkttype
, ...)
1606 va_start(ap
, pkttype
);
1607 pkt
= construct_packet(ssh
, pkttype
, ap
);
1612 static void defer_packet(Ssh ssh
, int pkttype
, ...)
1616 va_start(ap
, pkttype
);
1617 pkt
= construct_packet(ssh
, pkttype
, ap
);
1619 s_wrpkt_defer(ssh
, pkt
);
1622 static int ssh_versioncmp(char *a
, char *b
)
1625 unsigned long av
, bv
;
1627 av
= strtoul(a
, &ae
, 10);
1628 bv
= strtoul(b
, &be
, 10);
1630 return (av
< bv ?
-1 : +1);
1635 av
= strtoul(ae
, &ae
, 10);
1636 bv
= strtoul(be
, &be
, 10);
1638 return (av
< bv ?
-1 : +1);
1643 * Utility routines for putting an SSH-protocol `string' and
1644 * `uint32' into a hash state.
1646 static void hash_string(const struct ssh_hash
*h
, void *s
, void *str
, int len
)
1648 unsigned char lenblk
[4];
1649 PUT_32BIT(lenblk
, len
);
1650 h
->bytes(s
, lenblk
, 4);
1651 h
->bytes(s
, str
, len
);
1654 static void hash_uint32(const struct ssh_hash
*h
, void *s
, unsigned i
)
1656 unsigned char intblk
[4];
1657 PUT_32BIT(intblk
, i
);
1658 h
->bytes(s
, intblk
, 4);
1662 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1664 static void ssh_pkt_ensure(struct Packet
*pkt
, int length
)
1666 if (pkt
->maxlen
< length
) {
1667 unsigned char *body
= pkt
->body
;
1668 int offset
= body ? body
- pkt
->data
: 0;
1669 pkt
->maxlen
= length
+ 256;
1670 pkt
->data
= sresize(pkt
->data
, pkt
->maxlen
+ APIEXTRA
, unsigned char);
1671 if (body
) pkt
->body
= pkt
->data
+ offset
;
1674 static void ssh_pkt_adddata(struct Packet
*pkt
, void *data
, int len
)
1676 if (pkt
->logmode
!= PKTLOG_EMIT
) {
1678 pkt
->blanks
= sresize(pkt
->blanks
, pkt
->nblanks
, struct logblank_t
);
1680 pkt
->blanks
[pkt
->nblanks
-1].offset
= pkt
->length
-
1681 (pkt
->body
- pkt
->data
);
1682 pkt
->blanks
[pkt
->nblanks
-1].len
= len
;
1683 pkt
->blanks
[pkt
->nblanks
-1].type
= pkt
->logmode
;
1686 ssh_pkt_ensure(pkt
, pkt
->length
);
1687 memcpy(pkt
->data
+ pkt
->length
- len
, data
, len
);
1689 static void ssh_pkt_addbyte(struct Packet
*pkt
, unsigned char byte
)
1691 ssh_pkt_adddata(pkt
, &byte
, 1);
1693 static void ssh2_pkt_addbool(struct Packet
*pkt
, unsigned char value
)
1695 ssh_pkt_adddata(pkt
, &value
, 1);
1697 static void ssh_pkt_adduint32(struct Packet
*pkt
, unsigned long value
)
1700 PUT_32BIT(x
, value
);
1701 ssh_pkt_adddata(pkt
, x
, 4);
1703 static void ssh_pkt_addstring_start(struct Packet
*pkt
)
1705 ssh_pkt_adduint32(pkt
, 0);
1706 pkt
->savedpos
= pkt
->length
;
1708 static void ssh_pkt_addstring_str(struct Packet
*pkt
, char *data
)
1710 ssh_pkt_adddata(pkt
, data
, strlen(data
));
1711 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1713 static void ssh_pkt_addstring_data(struct Packet
*pkt
, char *data
, int len
)
1715 ssh_pkt_adddata(pkt
, data
, len
);
1716 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1718 static void ssh_pkt_addstring(struct Packet
*pkt
, char *data
)
1720 ssh_pkt_addstring_start(pkt
);
1721 ssh_pkt_addstring_str(pkt
, data
);
1723 static void ssh1_pkt_addmp(struct Packet
*pkt
, Bignum b
)
1725 int len
= ssh1_bignum_length(b
);
1726 unsigned char *data
= snewn(len
, unsigned char);
1727 (void) ssh1_write_bignum(data
, b
);
1728 ssh_pkt_adddata(pkt
, data
, len
);
1731 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
)
1734 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1735 p
= snewn(n
+ 1, unsigned char);
1737 for (i
= 1; i
<= n
; i
++)
1738 p
[i
] = bignum_byte(b
, n
- i
);
1740 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1742 memmove(p
, p
+ i
, n
+ 1 - i
);
1746 static void ssh2_pkt_addmp(struct Packet
*pkt
, Bignum b
)
1750 p
= ssh2_mpint_fmt(b
, &len
);
1751 ssh_pkt_addstring_start(pkt
);
1752 ssh_pkt_addstring_data(pkt
, (char *)p
, len
);
1756 static struct Packet
*ssh1_pkt_init(int pkt_type
)
1758 struct Packet
*pkt
= ssh_new_packet();
1759 pkt
->length
= 4 + 8; /* space for length + max padding */
1760 ssh_pkt_addbyte(pkt
, pkt_type
);
1761 pkt
->body
= pkt
->data
+ pkt
->length
;
1765 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1766 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1767 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1768 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1769 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1770 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1771 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1772 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1773 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1775 static struct Packet
*ssh2_pkt_init(int pkt_type
)
1777 struct Packet
*pkt
= ssh_new_packet();
1778 pkt
->length
= 5; /* space for packet length + padding length */
1780 ssh_pkt_addbyte(pkt
, (unsigned char) pkt_type
);
1781 pkt
->body
= pkt
->data
+ pkt
->length
; /* after packet type */
1786 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1787 * put the MAC on it. Final packet, ready to be sent, is stored in
1788 * pkt->data. Total length is returned.
1790 static int ssh2_pkt_construct(Ssh ssh
, struct Packet
*pkt
)
1792 int cipherblk
, maclen
, padding
, i
;
1795 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->data
[5],
1796 ssh2_pkt_type(ssh
->pkt_kctx
, ssh
->pkt_actx
, pkt
->data
[5]),
1797 pkt
->body
, pkt
->length
- (pkt
->body
- pkt
->data
),
1798 pkt
->nblanks
, pkt
->blanks
);
1799 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1803 * Compress packet payload.
1806 unsigned char *newpayload
;
1809 ssh
->cscomp
->compress(ssh
->cs_comp_ctx
, pkt
->data
+ 5,
1811 &newpayload
, &newlen
)) {
1813 ssh2_pkt_adddata(pkt
, newpayload
, newlen
);
1819 * Add padding. At least four bytes, and must also bring total
1820 * length (minus MAC) up to a multiple of the block size.
1821 * If pkt->forcepad is set, make sure the packet is at least that size
1824 cipherblk
= ssh
->cscipher ? ssh
->cscipher
->blksize
: 8; /* block size */
1825 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1827 if (pkt
->length
+ padding
< pkt
->forcepad
)
1828 padding
= pkt
->forcepad
- pkt
->length
;
1830 (cipherblk
- (pkt
->length
+ padding
) % cipherblk
) % cipherblk
;
1831 assert(padding
<= 255);
1832 maclen
= ssh
->csmac ? ssh
->csmac
->len
: 0;
1833 ssh2_pkt_ensure(pkt
, pkt
->length
+ padding
+ maclen
);
1834 pkt
->data
[4] = padding
;
1835 for (i
= 0; i
< padding
; i
++)
1836 pkt
->data
[pkt
->length
+ i
] = random_byte();
1837 PUT_32BIT(pkt
->data
, pkt
->length
+ padding
- 4);
1839 ssh
->csmac
->generate(ssh
->cs_mac_ctx
, pkt
->data
,
1840 pkt
->length
+ padding
,
1841 ssh
->v2_outgoing_sequence
);
1842 ssh
->v2_outgoing_sequence
++; /* whether or not we MACed */
1845 ssh
->cscipher
->encrypt(ssh
->cs_cipher_ctx
,
1846 pkt
->data
, pkt
->length
+ padding
);
1848 pkt
->encrypted_len
= pkt
->length
+ padding
;
1850 /* Ready-to-send packet starts at pkt->data. We return length. */
1851 return pkt
->length
+ padding
+ maclen
;
1855 * Routines called from the main SSH code to send packets. There
1856 * are quite a few of these, because we have two separate
1857 * mechanisms for delaying the sending of packets:
1859 * - In order to send an IGNORE message and a password message in
1860 * a single fixed-length blob, we require the ability to
1861 * concatenate the encrypted forms of those two packets _into_ a
1862 * single blob and then pass it to our <network.h> transport
1863 * layer in one go. Hence, there's a deferment mechanism which
1864 * works after packet encryption.
1866 * - In order to avoid sending any connection-layer messages
1867 * during repeat key exchange, we have to queue up any such
1868 * outgoing messages _before_ they are encrypted (and in
1869 * particular before they're allocated sequence numbers), and
1870 * then send them once we've finished.
1872 * I call these mechanisms `defer' and `queue' respectively, so as
1873 * to distinguish them reasonably easily.
1875 * The functions send_noqueue() and defer_noqueue() free the packet
1876 * structure they are passed. Every outgoing packet goes through
1877 * precisely one of these functions in its life; packets passed to
1878 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1879 * these or get queued, and then when the queue is later emptied
1880 * the packets are all passed to defer_noqueue().
1882 * When using a CBC-mode cipher, it's necessary to ensure that an
1883 * attacker can't provide data to be encrypted using an IV that they
1884 * know. We ensure this by prefixing each packet that might contain
1885 * user data with an SSH_MSG_IGNORE. This is done using the deferral
1886 * mechanism, so in this case send_noqueue() ends up redirecting to
1887 * defer_noqueue(). If you don't like this inefficiency, don't use
1891 static void ssh2_pkt_defer_noqueue(Ssh
, struct Packet
*, int);
1892 static void ssh_pkt_defersend(Ssh
);
1895 * Send an SSH-2 packet immediately, without queuing or deferring.
1897 static void ssh2_pkt_send_noqueue(Ssh ssh
, struct Packet
*pkt
)
1901 if (ssh
->cscipher
!= NULL
&& (ssh
->cscipher
->flags
& SSH_CIPHER_IS_CBC
)) {
1902 /* We need to send two packets, so use the deferral mechanism. */
1903 ssh2_pkt_defer_noqueue(ssh
, pkt
, FALSE
);
1904 ssh_pkt_defersend(ssh
);
1907 len
= ssh2_pkt_construct(ssh
, pkt
);
1908 backlog
= s_write(ssh
, pkt
->data
, len
);
1909 if (backlog
> SSH_MAX_BACKLOG
)
1910 ssh_throttle_all(ssh
, 1, backlog
);
1912 ssh
->outgoing_data_size
+= pkt
->encrypted_len
;
1913 if (!ssh
->kex_in_progress
&&
1914 ssh
->max_data_size
!= 0 &&
1915 ssh
->outgoing_data_size
> ssh
->max_data_size
)
1916 do_ssh2_transport(ssh
, "too much data sent", -1, NULL
);
1918 ssh_free_packet(pkt
);
1922 * Defer an SSH-2 packet.
1924 static void ssh2_pkt_defer_noqueue(Ssh ssh
, struct Packet
*pkt
, int noignore
)
1927 if (ssh
->cscipher
!= NULL
&& (ssh
->cscipher
->flags
& SSH_CIPHER_IS_CBC
) &&
1928 ssh
->deferred_len
== 0 && !noignore
) {
1930 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
1931 * get encrypted with a known IV.
1933 struct Packet
*ipkt
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
1934 ssh2_pkt_addstring_start(ipkt
);
1935 ssh2_pkt_defer_noqueue(ssh
, ipkt
, TRUE
);
1937 len
= ssh2_pkt_construct(ssh
, pkt
);
1938 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1939 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1940 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
1944 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
, pkt
->data
, len
);
1945 ssh
->deferred_len
+= len
;
1946 ssh
->deferred_data_size
+= pkt
->encrypted_len
;
1947 ssh_free_packet(pkt
);
1951 * Queue an SSH-2 packet.
1953 static void ssh2_pkt_queue(Ssh ssh
, struct Packet
*pkt
)
1955 assert(ssh
->queueing
);
1957 if (ssh
->queuelen
>= ssh
->queuesize
) {
1958 ssh
->queuesize
= ssh
->queuelen
+ 32;
1959 ssh
->queue
= sresize(ssh
->queue
, ssh
->queuesize
, struct Packet
*);
1962 ssh
->queue
[ssh
->queuelen
++] = pkt
;
1966 * Either queue or send a packet, depending on whether queueing is
1969 static void ssh2_pkt_send(Ssh ssh
, struct Packet
*pkt
)
1972 ssh2_pkt_queue(ssh
, pkt
);
1974 ssh2_pkt_send_noqueue(ssh
, pkt
);
1978 * Either queue or defer a packet, depending on whether queueing is
1981 static void ssh2_pkt_defer(Ssh ssh
, struct Packet
*pkt
)
1984 ssh2_pkt_queue(ssh
, pkt
);
1986 ssh2_pkt_defer_noqueue(ssh
, pkt
, FALSE
);
1990 * Send the whole deferred data block constructed by
1991 * ssh2_pkt_defer() or SSH-1's defer_packet().
1993 * The expected use of the defer mechanism is that you call
1994 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
1995 * not currently queueing, this simply sets up deferred_send_data
1996 * and then sends it. If we _are_ currently queueing, the calls to
1997 * ssh2_pkt_defer() put the deferred packets on to the queue
1998 * instead, and therefore ssh_pkt_defersend() has no deferred data
1999 * to send. Hence, there's no need to make it conditional on
2002 static void ssh_pkt_defersend(Ssh ssh
)
2005 backlog
= s_write(ssh
, ssh
->deferred_send_data
, ssh
->deferred_len
);
2006 ssh
->deferred_len
= ssh
->deferred_size
= 0;
2007 sfree(ssh
->deferred_send_data
);
2008 ssh
->deferred_send_data
= NULL
;
2009 if (backlog
> SSH_MAX_BACKLOG
)
2010 ssh_throttle_all(ssh
, 1, backlog
);
2012 ssh
->outgoing_data_size
+= ssh
->deferred_data_size
;
2013 if (!ssh
->kex_in_progress
&&
2014 ssh
->max_data_size
!= 0 &&
2015 ssh
->outgoing_data_size
> ssh
->max_data_size
)
2016 do_ssh2_transport(ssh
, "too much data sent", -1, NULL
);
2017 ssh
->deferred_data_size
= 0;
2021 * Send a packet whose length needs to be disguised (typically
2022 * passwords or keyboard-interactive responses).
2024 static void ssh2_pkt_send_with_padding(Ssh ssh
, struct Packet
*pkt
,
2030 * The simplest way to do this is to adjust the
2031 * variable-length padding field in the outgoing packet.
2033 * Currently compiled out, because some Cisco SSH servers
2034 * don't like excessively padded packets (bah, why's it
2037 pkt
->forcepad
= padsize
;
2038 ssh2_pkt_send(ssh
, pkt
);
2043 * If we can't do that, however, an alternative approach is
2044 * to use the pkt_defer mechanism to bundle the packet
2045 * tightly together with an SSH_MSG_IGNORE such that their
2046 * combined length is a constant. So first we construct the
2047 * final form of this packet and defer its sending.
2049 ssh2_pkt_defer(ssh
, pkt
);
2052 * Now construct an SSH_MSG_IGNORE which includes a string
2053 * that's an exact multiple of the cipher block size. (If
2054 * the cipher is NULL so that the block size is
2055 * unavailable, we don't do this trick at all, because we
2056 * gain nothing by it.)
2058 if (ssh
->cscipher
) {
2061 stringlen
= (256 - ssh
->deferred_len
);
2062 stringlen
+= ssh
->cscipher
->blksize
- 1;
2063 stringlen
-= (stringlen
% ssh
->cscipher
->blksize
);
2066 * Temporarily disable actual compression, so we
2067 * can guarantee to get this string exactly the
2068 * length we want it. The compression-disabling
2069 * routine should return an integer indicating how
2070 * many bytes we should adjust our string length
2074 ssh
->cscomp
->disable_compression(ssh
->cs_comp_ctx
);
2076 pkt
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
2077 ssh2_pkt_addstring_start(pkt
);
2078 for (i
= 0; i
< stringlen
; i
++) {
2079 char c
= (char) random_byte();
2080 ssh2_pkt_addstring_data(pkt
, &c
, 1);
2082 ssh2_pkt_defer(ssh
, pkt
);
2084 ssh_pkt_defersend(ssh
);
2089 * Send all queued SSH-2 packets. We send them by means of
2090 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2091 * packets that needed to be lumped together.
2093 static void ssh2_pkt_queuesend(Ssh ssh
)
2097 assert(!ssh
->queueing
);
2099 for (i
= 0; i
< ssh
->queuelen
; i
++)
2100 ssh2_pkt_defer_noqueue(ssh
, ssh
->queue
[i
], FALSE
);
2103 ssh_pkt_defersend(ssh
);
2107 void bndebug(char *string
, Bignum b
)
2111 p
= ssh2_mpint_fmt(b
, &len
);
2112 debug(("%s", string
));
2113 for (i
= 0; i
< len
; i
++)
2114 debug((" %02x", p
[i
]));
2120 static void hash_mpint(const struct ssh_hash
*h
, void *s
, Bignum b
)
2124 p
= ssh2_mpint_fmt(b
, &len
);
2125 hash_string(h
, s
, p
, len
);
2130 * Packet decode functions for both SSH-1 and SSH-2.
2132 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
)
2134 unsigned long value
;
2135 if (pkt
->length
- pkt
->savedpos
< 4)
2136 return 0; /* arrgh, no way to decline (FIXME?) */
2137 value
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
2141 static int ssh2_pkt_getbool(struct Packet
*pkt
)
2143 unsigned long value
;
2144 if (pkt
->length
- pkt
->savedpos
< 1)
2145 return 0; /* arrgh, no way to decline (FIXME?) */
2146 value
= pkt
->body
[pkt
->savedpos
] != 0;
2150 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
)
2155 if (pkt
->length
- pkt
->savedpos
< 4)
2157 len
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
2162 if (pkt
->length
- pkt
->savedpos
< *length
)
2164 *p
= (char *)(pkt
->body
+ pkt
->savedpos
);
2165 pkt
->savedpos
+= *length
;
2167 static void *ssh_pkt_getdata(struct Packet
*pkt
, int length
)
2169 if (pkt
->length
- pkt
->savedpos
< length
)
2171 pkt
->savedpos
+= length
;
2172 return pkt
->body
+ (pkt
->savedpos
- length
);
2174 static int ssh1_pkt_getrsakey(struct Packet
*pkt
, struct RSAKey
*key
,
2175 unsigned char **keystr
)
2179 j
= makekey(pkt
->body
+ pkt
->savedpos
,
2180 pkt
->length
- pkt
->savedpos
,
2187 assert(pkt
->savedpos
< pkt
->length
);
2191 static Bignum
ssh1_pkt_getmp(struct Packet
*pkt
)
2196 j
= ssh1_read_bignum(pkt
->body
+ pkt
->savedpos
,
2197 pkt
->length
- pkt
->savedpos
, &b
);
2205 static Bignum
ssh2_pkt_getmp(struct Packet
*pkt
)
2211 ssh_pkt_getstring(pkt
, &p
, &length
);
2216 b
= bignum_from_bytes((unsigned char *)p
, length
);
2221 * Helper function to add an SSH-2 signature blob to a packet.
2222 * Expects to be shown the public key blob as well as the signature
2223 * blob. Normally works just like ssh2_pkt_addstring, but will
2224 * fiddle with the signature packet if necessary for
2225 * BUG_SSH2_RSA_PADDING.
2227 static void ssh2_add_sigblob(Ssh ssh
, struct Packet
*pkt
,
2228 void *pkblob_v
, int pkblob_len
,
2229 void *sigblob_v
, int sigblob_len
)
2231 unsigned char *pkblob
= (unsigned char *)pkblob_v
;
2232 unsigned char *sigblob
= (unsigned char *)sigblob_v
;
2234 /* dmemdump(pkblob, pkblob_len); */
2235 /* dmemdump(sigblob, sigblob_len); */
2238 * See if this is in fact an ssh-rsa signature and a buggy
2239 * server; otherwise we can just do this the easy way.
2241 if ((ssh
->remote_bugs
& BUG_SSH2_RSA_PADDING
) &&
2242 (GET_32BIT(pkblob
) == 7 && !memcmp(pkblob
+4, "ssh-rsa", 7))) {
2243 int pos
, len
, siglen
;
2246 * Find the byte length of the modulus.
2249 pos
= 4+7; /* skip over "ssh-rsa" */
2250 pos
+= 4 + GET_32BIT(pkblob
+pos
); /* skip over exponent */
2251 len
= GET_32BIT(pkblob
+pos
); /* find length of modulus */
2252 pos
+= 4; /* find modulus itself */
2253 while (len
> 0 && pkblob
[pos
] == 0)
2255 /* debug(("modulus length is %d\n", len)); */
2258 * Now find the signature integer.
2260 pos
= 4+7; /* skip over "ssh-rsa" */
2261 siglen
= GET_32BIT(sigblob
+pos
);
2262 /* debug(("signature length is %d\n", siglen)); */
2264 if (len
!= siglen
) {
2265 unsigned char newlen
[4];
2266 ssh2_pkt_addstring_start(pkt
);
2267 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, pos
);
2268 /* dmemdump(sigblob, pos); */
2269 pos
+= 4; /* point to start of actual sig */
2270 PUT_32BIT(newlen
, len
);
2271 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 4);
2272 /* dmemdump(newlen, 4); */
2274 while (len
-- > siglen
) {
2275 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 1);
2276 /* dmemdump(newlen, 1); */
2278 ssh2_pkt_addstring_data(pkt
, (char *)(sigblob
+pos
), siglen
);
2279 /* dmemdump(sigblob+pos, siglen); */
2283 /* Otherwise fall through and do it the easy way. */
2286 ssh2_pkt_addstring_start(pkt
);
2287 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, sigblob_len
);
2291 * Examine the remote side's version string and compare it against
2292 * a list of known buggy implementations.
2294 static void ssh_detect_bugs(Ssh ssh
, char *vstring
)
2296 char *imp
; /* pointer to implementation part */
2298 imp
+= strcspn(imp
, "-");
2300 imp
+= strcspn(imp
, "-");
2303 ssh
->remote_bugs
= 0;
2306 * General notes on server version strings:
2307 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2308 * here -- in particular, we've heard of one that's perfectly happy
2309 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2310 * so we can't distinguish them.
2312 if (ssh
->cfg
.sshbug_ignore1
== FORCE_ON
||
2313 (ssh
->cfg
.sshbug_ignore1
== AUTO
&&
2314 (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
2315 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
2316 !strcmp(imp
, "1.2.22") || !strcmp(imp
, "Cisco-1.25") ||
2317 !strcmp(imp
, "OSU_1.4alpha3") || !strcmp(imp
, "OSU_1.5alpha4")))) {
2319 * These versions don't support SSH1_MSG_IGNORE, so we have
2320 * to use a different defence against password length
2323 ssh
->remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
2324 logevent("We believe remote version has SSH-1 ignore bug");
2327 if (ssh
->cfg
.sshbug_plainpw1
== FORCE_ON
||
2328 (ssh
->cfg
.sshbug_plainpw1
== AUTO
&&
2329 (!strcmp(imp
, "Cisco-1.25") || !strcmp(imp
, "OSU_1.4alpha3")))) {
2331 * These versions need a plain password sent; they can't
2332 * handle having a null and a random length of data after
2335 ssh
->remote_bugs
|= BUG_NEEDS_SSH1_PLAIN_PASSWORD
;
2336 logevent("We believe remote version needs a plain SSH-1 password");
2339 if (ssh
->cfg
.sshbug_rsa1
== FORCE_ON
||
2340 (ssh
->cfg
.sshbug_rsa1
== AUTO
&&
2341 (!strcmp(imp
, "Cisco-1.25")))) {
2343 * These versions apparently have no clue whatever about
2344 * RSA authentication and will panic and die if they see
2345 * an AUTH_RSA message.
2347 ssh
->remote_bugs
|= BUG_CHOKES_ON_RSA
;
2348 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2351 if (ssh
->cfg
.sshbug_hmac2
== FORCE_ON
||
2352 (ssh
->cfg
.sshbug_hmac2
== AUTO
&&
2353 !wc_match("* VShell", imp
) &&
2354 (wc_match("2.1.0*", imp
) || wc_match("2.0.*", imp
) ||
2355 wc_match("2.2.0*", imp
) || wc_match("2.3.0*", imp
) ||
2356 wc_match("2.1 *", imp
)))) {
2358 * These versions have the HMAC bug.
2360 ssh
->remote_bugs
|= BUG_SSH2_HMAC
;
2361 logevent("We believe remote version has SSH-2 HMAC bug");
2364 if (ssh
->cfg
.sshbug_derivekey2
== FORCE_ON
||
2365 (ssh
->cfg
.sshbug_derivekey2
== AUTO
&&
2366 !wc_match("* VShell", imp
) &&
2367 (wc_match("2.0.0*", imp
) || wc_match("2.0.10*", imp
) ))) {
2369 * These versions have the key-derivation bug (failing to
2370 * include the literal shared secret in the hashes that
2371 * generate the keys).
2373 ssh
->remote_bugs
|= BUG_SSH2_DERIVEKEY
;
2374 logevent("We believe remote version has SSH-2 key-derivation bug");
2377 if (ssh
->cfg
.sshbug_rsapad2
== FORCE_ON
||
2378 (ssh
->cfg
.sshbug_rsapad2
== AUTO
&&
2379 (wc_match("OpenSSH_2.[5-9]*", imp
) ||
2380 wc_match("OpenSSH_3.[0-2]*", imp
)))) {
2382 * These versions have the SSH-2 RSA padding bug.
2384 ssh
->remote_bugs
|= BUG_SSH2_RSA_PADDING
;
2385 logevent("We believe remote version has SSH-2 RSA padding bug");
2388 if (ssh
->cfg
.sshbug_pksessid2
== FORCE_ON
||
2389 (ssh
->cfg
.sshbug_pksessid2
== AUTO
&&
2390 wc_match("OpenSSH_2.[0-2]*", imp
))) {
2392 * These versions have the SSH-2 session-ID bug in
2393 * public-key authentication.
2395 ssh
->remote_bugs
|= BUG_SSH2_PK_SESSIONID
;
2396 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2399 if (ssh
->cfg
.sshbug_rekey2
== FORCE_ON
||
2400 (ssh
->cfg
.sshbug_rekey2
== AUTO
&&
2401 (wc_match("DigiSSH_2.0", imp
) ||
2402 wc_match("OpenSSH_2.[0-4]*", imp
) ||
2403 wc_match("OpenSSH_2.5.[0-3]*", imp
) ||
2404 wc_match("Sun_SSH_1.0", imp
) ||
2405 wc_match("Sun_SSH_1.0.1", imp
) ||
2406 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2407 wc_match("WeOnlyDo-*", imp
)))) {
2409 * These versions have the SSH-2 rekey bug.
2411 ssh
->remote_bugs
|= BUG_SSH2_REKEY
;
2412 logevent("We believe remote version has SSH-2 rekey bug");
2415 if (ssh
->cfg
.sshbug_maxpkt2
== FORCE_ON
||
2416 (ssh
->cfg
.sshbug_maxpkt2
== AUTO
&&
2417 (wc_match("1.36_sshlib GlobalSCAPE", imp
) ||
2418 wc_match("1.36 sshlib: GlobalScape", imp
)))) {
2420 * This version ignores our makpkt and needs to be throttled.
2422 ssh
->remote_bugs
|= BUG_SSH2_MAXPKT
;
2423 logevent("We believe remote version ignores SSH-2 maximum packet size");
2428 * The `software version' part of an SSH version string is required
2429 * to contain no spaces or minus signs.
2431 static void ssh_fix_verstring(char *str
)
2433 /* Eat "SSH-<protoversion>-". */
2434 assert(*str
== 'S'); str
++;
2435 assert(*str
== 'S'); str
++;
2436 assert(*str
== 'H'); str
++;
2437 assert(*str
== '-'); str
++;
2438 while (*str
&& *str
!= '-') str
++;
2439 assert(*str
== '-'); str
++;
2441 /* Convert minus signs and spaces in the remaining string into
2444 if (*str
== '-' || *str
== ' ')
2451 * Send an appropriate SSH version string.
2453 static void ssh_send_verstring(Ssh ssh
, char *svers
)
2457 if (ssh
->version
== 2) {
2459 * Construct a v2 version string.
2461 verstring
= dupprintf("SSH-2.0-%s\015\012", sshver
);
2464 * Construct a v1 version string.
2466 verstring
= dupprintf("SSH-%s-%s\012",
2467 (ssh_versioncmp(svers
, "1.5") <= 0 ?
2472 ssh_fix_verstring(verstring
);
2474 if (ssh
->version
== 2) {
2477 * Record our version string.
2479 len
= strcspn(verstring
, "\015\012");
2480 ssh
->v_c
= snewn(len
+ 1, char);
2481 memcpy(ssh
->v_c
, verstring
, len
);
2485 logeventf(ssh
, "We claim version: %.*s",
2486 strcspn(verstring
, "\015\012"), verstring
);
2487 s_write(ssh
, verstring
, strlen(verstring
));
2491 static int do_ssh_init(Ssh ssh
, unsigned char c
)
2493 struct do_ssh_init_state
{
2501 crState(do_ssh_init_state
);
2503 crBegin(ssh
->do_ssh_init_crstate
);
2505 /* Search for a line beginning with the string "SSH-" in the input. */
2507 if (c
!= 'S') goto no
;
2509 if (c
!= 'S') goto no
;
2511 if (c
!= 'H') goto no
;
2513 if (c
!= '-') goto no
;
2522 s
->vstring
= snewn(s
->vstrsize
, char);
2523 strcpy(s
->vstring
, "SSH-");
2527 crReturn(1); /* get another char */
2528 if (s
->vslen
>= s
->vstrsize
- 1) {
2530 s
->vstring
= sresize(s
->vstring
, s
->vstrsize
, char);
2532 s
->vstring
[s
->vslen
++] = c
;
2535 s
->version
[s
->i
] = '\0';
2537 } else if (s
->i
< sizeof(s
->version
) - 1)
2538 s
->version
[s
->i
++] = c
;
2539 } else if (c
== '\012')
2543 ssh
->agentfwd_enabled
= FALSE
;
2544 ssh
->rdpkt2_state
.incoming_sequence
= 0;
2546 s
->vstring
[s
->vslen
] = 0;
2547 s
->vstring
[strcspn(s
->vstring
, "\015\012")] = '\0';/* remove EOL chars */
2548 logeventf(ssh
, "Server version: %s", s
->vstring
);
2549 ssh_detect_bugs(ssh
, s
->vstring
);
2552 * Decide which SSH protocol version to support.
2555 /* Anything strictly below "2.0" means protocol 1 is supported. */
2556 s
->proto1
= ssh_versioncmp(s
->version
, "2.0") < 0;
2557 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2558 s
->proto2
= ssh_versioncmp(s
->version
, "1.99") >= 0;
2560 if (ssh
->cfg
.sshprot
== 0 && !s
->proto1
) {
2561 bombout(("SSH protocol version 1 required by user but not provided by server"));
2564 if (ssh
->cfg
.sshprot
== 3 && !s
->proto2
) {
2565 bombout(("SSH protocol version 2 required by user but not provided by server"));
2569 if (s
->proto2
&& (ssh
->cfg
.sshprot
>= 2 || !s
->proto1
))
2574 logeventf(ssh
, "Using SSH protocol version %d", ssh
->version
);
2576 /* Send the version string, if we haven't already */
2577 if (ssh
->cfg
.sshprot
!= 3)
2578 ssh_send_verstring(ssh
, s
->version
);
2580 if (ssh
->version
== 2) {
2583 * Record their version string.
2585 len
= strcspn(s
->vstring
, "\015\012");
2586 ssh
->v_s
= snewn(len
+ 1, char);
2587 memcpy(ssh
->v_s
, s
->vstring
, len
);
2591 * Initialise SSH-2 protocol.
2593 ssh
->protocol
= ssh2_protocol
;
2594 ssh2_protocol_setup(ssh
);
2595 ssh
->s_rdpkt
= ssh2_rdpkt
;
2598 * Initialise SSH-1 protocol.
2600 ssh
->protocol
= ssh1_protocol
;
2601 ssh1_protocol_setup(ssh
);
2602 ssh
->s_rdpkt
= ssh1_rdpkt
;
2604 if (ssh
->version
== 2)
2605 do_ssh2_transport(ssh
, NULL
, -1, NULL
);
2607 update_specials_menu(ssh
->frontend
);
2608 ssh
->state
= SSH_STATE_BEFORE_SIZE
;
2609 ssh
->pinger
= pinger_new(&ssh
->cfg
, &ssh_backend
, ssh
);
2616 static void ssh_process_incoming_data(Ssh ssh
,
2617 unsigned char **data
, int *datalen
)
2619 struct Packet
*pktin
;
2621 pktin
= ssh
->s_rdpkt(ssh
, data
, datalen
);
2623 ssh
->protocol(ssh
, NULL
, 0, pktin
);
2624 ssh_free_packet(pktin
);
2628 static void ssh_queue_incoming_data(Ssh ssh
,
2629 unsigned char **data
, int *datalen
)
2631 bufchain_add(&ssh
->queued_incoming_data
, *data
, *datalen
);
2636 static void ssh_process_queued_incoming_data(Ssh ssh
)
2639 unsigned char *data
;
2642 while (!ssh
->frozen
&& bufchain_size(&ssh
->queued_incoming_data
)) {
2643 bufchain_prefix(&ssh
->queued_incoming_data
, &vdata
, &len
);
2647 while (!ssh
->frozen
&& len
> 0)
2648 ssh_process_incoming_data(ssh
, &data
, &len
);
2651 bufchain_consume(&ssh
->queued_incoming_data
, origlen
- len
);
2655 static void ssh_set_frozen(Ssh ssh
, int frozen
)
2658 sk_set_frozen(ssh
->s
, frozen
);
2659 ssh
->frozen
= frozen
;
2662 static void ssh_gotdata(Ssh ssh
, unsigned char *data
, int datalen
)
2664 /* Log raw data, if we're in that mode. */
2666 log_packet(ssh
->logctx
, PKT_INCOMING
, -1, NULL
, data
, datalen
,
2669 crBegin(ssh
->ssh_gotdata_crstate
);
2672 * To begin with, feed the characters one by one to the
2673 * protocol initialisation / selection function do_ssh_init().
2674 * When that returns 0, we're done with the initial greeting
2675 * exchange and can move on to packet discipline.
2678 int ret
; /* need not be kept across crReturn */
2680 crReturnV
; /* more data please */
2681 ret
= do_ssh_init(ssh
, *data
);
2689 * We emerge from that loop when the initial negotiation is
2690 * over and we have selected an s_rdpkt function. Now pass
2691 * everything to s_rdpkt, and then pass the resulting packets
2692 * to the proper protocol handler.
2696 while (bufchain_size(&ssh
->queued_incoming_data
) > 0 || datalen
> 0) {
2698 ssh_queue_incoming_data(ssh
, &data
, &datalen
);
2699 /* This uses up all data and cannot cause anything interesting
2700 * to happen; indeed, for anything to happen at all, we must
2701 * return, so break out. */
2703 } else if (bufchain_size(&ssh
->queued_incoming_data
) > 0) {
2704 /* This uses up some or all data, and may freeze the
2706 ssh_process_queued_incoming_data(ssh
);
2708 /* This uses up some or all data, and may freeze the
2710 ssh_process_incoming_data(ssh
, &data
, &datalen
);
2712 /* FIXME this is probably EBW. */
2713 if (ssh
->state
== SSH_STATE_CLOSED
)
2716 /* We're out of data. Go and get some more. */
2722 static int ssh_do_close(Ssh ssh
, int notify_exit
)
2725 struct ssh_channel
*c
;
2727 ssh
->state
= SSH_STATE_CLOSED
;
2728 expire_timer_context(ssh
);
2733 notify_remote_exit(ssh
->frontend
);
2738 * Now we must shut down any port- and X-forwarded channels going
2739 * through this connection.
2741 if (ssh
->channels
) {
2742 while (NULL
!= (c
= index234(ssh
->channels
, 0))) {
2745 x11_close(c
->u
.x11
.s
);
2748 pfd_close(c
->u
.pfd
.s
);
2751 del234(ssh
->channels
, c
); /* moving next one to index 0 */
2752 if (ssh
->version
== 2)
2753 bufchain_clear(&c
->v
.v2
.outbuffer
);
2758 * Go through port-forwardings, and close any associated
2759 * listening sockets.
2761 if (ssh
->portfwds
) {
2762 struct ssh_portfwd
*pf
;
2763 while (NULL
!= (pf
= index234(ssh
->portfwds
, 0))) {
2764 /* Dispose of any listening socket. */
2766 pfd_terminate(pf
->local
);
2767 del234(ssh
->portfwds
, pf
); /* moving next one to index 0 */
2775 static void ssh_log(Plug plug
, int type
, SockAddr addr
, int port
,
2776 const char *error_msg
, int error_code
)
2778 Ssh ssh
= (Ssh
) plug
;
2779 char addrbuf
[256], *msg
;
2781 sk_getaddr(addr
, addrbuf
, lenof(addrbuf
));
2784 msg
= dupprintf("Connecting to %s port %d", addrbuf
, port
);
2786 msg
= dupprintf("Failed to connect to %s: %s", addrbuf
, error_msg
);
2792 static int ssh_closing(Plug plug
, const char *error_msg
, int error_code
,
2795 Ssh ssh
= (Ssh
) plug
;
2796 int need_notify
= ssh_do_close(ssh
, FALSE
);
2799 if (!ssh
->close_expected
)
2800 error_msg
= "Server unexpectedly closed network connection";
2802 error_msg
= "Server closed network connection";
2805 if (ssh
->close_expected
&& ssh
->clean_exit
&& ssh
->exitcode
< 0)
2809 notify_remote_exit(ssh
->frontend
);
2812 logevent(error_msg
);
2813 if (!ssh
->close_expected
|| !ssh
->clean_exit
)
2814 connection_fatal(ssh
->frontend
, "%s", error_msg
);
2818 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
2820 Ssh ssh
= (Ssh
) plug
;
2821 ssh_gotdata(ssh
, (unsigned char *)data
, len
);
2822 if (ssh
->state
== SSH_STATE_CLOSED
) {
2823 ssh_do_close(ssh
, TRUE
);
2829 static void ssh_sent(Plug plug
, int bufsize
)
2831 Ssh ssh
= (Ssh
) plug
;
2833 * If the send backlog on the SSH socket itself clears, we
2834 * should unthrottle the whole world if it was throttled.
2836 if (bufsize
< SSH_MAX_BACKLOG
)
2837 ssh_throttle_all(ssh
, 0, bufsize
);
2841 * Connect to specified host and port.
2842 * Returns an error message, or NULL on success.
2843 * Also places the canonical host name into `realhost'. It must be
2844 * freed by the caller.
2846 static const char *connect_to_host(Ssh ssh
, char *host
, int port
,
2847 char **realhost
, int nodelay
, int keepalive
)
2849 static const struct plug_function_table fn_table
= {
2860 if (*ssh
->cfg
.loghost
) {
2863 ssh
->savedhost
= dupstr(ssh
->cfg
.loghost
);
2864 ssh
->savedport
= 22; /* default ssh port */
2867 * A colon suffix on savedhost also lets us affect
2870 * (FIXME: do something about IPv6 address literals here.)
2872 colon
= strrchr(ssh
->savedhost
, ':');
2876 ssh
->savedport
= atoi(colon
);
2879 ssh
->savedhost
= dupstr(host
);
2881 port
= 22; /* default ssh port */
2882 ssh
->savedport
= port
;
2888 logeventf(ssh
, "Looking up host \"%s\"%s", host
,
2889 (ssh
->cfg
.addressfamily
== ADDRTYPE_IPV4 ?
" (IPv4)" :
2890 (ssh
->cfg
.addressfamily
== ADDRTYPE_IPV6 ?
" (IPv6)" : "")));
2891 addr
= name_lookup(host
, port
, realhost
, &ssh
->cfg
,
2892 ssh
->cfg
.addressfamily
);
2893 if ((err
= sk_addr_error(addr
)) != NULL
) {
2897 ssh
->fullhostname
= dupstr(*realhost
); /* save in case of GSSAPI */
2902 ssh
->fn
= &fn_table
;
2903 ssh
->s
= new_connection(addr
, *realhost
, port
,
2904 0, 1, nodelay
, keepalive
, (Plug
) ssh
, &ssh
->cfg
);
2905 if ((err
= sk_socket_error(ssh
->s
)) != NULL
) {
2907 notify_remote_exit(ssh
->frontend
);
2912 * If the SSH version number's fixed, set it now, and if it's SSH-2,
2913 * send the version string too.
2915 if (ssh
->cfg
.sshprot
== 0)
2917 if (ssh
->cfg
.sshprot
== 3) {
2919 ssh_send_verstring(ssh
, NULL
);
2923 * loghost, if configured, overrides realhost.
2925 if (*ssh
->cfg
.loghost
) {
2927 *realhost
= dupstr(ssh
->cfg
.loghost
);
2934 * Throttle or unthrottle the SSH connection.
2936 static void ssh_throttle_conn(Ssh ssh
, int adjust
)
2938 int old_count
= ssh
->conn_throttle_count
;
2939 ssh
->conn_throttle_count
+= adjust
;
2940 assert(ssh
->conn_throttle_count
>= 0);
2941 if (ssh
->conn_throttle_count
&& !old_count
) {
2942 ssh_set_frozen(ssh
, 1);
2943 } else if (!ssh
->conn_throttle_count
&& old_count
) {
2944 ssh_set_frozen(ssh
, 0);
2949 * Throttle or unthrottle _all_ local data streams (for when sends
2950 * on the SSH connection itself back up).
2952 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
)
2955 struct ssh_channel
*c
;
2957 if (enable
== ssh
->throttled_all
)
2959 ssh
->throttled_all
= enable
;
2960 ssh
->overall_bufsize
= bufsize
;
2963 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
2965 case CHAN_MAINSESSION
:
2967 * This is treated separately, outside the switch.
2971 x11_override_throttle(c
->u
.x11
.s
, enable
);
2974 /* Agent channels require no buffer management. */
2977 pfd_override_throttle(c
->u
.pfd
.s
, enable
);
2983 static void ssh_agent_callback(void *sshv
, void *reply
, int replylen
)
2985 Ssh ssh
= (Ssh
) sshv
;
2987 ssh
->agent_response
= reply
;
2988 ssh
->agent_response_len
= replylen
;
2990 if (ssh
->version
== 1)
2991 do_ssh1_login(ssh
, NULL
, -1, NULL
);
2993 do_ssh2_authconn(ssh
, NULL
, -1, NULL
);
2996 static void ssh_dialog_callback(void *sshv
, int ret
)
2998 Ssh ssh
= (Ssh
) sshv
;
3000 ssh
->user_response
= ret
;
3002 if (ssh
->version
== 1)
3003 do_ssh1_login(ssh
, NULL
, -1, NULL
);
3005 do_ssh2_transport(ssh
, NULL
, -1, NULL
);
3008 * This may have unfrozen the SSH connection, so do a
3011 ssh_process_queued_incoming_data(ssh
);
3014 static void ssh_agentf_callback(void *cv
, void *reply
, int replylen
)
3016 struct ssh_channel
*c
= (struct ssh_channel
*)cv
;
3018 void *sentreply
= reply
;
3021 /* Fake SSH_AGENT_FAILURE. */
3022 sentreply
= "\0\0\0\1\5";
3025 if (ssh
->version
== 2) {
3026 ssh2_add_channel_data(c
, sentreply
, replylen
);
3029 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
3030 PKT_INT
, c
->remoteid
,
3033 PKT_DATA
, sentreply
, replylen
,
3042 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3043 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3044 * => log `wire_reason'.
3046 static void ssh_disconnect(Ssh ssh
, char *client_reason
, char *wire_reason
,
3047 int code
, int clean_exit
)
3051 client_reason
= wire_reason
;
3053 error
= dupprintf("Disconnected: %s", client_reason
);
3055 error
= dupstr("Disconnected");
3057 if (ssh
->version
== 1) {
3058 send_packet(ssh
, SSH1_MSG_DISCONNECT
, PKT_STR
, wire_reason
,
3060 } else if (ssh
->version
== 2) {
3061 struct Packet
*pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3062 ssh2_pkt_adduint32(pktout
, code
);
3063 ssh2_pkt_addstring(pktout
, wire_reason
);
3064 ssh2_pkt_addstring(pktout
, "en"); /* language tag */
3065 ssh2_pkt_send_noqueue(ssh
, pktout
);
3068 ssh
->close_expected
= TRUE
;
3069 ssh
->clean_exit
= clean_exit
;
3070 ssh_closing((Plug
)ssh
, error
, 0, 0);
3075 * Handle the key exchange and user authentication phases.
3077 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
,
3078 struct Packet
*pktin
)
3081 unsigned char cookie
[8], *ptr
;
3082 struct RSAKey servkey
, hostkey
;
3083 struct MD5Context md5c
;
3084 struct do_ssh1_login_state
{
3086 unsigned char *rsabuf
, *keystr1
, *keystr2
;
3087 unsigned long supported_ciphers_mask
, supported_auths_mask
;
3088 int tried_publickey
, tried_agent
;
3089 int tis_auth_refused
, ccard_auth_refused
;
3090 unsigned char session_id
[16];
3093 void *publickey_blob
;
3094 int publickey_bloblen
;
3095 char *publickey_comment
;
3096 int publickey_encrypted
;
3097 prompts_t
*cur_prompt
;
3100 unsigned char request
[5], *response
, *p
;
3110 crState(do_ssh1_login_state
);
3112 crBegin(ssh
->do_ssh1_login_crstate
);
3117 if (pktin
->type
!= SSH1_SMSG_PUBLIC_KEY
) {
3118 bombout(("Public key packet not received"));
3122 logevent("Received public keys");
3124 ptr
= ssh_pkt_getdata(pktin
, 8);
3126 bombout(("SSH-1 public key packet stopped before random cookie"));
3129 memcpy(cookie
, ptr
, 8);
3131 if (!ssh1_pkt_getrsakey(pktin
, &servkey
, &s
->keystr1
) ||
3132 !ssh1_pkt_getrsakey(pktin
, &hostkey
, &s
->keystr2
)) {
3133 bombout(("Failed to read SSH-1 public keys from public key packet"));
3138 * Log the host key fingerprint.
3142 logevent("Host key fingerprint is:");
3143 strcpy(logmsg
, " ");
3144 hostkey
.comment
= NULL
;
3145 rsa_fingerprint(logmsg
+ strlen(logmsg
),
3146 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
3150 ssh
->v1_remote_protoflags
= ssh_pkt_getuint32(pktin
);
3151 s
->supported_ciphers_mask
= ssh_pkt_getuint32(pktin
);
3152 s
->supported_auths_mask
= ssh_pkt_getuint32(pktin
);
3153 if ((ssh
->remote_bugs
& BUG_CHOKES_ON_RSA
))
3154 s
->supported_auths_mask
&= ~(1 << SSH1_AUTH_RSA
);
3156 ssh
->v1_local_protoflags
=
3157 ssh
->v1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
3158 ssh
->v1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
3161 MD5Update(&md5c
, s
->keystr2
, hostkey
.bytes
);
3162 MD5Update(&md5c
, s
->keystr1
, servkey
.bytes
);
3163 MD5Update(&md5c
, cookie
, 8);
3164 MD5Final(s
->session_id
, &md5c
);
3166 for (i
= 0; i
< 32; i
++)
3167 ssh
->session_key
[i
] = random_byte();
3170 * Verify that the `bits' and `bytes' parameters match.
3172 if (hostkey
.bits
> hostkey
.bytes
* 8 ||
3173 servkey
.bits
> servkey
.bytes
* 8) {
3174 bombout(("SSH-1 public keys were badly formatted"));
3178 s
->len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
3180 s
->rsabuf
= snewn(s
->len
, unsigned char);
3183 * Verify the host key.
3187 * First format the key into a string.
3189 int len
= rsastr_len(&hostkey
);
3190 char fingerprint
[100];
3191 char *keystr
= snewn(len
, char);
3192 rsastr_fmt(keystr
, &hostkey
);
3193 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
3195 ssh_set_frozen(ssh
, 1);
3196 s
->dlgret
= verify_ssh_host_key(ssh
->frontend
,
3197 ssh
->savedhost
, ssh
->savedport
,
3198 "rsa", keystr
, fingerprint
,
3199 ssh_dialog_callback
, ssh
);
3201 if (s
->dlgret
< 0) {
3205 bombout(("Unexpected data from server while waiting"
3206 " for user host key response"));
3209 } while (pktin
|| inlen
> 0);
3210 s
->dlgret
= ssh
->user_response
;
3212 ssh_set_frozen(ssh
, 0);
3214 if (s
->dlgret
== 0) {
3215 ssh_disconnect(ssh
, "User aborted at host key verification",
3221 for (i
= 0; i
< 32; i
++) {
3222 s
->rsabuf
[i
] = ssh
->session_key
[i
];
3224 s
->rsabuf
[i
] ^= s
->session_id
[i
];
3227 if (hostkey
.bytes
> servkey
.bytes
) {
3228 ret
= rsaencrypt(s
->rsabuf
, 32, &servkey
);
3230 ret
= rsaencrypt(s
->rsabuf
, servkey
.bytes
, &hostkey
);
3232 ret
= rsaencrypt(s
->rsabuf
, 32, &hostkey
);
3234 ret
= rsaencrypt(s
->rsabuf
, hostkey
.bytes
, &servkey
);
3237 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3241 logevent("Encrypted session key");
3244 int cipher_chosen
= 0, warn
= 0;
3245 char *cipher_string
= NULL
;
3247 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
3248 int next_cipher
= ssh
->cfg
.ssh_cipherlist
[i
];
3249 if (next_cipher
== CIPHER_WARN
) {
3250 /* If/when we choose a cipher, warn about it */
3252 } else if (next_cipher
== CIPHER_AES
) {
3253 /* XXX Probably don't need to mention this. */
3254 logevent("AES not supported in SSH-1, skipping");
3256 switch (next_cipher
) {
3257 case CIPHER_3DES
: s
->cipher_type
= SSH_CIPHER_3DES
;
3258 cipher_string
= "3DES"; break;
3259 case CIPHER_BLOWFISH
: s
->cipher_type
= SSH_CIPHER_BLOWFISH
;
3260 cipher_string
= "Blowfish"; break;
3261 case CIPHER_DES
: s
->cipher_type
= SSH_CIPHER_DES
;
3262 cipher_string
= "single-DES"; break;
3264 if (s
->supported_ciphers_mask
& (1 << s
->cipher_type
))
3268 if (!cipher_chosen
) {
3269 if ((s
->supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
3270 bombout(("Server violates SSH-1 protocol by not "
3271 "supporting 3DES encryption"));
3273 /* shouldn't happen */
3274 bombout(("No supported ciphers found"));
3278 /* Warn about chosen cipher if necessary. */
3280 ssh_set_frozen(ssh
, 1);
3281 s
->dlgret
= askalg(ssh
->frontend
, "cipher", cipher_string
,
3282 ssh_dialog_callback
, ssh
);
3283 if (s
->dlgret
< 0) {
3287 bombout(("Unexpected data from server while waiting"
3288 " for user response"));
3291 } while (pktin
|| inlen
> 0);
3292 s
->dlgret
= ssh
->user_response
;
3294 ssh_set_frozen(ssh
, 0);
3295 if (s
->dlgret
== 0) {
3296 ssh_disconnect(ssh
, "User aborted at cipher warning", NULL
,
3303 switch (s
->cipher_type
) {
3304 case SSH_CIPHER_3DES
:
3305 logevent("Using 3DES encryption");
3307 case SSH_CIPHER_DES
:
3308 logevent("Using single-DES encryption");
3310 case SSH_CIPHER_BLOWFISH
:
3311 logevent("Using Blowfish encryption");
3315 send_packet(ssh
, SSH1_CMSG_SESSION_KEY
,
3316 PKT_CHAR
, s
->cipher_type
,
3317 PKT_DATA
, cookie
, 8,
3318 PKT_CHAR
, (s
->len
* 8) >> 8, PKT_CHAR
, (s
->len
* 8) & 0xFF,
3319 PKT_DATA
, s
->rsabuf
, s
->len
,
3320 PKT_INT
, ssh
->v1_local_protoflags
, PKT_END
);
3322 logevent("Trying to enable encryption...");
3326 ssh
->cipher
= (s
->cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
3327 s
->cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
3329 ssh
->v1_cipher_ctx
= ssh
->cipher
->make_context();
3330 ssh
->cipher
->sesskey(ssh
->v1_cipher_ctx
, ssh
->session_key
);
3331 logeventf(ssh
, "Initialised %s encryption", ssh
->cipher
->text_name
);
3333 ssh
->crcda_ctx
= crcda_make_context();
3334 logevent("Installing CRC compensation attack detector");
3336 if (servkey
.modulus
) {
3337 sfree(servkey
.modulus
);
3338 servkey
.modulus
= NULL
;
3340 if (servkey
.exponent
) {
3341 sfree(servkey
.exponent
);
3342 servkey
.exponent
= NULL
;
3344 if (hostkey
.modulus
) {
3345 sfree(hostkey
.modulus
);
3346 hostkey
.modulus
= NULL
;
3348 if (hostkey
.exponent
) {
3349 sfree(hostkey
.exponent
);
3350 hostkey
.exponent
= NULL
;
3354 if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3355 bombout(("Encryption not successfully enabled"));
3359 logevent("Successfully started encryption");
3361 fflush(stdout
); /* FIXME eh? */
3363 if (!*ssh
->cfg
.username
) {
3364 int ret
; /* need not be kept over crReturn */
3365 s
->cur_prompt
= new_prompts(ssh
->frontend
);
3366 s
->cur_prompt
->to_server
= TRUE
;
3367 s
->cur_prompt
->name
= dupstr("SSH login name");
3368 add_prompt(s
->cur_prompt
, dupstr("login as: "), TRUE
,
3369 lenof(s
->username
));
3370 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
3373 crWaitUntil(!pktin
);
3374 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
3379 * Failed to get a username. Terminate.
3381 free_prompts(s
->cur_prompt
);
3382 ssh_disconnect(ssh
, "No username provided", NULL
, 0, TRUE
);
3385 memcpy(s
->username
, s
->cur_prompt
->prompts
[0]->result
,
3386 lenof(s
->username
));
3387 free_prompts(s
->cur_prompt
);
3389 strncpy(s
->username
, ssh
->cfg
.username
, sizeof(s
->username
));
3390 s
->username
[sizeof(s
->username
)-1] = '\0';
3393 send_packet(ssh
, SSH1_CMSG_USER
, PKT_STR
, s
->username
, PKT_END
);
3395 char *userlog
= dupprintf("Sent username \"%s\"", s
->username
);
3397 if (flags
& FLAG_INTERACTIVE
&&
3398 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
3399 c_write_str(ssh
, userlog
);
3400 c_write_str(ssh
, "\r\n");
3408 if ((s
->supported_auths_mask
& (1 << SSH1_AUTH_RSA
)) == 0) {
3409 /* We must not attempt PK auth. Pretend we've already tried it. */
3410 s
->tried_publickey
= s
->tried_agent
= 1;
3412 s
->tried_publickey
= s
->tried_agent
= 0;
3414 s
->tis_auth_refused
= s
->ccard_auth_refused
= 0;
3416 * Load the public half of any configured keyfile for later use.
3418 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
3420 logeventf(ssh
, "Reading private key file \"%.150s\"",
3421 filename_to_str(&ssh
->cfg
.keyfile
));
3422 keytype
= key_type(&ssh
->cfg
.keyfile
);
3423 if (keytype
== SSH_KEYTYPE_SSH1
) {
3425 if (rsakey_pubblob(&ssh
->cfg
.keyfile
,
3426 &s
->publickey_blob
, &s
->publickey_bloblen
,
3427 &s
->publickey_comment
, &error
)) {
3428 s
->publickey_encrypted
= rsakey_encrypted(&ssh
->cfg
.keyfile
,
3432 logeventf(ssh
, "Unable to load private key (%s)", error
);
3433 msgbuf
= dupprintf("Unable to load private key file "
3434 "\"%.150s\" (%s)\r\n",
3435 filename_to_str(&ssh
->cfg
.keyfile
),
3437 c_write_str(ssh
, msgbuf
);
3439 s
->publickey_blob
= NULL
;
3443 logeventf(ssh
, "Unable to use this key file (%s)",
3444 key_type_to_str(keytype
));
3445 msgbuf
= dupprintf("Unable to use key file \"%.150s\""
3447 filename_to_str(&ssh
->cfg
.keyfile
),
3448 key_type_to_str(keytype
));
3449 c_write_str(ssh
, msgbuf
);
3451 s
->publickey_blob
= NULL
;
3454 s
->publickey_blob
= NULL
;
3456 while (pktin
->type
== SSH1_SMSG_FAILURE
) {
3457 s
->pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
3459 if (ssh
->cfg
.tryagent
&& agent_exists() && !s
->tried_agent
) {
3461 * Attempt RSA authentication using Pageant.
3467 logevent("Pageant is running. Requesting keys.");
3469 /* Request the keys held by the agent. */
3470 PUT_32BIT(s
->request
, 1);
3471 s
->request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
3472 if (!agent_query(s
->request
, 5, &r
, &s
->responselen
,
3473 ssh_agent_callback
, ssh
)) {
3477 bombout(("Unexpected data from server while waiting"
3478 " for agent response"));
3481 } while (pktin
|| inlen
> 0);
3482 r
= ssh
->agent_response
;
3483 s
->responselen
= ssh
->agent_response_len
;
3485 s
->response
= (unsigned char *) r
;
3486 if (s
->response
&& s
->responselen
>= 5 &&
3487 s
->response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
3488 s
->p
= s
->response
+ 5;
3489 s
->nkeys
= GET_32BIT(s
->p
);
3491 logeventf(ssh
, "Pageant has %d SSH-1 keys", s
->nkeys
);
3492 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
3493 unsigned char *pkblob
= s
->p
;
3497 do { /* do while (0) to make breaking easy */
3498 n
= ssh1_read_bignum
3499 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
3504 n
= ssh1_read_bignum
3505 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
3510 if (s
->responselen
- (s
->p
-s
->response
) < 4)
3512 s
->commentlen
= GET_32BIT(s
->p
);
3514 if (s
->responselen
- (s
->p
-s
->response
) <
3517 s
->commentp
= (char *)s
->p
;
3518 s
->p
+= s
->commentlen
;
3522 logevent("Pageant key list packet was truncated");
3526 if (s
->publickey_blob
) {
3527 if (!memcmp(pkblob
, s
->publickey_blob
,
3528 s
->publickey_bloblen
)) {
3529 logeventf(ssh
, "Pageant key #%d matches "
3530 "configured key file", s
->keyi
);
3531 s
->tried_publickey
= 1;
3533 /* Skip non-configured key */
3536 logeventf(ssh
, "Trying Pageant key #%d", s
->keyi
);
3537 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
3538 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
3540 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
3541 logevent("Key refused");
3544 logevent("Received RSA challenge");
3545 if ((s
->challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
3546 bombout(("Server's RSA challenge was badly formatted"));
3551 char *agentreq
, *q
, *ret
;
3554 len
= 1 + 4; /* message type, bit count */
3555 len
+= ssh1_bignum_length(s
->key
.exponent
);
3556 len
+= ssh1_bignum_length(s
->key
.modulus
);
3557 len
+= ssh1_bignum_length(s
->challenge
);
3558 len
+= 16; /* session id */
3559 len
+= 4; /* response format */
3560 agentreq
= snewn(4 + len
, char);
3561 PUT_32BIT(agentreq
, len
);
3563 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
3564 PUT_32BIT(q
, bignum_bitcount(s
->key
.modulus
));
3566 q
+= ssh1_write_bignum(q
, s
->key
.exponent
);
3567 q
+= ssh1_write_bignum(q
, s
->key
.modulus
);
3568 q
+= ssh1_write_bignum(q
, s
->challenge
);
3569 memcpy(q
, s
->session_id
, 16);
3571 PUT_32BIT(q
, 1); /* response format */
3572 if (!agent_query(agentreq
, len
+ 4, &vret
, &retlen
,
3573 ssh_agent_callback
, ssh
)) {
3578 bombout(("Unexpected data from server"
3579 " while waiting for agent"
3583 } while (pktin
|| inlen
> 0);
3584 vret
= ssh
->agent_response
;
3585 retlen
= ssh
->agent_response_len
;
3590 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
3591 logevent("Sending Pageant's response");
3592 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
3593 PKT_DATA
, ret
+ 5, 16,
3597 if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
3599 ("Pageant's response accepted");
3600 if (flags
& FLAG_VERBOSE
) {
3601 c_write_str(ssh
, "Authenticated using"
3603 c_write(ssh
, s
->commentp
,
3605 c_write_str(ssh
, "\" from agent\r\n");
3610 ("Pageant's response not accepted");
3613 ("Pageant failed to answer challenge");
3617 logevent("No reply received from Pageant");
3620 freebn(s
->key
.exponent
);
3621 freebn(s
->key
.modulus
);
3622 freebn(s
->challenge
);
3627 if (s
->publickey_blob
&& !s
->tried_publickey
)
3628 logevent("Configured key file not in Pageant");
3633 if (s
->publickey_blob
&& !s
->tried_publickey
) {
3635 * Try public key authentication with the specified
3638 int got_passphrase
; /* need not be kept over crReturn */
3639 if (flags
& FLAG_VERBOSE
)
3640 c_write_str(ssh
, "Trying public key authentication.\r\n");
3641 logeventf(ssh
, "Trying public key \"%s\"",
3642 filename_to_str(&ssh
->cfg
.keyfile
));
3643 s
->tried_publickey
= 1;
3644 got_passphrase
= FALSE
;
3645 while (!got_passphrase
) {
3647 * Get a passphrase, if necessary.
3649 char *passphrase
= NULL
; /* only written after crReturn */
3651 if (!s
->publickey_encrypted
) {
3652 if (flags
& FLAG_VERBOSE
)
3653 c_write_str(ssh
, "No passphrase required.\r\n");
3656 int ret
; /* need not be kept over crReturn */
3657 s
->cur_prompt
= new_prompts(ssh
->frontend
);
3658 s
->cur_prompt
->to_server
= FALSE
;
3659 s
->cur_prompt
->name
= dupstr("SSH key passphrase");
3660 add_prompt(s
->cur_prompt
,
3661 dupprintf("Passphrase for key \"%.100s\": ",
3662 s
->publickey_comment
),
3663 FALSE
, SSH_MAX_PASSWORD_LEN
);
3664 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
3667 crWaitUntil(!pktin
);
3668 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
3672 /* Failed to get a passphrase. Terminate. */
3673 free_prompts(s
->cur_prompt
);
3674 ssh_disconnect(ssh
, NULL
, "Unable to authenticate",
3678 passphrase
= dupstr(s
->cur_prompt
->prompts
[0]->result
);
3679 free_prompts(s
->cur_prompt
);
3682 * Try decrypting key with passphrase.
3684 ret
= loadrsakey(&ssh
->cfg
.keyfile
, &s
->key
, passphrase
,
3687 memset(passphrase
, 0, strlen(passphrase
));
3691 /* Correct passphrase. */
3692 got_passphrase
= TRUE
;
3693 } else if (ret
== 0) {
3694 c_write_str(ssh
, "Couldn't load private key from ");
3695 c_write_str(ssh
, filename_to_str(&ssh
->cfg
.keyfile
));
3696 c_write_str(ssh
, " (");
3697 c_write_str(ssh
, error
);
3698 c_write_str(ssh
, ").\r\n");
3699 got_passphrase
= FALSE
;
3700 break; /* go and try something else */
3701 } else if (ret
== -1) {
3702 c_write_str(ssh
, "Wrong passphrase.\r\n"); /* FIXME */
3703 got_passphrase
= FALSE
;
3706 assert(0 && "unexpected return from loadrsakey()");
3707 got_passphrase
= FALSE
; /* placate optimisers */
3711 if (got_passphrase
) {
3714 * Send a public key attempt.
3716 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
3717 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
3720 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3721 c_write_str(ssh
, "Server refused our public key.\r\n");
3722 continue; /* go and try something else */
3724 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
3725 bombout(("Bizarre response to offer of public key"));
3731 unsigned char buffer
[32];
3732 Bignum challenge
, response
;
3734 if ((challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
3735 bombout(("Server's RSA challenge was badly formatted"));
3738 response
= rsadecrypt(challenge
, &s
->key
);
3739 freebn(s
->key
.private_exponent
);/* burn the evidence */
3741 for (i
= 0; i
< 32; i
++) {
3742 buffer
[i
] = bignum_byte(response
, 31 - i
);
3746 MD5Update(&md5c
, buffer
, 32);
3747 MD5Update(&md5c
, s
->session_id
, 16);
3748 MD5Final(buffer
, &md5c
);
3750 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
3751 PKT_DATA
, buffer
, 16, PKT_END
);
3758 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3759 if (flags
& FLAG_VERBOSE
)
3760 c_write_str(ssh
, "Failed to authenticate with"
3761 " our public key.\r\n");
3762 continue; /* go and try something else */
3763 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3764 bombout(("Bizarre response to RSA authentication response"));
3768 break; /* we're through! */
3774 * Otherwise, try various forms of password-like authentication.
3776 s
->cur_prompt
= new_prompts(ssh
->frontend
);
3778 if (ssh
->cfg
.try_tis_auth
&&
3779 (s
->supported_auths_mask
& (1 << SSH1_AUTH_TIS
)) &&
3780 !s
->tis_auth_refused
) {
3781 s
->pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
3782 logevent("Requested TIS authentication");
3783 send_packet(ssh
, SSH1_CMSG_AUTH_TIS
, PKT_END
);
3785 if (pktin
->type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
3786 logevent("TIS authentication declined");
3787 if (flags
& FLAG_INTERACTIVE
)
3788 c_write_str(ssh
, "TIS authentication refused.\r\n");
3789 s
->tis_auth_refused
= 1;
3794 char *instr_suf
, *prompt
;
3796 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
3798 bombout(("TIS challenge packet was badly formed"));
3801 logevent("Received TIS challenge");
3802 s
->cur_prompt
->to_server
= TRUE
;
3803 s
->cur_prompt
->name
= dupstr("SSH TIS authentication");
3804 /* Prompt heuristic comes from OpenSSH */
3805 if (memchr(challenge
, '\n', challengelen
)) {
3806 instr_suf
= dupstr("");
3807 prompt
= dupprintf("%.*s", challengelen
, challenge
);
3809 instr_suf
= dupprintf("%.*s", challengelen
, challenge
);
3810 prompt
= dupstr("Response: ");
3812 s
->cur_prompt
->instruction
=
3813 dupprintf("Using TIS authentication.%s%s",
3814 (*instr_suf
) ?
"\n" : "",
3816 s
->cur_prompt
->instr_reqd
= TRUE
;
3817 add_prompt(s
->cur_prompt
, prompt
, FALSE
, SSH_MAX_PASSWORD_LEN
);
3821 if (ssh
->cfg
.try_tis_auth
&&
3822 (s
->supported_auths_mask
& (1 << SSH1_AUTH_CCARD
)) &&
3823 !s
->ccard_auth_refused
) {
3824 s
->pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
3825 logevent("Requested CryptoCard authentication");
3826 send_packet(ssh
, SSH1_CMSG_AUTH_CCARD
, PKT_END
);
3828 if (pktin
->type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
3829 logevent("CryptoCard authentication declined");
3830 c_write_str(ssh
, "CryptoCard authentication refused.\r\n");
3831 s
->ccard_auth_refused
= 1;
3836 char *instr_suf
, *prompt
;
3838 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
3840 bombout(("CryptoCard challenge packet was badly formed"));
3843 logevent("Received CryptoCard challenge");
3844 s
->cur_prompt
->to_server
= TRUE
;
3845 s
->cur_prompt
->name
= dupstr("SSH CryptoCard authentication");
3846 s
->cur_prompt
->name_reqd
= FALSE
;
3847 /* Prompt heuristic comes from OpenSSH */
3848 if (memchr(challenge
, '\n', challengelen
)) {
3849 instr_suf
= dupstr("");
3850 prompt
= dupprintf("%.*s", challengelen
, challenge
);
3852 instr_suf
= dupprintf("%.*s", challengelen
, challenge
);
3853 prompt
= dupstr("Response: ");
3855 s
->cur_prompt
->instruction
=
3856 dupprintf("Using CryptoCard authentication.%s%s",
3857 (*instr_suf
) ?
"\n" : "",
3859 s
->cur_prompt
->instr_reqd
= TRUE
;
3860 add_prompt(s
->cur_prompt
, prompt
, FALSE
, SSH_MAX_PASSWORD_LEN
);
3864 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
3865 if ((s
->supported_auths_mask
& (1 << SSH1_AUTH_PASSWORD
)) == 0) {
3866 bombout(("No supported authentication methods available"));
3869 s
->cur_prompt
->to_server
= TRUE
;
3870 s
->cur_prompt
->name
= dupstr("SSH password");
3871 add_prompt(s
->cur_prompt
, dupprintf("%.90s@%.90s's password: ",
3872 s
->username
, ssh
->savedhost
),
3873 FALSE
, SSH_MAX_PASSWORD_LEN
);
3877 * Show password prompt, having first obtained it via a TIS
3878 * or CryptoCard exchange if we're doing TIS or CryptoCard
3882 int ret
; /* need not be kept over crReturn */
3883 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
3886 crWaitUntil(!pktin
);
3887 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
3892 * Failed to get a password (for example
3893 * because one was supplied on the command line
3894 * which has already failed to work). Terminate.
3896 free_prompts(s
->cur_prompt
);
3897 ssh_disconnect(ssh
, NULL
, "Unable to authenticate", 0, TRUE
);
3902 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
3904 * Defence against traffic analysis: we send a
3905 * whole bunch of packets containing strings of
3906 * different lengths. One of these strings is the
3907 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3908 * The others are all random data in
3909 * SSH1_MSG_IGNORE packets. This way a passive
3910 * listener can't tell which is the password, and
3911 * hence can't deduce the password length.
3913 * Anybody with a password length greater than 16
3914 * bytes is going to have enough entropy in their
3915 * password that a listener won't find it _that_
3916 * much help to know how long it is. So what we'll
3919 * - if password length < 16, we send 15 packets
3920 * containing string lengths 1 through 15
3922 * - otherwise, we let N be the nearest multiple
3923 * of 8 below the password length, and send 8
3924 * packets containing string lengths N through
3925 * N+7. This won't obscure the order of
3926 * magnitude of the password length, but it will
3927 * introduce a bit of extra uncertainty.
3929 * A few servers can't deal with SSH1_MSG_IGNORE, at
3930 * least in this context. For these servers, we need
3931 * an alternative defence. We make use of the fact
3932 * that the password is interpreted as a C string:
3933 * so we can append a NUL, then some random data.
3935 * A few servers can deal with neither SSH1_MSG_IGNORE
3936 * here _nor_ a padded password string.
3937 * For these servers we are left with no defences
3938 * against password length sniffing.
3940 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
) &&
3941 !(ssh
->remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
3943 * The server can deal with SSH1_MSG_IGNORE, so
3944 * we can use the primary defence.
3946 int bottom
, top
, pwlen
, i
;
3949 pwlen
= strlen(s
->cur_prompt
->prompts
[0]->result
);
3951 bottom
= 0; /* zero length passwords are OK! :-) */
3954 bottom
= pwlen
& ~7;
3958 assert(pwlen
>= bottom
&& pwlen
<= top
);
3960 randomstr
= snewn(top
+ 1, char);
3962 for (i
= bottom
; i
<= top
; i
++) {
3964 defer_packet(ssh
, s
->pwpkt_type
,
3965 PKTT_PASSWORD
, PKT_STR
,
3966 s
->cur_prompt
->prompts
[0]->result
,
3967 PKTT_OTHER
, PKT_END
);
3969 for (j
= 0; j
< i
; j
++) {
3971 randomstr
[j
] = random_byte();
3972 } while (randomstr
[j
] == '\0');
3974 randomstr
[i
] = '\0';
3975 defer_packet(ssh
, SSH1_MSG_IGNORE
,
3976 PKT_STR
, randomstr
, PKT_END
);
3979 logevent("Sending password with camouflage packets");
3980 ssh_pkt_defersend(ssh
);
3983 else if (!(ssh
->remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
3985 * The server can't deal with SSH1_MSG_IGNORE
3986 * but can deal with padded passwords, so we
3987 * can use the secondary defence.
3993 len
= strlen(s
->cur_prompt
->prompts
[0]->result
);
3994 if (len
< sizeof(string
)) {
3996 strcpy(string
, s
->cur_prompt
->prompts
[0]->result
);
3997 len
++; /* cover the zero byte */
3998 while (len
< sizeof(string
)) {
3999 string
[len
++] = (char) random_byte();
4002 ss
= s
->cur_prompt
->prompts
[0]->result
;
4004 logevent("Sending length-padded password");
4005 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
4006 PKT_INT
, len
, PKT_DATA
, ss
, len
,
4007 PKTT_OTHER
, PKT_END
);
4010 * The server is believed unable to cope with
4011 * any of our password camouflage methods.
4014 len
= strlen(s
->cur_prompt
->prompts
[0]->result
);
4015 logevent("Sending unpadded password");
4016 send_packet(ssh
, s
->pwpkt_type
,
4017 PKTT_PASSWORD
, PKT_INT
, len
,
4018 PKT_DATA
, s
->cur_prompt
->prompts
[0]->result
, len
,
4019 PKTT_OTHER
, PKT_END
);
4022 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
4023 PKT_STR
, s
->cur_prompt
->prompts
[0]->result
,
4024 PKTT_OTHER
, PKT_END
);
4026 logevent("Sent password");
4027 free_prompts(s
->cur_prompt
);
4029 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4030 if (flags
& FLAG_VERBOSE
)
4031 c_write_str(ssh
, "Access denied\r\n");
4032 logevent("Authentication refused");
4033 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
4034 bombout(("Strange packet received, type %d", pktin
->type
));
4040 if (s
->publickey_blob
) {
4041 sfree(s
->publickey_blob
);
4042 sfree(s
->publickey_comment
);
4045 logevent("Authentication successful");
4050 void sshfwd_close(struct ssh_channel
*c
)
4054 if (ssh
->state
== SSH_STATE_CLOSED
)
4057 if (c
&& !c
->closes
) {
4059 * If halfopen is true, we have sent
4060 * CHANNEL_OPEN for this channel, but it hasn't even been
4061 * acknowledged by the server. So we must set a close flag
4062 * on it now, and then when the server acks the channel
4063 * open, we can close it then.
4066 if (ssh
->version
== 1) {
4067 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
4070 struct Packet
*pktout
;
4071 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
4072 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
4073 ssh2_pkt_send(ssh
, pktout
);
4076 c
->closes
= 1; /* sent MSG_CLOSE */
4077 if (c
->type
== CHAN_X11
) {
4079 logevent("Forwarded X11 connection terminated");
4080 } else if (c
->type
== CHAN_SOCKDATA
||
4081 c
->type
== CHAN_SOCKDATA_DORMANT
) {
4083 logevent("Forwarded port closed");
4088 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
4092 if (ssh
->state
== SSH_STATE_CLOSED
)
4095 if (ssh
->version
== 1) {
4096 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
4097 PKT_INT
, c
->remoteid
,
4098 PKT_INT
, len
, PKTT_DATA
, PKT_DATA
, buf
, len
,
4099 PKTT_OTHER
, PKT_END
);
4101 * In SSH-1 we can return 0 here - implying that forwarded
4102 * connections are never individually throttled - because
4103 * the only circumstance that can cause throttling will be
4104 * the whole SSH connection backing up, in which case
4105 * _everything_ will be throttled as a whole.
4109 ssh2_add_channel_data(c
, buf
, len
);
4110 return ssh2_try_send(c
);
4114 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
4119 if (ssh
->state
== SSH_STATE_CLOSED
)
4122 if (ssh
->version
== 1) {
4123 buflimit
= SSH1_BUFFER_LIMIT
;
4125 buflimit
= c
->v
.v2
.locmaxwin
;
4126 ssh2_set_window(c
, bufsize
< buflimit ? buflimit
- bufsize
: 0);
4128 if (c
->throttling_conn
&& bufsize
<= buflimit
) {
4129 c
->throttling_conn
= 0;
4130 ssh_throttle_conn(ssh
, -1);
4134 static void ssh_queueing_handler(Ssh ssh
, struct Packet
*pktin
)
4136 struct queued_handler
*qh
= ssh
->qhead
;
4140 assert(pktin
->type
== qh
->msg1
|| pktin
->type
== qh
->msg2
);
4143 assert(ssh
->packet_dispatch
[qh
->msg1
] == ssh_queueing_handler
);
4144 ssh
->packet_dispatch
[qh
->msg1
] = NULL
;
4147 assert(ssh
->packet_dispatch
[qh
->msg2
] == ssh_queueing_handler
);
4148 ssh
->packet_dispatch
[qh
->msg2
] = NULL
;
4152 ssh
->qhead
= qh
->next
;
4154 if (ssh
->qhead
->msg1
> 0) {
4155 assert(ssh
->packet_dispatch
[ssh
->qhead
->msg1
] == NULL
);
4156 ssh
->packet_dispatch
[ssh
->qhead
->msg1
] = ssh_queueing_handler
;
4158 if (ssh
->qhead
->msg2
> 0) {
4159 assert(ssh
->packet_dispatch
[ssh
->qhead
->msg2
] == NULL
);
4160 ssh
->packet_dispatch
[ssh
->qhead
->msg2
] = ssh_queueing_handler
;
4163 ssh
->qhead
= ssh
->qtail
= NULL
;
4164 ssh
->packet_dispatch
[pktin
->type
] = NULL
;
4167 qh
->handler(ssh
, pktin
, qh
->ctx
);
4172 static void ssh_queue_handler(Ssh ssh
, int msg1
, int msg2
,
4173 chandler_fn_t handler
, void *ctx
)
4175 struct queued_handler
*qh
;
4177 qh
= snew(struct queued_handler
);
4180 qh
->handler
= handler
;
4184 if (ssh
->qtail
== NULL
) {
4188 assert(ssh
->packet_dispatch
[qh
->msg1
] == NULL
);
4189 ssh
->packet_dispatch
[qh
->msg1
] = ssh_queueing_handler
;
4192 assert(ssh
->packet_dispatch
[qh
->msg2
] == NULL
);
4193 ssh
->packet_dispatch
[qh
->msg2
] = ssh_queueing_handler
;
4196 ssh
->qtail
->next
= qh
;
4201 static void ssh_rportfwd_succfail(Ssh ssh
, struct Packet
*pktin
, void *ctx
)
4203 struct ssh_rportfwd
*rpf
, *pf
= (struct ssh_rportfwd
*)ctx
;
4205 if (pktin
->type
== (ssh
->version
== 1 ? SSH1_SMSG_SUCCESS
:
4206 SSH2_MSG_REQUEST_SUCCESS
)) {
4207 logeventf(ssh
, "Remote port forwarding from %s enabled",
4210 logeventf(ssh
, "Remote port forwarding from %s refused",
4213 rpf
= del234(ssh
->rportfwds
, pf
);
4219 static void ssh_setup_portfwd(Ssh ssh
, const Config
*cfg
)
4221 const char *portfwd_strptr
= cfg
->portfwd
;
4222 struct ssh_portfwd
*epf
;
4225 if (!ssh
->portfwds
) {
4226 ssh
->portfwds
= newtree234(ssh_portcmp
);
4229 * Go through the existing port forwardings and tag them
4230 * with status==DESTROY. Any that we want to keep will be
4231 * re-enabled (status==KEEP) as we go through the
4232 * configuration and find out which bits are the same as
4235 struct ssh_portfwd
*epf
;
4237 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
4238 epf
->status
= DESTROY
;
4241 while (*portfwd_strptr
) {
4242 char address_family
, type
;
4243 int sport
,dport
,sserv
,dserv
;
4244 char sports
[256], dports
[256], saddr
[256], host
[256];
4247 address_family
= 'A';
4249 if (*portfwd_strptr
== 'A' ||
4250 *portfwd_strptr
== '4' ||
4251 *portfwd_strptr
== '6')
4252 address_family
= *portfwd_strptr
++;
4253 if (*portfwd_strptr
== 'L' ||
4254 *portfwd_strptr
== 'R' ||
4255 *portfwd_strptr
== 'D')
4256 type
= *portfwd_strptr
++;
4261 while (*portfwd_strptr
&& *portfwd_strptr
!= '\t') {
4262 if (*portfwd_strptr
== ':') {
4264 * We've seen a colon in the middle of the
4265 * source port number. This means that
4266 * everything we've seen until now is the
4267 * source _address_, so we'll move it into
4268 * saddr and start sports from the beginning
4273 if (ssh
->version
== 1 && type
== 'R') {
4274 logeventf(ssh
, "SSH-1 cannot handle remote source address "
4275 "spec \"%s\"; ignoring", sports
);
4277 strcpy(saddr
, sports
);
4280 if (n
< lenof(sports
)-1) sports
[n
++] = *portfwd_strptr
++;
4284 if (*portfwd_strptr
== '\t')
4287 while (*portfwd_strptr
&& *portfwd_strptr
!= ':') {
4288 if (n
< lenof(host
)-1) host
[n
++] = *portfwd_strptr
++;
4291 if (*portfwd_strptr
== ':')
4294 while (*portfwd_strptr
) {
4295 if (n
< lenof(dports
)-1) dports
[n
++] = *portfwd_strptr
++;
4299 dport
= atoi(dports
);
4303 dport
= net_service_lookup(dports
);
4305 logeventf(ssh
, "Service lookup failed for destination"
4306 " port \"%s\"", dports
);
4310 while (*portfwd_strptr
) portfwd_strptr
++;
4314 portfwd_strptr
++; /* eat the NUL and move to next one */
4316 sport
= atoi(sports
);
4320 sport
= net_service_lookup(sports
);
4322 logeventf(ssh
, "Service lookup failed for source"
4323 " port \"%s\"", sports
);
4326 if (sport
&& dport
) {
4327 /* Set up a description of the source port. */
4328 struct ssh_portfwd
*pfrec
, *epfrec
;
4330 pfrec
= snew(struct ssh_portfwd
);
4332 pfrec
->saddr
= *saddr ?
dupstr(saddr
) : NULL
;
4333 pfrec
->sserv
= sserv ?
dupstr(sports
) : NULL
;
4334 pfrec
->sport
= sport
;
4335 pfrec
->daddr
= *host ?
dupstr(host
) : NULL
;
4336 pfrec
->dserv
= dserv ?
dupstr(dports
) : NULL
;
4337 pfrec
->dport
= dport
;
4338 pfrec
->local
= NULL
;
4339 pfrec
->remote
= NULL
;
4340 pfrec
->addressfamily
= (address_family
== '4' ? ADDRTYPE_IPV4
:
4341 address_family
== '6' ? ADDRTYPE_IPV6
:
4344 epfrec
= add234(ssh
->portfwds
, pfrec
);
4345 if (epfrec
!= pfrec
) {
4347 * We already have a port forwarding with precisely
4348 * these parameters. Hence, no need to do anything;
4349 * simply tag the existing one as KEEP.
4351 epfrec
->status
= KEEP
;
4352 free_portfwd(pfrec
);
4354 pfrec
->status
= CREATE
;
4360 * Now go through and destroy any port forwardings which were
4363 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
4364 if (epf
->status
== DESTROY
) {
4367 message
= dupprintf("%s port forwarding from %s%s%d",
4368 epf
->type
== 'L' ?
"local" :
4369 epf
->type
== 'R' ?
"remote" : "dynamic",
4370 epf
->saddr ? epf
->saddr
: "",
4371 epf
->saddr ?
":" : "",
4374 if (epf
->type
!= 'D') {
4375 char *msg2
= dupprintf("%s to %s:%d", message
,
4376 epf
->daddr
, epf
->dport
);
4381 logeventf(ssh
, "Cancelling %s", message
);
4385 struct ssh_rportfwd
*rpf
= epf
->remote
;
4386 struct Packet
*pktout
;
4389 * Cancel the port forwarding at the server
4392 if (ssh
->version
== 1) {
4394 * We cannot cancel listening ports on the
4395 * server side in SSH-1! There's no message
4396 * to support it. Instead, we simply remove
4397 * the rportfwd record from the local end
4398 * so that any connections the server tries
4399 * to make on it are rejected.
4402 pktout
= ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4403 ssh2_pkt_addstring(pktout
, "cancel-tcpip-forward");
4404 ssh2_pkt_addbool(pktout
, 0);/* _don't_ want reply */
4406 ssh2_pkt_addstring(pktout
, epf
->saddr
);
4407 } else if (ssh
->cfg
.rport_acceptall
) {
4408 /* XXX: ssh->cfg.rport_acceptall may not represent
4409 * what was used to open the original connection,
4410 * since it's reconfigurable. */
4411 ssh2_pkt_addstring(pktout
, "0.0.0.0");
4413 ssh2_pkt_addstring(pktout
, "127.0.0.1");
4415 ssh2_pkt_adduint32(pktout
, epf
->sport
);
4416 ssh2_pkt_send(ssh
, pktout
);
4419 del234(ssh
->rportfwds
, rpf
);
4421 } else if (epf
->local
) {
4422 pfd_terminate(epf
->local
);
4425 delpos234(ssh
->portfwds
, i
);
4427 i
--; /* so we don't skip one in the list */
4431 * And finally, set up any new port forwardings (status==CREATE).
4433 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
4434 if (epf
->status
== CREATE
) {
4435 char *sportdesc
, *dportdesc
;
4436 sportdesc
= dupprintf("%s%s%s%s%d%s",
4437 epf
->saddr ? epf
->saddr
: "",
4438 epf
->saddr ?
":" : "",
4439 epf
->sserv ? epf
->sserv
: "",
4440 epf
->sserv ?
"(" : "",
4442 epf
->sserv ?
")" : "");
4443 if (epf
->type
== 'D') {
4446 dportdesc
= dupprintf("%s:%s%s%d%s",
4448 epf
->dserv ? epf
->dserv
: "",
4449 epf
->dserv ?
"(" : "",
4451 epf
->dserv ?
")" : "");
4454 if (epf
->type
== 'L') {
4455 const char *err
= pfd_addforward(epf
->daddr
, epf
->dport
,
4456 epf
->saddr
, epf
->sport
,
4459 epf
->addressfamily
);
4461 logeventf(ssh
, "Local %sport %s forwarding to %s%s%s",
4462 epf
->addressfamily
== ADDRTYPE_IPV4 ?
"IPv4 " :
4463 epf
->addressfamily
== ADDRTYPE_IPV6 ?
"IPv6 " : "",
4464 sportdesc
, dportdesc
,
4465 err ?
" failed: " : "", err ? err
: "");
4466 } else if (epf
->type
== 'D') {
4467 const char *err
= pfd_addforward(NULL
, -1,
4468 epf
->saddr
, epf
->sport
,
4471 epf
->addressfamily
);
4473 logeventf(ssh
, "Local %sport %s SOCKS dynamic forwarding%s%s",
4474 epf
->addressfamily
== ADDRTYPE_IPV4 ?
"IPv4 " :
4475 epf
->addressfamily
== ADDRTYPE_IPV6 ?
"IPv6 " : "",
4477 err ?
" failed: " : "", err ? err
: "");
4479 struct ssh_rportfwd
*pf
;
4482 * Ensure the remote port forwardings tree exists.
4484 if (!ssh
->rportfwds
) {
4485 if (ssh
->version
== 1)
4486 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh1
);
4488 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh2
);
4491 pf
= snew(struct ssh_rportfwd
);
4492 strncpy(pf
->dhost
, epf
->daddr
, lenof(pf
->dhost
)-1);
4493 pf
->dhost
[lenof(pf
->dhost
)-1] = '\0';
4494 pf
->dport
= epf
->dport
;
4495 pf
->sport
= epf
->sport
;
4496 if (add234(ssh
->rportfwds
, pf
) != pf
) {
4497 logeventf(ssh
, "Duplicate remote port forwarding to %s:%d",
4498 epf
->daddr
, epf
->dport
);
4501 logeventf(ssh
, "Requesting remote port %s"
4502 " forward to %s", sportdesc
, dportdesc
);
4504 pf
->sportdesc
= sportdesc
;
4509 if (ssh
->version
== 1) {
4510 send_packet(ssh
, SSH1_CMSG_PORT_FORWARD_REQUEST
,
4511 PKT_INT
, epf
->sport
,
4512 PKT_STR
, epf
->daddr
,
4513 PKT_INT
, epf
->dport
,
4515 ssh_queue_handler(ssh
, SSH1_SMSG_SUCCESS
,
4517 ssh_rportfwd_succfail
, pf
);
4519 struct Packet
*pktout
;
4520 pktout
= ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4521 ssh2_pkt_addstring(pktout
, "tcpip-forward");
4522 ssh2_pkt_addbool(pktout
, 1);/* want reply */
4524 ssh2_pkt_addstring(pktout
, epf
->saddr
);
4525 } else if (cfg
->rport_acceptall
) {
4526 ssh2_pkt_addstring(pktout
, "0.0.0.0");
4528 ssh2_pkt_addstring(pktout
, "127.0.0.1");
4530 ssh2_pkt_adduint32(pktout
, epf
->sport
);
4531 ssh2_pkt_send(ssh
, pktout
);
4533 ssh_queue_handler(ssh
, SSH2_MSG_REQUEST_SUCCESS
,
4534 SSH2_MSG_REQUEST_FAILURE
,
4535 ssh_rportfwd_succfail
, pf
);
4544 static void ssh1_smsg_stdout_stderr_data(Ssh ssh
, struct Packet
*pktin
)
4547 int stringlen
, bufsize
;
4549 ssh_pkt_getstring(pktin
, &string
, &stringlen
);
4550 if (string
== NULL
) {
4551 bombout(("Incoming terminal data packet was badly formed"));
4555 bufsize
= from_backend(ssh
->frontend
, pktin
->type
== SSH1_SMSG_STDERR_DATA
,
4557 if (!ssh
->v1_stdout_throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
4558 ssh
->v1_stdout_throttling
= 1;
4559 ssh_throttle_conn(ssh
, +1);
4563 static void ssh1_smsg_x11_open(Ssh ssh
, struct Packet
*pktin
)
4565 /* Remote side is trying to open a channel to talk to our
4566 * X-Server. Give them back a local channel number. */
4567 struct ssh_channel
*c
;
4568 int remoteid
= ssh_pkt_getuint32(pktin
);
4570 logevent("Received X11 connect request");
4571 /* Refuse if X11 forwarding is disabled. */
4572 if (!ssh
->X11_fwd_enabled
) {
4573 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4574 PKT_INT
, remoteid
, PKT_END
);
4575 logevent("Rejected X11 connect request");
4577 c
= snew(struct ssh_channel
);
4580 if (x11_init(&c
->u
.x11
.s
, ssh
->cfg
.x11_display
, c
,
4581 ssh
->x11auth
, NULL
, -1, &ssh
->cfg
) != NULL
) {
4582 logevent("Opening X11 forward connection failed");
4584 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4585 PKT_INT
, remoteid
, PKT_END
);
4588 ("Opening X11 forward connection succeeded");
4589 c
->remoteid
= remoteid
;
4590 c
->halfopen
= FALSE
;
4591 c
->localid
= alloc_channel_id(ssh
);
4593 c
->throttling_conn
= 0;
4594 c
->type
= CHAN_X11
; /* identify channel type */
4595 add234(ssh
->channels
, c
);
4596 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4597 PKT_INT
, c
->remoteid
, PKT_INT
,
4598 c
->localid
, PKT_END
);
4599 logevent("Opened X11 forward channel");
4604 static void ssh1_smsg_agent_open(Ssh ssh
, struct Packet
*pktin
)
4606 /* Remote side is trying to open a channel to talk to our
4607 * agent. Give them back a local channel number. */
4608 struct ssh_channel
*c
;
4609 int remoteid
= ssh_pkt_getuint32(pktin
);
4611 /* Refuse if agent forwarding is disabled. */
4612 if (!ssh
->agentfwd_enabled
) {
4613 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4614 PKT_INT
, remoteid
, PKT_END
);
4616 c
= snew(struct ssh_channel
);
4618 c
->remoteid
= remoteid
;
4619 c
->halfopen
= FALSE
;
4620 c
->localid
= alloc_channel_id(ssh
);
4622 c
->throttling_conn
= 0;
4623 c
->type
= CHAN_AGENT
; /* identify channel type */
4624 c
->u
.a
.lensofar
= 0;
4625 add234(ssh
->channels
, c
);
4626 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4627 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
4632 static void ssh1_msg_port_open(Ssh ssh
, struct Packet
*pktin
)
4634 /* Remote side is trying to open a channel to talk to a
4635 * forwarded port. Give them back a local channel number. */
4636 struct ssh_channel
*c
;
4637 struct ssh_rportfwd pf
, *pfp
;
4642 c
= snew(struct ssh_channel
);
4645 remoteid
= ssh_pkt_getuint32(pktin
);
4646 ssh_pkt_getstring(pktin
, &host
, &hostsize
);
4647 port
= ssh_pkt_getuint32(pktin
);
4649 if (hostsize
>= lenof(pf
.dhost
))
4650 hostsize
= lenof(pf
.dhost
)-1;
4651 memcpy(pf
.dhost
, host
, hostsize
);
4652 pf
.dhost
[hostsize
] = '\0';
4654 pfp
= find234(ssh
->rportfwds
, &pf
, NULL
);
4657 logeventf(ssh
, "Rejected remote port open request for %s:%d",
4659 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4660 PKT_INT
, remoteid
, PKT_END
);
4662 logeventf(ssh
, "Received remote port open request for %s:%d",
4664 e
= pfd_newconnect(&c
->u
.pfd
.s
, pf
.dhost
, port
,
4665 c
, &ssh
->cfg
, pfp
->pfrec
->addressfamily
);
4667 logeventf(ssh
, "Port open failed: %s", e
);
4669 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4670 PKT_INT
, remoteid
, PKT_END
);
4672 c
->remoteid
= remoteid
;
4673 c
->halfopen
= FALSE
;
4674 c
->localid
= alloc_channel_id(ssh
);
4676 c
->throttling_conn
= 0;
4677 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
4678 add234(ssh
->channels
, c
);
4679 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4680 PKT_INT
, c
->remoteid
, PKT_INT
,
4681 c
->localid
, PKT_END
);
4682 logevent("Forwarded port opened successfully");
4687 static void ssh1_msg_channel_open_confirmation(Ssh ssh
, struct Packet
*pktin
)
4689 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
4690 unsigned int localid
= ssh_pkt_getuint32(pktin
);
4691 struct ssh_channel
*c
;
4693 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
4694 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
4695 c
->remoteid
= localid
;
4696 c
->halfopen
= FALSE
;
4697 c
->type
= CHAN_SOCKDATA
;
4698 c
->throttling_conn
= 0;
4699 pfd_confirm(c
->u
.pfd
.s
);
4702 if (c
&& c
->closes
) {
4704 * We have a pending close on this channel,
4705 * which we decided on before the server acked
4706 * the channel open. So now we know the
4707 * remoteid, we can close it again.
4709 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
,
4710 PKT_INT
, c
->remoteid
, PKT_END
);
4714 static void ssh1_msg_channel_open_failure(Ssh ssh
, struct Packet
*pktin
)
4716 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
4717 struct ssh_channel
*c
;
4719 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
4720 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
4721 logevent("Forwarded connection refused by server");
4722 pfd_close(c
->u
.pfd
.s
);
4723 del234(ssh
->channels
, c
);
4728 static void ssh1_msg_channel_close(Ssh ssh
, struct Packet
*pktin
)
4730 /* Remote side closes a channel. */
4731 unsigned i
= ssh_pkt_getuint32(pktin
);
4732 struct ssh_channel
*c
;
4733 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
4734 if (c
&& !c
->halfopen
) {
4737 (pktin
->type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
4739 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
4740 logevent("Forwarded X11 connection terminated");
4741 assert(c
->u
.x11
.s
!= NULL
);
4742 x11_close(c
->u
.x11
.s
);
4745 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
4746 logevent("Forwarded port closed");
4747 assert(c
->u
.pfd
.s
!= NULL
);
4748 pfd_close(c
->u
.pfd
.s
);
4752 c
->closes
|= (closetype
<< 2); /* seen this message */
4753 if (!(c
->closes
& closetype
)) {
4754 send_packet(ssh
, pktin
->type
, PKT_INT
, c
->remoteid
,
4756 c
->closes
|= closetype
; /* sent it too */
4759 if (c
->closes
== 15) {
4760 del234(ssh
->channels
, c
);
4764 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4765 pktin
->type
== SSH1_MSG_CHANNEL_CLOSE ?
"" :
4766 "_CONFIRMATION", c ?
"half-open" : "nonexistent",
4771 static void ssh1_msg_channel_data(Ssh ssh
, struct Packet
*pktin
)
4773 /* Data sent down one of our channels. */
4774 int i
= ssh_pkt_getuint32(pktin
);
4777 struct ssh_channel
*c
;
4779 ssh_pkt_getstring(pktin
, &p
, &len
);
4781 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
4786 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
4789 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
4792 /* Data for an agent message. Buffer it. */
4794 if (c
->u
.a
.lensofar
< 4) {
4795 unsigned int l
= min(4 - c
->u
.a
.lensofar
, (unsigned)len
);
4796 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
4800 c
->u
.a
.lensofar
+= l
;
4802 if (c
->u
.a
.lensofar
== 4) {
4804 4 + GET_32BIT(c
->u
.a
.msglen
);
4805 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
4807 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
4809 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
4811 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
4813 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
4817 c
->u
.a
.lensofar
+= l
;
4819 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
4822 if (agent_query(c
->u
.a
.message
,
4825 ssh_agentf_callback
, c
))
4826 ssh_agentf_callback(c
, reply
, replylen
);
4827 sfree(c
->u
.a
.message
);
4828 c
->u
.a
.lensofar
= 0;
4831 bufsize
= 0; /* agent channels never back up */
4834 if (!c
->throttling_conn
&& bufsize
> SSH1_BUFFER_LIMIT
) {
4835 c
->throttling_conn
= 1;
4836 ssh_throttle_conn(ssh
, +1);
4841 static void ssh1_smsg_exit_status(Ssh ssh
, struct Packet
*pktin
)
4843 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
4844 logeventf(ssh
, "Server sent command exit status %d", ssh
->exitcode
);
4845 send_packet(ssh
, SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
4847 * In case `helpful' firewalls or proxies tack
4848 * extra human-readable text on the end of the
4849 * session which we might mistake for another
4850 * encrypted packet, we close the session once
4851 * we've sent EXIT_CONFIRMATION.
4853 ssh_disconnect(ssh
, NULL
, NULL
, 0, TRUE
);
4856 /* Helper function to deal with sending tty modes for REQUEST_PTY */
4857 static void ssh1_send_ttymode(void *data
, char *mode
, char *val
)
4859 struct Packet
*pktout
= (struct Packet
*)data
;
4861 unsigned int arg
= 0;
4862 while (strcmp(mode
, ssh_ttymodes
[i
].mode
) != 0) i
++;
4863 if (i
== lenof(ssh_ttymodes
)) return;
4864 switch (ssh_ttymodes
[i
].type
) {
4866 arg
= ssh_tty_parse_specchar(val
);
4869 arg
= ssh_tty_parse_boolean(val
);
4872 ssh2_pkt_addbyte(pktout
, ssh_ttymodes
[i
].opcode
);
4873 ssh2_pkt_addbyte(pktout
, arg
);
4877 static void do_ssh1_connection(Ssh ssh
, unsigned char *in
, int inlen
,
4878 struct Packet
*pktin
)
4880 crBegin(ssh
->do_ssh1_connection_crstate
);
4882 ssh
->packet_dispatch
[SSH1_SMSG_STDOUT_DATA
] =
4883 ssh
->packet_dispatch
[SSH1_SMSG_STDERR_DATA
] =
4884 ssh1_smsg_stdout_stderr_data
;
4886 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
] =
4887 ssh1_msg_channel_open_confirmation
;
4888 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_OPEN_FAILURE
] =
4889 ssh1_msg_channel_open_failure
;
4890 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_CLOSE
] =
4891 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
] =
4892 ssh1_msg_channel_close
;
4893 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_DATA
] = ssh1_msg_channel_data
;
4894 ssh
->packet_dispatch
[SSH1_SMSG_EXIT_STATUS
] = ssh1_smsg_exit_status
;
4896 if (ssh
->cfg
.agentfwd
&& agent_exists()) {
4897 logevent("Requesting agent forwarding");
4898 send_packet(ssh
, SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
4902 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4903 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4904 bombout(("Protocol confusion"));
4906 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4907 logevent("Agent forwarding refused");
4909 logevent("Agent forwarding enabled");
4910 ssh
->agentfwd_enabled
= TRUE
;
4911 ssh
->packet_dispatch
[SSH1_SMSG_AGENT_OPEN
] = ssh1_smsg_agent_open
;
4915 if (ssh
->cfg
.x11_forward
) {
4916 char proto
[20], data
[64];
4917 logevent("Requesting X11 forwarding");
4918 ssh
->x11auth
= x11_invent_auth(proto
, sizeof(proto
),
4919 data
, sizeof(data
), ssh
->cfg
.x11_auth
);
4920 x11_get_real_auth(ssh
->x11auth
, ssh
->cfg
.x11_display
);
4922 * Note that while we blank the X authentication data here, we don't
4923 * take any special action to blank the start of an X11 channel,
4924 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
4925 * without having session blanking enabled is likely to leak your
4926 * cookie into the log.
4928 if (ssh
->v1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
4929 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
4931 PKTT_PASSWORD
, PKT_STR
, data
, PKTT_OTHER
,
4932 PKT_INT
, x11_get_screen_number(ssh
->cfg
.x11_display
),
4935 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
4937 PKTT_PASSWORD
, PKT_STR
, data
, PKTT_OTHER
, PKT_END
);
4942 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4943 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4944 bombout(("Protocol confusion"));
4946 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4947 logevent("X11 forwarding refused");
4949 logevent("X11 forwarding enabled");
4950 ssh
->X11_fwd_enabled
= TRUE
;
4951 ssh
->packet_dispatch
[SSH1_SMSG_X11_OPEN
] = ssh1_smsg_x11_open
;
4955 ssh_setup_portfwd(ssh
, &ssh
->cfg
);
4956 ssh
->packet_dispatch
[SSH1_MSG_PORT_OPEN
] = ssh1_msg_port_open
;
4958 if (!ssh
->cfg
.nopty
) {
4960 /* Unpick the terminal-speed string. */
4961 /* XXX perhaps we should allow no speeds to be sent. */
4962 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
4963 sscanf(ssh
->cfg
.termspeed
, "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
4964 /* Send the pty request. */
4965 pkt
= ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY
);
4966 ssh_pkt_addstring(pkt
, ssh
->cfg
.termtype
);
4967 ssh_pkt_adduint32(pkt
, ssh
->term_height
);
4968 ssh_pkt_adduint32(pkt
, ssh
->term_width
);
4969 ssh_pkt_adduint32(pkt
, 0); /* width in pixels */
4970 ssh_pkt_adduint32(pkt
, 0); /* height in pixels */
4971 parse_ttymodes(ssh
, ssh
->cfg
.ttymodes
,
4972 ssh1_send_ttymode
, (void *)pkt
);
4973 ssh_pkt_addbyte(pkt
, SSH1_TTY_OP_ISPEED
);
4974 ssh_pkt_adduint32(pkt
, ssh
->ispeed
);
4975 ssh_pkt_addbyte(pkt
, SSH1_TTY_OP_OSPEED
);
4976 ssh_pkt_adduint32(pkt
, ssh
->ospeed
);
4977 ssh_pkt_addbyte(pkt
, SSH_TTY_OP_END
);
4979 ssh
->state
= SSH_STATE_INTERMED
;
4983 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4984 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4985 bombout(("Protocol confusion"));
4987 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4988 c_write_str(ssh
, "Server refused to allocate pty\r\n");
4989 ssh
->editing
= ssh
->echoing
= 1;
4991 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
4992 ssh
->ospeed
, ssh
->ispeed
);
4994 ssh
->editing
= ssh
->echoing
= 1;
4997 if (ssh
->cfg
.compression
) {
4998 send_packet(ssh
, SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
5002 if (pktin
->type
!= SSH1_SMSG_SUCCESS
5003 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
5004 bombout(("Protocol confusion"));
5006 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
5007 c_write_str(ssh
, "Server refused to compress\r\n");
5009 logevent("Started compression");
5010 ssh
->v1_compressing
= TRUE
;
5011 ssh
->cs_comp_ctx
= zlib_compress_init();
5012 logevent("Initialised zlib (RFC1950) compression");
5013 ssh
->sc_comp_ctx
= zlib_decompress_init();
5014 logevent("Initialised zlib (RFC1950) decompression");
5018 * Start the shell or command.
5020 * Special case: if the first-choice command is an SSH-2
5021 * subsystem (hence not usable here) and the second choice
5022 * exists, we fall straight back to that.
5025 char *cmd
= ssh
->cfg
.remote_cmd_ptr
;
5027 if (!cmd
) cmd
= ssh
->cfg
.remote_cmd
;
5029 if (ssh
->cfg
.ssh_subsys
&& ssh
->cfg
.remote_cmd_ptr2
) {
5030 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
5031 ssh
->fallback_cmd
= TRUE
;
5034 send_packet(ssh
, SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
5036 send_packet(ssh
, SSH1_CMSG_EXEC_SHELL
, PKT_END
);
5037 logevent("Started session");
5040 ssh
->state
= SSH_STATE_SESSION
;
5041 if (ssh
->size_needed
)
5042 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
5043 if (ssh
->eof_needed
)
5044 ssh_special(ssh
, TS_EOF
);
5047 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
5049 ssh
->channels
= newtree234(ssh_channelcmp
);
5053 * By this point, most incoming packets are already being
5054 * handled by the dispatch table, and we need only pay
5055 * attention to the unusual ones.
5060 if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
5061 /* may be from EXEC_SHELL on some servers */
5062 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
5063 /* may be from EXEC_SHELL on some servers
5064 * if no pty is available or in other odd cases. Ignore */
5066 bombout(("Strange packet received: type %d", pktin
->type
));
5071 int len
= min(inlen
, 512);
5072 send_packet(ssh
, SSH1_CMSG_STDIN_DATA
,
5073 PKT_INT
, len
, PKTT_DATA
, PKT_DATA
, in
, len
,
5074 PKTT_OTHER
, PKT_END
);
5085 * Handle the top-level SSH-2 protocol.
5087 static void ssh1_msg_debug(Ssh ssh
, struct Packet
*pktin
)
5092 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
5093 logeventf(ssh
, "Remote debug message: %.*s", msglen
, msg
);
5096 static void ssh1_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
5098 /* log reason code in disconnect message */
5102 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
5103 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen
, msg
));
5106 static void ssh_msg_ignore(Ssh ssh
, struct Packet
*pktin
)
5108 /* Do nothing, because we're ignoring it! Duhh. */
5111 static void ssh1_protocol_setup(Ssh ssh
)
5116 * Most messages are handled by the coroutines.
5118 for (i
= 0; i
< 256; i
++)
5119 ssh
->packet_dispatch
[i
] = NULL
;
5122 * These special message types we install handlers for.
5124 ssh
->packet_dispatch
[SSH1_MSG_DISCONNECT
] = ssh1_msg_disconnect
;
5125 ssh
->packet_dispatch
[SSH1_MSG_IGNORE
] = ssh_msg_ignore
;
5126 ssh
->packet_dispatch
[SSH1_MSG_DEBUG
] = ssh1_msg_debug
;
5129 static void ssh1_protocol(Ssh ssh
, void *vin
, int inlen
,
5130 struct Packet
*pktin
)
5132 unsigned char *in
=(unsigned char*)vin
;
5133 if (ssh
->state
== SSH_STATE_CLOSED
)
5136 if (pktin
&& ssh
->packet_dispatch
[pktin
->type
]) {
5137 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
5141 if (!ssh
->protocol_initial_phase_done
) {
5142 if (do_ssh1_login(ssh
, in
, inlen
, pktin
))
5143 ssh
->protocol_initial_phase_done
= TRUE
;
5148 do_ssh1_connection(ssh
, in
, inlen
, pktin
);
5152 * Utility routine for decoding comma-separated strings in KEXINIT.
5154 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
5157 if (!needle
|| !haystack
) /* protect against null pointers */
5159 needlen
= strlen(needle
);
5162 * Is it at the start of the string?
5164 if (haylen
>= needlen
&& /* haystack is long enough */
5165 !memcmp(needle
, haystack
, needlen
) && /* initial match */
5166 (haylen
== needlen
|| haystack
[needlen
] == ',')
5167 /* either , or EOS follows */
5171 * If not, search for the next comma and resume after that.
5172 * If no comma found, terminate.
5174 while (haylen
> 0 && *haystack
!= ',')
5175 haylen
--, haystack
++;
5178 haylen
--, haystack
++; /* skip over comma itself */
5183 * Similar routine for checking whether we have the first string in a list.
5185 static int first_in_commasep_string(char *needle
, char *haystack
, int haylen
)
5188 if (!needle
|| !haystack
) /* protect against null pointers */
5190 needlen
= strlen(needle
);
5192 * Is it at the start of the string?
5194 if (haylen
>= needlen
&& /* haystack is long enough */
5195 !memcmp(needle
, haystack
, needlen
) && /* initial match */
5196 (haylen
== needlen
|| haystack
[needlen
] == ',')
5197 /* either , or EOS follows */
5205 * SSH-2 key creation method.
5206 * (Currently assumes 2 lots of any hash are sufficient to generate
5207 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5209 #define SSH2_MKKEY_ITERS (2)
5210 static void ssh2_mkkey(Ssh ssh
, Bignum K
, unsigned char *H
, char chr
,
5211 unsigned char *keyspace
)
5213 const struct ssh_hash
*h
= ssh
->kex
->hash
;
5215 /* First hlen bytes. */
5217 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
5218 hash_mpint(h
, s
, K
);
5219 h
->bytes(s
, H
, h
->hlen
);
5220 h
->bytes(s
, &chr
, 1);
5221 h
->bytes(s
, ssh
->v2_session_id
, ssh
->v2_session_id_len
);
5222 h
->final(s
, keyspace
);
5223 /* Next hlen bytes. */
5225 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
5226 hash_mpint(h
, s
, K
);
5227 h
->bytes(s
, H
, h
->hlen
);
5228 h
->bytes(s
, keyspace
, h
->hlen
);
5229 h
->final(s
, keyspace
+ h
->hlen
);
5233 * Handle the SSH-2 transport layer.
5235 static int do_ssh2_transport(Ssh ssh
, void *vin
, int inlen
,
5236 struct Packet
*pktin
)
5238 unsigned char *in
= (unsigned char *)vin
;
5239 struct do_ssh2_transport_state
{
5240 int nbits
, pbits
, warn_kex
, warn_cscipher
, warn_sccipher
;
5241 Bignum p
, g
, e
, f
, K
;
5244 int kex_init_value
, kex_reply_value
;
5245 const struct ssh_mac
**maclist
;
5247 const struct ssh2_cipher
*cscipher_tobe
;
5248 const struct ssh2_cipher
*sccipher_tobe
;
5249 const struct ssh_mac
*csmac_tobe
;
5250 const struct ssh_mac
*scmac_tobe
;
5251 const struct ssh_compress
*cscomp_tobe
;
5252 const struct ssh_compress
*sccomp_tobe
;
5253 char *hostkeydata
, *sigdata
, *rsakeydata
, *keystr
, *fingerprint
;
5254 int hostkeylen
, siglen
, rsakeylen
;
5255 void *hkey
; /* actual host key */
5256 void *rsakey
; /* for RSA kex */
5257 unsigned char exchange_hash
[SSH2_KEX_MAX_HASH_LEN
];
5258 int n_preferred_kex
;
5259 const struct ssh_kexes
*preferred_kex
[KEX_MAX
];
5260 int n_preferred_ciphers
;
5261 const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
5262 const struct ssh_compress
*preferred_comp
;
5263 int got_session_id
, activated_authconn
;
5264 struct Packet
*pktout
;
5269 crState(do_ssh2_transport_state
);
5271 crBegin(ssh
->do_ssh2_transport_crstate
);
5273 s
->cscipher_tobe
= s
->sccipher_tobe
= NULL
;
5274 s
->csmac_tobe
= s
->scmac_tobe
= NULL
;
5275 s
->cscomp_tobe
= s
->sccomp_tobe
= NULL
;
5277 s
->got_session_id
= s
->activated_authconn
= FALSE
;
5280 * Be prepared to work around the buggy MAC problem.
5282 if (ssh
->remote_bugs
& BUG_SSH2_HMAC
)
5283 s
->maclist
= buggymacs
, s
->nmacs
= lenof(buggymacs
);
5285 s
->maclist
= macs
, s
->nmacs
= lenof(macs
);
5288 ssh
->pkt_kctx
= SSH2_PKTCTX_NOKEX
;
5290 int i
, j
, commalist_started
;
5293 * Set up the preferred key exchange. (NULL => warn below here)
5295 s
->n_preferred_kex
= 0;
5296 for (i
= 0; i
< KEX_MAX
; i
++) {
5297 switch (ssh
->cfg
.ssh_kexlist
[i
]) {
5299 s
->preferred_kex
[s
->n_preferred_kex
++] =
5300 &ssh_diffiehellman_gex
;
5303 s
->preferred_kex
[s
->n_preferred_kex
++] =
5304 &ssh_diffiehellman_group14
;
5307 s
->preferred_kex
[s
->n_preferred_kex
++] =
5308 &ssh_diffiehellman_group1
;
5311 s
->preferred_kex
[s
->n_preferred_kex
++] =
5315 /* Flag for later. Don't bother if it's the last in
5317 if (i
< KEX_MAX
- 1) {
5318 s
->preferred_kex
[s
->n_preferred_kex
++] = NULL
;
5325 * Set up the preferred ciphers. (NULL => warn below here)
5327 s
->n_preferred_ciphers
= 0;
5328 for (i
= 0; i
< CIPHER_MAX
; i
++) {
5329 switch (ssh
->cfg
.ssh_cipherlist
[i
]) {
5330 case CIPHER_BLOWFISH
:
5331 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_blowfish
;
5334 if (ssh
->cfg
.ssh2_des_cbc
) {
5335 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_des
;
5339 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_3des
;
5342 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_aes
;
5344 case CIPHER_ARCFOUR
:
5345 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_arcfour
;
5348 /* Flag for later. Don't bother if it's the last in
5350 if (i
< CIPHER_MAX
- 1) {
5351 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = NULL
;
5358 * Set up preferred compression.
5360 if (ssh
->cfg
.compression
)
5361 s
->preferred_comp
= &ssh_zlib
;
5363 s
->preferred_comp
= &ssh_comp_none
;
5366 * Enable queueing of outgoing auth- or connection-layer
5367 * packets while we are in the middle of a key exchange.
5369 ssh
->queueing
= TRUE
;
5372 * Flag that KEX is in progress.
5374 ssh
->kex_in_progress
= TRUE
;
5377 * Construct and send our key exchange packet.
5379 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEXINIT
);
5380 for (i
= 0; i
< 16; i
++)
5381 ssh2_pkt_addbyte(s
->pktout
, (unsigned char) random_byte());
5382 /* List key exchange algorithms. */
5383 ssh2_pkt_addstring_start(s
->pktout
);
5384 commalist_started
= 0;
5385 for (i
= 0; i
< s
->n_preferred_kex
; i
++) {
5386 const struct ssh_kexes
*k
= s
->preferred_kex
[i
];
5387 if (!k
) continue; /* warning flag */
5388 for (j
= 0; j
< k
->nkexes
; j
++) {
5389 if (commalist_started
)
5390 ssh2_pkt_addstring_str(s
->pktout
, ",");
5391 ssh2_pkt_addstring_str(s
->pktout
, k
->list
[j
]->name
);
5392 commalist_started
= 1;
5395 /* List server host key algorithms. */
5396 ssh2_pkt_addstring_start(s
->pktout
);
5397 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
5398 ssh2_pkt_addstring_str(s
->pktout
, hostkey_algs
[i
]->name
);
5399 if (i
< lenof(hostkey_algs
) - 1)
5400 ssh2_pkt_addstring_str(s
->pktout
, ",");
5402 /* List client->server encryption algorithms. */
5403 ssh2_pkt_addstring_start(s
->pktout
);
5404 commalist_started
= 0;
5405 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5406 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5407 if (!c
) continue; /* warning flag */
5408 for (j
= 0; j
< c
->nciphers
; j
++) {
5409 if (commalist_started
)
5410 ssh2_pkt_addstring_str(s
->pktout
, ",");
5411 ssh2_pkt_addstring_str(s
->pktout
, c
->list
[j
]->name
);
5412 commalist_started
= 1;
5415 /* List server->client encryption algorithms. */
5416 ssh2_pkt_addstring_start(s
->pktout
);
5417 commalist_started
= 0;
5418 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5419 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5420 if (!c
) continue; /* warning flag */
5421 for (j
= 0; j
< c
->nciphers
; j
++) {
5422 if (commalist_started
)
5423 ssh2_pkt_addstring_str(s
->pktout
, ",");
5424 ssh2_pkt_addstring_str(s
->pktout
, c
->list
[j
]->name
);
5425 commalist_started
= 1;
5428 /* List client->server MAC algorithms. */
5429 ssh2_pkt_addstring_start(s
->pktout
);
5430 for (i
= 0; i
< s
->nmacs
; i
++) {
5431 ssh2_pkt_addstring_str(s
->pktout
, s
->maclist
[i
]->name
);
5432 if (i
< s
->nmacs
- 1)
5433 ssh2_pkt_addstring_str(s
->pktout
, ",");
5435 /* List server->client MAC algorithms. */
5436 ssh2_pkt_addstring_start(s
->pktout
);
5437 for (i
= 0; i
< s
->nmacs
; i
++) {
5438 ssh2_pkt_addstring_str(s
->pktout
, s
->maclist
[i
]->name
);
5439 if (i
< s
->nmacs
- 1)
5440 ssh2_pkt_addstring_str(s
->pktout
, ",");
5442 /* List client->server compression algorithms. */
5443 ssh2_pkt_addstring_start(s
->pktout
);
5444 assert(lenof(compressions
) > 1);
5445 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_comp
->name
);
5446 for (i
= 0; i
< lenof(compressions
); i
++) {
5447 const struct ssh_compress
*c
= compressions
[i
];
5448 if (c
!= s
->preferred_comp
) {
5449 ssh2_pkt_addstring_str(s
->pktout
, ",");
5450 ssh2_pkt_addstring_str(s
->pktout
, c
->name
);
5453 /* List server->client compression algorithms. */
5454 ssh2_pkt_addstring_start(s
->pktout
);
5455 assert(lenof(compressions
) > 1);
5456 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_comp
->name
);
5457 for (i
= 0; i
< lenof(compressions
); i
++) {
5458 const struct ssh_compress
*c
= compressions
[i
];
5459 if (c
!= s
->preferred_comp
) {
5460 ssh2_pkt_addstring_str(s
->pktout
, ",");
5461 ssh2_pkt_addstring_str(s
->pktout
, c
->name
);
5464 /* List client->server languages. Empty list. */
5465 ssh2_pkt_addstring_start(s
->pktout
);
5466 /* List server->client languages. Empty list. */
5467 ssh2_pkt_addstring_start(s
->pktout
);
5468 /* First KEX packet does _not_ follow, because we're not that brave. */
5469 ssh2_pkt_addbool(s
->pktout
, FALSE
);
5471 ssh2_pkt_adduint32(s
->pktout
, 0);
5474 s
->our_kexinitlen
= s
->pktout
->length
- 5;
5475 s
->our_kexinit
= snewn(s
->our_kexinitlen
, unsigned char);
5476 memcpy(s
->our_kexinit
, s
->pktout
->data
+ 5, s
->our_kexinitlen
);
5478 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5484 * Now examine the other side's KEXINIT to see what we're up
5488 char *str
, *preferred
;
5491 if (pktin
->type
!= SSH2_MSG_KEXINIT
) {
5492 bombout(("expected key exchange packet from server"));
5496 ssh
->hostkey
= NULL
;
5497 s
->cscipher_tobe
= NULL
;
5498 s
->sccipher_tobe
= NULL
;
5499 s
->csmac_tobe
= NULL
;
5500 s
->scmac_tobe
= NULL
;
5501 s
->cscomp_tobe
= NULL
;
5502 s
->sccomp_tobe
= NULL
;
5503 s
->warn_kex
= s
->warn_cscipher
= s
->warn_sccipher
= FALSE
;
5505 pktin
->savedpos
+= 16; /* skip garbage cookie */
5506 ssh_pkt_getstring(pktin
, &str
, &len
); /* key exchange algorithms */
5509 for (i
= 0; i
< s
->n_preferred_kex
; i
++) {
5510 const struct ssh_kexes
*k
= s
->preferred_kex
[i
];
5514 for (j
= 0; j
< k
->nkexes
; j
++) {
5515 if (!preferred
) preferred
= k
->list
[j
]->name
;
5516 if (in_commasep_string(k
->list
[j
]->name
, str
, len
)) {
5517 ssh
->kex
= k
->list
[j
];
5526 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5527 str ? str
: "(null)"));
5531 * Note that the server's guess is considered wrong if it doesn't match
5532 * the first algorithm in our list, even if it's still the algorithm
5535 s
->guessok
= first_in_commasep_string(preferred
, str
, len
);
5536 ssh_pkt_getstring(pktin
, &str
, &len
); /* host key algorithms */
5537 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
5538 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
5539 ssh
->hostkey
= hostkey_algs
[i
];
5543 s
->guessok
= s
->guessok
&&
5544 first_in_commasep_string(hostkey_algs
[0]->name
, str
, len
);
5545 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server cipher */
5546 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5547 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5549 s
->warn_cscipher
= TRUE
;
5551 for (j
= 0; j
< c
->nciphers
; j
++) {
5552 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
5553 s
->cscipher_tobe
= c
->list
[j
];
5558 if (s
->cscipher_tobe
)
5561 if (!s
->cscipher_tobe
) {
5562 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5563 str ? str
: "(null)"));
5567 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client cipher */
5568 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5569 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5571 s
->warn_sccipher
= TRUE
;
5573 for (j
= 0; j
< c
->nciphers
; j
++) {
5574 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
5575 s
->sccipher_tobe
= c
->list
[j
];
5580 if (s
->sccipher_tobe
)
5583 if (!s
->sccipher_tobe
) {
5584 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5585 str ? str
: "(null)"));
5589 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server mac */
5590 for (i
= 0; i
< s
->nmacs
; i
++) {
5591 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
5592 s
->csmac_tobe
= s
->maclist
[i
];
5596 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client mac */
5597 for (i
= 0; i
< s
->nmacs
; i
++) {
5598 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
5599 s
->scmac_tobe
= s
->maclist
[i
];
5603 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server compression */
5604 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
5605 const struct ssh_compress
*c
=
5606 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
5607 if (in_commasep_string(c
->name
, str
, len
)) {
5612 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client compression */
5613 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
5614 const struct ssh_compress
*c
=
5615 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
5616 if (in_commasep_string(c
->name
, str
, len
)) {
5621 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server language */
5622 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client language */
5623 s
->ignorepkt
= ssh2_pkt_getbool(pktin
) && !s
->guessok
;
5626 ssh_set_frozen(ssh
, 1);
5627 s
->dlgret
= askalg(ssh
->frontend
, "key-exchange algorithm",
5629 ssh_dialog_callback
, ssh
);
5630 if (s
->dlgret
< 0) {
5634 bombout(("Unexpected data from server while"
5635 " waiting for user response"));
5638 } while (pktin
|| inlen
> 0);
5639 s
->dlgret
= ssh
->user_response
;
5641 ssh_set_frozen(ssh
, 0);
5642 if (s
->dlgret
== 0) {
5643 ssh_disconnect(ssh
, "User aborted at kex warning", NULL
,
5649 if (s
->warn_cscipher
) {
5650 ssh_set_frozen(ssh
, 1);
5651 s
->dlgret
= askalg(ssh
->frontend
,
5652 "client-to-server cipher",
5653 s
->cscipher_tobe
->name
,
5654 ssh_dialog_callback
, ssh
);
5655 if (s
->dlgret
< 0) {
5659 bombout(("Unexpected data from server while"
5660 " waiting for user response"));
5663 } while (pktin
|| inlen
> 0);
5664 s
->dlgret
= ssh
->user_response
;
5666 ssh_set_frozen(ssh
, 0);
5667 if (s
->dlgret
== 0) {
5668 ssh_disconnect(ssh
, "User aborted at cipher warning", NULL
,
5674 if (s
->warn_sccipher
) {
5675 ssh_set_frozen(ssh
, 1);
5676 s
->dlgret
= askalg(ssh
->frontend
,
5677 "server-to-client cipher",
5678 s
->sccipher_tobe
->name
,
5679 ssh_dialog_callback
, ssh
);
5680 if (s
->dlgret
< 0) {
5684 bombout(("Unexpected data from server while"
5685 " waiting for user response"));
5688 } while (pktin
|| inlen
> 0);
5689 s
->dlgret
= ssh
->user_response
;
5691 ssh_set_frozen(ssh
, 0);
5692 if (s
->dlgret
== 0) {
5693 ssh_disconnect(ssh
, "User aborted at cipher warning", NULL
,
5699 ssh
->exhash
= ssh
->kex
->hash
->init();
5700 hash_string(ssh
->kex
->hash
, ssh
->exhash
, ssh
->v_c
, strlen(ssh
->v_c
));
5701 hash_string(ssh
->kex
->hash
, ssh
->exhash
, ssh
->v_s
, strlen(ssh
->v_s
));
5702 hash_string(ssh
->kex
->hash
, ssh
->exhash
,
5703 s
->our_kexinit
, s
->our_kexinitlen
);
5704 sfree(s
->our_kexinit
);
5705 if (pktin
->length
> 5)
5706 hash_string(ssh
->kex
->hash
, ssh
->exhash
,
5707 pktin
->data
+ 5, pktin
->length
- 5);
5709 if (s
->ignorepkt
) /* first_kex_packet_follows */
5710 crWaitUntil(pktin
); /* Ignore packet */
5713 if (ssh
->kex
->main_type
== KEXTYPE_DH
) {
5715 * Work out the number of bits of key we will need from the
5716 * key exchange. We start with the maximum key length of
5722 csbits
= s
->cscipher_tobe
->keylen
;
5723 scbits
= s
->sccipher_tobe
->keylen
;
5724 s
->nbits
= (csbits
> scbits ? csbits
: scbits
);
5726 /* The keys only have hlen-bit entropy, since they're based on
5727 * a hash. So cap the key size at hlen bits. */
5728 if (s
->nbits
> ssh
->kex
->hash
->hlen
* 8)
5729 s
->nbits
= ssh
->kex
->hash
->hlen
* 8;
5732 * If we're doing Diffie-Hellman group exchange, start by
5733 * requesting a group.
5735 if (!ssh
->kex
->pdata
) {
5736 logevent("Doing Diffie-Hellman group exchange");
5737 ssh
->pkt_kctx
= SSH2_PKTCTX_DHGEX
;
5739 * Work out how big a DH group we will need to allow that
5742 s
->pbits
= 512 << ((s
->nbits
- 1) / 64);
5743 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
5744 ssh2_pkt_adduint32(s
->pktout
, s
->pbits
);
5745 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5748 if (pktin
->type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
5749 bombout(("expected key exchange group packet from server"));
5752 s
->p
= ssh2_pkt_getmp(pktin
);
5753 s
->g
= ssh2_pkt_getmp(pktin
);
5754 if (!s
->p
|| !s
->g
) {
5755 bombout(("unable to read mp-ints from incoming group packet"));
5758 ssh
->kex_ctx
= dh_setup_gex(s
->p
, s
->g
);
5759 s
->kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
5760 s
->kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
5762 ssh
->pkt_kctx
= SSH2_PKTCTX_DHGROUP
;
5763 ssh
->kex_ctx
= dh_setup_group(ssh
->kex
);
5764 s
->kex_init_value
= SSH2_MSG_KEXDH_INIT
;
5765 s
->kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
5766 logeventf(ssh
, "Using Diffie-Hellman with standard group \"%s\"",
5767 ssh
->kex
->groupname
);
5770 logeventf(ssh
, "Doing Diffie-Hellman key exchange with hash %s",
5771 ssh
->kex
->hash
->text_name
);
5773 * Now generate and send e for Diffie-Hellman.
5775 set_busy_status(ssh
->frontend
, BUSY_CPU
); /* this can take a while */
5776 s
->e
= dh_create_e(ssh
->kex_ctx
, s
->nbits
* 2);
5777 s
->pktout
= ssh2_pkt_init(s
->kex_init_value
);
5778 ssh2_pkt_addmp(s
->pktout
, s
->e
);
5779 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5781 set_busy_status(ssh
->frontend
, BUSY_WAITING
); /* wait for server */
5783 if (pktin
->type
!= s
->kex_reply_value
) {
5784 bombout(("expected key exchange reply packet from server"));
5787 set_busy_status(ssh
->frontend
, BUSY_CPU
); /* cogitate */
5788 ssh_pkt_getstring(pktin
, &s
->hostkeydata
, &s
->hostkeylen
);
5789 s
->hkey
= ssh
->hostkey
->newkey(s
->hostkeydata
, s
->hostkeylen
);
5790 s
->f
= ssh2_pkt_getmp(pktin
);
5792 bombout(("unable to parse key exchange reply packet"));
5795 ssh_pkt_getstring(pktin
, &s
->sigdata
, &s
->siglen
);
5797 s
->K
= dh_find_K(ssh
->kex_ctx
, s
->f
);
5799 /* We assume everything from now on will be quick, and it might
5800 * involve user interaction. */
5801 set_busy_status(ssh
->frontend
, BUSY_NOT
);
5803 hash_string(ssh
->kex
->hash
, ssh
->exhash
, s
->hostkeydata
, s
->hostkeylen
);
5804 if (!ssh
->kex
->pdata
) {
5805 hash_uint32(ssh
->kex
->hash
, ssh
->exhash
, s
->pbits
);
5806 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->p
);
5807 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->g
);
5809 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->e
);
5810 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->f
);
5812 dh_cleanup(ssh
->kex_ctx
);
5814 if (!ssh
->kex
->pdata
) {
5819 logeventf(ssh
, "Doing RSA key exchange with hash %s",
5820 ssh
->kex
->hash
->text_name
);
5821 ssh
->pkt_kctx
= SSH2_PKTCTX_RSAKEX
;
5823 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
5827 if (pktin
->type
!= SSH2_MSG_KEXRSA_PUBKEY
) {
5828 bombout(("expected RSA public key packet from server"));
5832 ssh_pkt_getstring(pktin
, &s
->hostkeydata
, &s
->hostkeylen
);
5833 hash_string(ssh
->kex
->hash
, ssh
->exhash
,
5834 s
->hostkeydata
, s
->hostkeylen
);
5835 s
->hkey
= ssh
->hostkey
->newkey(s
->hostkeydata
, s
->hostkeylen
);
5839 ssh_pkt_getstring(pktin
, &keydata
, &s
->rsakeylen
);
5840 s
->rsakeydata
= snewn(s
->rsakeylen
, char);
5841 memcpy(s
->rsakeydata
, keydata
, s
->rsakeylen
);
5844 s
->rsakey
= ssh_rsakex_newkey(s
->rsakeydata
, s
->rsakeylen
);
5846 sfree(s
->rsakeydata
);
5847 bombout(("unable to parse RSA public key from server"));
5851 hash_string(ssh
->kex
->hash
, ssh
->exhash
, s
->rsakeydata
, s
->rsakeylen
);
5854 * Next, set up a shared secret K, of precisely KLEN -
5855 * 2*HLEN - 49 bits, where KLEN is the bit length of the
5856 * RSA key modulus and HLEN is the bit length of the hash
5860 int klen
= ssh_rsakex_klen(s
->rsakey
);
5861 int nbits
= klen
- (2*ssh
->kex
->hash
->hlen
*8 + 49);
5863 unsigned char *kstr1
, *kstr2
, *outstr
;
5864 int kstr1len
, kstr2len
, outstrlen
;
5866 s
->K
= bn_power_2(nbits
- 1);
5868 for (i
= 0; i
< nbits
; i
++) {
5870 byte
= random_byte();
5872 bignum_set_bit(s
->K
, i
, (byte
>> (i
& 7)) & 1);
5876 * Encode this as an mpint.
5878 kstr1
= ssh2_mpint_fmt(s
->K
, &kstr1len
);
5879 kstr2
= snewn(kstr2len
= 4 + kstr1len
, unsigned char);
5880 PUT_32BIT(kstr2
, kstr1len
);
5881 memcpy(kstr2
+ 4, kstr1
, kstr1len
);
5884 * Encrypt it with the given RSA key.
5886 outstrlen
= (klen
+ 7) / 8;
5887 outstr
= snewn(outstrlen
, unsigned char);
5888 ssh_rsakex_encrypt(ssh
->kex
->hash
, kstr2
, kstr2len
,
5889 outstr
, outstrlen
, s
->rsakey
);
5892 * And send it off in a return packet.
5894 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET
);
5895 ssh2_pkt_addstring_start(s
->pktout
);
5896 ssh2_pkt_addstring_data(s
->pktout
, (char *)outstr
, outstrlen
);
5897 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5899 hash_string(ssh
->kex
->hash
, ssh
->exhash
, outstr
, outstrlen
);
5906 ssh_rsakex_freekey(s
->rsakey
);
5909 if (pktin
->type
!= SSH2_MSG_KEXRSA_DONE
) {
5910 sfree(s
->rsakeydata
);
5911 bombout(("expected signature packet from server"));
5915 ssh_pkt_getstring(pktin
, &s
->sigdata
, &s
->siglen
);
5917 sfree(s
->rsakeydata
);
5920 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->K
);
5921 assert(ssh
->kex
->hash
->hlen
<= sizeof(s
->exchange_hash
));
5922 ssh
->kex
->hash
->final(ssh
->exhash
, s
->exchange_hash
);
5924 ssh
->kex_ctx
= NULL
;
5927 debug(("Exchange hash is:\n"));
5928 dmemdump(s
->exchange_hash
, ssh
->kex
->hash
->hlen
);
5932 !ssh
->hostkey
->verifysig(s
->hkey
, s
->sigdata
, s
->siglen
,
5933 (char *)s
->exchange_hash
,
5934 ssh
->kex
->hash
->hlen
)) {
5935 bombout(("Server's host key did not match the signature supplied"));
5940 * Authenticate remote host: verify host key. (We've already
5941 * checked the signature of the exchange hash.)
5943 s
->keystr
= ssh
->hostkey
->fmtkey(s
->hkey
);
5944 s
->fingerprint
= ssh
->hostkey
->fingerprint(s
->hkey
);
5945 ssh_set_frozen(ssh
, 1);
5946 s
->dlgret
= verify_ssh_host_key(ssh
->frontend
,
5947 ssh
->savedhost
, ssh
->savedport
,
5948 ssh
->hostkey
->keytype
, s
->keystr
,
5950 ssh_dialog_callback
, ssh
);
5951 if (s
->dlgret
< 0) {
5955 bombout(("Unexpected data from server while waiting"
5956 " for user host key response"));
5959 } while (pktin
|| inlen
> 0);
5960 s
->dlgret
= ssh
->user_response
;
5962 ssh_set_frozen(ssh
, 0);
5963 if (s
->dlgret
== 0) {
5964 ssh_disconnect(ssh
, "User aborted at host key verification", NULL
,
5968 if (!s
->got_session_id
) { /* don't bother logging this in rekeys */
5969 logevent("Host key fingerprint is:");
5970 logevent(s
->fingerprint
);
5972 sfree(s
->fingerprint
);
5974 ssh
->hostkey
->freekey(s
->hkey
);
5977 * The exchange hash from the very first key exchange is also
5978 * the session id, used in session key construction and
5981 if (!s
->got_session_id
) {
5982 assert(sizeof(s
->exchange_hash
) <= sizeof(ssh
->v2_session_id
));
5983 memcpy(ssh
->v2_session_id
, s
->exchange_hash
,
5984 sizeof(s
->exchange_hash
));
5985 ssh
->v2_session_id_len
= ssh
->kex
->hash
->hlen
;
5986 assert(ssh
->v2_session_id_len
<= sizeof(ssh
->v2_session_id
));
5987 s
->got_session_id
= TRUE
;
5991 * Send SSH2_MSG_NEWKEYS.
5993 s
->pktout
= ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
5994 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5995 ssh
->outgoing_data_size
= 0; /* start counting from here */
5998 * We've sent client NEWKEYS, so create and initialise
5999 * client-to-server session keys.
6001 if (ssh
->cs_cipher_ctx
)
6002 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
6003 ssh
->cscipher
= s
->cscipher_tobe
;
6004 ssh
->cs_cipher_ctx
= ssh
->cscipher
->make_context();
6006 if (ssh
->cs_mac_ctx
)
6007 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
6008 ssh
->csmac
= s
->csmac_tobe
;
6009 ssh
->cs_mac_ctx
= ssh
->csmac
->make_context();
6011 if (ssh
->cs_comp_ctx
)
6012 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
6013 ssh
->cscomp
= s
->cscomp_tobe
;
6014 ssh
->cs_comp_ctx
= ssh
->cscomp
->compress_init();
6017 * Set IVs on client-to-server keys. Here we use the exchange
6018 * hash from the _first_ key exchange.
6021 unsigned char keyspace
[SSH2_KEX_MAX_HASH_LEN
* SSH2_MKKEY_ITERS
];
6022 assert(sizeof(keyspace
) >= ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6023 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'C',keyspace
);
6024 assert((ssh
->cscipher
->keylen
+7) / 8 <=
6025 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6026 ssh
->cscipher
->setkey(ssh
->cs_cipher_ctx
, keyspace
);
6027 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'A',keyspace
);
6028 assert(ssh
->cscipher
->blksize
<=
6029 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6030 ssh
->cscipher
->setiv(ssh
->cs_cipher_ctx
, keyspace
);
6031 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'E',keyspace
);
6032 assert(ssh
->csmac
->len
<=
6033 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6034 ssh
->csmac
->setkey(ssh
->cs_mac_ctx
, keyspace
);
6035 memset(keyspace
, 0, sizeof(keyspace
));
6038 logeventf(ssh
, "Initialised %.200s client->server encryption",
6039 ssh
->cscipher
->text_name
);
6040 logeventf(ssh
, "Initialised %.200s client->server MAC algorithm",
6041 ssh
->csmac
->text_name
);
6042 if (ssh
->cscomp
->text_name
)
6043 logeventf(ssh
, "Initialised %s compression",
6044 ssh
->cscomp
->text_name
);
6047 * Now our end of the key exchange is complete, we can send all
6048 * our queued higher-layer packets.
6050 ssh
->queueing
= FALSE
;
6051 ssh2_pkt_queuesend(ssh
);
6054 * Expect SSH2_MSG_NEWKEYS from server.
6057 if (pktin
->type
!= SSH2_MSG_NEWKEYS
) {
6058 bombout(("expected new-keys packet from server"));
6061 ssh
->incoming_data_size
= 0; /* start counting from here */
6064 * We've seen server NEWKEYS, so create and initialise
6065 * server-to-client session keys.
6067 if (ssh
->sc_cipher_ctx
)
6068 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
6069 ssh
->sccipher
= s
->sccipher_tobe
;
6070 ssh
->sc_cipher_ctx
= ssh
->sccipher
->make_context();
6072 if (ssh
->sc_mac_ctx
)
6073 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
6074 ssh
->scmac
= s
->scmac_tobe
;
6075 ssh
->sc_mac_ctx
= ssh
->scmac
->make_context();
6077 if (ssh
->sc_comp_ctx
)
6078 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
6079 ssh
->sccomp
= s
->sccomp_tobe
;
6080 ssh
->sc_comp_ctx
= ssh
->sccomp
->decompress_init();
6083 * Set IVs on server-to-client keys. Here we use the exchange
6084 * hash from the _first_ key exchange.
6087 unsigned char keyspace
[SSH2_KEX_MAX_HASH_LEN
* SSH2_MKKEY_ITERS
];
6088 assert(sizeof(keyspace
) >= ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6089 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'D',keyspace
);
6090 assert((ssh
->sccipher
->keylen
+7) / 8 <=
6091 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6092 ssh
->sccipher
->setkey(ssh
->sc_cipher_ctx
, keyspace
);
6093 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'B',keyspace
);
6094 assert(ssh
->sccipher
->blksize
<=
6095 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6096 ssh
->sccipher
->setiv(ssh
->sc_cipher_ctx
, keyspace
);
6097 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'F',keyspace
);
6098 assert(ssh
->scmac
->len
<=
6099 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6100 ssh
->scmac
->setkey(ssh
->sc_mac_ctx
, keyspace
);
6101 memset(keyspace
, 0, sizeof(keyspace
));
6103 logeventf(ssh
, "Initialised %.200s server->client encryption",
6104 ssh
->sccipher
->text_name
);
6105 logeventf(ssh
, "Initialised %.200s server->client MAC algorithm",
6106 ssh
->scmac
->text_name
);
6107 if (ssh
->sccomp
->text_name
)
6108 logeventf(ssh
, "Initialised %s decompression",
6109 ssh
->sccomp
->text_name
);
6112 * Free shared secret.
6117 * Key exchange is over. Loop straight back round if we have a
6118 * deferred rekey reason.
6120 if (ssh
->deferred_rekey_reason
) {
6121 logevent(ssh
->deferred_rekey_reason
);
6123 ssh
->deferred_rekey_reason
= NULL
;
6124 goto begin_key_exchange
;
6128 * Otherwise, schedule a timer for our next rekey.
6130 ssh
->kex_in_progress
= FALSE
;
6131 ssh
->last_rekey
= GETTICKCOUNT();
6132 if (ssh
->cfg
.ssh_rekey_time
!= 0)
6133 ssh
->next_rekey
= schedule_timer(ssh
->cfg
.ssh_rekey_time
*60*TICKSPERSEC
,
6137 * If this is the first key exchange phase, we must pass the
6138 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
6139 * wants to see it but because it will need time to initialise
6140 * itself before it sees an actual packet. In subsequent key
6141 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
6142 * it would only confuse the layer above.
6144 if (s
->activated_authconn
) {
6147 s
->activated_authconn
= TRUE
;
6150 * Now we're encrypting. Begin returning 1 to the protocol main
6151 * function so that other things can run on top of the
6152 * transport. If we ever see a KEXINIT, we must go back to the
6155 * We _also_ go back to the start if we see pktin==NULL and
6156 * inlen==-1, because this is a special signal meaning
6157 * `initiate client-driven rekey', and `in' contains a message
6158 * giving the reason for the rekey.
6160 while (!((pktin
&& pktin
->type
== SSH2_MSG_KEXINIT
) ||
6161 (!pktin
&& inlen
== -1))) {
6166 logevent("Server initiated key re-exchange");
6169 * Special case: if the server bug is set that doesn't
6170 * allow rekeying, we give a different log message and
6171 * continue waiting. (If such a server _initiates_ a rekey,
6172 * we process it anyway!)
6174 if ((ssh
->remote_bugs
& BUG_SSH2_REKEY
)) {
6175 logeventf(ssh
, "Server bug prevents key re-exchange (%s)",
6177 /* Reset the counters, so that at least this message doesn't
6178 * hit the event log _too_ often. */
6179 ssh
->outgoing_data_size
= 0;
6180 ssh
->incoming_data_size
= 0;
6181 if (ssh
->cfg
.ssh_rekey_time
!= 0) {
6183 schedule_timer(ssh
->cfg
.ssh_rekey_time
*60*TICKSPERSEC
,
6186 goto wait_for_rekey
; /* this is utterly horrid */
6188 logeventf(ssh
, "Initiating key re-exchange (%s)", (char *)in
);
6191 goto begin_key_exchange
;
6197 * Add data to an SSH-2 channel output buffer.
6199 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
6202 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
6206 * Attempt to send data on an SSH-2 channel.
6208 static int ssh2_try_send(struct ssh_channel
*c
)
6211 struct Packet
*pktout
;
6213 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
6216 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
6217 if ((unsigned)len
> c
->v
.v2
.remwindow
)
6218 len
= c
->v
.v2
.remwindow
;
6219 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
6220 len
= c
->v
.v2
.remmaxpkt
;
6221 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
6222 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6223 ssh2_pkt_addstring_start(pktout
);
6224 dont_log_data(ssh
, pktout
, PKTLOG_OMIT
);
6225 ssh2_pkt_addstring_data(pktout
, data
, len
);
6226 end_log_omission(ssh
, pktout
);
6227 ssh2_pkt_send(ssh
, pktout
);
6228 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
6229 c
->v
.v2
.remwindow
-= len
;
6233 * After having sent as much data as we can, return the amount
6236 return bufchain_size(&c
->v
.v2
.outbuffer
);
6239 static void ssh2_try_send_and_unthrottle(struct ssh_channel
*c
)
6243 return; /* don't send on closing channels */
6244 bufsize
= ssh2_try_send(c
);
6247 case CHAN_MAINSESSION
:
6248 /* stdin need not receive an unthrottle
6249 * notification since it will be polled */
6252 x11_unthrottle(c
->u
.x11
.s
);
6255 /* agent sockets are request/response and need no
6256 * buffer management */
6259 pfd_unthrottle(c
->u
.pfd
.s
);
6266 * Set up most of a new ssh_channel for SSH-2.
6268 static void ssh2_channel_init(struct ssh_channel
*c
)
6271 c
->localid
= alloc_channel_id(ssh
);
6273 c
->throttling_conn
= FALSE
;
6274 c
->v
.v2
.locwindow
= c
->v
.v2
.locmaxwin
= c
->v
.v2
.remlocwin
=
6275 ssh
->cfg
.ssh_simple ? OUR_V2_BIGWIN
: OUR_V2_WINSIZE
;
6276 c
->v
.v2
.winadj_head
= c
->v
.v2
.winadj_tail
= NULL
;
6277 c
->v
.v2
.throttle_state
= UNTHROTTLED
;
6278 bufchain_init(&c
->v
.v2
.outbuffer
);
6282 * Potentially enlarge the window on an SSH-2 channel.
6284 static void ssh2_set_window(struct ssh_channel
*c
, int newwin
)
6289 * Never send WINDOW_ADJUST for a channel that the remote side
6290 * already thinks it's closed; there's no point, since it won't
6291 * be sending any more data anyway.
6297 * If the remote end has a habit of ignoring maxpkt, limit the
6298 * window so that it has no choice (assuming it doesn't ignore the
6301 if ((ssh
->remote_bugs
& BUG_SSH2_MAXPKT
) && newwin
> OUR_V2_MAXPKT
)
6302 newwin
= OUR_V2_MAXPKT
;
6306 * Only send a WINDOW_ADJUST if there's significantly more window
6307 * available than the other end thinks there is. This saves us
6308 * sending a WINDOW_ADJUST for every character in a shell session.
6310 * "Significant" is arbitrarily defined as half the window size.
6312 if (newwin
/ 2 >= c
->v
.v2
.locwindow
) {
6313 struct Packet
*pktout
;
6317 * In order to keep track of how much window the client
6318 * actually has available, we'd like it to acknowledge each
6319 * WINDOW_ADJUST. We can't do that directly, so we accompany
6320 * it with a CHANNEL_REQUEST that has to be acknowledged.
6322 * This is only necessary if we're opening the window wide.
6323 * If we're not, then throughput is being constrained by
6324 * something other than the maximum window size anyway.
6326 * We also only send this if the main channel has finished its
6327 * initial CHANNEL_REQUESTs and installed the default
6328 * CHANNEL_FAILURE handler, so as not to risk giving it
6329 * unexpected CHANNEL_FAILUREs.
6331 if (newwin
== c
->v
.v2
.locmaxwin
&&
6332 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_FAILURE
]) {
6333 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
6334 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6335 ssh2_pkt_addstring(pktout
, "winadj@putty.projects.tartarus.org");
6336 ssh2_pkt_addbool(pktout
, TRUE
);
6337 ssh2_pkt_send(ssh
, pktout
);
6340 * CHANNEL_FAILURE doesn't come with any indication of
6341 * what message caused it, so we have to keep track of the
6342 * outstanding CHANNEL_REQUESTs ourselves.
6344 wa
= snew(struct winadj
);
6345 wa
->size
= newwin
- c
->v
.v2
.locwindow
;
6347 if (!c
->v
.v2
.winadj_head
)
6348 c
->v
.v2
.winadj_head
= wa
;
6350 c
->v
.v2
.winadj_tail
->next
= wa
;
6351 c
->v
.v2
.winadj_tail
= wa
;
6352 if (c
->v
.v2
.throttle_state
!= UNTHROTTLED
)
6353 c
->v
.v2
.throttle_state
= UNTHROTTLING
;
6355 /* Pretend the WINDOW_ADJUST was acked immediately. */
6356 c
->v
.v2
.remlocwin
= newwin
;
6357 c
->v
.v2
.throttle_state
= THROTTLED
;
6359 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
6360 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6361 ssh2_pkt_adduint32(pktout
, newwin
- c
->v
.v2
.locwindow
);
6362 ssh2_pkt_send(ssh
, pktout
);
6363 c
->v
.v2
.locwindow
= newwin
;
6368 * Find the channel associated with a message. If there's no channel,
6369 * or it's not properly open, make a noise about it and return NULL.
6371 static struct ssh_channel
*ssh2_channel_msg(Ssh ssh
, struct Packet
*pktin
)
6373 unsigned localid
= ssh_pkt_getuint32(pktin
);
6374 struct ssh_channel
*c
;
6376 c
= find234(ssh
->channels
, &localid
, ssh_channelfind
);
6378 (c
->halfopen
&& pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
&&
6379 pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_FAILURE
)) {
6380 char *buf
= dupprintf("Received %s for %s channel %u",
6381 ssh2_pkt_type(ssh
->pkt_kctx
, ssh
->pkt_actx
,
6383 c ?
"half-open" : "nonexistent", localid
);
6384 ssh_disconnect(ssh
, NULL
, buf
, SSH2_DISCONNECT_PROTOCOL_ERROR
, FALSE
);
6391 static void ssh2_msg_channel_success(Ssh ssh
, struct Packet
*pktin
)
6394 * This should never get called. All channel requests are either
6395 * sent with want_reply false or are sent before this handler gets
6398 struct ssh_channel
*c
;
6401 c
= ssh2_channel_msg(ssh
, pktin
);
6404 wa
= c
->v
.v2
.winadj_head
;
6406 ssh_disconnect(ssh
, NULL
, "Received SSH_MSG_CHANNEL_SUCCESS for "
6407 "\"winadj@putty.projects.tartarus.org\"",
6408 SSH2_DISCONNECT_PROTOCOL_ERROR
, FALSE
);
6410 ssh_disconnect(ssh
, NULL
,
6411 "Received unsolicited SSH_MSG_CHANNEL_SUCCESS",
6412 SSH2_DISCONNECT_PROTOCOL_ERROR
, FALSE
);
6415 static void ssh2_msg_channel_failure(Ssh ssh
, struct Packet
*pktin
)
6418 * The only time this should get called is for "winadj@putty"
6419 * messages sent above. All other channel requests are either
6420 * sent with want_reply false or are sent before this handler gets
6423 struct ssh_channel
*c
;
6426 c
= ssh2_channel_msg(ssh
, pktin
);
6429 wa
= c
->v
.v2
.winadj_head
;
6431 ssh_disconnect(ssh
, NULL
,
6432 "Received unsolicited SSH_MSG_CHANNEL_FAILURE",
6433 SSH2_DISCONNECT_PROTOCOL_ERROR
, FALSE
);
6436 c
->v
.v2
.winadj_head
= wa
->next
;
6437 c
->v
.v2
.remlocwin
+= wa
->size
;
6440 * winadj messages are only sent when the window is fully open, so
6441 * if we get an ack of one, we know any pending unthrottle is
6444 if (c
->v
.v2
.throttle_state
== UNTHROTTLING
)
6445 c
->v
.v2
.throttle_state
= UNTHROTTLED
;
6448 static void ssh2_msg_channel_window_adjust(Ssh ssh
, struct Packet
*pktin
)
6450 struct ssh_channel
*c
;
6451 c
= ssh2_channel_msg(ssh
, pktin
);
6455 c
->v
.v2
.remwindow
+= ssh_pkt_getuint32(pktin
);
6456 ssh2_try_send_and_unthrottle(c
);
6460 static void ssh2_msg_channel_data(Ssh ssh
, struct Packet
*pktin
)
6464 struct ssh_channel
*c
;
6465 c
= ssh2_channel_msg(ssh
, pktin
);
6468 if (pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
6469 ssh_pkt_getuint32(pktin
) != SSH2_EXTENDED_DATA_STDERR
)
6470 return; /* extended but not stderr */
6471 ssh_pkt_getstring(pktin
, &data
, &length
);
6474 c
->v
.v2
.locwindow
-= length
;
6475 c
->v
.v2
.remlocwin
-= length
;
6477 case CHAN_MAINSESSION
:
6479 from_backend(ssh
->frontend
, pktin
->type
==
6480 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
6484 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
6487 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
6490 while (length
> 0) {
6491 if (c
->u
.a
.lensofar
< 4) {
6492 unsigned int l
= min(4 - c
->u
.a
.lensofar
,
6494 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
6498 c
->u
.a
.lensofar
+= l
;
6500 if (c
->u
.a
.lensofar
== 4) {
6502 4 + GET_32BIT(c
->u
.a
.msglen
);
6503 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
6505 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
6507 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
6509 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
6511 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
6515 c
->u
.a
.lensofar
+= l
;
6517 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
6520 if (agent_query(c
->u
.a
.message
,
6523 ssh_agentf_callback
, c
))
6524 ssh_agentf_callback(c
, reply
, replylen
);
6525 sfree(c
->u
.a
.message
);
6526 c
->u
.a
.lensofar
= 0;
6533 * If it looks like the remote end hit the end of its window,
6534 * and we didn't want it to do that, think about using a
6537 if (c
->v
.v2
.remlocwin
<= 0 && c
->v
.v2
.throttle_state
== UNTHROTTLED
&&
6538 c
->v
.v2
.locmaxwin
< 0x40000000)
6539 c
->v
.v2
.locmaxwin
+= OUR_V2_WINSIZE
;
6541 * If we are not buffering too much data,
6542 * enlarge the window again at the remote side.
6543 * If we are buffering too much, we may still
6544 * need to adjust the window if the server's
6547 ssh2_set_window(c
, bufsize
< c
->v
.v2
.locmaxwin ?
6548 c
->v
.v2
.locmaxwin
- bufsize
: 0);
6550 * If we're either buffering way too much data, or if we're
6551 * buffering anything at all and we're in "simple" mode,
6552 * throttle the whole channel.
6554 if ((bufsize
> c
->v
.v2
.locmaxwin
||
6555 (ssh
->cfg
.ssh_simple
&& bufsize
> 0)) &&
6556 !c
->throttling_conn
) {
6557 c
->throttling_conn
= 1;
6558 ssh_throttle_conn(ssh
, +1);
6563 static void ssh2_msg_channel_eof(Ssh ssh
, struct Packet
*pktin
)
6565 struct ssh_channel
*c
;
6567 c
= ssh2_channel_msg(ssh
, pktin
);
6571 if (c
->type
== CHAN_X11
) {
6573 * Remote EOF on an X11 channel means we should
6574 * wrap up and close the channel ourselves.
6576 x11_close(c
->u
.x11
.s
);
6578 } else if (c
->type
== CHAN_AGENT
) {
6580 } else if (c
->type
== CHAN_SOCKDATA
) {
6581 pfd_close(c
->u
.pfd
.s
);
6586 static void ssh2_msg_channel_close(Ssh ssh
, struct Packet
*pktin
)
6588 struct ssh_channel
*c
;
6589 struct Packet
*pktout
;
6591 c
= ssh2_channel_msg(ssh
, pktin
);
6594 /* Do pre-close processing on the channel. */
6596 case CHAN_MAINSESSION
:
6597 ssh
->mainchan
= NULL
;
6598 update_specials_menu(ssh
->frontend
);
6601 if (c
->u
.x11
.s
!= NULL
)
6602 x11_close(c
->u
.x11
.s
);
6609 if (c
->u
.pfd
.s
!= NULL
)
6610 pfd_close(c
->u
.pfd
.s
);
6614 if (c
->closes
== 0) {
6615 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
6616 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6617 ssh2_pkt_send(ssh
, pktout
);
6619 del234(ssh
->channels
, c
);
6620 bufchain_clear(&c
->v
.v2
.outbuffer
);
6624 * See if that was the last channel left open.
6625 * (This is only our termination condition if we're
6626 * not running in -N mode.)
6628 if (!ssh
->cfg
.ssh_no_shell
&& count234(ssh
->channels
) == 0) {
6630 * We used to send SSH_MSG_DISCONNECT here,
6631 * because I'd believed that _every_ conforming
6632 * SSH-2 connection had to end with a disconnect
6633 * being sent by at least one side; apparently
6634 * I was wrong and it's perfectly OK to
6635 * unceremoniously slam the connection shut
6636 * when you're done, and indeed OpenSSH feels
6637 * this is more polite than sending a
6638 * DISCONNECT. So now we don't.
6640 ssh_disconnect(ssh
, "All channels closed", NULL
, 0, TRUE
);
6644 static void ssh2_msg_channel_open_confirmation(Ssh ssh
, struct Packet
*pktin
)
6646 struct ssh_channel
*c
;
6647 struct Packet
*pktout
;
6649 c
= ssh2_channel_msg(ssh
, pktin
);
6652 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
6653 return; /* dunno why they're confirming this */
6654 c
->remoteid
= ssh_pkt_getuint32(pktin
);
6655 c
->halfopen
= FALSE
;
6656 c
->type
= CHAN_SOCKDATA
;
6657 c
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
6658 c
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
6660 pfd_confirm(c
->u
.pfd
.s
);
6663 * We have a pending close on this channel,
6664 * which we decided on before the server acked
6665 * the channel open. So now we know the
6666 * remoteid, we can close it again.
6668 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
6669 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6670 ssh2_pkt_send(ssh
, pktout
);
6674 static void ssh2_msg_channel_open_failure(Ssh ssh
, struct Packet
*pktin
)
6676 static const char *const reasons
[] = {
6677 "<unknown reason code>",
6678 "Administratively prohibited",
6680 "Unknown channel type",
6681 "Resource shortage",
6683 unsigned reason_code
;
6684 char *reason_string
;
6686 struct ssh_channel
*c
;
6687 c
= ssh2_channel_msg(ssh
, pktin
);
6690 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
6691 return; /* dunno why they're failing this */
6693 reason_code
= ssh_pkt_getuint32(pktin
);
6694 if (reason_code
>= lenof(reasons
))
6695 reason_code
= 0; /* ensure reasons[reason_code] in range */
6696 ssh_pkt_getstring(pktin
, &reason_string
, &reason_length
);
6697 logeventf(ssh
, "Forwarded connection refused by server: %s [%.*s]",
6698 reasons
[reason_code
], reason_length
, reason_string
);
6700 pfd_close(c
->u
.pfd
.s
);
6702 del234(ssh
->channels
, c
);
6706 static void ssh2_msg_channel_request(Ssh ssh
, struct Packet
*pktin
)
6709 int typelen
, want_reply
;
6710 int reply
= SSH2_MSG_CHANNEL_FAILURE
; /* default */
6711 struct ssh_channel
*c
;
6712 struct Packet
*pktout
;
6714 c
= ssh2_channel_msg(ssh
, pktin
);
6717 ssh_pkt_getstring(pktin
, &type
, &typelen
);
6718 want_reply
= ssh2_pkt_getbool(pktin
);
6721 * Having got the channel number, we now look at
6722 * the request type string to see if it's something
6725 if (c
== ssh
->mainchan
) {
6727 * We recognise "exit-status" and "exit-signal" on
6728 * the primary channel.
6730 if (typelen
== 11 &&
6731 !memcmp(type
, "exit-status", 11)) {
6733 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
6734 logeventf(ssh
, "Server sent command exit status %d",
6736 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
6738 } else if (typelen
== 11 &&
6739 !memcmp(type
, "exit-signal", 11)) {
6741 int is_plausible
= TRUE
, is_int
= FALSE
;
6742 char *fmt_sig
= "", *fmt_msg
= "";
6744 int msglen
= 0, core
= FALSE
;
6745 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
6746 * provide an `int' for the signal, despite its
6747 * having been a `string' in the drafts of RFC 4254 since at
6748 * least 2001. (Fixed in session.c 1.147.) Try to
6749 * infer which we can safely parse it as. */
6751 unsigned char *p
= pktin
->body
+
6753 long len
= pktin
->length
- pktin
->savedpos
;
6754 unsigned long num
= GET_32BIT(p
); /* what is it? */
6755 /* If it's 0, it hardly matters; assume string */
6759 int maybe_int
= FALSE
, maybe_str
= FALSE
;
6760 #define CHECK_HYPOTHESIS(offset, result) \
6763 if (q >= 0 && q+4 <= len) { \
6764 q = q + 4 + GET_32BIT(p+q); \
6765 if (q >= 0 && q+4 <= len && \
6766 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
6770 CHECK_HYPOTHESIS(4+1, maybe_int
);
6771 CHECK_HYPOTHESIS(4+num
+1, maybe_str
);
6772 #undef CHECK_HYPOTHESIS
6773 if (maybe_int
&& !maybe_str
)
6775 else if (!maybe_int
&& maybe_str
)
6778 /* Crikey. Either or neither. Panic. */
6779 is_plausible
= FALSE
;
6782 ssh
->exitcode
= 128; /* means `unknown signal' */
6785 /* Old non-standard OpenSSH. */
6786 int signum
= ssh_pkt_getuint32(pktin
);
6787 fmt_sig
= dupprintf(" %d", signum
);
6788 ssh
->exitcode
= 128 + signum
;
6790 /* As per RFC 4254. */
6793 ssh_pkt_getstring(pktin
, &sig
, &siglen
);
6794 /* Signal name isn't supposed to be blank, but
6795 * let's cope gracefully if it is. */
6797 fmt_sig
= dupprintf(" \"%.*s\"",
6802 * Really hideous method of translating the
6803 * signal description back into a locally
6804 * meaningful number.
6809 #define TRANSLATE_SIGNAL(s) \
6810 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
6811 ssh->exitcode = 128 + SIG ## s
6813 TRANSLATE_SIGNAL(ABRT
);
6816 TRANSLATE_SIGNAL(ALRM
);
6819 TRANSLATE_SIGNAL(FPE
);
6822 TRANSLATE_SIGNAL(HUP
);
6825 TRANSLATE_SIGNAL(ILL
);
6828 TRANSLATE_SIGNAL(INT
);
6831 TRANSLATE_SIGNAL(KILL
);
6834 TRANSLATE_SIGNAL(PIPE
);
6837 TRANSLATE_SIGNAL(QUIT
);
6840 TRANSLATE_SIGNAL(SEGV
);
6843 TRANSLATE_SIGNAL(TERM
);
6846 TRANSLATE_SIGNAL(USR1
);
6849 TRANSLATE_SIGNAL(USR2
);
6851 #undef TRANSLATE_SIGNAL
6853 ssh
->exitcode
= 128;
6855 core
= ssh2_pkt_getbool(pktin
);
6856 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
6858 fmt_msg
= dupprintf(" (\"%.*s\")", msglen
, msg
);
6860 /* ignore lang tag */
6861 } /* else don't attempt to parse */
6862 logeventf(ssh
, "Server exited on signal%s%s%s",
6863 fmt_sig
, core ?
" (core dumped)" : "",
6865 if (*fmt_sig
) sfree(fmt_sig
);
6866 if (*fmt_msg
) sfree(fmt_msg
);
6867 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
6872 * This is a channel request we don't know
6873 * about, so we now either ignore the request
6874 * or respond with CHANNEL_FAILURE, depending
6877 reply
= SSH2_MSG_CHANNEL_FAILURE
;
6880 pktout
= ssh2_pkt_init(reply
);
6881 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6882 ssh2_pkt_send(ssh
, pktout
);
6886 static void ssh2_msg_global_request(Ssh ssh
, struct Packet
*pktin
)
6889 int typelen
, want_reply
;
6890 struct Packet
*pktout
;
6892 ssh_pkt_getstring(pktin
, &type
, &typelen
);
6893 want_reply
= ssh2_pkt_getbool(pktin
);
6896 * We currently don't support any global requests
6897 * at all, so we either ignore the request or
6898 * respond with REQUEST_FAILURE, depending on
6902 pktout
= ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE
);
6903 ssh2_pkt_send(ssh
, pktout
);
6907 static void ssh2_msg_channel_open(Ssh ssh
, struct Packet
*pktin
)
6915 struct ssh_channel
*c
;
6916 unsigned remid
, winsize
, pktsize
;
6917 struct Packet
*pktout
;
6919 ssh_pkt_getstring(pktin
, &type
, &typelen
);
6920 c
= snew(struct ssh_channel
);
6923 remid
= ssh_pkt_getuint32(pktin
);
6924 winsize
= ssh_pkt_getuint32(pktin
);
6925 pktsize
= ssh_pkt_getuint32(pktin
);
6927 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
6930 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
6931 addrstr
= snewn(peeraddrlen
+1, char);
6932 memcpy(addrstr
, peeraddr
, peeraddrlen
);
6933 addrstr
[peeraddrlen
] = '\0';
6934 peerport
= ssh_pkt_getuint32(pktin
);
6936 logeventf(ssh
, "Received X11 connect request from %s:%d",
6939 if (!ssh
->X11_fwd_enabled
)
6940 error
= "X11 forwarding is not enabled";
6941 else if (x11_init(&c
->u
.x11
.s
, ssh
->cfg
.x11_display
, c
,
6942 ssh
->x11auth
, addrstr
, peerport
,
6943 &ssh
->cfg
) != NULL
) {
6944 error
= "Unable to open an X11 connection";
6946 logevent("Opening X11 forward connection succeeded");
6951 } else if (typelen
== 15 &&
6952 !memcmp(type
, "forwarded-tcpip", 15)) {
6953 struct ssh_rportfwd pf
, *realpf
;
6956 ssh_pkt_getstring(pktin
, &dummy
, &dummylen
);/* skip address */
6957 pf
.sport
= ssh_pkt_getuint32(pktin
);
6958 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
6959 peerport
= ssh_pkt_getuint32(pktin
);
6960 realpf
= find234(ssh
->rportfwds
, &pf
, NULL
);
6961 logeventf(ssh
, "Received remote port %d open request "
6962 "from %s:%d", pf
.sport
, peeraddr
, peerport
);
6963 if (realpf
== NULL
) {
6964 error
= "Remote port is not recognised";
6966 const char *e
= pfd_newconnect(&c
->u
.pfd
.s
,
6970 realpf
->pfrec
->addressfamily
);
6971 logeventf(ssh
, "Attempting to forward remote port to "
6972 "%s:%d", realpf
->dhost
, realpf
->dport
);
6974 logeventf(ssh
, "Port open failed: %s", e
);
6975 error
= "Port open failed";
6977 logevent("Forwarded port opened successfully");
6978 c
->type
= CHAN_SOCKDATA
;
6981 } else if (typelen
== 22 &&
6982 !memcmp(type
, "auth-agent@openssh.com", 22)) {
6983 if (!ssh
->agentfwd_enabled
)
6984 error
= "Agent forwarding is not enabled";
6986 c
->type
= CHAN_AGENT
; /* identify channel type */
6987 c
->u
.a
.lensofar
= 0;
6990 error
= "Unsupported channel type requested";
6993 c
->remoteid
= remid
;
6994 c
->halfopen
= FALSE
;
6996 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
6997 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6998 ssh2_pkt_adduint32(pktout
, SSH2_OPEN_CONNECT_FAILED
);
6999 ssh2_pkt_addstring(pktout
, error
);
7000 ssh2_pkt_addstring(pktout
, "en"); /* language tag */
7001 ssh2_pkt_send(ssh
, pktout
);
7002 logeventf(ssh
, "Rejected channel open: %s", error
);
7005 ssh2_channel_init(c
);
7006 c
->v
.v2
.remwindow
= winsize
;
7007 c
->v
.v2
.remmaxpkt
= pktsize
;
7008 add234(ssh
->channels
, c
);
7009 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
7010 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
7011 ssh2_pkt_adduint32(pktout
, c
->localid
);
7012 ssh2_pkt_adduint32(pktout
, c
->v
.v2
.locwindow
);
7013 ssh2_pkt_adduint32(pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
7014 ssh2_pkt_send(ssh
, pktout
);
7019 * Buffer banner messages for later display at some convenient point.
7021 static void ssh2_msg_userauth_banner(Ssh ssh
, struct Packet
*pktin
)
7023 /* Arbitrary limit to prevent unbounded inflation of buffer */
7024 if (bufchain_size(&ssh
->banner
) <= 131072) {
7025 char *banner
= NULL
;
7027 ssh_pkt_getstring(pktin
, &banner
, &size
);
7029 bufchain_add(&ssh
->banner
, banner
, size
);
7033 /* Helper function to deal with sending tty modes for "pty-req" */
7034 static void ssh2_send_ttymode(void *data
, char *mode
, char *val
)
7036 struct Packet
*pktout
= (struct Packet
*)data
;
7038 unsigned int arg
= 0;
7039 while (strcmp(mode
, ssh_ttymodes
[i
].mode
) != 0) i
++;
7040 if (i
== lenof(ssh_ttymodes
)) return;
7041 switch (ssh_ttymodes
[i
].type
) {
7043 arg
= ssh_tty_parse_specchar(val
);
7046 arg
= ssh_tty_parse_boolean(val
);
7049 ssh2_pkt_addbyte(pktout
, ssh_ttymodes
[i
].opcode
);
7050 ssh2_pkt_adduint32(pktout
, arg
);
7054 * Handle the SSH-2 userauth and connection layers.
7056 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
,
7057 struct Packet
*pktin
)
7059 struct do_ssh2_authconn_state
{
7062 AUTH_TYPE_PUBLICKEY
,
7063 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
7064 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
7067 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
7068 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7070 int done_service_req
;
7071 int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
7072 int tried_pubkey_config
, done_agent
;
7075 int kbd_inter_refused
;
7077 prompts_t
*cur_prompt
;
7082 void *publickey_blob
;
7083 int publickey_bloblen
;
7084 int publickey_encrypted
;
7085 char *publickey_algorithm
;
7086 char *publickey_comment
;
7087 unsigned char agent_request
[5], *agent_response
, *agentp
;
7088 int agent_responselen
;
7089 unsigned char *pkblob_in_agent
;
7091 char *pkblob
, *alg
, *commentp
;
7092 int pklen
, alglen
, commentlen
;
7093 int siglen
, retlen
, len
;
7094 char *q
, *agentreq
, *ret
;
7096 int num_env
, env_left
, env_ok
;
7097 struct Packet
*pktout
;
7098 Ssh_gss_ctx gss_ctx
;
7099 Ssh_gss_buf gss_buf
;
7100 Ssh_gss_buf gss_rcvtok
, gss_sndtok
;
7101 Ssh_gss_name gss_srv_name
;
7102 Ssh_gss_stat gss_stat
;
7104 crState(do_ssh2_authconn_state
);
7106 crBegin(ssh
->do_ssh2_authconn_crstate
);
7108 s
->done_service_req
= FALSE
;
7109 s
->we_are_in
= FALSE
;
7110 s
->tried_gssapi
= FALSE
;
7112 if (!ssh
->cfg
.ssh_no_userauth
) {
7114 * Request userauth protocol, and await a response to it.
7116 s
->pktout
= ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
7117 ssh2_pkt_addstring(s
->pktout
, "ssh-userauth");
7118 ssh2_pkt_send(ssh
, s
->pktout
);
7119 crWaitUntilV(pktin
);
7120 if (pktin
->type
== SSH2_MSG_SERVICE_ACCEPT
)
7121 s
->done_service_req
= TRUE
;
7123 if (!s
->done_service_req
) {
7125 * Request connection protocol directly, without authentication.
7127 s
->pktout
= ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
7128 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7129 ssh2_pkt_send(ssh
, s
->pktout
);
7130 crWaitUntilV(pktin
);
7131 if (pktin
->type
== SSH2_MSG_SERVICE_ACCEPT
) {
7132 s
->we_are_in
= TRUE
; /* no auth required */
7134 bombout(("Server refused service request"));
7139 /* Arrange to be able to deal with any BANNERs that come in.
7140 * (We do this now as packets may come in during the next bit.) */
7141 bufchain_init(&ssh
->banner
);
7142 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] =
7143 ssh2_msg_userauth_banner
;
7146 * Misc one-time setup for authentication.
7148 s
->publickey_blob
= NULL
;
7149 if (!s
->we_are_in
) {
7152 * Load the public half of any configured public key file
7155 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
7157 logeventf(ssh
, "Reading private key file \"%.150s\"",
7158 filename_to_str(&ssh
->cfg
.keyfile
));
7159 keytype
= key_type(&ssh
->cfg
.keyfile
);
7160 if (keytype
== SSH_KEYTYPE_SSH2
) {
7163 ssh2_userkey_loadpub(&ssh
->cfg
.keyfile
,
7164 &s
->publickey_algorithm
,
7165 &s
->publickey_bloblen
,
7166 &s
->publickey_comment
, &error
);
7167 if (s
->publickey_blob
) {
7168 s
->publickey_encrypted
=
7169 ssh2_userkey_encrypted(&ssh
->cfg
.keyfile
, NULL
);
7172 logeventf(ssh
, "Unable to load private key (%s)",
7174 msgbuf
= dupprintf("Unable to load private key file "
7175 "\"%.150s\" (%s)\r\n",
7176 filename_to_str(&ssh
->cfg
.keyfile
),
7178 c_write_str(ssh
, msgbuf
);
7183 logeventf(ssh
, "Unable to use this key file (%s)",
7184 key_type_to_str(keytype
));
7185 msgbuf
= dupprintf("Unable to use key file \"%.150s\""
7187 filename_to_str(&ssh
->cfg
.keyfile
),
7188 key_type_to_str(keytype
));
7189 c_write_str(ssh
, msgbuf
);
7191 s
->publickey_blob
= NULL
;
7196 * Find out about any keys Pageant has (but if there's a
7197 * public key configured, filter out all others).
7200 s
->agent_response
= NULL
;
7201 s
->pkblob_in_agent
= NULL
;
7202 if (ssh
->cfg
.tryagent
&& agent_exists()) {
7206 logevent("Pageant is running. Requesting keys.");
7208 /* Request the keys held by the agent. */
7209 PUT_32BIT(s
->agent_request
, 1);
7210 s
->agent_request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
7211 if (!agent_query(s
->agent_request
, 5, &r
, &s
->agent_responselen
,
7212 ssh_agent_callback
, ssh
)) {
7216 bombout(("Unexpected data from server while"
7217 " waiting for agent response"));
7220 } while (pktin
|| inlen
> 0);
7221 r
= ssh
->agent_response
;
7222 s
->agent_responselen
= ssh
->agent_response_len
;
7224 s
->agent_response
= (unsigned char *) r
;
7225 if (s
->agent_response
&& s
->agent_responselen
>= 5 &&
7226 s
->agent_response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
7229 p
= s
->agent_response
+ 5;
7230 s
->nkeys
= GET_32BIT(p
);
7232 logeventf(ssh
, "Pageant has %d SSH-2 keys", s
->nkeys
);
7233 if (s
->publickey_blob
) {
7234 /* See if configured key is in agent. */
7235 for (keyi
= 0; keyi
< s
->nkeys
; keyi
++) {
7236 s
->pklen
= GET_32BIT(p
);
7237 if (s
->pklen
== s
->publickey_bloblen
&&
7238 !memcmp(p
+4, s
->publickey_blob
,
7239 s
->publickey_bloblen
)) {
7240 logeventf(ssh
, "Pageant key #%d matches "
7241 "configured key file", keyi
);
7243 s
->pkblob_in_agent
= p
;
7247 p
+= GET_32BIT(p
) + 4; /* comment */
7249 if (!s
->pkblob_in_agent
) {
7250 logevent("Configured key file not in Pageant");
7260 * We repeat this whole loop, including the username prompt,
7261 * until we manage a successful authentication. If the user
7262 * types the wrong _password_, they can be sent back to the
7263 * beginning to try another username, if this is configured on.
7264 * (If they specify a username in the config, they are never
7265 * asked, even if they do give a wrong password.)
7267 * I think this best serves the needs of
7269 * - the people who have no configuration, no keys, and just
7270 * want to try repeated (username,password) pairs until they
7271 * type both correctly
7273 * - people who have keys and configuration but occasionally
7274 * need to fall back to passwords
7276 * - people with a key held in Pageant, who might not have
7277 * logged in to a particular machine before; so they want to
7278 * type a username, and then _either_ their key will be
7279 * accepted, _or_ they will type a password. If they mistype
7280 * the username they will want to be able to get back and
7283 s
->username
[0] = '\0';
7284 s
->got_username
= FALSE
;
7285 while (!s
->we_are_in
) {
7289 if (s
->got_username
&& !ssh
->cfg
.change_username
) {
7291 * We got a username last time round this loop, and
7292 * with change_username turned off we don't try to get
7295 } else if (!*ssh
->cfg
.username
) {
7296 int ret
; /* need not be kept over crReturn */
7297 s
->cur_prompt
= new_prompts(ssh
->frontend
);
7298 s
->cur_prompt
->to_server
= TRUE
;
7299 s
->cur_prompt
->name
= dupstr("SSH login name");
7300 add_prompt(s
->cur_prompt
, dupstr("login as: "), TRUE
,
7301 lenof(s
->username
));
7302 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
7305 crWaitUntilV(!pktin
);
7306 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
7311 * get_userpass_input() failed to get a username.
7314 free_prompts(s
->cur_prompt
);
7315 ssh_disconnect(ssh
, "No username provided", NULL
, 0, TRUE
);
7318 memcpy(s
->username
, s
->cur_prompt
->prompts
[0]->result
,
7319 lenof(s
->username
));
7320 free_prompts(s
->cur_prompt
);
7323 strncpy(s
->username
, ssh
->cfg
.username
, sizeof(s
->username
));
7324 s
->username
[sizeof(s
->username
)-1] = '\0';
7325 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
7326 stuff
= dupprintf("Using username \"%s\".\r\n", s
->username
);
7327 c_write_str(ssh
, stuff
);
7331 s
->got_username
= TRUE
;
7334 * Send an authentication request using method "none": (a)
7335 * just in case it succeeds, and (b) so that we know what
7336 * authentication methods we can usefully try next.
7338 ssh
->pkt_actx
= SSH2_PKTCTX_NOAUTH
;
7340 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7341 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7342 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");/* service requested */
7343 ssh2_pkt_addstring(s
->pktout
, "none"); /* method */
7344 ssh2_pkt_send(ssh
, s
->pktout
);
7345 s
->type
= AUTH_TYPE_NONE
;
7347 s
->we_are_in
= FALSE
;
7349 s
->tried_pubkey_config
= FALSE
;
7350 s
->kbd_inter_refused
= FALSE
;
7352 /* Reset agent request state. */
7353 s
->done_agent
= FALSE
;
7354 if (s
->agent_response
) {
7355 if (s
->pkblob_in_agent
) {
7356 s
->agentp
= s
->pkblob_in_agent
;
7358 s
->agentp
= s
->agent_response
+ 5 + 4;
7365 * Wait for the result of the last authentication request.
7368 crWaitUntilV(pktin
);
7370 * Now is a convenient point to spew any banner material
7371 * that we've accumulated. (This should ensure that when
7372 * we exit the auth loop, we haven't any left to deal
7376 int size
= bufchain_size(&ssh
->banner
);
7378 * Don't show the banner if we're operating in
7379 * non-verbose non-interactive mode. (It's probably
7380 * a script, which means nobody will read the
7381 * banner _anyway_, and moreover the printing of
7382 * the banner will screw up processing on the
7383 * output of (say) plink.)
7385 if (size
&& (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
))) {
7386 char *banner
= snewn(size
, char);
7387 bufchain_fetch(&ssh
->banner
, banner
, size
);
7388 c_write_untrusted(ssh
, banner
, size
);
7391 bufchain_clear(&ssh
->banner
);
7393 if (pktin
->type
== SSH2_MSG_USERAUTH_SUCCESS
) {
7394 logevent("Access granted");
7395 s
->we_are_in
= TRUE
;
7399 if (pktin
->type
!= SSH2_MSG_USERAUTH_FAILURE
&& s
->type
!= AUTH_TYPE_GSSAPI
) {
7400 bombout(("Strange packet received during authentication: "
7401 "type %d", pktin
->type
));
7408 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7409 * we can look at the string in it and know what we can
7410 * helpfully try next.
7412 if (pktin
->type
== SSH2_MSG_USERAUTH_FAILURE
) {
7415 ssh_pkt_getstring(pktin
, &methods
, &methlen
);
7416 if (!ssh2_pkt_getbool(pktin
)) {
7418 * We have received an unequivocal Access
7419 * Denied. This can translate to a variety of
7422 * - if we'd just tried "none" authentication,
7423 * it's not worth printing anything at all
7425 * - if we'd just tried a public key _offer_,
7426 * the message should be "Server refused our
7427 * key" (or no message at all if the key
7428 * came from Pageant)
7430 * - if we'd just tried anything else, the
7431 * message really should be "Access denied".
7433 * Additionally, if we'd just tried password
7434 * authentication, we should break out of this
7435 * whole loop so as to go back to the username
7436 * prompt (iff we're configured to allow
7437 * username change attempts).
7439 if (s
->type
== AUTH_TYPE_NONE
) {
7441 } else if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
7442 s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
7443 if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
7444 c_write_str(ssh
, "Server refused our key\r\n");
7445 logevent("Server refused public key");
7446 } else if (s
->type
==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
7447 /* server declined keyboard-interactive; ignore */
7449 c_write_str(ssh
, "Access denied\r\n");
7450 logevent("Access denied");
7451 if (s
->type
== AUTH_TYPE_PASSWORD
&&
7452 ssh
->cfg
.change_username
) {
7453 /* XXX perhaps we should allow
7454 * keyboard-interactive to do this too? */
7455 s
->we_are_in
= FALSE
;
7460 c_write_str(ssh
, "Further authentication required\r\n");
7461 logevent("Further authentication required");
7465 in_commasep_string("publickey", methods
, methlen
);
7467 in_commasep_string("password", methods
, methlen
);
7468 s
->can_keyb_inter
= ssh
->cfg
.try_ki_auth
&&
7469 in_commasep_string("keyboard-interactive", methods
, methlen
);
7471 s
->can_gssapi
= ssh
->cfg
.try_gssapi_auth
&&
7472 in_commasep_string("gssapi-with-mic", methods
, methlen
) &&
7477 ssh
->pkt_actx
= SSH2_PKTCTX_NOAUTH
;
7479 if (s
->can_pubkey
&& !s
->done_agent
&& s
->nkeys
) {
7482 * Attempt public-key authentication using a key from Pageant.
7485 ssh
->pkt_actx
= SSH2_PKTCTX_PUBLICKEY
;
7487 logeventf(ssh
, "Trying Pageant key #%d", s
->keyi
);
7489 /* Unpack key from agent response */
7490 s
->pklen
= GET_32BIT(s
->agentp
);
7492 s
->pkblob
= (char *)s
->agentp
;
7493 s
->agentp
+= s
->pklen
;
7494 s
->alglen
= GET_32BIT(s
->pkblob
);
7495 s
->alg
= s
->pkblob
+ 4;
7496 s
->commentlen
= GET_32BIT(s
->agentp
);
7498 s
->commentp
= (char *)s
->agentp
;
7499 s
->agentp
+= s
->commentlen
;
7500 /* s->agentp now points at next key, if any */
7502 /* See if server will accept it */
7503 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7504 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7505 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7506 /* service requested */
7507 ssh2_pkt_addstring(s
->pktout
, "publickey");
7509 ssh2_pkt_addbool(s
->pktout
, FALSE
); /* no signature included */
7510 ssh2_pkt_addstring_start(s
->pktout
);
7511 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
7512 ssh2_pkt_addstring_start(s
->pktout
);
7513 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
7514 ssh2_pkt_send(ssh
, s
->pktout
);
7515 s
->type
= AUTH_TYPE_PUBLICKEY_OFFER_QUIET
;
7517 crWaitUntilV(pktin
);
7518 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
7520 /* Offer of key refused. */
7527 if (flags
& FLAG_VERBOSE
) {
7528 c_write_str(ssh
, "Authenticating with "
7530 c_write(ssh
, s
->commentp
, s
->commentlen
);
7531 c_write_str(ssh
, "\" from agent\r\n");
7535 * Server is willing to accept the key.
7536 * Construct a SIGN_REQUEST.
7538 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7539 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7540 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7541 /* service requested */
7542 ssh2_pkt_addstring(s
->pktout
, "publickey");
7544 ssh2_pkt_addbool(s
->pktout
, TRUE
); /* signature included */
7545 ssh2_pkt_addstring_start(s
->pktout
);
7546 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
7547 ssh2_pkt_addstring_start(s
->pktout
);
7548 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
7550 /* Ask agent for signature. */
7551 s
->siglen
= s
->pktout
->length
- 5 + 4 +
7552 ssh
->v2_session_id_len
;
7553 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
7555 s
->len
= 1; /* message type */
7556 s
->len
+= 4 + s
->pklen
; /* key blob */
7557 s
->len
+= 4 + s
->siglen
; /* data to sign */
7558 s
->len
+= 4; /* flags */
7559 s
->agentreq
= snewn(4 + s
->len
, char);
7560 PUT_32BIT(s
->agentreq
, s
->len
);
7561 s
->q
= s
->agentreq
+ 4;
7562 *s
->q
++ = SSH2_AGENTC_SIGN_REQUEST
;
7563 PUT_32BIT(s
->q
, s
->pklen
);
7565 memcpy(s
->q
, s
->pkblob
, s
->pklen
);
7567 PUT_32BIT(s
->q
, s
->siglen
);
7569 /* Now the data to be signed... */
7570 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
7571 PUT_32BIT(s
->q
, ssh
->v2_session_id_len
);
7574 memcpy(s
->q
, ssh
->v2_session_id
,
7575 ssh
->v2_session_id_len
);
7576 s
->q
+= ssh
->v2_session_id_len
;
7577 memcpy(s
->q
, s
->pktout
->data
+ 5,
7578 s
->pktout
->length
- 5);
7579 s
->q
+= s
->pktout
->length
- 5;
7580 /* And finally the (zero) flags word. */
7582 if (!agent_query(s
->agentreq
, s
->len
+ 4,
7584 ssh_agent_callback
, ssh
)) {
7588 bombout(("Unexpected data from server"
7589 " while waiting for agent"
7593 } while (pktin
|| inlen
> 0);
7594 vret
= ssh
->agent_response
;
7595 s
->retlen
= ssh
->agent_response_len
;
7600 if (s
->ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
7601 logevent("Sending Pageant's response");
7602 ssh2_add_sigblob(ssh
, s
->pktout
,
7603 s
->pkblob
, s
->pklen
,
7605 GET_32BIT(s
->ret
+ 5));
7606 ssh2_pkt_send(ssh
, s
->pktout
);
7607 s
->type
= AUTH_TYPE_PUBLICKEY
;
7609 /* FIXME: less drastic response */
7610 bombout(("Pageant failed to answer challenge"));
7616 /* Do we have any keys left to try? */
7617 if (s
->pkblob_in_agent
) {
7618 s
->done_agent
= TRUE
;
7619 s
->tried_pubkey_config
= TRUE
;
7622 if (s
->keyi
>= s
->nkeys
)
7623 s
->done_agent
= TRUE
;
7626 } else if (s
->can_pubkey
&& s
->publickey_blob
&&
7627 !s
->tried_pubkey_config
) {
7629 struct ssh2_userkey
*key
; /* not live over crReturn */
7630 char *passphrase
; /* not live over crReturn */
7632 ssh
->pkt_actx
= SSH2_PKTCTX_PUBLICKEY
;
7634 s
->tried_pubkey_config
= TRUE
;
7637 * Try the public key supplied in the configuration.
7639 * First, offer the public blob to see if the server is
7640 * willing to accept it.
7642 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7643 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7644 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7645 /* service requested */
7646 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
7647 ssh2_pkt_addbool(s
->pktout
, FALSE
);
7648 /* no signature included */
7649 ssh2_pkt_addstring(s
->pktout
, s
->publickey_algorithm
);
7650 ssh2_pkt_addstring_start(s
->pktout
);
7651 ssh2_pkt_addstring_data(s
->pktout
,
7652 (char *)s
->publickey_blob
,
7653 s
->publickey_bloblen
);
7654 ssh2_pkt_send(ssh
, s
->pktout
);
7655 logevent("Offered public key");
7657 crWaitUntilV(pktin
);
7658 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
7659 /* Key refused. Give up. */
7660 s
->gotit
= TRUE
; /* reconsider message next loop */
7661 s
->type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
7662 continue; /* process this new message */
7664 logevent("Offer of public key accepted");
7667 * Actually attempt a serious authentication using
7670 if (flags
& FLAG_VERBOSE
) {
7671 c_write_str(ssh
, "Authenticating with public key \"");
7672 c_write_str(ssh
, s
->publickey_comment
);
7673 c_write_str(ssh
, "\"\r\n");
7677 const char *error
; /* not live over crReturn */
7678 if (s
->publickey_encrypted
) {
7680 * Get a passphrase from the user.
7682 int ret
; /* need not be kept over crReturn */
7683 s
->cur_prompt
= new_prompts(ssh
->frontend
);
7684 s
->cur_prompt
->to_server
= FALSE
;
7685 s
->cur_prompt
->name
= dupstr("SSH key passphrase");
7686 add_prompt(s
->cur_prompt
,
7687 dupprintf("Passphrase for key \"%.100s\": ",
7688 s
->publickey_comment
),
7689 FALSE
, SSH_MAX_PASSWORD_LEN
);
7690 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
7693 crWaitUntilV(!pktin
);
7694 ret
= get_userpass_input(s
->cur_prompt
,
7699 /* Failed to get a passphrase. Terminate. */
7700 free_prompts(s
->cur_prompt
);
7701 ssh_disconnect(ssh
, NULL
,
7702 "Unable to authenticate",
7703 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER
,
7708 dupstr(s
->cur_prompt
->prompts
[0]->result
);
7709 free_prompts(s
->cur_prompt
);
7711 passphrase
= NULL
; /* no passphrase needed */
7715 * Try decrypting the key.
7717 key
= ssh2_load_userkey(&ssh
->cfg
.keyfile
, passphrase
,
7720 /* burn the evidence */
7721 memset(passphrase
, 0, strlen(passphrase
));
7724 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
7726 (key
== SSH2_WRONG_PASSPHRASE
)) {
7727 c_write_str(ssh
, "Wrong passphrase\r\n");
7729 /* and loop again */
7731 c_write_str(ssh
, "Unable to load private key (");
7732 c_write_str(ssh
, error
);
7733 c_write_str(ssh
, ")\r\n");
7735 break; /* try something else */
7741 unsigned char *pkblob
, *sigblob
, *sigdata
;
7742 int pkblob_len
, sigblob_len
, sigdata_len
;
7746 * We have loaded the private key and the server
7747 * has announced that it's willing to accept it.
7748 * Hallelujah. Generate a signature and send it.
7750 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7751 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7752 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7753 /* service requested */
7754 ssh2_pkt_addstring(s
->pktout
, "publickey");
7756 ssh2_pkt_addbool(s
->pktout
, TRUE
);
7757 /* signature follows */
7758 ssh2_pkt_addstring(s
->pktout
, key
->alg
->name
);
7759 pkblob
= key
->alg
->public_blob(key
->data
,
7761 ssh2_pkt_addstring_start(s
->pktout
);
7762 ssh2_pkt_addstring_data(s
->pktout
, (char *)pkblob
,
7766 * The data to be signed is:
7770 * followed by everything so far placed in the
7773 sigdata_len
= s
->pktout
->length
- 5 + 4 +
7774 ssh
->v2_session_id_len
;
7775 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
7777 sigdata
= snewn(sigdata_len
, unsigned char);
7779 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
7780 PUT_32BIT(sigdata
+p
, ssh
->v2_session_id_len
);
7783 memcpy(sigdata
+p
, ssh
->v2_session_id
,
7784 ssh
->v2_session_id_len
);
7785 p
+= ssh
->v2_session_id_len
;
7786 memcpy(sigdata
+p
, s
->pktout
->data
+ 5,
7787 s
->pktout
->length
- 5);
7788 p
+= s
->pktout
->length
- 5;
7789 assert(p
== sigdata_len
);
7790 sigblob
= key
->alg
->sign(key
->data
, (char *)sigdata
,
7791 sigdata_len
, &sigblob_len
);
7792 ssh2_add_sigblob(ssh
, s
->pktout
, pkblob
, pkblob_len
,
7793 sigblob
, sigblob_len
);
7798 ssh2_pkt_send(ssh
, s
->pktout
);
7799 s
->type
= AUTH_TYPE_PUBLICKEY
;
7800 key
->alg
->freekey(key
->data
);
7804 } else if (s
->can_gssapi
&& !s
->tried_gssapi
) {
7806 /* GSSAPI Authentication */
7810 s
->type
= AUTH_TYPE_GSSAPI
;
7811 s
->tried_gssapi
= TRUE
;
7813 ssh
->pkt_actx
= SSH2_PKTCTX_GSSAPI
;
7815 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
7816 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7817 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7818 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7819 ssh2_pkt_addstring(s
->pktout
, "gssapi-with-mic");
7821 /* add mechanism info */
7822 ssh_gss_indicate_mech(&s
->gss_buf
);
7824 /* number of GSSAPI mechanisms */
7825 ssh2_pkt_adduint32(s
->pktout
,1);
7827 /* length of OID + 2 */
7828 ssh2_pkt_adduint32(s
->pktout
, s
->gss_buf
.len
+ 2);
7829 ssh2_pkt_addbyte(s
->pktout
, SSH2_GSS_OIDTYPE
);
7832 ssh2_pkt_addbyte(s
->pktout
, (unsigned char) s
->gss_buf
.len
);
7834 ssh_pkt_adddata(s
->pktout
, s
->gss_buf
.data
, s
->gss_buf
.len
);
7835 ssh2_pkt_send(ssh
, s
->pktout
);
7836 crWaitUntilV(pktin
);
7837 if (pktin
->type
!= SSH2_MSG_USERAUTH_GSSAPI_RESPONSE
) {
7838 logevent("GSSAPI authentication request refused");
7842 /* check returned packet ... */
7844 ssh_pkt_getstring(pktin
,&s
->gss_rcvtok
.data
,&s
->gss_rcvtok
.len
);
7845 if (s
->gss_rcvtok
.len
!= s
->gss_buf
.len
+ 2 ||
7846 s
->gss_rcvtok
.data
[0] != SSH2_GSS_OIDTYPE
||
7847 s
->gss_rcvtok
.data
[1] != s
->gss_buf
.len
||
7848 memcmp(s
->gss_rcvtok
.data
+2,s
->gss_buf
.data
,s
->gss_buf
.len
) ) {
7849 logevent("GSSAPI authentication - wrong response from server");
7853 /* now start running */
7854 s
->gss_stat
= ssh_gss_import_name(ssh
->fullhostname
,
7856 if (s
->gss_stat
!= SSH_GSS_OK
) {
7857 if (s
->gss_stat
== SSH_GSS_BAD_HOST_NAME
)
7858 logevent("GSSAPI import name failed - Bad service name");
7860 logevent("GSSAPI import name failed");
7864 /* fetch TGT into GSS engine */
7865 s
->gss_stat
= ssh_gss_acquire_cred(&s
->gss_ctx
);
7867 if (s
->gss_stat
!= SSH_GSS_OK
) {
7868 logevent("GSSAPI authentication failed to get credentials");
7869 ssh_gss_release_name(&s
->gss_srv_name
);
7873 /* initial tokens are empty */
7874 s
->gss_rcvtok
.len
= s
->gss_sndtok
.len
= 0;
7875 s
->gss_rcvtok
.data
= s
->gss_sndtok
.data
= NULL
;
7877 /* now enter the loop */
7879 s
->gss_stat
= ssh_gss_init_sec_context(&s
->gss_ctx
,
7885 if (s
->gss_stat
!=SSH_GSS_S_COMPLETE
&&
7886 s
->gss_stat
!=SSH_GSS_S_CONTINUE_NEEDED
) {
7887 logevent("GSSAPI authentication initialisation failed");
7889 if (ssh_gss_display_status(s
->gss_ctx
,&s
->gss_buf
) == SSH_GSS_OK
) {
7890 logevent(s
->gss_buf
.data
);
7891 sfree(s
->gss_buf
.data
);
7896 logevent("GSSAPI authentication initialised");
7898 /* Client and server now exchange tokens until GSSAPI
7899 * no longer says CONTINUE_NEEDED */
7901 if (s
->gss_sndtok
.len
!= 0) {
7902 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN
);
7903 ssh_pkt_addstring_start(s
->pktout
);
7904 ssh_pkt_addstring_data(s
->pktout
,s
->gss_sndtok
.data
,s
->gss_sndtok
.len
);
7905 ssh2_pkt_send(ssh
, s
->pktout
);
7906 ssh_gss_free_tok(&s
->gss_sndtok
);
7909 if (s
->gss_stat
== SSH_GSS_S_CONTINUE_NEEDED
) {
7910 crWaitUntilV(pktin
);
7911 if (pktin
->type
!= SSH2_MSG_USERAUTH_GSSAPI_TOKEN
) {
7912 logevent("GSSAPI authentication - bad server response");
7913 s
->gss_stat
= SSH_GSS_FAILURE
;
7916 ssh_pkt_getstring(pktin
,&s
->gss_rcvtok
.data
,&s
->gss_rcvtok
.len
);
7918 } while (s
-> gss_stat
== SSH_GSS_S_CONTINUE_NEEDED
);
7920 if (s
->gss_stat
!= SSH_GSS_OK
) {
7921 ssh_gss_release_name(&s
->gss_srv_name
);
7922 ssh_gss_release_cred(&s
->gss_ctx
);
7925 logevent("GSSAPI authentication loop finished OK");
7927 /* Now send the MIC */
7929 s
->pktout
= ssh2_pkt_init(0);
7930 micoffset
= s
->pktout
->length
;
7931 ssh_pkt_addstring_start(s
->pktout
);
7932 ssh_pkt_addstring_data(s
->pktout
, (char *)ssh
->v2_session_id
, ssh
->v2_session_id_len
);
7933 ssh_pkt_addbyte(s
->pktout
, SSH2_MSG_USERAUTH_REQUEST
);
7934 ssh_pkt_addstring(s
->pktout
, s
->username
);
7935 ssh_pkt_addstring(s
->pktout
, "ssh-connection");
7936 ssh_pkt_addstring(s
->pktout
, "gssapi-with-mic");
7938 s
->gss_buf
.data
= (char *)s
->pktout
->data
+ micoffset
;
7939 s
->gss_buf
.len
= s
->pktout
->length
- micoffset
;
7941 ssh_gss_get_mic(s
->gss_ctx
, &s
->gss_buf
, &mic
);
7942 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC
);
7943 ssh_pkt_addstring_start(s
->pktout
);
7944 ssh_pkt_addstring_data(s
->pktout
, mic
.data
, mic
.len
);
7945 ssh2_pkt_send(ssh
, s
->pktout
);
7946 ssh_gss_free_mic(&mic
);
7950 ssh_gss_release_name(&s
->gss_srv_name
);
7951 ssh_gss_release_cred(&s
->gss_ctx
);
7954 } else if (s
->can_keyb_inter
&& !s
->kbd_inter_refused
) {
7957 * Keyboard-interactive authentication.
7960 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
7962 ssh
->pkt_actx
= SSH2_PKTCTX_KBDINTER
;
7964 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7965 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7966 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7967 /* service requested */
7968 ssh2_pkt_addstring(s
->pktout
, "keyboard-interactive");
7970 ssh2_pkt_addstring(s
->pktout
, ""); /* lang */
7971 ssh2_pkt_addstring(s
->pktout
, ""); /* submethods */
7972 ssh2_pkt_send(ssh
, s
->pktout
);
7974 crWaitUntilV(pktin
);
7975 if (pktin
->type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
7976 /* Server is not willing to do keyboard-interactive
7977 * at all (or, bizarrely but legally, accepts the
7978 * user without actually issuing any prompts).
7979 * Give up on it entirely. */
7981 if (pktin
->type
== SSH2_MSG_USERAUTH_FAILURE
)
7982 logevent("Keyboard-interactive authentication refused");
7983 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
7984 s
->kbd_inter_refused
= TRUE
; /* don't try it again */
7989 * Loop while the server continues to send INFO_REQUESTs.
7991 while (pktin
->type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
7993 char *name
, *inst
, *lang
;
7994 int name_len
, inst_len
, lang_len
;
7998 * We've got a fresh USERAUTH_INFO_REQUEST.
7999 * Get the preamble and start building a prompt.
8001 ssh_pkt_getstring(pktin
, &name
, &name_len
);
8002 ssh_pkt_getstring(pktin
, &inst
, &inst_len
);
8003 ssh_pkt_getstring(pktin
, &lang
, &lang_len
);
8004 s
->cur_prompt
= new_prompts(ssh
->frontend
);
8005 s
->cur_prompt
->to_server
= TRUE
;
8007 /* FIXME: better prefix to distinguish from
8009 s
->cur_prompt
->name
=
8010 dupprintf("SSH server: %.*s", name_len
, name
);
8011 s
->cur_prompt
->name_reqd
= TRUE
;
8013 s
->cur_prompt
->name
=
8014 dupstr("SSH server authentication");
8015 s
->cur_prompt
->name_reqd
= FALSE
;
8017 /* FIXME: ugly to print "Using..." in prompt _every_
8018 * time round. Can this be done more subtly? */
8019 s
->cur_prompt
->instruction
=
8020 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8021 inst_len ?
"\n" : "", inst_len
, inst
);
8022 s
->cur_prompt
->instr_reqd
= TRUE
;
8025 * Get any prompt(s) from the packet.
8027 s
->num_prompts
= ssh_pkt_getuint32(pktin
);
8028 for (i
= 0; i
< s
->num_prompts
; i
++) {
8032 static char noprompt
[] =
8033 "<server failed to send prompt>: ";
8035 ssh_pkt_getstring(pktin
, &prompt
, &prompt_len
);
8036 echo
= ssh2_pkt_getbool(pktin
);
8039 prompt_len
= lenof(noprompt
)-1;
8041 add_prompt(s
->cur_prompt
,
8042 dupprintf("%.*s", prompt_len
, prompt
),
8043 echo
, SSH_MAX_PASSWORD_LEN
);
8047 * Display any instructions, and get the user's
8051 int ret
; /* not live over crReturn */
8052 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
8055 crWaitUntilV(!pktin
);
8056 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
8061 * Failed to get responses. Terminate.
8063 free_prompts(s
->cur_prompt
);
8064 ssh_disconnect(ssh
, NULL
, "Unable to authenticate",
8065 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER
,
8072 * Send the response(s) to the server.
8074 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
8075 ssh2_pkt_adduint32(s
->pktout
, s
->num_prompts
);
8076 for (i
=0; i
< s
->num_prompts
; i
++) {
8077 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
8078 ssh2_pkt_addstring(s
->pktout
,
8079 s
->cur_prompt
->prompts
[i
]->result
);
8080 end_log_omission(ssh
, s
->pktout
);
8082 ssh2_pkt_send_with_padding(ssh
, s
->pktout
, 256);
8085 * Get the next packet in case it's another
8088 crWaitUntilV(pktin
);
8093 * We should have SUCCESS or FAILURE now.
8097 } else if (s
->can_passwd
) {
8100 * Plain old password authentication.
8102 int ret
; /* not live over crReturn */
8103 int changereq_first_time
; /* not live over crReturn */
8105 ssh
->pkt_actx
= SSH2_PKTCTX_PASSWORD
;
8107 s
->cur_prompt
= new_prompts(ssh
->frontend
);
8108 s
->cur_prompt
->to_server
= TRUE
;
8109 s
->cur_prompt
->name
= dupstr("SSH password");
8110 add_prompt(s
->cur_prompt
, dupprintf("%.90s@%.90s's password: ",
8113 FALSE
, SSH_MAX_PASSWORD_LEN
);
8115 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
8118 crWaitUntilV(!pktin
);
8119 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
8124 * Failed to get responses. Terminate.
8126 free_prompts(s
->cur_prompt
);
8127 ssh_disconnect(ssh
, NULL
, "Unable to authenticate",
8128 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER
,
8133 * Squirrel away the password. (We may need it later if
8134 * asked to change it.)
8136 s
->password
= dupstr(s
->cur_prompt
->prompts
[0]->result
);
8137 free_prompts(s
->cur_prompt
);
8140 * Send the password packet.
8142 * We pad out the password packet to 256 bytes to make
8143 * it harder for an attacker to find the length of the
8146 * Anyone using a password longer than 256 bytes
8147 * probably doesn't have much to worry about from
8148 * people who find out how long their password is!
8150 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
8151 ssh2_pkt_addstring(s
->pktout
, s
->username
);
8152 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
8153 /* service requested */
8154 ssh2_pkt_addstring(s
->pktout
, "password");
8155 ssh2_pkt_addbool(s
->pktout
, FALSE
);
8156 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
8157 ssh2_pkt_addstring(s
->pktout
, s
->password
);
8158 end_log_omission(ssh
, s
->pktout
);
8159 ssh2_pkt_send_with_padding(ssh
, s
->pktout
, 256);
8160 logevent("Sent password");
8161 s
->type
= AUTH_TYPE_PASSWORD
;
8164 * Wait for next packet, in case it's a password change
8167 crWaitUntilV(pktin
);
8168 changereq_first_time
= TRUE
;
8170 while (pktin
->type
== SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
) {
8173 * We're being asked for a new password
8174 * (perhaps not for the first time).
8175 * Loop until the server accepts it.
8178 int got_new
= FALSE
; /* not live over crReturn */
8179 char *prompt
; /* not live over crReturn */
8180 int prompt_len
; /* not live over crReturn */
8184 if (changereq_first_time
)
8185 msg
= "Server requested password change";
8187 msg
= "Server rejected new password";
8189 c_write_str(ssh
, msg
);
8190 c_write_str(ssh
, "\r\n");
8193 ssh_pkt_getstring(pktin
, &prompt
, &prompt_len
);
8195 s
->cur_prompt
= new_prompts(ssh
->frontend
);
8196 s
->cur_prompt
->to_server
= TRUE
;
8197 s
->cur_prompt
->name
= dupstr("New SSH password");
8198 s
->cur_prompt
->instruction
=
8199 dupprintf("%.*s", prompt_len
, prompt
);
8200 s
->cur_prompt
->instr_reqd
= TRUE
;
8202 * There's no explicit requirement in the protocol
8203 * for the "old" passwords in the original and
8204 * password-change messages to be the same, and
8205 * apparently some Cisco kit supports password change
8206 * by the user entering a blank password originally
8207 * and the real password subsequently, so,
8208 * reluctantly, we prompt for the old password again.
8210 * (On the other hand, some servers don't even bother
8211 * to check this field.)
8213 add_prompt(s
->cur_prompt
,
8214 dupstr("Current password (blank for previously entered password): "),
8215 FALSE
, SSH_MAX_PASSWORD_LEN
);
8216 add_prompt(s
->cur_prompt
, dupstr("Enter new password: "),
8217 FALSE
, SSH_MAX_PASSWORD_LEN
);
8218 add_prompt(s
->cur_prompt
, dupstr("Confirm new password: "),
8219 FALSE
, SSH_MAX_PASSWORD_LEN
);
8222 * Loop until the user manages to enter the same
8227 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
8230 crWaitUntilV(!pktin
);
8231 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
8236 * Failed to get responses. Terminate.
8238 /* burn the evidence */
8239 free_prompts(s
->cur_prompt
);
8240 memset(s
->password
, 0, strlen(s
->password
));
8242 ssh_disconnect(ssh
, NULL
, "Unable to authenticate",
8243 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER
,
8249 * If the user specified a new original password
8250 * (IYSWIM), overwrite any previously specified
8252 * (A side effect is that the user doesn't have to
8253 * re-enter it if they louse up the new password.)
8255 if (s
->cur_prompt
->prompts
[0]->result
[0]) {
8256 memset(s
->password
, 0, strlen(s
->password
));
8257 /* burn the evidence */
8260 dupstr(s
->cur_prompt
->prompts
[0]->result
);
8264 * Check the two new passwords match.
8266 got_new
= (strcmp(s
->cur_prompt
->prompts
[1]->result
,
8267 s
->cur_prompt
->prompts
[2]->result
)
8270 /* They don't. Silly user. */
8271 c_write_str(ssh
, "Passwords do not match\r\n");
8276 * Send the new password (along with the old one).
8277 * (see above for padding rationale)
8279 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
8280 ssh2_pkt_addstring(s
->pktout
, s
->username
);
8281 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
8282 /* service requested */
8283 ssh2_pkt_addstring(s
->pktout
, "password");
8284 ssh2_pkt_addbool(s
->pktout
, TRUE
);
8285 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
8286 ssh2_pkt_addstring(s
->pktout
, s
->password
);
8287 ssh2_pkt_addstring(s
->pktout
,
8288 s
->cur_prompt
->prompts
[1]->result
);
8289 free_prompts(s
->cur_prompt
);
8290 end_log_omission(ssh
, s
->pktout
);
8291 ssh2_pkt_send_with_padding(ssh
, s
->pktout
, 256);
8292 logevent("Sent new password");
8295 * Now see what the server has to say about it.
8296 * (If it's CHANGEREQ again, it's not happy with the
8299 crWaitUntilV(pktin
);
8300 changereq_first_time
= FALSE
;
8305 * We need to reexamine the current pktin at the top
8306 * of the loop. Either:
8307 * - we weren't asked to change password at all, in
8308 * which case it's a SUCCESS or FAILURE with the
8310 * - we sent a new password, and the server was
8311 * either OK with it (SUCCESS or FAILURE w/partial
8312 * success) or unhappy with the _old_ password
8313 * (FAILURE w/o partial success)
8314 * In any of these cases, we go back to the top of
8315 * the loop and start again.
8320 * We don't need the old password any more, in any
8321 * case. Burn the evidence.
8323 memset(s
->password
, 0, strlen(s
->password
));
8328 ssh_disconnect(ssh
, NULL
,
8329 "No supported authentication methods available",
8330 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE
,
8338 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] = NULL
;
8340 /* Clear up various bits and pieces from authentication. */
8341 if (s
->publickey_blob
) {
8342 sfree(s
->publickey_blob
);
8343 sfree(s
->publickey_comment
);
8345 if (s
->agent_response
)
8346 sfree(s
->agent_response
);
8349 * Now the connection protocol has started, one way or another.
8352 ssh
->channels
= newtree234(ssh_channelcmp
);
8355 * Set up handlers for some connection protocol messages, so we
8356 * don't have to handle them repeatedly in this coroutine.
8358 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] =
8359 ssh2_msg_channel_window_adjust
;
8360 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] =
8361 ssh2_msg_global_request
;
8364 * Create the main session channel.
8366 if (ssh
->cfg
.ssh_no_shell
) {
8367 ssh
->mainchan
= NULL
;
8368 } else if (*ssh
->cfg
.ssh_nc_host
) {
8370 * Just start a direct-tcpip channel and use it as the main
8373 ssh
->mainchan
= snew(struct ssh_channel
);
8374 ssh
->mainchan
->ssh
= ssh
;
8375 ssh2_channel_init(ssh
->mainchan
);
8377 "Opening direct-tcpip channel to %s:%d in place of session",
8378 ssh
->cfg
.ssh_nc_host
, ssh
->cfg
.ssh_nc_port
);
8379 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
8380 ssh2_pkt_addstring(s
->pktout
, "direct-tcpip");
8381 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->localid
);
8382 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->v
.v2
.locwindow
);/* our window size */
8383 ssh2_pkt_adduint32(s
->pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
8384 ssh2_pkt_addstring(s
->pktout
, ssh
->cfg
.ssh_nc_host
);
8385 ssh2_pkt_adduint32(s
->pktout
, ssh
->cfg
.ssh_nc_port
);
8387 * There's nothing meaningful to put in the originator
8388 * fields, but some servers insist on syntactically correct
8391 ssh2_pkt_addstring(s
->pktout
, "0.0.0.0");
8392 ssh2_pkt_adduint32(s
->pktout
, 0);
8393 ssh2_pkt_send(ssh
, s
->pktout
);
8395 crWaitUntilV(pktin
);
8396 if (pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
8397 bombout(("Server refused to open a direct-tcpip channel"));
8399 /* FIXME: error data comes back in FAILURE packet */
8401 if (ssh_pkt_getuint32(pktin
) != ssh
->mainchan
->localid
) {
8402 bombout(("Server's channel confirmation cited wrong channel"));
8405 ssh
->mainchan
->remoteid
= ssh_pkt_getuint32(pktin
);
8406 ssh
->mainchan
->halfopen
= FALSE
;
8407 ssh
->mainchan
->type
= CHAN_MAINSESSION
;
8408 ssh
->mainchan
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
8409 ssh
->mainchan
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
8410 add234(ssh
->channels
, ssh
->mainchan
);
8411 update_specials_menu(ssh
->frontend
);
8412 logevent("Opened direct-tcpip channel");
8415 ssh
->mainchan
= snew(struct ssh_channel
);
8416 ssh
->mainchan
->ssh
= ssh
;
8417 ssh2_channel_init(ssh
->mainchan
);
8418 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
8419 ssh2_pkt_addstring(s
->pktout
, "session");
8420 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->localid
);
8421 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->v
.v2
.locwindow
);/* our window size */
8422 ssh2_pkt_adduint32(s
->pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
8423 ssh2_pkt_send(ssh
, s
->pktout
);
8424 crWaitUntilV(pktin
);
8425 if (pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
8426 bombout(("Server refused to open a session"));
8428 /* FIXME: error data comes back in FAILURE packet */
8430 if (ssh_pkt_getuint32(pktin
) != ssh
->mainchan
->localid
) {
8431 bombout(("Server's channel confirmation cited wrong channel"));
8434 ssh
->mainchan
->remoteid
= ssh_pkt_getuint32(pktin
);
8435 ssh
->mainchan
->halfopen
= FALSE
;
8436 ssh
->mainchan
->type
= CHAN_MAINSESSION
;
8437 ssh
->mainchan
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
8438 ssh
->mainchan
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
8439 add234(ssh
->channels
, ssh
->mainchan
);
8440 update_specials_menu(ssh
->frontend
);
8441 logevent("Opened channel for session");
8442 ssh
->ncmode
= FALSE
;
8446 * Now we have a channel, make dispatch table entries for
8447 * general channel-based messages.
8449 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] =
8450 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] =
8451 ssh2_msg_channel_data
;
8452 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = ssh2_msg_channel_eof
;
8453 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = ssh2_msg_channel_close
;
8454 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] =
8455 ssh2_msg_channel_open_confirmation
;
8456 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] =
8457 ssh2_msg_channel_open_failure
;
8458 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_REQUEST
] =
8459 ssh2_msg_channel_request
;
8460 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] =
8461 ssh2_msg_channel_open
;
8463 if (ssh
->cfg
.ssh_simple
) {
8465 * This message indicates to the server that we promise
8466 * not to try to run any other channel in parallel with
8467 * this one, so it's safe for it to advertise a very large
8468 * window and leave the flow control to TCP.
8470 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8471 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
8472 ssh2_pkt_addstring(s
->pktout
, "simple@putty.projects.tartarus.org");
8473 ssh2_pkt_addbool(s
->pktout
, 0); /* no reply */
8474 ssh2_pkt_send(ssh
, s
->pktout
);
8478 * Potentially enable X11 forwarding.
8480 if (ssh
->mainchan
&& !ssh
->ncmode
&& ssh
->cfg
.x11_forward
) {
8481 char proto
[20], data
[64];
8482 logevent("Requesting X11 forwarding");
8483 ssh
->x11auth
= x11_invent_auth(proto
, sizeof(proto
),
8484 data
, sizeof(data
), ssh
->cfg
.x11_auth
);
8485 x11_get_real_auth(ssh
->x11auth
, ssh
->cfg
.x11_display
);
8486 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8487 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
8488 ssh2_pkt_addstring(s
->pktout
, "x11-req");
8489 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8490 ssh2_pkt_addbool(s
->pktout
, 0); /* many connections */
8491 ssh2_pkt_addstring(s
->pktout
, proto
);
8493 * Note that while we blank the X authentication data here, we don't
8494 * take any special action to blank the start of an X11 channel,
8495 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
8496 * without having session blanking enabled is likely to leak your
8497 * cookie into the log.
8499 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
8500 ssh2_pkt_addstring(s
->pktout
, data
);
8501 end_log_omission(ssh
, s
->pktout
);
8502 ssh2_pkt_adduint32(s
->pktout
, x11_get_screen_number(ssh
->cfg
.x11_display
));
8503 ssh2_pkt_send(ssh
, s
->pktout
);
8505 crWaitUntilV(pktin
);
8507 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
8508 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
8509 bombout(("Unexpected response to X11 forwarding request:"
8510 " packet type %d", pktin
->type
));
8513 logevent("X11 forwarding refused");
8515 logevent("X11 forwarding enabled");
8516 ssh
->X11_fwd_enabled
= TRUE
;
8521 * Enable port forwardings.
8523 ssh_setup_portfwd(ssh
, &ssh
->cfg
);
8526 * Potentially enable agent forwarding.
8528 if (ssh
->mainchan
&& !ssh
->ncmode
&& ssh
->cfg
.agentfwd
&& agent_exists()) {
8529 logevent("Requesting OpenSSH-style agent forwarding");
8530 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8531 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
8532 ssh2_pkt_addstring(s
->pktout
, "auth-agent-req@openssh.com");
8533 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8534 ssh2_pkt_send(ssh
, s
->pktout
);
8536 crWaitUntilV(pktin
);
8538 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
8539 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
8540 bombout(("Unexpected response to agent forwarding request:"
8541 " packet type %d", pktin
->type
));
8544 logevent("Agent forwarding refused");
8546 logevent("Agent forwarding enabled");
8547 ssh
->agentfwd_enabled
= TRUE
;
8552 * Now allocate a pty for the session.
8554 if (ssh
->mainchan
&& !ssh
->ncmode
&& !ssh
->cfg
.nopty
) {
8555 /* Unpick the terminal-speed string. */
8556 /* XXX perhaps we should allow no speeds to be sent. */
8557 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
8558 sscanf(ssh
->cfg
.termspeed
, "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
8559 /* Build the pty request. */
8560 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8561 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
); /* recipient channel */
8562 ssh2_pkt_addstring(s
->pktout
, "pty-req");
8563 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8564 ssh2_pkt_addstring(s
->pktout
, ssh
->cfg
.termtype
);
8565 ssh2_pkt_adduint32(s
->pktout
, ssh
->term_width
);
8566 ssh2_pkt_adduint32(s
->pktout
, ssh
->term_height
);
8567 ssh2_pkt_adduint32(s
->pktout
, 0); /* pixel width */
8568 ssh2_pkt_adduint32(s
->pktout
, 0); /* pixel height */
8569 ssh2_pkt_addstring_start(s
->pktout
);
8570 parse_ttymodes(ssh
, ssh
->cfg
.ttymodes
,
8571 ssh2_send_ttymode
, (void *)s
->pktout
);
8572 ssh2_pkt_addbyte(s
->pktout
, SSH2_TTY_OP_ISPEED
);
8573 ssh2_pkt_adduint32(s
->pktout
, ssh
->ispeed
);
8574 ssh2_pkt_addbyte(s
->pktout
, SSH2_TTY_OP_OSPEED
);
8575 ssh2_pkt_adduint32(s
->pktout
, ssh
->ospeed
);
8576 ssh2_pkt_addstring_data(s
->pktout
, "\0", 1); /* TTY_OP_END */
8577 ssh2_pkt_send(ssh
, s
->pktout
);
8578 ssh
->state
= SSH_STATE_INTERMED
;
8580 crWaitUntilV(pktin
);
8582 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
8583 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
8584 bombout(("Unexpected response to pty request:"
8585 " packet type %d", pktin
->type
));
8588 c_write_str(ssh
, "Server refused to allocate pty\r\n");
8589 ssh
->editing
= ssh
->echoing
= 1;
8591 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8592 ssh
->ospeed
, ssh
->ispeed
);
8595 ssh
->editing
= ssh
->echoing
= 1;
8599 * Send environment variables.
8601 * Simplest thing here is to send all the requests at once, and
8602 * then wait for a whole bunch of successes or failures.
8604 if (ssh
->mainchan
&& !ssh
->ncmode
&& *ssh
->cfg
.environmt
) {
8605 char *e
= ssh
->cfg
.environmt
;
8606 char *var
, *varend
, *val
;
8612 while (*e
&& *e
!= '\t') e
++;
8614 if (*e
== '\t') e
++;
8619 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8620 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
8621 ssh2_pkt_addstring(s
->pktout
, "env");
8622 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8623 ssh2_pkt_addstring_start(s
->pktout
);
8624 ssh2_pkt_addstring_data(s
->pktout
, var
, varend
-var
);
8625 ssh2_pkt_addstring(s
->pktout
, val
);
8626 ssh2_pkt_send(ssh
, s
->pktout
);
8631 logeventf(ssh
, "Sent %d environment variables", s
->num_env
);
8634 s
->env_left
= s
->num_env
;
8636 while (s
->env_left
> 0) {
8637 crWaitUntilV(pktin
);
8639 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
8640 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
8641 bombout(("Unexpected response to environment request:"
8642 " packet type %d", pktin
->type
));
8652 if (s
->env_ok
== s
->num_env
) {
8653 logevent("All environment variables successfully set");
8654 } else if (s
->env_ok
== 0) {
8655 logevent("All environment variables refused");
8656 c_write_str(ssh
, "Server refused to set environment variables\r\n");
8658 logeventf(ssh
, "%d environment variables refused",
8659 s
->num_env
- s
->env_ok
);
8660 c_write_str(ssh
, "Server refused to set all environment variables\r\n");
8665 * Start a shell or a remote command. We may have to attempt
8666 * this twice if the config data has provided a second choice
8669 if (ssh
->mainchan
&& !ssh
->ncmode
) while (1) {
8673 if (ssh
->fallback_cmd
) {
8674 subsys
= ssh
->cfg
.ssh_subsys2
;
8675 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
8677 subsys
= ssh
->cfg
.ssh_subsys
;
8678 cmd
= ssh
->cfg
.remote_cmd_ptr
;
8679 if (!cmd
) cmd
= ssh
->cfg
.remote_cmd
;
8682 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8683 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
); /* recipient channel */
8685 ssh2_pkt_addstring(s
->pktout
, "subsystem");
8686 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8687 ssh2_pkt_addstring(s
->pktout
, cmd
);
8689 ssh2_pkt_addstring(s
->pktout
, "exec");
8690 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8691 ssh2_pkt_addstring(s
->pktout
, cmd
);
8693 ssh2_pkt_addstring(s
->pktout
, "shell");
8694 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8696 ssh2_pkt_send(ssh
, s
->pktout
);
8698 crWaitUntilV(pktin
);
8700 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
8701 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
8702 bombout(("Unexpected response to shell/command request:"
8703 " packet type %d", pktin
->type
));
8707 * We failed to start the command. If this is the
8708 * fallback command, we really are finished; if it's
8709 * not, and if the fallback command exists, try falling
8710 * back to it before complaining.
8712 if (!ssh
->fallback_cmd
&& ssh
->cfg
.remote_cmd_ptr2
!= NULL
) {
8713 logevent("Primary command failed; attempting fallback");
8714 ssh
->fallback_cmd
= TRUE
;
8717 bombout(("Server refused to start a shell/command"));
8720 logevent("Started a shell/command");
8725 ssh
->state
= SSH_STATE_SESSION
;
8726 if (ssh
->size_needed
)
8727 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
8728 if (ssh
->eof_needed
)
8729 ssh_special(ssh
, TS_EOF
);
8732 * All the initial channel requests are done, so install the default
8735 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_SUCCESS
] = ssh2_msg_channel_success
;
8736 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_FAILURE
] = ssh2_msg_channel_failure
;
8742 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
8747 s
->try_send
= FALSE
;
8751 * _All_ the connection-layer packets we expect to
8752 * receive are now handled by the dispatch table.
8753 * Anything that reaches here must be bogus.
8756 bombout(("Strange packet received: type %d", pktin
->type
));
8758 } else if (ssh
->mainchan
) {
8760 * We have spare data. Add it to the channel buffer.
8762 ssh2_add_channel_data(ssh
->mainchan
, (char *)in
, inlen
);
8767 struct ssh_channel
*c
;
8769 * Try to send data on all channels if we can.
8771 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++)
8772 ssh2_try_send_and_unthrottle(c
);
8780 * Handlers for SSH-2 messages that might arrive at any moment.
8782 static void ssh2_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
8784 /* log reason code in disconnect message */
8788 reason
= ssh_pkt_getuint32(pktin
);
8789 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
8791 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
8792 buf
= dupprintf("Received disconnect message (%s)",
8793 ssh2_disconnect_reasons
[reason
]);
8795 buf
= dupprintf("Received disconnect message (unknown"
8796 " type %d)", reason
);
8800 buf
= dupprintf("Disconnection message text: %.*s",
8803 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
8805 (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) ?
8806 ssh2_disconnect_reasons
[reason
] : "unknown",
8811 static void ssh2_msg_debug(Ssh ssh
, struct Packet
*pktin
)
8813 /* log the debug message */
8818 /* XXX maybe we should actually take notice of this */
8819 always_display
= ssh2_pkt_getbool(pktin
);
8820 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
8822 logeventf(ssh
, "Remote debug message: %.*s", msglen
, msg
);
8825 static void ssh2_msg_something_unimplemented(Ssh ssh
, struct Packet
*pktin
)
8827 struct Packet
*pktout
;
8828 pktout
= ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED
);
8829 ssh2_pkt_adduint32(pktout
, pktin
->sequence
);
8831 * UNIMPLEMENTED messages MUST appear in the same order as the
8832 * messages they respond to. Hence, never queue them.
8834 ssh2_pkt_send_noqueue(ssh
, pktout
);
8838 * Handle the top-level SSH-2 protocol.
8840 static void ssh2_protocol_setup(Ssh ssh
)
8845 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
8847 for (i
= 0; i
< 256; i
++)
8848 ssh
->packet_dispatch
[i
] = ssh2_msg_something_unimplemented
;
8851 * Any message we actually understand, we set to NULL so that
8852 * the coroutines will get it.
8854 ssh
->packet_dispatch
[SSH2_MSG_UNIMPLEMENTED
] = NULL
;
8855 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_REQUEST
] = NULL
;
8856 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_ACCEPT
] = NULL
;
8857 ssh
->packet_dispatch
[SSH2_MSG_KEXINIT
] = NULL
;
8858 ssh
->packet_dispatch
[SSH2_MSG_NEWKEYS
] = NULL
;
8859 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_INIT
] = NULL
;
8860 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_REPLY
] = NULL
;
8861 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
8862 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
8863 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_INIT
] = NULL
;
8864 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_REPLY
] = NULL
;
8865 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_REQUEST
] = NULL
;
8866 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_FAILURE
] = NULL
;
8867 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_SUCCESS
] = NULL
;
8868 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] = NULL
;
8869 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_PK_OK
] = NULL
;
8870 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
8871 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
8872 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_INFO_RESPONSE
] = NULL
;
8873 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] = NULL
;
8874 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_SUCCESS
] = NULL
;
8875 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_FAILURE
] = NULL
;
8876 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] = NULL
;
8877 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] = NULL
;
8878 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] = NULL
;
8879 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] = NULL
;
8880 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] = NULL
;
8881 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] = NULL
;
8882 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = NULL
;
8883 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = NULL
;
8884 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_REQUEST
] = NULL
;
8885 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_SUCCESS
] = NULL
;
8886 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_FAILURE
] = NULL
;
8889 * These special message types we install handlers for.
8891 ssh
->packet_dispatch
[SSH2_MSG_DISCONNECT
] = ssh2_msg_disconnect
;
8892 ssh
->packet_dispatch
[SSH2_MSG_IGNORE
] = ssh_msg_ignore
; /* shared with SSH-1 */
8893 ssh
->packet_dispatch
[SSH2_MSG_DEBUG
] = ssh2_msg_debug
;
8896 static void ssh2_timer(void *ctx
, long now
)
8900 if (ssh
->state
== SSH_STATE_CLOSED
)
8903 if (!ssh
->kex_in_progress
&& ssh
->cfg
.ssh_rekey_time
!= 0 &&
8904 now
- ssh
->next_rekey
>= 0) {
8905 do_ssh2_transport(ssh
, "timeout", -1, NULL
);
8909 static void ssh2_protocol(Ssh ssh
, void *vin
, int inlen
,
8910 struct Packet
*pktin
)
8912 unsigned char *in
= (unsigned char *)vin
;
8913 if (ssh
->state
== SSH_STATE_CLOSED
)
8917 ssh
->incoming_data_size
+= pktin
->encrypted_len
;
8918 if (!ssh
->kex_in_progress
&&
8919 ssh
->max_data_size
!= 0 &&
8920 ssh
->incoming_data_size
> ssh
->max_data_size
)
8921 do_ssh2_transport(ssh
, "too much data received", -1, NULL
);
8924 if (pktin
&& ssh
->packet_dispatch
[pktin
->type
]) {
8925 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
8929 if (!ssh
->protocol_initial_phase_done
||
8930 (pktin
&& pktin
->type
>= 20 && pktin
->type
< 50)) {
8931 if (do_ssh2_transport(ssh
, in
, inlen
, pktin
) &&
8932 !ssh
->protocol_initial_phase_done
) {
8933 ssh
->protocol_initial_phase_done
= TRUE
;
8935 * Allow authconn to initialise itself.
8937 do_ssh2_authconn(ssh
, NULL
, 0, NULL
);
8940 do_ssh2_authconn(ssh
, in
, inlen
, pktin
);
8945 * Called to set up the connection.
8947 * Returns an error message, or NULL on success.
8949 static const char *ssh_init(void *frontend_handle
, void **backend_handle
,
8951 char *host
, int port
, char **realhost
, int nodelay
,
8957 ssh
= snew(struct ssh_tag
);
8958 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
8959 ssh
->version
= 0; /* when not ready yet */
8962 ssh
->v1_cipher_ctx
= NULL
;
8963 ssh
->crcda_ctx
= NULL
;
8964 ssh
->cscipher
= NULL
;
8965 ssh
->cs_cipher_ctx
= NULL
;
8966 ssh
->sccipher
= NULL
;
8967 ssh
->sc_cipher_ctx
= NULL
;
8969 ssh
->cs_mac_ctx
= NULL
;
8971 ssh
->sc_mac_ctx
= NULL
;
8973 ssh
->cs_comp_ctx
= NULL
;
8975 ssh
->sc_comp_ctx
= NULL
;
8977 ssh
->kex_ctx
= NULL
;
8978 ssh
->hostkey
= NULL
;
8980 ssh
->close_expected
= FALSE
;
8981 ssh
->clean_exit
= FALSE
;
8982 ssh
->state
= SSH_STATE_PREPACKET
;
8983 ssh
->size_needed
= FALSE
;
8984 ssh
->eof_needed
= FALSE
;
8987 ssh
->deferred_send_data
= NULL
;
8988 ssh
->deferred_len
= 0;
8989 ssh
->deferred_size
= 0;
8990 ssh
->fallback_cmd
= 0;
8991 ssh
->pkt_kctx
= SSH2_PKTCTX_NOKEX
;
8992 ssh
->pkt_actx
= SSH2_PKTCTX_NOAUTH
;
8993 ssh
->x11auth
= NULL
;
8994 ssh
->v1_compressing
= FALSE
;
8995 ssh
->v2_outgoing_sequence
= 0;
8996 ssh
->ssh1_rdpkt_crstate
= 0;
8997 ssh
->ssh2_rdpkt_crstate
= 0;
8998 ssh
->do_ssh_init_crstate
= 0;
8999 ssh
->ssh_gotdata_crstate
= 0;
9000 ssh
->do_ssh1_connection_crstate
= 0;
9001 ssh
->do_ssh1_login_crstate
= 0;
9002 ssh
->do_ssh2_transport_crstate
= 0;
9003 ssh
->do_ssh2_authconn_crstate
= 0;
9004 ssh
->do_ssh_init_state
= NULL
;
9005 ssh
->do_ssh1_login_state
= NULL
;
9006 ssh
->do_ssh2_transport_state
= NULL
;
9007 ssh
->do_ssh2_authconn_state
= NULL
;
9010 ssh
->mainchan
= NULL
;
9011 ssh
->throttled_all
= 0;
9012 ssh
->v1_stdout_throttling
= 0;
9014 ssh
->queuelen
= ssh
->queuesize
= 0;
9015 ssh
->queueing
= FALSE
;
9016 ssh
->qhead
= ssh
->qtail
= NULL
;
9017 ssh
->deferred_rekey_reason
= NULL
;
9018 bufchain_init(&ssh
->queued_incoming_data
);
9019 ssh
->frozen
= FALSE
;
9021 *backend_handle
= ssh
;
9024 if (crypto_startup() == 0)
9025 return "Microsoft high encryption pack not installed!";
9028 ssh
->frontend
= frontend_handle
;
9029 ssh
->term_width
= ssh
->cfg
.width
;
9030 ssh
->term_height
= ssh
->cfg
.height
;
9032 ssh
->channels
= NULL
;
9033 ssh
->rportfwds
= NULL
;
9034 ssh
->portfwds
= NULL
;
9039 ssh
->conn_throttle_count
= 0;
9040 ssh
->overall_bufsize
= 0;
9041 ssh
->fallback_cmd
= 0;
9043 ssh
->protocol
= NULL
;
9045 ssh
->protocol_initial_phase_done
= FALSE
;
9049 ssh
->incoming_data_size
= ssh
->outgoing_data_size
=
9050 ssh
->deferred_data_size
= 0L;
9051 ssh
->max_data_size
= parse_blocksize(ssh
->cfg
.ssh_rekey_data
);
9052 ssh
->kex_in_progress
= FALSE
;
9054 p
= connect_to_host(ssh
, host
, port
, realhost
, nodelay
, keepalive
);
9063 static void ssh_free(void *handle
)
9065 Ssh ssh
= (Ssh
) handle
;
9066 struct ssh_channel
*c
;
9067 struct ssh_rportfwd
*pf
;
9069 if (ssh
->v1_cipher_ctx
)
9070 ssh
->cipher
->free_context(ssh
->v1_cipher_ctx
);
9071 if (ssh
->cs_cipher_ctx
)
9072 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
9073 if (ssh
->sc_cipher_ctx
)
9074 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
9075 if (ssh
->cs_mac_ctx
)
9076 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
9077 if (ssh
->sc_mac_ctx
)
9078 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
9079 if (ssh
->cs_comp_ctx
) {
9081 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
9083 zlib_compress_cleanup(ssh
->cs_comp_ctx
);
9085 if (ssh
->sc_comp_ctx
) {
9087 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
9089 zlib_decompress_cleanup(ssh
->sc_comp_ctx
);
9092 dh_cleanup(ssh
->kex_ctx
);
9093 sfree(ssh
->savedhost
);
9095 while (ssh
->queuelen
-- > 0)
9096 ssh_free_packet(ssh
->queue
[ssh
->queuelen
]);
9099 while (ssh
->qhead
) {
9100 struct queued_handler
*qh
= ssh
->qhead
;
9101 ssh
->qhead
= qh
->next
;
9104 ssh
->qhead
= ssh
->qtail
= NULL
;
9106 if (ssh
->channels
) {
9107 while ((c
= delpos234(ssh
->channels
, 0)) != NULL
) {
9110 if (c
->u
.x11
.s
!= NULL
)
9111 x11_close(c
->u
.x11
.s
);
9114 if (c
->u
.pfd
.s
!= NULL
)
9115 pfd_close(c
->u
.pfd
.s
);
9120 freetree234(ssh
->channels
);
9121 ssh
->channels
= NULL
;
9124 if (ssh
->rportfwds
) {
9125 while ((pf
= delpos234(ssh
->rportfwds
, 0)) != NULL
)
9127 freetree234(ssh
->rportfwds
);
9128 ssh
->rportfwds
= NULL
;
9130 sfree(ssh
->deferred_send_data
);
9132 x11_free_auth(ssh
->x11auth
);
9133 sfree(ssh
->do_ssh_init_state
);
9134 sfree(ssh
->do_ssh1_login_state
);
9135 sfree(ssh
->do_ssh2_transport_state
);
9136 sfree(ssh
->do_ssh2_authconn_state
);
9139 sfree(ssh
->fullhostname
);
9140 if (ssh
->crcda_ctx
) {
9141 crcda_free_context(ssh
->crcda_ctx
);
9142 ssh
->crcda_ctx
= NULL
;
9145 ssh_do_close(ssh
, TRUE
);
9146 expire_timer_context(ssh
);
9148 pinger_free(ssh
->pinger
);
9149 bufchain_clear(&ssh
->queued_incoming_data
);
9156 * Reconfigure the SSH backend.
9158 static void ssh_reconfig(void *handle
, Config
*cfg
)
9160 Ssh ssh
= (Ssh
) handle
;
9161 char *rekeying
= NULL
, rekey_mandatory
= FALSE
;
9162 unsigned long old_max_data_size
;
9164 pinger_reconfig(ssh
->pinger
, &ssh
->cfg
, cfg
);
9166 ssh_setup_portfwd(ssh
, cfg
);
9168 if (ssh
->cfg
.ssh_rekey_time
!= cfg
->ssh_rekey_time
&&
9169 cfg
->ssh_rekey_time
!= 0) {
9170 long new_next
= ssh
->last_rekey
+ cfg
->ssh_rekey_time
*60*TICKSPERSEC
;
9171 long now
= GETTICKCOUNT();
9173 if (new_next
- now
< 0) {
9174 rekeying
= "timeout shortened";
9176 ssh
->next_rekey
= schedule_timer(new_next
- now
, ssh2_timer
, ssh
);
9180 old_max_data_size
= ssh
->max_data_size
;
9181 ssh
->max_data_size
= parse_blocksize(cfg
->ssh_rekey_data
);
9182 if (old_max_data_size
!= ssh
->max_data_size
&&
9183 ssh
->max_data_size
!= 0) {
9184 if (ssh
->outgoing_data_size
> ssh
->max_data_size
||
9185 ssh
->incoming_data_size
> ssh
->max_data_size
)
9186 rekeying
= "data limit lowered";
9189 if (ssh
->cfg
.compression
!= cfg
->compression
) {
9190 rekeying
= "compression setting changed";
9191 rekey_mandatory
= TRUE
;
9194 if (ssh
->cfg
.ssh2_des_cbc
!= cfg
->ssh2_des_cbc
||
9195 memcmp(ssh
->cfg
.ssh_cipherlist
, cfg
->ssh_cipherlist
,
9196 sizeof(ssh
->cfg
.ssh_cipherlist
))) {
9197 rekeying
= "cipher settings changed";
9198 rekey_mandatory
= TRUE
;
9201 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
9204 if (!ssh
->kex_in_progress
) {
9205 do_ssh2_transport(ssh
, rekeying
, -1, NULL
);
9206 } else if (rekey_mandatory
) {
9207 ssh
->deferred_rekey_reason
= rekeying
;
9213 * Called to send data down the SSH connection.
9215 static int ssh_send(void *handle
, char *buf
, int len
)
9217 Ssh ssh
= (Ssh
) handle
;
9219 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
9222 ssh
->protocol(ssh
, (unsigned char *)buf
, len
, 0);
9224 return ssh_sendbuffer(ssh
);
9228 * Called to query the current amount of buffered stdin data.
9230 static int ssh_sendbuffer(void *handle
)
9232 Ssh ssh
= (Ssh
) handle
;
9235 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
9239 * If the SSH socket itself has backed up, add the total backup
9240 * size on that to any individual buffer on the stdin channel.
9243 if (ssh
->throttled_all
)
9244 override_value
= ssh
->overall_bufsize
;
9246 if (ssh
->version
== 1) {
9247 return override_value
;
9248 } else if (ssh
->version
== 2) {
9249 if (!ssh
->mainchan
|| ssh
->mainchan
->closes
> 0)
9250 return override_value
;
9252 return (override_value
+
9253 bufchain_size(&ssh
->mainchan
->v
.v2
.outbuffer
));
9260 * Called to set the size of the window from SSH's POV.
9262 static void ssh_size(void *handle
, int width
, int height
)
9264 Ssh ssh
= (Ssh
) handle
;
9265 struct Packet
*pktout
;
9267 ssh
->term_width
= width
;
9268 ssh
->term_height
= height
;
9270 switch (ssh
->state
) {
9271 case SSH_STATE_BEFORE_SIZE
:
9272 case SSH_STATE_PREPACKET
:
9273 case SSH_STATE_CLOSED
:
9274 break; /* do nothing */
9275 case SSH_STATE_INTERMED
:
9276 ssh
->size_needed
= TRUE
; /* buffer for later */
9278 case SSH_STATE_SESSION
:
9279 if (!ssh
->cfg
.nopty
) {
9280 if (ssh
->version
== 1) {
9281 send_packet(ssh
, SSH1_CMSG_WINDOW_SIZE
,
9282 PKT_INT
, ssh
->term_height
,
9283 PKT_INT
, ssh
->term_width
,
9284 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
9285 } else if (ssh
->mainchan
) {
9286 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
9287 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
9288 ssh2_pkt_addstring(pktout
, "window-change");
9289 ssh2_pkt_addbool(pktout
, 0);
9290 ssh2_pkt_adduint32(pktout
, ssh
->term_width
);
9291 ssh2_pkt_adduint32(pktout
, ssh
->term_height
);
9292 ssh2_pkt_adduint32(pktout
, 0);
9293 ssh2_pkt_adduint32(pktout
, 0);
9294 ssh2_pkt_send(ssh
, pktout
);
9302 * Return a list of the special codes that make sense in this
9305 static const struct telnet_special
*ssh_get_specials(void *handle
)
9307 static const struct telnet_special ssh1_ignore_special
[] = {
9308 {"IGNORE message", TS_NOP
}
9310 static const struct telnet_special ssh2_transport_specials
[] = {
9311 {"IGNORE message", TS_NOP
},
9312 {"Repeat key exchange", TS_REKEY
},
9314 static const struct telnet_special ssh2_session_specials
[] = {
9317 /* These are the signal names defined by RFC 4254.
9318 * They include all the ISO C signals, but are a subset of the POSIX
9319 * required signals. */
9320 {"SIGINT (Interrupt)", TS_SIGINT
},
9321 {"SIGTERM (Terminate)", TS_SIGTERM
},
9322 {"SIGKILL (Kill)", TS_SIGKILL
},
9323 {"SIGQUIT (Quit)", TS_SIGQUIT
},
9324 {"SIGHUP (Hangup)", TS_SIGHUP
},
9325 {"More signals", TS_SUBMENU
},
9326 {"SIGABRT", TS_SIGABRT
}, {"SIGALRM", TS_SIGALRM
},
9327 {"SIGFPE", TS_SIGFPE
}, {"SIGILL", TS_SIGILL
},
9328 {"SIGPIPE", TS_SIGPIPE
}, {"SIGSEGV", TS_SIGSEGV
},
9329 {"SIGUSR1", TS_SIGUSR1
}, {"SIGUSR2", TS_SIGUSR2
},
9332 static const struct telnet_special specials_end
[] = {
9335 /* XXX review this length for any changes: */
9336 static struct telnet_special ssh_specials
[lenof(ssh2_transport_specials
) +
9337 lenof(ssh2_session_specials
) +
9338 lenof(specials_end
)];
9339 Ssh ssh
= (Ssh
) handle
;
9341 #define ADD_SPECIALS(name) \
9343 assert((i + lenof(name)) <= lenof(ssh_specials)); \
9344 memcpy(&ssh_specials[i], name, sizeof name); \
9348 if (ssh
->version
== 1) {
9349 /* Don't bother offering IGNORE if we've decided the remote
9350 * won't cope with it, since we wouldn't bother sending it if
9352 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
9353 ADD_SPECIALS(ssh1_ignore_special
);
9354 } else if (ssh
->version
== 2) {
9355 ADD_SPECIALS(ssh2_transport_specials
);
9357 ADD_SPECIALS(ssh2_session_specials
);
9358 } /* else we're not ready yet */
9361 ADD_SPECIALS(specials_end
);
9362 return ssh_specials
;
9370 * Send special codes. TS_EOF is useful for `plink', so you
9371 * can send an EOF and collect resulting output (e.g. `plink
9374 static void ssh_special(void *handle
, Telnet_Special code
)
9376 Ssh ssh
= (Ssh
) handle
;
9377 struct Packet
*pktout
;
9379 if (code
== TS_EOF
) {
9380 if (ssh
->state
!= SSH_STATE_SESSION
) {
9382 * Buffer the EOF in case we are pre-SESSION, so we can
9383 * send it as soon as we reach SESSION.
9386 ssh
->eof_needed
= TRUE
;
9389 if (ssh
->version
== 1) {
9390 send_packet(ssh
, SSH1_CMSG_EOF
, PKT_END
);
9391 } else if (ssh
->mainchan
) {
9392 struct Packet
*pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
9393 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
9394 ssh2_pkt_send(ssh
, pktout
);
9395 ssh
->send_ok
= 0; /* now stop trying to read from stdin */
9397 logevent("Sent EOF message");
9398 } else if (code
== TS_PING
|| code
== TS_NOP
) {
9399 if (ssh
->state
== SSH_STATE_CLOSED
9400 || ssh
->state
== SSH_STATE_PREPACKET
) return;
9401 if (ssh
->version
== 1) {
9402 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
9403 send_packet(ssh
, SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
9405 pktout
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
9406 ssh2_pkt_addstring_start(pktout
);
9407 ssh2_pkt_send_noqueue(ssh
, pktout
);
9409 } else if (code
== TS_REKEY
) {
9410 if (!ssh
->kex_in_progress
&& ssh
->version
== 2) {
9411 do_ssh2_transport(ssh
, "at user request", -1, NULL
);
9413 } else if (code
== TS_BRK
) {
9414 if (ssh
->state
== SSH_STATE_CLOSED
9415 || ssh
->state
== SSH_STATE_PREPACKET
) return;
9416 if (ssh
->version
== 1) {
9417 logevent("Unable to send BREAK signal in SSH-1");
9418 } else if (ssh
->mainchan
) {
9419 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
9420 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
9421 ssh2_pkt_addstring(pktout
, "break");
9422 ssh2_pkt_addbool(pktout
, 0);
9423 ssh2_pkt_adduint32(pktout
, 0); /* default break length */
9424 ssh2_pkt_send(ssh
, pktout
);
9427 /* Is is a POSIX signal? */
9428 char *signame
= NULL
;
9429 if (code
== TS_SIGABRT
) signame
= "ABRT";
9430 if (code
== TS_SIGALRM
) signame
= "ALRM";
9431 if (code
== TS_SIGFPE
) signame
= "FPE";
9432 if (code
== TS_SIGHUP
) signame
= "HUP";
9433 if (code
== TS_SIGILL
) signame
= "ILL";
9434 if (code
== TS_SIGINT
) signame
= "INT";
9435 if (code
== TS_SIGKILL
) signame
= "KILL";
9436 if (code
== TS_SIGPIPE
) signame
= "PIPE";
9437 if (code
== TS_SIGQUIT
) signame
= "QUIT";
9438 if (code
== TS_SIGSEGV
) signame
= "SEGV";
9439 if (code
== TS_SIGTERM
) signame
= "TERM";
9440 if (code
== TS_SIGUSR1
) signame
= "USR1";
9441 if (code
== TS_SIGUSR2
) signame
= "USR2";
9442 /* The SSH-2 protocol does in principle support arbitrary named
9443 * signals, including signame@domain, but we don't support those. */
9445 /* It's a signal. */
9446 if (ssh
->version
== 2 && ssh
->mainchan
) {
9447 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
9448 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
9449 ssh2_pkt_addstring(pktout
, "signal");
9450 ssh2_pkt_addbool(pktout
, 0);
9451 ssh2_pkt_addstring(pktout
, signame
);
9452 ssh2_pkt_send(ssh
, pktout
);
9453 logeventf(ssh
, "Sent signal SIG%s", signame
);
9456 /* Never heard of it. Do nothing */
9461 void *new_sock_channel(void *handle
, Socket s
)
9463 Ssh ssh
= (Ssh
) handle
;
9464 struct ssh_channel
*c
;
9465 c
= snew(struct ssh_channel
);
9468 ssh2_channel_init(c
);
9470 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
9472 add234(ssh
->channels
, c
);
9477 * This is called when stdout/stderr (the entity to which
9478 * from_backend sends data) manages to clear some backlog.
9480 static void ssh_unthrottle(void *handle
, int bufsize
)
9482 Ssh ssh
= (Ssh
) handle
;
9485 if (ssh
->version
== 1) {
9486 if (ssh
->v1_stdout_throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
9487 ssh
->v1_stdout_throttling
= 0;
9488 ssh_throttle_conn(ssh
, -1);
9491 if (ssh
->mainchan
) {
9492 ssh2_set_window(ssh
->mainchan
,
9493 bufsize
< ssh
->mainchan
->v
.v2
.locmaxwin ?
9494 ssh
->mainchan
->v
.v2
.locmaxwin
- bufsize
: 0);
9495 if (ssh
->cfg
.ssh_simple
)
9498 buflimit
= ssh
->mainchan
->v
.v2
.locmaxwin
;
9499 if (ssh
->mainchan
->throttling_conn
&& bufsize
<= buflimit
) {
9500 ssh
->mainchan
->throttling_conn
= 0;
9501 ssh_throttle_conn(ssh
, -1);
9507 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
9509 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
9511 struct Packet
*pktout
;
9513 logeventf(ssh
, "Opening forwarded connection to %s:%d", hostname
, port
);
9515 if (ssh
->version
== 1) {
9516 send_packet(ssh
, SSH1_MSG_PORT_OPEN
,
9517 PKT_INT
, c
->localid
,
9520 /* PKT_STR, <org:orgport>, */
9523 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
9524 ssh2_pkt_addstring(pktout
, "direct-tcpip");
9525 ssh2_pkt_adduint32(pktout
, c
->localid
);
9526 ssh2_pkt_adduint32(pktout
, c
->v
.v2
.locwindow
);/* our window size */
9527 ssh2_pkt_adduint32(pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
9528 ssh2_pkt_addstring(pktout
, hostname
);
9529 ssh2_pkt_adduint32(pktout
, port
);
9531 * We make up values for the originator data; partly it's
9532 * too much hassle to keep track, and partly I'm not
9533 * convinced the server should be told details like that
9534 * about my local network configuration.
9535 * The "originator IP address" is syntactically a numeric
9536 * IP address, and some servers (e.g., Tectia) get upset
9537 * if it doesn't match this syntax.
9539 ssh2_pkt_addstring(pktout
, "0.0.0.0");
9540 ssh2_pkt_adduint32(pktout
, 0);
9541 ssh2_pkt_send(ssh
, pktout
);
9545 static int ssh_connected(void *handle
)
9547 Ssh ssh
= (Ssh
) handle
;
9548 return ssh
->s
!= NULL
;
9551 static int ssh_sendok(void *handle
)
9553 Ssh ssh
= (Ssh
) handle
;
9554 return ssh
->send_ok
;
9557 static int ssh_ldisc(void *handle
, int option
)
9559 Ssh ssh
= (Ssh
) handle
;
9560 if (option
== LD_ECHO
)
9561 return ssh
->echoing
;
9562 if (option
== LD_EDIT
)
9563 return ssh
->editing
;
9567 static void ssh_provide_ldisc(void *handle
, void *ldisc
)
9569 Ssh ssh
= (Ssh
) handle
;
9573 static void ssh_provide_logctx(void *handle
, void *logctx
)
9575 Ssh ssh
= (Ssh
) handle
;
9576 ssh
->logctx
= logctx
;
9579 static int ssh_return_exitcode(void *handle
)
9581 Ssh ssh
= (Ssh
) handle
;
9585 return (ssh
->exitcode
>= 0 ? ssh
->exitcode
: INT_MAX
);
9589 * cfg_info for SSH is the currently running version of the
9590 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
9592 static int ssh_cfg_info(void *handle
)
9594 Ssh ssh
= (Ssh
) handle
;
9595 return ssh
->version
;
9599 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
9600 * that fails. This variable is the means by which scp.c can reach
9601 * into the SSH code and find out which one it got.
9603 extern int ssh_fallback_cmd(void *handle
)
9605 Ssh ssh
= (Ssh
) handle
;
9606 return ssh
->fallback_cmd
;
9609 Backend ssh_backend
= {
9619 ssh_return_exitcode
,