27 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
28 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
29 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
30 #define SSH1_CMSG_USER 4 /* 0x4 */
31 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
32 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
33 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
34 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
35 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
36 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
37 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
38 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
39 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
40 #define SSH1_SMSG_FAILURE 15 /* 0xf */
41 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
42 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
43 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
44 #define SSH1_CMSG_EOF 19 /* 0x13 */
45 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
46 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
47 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
48 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
49 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
50 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
51 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
52 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
53 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
54 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
55 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
56 #define SSH1_MSG_IGNORE 32 /* 0x20 */
57 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
58 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
59 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
60 #define SSH1_MSG_DEBUG 36 /* 0x24 */
61 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
62 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
63 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
64 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
65 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
66 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
67 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
69 #define SSH1_AUTH_RHOSTS 1 /* 0x1 */
70 #define SSH1_AUTH_RSA 2 /* 0x2 */
71 #define SSH1_AUTH_PASSWORD 3 /* 0x3 */
72 #define SSH1_AUTH_RHOSTS_RSA 4 /* 0x4 */
73 #define SSH1_AUTH_TIS 5 /* 0x5 */
74 #define SSH1_AUTH_CCARD 16 /* 0x10 */
76 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
77 /* Mask for protoflags we will echo back to server if seen */
78 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
80 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
81 #define SSH2_MSG_IGNORE 2 /* 0x2 */
82 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
83 #define SSH2_MSG_DEBUG 4 /* 0x4 */
84 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
85 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
86 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
87 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
88 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
89 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
90 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
91 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
92 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
93 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
94 #define SSH2_MSG_KEXRSA_PUBKEY 30 /* 0x1e */
95 #define SSH2_MSG_KEXRSA_SECRET 31 /* 0x1f */
96 #define SSH2_MSG_KEXRSA_DONE 32 /* 0x20 */
97 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
98 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
99 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
100 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
101 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
102 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
103 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
104 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
105 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
106 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
107 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
108 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
109 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
110 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
111 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
112 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
113 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
114 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
115 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
116 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
117 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
118 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
119 #define SSH2_MSG_USERAUTH_GSSAPI_RESPONSE 60
120 #define SSH2_MSG_USERAUTH_GSSAPI_TOKEN 61
121 #define SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE 63
122 #define SSH2_MSG_USERAUTH_GSSAPI_ERROR 64
123 #define SSH2_MSG_USERAUTH_GSSAPI_ERRTOK 65
124 #define SSH2_MSG_USERAUTH_GSSAPI_MIC 66
127 * Packet type contexts, so that ssh2_pkt_type can correctly decode
128 * the ambiguous type numbers back into the correct type strings.
138 SSH2_PKTCTX_PUBLICKEY
,
139 SSH2_PKTCTX_PASSWORD
,
144 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
145 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
146 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
147 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
148 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
149 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
150 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
151 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
152 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
153 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
154 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
155 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
156 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
157 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
158 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
160 static const char *const ssh2_disconnect_reasons
[] = {
162 "host not allowed to connect",
164 "key exchange failed",
165 "host authentication failed",
168 "service not available",
169 "protocol version not supported",
170 "host key not verifiable",
173 "too many connections",
174 "auth cancelled by user",
175 "no more auth methods available",
179 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
180 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
181 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
182 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
184 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
187 * Various remote-bug flags.
189 #define BUG_CHOKES_ON_SSH1_IGNORE 1
190 #define BUG_SSH2_HMAC 2
191 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
192 #define BUG_CHOKES_ON_RSA 8
193 #define BUG_SSH2_RSA_PADDING 16
194 #define BUG_SSH2_DERIVEKEY 32
195 #define BUG_SSH2_REKEY 64
196 #define BUG_SSH2_PK_SESSIONID 128
197 #define BUG_SSH2_MAXPKT 256
198 #define BUG_CHOKES_ON_SSH2_IGNORE 512
201 * Codes for terminal modes.
202 * Most of these are the same in SSH-1 and SSH-2.
203 * This list is derived from RFC 4254 and
206 static const struct {
207 const char* const mode
;
209 enum { TTY_OP_CHAR
, TTY_OP_BOOL
} type
;
211 /* "V" prefix discarded for special characters relative to SSH specs */
212 { "INTR", 1, TTY_OP_CHAR
},
213 { "QUIT", 2, TTY_OP_CHAR
},
214 { "ERASE", 3, TTY_OP_CHAR
},
215 { "KILL", 4, TTY_OP_CHAR
},
216 { "EOF", 5, TTY_OP_CHAR
},
217 { "EOL", 6, TTY_OP_CHAR
},
218 { "EOL2", 7, TTY_OP_CHAR
},
219 { "START", 8, TTY_OP_CHAR
},
220 { "STOP", 9, TTY_OP_CHAR
},
221 { "SUSP", 10, TTY_OP_CHAR
},
222 { "DSUSP", 11, TTY_OP_CHAR
},
223 { "REPRINT", 12, TTY_OP_CHAR
},
224 { "WERASE", 13, TTY_OP_CHAR
},
225 { "LNEXT", 14, TTY_OP_CHAR
},
226 { "FLUSH", 15, TTY_OP_CHAR
},
227 { "SWTCH", 16, TTY_OP_CHAR
},
228 { "STATUS", 17, TTY_OP_CHAR
},
229 { "DISCARD", 18, TTY_OP_CHAR
},
230 { "IGNPAR", 30, TTY_OP_BOOL
},
231 { "PARMRK", 31, TTY_OP_BOOL
},
232 { "INPCK", 32, TTY_OP_BOOL
},
233 { "ISTRIP", 33, TTY_OP_BOOL
},
234 { "INLCR", 34, TTY_OP_BOOL
},
235 { "IGNCR", 35, TTY_OP_BOOL
},
236 { "ICRNL", 36, TTY_OP_BOOL
},
237 { "IUCLC", 37, TTY_OP_BOOL
},
238 { "IXON", 38, TTY_OP_BOOL
},
239 { "IXANY", 39, TTY_OP_BOOL
},
240 { "IXOFF", 40, TTY_OP_BOOL
},
241 { "IMAXBEL", 41, TTY_OP_BOOL
},
242 { "ISIG", 50, TTY_OP_BOOL
},
243 { "ICANON", 51, TTY_OP_BOOL
},
244 { "XCASE", 52, TTY_OP_BOOL
},
245 { "ECHO", 53, TTY_OP_BOOL
},
246 { "ECHOE", 54, TTY_OP_BOOL
},
247 { "ECHOK", 55, TTY_OP_BOOL
},
248 { "ECHONL", 56, TTY_OP_BOOL
},
249 { "NOFLSH", 57, TTY_OP_BOOL
},
250 { "TOSTOP", 58, TTY_OP_BOOL
},
251 { "IEXTEN", 59, TTY_OP_BOOL
},
252 { "ECHOCTL", 60, TTY_OP_BOOL
},
253 { "ECHOKE", 61, TTY_OP_BOOL
},
254 { "PENDIN", 62, TTY_OP_BOOL
}, /* XXX is this a real mode? */
255 { "OPOST", 70, TTY_OP_BOOL
},
256 { "OLCUC", 71, TTY_OP_BOOL
},
257 { "ONLCR", 72, TTY_OP_BOOL
},
258 { "OCRNL", 73, TTY_OP_BOOL
},
259 { "ONOCR", 74, TTY_OP_BOOL
},
260 { "ONLRET", 75, TTY_OP_BOOL
},
261 { "CS7", 90, TTY_OP_BOOL
},
262 { "CS8", 91, TTY_OP_BOOL
},
263 { "PARENB", 92, TTY_OP_BOOL
},
264 { "PARODD", 93, TTY_OP_BOOL
}
267 /* Miscellaneous other tty-related constants. */
268 #define SSH_TTY_OP_END 0
269 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
270 #define SSH1_TTY_OP_ISPEED 192
271 #define SSH1_TTY_OP_OSPEED 193
272 #define SSH2_TTY_OP_ISPEED 128
273 #define SSH2_TTY_OP_OSPEED 129
275 /* Helper functions for parsing tty-related config. */
276 static unsigned int ssh_tty_parse_specchar(char *s
)
281 ret
= ctrlparse(s
, &next
);
282 if (!next
) ret
= s
[0];
284 ret
= 255; /* special value meaning "don't set" */
288 static unsigned int ssh_tty_parse_boolean(char *s
)
290 if (stricmp(s
, "yes") == 0 ||
291 stricmp(s
, "on") == 0 ||
292 stricmp(s
, "true") == 0 ||
293 stricmp(s
, "+") == 0)
295 else if (stricmp(s
, "no") == 0 ||
296 stricmp(s
, "off") == 0 ||
297 stricmp(s
, "false") == 0 ||
298 stricmp(s
, "-") == 0)
299 return 0; /* false */
301 return (atoi(s
) != 0);
304 #define translate(x) if (type == x) return #x
305 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
306 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
307 static char *ssh1_pkt_type(int type
)
309 translate(SSH1_MSG_DISCONNECT
);
310 translate(SSH1_SMSG_PUBLIC_KEY
);
311 translate(SSH1_CMSG_SESSION_KEY
);
312 translate(SSH1_CMSG_USER
);
313 translate(SSH1_CMSG_AUTH_RSA
);
314 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE
);
315 translate(SSH1_CMSG_AUTH_RSA_RESPONSE
);
316 translate(SSH1_CMSG_AUTH_PASSWORD
);
317 translate(SSH1_CMSG_REQUEST_PTY
);
318 translate(SSH1_CMSG_WINDOW_SIZE
);
319 translate(SSH1_CMSG_EXEC_SHELL
);
320 translate(SSH1_CMSG_EXEC_CMD
);
321 translate(SSH1_SMSG_SUCCESS
);
322 translate(SSH1_SMSG_FAILURE
);
323 translate(SSH1_CMSG_STDIN_DATA
);
324 translate(SSH1_SMSG_STDOUT_DATA
);
325 translate(SSH1_SMSG_STDERR_DATA
);
326 translate(SSH1_CMSG_EOF
);
327 translate(SSH1_SMSG_EXIT_STATUS
);
328 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
);
329 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE
);
330 translate(SSH1_MSG_CHANNEL_DATA
);
331 translate(SSH1_MSG_CHANNEL_CLOSE
);
332 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
);
333 translate(SSH1_SMSG_X11_OPEN
);
334 translate(SSH1_CMSG_PORT_FORWARD_REQUEST
);
335 translate(SSH1_MSG_PORT_OPEN
);
336 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING
);
337 translate(SSH1_SMSG_AGENT_OPEN
);
338 translate(SSH1_MSG_IGNORE
);
339 translate(SSH1_CMSG_EXIT_CONFIRMATION
);
340 translate(SSH1_CMSG_X11_REQUEST_FORWARDING
);
341 translate(SSH1_CMSG_AUTH_RHOSTS_RSA
);
342 translate(SSH1_MSG_DEBUG
);
343 translate(SSH1_CMSG_REQUEST_COMPRESSION
);
344 translate(SSH1_CMSG_AUTH_TIS
);
345 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE
);
346 translate(SSH1_CMSG_AUTH_TIS_RESPONSE
);
347 translate(SSH1_CMSG_AUTH_CCARD
);
348 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE
);
349 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE
);
352 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx
, Pkt_ACtx pkt_actx
, int type
)
354 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE
,SSH2_PKTCTX_GSSAPI
);
355 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN
,SSH2_PKTCTX_GSSAPI
);
356 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE
,SSH2_PKTCTX_GSSAPI
);
357 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR
,SSH2_PKTCTX_GSSAPI
);
358 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK
,SSH2_PKTCTX_GSSAPI
);
359 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC
, SSH2_PKTCTX_GSSAPI
);
360 translate(SSH2_MSG_DISCONNECT
);
361 translate(SSH2_MSG_IGNORE
);
362 translate(SSH2_MSG_UNIMPLEMENTED
);
363 translate(SSH2_MSG_DEBUG
);
364 translate(SSH2_MSG_SERVICE_REQUEST
);
365 translate(SSH2_MSG_SERVICE_ACCEPT
);
366 translate(SSH2_MSG_KEXINIT
);
367 translate(SSH2_MSG_NEWKEYS
);
368 translatek(SSH2_MSG_KEXDH_INIT
, SSH2_PKTCTX_DHGROUP
);
369 translatek(SSH2_MSG_KEXDH_REPLY
, SSH2_PKTCTX_DHGROUP
);
370 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST
, SSH2_PKTCTX_DHGEX
);
371 translatek(SSH2_MSG_KEX_DH_GEX_GROUP
, SSH2_PKTCTX_DHGEX
);
372 translatek(SSH2_MSG_KEX_DH_GEX_INIT
, SSH2_PKTCTX_DHGEX
);
373 translatek(SSH2_MSG_KEX_DH_GEX_REPLY
, SSH2_PKTCTX_DHGEX
);
374 translatek(SSH2_MSG_KEXRSA_PUBKEY
, SSH2_PKTCTX_RSAKEX
);
375 translatek(SSH2_MSG_KEXRSA_SECRET
, SSH2_PKTCTX_RSAKEX
);
376 translatek(SSH2_MSG_KEXRSA_DONE
, SSH2_PKTCTX_RSAKEX
);
377 translate(SSH2_MSG_USERAUTH_REQUEST
);
378 translate(SSH2_MSG_USERAUTH_FAILURE
);
379 translate(SSH2_MSG_USERAUTH_SUCCESS
);
380 translate(SSH2_MSG_USERAUTH_BANNER
);
381 translatea(SSH2_MSG_USERAUTH_PK_OK
, SSH2_PKTCTX_PUBLICKEY
);
382 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
, SSH2_PKTCTX_PASSWORD
);
383 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST
, SSH2_PKTCTX_KBDINTER
);
384 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE
, SSH2_PKTCTX_KBDINTER
);
385 translate(SSH2_MSG_GLOBAL_REQUEST
);
386 translate(SSH2_MSG_REQUEST_SUCCESS
);
387 translate(SSH2_MSG_REQUEST_FAILURE
);
388 translate(SSH2_MSG_CHANNEL_OPEN
);
389 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
390 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
391 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
392 translate(SSH2_MSG_CHANNEL_DATA
);
393 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA
);
394 translate(SSH2_MSG_CHANNEL_EOF
);
395 translate(SSH2_MSG_CHANNEL_CLOSE
);
396 translate(SSH2_MSG_CHANNEL_REQUEST
);
397 translate(SSH2_MSG_CHANNEL_SUCCESS
);
398 translate(SSH2_MSG_CHANNEL_FAILURE
);
404 /* Enumeration values for fields in SSH-1 packets */
406 PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
,
407 /* These values are for communicating relevant semantics of
408 * fields to the packet logging code. */
409 PKTT_OTHER
, PKTT_PASSWORD
, PKTT_DATA
413 * Coroutine mechanics for the sillier bits of the code. If these
414 * macros look impenetrable to you, you might find it helpful to
417 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
419 * which explains the theory behind these macros.
421 * In particular, if you are getting `case expression not constant'
422 * errors when building with MS Visual Studio, this is because MS's
423 * Edit and Continue debugging feature causes their compiler to
424 * violate ANSI C. To disable Edit and Continue debugging:
426 * - right-click ssh.c in the FileView
428 * - select the C/C++ tab and the General category
429 * - under `Debug info:', select anything _other_ than `Program
430 * Database for Edit and Continue'.
432 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
435 if (!ssh->t) ssh->t = snew(struct t); \
437 #define crFinish(z) } *crLine = 0; return (z); }
438 #define crFinishV } *crLine = 0; return; }
439 #define crReturn(z) \
441 *crLine =__LINE__; return (z); case __LINE__:;\
445 *crLine=__LINE__; return; case __LINE__:;\
447 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
448 #define crStopV do{ *crLine = 0; return; }while(0)
449 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
450 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
452 typedef struct ssh_tag
*Ssh
;
455 static struct Packet
*ssh1_pkt_init(int pkt_type
);
456 static struct Packet
*ssh2_pkt_init(int pkt_type
);
457 static void ssh_pkt_ensure(struct Packet
*, int length
);
458 static void ssh_pkt_adddata(struct Packet
*, void *data
, int len
);
459 static void ssh_pkt_addbyte(struct Packet
*, unsigned char value
);
460 static void ssh2_pkt_addbool(struct Packet
*, unsigned char value
);
461 static void ssh_pkt_adduint32(struct Packet
*, unsigned long value
);
462 static void ssh_pkt_addstring_start(struct Packet
*);
463 static void ssh_pkt_addstring_str(struct Packet
*, char *data
);
464 static void ssh_pkt_addstring_data(struct Packet
*, char *data
, int len
);
465 static void ssh_pkt_addstring(struct Packet
*, char *data
);
466 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
);
467 static void ssh1_pkt_addmp(struct Packet
*, Bignum b
);
468 static void ssh2_pkt_addmp(struct Packet
*, Bignum b
);
469 static int ssh2_pkt_construct(Ssh
, struct Packet
*);
470 static void ssh2_pkt_send(Ssh
, struct Packet
*);
471 static void ssh2_pkt_send_noqueue(Ssh
, struct Packet
*);
472 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
,
473 struct Packet
*pktin
);
474 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
,
475 struct Packet
*pktin
);
478 * Buffer management constants. There are several of these for
479 * various different purposes:
481 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
482 * on a local data stream before we throttle the whole SSH
483 * connection (in SSH-1 only). Throttling the whole connection is
484 * pretty drastic so we set this high in the hope it won't
487 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
488 * on the SSH connection itself before we defensively throttle
489 * _all_ local data streams. This is pretty drastic too (though
490 * thankfully unlikely in SSH-2 since the window mechanism should
491 * ensure that the server never has any need to throttle its end
492 * of the connection), so we set this high as well.
494 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
497 * - OUR_V2_BIGWIN is the window size we advertise for the only
498 * channel in a simple connection. It must be <= INT_MAX.
500 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
501 * to the remote side. This actually has nothing to do with the
502 * size of the _packet_, but is instead a limit on the amount
503 * of data we're willing to receive in a single SSH2 channel
506 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
507 * _packet_ we're prepared to cope with. It must be a multiple
508 * of the cipher block size, and must be at least 35000.
511 #define SSH1_BUFFER_LIMIT 32768
512 #define SSH_MAX_BACKLOG 32768
513 #define OUR_V2_WINSIZE 16384
514 #define OUR_V2_BIGWIN 0x7fffffff
515 #define OUR_V2_MAXPKT 0x4000UL
516 #define OUR_V2_PACKETLIMIT 0x9000UL
518 /* Maximum length of passwords/passphrases (arbitrary) */
519 #define SSH_MAX_PASSWORD_LEN 100
521 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
523 const static struct ssh_mac
*macs
[] = {
524 &ssh_hmac_sha1
, &ssh_hmac_sha1_96
, &ssh_hmac_md5
526 const static struct ssh_mac
*buggymacs
[] = {
527 &ssh_hmac_sha1_buggy
, &ssh_hmac_sha1_96_buggy
, &ssh_hmac_md5
530 static void *ssh_comp_none_init(void)
534 static void ssh_comp_none_cleanup(void *handle
)
537 static int ssh_comp_none_block(void *handle
, unsigned char *block
, int len
,
538 unsigned char **outblock
, int *outlen
)
542 static int ssh_comp_none_disable(void *handle
)
546 const static struct ssh_compress ssh_comp_none
= {
548 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
549 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
550 ssh_comp_none_disable
, NULL
552 extern const struct ssh_compress ssh_zlib
;
553 const static struct ssh_compress
*compressions
[] = {
554 &ssh_zlib
, &ssh_comp_none
557 enum { /* channel types */
562 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
566 * little structure to keep track of outstanding WINDOW_ADJUSTs
574 * 2-3-4 tree storing channels.
577 Ssh ssh
; /* pointer back to main context */
578 unsigned remoteid
, localid
;
580 /* True if we opened this channel but server hasn't confirmed. */
583 * In SSH-1, this value contains four bits:
585 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
586 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
587 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
588 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
590 * A channel is completely finished with when all four bits are set.
595 * This flag indicates that a close is pending on the outgoing
596 * side of the channel: that is, wherever we're getting the data
597 * for this channel has sent us some data followed by EOF. We
598 * can't actually close the channel until we've finished sending
599 * the data, so we set this flag instead to remind us to
600 * initiate the closing process once our buffer is clear.
605 * True if this channel is causing the underlying connection to be
610 struct ssh2_data_channel
{
612 unsigned remwindow
, remmaxpkt
;
613 /* locwindow is signed so we can cope with excess data. */
614 int locwindow
, locmaxwin
;
616 * remlocwin is the amount of local window that we think
617 * the remote end had available to it after it sent the
618 * last data packet or window adjust ack.
622 * These store the list of window adjusts that haven't
625 struct winadj
*winadj_head
, *winadj_tail
;
626 enum { THROTTLED
, UNTHROTTLING
, UNTHROTTLED
} throttle_state
;
630 struct ssh_agent_channel
{
631 unsigned char *message
;
632 unsigned char msglen
[4];
633 unsigned lensofar
, totallen
;
635 struct ssh_x11_channel
{
638 struct ssh_pfd_channel
{
645 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
646 * use this structure in different ways, reflecting SSH-2's
647 * altogether saner approach to port forwarding.
649 * In SSH-1, you arrange a remote forwarding by sending the server
650 * the remote port number, and the local destination host:port.
651 * When a connection comes in, the server sends you back that
652 * host:port pair, and you connect to it. This is a ready-made
653 * security hole if you're not on the ball: a malicious server
654 * could send you back _any_ host:port pair, so if you trustingly
655 * connect to the address it gives you then you've just opened the
656 * entire inside of your corporate network just by connecting
657 * through it to a dodgy SSH server. Hence, we must store a list of
658 * host:port pairs we _are_ trying to forward to, and reject a
659 * connection request from the server if it's not in the list.
661 * In SSH-2, each side of the connection minds its own business and
662 * doesn't send unnecessary information to the other. You arrange a
663 * remote forwarding by sending the server just the remote port
664 * number. When a connection comes in, the server tells you which
665 * of its ports was connected to; and _you_ have to remember what
666 * local host:port pair went with that port number.
668 * Hence, in SSH-1 this structure is indexed by destination
669 * host:port pair, whereas in SSH-2 it is indexed by source port.
671 struct ssh_portfwd
; /* forward declaration */
673 struct ssh_rportfwd
{
674 unsigned sport
, dport
;
677 struct ssh_portfwd
*pfrec
;
679 #define free_rportfwd(pf) ( \
680 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
683 * Separately to the rportfwd tree (which is for looking up port
684 * open requests from the server), a tree of _these_ structures is
685 * used to keep track of all the currently open port forwardings,
686 * so that we can reconfigure in mid-session if the user requests
690 enum { DESTROY
, KEEP
, CREATE
} status
;
692 unsigned sport
, dport
;
695 struct ssh_rportfwd
*remote
;
699 #define free_portfwd(pf) ( \
700 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
701 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
704 long length
; /* length of `data' actually used */
705 long forcepad
; /* SSH-2: force padding to at least this length */
706 int type
; /* only used for incoming packets */
707 unsigned long sequence
; /* SSH-2 incoming sequence number */
708 unsigned char *data
; /* allocated storage */
709 unsigned char *body
; /* offset of payload within `data' */
710 long savedpos
; /* temporary index into `data' (for strings) */
711 long maxlen
; /* amount of storage allocated for `data' */
712 long encrypted_len
; /* for SSH-2 total-size counting */
715 * State associated with packet logging
719 struct logblank_t
*blanks
;
722 static void ssh1_protocol(Ssh ssh
, void *vin
, int inlen
,
723 struct Packet
*pktin
);
724 static void ssh2_protocol(Ssh ssh
, void *vin
, int inlen
,
725 struct Packet
*pktin
);
726 static void ssh1_protocol_setup(Ssh ssh
);
727 static void ssh2_protocol_setup(Ssh ssh
);
728 static void ssh_size(void *handle
, int width
, int height
);
729 static void ssh_special(void *handle
, Telnet_Special
);
730 static int ssh2_try_send(struct ssh_channel
*c
);
731 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
);
732 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
);
733 static void ssh2_set_window(struct ssh_channel
*c
, int newwin
);
734 static int ssh_sendbuffer(void *handle
);
735 static int ssh_do_close(Ssh ssh
, int notify_exit
);
736 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
);
737 static int ssh2_pkt_getbool(struct Packet
*pkt
);
738 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
);
739 static void ssh2_timer(void *ctx
, long now
);
740 static int do_ssh2_transport(Ssh ssh
, void *vin
, int inlen
,
741 struct Packet
*pktin
);
743 struct rdpkt1_state_tag
{
744 long len
, pad
, biglen
, to_read
;
745 unsigned long realcrc
, gotcrc
;
749 struct Packet
*pktin
;
752 struct rdpkt2_state_tag
{
753 long len
, pad
, payload
, packetlen
, maclen
;
756 unsigned long incoming_sequence
;
757 struct Packet
*pktin
;
760 typedef void (*handler_fn_t
)(Ssh ssh
, struct Packet
*pktin
);
761 typedef void (*chandler_fn_t
)(Ssh ssh
, struct Packet
*pktin
, void *ctx
);
763 struct queued_handler
;
764 struct queued_handler
{
766 chandler_fn_t handler
;
768 struct queued_handler
*next
;
772 const struct plug_function_table
*fn
;
773 /* the above field _must_ be first in the structure */
783 unsigned char session_key
[32];
785 int v1_remote_protoflags
;
786 int v1_local_protoflags
;
787 int agentfwd_enabled
;
790 const struct ssh_cipher
*cipher
;
793 const struct ssh2_cipher
*cscipher
, *sccipher
;
794 void *cs_cipher_ctx
, *sc_cipher_ctx
;
795 const struct ssh_mac
*csmac
, *scmac
;
796 void *cs_mac_ctx
, *sc_mac_ctx
;
797 const struct ssh_compress
*cscomp
, *sccomp
;
798 void *cs_comp_ctx
, *sc_comp_ctx
;
799 const struct ssh_kex
*kex
;
800 const struct ssh_signkey
*hostkey
;
801 unsigned char v2_session_id
[SSH2_KEX_MAX_HASH_LEN
];
802 int v2_session_id_len
;
808 int echoing
, editing
;
812 int ospeed
, ispeed
; /* temporaries */
813 int term_width
, term_height
;
815 tree234
*channels
; /* indexed by local id */
816 struct ssh_channel
*mainchan
; /* primary session channel */
817 int ncmode
; /* is primary channel direct-tcpip? */
822 tree234
*rportfwds
, *portfwds
;
826 SSH_STATE_BEFORE_SIZE
,
832 int size_needed
, eof_needed
;
834 struct Packet
**queue
;
835 int queuelen
, queuesize
;
837 unsigned char *deferred_send_data
;
838 int deferred_len
, deferred_size
;
841 * Gross hack: pscp will try to start SFTP but fall back to
842 * scp1 if that fails. This variable is the means by which
843 * scp.c can reach into the SSH code and find out which one it
848 bufchain banner
; /* accumulates banners during do_ssh2_authconn */
853 struct X11Display
*x11disp
;
856 int conn_throttle_count
;
859 int v1_stdout_throttling
;
860 unsigned long v2_outgoing_sequence
;
862 int ssh1_rdpkt_crstate
;
863 int ssh2_rdpkt_crstate
;
864 int do_ssh_init_crstate
;
865 int ssh_gotdata_crstate
;
866 int do_ssh1_login_crstate
;
867 int do_ssh1_connection_crstate
;
868 int do_ssh2_transport_crstate
;
869 int do_ssh2_authconn_crstate
;
871 void *do_ssh_init_state
;
872 void *do_ssh1_login_state
;
873 void *do_ssh2_transport_state
;
874 void *do_ssh2_authconn_state
;
876 struct rdpkt1_state_tag rdpkt1_state
;
877 struct rdpkt2_state_tag rdpkt2_state
;
879 /* SSH-1 and SSH-2 use this for different things, but both use it */
880 int protocol_initial_phase_done
;
882 void (*protocol
) (Ssh ssh
, void *vin
, int inlen
,
884 struct Packet
*(*s_rdpkt
) (Ssh ssh
, unsigned char **data
, int *datalen
);
887 * We maintain a full _copy_ of a Config structure here, not
888 * merely a pointer to it. That way, when we're passed a new
889 * one for reconfiguration, we can check the differences and
890 * potentially reconfigure port forwardings etc in mid-session.
895 * Used to transfer data back from async callbacks.
897 void *agent_response
;
898 int agent_response_len
;
902 * The SSH connection can be set as `frozen', meaning we are
903 * not currently accepting incoming data from the network. This
904 * is slightly more serious than setting the _socket_ as
905 * frozen, because we may already have had data passed to us
906 * from the network which we need to delay processing until
907 * after the freeze is lifted, so we also need a bufchain to
911 bufchain queued_incoming_data
;
914 * Dispatch table for packet types that we may have to deal
917 handler_fn_t packet_dispatch
[256];
920 * Queues of one-off handler functions for success/failure
921 * indications from a request.
923 struct queued_handler
*qhead
, *qtail
;
926 * This module deals with sending keepalives.
931 * Track incoming and outgoing data sizes and time, for
934 unsigned long incoming_data_size
, outgoing_data_size
, deferred_data_size
;
935 unsigned long max_data_size
;
937 long next_rekey
, last_rekey
;
938 char *deferred_rekey_reason
; /* points to STATIC string; don't free */
941 * Fully qualified host name, which we need if doing GSSAPI.
947 * GSSAPI libraries for this session.
949 struct ssh_gss_liblist
*gsslibs
;
953 #define logevent(s) logevent(ssh->frontend, s)
955 /* logevent, only printf-formatted. */
956 static void logeventf(Ssh ssh
, const char *fmt
, ...)
962 buf
= dupvprintf(fmt
, ap
);
968 #define bombout(msg) \
970 char *text = dupprintf msg; \
971 ssh_do_close(ssh, FALSE); \
973 connection_fatal(ssh->frontend, "%s", text); \
977 /* Functions to leave bits out of the SSH packet log file. */
979 static void dont_log_password(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
981 if (ssh
->cfg
.logomitpass
)
982 pkt
->logmode
= blanktype
;
985 static void dont_log_data(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
987 if (ssh
->cfg
.logomitdata
)
988 pkt
->logmode
= blanktype
;
991 static void end_log_omission(Ssh ssh
, struct Packet
*pkt
)
993 pkt
->logmode
= PKTLOG_EMIT
;
996 /* Helper function for common bits of parsing cfg.ttymodes. */
997 static void parse_ttymodes(Ssh ssh
, char *modes
,
998 void (*do_mode
)(void *data
, char *mode
, char *val
),
1002 char *t
= strchr(modes
, '\t');
1003 char *m
= snewn(t
-modes
+1, char);
1005 strncpy(m
, modes
, t
-modes
);
1008 val
= get_ttymode(ssh
->frontend
, m
);
1012 do_mode(data
, m
, val
);
1015 modes
+= strlen(modes
) + 1;
1019 static int ssh_channelcmp(void *av
, void *bv
)
1021 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
1022 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
1023 if (a
->localid
< b
->localid
)
1025 if (a
->localid
> b
->localid
)
1029 static int ssh_channelfind(void *av
, void *bv
)
1031 unsigned *a
= (unsigned *) av
;
1032 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
1033 if (*a
< b
->localid
)
1035 if (*a
> b
->localid
)
1040 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
1042 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
1043 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
1045 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
1046 return i
< 0 ?
-1 : +1;
1047 if (a
->dport
> b
->dport
)
1049 if (a
->dport
< b
->dport
)
1054 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
1056 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
1057 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
1059 if (a
->sport
> b
->sport
)
1061 if (a
->sport
< b
->sport
)
1067 * Special form of strcmp which can cope with NULL inputs. NULL is
1068 * defined to sort before even the empty string.
1070 static int nullstrcmp(const char *a
, const char *b
)
1072 if (a
== NULL
&& b
== NULL
)
1078 return strcmp(a
, b
);
1081 static int ssh_portcmp(void *av
, void *bv
)
1083 struct ssh_portfwd
*a
= (struct ssh_portfwd
*) av
;
1084 struct ssh_portfwd
*b
= (struct ssh_portfwd
*) bv
;
1086 if (a
->type
> b
->type
)
1088 if (a
->type
< b
->type
)
1090 if (a
->addressfamily
> b
->addressfamily
)
1092 if (a
->addressfamily
< b
->addressfamily
)
1094 if ( (i
= nullstrcmp(a
->saddr
, b
->saddr
)) != 0)
1095 return i
< 0 ?
-1 : +1;
1096 if (a
->sport
> b
->sport
)
1098 if (a
->sport
< b
->sport
)
1100 if (a
->type
!= 'D') {
1101 if ( (i
= nullstrcmp(a
->daddr
, b
->daddr
)) != 0)
1102 return i
< 0 ?
-1 : +1;
1103 if (a
->dport
> b
->dport
)
1105 if (a
->dport
< b
->dport
)
1111 static int alloc_channel_id(Ssh ssh
)
1113 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
1114 unsigned low
, high
, mid
;
1116 struct ssh_channel
*c
;
1119 * First-fit allocation of channel numbers: always pick the
1120 * lowest unused one. To do this, binary-search using the
1121 * counted B-tree to find the largest channel ID which is in a
1122 * contiguous sequence from the beginning. (Precisely
1123 * everything in that sequence must have ID equal to its tree
1124 * index plus CHANNEL_NUMBER_OFFSET.)
1126 tsize
= count234(ssh
->channels
);
1130 while (high
- low
> 1) {
1131 mid
= (high
+ low
) / 2;
1132 c
= index234(ssh
->channels
, mid
);
1133 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
1134 low
= mid
; /* this one is fine */
1136 high
= mid
; /* this one is past it */
1139 * Now low points to either -1, or the tree index of the
1140 * largest ID in the initial sequence.
1143 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
1144 assert(NULL
== find234(ssh
->channels
, &i
, ssh_channelfind
));
1146 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
1149 static void c_write_stderr(int trusted
, const char *buf
, int len
)
1152 for (i
= 0; i
< len
; i
++)
1153 if (buf
[i
] != '\r' && (trusted
|| buf
[i
] == '\n' || (buf
[i
] & 0x60)))
1154 fputc(buf
[i
], stderr
);
1157 static void c_write(Ssh ssh
, const char *buf
, int len
)
1159 if (flags
& FLAG_STDERR
)
1160 c_write_stderr(1, buf
, len
);
1162 from_backend(ssh
->frontend
, 1, buf
, len
);
1165 static void c_write_untrusted(Ssh ssh
, const char *buf
, int len
)
1167 if (flags
& FLAG_STDERR
)
1168 c_write_stderr(0, buf
, len
);
1170 from_backend_untrusted(ssh
->frontend
, buf
, len
);
1173 static void c_write_str(Ssh ssh
, const char *buf
)
1175 c_write(ssh
, buf
, strlen(buf
));
1178 static void ssh_free_packet(struct Packet
*pkt
)
1183 static struct Packet
*ssh_new_packet(void)
1185 struct Packet
*pkt
= snew(struct Packet
);
1187 pkt
->body
= pkt
->data
= NULL
;
1189 pkt
->logmode
= PKTLOG_EMIT
;
1197 * Collect incoming data in the incoming packet buffer.
1198 * Decipher and verify the packet when it is completely read.
1199 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1200 * Update the *data and *datalen variables.
1201 * Return a Packet structure when a packet is completed.
1203 static struct Packet
*ssh1_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
1205 struct rdpkt1_state_tag
*st
= &ssh
->rdpkt1_state
;
1207 crBegin(ssh
->ssh1_rdpkt_crstate
);
1209 st
->pktin
= ssh_new_packet();
1211 st
->pktin
->type
= 0;
1212 st
->pktin
->length
= 0;
1214 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
1215 while ((*datalen
) == 0)
1217 st
->len
= (st
->len
<< 8) + **data
;
1218 (*data
)++, (*datalen
)--;
1221 st
->pad
= 8 - (st
->len
% 8);
1222 st
->biglen
= st
->len
+ st
->pad
;
1223 st
->pktin
->length
= st
->len
- 5;
1225 if (st
->biglen
< 0) {
1226 bombout(("Extremely large packet length from server suggests"
1227 " data stream corruption"));
1228 ssh_free_packet(st
->pktin
);
1232 st
->pktin
->maxlen
= st
->biglen
;
1233 st
->pktin
->data
= snewn(st
->biglen
+ APIEXTRA
, unsigned char);
1235 st
->to_read
= st
->biglen
;
1236 st
->p
= st
->pktin
->data
;
1237 while (st
->to_read
> 0) {
1238 st
->chunk
= st
->to_read
;
1239 while ((*datalen
) == 0)
1241 if (st
->chunk
> (*datalen
))
1242 st
->chunk
= (*datalen
);
1243 memcpy(st
->p
, *data
, st
->chunk
);
1245 *datalen
-= st
->chunk
;
1247 st
->to_read
-= st
->chunk
;
1250 if (ssh
->cipher
&& detect_attack(ssh
->crcda_ctx
, st
->pktin
->data
,
1251 st
->biglen
, NULL
)) {
1252 bombout(("Network attack (CRC compensation) detected!"));
1253 ssh_free_packet(st
->pktin
);
1258 ssh
->cipher
->decrypt(ssh
->v1_cipher_ctx
, st
->pktin
->data
, st
->biglen
);
1260 st
->realcrc
= crc32_compute(st
->pktin
->data
, st
->biglen
- 4);
1261 st
->gotcrc
= GET_32BIT(st
->pktin
->data
+ st
->biglen
- 4);
1262 if (st
->gotcrc
!= st
->realcrc
) {
1263 bombout(("Incorrect CRC received on packet"));
1264 ssh_free_packet(st
->pktin
);
1268 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
1269 st
->pktin
->savedpos
= 0;
1271 if (ssh
->v1_compressing
) {
1272 unsigned char *decompblk
;
1274 if (!zlib_decompress_block(ssh
->sc_comp_ctx
,
1275 st
->pktin
->body
- 1, st
->pktin
->length
+ 1,
1276 &decompblk
, &decomplen
)) {
1277 bombout(("Zlib decompression encountered invalid data"));
1278 ssh_free_packet(st
->pktin
);
1282 if (st
->pktin
->maxlen
< st
->pad
+ decomplen
) {
1283 st
->pktin
->maxlen
= st
->pad
+ decomplen
;
1284 st
->pktin
->data
= sresize(st
->pktin
->data
,
1285 st
->pktin
->maxlen
+ APIEXTRA
,
1287 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
1290 memcpy(st
->pktin
->body
- 1, decompblk
, decomplen
);
1292 st
->pktin
->length
= decomplen
- 1;
1295 st
->pktin
->type
= st
->pktin
->body
[-1];
1298 * Log incoming packet, possibly omitting sensitive fields.
1302 struct logblank_t blank
;
1303 if (ssh
->cfg
.logomitdata
) {
1304 int do_blank
= FALSE
, blank_prefix
= 0;
1305 /* "Session data" packets - omit the data field */
1306 if ((st
->pktin
->type
== SSH1_SMSG_STDOUT_DATA
) ||
1307 (st
->pktin
->type
== SSH1_SMSG_STDERR_DATA
)) {
1308 do_blank
= TRUE
; blank_prefix
= 4;
1309 } else if (st
->pktin
->type
== SSH1_MSG_CHANNEL_DATA
) {
1310 do_blank
= TRUE
; blank_prefix
= 8;
1313 blank
.offset
= blank_prefix
;
1314 blank
.len
= st
->pktin
->length
;
1315 blank
.type
= PKTLOG_OMIT
;
1319 log_packet(ssh
->logctx
,
1320 PKT_INCOMING
, st
->pktin
->type
,
1321 ssh1_pkt_type(st
->pktin
->type
),
1322 st
->pktin
->body
, st
->pktin
->length
,
1323 nblanks
, &blank
, NULL
);
1326 crFinish(st
->pktin
);
1329 static struct Packet
*ssh2_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
1331 struct rdpkt2_state_tag
*st
= &ssh
->rdpkt2_state
;
1333 crBegin(ssh
->ssh2_rdpkt_crstate
);
1335 st
->pktin
= ssh_new_packet();
1337 st
->pktin
->type
= 0;
1338 st
->pktin
->length
= 0;
1340 st
->cipherblk
= ssh
->sccipher
->blksize
;
1343 if (st
->cipherblk
< 8)
1345 st
->maclen
= ssh
->scmac ? ssh
->scmac
->len
: 0;
1347 if (ssh
->sccipher
&& (ssh
->sccipher
->flags
& SSH_CIPHER_IS_CBC
) &&
1350 * When dealing with a CBC-mode cipher, we want to avoid the
1351 * possibility of an attacker's tweaking the ciphertext stream
1352 * so as to cause us to feed the same block to the block
1353 * cipher more than once and thus leak information
1354 * (VU#958563). The way we do this is not to take any
1355 * decisions on the basis of anything we've decrypted until
1356 * we've verified it with a MAC. That includes the packet
1357 * length, so we just read data and check the MAC repeatedly,
1358 * and when the MAC passes, see if the length we've got is
1362 /* May as well allocate the whole lot now. */
1363 st
->pktin
->data
= snewn(OUR_V2_PACKETLIMIT
+ st
->maclen
+ APIEXTRA
,
1366 /* Read an amount corresponding to the MAC. */
1367 for (st
->i
= 0; st
->i
< st
->maclen
; st
->i
++) {
1368 while ((*datalen
) == 0)
1370 st
->pktin
->data
[st
->i
] = *(*data
)++;
1376 unsigned char seq
[4];
1377 ssh
->scmac
->start(ssh
->sc_mac_ctx
);
1378 PUT_32BIT(seq
, st
->incoming_sequence
);
1379 ssh
->scmac
->bytes(ssh
->sc_mac_ctx
, seq
, 4);
1382 for (;;) { /* Once around this loop per cipher block. */
1383 /* Read another cipher-block's worth, and tack it onto the end. */
1384 for (st
->i
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
1385 while ((*datalen
) == 0)
1387 st
->pktin
->data
[st
->packetlen
+st
->maclen
+st
->i
] = *(*data
)++;
1390 /* Decrypt one more block (a little further back in the stream). */
1391 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1392 st
->pktin
->data
+ st
->packetlen
,
1394 /* Feed that block to the MAC. */
1395 ssh
->scmac
->bytes(ssh
->sc_mac_ctx
,
1396 st
->pktin
->data
+ st
->packetlen
, st
->cipherblk
);
1397 st
->packetlen
+= st
->cipherblk
;
1398 /* See if that gives us a valid packet. */
1399 if (ssh
->scmac
->verresult(ssh
->sc_mac_ctx
,
1400 st
->pktin
->data
+ st
->packetlen
) &&
1401 (st
->len
= GET_32BIT(st
->pktin
->data
)) + 4 == st
->packetlen
)
1403 if (st
->packetlen
>= OUR_V2_PACKETLIMIT
) {
1404 bombout(("No valid incoming packet found"));
1405 ssh_free_packet(st
->pktin
);
1409 st
->pktin
->maxlen
= st
->packetlen
+ st
->maclen
;
1410 st
->pktin
->data
= sresize(st
->pktin
->data
,
1411 st
->pktin
->maxlen
+ APIEXTRA
,
1414 st
->pktin
->data
= snewn(st
->cipherblk
+ APIEXTRA
, unsigned char);
1417 * Acquire and decrypt the first block of the packet. This will
1418 * contain the length and padding details.
1420 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
1421 while ((*datalen
) == 0)
1423 st
->pktin
->data
[st
->i
] = *(*data
)++;
1428 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1429 st
->pktin
->data
, st
->cipherblk
);
1432 * Now get the length figure.
1434 st
->len
= GET_32BIT(st
->pktin
->data
);
1437 * _Completely_ silly lengths should be stomped on before they
1438 * do us any more damage.
1440 if (st
->len
< 0 || st
->len
> OUR_V2_PACKETLIMIT
||
1441 (st
->len
+ 4) % st
->cipherblk
!= 0) {
1442 bombout(("Incoming packet was garbled on decryption"));
1443 ssh_free_packet(st
->pktin
);
1448 * So now we can work out the total packet length.
1450 st
->packetlen
= st
->len
+ 4;
1453 * Allocate memory for the rest of the packet.
1455 st
->pktin
->maxlen
= st
->packetlen
+ st
->maclen
;
1456 st
->pktin
->data
= sresize(st
->pktin
->data
,
1457 st
->pktin
->maxlen
+ APIEXTRA
,
1461 * Read and decrypt the remainder of the packet.
1463 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
1465 while ((*datalen
) == 0)
1467 st
->pktin
->data
[st
->i
] = *(*data
)++;
1470 /* Decrypt everything _except_ the MAC. */
1472 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1473 st
->pktin
->data
+ st
->cipherblk
,
1474 st
->packetlen
- st
->cipherblk
);
1480 && !ssh
->scmac
->verify(ssh
->sc_mac_ctx
, st
->pktin
->data
,
1481 st
->len
+ 4, st
->incoming_sequence
)) {
1482 bombout(("Incorrect MAC received on packet"));
1483 ssh_free_packet(st
->pktin
);
1487 /* Get and sanity-check the amount of random padding. */
1488 st
->pad
= st
->pktin
->data
[4];
1489 if (st
->pad
< 4 || st
->len
- st
->pad
< 1) {
1490 bombout(("Invalid padding length on received packet"));
1491 ssh_free_packet(st
->pktin
);
1495 * This enables us to deduce the payload length.
1497 st
->payload
= st
->len
- st
->pad
- 1;
1499 st
->pktin
->length
= st
->payload
+ 5;
1500 st
->pktin
->encrypted_len
= st
->packetlen
;
1502 st
->pktin
->sequence
= st
->incoming_sequence
++;
1505 * Decompress packet payload.
1508 unsigned char *newpayload
;
1511 ssh
->sccomp
->decompress(ssh
->sc_comp_ctx
,
1512 st
->pktin
->data
+ 5, st
->pktin
->length
- 5,
1513 &newpayload
, &newlen
)) {
1514 if (st
->pktin
->maxlen
< newlen
+ 5) {
1515 st
->pktin
->maxlen
= newlen
+ 5;
1516 st
->pktin
->data
= sresize(st
->pktin
->data
,
1517 st
->pktin
->maxlen
+ APIEXTRA
,
1520 st
->pktin
->length
= 5 + newlen
;
1521 memcpy(st
->pktin
->data
+ 5, newpayload
, newlen
);
1526 st
->pktin
->savedpos
= 6;
1527 st
->pktin
->body
= st
->pktin
->data
;
1528 st
->pktin
->type
= st
->pktin
->data
[5];
1531 * Log incoming packet, possibly omitting sensitive fields.
1535 struct logblank_t blank
;
1536 if (ssh
->cfg
.logomitdata
) {
1537 int do_blank
= FALSE
, blank_prefix
= 0;
1538 /* "Session data" packets - omit the data field */
1539 if (st
->pktin
->type
== SSH2_MSG_CHANNEL_DATA
) {
1540 do_blank
= TRUE
; blank_prefix
= 8;
1541 } else if (st
->pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
1542 do_blank
= TRUE
; blank_prefix
= 12;
1545 blank
.offset
= blank_prefix
;
1546 blank
.len
= (st
->pktin
->length
-6) - blank_prefix
;
1547 blank
.type
= PKTLOG_OMIT
;
1551 log_packet(ssh
->logctx
, PKT_INCOMING
, st
->pktin
->type
,
1552 ssh2_pkt_type(ssh
->pkt_kctx
, ssh
->pkt_actx
,
1554 st
->pktin
->data
+6, st
->pktin
->length
-6,
1555 nblanks
, &blank
, &st
->pktin
->sequence
);
1558 crFinish(st
->pktin
);
1561 static int s_wrpkt_prepare(Ssh ssh
, struct Packet
*pkt
, int *offset_p
)
1563 int pad
, biglen
, i
, pktoffs
;
1567 * XXX various versions of SC (including 8.8.4) screw up the
1568 * register allocation in this function and use the same register
1569 * (D6) for len and as a temporary, with predictable results. The
1570 * following sledgehammer prevents this.
1577 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->data
[12],
1578 ssh1_pkt_type(pkt
->data
[12]),
1579 pkt
->body
, pkt
->length
- (pkt
->body
- pkt
->data
),
1580 pkt
->nblanks
, pkt
->blanks
, NULL
);
1581 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1584 if (ssh
->v1_compressing
) {
1585 unsigned char *compblk
;
1587 zlib_compress_block(ssh
->cs_comp_ctx
,
1588 pkt
->data
+ 12, pkt
->length
- 12,
1589 &compblk
, &complen
);
1590 ssh_pkt_ensure(pkt
, complen
+ 2); /* just in case it's got bigger */
1591 memcpy(pkt
->data
+ 12, compblk
, complen
);
1593 pkt
->length
= complen
+ 12;
1596 ssh_pkt_ensure(pkt
, pkt
->length
+ 4); /* space for CRC */
1598 len
= pkt
->length
- 4 - 8; /* len(type+data+CRC) */
1599 pad
= 8 - (len
% 8);
1601 biglen
= len
+ pad
; /* len(padding+type+data+CRC) */
1603 for (i
= pktoffs
; i
< 4+8; i
++)
1604 pkt
->data
[i
] = random_byte();
1605 crc
= crc32_compute(pkt
->data
+ pktoffs
+ 4, biglen
- 4); /* all ex len */
1606 PUT_32BIT(pkt
->data
+ pktoffs
+ 4 + biglen
- 4, crc
);
1607 PUT_32BIT(pkt
->data
+ pktoffs
, len
);
1610 ssh
->cipher
->encrypt(ssh
->v1_cipher_ctx
,
1611 pkt
->data
+ pktoffs
+ 4, biglen
);
1613 if (offset_p
) *offset_p
= pktoffs
;
1614 return biglen
+ 4; /* len(length+padding+type+data+CRC) */
1617 static int s_write(Ssh ssh
, void *data
, int len
)
1620 log_packet(ssh
->logctx
, PKT_OUTGOING
, -1, NULL
, data
, len
,
1622 return sk_write(ssh
->s
, (char *)data
, len
);
1625 static void s_wrpkt(Ssh ssh
, struct Packet
*pkt
)
1627 int len
, backlog
, offset
;
1628 len
= s_wrpkt_prepare(ssh
, pkt
, &offset
);
1629 backlog
= s_write(ssh
, pkt
->data
+ offset
, len
);
1630 if (backlog
> SSH_MAX_BACKLOG
)
1631 ssh_throttle_all(ssh
, 1, backlog
);
1632 ssh_free_packet(pkt
);
1635 static void s_wrpkt_defer(Ssh ssh
, struct Packet
*pkt
)
1638 len
= s_wrpkt_prepare(ssh
, pkt
, &offset
);
1639 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1640 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1641 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
1645 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
,
1646 pkt
->data
+ offset
, len
);
1647 ssh
->deferred_len
+= len
;
1648 ssh_free_packet(pkt
);
1652 * Construct a SSH-1 packet with the specified contents.
1653 * (This all-at-once interface used to be the only one, but now SSH-1
1654 * packets can also be constructed incrementally.)
1656 static struct Packet
*construct_packet(Ssh ssh
, int pkttype
, va_list ap
)
1662 pkt
= ssh1_pkt_init(pkttype
);
1664 while ((argtype
= va_arg(ap
, int)) != PKT_END
) {
1665 unsigned char *argp
, argchar
;
1667 unsigned long argint
;
1670 /* Actual fields in the packet */
1672 argint
= va_arg(ap
, int);
1673 ssh_pkt_adduint32(pkt
, argint
);
1676 argchar
= (unsigned char) va_arg(ap
, int);
1677 ssh_pkt_addbyte(pkt
, argchar
);
1680 argp
= va_arg(ap
, unsigned char *);
1681 arglen
= va_arg(ap
, int);
1682 ssh_pkt_adddata(pkt
, argp
, arglen
);
1685 sargp
= va_arg(ap
, char *);
1686 ssh_pkt_addstring(pkt
, sargp
);
1689 bn
= va_arg(ap
, Bignum
);
1690 ssh1_pkt_addmp(pkt
, bn
);
1692 /* Tokens for modifications to packet logging */
1694 dont_log_password(ssh
, pkt
, PKTLOG_BLANK
);
1697 dont_log_data(ssh
, pkt
, PKTLOG_OMIT
);
1700 end_log_omission(ssh
, pkt
);
1708 static void send_packet(Ssh ssh
, int pkttype
, ...)
1712 va_start(ap
, pkttype
);
1713 pkt
= construct_packet(ssh
, pkttype
, ap
);
1718 static void defer_packet(Ssh ssh
, int pkttype
, ...)
1722 va_start(ap
, pkttype
);
1723 pkt
= construct_packet(ssh
, pkttype
, ap
);
1725 s_wrpkt_defer(ssh
, pkt
);
1728 static int ssh_versioncmp(char *a
, char *b
)
1731 unsigned long av
, bv
;
1733 av
= strtoul(a
, &ae
, 10);
1734 bv
= strtoul(b
, &be
, 10);
1736 return (av
< bv ?
-1 : +1);
1741 av
= strtoul(ae
, &ae
, 10);
1742 bv
= strtoul(be
, &be
, 10);
1744 return (av
< bv ?
-1 : +1);
1749 * Utility routines for putting an SSH-protocol `string' and
1750 * `uint32' into a hash state.
1752 static void hash_string(const struct ssh_hash
*h
, void *s
, void *str
, int len
)
1754 unsigned char lenblk
[4];
1755 PUT_32BIT(lenblk
, len
);
1756 h
->bytes(s
, lenblk
, 4);
1757 h
->bytes(s
, str
, len
);
1760 static void hash_uint32(const struct ssh_hash
*h
, void *s
, unsigned i
)
1762 unsigned char intblk
[4];
1763 PUT_32BIT(intblk
, i
);
1764 h
->bytes(s
, intblk
, 4);
1768 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1770 static void ssh_pkt_ensure(struct Packet
*pkt
, int length
)
1772 if (pkt
->maxlen
< length
) {
1773 unsigned char *body
= pkt
->body
;
1774 int offset
= body ? body
- pkt
->data
: 0;
1775 pkt
->maxlen
= length
+ 256;
1776 pkt
->data
= sresize(pkt
->data
, pkt
->maxlen
+ APIEXTRA
, unsigned char);
1777 if (body
) pkt
->body
= pkt
->data
+ offset
;
1780 static void ssh_pkt_adddata(struct Packet
*pkt
, void *data
, int len
)
1782 if (pkt
->logmode
!= PKTLOG_EMIT
) {
1784 pkt
->blanks
= sresize(pkt
->blanks
, pkt
->nblanks
, struct logblank_t
);
1786 pkt
->blanks
[pkt
->nblanks
-1].offset
= pkt
->length
-
1787 (pkt
->body
- pkt
->data
);
1788 pkt
->blanks
[pkt
->nblanks
-1].len
= len
;
1789 pkt
->blanks
[pkt
->nblanks
-1].type
= pkt
->logmode
;
1792 ssh_pkt_ensure(pkt
, pkt
->length
);
1793 memcpy(pkt
->data
+ pkt
->length
- len
, data
, len
);
1795 static void ssh_pkt_addbyte(struct Packet
*pkt
, unsigned char byte
)
1797 ssh_pkt_adddata(pkt
, &byte
, 1);
1799 static void ssh2_pkt_addbool(struct Packet
*pkt
, unsigned char value
)
1801 ssh_pkt_adddata(pkt
, &value
, 1);
1803 static void ssh_pkt_adduint32(struct Packet
*pkt
, unsigned long value
)
1806 PUT_32BIT(x
, value
);
1807 ssh_pkt_adddata(pkt
, x
, 4);
1809 static void ssh_pkt_addstring_start(struct Packet
*pkt
)
1811 ssh_pkt_adduint32(pkt
, 0);
1812 pkt
->savedpos
= pkt
->length
;
1814 static void ssh_pkt_addstring_str(struct Packet
*pkt
, char *data
)
1816 ssh_pkt_adddata(pkt
, data
, strlen(data
));
1817 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1819 static void ssh_pkt_addstring_data(struct Packet
*pkt
, char *data
, int len
)
1821 ssh_pkt_adddata(pkt
, data
, len
);
1822 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1824 static void ssh_pkt_addstring(struct Packet
*pkt
, char *data
)
1826 ssh_pkt_addstring_start(pkt
);
1827 ssh_pkt_addstring_str(pkt
, data
);
1829 static void ssh1_pkt_addmp(struct Packet
*pkt
, Bignum b
)
1831 int len
= ssh1_bignum_length(b
);
1832 unsigned char *data
= snewn(len
, unsigned char);
1833 (void) ssh1_write_bignum(data
, b
);
1834 ssh_pkt_adddata(pkt
, data
, len
);
1837 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
)
1840 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1841 p
= snewn(n
+ 1, unsigned char);
1843 for (i
= 1; i
<= n
; i
++)
1844 p
[i
] = bignum_byte(b
, n
- i
);
1846 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1848 memmove(p
, p
+ i
, n
+ 1 - i
);
1852 static void ssh2_pkt_addmp(struct Packet
*pkt
, Bignum b
)
1856 p
= ssh2_mpint_fmt(b
, &len
);
1857 ssh_pkt_addstring_start(pkt
);
1858 ssh_pkt_addstring_data(pkt
, (char *)p
, len
);
1862 static struct Packet
*ssh1_pkt_init(int pkt_type
)
1864 struct Packet
*pkt
= ssh_new_packet();
1865 pkt
->length
= 4 + 8; /* space for length + max padding */
1866 ssh_pkt_addbyte(pkt
, pkt_type
);
1867 pkt
->body
= pkt
->data
+ pkt
->length
;
1871 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1872 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1873 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1874 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1875 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1876 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1877 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1878 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1879 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1881 static struct Packet
*ssh2_pkt_init(int pkt_type
)
1883 struct Packet
*pkt
= ssh_new_packet();
1884 pkt
->length
= 5; /* space for packet length + padding length */
1886 ssh_pkt_addbyte(pkt
, (unsigned char) pkt_type
);
1887 pkt
->body
= pkt
->data
+ pkt
->length
; /* after packet type */
1892 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1893 * put the MAC on it. Final packet, ready to be sent, is stored in
1894 * pkt->data. Total length is returned.
1896 static int ssh2_pkt_construct(Ssh ssh
, struct Packet
*pkt
)
1898 int cipherblk
, maclen
, padding
, i
;
1901 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->data
[5],
1902 ssh2_pkt_type(ssh
->pkt_kctx
, ssh
->pkt_actx
, pkt
->data
[5]),
1903 pkt
->body
, pkt
->length
- (pkt
->body
- pkt
->data
),
1904 pkt
->nblanks
, pkt
->blanks
, &ssh
->v2_outgoing_sequence
);
1905 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1909 * Compress packet payload.
1912 unsigned char *newpayload
;
1915 ssh
->cscomp
->compress(ssh
->cs_comp_ctx
, pkt
->data
+ 5,
1917 &newpayload
, &newlen
)) {
1919 ssh2_pkt_adddata(pkt
, newpayload
, newlen
);
1925 * Add padding. At least four bytes, and must also bring total
1926 * length (minus MAC) up to a multiple of the block size.
1927 * If pkt->forcepad is set, make sure the packet is at least that size
1930 cipherblk
= ssh
->cscipher ? ssh
->cscipher
->blksize
: 8; /* block size */
1931 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1933 if (pkt
->length
+ padding
< pkt
->forcepad
)
1934 padding
= pkt
->forcepad
- pkt
->length
;
1936 (cipherblk
- (pkt
->length
+ padding
) % cipherblk
) % cipherblk
;
1937 assert(padding
<= 255);
1938 maclen
= ssh
->csmac ? ssh
->csmac
->len
: 0;
1939 ssh2_pkt_ensure(pkt
, pkt
->length
+ padding
+ maclen
);
1940 pkt
->data
[4] = padding
;
1941 for (i
= 0; i
< padding
; i
++)
1942 pkt
->data
[pkt
->length
+ i
] = random_byte();
1943 PUT_32BIT(pkt
->data
, pkt
->length
+ padding
- 4);
1945 ssh
->csmac
->generate(ssh
->cs_mac_ctx
, pkt
->data
,
1946 pkt
->length
+ padding
,
1947 ssh
->v2_outgoing_sequence
);
1948 ssh
->v2_outgoing_sequence
++; /* whether or not we MACed */
1951 ssh
->cscipher
->encrypt(ssh
->cs_cipher_ctx
,
1952 pkt
->data
, pkt
->length
+ padding
);
1954 pkt
->encrypted_len
= pkt
->length
+ padding
;
1956 /* Ready-to-send packet starts at pkt->data. We return length. */
1957 return pkt
->length
+ padding
+ maclen
;
1961 * Routines called from the main SSH code to send packets. There
1962 * are quite a few of these, because we have two separate
1963 * mechanisms for delaying the sending of packets:
1965 * - In order to send an IGNORE message and a password message in
1966 * a single fixed-length blob, we require the ability to
1967 * concatenate the encrypted forms of those two packets _into_ a
1968 * single blob and then pass it to our <network.h> transport
1969 * layer in one go. Hence, there's a deferment mechanism which
1970 * works after packet encryption.
1972 * - In order to avoid sending any connection-layer messages
1973 * during repeat key exchange, we have to queue up any such
1974 * outgoing messages _before_ they are encrypted (and in
1975 * particular before they're allocated sequence numbers), and
1976 * then send them once we've finished.
1978 * I call these mechanisms `defer' and `queue' respectively, so as
1979 * to distinguish them reasonably easily.
1981 * The functions send_noqueue() and defer_noqueue() free the packet
1982 * structure they are passed. Every outgoing packet goes through
1983 * precisely one of these functions in its life; packets passed to
1984 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1985 * these or get queued, and then when the queue is later emptied
1986 * the packets are all passed to defer_noqueue().
1988 * When using a CBC-mode cipher, it's necessary to ensure that an
1989 * attacker can't provide data to be encrypted using an IV that they
1990 * know. We ensure this by prefixing each packet that might contain
1991 * user data with an SSH_MSG_IGNORE. This is done using the deferral
1992 * mechanism, so in this case send_noqueue() ends up redirecting to
1993 * defer_noqueue(). If you don't like this inefficiency, don't use
1997 static void ssh2_pkt_defer_noqueue(Ssh
, struct Packet
*, int);
1998 static void ssh_pkt_defersend(Ssh
);
2001 * Send an SSH-2 packet immediately, without queuing or deferring.
2003 static void ssh2_pkt_send_noqueue(Ssh ssh
, struct Packet
*pkt
)
2007 if (ssh
->cscipher
!= NULL
&& (ssh
->cscipher
->flags
& SSH_CIPHER_IS_CBC
)) {
2008 /* We need to send two packets, so use the deferral mechanism. */
2009 ssh2_pkt_defer_noqueue(ssh
, pkt
, FALSE
);
2010 ssh_pkt_defersend(ssh
);
2013 len
= ssh2_pkt_construct(ssh
, pkt
);
2014 backlog
= s_write(ssh
, pkt
->data
, len
);
2015 if (backlog
> SSH_MAX_BACKLOG
)
2016 ssh_throttle_all(ssh
, 1, backlog
);
2018 ssh
->outgoing_data_size
+= pkt
->encrypted_len
;
2019 if (!ssh
->kex_in_progress
&&
2020 ssh
->max_data_size
!= 0 &&
2021 ssh
->outgoing_data_size
> ssh
->max_data_size
)
2022 do_ssh2_transport(ssh
, "too much data sent", -1, NULL
);
2024 ssh_free_packet(pkt
);
2028 * Defer an SSH-2 packet.
2030 static void ssh2_pkt_defer_noqueue(Ssh ssh
, struct Packet
*pkt
, int noignore
)
2033 if (ssh
->cscipher
!= NULL
&& (ssh
->cscipher
->flags
& SSH_CIPHER_IS_CBC
) &&
2034 ssh
->deferred_len
== 0 && !noignore
&&
2035 !(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH2_IGNORE
)) {
2037 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2038 * get encrypted with a known IV.
2040 struct Packet
*ipkt
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
2041 ssh2_pkt_addstring_start(ipkt
);
2042 ssh2_pkt_defer_noqueue(ssh
, ipkt
, TRUE
);
2044 len
= ssh2_pkt_construct(ssh
, pkt
);
2045 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
2046 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
2047 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
2051 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
, pkt
->data
, len
);
2052 ssh
->deferred_len
+= len
;
2053 ssh
->deferred_data_size
+= pkt
->encrypted_len
;
2054 ssh_free_packet(pkt
);
2058 * Queue an SSH-2 packet.
2060 static void ssh2_pkt_queue(Ssh ssh
, struct Packet
*pkt
)
2062 assert(ssh
->queueing
);
2064 if (ssh
->queuelen
>= ssh
->queuesize
) {
2065 ssh
->queuesize
= ssh
->queuelen
+ 32;
2066 ssh
->queue
= sresize(ssh
->queue
, ssh
->queuesize
, struct Packet
*);
2069 ssh
->queue
[ssh
->queuelen
++] = pkt
;
2073 * Either queue or send a packet, depending on whether queueing is
2076 static void ssh2_pkt_send(Ssh ssh
, struct Packet
*pkt
)
2079 ssh2_pkt_queue(ssh
, pkt
);
2081 ssh2_pkt_send_noqueue(ssh
, pkt
);
2085 * Either queue or defer a packet, depending on whether queueing is
2088 static void ssh2_pkt_defer(Ssh ssh
, struct Packet
*pkt
)
2091 ssh2_pkt_queue(ssh
, pkt
);
2093 ssh2_pkt_defer_noqueue(ssh
, pkt
, FALSE
);
2097 * Send the whole deferred data block constructed by
2098 * ssh2_pkt_defer() or SSH-1's defer_packet().
2100 * The expected use of the defer mechanism is that you call
2101 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2102 * not currently queueing, this simply sets up deferred_send_data
2103 * and then sends it. If we _are_ currently queueing, the calls to
2104 * ssh2_pkt_defer() put the deferred packets on to the queue
2105 * instead, and therefore ssh_pkt_defersend() has no deferred data
2106 * to send. Hence, there's no need to make it conditional on
2109 static void ssh_pkt_defersend(Ssh ssh
)
2112 backlog
= s_write(ssh
, ssh
->deferred_send_data
, ssh
->deferred_len
);
2113 ssh
->deferred_len
= ssh
->deferred_size
= 0;
2114 sfree(ssh
->deferred_send_data
);
2115 ssh
->deferred_send_data
= NULL
;
2116 if (backlog
> SSH_MAX_BACKLOG
)
2117 ssh_throttle_all(ssh
, 1, backlog
);
2119 ssh
->outgoing_data_size
+= ssh
->deferred_data_size
;
2120 if (!ssh
->kex_in_progress
&&
2121 ssh
->max_data_size
!= 0 &&
2122 ssh
->outgoing_data_size
> ssh
->max_data_size
)
2123 do_ssh2_transport(ssh
, "too much data sent", -1, NULL
);
2124 ssh
->deferred_data_size
= 0;
2128 * Send a packet whose length needs to be disguised (typically
2129 * passwords or keyboard-interactive responses).
2131 static void ssh2_pkt_send_with_padding(Ssh ssh
, struct Packet
*pkt
,
2137 * The simplest way to do this is to adjust the
2138 * variable-length padding field in the outgoing packet.
2140 * Currently compiled out, because some Cisco SSH servers
2141 * don't like excessively padded packets (bah, why's it
2144 pkt
->forcepad
= padsize
;
2145 ssh2_pkt_send(ssh
, pkt
);
2150 * If we can't do that, however, an alternative approach is
2151 * to use the pkt_defer mechanism to bundle the packet
2152 * tightly together with an SSH_MSG_IGNORE such that their
2153 * combined length is a constant. So first we construct the
2154 * final form of this packet and defer its sending.
2156 ssh2_pkt_defer(ssh
, pkt
);
2159 * Now construct an SSH_MSG_IGNORE which includes a string
2160 * that's an exact multiple of the cipher block size. (If
2161 * the cipher is NULL so that the block size is
2162 * unavailable, we don't do this trick at all, because we
2163 * gain nothing by it.)
2165 if (ssh
->cscipher
&&
2166 !(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH2_IGNORE
)) {
2169 stringlen
= (256 - ssh
->deferred_len
);
2170 stringlen
+= ssh
->cscipher
->blksize
- 1;
2171 stringlen
-= (stringlen
% ssh
->cscipher
->blksize
);
2174 * Temporarily disable actual compression, so we
2175 * can guarantee to get this string exactly the
2176 * length we want it. The compression-disabling
2177 * routine should return an integer indicating how
2178 * many bytes we should adjust our string length
2182 ssh
->cscomp
->disable_compression(ssh
->cs_comp_ctx
);
2184 pkt
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
2185 ssh2_pkt_addstring_start(pkt
);
2186 for (i
= 0; i
< stringlen
; i
++) {
2187 char c
= (char) random_byte();
2188 ssh2_pkt_addstring_data(pkt
, &c
, 1);
2190 ssh2_pkt_defer(ssh
, pkt
);
2192 ssh_pkt_defersend(ssh
);
2197 * Send all queued SSH-2 packets. We send them by means of
2198 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2199 * packets that needed to be lumped together.
2201 static void ssh2_pkt_queuesend(Ssh ssh
)
2205 assert(!ssh
->queueing
);
2207 for (i
= 0; i
< ssh
->queuelen
; i
++)
2208 ssh2_pkt_defer_noqueue(ssh
, ssh
->queue
[i
], FALSE
);
2211 ssh_pkt_defersend(ssh
);
2215 void bndebug(char *string
, Bignum b
)
2219 p
= ssh2_mpint_fmt(b
, &len
);
2220 debug(("%s", string
));
2221 for (i
= 0; i
< len
; i
++)
2222 debug((" %02x", p
[i
]));
2228 static void hash_mpint(const struct ssh_hash
*h
, void *s
, Bignum b
)
2232 p
= ssh2_mpint_fmt(b
, &len
);
2233 hash_string(h
, s
, p
, len
);
2238 * Packet decode functions for both SSH-1 and SSH-2.
2240 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
)
2242 unsigned long value
;
2243 if (pkt
->length
- pkt
->savedpos
< 4)
2244 return 0; /* arrgh, no way to decline (FIXME?) */
2245 value
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
2249 static int ssh2_pkt_getbool(struct Packet
*pkt
)
2251 unsigned long value
;
2252 if (pkt
->length
- pkt
->savedpos
< 1)
2253 return 0; /* arrgh, no way to decline (FIXME?) */
2254 value
= pkt
->body
[pkt
->savedpos
] != 0;
2258 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
)
2263 if (pkt
->length
- pkt
->savedpos
< 4)
2265 len
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
2270 if (pkt
->length
- pkt
->savedpos
< *length
)
2272 *p
= (char *)(pkt
->body
+ pkt
->savedpos
);
2273 pkt
->savedpos
+= *length
;
2275 static void *ssh_pkt_getdata(struct Packet
*pkt
, int length
)
2277 if (pkt
->length
- pkt
->savedpos
< length
)
2279 pkt
->savedpos
+= length
;
2280 return pkt
->body
+ (pkt
->savedpos
- length
);
2282 static int ssh1_pkt_getrsakey(struct Packet
*pkt
, struct RSAKey
*key
,
2283 unsigned char **keystr
)
2287 j
= makekey(pkt
->body
+ pkt
->savedpos
,
2288 pkt
->length
- pkt
->savedpos
,
2295 assert(pkt
->savedpos
< pkt
->length
);
2299 static Bignum
ssh1_pkt_getmp(struct Packet
*pkt
)
2304 j
= ssh1_read_bignum(pkt
->body
+ pkt
->savedpos
,
2305 pkt
->length
- pkt
->savedpos
, &b
);
2313 static Bignum
ssh2_pkt_getmp(struct Packet
*pkt
)
2319 ssh_pkt_getstring(pkt
, &p
, &length
);
2324 b
= bignum_from_bytes((unsigned char *)p
, length
);
2329 * Helper function to add an SSH-2 signature blob to a packet.
2330 * Expects to be shown the public key blob as well as the signature
2331 * blob. Normally works just like ssh2_pkt_addstring, but will
2332 * fiddle with the signature packet if necessary for
2333 * BUG_SSH2_RSA_PADDING.
2335 static void ssh2_add_sigblob(Ssh ssh
, struct Packet
*pkt
,
2336 void *pkblob_v
, int pkblob_len
,
2337 void *sigblob_v
, int sigblob_len
)
2339 unsigned char *pkblob
= (unsigned char *)pkblob_v
;
2340 unsigned char *sigblob
= (unsigned char *)sigblob_v
;
2342 /* dmemdump(pkblob, pkblob_len); */
2343 /* dmemdump(sigblob, sigblob_len); */
2346 * See if this is in fact an ssh-rsa signature and a buggy
2347 * server; otherwise we can just do this the easy way.
2349 if ((ssh
->remote_bugs
& BUG_SSH2_RSA_PADDING
) &&
2350 (GET_32BIT(pkblob
) == 7 && !memcmp(pkblob
+4, "ssh-rsa", 7))) {
2351 int pos
, len
, siglen
;
2354 * Find the byte length of the modulus.
2357 pos
= 4+7; /* skip over "ssh-rsa" */
2358 pos
+= 4 + GET_32BIT(pkblob
+pos
); /* skip over exponent */
2359 len
= GET_32BIT(pkblob
+pos
); /* find length of modulus */
2360 pos
+= 4; /* find modulus itself */
2361 while (len
> 0 && pkblob
[pos
] == 0)
2363 /* debug(("modulus length is %d\n", len)); */
2366 * Now find the signature integer.
2368 pos
= 4+7; /* skip over "ssh-rsa" */
2369 siglen
= GET_32BIT(sigblob
+pos
);
2370 /* debug(("signature length is %d\n", siglen)); */
2372 if (len
!= siglen
) {
2373 unsigned char newlen
[4];
2374 ssh2_pkt_addstring_start(pkt
);
2375 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, pos
);
2376 /* dmemdump(sigblob, pos); */
2377 pos
+= 4; /* point to start of actual sig */
2378 PUT_32BIT(newlen
, len
);
2379 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 4);
2380 /* dmemdump(newlen, 4); */
2382 while (len
-- > siglen
) {
2383 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 1);
2384 /* dmemdump(newlen, 1); */
2386 ssh2_pkt_addstring_data(pkt
, (char *)(sigblob
+pos
), siglen
);
2387 /* dmemdump(sigblob+pos, siglen); */
2391 /* Otherwise fall through and do it the easy way. */
2394 ssh2_pkt_addstring_start(pkt
);
2395 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, sigblob_len
);
2399 * Examine the remote side's version string and compare it against
2400 * a list of known buggy implementations.
2402 static void ssh_detect_bugs(Ssh ssh
, char *vstring
)
2404 char *imp
; /* pointer to implementation part */
2406 imp
+= strcspn(imp
, "-");
2408 imp
+= strcspn(imp
, "-");
2411 ssh
->remote_bugs
= 0;
2414 * General notes on server version strings:
2415 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2416 * here -- in particular, we've heard of one that's perfectly happy
2417 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2418 * so we can't distinguish them.
2420 if (ssh
->cfg
.sshbug_ignore1
== FORCE_ON
||
2421 (ssh
->cfg
.sshbug_ignore1
== AUTO
&&
2422 (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
2423 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
2424 !strcmp(imp
, "1.2.22") || !strcmp(imp
, "Cisco-1.25") ||
2425 !strcmp(imp
, "OSU_1.4alpha3") || !strcmp(imp
, "OSU_1.5alpha4")))) {
2427 * These versions don't support SSH1_MSG_IGNORE, so we have
2428 * to use a different defence against password length
2431 ssh
->remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
2432 logevent("We believe remote version has SSH-1 ignore bug");
2435 if (ssh
->cfg
.sshbug_plainpw1
== FORCE_ON
||
2436 (ssh
->cfg
.sshbug_plainpw1
== AUTO
&&
2437 (!strcmp(imp
, "Cisco-1.25") || !strcmp(imp
, "OSU_1.4alpha3")))) {
2439 * These versions need a plain password sent; they can't
2440 * handle having a null and a random length of data after
2443 ssh
->remote_bugs
|= BUG_NEEDS_SSH1_PLAIN_PASSWORD
;
2444 logevent("We believe remote version needs a plain SSH-1 password");
2447 if (ssh
->cfg
.sshbug_rsa1
== FORCE_ON
||
2448 (ssh
->cfg
.sshbug_rsa1
== AUTO
&&
2449 (!strcmp(imp
, "Cisco-1.25")))) {
2451 * These versions apparently have no clue whatever about
2452 * RSA authentication and will panic and die if they see
2453 * an AUTH_RSA message.
2455 ssh
->remote_bugs
|= BUG_CHOKES_ON_RSA
;
2456 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2459 if (ssh
->cfg
.sshbug_hmac2
== FORCE_ON
||
2460 (ssh
->cfg
.sshbug_hmac2
== AUTO
&&
2461 !wc_match("* VShell", imp
) &&
2462 (wc_match("2.1.0*", imp
) || wc_match("2.0.*", imp
) ||
2463 wc_match("2.2.0*", imp
) || wc_match("2.3.0*", imp
) ||
2464 wc_match("2.1 *", imp
)))) {
2466 * These versions have the HMAC bug.
2468 ssh
->remote_bugs
|= BUG_SSH2_HMAC
;
2469 logevent("We believe remote version has SSH-2 HMAC bug");
2472 if (ssh
->cfg
.sshbug_derivekey2
== FORCE_ON
||
2473 (ssh
->cfg
.sshbug_derivekey2
== AUTO
&&
2474 !wc_match("* VShell", imp
) &&
2475 (wc_match("2.0.0*", imp
) || wc_match("2.0.10*", imp
) ))) {
2477 * These versions have the key-derivation bug (failing to
2478 * include the literal shared secret in the hashes that
2479 * generate the keys).
2481 ssh
->remote_bugs
|= BUG_SSH2_DERIVEKEY
;
2482 logevent("We believe remote version has SSH-2 key-derivation bug");
2485 if (ssh
->cfg
.sshbug_rsapad2
== FORCE_ON
||
2486 (ssh
->cfg
.sshbug_rsapad2
== AUTO
&&
2487 (wc_match("OpenSSH_2.[5-9]*", imp
) ||
2488 wc_match("OpenSSH_3.[0-2]*", imp
)))) {
2490 * These versions have the SSH-2 RSA padding bug.
2492 ssh
->remote_bugs
|= BUG_SSH2_RSA_PADDING
;
2493 logevent("We believe remote version has SSH-2 RSA padding bug");
2496 if (ssh
->cfg
.sshbug_pksessid2
== FORCE_ON
||
2497 (ssh
->cfg
.sshbug_pksessid2
== AUTO
&&
2498 wc_match("OpenSSH_2.[0-2]*", imp
))) {
2500 * These versions have the SSH-2 session-ID bug in
2501 * public-key authentication.
2503 ssh
->remote_bugs
|= BUG_SSH2_PK_SESSIONID
;
2504 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2507 if (ssh
->cfg
.sshbug_rekey2
== FORCE_ON
||
2508 (ssh
->cfg
.sshbug_rekey2
== AUTO
&&
2509 (wc_match("DigiSSH_2.0", imp
) ||
2510 wc_match("OpenSSH_2.[0-4]*", imp
) ||
2511 wc_match("OpenSSH_2.5.[0-3]*", imp
) ||
2512 wc_match("Sun_SSH_1.0", imp
) ||
2513 wc_match("Sun_SSH_1.0.1", imp
) ||
2514 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2515 wc_match("WeOnlyDo-*", imp
)))) {
2517 * These versions have the SSH-2 rekey bug.
2519 ssh
->remote_bugs
|= BUG_SSH2_REKEY
;
2520 logevent("We believe remote version has SSH-2 rekey bug");
2523 if (ssh
->cfg
.sshbug_maxpkt2
== FORCE_ON
||
2524 (ssh
->cfg
.sshbug_maxpkt2
== AUTO
&&
2525 (wc_match("1.36_sshlib GlobalSCAPE", imp
) ||
2526 wc_match("1.36 sshlib: GlobalScape", imp
)))) {
2528 * This version ignores our makpkt and needs to be throttled.
2530 ssh
->remote_bugs
|= BUG_SSH2_MAXPKT
;
2531 logevent("We believe remote version ignores SSH-2 maximum packet size");
2534 if (ssh
->cfg
.sshbug_ignore2
== FORCE_ON
) {
2536 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2537 * none detected automatically.
2539 ssh
->remote_bugs
|= BUG_CHOKES_ON_SSH2_IGNORE
;
2540 logevent("We believe remote version has SSH-2 ignore bug");
2545 * The `software version' part of an SSH version string is required
2546 * to contain no spaces or minus signs.
2548 static void ssh_fix_verstring(char *str
)
2550 /* Eat "SSH-<protoversion>-". */
2551 assert(*str
== 'S'); str
++;
2552 assert(*str
== 'S'); str
++;
2553 assert(*str
== 'H'); str
++;
2554 assert(*str
== '-'); str
++;
2555 while (*str
&& *str
!= '-') str
++;
2556 assert(*str
== '-'); str
++;
2558 /* Convert minus signs and spaces in the remaining string into
2561 if (*str
== '-' || *str
== ' ')
2568 * Send an appropriate SSH version string.
2570 static void ssh_send_verstring(Ssh ssh
, char *svers
)
2574 if (ssh
->version
== 2) {
2576 * Construct a v2 version string.
2578 verstring
= dupprintf("SSH-2.0-%s\015\012", sshver
);
2581 * Construct a v1 version string.
2583 verstring
= dupprintf("SSH-%s-%s\012",
2584 (ssh_versioncmp(svers
, "1.5") <= 0 ?
2589 ssh_fix_verstring(verstring
);
2591 if (ssh
->version
== 2) {
2594 * Record our version string.
2596 len
= strcspn(verstring
, "\015\012");
2597 ssh
->v_c
= snewn(len
+ 1, char);
2598 memcpy(ssh
->v_c
, verstring
, len
);
2602 logeventf(ssh
, "We claim version: %.*s",
2603 strcspn(verstring
, "\015\012"), verstring
);
2604 s_write(ssh
, verstring
, strlen(verstring
));
2608 static int do_ssh_init(Ssh ssh
, unsigned char c
)
2610 struct do_ssh_init_state
{
2618 crState(do_ssh_init_state
);
2620 crBegin(ssh
->do_ssh_init_crstate
);
2622 /* Search for a line beginning with the string "SSH-" in the input. */
2624 if (c
!= 'S') goto no
;
2626 if (c
!= 'S') goto no
;
2628 if (c
!= 'H') goto no
;
2630 if (c
!= '-') goto no
;
2639 s
->vstring
= snewn(s
->vstrsize
, char);
2640 strcpy(s
->vstring
, "SSH-");
2644 crReturn(1); /* get another char */
2645 if (s
->vslen
>= s
->vstrsize
- 1) {
2647 s
->vstring
= sresize(s
->vstring
, s
->vstrsize
, char);
2649 s
->vstring
[s
->vslen
++] = c
;
2652 s
->version
[s
->i
] = '\0';
2654 } else if (s
->i
< sizeof(s
->version
) - 1)
2655 s
->version
[s
->i
++] = c
;
2656 } else if (c
== '\012')
2660 ssh
->agentfwd_enabled
= FALSE
;
2661 ssh
->rdpkt2_state
.incoming_sequence
= 0;
2663 s
->vstring
[s
->vslen
] = 0;
2664 s
->vstring
[strcspn(s
->vstring
, "\015\012")] = '\0';/* remove EOL chars */
2665 logeventf(ssh
, "Server version: %s", s
->vstring
);
2666 ssh_detect_bugs(ssh
, s
->vstring
);
2669 * Decide which SSH protocol version to support.
2672 /* Anything strictly below "2.0" means protocol 1 is supported. */
2673 s
->proto1
= ssh_versioncmp(s
->version
, "2.0") < 0;
2674 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2675 s
->proto2
= ssh_versioncmp(s
->version
, "1.99") >= 0;
2677 if (ssh
->cfg
.sshprot
== 0 && !s
->proto1
) {
2678 bombout(("SSH protocol version 1 required by user but not provided by server"));
2681 if (ssh
->cfg
.sshprot
== 3 && !s
->proto2
) {
2682 bombout(("SSH protocol version 2 required by user but not provided by server"));
2686 if (s
->proto2
&& (ssh
->cfg
.sshprot
>= 2 || !s
->proto1
))
2691 logeventf(ssh
, "Using SSH protocol version %d", ssh
->version
);
2693 /* Send the version string, if we haven't already */
2694 if (ssh
->cfg
.sshprot
!= 3)
2695 ssh_send_verstring(ssh
, s
->version
);
2697 if (ssh
->version
== 2) {
2700 * Record their version string.
2702 len
= strcspn(s
->vstring
, "\015\012");
2703 ssh
->v_s
= snewn(len
+ 1, char);
2704 memcpy(ssh
->v_s
, s
->vstring
, len
);
2708 * Initialise SSH-2 protocol.
2710 ssh
->protocol
= ssh2_protocol
;
2711 ssh2_protocol_setup(ssh
);
2712 ssh
->s_rdpkt
= ssh2_rdpkt
;
2715 * Initialise SSH-1 protocol.
2717 ssh
->protocol
= ssh1_protocol
;
2718 ssh1_protocol_setup(ssh
);
2719 ssh
->s_rdpkt
= ssh1_rdpkt
;
2721 if (ssh
->version
== 2)
2722 do_ssh2_transport(ssh
, NULL
, -1, NULL
);
2724 update_specials_menu(ssh
->frontend
);
2725 ssh
->state
= SSH_STATE_BEFORE_SIZE
;
2726 ssh
->pinger
= pinger_new(&ssh
->cfg
, &ssh_backend
, ssh
);
2733 static void ssh_process_incoming_data(Ssh ssh
,
2734 unsigned char **data
, int *datalen
)
2736 struct Packet
*pktin
;
2738 pktin
= ssh
->s_rdpkt(ssh
, data
, datalen
);
2740 ssh
->protocol(ssh
, NULL
, 0, pktin
);
2741 ssh_free_packet(pktin
);
2745 static void ssh_queue_incoming_data(Ssh ssh
,
2746 unsigned char **data
, int *datalen
)
2748 bufchain_add(&ssh
->queued_incoming_data
, *data
, *datalen
);
2753 static void ssh_process_queued_incoming_data(Ssh ssh
)
2756 unsigned char *data
;
2759 while (!ssh
->frozen
&& bufchain_size(&ssh
->queued_incoming_data
)) {
2760 bufchain_prefix(&ssh
->queued_incoming_data
, &vdata
, &len
);
2764 while (!ssh
->frozen
&& len
> 0)
2765 ssh_process_incoming_data(ssh
, &data
, &len
);
2768 bufchain_consume(&ssh
->queued_incoming_data
, origlen
- len
);
2772 static void ssh_set_frozen(Ssh ssh
, int frozen
)
2775 sk_set_frozen(ssh
->s
, frozen
);
2776 ssh
->frozen
= frozen
;
2779 static void ssh_gotdata(Ssh ssh
, unsigned char *data
, int datalen
)
2781 /* Log raw data, if we're in that mode. */
2783 log_packet(ssh
->logctx
, PKT_INCOMING
, -1, NULL
, data
, datalen
,
2786 crBegin(ssh
->ssh_gotdata_crstate
);
2789 * To begin with, feed the characters one by one to the
2790 * protocol initialisation / selection function do_ssh_init().
2791 * When that returns 0, we're done with the initial greeting
2792 * exchange and can move on to packet discipline.
2795 int ret
; /* need not be kept across crReturn */
2797 crReturnV
; /* more data please */
2798 ret
= do_ssh_init(ssh
, *data
);
2806 * We emerge from that loop when the initial negotiation is
2807 * over and we have selected an s_rdpkt function. Now pass
2808 * everything to s_rdpkt, and then pass the resulting packets
2809 * to the proper protocol handler.
2813 while (bufchain_size(&ssh
->queued_incoming_data
) > 0 || datalen
> 0) {
2815 ssh_queue_incoming_data(ssh
, &data
, &datalen
);
2816 /* This uses up all data and cannot cause anything interesting
2817 * to happen; indeed, for anything to happen at all, we must
2818 * return, so break out. */
2820 } else if (bufchain_size(&ssh
->queued_incoming_data
) > 0) {
2821 /* This uses up some or all data, and may freeze the
2823 ssh_process_queued_incoming_data(ssh
);
2825 /* This uses up some or all data, and may freeze the
2827 ssh_process_incoming_data(ssh
, &data
, &datalen
);
2829 /* FIXME this is probably EBW. */
2830 if (ssh
->state
== SSH_STATE_CLOSED
)
2833 /* We're out of data. Go and get some more. */
2839 static int ssh_do_close(Ssh ssh
, int notify_exit
)
2842 struct ssh_channel
*c
;
2844 ssh
->state
= SSH_STATE_CLOSED
;
2845 expire_timer_context(ssh
);
2850 notify_remote_exit(ssh
->frontend
);
2855 * Now we must shut down any port- and X-forwarded channels going
2856 * through this connection.
2858 if (ssh
->channels
) {
2859 while (NULL
!= (c
= index234(ssh
->channels
, 0))) {
2862 x11_close(c
->u
.x11
.s
);
2865 case CHAN_SOCKDATA_DORMANT
:
2866 pfd_close(c
->u
.pfd
.s
);
2869 del234(ssh
->channels
, c
); /* moving next one to index 0 */
2870 if (ssh
->version
== 2)
2871 bufchain_clear(&c
->v
.v2
.outbuffer
);
2876 * Go through port-forwardings, and close any associated
2877 * listening sockets.
2879 if (ssh
->portfwds
) {
2880 struct ssh_portfwd
*pf
;
2881 while (NULL
!= (pf
= index234(ssh
->portfwds
, 0))) {
2882 /* Dispose of any listening socket. */
2884 pfd_terminate(pf
->local
);
2885 del234(ssh
->portfwds
, pf
); /* moving next one to index 0 */
2888 freetree234(ssh
->portfwds
);
2889 ssh
->portfwds
= NULL
;
2895 static void ssh_log(Plug plug
, int type
, SockAddr addr
, int port
,
2896 const char *error_msg
, int error_code
)
2898 Ssh ssh
= (Ssh
) plug
;
2899 char addrbuf
[256], *msg
;
2901 sk_getaddr(addr
, addrbuf
, lenof(addrbuf
));
2904 msg
= dupprintf("Connecting to %s port %d", addrbuf
, port
);
2906 msg
= dupprintf("Failed to connect to %s: %s", addrbuf
, error_msg
);
2912 static int ssh_closing(Plug plug
, const char *error_msg
, int error_code
,
2915 Ssh ssh
= (Ssh
) plug
;
2916 int need_notify
= ssh_do_close(ssh
, FALSE
);
2919 if (!ssh
->close_expected
)
2920 error_msg
= "Server unexpectedly closed network connection";
2922 error_msg
= "Server closed network connection";
2925 if (ssh
->close_expected
&& ssh
->clean_exit
&& ssh
->exitcode
< 0)
2929 notify_remote_exit(ssh
->frontend
);
2932 logevent(error_msg
);
2933 if (!ssh
->close_expected
|| !ssh
->clean_exit
)
2934 connection_fatal(ssh
->frontend
, "%s", error_msg
);
2938 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
2940 Ssh ssh
= (Ssh
) plug
;
2941 ssh_gotdata(ssh
, (unsigned char *)data
, len
);
2942 if (ssh
->state
== SSH_STATE_CLOSED
) {
2943 ssh_do_close(ssh
, TRUE
);
2949 static void ssh_sent(Plug plug
, int bufsize
)
2951 Ssh ssh
= (Ssh
) plug
;
2953 * If the send backlog on the SSH socket itself clears, we
2954 * should unthrottle the whole world if it was throttled.
2956 if (bufsize
< SSH_MAX_BACKLOG
)
2957 ssh_throttle_all(ssh
, 0, bufsize
);
2961 * Connect to specified host and port.
2962 * Returns an error message, or NULL on success.
2963 * Also places the canonical host name into `realhost'. It must be
2964 * freed by the caller.
2966 static const char *connect_to_host(Ssh ssh
, char *host
, int port
,
2967 char **realhost
, int nodelay
, int keepalive
)
2969 static const struct plug_function_table fn_table
= {
2980 if (*ssh
->cfg
.loghost
) {
2983 ssh
->savedhost
= dupstr(ssh
->cfg
.loghost
);
2984 ssh
->savedport
= 22; /* default ssh port */
2987 * A colon suffix on savedhost also lets us affect
2990 * (FIXME: do something about IPv6 address literals here.)
2992 colon
= strrchr(ssh
->savedhost
, ':');
2996 ssh
->savedport
= atoi(colon
);
2999 ssh
->savedhost
= dupstr(host
);
3001 port
= 22; /* default ssh port */
3002 ssh
->savedport
= port
;
3008 logeventf(ssh
, "Looking up host \"%s\"%s", host
,
3009 (ssh
->cfg
.addressfamily
== ADDRTYPE_IPV4 ?
" (IPv4)" :
3010 (ssh
->cfg
.addressfamily
== ADDRTYPE_IPV6 ?
" (IPv6)" : "")));
3011 addr
= name_lookup(host
, port
, realhost
, &ssh
->cfg
,
3012 ssh
->cfg
.addressfamily
);
3013 if ((err
= sk_addr_error(addr
)) != NULL
) {
3017 ssh
->fullhostname
= dupstr(*realhost
); /* save in case of GSSAPI */
3022 ssh
->fn
= &fn_table
;
3023 ssh
->s
= new_connection(addr
, *realhost
, port
,
3024 0, 1, nodelay
, keepalive
, (Plug
) ssh
, &ssh
->cfg
);
3025 if ((err
= sk_socket_error(ssh
->s
)) != NULL
) {
3027 notify_remote_exit(ssh
->frontend
);
3032 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3033 * send the version string too.
3035 if (ssh
->cfg
.sshprot
== 0)
3037 if (ssh
->cfg
.sshprot
== 3) {
3039 ssh_send_verstring(ssh
, NULL
);
3043 * loghost, if configured, overrides realhost.
3045 if (*ssh
->cfg
.loghost
) {
3047 *realhost
= dupstr(ssh
->cfg
.loghost
);
3054 * Throttle or unthrottle the SSH connection.
3056 static void ssh_throttle_conn(Ssh ssh
, int adjust
)
3058 int old_count
= ssh
->conn_throttle_count
;
3059 ssh
->conn_throttle_count
+= adjust
;
3060 assert(ssh
->conn_throttle_count
>= 0);
3061 if (ssh
->conn_throttle_count
&& !old_count
) {
3062 ssh_set_frozen(ssh
, 1);
3063 } else if (!ssh
->conn_throttle_count
&& old_count
) {
3064 ssh_set_frozen(ssh
, 0);
3069 * Throttle or unthrottle _all_ local data streams (for when sends
3070 * on the SSH connection itself back up).
3072 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
)
3075 struct ssh_channel
*c
;
3077 if (enable
== ssh
->throttled_all
)
3079 ssh
->throttled_all
= enable
;
3080 ssh
->overall_bufsize
= bufsize
;
3083 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
3085 case CHAN_MAINSESSION
:
3087 * This is treated separately, outside the switch.
3091 x11_override_throttle(c
->u
.x11
.s
, enable
);
3094 /* Agent channels require no buffer management. */
3097 pfd_override_throttle(c
->u
.pfd
.s
, enable
);
3103 static void ssh_agent_callback(void *sshv
, void *reply
, int replylen
)
3105 Ssh ssh
= (Ssh
) sshv
;
3107 ssh
->agent_response
= reply
;
3108 ssh
->agent_response_len
= replylen
;
3110 if (ssh
->version
== 1)
3111 do_ssh1_login(ssh
, NULL
, -1, NULL
);
3113 do_ssh2_authconn(ssh
, NULL
, -1, NULL
);
3116 static void ssh_dialog_callback(void *sshv
, int ret
)
3118 Ssh ssh
= (Ssh
) sshv
;
3120 ssh
->user_response
= ret
;
3122 if (ssh
->version
== 1)
3123 do_ssh1_login(ssh
, NULL
, -1, NULL
);
3125 do_ssh2_transport(ssh
, NULL
, -1, NULL
);
3128 * This may have unfrozen the SSH connection, so do a
3131 ssh_process_queued_incoming_data(ssh
);
3134 static void ssh_agentf_callback(void *cv
, void *reply
, int replylen
)
3136 struct ssh_channel
*c
= (struct ssh_channel
*)cv
;
3138 void *sentreply
= reply
;
3141 /* Fake SSH_AGENT_FAILURE. */
3142 sentreply
= "\0\0\0\1\5";
3145 if (ssh
->version
== 2) {
3146 ssh2_add_channel_data(c
, sentreply
, replylen
);
3149 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
3150 PKT_INT
, c
->remoteid
,
3153 PKT_DATA
, sentreply
, replylen
,
3162 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3163 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3164 * => log `wire_reason'.
3166 static void ssh_disconnect(Ssh ssh
, char *client_reason
, char *wire_reason
,
3167 int code
, int clean_exit
)
3171 client_reason
= wire_reason
;
3173 error
= dupprintf("Disconnected: %s", client_reason
);
3175 error
= dupstr("Disconnected");
3177 if (ssh
->version
== 1) {
3178 send_packet(ssh
, SSH1_MSG_DISCONNECT
, PKT_STR
, wire_reason
,
3180 } else if (ssh
->version
== 2) {
3181 struct Packet
*pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3182 ssh2_pkt_adduint32(pktout
, code
);
3183 ssh2_pkt_addstring(pktout
, wire_reason
);
3184 ssh2_pkt_addstring(pktout
, "en"); /* language tag */
3185 ssh2_pkt_send_noqueue(ssh
, pktout
);
3188 ssh
->close_expected
= TRUE
;
3189 ssh
->clean_exit
= clean_exit
;
3190 ssh_closing((Plug
)ssh
, error
, 0, 0);
3195 * Handle the key exchange and user authentication phases.
3197 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
,
3198 struct Packet
*pktin
)
3201 unsigned char cookie
[8], *ptr
;
3202 struct RSAKey servkey
, hostkey
;
3203 struct MD5Context md5c
;
3204 struct do_ssh1_login_state
{
3206 unsigned char *rsabuf
, *keystr1
, *keystr2
;
3207 unsigned long supported_ciphers_mask
, supported_auths_mask
;
3208 int tried_publickey
, tried_agent
;
3209 int tis_auth_refused
, ccard_auth_refused
;
3210 unsigned char session_id
[16];
3213 void *publickey_blob
;
3214 int publickey_bloblen
;
3215 char *publickey_comment
;
3216 int publickey_encrypted
;
3217 prompts_t
*cur_prompt
;
3220 unsigned char request
[5], *response
, *p
;
3230 crState(do_ssh1_login_state
);
3232 crBegin(ssh
->do_ssh1_login_crstate
);
3237 if (pktin
->type
!= SSH1_SMSG_PUBLIC_KEY
) {
3238 bombout(("Public key packet not received"));
3242 logevent("Received public keys");
3244 ptr
= ssh_pkt_getdata(pktin
, 8);
3246 bombout(("SSH-1 public key packet stopped before random cookie"));
3249 memcpy(cookie
, ptr
, 8);
3251 if (!ssh1_pkt_getrsakey(pktin
, &servkey
, &s
->keystr1
) ||
3252 !ssh1_pkt_getrsakey(pktin
, &hostkey
, &s
->keystr2
)) {
3253 bombout(("Failed to read SSH-1 public keys from public key packet"));
3258 * Log the host key fingerprint.
3262 logevent("Host key fingerprint is:");
3263 strcpy(logmsg
, " ");
3264 hostkey
.comment
= NULL
;
3265 rsa_fingerprint(logmsg
+ strlen(logmsg
),
3266 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
3270 ssh
->v1_remote_protoflags
= ssh_pkt_getuint32(pktin
);
3271 s
->supported_ciphers_mask
= ssh_pkt_getuint32(pktin
);
3272 s
->supported_auths_mask
= ssh_pkt_getuint32(pktin
);
3273 if ((ssh
->remote_bugs
& BUG_CHOKES_ON_RSA
))
3274 s
->supported_auths_mask
&= ~(1 << SSH1_AUTH_RSA
);
3276 ssh
->v1_local_protoflags
=
3277 ssh
->v1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
3278 ssh
->v1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
3281 MD5Update(&md5c
, s
->keystr2
, hostkey
.bytes
);
3282 MD5Update(&md5c
, s
->keystr1
, servkey
.bytes
);
3283 MD5Update(&md5c
, cookie
, 8);
3284 MD5Final(s
->session_id
, &md5c
);
3286 for (i
= 0; i
< 32; i
++)
3287 ssh
->session_key
[i
] = random_byte();
3290 * Verify that the `bits' and `bytes' parameters match.
3292 if (hostkey
.bits
> hostkey
.bytes
* 8 ||
3293 servkey
.bits
> servkey
.bytes
* 8) {
3294 bombout(("SSH-1 public keys were badly formatted"));
3298 s
->len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
3300 s
->rsabuf
= snewn(s
->len
, unsigned char);
3303 * Verify the host key.
3307 * First format the key into a string.
3309 int len
= rsastr_len(&hostkey
);
3310 char fingerprint
[100];
3311 char *keystr
= snewn(len
, char);
3312 rsastr_fmt(keystr
, &hostkey
);
3313 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
3315 ssh_set_frozen(ssh
, 1);
3316 s
->dlgret
= verify_ssh_host_key(ssh
->frontend
,
3317 ssh
->savedhost
, ssh
->savedport
,
3318 "rsa", keystr
, fingerprint
,
3319 ssh_dialog_callback
, ssh
);
3321 if (s
->dlgret
< 0) {
3325 bombout(("Unexpected data from server while waiting"
3326 " for user host key response"));
3329 } while (pktin
|| inlen
> 0);
3330 s
->dlgret
= ssh
->user_response
;
3332 ssh_set_frozen(ssh
, 0);
3334 if (s
->dlgret
== 0) {
3335 ssh_disconnect(ssh
, "User aborted at host key verification",
3341 for (i
= 0; i
< 32; i
++) {
3342 s
->rsabuf
[i
] = ssh
->session_key
[i
];
3344 s
->rsabuf
[i
] ^= s
->session_id
[i
];
3347 if (hostkey
.bytes
> servkey
.bytes
) {
3348 ret
= rsaencrypt(s
->rsabuf
, 32, &servkey
);
3350 ret
= rsaencrypt(s
->rsabuf
, servkey
.bytes
, &hostkey
);
3352 ret
= rsaencrypt(s
->rsabuf
, 32, &hostkey
);
3354 ret
= rsaencrypt(s
->rsabuf
, hostkey
.bytes
, &servkey
);
3357 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3361 logevent("Encrypted session key");
3364 int cipher_chosen
= 0, warn
= 0;
3365 char *cipher_string
= NULL
;
3367 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
3368 int next_cipher
= ssh
->cfg
.ssh_cipherlist
[i
];
3369 if (next_cipher
== CIPHER_WARN
) {
3370 /* If/when we choose a cipher, warn about it */
3372 } else if (next_cipher
== CIPHER_AES
) {
3373 /* XXX Probably don't need to mention this. */
3374 logevent("AES not supported in SSH-1, skipping");
3376 switch (next_cipher
) {
3377 case CIPHER_3DES
: s
->cipher_type
= SSH_CIPHER_3DES
;
3378 cipher_string
= "3DES"; break;
3379 case CIPHER_BLOWFISH
: s
->cipher_type
= SSH_CIPHER_BLOWFISH
;
3380 cipher_string
= "Blowfish"; break;
3381 case CIPHER_DES
: s
->cipher_type
= SSH_CIPHER_DES
;
3382 cipher_string
= "single-DES"; break;
3384 if (s
->supported_ciphers_mask
& (1 << s
->cipher_type
))
3388 if (!cipher_chosen
) {
3389 if ((s
->supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
3390 bombout(("Server violates SSH-1 protocol by not "
3391 "supporting 3DES encryption"));
3393 /* shouldn't happen */
3394 bombout(("No supported ciphers found"));
3398 /* Warn about chosen cipher if necessary. */
3400 ssh_set_frozen(ssh
, 1);
3401 s
->dlgret
= askalg(ssh
->frontend
, "cipher", cipher_string
,
3402 ssh_dialog_callback
, ssh
);
3403 if (s
->dlgret
< 0) {
3407 bombout(("Unexpected data from server while waiting"
3408 " for user response"));
3411 } while (pktin
|| inlen
> 0);
3412 s
->dlgret
= ssh
->user_response
;
3414 ssh_set_frozen(ssh
, 0);
3415 if (s
->dlgret
== 0) {
3416 ssh_disconnect(ssh
, "User aborted at cipher warning", NULL
,
3423 switch (s
->cipher_type
) {
3424 case SSH_CIPHER_3DES
:
3425 logevent("Using 3DES encryption");
3427 case SSH_CIPHER_DES
:
3428 logevent("Using single-DES encryption");
3430 case SSH_CIPHER_BLOWFISH
:
3431 logevent("Using Blowfish encryption");
3435 send_packet(ssh
, SSH1_CMSG_SESSION_KEY
,
3436 PKT_CHAR
, s
->cipher_type
,
3437 PKT_DATA
, cookie
, 8,
3438 PKT_CHAR
, (s
->len
* 8) >> 8, PKT_CHAR
, (s
->len
* 8) & 0xFF,
3439 PKT_DATA
, s
->rsabuf
, s
->len
,
3440 PKT_INT
, ssh
->v1_local_protoflags
, PKT_END
);
3442 logevent("Trying to enable encryption...");
3446 ssh
->cipher
= (s
->cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
3447 s
->cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
3449 ssh
->v1_cipher_ctx
= ssh
->cipher
->make_context();
3450 ssh
->cipher
->sesskey(ssh
->v1_cipher_ctx
, ssh
->session_key
);
3451 logeventf(ssh
, "Initialised %s encryption", ssh
->cipher
->text_name
);
3453 ssh
->crcda_ctx
= crcda_make_context();
3454 logevent("Installing CRC compensation attack detector");
3456 if (servkey
.modulus
) {
3457 sfree(servkey
.modulus
);
3458 servkey
.modulus
= NULL
;
3460 if (servkey
.exponent
) {
3461 sfree(servkey
.exponent
);
3462 servkey
.exponent
= NULL
;
3464 if (hostkey
.modulus
) {
3465 sfree(hostkey
.modulus
);
3466 hostkey
.modulus
= NULL
;
3468 if (hostkey
.exponent
) {
3469 sfree(hostkey
.exponent
);
3470 hostkey
.exponent
= NULL
;
3474 if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3475 bombout(("Encryption not successfully enabled"));
3479 logevent("Successfully started encryption");
3481 fflush(stdout
); /* FIXME eh? */
3483 if (!get_remote_username(&ssh
->cfg
, s
->username
,
3484 sizeof(s
->username
))) {
3485 int ret
; /* need not be kept over crReturn */
3486 s
->cur_prompt
= new_prompts(ssh
->frontend
);
3487 s
->cur_prompt
->to_server
= TRUE
;
3488 s
->cur_prompt
->name
= dupstr("SSH login name");
3489 add_prompt(s
->cur_prompt
, dupstr("login as: "), TRUE
,
3490 lenof(s
->username
));
3491 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
3494 crWaitUntil(!pktin
);
3495 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
3500 * Failed to get a username. Terminate.
3502 free_prompts(s
->cur_prompt
);
3503 ssh_disconnect(ssh
, "No username provided", NULL
, 0, TRUE
);
3506 memcpy(s
->username
, s
->cur_prompt
->prompts
[0]->result
,
3507 lenof(s
->username
));
3508 free_prompts(s
->cur_prompt
);
3511 send_packet(ssh
, SSH1_CMSG_USER
, PKT_STR
, s
->username
, PKT_END
);
3513 char *userlog
= dupprintf("Sent username \"%s\"", s
->username
);
3515 if (flags
& FLAG_INTERACTIVE
&&
3516 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
3517 c_write_str(ssh
, userlog
);
3518 c_write_str(ssh
, "\r\n");
3526 if ((s
->supported_auths_mask
& (1 << SSH1_AUTH_RSA
)) == 0) {
3527 /* We must not attempt PK auth. Pretend we've already tried it. */
3528 s
->tried_publickey
= s
->tried_agent
= 1;
3530 s
->tried_publickey
= s
->tried_agent
= 0;
3532 s
->tis_auth_refused
= s
->ccard_auth_refused
= 0;
3534 * Load the public half of any configured keyfile for later use.
3536 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
3538 logeventf(ssh
, "Reading private key file \"%.150s\"",
3539 filename_to_str(&ssh
->cfg
.keyfile
));
3540 keytype
= key_type(&ssh
->cfg
.keyfile
);
3541 if (keytype
== SSH_KEYTYPE_SSH1
) {
3543 if (rsakey_pubblob(&ssh
->cfg
.keyfile
,
3544 &s
->publickey_blob
, &s
->publickey_bloblen
,
3545 &s
->publickey_comment
, &error
)) {
3546 s
->publickey_encrypted
= rsakey_encrypted(&ssh
->cfg
.keyfile
,
3550 logeventf(ssh
, "Unable to load private key (%s)", error
);
3551 msgbuf
= dupprintf("Unable to load private key file "
3552 "\"%.150s\" (%s)\r\n",
3553 filename_to_str(&ssh
->cfg
.keyfile
),
3555 c_write_str(ssh
, msgbuf
);
3557 s
->publickey_blob
= NULL
;
3561 logeventf(ssh
, "Unable to use this key file (%s)",
3562 key_type_to_str(keytype
));
3563 msgbuf
= dupprintf("Unable to use key file \"%.150s\""
3565 filename_to_str(&ssh
->cfg
.keyfile
),
3566 key_type_to_str(keytype
));
3567 c_write_str(ssh
, msgbuf
);
3569 s
->publickey_blob
= NULL
;
3572 s
->publickey_blob
= NULL
;
3574 while (pktin
->type
== SSH1_SMSG_FAILURE
) {
3575 s
->pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
3577 if (ssh
->cfg
.tryagent
&& agent_exists() && !s
->tried_agent
) {
3579 * Attempt RSA authentication using Pageant.
3585 logevent("Pageant is running. Requesting keys.");
3587 /* Request the keys held by the agent. */
3588 PUT_32BIT(s
->request
, 1);
3589 s
->request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
3590 if (!agent_query(s
->request
, 5, &r
, &s
->responselen
,
3591 ssh_agent_callback
, ssh
)) {
3595 bombout(("Unexpected data from server while waiting"
3596 " for agent response"));
3599 } while (pktin
|| inlen
> 0);
3600 r
= ssh
->agent_response
;
3601 s
->responselen
= ssh
->agent_response_len
;
3603 s
->response
= (unsigned char *) r
;
3604 if (s
->response
&& s
->responselen
>= 5 &&
3605 s
->response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
3606 s
->p
= s
->response
+ 5;
3607 s
->nkeys
= GET_32BIT(s
->p
);
3609 logeventf(ssh
, "Pageant has %d SSH-1 keys", s
->nkeys
);
3610 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
3611 unsigned char *pkblob
= s
->p
;
3615 do { /* do while (0) to make breaking easy */
3616 n
= ssh1_read_bignum
3617 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
3622 n
= ssh1_read_bignum
3623 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
3628 if (s
->responselen
- (s
->p
-s
->response
) < 4)
3630 s
->commentlen
= GET_32BIT(s
->p
);
3632 if (s
->responselen
- (s
->p
-s
->response
) <
3635 s
->commentp
= (char *)s
->p
;
3636 s
->p
+= s
->commentlen
;
3640 logevent("Pageant key list packet was truncated");
3644 if (s
->publickey_blob
) {
3645 if (!memcmp(pkblob
, s
->publickey_blob
,
3646 s
->publickey_bloblen
)) {
3647 logeventf(ssh
, "Pageant key #%d matches "
3648 "configured key file", s
->keyi
);
3649 s
->tried_publickey
= 1;
3651 /* Skip non-configured key */
3654 logeventf(ssh
, "Trying Pageant key #%d", s
->keyi
);
3655 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
3656 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
3658 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
3659 logevent("Key refused");
3662 logevent("Received RSA challenge");
3663 if ((s
->challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
3664 bombout(("Server's RSA challenge was badly formatted"));
3669 char *agentreq
, *q
, *ret
;
3672 len
= 1 + 4; /* message type, bit count */
3673 len
+= ssh1_bignum_length(s
->key
.exponent
);
3674 len
+= ssh1_bignum_length(s
->key
.modulus
);
3675 len
+= ssh1_bignum_length(s
->challenge
);
3676 len
+= 16; /* session id */
3677 len
+= 4; /* response format */
3678 agentreq
= snewn(4 + len
, char);
3679 PUT_32BIT(agentreq
, len
);
3681 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
3682 PUT_32BIT(q
, bignum_bitcount(s
->key
.modulus
));
3684 q
+= ssh1_write_bignum(q
, s
->key
.exponent
);
3685 q
+= ssh1_write_bignum(q
, s
->key
.modulus
);
3686 q
+= ssh1_write_bignum(q
, s
->challenge
);
3687 memcpy(q
, s
->session_id
, 16);
3689 PUT_32BIT(q
, 1); /* response format */
3690 if (!agent_query(agentreq
, len
+ 4, &vret
, &retlen
,
3691 ssh_agent_callback
, ssh
)) {
3696 bombout(("Unexpected data from server"
3697 " while waiting for agent"
3701 } while (pktin
|| inlen
> 0);
3702 vret
= ssh
->agent_response
;
3703 retlen
= ssh
->agent_response_len
;
3708 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
3709 logevent("Sending Pageant's response");
3710 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
3711 PKT_DATA
, ret
+ 5, 16,
3715 if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
3717 ("Pageant's response accepted");
3718 if (flags
& FLAG_VERBOSE
) {
3719 c_write_str(ssh
, "Authenticated using"
3721 c_write(ssh
, s
->commentp
,
3723 c_write_str(ssh
, "\" from agent\r\n");
3728 ("Pageant's response not accepted");
3731 ("Pageant failed to answer challenge");
3735 logevent("No reply received from Pageant");
3738 freebn(s
->key
.exponent
);
3739 freebn(s
->key
.modulus
);
3740 freebn(s
->challenge
);
3745 if (s
->publickey_blob
&& !s
->tried_publickey
)
3746 logevent("Configured key file not in Pageant");
3748 logevent("Failed to get reply from Pageant");
3753 if (s
->publickey_blob
&& !s
->tried_publickey
) {
3755 * Try public key authentication with the specified
3758 int got_passphrase
; /* need not be kept over crReturn */
3759 if (flags
& FLAG_VERBOSE
)
3760 c_write_str(ssh
, "Trying public key authentication.\r\n");
3761 logeventf(ssh
, "Trying public key \"%s\"",
3762 filename_to_str(&ssh
->cfg
.keyfile
));
3763 s
->tried_publickey
= 1;
3764 got_passphrase
= FALSE
;
3765 while (!got_passphrase
) {
3767 * Get a passphrase, if necessary.
3769 char *passphrase
= NULL
; /* only written after crReturn */
3771 if (!s
->publickey_encrypted
) {
3772 if (flags
& FLAG_VERBOSE
)
3773 c_write_str(ssh
, "No passphrase required.\r\n");
3776 int ret
; /* need not be kept over crReturn */
3777 s
->cur_prompt
= new_prompts(ssh
->frontend
);
3778 s
->cur_prompt
->to_server
= FALSE
;
3779 s
->cur_prompt
->name
= dupstr("SSH key passphrase");
3780 add_prompt(s
->cur_prompt
,
3781 dupprintf("Passphrase for key \"%.100s\": ",
3782 s
->publickey_comment
),
3783 FALSE
, SSH_MAX_PASSWORD_LEN
);
3784 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
3787 crWaitUntil(!pktin
);
3788 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
3792 /* Failed to get a passphrase. Terminate. */
3793 free_prompts(s
->cur_prompt
);
3794 ssh_disconnect(ssh
, NULL
, "Unable to authenticate",
3798 passphrase
= dupstr(s
->cur_prompt
->prompts
[0]->result
);
3799 free_prompts(s
->cur_prompt
);
3802 * Try decrypting key with passphrase.
3804 ret
= loadrsakey(&ssh
->cfg
.keyfile
, &s
->key
, passphrase
,
3807 memset(passphrase
, 0, strlen(passphrase
));
3811 /* Correct passphrase. */
3812 got_passphrase
= TRUE
;
3813 } else if (ret
== 0) {
3814 c_write_str(ssh
, "Couldn't load private key from ");
3815 c_write_str(ssh
, filename_to_str(&ssh
->cfg
.keyfile
));
3816 c_write_str(ssh
, " (");
3817 c_write_str(ssh
, error
);
3818 c_write_str(ssh
, ").\r\n");
3819 got_passphrase
= FALSE
;
3820 break; /* go and try something else */
3821 } else if (ret
== -1) {
3822 c_write_str(ssh
, "Wrong passphrase.\r\n"); /* FIXME */
3823 got_passphrase
= FALSE
;
3826 assert(0 && "unexpected return from loadrsakey()");
3827 got_passphrase
= FALSE
; /* placate optimisers */
3831 if (got_passphrase
) {
3834 * Send a public key attempt.
3836 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
3837 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
3840 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3841 c_write_str(ssh
, "Server refused our public key.\r\n");
3842 continue; /* go and try something else */
3844 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
3845 bombout(("Bizarre response to offer of public key"));
3851 unsigned char buffer
[32];
3852 Bignum challenge
, response
;
3854 if ((challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
3855 bombout(("Server's RSA challenge was badly formatted"));
3858 response
= rsadecrypt(challenge
, &s
->key
);
3859 freebn(s
->key
.private_exponent
);/* burn the evidence */
3861 for (i
= 0; i
< 32; i
++) {
3862 buffer
[i
] = bignum_byte(response
, 31 - i
);
3866 MD5Update(&md5c
, buffer
, 32);
3867 MD5Update(&md5c
, s
->session_id
, 16);
3868 MD5Final(buffer
, &md5c
);
3870 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
3871 PKT_DATA
, buffer
, 16, PKT_END
);
3878 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3879 if (flags
& FLAG_VERBOSE
)
3880 c_write_str(ssh
, "Failed to authenticate with"
3881 " our public key.\r\n");
3882 continue; /* go and try something else */
3883 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3884 bombout(("Bizarre response to RSA authentication response"));
3888 break; /* we're through! */
3894 * Otherwise, try various forms of password-like authentication.
3896 s
->cur_prompt
= new_prompts(ssh
->frontend
);
3898 if (ssh
->cfg
.try_tis_auth
&&
3899 (s
->supported_auths_mask
& (1 << SSH1_AUTH_TIS
)) &&
3900 !s
->tis_auth_refused
) {
3901 s
->pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
3902 logevent("Requested TIS authentication");
3903 send_packet(ssh
, SSH1_CMSG_AUTH_TIS
, PKT_END
);
3905 if (pktin
->type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
3906 logevent("TIS authentication declined");
3907 if (flags
& FLAG_INTERACTIVE
)
3908 c_write_str(ssh
, "TIS authentication refused.\r\n");
3909 s
->tis_auth_refused
= 1;
3914 char *instr_suf
, *prompt
;
3916 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
3918 bombout(("TIS challenge packet was badly formed"));
3921 logevent("Received TIS challenge");
3922 s
->cur_prompt
->to_server
= TRUE
;
3923 s
->cur_prompt
->name
= dupstr("SSH TIS authentication");
3924 /* Prompt heuristic comes from OpenSSH */
3925 if (memchr(challenge
, '\n', challengelen
)) {
3926 instr_suf
= dupstr("");
3927 prompt
= dupprintf("%.*s", challengelen
, challenge
);
3929 instr_suf
= dupprintf("%.*s", challengelen
, challenge
);
3930 prompt
= dupstr("Response: ");
3932 s
->cur_prompt
->instruction
=
3933 dupprintf("Using TIS authentication.%s%s",
3934 (*instr_suf
) ?
"\n" : "",
3936 s
->cur_prompt
->instr_reqd
= TRUE
;
3937 add_prompt(s
->cur_prompt
, prompt
, FALSE
, SSH_MAX_PASSWORD_LEN
);
3941 if (ssh
->cfg
.try_tis_auth
&&
3942 (s
->supported_auths_mask
& (1 << SSH1_AUTH_CCARD
)) &&
3943 !s
->ccard_auth_refused
) {
3944 s
->pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
3945 logevent("Requested CryptoCard authentication");
3946 send_packet(ssh
, SSH1_CMSG_AUTH_CCARD
, PKT_END
);
3948 if (pktin
->type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
3949 logevent("CryptoCard authentication declined");
3950 c_write_str(ssh
, "CryptoCard authentication refused.\r\n");
3951 s
->ccard_auth_refused
= 1;
3956 char *instr_suf
, *prompt
;
3958 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
3960 bombout(("CryptoCard challenge packet was badly formed"));
3963 logevent("Received CryptoCard challenge");
3964 s
->cur_prompt
->to_server
= TRUE
;
3965 s
->cur_prompt
->name
= dupstr("SSH CryptoCard authentication");
3966 s
->cur_prompt
->name_reqd
= FALSE
;
3967 /* Prompt heuristic comes from OpenSSH */
3968 if (memchr(challenge
, '\n', challengelen
)) {
3969 instr_suf
= dupstr("");
3970 prompt
= dupprintf("%.*s", challengelen
, challenge
);
3972 instr_suf
= dupprintf("%.*s", challengelen
, challenge
);
3973 prompt
= dupstr("Response: ");
3975 s
->cur_prompt
->instruction
=
3976 dupprintf("Using CryptoCard authentication.%s%s",
3977 (*instr_suf
) ?
"\n" : "",
3979 s
->cur_prompt
->instr_reqd
= TRUE
;
3980 add_prompt(s
->cur_prompt
, prompt
, FALSE
, SSH_MAX_PASSWORD_LEN
);
3984 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
3985 if ((s
->supported_auths_mask
& (1 << SSH1_AUTH_PASSWORD
)) == 0) {
3986 bombout(("No supported authentication methods available"));
3989 s
->cur_prompt
->to_server
= TRUE
;
3990 s
->cur_prompt
->name
= dupstr("SSH password");
3991 add_prompt(s
->cur_prompt
, dupprintf("%.90s@%.90s's password: ",
3992 s
->username
, ssh
->savedhost
),
3993 FALSE
, SSH_MAX_PASSWORD_LEN
);
3997 * Show password prompt, having first obtained it via a TIS
3998 * or CryptoCard exchange if we're doing TIS or CryptoCard
4002 int ret
; /* need not be kept over crReturn */
4003 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
4006 crWaitUntil(!pktin
);
4007 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
4012 * Failed to get a password (for example
4013 * because one was supplied on the command line
4014 * which has already failed to work). Terminate.
4016 free_prompts(s
->cur_prompt
);
4017 ssh_disconnect(ssh
, NULL
, "Unable to authenticate", 0, TRUE
);
4022 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
4024 * Defence against traffic analysis: we send a
4025 * whole bunch of packets containing strings of
4026 * different lengths. One of these strings is the
4027 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4028 * The others are all random data in
4029 * SSH1_MSG_IGNORE packets. This way a passive
4030 * listener can't tell which is the password, and
4031 * hence can't deduce the password length.
4033 * Anybody with a password length greater than 16
4034 * bytes is going to have enough entropy in their
4035 * password that a listener won't find it _that_
4036 * much help to know how long it is. So what we'll
4039 * - if password length < 16, we send 15 packets
4040 * containing string lengths 1 through 15
4042 * - otherwise, we let N be the nearest multiple
4043 * of 8 below the password length, and send 8
4044 * packets containing string lengths N through
4045 * N+7. This won't obscure the order of
4046 * magnitude of the password length, but it will
4047 * introduce a bit of extra uncertainty.
4049 * A few servers can't deal with SSH1_MSG_IGNORE, at
4050 * least in this context. For these servers, we need
4051 * an alternative defence. We make use of the fact
4052 * that the password is interpreted as a C string:
4053 * so we can append a NUL, then some random data.
4055 * A few servers can deal with neither SSH1_MSG_IGNORE
4056 * here _nor_ a padded password string.
4057 * For these servers we are left with no defences
4058 * against password length sniffing.
4060 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
) &&
4061 !(ssh
->remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
4063 * The server can deal with SSH1_MSG_IGNORE, so
4064 * we can use the primary defence.
4066 int bottom
, top
, pwlen
, i
;
4069 pwlen
= strlen(s
->cur_prompt
->prompts
[0]->result
);
4071 bottom
= 0; /* zero length passwords are OK! :-) */
4074 bottom
= pwlen
& ~7;
4078 assert(pwlen
>= bottom
&& pwlen
<= top
);
4080 randomstr
= snewn(top
+ 1, char);
4082 for (i
= bottom
; i
<= top
; i
++) {
4084 defer_packet(ssh
, s
->pwpkt_type
,
4085 PKTT_PASSWORD
, PKT_STR
,
4086 s
->cur_prompt
->prompts
[0]->result
,
4087 PKTT_OTHER
, PKT_END
);
4089 for (j
= 0; j
< i
; j
++) {
4091 randomstr
[j
] = random_byte();
4092 } while (randomstr
[j
] == '\0');
4094 randomstr
[i
] = '\0';
4095 defer_packet(ssh
, SSH1_MSG_IGNORE
,
4096 PKT_STR
, randomstr
, PKT_END
);
4099 logevent("Sending password with camouflage packets");
4100 ssh_pkt_defersend(ssh
);
4103 else if (!(ssh
->remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
4105 * The server can't deal with SSH1_MSG_IGNORE
4106 * but can deal with padded passwords, so we
4107 * can use the secondary defence.
4113 len
= strlen(s
->cur_prompt
->prompts
[0]->result
);
4114 if (len
< sizeof(string
)) {
4116 strcpy(string
, s
->cur_prompt
->prompts
[0]->result
);
4117 len
++; /* cover the zero byte */
4118 while (len
< sizeof(string
)) {
4119 string
[len
++] = (char) random_byte();
4122 ss
= s
->cur_prompt
->prompts
[0]->result
;
4124 logevent("Sending length-padded password");
4125 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
4126 PKT_INT
, len
, PKT_DATA
, ss
, len
,
4127 PKTT_OTHER
, PKT_END
);
4130 * The server is believed unable to cope with
4131 * any of our password camouflage methods.
4134 len
= strlen(s
->cur_prompt
->prompts
[0]->result
);
4135 logevent("Sending unpadded password");
4136 send_packet(ssh
, s
->pwpkt_type
,
4137 PKTT_PASSWORD
, PKT_INT
, len
,
4138 PKT_DATA
, s
->cur_prompt
->prompts
[0]->result
, len
,
4139 PKTT_OTHER
, PKT_END
);
4142 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
4143 PKT_STR
, s
->cur_prompt
->prompts
[0]->result
,
4144 PKTT_OTHER
, PKT_END
);
4146 logevent("Sent password");
4147 free_prompts(s
->cur_prompt
);
4149 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4150 if (flags
& FLAG_VERBOSE
)
4151 c_write_str(ssh
, "Access denied\r\n");
4152 logevent("Authentication refused");
4153 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
4154 bombout(("Strange packet received, type %d", pktin
->type
));
4160 if (s
->publickey_blob
) {
4161 sfree(s
->publickey_blob
);
4162 sfree(s
->publickey_comment
);
4165 logevent("Authentication successful");
4170 void sshfwd_close(struct ssh_channel
*c
)
4174 if (ssh
->state
== SSH_STATE_CLOSED
)
4179 * If halfopen is true, we have sent
4180 * CHANNEL_OPEN for this channel, but it hasn't even been
4181 * acknowledged by the server. So we must set a close flag
4182 * on it now, and then when the server acks the channel
4183 * open, we can close it then.
4186 if (ssh
->version
== 1) {
4187 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
4189 c
->closes
= 1; /* sent MSG_CLOSE */
4191 int bytes_to_send
= bufchain_size(&c
->v
.v2
.outbuffer
);
4192 if (bytes_to_send
> 0) {
4194 * If we still have unsent data in our outgoing
4195 * buffer for this channel, we can't actually
4196 * initiate a close operation yet or that data
4197 * will be lost. Instead, set the pending_close
4198 * flag so that when we do clear the buffer
4199 * we'll start closing the channel.
4201 char logmsg
[160] = {'\0'};
4204 "Forwarded port pending to be closed : "
4205 "%d bytes remaining",
4209 c
->pending_close
= TRUE
;
4212 * No locally buffered data, so we can send the
4213 * close message immediately.
4215 struct Packet
*pktout
;
4216 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
4217 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
4218 ssh2_pkt_send(ssh
, pktout
);
4219 c
->closes
= 1; /* sent MSG_CLOSE */
4220 logevent("Nothing left to send, closing channel");
4225 if (c
->type
== CHAN_X11
) {
4227 logevent("Forwarded X11 connection terminated");
4228 } else if (c
->type
== CHAN_SOCKDATA
||
4229 c
->type
== CHAN_SOCKDATA_DORMANT
) {
4231 logevent("Forwarded port closed");
4236 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
4240 if (ssh
->state
== SSH_STATE_CLOSED
)
4243 if (ssh
->version
== 1) {
4244 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
4245 PKT_INT
, c
->remoteid
,
4246 PKT_INT
, len
, PKTT_DATA
, PKT_DATA
, buf
, len
,
4247 PKTT_OTHER
, PKT_END
);
4249 * In SSH-1 we can return 0 here - implying that forwarded
4250 * connections are never individually throttled - because
4251 * the only circumstance that can cause throttling will be
4252 * the whole SSH connection backing up, in which case
4253 * _everything_ will be throttled as a whole.
4257 ssh2_add_channel_data(c
, buf
, len
);
4258 return ssh2_try_send(c
);
4262 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
4267 if (ssh
->state
== SSH_STATE_CLOSED
)
4270 if (ssh
->version
== 1) {
4271 buflimit
= SSH1_BUFFER_LIMIT
;
4273 buflimit
= c
->v
.v2
.locmaxwin
;
4274 ssh2_set_window(c
, bufsize
< buflimit ? buflimit
- bufsize
: 0);
4276 if (c
->throttling_conn
&& bufsize
<= buflimit
) {
4277 c
->throttling_conn
= 0;
4278 ssh_throttle_conn(ssh
, -1);
4282 static void ssh_queueing_handler(Ssh ssh
, struct Packet
*pktin
)
4284 struct queued_handler
*qh
= ssh
->qhead
;
4288 assert(pktin
->type
== qh
->msg1
|| pktin
->type
== qh
->msg2
);
4291 assert(ssh
->packet_dispatch
[qh
->msg1
] == ssh_queueing_handler
);
4292 ssh
->packet_dispatch
[qh
->msg1
] = NULL
;
4295 assert(ssh
->packet_dispatch
[qh
->msg2
] == ssh_queueing_handler
);
4296 ssh
->packet_dispatch
[qh
->msg2
] = NULL
;
4300 ssh
->qhead
= qh
->next
;
4302 if (ssh
->qhead
->msg1
> 0) {
4303 assert(ssh
->packet_dispatch
[ssh
->qhead
->msg1
] == NULL
);
4304 ssh
->packet_dispatch
[ssh
->qhead
->msg1
] = ssh_queueing_handler
;
4306 if (ssh
->qhead
->msg2
> 0) {
4307 assert(ssh
->packet_dispatch
[ssh
->qhead
->msg2
] == NULL
);
4308 ssh
->packet_dispatch
[ssh
->qhead
->msg2
] = ssh_queueing_handler
;
4311 ssh
->qhead
= ssh
->qtail
= NULL
;
4312 ssh
->packet_dispatch
[pktin
->type
] = NULL
;
4315 qh
->handler(ssh
, pktin
, qh
->ctx
);
4320 static void ssh_queue_handler(Ssh ssh
, int msg1
, int msg2
,
4321 chandler_fn_t handler
, void *ctx
)
4323 struct queued_handler
*qh
;
4325 qh
= snew(struct queued_handler
);
4328 qh
->handler
= handler
;
4332 if (ssh
->qtail
== NULL
) {
4336 assert(ssh
->packet_dispatch
[qh
->msg1
] == NULL
);
4337 ssh
->packet_dispatch
[qh
->msg1
] = ssh_queueing_handler
;
4340 assert(ssh
->packet_dispatch
[qh
->msg2
] == NULL
);
4341 ssh
->packet_dispatch
[qh
->msg2
] = ssh_queueing_handler
;
4344 ssh
->qtail
->next
= qh
;
4349 static void ssh_rportfwd_succfail(Ssh ssh
, struct Packet
*pktin
, void *ctx
)
4351 struct ssh_rportfwd
*rpf
, *pf
= (struct ssh_rportfwd
*)ctx
;
4353 if (pktin
->type
== (ssh
->version
== 1 ? SSH1_SMSG_SUCCESS
:
4354 SSH2_MSG_REQUEST_SUCCESS
)) {
4355 logeventf(ssh
, "Remote port forwarding from %s enabled",
4358 logeventf(ssh
, "Remote port forwarding from %s refused",
4361 rpf
= del234(ssh
->rportfwds
, pf
);
4363 pf
->pfrec
->remote
= NULL
;
4368 static void ssh_setup_portfwd(Ssh ssh
, const Config
*cfg
)
4370 const char *portfwd_strptr
= cfg
->portfwd
;
4371 struct ssh_portfwd
*epf
;
4374 if (!ssh
->portfwds
) {
4375 ssh
->portfwds
= newtree234(ssh_portcmp
);
4378 * Go through the existing port forwardings and tag them
4379 * with status==DESTROY. Any that we want to keep will be
4380 * re-enabled (status==KEEP) as we go through the
4381 * configuration and find out which bits are the same as
4384 struct ssh_portfwd
*epf
;
4386 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
4387 epf
->status
= DESTROY
;
4390 while (*portfwd_strptr
) {
4391 char address_family
, type
;
4392 int sport
,dport
,sserv
,dserv
;
4393 char sports
[256], dports
[256], saddr
[256], host
[256];
4396 address_family
= 'A';
4398 if (*portfwd_strptr
== 'A' ||
4399 *portfwd_strptr
== '4' ||
4400 *portfwd_strptr
== '6')
4401 address_family
= *portfwd_strptr
++;
4402 if (*portfwd_strptr
== 'L' ||
4403 *portfwd_strptr
== 'R' ||
4404 *portfwd_strptr
== 'D')
4405 type
= *portfwd_strptr
++;
4410 while (*portfwd_strptr
&& *portfwd_strptr
!= '\t') {
4411 if (*portfwd_strptr
== ':') {
4413 * We've seen a colon in the middle of the
4414 * source port number. This means that
4415 * everything we've seen until now is the
4416 * source _address_, so we'll move it into
4417 * saddr and start sports from the beginning
4422 if (ssh
->version
== 1 && type
== 'R') {
4423 logeventf(ssh
, "SSH-1 cannot handle remote source address "
4424 "spec \"%s\"; ignoring", sports
);
4426 strcpy(saddr
, sports
);
4429 if (n
< lenof(sports
)-1) sports
[n
++] = *portfwd_strptr
++;
4433 if (*portfwd_strptr
== '\t')
4436 while (*portfwd_strptr
&& *portfwd_strptr
!= ':') {
4437 if (n
< lenof(host
)-1) host
[n
++] = *portfwd_strptr
++;
4440 if (*portfwd_strptr
== ':')
4443 while (*portfwd_strptr
) {
4444 if (n
< lenof(dports
)-1) dports
[n
++] = *portfwd_strptr
++;
4448 dport
= atoi(dports
);
4452 dport
= net_service_lookup(dports
);
4454 logeventf(ssh
, "Service lookup failed for destination"
4455 " port \"%s\"", dports
);
4459 while (*portfwd_strptr
) portfwd_strptr
++;
4463 portfwd_strptr
++; /* eat the NUL and move to next one */
4465 sport
= atoi(sports
);
4469 sport
= net_service_lookup(sports
);
4471 logeventf(ssh
, "Service lookup failed for source"
4472 " port \"%s\"", sports
);
4475 if (sport
&& dport
) {
4476 /* Set up a description of the source port. */
4477 struct ssh_portfwd
*pfrec
, *epfrec
;
4479 pfrec
= snew(struct ssh_portfwd
);
4481 pfrec
->saddr
= *saddr ?
dupstr(saddr
) : NULL
;
4482 pfrec
->sserv
= sserv ?
dupstr(sports
) : NULL
;
4483 pfrec
->sport
= sport
;
4484 pfrec
->daddr
= *host ?
dupstr(host
) : NULL
;
4485 pfrec
->dserv
= dserv ?
dupstr(dports
) : NULL
;
4486 pfrec
->dport
= dport
;
4487 pfrec
->local
= NULL
;
4488 pfrec
->remote
= NULL
;
4489 pfrec
->addressfamily
= (address_family
== '4' ? ADDRTYPE_IPV4
:
4490 address_family
== '6' ? ADDRTYPE_IPV6
:
4493 epfrec
= add234(ssh
->portfwds
, pfrec
);
4494 if (epfrec
!= pfrec
) {
4495 if (epfrec
->status
== DESTROY
) {
4497 * We already have a port forwarding up and running
4498 * with precisely these parameters. Hence, no need
4499 * to do anything; simply re-tag the existing one
4502 epfrec
->status
= KEEP
;
4505 * Anything else indicates that there was a duplicate
4506 * in our input, which we'll silently ignore.
4508 free_portfwd(pfrec
);
4510 pfrec
->status
= CREATE
;
4516 * Now go through and destroy any port forwardings which were
4519 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
4520 if (epf
->status
== DESTROY
) {
4523 message
= dupprintf("%s port forwarding from %s%s%d",
4524 epf
->type
== 'L' ?
"local" :
4525 epf
->type
== 'R' ?
"remote" : "dynamic",
4526 epf
->saddr ? epf
->saddr
: "",
4527 epf
->saddr ?
":" : "",
4530 if (epf
->type
!= 'D') {
4531 char *msg2
= dupprintf("%s to %s:%d", message
,
4532 epf
->daddr
, epf
->dport
);
4537 logeventf(ssh
, "Cancelling %s", message
);
4540 /* epf->remote or epf->local may be NULL if setting up a
4541 * forwarding failed. */
4543 struct ssh_rportfwd
*rpf
= epf
->remote
;
4544 struct Packet
*pktout
;
4547 * Cancel the port forwarding at the server
4550 if (ssh
->version
== 1) {
4552 * We cannot cancel listening ports on the
4553 * server side in SSH-1! There's no message
4554 * to support it. Instead, we simply remove
4555 * the rportfwd record from the local end
4556 * so that any connections the server tries
4557 * to make on it are rejected.
4560 pktout
= ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4561 ssh2_pkt_addstring(pktout
, "cancel-tcpip-forward");
4562 ssh2_pkt_addbool(pktout
, 0);/* _don't_ want reply */
4564 ssh2_pkt_addstring(pktout
, epf
->saddr
);
4565 } else if (ssh
->cfg
.rport_acceptall
) {
4566 /* XXX: ssh->cfg.rport_acceptall may not represent
4567 * what was used to open the original connection,
4568 * since it's reconfigurable. */
4569 ssh2_pkt_addstring(pktout
, "0.0.0.0");
4571 ssh2_pkt_addstring(pktout
, "127.0.0.1");
4573 ssh2_pkt_adduint32(pktout
, epf
->sport
);
4574 ssh2_pkt_send(ssh
, pktout
);
4577 del234(ssh
->rportfwds
, rpf
);
4579 } else if (epf
->local
) {
4580 pfd_terminate(epf
->local
);
4583 delpos234(ssh
->portfwds
, i
);
4585 i
--; /* so we don't skip one in the list */
4589 * And finally, set up any new port forwardings (status==CREATE).
4591 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
4592 if (epf
->status
== CREATE
) {
4593 char *sportdesc
, *dportdesc
;
4594 sportdesc
= dupprintf("%s%s%s%s%d%s",
4595 epf
->saddr ? epf
->saddr
: "",
4596 epf
->saddr ?
":" : "",
4597 epf
->sserv ? epf
->sserv
: "",
4598 epf
->sserv ?
"(" : "",
4600 epf
->sserv ?
")" : "");
4601 if (epf
->type
== 'D') {
4604 dportdesc
= dupprintf("%s:%s%s%d%s",
4606 epf
->dserv ? epf
->dserv
: "",
4607 epf
->dserv ?
"(" : "",
4609 epf
->dserv ?
")" : "");
4612 if (epf
->type
== 'L') {
4613 const char *err
= pfd_addforward(epf
->daddr
, epf
->dport
,
4614 epf
->saddr
, epf
->sport
,
4617 epf
->addressfamily
);
4619 logeventf(ssh
, "Local %sport %s forwarding to %s%s%s",
4620 epf
->addressfamily
== ADDRTYPE_IPV4 ?
"IPv4 " :
4621 epf
->addressfamily
== ADDRTYPE_IPV6 ?
"IPv6 " : "",
4622 sportdesc
, dportdesc
,
4623 err ?
" failed: " : "", err ? err
: "");
4624 } else if (epf
->type
== 'D') {
4625 const char *err
= pfd_addforward(NULL
, -1,
4626 epf
->saddr
, epf
->sport
,
4629 epf
->addressfamily
);
4631 logeventf(ssh
, "Local %sport %s SOCKS dynamic forwarding%s%s",
4632 epf
->addressfamily
== ADDRTYPE_IPV4 ?
"IPv4 " :
4633 epf
->addressfamily
== ADDRTYPE_IPV6 ?
"IPv6 " : "",
4635 err ?
" failed: " : "", err ? err
: "");
4637 struct ssh_rportfwd
*pf
;
4640 * Ensure the remote port forwardings tree exists.
4642 if (!ssh
->rportfwds
) {
4643 if (ssh
->version
== 1)
4644 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh1
);
4646 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh2
);
4649 pf
= snew(struct ssh_rportfwd
);
4650 strncpy(pf
->dhost
, epf
->daddr
, lenof(pf
->dhost
)-1);
4651 pf
->dhost
[lenof(pf
->dhost
)-1] = '\0';
4652 pf
->dport
= epf
->dport
;
4653 pf
->sport
= epf
->sport
;
4654 if (add234(ssh
->rportfwds
, pf
) != pf
) {
4655 logeventf(ssh
, "Duplicate remote port forwarding to %s:%d",
4656 epf
->daddr
, epf
->dport
);
4659 logeventf(ssh
, "Requesting remote port %s"
4660 " forward to %s", sportdesc
, dportdesc
);
4662 pf
->sportdesc
= sportdesc
;
4667 if (ssh
->version
== 1) {
4668 send_packet(ssh
, SSH1_CMSG_PORT_FORWARD_REQUEST
,
4669 PKT_INT
, epf
->sport
,
4670 PKT_STR
, epf
->daddr
,
4671 PKT_INT
, epf
->dport
,
4673 ssh_queue_handler(ssh
, SSH1_SMSG_SUCCESS
,
4675 ssh_rportfwd_succfail
, pf
);
4677 struct Packet
*pktout
;
4678 pktout
= ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4679 ssh2_pkt_addstring(pktout
, "tcpip-forward");
4680 ssh2_pkt_addbool(pktout
, 1);/* want reply */
4682 ssh2_pkt_addstring(pktout
, epf
->saddr
);
4683 } else if (cfg
->rport_acceptall
) {
4684 ssh2_pkt_addstring(pktout
, "0.0.0.0");
4686 ssh2_pkt_addstring(pktout
, "127.0.0.1");
4688 ssh2_pkt_adduint32(pktout
, epf
->sport
);
4689 ssh2_pkt_send(ssh
, pktout
);
4691 ssh_queue_handler(ssh
, SSH2_MSG_REQUEST_SUCCESS
,
4692 SSH2_MSG_REQUEST_FAILURE
,
4693 ssh_rportfwd_succfail
, pf
);
4702 static void ssh1_smsg_stdout_stderr_data(Ssh ssh
, struct Packet
*pktin
)
4705 int stringlen
, bufsize
;
4707 ssh_pkt_getstring(pktin
, &string
, &stringlen
);
4708 if (string
== NULL
) {
4709 bombout(("Incoming terminal data packet was badly formed"));
4713 bufsize
= from_backend(ssh
->frontend
, pktin
->type
== SSH1_SMSG_STDERR_DATA
,
4715 if (!ssh
->v1_stdout_throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
4716 ssh
->v1_stdout_throttling
= 1;
4717 ssh_throttle_conn(ssh
, +1);
4721 static void ssh1_smsg_x11_open(Ssh ssh
, struct Packet
*pktin
)
4723 /* Remote side is trying to open a channel to talk to our
4724 * X-Server. Give them back a local channel number. */
4725 struct ssh_channel
*c
;
4726 int remoteid
= ssh_pkt_getuint32(pktin
);
4728 logevent("Received X11 connect request");
4729 /* Refuse if X11 forwarding is disabled. */
4730 if (!ssh
->X11_fwd_enabled
) {
4731 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4732 PKT_INT
, remoteid
, PKT_END
);
4733 logevent("Rejected X11 connect request");
4735 c
= snew(struct ssh_channel
);
4738 if (x11_init(&c
->u
.x11
.s
, ssh
->x11disp
, c
,
4739 NULL
, -1, &ssh
->cfg
) != NULL
) {
4740 logevent("Opening X11 forward connection failed");
4742 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4743 PKT_INT
, remoteid
, PKT_END
);
4746 ("Opening X11 forward connection succeeded");
4747 c
->remoteid
= remoteid
;
4748 c
->halfopen
= FALSE
;
4749 c
->localid
= alloc_channel_id(ssh
);
4751 c
->pending_close
= FALSE
;
4752 c
->throttling_conn
= 0;
4753 c
->type
= CHAN_X11
; /* identify channel type */
4754 add234(ssh
->channels
, c
);
4755 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4756 PKT_INT
, c
->remoteid
, PKT_INT
,
4757 c
->localid
, PKT_END
);
4758 logevent("Opened X11 forward channel");
4763 static void ssh1_smsg_agent_open(Ssh ssh
, struct Packet
*pktin
)
4765 /* Remote side is trying to open a channel to talk to our
4766 * agent. Give them back a local channel number. */
4767 struct ssh_channel
*c
;
4768 int remoteid
= ssh_pkt_getuint32(pktin
);
4770 /* Refuse if agent forwarding is disabled. */
4771 if (!ssh
->agentfwd_enabled
) {
4772 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4773 PKT_INT
, remoteid
, PKT_END
);
4775 c
= snew(struct ssh_channel
);
4777 c
->remoteid
= remoteid
;
4778 c
->halfopen
= FALSE
;
4779 c
->localid
= alloc_channel_id(ssh
);
4781 c
->pending_close
= FALSE
;
4782 c
->throttling_conn
= 0;
4783 c
->type
= CHAN_AGENT
; /* identify channel type */
4784 c
->u
.a
.lensofar
= 0;
4785 add234(ssh
->channels
, c
);
4786 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4787 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
4792 static void ssh1_msg_port_open(Ssh ssh
, struct Packet
*pktin
)
4794 /* Remote side is trying to open a channel to talk to a
4795 * forwarded port. Give them back a local channel number. */
4796 struct ssh_channel
*c
;
4797 struct ssh_rportfwd pf
, *pfp
;
4802 c
= snew(struct ssh_channel
);
4805 remoteid
= ssh_pkt_getuint32(pktin
);
4806 ssh_pkt_getstring(pktin
, &host
, &hostsize
);
4807 port
= ssh_pkt_getuint32(pktin
);
4809 if (hostsize
>= lenof(pf
.dhost
))
4810 hostsize
= lenof(pf
.dhost
)-1;
4811 memcpy(pf
.dhost
, host
, hostsize
);
4812 pf
.dhost
[hostsize
] = '\0';
4814 pfp
= find234(ssh
->rportfwds
, &pf
, NULL
);
4817 logeventf(ssh
, "Rejected remote port open request for %s:%d",
4819 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4820 PKT_INT
, remoteid
, PKT_END
);
4822 logeventf(ssh
, "Received remote port open request for %s:%d",
4824 e
= pfd_newconnect(&c
->u
.pfd
.s
, pf
.dhost
, port
,
4825 c
, &ssh
->cfg
, pfp
->pfrec
->addressfamily
);
4827 logeventf(ssh
, "Port open failed: %s", e
);
4829 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4830 PKT_INT
, remoteid
, PKT_END
);
4832 c
->remoteid
= remoteid
;
4833 c
->halfopen
= FALSE
;
4834 c
->localid
= alloc_channel_id(ssh
);
4836 c
->pending_close
= FALSE
;
4837 c
->throttling_conn
= 0;
4838 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
4839 add234(ssh
->channels
, c
);
4840 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4841 PKT_INT
, c
->remoteid
, PKT_INT
,
4842 c
->localid
, PKT_END
);
4843 logevent("Forwarded port opened successfully");
4848 static void ssh1_msg_channel_open_confirmation(Ssh ssh
, struct Packet
*pktin
)
4850 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
4851 unsigned int localid
= ssh_pkt_getuint32(pktin
);
4852 struct ssh_channel
*c
;
4854 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
4855 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
4856 c
->remoteid
= localid
;
4857 c
->halfopen
= FALSE
;
4858 c
->type
= CHAN_SOCKDATA
;
4859 c
->throttling_conn
= 0;
4860 pfd_confirm(c
->u
.pfd
.s
);
4863 if (c
&& c
->closes
) {
4865 * We have a pending close on this channel,
4866 * which we decided on before the server acked
4867 * the channel open. So now we know the
4868 * remoteid, we can close it again.
4870 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
,
4871 PKT_INT
, c
->remoteid
, PKT_END
);
4875 static void ssh1_msg_channel_open_failure(Ssh ssh
, struct Packet
*pktin
)
4877 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
4878 struct ssh_channel
*c
;
4880 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
4881 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
4882 logevent("Forwarded connection refused by server");
4883 pfd_close(c
->u
.pfd
.s
);
4884 del234(ssh
->channels
, c
);
4889 static void ssh1_msg_channel_close(Ssh ssh
, struct Packet
*pktin
)
4891 /* Remote side closes a channel. */
4892 unsigned i
= ssh_pkt_getuint32(pktin
);
4893 struct ssh_channel
*c
;
4894 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
4895 if (c
&& !c
->halfopen
) {
4898 (pktin
->type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
4900 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
4901 logevent("Forwarded X11 connection terminated");
4902 assert(c
->u
.x11
.s
!= NULL
);
4903 x11_close(c
->u
.x11
.s
);
4906 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
4907 logevent("Forwarded port closed");
4908 assert(c
->u
.pfd
.s
!= NULL
);
4909 pfd_close(c
->u
.pfd
.s
);
4913 c
->closes
|= (closetype
<< 2); /* seen this message */
4914 if (!(c
->closes
& closetype
)) {
4915 send_packet(ssh
, pktin
->type
, PKT_INT
, c
->remoteid
,
4917 c
->closes
|= closetype
; /* sent it too */
4920 if (c
->closes
== 15) {
4921 del234(ssh
->channels
, c
);
4925 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4926 pktin
->type
== SSH1_MSG_CHANNEL_CLOSE ?
"" :
4927 "_CONFIRMATION", c ?
"half-open" : "nonexistent",
4932 static void ssh1_msg_channel_data(Ssh ssh
, struct Packet
*pktin
)
4934 /* Data sent down one of our channels. */
4935 int i
= ssh_pkt_getuint32(pktin
);
4938 struct ssh_channel
*c
;
4940 ssh_pkt_getstring(pktin
, &p
, &len
);
4942 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
4947 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
4950 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
4953 /* Data for an agent message. Buffer it. */
4955 if (c
->u
.a
.lensofar
< 4) {
4956 unsigned int l
= min(4 - c
->u
.a
.lensofar
, (unsigned)len
);
4957 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
4961 c
->u
.a
.lensofar
+= l
;
4963 if (c
->u
.a
.lensofar
== 4) {
4965 4 + GET_32BIT(c
->u
.a
.msglen
);
4966 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
4968 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
4970 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
4972 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
4974 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
4978 c
->u
.a
.lensofar
+= l
;
4980 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
4983 if (agent_query(c
->u
.a
.message
,
4986 ssh_agentf_callback
, c
))
4987 ssh_agentf_callback(c
, reply
, replylen
);
4988 sfree(c
->u
.a
.message
);
4989 c
->u
.a
.lensofar
= 0;
4992 bufsize
= 0; /* agent channels never back up */
4995 if (!c
->throttling_conn
&& bufsize
> SSH1_BUFFER_LIMIT
) {
4996 c
->throttling_conn
= 1;
4997 ssh_throttle_conn(ssh
, +1);
5002 static void ssh1_smsg_exit_status(Ssh ssh
, struct Packet
*pktin
)
5004 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
5005 logeventf(ssh
, "Server sent command exit status %d", ssh
->exitcode
);
5006 send_packet(ssh
, SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
5008 * In case `helpful' firewalls or proxies tack
5009 * extra human-readable text on the end of the
5010 * session which we might mistake for another
5011 * encrypted packet, we close the session once
5012 * we've sent EXIT_CONFIRMATION.
5014 ssh_disconnect(ssh
, NULL
, NULL
, 0, TRUE
);
5017 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5018 static void ssh1_send_ttymode(void *data
, char *mode
, char *val
)
5020 struct Packet
*pktout
= (struct Packet
*)data
;
5022 unsigned int arg
= 0;
5023 while (strcmp(mode
, ssh_ttymodes
[i
].mode
) != 0) i
++;
5024 if (i
== lenof(ssh_ttymodes
)) return;
5025 switch (ssh_ttymodes
[i
].type
) {
5027 arg
= ssh_tty_parse_specchar(val
);
5030 arg
= ssh_tty_parse_boolean(val
);
5033 ssh2_pkt_addbyte(pktout
, ssh_ttymodes
[i
].opcode
);
5034 ssh2_pkt_addbyte(pktout
, arg
);
5038 static void do_ssh1_connection(Ssh ssh
, unsigned char *in
, int inlen
,
5039 struct Packet
*pktin
)
5041 crBegin(ssh
->do_ssh1_connection_crstate
);
5043 ssh
->packet_dispatch
[SSH1_SMSG_STDOUT_DATA
] =
5044 ssh
->packet_dispatch
[SSH1_SMSG_STDERR_DATA
] =
5045 ssh1_smsg_stdout_stderr_data
;
5047 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
] =
5048 ssh1_msg_channel_open_confirmation
;
5049 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_OPEN_FAILURE
] =
5050 ssh1_msg_channel_open_failure
;
5051 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_CLOSE
] =
5052 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
] =
5053 ssh1_msg_channel_close
;
5054 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_DATA
] = ssh1_msg_channel_data
;
5055 ssh
->packet_dispatch
[SSH1_SMSG_EXIT_STATUS
] = ssh1_smsg_exit_status
;
5057 if (ssh
->cfg
.agentfwd
&& agent_exists()) {
5058 logevent("Requesting agent forwarding");
5059 send_packet(ssh
, SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
5063 if (pktin
->type
!= SSH1_SMSG_SUCCESS
5064 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
5065 bombout(("Protocol confusion"));
5067 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
5068 logevent("Agent forwarding refused");
5070 logevent("Agent forwarding enabled");
5071 ssh
->agentfwd_enabled
= TRUE
;
5072 ssh
->packet_dispatch
[SSH1_SMSG_AGENT_OPEN
] = ssh1_smsg_agent_open
;
5076 if (ssh
->cfg
.x11_forward
&&
5077 (ssh
->x11disp
= x11_setup_display(ssh
->cfg
.x11_display
,
5078 ssh
->cfg
.x11_auth
, &ssh
->cfg
))) {
5079 logevent("Requesting X11 forwarding");
5081 * Note that while we blank the X authentication data here, we don't
5082 * take any special action to blank the start of an X11 channel,
5083 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
5084 * without having session blanking enabled is likely to leak your
5085 * cookie into the log.
5087 if (ssh
->v1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
5088 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
5089 PKT_STR
, ssh
->x11disp
->remoteauthprotoname
,
5091 PKT_STR
, ssh
->x11disp
->remoteauthdatastring
,
5093 PKT_INT
, ssh
->x11disp
->screennum
,
5096 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
5097 PKT_STR
, ssh
->x11disp
->remoteauthprotoname
,
5099 PKT_STR
, ssh
->x11disp
->remoteauthdatastring
,
5106 if (pktin
->type
!= SSH1_SMSG_SUCCESS
5107 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
5108 bombout(("Protocol confusion"));
5110 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
5111 logevent("X11 forwarding refused");
5113 logevent("X11 forwarding enabled");
5114 ssh
->X11_fwd_enabled
= TRUE
;
5115 ssh
->packet_dispatch
[SSH1_SMSG_X11_OPEN
] = ssh1_smsg_x11_open
;
5119 ssh_setup_portfwd(ssh
, &ssh
->cfg
);
5120 ssh
->packet_dispatch
[SSH1_MSG_PORT_OPEN
] = ssh1_msg_port_open
;
5122 if (!ssh
->cfg
.nopty
) {
5124 /* Unpick the terminal-speed string. */
5125 /* XXX perhaps we should allow no speeds to be sent. */
5126 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
5127 sscanf(ssh
->cfg
.termspeed
, "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
5128 /* Send the pty request. */
5129 pkt
= ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY
);
5130 ssh_pkt_addstring(pkt
, ssh
->cfg
.termtype
);
5131 ssh_pkt_adduint32(pkt
, ssh
->term_height
);
5132 ssh_pkt_adduint32(pkt
, ssh
->term_width
);
5133 ssh_pkt_adduint32(pkt
, 0); /* width in pixels */
5134 ssh_pkt_adduint32(pkt
, 0); /* height in pixels */
5135 parse_ttymodes(ssh
, ssh
->cfg
.ttymodes
,
5136 ssh1_send_ttymode
, (void *)pkt
);
5137 ssh_pkt_addbyte(pkt
, SSH1_TTY_OP_ISPEED
);
5138 ssh_pkt_adduint32(pkt
, ssh
->ispeed
);
5139 ssh_pkt_addbyte(pkt
, SSH1_TTY_OP_OSPEED
);
5140 ssh_pkt_adduint32(pkt
, ssh
->ospeed
);
5141 ssh_pkt_addbyte(pkt
, SSH_TTY_OP_END
);
5143 ssh
->state
= SSH_STATE_INTERMED
;
5147 if (pktin
->type
!= SSH1_SMSG_SUCCESS
5148 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
5149 bombout(("Protocol confusion"));
5151 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
5152 c_write_str(ssh
, "Server refused to allocate pty\r\n");
5153 ssh
->editing
= ssh
->echoing
= 1;
5155 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5156 ssh
->ospeed
, ssh
->ispeed
);
5158 ssh
->editing
= ssh
->echoing
= 1;
5161 if (ssh
->cfg
.compression
) {
5162 send_packet(ssh
, SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
5166 if (pktin
->type
!= SSH1_SMSG_SUCCESS
5167 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
5168 bombout(("Protocol confusion"));
5170 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
5171 c_write_str(ssh
, "Server refused to compress\r\n");
5173 logevent("Started compression");
5174 ssh
->v1_compressing
= TRUE
;
5175 ssh
->cs_comp_ctx
= zlib_compress_init();
5176 logevent("Initialised zlib (RFC1950) compression");
5177 ssh
->sc_comp_ctx
= zlib_decompress_init();
5178 logevent("Initialised zlib (RFC1950) decompression");
5182 * Start the shell or command.
5184 * Special case: if the first-choice command is an SSH-2
5185 * subsystem (hence not usable here) and the second choice
5186 * exists, we fall straight back to that.
5189 char *cmd
= ssh
->cfg
.remote_cmd_ptr
;
5191 if (!cmd
) cmd
= ssh
->cfg
.remote_cmd
;
5193 if (ssh
->cfg
.ssh_subsys
&& ssh
->cfg
.remote_cmd_ptr2
) {
5194 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
5195 ssh
->fallback_cmd
= TRUE
;
5198 send_packet(ssh
, SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
5200 send_packet(ssh
, SSH1_CMSG_EXEC_SHELL
, PKT_END
);
5201 logevent("Started session");
5204 ssh
->state
= SSH_STATE_SESSION
;
5205 if (ssh
->size_needed
)
5206 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
5207 if (ssh
->eof_needed
)
5208 ssh_special(ssh
, TS_EOF
);
5211 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
5213 ssh
->channels
= newtree234(ssh_channelcmp
);
5217 * By this point, most incoming packets are already being
5218 * handled by the dispatch table, and we need only pay
5219 * attention to the unusual ones.
5224 if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
5225 /* may be from EXEC_SHELL on some servers */
5226 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
5227 /* may be from EXEC_SHELL on some servers
5228 * if no pty is available or in other odd cases. Ignore */
5230 bombout(("Strange packet received: type %d", pktin
->type
));
5235 int len
= min(inlen
, 512);
5236 send_packet(ssh
, SSH1_CMSG_STDIN_DATA
,
5237 PKT_INT
, len
, PKTT_DATA
, PKT_DATA
, in
, len
,
5238 PKTT_OTHER
, PKT_END
);
5249 * Handle the top-level SSH-2 protocol.
5251 static void ssh1_msg_debug(Ssh ssh
, struct Packet
*pktin
)
5256 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
5257 logeventf(ssh
, "Remote debug message: %.*s", msglen
, msg
);
5260 static void ssh1_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
5262 /* log reason code in disconnect message */
5266 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
5267 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen
, msg
));
5270 static void ssh_msg_ignore(Ssh ssh
, struct Packet
*pktin
)
5272 /* Do nothing, because we're ignoring it! Duhh. */
5275 static void ssh1_protocol_setup(Ssh ssh
)
5280 * Most messages are handled by the coroutines.
5282 for (i
= 0; i
< 256; i
++)
5283 ssh
->packet_dispatch
[i
] = NULL
;
5286 * These special message types we install handlers for.
5288 ssh
->packet_dispatch
[SSH1_MSG_DISCONNECT
] = ssh1_msg_disconnect
;
5289 ssh
->packet_dispatch
[SSH1_MSG_IGNORE
] = ssh_msg_ignore
;
5290 ssh
->packet_dispatch
[SSH1_MSG_DEBUG
] = ssh1_msg_debug
;
5293 static void ssh1_protocol(Ssh ssh
, void *vin
, int inlen
,
5294 struct Packet
*pktin
)
5296 unsigned char *in
=(unsigned char*)vin
;
5297 if (ssh
->state
== SSH_STATE_CLOSED
)
5300 if (pktin
&& ssh
->packet_dispatch
[pktin
->type
]) {
5301 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
5305 if (!ssh
->protocol_initial_phase_done
) {
5306 if (do_ssh1_login(ssh
, in
, inlen
, pktin
))
5307 ssh
->protocol_initial_phase_done
= TRUE
;
5312 do_ssh1_connection(ssh
, in
, inlen
, pktin
);
5316 * Utility routine for decoding comma-separated strings in KEXINIT.
5318 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
5321 if (!needle
|| !haystack
) /* protect against null pointers */
5323 needlen
= strlen(needle
);
5326 * Is it at the start of the string?
5328 if (haylen
>= needlen
&& /* haystack is long enough */
5329 !memcmp(needle
, haystack
, needlen
) && /* initial match */
5330 (haylen
== needlen
|| haystack
[needlen
] == ',')
5331 /* either , or EOS follows */
5335 * If not, search for the next comma and resume after that.
5336 * If no comma found, terminate.
5338 while (haylen
> 0 && *haystack
!= ',')
5339 haylen
--, haystack
++;
5342 haylen
--, haystack
++; /* skip over comma itself */
5347 * Similar routine for checking whether we have the first string in a list.
5349 static int first_in_commasep_string(char *needle
, char *haystack
, int haylen
)
5352 if (!needle
|| !haystack
) /* protect against null pointers */
5354 needlen
= strlen(needle
);
5356 * Is it at the start of the string?
5358 if (haylen
>= needlen
&& /* haystack is long enough */
5359 !memcmp(needle
, haystack
, needlen
) && /* initial match */
5360 (haylen
== needlen
|| haystack
[needlen
] == ',')
5361 /* either , or EOS follows */
5369 * SSH-2 key creation method.
5370 * (Currently assumes 2 lots of any hash are sufficient to generate
5371 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5373 #define SSH2_MKKEY_ITERS (2)
5374 static void ssh2_mkkey(Ssh ssh
, Bignum K
, unsigned char *H
, char chr
,
5375 unsigned char *keyspace
)
5377 const struct ssh_hash
*h
= ssh
->kex
->hash
;
5379 /* First hlen bytes. */
5381 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
5382 hash_mpint(h
, s
, K
);
5383 h
->bytes(s
, H
, h
->hlen
);
5384 h
->bytes(s
, &chr
, 1);
5385 h
->bytes(s
, ssh
->v2_session_id
, ssh
->v2_session_id_len
);
5386 h
->final(s
, keyspace
);
5387 /* Next hlen bytes. */
5389 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
5390 hash_mpint(h
, s
, K
);
5391 h
->bytes(s
, H
, h
->hlen
);
5392 h
->bytes(s
, keyspace
, h
->hlen
);
5393 h
->final(s
, keyspace
+ h
->hlen
);
5397 * Handle the SSH-2 transport layer.
5399 static int do_ssh2_transport(Ssh ssh
, void *vin
, int inlen
,
5400 struct Packet
*pktin
)
5402 unsigned char *in
= (unsigned char *)vin
;
5403 struct do_ssh2_transport_state
{
5404 int nbits
, pbits
, warn_kex
, warn_cscipher
, warn_sccipher
;
5405 Bignum p
, g
, e
, f
, K
;
5408 int kex_init_value
, kex_reply_value
;
5409 const struct ssh_mac
**maclist
;
5411 const struct ssh2_cipher
*cscipher_tobe
;
5412 const struct ssh2_cipher
*sccipher_tobe
;
5413 const struct ssh_mac
*csmac_tobe
;
5414 const struct ssh_mac
*scmac_tobe
;
5415 const struct ssh_compress
*cscomp_tobe
;
5416 const struct ssh_compress
*sccomp_tobe
;
5417 char *hostkeydata
, *sigdata
, *rsakeydata
, *keystr
, *fingerprint
;
5418 int hostkeylen
, siglen
, rsakeylen
;
5419 void *hkey
; /* actual host key */
5420 void *rsakey
; /* for RSA kex */
5421 unsigned char exchange_hash
[SSH2_KEX_MAX_HASH_LEN
];
5422 int n_preferred_kex
;
5423 const struct ssh_kexes
*preferred_kex
[KEX_MAX
];
5424 int n_preferred_ciphers
;
5425 const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
5426 const struct ssh_compress
*preferred_comp
;
5427 int userauth_succeeded
; /* for delayed compression */
5428 int pending_compression
;
5429 int got_session_id
, activated_authconn
;
5430 struct Packet
*pktout
;
5435 crState(do_ssh2_transport_state
);
5437 crBegin(ssh
->do_ssh2_transport_crstate
);
5439 s
->cscipher_tobe
= s
->sccipher_tobe
= NULL
;
5440 s
->csmac_tobe
= s
->scmac_tobe
= NULL
;
5441 s
->cscomp_tobe
= s
->sccomp_tobe
= NULL
;
5443 s
->got_session_id
= s
->activated_authconn
= FALSE
;
5444 s
->userauth_succeeded
= FALSE
;
5445 s
->pending_compression
= FALSE
;
5448 * Be prepared to work around the buggy MAC problem.
5450 if (ssh
->remote_bugs
& BUG_SSH2_HMAC
)
5451 s
->maclist
= buggymacs
, s
->nmacs
= lenof(buggymacs
);
5453 s
->maclist
= macs
, s
->nmacs
= lenof(macs
);
5456 ssh
->pkt_kctx
= SSH2_PKTCTX_NOKEX
;
5458 int i
, j
, commalist_started
;
5461 * Set up the preferred key exchange. (NULL => warn below here)
5463 s
->n_preferred_kex
= 0;
5464 for (i
= 0; i
< KEX_MAX
; i
++) {
5465 switch (ssh
->cfg
.ssh_kexlist
[i
]) {
5467 s
->preferred_kex
[s
->n_preferred_kex
++] =
5468 &ssh_diffiehellman_gex
;
5471 s
->preferred_kex
[s
->n_preferred_kex
++] =
5472 &ssh_diffiehellman_group14
;
5475 s
->preferred_kex
[s
->n_preferred_kex
++] =
5476 &ssh_diffiehellman_group1
;
5479 s
->preferred_kex
[s
->n_preferred_kex
++] =
5483 /* Flag for later. Don't bother if it's the last in
5485 if (i
< KEX_MAX
- 1) {
5486 s
->preferred_kex
[s
->n_preferred_kex
++] = NULL
;
5493 * Set up the preferred ciphers. (NULL => warn below here)
5495 s
->n_preferred_ciphers
= 0;
5496 for (i
= 0; i
< CIPHER_MAX
; i
++) {
5497 switch (ssh
->cfg
.ssh_cipherlist
[i
]) {
5498 case CIPHER_BLOWFISH
:
5499 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_blowfish
;
5502 if (ssh
->cfg
.ssh2_des_cbc
) {
5503 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_des
;
5507 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_3des
;
5510 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_aes
;
5512 case CIPHER_ARCFOUR
:
5513 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_arcfour
;
5516 /* Flag for later. Don't bother if it's the last in
5518 if (i
< CIPHER_MAX
- 1) {
5519 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = NULL
;
5526 * Set up preferred compression.
5528 if (ssh
->cfg
.compression
)
5529 s
->preferred_comp
= &ssh_zlib
;
5531 s
->preferred_comp
= &ssh_comp_none
;
5534 * Enable queueing of outgoing auth- or connection-layer
5535 * packets while we are in the middle of a key exchange.
5537 ssh
->queueing
= TRUE
;
5540 * Flag that KEX is in progress.
5542 ssh
->kex_in_progress
= TRUE
;
5545 * Construct and send our key exchange packet.
5547 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEXINIT
);
5548 for (i
= 0; i
< 16; i
++)
5549 ssh2_pkt_addbyte(s
->pktout
, (unsigned char) random_byte());
5550 /* List key exchange algorithms. */
5551 ssh2_pkt_addstring_start(s
->pktout
);
5552 commalist_started
= 0;
5553 for (i
= 0; i
< s
->n_preferred_kex
; i
++) {
5554 const struct ssh_kexes
*k
= s
->preferred_kex
[i
];
5555 if (!k
) continue; /* warning flag */
5556 for (j
= 0; j
< k
->nkexes
; j
++) {
5557 if (commalist_started
)
5558 ssh2_pkt_addstring_str(s
->pktout
, ",");
5559 ssh2_pkt_addstring_str(s
->pktout
, k
->list
[j
]->name
);
5560 commalist_started
= 1;
5563 /* List server host key algorithms. */
5564 ssh2_pkt_addstring_start(s
->pktout
);
5565 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
5566 ssh2_pkt_addstring_str(s
->pktout
, hostkey_algs
[i
]->name
);
5567 if (i
< lenof(hostkey_algs
) - 1)
5568 ssh2_pkt_addstring_str(s
->pktout
, ",");
5570 /* List client->server encryption algorithms. */
5571 ssh2_pkt_addstring_start(s
->pktout
);
5572 commalist_started
= 0;
5573 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5574 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5575 if (!c
) continue; /* warning flag */
5576 for (j
= 0; j
< c
->nciphers
; j
++) {
5577 if (commalist_started
)
5578 ssh2_pkt_addstring_str(s
->pktout
, ",");
5579 ssh2_pkt_addstring_str(s
->pktout
, c
->list
[j
]->name
);
5580 commalist_started
= 1;
5583 /* List server->client encryption algorithms. */
5584 ssh2_pkt_addstring_start(s
->pktout
);
5585 commalist_started
= 0;
5586 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5587 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5588 if (!c
) continue; /* warning flag */
5589 for (j
= 0; j
< c
->nciphers
; j
++) {
5590 if (commalist_started
)
5591 ssh2_pkt_addstring_str(s
->pktout
, ",");
5592 ssh2_pkt_addstring_str(s
->pktout
, c
->list
[j
]->name
);
5593 commalist_started
= 1;
5596 /* List client->server MAC algorithms. */
5597 ssh2_pkt_addstring_start(s
->pktout
);
5598 for (i
= 0; i
< s
->nmacs
; i
++) {
5599 ssh2_pkt_addstring_str(s
->pktout
, s
->maclist
[i
]->name
);
5600 if (i
< s
->nmacs
- 1)
5601 ssh2_pkt_addstring_str(s
->pktout
, ",");
5603 /* List server->client MAC algorithms. */
5604 ssh2_pkt_addstring_start(s
->pktout
);
5605 for (i
= 0; i
< s
->nmacs
; i
++) {
5606 ssh2_pkt_addstring_str(s
->pktout
, s
->maclist
[i
]->name
);
5607 if (i
< s
->nmacs
- 1)
5608 ssh2_pkt_addstring_str(s
->pktout
, ",");
5610 /* List client->server compression algorithms,
5611 * then server->client compression algorithms. (We use the
5612 * same set twice.) */
5613 for (j
= 0; j
< 2; j
++) {
5614 ssh2_pkt_addstring_start(s
->pktout
);
5615 assert(lenof(compressions
) > 1);
5616 /* Prefer non-delayed versions */
5617 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_comp
->name
);
5618 /* We don't even list delayed versions of algorithms until
5619 * they're allowed to be used, to avoid a race. See the end of
5621 if (s
->userauth_succeeded
&& s
->preferred_comp
->delayed_name
) {
5622 ssh2_pkt_addstring_str(s
->pktout
, ",");
5623 ssh2_pkt_addstring_str(s
->pktout
,
5624 s
->preferred_comp
->delayed_name
);
5626 for (i
= 0; i
< lenof(compressions
); i
++) {
5627 const struct ssh_compress
*c
= compressions
[i
];
5628 if (c
!= s
->preferred_comp
) {
5629 ssh2_pkt_addstring_str(s
->pktout
, ",");
5630 ssh2_pkt_addstring_str(s
->pktout
, c
->name
);
5631 if (s
->userauth_succeeded
&& c
->delayed_name
) {
5632 ssh2_pkt_addstring_str(s
->pktout
, ",");
5633 ssh2_pkt_addstring_str(s
->pktout
, c
->delayed_name
);
5638 /* List client->server languages. Empty list. */
5639 ssh2_pkt_addstring_start(s
->pktout
);
5640 /* List server->client languages. Empty list. */
5641 ssh2_pkt_addstring_start(s
->pktout
);
5642 /* First KEX packet does _not_ follow, because we're not that brave. */
5643 ssh2_pkt_addbool(s
->pktout
, FALSE
);
5645 ssh2_pkt_adduint32(s
->pktout
, 0);
5648 s
->our_kexinitlen
= s
->pktout
->length
- 5;
5649 s
->our_kexinit
= snewn(s
->our_kexinitlen
, unsigned char);
5650 memcpy(s
->our_kexinit
, s
->pktout
->data
+ 5, s
->our_kexinitlen
);
5652 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5658 * Now examine the other side's KEXINIT to see what we're up
5662 char *str
, *preferred
;
5665 if (pktin
->type
!= SSH2_MSG_KEXINIT
) {
5666 bombout(("expected key exchange packet from server"));
5670 ssh
->hostkey
= NULL
;
5671 s
->cscipher_tobe
= NULL
;
5672 s
->sccipher_tobe
= NULL
;
5673 s
->csmac_tobe
= NULL
;
5674 s
->scmac_tobe
= NULL
;
5675 s
->cscomp_tobe
= NULL
;
5676 s
->sccomp_tobe
= NULL
;
5677 s
->warn_kex
= s
->warn_cscipher
= s
->warn_sccipher
= FALSE
;
5679 pktin
->savedpos
+= 16; /* skip garbage cookie */
5680 ssh_pkt_getstring(pktin
, &str
, &len
); /* key exchange algorithms */
5683 for (i
= 0; i
< s
->n_preferred_kex
; i
++) {
5684 const struct ssh_kexes
*k
= s
->preferred_kex
[i
];
5688 for (j
= 0; j
< k
->nkexes
; j
++) {
5689 if (!preferred
) preferred
= k
->list
[j
]->name
;
5690 if (in_commasep_string(k
->list
[j
]->name
, str
, len
)) {
5691 ssh
->kex
= k
->list
[j
];
5700 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5701 str ? str
: "(null)"));
5705 * Note that the server's guess is considered wrong if it doesn't match
5706 * the first algorithm in our list, even if it's still the algorithm
5709 s
->guessok
= first_in_commasep_string(preferred
, str
, len
);
5710 ssh_pkt_getstring(pktin
, &str
, &len
); /* host key algorithms */
5711 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
5712 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
5713 ssh
->hostkey
= hostkey_algs
[i
];
5717 s
->guessok
= s
->guessok
&&
5718 first_in_commasep_string(hostkey_algs
[0]->name
, str
, len
);
5719 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server cipher */
5720 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5721 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5723 s
->warn_cscipher
= TRUE
;
5725 for (j
= 0; j
< c
->nciphers
; j
++) {
5726 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
5727 s
->cscipher_tobe
= c
->list
[j
];
5732 if (s
->cscipher_tobe
)
5735 if (!s
->cscipher_tobe
) {
5736 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5737 str ? str
: "(null)"));
5741 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client cipher */
5742 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5743 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5745 s
->warn_sccipher
= TRUE
;
5747 for (j
= 0; j
< c
->nciphers
; j
++) {
5748 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
5749 s
->sccipher_tobe
= c
->list
[j
];
5754 if (s
->sccipher_tobe
)
5757 if (!s
->sccipher_tobe
) {
5758 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5759 str ? str
: "(null)"));
5763 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server mac */
5764 for (i
= 0; i
< s
->nmacs
; i
++) {
5765 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
5766 s
->csmac_tobe
= s
->maclist
[i
];
5770 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client mac */
5771 for (i
= 0; i
< s
->nmacs
; i
++) {
5772 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
5773 s
->scmac_tobe
= s
->maclist
[i
];
5777 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server compression */
5778 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
5779 const struct ssh_compress
*c
=
5780 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
5781 if (in_commasep_string(c
->name
, str
, len
)) {
5784 } else if (in_commasep_string(c
->delayed_name
, str
, len
)) {
5785 if (s
->userauth_succeeded
) {
5789 s
->pending_compression
= TRUE
; /* try this later */
5793 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client compression */
5794 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
5795 const struct ssh_compress
*c
=
5796 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
5797 if (in_commasep_string(c
->name
, str
, len
)) {
5800 } else if (in_commasep_string(c
->delayed_name
, str
, len
)) {
5801 if (s
->userauth_succeeded
) {
5805 s
->pending_compression
= TRUE
; /* try this later */
5809 if (s
->pending_compression
) {
5810 logevent("Server supports delayed compression; "
5811 "will try this later");
5813 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server language */
5814 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client language */
5815 s
->ignorepkt
= ssh2_pkt_getbool(pktin
) && !s
->guessok
;
5818 ssh_set_frozen(ssh
, 1);
5819 s
->dlgret
= askalg(ssh
->frontend
, "key-exchange algorithm",
5821 ssh_dialog_callback
, ssh
);
5822 if (s
->dlgret
< 0) {
5826 bombout(("Unexpected data from server while"
5827 " waiting for user response"));
5830 } while (pktin
|| inlen
> 0);
5831 s
->dlgret
= ssh
->user_response
;
5833 ssh_set_frozen(ssh
, 0);
5834 if (s
->dlgret
== 0) {
5835 ssh_disconnect(ssh
, "User aborted at kex warning", NULL
,
5841 if (s
->warn_cscipher
) {
5842 ssh_set_frozen(ssh
, 1);
5843 s
->dlgret
= askalg(ssh
->frontend
,
5844 "client-to-server cipher",
5845 s
->cscipher_tobe
->name
,
5846 ssh_dialog_callback
, ssh
);
5847 if (s
->dlgret
< 0) {
5851 bombout(("Unexpected data from server while"
5852 " waiting for user response"));
5855 } while (pktin
|| inlen
> 0);
5856 s
->dlgret
= ssh
->user_response
;
5858 ssh_set_frozen(ssh
, 0);
5859 if (s
->dlgret
== 0) {
5860 ssh_disconnect(ssh
, "User aborted at cipher warning", NULL
,
5866 if (s
->warn_sccipher
) {
5867 ssh_set_frozen(ssh
, 1);
5868 s
->dlgret
= askalg(ssh
->frontend
,
5869 "server-to-client cipher",
5870 s
->sccipher_tobe
->name
,
5871 ssh_dialog_callback
, ssh
);
5872 if (s
->dlgret
< 0) {
5876 bombout(("Unexpected data from server while"
5877 " waiting for user response"));
5880 } while (pktin
|| inlen
> 0);
5881 s
->dlgret
= ssh
->user_response
;
5883 ssh_set_frozen(ssh
, 0);
5884 if (s
->dlgret
== 0) {
5885 ssh_disconnect(ssh
, "User aborted at cipher warning", NULL
,
5891 ssh
->exhash
= ssh
->kex
->hash
->init();
5892 hash_string(ssh
->kex
->hash
, ssh
->exhash
, ssh
->v_c
, strlen(ssh
->v_c
));
5893 hash_string(ssh
->kex
->hash
, ssh
->exhash
, ssh
->v_s
, strlen(ssh
->v_s
));
5894 hash_string(ssh
->kex
->hash
, ssh
->exhash
,
5895 s
->our_kexinit
, s
->our_kexinitlen
);
5896 sfree(s
->our_kexinit
);
5897 if (pktin
->length
> 5)
5898 hash_string(ssh
->kex
->hash
, ssh
->exhash
,
5899 pktin
->data
+ 5, pktin
->length
- 5);
5901 if (s
->ignorepkt
) /* first_kex_packet_follows */
5902 crWaitUntil(pktin
); /* Ignore packet */
5905 if (ssh
->kex
->main_type
== KEXTYPE_DH
) {
5907 * Work out the number of bits of key we will need from the
5908 * key exchange. We start with the maximum key length of
5914 csbits
= s
->cscipher_tobe
->keylen
;
5915 scbits
= s
->sccipher_tobe
->keylen
;
5916 s
->nbits
= (csbits
> scbits ? csbits
: scbits
);
5918 /* The keys only have hlen-bit entropy, since they're based on
5919 * a hash. So cap the key size at hlen bits. */
5920 if (s
->nbits
> ssh
->kex
->hash
->hlen
* 8)
5921 s
->nbits
= ssh
->kex
->hash
->hlen
* 8;
5924 * If we're doing Diffie-Hellman group exchange, start by
5925 * requesting a group.
5927 if (!ssh
->kex
->pdata
) {
5928 logevent("Doing Diffie-Hellman group exchange");
5929 ssh
->pkt_kctx
= SSH2_PKTCTX_DHGEX
;
5931 * Work out how big a DH group we will need to allow that
5934 s
->pbits
= 512 << ((s
->nbits
- 1) / 64);
5935 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
5936 ssh2_pkt_adduint32(s
->pktout
, s
->pbits
);
5937 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5940 if (pktin
->type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
5941 bombout(("expected key exchange group packet from server"));
5944 s
->p
= ssh2_pkt_getmp(pktin
);
5945 s
->g
= ssh2_pkt_getmp(pktin
);
5946 if (!s
->p
|| !s
->g
) {
5947 bombout(("unable to read mp-ints from incoming group packet"));
5950 ssh
->kex_ctx
= dh_setup_gex(s
->p
, s
->g
);
5951 s
->kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
5952 s
->kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
5954 ssh
->pkt_kctx
= SSH2_PKTCTX_DHGROUP
;
5955 ssh
->kex_ctx
= dh_setup_group(ssh
->kex
);
5956 s
->kex_init_value
= SSH2_MSG_KEXDH_INIT
;
5957 s
->kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
5958 logeventf(ssh
, "Using Diffie-Hellman with standard group \"%s\"",
5959 ssh
->kex
->groupname
);
5962 logeventf(ssh
, "Doing Diffie-Hellman key exchange with hash %s",
5963 ssh
->kex
->hash
->text_name
);
5965 * Now generate and send e for Diffie-Hellman.
5967 set_busy_status(ssh
->frontend
, BUSY_CPU
); /* this can take a while */
5968 s
->e
= dh_create_e(ssh
->kex_ctx
, s
->nbits
* 2);
5969 s
->pktout
= ssh2_pkt_init(s
->kex_init_value
);
5970 ssh2_pkt_addmp(s
->pktout
, s
->e
);
5971 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5973 set_busy_status(ssh
->frontend
, BUSY_WAITING
); /* wait for server */
5975 if (pktin
->type
!= s
->kex_reply_value
) {
5976 bombout(("expected key exchange reply packet from server"));
5979 set_busy_status(ssh
->frontend
, BUSY_CPU
); /* cogitate */
5980 ssh_pkt_getstring(pktin
, &s
->hostkeydata
, &s
->hostkeylen
);
5981 s
->hkey
= ssh
->hostkey
->newkey(s
->hostkeydata
, s
->hostkeylen
);
5982 s
->f
= ssh2_pkt_getmp(pktin
);
5984 bombout(("unable to parse key exchange reply packet"));
5987 ssh_pkt_getstring(pktin
, &s
->sigdata
, &s
->siglen
);
5989 s
->K
= dh_find_K(ssh
->kex_ctx
, s
->f
);
5991 /* We assume everything from now on will be quick, and it might
5992 * involve user interaction. */
5993 set_busy_status(ssh
->frontend
, BUSY_NOT
);
5995 hash_string(ssh
->kex
->hash
, ssh
->exhash
, s
->hostkeydata
, s
->hostkeylen
);
5996 if (!ssh
->kex
->pdata
) {
5997 hash_uint32(ssh
->kex
->hash
, ssh
->exhash
, s
->pbits
);
5998 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->p
);
5999 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->g
);
6001 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->e
);
6002 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->f
);
6004 dh_cleanup(ssh
->kex_ctx
);
6006 if (!ssh
->kex
->pdata
) {
6011 logeventf(ssh
, "Doing RSA key exchange with hash %s",
6012 ssh
->kex
->hash
->text_name
);
6013 ssh
->pkt_kctx
= SSH2_PKTCTX_RSAKEX
;
6015 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6019 if (pktin
->type
!= SSH2_MSG_KEXRSA_PUBKEY
) {
6020 bombout(("expected RSA public key packet from server"));
6024 ssh_pkt_getstring(pktin
, &s
->hostkeydata
, &s
->hostkeylen
);
6025 hash_string(ssh
->kex
->hash
, ssh
->exhash
,
6026 s
->hostkeydata
, s
->hostkeylen
);
6027 s
->hkey
= ssh
->hostkey
->newkey(s
->hostkeydata
, s
->hostkeylen
);
6031 ssh_pkt_getstring(pktin
, &keydata
, &s
->rsakeylen
);
6032 s
->rsakeydata
= snewn(s
->rsakeylen
, char);
6033 memcpy(s
->rsakeydata
, keydata
, s
->rsakeylen
);
6036 s
->rsakey
= ssh_rsakex_newkey(s
->rsakeydata
, s
->rsakeylen
);
6038 sfree(s
->rsakeydata
);
6039 bombout(("unable to parse RSA public key from server"));
6043 hash_string(ssh
->kex
->hash
, ssh
->exhash
, s
->rsakeydata
, s
->rsakeylen
);
6046 * Next, set up a shared secret K, of precisely KLEN -
6047 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6048 * RSA key modulus and HLEN is the bit length of the hash
6052 int klen
= ssh_rsakex_klen(s
->rsakey
);
6053 int nbits
= klen
- (2*ssh
->kex
->hash
->hlen
*8 + 49);
6055 unsigned char *kstr1
, *kstr2
, *outstr
;
6056 int kstr1len
, kstr2len
, outstrlen
;
6058 s
->K
= bn_power_2(nbits
- 1);
6060 for (i
= 0; i
< nbits
; i
++) {
6062 byte
= random_byte();
6064 bignum_set_bit(s
->K
, i
, (byte
>> (i
& 7)) & 1);
6068 * Encode this as an mpint.
6070 kstr1
= ssh2_mpint_fmt(s
->K
, &kstr1len
);
6071 kstr2
= snewn(kstr2len
= 4 + kstr1len
, unsigned char);
6072 PUT_32BIT(kstr2
, kstr1len
);
6073 memcpy(kstr2
+ 4, kstr1
, kstr1len
);
6076 * Encrypt it with the given RSA key.
6078 outstrlen
= (klen
+ 7) / 8;
6079 outstr
= snewn(outstrlen
, unsigned char);
6080 ssh_rsakex_encrypt(ssh
->kex
->hash
, kstr2
, kstr2len
,
6081 outstr
, outstrlen
, s
->rsakey
);
6084 * And send it off in a return packet.
6086 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET
);
6087 ssh2_pkt_addstring_start(s
->pktout
);
6088 ssh2_pkt_addstring_data(s
->pktout
, (char *)outstr
, outstrlen
);
6089 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
6091 hash_string(ssh
->kex
->hash
, ssh
->exhash
, outstr
, outstrlen
);
6098 ssh_rsakex_freekey(s
->rsakey
);
6101 if (pktin
->type
!= SSH2_MSG_KEXRSA_DONE
) {
6102 sfree(s
->rsakeydata
);
6103 bombout(("expected signature packet from server"));
6107 ssh_pkt_getstring(pktin
, &s
->sigdata
, &s
->siglen
);
6109 sfree(s
->rsakeydata
);
6112 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->K
);
6113 assert(ssh
->kex
->hash
->hlen
<= sizeof(s
->exchange_hash
));
6114 ssh
->kex
->hash
->final(ssh
->exhash
, s
->exchange_hash
);
6116 ssh
->kex_ctx
= NULL
;
6119 debug(("Exchange hash is:\n"));
6120 dmemdump(s
->exchange_hash
, ssh
->kex
->hash
->hlen
);
6124 !ssh
->hostkey
->verifysig(s
->hkey
, s
->sigdata
, s
->siglen
,
6125 (char *)s
->exchange_hash
,
6126 ssh
->kex
->hash
->hlen
)) {
6127 bombout(("Server's host key did not match the signature supplied"));
6132 * Authenticate remote host: verify host key. (We've already
6133 * checked the signature of the exchange hash.)
6135 s
->keystr
= ssh
->hostkey
->fmtkey(s
->hkey
);
6136 s
->fingerprint
= ssh
->hostkey
->fingerprint(s
->hkey
);
6137 ssh_set_frozen(ssh
, 1);
6138 s
->dlgret
= verify_ssh_host_key(ssh
->frontend
,
6139 ssh
->savedhost
, ssh
->savedport
,
6140 ssh
->hostkey
->keytype
, s
->keystr
,
6142 ssh_dialog_callback
, ssh
);
6143 if (s
->dlgret
< 0) {
6147 bombout(("Unexpected data from server while waiting"
6148 " for user host key response"));
6151 } while (pktin
|| inlen
> 0);
6152 s
->dlgret
= ssh
->user_response
;
6154 ssh_set_frozen(ssh
, 0);
6155 if (s
->dlgret
== 0) {
6156 ssh_disconnect(ssh
, "User aborted at host key verification", NULL
,
6160 if (!s
->got_session_id
) { /* don't bother logging this in rekeys */
6161 logevent("Host key fingerprint is:");
6162 logevent(s
->fingerprint
);
6164 sfree(s
->fingerprint
);
6166 ssh
->hostkey
->freekey(s
->hkey
);
6169 * The exchange hash from the very first key exchange is also
6170 * the session id, used in session key construction and
6173 if (!s
->got_session_id
) {
6174 assert(sizeof(s
->exchange_hash
) <= sizeof(ssh
->v2_session_id
));
6175 memcpy(ssh
->v2_session_id
, s
->exchange_hash
,
6176 sizeof(s
->exchange_hash
));
6177 ssh
->v2_session_id_len
= ssh
->kex
->hash
->hlen
;
6178 assert(ssh
->v2_session_id_len
<= sizeof(ssh
->v2_session_id
));
6179 s
->got_session_id
= TRUE
;
6183 * Send SSH2_MSG_NEWKEYS.
6185 s
->pktout
= ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
6186 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
6187 ssh
->outgoing_data_size
= 0; /* start counting from here */
6190 * We've sent client NEWKEYS, so create and initialise
6191 * client-to-server session keys.
6193 if (ssh
->cs_cipher_ctx
)
6194 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
6195 ssh
->cscipher
= s
->cscipher_tobe
;
6196 ssh
->cs_cipher_ctx
= ssh
->cscipher
->make_context();
6198 if (ssh
->cs_mac_ctx
)
6199 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
6200 ssh
->csmac
= s
->csmac_tobe
;
6201 ssh
->cs_mac_ctx
= ssh
->csmac
->make_context();
6203 if (ssh
->cs_comp_ctx
)
6204 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
6205 ssh
->cscomp
= s
->cscomp_tobe
;
6206 ssh
->cs_comp_ctx
= ssh
->cscomp
->compress_init();
6209 * Set IVs on client-to-server keys. Here we use the exchange
6210 * hash from the _first_ key exchange.
6213 unsigned char keyspace
[SSH2_KEX_MAX_HASH_LEN
* SSH2_MKKEY_ITERS
];
6214 assert(sizeof(keyspace
) >= ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6215 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'C',keyspace
);
6216 assert((ssh
->cscipher
->keylen
+7) / 8 <=
6217 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6218 ssh
->cscipher
->setkey(ssh
->cs_cipher_ctx
, keyspace
);
6219 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'A',keyspace
);
6220 assert(ssh
->cscipher
->blksize
<=
6221 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6222 ssh
->cscipher
->setiv(ssh
->cs_cipher_ctx
, keyspace
);
6223 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'E',keyspace
);
6224 assert(ssh
->csmac
->len
<=
6225 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6226 ssh
->csmac
->setkey(ssh
->cs_mac_ctx
, keyspace
);
6227 memset(keyspace
, 0, sizeof(keyspace
));
6230 logeventf(ssh
, "Initialised %.200s client->server encryption",
6231 ssh
->cscipher
->text_name
);
6232 logeventf(ssh
, "Initialised %.200s client->server MAC algorithm",
6233 ssh
->csmac
->text_name
);
6234 if (ssh
->cscomp
->text_name
)
6235 logeventf(ssh
, "Initialised %s compression",
6236 ssh
->cscomp
->text_name
);
6239 * Now our end of the key exchange is complete, we can send all
6240 * our queued higher-layer packets.
6242 ssh
->queueing
= FALSE
;
6243 ssh2_pkt_queuesend(ssh
);
6246 * Expect SSH2_MSG_NEWKEYS from server.
6249 if (pktin
->type
!= SSH2_MSG_NEWKEYS
) {
6250 bombout(("expected new-keys packet from server"));
6253 ssh
->incoming_data_size
= 0; /* start counting from here */
6256 * We've seen server NEWKEYS, so create and initialise
6257 * server-to-client session keys.
6259 if (ssh
->sc_cipher_ctx
)
6260 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
6261 ssh
->sccipher
= s
->sccipher_tobe
;
6262 ssh
->sc_cipher_ctx
= ssh
->sccipher
->make_context();
6264 if (ssh
->sc_mac_ctx
)
6265 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
6266 ssh
->scmac
= s
->scmac_tobe
;
6267 ssh
->sc_mac_ctx
= ssh
->scmac
->make_context();
6269 if (ssh
->sc_comp_ctx
)
6270 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
6271 ssh
->sccomp
= s
->sccomp_tobe
;
6272 ssh
->sc_comp_ctx
= ssh
->sccomp
->decompress_init();
6275 * Set IVs on server-to-client keys. Here we use the exchange
6276 * hash from the _first_ key exchange.
6279 unsigned char keyspace
[SSH2_KEX_MAX_HASH_LEN
* SSH2_MKKEY_ITERS
];
6280 assert(sizeof(keyspace
) >= ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6281 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'D',keyspace
);
6282 assert((ssh
->sccipher
->keylen
+7) / 8 <=
6283 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6284 ssh
->sccipher
->setkey(ssh
->sc_cipher_ctx
, keyspace
);
6285 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'B',keyspace
);
6286 assert(ssh
->sccipher
->blksize
<=
6287 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6288 ssh
->sccipher
->setiv(ssh
->sc_cipher_ctx
, keyspace
);
6289 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'F',keyspace
);
6290 assert(ssh
->scmac
->len
<=
6291 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6292 ssh
->scmac
->setkey(ssh
->sc_mac_ctx
, keyspace
);
6293 memset(keyspace
, 0, sizeof(keyspace
));
6295 logeventf(ssh
, "Initialised %.200s server->client encryption",
6296 ssh
->sccipher
->text_name
);
6297 logeventf(ssh
, "Initialised %.200s server->client MAC algorithm",
6298 ssh
->scmac
->text_name
);
6299 if (ssh
->sccomp
->text_name
)
6300 logeventf(ssh
, "Initialised %s decompression",
6301 ssh
->sccomp
->text_name
);
6304 * Free shared secret.
6309 * Key exchange is over. Loop straight back round if we have a
6310 * deferred rekey reason.
6312 if (ssh
->deferred_rekey_reason
) {
6313 logevent(ssh
->deferred_rekey_reason
);
6315 ssh
->deferred_rekey_reason
= NULL
;
6316 goto begin_key_exchange
;
6320 * Otherwise, schedule a timer for our next rekey.
6322 ssh
->kex_in_progress
= FALSE
;
6323 ssh
->last_rekey
= GETTICKCOUNT();
6324 if (ssh
->cfg
.ssh_rekey_time
!= 0)
6325 ssh
->next_rekey
= schedule_timer(ssh
->cfg
.ssh_rekey_time
*60*TICKSPERSEC
,
6329 * If this is the first key exchange phase, we must pass the
6330 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
6331 * wants to see it but because it will need time to initialise
6332 * itself before it sees an actual packet. In subsequent key
6333 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
6334 * it would only confuse the layer above.
6336 if (s
->activated_authconn
) {
6339 s
->activated_authconn
= TRUE
;
6342 * Now we're encrypting. Begin returning 1 to the protocol main
6343 * function so that other things can run on top of the
6344 * transport. If we ever see a KEXINIT, we must go back to the
6347 * We _also_ go back to the start if we see pktin==NULL and
6348 * inlen negative, because this is a special signal meaning
6349 * `initiate client-driven rekey', and `in' contains a message
6350 * giving the reason for the rekey.
6352 * inlen==-1 means always initiate a rekey;
6353 * inlen==-2 means that userauth has completed successfully and
6354 * we should consider rekeying (for delayed compression).
6356 while (!((pktin
&& pktin
->type
== SSH2_MSG_KEXINIT
) ||
6357 (!pktin
&& inlen
< 0))) {
6362 logevent("Server initiated key re-exchange");
6366 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6367 * delayed compression, if it's available.
6369 * draft-miller-secsh-compression-delayed-00 says that you
6370 * negotiate delayed compression in the first key exchange, and
6371 * both sides start compressing when the server has sent
6372 * USERAUTH_SUCCESS. This has a race condition -- the server
6373 * can't know when the client has seen it, and thus which incoming
6374 * packets it should treat as compressed.
6376 * Instead, we do the initial key exchange without offering the
6377 * delayed methods, but note if the server offers them; when we
6378 * get here, if a delayed method was available that was higher
6379 * on our list than what we got, we initiate a rekey in which we
6380 * _do_ list the delayed methods (and hopefully get it as a
6381 * result). Subsequent rekeys will do the same.
6383 assert(!s
->userauth_succeeded
); /* should only happen once */
6384 s
->userauth_succeeded
= TRUE
;
6385 if (!s
->pending_compression
)
6386 /* Can't see any point rekeying. */
6387 goto wait_for_rekey
; /* this is utterly horrid */
6388 /* else fall through to rekey... */
6389 s
->pending_compression
= FALSE
;
6392 * Now we've decided to rekey.
6394 * Special case: if the server bug is set that doesn't
6395 * allow rekeying, we give a different log message and
6396 * continue waiting. (If such a server _initiates_ a rekey,
6397 * we process it anyway!)
6399 if ((ssh
->remote_bugs
& BUG_SSH2_REKEY
)) {
6400 logeventf(ssh
, "Server bug prevents key re-exchange (%s)",
6402 /* Reset the counters, so that at least this message doesn't
6403 * hit the event log _too_ often. */
6404 ssh
->outgoing_data_size
= 0;
6405 ssh
->incoming_data_size
= 0;
6406 if (ssh
->cfg
.ssh_rekey_time
!= 0) {
6408 schedule_timer(ssh
->cfg
.ssh_rekey_time
*60*TICKSPERSEC
,
6411 goto wait_for_rekey
; /* this is still utterly horrid */
6413 logeventf(ssh
, "Initiating key re-exchange (%s)", (char *)in
);
6416 goto begin_key_exchange
;
6422 * Add data to an SSH-2 channel output buffer.
6424 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
6427 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
6431 * Attempt to send data on an SSH-2 channel.
6433 static int ssh2_try_send(struct ssh_channel
*c
)
6436 struct Packet
*pktout
;
6438 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
6441 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
6442 if ((unsigned)len
> c
->v
.v2
.remwindow
)
6443 len
= c
->v
.v2
.remwindow
;
6444 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
6445 len
= c
->v
.v2
.remmaxpkt
;
6446 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
6447 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6448 ssh2_pkt_addstring_start(pktout
);
6449 dont_log_data(ssh
, pktout
, PKTLOG_OMIT
);
6450 ssh2_pkt_addstring_data(pktout
, data
, len
);
6451 end_log_omission(ssh
, pktout
);
6452 ssh2_pkt_send(ssh
, pktout
);
6453 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
6454 c
->v
.v2
.remwindow
-= len
;
6458 * After having sent as much data as we can, return the amount
6461 return bufchain_size(&c
->v
.v2
.outbuffer
);
6464 static void ssh2_try_send_and_unthrottle(Ssh ssh
, struct ssh_channel
*c
)
6468 return; /* don't send on closing channels */
6469 bufsize
= ssh2_try_send(c
);
6472 case CHAN_MAINSESSION
:
6473 /* stdin need not receive an unthrottle
6474 * notification since it will be polled */
6477 x11_unthrottle(c
->u
.x11
.s
);
6480 /* agent sockets are request/response and need no
6481 * buffer management */
6484 pfd_unthrottle(c
->u
.pfd
.s
);
6490 * If we've emptied the channel's output buffer and there's a
6491 * pending close event, start the channel-closing procedure.
6493 if (c
->pending_close
&& bufchain_size(&c
->v
.v2
.outbuffer
) == 0) {
6494 struct Packet
*pktout
;
6495 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
6496 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6497 ssh2_pkt_send(ssh
, pktout
);
6499 c
->pending_close
= FALSE
;
6504 * Set up most of a new ssh_channel for SSH-2.
6506 static void ssh2_channel_init(struct ssh_channel
*c
)
6509 c
->localid
= alloc_channel_id(ssh
);
6511 c
->pending_close
= FALSE
;
6512 c
->throttling_conn
= FALSE
;
6513 c
->v
.v2
.locwindow
= c
->v
.v2
.locmaxwin
= c
->v
.v2
.remlocwin
=
6514 ssh
->cfg
.ssh_simple ? OUR_V2_BIGWIN
: OUR_V2_WINSIZE
;
6515 c
->v
.v2
.winadj_head
= c
->v
.v2
.winadj_tail
= NULL
;
6516 c
->v
.v2
.throttle_state
= UNTHROTTLED
;
6517 bufchain_init(&c
->v
.v2
.outbuffer
);
6521 * Potentially enlarge the window on an SSH-2 channel.
6523 static void ssh2_set_window(struct ssh_channel
*c
, int newwin
)
6528 * Never send WINDOW_ADJUST for a channel that the remote side
6529 * already thinks it's closed; there's no point, since it won't
6530 * be sending any more data anyway.
6536 * If the remote end has a habit of ignoring maxpkt, limit the
6537 * window so that it has no choice (assuming it doesn't ignore the
6540 if ((ssh
->remote_bugs
& BUG_SSH2_MAXPKT
) && newwin
> OUR_V2_MAXPKT
)
6541 newwin
= OUR_V2_MAXPKT
;
6545 * Only send a WINDOW_ADJUST if there's significantly more window
6546 * available than the other end thinks there is. This saves us
6547 * sending a WINDOW_ADJUST for every character in a shell session.
6549 * "Significant" is arbitrarily defined as half the window size.
6551 if (newwin
/ 2 >= c
->v
.v2
.locwindow
) {
6552 struct Packet
*pktout
;
6556 * In order to keep track of how much window the client
6557 * actually has available, we'd like it to acknowledge each
6558 * WINDOW_ADJUST. We can't do that directly, so we accompany
6559 * it with a CHANNEL_REQUEST that has to be acknowledged.
6561 * This is only necessary if we're opening the window wide.
6562 * If we're not, then throughput is being constrained by
6563 * something other than the maximum window size anyway.
6565 * We also only send this if the main channel has finished its
6566 * initial CHANNEL_REQUESTs and installed the default
6567 * CHANNEL_FAILURE handler, so as not to risk giving it
6568 * unexpected CHANNEL_FAILUREs.
6570 if (newwin
== c
->v
.v2
.locmaxwin
&&
6571 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_FAILURE
]) {
6572 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
6573 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6574 ssh2_pkt_addstring(pktout
, "winadj@putty.projects.tartarus.org");
6575 ssh2_pkt_addbool(pktout
, TRUE
);
6576 ssh2_pkt_send(ssh
, pktout
);
6579 * CHANNEL_FAILURE doesn't come with any indication of
6580 * what message caused it, so we have to keep track of the
6581 * outstanding CHANNEL_REQUESTs ourselves.
6583 wa
= snew(struct winadj
);
6584 wa
->size
= newwin
- c
->v
.v2
.locwindow
;
6586 if (!c
->v
.v2
.winadj_head
)
6587 c
->v
.v2
.winadj_head
= wa
;
6589 c
->v
.v2
.winadj_tail
->next
= wa
;
6590 c
->v
.v2
.winadj_tail
= wa
;
6591 if (c
->v
.v2
.throttle_state
!= UNTHROTTLED
)
6592 c
->v
.v2
.throttle_state
= UNTHROTTLING
;
6594 /* Pretend the WINDOW_ADJUST was acked immediately. */
6595 c
->v
.v2
.remlocwin
= newwin
;
6596 c
->v
.v2
.throttle_state
= THROTTLED
;
6598 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
6599 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6600 ssh2_pkt_adduint32(pktout
, newwin
- c
->v
.v2
.locwindow
);
6601 ssh2_pkt_send(ssh
, pktout
);
6602 c
->v
.v2
.locwindow
= newwin
;
6607 * Find the channel associated with a message. If there's no channel,
6608 * or it's not properly open, make a noise about it and return NULL.
6610 static struct ssh_channel
*ssh2_channel_msg(Ssh ssh
, struct Packet
*pktin
)
6612 unsigned localid
= ssh_pkt_getuint32(pktin
);
6613 struct ssh_channel
*c
;
6615 c
= find234(ssh
->channels
, &localid
, ssh_channelfind
);
6617 (c
->halfopen
&& pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
&&
6618 pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_FAILURE
)) {
6619 char *buf
= dupprintf("Received %s for %s channel %u",
6620 ssh2_pkt_type(ssh
->pkt_kctx
, ssh
->pkt_actx
,
6622 c ?
"half-open" : "nonexistent", localid
);
6623 ssh_disconnect(ssh
, NULL
, buf
, SSH2_DISCONNECT_PROTOCOL_ERROR
, FALSE
);
6630 static int ssh2_handle_winadj_response(struct ssh_channel
*c
)
6632 struct winadj
*wa
= c
->v
.v2
.winadj_head
;
6635 c
->v
.v2
.winadj_head
= wa
->next
;
6636 c
->v
.v2
.remlocwin
+= wa
->size
;
6639 * winadj messages are only sent when the window is fully open, so
6640 * if we get an ack of one, we know any pending unthrottle is
6643 if (c
->v
.v2
.throttle_state
== UNTHROTTLING
)
6644 c
->v
.v2
.throttle_state
= UNTHROTTLED
;
6648 static void ssh2_msg_channel_success(Ssh ssh
, struct Packet
*pktin
)
6651 * This should never get called. All channel requests are either
6652 * sent with want_reply false, are sent before this handler gets
6653 * installed, or are "winadj@putty" requests, which servers should
6654 * never respond to with success.
6656 * However, at least one server ("boks_sshd") is known to return
6657 * SUCCESS for channel requests it's never heard of, such as
6658 * "winadj@putty". Raised with foxt.com as bug 090916-090424, but
6659 * for the sake of a quiet life, we handle it just the same as the
6662 struct ssh_channel
*c
;
6664 c
= ssh2_channel_msg(ssh
, pktin
);
6667 if (!ssh2_handle_winadj_response(c
))
6668 ssh_disconnect(ssh
, NULL
,
6669 "Received unsolicited SSH_MSG_CHANNEL_SUCCESS",
6670 SSH2_DISCONNECT_PROTOCOL_ERROR
, FALSE
);
6673 static void ssh2_msg_channel_failure(Ssh ssh
, struct Packet
*pktin
)
6676 * The only time this should get called is for "winadj@putty"
6677 * messages sent above. All other channel requests are either
6678 * sent with want_reply false or are sent before this handler gets
6681 struct ssh_channel
*c
;
6683 c
= ssh2_channel_msg(ssh
, pktin
);
6686 if (!ssh2_handle_winadj_response(c
))
6687 ssh_disconnect(ssh
, NULL
,
6688 "Received unsolicited SSH_MSG_CHANNEL_FAILURE",
6689 SSH2_DISCONNECT_PROTOCOL_ERROR
, FALSE
);
6692 static void ssh2_msg_channel_window_adjust(Ssh ssh
, struct Packet
*pktin
)
6694 struct ssh_channel
*c
;
6695 c
= ssh2_channel_msg(ssh
, pktin
);
6699 c
->v
.v2
.remwindow
+= ssh_pkt_getuint32(pktin
);
6700 ssh2_try_send_and_unthrottle(ssh
, c
);
6704 static void ssh2_msg_channel_data(Ssh ssh
, struct Packet
*pktin
)
6708 struct ssh_channel
*c
;
6709 c
= ssh2_channel_msg(ssh
, pktin
);
6712 if (pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
6713 ssh_pkt_getuint32(pktin
) != SSH2_EXTENDED_DATA_STDERR
)
6714 return; /* extended but not stderr */
6715 ssh_pkt_getstring(pktin
, &data
, &length
);
6718 c
->v
.v2
.locwindow
-= length
;
6719 c
->v
.v2
.remlocwin
-= length
;
6721 case CHAN_MAINSESSION
:
6723 from_backend(ssh
->frontend
, pktin
->type
==
6724 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
6728 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
6731 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
6734 while (length
> 0) {
6735 if (c
->u
.a
.lensofar
< 4) {
6736 unsigned int l
= min(4 - c
->u
.a
.lensofar
,
6738 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
6742 c
->u
.a
.lensofar
+= l
;
6744 if (c
->u
.a
.lensofar
== 4) {
6746 4 + GET_32BIT(c
->u
.a
.msglen
);
6747 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
6749 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
6751 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
6753 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
6755 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
6759 c
->u
.a
.lensofar
+= l
;
6761 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
6764 if (agent_query(c
->u
.a
.message
,
6767 ssh_agentf_callback
, c
))
6768 ssh_agentf_callback(c
, reply
, replylen
);
6769 sfree(c
->u
.a
.message
);
6770 c
->u
.a
.lensofar
= 0;
6777 * If it looks like the remote end hit the end of its window,
6778 * and we didn't want it to do that, think about using a
6781 if (c
->v
.v2
.remlocwin
<= 0 && c
->v
.v2
.throttle_state
== UNTHROTTLED
&&
6782 c
->v
.v2
.locmaxwin
< 0x40000000)
6783 c
->v
.v2
.locmaxwin
+= OUR_V2_WINSIZE
;
6785 * If we are not buffering too much data,
6786 * enlarge the window again at the remote side.
6787 * If we are buffering too much, we may still
6788 * need to adjust the window if the server's
6791 ssh2_set_window(c
, bufsize
< c
->v
.v2
.locmaxwin ?
6792 c
->v
.v2
.locmaxwin
- bufsize
: 0);
6794 * If we're either buffering way too much data, or if we're
6795 * buffering anything at all and we're in "simple" mode,
6796 * throttle the whole channel.
6798 if ((bufsize
> c
->v
.v2
.locmaxwin
||
6799 (ssh
->cfg
.ssh_simple
&& bufsize
> 0)) &&
6800 !c
->throttling_conn
) {
6801 c
->throttling_conn
= 1;
6802 ssh_throttle_conn(ssh
, +1);
6807 static void ssh2_msg_channel_eof(Ssh ssh
, struct Packet
*pktin
)
6809 struct ssh_channel
*c
;
6811 c
= ssh2_channel_msg(ssh
, pktin
);
6815 if (c
->type
== CHAN_X11
) {
6817 * Remote EOF on an X11 channel means we should
6818 * wrap up and close the channel ourselves.
6820 x11_close(c
->u
.x11
.s
);
6823 } else if (c
->type
== CHAN_AGENT
) {
6825 } else if (c
->type
== CHAN_SOCKDATA
) {
6826 pfd_close(c
->u
.pfd
.s
);
6832 static void ssh2_msg_channel_close(Ssh ssh
, struct Packet
*pktin
)
6834 struct ssh_channel
*c
;
6835 struct Packet
*pktout
;
6837 c
= ssh2_channel_msg(ssh
, pktin
);
6840 /* Do pre-close processing on the channel. */
6842 case CHAN_MAINSESSION
:
6843 ssh
->mainchan
= NULL
;
6844 update_specials_menu(ssh
->frontend
);
6847 if (c
->u
.x11
.s
!= NULL
)
6848 x11_close(c
->u
.x11
.s
);
6855 if (c
->u
.pfd
.s
!= NULL
)
6856 pfd_close(c
->u
.pfd
.s
);
6860 if (c
->closes
== 0) {
6861 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
6862 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6863 ssh2_pkt_send(ssh
, pktout
);
6865 del234(ssh
->channels
, c
);
6866 bufchain_clear(&c
->v
.v2
.outbuffer
);
6870 * See if that was the last channel left open.
6871 * (This is only our termination condition if we're
6872 * not running in -N mode.)
6874 if (!ssh
->cfg
.ssh_no_shell
&& count234(ssh
->channels
) == 0) {
6876 * We used to send SSH_MSG_DISCONNECT here,
6877 * because I'd believed that _every_ conforming
6878 * SSH-2 connection had to end with a disconnect
6879 * being sent by at least one side; apparently
6880 * I was wrong and it's perfectly OK to
6881 * unceremoniously slam the connection shut
6882 * when you're done, and indeed OpenSSH feels
6883 * this is more polite than sending a
6884 * DISCONNECT. So now we don't.
6886 ssh_disconnect(ssh
, "All channels closed", NULL
, 0, TRUE
);
6890 static void ssh2_msg_channel_open_confirmation(Ssh ssh
, struct Packet
*pktin
)
6892 struct ssh_channel
*c
;
6893 struct Packet
*pktout
;
6895 c
= ssh2_channel_msg(ssh
, pktin
);
6898 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
6899 return; /* dunno why they're confirming this */
6900 c
->remoteid
= ssh_pkt_getuint32(pktin
);
6901 c
->halfopen
= FALSE
;
6902 c
->type
= CHAN_SOCKDATA
;
6903 c
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
6904 c
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
6906 pfd_confirm(c
->u
.pfd
.s
);
6909 * We have a pending close on this channel,
6910 * which we decided on before the server acked
6911 * the channel open. So now we know the
6912 * remoteid, we can close it again.
6914 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
6915 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6916 ssh2_pkt_send(ssh
, pktout
);
6920 static void ssh2_msg_channel_open_failure(Ssh ssh
, struct Packet
*pktin
)
6922 static const char *const reasons
[] = {
6923 "<unknown reason code>",
6924 "Administratively prohibited",
6926 "Unknown channel type",
6927 "Resource shortage",
6929 unsigned reason_code
;
6930 char *reason_string
;
6932 struct ssh_channel
*c
;
6933 c
= ssh2_channel_msg(ssh
, pktin
);
6936 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
6937 return; /* dunno why they're failing this */
6939 reason_code
= ssh_pkt_getuint32(pktin
);
6940 if (reason_code
>= lenof(reasons
))
6941 reason_code
= 0; /* ensure reasons[reason_code] in range */
6942 ssh_pkt_getstring(pktin
, &reason_string
, &reason_length
);
6943 logeventf(ssh
, "Forwarded connection refused by server: %s [%.*s]",
6944 reasons
[reason_code
], reason_length
, reason_string
);
6946 pfd_close(c
->u
.pfd
.s
);
6948 del234(ssh
->channels
, c
);
6952 static void ssh2_msg_channel_request(Ssh ssh
, struct Packet
*pktin
)
6955 int typelen
, want_reply
;
6956 int reply
= SSH2_MSG_CHANNEL_FAILURE
; /* default */
6957 struct ssh_channel
*c
;
6958 struct Packet
*pktout
;
6960 c
= ssh2_channel_msg(ssh
, pktin
);
6963 ssh_pkt_getstring(pktin
, &type
, &typelen
);
6964 want_reply
= ssh2_pkt_getbool(pktin
);
6967 * Having got the channel number, we now look at
6968 * the request type string to see if it's something
6971 if (c
== ssh
->mainchan
) {
6973 * We recognise "exit-status" and "exit-signal" on
6974 * the primary channel.
6976 if (typelen
== 11 &&
6977 !memcmp(type
, "exit-status", 11)) {
6979 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
6980 logeventf(ssh
, "Server sent command exit status %d",
6982 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
6984 } else if (typelen
== 11 &&
6985 !memcmp(type
, "exit-signal", 11)) {
6987 int is_plausible
= TRUE
, is_int
= FALSE
;
6988 char *fmt_sig
= "", *fmt_msg
= "";
6990 int msglen
= 0, core
= FALSE
;
6991 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
6992 * provide an `int' for the signal, despite its
6993 * having been a `string' in the drafts of RFC 4254 since at
6994 * least 2001. (Fixed in session.c 1.147.) Try to
6995 * infer which we can safely parse it as. */
6997 unsigned char *p
= pktin
->body
+
6999 long len
= pktin
->length
- pktin
->savedpos
;
7000 unsigned long num
= GET_32BIT(p
); /* what is it? */
7001 /* If it's 0, it hardly matters; assume string */
7005 int maybe_int
= FALSE
, maybe_str
= FALSE
;
7006 #define CHECK_HYPOTHESIS(offset, result) \
7009 if (q >= 0 && q+4 <= len) { \
7010 q = q + 4 + GET_32BIT(p+q); \
7011 if (q >= 0 && q+4 <= len && \
7012 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
7016 CHECK_HYPOTHESIS(4+1, maybe_int
);
7017 CHECK_HYPOTHESIS(4+num
+1, maybe_str
);
7018 #undef CHECK_HYPOTHESIS
7019 if (maybe_int
&& !maybe_str
)
7021 else if (!maybe_int
&& maybe_str
)
7024 /* Crikey. Either or neither. Panic. */
7025 is_plausible
= FALSE
;
7028 ssh
->exitcode
= 128; /* means `unknown signal' */
7031 /* Old non-standard OpenSSH. */
7032 int signum
= ssh_pkt_getuint32(pktin
);
7033 fmt_sig
= dupprintf(" %d", signum
);
7034 ssh
->exitcode
= 128 + signum
;
7036 /* As per RFC 4254. */
7039 ssh_pkt_getstring(pktin
, &sig
, &siglen
);
7040 /* Signal name isn't supposed to be blank, but
7041 * let's cope gracefully if it is. */
7043 fmt_sig
= dupprintf(" \"%.*s\"",
7048 * Really hideous method of translating the
7049 * signal description back into a locally
7050 * meaningful number.
7055 #define TRANSLATE_SIGNAL(s) \
7056 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7057 ssh->exitcode = 128 + SIG ## s
7059 TRANSLATE_SIGNAL(ABRT
);
7062 TRANSLATE_SIGNAL(ALRM
);
7065 TRANSLATE_SIGNAL(FPE
);
7068 TRANSLATE_SIGNAL(HUP
);
7071 TRANSLATE_SIGNAL(ILL
);
7074 TRANSLATE_SIGNAL(INT
);
7077 TRANSLATE_SIGNAL(KILL
);
7080 TRANSLATE_SIGNAL(PIPE
);
7083 TRANSLATE_SIGNAL(QUIT
);
7086 TRANSLATE_SIGNAL(SEGV
);
7089 TRANSLATE_SIGNAL(TERM
);
7092 TRANSLATE_SIGNAL(USR1
);
7095 TRANSLATE_SIGNAL(USR2
);
7097 #undef TRANSLATE_SIGNAL
7099 ssh
->exitcode
= 128;
7101 core
= ssh2_pkt_getbool(pktin
);
7102 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
7104 fmt_msg
= dupprintf(" (\"%.*s\")", msglen
, msg
);
7106 /* ignore lang tag */
7107 } /* else don't attempt to parse */
7108 logeventf(ssh
, "Server exited on signal%s%s%s",
7109 fmt_sig
, core ?
" (core dumped)" : "",
7111 if (*fmt_sig
) sfree(fmt_sig
);
7112 if (*fmt_msg
) sfree(fmt_msg
);
7113 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
7118 * This is a channel request we don't know
7119 * about, so we now either ignore the request
7120 * or respond with CHANNEL_FAILURE, depending
7123 reply
= SSH2_MSG_CHANNEL_FAILURE
;
7126 pktout
= ssh2_pkt_init(reply
);
7127 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
7128 ssh2_pkt_send(ssh
, pktout
);
7132 static void ssh2_msg_global_request(Ssh ssh
, struct Packet
*pktin
)
7135 int typelen
, want_reply
;
7136 struct Packet
*pktout
;
7138 ssh_pkt_getstring(pktin
, &type
, &typelen
);
7139 want_reply
= ssh2_pkt_getbool(pktin
);
7142 * We currently don't support any global requests
7143 * at all, so we either ignore the request or
7144 * respond with REQUEST_FAILURE, depending on
7148 pktout
= ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE
);
7149 ssh2_pkt_send(ssh
, pktout
);
7153 static void ssh2_msg_channel_open(Ssh ssh
, struct Packet
*pktin
)
7161 struct ssh_channel
*c
;
7162 unsigned remid
, winsize
, pktsize
;
7163 struct Packet
*pktout
;
7165 ssh_pkt_getstring(pktin
, &type
, &typelen
);
7166 c
= snew(struct ssh_channel
);
7169 remid
= ssh_pkt_getuint32(pktin
);
7170 winsize
= ssh_pkt_getuint32(pktin
);
7171 pktsize
= ssh_pkt_getuint32(pktin
);
7173 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
7177 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
7178 addrstr
= snewn(peeraddrlen
+1, char);
7179 memcpy(addrstr
, peeraddr
, peeraddrlen
);
7180 addrstr
[peeraddrlen
] = '\0';
7181 peerport
= ssh_pkt_getuint32(pktin
);
7183 logeventf(ssh
, "Received X11 connect request from %s:%d",
7186 if (!ssh
->X11_fwd_enabled
)
7187 error
= "X11 forwarding is not enabled";
7188 else if ((x11err
= x11_init(&c
->u
.x11
.s
, ssh
->x11disp
, c
,
7189 addrstr
, peerport
, &ssh
->cfg
)) != NULL
) {
7190 logeventf(ssh
, "Local X11 connection failed: %s", x11err
);
7191 error
= "Unable to open an X11 connection";
7193 logevent("Opening X11 forward connection succeeded");
7198 } else if (typelen
== 15 &&
7199 !memcmp(type
, "forwarded-tcpip", 15)) {
7200 struct ssh_rportfwd pf
, *realpf
;
7203 ssh_pkt_getstring(pktin
, &dummy
, &dummylen
);/* skip address */
7204 pf
.sport
= ssh_pkt_getuint32(pktin
);
7205 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
7206 peerport
= ssh_pkt_getuint32(pktin
);
7207 realpf
= find234(ssh
->rportfwds
, &pf
, NULL
);
7208 logeventf(ssh
, "Received remote port %d open request "
7209 "from %s:%d", pf
.sport
, peeraddr
, peerport
);
7210 if (realpf
== NULL
) {
7211 error
= "Remote port is not recognised";
7213 const char *e
= pfd_newconnect(&c
->u
.pfd
.s
,
7217 realpf
->pfrec
->addressfamily
);
7218 logeventf(ssh
, "Attempting to forward remote port to "
7219 "%s:%d", realpf
->dhost
, realpf
->dport
);
7221 logeventf(ssh
, "Port open failed: %s", e
);
7222 error
= "Port open failed";
7224 logevent("Forwarded port opened successfully");
7225 c
->type
= CHAN_SOCKDATA
;
7228 } else if (typelen
== 22 &&
7229 !memcmp(type
, "auth-agent@openssh.com", 22)) {
7230 if (!ssh
->agentfwd_enabled
)
7231 error
= "Agent forwarding is not enabled";
7233 c
->type
= CHAN_AGENT
; /* identify channel type */
7234 c
->u
.a
.lensofar
= 0;
7237 error
= "Unsupported channel type requested";
7240 c
->remoteid
= remid
;
7241 c
->halfopen
= FALSE
;
7243 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
7244 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
7245 ssh2_pkt_adduint32(pktout
, SSH2_OPEN_CONNECT_FAILED
);
7246 ssh2_pkt_addstring(pktout
, error
);
7247 ssh2_pkt_addstring(pktout
, "en"); /* language tag */
7248 ssh2_pkt_send(ssh
, pktout
);
7249 logeventf(ssh
, "Rejected channel open: %s", error
);
7252 ssh2_channel_init(c
);
7253 c
->v
.v2
.remwindow
= winsize
;
7254 c
->v
.v2
.remmaxpkt
= pktsize
;
7255 add234(ssh
->channels
, c
);
7256 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
7257 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
7258 ssh2_pkt_adduint32(pktout
, c
->localid
);
7259 ssh2_pkt_adduint32(pktout
, c
->v
.v2
.locwindow
);
7260 ssh2_pkt_adduint32(pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
7261 ssh2_pkt_send(ssh
, pktout
);
7266 * Buffer banner messages for later display at some convenient point,
7267 * if we're going to display them.
7269 static void ssh2_msg_userauth_banner(Ssh ssh
, struct Packet
*pktin
)
7271 /* Arbitrary limit to prevent unbounded inflation of buffer */
7272 if (ssh
->cfg
.ssh_show_banner
&&
7273 bufchain_size(&ssh
->banner
) <= 131072) {
7274 char *banner
= NULL
;
7276 ssh_pkt_getstring(pktin
, &banner
, &size
);
7278 bufchain_add(&ssh
->banner
, banner
, size
);
7282 /* Helper function to deal with sending tty modes for "pty-req" */
7283 static void ssh2_send_ttymode(void *data
, char *mode
, char *val
)
7285 struct Packet
*pktout
= (struct Packet
*)data
;
7287 unsigned int arg
= 0;
7288 while (strcmp(mode
, ssh_ttymodes
[i
].mode
) != 0) i
++;
7289 if (i
== lenof(ssh_ttymodes
)) return;
7290 switch (ssh_ttymodes
[i
].type
) {
7292 arg
= ssh_tty_parse_specchar(val
);
7295 arg
= ssh_tty_parse_boolean(val
);
7298 ssh2_pkt_addbyte(pktout
, ssh_ttymodes
[i
].opcode
);
7299 ssh2_pkt_adduint32(pktout
, arg
);
7303 * Handle the SSH-2 userauth and connection layers.
7305 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
,
7306 struct Packet
*pktin
)
7308 struct do_ssh2_authconn_state
{
7311 AUTH_TYPE_PUBLICKEY
,
7312 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
7313 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
7316 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
7317 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7319 int done_service_req
;
7320 int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
7321 int tried_pubkey_config
, done_agent
;
7326 int kbd_inter_refused
;
7327 int we_are_in
, userauth_success
;
7328 prompts_t
*cur_prompt
;
7333 void *publickey_blob
;
7334 int publickey_bloblen
;
7335 int publickey_encrypted
;
7336 char *publickey_algorithm
;
7337 char *publickey_comment
;
7338 unsigned char agent_request
[5], *agent_response
, *agentp
;
7339 int agent_responselen
;
7340 unsigned char *pkblob_in_agent
;
7342 char *pkblob
, *alg
, *commentp
;
7343 int pklen
, alglen
, commentlen
;
7344 int siglen
, retlen
, len
;
7345 char *q
, *agentreq
, *ret
;
7347 int num_env
, env_left
, env_ok
;
7348 struct Packet
*pktout
;
7350 struct ssh_gss_library
*gsslib
;
7351 Ssh_gss_ctx gss_ctx
;
7352 Ssh_gss_buf gss_buf
;
7353 Ssh_gss_buf gss_rcvtok
, gss_sndtok
;
7354 Ssh_gss_name gss_srv_name
;
7355 Ssh_gss_stat gss_stat
;
7358 crState(do_ssh2_authconn_state
);
7360 crBegin(ssh
->do_ssh2_authconn_crstate
);
7362 s
->done_service_req
= FALSE
;
7363 s
->we_are_in
= s
->userauth_success
= FALSE
;
7365 s
->tried_gssapi
= FALSE
;
7368 if (!ssh
->cfg
.ssh_no_userauth
) {
7370 * Request userauth protocol, and await a response to it.
7372 s
->pktout
= ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
7373 ssh2_pkt_addstring(s
->pktout
, "ssh-userauth");
7374 ssh2_pkt_send(ssh
, s
->pktout
);
7375 crWaitUntilV(pktin
);
7376 if (pktin
->type
== SSH2_MSG_SERVICE_ACCEPT
)
7377 s
->done_service_req
= TRUE
;
7379 if (!s
->done_service_req
) {
7381 * Request connection protocol directly, without authentication.
7383 s
->pktout
= ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
7384 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7385 ssh2_pkt_send(ssh
, s
->pktout
);
7386 crWaitUntilV(pktin
);
7387 if (pktin
->type
== SSH2_MSG_SERVICE_ACCEPT
) {
7388 s
->we_are_in
= TRUE
; /* no auth required */
7390 bombout(("Server refused service request"));
7395 /* Arrange to be able to deal with any BANNERs that come in.
7396 * (We do this now as packets may come in during the next bit.) */
7397 bufchain_init(&ssh
->banner
);
7398 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] =
7399 ssh2_msg_userauth_banner
;
7402 * Misc one-time setup for authentication.
7404 s
->publickey_blob
= NULL
;
7405 if (!s
->we_are_in
) {
7408 * Load the public half of any configured public key file
7411 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
7413 logeventf(ssh
, "Reading private key file \"%.150s\"",
7414 filename_to_str(&ssh
->cfg
.keyfile
));
7415 keytype
= key_type(&ssh
->cfg
.keyfile
);
7416 if (keytype
== SSH_KEYTYPE_SSH2
) {
7419 ssh2_userkey_loadpub(&ssh
->cfg
.keyfile
,
7420 &s
->publickey_algorithm
,
7421 &s
->publickey_bloblen
,
7422 &s
->publickey_comment
, &error
);
7423 if (s
->publickey_blob
) {
7424 s
->publickey_encrypted
=
7425 ssh2_userkey_encrypted(&ssh
->cfg
.keyfile
, NULL
);
7428 logeventf(ssh
, "Unable to load private key (%s)",
7430 msgbuf
= dupprintf("Unable to load private key file "
7431 "\"%.150s\" (%s)\r\n",
7432 filename_to_str(&ssh
->cfg
.keyfile
),
7434 c_write_str(ssh
, msgbuf
);
7439 logeventf(ssh
, "Unable to use this key file (%s)",
7440 key_type_to_str(keytype
));
7441 msgbuf
= dupprintf("Unable to use key file \"%.150s\""
7443 filename_to_str(&ssh
->cfg
.keyfile
),
7444 key_type_to_str(keytype
));
7445 c_write_str(ssh
, msgbuf
);
7447 s
->publickey_blob
= NULL
;
7452 * Find out about any keys Pageant has (but if there's a
7453 * public key configured, filter out all others).
7456 s
->agent_response
= NULL
;
7457 s
->pkblob_in_agent
= NULL
;
7458 if (ssh
->cfg
.tryagent
&& agent_exists()) {
7462 logevent("Pageant is running. Requesting keys.");
7464 /* Request the keys held by the agent. */
7465 PUT_32BIT(s
->agent_request
, 1);
7466 s
->agent_request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
7467 if (!agent_query(s
->agent_request
, 5, &r
, &s
->agent_responselen
,
7468 ssh_agent_callback
, ssh
)) {
7472 bombout(("Unexpected data from server while"
7473 " waiting for agent response"));
7476 } while (pktin
|| inlen
> 0);
7477 r
= ssh
->agent_response
;
7478 s
->agent_responselen
= ssh
->agent_response_len
;
7480 s
->agent_response
= (unsigned char *) r
;
7481 if (s
->agent_response
&& s
->agent_responselen
>= 5 &&
7482 s
->agent_response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
7485 p
= s
->agent_response
+ 5;
7486 s
->nkeys
= GET_32BIT(p
);
7488 logeventf(ssh
, "Pageant has %d SSH-2 keys", s
->nkeys
);
7489 if (s
->publickey_blob
) {
7490 /* See if configured key is in agent. */
7491 for (keyi
= 0; keyi
< s
->nkeys
; keyi
++) {
7492 s
->pklen
= GET_32BIT(p
);
7493 if (s
->pklen
== s
->publickey_bloblen
&&
7494 !memcmp(p
+4, s
->publickey_blob
,
7495 s
->publickey_bloblen
)) {
7496 logeventf(ssh
, "Pageant key #%d matches "
7497 "configured key file", keyi
);
7499 s
->pkblob_in_agent
= p
;
7503 p
+= GET_32BIT(p
) + 4; /* comment */
7505 if (!s
->pkblob_in_agent
) {
7506 logevent("Configured key file not in Pageant");
7511 logevent("Failed to get reply from Pageant");
7518 * We repeat this whole loop, including the username prompt,
7519 * until we manage a successful authentication. If the user
7520 * types the wrong _password_, they can be sent back to the
7521 * beginning to try another username, if this is configured on.
7522 * (If they specify a username in the config, they are never
7523 * asked, even if they do give a wrong password.)
7525 * I think this best serves the needs of
7527 * - the people who have no configuration, no keys, and just
7528 * want to try repeated (username,password) pairs until they
7529 * type both correctly
7531 * - people who have keys and configuration but occasionally
7532 * need to fall back to passwords
7534 * - people with a key held in Pageant, who might not have
7535 * logged in to a particular machine before; so they want to
7536 * type a username, and then _either_ their key will be
7537 * accepted, _or_ they will type a password. If they mistype
7538 * the username they will want to be able to get back and
7541 s
->username
[0] = '\0';
7542 s
->got_username
= FALSE
;
7543 while (!s
->we_are_in
) {
7547 if (s
->got_username
&& !ssh
->cfg
.change_username
) {
7549 * We got a username last time round this loop, and
7550 * with change_username turned off we don't try to get
7553 } else if (!get_remote_username(&ssh
->cfg
, s
->username
,
7554 sizeof(s
->username
))) {
7555 int ret
; /* need not be kept over crReturn */
7556 s
->cur_prompt
= new_prompts(ssh
->frontend
);
7557 s
->cur_prompt
->to_server
= TRUE
;
7558 s
->cur_prompt
->name
= dupstr("SSH login name");
7559 add_prompt(s
->cur_prompt
, dupstr("login as: "), TRUE
,
7560 lenof(s
->username
));
7561 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
7564 crWaitUntilV(!pktin
);
7565 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
7570 * get_userpass_input() failed to get a username.
7573 free_prompts(s
->cur_prompt
);
7574 ssh_disconnect(ssh
, "No username provided", NULL
, 0, TRUE
);
7577 memcpy(s
->username
, s
->cur_prompt
->prompts
[0]->result
,
7578 lenof(s
->username
));
7579 free_prompts(s
->cur_prompt
);
7582 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
7583 stuff
= dupprintf("Using username \"%s\".\r\n", s
->username
);
7584 c_write_str(ssh
, stuff
);
7588 s
->got_username
= TRUE
;
7591 * Send an authentication request using method "none": (a)
7592 * just in case it succeeds, and (b) so that we know what
7593 * authentication methods we can usefully try next.
7595 ssh
->pkt_actx
= SSH2_PKTCTX_NOAUTH
;
7597 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7598 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7599 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");/* service requested */
7600 ssh2_pkt_addstring(s
->pktout
, "none"); /* method */
7601 ssh2_pkt_send(ssh
, s
->pktout
);
7602 s
->type
= AUTH_TYPE_NONE
;
7604 s
->we_are_in
= FALSE
;
7606 s
->tried_pubkey_config
= FALSE
;
7607 s
->kbd_inter_refused
= FALSE
;
7609 /* Reset agent request state. */
7610 s
->done_agent
= FALSE
;
7611 if (s
->agent_response
) {
7612 if (s
->pkblob_in_agent
) {
7613 s
->agentp
= s
->pkblob_in_agent
;
7615 s
->agentp
= s
->agent_response
+ 5 + 4;
7621 char *methods
= NULL
;
7625 * Wait for the result of the last authentication request.
7628 crWaitUntilV(pktin
);
7630 * Now is a convenient point to spew any banner material
7631 * that we've accumulated. (This should ensure that when
7632 * we exit the auth loop, we haven't any left to deal
7636 int size
= bufchain_size(&ssh
->banner
);
7638 * Don't show the banner if we're operating in
7639 * non-verbose non-interactive mode. (It's probably
7640 * a script, which means nobody will read the
7641 * banner _anyway_, and moreover the printing of
7642 * the banner will screw up processing on the
7643 * output of (say) plink.)
7645 if (size
&& (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
))) {
7646 char *banner
= snewn(size
, char);
7647 bufchain_fetch(&ssh
->banner
, banner
, size
);
7648 c_write_untrusted(ssh
, banner
, size
);
7651 bufchain_clear(&ssh
->banner
);
7653 if (pktin
->type
== SSH2_MSG_USERAUTH_SUCCESS
) {
7654 logevent("Access granted");
7655 s
->we_are_in
= s
->userauth_success
= TRUE
;
7659 if (pktin
->type
!= SSH2_MSG_USERAUTH_FAILURE
&& s
->type
!= AUTH_TYPE_GSSAPI
) {
7660 bombout(("Strange packet received during authentication: "
7661 "type %d", pktin
->type
));
7668 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7669 * we can look at the string in it and know what we can
7670 * helpfully try next.
7672 if (pktin
->type
== SSH2_MSG_USERAUTH_FAILURE
) {
7673 ssh_pkt_getstring(pktin
, &methods
, &methlen
);
7674 if (!ssh2_pkt_getbool(pktin
)) {
7676 * We have received an unequivocal Access
7677 * Denied. This can translate to a variety of
7680 * - if we'd just tried "none" authentication,
7681 * it's not worth printing anything at all
7683 * - if we'd just tried a public key _offer_,
7684 * the message should be "Server refused our
7685 * key" (or no message at all if the key
7686 * came from Pageant)
7688 * - if we'd just tried anything else, the
7689 * message really should be "Access denied".
7691 * Additionally, if we'd just tried password
7692 * authentication, we should break out of this
7693 * whole loop so as to go back to the username
7694 * prompt (iff we're configured to allow
7695 * username change attempts).
7697 if (s
->type
== AUTH_TYPE_NONE
) {
7699 } else if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
7700 s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
7701 if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
7702 c_write_str(ssh
, "Server refused our key\r\n");
7703 logevent("Server refused public key");
7704 } else if (s
->type
==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
7705 /* server declined keyboard-interactive; ignore */
7707 c_write_str(ssh
, "Access denied\r\n");
7708 logevent("Access denied");
7709 if (s
->type
== AUTH_TYPE_PASSWORD
&&
7710 ssh
->cfg
.change_username
) {
7711 /* XXX perhaps we should allow
7712 * keyboard-interactive to do this too? */
7713 s
->we_are_in
= FALSE
;
7718 c_write_str(ssh
, "Further authentication required\r\n");
7719 logevent("Further authentication required");
7723 in_commasep_string("publickey", methods
, methlen
);
7725 in_commasep_string("password", methods
, methlen
);
7726 s
->can_keyb_inter
= ssh
->cfg
.try_ki_auth
&&
7727 in_commasep_string("keyboard-interactive", methods
, methlen
);
7730 ssh
->gsslibs
= ssh_gss_setup(&ssh
->cfg
);
7731 s
->can_gssapi
= ssh
->cfg
.try_gssapi_auth
&&
7732 in_commasep_string("gssapi-with-mic", methods
, methlen
) &&
7733 ssh
->gsslibs
->nlibraries
> 0;
7737 ssh
->pkt_actx
= SSH2_PKTCTX_NOAUTH
;
7739 if (s
->can_pubkey
&& !s
->done_agent
&& s
->nkeys
) {
7742 * Attempt public-key authentication using a key from Pageant.
7745 ssh
->pkt_actx
= SSH2_PKTCTX_PUBLICKEY
;
7747 logeventf(ssh
, "Trying Pageant key #%d", s
->keyi
);
7749 /* Unpack key from agent response */
7750 s
->pklen
= GET_32BIT(s
->agentp
);
7752 s
->pkblob
= (char *)s
->agentp
;
7753 s
->agentp
+= s
->pklen
;
7754 s
->alglen
= GET_32BIT(s
->pkblob
);
7755 s
->alg
= s
->pkblob
+ 4;
7756 s
->commentlen
= GET_32BIT(s
->agentp
);
7758 s
->commentp
= (char *)s
->agentp
;
7759 s
->agentp
+= s
->commentlen
;
7760 /* s->agentp now points at next key, if any */
7762 /* See if server will accept it */
7763 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7764 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7765 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7766 /* service requested */
7767 ssh2_pkt_addstring(s
->pktout
, "publickey");
7769 ssh2_pkt_addbool(s
->pktout
, FALSE
); /* no signature included */
7770 ssh2_pkt_addstring_start(s
->pktout
);
7771 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
7772 ssh2_pkt_addstring_start(s
->pktout
);
7773 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
7774 ssh2_pkt_send(ssh
, s
->pktout
);
7775 s
->type
= AUTH_TYPE_PUBLICKEY_OFFER_QUIET
;
7777 crWaitUntilV(pktin
);
7778 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
7780 /* Offer of key refused. */
7787 if (flags
& FLAG_VERBOSE
) {
7788 c_write_str(ssh
, "Authenticating with "
7790 c_write(ssh
, s
->commentp
, s
->commentlen
);
7791 c_write_str(ssh
, "\" from agent\r\n");
7795 * Server is willing to accept the key.
7796 * Construct a SIGN_REQUEST.
7798 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7799 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7800 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7801 /* service requested */
7802 ssh2_pkt_addstring(s
->pktout
, "publickey");
7804 ssh2_pkt_addbool(s
->pktout
, TRUE
); /* signature included */
7805 ssh2_pkt_addstring_start(s
->pktout
);
7806 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
7807 ssh2_pkt_addstring_start(s
->pktout
);
7808 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
7810 /* Ask agent for signature. */
7811 s
->siglen
= s
->pktout
->length
- 5 + 4 +
7812 ssh
->v2_session_id_len
;
7813 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
7815 s
->len
= 1; /* message type */
7816 s
->len
+= 4 + s
->pklen
; /* key blob */
7817 s
->len
+= 4 + s
->siglen
; /* data to sign */
7818 s
->len
+= 4; /* flags */
7819 s
->agentreq
= snewn(4 + s
->len
, char);
7820 PUT_32BIT(s
->agentreq
, s
->len
);
7821 s
->q
= s
->agentreq
+ 4;
7822 *s
->q
++ = SSH2_AGENTC_SIGN_REQUEST
;
7823 PUT_32BIT(s
->q
, s
->pklen
);
7825 memcpy(s
->q
, s
->pkblob
, s
->pklen
);
7827 PUT_32BIT(s
->q
, s
->siglen
);
7829 /* Now the data to be signed... */
7830 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
7831 PUT_32BIT(s
->q
, ssh
->v2_session_id_len
);
7834 memcpy(s
->q
, ssh
->v2_session_id
,
7835 ssh
->v2_session_id_len
);
7836 s
->q
+= ssh
->v2_session_id_len
;
7837 memcpy(s
->q
, s
->pktout
->data
+ 5,
7838 s
->pktout
->length
- 5);
7839 s
->q
+= s
->pktout
->length
- 5;
7840 /* And finally the (zero) flags word. */
7842 if (!agent_query(s
->agentreq
, s
->len
+ 4,
7844 ssh_agent_callback
, ssh
)) {
7848 bombout(("Unexpected data from server"
7849 " while waiting for agent"
7853 } while (pktin
|| inlen
> 0);
7854 vret
= ssh
->agent_response
;
7855 s
->retlen
= ssh
->agent_response_len
;
7860 if (s
->ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
7861 logevent("Sending Pageant's response");
7862 ssh2_add_sigblob(ssh
, s
->pktout
,
7863 s
->pkblob
, s
->pklen
,
7865 GET_32BIT(s
->ret
+ 5));
7866 ssh2_pkt_send(ssh
, s
->pktout
);
7867 s
->type
= AUTH_TYPE_PUBLICKEY
;
7869 /* FIXME: less drastic response */
7870 bombout(("Pageant failed to answer challenge"));
7876 /* Do we have any keys left to try? */
7877 if (s
->pkblob_in_agent
) {
7878 s
->done_agent
= TRUE
;
7879 s
->tried_pubkey_config
= TRUE
;
7882 if (s
->keyi
>= s
->nkeys
)
7883 s
->done_agent
= TRUE
;
7886 } else if (s
->can_pubkey
&& s
->publickey_blob
&&
7887 !s
->tried_pubkey_config
) {
7889 struct ssh2_userkey
*key
; /* not live over crReturn */
7890 char *passphrase
; /* not live over crReturn */
7892 ssh
->pkt_actx
= SSH2_PKTCTX_PUBLICKEY
;
7894 s
->tried_pubkey_config
= TRUE
;
7897 * Try the public key supplied in the configuration.
7899 * First, offer the public blob to see if the server is
7900 * willing to accept it.
7902 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7903 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7904 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7905 /* service requested */
7906 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
7907 ssh2_pkt_addbool(s
->pktout
, FALSE
);
7908 /* no signature included */
7909 ssh2_pkt_addstring(s
->pktout
, s
->publickey_algorithm
);
7910 ssh2_pkt_addstring_start(s
->pktout
);
7911 ssh2_pkt_addstring_data(s
->pktout
,
7912 (char *)s
->publickey_blob
,
7913 s
->publickey_bloblen
);
7914 ssh2_pkt_send(ssh
, s
->pktout
);
7915 logevent("Offered public key");
7917 crWaitUntilV(pktin
);
7918 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
7919 /* Key refused. Give up. */
7920 s
->gotit
= TRUE
; /* reconsider message next loop */
7921 s
->type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
7922 continue; /* process this new message */
7924 logevent("Offer of public key accepted");
7927 * Actually attempt a serious authentication using
7930 if (flags
& FLAG_VERBOSE
) {
7931 c_write_str(ssh
, "Authenticating with public key \"");
7932 c_write_str(ssh
, s
->publickey_comment
);
7933 c_write_str(ssh
, "\"\r\n");
7937 const char *error
; /* not live over crReturn */
7938 if (s
->publickey_encrypted
) {
7940 * Get a passphrase from the user.
7942 int ret
; /* need not be kept over crReturn */
7943 s
->cur_prompt
= new_prompts(ssh
->frontend
);
7944 s
->cur_prompt
->to_server
= FALSE
;
7945 s
->cur_prompt
->name
= dupstr("SSH key passphrase");
7946 add_prompt(s
->cur_prompt
,
7947 dupprintf("Passphrase for key \"%.100s\": ",
7948 s
->publickey_comment
),
7949 FALSE
, SSH_MAX_PASSWORD_LEN
);
7950 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
7953 crWaitUntilV(!pktin
);
7954 ret
= get_userpass_input(s
->cur_prompt
,
7959 /* Failed to get a passphrase. Terminate. */
7960 free_prompts(s
->cur_prompt
);
7961 ssh_disconnect(ssh
, NULL
,
7962 "Unable to authenticate",
7963 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER
,
7968 dupstr(s
->cur_prompt
->prompts
[0]->result
);
7969 free_prompts(s
->cur_prompt
);
7971 passphrase
= NULL
; /* no passphrase needed */
7975 * Try decrypting the key.
7977 key
= ssh2_load_userkey(&ssh
->cfg
.keyfile
, passphrase
,
7980 /* burn the evidence */
7981 memset(passphrase
, 0, strlen(passphrase
));
7984 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
7986 (key
== SSH2_WRONG_PASSPHRASE
)) {
7987 c_write_str(ssh
, "Wrong passphrase\r\n");
7989 /* and loop again */
7991 c_write_str(ssh
, "Unable to load private key (");
7992 c_write_str(ssh
, error
);
7993 c_write_str(ssh
, ")\r\n");
7995 break; /* try something else */
8001 unsigned char *pkblob
, *sigblob
, *sigdata
;
8002 int pkblob_len
, sigblob_len
, sigdata_len
;
8006 * We have loaded the private key and the server
8007 * has announced that it's willing to accept it.
8008 * Hallelujah. Generate a signature and send it.
8010 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
8011 ssh2_pkt_addstring(s
->pktout
, s
->username
);
8012 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
8013 /* service requested */
8014 ssh2_pkt_addstring(s
->pktout
, "publickey");
8016 ssh2_pkt_addbool(s
->pktout
, TRUE
);
8017 /* signature follows */
8018 ssh2_pkt_addstring(s
->pktout
, key
->alg
->name
);
8019 pkblob
= key
->alg
->public_blob(key
->data
,
8021 ssh2_pkt_addstring_start(s
->pktout
);
8022 ssh2_pkt_addstring_data(s
->pktout
, (char *)pkblob
,
8026 * The data to be signed is:
8030 * followed by everything so far placed in the
8033 sigdata_len
= s
->pktout
->length
- 5 + 4 +
8034 ssh
->v2_session_id_len
;
8035 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
8037 sigdata
= snewn(sigdata_len
, unsigned char);
8039 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
8040 PUT_32BIT(sigdata
+p
, ssh
->v2_session_id_len
);
8043 memcpy(sigdata
+p
, ssh
->v2_session_id
,
8044 ssh
->v2_session_id_len
);
8045 p
+= ssh
->v2_session_id_len
;
8046 memcpy(sigdata
+p
, s
->pktout
->data
+ 5,
8047 s
->pktout
->length
- 5);
8048 p
+= s
->pktout
->length
- 5;
8049 assert(p
== sigdata_len
);
8050 sigblob
= key
->alg
->sign(key
->data
, (char *)sigdata
,
8051 sigdata_len
, &sigblob_len
);
8052 ssh2_add_sigblob(ssh
, s
->pktout
, pkblob
, pkblob_len
,
8053 sigblob
, sigblob_len
);
8058 ssh2_pkt_send(ssh
, s
->pktout
);
8059 s
->type
= AUTH_TYPE_PUBLICKEY
;
8060 key
->alg
->freekey(key
->data
);
8064 } else if (s
->can_gssapi
&& !s
->tried_gssapi
) {
8066 /* GSSAPI Authentication */
8071 s
->type
= AUTH_TYPE_GSSAPI
;
8072 s
->tried_gssapi
= TRUE
;
8074 ssh
->pkt_actx
= SSH2_PKTCTX_GSSAPI
;
8077 * Pick the highest GSS library on the preference
8083 for (i
= 0; i
< ngsslibs
; i
++) {
8084 int want_id
= ssh
->cfg
.ssh_gsslist
[i
];
8085 for (j
= 0; j
< ssh
->gsslibs
->nlibraries
; j
++)
8086 if (ssh
->gsslibs
->libraries
[j
].id
== want_id
) {
8087 s
->gsslib
= &ssh
->gsslibs
->libraries
[j
];
8088 goto got_gsslib
; /* double break */
8093 * We always expect to have found something in
8094 * the above loop: we only came here if there
8095 * was at least one viable GSS library, and the
8096 * preference list should always mention
8097 * everything and only change the order.
8102 if (s
->gsslib
->gsslogmsg
)
8103 logevent(s
->gsslib
->gsslogmsg
);
8105 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8106 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
8107 ssh2_pkt_addstring(s
->pktout
, s
->username
);
8108 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
8109 ssh2_pkt_addstring(s
->pktout
, "gssapi-with-mic");
8111 /* add mechanism info */
8112 s
->gsslib
->indicate_mech(s
->gsslib
, &s
->gss_buf
);
8114 /* number of GSSAPI mechanisms */
8115 ssh2_pkt_adduint32(s
->pktout
,1);
8117 /* length of OID + 2 */
8118 ssh2_pkt_adduint32(s
->pktout
, s
->gss_buf
.length
+ 2);
8119 ssh2_pkt_addbyte(s
->pktout
, SSH2_GSS_OIDTYPE
);
8122 ssh2_pkt_addbyte(s
->pktout
, (unsigned char) s
->gss_buf
.length
);
8124 ssh_pkt_adddata(s
->pktout
, s
->gss_buf
.value
,
8126 ssh2_pkt_send(ssh
, s
->pktout
);
8127 crWaitUntilV(pktin
);
8128 if (pktin
->type
!= SSH2_MSG_USERAUTH_GSSAPI_RESPONSE
) {
8129 logevent("GSSAPI authentication request refused");
8133 /* check returned packet ... */
8135 ssh_pkt_getstring(pktin
, &data
, &len
);
8136 s
->gss_rcvtok
.value
= data
;
8137 s
->gss_rcvtok
.length
= len
;
8138 if (s
->gss_rcvtok
.length
!= s
->gss_buf
.length
+ 2 ||
8139 ((char *)s
->gss_rcvtok
.value
)[0] != SSH2_GSS_OIDTYPE
||
8140 ((char *)s
->gss_rcvtok
.value
)[1] != s
->gss_buf
.length
||
8141 memcmp((char *)s
->gss_rcvtok
.value
+ 2,
8142 s
->gss_buf
.value
,s
->gss_buf
.length
) ) {
8143 logevent("GSSAPI authentication - wrong response from server");
8147 /* now start running */
8148 s
->gss_stat
= s
->gsslib
->import_name(s
->gsslib
,
8151 if (s
->gss_stat
!= SSH_GSS_OK
) {
8152 if (s
->gss_stat
== SSH_GSS_BAD_HOST_NAME
)
8153 logevent("GSSAPI import name failed - Bad service name");
8155 logevent("GSSAPI import name failed");
8159 /* fetch TGT into GSS engine */
8160 s
->gss_stat
= s
->gsslib
->acquire_cred(s
->gsslib
, &s
->gss_ctx
);
8162 if (s
->gss_stat
!= SSH_GSS_OK
) {
8163 logevent("GSSAPI authentication failed to get credentials");
8164 s
->gsslib
->release_name(s
->gsslib
, &s
->gss_srv_name
);
8168 /* initial tokens are empty */
8169 SSH_GSS_CLEAR_BUF(&s
->gss_rcvtok
);
8170 SSH_GSS_CLEAR_BUF(&s
->gss_sndtok
);
8172 /* now enter the loop */
8174 s
->gss_stat
= s
->gsslib
->init_sec_context
8182 if (s
->gss_stat
!=SSH_GSS_S_COMPLETE
&&
8183 s
->gss_stat
!=SSH_GSS_S_CONTINUE_NEEDED
) {
8184 logevent("GSSAPI authentication initialisation failed");
8186 if (s
->gsslib
->display_status(s
->gsslib
, s
->gss_ctx
,
8187 &s
->gss_buf
) == SSH_GSS_OK
) {
8188 logevent(s
->gss_buf
.value
);
8189 sfree(s
->gss_buf
.value
);
8194 logevent("GSSAPI authentication initialised");
8196 /* Client and server now exchange tokens until GSSAPI
8197 * no longer says CONTINUE_NEEDED */
8199 if (s
->gss_sndtok
.length
!= 0) {
8200 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN
);
8201 ssh_pkt_addstring_start(s
->pktout
);
8202 ssh_pkt_addstring_data(s
->pktout
,s
->gss_sndtok
.value
,s
->gss_sndtok
.length
);
8203 ssh2_pkt_send(ssh
, s
->pktout
);
8204 s
->gsslib
->free_tok(s
->gsslib
, &s
->gss_sndtok
);
8207 if (s
->gss_stat
== SSH_GSS_S_CONTINUE_NEEDED
) {
8208 crWaitUntilV(pktin
);
8209 if (pktin
->type
!= SSH2_MSG_USERAUTH_GSSAPI_TOKEN
) {
8210 logevent("GSSAPI authentication - bad server response");
8211 s
->gss_stat
= SSH_GSS_FAILURE
;
8214 ssh_pkt_getstring(pktin
, &data
, &len
);
8215 s
->gss_rcvtok
.value
= data
;
8216 s
->gss_rcvtok
.length
= len
;
8218 } while (s
-> gss_stat
== SSH_GSS_S_CONTINUE_NEEDED
);
8220 if (s
->gss_stat
!= SSH_GSS_OK
) {
8221 s
->gsslib
->release_name(s
->gsslib
, &s
->gss_srv_name
);
8222 s
->gsslib
->release_cred(s
->gsslib
, &s
->gss_ctx
);
8225 logevent("GSSAPI authentication loop finished OK");
8227 /* Now send the MIC */
8229 s
->pktout
= ssh2_pkt_init(0);
8230 micoffset
= s
->pktout
->length
;
8231 ssh_pkt_addstring_start(s
->pktout
);
8232 ssh_pkt_addstring_data(s
->pktout
, (char *)ssh
->v2_session_id
, ssh
->v2_session_id_len
);
8233 ssh_pkt_addbyte(s
->pktout
, SSH2_MSG_USERAUTH_REQUEST
);
8234 ssh_pkt_addstring(s
->pktout
, s
->username
);
8235 ssh_pkt_addstring(s
->pktout
, "ssh-connection");
8236 ssh_pkt_addstring(s
->pktout
, "gssapi-with-mic");
8238 s
->gss_buf
.value
= (char *)s
->pktout
->data
+ micoffset
;
8239 s
->gss_buf
.length
= s
->pktout
->length
- micoffset
;
8241 s
->gsslib
->get_mic(s
->gsslib
, s
->gss_ctx
, &s
->gss_buf
, &mic
);
8242 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC
);
8243 ssh_pkt_addstring_start(s
->pktout
);
8244 ssh_pkt_addstring_data(s
->pktout
, mic
.value
, mic
.length
);
8245 ssh2_pkt_send(ssh
, s
->pktout
);
8246 s
->gsslib
->free_mic(s
->gsslib
, &mic
);
8250 s
->gsslib
->release_name(s
->gsslib
, &s
->gss_srv_name
);
8251 s
->gsslib
->release_cred(s
->gsslib
, &s
->gss_ctx
);
8254 } else if (s
->can_keyb_inter
&& !s
->kbd_inter_refused
) {
8257 * Keyboard-interactive authentication.
8260 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
8262 ssh
->pkt_actx
= SSH2_PKTCTX_KBDINTER
;
8264 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
8265 ssh2_pkt_addstring(s
->pktout
, s
->username
);
8266 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
8267 /* service requested */
8268 ssh2_pkt_addstring(s
->pktout
, "keyboard-interactive");
8270 ssh2_pkt_addstring(s
->pktout
, ""); /* lang */
8271 ssh2_pkt_addstring(s
->pktout
, ""); /* submethods */
8272 ssh2_pkt_send(ssh
, s
->pktout
);
8274 crWaitUntilV(pktin
);
8275 if (pktin
->type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
8276 /* Server is not willing to do keyboard-interactive
8277 * at all (or, bizarrely but legally, accepts the
8278 * user without actually issuing any prompts).
8279 * Give up on it entirely. */
8281 if (pktin
->type
== SSH2_MSG_USERAUTH_FAILURE
)
8282 logevent("Keyboard-interactive authentication refused");
8283 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
8284 s
->kbd_inter_refused
= TRUE
; /* don't try it again */
8289 * Loop while the server continues to send INFO_REQUESTs.
8291 while (pktin
->type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
8293 char *name
, *inst
, *lang
;
8294 int name_len
, inst_len
, lang_len
;
8298 * We've got a fresh USERAUTH_INFO_REQUEST.
8299 * Get the preamble and start building a prompt.
8301 ssh_pkt_getstring(pktin
, &name
, &name_len
);
8302 ssh_pkt_getstring(pktin
, &inst
, &inst_len
);
8303 ssh_pkt_getstring(pktin
, &lang
, &lang_len
);
8304 s
->cur_prompt
= new_prompts(ssh
->frontend
);
8305 s
->cur_prompt
->to_server
= TRUE
;
8308 * Get any prompt(s) from the packet.
8310 s
->num_prompts
= ssh_pkt_getuint32(pktin
);
8311 for (i
= 0; i
< s
->num_prompts
; i
++) {
8315 static char noprompt
[] =
8316 "<server failed to send prompt>: ";
8318 ssh_pkt_getstring(pktin
, &prompt
, &prompt_len
);
8319 echo
= ssh2_pkt_getbool(pktin
);
8322 prompt_len
= lenof(noprompt
)-1;
8324 add_prompt(s
->cur_prompt
,
8325 dupprintf("%.*s", prompt_len
, prompt
),
8326 echo
, SSH_MAX_PASSWORD_LEN
);
8330 /* FIXME: better prefix to distinguish from
8332 s
->cur_prompt
->name
=
8333 dupprintf("SSH server: %.*s", name_len
, name
);
8334 s
->cur_prompt
->name_reqd
= TRUE
;
8336 s
->cur_prompt
->name
=
8337 dupstr("SSH server authentication");
8338 s
->cur_prompt
->name_reqd
= FALSE
;
8340 /* We add a prefix to try to make it clear that a prompt
8341 * has come from the server.
8342 * FIXME: ugly to print "Using..." in prompt _every_
8343 * time round. Can this be done more subtly? */
8344 /* Special case: for reasons best known to themselves,
8345 * some servers send k-i requests with no prompts and
8346 * nothing to display. Keep quiet in this case. */
8347 if (s
->num_prompts
|| name_len
|| inst_len
) {
8348 s
->cur_prompt
->instruction
=
8349 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8350 inst_len ?
"\n" : "", inst_len
, inst
);
8351 s
->cur_prompt
->instr_reqd
= TRUE
;
8353 s
->cur_prompt
->instr_reqd
= FALSE
;
8357 * Display any instructions, and get the user's
8361 int ret
; /* not live over crReturn */
8362 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
8365 crWaitUntilV(!pktin
);
8366 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
8371 * Failed to get responses. Terminate.
8373 free_prompts(s
->cur_prompt
);
8374 ssh_disconnect(ssh
, NULL
, "Unable to authenticate",
8375 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER
,
8382 * Send the response(s) to the server.
8384 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
8385 ssh2_pkt_adduint32(s
->pktout
, s
->num_prompts
);
8386 for (i
=0; i
< s
->num_prompts
; i
++) {
8387 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
8388 ssh2_pkt_addstring(s
->pktout
,
8389 s
->cur_prompt
->prompts
[i
]->result
);
8390 end_log_omission(ssh
, s
->pktout
);
8392 ssh2_pkt_send_with_padding(ssh
, s
->pktout
, 256);
8395 * Get the next packet in case it's another
8398 crWaitUntilV(pktin
);
8403 * We should have SUCCESS or FAILURE now.
8407 } else if (s
->can_passwd
) {
8410 * Plain old password authentication.
8412 int ret
; /* not live over crReturn */
8413 int changereq_first_time
; /* not live over crReturn */
8415 ssh
->pkt_actx
= SSH2_PKTCTX_PASSWORD
;
8417 s
->cur_prompt
= new_prompts(ssh
->frontend
);
8418 s
->cur_prompt
->to_server
= TRUE
;
8419 s
->cur_prompt
->name
= dupstr("SSH password");
8420 add_prompt(s
->cur_prompt
, dupprintf("%.90s@%.90s's password: ",
8423 FALSE
, SSH_MAX_PASSWORD_LEN
);
8425 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
8428 crWaitUntilV(!pktin
);
8429 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
8434 * Failed to get responses. Terminate.
8436 free_prompts(s
->cur_prompt
);
8437 ssh_disconnect(ssh
, NULL
, "Unable to authenticate",
8438 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER
,
8443 * Squirrel away the password. (We may need it later if
8444 * asked to change it.)
8446 s
->password
= dupstr(s
->cur_prompt
->prompts
[0]->result
);
8447 free_prompts(s
->cur_prompt
);
8450 * Send the password packet.
8452 * We pad out the password packet to 256 bytes to make
8453 * it harder for an attacker to find the length of the
8456 * Anyone using a password longer than 256 bytes
8457 * probably doesn't have much to worry about from
8458 * people who find out how long their password is!
8460 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
8461 ssh2_pkt_addstring(s
->pktout
, s
->username
);
8462 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
8463 /* service requested */
8464 ssh2_pkt_addstring(s
->pktout
, "password");
8465 ssh2_pkt_addbool(s
->pktout
, FALSE
);
8466 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
8467 ssh2_pkt_addstring(s
->pktout
, s
->password
);
8468 end_log_omission(ssh
, s
->pktout
);
8469 ssh2_pkt_send_with_padding(ssh
, s
->pktout
, 256);
8470 logevent("Sent password");
8471 s
->type
= AUTH_TYPE_PASSWORD
;
8474 * Wait for next packet, in case it's a password change
8477 crWaitUntilV(pktin
);
8478 changereq_first_time
= TRUE
;
8480 while (pktin
->type
== SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
) {
8483 * We're being asked for a new password
8484 * (perhaps not for the first time).
8485 * Loop until the server accepts it.
8488 int got_new
= FALSE
; /* not live over crReturn */
8489 char *prompt
; /* not live over crReturn */
8490 int prompt_len
; /* not live over crReturn */
8494 if (changereq_first_time
)
8495 msg
= "Server requested password change";
8497 msg
= "Server rejected new password";
8499 c_write_str(ssh
, msg
);
8500 c_write_str(ssh
, "\r\n");
8503 ssh_pkt_getstring(pktin
, &prompt
, &prompt_len
);
8505 s
->cur_prompt
= new_prompts(ssh
->frontend
);
8506 s
->cur_prompt
->to_server
= TRUE
;
8507 s
->cur_prompt
->name
= dupstr("New SSH password");
8508 s
->cur_prompt
->instruction
=
8509 dupprintf("%.*s", prompt_len
, prompt
);
8510 s
->cur_prompt
->instr_reqd
= TRUE
;
8512 * There's no explicit requirement in the protocol
8513 * for the "old" passwords in the original and
8514 * password-change messages to be the same, and
8515 * apparently some Cisco kit supports password change
8516 * by the user entering a blank password originally
8517 * and the real password subsequently, so,
8518 * reluctantly, we prompt for the old password again.
8520 * (On the other hand, some servers don't even bother
8521 * to check this field.)
8523 add_prompt(s
->cur_prompt
,
8524 dupstr("Current password (blank for previously entered password): "),
8525 FALSE
, SSH_MAX_PASSWORD_LEN
);
8526 add_prompt(s
->cur_prompt
, dupstr("Enter new password: "),
8527 FALSE
, SSH_MAX_PASSWORD_LEN
);
8528 add_prompt(s
->cur_prompt
, dupstr("Confirm new password: "),
8529 FALSE
, SSH_MAX_PASSWORD_LEN
);
8532 * Loop until the user manages to enter the same
8537 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
8540 crWaitUntilV(!pktin
);
8541 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
8546 * Failed to get responses. Terminate.
8548 /* burn the evidence */
8549 free_prompts(s
->cur_prompt
);
8550 memset(s
->password
, 0, strlen(s
->password
));
8552 ssh_disconnect(ssh
, NULL
, "Unable to authenticate",
8553 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER
,
8559 * If the user specified a new original password
8560 * (IYSWIM), overwrite any previously specified
8562 * (A side effect is that the user doesn't have to
8563 * re-enter it if they louse up the new password.)
8565 if (s
->cur_prompt
->prompts
[0]->result
[0]) {
8566 memset(s
->password
, 0, strlen(s
->password
));
8567 /* burn the evidence */
8570 dupstr(s
->cur_prompt
->prompts
[0]->result
);
8574 * Check the two new passwords match.
8576 got_new
= (strcmp(s
->cur_prompt
->prompts
[1]->result
,
8577 s
->cur_prompt
->prompts
[2]->result
)
8580 /* They don't. Silly user. */
8581 c_write_str(ssh
, "Passwords do not match\r\n");
8586 * Send the new password (along with the old one).
8587 * (see above for padding rationale)
8589 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
8590 ssh2_pkt_addstring(s
->pktout
, s
->username
);
8591 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
8592 /* service requested */
8593 ssh2_pkt_addstring(s
->pktout
, "password");
8594 ssh2_pkt_addbool(s
->pktout
, TRUE
);
8595 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
8596 ssh2_pkt_addstring(s
->pktout
, s
->password
);
8597 ssh2_pkt_addstring(s
->pktout
,
8598 s
->cur_prompt
->prompts
[1]->result
);
8599 free_prompts(s
->cur_prompt
);
8600 end_log_omission(ssh
, s
->pktout
);
8601 ssh2_pkt_send_with_padding(ssh
, s
->pktout
, 256);
8602 logevent("Sent new password");
8605 * Now see what the server has to say about it.
8606 * (If it's CHANGEREQ again, it's not happy with the
8609 crWaitUntilV(pktin
);
8610 changereq_first_time
= FALSE
;
8615 * We need to reexamine the current pktin at the top
8616 * of the loop. Either:
8617 * - we weren't asked to change password at all, in
8618 * which case it's a SUCCESS or FAILURE with the
8620 * - we sent a new password, and the server was
8621 * either OK with it (SUCCESS or FAILURE w/partial
8622 * success) or unhappy with the _old_ password
8623 * (FAILURE w/o partial success)
8624 * In any of these cases, we go back to the top of
8625 * the loop and start again.
8630 * We don't need the old password any more, in any
8631 * case. Burn the evidence.
8633 memset(s
->password
, 0, strlen(s
->password
));
8637 char *str
= dupprintf("No supported authentication methods available"
8638 " (server sent: %.*s)",
8641 ssh_disconnect(ssh
, str
,
8642 "No supported authentication methods available",
8643 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE
,
8653 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] = NULL
;
8655 /* Clear up various bits and pieces from authentication. */
8656 if (s
->publickey_blob
) {
8657 sfree(s
->publickey_blob
);
8658 sfree(s
->publickey_comment
);
8660 if (s
->agent_response
)
8661 sfree(s
->agent_response
);
8663 if (s
->userauth_success
) {
8665 * We've just received USERAUTH_SUCCESS, and we haven't sent any
8666 * packets since. Signal the transport layer to consider enacting
8667 * delayed compression.
8669 * (Relying on we_are_in is not sufficient, as
8670 * draft-miller-secsh-compression-delayed is quite clear that it
8671 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
8672 * become set for other reasons.)
8674 do_ssh2_transport(ssh
, "enabling delayed compression", -2, NULL
);
8678 * Now the connection protocol has started, one way or another.
8681 ssh
->channels
= newtree234(ssh_channelcmp
);
8684 * Set up handlers for some connection protocol messages, so we
8685 * don't have to handle them repeatedly in this coroutine.
8687 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] =
8688 ssh2_msg_channel_window_adjust
;
8689 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] =
8690 ssh2_msg_global_request
;
8693 * Create the main session channel.
8695 if (ssh
->cfg
.ssh_no_shell
) {
8696 ssh
->mainchan
= NULL
;
8697 } else if (*ssh
->cfg
.ssh_nc_host
) {
8699 * Just start a direct-tcpip channel and use it as the main
8702 ssh
->mainchan
= snew(struct ssh_channel
);
8703 ssh
->mainchan
->ssh
= ssh
;
8704 ssh2_channel_init(ssh
->mainchan
);
8706 "Opening direct-tcpip channel to %s:%d in place of session",
8707 ssh
->cfg
.ssh_nc_host
, ssh
->cfg
.ssh_nc_port
);
8708 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
8709 ssh2_pkt_addstring(s
->pktout
, "direct-tcpip");
8710 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->localid
);
8711 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->v
.v2
.locwindow
);/* our window size */
8712 ssh2_pkt_adduint32(s
->pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
8713 ssh2_pkt_addstring(s
->pktout
, ssh
->cfg
.ssh_nc_host
);
8714 ssh2_pkt_adduint32(s
->pktout
, ssh
->cfg
.ssh_nc_port
);
8716 * There's nothing meaningful to put in the originator
8717 * fields, but some servers insist on syntactically correct
8720 ssh2_pkt_addstring(s
->pktout
, "0.0.0.0");
8721 ssh2_pkt_adduint32(s
->pktout
, 0);
8722 ssh2_pkt_send(ssh
, s
->pktout
);
8724 crWaitUntilV(pktin
);
8725 if (pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
8726 bombout(("Server refused to open a direct-tcpip channel"));
8728 /* FIXME: error data comes back in FAILURE packet */
8730 if (ssh_pkt_getuint32(pktin
) != ssh
->mainchan
->localid
) {
8731 bombout(("Server's channel confirmation cited wrong channel"));
8734 ssh
->mainchan
->remoteid
= ssh_pkt_getuint32(pktin
);
8735 ssh
->mainchan
->halfopen
= FALSE
;
8736 ssh
->mainchan
->type
= CHAN_MAINSESSION
;
8737 ssh
->mainchan
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
8738 ssh
->mainchan
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
8739 add234(ssh
->channels
, ssh
->mainchan
);
8740 update_specials_menu(ssh
->frontend
);
8741 logevent("Opened direct-tcpip channel");
8744 ssh
->mainchan
= snew(struct ssh_channel
);
8745 ssh
->mainchan
->ssh
= ssh
;
8746 ssh2_channel_init(ssh
->mainchan
);
8747 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
8748 ssh2_pkt_addstring(s
->pktout
, "session");
8749 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->localid
);
8750 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->v
.v2
.locwindow
);/* our window size */
8751 ssh2_pkt_adduint32(s
->pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
8752 ssh2_pkt_send(ssh
, s
->pktout
);
8753 crWaitUntilV(pktin
);
8754 if (pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
8755 bombout(("Server refused to open a session"));
8757 /* FIXME: error data comes back in FAILURE packet */
8759 if (ssh_pkt_getuint32(pktin
) != ssh
->mainchan
->localid
) {
8760 bombout(("Server's channel confirmation cited wrong channel"));
8763 ssh
->mainchan
->remoteid
= ssh_pkt_getuint32(pktin
);
8764 ssh
->mainchan
->halfopen
= FALSE
;
8765 ssh
->mainchan
->type
= CHAN_MAINSESSION
;
8766 ssh
->mainchan
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
8767 ssh
->mainchan
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
8768 add234(ssh
->channels
, ssh
->mainchan
);
8769 update_specials_menu(ssh
->frontend
);
8770 logevent("Opened channel for session");
8771 ssh
->ncmode
= FALSE
;
8775 * Now we have a channel, make dispatch table entries for
8776 * general channel-based messages.
8778 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] =
8779 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] =
8780 ssh2_msg_channel_data
;
8781 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = ssh2_msg_channel_eof
;
8782 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = ssh2_msg_channel_close
;
8783 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] =
8784 ssh2_msg_channel_open_confirmation
;
8785 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] =
8786 ssh2_msg_channel_open_failure
;
8787 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_REQUEST
] =
8788 ssh2_msg_channel_request
;
8789 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] =
8790 ssh2_msg_channel_open
;
8792 if (ssh
->mainchan
&& ssh
->cfg
.ssh_simple
) {
8794 * This message indicates to the server that we promise
8795 * not to try to run any other channel in parallel with
8796 * this one, so it's safe for it to advertise a very large
8797 * window and leave the flow control to TCP.
8799 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8800 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
8801 ssh2_pkt_addstring(s
->pktout
, "simple@putty.projects.tartarus.org");
8802 ssh2_pkt_addbool(s
->pktout
, 0); /* no reply */
8803 ssh2_pkt_send(ssh
, s
->pktout
);
8807 * Potentially enable X11 forwarding.
8809 if (ssh
->mainchan
&& !ssh
->ncmode
&& ssh
->cfg
.x11_forward
&&
8810 (ssh
->x11disp
= x11_setup_display(ssh
->cfg
.x11_display
,
8811 ssh
->cfg
.x11_auth
, &ssh
->cfg
))) {
8812 logevent("Requesting X11 forwarding");
8813 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8814 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
8815 ssh2_pkt_addstring(s
->pktout
, "x11-req");
8816 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8817 ssh2_pkt_addbool(s
->pktout
, 0); /* many connections */
8818 ssh2_pkt_addstring(s
->pktout
, ssh
->x11disp
->remoteauthprotoname
);
8820 * Note that while we blank the X authentication data here, we don't
8821 * take any special action to blank the start of an X11 channel,
8822 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
8823 * without having session blanking enabled is likely to leak your
8824 * cookie into the log.
8826 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
8827 ssh2_pkt_addstring(s
->pktout
, ssh
->x11disp
->remoteauthdatastring
);
8828 end_log_omission(ssh
, s
->pktout
);
8829 ssh2_pkt_adduint32(s
->pktout
, ssh
->x11disp
->screennum
);
8830 ssh2_pkt_send(ssh
, s
->pktout
);
8832 crWaitUntilV(pktin
);
8834 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
8835 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
8836 bombout(("Unexpected response to X11 forwarding request:"
8837 " packet type %d", pktin
->type
));
8840 logevent("X11 forwarding refused");
8842 logevent("X11 forwarding enabled");
8843 ssh
->X11_fwd_enabled
= TRUE
;
8848 * Enable port forwardings.
8850 ssh_setup_portfwd(ssh
, &ssh
->cfg
);
8853 * Potentially enable agent forwarding.
8855 if (ssh
->mainchan
&& !ssh
->ncmode
&& ssh
->cfg
.agentfwd
&& agent_exists()) {
8856 logevent("Requesting OpenSSH-style agent forwarding");
8857 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8858 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
8859 ssh2_pkt_addstring(s
->pktout
, "auth-agent-req@openssh.com");
8860 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8861 ssh2_pkt_send(ssh
, s
->pktout
);
8863 crWaitUntilV(pktin
);
8865 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
8866 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
8867 bombout(("Unexpected response to agent forwarding request:"
8868 " packet type %d", pktin
->type
));
8871 logevent("Agent forwarding refused");
8873 logevent("Agent forwarding enabled");
8874 ssh
->agentfwd_enabled
= TRUE
;
8879 * Now allocate a pty for the session.
8881 if (ssh
->mainchan
&& !ssh
->ncmode
&& !ssh
->cfg
.nopty
) {
8882 /* Unpick the terminal-speed string. */
8883 /* XXX perhaps we should allow no speeds to be sent. */
8884 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
8885 sscanf(ssh
->cfg
.termspeed
, "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
8886 /* Build the pty request. */
8887 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8888 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
); /* recipient channel */
8889 ssh2_pkt_addstring(s
->pktout
, "pty-req");
8890 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8891 ssh2_pkt_addstring(s
->pktout
, ssh
->cfg
.termtype
);
8892 ssh2_pkt_adduint32(s
->pktout
, ssh
->term_width
);
8893 ssh2_pkt_adduint32(s
->pktout
, ssh
->term_height
);
8894 ssh2_pkt_adduint32(s
->pktout
, 0); /* pixel width */
8895 ssh2_pkt_adduint32(s
->pktout
, 0); /* pixel height */
8896 ssh2_pkt_addstring_start(s
->pktout
);
8897 parse_ttymodes(ssh
, ssh
->cfg
.ttymodes
,
8898 ssh2_send_ttymode
, (void *)s
->pktout
);
8899 ssh2_pkt_addbyte(s
->pktout
, SSH2_TTY_OP_ISPEED
);
8900 ssh2_pkt_adduint32(s
->pktout
, ssh
->ispeed
);
8901 ssh2_pkt_addbyte(s
->pktout
, SSH2_TTY_OP_OSPEED
);
8902 ssh2_pkt_adduint32(s
->pktout
, ssh
->ospeed
);
8903 ssh2_pkt_addstring_data(s
->pktout
, "\0", 1); /* TTY_OP_END */
8904 ssh2_pkt_send(ssh
, s
->pktout
);
8905 ssh
->state
= SSH_STATE_INTERMED
;
8907 crWaitUntilV(pktin
);
8909 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
8910 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
8911 bombout(("Unexpected response to pty request:"
8912 " packet type %d", pktin
->type
));
8915 c_write_str(ssh
, "Server refused to allocate pty\r\n");
8916 ssh
->editing
= ssh
->echoing
= 1;
8918 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8919 ssh
->ospeed
, ssh
->ispeed
);
8922 ssh
->editing
= ssh
->echoing
= 1;
8926 * Send environment variables.
8928 * Simplest thing here is to send all the requests at once, and
8929 * then wait for a whole bunch of successes or failures.
8931 if (ssh
->mainchan
&& !ssh
->ncmode
&& *ssh
->cfg
.environmt
) {
8932 char *e
= ssh
->cfg
.environmt
;
8933 char *var
, *varend
, *val
;
8939 while (*e
&& *e
!= '\t') e
++;
8941 if (*e
== '\t') e
++;
8946 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8947 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
8948 ssh2_pkt_addstring(s
->pktout
, "env");
8949 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8950 ssh2_pkt_addstring_start(s
->pktout
);
8951 ssh2_pkt_addstring_data(s
->pktout
, var
, varend
-var
);
8952 ssh2_pkt_addstring(s
->pktout
, val
);
8953 ssh2_pkt_send(ssh
, s
->pktout
);
8958 logeventf(ssh
, "Sent %d environment variables", s
->num_env
);
8961 s
->env_left
= s
->num_env
;
8963 while (s
->env_left
> 0) {
8964 crWaitUntilV(pktin
);
8966 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
8967 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
8968 bombout(("Unexpected response to environment request:"
8969 " packet type %d", pktin
->type
));
8979 if (s
->env_ok
== s
->num_env
) {
8980 logevent("All environment variables successfully set");
8981 } else if (s
->env_ok
== 0) {
8982 logevent("All environment variables refused");
8983 c_write_str(ssh
, "Server refused to set environment variables\r\n");
8985 logeventf(ssh
, "%d environment variables refused",
8986 s
->num_env
- s
->env_ok
);
8987 c_write_str(ssh
, "Server refused to set all environment variables\r\n");
8992 * Start a shell or a remote command. We may have to attempt
8993 * this twice if the config data has provided a second choice
8996 if (ssh
->mainchan
&& !ssh
->ncmode
) while (1) {
9000 if (ssh
->fallback_cmd
) {
9001 subsys
= ssh
->cfg
.ssh_subsys2
;
9002 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
9004 subsys
= ssh
->cfg
.ssh_subsys
;
9005 cmd
= ssh
->cfg
.remote_cmd_ptr
;
9006 if (!cmd
) cmd
= ssh
->cfg
.remote_cmd
;
9009 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
9010 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
); /* recipient channel */
9012 ssh2_pkt_addstring(s
->pktout
, "subsystem");
9013 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
9014 ssh2_pkt_addstring(s
->pktout
, cmd
);
9016 ssh2_pkt_addstring(s
->pktout
, "exec");
9017 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
9018 ssh2_pkt_addstring(s
->pktout
, cmd
);
9020 ssh2_pkt_addstring(s
->pktout
, "shell");
9021 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
9023 ssh2_pkt_send(ssh
, s
->pktout
);
9025 crWaitUntilV(pktin
);
9027 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
9028 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
9029 bombout(("Unexpected response to shell/command request:"
9030 " packet type %d", pktin
->type
));
9034 * We failed to start the command. If this is the
9035 * fallback command, we really are finished; if it's
9036 * not, and if the fallback command exists, try falling
9037 * back to it before complaining.
9039 if (!ssh
->fallback_cmd
&& ssh
->cfg
.remote_cmd_ptr2
!= NULL
) {
9040 logevent("Primary command failed; attempting fallback");
9041 ssh
->fallback_cmd
= TRUE
;
9044 bombout(("Server refused to start a shell/command"));
9047 logevent("Started a shell/command");
9052 ssh
->state
= SSH_STATE_SESSION
;
9053 if (ssh
->size_needed
)
9054 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
9055 if (ssh
->eof_needed
)
9056 ssh_special(ssh
, TS_EOF
);
9059 * All the initial channel requests are done, so install the default
9062 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_SUCCESS
] = ssh2_msg_channel_success
;
9063 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_FAILURE
] = ssh2_msg_channel_failure
;
9069 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
9074 s
->try_send
= FALSE
;
9078 * _All_ the connection-layer packets we expect to
9079 * receive are now handled by the dispatch table.
9080 * Anything that reaches here must be bogus.
9083 bombout(("Strange packet received: type %d", pktin
->type
));
9085 } else if (ssh
->mainchan
) {
9087 * We have spare data. Add it to the channel buffer.
9089 ssh2_add_channel_data(ssh
->mainchan
, (char *)in
, inlen
);
9094 struct ssh_channel
*c
;
9096 * Try to send data on all channels if we can.
9098 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++)
9099 ssh2_try_send_and_unthrottle(ssh
, c
);
9107 * Handlers for SSH-2 messages that might arrive at any moment.
9109 static void ssh2_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
9111 /* log reason code in disconnect message */
9115 reason
= ssh_pkt_getuint32(pktin
);
9116 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
9118 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
9119 buf
= dupprintf("Received disconnect message (%s)",
9120 ssh2_disconnect_reasons
[reason
]);
9122 buf
= dupprintf("Received disconnect message (unknown"
9123 " type %d)", reason
);
9127 buf
= dupprintf("Disconnection message text: %.*s",
9130 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
9132 (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) ?
9133 ssh2_disconnect_reasons
[reason
] : "unknown",
9138 static void ssh2_msg_debug(Ssh ssh
, struct Packet
*pktin
)
9140 /* log the debug message */
9144 /* XXX maybe we should actually take notice of the return value */
9145 ssh2_pkt_getbool(pktin
);
9146 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
9148 logeventf(ssh
, "Remote debug message: %.*s", msglen
, msg
);
9151 static void ssh2_msg_something_unimplemented(Ssh ssh
, struct Packet
*pktin
)
9153 struct Packet
*pktout
;
9154 pktout
= ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED
);
9155 ssh2_pkt_adduint32(pktout
, pktin
->sequence
);
9157 * UNIMPLEMENTED messages MUST appear in the same order as the
9158 * messages they respond to. Hence, never queue them.
9160 ssh2_pkt_send_noqueue(ssh
, pktout
);
9164 * Handle the top-level SSH-2 protocol.
9166 static void ssh2_protocol_setup(Ssh ssh
)
9171 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9173 for (i
= 0; i
< 256; i
++)
9174 ssh
->packet_dispatch
[i
] = ssh2_msg_something_unimplemented
;
9177 * Any message we actually understand, we set to NULL so that
9178 * the coroutines will get it.
9180 ssh
->packet_dispatch
[SSH2_MSG_UNIMPLEMENTED
] = NULL
;
9181 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_REQUEST
] = NULL
;
9182 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_ACCEPT
] = NULL
;
9183 ssh
->packet_dispatch
[SSH2_MSG_KEXINIT
] = NULL
;
9184 ssh
->packet_dispatch
[SSH2_MSG_NEWKEYS
] = NULL
;
9185 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_INIT
] = NULL
;
9186 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_REPLY
] = NULL
;
9187 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
9188 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
9189 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_INIT
] = NULL
;
9190 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_REPLY
] = NULL
;
9191 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_REQUEST
] = NULL
;
9192 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_FAILURE
] = NULL
;
9193 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_SUCCESS
] = NULL
;
9194 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] = NULL
;
9195 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_PK_OK
] = NULL
;
9196 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
9197 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
9198 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_INFO_RESPONSE
] = NULL
;
9199 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] = NULL
;
9200 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_SUCCESS
] = NULL
;
9201 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_FAILURE
] = NULL
;
9202 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] = NULL
;
9203 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] = NULL
;
9204 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] = NULL
;
9205 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] = NULL
;
9206 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] = NULL
;
9207 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] = NULL
;
9208 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = NULL
;
9209 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = NULL
;
9210 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_REQUEST
] = NULL
;
9211 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_SUCCESS
] = NULL
;
9212 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_FAILURE
] = NULL
;
9215 * These special message types we install handlers for.
9217 ssh
->packet_dispatch
[SSH2_MSG_DISCONNECT
] = ssh2_msg_disconnect
;
9218 ssh
->packet_dispatch
[SSH2_MSG_IGNORE
] = ssh_msg_ignore
; /* shared with SSH-1 */
9219 ssh
->packet_dispatch
[SSH2_MSG_DEBUG
] = ssh2_msg_debug
;
9222 static void ssh2_timer(void *ctx
, long now
)
9226 if (ssh
->state
== SSH_STATE_CLOSED
)
9229 if (!ssh
->kex_in_progress
&& ssh
->cfg
.ssh_rekey_time
!= 0 &&
9230 now
- ssh
->next_rekey
>= 0) {
9231 do_ssh2_transport(ssh
, "timeout", -1, NULL
);
9235 static void ssh2_protocol(Ssh ssh
, void *vin
, int inlen
,
9236 struct Packet
*pktin
)
9238 unsigned char *in
= (unsigned char *)vin
;
9239 if (ssh
->state
== SSH_STATE_CLOSED
)
9243 ssh
->incoming_data_size
+= pktin
->encrypted_len
;
9244 if (!ssh
->kex_in_progress
&&
9245 ssh
->max_data_size
!= 0 &&
9246 ssh
->incoming_data_size
> ssh
->max_data_size
)
9247 do_ssh2_transport(ssh
, "too much data received", -1, NULL
);
9250 if (pktin
&& ssh
->packet_dispatch
[pktin
->type
]) {
9251 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
9255 if (!ssh
->protocol_initial_phase_done
||
9256 (pktin
&& pktin
->type
>= 20 && pktin
->type
< 50)) {
9257 if (do_ssh2_transport(ssh
, in
, inlen
, pktin
) &&
9258 !ssh
->protocol_initial_phase_done
) {
9259 ssh
->protocol_initial_phase_done
= TRUE
;
9261 * Allow authconn to initialise itself.
9263 do_ssh2_authconn(ssh
, NULL
, 0, NULL
);
9266 do_ssh2_authconn(ssh
, in
, inlen
, pktin
);
9271 * Called to set up the connection.
9273 * Returns an error message, or NULL on success.
9275 static const char *ssh_init(void *frontend_handle
, void **backend_handle
,
9277 char *host
, int port
, char **realhost
, int nodelay
,
9283 ssh
= snew(struct ssh_tag
);
9284 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
9285 ssh
->version
= 0; /* when not ready yet */
9288 ssh
->v1_cipher_ctx
= NULL
;
9289 ssh
->crcda_ctx
= NULL
;
9290 ssh
->cscipher
= NULL
;
9291 ssh
->cs_cipher_ctx
= NULL
;
9292 ssh
->sccipher
= NULL
;
9293 ssh
->sc_cipher_ctx
= NULL
;
9295 ssh
->cs_mac_ctx
= NULL
;
9297 ssh
->sc_mac_ctx
= NULL
;
9299 ssh
->cs_comp_ctx
= NULL
;
9301 ssh
->sc_comp_ctx
= NULL
;
9303 ssh
->kex_ctx
= NULL
;
9304 ssh
->hostkey
= NULL
;
9306 ssh
->close_expected
= FALSE
;
9307 ssh
->clean_exit
= FALSE
;
9308 ssh
->state
= SSH_STATE_PREPACKET
;
9309 ssh
->size_needed
= FALSE
;
9310 ssh
->eof_needed
= FALSE
;
9313 ssh
->deferred_send_data
= NULL
;
9314 ssh
->deferred_len
= 0;
9315 ssh
->deferred_size
= 0;
9316 ssh
->fallback_cmd
= 0;
9317 ssh
->pkt_kctx
= SSH2_PKTCTX_NOKEX
;
9318 ssh
->pkt_actx
= SSH2_PKTCTX_NOAUTH
;
9319 ssh
->x11disp
= NULL
;
9320 ssh
->v1_compressing
= FALSE
;
9321 ssh
->v2_outgoing_sequence
= 0;
9322 ssh
->ssh1_rdpkt_crstate
= 0;
9323 ssh
->ssh2_rdpkt_crstate
= 0;
9324 ssh
->do_ssh_init_crstate
= 0;
9325 ssh
->ssh_gotdata_crstate
= 0;
9326 ssh
->do_ssh1_connection_crstate
= 0;
9327 ssh
->do_ssh1_login_crstate
= 0;
9328 ssh
->do_ssh2_transport_crstate
= 0;
9329 ssh
->do_ssh2_authconn_crstate
= 0;
9330 ssh
->do_ssh_init_state
= NULL
;
9331 ssh
->do_ssh1_login_state
= NULL
;
9332 ssh
->do_ssh2_transport_state
= NULL
;
9333 ssh
->do_ssh2_authconn_state
= NULL
;
9336 ssh
->mainchan
= NULL
;
9337 ssh
->throttled_all
= 0;
9338 ssh
->v1_stdout_throttling
= 0;
9340 ssh
->queuelen
= ssh
->queuesize
= 0;
9341 ssh
->queueing
= FALSE
;
9342 ssh
->qhead
= ssh
->qtail
= NULL
;
9343 ssh
->deferred_rekey_reason
= NULL
;
9344 bufchain_init(&ssh
->queued_incoming_data
);
9345 ssh
->frozen
= FALSE
;
9347 *backend_handle
= ssh
;
9350 if (crypto_startup() == 0)
9351 return "Microsoft high encryption pack not installed!";
9354 ssh
->frontend
= frontend_handle
;
9355 ssh
->term_width
= ssh
->cfg
.width
;
9356 ssh
->term_height
= ssh
->cfg
.height
;
9358 ssh
->channels
= NULL
;
9359 ssh
->rportfwds
= NULL
;
9360 ssh
->portfwds
= NULL
;
9365 ssh
->conn_throttle_count
= 0;
9366 ssh
->overall_bufsize
= 0;
9367 ssh
->fallback_cmd
= 0;
9369 ssh
->protocol
= NULL
;
9371 ssh
->protocol_initial_phase_done
= FALSE
;
9375 ssh
->incoming_data_size
= ssh
->outgoing_data_size
=
9376 ssh
->deferred_data_size
= 0L;
9377 ssh
->max_data_size
= parse_blocksize(ssh
->cfg
.ssh_rekey_data
);
9378 ssh
->kex_in_progress
= FALSE
;
9381 ssh
->gsslibs
= NULL
;
9384 p
= connect_to_host(ssh
, host
, port
, realhost
, nodelay
, keepalive
);
9393 static void ssh_free(void *handle
)
9395 Ssh ssh
= (Ssh
) handle
;
9396 struct ssh_channel
*c
;
9397 struct ssh_rportfwd
*pf
;
9399 if (ssh
->v1_cipher_ctx
)
9400 ssh
->cipher
->free_context(ssh
->v1_cipher_ctx
);
9401 if (ssh
->cs_cipher_ctx
)
9402 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
9403 if (ssh
->sc_cipher_ctx
)
9404 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
9405 if (ssh
->cs_mac_ctx
)
9406 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
9407 if (ssh
->sc_mac_ctx
)
9408 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
9409 if (ssh
->cs_comp_ctx
) {
9411 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
9413 zlib_compress_cleanup(ssh
->cs_comp_ctx
);
9415 if (ssh
->sc_comp_ctx
) {
9417 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
9419 zlib_decompress_cleanup(ssh
->sc_comp_ctx
);
9422 dh_cleanup(ssh
->kex_ctx
);
9423 sfree(ssh
->savedhost
);
9425 while (ssh
->queuelen
-- > 0)
9426 ssh_free_packet(ssh
->queue
[ssh
->queuelen
]);
9429 while (ssh
->qhead
) {
9430 struct queued_handler
*qh
= ssh
->qhead
;
9431 ssh
->qhead
= qh
->next
;
9434 ssh
->qhead
= ssh
->qtail
= NULL
;
9436 if (ssh
->channels
) {
9437 while ((c
= delpos234(ssh
->channels
, 0)) != NULL
) {
9440 if (c
->u
.x11
.s
!= NULL
)
9441 x11_close(c
->u
.x11
.s
);
9444 case CHAN_SOCKDATA_DORMANT
:
9445 if (c
->u
.pfd
.s
!= NULL
)
9446 pfd_close(c
->u
.pfd
.s
);
9451 freetree234(ssh
->channels
);
9452 ssh
->channels
= NULL
;
9455 if (ssh
->rportfwds
) {
9456 while ((pf
= delpos234(ssh
->rportfwds
, 0)) != NULL
)
9458 freetree234(ssh
->rportfwds
);
9459 ssh
->rportfwds
= NULL
;
9461 sfree(ssh
->deferred_send_data
);
9463 x11_free_display(ssh
->x11disp
);
9464 sfree(ssh
->do_ssh_init_state
);
9465 sfree(ssh
->do_ssh1_login_state
);
9466 sfree(ssh
->do_ssh2_transport_state
);
9467 sfree(ssh
->do_ssh2_authconn_state
);
9470 sfree(ssh
->fullhostname
);
9471 if (ssh
->crcda_ctx
) {
9472 crcda_free_context(ssh
->crcda_ctx
);
9473 ssh
->crcda_ctx
= NULL
;
9476 ssh_do_close(ssh
, TRUE
);
9477 expire_timer_context(ssh
);
9479 pinger_free(ssh
->pinger
);
9480 bufchain_clear(&ssh
->queued_incoming_data
);
9483 ssh_gss_cleanup(ssh
->gsslibs
);
9491 * Reconfigure the SSH backend.
9493 static void ssh_reconfig(void *handle
, Config
*cfg
)
9495 Ssh ssh
= (Ssh
) handle
;
9496 char *rekeying
= NULL
, rekey_mandatory
= FALSE
;
9497 unsigned long old_max_data_size
;
9499 pinger_reconfig(ssh
->pinger
, &ssh
->cfg
, cfg
);
9501 ssh_setup_portfwd(ssh
, cfg
);
9503 if (ssh
->cfg
.ssh_rekey_time
!= cfg
->ssh_rekey_time
&&
9504 cfg
->ssh_rekey_time
!= 0) {
9505 long new_next
= ssh
->last_rekey
+ cfg
->ssh_rekey_time
*60*TICKSPERSEC
;
9506 long now
= GETTICKCOUNT();
9508 if (new_next
- now
< 0) {
9509 rekeying
= "timeout shortened";
9511 ssh
->next_rekey
= schedule_timer(new_next
- now
, ssh2_timer
, ssh
);
9515 old_max_data_size
= ssh
->max_data_size
;
9516 ssh
->max_data_size
= parse_blocksize(cfg
->ssh_rekey_data
);
9517 if (old_max_data_size
!= ssh
->max_data_size
&&
9518 ssh
->max_data_size
!= 0) {
9519 if (ssh
->outgoing_data_size
> ssh
->max_data_size
||
9520 ssh
->incoming_data_size
> ssh
->max_data_size
)
9521 rekeying
= "data limit lowered";
9524 if (ssh
->cfg
.compression
!= cfg
->compression
) {
9525 rekeying
= "compression setting changed";
9526 rekey_mandatory
= TRUE
;
9529 if (ssh
->cfg
.ssh2_des_cbc
!= cfg
->ssh2_des_cbc
||
9530 memcmp(ssh
->cfg
.ssh_cipherlist
, cfg
->ssh_cipherlist
,
9531 sizeof(ssh
->cfg
.ssh_cipherlist
))) {
9532 rekeying
= "cipher settings changed";
9533 rekey_mandatory
= TRUE
;
9536 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
9539 if (!ssh
->kex_in_progress
) {
9540 do_ssh2_transport(ssh
, rekeying
, -1, NULL
);
9541 } else if (rekey_mandatory
) {
9542 ssh
->deferred_rekey_reason
= rekeying
;
9548 * Called to send data down the SSH connection.
9550 static int ssh_send(void *handle
, char *buf
, int len
)
9552 Ssh ssh
= (Ssh
) handle
;
9554 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
9557 ssh
->protocol(ssh
, (unsigned char *)buf
, len
, 0);
9559 return ssh_sendbuffer(ssh
);
9563 * Called to query the current amount of buffered stdin data.
9565 static int ssh_sendbuffer(void *handle
)
9567 Ssh ssh
= (Ssh
) handle
;
9570 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
9574 * If the SSH socket itself has backed up, add the total backup
9575 * size on that to any individual buffer on the stdin channel.
9578 if (ssh
->throttled_all
)
9579 override_value
= ssh
->overall_bufsize
;
9581 if (ssh
->version
== 1) {
9582 return override_value
;
9583 } else if (ssh
->version
== 2) {
9584 if (!ssh
->mainchan
|| ssh
->mainchan
->closes
> 0)
9585 return override_value
;
9587 return (override_value
+
9588 bufchain_size(&ssh
->mainchan
->v
.v2
.outbuffer
));
9595 * Called to set the size of the window from SSH's POV.
9597 static void ssh_size(void *handle
, int width
, int height
)
9599 Ssh ssh
= (Ssh
) handle
;
9600 struct Packet
*pktout
;
9602 ssh
->term_width
= width
;
9603 ssh
->term_height
= height
;
9605 switch (ssh
->state
) {
9606 case SSH_STATE_BEFORE_SIZE
:
9607 case SSH_STATE_PREPACKET
:
9608 case SSH_STATE_CLOSED
:
9609 break; /* do nothing */
9610 case SSH_STATE_INTERMED
:
9611 ssh
->size_needed
= TRUE
; /* buffer for later */
9613 case SSH_STATE_SESSION
:
9614 if (!ssh
->cfg
.nopty
) {
9615 if (ssh
->version
== 1) {
9616 send_packet(ssh
, SSH1_CMSG_WINDOW_SIZE
,
9617 PKT_INT
, ssh
->term_height
,
9618 PKT_INT
, ssh
->term_width
,
9619 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
9620 } else if (ssh
->mainchan
) {
9621 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
9622 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
9623 ssh2_pkt_addstring(pktout
, "window-change");
9624 ssh2_pkt_addbool(pktout
, 0);
9625 ssh2_pkt_adduint32(pktout
, ssh
->term_width
);
9626 ssh2_pkt_adduint32(pktout
, ssh
->term_height
);
9627 ssh2_pkt_adduint32(pktout
, 0);
9628 ssh2_pkt_adduint32(pktout
, 0);
9629 ssh2_pkt_send(ssh
, pktout
);
9637 * Return a list of the special codes that make sense in this
9640 static const struct telnet_special
*ssh_get_specials(void *handle
)
9642 static const struct telnet_special ssh1_ignore_special
[] = {
9643 {"IGNORE message", TS_NOP
}
9645 static const struct telnet_special ssh2_ignore_special
[] = {
9646 {"IGNORE message", TS_NOP
},
9648 static const struct telnet_special ssh2_rekey_special
[] = {
9649 {"Repeat key exchange", TS_REKEY
},
9651 static const struct telnet_special ssh2_session_specials
[] = {
9654 /* These are the signal names defined by RFC 4254.
9655 * They include all the ISO C signals, but are a subset of the POSIX
9656 * required signals. */
9657 {"SIGINT (Interrupt)", TS_SIGINT
},
9658 {"SIGTERM (Terminate)", TS_SIGTERM
},
9659 {"SIGKILL (Kill)", TS_SIGKILL
},
9660 {"SIGQUIT (Quit)", TS_SIGQUIT
},
9661 {"SIGHUP (Hangup)", TS_SIGHUP
},
9662 {"More signals", TS_SUBMENU
},
9663 {"SIGABRT", TS_SIGABRT
}, {"SIGALRM", TS_SIGALRM
},
9664 {"SIGFPE", TS_SIGFPE
}, {"SIGILL", TS_SIGILL
},
9665 {"SIGPIPE", TS_SIGPIPE
}, {"SIGSEGV", TS_SIGSEGV
},
9666 {"SIGUSR1", TS_SIGUSR1
}, {"SIGUSR2", TS_SIGUSR2
},
9669 static const struct telnet_special specials_end
[] = {
9672 /* XXX review this length for any changes: */
9673 static struct telnet_special ssh_specials
[lenof(ssh2_ignore_special
) +
9674 lenof(ssh2_rekey_special
) +
9675 lenof(ssh2_session_specials
) +
9676 lenof(specials_end
)];
9677 Ssh ssh
= (Ssh
) handle
;
9679 #define ADD_SPECIALS(name) \
9681 assert((i + lenof(name)) <= lenof(ssh_specials)); \
9682 memcpy(&ssh_specials[i], name, sizeof name); \
9686 if (ssh
->version
== 1) {
9687 /* Don't bother offering IGNORE if we've decided the remote
9688 * won't cope with it, since we wouldn't bother sending it if
9690 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
9691 ADD_SPECIALS(ssh1_ignore_special
);
9692 } else if (ssh
->version
== 2) {
9693 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH2_IGNORE
))
9694 ADD_SPECIALS(ssh2_ignore_special
);
9695 if (!(ssh
->remote_bugs
& BUG_SSH2_REKEY
))
9696 ADD_SPECIALS(ssh2_rekey_special
);
9698 ADD_SPECIALS(ssh2_session_specials
);
9699 } /* else we're not ready yet */
9702 ADD_SPECIALS(specials_end
);
9703 return ssh_specials
;
9711 * Send special codes. TS_EOF is useful for `plink', so you
9712 * can send an EOF and collect resulting output (e.g. `plink
9715 static void ssh_special(void *handle
, Telnet_Special code
)
9717 Ssh ssh
= (Ssh
) handle
;
9718 struct Packet
*pktout
;
9720 if (code
== TS_EOF
) {
9721 if (ssh
->state
!= SSH_STATE_SESSION
) {
9723 * Buffer the EOF in case we are pre-SESSION, so we can
9724 * send it as soon as we reach SESSION.
9727 ssh
->eof_needed
= TRUE
;
9730 if (ssh
->version
== 1) {
9731 send_packet(ssh
, SSH1_CMSG_EOF
, PKT_END
);
9732 } else if (ssh
->mainchan
) {
9733 struct Packet
*pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
9734 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
9735 ssh2_pkt_send(ssh
, pktout
);
9736 ssh
->send_ok
= 0; /* now stop trying to read from stdin */
9738 logevent("Sent EOF message");
9739 } else if (code
== TS_PING
|| code
== TS_NOP
) {
9740 if (ssh
->state
== SSH_STATE_CLOSED
9741 || ssh
->state
== SSH_STATE_PREPACKET
) return;
9742 if (ssh
->version
== 1) {
9743 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
9744 send_packet(ssh
, SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
9746 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH2_IGNORE
)) {
9747 pktout
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
9748 ssh2_pkt_addstring_start(pktout
);
9749 ssh2_pkt_send_noqueue(ssh
, pktout
);
9752 } else if (code
== TS_REKEY
) {
9753 if (!ssh
->kex_in_progress
&& ssh
->version
== 2) {
9754 do_ssh2_transport(ssh
, "at user request", -1, NULL
);
9756 } else if (code
== TS_BRK
) {
9757 if (ssh
->state
== SSH_STATE_CLOSED
9758 || ssh
->state
== SSH_STATE_PREPACKET
) return;
9759 if (ssh
->version
== 1) {
9760 logevent("Unable to send BREAK signal in SSH-1");
9761 } else if (ssh
->mainchan
) {
9762 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
9763 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
9764 ssh2_pkt_addstring(pktout
, "break");
9765 ssh2_pkt_addbool(pktout
, 0);
9766 ssh2_pkt_adduint32(pktout
, 0); /* default break length */
9767 ssh2_pkt_send(ssh
, pktout
);
9770 /* Is is a POSIX signal? */
9771 char *signame
= NULL
;
9772 if (code
== TS_SIGABRT
) signame
= "ABRT";
9773 if (code
== TS_SIGALRM
) signame
= "ALRM";
9774 if (code
== TS_SIGFPE
) signame
= "FPE";
9775 if (code
== TS_SIGHUP
) signame
= "HUP";
9776 if (code
== TS_SIGILL
) signame
= "ILL";
9777 if (code
== TS_SIGINT
) signame
= "INT";
9778 if (code
== TS_SIGKILL
) signame
= "KILL";
9779 if (code
== TS_SIGPIPE
) signame
= "PIPE";
9780 if (code
== TS_SIGQUIT
) signame
= "QUIT";
9781 if (code
== TS_SIGSEGV
) signame
= "SEGV";
9782 if (code
== TS_SIGTERM
) signame
= "TERM";
9783 if (code
== TS_SIGUSR1
) signame
= "USR1";
9784 if (code
== TS_SIGUSR2
) signame
= "USR2";
9785 /* The SSH-2 protocol does in principle support arbitrary named
9786 * signals, including signame@domain, but we don't support those. */
9788 /* It's a signal. */
9789 if (ssh
->version
== 2 && ssh
->mainchan
) {
9790 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
9791 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
9792 ssh2_pkt_addstring(pktout
, "signal");
9793 ssh2_pkt_addbool(pktout
, 0);
9794 ssh2_pkt_addstring(pktout
, signame
);
9795 ssh2_pkt_send(ssh
, pktout
);
9796 logeventf(ssh
, "Sent signal SIG%s", signame
);
9799 /* Never heard of it. Do nothing */
9804 void *new_sock_channel(void *handle
, Socket s
)
9806 Ssh ssh
= (Ssh
) handle
;
9807 struct ssh_channel
*c
;
9808 c
= snew(struct ssh_channel
);
9811 ssh2_channel_init(c
);
9813 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
9815 add234(ssh
->channels
, c
);
9820 * This is called when stdout/stderr (the entity to which
9821 * from_backend sends data) manages to clear some backlog.
9823 static void ssh_unthrottle(void *handle
, int bufsize
)
9825 Ssh ssh
= (Ssh
) handle
;
9828 if (ssh
->version
== 1) {
9829 if (ssh
->v1_stdout_throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
9830 ssh
->v1_stdout_throttling
= 0;
9831 ssh_throttle_conn(ssh
, -1);
9834 if (ssh
->mainchan
) {
9835 ssh2_set_window(ssh
->mainchan
,
9836 bufsize
< ssh
->mainchan
->v
.v2
.locmaxwin ?
9837 ssh
->mainchan
->v
.v2
.locmaxwin
- bufsize
: 0);
9838 if (ssh
->cfg
.ssh_simple
)
9841 buflimit
= ssh
->mainchan
->v
.v2
.locmaxwin
;
9842 if (ssh
->mainchan
->throttling_conn
&& bufsize
<= buflimit
) {
9843 ssh
->mainchan
->throttling_conn
= 0;
9844 ssh_throttle_conn(ssh
, -1);
9850 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
9852 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
9854 struct Packet
*pktout
;
9856 logeventf(ssh
, "Opening forwarded connection to %s:%d", hostname
, port
);
9858 if (ssh
->version
== 1) {
9859 send_packet(ssh
, SSH1_MSG_PORT_OPEN
,
9860 PKT_INT
, c
->localid
,
9863 /* PKT_STR, <org:orgport>, */
9866 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
9867 ssh2_pkt_addstring(pktout
, "direct-tcpip");
9868 ssh2_pkt_adduint32(pktout
, c
->localid
);
9869 ssh2_pkt_adduint32(pktout
, c
->v
.v2
.locwindow
);/* our window size */
9870 ssh2_pkt_adduint32(pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
9871 ssh2_pkt_addstring(pktout
, hostname
);
9872 ssh2_pkt_adduint32(pktout
, port
);
9874 * We make up values for the originator data; partly it's
9875 * too much hassle to keep track, and partly I'm not
9876 * convinced the server should be told details like that
9877 * about my local network configuration.
9878 * The "originator IP address" is syntactically a numeric
9879 * IP address, and some servers (e.g., Tectia) get upset
9880 * if it doesn't match this syntax.
9882 ssh2_pkt_addstring(pktout
, "0.0.0.0");
9883 ssh2_pkt_adduint32(pktout
, 0);
9884 ssh2_pkt_send(ssh
, pktout
);
9888 static int ssh_connected(void *handle
)
9890 Ssh ssh
= (Ssh
) handle
;
9891 return ssh
->s
!= NULL
;
9894 static int ssh_sendok(void *handle
)
9896 Ssh ssh
= (Ssh
) handle
;
9897 return ssh
->send_ok
;
9900 static int ssh_ldisc(void *handle
, int option
)
9902 Ssh ssh
= (Ssh
) handle
;
9903 if (option
== LD_ECHO
)
9904 return ssh
->echoing
;
9905 if (option
== LD_EDIT
)
9906 return ssh
->editing
;
9910 static void ssh_provide_ldisc(void *handle
, void *ldisc
)
9912 Ssh ssh
= (Ssh
) handle
;
9916 static void ssh_provide_logctx(void *handle
, void *logctx
)
9918 Ssh ssh
= (Ssh
) handle
;
9919 ssh
->logctx
= logctx
;
9922 static int ssh_return_exitcode(void *handle
)
9924 Ssh ssh
= (Ssh
) handle
;
9928 return (ssh
->exitcode
>= 0 ? ssh
->exitcode
: INT_MAX
);
9932 * cfg_info for SSH is the currently running version of the
9933 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
9935 static int ssh_cfg_info(void *handle
)
9937 Ssh ssh
= (Ssh
) handle
;
9938 return ssh
->version
;
9942 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
9943 * that fails. This variable is the means by which scp.c can reach
9944 * into the SSH code and find out which one it got.
9946 extern int ssh_fallback_cmd(void *handle
)
9948 Ssh ssh
= (Ssh
) handle
;
9949 return ssh
->fallback_cmd
;
9952 Backend ssh_backend
= {
9962 ssh_return_exitcode
,