23 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
24 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
25 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
26 #define SSH1_CMSG_USER 4 /* 0x4 */
27 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
28 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
29 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
30 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
31 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
32 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
33 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
34 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
35 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
36 #define SSH1_SMSG_FAILURE 15 /* 0xf */
37 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
38 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
39 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
40 #define SSH1_CMSG_EOF 19 /* 0x13 */
41 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
42 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
43 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
44 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
45 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
46 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
47 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
48 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
49 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
50 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
51 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
52 #define SSH1_MSG_IGNORE 32 /* 0x20 */
53 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
54 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
55 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
56 #define SSH1_MSG_DEBUG 36 /* 0x24 */
57 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
58 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
59 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
60 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
61 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
62 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
63 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
65 #define SSH1_AUTH_TIS 5 /* 0x5 */
66 #define SSH1_AUTH_CCARD 16 /* 0x10 */
68 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
69 /* Mask for protoflags we will echo back to server if seen */
70 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
72 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
73 #define SSH2_MSG_IGNORE 2 /* 0x2 */
74 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
75 #define SSH2_MSG_DEBUG 4 /* 0x4 */
76 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
77 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
78 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
79 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
80 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
81 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
82 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
83 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
84 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
85 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
86 #define SSH2_MSG_KEXRSA_PUBKEY 30 /* 0x1e */
87 #define SSH2_MSG_KEXRSA_SECRET 31 /* 0x1f */
88 #define SSH2_MSG_KEXRSA_DONE 32 /* 0x20 */
89 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
90 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
91 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
92 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
93 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
94 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
95 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
96 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
97 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
98 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
99 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
100 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
101 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
102 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
103 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
104 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
105 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
106 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
107 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
108 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
109 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
110 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
113 * Packet type contexts, so that ssh2_pkt_type can correctly decode
114 * the ambiguous type numbers back into the correct type strings.
116 #define SSH2_PKTCTX_DHGROUP 0x0001
117 #define SSH2_PKTCTX_DHGEX 0x0002
118 #define SSH2_PKTCTX_RSAKEX 0x0004
119 #define SSH2_PKTCTX_KEX_MASK 0x000F
120 #define SSH2_PKTCTX_PUBLICKEY 0x0010
121 #define SSH2_PKTCTX_PASSWORD 0x0020
122 #define SSH2_PKTCTX_KBDINTER 0x0040
123 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
125 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
126 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
127 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
128 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
129 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
130 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
131 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
132 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
133 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
134 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
135 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
136 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
137 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
138 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
139 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
141 static const char *const ssh2_disconnect_reasons
[] = {
143 "host not allowed to connect",
145 "key exchange failed",
146 "host authentication failed",
149 "service not available",
150 "protocol version not supported",
151 "host key not verifiable",
154 "too many connections",
155 "auth cancelled by user",
156 "no more auth methods available",
160 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
161 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
162 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
163 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
165 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
168 * Various remote-bug flags.
170 #define BUG_CHOKES_ON_SSH1_IGNORE 1
171 #define BUG_SSH2_HMAC 2
172 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
173 #define BUG_CHOKES_ON_RSA 8
174 #define BUG_SSH2_RSA_PADDING 16
175 #define BUG_SSH2_DERIVEKEY 32
176 #define BUG_SSH2_REKEY 64
177 #define BUG_SSH2_PK_SESSIONID 128
180 * Codes for terminal modes.
181 * Most of these are the same in SSH-1 and SSH-2.
182 * This list is derived from draft-ietf-secsh-connect-25 and
185 static const struct {
186 const char* const mode
;
188 enum { TTY_OP_CHAR
, TTY_OP_BOOL
} type
;
190 /* "V" prefix discarded for special characters relative to SSH specs */
191 { "INTR", 1, TTY_OP_CHAR
},
192 { "QUIT", 2, TTY_OP_CHAR
},
193 { "ERASE", 3, TTY_OP_CHAR
},
194 { "KILL", 4, TTY_OP_CHAR
},
195 { "EOF", 5, TTY_OP_CHAR
},
196 { "EOL", 6, TTY_OP_CHAR
},
197 { "EOL2", 7, TTY_OP_CHAR
},
198 { "START", 8, TTY_OP_CHAR
},
199 { "STOP", 9, TTY_OP_CHAR
},
200 { "SUSP", 10, TTY_OP_CHAR
},
201 { "DSUSP", 11, TTY_OP_CHAR
},
202 { "REPRINT", 12, TTY_OP_CHAR
},
203 { "WERASE", 13, TTY_OP_CHAR
},
204 { "LNEXT", 14, TTY_OP_CHAR
},
205 { "FLUSH", 15, TTY_OP_CHAR
},
206 { "SWTCH", 16, TTY_OP_CHAR
},
207 { "STATUS", 17, TTY_OP_CHAR
},
208 { "DISCARD", 18, TTY_OP_CHAR
},
209 { "IGNPAR", 30, TTY_OP_BOOL
},
210 { "PARMRK", 31, TTY_OP_BOOL
},
211 { "INPCK", 32, TTY_OP_BOOL
},
212 { "ISTRIP", 33, TTY_OP_BOOL
},
213 { "INLCR", 34, TTY_OP_BOOL
},
214 { "IGNCR", 35, TTY_OP_BOOL
},
215 { "ICRNL", 36, TTY_OP_BOOL
},
216 { "IUCLC", 37, TTY_OP_BOOL
},
217 { "IXON", 38, TTY_OP_BOOL
},
218 { "IXANY", 39, TTY_OP_BOOL
},
219 { "IXOFF", 40, TTY_OP_BOOL
},
220 { "IMAXBEL", 41, TTY_OP_BOOL
},
221 { "ISIG", 50, TTY_OP_BOOL
},
222 { "ICANON", 51, TTY_OP_BOOL
},
223 { "XCASE", 52, TTY_OP_BOOL
},
224 { "ECHO", 53, TTY_OP_BOOL
},
225 { "ECHOE", 54, TTY_OP_BOOL
},
226 { "ECHOK", 55, TTY_OP_BOOL
},
227 { "ECHONL", 56, TTY_OP_BOOL
},
228 { "NOFLSH", 57, TTY_OP_BOOL
},
229 { "TOSTOP", 58, TTY_OP_BOOL
},
230 { "IEXTEN", 59, TTY_OP_BOOL
},
231 { "ECHOCTL", 60, TTY_OP_BOOL
},
232 { "ECHOKE", 61, TTY_OP_BOOL
},
233 { "PENDIN", 62, TTY_OP_BOOL
}, /* XXX is this a real mode? */
234 { "OPOST", 70, TTY_OP_BOOL
},
235 { "OLCUC", 71, TTY_OP_BOOL
},
236 { "ONLCR", 72, TTY_OP_BOOL
},
237 { "OCRNL", 73, TTY_OP_BOOL
},
238 { "ONOCR", 74, TTY_OP_BOOL
},
239 { "ONLRET", 75, TTY_OP_BOOL
},
240 { "CS7", 90, TTY_OP_BOOL
},
241 { "CS8", 91, TTY_OP_BOOL
},
242 { "PARENB", 92, TTY_OP_BOOL
},
243 { "PARODD", 93, TTY_OP_BOOL
}
246 /* Miscellaneous other tty-related constants. */
247 #define SSH_TTY_OP_END 0
248 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
249 #define SSH1_TTY_OP_ISPEED 192
250 #define SSH1_TTY_OP_OSPEED 193
251 #define SSH2_TTY_OP_ISPEED 128
252 #define SSH2_TTY_OP_OSPEED 129
254 /* Helper functions for parsing tty-related config. */
255 static unsigned int ssh_tty_parse_specchar(char *s
)
260 ret
= ctrlparse(s
, &next
);
261 if (!next
) ret
= s
[0];
263 ret
= 255; /* special value meaning "don't set" */
267 static unsigned int ssh_tty_parse_boolean(char *s
)
269 if (stricmp(s
, "yes") == 0 ||
270 stricmp(s
, "on") == 0 ||
271 stricmp(s
, "true") == 0 ||
272 stricmp(s
, "+") == 0)
274 else if (stricmp(s
, "no") == 0 ||
275 stricmp(s
, "off") == 0 ||
276 stricmp(s
, "false") == 0 ||
277 stricmp(s
, "-") == 0)
278 return 0; /* false */
280 return (atoi(s
) != 0);
283 #define translate(x) if (type == x) return #x
284 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
285 static char *ssh1_pkt_type(int type
)
287 translate(SSH1_MSG_DISCONNECT
);
288 translate(SSH1_SMSG_PUBLIC_KEY
);
289 translate(SSH1_CMSG_SESSION_KEY
);
290 translate(SSH1_CMSG_USER
);
291 translate(SSH1_CMSG_AUTH_RSA
);
292 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE
);
293 translate(SSH1_CMSG_AUTH_RSA_RESPONSE
);
294 translate(SSH1_CMSG_AUTH_PASSWORD
);
295 translate(SSH1_CMSG_REQUEST_PTY
);
296 translate(SSH1_CMSG_WINDOW_SIZE
);
297 translate(SSH1_CMSG_EXEC_SHELL
);
298 translate(SSH1_CMSG_EXEC_CMD
);
299 translate(SSH1_SMSG_SUCCESS
);
300 translate(SSH1_SMSG_FAILURE
);
301 translate(SSH1_CMSG_STDIN_DATA
);
302 translate(SSH1_SMSG_STDOUT_DATA
);
303 translate(SSH1_SMSG_STDERR_DATA
);
304 translate(SSH1_CMSG_EOF
);
305 translate(SSH1_SMSG_EXIT_STATUS
);
306 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
);
307 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE
);
308 translate(SSH1_MSG_CHANNEL_DATA
);
309 translate(SSH1_MSG_CHANNEL_CLOSE
);
310 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
);
311 translate(SSH1_SMSG_X11_OPEN
);
312 translate(SSH1_CMSG_PORT_FORWARD_REQUEST
);
313 translate(SSH1_MSG_PORT_OPEN
);
314 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING
);
315 translate(SSH1_SMSG_AGENT_OPEN
);
316 translate(SSH1_MSG_IGNORE
);
317 translate(SSH1_CMSG_EXIT_CONFIRMATION
);
318 translate(SSH1_CMSG_X11_REQUEST_FORWARDING
);
319 translate(SSH1_CMSG_AUTH_RHOSTS_RSA
);
320 translate(SSH1_MSG_DEBUG
);
321 translate(SSH1_CMSG_REQUEST_COMPRESSION
);
322 translate(SSH1_CMSG_AUTH_TIS
);
323 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE
);
324 translate(SSH1_CMSG_AUTH_TIS_RESPONSE
);
325 translate(SSH1_CMSG_AUTH_CCARD
);
326 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE
);
327 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE
);
330 static char *ssh2_pkt_type(int pkt_ctx
, int type
)
332 translate(SSH2_MSG_DISCONNECT
);
333 translate(SSH2_MSG_IGNORE
);
334 translate(SSH2_MSG_UNIMPLEMENTED
);
335 translate(SSH2_MSG_DEBUG
);
336 translate(SSH2_MSG_SERVICE_REQUEST
);
337 translate(SSH2_MSG_SERVICE_ACCEPT
);
338 translate(SSH2_MSG_KEXINIT
);
339 translate(SSH2_MSG_NEWKEYS
);
340 translatec(SSH2_MSG_KEXDH_INIT
, SSH2_PKTCTX_DHGROUP
);
341 translatec(SSH2_MSG_KEXDH_REPLY
, SSH2_PKTCTX_DHGROUP
);
342 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST
, SSH2_PKTCTX_DHGEX
);
343 translatec(SSH2_MSG_KEX_DH_GEX_GROUP
, SSH2_PKTCTX_DHGEX
);
344 translatec(SSH2_MSG_KEX_DH_GEX_INIT
, SSH2_PKTCTX_DHGEX
);
345 translatec(SSH2_MSG_KEX_DH_GEX_REPLY
, SSH2_PKTCTX_DHGEX
);
346 translatec(SSH2_MSG_KEXRSA_PUBKEY
, SSH2_PKTCTX_RSAKEX
);
347 translatec(SSH2_MSG_KEXRSA_SECRET
, SSH2_PKTCTX_RSAKEX
);
348 translatec(SSH2_MSG_KEXRSA_DONE
, SSH2_PKTCTX_RSAKEX
);
349 translate(SSH2_MSG_USERAUTH_REQUEST
);
350 translate(SSH2_MSG_USERAUTH_FAILURE
);
351 translate(SSH2_MSG_USERAUTH_SUCCESS
);
352 translate(SSH2_MSG_USERAUTH_BANNER
);
353 translatec(SSH2_MSG_USERAUTH_PK_OK
, SSH2_PKTCTX_PUBLICKEY
);
354 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
, SSH2_PKTCTX_PASSWORD
);
355 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST
, SSH2_PKTCTX_KBDINTER
);
356 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE
, SSH2_PKTCTX_KBDINTER
);
357 translate(SSH2_MSG_GLOBAL_REQUEST
);
358 translate(SSH2_MSG_REQUEST_SUCCESS
);
359 translate(SSH2_MSG_REQUEST_FAILURE
);
360 translate(SSH2_MSG_CHANNEL_OPEN
);
361 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
362 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
363 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
364 translate(SSH2_MSG_CHANNEL_DATA
);
365 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA
);
366 translate(SSH2_MSG_CHANNEL_EOF
);
367 translate(SSH2_MSG_CHANNEL_CLOSE
);
368 translate(SSH2_MSG_CHANNEL_REQUEST
);
369 translate(SSH2_MSG_CHANNEL_SUCCESS
);
370 translate(SSH2_MSG_CHANNEL_FAILURE
);
376 /* Enumeration values for fields in SSH-1 packets */
378 PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
,
379 /* These values are for communicating relevant semantics of
380 * fields to the packet logging code. */
381 PKTT_OTHER
, PKTT_PASSWORD
, PKTT_DATA
385 * Coroutine mechanics for the sillier bits of the code. If these
386 * macros look impenetrable to you, you might find it helpful to
389 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
391 * which explains the theory behind these macros.
393 * In particular, if you are getting `case expression not constant'
394 * errors when building with MS Visual Studio, this is because MS's
395 * Edit and Continue debugging feature causes their compiler to
396 * violate ANSI C. To disable Edit and Continue debugging:
398 * - right-click ssh.c in the FileView
400 * - select the C/C++ tab and the General category
401 * - under `Debug info:', select anything _other_ than `Program
402 * Database for Edit and Continue'.
404 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
407 if (!ssh->t) ssh->t = snew(struct t); \
409 #define crFinish(z) } *crLine = 0; return (z); }
410 #define crFinishV } *crLine = 0; return; }
411 #define crReturn(z) \
413 *crLine =__LINE__; return (z); case __LINE__:;\
417 *crLine=__LINE__; return; case __LINE__:;\
419 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
420 #define crStopV do{ *crLine = 0; return; }while(0)
421 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
422 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
424 typedef struct ssh_tag
*Ssh
;
427 static struct Packet
*ssh1_pkt_init(int pkt_type
);
428 static struct Packet
*ssh2_pkt_init(int pkt_type
);
429 static void ssh_pkt_ensure(struct Packet
*, int length
);
430 static void ssh_pkt_adddata(struct Packet
*, void *data
, int len
);
431 static void ssh_pkt_addbyte(struct Packet
*, unsigned char value
);
432 static void ssh2_pkt_addbool(struct Packet
*, unsigned char value
);
433 static void ssh_pkt_adduint32(struct Packet
*, unsigned long value
);
434 static void ssh_pkt_addstring_start(struct Packet
*);
435 static void ssh_pkt_addstring_str(struct Packet
*, char *data
);
436 static void ssh_pkt_addstring_data(struct Packet
*, char *data
, int len
);
437 static void ssh_pkt_addstring(struct Packet
*, char *data
);
438 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
);
439 static void ssh1_pkt_addmp(struct Packet
*, Bignum b
);
440 static void ssh2_pkt_addmp(struct Packet
*, Bignum b
);
441 static int ssh2_pkt_construct(Ssh
, struct Packet
*);
442 static void ssh2_pkt_send(Ssh
, struct Packet
*);
443 static void ssh2_pkt_send_noqueue(Ssh
, struct Packet
*);
444 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
,
445 struct Packet
*pktin
);
446 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
,
447 struct Packet
*pktin
);
450 * Buffer management constants. There are several of these for
451 * various different purposes:
453 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
454 * on a local data stream before we throttle the whole SSH
455 * connection (in SSH-1 only). Throttling the whole connection is
456 * pretty drastic so we set this high in the hope it won't
459 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
460 * on the SSH connection itself before we defensively throttle
461 * _all_ local data streams. This is pretty drastic too (though
462 * thankfully unlikely in SSH-2 since the window mechanism should
463 * ensure that the server never has any need to throttle its end
464 * of the connection), so we set this high as well.
466 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
470 #define SSH1_BUFFER_LIMIT 32768
471 #define SSH_MAX_BACKLOG 32768
472 #define OUR_V2_WINSIZE 16384
473 #define OUR_V2_MAXPKT 0x4000UL
475 /* Maximum length of passwords/passphrases (arbitrary) */
476 #define SSH_MAX_PASSWORD_LEN 100
478 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
480 const static struct ssh_mac
*macs
[] = {
481 &ssh_hmac_sha1
, &ssh_hmac_sha1_96
, &ssh_hmac_md5
483 const static struct ssh_mac
*buggymacs
[] = {
484 &ssh_hmac_sha1_buggy
, &ssh_hmac_sha1_96_buggy
, &ssh_hmac_md5
487 static void *ssh_comp_none_init(void)
491 static void ssh_comp_none_cleanup(void *handle
)
494 static int ssh_comp_none_block(void *handle
, unsigned char *block
, int len
,
495 unsigned char **outblock
, int *outlen
)
499 static int ssh_comp_none_disable(void *handle
)
503 const static struct ssh_compress ssh_comp_none
= {
505 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
506 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
507 ssh_comp_none_disable
, NULL
509 extern const struct ssh_compress ssh_zlib
;
510 const static struct ssh_compress
*compressions
[] = {
511 &ssh_zlib
, &ssh_comp_none
514 enum { /* channel types */
519 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
523 * 2-3-4 tree storing channels.
526 Ssh ssh
; /* pointer back to main context */
527 unsigned remoteid
, localid
;
529 /* True if we opened this channel but server hasn't confirmed. */
532 * In SSH-1, this value contains four bits:
534 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
535 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
536 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
537 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
539 * A channel is completely finished with when all four bits are set.
543 struct ssh1_data_channel
{
546 struct ssh2_data_channel
{
548 unsigned remwindow
, remmaxpkt
;
553 struct ssh_agent_channel
{
554 unsigned char *message
;
555 unsigned char msglen
[4];
556 unsigned lensofar
, totallen
;
558 struct ssh_x11_channel
{
561 struct ssh_pfd_channel
{
568 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
569 * use this structure in different ways, reflecting SSH-2's
570 * altogether saner approach to port forwarding.
572 * In SSH-1, you arrange a remote forwarding by sending the server
573 * the remote port number, and the local destination host:port.
574 * When a connection comes in, the server sends you back that
575 * host:port pair, and you connect to it. This is a ready-made
576 * security hole if you're not on the ball: a malicious server
577 * could send you back _any_ host:port pair, so if you trustingly
578 * connect to the address it gives you then you've just opened the
579 * entire inside of your corporate network just by connecting
580 * through it to a dodgy SSH server. Hence, we must store a list of
581 * host:port pairs we _are_ trying to forward to, and reject a
582 * connection request from the server if it's not in the list.
584 * In SSH-2, each side of the connection minds its own business and
585 * doesn't send unnecessary information to the other. You arrange a
586 * remote forwarding by sending the server just the remote port
587 * number. When a connection comes in, the server tells you which
588 * of its ports was connected to; and _you_ have to remember what
589 * local host:port pair went with that port number.
591 * Hence, in SSH-1 this structure is indexed by destination
592 * host:port pair, whereas in SSH-2 it is indexed by source port.
594 struct ssh_portfwd
; /* forward declaration */
596 struct ssh_rportfwd
{
597 unsigned sport
, dport
;
600 struct ssh_portfwd
*pfrec
;
602 #define free_rportfwd(pf) ( \
603 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
606 * Separately to the rportfwd tree (which is for looking up port
607 * open requests from the server), a tree of _these_ structures is
608 * used to keep track of all the currently open port forwardings,
609 * so that we can reconfigure in mid-session if the user requests
613 enum { DESTROY
, KEEP
, CREATE
} status
;
615 unsigned sport
, dport
;
618 struct ssh_rportfwd
*remote
;
622 #define free_portfwd(pf) ( \
623 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
624 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
627 long length
; /* length of `data' actually used */
628 long forcepad
; /* SSH-2: force padding to at least this length */
629 int type
; /* only used for incoming packets */
630 unsigned long sequence
; /* SSH-2 incoming sequence number */
631 unsigned char *data
; /* allocated storage */
632 unsigned char *body
; /* offset of payload within `data' */
633 long savedpos
; /* temporary index into `data' (for strings) */
634 long maxlen
; /* amount of storage allocated for `data' */
635 long encrypted_len
; /* for SSH-2 total-size counting */
638 * State associated with packet logging
642 struct logblank_t
*blanks
;
645 static void ssh1_protocol(Ssh ssh
, void *vin
, int inlen
,
646 struct Packet
*pktin
);
647 static void ssh2_protocol(Ssh ssh
, void *vin
, int inlen
,
648 struct Packet
*pktin
);
649 static void ssh1_protocol_setup(Ssh ssh
);
650 static void ssh2_protocol_setup(Ssh ssh
);
651 static void ssh_size(void *handle
, int width
, int height
);
652 static void ssh_special(void *handle
, Telnet_Special
);
653 static int ssh2_try_send(struct ssh_channel
*c
);
654 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
);
655 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
);
656 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
);
657 static int ssh_sendbuffer(void *handle
);
658 static int ssh_do_close(Ssh ssh
, int notify_exit
);
659 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
);
660 static int ssh2_pkt_getbool(struct Packet
*pkt
);
661 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
);
662 static void ssh2_timer(void *ctx
, long now
);
663 static int do_ssh2_transport(Ssh ssh
, void *vin
, int inlen
,
664 struct Packet
*pktin
);
666 struct rdpkt1_state_tag
{
667 long len
, pad
, biglen
, to_read
;
668 unsigned long realcrc
, gotcrc
;
672 struct Packet
*pktin
;
675 struct rdpkt2_state_tag
{
676 long len
, pad
, payload
, packetlen
, maclen
;
679 unsigned long incoming_sequence
;
680 struct Packet
*pktin
;
683 typedef void (*handler_fn_t
)(Ssh ssh
, struct Packet
*pktin
);
684 typedef void (*chandler_fn_t
)(Ssh ssh
, struct Packet
*pktin
, void *ctx
);
686 struct queued_handler
;
687 struct queued_handler
{
689 chandler_fn_t handler
;
691 struct queued_handler
*next
;
695 const struct plug_function_table
*fn
;
696 /* the above field _must_ be first in the structure */
706 unsigned char session_key
[32];
708 int v1_remote_protoflags
;
709 int v1_local_protoflags
;
710 int agentfwd_enabled
;
713 const struct ssh_cipher
*cipher
;
716 const struct ssh2_cipher
*cscipher
, *sccipher
;
717 void *cs_cipher_ctx
, *sc_cipher_ctx
;
718 const struct ssh_mac
*csmac
, *scmac
;
719 void *cs_mac_ctx
, *sc_mac_ctx
;
720 const struct ssh_compress
*cscomp
, *sccomp
;
721 void *cs_comp_ctx
, *sc_comp_ctx
;
722 const struct ssh_kex
*kex
;
723 const struct ssh_signkey
*hostkey
;
724 unsigned char v2_session_id
[SSH2_KEX_MAX_HASH_LEN
];
725 int v2_session_id_len
;
731 int echoing
, editing
;
735 int ospeed
, ispeed
; /* temporaries */
736 int term_width
, term_height
;
738 tree234
*channels
; /* indexed by local id */
739 struct ssh_channel
*mainchan
; /* primary session channel */
740 int ncmode
; /* is primary channel direct-tcpip? */
745 tree234
*rportfwds
, *portfwds
;
749 SSH_STATE_BEFORE_SIZE
,
755 int size_needed
, eof_needed
;
757 struct Packet
**queue
;
758 int queuelen
, queuesize
;
760 unsigned char *deferred_send_data
;
761 int deferred_len
, deferred_size
;
764 * Gross hack: pscp will try to start SFTP but fall back to
765 * scp1 if that fails. This variable is the means by which
766 * scp.c can reach into the SSH code and find out which one it
771 bufchain banner
; /* accumulates banners during do_ssh2_authconn */
778 int v1_throttle_count
;
781 int v1_stdout_throttling
;
782 unsigned long v2_outgoing_sequence
;
784 int ssh1_rdpkt_crstate
;
785 int ssh2_rdpkt_crstate
;
786 int do_ssh_init_crstate
;
787 int ssh_gotdata_crstate
;
788 int do_ssh1_login_crstate
;
789 int do_ssh1_connection_crstate
;
790 int do_ssh2_transport_crstate
;
791 int do_ssh2_authconn_crstate
;
793 void *do_ssh_init_state
;
794 void *do_ssh1_login_state
;
795 void *do_ssh2_transport_state
;
796 void *do_ssh2_authconn_state
;
798 struct rdpkt1_state_tag rdpkt1_state
;
799 struct rdpkt2_state_tag rdpkt2_state
;
801 /* SSH-1 and SSH-2 use this for different things, but both use it */
802 int protocol_initial_phase_done
;
804 void (*protocol
) (Ssh ssh
, void *vin
, int inlen
,
806 struct Packet
*(*s_rdpkt
) (Ssh ssh
, unsigned char **data
, int *datalen
);
809 * We maintain a full _copy_ of a Config structure here, not
810 * merely a pointer to it. That way, when we're passed a new
811 * one for reconfiguration, we can check the differences and
812 * potentially reconfigure port forwardings etc in mid-session.
817 * Used to transfer data back from async callbacks.
819 void *agent_response
;
820 int agent_response_len
;
824 * The SSH connection can be set as `frozen', meaning we are
825 * not currently accepting incoming data from the network. This
826 * is slightly more serious than setting the _socket_ as
827 * frozen, because we may already have had data passed to us
828 * from the network which we need to delay processing until
829 * after the freeze is lifted, so we also need a bufchain to
833 bufchain queued_incoming_data
;
836 * Dispatch table for packet types that we may have to deal
839 handler_fn_t packet_dispatch
[256];
842 * Queues of one-off handler functions for success/failure
843 * indications from a request.
845 struct queued_handler
*qhead
, *qtail
;
848 * This module deals with sending keepalives.
853 * Track incoming and outgoing data sizes and time, for
856 unsigned long incoming_data_size
, outgoing_data_size
, deferred_data_size
;
857 unsigned long max_data_size
;
859 long next_rekey
, last_rekey
;
860 char *deferred_rekey_reason
; /* points to STATIC string; don't free */
863 #define logevent(s) logevent(ssh->frontend, s)
865 /* logevent, only printf-formatted. */
866 static void logeventf(Ssh ssh
, const char *fmt
, ...)
872 buf
= dupvprintf(fmt
, ap
);
878 #define bombout(msg) \
880 char *text = dupprintf msg; \
881 ssh_do_close(ssh, FALSE); \
883 connection_fatal(ssh->frontend, "%s", text); \
887 /* Functions to leave bits out of the SSH packet log file. */
889 static void dont_log_password(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
891 if (ssh
->cfg
.logomitpass
)
892 pkt
->logmode
= blanktype
;
895 static void dont_log_data(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
897 if (ssh
->cfg
.logomitdata
)
898 pkt
->logmode
= blanktype
;
901 static void end_log_omission(Ssh ssh
, struct Packet
*pkt
)
903 pkt
->logmode
= PKTLOG_EMIT
;
906 /* Helper function for common bits of parsing cfg.ttymodes. */
907 static void parse_ttymodes(Ssh ssh
, char *modes
,
908 void (*do_mode
)(void *data
, char *mode
, char *val
),
912 char *t
= strchr(modes
, '\t');
913 char *m
= snewn(t
-modes
+1, char);
915 strncpy(m
, modes
, t
-modes
);
918 val
= get_ttymode(ssh
->frontend
, m
);
922 do_mode(data
, m
, val
);
925 modes
+= strlen(modes
) + 1;
929 static int ssh_channelcmp(void *av
, void *bv
)
931 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
932 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
933 if (a
->localid
< b
->localid
)
935 if (a
->localid
> b
->localid
)
939 static int ssh_channelfind(void *av
, void *bv
)
941 unsigned *a
= (unsigned *) av
;
942 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
950 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
952 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
953 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
955 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
956 return i
< 0 ?
-1 : +1;
957 if (a
->dport
> b
->dport
)
959 if (a
->dport
< b
->dport
)
964 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
966 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
967 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
969 if (a
->sport
> b
->sport
)
971 if (a
->sport
< b
->sport
)
977 * Special form of strcmp which can cope with NULL inputs. NULL is
978 * defined to sort before even the empty string.
980 static int nullstrcmp(const char *a
, const char *b
)
982 if (a
== NULL
&& b
== NULL
)
991 static int ssh_portcmp(void *av
, void *bv
)
993 struct ssh_portfwd
*a
= (struct ssh_portfwd
*) av
;
994 struct ssh_portfwd
*b
= (struct ssh_portfwd
*) bv
;
996 if (a
->type
> b
->type
)
998 if (a
->type
< b
->type
)
1000 if (a
->addressfamily
> b
->addressfamily
)
1002 if (a
->addressfamily
< b
->addressfamily
)
1004 if ( (i
= nullstrcmp(a
->saddr
, b
->saddr
)) != 0)
1005 return i
< 0 ?
-1 : +1;
1006 if (a
->sport
> b
->sport
)
1008 if (a
->sport
< b
->sport
)
1010 if (a
->type
!= 'D') {
1011 if ( (i
= nullstrcmp(a
->daddr
, b
->daddr
)) != 0)
1012 return i
< 0 ?
-1 : +1;
1013 if (a
->dport
> b
->dport
)
1015 if (a
->dport
< b
->dport
)
1021 static int alloc_channel_id(Ssh ssh
)
1023 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
1024 unsigned low
, high
, mid
;
1026 struct ssh_channel
*c
;
1029 * First-fit allocation of channel numbers: always pick the
1030 * lowest unused one. To do this, binary-search using the
1031 * counted B-tree to find the largest channel ID which is in a
1032 * contiguous sequence from the beginning. (Precisely
1033 * everything in that sequence must have ID equal to its tree
1034 * index plus CHANNEL_NUMBER_OFFSET.)
1036 tsize
= count234(ssh
->channels
);
1040 while (high
- low
> 1) {
1041 mid
= (high
+ low
) / 2;
1042 c
= index234(ssh
->channels
, mid
);
1043 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
1044 low
= mid
; /* this one is fine */
1046 high
= mid
; /* this one is past it */
1049 * Now low points to either -1, or the tree index of the
1050 * largest ID in the initial sequence.
1053 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
1054 assert(NULL
== find234(ssh
->channels
, &i
, ssh_channelfind
));
1056 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
1059 static void c_write_stderr(int trusted
, const char *buf
, int len
)
1062 for (i
= 0; i
< len
; i
++)
1063 if (buf
[i
] != '\r' && (trusted
|| buf
[i
] == '\n' || (buf
[i
] & 0x60)))
1064 fputc(buf
[i
], stderr
);
1067 static void c_write(Ssh ssh
, const char *buf
, int len
)
1069 if (flags
& FLAG_STDERR
)
1070 c_write_stderr(1, buf
, len
);
1072 from_backend(ssh
->frontend
, 1, buf
, len
);
1075 static void c_write_untrusted(Ssh ssh
, const char *buf
, int len
)
1077 if (flags
& FLAG_STDERR
)
1078 c_write_stderr(0, buf
, len
);
1080 from_backend_untrusted(ssh
->frontend
, buf
, len
);
1083 static void c_write_str(Ssh ssh
, const char *buf
)
1085 c_write(ssh
, buf
, strlen(buf
));
1088 static void ssh_free_packet(struct Packet
*pkt
)
1093 static struct Packet
*ssh_new_packet(void)
1095 struct Packet
*pkt
= snew(struct Packet
);
1097 pkt
->body
= pkt
->data
= NULL
;
1099 pkt
->logmode
= PKTLOG_EMIT
;
1107 * Collect incoming data in the incoming packet buffer.
1108 * Decipher and verify the packet when it is completely read.
1109 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1110 * Update the *data and *datalen variables.
1111 * Return a Packet structure when a packet is completed.
1113 static struct Packet
*ssh1_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
1115 struct rdpkt1_state_tag
*st
= &ssh
->rdpkt1_state
;
1117 crBegin(ssh
->ssh1_rdpkt_crstate
);
1119 st
->pktin
= ssh_new_packet();
1121 st
->pktin
->type
= 0;
1122 st
->pktin
->length
= 0;
1124 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
1125 while ((*datalen
) == 0)
1127 st
->len
= (st
->len
<< 8) + **data
;
1128 (*data
)++, (*datalen
)--;
1131 st
->pad
= 8 - (st
->len
% 8);
1132 st
->biglen
= st
->len
+ st
->pad
;
1133 st
->pktin
->length
= st
->len
- 5;
1135 if (st
->biglen
< 0) {
1136 bombout(("Extremely large packet length from server suggests"
1137 " data stream corruption"));
1138 ssh_free_packet(st
->pktin
);
1142 st
->pktin
->maxlen
= st
->biglen
;
1143 st
->pktin
->data
= snewn(st
->biglen
+ APIEXTRA
, unsigned char);
1145 st
->to_read
= st
->biglen
;
1146 st
->p
= st
->pktin
->data
;
1147 while (st
->to_read
> 0) {
1148 st
->chunk
= st
->to_read
;
1149 while ((*datalen
) == 0)
1151 if (st
->chunk
> (*datalen
))
1152 st
->chunk
= (*datalen
);
1153 memcpy(st
->p
, *data
, st
->chunk
);
1155 *datalen
-= st
->chunk
;
1157 st
->to_read
-= st
->chunk
;
1160 if (ssh
->cipher
&& detect_attack(ssh
->crcda_ctx
, st
->pktin
->data
,
1161 st
->biglen
, NULL
)) {
1162 bombout(("Network attack (CRC compensation) detected!"));
1163 ssh_free_packet(st
->pktin
);
1168 ssh
->cipher
->decrypt(ssh
->v1_cipher_ctx
, st
->pktin
->data
, st
->biglen
);
1170 st
->realcrc
= crc32_compute(st
->pktin
->data
, st
->biglen
- 4);
1171 st
->gotcrc
= GET_32BIT(st
->pktin
->data
+ st
->biglen
- 4);
1172 if (st
->gotcrc
!= st
->realcrc
) {
1173 bombout(("Incorrect CRC received on packet"));
1174 ssh_free_packet(st
->pktin
);
1178 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
1179 st
->pktin
->savedpos
= 0;
1181 if (ssh
->v1_compressing
) {
1182 unsigned char *decompblk
;
1184 if (!zlib_decompress_block(ssh
->sc_comp_ctx
,
1185 st
->pktin
->body
- 1, st
->pktin
->length
+ 1,
1186 &decompblk
, &decomplen
)) {
1187 bombout(("Zlib decompression encountered invalid data"));
1188 ssh_free_packet(st
->pktin
);
1192 if (st
->pktin
->maxlen
< st
->pad
+ decomplen
) {
1193 st
->pktin
->maxlen
= st
->pad
+ decomplen
;
1194 st
->pktin
->data
= sresize(st
->pktin
->data
,
1195 st
->pktin
->maxlen
+ APIEXTRA
,
1197 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
1200 memcpy(st
->pktin
->body
- 1, decompblk
, decomplen
);
1202 st
->pktin
->length
= decomplen
- 1;
1205 st
->pktin
->type
= st
->pktin
->body
[-1];
1208 * Log incoming packet, possibly omitting sensitive fields.
1212 struct logblank_t blank
;
1213 if (ssh
->cfg
.logomitdata
) {
1214 int do_blank
= FALSE
, blank_prefix
= 0;
1215 /* "Session data" packets - omit the data field */
1216 if ((st
->pktin
->type
== SSH1_SMSG_STDOUT_DATA
) ||
1217 (st
->pktin
->type
== SSH1_SMSG_STDERR_DATA
)) {
1218 do_blank
= TRUE
; blank_prefix
= 0;
1219 } else if (st
->pktin
->type
== SSH1_MSG_CHANNEL_DATA
) {
1220 do_blank
= TRUE
; blank_prefix
= 4;
1223 blank
.offset
= blank_prefix
;
1224 blank
.len
= st
->pktin
->length
;
1225 blank
.type
= PKTLOG_OMIT
;
1229 log_packet(ssh
->logctx
,
1230 PKT_INCOMING
, st
->pktin
->type
,
1231 ssh1_pkt_type(st
->pktin
->type
),
1232 st
->pktin
->body
, st
->pktin
->length
,
1236 crFinish(st
->pktin
);
1239 static struct Packet
*ssh2_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
1241 struct rdpkt2_state_tag
*st
= &ssh
->rdpkt2_state
;
1243 crBegin(ssh
->ssh2_rdpkt_crstate
);
1245 st
->pktin
= ssh_new_packet();
1247 st
->pktin
->type
= 0;
1248 st
->pktin
->length
= 0;
1250 st
->cipherblk
= ssh
->sccipher
->blksize
;
1253 if (st
->cipherblk
< 8)
1256 st
->pktin
->data
= snewn(st
->cipherblk
+ APIEXTRA
, unsigned char);
1259 * Acquire and decrypt the first block of the packet. This will
1260 * contain the length and padding details.
1262 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
1263 while ((*datalen
) == 0)
1265 st
->pktin
->data
[st
->i
] = *(*data
)++;
1270 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1271 st
->pktin
->data
, st
->cipherblk
);
1274 * Now get the length and padding figures.
1276 st
->len
= GET_32BIT(st
->pktin
->data
);
1277 st
->pad
= st
->pktin
->data
[4];
1280 * _Completely_ silly lengths should be stomped on before they
1281 * do us any more damage.
1283 if (st
->len
< 0 || st
->len
> 35000 || st
->pad
< 4 ||
1284 st
->len
- st
->pad
< 1 || (st
->len
+ 4) % st
->cipherblk
!= 0) {
1285 bombout(("Incoming packet was garbled on decryption"));
1286 ssh_free_packet(st
->pktin
);
1291 * This enables us to deduce the payload length.
1293 st
->payload
= st
->len
- st
->pad
- 1;
1295 st
->pktin
->length
= st
->payload
+ 5;
1298 * So now we can work out the total packet length.
1300 st
->packetlen
= st
->len
+ 4;
1301 st
->maclen
= ssh
->scmac ? ssh
->scmac
->len
: 0;
1304 * Allocate memory for the rest of the packet.
1306 st
->pktin
->maxlen
= st
->packetlen
+ st
->maclen
;
1307 st
->pktin
->data
= sresize(st
->pktin
->data
,
1308 st
->pktin
->maxlen
+ APIEXTRA
,
1312 * Read and decrypt the remainder of the packet.
1314 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
1316 while ((*datalen
) == 0)
1318 st
->pktin
->data
[st
->i
] = *(*data
)++;
1321 /* Decrypt everything _except_ the MAC. */
1323 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1324 st
->pktin
->data
+ st
->cipherblk
,
1325 st
->packetlen
- st
->cipherblk
);
1327 st
->pktin
->encrypted_len
= st
->packetlen
;
1333 && !ssh
->scmac
->verify(ssh
->sc_mac_ctx
, st
->pktin
->data
, st
->len
+ 4,
1334 st
->incoming_sequence
)) {
1335 bombout(("Incorrect MAC received on packet"));
1336 ssh_free_packet(st
->pktin
);
1340 st
->pktin
->sequence
= st
->incoming_sequence
++;
1343 * Decompress packet payload.
1346 unsigned char *newpayload
;
1349 ssh
->sccomp
->decompress(ssh
->sc_comp_ctx
,
1350 st
->pktin
->data
+ 5, st
->pktin
->length
- 5,
1351 &newpayload
, &newlen
)) {
1352 if (st
->pktin
->maxlen
< newlen
+ 5) {
1353 st
->pktin
->maxlen
= newlen
+ 5;
1354 st
->pktin
->data
= sresize(st
->pktin
->data
,
1355 st
->pktin
->maxlen
+ APIEXTRA
,
1358 st
->pktin
->length
= 5 + newlen
;
1359 memcpy(st
->pktin
->data
+ 5, newpayload
, newlen
);
1364 st
->pktin
->savedpos
= 6;
1365 st
->pktin
->body
= st
->pktin
->data
;
1366 st
->pktin
->type
= st
->pktin
->data
[5];
1369 * Log incoming packet, possibly omitting sensitive fields.
1373 struct logblank_t blank
;
1374 if (ssh
->cfg
.logomitdata
) {
1375 int do_blank
= FALSE
, blank_prefix
= 0;
1376 /* "Session data" packets - omit the data field */
1377 if (st
->pktin
->type
== SSH2_MSG_CHANNEL_DATA
) {
1378 do_blank
= TRUE
; blank_prefix
= 4;
1379 } else if (st
->pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
1380 do_blank
= TRUE
; blank_prefix
= 8;
1383 blank
.offset
= blank_prefix
;
1384 blank
.len
= (st
->pktin
->length
-6) - blank_prefix
;
1385 blank
.type
= PKTLOG_OMIT
;
1389 log_packet(ssh
->logctx
, PKT_INCOMING
, st
->pktin
->type
,
1390 ssh2_pkt_type(ssh
->pkt_ctx
, st
->pktin
->type
),
1391 st
->pktin
->data
+6, st
->pktin
->length
-6,
1395 crFinish(st
->pktin
);
1398 static int s_wrpkt_prepare(Ssh ssh
, struct Packet
*pkt
, int *offset_p
)
1400 int pad
, biglen
, i
, pktoffs
;
1404 * XXX various versions of SC (including 8.8.4) screw up the
1405 * register allocation in this function and use the same register
1406 * (D6) for len and as a temporary, with predictable results. The
1407 * following sledgehammer prevents this.
1414 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->data
[12],
1415 ssh1_pkt_type(pkt
->data
[12]),
1416 pkt
->body
, pkt
->length
- (pkt
->body
- pkt
->data
),
1417 pkt
->nblanks
, pkt
->blanks
);
1418 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1421 if (ssh
->v1_compressing
) {
1422 unsigned char *compblk
;
1424 zlib_compress_block(ssh
->cs_comp_ctx
,
1425 pkt
->data
+ 12, pkt
->length
- 12,
1426 &compblk
, &complen
);
1427 memcpy(pkt
->data
+ 12, compblk
, complen
);
1429 pkt
->length
= complen
+ 12;
1432 ssh_pkt_ensure(pkt
, pkt
->length
+ 4); /* space for CRC */
1434 len
= pkt
->length
- 4 - 8; /* len(type+data+CRC) */
1435 pad
= 8 - (len
% 8);
1437 biglen
= len
+ pad
; /* len(padding+type+data+CRC) */
1439 for (i
= pktoffs
; i
< 4+8; i
++)
1440 pkt
->data
[i
] = random_byte();
1441 crc
= crc32_compute(pkt
->data
+ pktoffs
+ 4, biglen
- 4); /* all ex len */
1442 PUT_32BIT(pkt
->data
+ pktoffs
+ 4 + biglen
- 4, crc
);
1443 PUT_32BIT(pkt
->data
+ pktoffs
, len
);
1446 ssh
->cipher
->encrypt(ssh
->v1_cipher_ctx
,
1447 pkt
->data
+ pktoffs
+ 4, biglen
);
1449 if (offset_p
) *offset_p
= pktoffs
;
1450 return biglen
+ 4; /* len(length+padding+type+data+CRC) */
1453 static int s_write(Ssh ssh
, void *data
, int len
)
1455 log_packet(ssh
->logctx
, PKT_OUTGOING
, -1, NULL
, data
, len
, 0, NULL
);
1456 return sk_write(ssh
->s
, (char *)data
, len
);
1459 static void s_wrpkt(Ssh ssh
, struct Packet
*pkt
)
1461 int len
, backlog
, offset
;
1462 len
= s_wrpkt_prepare(ssh
, pkt
, &offset
);
1463 backlog
= s_write(ssh
, pkt
->data
+ offset
, len
);
1464 if (backlog
> SSH_MAX_BACKLOG
)
1465 ssh_throttle_all(ssh
, 1, backlog
);
1466 ssh_free_packet(pkt
);
1469 static void s_wrpkt_defer(Ssh ssh
, struct Packet
*pkt
)
1472 len
= s_wrpkt_prepare(ssh
, pkt
, &offset
);
1473 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1474 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1475 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
1479 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
,
1480 pkt
->data
+ offset
, len
);
1481 ssh
->deferred_len
+= len
;
1482 ssh_free_packet(pkt
);
1486 * Construct a SSH-1 packet with the specified contents.
1487 * (This all-at-once interface used to be the only one, but now SSH-1
1488 * packets can also be constructed incrementally.)
1490 static struct Packet
*construct_packet(Ssh ssh
, int pkttype
, va_list ap
)
1496 pkt
= ssh1_pkt_init(pkttype
);
1498 while ((argtype
= va_arg(ap
, int)) != PKT_END
) {
1499 unsigned char *argp
, argchar
;
1501 unsigned long argint
;
1504 /* Actual fields in the packet */
1506 argint
= va_arg(ap
, int);
1507 ssh_pkt_adduint32(pkt
, argint
);
1510 argchar
= (unsigned char) va_arg(ap
, int);
1511 ssh_pkt_addbyte(pkt
, argchar
);
1514 argp
= va_arg(ap
, unsigned char *);
1515 arglen
= va_arg(ap
, int);
1516 ssh_pkt_adddata(pkt
, argp
, arglen
);
1519 sargp
= va_arg(ap
, char *);
1520 ssh_pkt_addstring(pkt
, sargp
);
1523 bn
= va_arg(ap
, Bignum
);
1524 ssh1_pkt_addmp(pkt
, bn
);
1526 /* Tokens for modifications to packet logging */
1528 dont_log_password(ssh
, pkt
, PKTLOG_BLANK
);
1531 dont_log_data(ssh
, pkt
, PKTLOG_OMIT
);
1534 end_log_omission(ssh
, pkt
);
1542 static void send_packet(Ssh ssh
, int pkttype
, ...)
1546 va_start(ap
, pkttype
);
1547 pkt
= construct_packet(ssh
, pkttype
, ap
);
1552 static void defer_packet(Ssh ssh
, int pkttype
, ...)
1556 va_start(ap
, pkttype
);
1557 pkt
= construct_packet(ssh
, pkttype
, ap
);
1559 s_wrpkt_defer(ssh
, pkt
);
1562 static int ssh_versioncmp(char *a
, char *b
)
1565 unsigned long av
, bv
;
1567 av
= strtoul(a
, &ae
, 10);
1568 bv
= strtoul(b
, &be
, 10);
1570 return (av
< bv ?
-1 : +1);
1575 av
= strtoul(ae
, &ae
, 10);
1576 bv
= strtoul(be
, &be
, 10);
1578 return (av
< bv ?
-1 : +1);
1583 * Utility routines for putting an SSH-protocol `string' and
1584 * `uint32' into a hash state.
1586 static void hash_string(const struct ssh_hash
*h
, void *s
, void *str
, int len
)
1588 unsigned char lenblk
[4];
1589 PUT_32BIT(lenblk
, len
);
1590 h
->bytes(s
, lenblk
, 4);
1591 h
->bytes(s
, str
, len
);
1594 static void hash_uint32(const struct ssh_hash
*h
, void *s
, unsigned i
)
1596 unsigned char intblk
[4];
1597 PUT_32BIT(intblk
, i
);
1598 h
->bytes(s
, intblk
, 4);
1602 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1604 static void ssh_pkt_ensure(struct Packet
*pkt
, int length
)
1606 if (pkt
->maxlen
< length
) {
1607 unsigned char *body
= pkt
->body
;
1608 int offset
= body ? body
- pkt
->data
: 0;
1609 pkt
->maxlen
= length
+ 256;
1610 pkt
->data
= sresize(pkt
->data
, pkt
->maxlen
+ APIEXTRA
, unsigned char);
1611 if (body
) pkt
->body
= pkt
->data
+ offset
;
1614 static void ssh_pkt_adddata(struct Packet
*pkt
, void *data
, int len
)
1616 if (pkt
->logmode
!= PKTLOG_EMIT
) {
1618 pkt
->blanks
= sresize(pkt
->blanks
, pkt
->nblanks
, struct logblank_t
);
1620 pkt
->blanks
[pkt
->nblanks
-1].offset
= pkt
->length
-
1621 (pkt
->body
- pkt
->data
);
1622 pkt
->blanks
[pkt
->nblanks
-1].len
= len
;
1623 pkt
->blanks
[pkt
->nblanks
-1].type
= pkt
->logmode
;
1626 ssh_pkt_ensure(pkt
, pkt
->length
);
1627 memcpy(pkt
->data
+ pkt
->length
- len
, data
, len
);
1629 static void ssh_pkt_addbyte(struct Packet
*pkt
, unsigned char byte
)
1631 ssh_pkt_adddata(pkt
, &byte
, 1);
1633 static void ssh2_pkt_addbool(struct Packet
*pkt
, unsigned char value
)
1635 ssh_pkt_adddata(pkt
, &value
, 1);
1637 static void ssh_pkt_adduint32(struct Packet
*pkt
, unsigned long value
)
1640 PUT_32BIT(x
, value
);
1641 ssh_pkt_adddata(pkt
, x
, 4);
1643 static void ssh_pkt_addstring_start(struct Packet
*pkt
)
1645 ssh_pkt_adduint32(pkt
, 0);
1646 pkt
->savedpos
= pkt
->length
;
1648 static void ssh_pkt_addstring_str(struct Packet
*pkt
, char *data
)
1650 ssh_pkt_adddata(pkt
, data
, strlen(data
));
1651 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1653 static void ssh_pkt_addstring_data(struct Packet
*pkt
, char *data
, int len
)
1655 ssh_pkt_adddata(pkt
, data
, len
);
1656 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1658 static void ssh_pkt_addstring(struct Packet
*pkt
, char *data
)
1660 ssh_pkt_addstring_start(pkt
);
1661 ssh_pkt_addstring_str(pkt
, data
);
1663 static void ssh1_pkt_addmp(struct Packet
*pkt
, Bignum b
)
1665 int len
= ssh1_bignum_length(b
);
1666 unsigned char *data
= snewn(len
, unsigned char);
1667 (void) ssh1_write_bignum(data
, b
);
1668 ssh_pkt_adddata(pkt
, data
, len
);
1671 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
)
1674 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1675 p
= snewn(n
+ 1, unsigned char);
1677 for (i
= 1; i
<= n
; i
++)
1678 p
[i
] = bignum_byte(b
, n
- i
);
1680 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1682 memmove(p
, p
+ i
, n
+ 1 - i
);
1686 static void ssh2_pkt_addmp(struct Packet
*pkt
, Bignum b
)
1690 p
= ssh2_mpint_fmt(b
, &len
);
1691 ssh_pkt_addstring_start(pkt
);
1692 ssh_pkt_addstring_data(pkt
, (char *)p
, len
);
1696 static struct Packet
*ssh1_pkt_init(int pkt_type
)
1698 struct Packet
*pkt
= ssh_new_packet();
1699 pkt
->length
= 4 + 8; /* space for length + max padding */
1700 ssh_pkt_addbyte(pkt
, pkt_type
);
1701 pkt
->body
= pkt
->data
+ pkt
->length
;
1705 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1706 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1707 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1708 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1709 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1710 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1711 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1712 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1713 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1715 static struct Packet
*ssh2_pkt_init(int pkt_type
)
1717 struct Packet
*pkt
= ssh_new_packet();
1718 pkt
->length
= 5; /* space for packet length + padding length */
1720 ssh_pkt_addbyte(pkt
, (unsigned char) pkt_type
);
1721 pkt
->body
= pkt
->data
+ pkt
->length
; /* after packet type */
1726 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1727 * put the MAC on it. Final packet, ready to be sent, is stored in
1728 * pkt->data. Total length is returned.
1730 static int ssh2_pkt_construct(Ssh ssh
, struct Packet
*pkt
)
1732 int cipherblk
, maclen
, padding
, i
;
1735 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->data
[5],
1736 ssh2_pkt_type(ssh
->pkt_ctx
, pkt
->data
[5]),
1737 pkt
->body
, pkt
->length
- (pkt
->body
- pkt
->data
),
1738 pkt
->nblanks
, pkt
->blanks
);
1739 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1743 * Compress packet payload.
1746 unsigned char *newpayload
;
1749 ssh
->cscomp
->compress(ssh
->cs_comp_ctx
, pkt
->data
+ 5,
1751 &newpayload
, &newlen
)) {
1753 ssh2_pkt_adddata(pkt
, newpayload
, newlen
);
1759 * Add padding. At least four bytes, and must also bring total
1760 * length (minus MAC) up to a multiple of the block size.
1761 * If pkt->forcepad is set, make sure the packet is at least that size
1764 cipherblk
= ssh
->cscipher ? ssh
->cscipher
->blksize
: 8; /* block size */
1765 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1767 if (pkt
->length
+ padding
< pkt
->forcepad
)
1768 padding
= pkt
->forcepad
- pkt
->length
;
1770 (cipherblk
- (pkt
->length
+ padding
) % cipherblk
) % cipherblk
;
1771 assert(padding
<= 255);
1772 maclen
= ssh
->csmac ? ssh
->csmac
->len
: 0;
1773 ssh2_pkt_ensure(pkt
, pkt
->length
+ padding
+ maclen
);
1774 pkt
->data
[4] = padding
;
1775 for (i
= 0; i
< padding
; i
++)
1776 pkt
->data
[pkt
->length
+ i
] = random_byte();
1777 PUT_32BIT(pkt
->data
, pkt
->length
+ padding
- 4);
1779 ssh
->csmac
->generate(ssh
->cs_mac_ctx
, pkt
->data
,
1780 pkt
->length
+ padding
,
1781 ssh
->v2_outgoing_sequence
);
1782 ssh
->v2_outgoing_sequence
++; /* whether or not we MACed */
1785 ssh
->cscipher
->encrypt(ssh
->cs_cipher_ctx
,
1786 pkt
->data
, pkt
->length
+ padding
);
1788 pkt
->encrypted_len
= pkt
->length
+ padding
;
1790 /* Ready-to-send packet starts at pkt->data. We return length. */
1791 return pkt
->length
+ padding
+ maclen
;
1795 * Routines called from the main SSH code to send packets. There
1796 * are quite a few of these, because we have two separate
1797 * mechanisms for delaying the sending of packets:
1799 * - In order to send an IGNORE message and a password message in
1800 * a single fixed-length blob, we require the ability to
1801 * concatenate the encrypted forms of those two packets _into_ a
1802 * single blob and then pass it to our <network.h> transport
1803 * layer in one go. Hence, there's a deferment mechanism which
1804 * works after packet encryption.
1806 * - In order to avoid sending any connection-layer messages
1807 * during repeat key exchange, we have to queue up any such
1808 * outgoing messages _before_ they are encrypted (and in
1809 * particular before they're allocated sequence numbers), and
1810 * then send them once we've finished.
1812 * I call these mechanisms `defer' and `queue' respectively, so as
1813 * to distinguish them reasonably easily.
1815 * The functions send_noqueue() and defer_noqueue() free the packet
1816 * structure they are passed. Every outgoing packet goes through
1817 * precisely one of these functions in its life; packets passed to
1818 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1819 * these or get queued, and then when the queue is later emptied
1820 * the packets are all passed to defer_noqueue().
1822 * When using a CBC-mode cipher, it's necessary to ensure that an
1823 * attacker can't provide data to be encrypted using an IV that they
1824 * know. We ensure this by prefixing each packet that might contain
1825 * user data with an SSH_MSG_IGNORE. This is done using the deferral
1826 * mechanism, so in this case send_noqueue() ends up redirecting to
1827 * defer_noqueue(). If you don't like this inefficiency, don't use
1831 static void ssh2_pkt_defer_noqueue(Ssh
, struct Packet
*, int);
1832 static void ssh_pkt_defersend(Ssh
);
1835 * Send an SSH-2 packet immediately, without queuing or deferring.
1837 static void ssh2_pkt_send_noqueue(Ssh ssh
, struct Packet
*pkt
)
1841 if (ssh
->cscipher
!= NULL
&& (ssh
->cscipher
->flags
& SSH_CIPHER_IS_CBC
)) {
1842 /* We need to send two packets, so use the deferral mechanism. */
1843 ssh2_pkt_defer_noqueue(ssh
, pkt
, FALSE
);
1844 ssh_pkt_defersend(ssh
);
1847 len
= ssh2_pkt_construct(ssh
, pkt
);
1848 backlog
= s_write(ssh
, pkt
->data
, len
);
1849 if (backlog
> SSH_MAX_BACKLOG
)
1850 ssh_throttle_all(ssh
, 1, backlog
);
1852 ssh
->outgoing_data_size
+= pkt
->encrypted_len
;
1853 if (!ssh
->kex_in_progress
&&
1854 ssh
->max_data_size
!= 0 &&
1855 ssh
->outgoing_data_size
> ssh
->max_data_size
)
1856 do_ssh2_transport(ssh
, "too much data sent", -1, NULL
);
1858 ssh_free_packet(pkt
);
1862 * Defer an SSH-2 packet.
1864 static void ssh2_pkt_defer_noqueue(Ssh ssh
, struct Packet
*pkt
, int noignore
)
1867 if (ssh
->cscipher
!= NULL
&& (ssh
->cscipher
->flags
& SSH_CIPHER_IS_CBC
) &&
1868 ssh
->deferred_len
== 0 && !noignore
) {
1870 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
1871 * get encrypted with a known IV.
1873 struct Packet
*ipkt
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
1874 ssh2_pkt_addstring_start(ipkt
);
1875 ssh2_pkt_defer_noqueue(ssh
, ipkt
, TRUE
);
1877 len
= ssh2_pkt_construct(ssh
, pkt
);
1878 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1879 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1880 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
1884 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
, pkt
->data
, len
);
1885 ssh
->deferred_len
+= len
;
1886 ssh
->deferred_data_size
+= pkt
->encrypted_len
;
1887 ssh_free_packet(pkt
);
1891 * Queue an SSH-2 packet.
1893 static void ssh2_pkt_queue(Ssh ssh
, struct Packet
*pkt
)
1895 assert(ssh
->queueing
);
1897 if (ssh
->queuelen
>= ssh
->queuesize
) {
1898 ssh
->queuesize
= ssh
->queuelen
+ 32;
1899 ssh
->queue
= sresize(ssh
->queue
, ssh
->queuesize
, struct Packet
*);
1902 ssh
->queue
[ssh
->queuelen
++] = pkt
;
1906 * Either queue or send a packet, depending on whether queueing is
1909 static void ssh2_pkt_send(Ssh ssh
, struct Packet
*pkt
)
1912 ssh2_pkt_queue(ssh
, pkt
);
1914 ssh2_pkt_send_noqueue(ssh
, pkt
);
1918 * Either queue or defer a packet, depending on whether queueing is
1921 static void ssh2_pkt_defer(Ssh ssh
, struct Packet
*pkt
)
1924 ssh2_pkt_queue(ssh
, pkt
);
1926 ssh2_pkt_defer_noqueue(ssh
, pkt
, FALSE
);
1930 * Send the whole deferred data block constructed by
1931 * ssh2_pkt_defer() or SSH-1's defer_packet().
1933 * The expected use of the defer mechanism is that you call
1934 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
1935 * not currently queueing, this simply sets up deferred_send_data
1936 * and then sends it. If we _are_ currently queueing, the calls to
1937 * ssh2_pkt_defer() put the deferred packets on to the queue
1938 * instead, and therefore ssh_pkt_defersend() has no deferred data
1939 * to send. Hence, there's no need to make it conditional on
1942 static void ssh_pkt_defersend(Ssh ssh
)
1945 backlog
= s_write(ssh
, ssh
->deferred_send_data
, ssh
->deferred_len
);
1946 ssh
->deferred_len
= ssh
->deferred_size
= 0;
1947 sfree(ssh
->deferred_send_data
);
1948 ssh
->deferred_send_data
= NULL
;
1949 if (backlog
> SSH_MAX_BACKLOG
)
1950 ssh_throttle_all(ssh
, 1, backlog
);
1952 ssh
->outgoing_data_size
+= ssh
->deferred_data_size
;
1953 if (!ssh
->kex_in_progress
&&
1954 ssh
->max_data_size
!= 0 &&
1955 ssh
->outgoing_data_size
> ssh
->max_data_size
)
1956 do_ssh2_transport(ssh
, "too much data sent", -1, NULL
);
1957 ssh
->deferred_data_size
= 0;
1961 * Send a packet whose length needs to be disguised (typically
1962 * passwords or keyboard-interactive responses).
1964 static void ssh2_pkt_send_with_padding(Ssh ssh
, struct Packet
*pkt
,
1970 * The simplest way to do this is to adjust the
1971 * variable-length padding field in the outgoing packet.
1973 * Currently compiled out, because some Cisco SSH servers
1974 * don't like excessively padded packets (bah, why's it
1977 pkt
->forcepad
= padsize
;
1978 ssh2_pkt_send(ssh
, pkt
);
1983 * If we can't do that, however, an alternative approach is
1984 * to use the pkt_defer mechanism to bundle the packet
1985 * tightly together with an SSH_MSG_IGNORE such that their
1986 * combined length is a constant. So first we construct the
1987 * final form of this packet and defer its sending.
1989 ssh2_pkt_defer(ssh
, pkt
);
1992 * Now construct an SSH_MSG_IGNORE which includes a string
1993 * that's an exact multiple of the cipher block size. (If
1994 * the cipher is NULL so that the block size is
1995 * unavailable, we don't do this trick at all, because we
1996 * gain nothing by it.)
1998 if (ssh
->cscipher
) {
2001 stringlen
= (256 - ssh
->deferred_len
);
2002 stringlen
+= ssh
->cscipher
->blksize
- 1;
2003 stringlen
-= (stringlen
% ssh
->cscipher
->blksize
);
2006 * Temporarily disable actual compression, so we
2007 * can guarantee to get this string exactly the
2008 * length we want it. The compression-disabling
2009 * routine should return an integer indicating how
2010 * many bytes we should adjust our string length
2014 ssh
->cscomp
->disable_compression(ssh
->cs_comp_ctx
);
2016 pkt
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
2017 ssh2_pkt_addstring_start(pkt
);
2018 for (i
= 0; i
< stringlen
; i
++) {
2019 char c
= (char) random_byte();
2020 ssh2_pkt_addstring_data(pkt
, &c
, 1);
2022 ssh2_pkt_defer(ssh
, pkt
);
2024 ssh_pkt_defersend(ssh
);
2029 * Send all queued SSH-2 packets. We send them by means of
2030 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2031 * packets that needed to be lumped together.
2033 static void ssh2_pkt_queuesend(Ssh ssh
)
2037 assert(!ssh
->queueing
);
2039 for (i
= 0; i
< ssh
->queuelen
; i
++)
2040 ssh2_pkt_defer_noqueue(ssh
, ssh
->queue
[i
], FALSE
);
2043 ssh_pkt_defersend(ssh
);
2047 void bndebug(char *string
, Bignum b
)
2051 p
= ssh2_mpint_fmt(b
, &len
);
2052 debug(("%s", string
));
2053 for (i
= 0; i
< len
; i
++)
2054 debug((" %02x", p
[i
]));
2060 static void hash_mpint(const struct ssh_hash
*h
, void *s
, Bignum b
)
2064 p
= ssh2_mpint_fmt(b
, &len
);
2065 hash_string(h
, s
, p
, len
);
2070 * Packet decode functions for both SSH-1 and SSH-2.
2072 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
)
2074 unsigned long value
;
2075 if (pkt
->length
- pkt
->savedpos
< 4)
2076 return 0; /* arrgh, no way to decline (FIXME?) */
2077 value
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
2081 static int ssh2_pkt_getbool(struct Packet
*pkt
)
2083 unsigned long value
;
2084 if (pkt
->length
- pkt
->savedpos
< 1)
2085 return 0; /* arrgh, no way to decline (FIXME?) */
2086 value
= pkt
->body
[pkt
->savedpos
] != 0;
2090 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
)
2095 if (pkt
->length
- pkt
->savedpos
< 4)
2097 len
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
2102 if (pkt
->length
- pkt
->savedpos
< *length
)
2104 *p
= (char *)(pkt
->body
+ pkt
->savedpos
);
2105 pkt
->savedpos
+= *length
;
2107 static void *ssh_pkt_getdata(struct Packet
*pkt
, int length
)
2109 if (pkt
->length
- pkt
->savedpos
< length
)
2111 pkt
->savedpos
+= length
;
2112 return pkt
->body
+ (pkt
->savedpos
- length
);
2114 static int ssh1_pkt_getrsakey(struct Packet
*pkt
, struct RSAKey
*key
,
2115 unsigned char **keystr
)
2119 j
= makekey(pkt
->body
+ pkt
->savedpos
,
2120 pkt
->length
- pkt
->savedpos
,
2127 assert(pkt
->savedpos
< pkt
->length
);
2131 static Bignum
ssh1_pkt_getmp(struct Packet
*pkt
)
2136 j
= ssh1_read_bignum(pkt
->body
+ pkt
->savedpos
,
2137 pkt
->length
- pkt
->savedpos
, &b
);
2145 static Bignum
ssh2_pkt_getmp(struct Packet
*pkt
)
2151 ssh_pkt_getstring(pkt
, &p
, &length
);
2156 b
= bignum_from_bytes((unsigned char *)p
, length
);
2161 * Helper function to add an SSH-2 signature blob to a packet.
2162 * Expects to be shown the public key blob as well as the signature
2163 * blob. Normally works just like ssh2_pkt_addstring, but will
2164 * fiddle with the signature packet if necessary for
2165 * BUG_SSH2_RSA_PADDING.
2167 static void ssh2_add_sigblob(Ssh ssh
, struct Packet
*pkt
,
2168 void *pkblob_v
, int pkblob_len
,
2169 void *sigblob_v
, int sigblob_len
)
2171 unsigned char *pkblob
= (unsigned char *)pkblob_v
;
2172 unsigned char *sigblob
= (unsigned char *)sigblob_v
;
2174 /* dmemdump(pkblob, pkblob_len); */
2175 /* dmemdump(sigblob, sigblob_len); */
2178 * See if this is in fact an ssh-rsa signature and a buggy
2179 * server; otherwise we can just do this the easy way.
2181 if ((ssh
->remote_bugs
& BUG_SSH2_RSA_PADDING
) &&
2182 (GET_32BIT(pkblob
) == 7 && !memcmp(pkblob
+4, "ssh-rsa", 7))) {
2183 int pos
, len
, siglen
;
2186 * Find the byte length of the modulus.
2189 pos
= 4+7; /* skip over "ssh-rsa" */
2190 pos
+= 4 + GET_32BIT(pkblob
+pos
); /* skip over exponent */
2191 len
= GET_32BIT(pkblob
+pos
); /* find length of modulus */
2192 pos
+= 4; /* find modulus itself */
2193 while (len
> 0 && pkblob
[pos
] == 0)
2195 /* debug(("modulus length is %d\n", len)); */
2198 * Now find the signature integer.
2200 pos
= 4+7; /* skip over "ssh-rsa" */
2201 siglen
= GET_32BIT(sigblob
+pos
);
2202 /* debug(("signature length is %d\n", siglen)); */
2204 if (len
!= siglen
) {
2205 unsigned char newlen
[4];
2206 ssh2_pkt_addstring_start(pkt
);
2207 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, pos
);
2208 /* dmemdump(sigblob, pos); */
2209 pos
+= 4; /* point to start of actual sig */
2210 PUT_32BIT(newlen
, len
);
2211 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 4);
2212 /* dmemdump(newlen, 4); */
2214 while (len
-- > siglen
) {
2215 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 1);
2216 /* dmemdump(newlen, 1); */
2218 ssh2_pkt_addstring_data(pkt
, (char *)(sigblob
+pos
), siglen
);
2219 /* dmemdump(sigblob+pos, siglen); */
2223 /* Otherwise fall through and do it the easy way. */
2226 ssh2_pkt_addstring_start(pkt
);
2227 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, sigblob_len
);
2231 * Examine the remote side's version string and compare it against
2232 * a list of known buggy implementations.
2234 static void ssh_detect_bugs(Ssh ssh
, char *vstring
)
2236 char *imp
; /* pointer to implementation part */
2238 imp
+= strcspn(imp
, "-");
2240 imp
+= strcspn(imp
, "-");
2243 ssh
->remote_bugs
= 0;
2246 * General notes on server version strings:
2247 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2248 * here -- in particular, we've heard of one that's perfectly happy
2249 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2250 * so we can't distinguish them.
2252 if (ssh
->cfg
.sshbug_ignore1
== FORCE_ON
||
2253 (ssh
->cfg
.sshbug_ignore1
== AUTO
&&
2254 (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
2255 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
2256 !strcmp(imp
, "1.2.22") || !strcmp(imp
, "Cisco-1.25") ||
2257 !strcmp(imp
, "OSU_1.4alpha3") || !strcmp(imp
, "OSU_1.5alpha4")))) {
2259 * These versions don't support SSH1_MSG_IGNORE, so we have
2260 * to use a different defence against password length
2263 ssh
->remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
2264 logevent("We believe remote version has SSH-1 ignore bug");
2267 if (ssh
->cfg
.sshbug_plainpw1
== FORCE_ON
||
2268 (ssh
->cfg
.sshbug_plainpw1
== AUTO
&&
2269 (!strcmp(imp
, "Cisco-1.25") || !strcmp(imp
, "OSU_1.4alpha3")))) {
2271 * These versions need a plain password sent; they can't
2272 * handle having a null and a random length of data after
2275 ssh
->remote_bugs
|= BUG_NEEDS_SSH1_PLAIN_PASSWORD
;
2276 logevent("We believe remote version needs a plain SSH-1 password");
2279 if (ssh
->cfg
.sshbug_rsa1
== FORCE_ON
||
2280 (ssh
->cfg
.sshbug_rsa1
== AUTO
&&
2281 (!strcmp(imp
, "Cisco-1.25")))) {
2283 * These versions apparently have no clue whatever about
2284 * RSA authentication and will panic and die if they see
2285 * an AUTH_RSA message.
2287 ssh
->remote_bugs
|= BUG_CHOKES_ON_RSA
;
2288 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2291 if (ssh
->cfg
.sshbug_hmac2
== FORCE_ON
||
2292 (ssh
->cfg
.sshbug_hmac2
== AUTO
&&
2293 !wc_match("* VShell", imp
) &&
2294 (wc_match("2.1.0*", imp
) || wc_match("2.0.*", imp
) ||
2295 wc_match("2.2.0*", imp
) || wc_match("2.3.0*", imp
) ||
2296 wc_match("2.1 *", imp
)))) {
2298 * These versions have the HMAC bug.
2300 ssh
->remote_bugs
|= BUG_SSH2_HMAC
;
2301 logevent("We believe remote version has SSH-2 HMAC bug");
2304 if (ssh
->cfg
.sshbug_derivekey2
== FORCE_ON
||
2305 (ssh
->cfg
.sshbug_derivekey2
== AUTO
&&
2306 !wc_match("* VShell", imp
) &&
2307 (wc_match("2.0.0*", imp
) || wc_match("2.0.10*", imp
) ))) {
2309 * These versions have the key-derivation bug (failing to
2310 * include the literal shared secret in the hashes that
2311 * generate the keys).
2313 ssh
->remote_bugs
|= BUG_SSH2_DERIVEKEY
;
2314 logevent("We believe remote version has SSH-2 key-derivation bug");
2317 if (ssh
->cfg
.sshbug_rsapad2
== FORCE_ON
||
2318 (ssh
->cfg
.sshbug_rsapad2
== AUTO
&&
2319 (wc_match("OpenSSH_2.[5-9]*", imp
) ||
2320 wc_match("OpenSSH_3.[0-2]*", imp
)))) {
2322 * These versions have the SSH-2 RSA padding bug.
2324 ssh
->remote_bugs
|= BUG_SSH2_RSA_PADDING
;
2325 logevent("We believe remote version has SSH-2 RSA padding bug");
2328 if (ssh
->cfg
.sshbug_pksessid2
== FORCE_ON
||
2329 (ssh
->cfg
.sshbug_pksessid2
== AUTO
&&
2330 wc_match("OpenSSH_2.[0-2]*", imp
))) {
2332 * These versions have the SSH-2 session-ID bug in
2333 * public-key authentication.
2335 ssh
->remote_bugs
|= BUG_SSH2_PK_SESSIONID
;
2336 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2339 if (ssh
->cfg
.sshbug_rekey2
== FORCE_ON
||
2340 (ssh
->cfg
.sshbug_rekey2
== AUTO
&&
2341 (wc_match("DigiSSH_2.0", imp
) ||
2342 wc_match("OpenSSH_2.[0-4]*", imp
) ||
2343 wc_match("OpenSSH_2.5.[0-3]*", imp
) ||
2344 wc_match("Sun_SSH_1.0", imp
) ||
2345 wc_match("Sun_SSH_1.0.1", imp
) ||
2346 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2347 wc_match("WeOnlyDo-*", imp
)))) {
2349 * These versions have the SSH-2 rekey bug.
2351 ssh
->remote_bugs
|= BUG_SSH2_REKEY
;
2352 logevent("We believe remote version has SSH-2 rekey bug");
2357 * The `software version' part of an SSH version string is required
2358 * to contain no spaces or minus signs.
2360 static void ssh_fix_verstring(char *str
)
2362 /* Eat "SSH-<protoversion>-". */
2363 assert(*str
== 'S'); str
++;
2364 assert(*str
== 'S'); str
++;
2365 assert(*str
== 'H'); str
++;
2366 assert(*str
== '-'); str
++;
2367 while (*str
&& *str
!= '-') str
++;
2368 assert(*str
== '-'); str
++;
2370 /* Convert minus signs and spaces in the remaining string into
2373 if (*str
== '-' || *str
== ' ')
2379 static int do_ssh_init(Ssh ssh
, unsigned char c
)
2381 struct do_ssh_init_state
{
2389 crState(do_ssh_init_state
);
2391 crBegin(ssh
->do_ssh_init_crstate
);
2393 /* Search for a line beginning with the string "SSH-" in the input. */
2395 if (c
!= 'S') goto no
;
2397 if (c
!= 'S') goto no
;
2399 if (c
!= 'H') goto no
;
2401 if (c
!= '-') goto no
;
2410 s
->vstring
= snewn(s
->vstrsize
, char);
2411 strcpy(s
->vstring
, "SSH-");
2415 crReturn(1); /* get another char */
2416 if (s
->vslen
>= s
->vstrsize
- 1) {
2418 s
->vstring
= sresize(s
->vstring
, s
->vstrsize
, char);
2420 s
->vstring
[s
->vslen
++] = c
;
2423 s
->version
[s
->i
] = '\0';
2425 } else if (s
->i
< sizeof(s
->version
) - 1)
2426 s
->version
[s
->i
++] = c
;
2427 } else if (c
== '\012')
2431 ssh
->agentfwd_enabled
= FALSE
;
2432 ssh
->rdpkt2_state
.incoming_sequence
= 0;
2434 s
->vstring
[s
->vslen
] = 0;
2435 s
->vstring
[strcspn(s
->vstring
, "\015\012")] = '\0';/* remove EOL chars */
2436 logeventf(ssh
, "Server version: %s", s
->vstring
);
2437 ssh_detect_bugs(ssh
, s
->vstring
);
2440 * Decide which SSH protocol version to support.
2443 /* Anything strictly below "2.0" means protocol 1 is supported. */
2444 s
->proto1
= ssh_versioncmp(s
->version
, "2.0") < 0;
2445 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2446 s
->proto2
= ssh_versioncmp(s
->version
, "1.99") >= 0;
2448 if (ssh
->cfg
.sshprot
== 0 && !s
->proto1
) {
2449 bombout(("SSH protocol version 1 required by user but not provided by server"));
2452 if (ssh
->cfg
.sshprot
== 3 && !s
->proto2
) {
2453 bombout(("SSH protocol version 2 required by user but not provided by server"));
2460 if (s
->proto2
&& (ssh
->cfg
.sshprot
>= 2 || !s
->proto1
)) {
2462 * Construct a v2 version string.
2464 verstring
= dupprintf("SSH-2.0-%s\015\012", sshver
);
2468 * Construct a v1 version string.
2470 verstring
= dupprintf("SSH-%s-%s\012",
2471 (ssh_versioncmp(s
->version
, "1.5") <= 0 ?
2472 s
->version
: "1.5"),
2477 ssh_fix_verstring(verstring
);
2479 if (ssh
->version
== 2) {
2482 * Hash our version string and their version string.
2484 len
= strcspn(verstring
, "\015\012");
2485 ssh
->v_c
= snewn(len
+ 1, char);
2486 memcpy(ssh
->v_c
, verstring
, len
);
2488 len
= strcspn(s
->vstring
, "\015\012");
2489 ssh
->v_s
= snewn(len
+ 1, char);
2490 memcpy(ssh
->v_s
, s
->vstring
, len
);
2494 * Initialise SSH-2 protocol.
2496 ssh
->protocol
= ssh2_protocol
;
2497 ssh2_protocol_setup(ssh
);
2498 ssh
->s_rdpkt
= ssh2_rdpkt
;
2501 * Initialise SSH-1 protocol.
2503 ssh
->protocol
= ssh1_protocol
;
2504 ssh1_protocol_setup(ssh
);
2505 ssh
->s_rdpkt
= ssh1_rdpkt
;
2507 logeventf(ssh
, "We claim version: %.*s",
2508 strcspn(verstring
, "\015\012"), verstring
);
2509 s_write(ssh
, verstring
, strlen(verstring
));
2511 if (ssh
->version
== 2)
2512 do_ssh2_transport(ssh
, NULL
, -1, NULL
);
2515 logeventf(ssh
, "Using SSH protocol version %d", ssh
->version
);
2517 update_specials_menu(ssh
->frontend
);
2518 ssh
->state
= SSH_STATE_BEFORE_SIZE
;
2519 ssh
->pinger
= pinger_new(&ssh
->cfg
, &ssh_backend
, ssh
);
2526 static void ssh_process_incoming_data(Ssh ssh
,
2527 unsigned char **data
, int *datalen
)
2529 struct Packet
*pktin
;
2531 pktin
= ssh
->s_rdpkt(ssh
, data
, datalen
);
2533 ssh
->protocol(ssh
, NULL
, 0, pktin
);
2534 ssh_free_packet(pktin
);
2538 static void ssh_queue_incoming_data(Ssh ssh
,
2539 unsigned char **data
, int *datalen
)
2541 bufchain_add(&ssh
->queued_incoming_data
, *data
, *datalen
);
2546 static void ssh_process_queued_incoming_data(Ssh ssh
)
2549 unsigned char *data
;
2552 while (!ssh
->frozen
&& bufchain_size(&ssh
->queued_incoming_data
)) {
2553 bufchain_prefix(&ssh
->queued_incoming_data
, &vdata
, &len
);
2557 while (!ssh
->frozen
&& len
> 0)
2558 ssh_process_incoming_data(ssh
, &data
, &len
);
2561 bufchain_consume(&ssh
->queued_incoming_data
, origlen
- len
);
2565 static void ssh_set_frozen(Ssh ssh
, int frozen
)
2568 sk_set_frozen(ssh
->s
, frozen
);
2569 ssh
->frozen
= frozen
;
2572 static void ssh_gotdata(Ssh ssh
, unsigned char *data
, int datalen
)
2574 /* Log raw data, if we're in that mode. */
2575 log_packet(ssh
->logctx
, PKT_INCOMING
, -1, NULL
, data
, datalen
, 0, NULL
);
2577 crBegin(ssh
->ssh_gotdata_crstate
);
2580 * To begin with, feed the characters one by one to the
2581 * protocol initialisation / selection function do_ssh_init().
2582 * When that returns 0, we're done with the initial greeting
2583 * exchange and can move on to packet discipline.
2586 int ret
; /* need not be kept across crReturn */
2588 crReturnV
; /* more data please */
2589 ret
= do_ssh_init(ssh
, *data
);
2597 * We emerge from that loop when the initial negotiation is
2598 * over and we have selected an s_rdpkt function. Now pass
2599 * everything to s_rdpkt, and then pass the resulting packets
2600 * to the proper protocol handler.
2604 while (bufchain_size(&ssh
->queued_incoming_data
) > 0 || datalen
> 0) {
2606 ssh_queue_incoming_data(ssh
, &data
, &datalen
);
2607 /* This uses up all data and cannot cause anything interesting
2608 * to happen; indeed, for anything to happen at all, we must
2609 * return, so break out. */
2611 } else if (bufchain_size(&ssh
->queued_incoming_data
) > 0) {
2612 /* This uses up some or all data, and may freeze the
2614 ssh_process_queued_incoming_data(ssh
);
2616 /* This uses up some or all data, and may freeze the
2618 ssh_process_incoming_data(ssh
, &data
, &datalen
);
2620 /* FIXME this is probably EBW. */
2621 if (ssh
->state
== SSH_STATE_CLOSED
)
2624 /* We're out of data. Go and get some more. */
2630 static int ssh_do_close(Ssh ssh
, int notify_exit
)
2633 struct ssh_channel
*c
;
2635 ssh
->state
= SSH_STATE_CLOSED
;
2636 expire_timer_context(ssh
);
2641 notify_remote_exit(ssh
->frontend
);
2646 * Now we must shut down any port- and X-forwarded channels going
2647 * through this connection.
2649 if (ssh
->channels
) {
2650 while (NULL
!= (c
= index234(ssh
->channels
, 0))) {
2653 x11_close(c
->u
.x11
.s
);
2656 pfd_close(c
->u
.pfd
.s
);
2659 del234(ssh
->channels
, c
); /* moving next one to index 0 */
2660 if (ssh
->version
== 2)
2661 bufchain_clear(&c
->v
.v2
.outbuffer
);
2666 * Go through port-forwardings, and close any associated
2667 * listening sockets.
2669 if (ssh
->portfwds
) {
2670 struct ssh_portfwd
*pf
;
2671 while (NULL
!= (pf
= index234(ssh
->portfwds
, 0))) {
2672 /* Dispose of any listening socket. */
2674 pfd_terminate(pf
->local
);
2675 del234(ssh
->portfwds
, pf
); /* moving next one to index 0 */
2683 static void ssh_log(Plug plug
, int type
, SockAddr addr
, int port
,
2684 const char *error_msg
, int error_code
)
2686 Ssh ssh
= (Ssh
) plug
;
2687 char addrbuf
[256], *msg
;
2689 sk_getaddr(addr
, addrbuf
, lenof(addrbuf
));
2692 msg
= dupprintf("Connecting to %s port %d", addrbuf
, port
);
2694 msg
= dupprintf("Failed to connect to %s: %s", addrbuf
, error_msg
);
2700 static int ssh_closing(Plug plug
, const char *error_msg
, int error_code
,
2703 Ssh ssh
= (Ssh
) plug
;
2704 int need_notify
= ssh_do_close(ssh
, FALSE
);
2707 if (!ssh
->close_expected
)
2708 error_msg
= "Server unexpectedly closed network connection";
2710 error_msg
= "Server closed network connection";
2713 if (ssh
->close_expected
&& ssh
->clean_exit
&& ssh
->exitcode
< 0)
2717 notify_remote_exit(ssh
->frontend
);
2720 logevent(error_msg
);
2721 if (!ssh
->close_expected
|| !ssh
->clean_exit
)
2722 connection_fatal(ssh
->frontend
, "%s", error_msg
);
2726 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
2728 Ssh ssh
= (Ssh
) plug
;
2729 ssh_gotdata(ssh
, (unsigned char *)data
, len
);
2730 if (ssh
->state
== SSH_STATE_CLOSED
) {
2731 ssh_do_close(ssh
, TRUE
);
2737 static void ssh_sent(Plug plug
, int bufsize
)
2739 Ssh ssh
= (Ssh
) plug
;
2741 * If the send backlog on the SSH socket itself clears, we
2742 * should unthrottle the whole world if it was throttled.
2744 if (bufsize
< SSH_MAX_BACKLOG
)
2745 ssh_throttle_all(ssh
, 0, bufsize
);
2749 * Connect to specified host and port.
2750 * Returns an error message, or NULL on success.
2751 * Also places the canonical host name into `realhost'. It must be
2752 * freed by the caller.
2754 static const char *connect_to_host(Ssh ssh
, char *host
, int port
,
2755 char **realhost
, int nodelay
, int keepalive
)
2757 static const struct plug_function_table fn_table
= {
2768 ssh
->savedhost
= snewn(1 + strlen(host
), char);
2769 strcpy(ssh
->savedhost
, host
);
2772 port
= 22; /* default ssh port */
2773 ssh
->savedport
= port
;
2778 logeventf(ssh
, "Looking up host \"%s\"%s", host
,
2779 (ssh
->cfg
.addressfamily
== ADDRTYPE_IPV4 ?
" (IPv4)" :
2780 (ssh
->cfg
.addressfamily
== ADDRTYPE_IPV6 ?
" (IPv6)" : "")));
2781 addr
= name_lookup(host
, port
, realhost
, &ssh
->cfg
,
2782 ssh
->cfg
.addressfamily
);
2783 if ((err
= sk_addr_error(addr
)) != NULL
) {
2791 ssh
->fn
= &fn_table
;
2792 ssh
->s
= new_connection(addr
, *realhost
, port
,
2793 0, 1, nodelay
, keepalive
, (Plug
) ssh
, &ssh
->cfg
);
2794 if ((err
= sk_socket_error(ssh
->s
)) != NULL
) {
2796 notify_remote_exit(ssh
->frontend
);
2804 * Throttle or unthrottle the SSH connection.
2806 static void ssh1_throttle(Ssh ssh
, int adjust
)
2808 int old_count
= ssh
->v1_throttle_count
;
2809 ssh
->v1_throttle_count
+= adjust
;
2810 assert(ssh
->v1_throttle_count
>= 0);
2811 if (ssh
->v1_throttle_count
&& !old_count
) {
2812 ssh_set_frozen(ssh
, 1);
2813 } else if (!ssh
->v1_throttle_count
&& old_count
) {
2814 ssh_set_frozen(ssh
, 0);
2819 * Throttle or unthrottle _all_ local data streams (for when sends
2820 * on the SSH connection itself back up).
2822 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
)
2825 struct ssh_channel
*c
;
2827 if (enable
== ssh
->throttled_all
)
2829 ssh
->throttled_all
= enable
;
2830 ssh
->overall_bufsize
= bufsize
;
2833 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
2835 case CHAN_MAINSESSION
:
2837 * This is treated separately, outside the switch.
2841 x11_override_throttle(c
->u
.x11
.s
, enable
);
2844 /* Agent channels require no buffer management. */
2847 pfd_override_throttle(c
->u
.pfd
.s
, enable
);
2853 static void ssh_agent_callback(void *sshv
, void *reply
, int replylen
)
2855 Ssh ssh
= (Ssh
) sshv
;
2857 ssh
->agent_response
= reply
;
2858 ssh
->agent_response_len
= replylen
;
2860 if (ssh
->version
== 1)
2861 do_ssh1_login(ssh
, NULL
, -1, NULL
);
2863 do_ssh2_authconn(ssh
, NULL
, -1, NULL
);
2866 static void ssh_dialog_callback(void *sshv
, int ret
)
2868 Ssh ssh
= (Ssh
) sshv
;
2870 ssh
->user_response
= ret
;
2872 if (ssh
->version
== 1)
2873 do_ssh1_login(ssh
, NULL
, -1, NULL
);
2875 do_ssh2_transport(ssh
, NULL
, -1, NULL
);
2878 * This may have unfrozen the SSH connection, so do a
2881 ssh_process_queued_incoming_data(ssh
);
2884 static void ssh_agentf_callback(void *cv
, void *reply
, int replylen
)
2886 struct ssh_channel
*c
= (struct ssh_channel
*)cv
;
2888 void *sentreply
= reply
;
2891 /* Fake SSH_AGENT_FAILURE. */
2892 sentreply
= "\0\0\0\1\5";
2895 if (ssh
->version
== 2) {
2896 ssh2_add_channel_data(c
, sentreply
, replylen
);
2899 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
2900 PKT_INT
, c
->remoteid
,
2903 PKT_DATA
, sentreply
, replylen
,
2912 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
2913 * non-NULL, otherwise just close the connection. `client_reason' == NULL
2914 * => log `wire_reason'.
2916 static void ssh_disconnect(Ssh ssh
, char *client_reason
, char *wire_reason
,
2917 int code
, int clean_exit
)
2921 client_reason
= wire_reason
;
2923 error
= dupprintf("Disconnected: %s", client_reason
);
2925 error
= dupstr("Disconnected");
2927 if (ssh
->version
== 1) {
2928 send_packet(ssh
, SSH1_MSG_DISCONNECT
, PKT_STR
, wire_reason
,
2930 } else if (ssh
->version
== 2) {
2931 struct Packet
*pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
2932 ssh2_pkt_adduint32(pktout
, code
);
2933 ssh2_pkt_addstring(pktout
, wire_reason
);
2934 ssh2_pkt_addstring(pktout
, "en"); /* language tag */
2935 ssh2_pkt_send_noqueue(ssh
, pktout
);
2938 ssh
->close_expected
= TRUE
;
2939 ssh
->clean_exit
= clean_exit
;
2940 ssh_closing((Plug
)ssh
, error
, 0, 0);
2945 * Handle the key exchange and user authentication phases.
2947 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
,
2948 struct Packet
*pktin
)
2951 unsigned char cookie
[8], *ptr
;
2952 struct RSAKey servkey
, hostkey
;
2953 struct MD5Context md5c
;
2954 struct do_ssh1_login_state
{
2956 unsigned char *rsabuf
, *keystr1
, *keystr2
;
2957 unsigned long supported_ciphers_mask
, supported_auths_mask
;
2958 int tried_publickey
, tried_agent
;
2959 int tis_auth_refused
, ccard_auth_refused
;
2960 unsigned char session_id
[16];
2963 void *publickey_blob
;
2964 int publickey_bloblen
;
2965 char *publickey_comment
;
2966 int publickey_encrypted
;
2967 prompts_t
*cur_prompt
;
2970 unsigned char request
[5], *response
, *p
;
2980 crState(do_ssh1_login_state
);
2982 crBegin(ssh
->do_ssh1_login_crstate
);
2987 if (pktin
->type
!= SSH1_SMSG_PUBLIC_KEY
) {
2988 bombout(("Public key packet not received"));
2992 logevent("Received public keys");
2994 ptr
= ssh_pkt_getdata(pktin
, 8);
2996 bombout(("SSH-1 public key packet stopped before random cookie"));
2999 memcpy(cookie
, ptr
, 8);
3001 if (!ssh1_pkt_getrsakey(pktin
, &servkey
, &s
->keystr1
) ||
3002 !ssh1_pkt_getrsakey(pktin
, &hostkey
, &s
->keystr2
)) {
3003 bombout(("Failed to read SSH-1 public keys from public key packet"));
3008 * Log the host key fingerprint.
3012 logevent("Host key fingerprint is:");
3013 strcpy(logmsg
, " ");
3014 hostkey
.comment
= NULL
;
3015 rsa_fingerprint(logmsg
+ strlen(logmsg
),
3016 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
3020 ssh
->v1_remote_protoflags
= ssh_pkt_getuint32(pktin
);
3021 s
->supported_ciphers_mask
= ssh_pkt_getuint32(pktin
);
3022 s
->supported_auths_mask
= ssh_pkt_getuint32(pktin
);
3024 ssh
->v1_local_protoflags
=
3025 ssh
->v1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
3026 ssh
->v1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
3029 MD5Update(&md5c
, s
->keystr2
, hostkey
.bytes
);
3030 MD5Update(&md5c
, s
->keystr1
, servkey
.bytes
);
3031 MD5Update(&md5c
, cookie
, 8);
3032 MD5Final(s
->session_id
, &md5c
);
3034 for (i
= 0; i
< 32; i
++)
3035 ssh
->session_key
[i
] = random_byte();
3038 * Verify that the `bits' and `bytes' parameters match.
3040 if (hostkey
.bits
> hostkey
.bytes
* 8 ||
3041 servkey
.bits
> servkey
.bytes
* 8) {
3042 bombout(("SSH-1 public keys were badly formatted"));
3046 s
->len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
3048 s
->rsabuf
= snewn(s
->len
, unsigned char);
3051 * Verify the host key.
3055 * First format the key into a string.
3057 int len
= rsastr_len(&hostkey
);
3058 char fingerprint
[100];
3059 char *keystr
= snewn(len
, char);
3060 rsastr_fmt(keystr
, &hostkey
);
3061 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
3063 ssh_set_frozen(ssh
, 1);
3064 s
->dlgret
= verify_ssh_host_key(ssh
->frontend
,
3065 ssh
->savedhost
, ssh
->savedport
,
3066 "rsa", keystr
, fingerprint
,
3067 ssh_dialog_callback
, ssh
);
3069 if (s
->dlgret
< 0) {
3073 bombout(("Unexpected data from server while waiting"
3074 " for user host key response"));
3077 } while (pktin
|| inlen
> 0);
3078 s
->dlgret
= ssh
->user_response
;
3080 ssh_set_frozen(ssh
, 0);
3082 if (s
->dlgret
== 0) {
3083 ssh_disconnect(ssh
, "User aborted at host key verification",
3089 for (i
= 0; i
< 32; i
++) {
3090 s
->rsabuf
[i
] = ssh
->session_key
[i
];
3092 s
->rsabuf
[i
] ^= s
->session_id
[i
];
3095 if (hostkey
.bytes
> servkey
.bytes
) {
3096 ret
= rsaencrypt(s
->rsabuf
, 32, &servkey
);
3098 ret
= rsaencrypt(s
->rsabuf
, servkey
.bytes
, &hostkey
);
3100 ret
= rsaencrypt(s
->rsabuf
, 32, &hostkey
);
3102 ret
= rsaencrypt(s
->rsabuf
, hostkey
.bytes
, &servkey
);
3105 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3109 logevent("Encrypted session key");
3112 int cipher_chosen
= 0, warn
= 0;
3113 char *cipher_string
= NULL
;
3115 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
3116 int next_cipher
= ssh
->cfg
.ssh_cipherlist
[i
];
3117 if (next_cipher
== CIPHER_WARN
) {
3118 /* If/when we choose a cipher, warn about it */
3120 } else if (next_cipher
== CIPHER_AES
) {
3121 /* XXX Probably don't need to mention this. */
3122 logevent("AES not supported in SSH-1, skipping");
3124 switch (next_cipher
) {
3125 case CIPHER_3DES
: s
->cipher_type
= SSH_CIPHER_3DES
;
3126 cipher_string
= "3DES"; break;
3127 case CIPHER_BLOWFISH
: s
->cipher_type
= SSH_CIPHER_BLOWFISH
;
3128 cipher_string
= "Blowfish"; break;
3129 case CIPHER_DES
: s
->cipher_type
= SSH_CIPHER_DES
;
3130 cipher_string
= "single-DES"; break;
3132 if (s
->supported_ciphers_mask
& (1 << s
->cipher_type
))
3136 if (!cipher_chosen
) {
3137 if ((s
->supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
3138 bombout(("Server violates SSH-1 protocol by not "
3139 "supporting 3DES encryption"));
3141 /* shouldn't happen */
3142 bombout(("No supported ciphers found"));
3146 /* Warn about chosen cipher if necessary. */
3148 ssh_set_frozen(ssh
, 1);
3149 s
->dlgret
= askalg(ssh
->frontend
, "cipher", cipher_string
,
3150 ssh_dialog_callback
, ssh
);
3151 if (s
->dlgret
< 0) {
3155 bombout(("Unexpected data from server while waiting"
3156 " for user response"));
3159 } while (pktin
|| inlen
> 0);
3160 s
->dlgret
= ssh
->user_response
;
3162 ssh_set_frozen(ssh
, 0);
3163 if (s
->dlgret
== 0) {
3164 ssh_disconnect(ssh
, "User aborted at cipher warning", NULL
,
3171 switch (s
->cipher_type
) {
3172 case SSH_CIPHER_3DES
:
3173 logevent("Using 3DES encryption");
3175 case SSH_CIPHER_DES
:
3176 logevent("Using single-DES encryption");
3178 case SSH_CIPHER_BLOWFISH
:
3179 logevent("Using Blowfish encryption");
3183 send_packet(ssh
, SSH1_CMSG_SESSION_KEY
,
3184 PKT_CHAR
, s
->cipher_type
,
3185 PKT_DATA
, cookie
, 8,
3186 PKT_CHAR
, (s
->len
* 8) >> 8, PKT_CHAR
, (s
->len
* 8) & 0xFF,
3187 PKT_DATA
, s
->rsabuf
, s
->len
,
3188 PKT_INT
, ssh
->v1_local_protoflags
, PKT_END
);
3190 logevent("Trying to enable encryption...");
3194 ssh
->cipher
= (s
->cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
3195 s
->cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
3197 ssh
->v1_cipher_ctx
= ssh
->cipher
->make_context();
3198 ssh
->cipher
->sesskey(ssh
->v1_cipher_ctx
, ssh
->session_key
);
3199 logeventf(ssh
, "Initialised %s encryption", ssh
->cipher
->text_name
);
3201 ssh
->crcda_ctx
= crcda_make_context();
3202 logevent("Installing CRC compensation attack detector");
3204 if (servkey
.modulus
) {
3205 sfree(servkey
.modulus
);
3206 servkey
.modulus
= NULL
;
3208 if (servkey
.exponent
) {
3209 sfree(servkey
.exponent
);
3210 servkey
.exponent
= NULL
;
3212 if (hostkey
.modulus
) {
3213 sfree(hostkey
.modulus
);
3214 hostkey
.modulus
= NULL
;
3216 if (hostkey
.exponent
) {
3217 sfree(hostkey
.exponent
);
3218 hostkey
.exponent
= NULL
;
3222 if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3223 bombout(("Encryption not successfully enabled"));
3227 logevent("Successfully started encryption");
3229 fflush(stdout
); /* FIXME eh? */
3231 if (!*ssh
->cfg
.username
) {
3232 int ret
; /* need not be kept over crReturn */
3233 s
->cur_prompt
= new_prompts(ssh
->frontend
);
3234 s
->cur_prompt
->to_server
= TRUE
;
3235 s
->cur_prompt
->name
= dupstr("SSH login name");
3236 add_prompt(s
->cur_prompt
, dupstr("login as: "), TRUE
,
3237 lenof(s
->username
));
3238 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
3241 crWaitUntil(!pktin
);
3242 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
3247 * Failed to get a username. Terminate.
3249 free_prompts(s
->cur_prompt
);
3250 ssh_disconnect(ssh
, "No username provided", NULL
, 0, TRUE
);
3253 memcpy(s
->username
, s
->cur_prompt
->prompts
[0]->result
,
3254 lenof(s
->username
));
3255 free_prompts(s
->cur_prompt
);
3257 strncpy(s
->username
, ssh
->cfg
.username
, sizeof(s
->username
));
3258 s
->username
[sizeof(s
->username
)-1] = '\0';
3261 send_packet(ssh
, SSH1_CMSG_USER
, PKT_STR
, s
->username
, PKT_END
);
3263 char *userlog
= dupprintf("Sent username \"%s\"", s
->username
);
3265 if (flags
& FLAG_INTERACTIVE
&&
3266 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
3267 c_write_str(ssh
, userlog
);
3268 c_write_str(ssh
, "\r\n");
3276 if ((ssh
->remote_bugs
& BUG_CHOKES_ON_RSA
)) {
3277 /* We must not attempt PK auth. Pretend we've already tried it. */
3278 s
->tried_publickey
= s
->tried_agent
= 1;
3280 s
->tried_publickey
= s
->tried_agent
= 0;
3282 s
->tis_auth_refused
= s
->ccard_auth_refused
= 0;
3284 * Load the public half of any configured keyfile for later use.
3286 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
3288 logeventf(ssh
, "Reading private key file \"%.150s\"",
3289 filename_to_str(&ssh
->cfg
.keyfile
));
3290 keytype
= key_type(&ssh
->cfg
.keyfile
);
3291 if (keytype
== SSH_KEYTYPE_SSH1
) {
3293 if (rsakey_pubblob(&ssh
->cfg
.keyfile
,
3294 &s
->publickey_blob
, &s
->publickey_bloblen
,
3295 &s
->publickey_comment
, &error
)) {
3296 s
->publickey_encrypted
= rsakey_encrypted(&ssh
->cfg
.keyfile
,
3300 logeventf(ssh
, "Unable to load private key (%s)", error
);
3301 msgbuf
= dupprintf("Unable to load private key file "
3302 "\"%.150s\" (%s)\r\n",
3303 filename_to_str(&ssh
->cfg
.keyfile
),
3305 c_write_str(ssh
, msgbuf
);
3307 s
->publickey_blob
= NULL
;
3311 logeventf(ssh
, "Unable to use this key file (%s)",
3312 key_type_to_str(keytype
));
3313 msgbuf
= dupprintf("Unable to use key file \"%.150s\""
3315 filename_to_str(&ssh
->cfg
.keyfile
),
3316 key_type_to_str(keytype
));
3317 c_write_str(ssh
, msgbuf
);
3319 s
->publickey_blob
= NULL
;
3322 s
->publickey_blob
= NULL
;
3324 while (pktin
->type
== SSH1_SMSG_FAILURE
) {
3325 s
->pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
3327 if (ssh
->cfg
.tryagent
&& agent_exists() && !s
->tried_agent
) {
3329 * Attempt RSA authentication using Pageant.
3335 logevent("Pageant is running. Requesting keys.");
3337 /* Request the keys held by the agent. */
3338 PUT_32BIT(s
->request
, 1);
3339 s
->request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
3340 if (!agent_query(s
->request
, 5, &r
, &s
->responselen
,
3341 ssh_agent_callback
, ssh
)) {
3345 bombout(("Unexpected data from server while waiting"
3346 " for agent response"));
3349 } while (pktin
|| inlen
> 0);
3350 r
= ssh
->agent_response
;
3351 s
->responselen
= ssh
->agent_response_len
;
3353 s
->response
= (unsigned char *) r
;
3354 if (s
->response
&& s
->responselen
>= 5 &&
3355 s
->response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
3356 s
->p
= s
->response
+ 5;
3357 s
->nkeys
= GET_32BIT(s
->p
);
3359 logeventf(ssh
, "Pageant has %d SSH-1 keys", s
->nkeys
);
3360 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
3361 unsigned char *pkblob
= s
->p
;
3365 do { /* do while (0) to make breaking easy */
3366 n
= ssh1_read_bignum
3367 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
3372 n
= ssh1_read_bignum
3373 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
3378 if (s
->responselen
- (s
->p
-s
->response
) < 4)
3380 s
->commentlen
= GET_32BIT(s
->p
);
3382 if (s
->responselen
- (s
->p
-s
->response
) <
3385 s
->commentp
= (char *)s
->p
;
3386 s
->p
+= s
->commentlen
;
3390 logevent("Pageant key list packet was truncated");
3394 if (s
->publickey_blob
) {
3395 if (!memcmp(pkblob
, s
->publickey_blob
,
3396 s
->publickey_bloblen
)) {
3397 logeventf(ssh
, "Pageant key #%d matches "
3398 "configured key file", s
->keyi
);
3399 s
->tried_publickey
= 1;
3401 /* Skip non-configured key */
3404 logeventf(ssh
, "Trying Pageant key #%d", s
->keyi
);
3405 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
3406 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
3408 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
3409 logevent("Key refused");
3412 logevent("Received RSA challenge");
3413 if ((s
->challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
3414 bombout(("Server's RSA challenge was badly formatted"));
3419 char *agentreq
, *q
, *ret
;
3422 len
= 1 + 4; /* message type, bit count */
3423 len
+= ssh1_bignum_length(s
->key
.exponent
);
3424 len
+= ssh1_bignum_length(s
->key
.modulus
);
3425 len
+= ssh1_bignum_length(s
->challenge
);
3426 len
+= 16; /* session id */
3427 len
+= 4; /* response format */
3428 agentreq
= snewn(4 + len
, char);
3429 PUT_32BIT(agentreq
, len
);
3431 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
3432 PUT_32BIT(q
, bignum_bitcount(s
->key
.modulus
));
3434 q
+= ssh1_write_bignum(q
, s
->key
.exponent
);
3435 q
+= ssh1_write_bignum(q
, s
->key
.modulus
);
3436 q
+= ssh1_write_bignum(q
, s
->challenge
);
3437 memcpy(q
, s
->session_id
, 16);
3439 PUT_32BIT(q
, 1); /* response format */
3440 if (!agent_query(agentreq
, len
+ 4, &vret
, &retlen
,
3441 ssh_agent_callback
, ssh
)) {
3446 bombout(("Unexpected data from server"
3447 " while waiting for agent"
3451 } while (pktin
|| inlen
> 0);
3452 vret
= ssh
->agent_response
;
3453 retlen
= ssh
->agent_response_len
;
3458 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
3459 logevent("Sending Pageant's response");
3460 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
3461 PKT_DATA
, ret
+ 5, 16,
3465 if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
3467 ("Pageant's response accepted");
3468 if (flags
& FLAG_VERBOSE
) {
3469 c_write_str(ssh
, "Authenticated using"
3471 c_write(ssh
, s
->commentp
,
3473 c_write_str(ssh
, "\" from agent\r\n");
3478 ("Pageant's response not accepted");
3481 ("Pageant failed to answer challenge");
3485 logevent("No reply received from Pageant");
3488 freebn(s
->key
.exponent
);
3489 freebn(s
->key
.modulus
);
3490 freebn(s
->challenge
);
3495 if (s
->publickey_blob
&& !s
->tried_publickey
)
3496 logevent("Configured key file not in Pageant");
3501 if (s
->publickey_blob
&& !s
->tried_publickey
) {
3503 * Try public key authentication with the specified
3506 int got_passphrase
; /* need not be kept over crReturn */
3507 if (flags
& FLAG_VERBOSE
)
3508 c_write_str(ssh
, "Trying public key authentication.\r\n");
3509 logeventf(ssh
, "Trying public key \"%s\"",
3510 filename_to_str(&ssh
->cfg
.keyfile
));
3511 s
->tried_publickey
= 1;
3512 got_passphrase
= FALSE
;
3513 while (!got_passphrase
) {
3515 * Get a passphrase, if necessary.
3517 char *passphrase
= NULL
; /* only written after crReturn */
3519 if (!s
->publickey_encrypted
) {
3520 if (flags
& FLAG_VERBOSE
)
3521 c_write_str(ssh
, "No passphrase required.\r\n");
3524 int ret
; /* need not be kept over crReturn */
3525 s
->cur_prompt
= new_prompts(ssh
->frontend
);
3526 s
->cur_prompt
->to_server
= FALSE
;
3527 s
->cur_prompt
->name
= dupstr("SSH key passphrase");
3528 add_prompt(s
->cur_prompt
,
3529 dupprintf("Passphrase for key \"%.100s\": ",
3530 s
->publickey_comment
),
3531 FALSE
, SSH_MAX_PASSWORD_LEN
);
3532 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
3535 crWaitUntil(!pktin
);
3536 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
3540 /* Failed to get a passphrase. Terminate. */
3541 free_prompts(s
->cur_prompt
);
3542 ssh_disconnect(ssh
, NULL
, "Unable to authenticate",
3546 passphrase
= dupstr(s
->cur_prompt
->prompts
[0]->result
);
3547 free_prompts(s
->cur_prompt
);
3550 * Try decrypting key with passphrase.
3552 ret
= loadrsakey(&ssh
->cfg
.keyfile
, &s
->key
, passphrase
,
3555 memset(passphrase
, 0, strlen(passphrase
));
3559 /* Correct passphrase. */
3560 got_passphrase
= TRUE
;
3561 } else if (ret
== 0) {
3562 c_write_str(ssh
, "Couldn't load private key from ");
3563 c_write_str(ssh
, filename_to_str(&ssh
->cfg
.keyfile
));
3564 c_write_str(ssh
, " (");
3565 c_write_str(ssh
, error
);
3566 c_write_str(ssh
, ").\r\n");
3567 got_passphrase
= FALSE
;
3568 break; /* go and try something else */
3569 } else if (ret
== -1) {
3570 c_write_str(ssh
, "Wrong passphrase.\r\n"); /* FIXME */
3571 got_passphrase
= FALSE
;
3574 assert(0 && "unexpected return from loadrsakey()");
3575 got_passphrase
= FALSE
; /* placate optimisers */
3579 if (got_passphrase
) {
3582 * Send a public key attempt.
3584 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
3585 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
3588 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3589 c_write_str(ssh
, "Server refused our public key.\r\n");
3590 continue; /* go and try something else */
3592 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
3593 bombout(("Bizarre response to offer of public key"));
3599 unsigned char buffer
[32];
3600 Bignum challenge
, response
;
3602 if ((challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
3603 bombout(("Server's RSA challenge was badly formatted"));
3606 response
= rsadecrypt(challenge
, &s
->key
);
3607 freebn(s
->key
.private_exponent
);/* burn the evidence */
3609 for (i
= 0; i
< 32; i
++) {
3610 buffer
[i
] = bignum_byte(response
, 31 - i
);
3614 MD5Update(&md5c
, buffer
, 32);
3615 MD5Update(&md5c
, s
->session_id
, 16);
3616 MD5Final(buffer
, &md5c
);
3618 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
3619 PKT_DATA
, buffer
, 16, PKT_END
);
3626 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3627 if (flags
& FLAG_VERBOSE
)
3628 c_write_str(ssh
, "Failed to authenticate with"
3629 " our public key.\r\n");
3630 continue; /* go and try something else */
3631 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3632 bombout(("Bizarre response to RSA authentication response"));
3636 break; /* we're through! */
3642 * Otherwise, try various forms of password-like authentication.
3644 s
->cur_prompt
= new_prompts(ssh
->frontend
);
3646 if (ssh
->cfg
.try_tis_auth
&&
3647 (s
->supported_auths_mask
& (1 << SSH1_AUTH_TIS
)) &&
3648 !s
->tis_auth_refused
) {
3649 s
->pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
3650 logevent("Requested TIS authentication");
3651 send_packet(ssh
, SSH1_CMSG_AUTH_TIS
, PKT_END
);
3653 if (pktin
->type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
3654 logevent("TIS authentication declined");
3655 if (flags
& FLAG_INTERACTIVE
)
3656 c_write_str(ssh
, "TIS authentication refused.\r\n");
3657 s
->tis_auth_refused
= 1;
3662 char *instr_suf
, *prompt
;
3664 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
3666 bombout(("TIS challenge packet was badly formed"));
3669 logevent("Received TIS challenge");
3670 s
->cur_prompt
->to_server
= TRUE
;
3671 s
->cur_prompt
->name
= dupstr("SSH TIS authentication");
3672 /* Prompt heuristic comes from OpenSSH */
3673 if (memchr(challenge
, '\n', challengelen
)) {
3674 instr_suf
= dupstr("");
3675 prompt
= dupprintf("%.*s", challengelen
, challenge
);
3677 instr_suf
= dupprintf("%.*s", challengelen
, challenge
);
3678 prompt
= dupstr("Response: ");
3680 s
->cur_prompt
->instruction
=
3681 dupprintf("Using TIS authentication.%s%s",
3682 (*instr_suf
) ?
"\n" : "",
3684 s
->cur_prompt
->instr_reqd
= TRUE
;
3685 add_prompt(s
->cur_prompt
, prompt
, FALSE
, SSH_MAX_PASSWORD_LEN
);
3689 if (ssh
->cfg
.try_tis_auth
&&
3690 (s
->supported_auths_mask
& (1 << SSH1_AUTH_CCARD
)) &&
3691 !s
->ccard_auth_refused
) {
3692 s
->pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
3693 logevent("Requested CryptoCard authentication");
3694 send_packet(ssh
, SSH1_CMSG_AUTH_CCARD
, PKT_END
);
3696 if (pktin
->type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
3697 logevent("CryptoCard authentication declined");
3698 c_write_str(ssh
, "CryptoCard authentication refused.\r\n");
3699 s
->ccard_auth_refused
= 1;
3704 char *instr_suf
, *prompt
;
3706 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
3708 bombout(("CryptoCard challenge packet was badly formed"));
3711 logevent("Received CryptoCard challenge");
3712 s
->cur_prompt
->to_server
= TRUE
;
3713 s
->cur_prompt
->name
= dupstr("SSH CryptoCard authentication");
3714 s
->cur_prompt
->name_reqd
= FALSE
;
3715 /* Prompt heuristic comes from OpenSSH */
3716 if (memchr(challenge
, '\n', challengelen
)) {
3717 instr_suf
= dupstr("");
3718 prompt
= dupprintf("%.*s", challengelen
, challenge
);
3720 instr_suf
= dupprintf("%.*s", challengelen
, challenge
);
3721 prompt
= dupstr("Response: ");
3723 s
->cur_prompt
->instruction
=
3724 dupprintf("Using CryptoCard authentication.%s%s",
3725 (*instr_suf
) ?
"\n" : "",
3727 s
->cur_prompt
->instr_reqd
= TRUE
;
3728 add_prompt(s
->cur_prompt
, prompt
, FALSE
, SSH_MAX_PASSWORD_LEN
);
3732 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
3733 s
->cur_prompt
->to_server
= TRUE
;
3734 s
->cur_prompt
->name
= dupstr("SSH password");
3735 add_prompt(s
->cur_prompt
, dupprintf("%.90s@%.90s's password: ",
3736 s
->username
, ssh
->savedhost
),
3737 FALSE
, SSH_MAX_PASSWORD_LEN
);
3741 * Show password prompt, having first obtained it via a TIS
3742 * or CryptoCard exchange if we're doing TIS or CryptoCard
3746 int ret
; /* need not be kept over crReturn */
3747 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
3750 crWaitUntil(!pktin
);
3751 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
3756 * Failed to get a password (for example
3757 * because one was supplied on the command line
3758 * which has already failed to work). Terminate.
3760 free_prompts(s
->cur_prompt
);
3761 ssh_disconnect(ssh
, NULL
, "Unable to authenticate", 0, TRUE
);
3766 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
3768 * Defence against traffic analysis: we send a
3769 * whole bunch of packets containing strings of
3770 * different lengths. One of these strings is the
3771 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3772 * The others are all random data in
3773 * SSH1_MSG_IGNORE packets. This way a passive
3774 * listener can't tell which is the password, and
3775 * hence can't deduce the password length.
3777 * Anybody with a password length greater than 16
3778 * bytes is going to have enough entropy in their
3779 * password that a listener won't find it _that_
3780 * much help to know how long it is. So what we'll
3783 * - if password length < 16, we send 15 packets
3784 * containing string lengths 1 through 15
3786 * - otherwise, we let N be the nearest multiple
3787 * of 8 below the password length, and send 8
3788 * packets containing string lengths N through
3789 * N+7. This won't obscure the order of
3790 * magnitude of the password length, but it will
3791 * introduce a bit of extra uncertainty.
3793 * A few servers can't deal with SSH1_MSG_IGNORE, at
3794 * least in this context. For these servers, we need
3795 * an alternative defence. We make use of the fact
3796 * that the password is interpreted as a C string:
3797 * so we can append a NUL, then some random data.
3799 * A few servers can deal with neither SSH1_MSG_IGNORE
3800 * here _nor_ a padded password string.
3801 * For these servers we are left with no defences
3802 * against password length sniffing.
3804 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
) &&
3805 !(ssh
->remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
3807 * The server can deal with SSH1_MSG_IGNORE, so
3808 * we can use the primary defence.
3810 int bottom
, top
, pwlen
, i
;
3813 pwlen
= strlen(s
->cur_prompt
->prompts
[0]->result
);
3815 bottom
= 0; /* zero length passwords are OK! :-) */
3818 bottom
= pwlen
& ~7;
3822 assert(pwlen
>= bottom
&& pwlen
<= top
);
3824 randomstr
= snewn(top
+ 1, char);
3826 for (i
= bottom
; i
<= top
; i
++) {
3828 defer_packet(ssh
, s
->pwpkt_type
,
3829 PKTT_PASSWORD
, PKT_STR
,
3830 s
->cur_prompt
->prompts
[0]->result
,
3831 PKTT_OTHER
, PKT_END
);
3833 for (j
= 0; j
< i
; j
++) {
3835 randomstr
[j
] = random_byte();
3836 } while (randomstr
[j
] == '\0');
3838 randomstr
[i
] = '\0';
3839 defer_packet(ssh
, SSH1_MSG_IGNORE
,
3840 PKT_STR
, randomstr
, PKT_END
);
3843 logevent("Sending password with camouflage packets");
3844 ssh_pkt_defersend(ssh
);
3847 else if (!(ssh
->remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
3849 * The server can't deal with SSH1_MSG_IGNORE
3850 * but can deal with padded passwords, so we
3851 * can use the secondary defence.
3857 len
= strlen(s
->cur_prompt
->prompts
[0]->result
);
3858 if (len
< sizeof(string
)) {
3860 strcpy(string
, s
->cur_prompt
->prompts
[0]->result
);
3861 len
++; /* cover the zero byte */
3862 while (len
< sizeof(string
)) {
3863 string
[len
++] = (char) random_byte();
3866 ss
= s
->cur_prompt
->prompts
[0]->result
;
3868 logevent("Sending length-padded password");
3869 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
3870 PKT_INT
, len
, PKT_DATA
, ss
, len
,
3871 PKTT_OTHER
, PKT_END
);
3874 * The server is believed unable to cope with
3875 * any of our password camouflage methods.
3878 len
= strlen(s
->cur_prompt
->prompts
[0]->result
);
3879 logevent("Sending unpadded password");
3880 send_packet(ssh
, s
->pwpkt_type
,
3881 PKTT_PASSWORD
, PKT_INT
, len
,
3882 PKT_DATA
, s
->cur_prompt
->prompts
[0]->result
, len
,
3883 PKTT_OTHER
, PKT_END
);
3886 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
3887 PKT_STR
, s
->cur_prompt
->prompts
[0]->result
,
3888 PKTT_OTHER
, PKT_END
);
3890 logevent("Sent password");
3891 free_prompts(s
->cur_prompt
);
3893 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3894 if (flags
& FLAG_VERBOSE
)
3895 c_write_str(ssh
, "Access denied\r\n");
3896 logevent("Authentication refused");
3897 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3898 bombout(("Strange packet received, type %d", pktin
->type
));
3904 if (s
->publickey_blob
) {
3905 sfree(s
->publickey_blob
);
3906 sfree(s
->publickey_comment
);
3909 logevent("Authentication successful");
3914 void sshfwd_close(struct ssh_channel
*c
)
3918 if (ssh
->state
== SSH_STATE_CLOSED
)
3921 if (c
&& !c
->closes
) {
3923 * If halfopen is true, we have sent
3924 * CHANNEL_OPEN for this channel, but it hasn't even been
3925 * acknowledged by the server. So we must set a close flag
3926 * on it now, and then when the server acks the channel
3927 * open, we can close it then.
3930 if (ssh
->version
== 1) {
3931 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
3934 struct Packet
*pktout
;
3935 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
3936 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
3937 ssh2_pkt_send(ssh
, pktout
);
3940 c
->closes
= 1; /* sent MSG_CLOSE */
3941 if (c
->type
== CHAN_X11
) {
3943 logevent("Forwarded X11 connection terminated");
3944 } else if (c
->type
== CHAN_SOCKDATA
||
3945 c
->type
== CHAN_SOCKDATA_DORMANT
) {
3947 logevent("Forwarded port closed");
3952 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
3956 if (ssh
->state
== SSH_STATE_CLOSED
)
3959 if (ssh
->version
== 1) {
3960 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
3961 PKT_INT
, c
->remoteid
,
3963 PKT_INT
, len
, PKT_DATA
, buf
, len
,
3964 PKTT_OTHER
, PKT_END
);
3966 * In SSH-1 we can return 0 here - implying that forwarded
3967 * connections are never individually throttled - because
3968 * the only circumstance that can cause throttling will be
3969 * the whole SSH connection backing up, in which case
3970 * _everything_ will be throttled as a whole.
3974 ssh2_add_channel_data(c
, buf
, len
);
3975 return ssh2_try_send(c
);
3979 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
3983 if (ssh
->state
== SSH_STATE_CLOSED
)
3986 if (ssh
->version
== 1) {
3987 if (c
->v
.v1
.throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
3988 c
->v
.v1
.throttling
= 0;
3989 ssh1_throttle(ssh
, -1);
3992 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
3996 static void ssh_queueing_handler(Ssh ssh
, struct Packet
*pktin
)
3998 struct queued_handler
*qh
= ssh
->qhead
;
4002 assert(pktin
->type
== qh
->msg1
|| pktin
->type
== qh
->msg2
);
4005 assert(ssh
->packet_dispatch
[qh
->msg1
] == ssh_queueing_handler
);
4006 ssh
->packet_dispatch
[qh
->msg1
] = NULL
;
4009 assert(ssh
->packet_dispatch
[qh
->msg2
] == ssh_queueing_handler
);
4010 ssh
->packet_dispatch
[qh
->msg2
] = NULL
;
4014 ssh
->qhead
= qh
->next
;
4016 if (ssh
->qhead
->msg1
> 0) {
4017 assert(ssh
->packet_dispatch
[ssh
->qhead
->msg1
] == NULL
);
4018 ssh
->packet_dispatch
[ssh
->qhead
->msg1
] = ssh_queueing_handler
;
4020 if (ssh
->qhead
->msg2
> 0) {
4021 assert(ssh
->packet_dispatch
[ssh
->qhead
->msg2
] == NULL
);
4022 ssh
->packet_dispatch
[ssh
->qhead
->msg2
] = ssh_queueing_handler
;
4025 ssh
->qhead
= ssh
->qtail
= NULL
;
4026 ssh
->packet_dispatch
[pktin
->type
] = NULL
;
4029 qh
->handler(ssh
, pktin
, qh
->ctx
);
4034 static void ssh_queue_handler(Ssh ssh
, int msg1
, int msg2
,
4035 chandler_fn_t handler
, void *ctx
)
4037 struct queued_handler
*qh
;
4039 qh
= snew(struct queued_handler
);
4042 qh
->handler
= handler
;
4046 if (ssh
->qtail
== NULL
) {
4050 assert(ssh
->packet_dispatch
[qh
->msg1
] == NULL
);
4051 ssh
->packet_dispatch
[qh
->msg1
] = ssh_queueing_handler
;
4054 assert(ssh
->packet_dispatch
[qh
->msg2
] == NULL
);
4055 ssh
->packet_dispatch
[qh
->msg2
] = ssh_queueing_handler
;
4058 ssh
->qtail
->next
= qh
;
4063 static void ssh_rportfwd_succfail(Ssh ssh
, struct Packet
*pktin
, void *ctx
)
4065 struct ssh_rportfwd
*rpf
, *pf
= (struct ssh_rportfwd
*)ctx
;
4067 if (pktin
->type
== (ssh
->version
== 1 ? SSH1_SMSG_SUCCESS
:
4068 SSH2_MSG_REQUEST_SUCCESS
)) {
4069 logeventf(ssh
, "Remote port forwarding from %s enabled",
4072 logeventf(ssh
, "Remote port forwarding from %s refused",
4075 rpf
= del234(ssh
->rportfwds
, pf
);
4081 static void ssh_setup_portfwd(Ssh ssh
, const Config
*cfg
)
4083 const char *portfwd_strptr
= cfg
->portfwd
;
4084 struct ssh_portfwd
*epf
;
4087 if (!ssh
->portfwds
) {
4088 ssh
->portfwds
= newtree234(ssh_portcmp
);
4091 * Go through the existing port forwardings and tag them
4092 * with status==DESTROY. Any that we want to keep will be
4093 * re-enabled (status==KEEP) as we go through the
4094 * configuration and find out which bits are the same as
4097 struct ssh_portfwd
*epf
;
4099 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
4100 epf
->status
= DESTROY
;
4103 while (*portfwd_strptr
) {
4104 char address_family
, type
;
4105 int sport
,dport
,sserv
,dserv
;
4106 char sports
[256], dports
[256], saddr
[256], host
[256];
4109 address_family
= 'A';
4111 if (*portfwd_strptr
== 'A' ||
4112 *portfwd_strptr
== '4' ||
4113 *portfwd_strptr
== '6')
4114 address_family
= *portfwd_strptr
++;
4115 if (*portfwd_strptr
== 'L' ||
4116 *portfwd_strptr
== 'R' ||
4117 *portfwd_strptr
== 'D')
4118 type
= *portfwd_strptr
++;
4123 while (*portfwd_strptr
&& *portfwd_strptr
!= '\t') {
4124 if (*portfwd_strptr
== ':') {
4126 * We've seen a colon in the middle of the
4127 * source port number. This means that
4128 * everything we've seen until now is the
4129 * source _address_, so we'll move it into
4130 * saddr and start sports from the beginning
4135 if (ssh
->version
== 1 && type
== 'R') {
4136 logeventf(ssh
, "SSH-1 cannot handle remote source address "
4137 "spec \"%s\"; ignoring", sports
);
4139 strcpy(saddr
, sports
);
4142 if (n
< lenof(sports
)-1) sports
[n
++] = *portfwd_strptr
++;
4146 if (*portfwd_strptr
== '\t')
4149 while (*portfwd_strptr
&& *portfwd_strptr
!= ':') {
4150 if (n
< lenof(host
)-1) host
[n
++] = *portfwd_strptr
++;
4153 if (*portfwd_strptr
== ':')
4156 while (*portfwd_strptr
) {
4157 if (n
< lenof(dports
)-1) dports
[n
++] = *portfwd_strptr
++;
4161 dport
= atoi(dports
);
4165 dport
= net_service_lookup(dports
);
4167 logeventf(ssh
, "Service lookup failed for destination"
4168 " port \"%s\"", dports
);
4172 while (*portfwd_strptr
) portfwd_strptr
++;
4176 portfwd_strptr
++; /* eat the NUL and move to next one */
4178 sport
= atoi(sports
);
4182 sport
= net_service_lookup(sports
);
4184 logeventf(ssh
, "Service lookup failed for source"
4185 " port \"%s\"", sports
);
4188 if (sport
&& dport
) {
4189 /* Set up a description of the source port. */
4190 struct ssh_portfwd
*pfrec
, *epfrec
;
4192 pfrec
= snew(struct ssh_portfwd
);
4194 pfrec
->saddr
= *saddr ?
dupstr(saddr
) : NULL
;
4195 pfrec
->sserv
= sserv ?
dupstr(sports
) : NULL
;
4196 pfrec
->sport
= sport
;
4197 pfrec
->daddr
= *host ?
dupstr(host
) : NULL
;
4198 pfrec
->dserv
= dserv ?
dupstr(dports
) : NULL
;
4199 pfrec
->dport
= dport
;
4200 pfrec
->local
= NULL
;
4201 pfrec
->remote
= NULL
;
4202 pfrec
->addressfamily
= (address_family
== '4' ? ADDRTYPE_IPV4
:
4203 address_family
== '6' ? ADDRTYPE_IPV6
:
4206 epfrec
= add234(ssh
->portfwds
, pfrec
);
4207 if (epfrec
!= pfrec
) {
4209 * We already have a port forwarding with precisely
4210 * these parameters. Hence, no need to do anything;
4211 * simply tag the existing one as KEEP.
4213 epfrec
->status
= KEEP
;
4214 free_portfwd(pfrec
);
4216 pfrec
->status
= CREATE
;
4222 * Now go through and destroy any port forwardings which were
4225 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
4226 if (epf
->status
== DESTROY
) {
4229 message
= dupprintf("%s port forwarding from %s%s%d",
4230 epf
->type
== 'L' ?
"local" :
4231 epf
->type
== 'R' ?
"remote" : "dynamic",
4232 epf
->saddr ? epf
->saddr
: "",
4233 epf
->saddr ?
":" : "",
4236 if (epf
->type
!= 'D') {
4237 char *msg2
= dupprintf("%s to %s:%d", message
,
4238 epf
->daddr
, epf
->dport
);
4243 logeventf(ssh
, "Cancelling %s", message
);
4247 struct ssh_rportfwd
*rpf
= epf
->remote
;
4248 struct Packet
*pktout
;
4251 * Cancel the port forwarding at the server
4254 if (ssh
->version
== 1) {
4256 * We cannot cancel listening ports on the
4257 * server side in SSH-1! There's no message
4258 * to support it. Instead, we simply remove
4259 * the rportfwd record from the local end
4260 * so that any connections the server tries
4261 * to make on it are rejected.
4264 pktout
= ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4265 ssh2_pkt_addstring(pktout
, "cancel-tcpip-forward");
4266 ssh2_pkt_addbool(pktout
, 0);/* _don't_ want reply */
4268 ssh2_pkt_addstring(pktout
, epf
->saddr
);
4269 } else if (ssh
->cfg
.rport_acceptall
) {
4270 /* XXX: ssh->cfg.rport_acceptall may not represent
4271 * what was used to open the original connection,
4272 * since it's reconfigurable. */
4273 ssh2_pkt_addstring(pktout
, "0.0.0.0");
4275 ssh2_pkt_addstring(pktout
, "127.0.0.1");
4277 ssh2_pkt_adduint32(pktout
, epf
->sport
);
4278 ssh2_pkt_send(ssh
, pktout
);
4281 del234(ssh
->rportfwds
, rpf
);
4283 } else if (epf
->local
) {
4284 pfd_terminate(epf
->local
);
4287 delpos234(ssh
->portfwds
, i
);
4289 i
--; /* so we don't skip one in the list */
4293 * And finally, set up any new port forwardings (status==CREATE).
4295 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
4296 if (epf
->status
== CREATE
) {
4297 char *sportdesc
, *dportdesc
;
4298 sportdesc
= dupprintf("%s%s%s%s%d%s",
4299 epf
->saddr ? epf
->saddr
: "",
4300 epf
->saddr ?
":" : "",
4301 epf
->sserv ? epf
->sserv
: "",
4302 epf
->sserv ?
"(" : "",
4304 epf
->sserv ?
")" : "");
4305 if (epf
->type
== 'D') {
4308 dportdesc
= dupprintf("%s:%s%s%d%s",
4310 epf
->dserv ? epf
->dserv
: "",
4311 epf
->dserv ?
"(" : "",
4313 epf
->dserv ?
")" : "");
4316 if (epf
->type
== 'L') {
4317 const char *err
= pfd_addforward(epf
->daddr
, epf
->dport
,
4318 epf
->saddr
, epf
->sport
,
4321 epf
->addressfamily
);
4323 logeventf(ssh
, "Local %sport %s forwarding to %s%s%s",
4324 epf
->addressfamily
== ADDRTYPE_IPV4 ?
"IPv4 " :
4325 epf
->addressfamily
== ADDRTYPE_IPV6 ?
"IPv6 " : "",
4326 sportdesc
, dportdesc
,
4327 err ?
" failed: " : "", err ? err
: "");
4328 } else if (epf
->type
== 'D') {
4329 const char *err
= pfd_addforward(NULL
, -1,
4330 epf
->saddr
, epf
->sport
,
4333 epf
->addressfamily
);
4335 logeventf(ssh
, "Local %sport %s SOCKS dynamic forwarding%s%s",
4336 epf
->addressfamily
== ADDRTYPE_IPV4 ?
"IPv4 " :
4337 epf
->addressfamily
== ADDRTYPE_IPV6 ?
"IPv6 " : "",
4339 err ?
" failed: " : "", err ? err
: "");
4341 struct ssh_rportfwd
*pf
;
4344 * Ensure the remote port forwardings tree exists.
4346 if (!ssh
->rportfwds
) {
4347 if (ssh
->version
== 1)
4348 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh1
);
4350 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh2
);
4353 pf
= snew(struct ssh_rportfwd
);
4354 strncpy(pf
->dhost
, epf
->daddr
, lenof(pf
->dhost
)-1);
4355 pf
->dhost
[lenof(pf
->dhost
)-1] = '\0';
4356 pf
->dport
= epf
->dport
;
4357 pf
->sport
= epf
->sport
;
4358 if (add234(ssh
->rportfwds
, pf
) != pf
) {
4359 logeventf(ssh
, "Duplicate remote port forwarding to %s:%d",
4360 epf
->daddr
, epf
->dport
);
4363 logeventf(ssh
, "Requesting remote port %s"
4364 " forward to %s", sportdesc
, dportdesc
);
4366 pf
->sportdesc
= sportdesc
;
4371 if (ssh
->version
== 1) {
4372 send_packet(ssh
, SSH1_CMSG_PORT_FORWARD_REQUEST
,
4373 PKT_INT
, epf
->sport
,
4374 PKT_STR
, epf
->daddr
,
4375 PKT_INT
, epf
->dport
,
4377 ssh_queue_handler(ssh
, SSH1_SMSG_SUCCESS
,
4379 ssh_rportfwd_succfail
, pf
);
4381 struct Packet
*pktout
;
4382 pktout
= ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4383 ssh2_pkt_addstring(pktout
, "tcpip-forward");
4384 ssh2_pkt_addbool(pktout
, 1);/* want reply */
4386 ssh2_pkt_addstring(pktout
, epf
->saddr
);
4387 } else if (cfg
->rport_acceptall
) {
4388 ssh2_pkt_addstring(pktout
, "0.0.0.0");
4390 ssh2_pkt_addstring(pktout
, "127.0.0.1");
4392 ssh2_pkt_adduint32(pktout
, epf
->sport
);
4393 ssh2_pkt_send(ssh
, pktout
);
4395 ssh_queue_handler(ssh
, SSH2_MSG_REQUEST_SUCCESS
,
4396 SSH2_MSG_REQUEST_FAILURE
,
4397 ssh_rportfwd_succfail
, pf
);
4406 static void ssh1_smsg_stdout_stderr_data(Ssh ssh
, struct Packet
*pktin
)
4409 int stringlen
, bufsize
;
4411 ssh_pkt_getstring(pktin
, &string
, &stringlen
);
4412 if (string
== NULL
) {
4413 bombout(("Incoming terminal data packet was badly formed"));
4417 bufsize
= from_backend(ssh
->frontend
, pktin
->type
== SSH1_SMSG_STDERR_DATA
,
4419 if (!ssh
->v1_stdout_throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
4420 ssh
->v1_stdout_throttling
= 1;
4421 ssh1_throttle(ssh
, +1);
4425 static void ssh1_smsg_x11_open(Ssh ssh
, struct Packet
*pktin
)
4427 /* Remote side is trying to open a channel to talk to our
4428 * X-Server. Give them back a local channel number. */
4429 struct ssh_channel
*c
;
4430 int remoteid
= ssh_pkt_getuint32(pktin
);
4432 logevent("Received X11 connect request");
4433 /* Refuse if X11 forwarding is disabled. */
4434 if (!ssh
->X11_fwd_enabled
) {
4435 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4436 PKT_INT
, remoteid
, PKT_END
);
4437 logevent("Rejected X11 connect request");
4439 c
= snew(struct ssh_channel
);
4442 if (x11_init(&c
->u
.x11
.s
, ssh
->cfg
.x11_display
, c
,
4443 ssh
->x11auth
, NULL
, -1, &ssh
->cfg
) != NULL
) {
4444 logevent("Opening X11 forward connection failed");
4446 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4447 PKT_INT
, remoteid
, PKT_END
);
4450 ("Opening X11 forward connection succeeded");
4451 c
->remoteid
= remoteid
;
4452 c
->halfopen
= FALSE
;
4453 c
->localid
= alloc_channel_id(ssh
);
4455 c
->v
.v1
.throttling
= 0;
4456 c
->type
= CHAN_X11
; /* identify channel type */
4457 add234(ssh
->channels
, c
);
4458 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4459 PKT_INT
, c
->remoteid
, PKT_INT
,
4460 c
->localid
, PKT_END
);
4461 logevent("Opened X11 forward channel");
4466 static void ssh1_smsg_agent_open(Ssh ssh
, struct Packet
*pktin
)
4468 /* Remote side is trying to open a channel to talk to our
4469 * agent. Give them back a local channel number. */
4470 struct ssh_channel
*c
;
4471 int remoteid
= ssh_pkt_getuint32(pktin
);
4473 /* Refuse if agent forwarding is disabled. */
4474 if (!ssh
->agentfwd_enabled
) {
4475 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4476 PKT_INT
, remoteid
, PKT_END
);
4478 c
= snew(struct ssh_channel
);
4480 c
->remoteid
= remoteid
;
4481 c
->halfopen
= FALSE
;
4482 c
->localid
= alloc_channel_id(ssh
);
4484 c
->v
.v1
.throttling
= 0;
4485 c
->type
= CHAN_AGENT
; /* identify channel type */
4486 c
->u
.a
.lensofar
= 0;
4487 add234(ssh
->channels
, c
);
4488 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4489 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
4494 static void ssh1_msg_port_open(Ssh ssh
, struct Packet
*pktin
)
4496 /* Remote side is trying to open a channel to talk to a
4497 * forwarded port. Give them back a local channel number. */
4498 struct ssh_channel
*c
;
4499 struct ssh_rportfwd pf
, *pfp
;
4504 c
= snew(struct ssh_channel
);
4507 remoteid
= ssh_pkt_getuint32(pktin
);
4508 ssh_pkt_getstring(pktin
, &host
, &hostsize
);
4509 port
= ssh_pkt_getuint32(pktin
);
4511 if (hostsize
>= lenof(pf
.dhost
))
4512 hostsize
= lenof(pf
.dhost
)-1;
4513 memcpy(pf
.dhost
, host
, hostsize
);
4514 pf
.dhost
[hostsize
] = '\0';
4516 pfp
= find234(ssh
->rportfwds
, &pf
, NULL
);
4519 logeventf(ssh
, "Rejected remote port open request for %s:%d",
4521 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4522 PKT_INT
, remoteid
, PKT_END
);
4524 logeventf(ssh
, "Received remote port open request for %s:%d",
4526 e
= pfd_newconnect(&c
->u
.pfd
.s
, pf
.dhost
, port
,
4527 c
, &ssh
->cfg
, pfp
->pfrec
->addressfamily
);
4529 logeventf(ssh
, "Port open failed: %s", e
);
4531 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4532 PKT_INT
, remoteid
, PKT_END
);
4534 c
->remoteid
= remoteid
;
4535 c
->halfopen
= FALSE
;
4536 c
->localid
= alloc_channel_id(ssh
);
4538 c
->v
.v1
.throttling
= 0;
4539 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
4540 add234(ssh
->channels
, c
);
4541 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4542 PKT_INT
, c
->remoteid
, PKT_INT
,
4543 c
->localid
, PKT_END
);
4544 logevent("Forwarded port opened successfully");
4549 static void ssh1_msg_channel_open_confirmation(Ssh ssh
, struct Packet
*pktin
)
4551 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
4552 unsigned int localid
= ssh_pkt_getuint32(pktin
);
4553 struct ssh_channel
*c
;
4555 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
4556 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
4557 c
->remoteid
= localid
;
4558 c
->halfopen
= FALSE
;
4559 c
->type
= CHAN_SOCKDATA
;
4560 c
->v
.v1
.throttling
= 0;
4561 pfd_confirm(c
->u
.pfd
.s
);
4564 if (c
&& c
->closes
) {
4566 * We have a pending close on this channel,
4567 * which we decided on before the server acked
4568 * the channel open. So now we know the
4569 * remoteid, we can close it again.
4571 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
,
4572 PKT_INT
, c
->remoteid
, PKT_END
);
4576 static void ssh1_msg_channel_open_failure(Ssh ssh
, struct Packet
*pktin
)
4578 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
4579 struct ssh_channel
*c
;
4581 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
4582 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
4583 logevent("Forwarded connection refused by server");
4584 pfd_close(c
->u
.pfd
.s
);
4585 del234(ssh
->channels
, c
);
4590 static void ssh1_msg_channel_close(Ssh ssh
, struct Packet
*pktin
)
4592 /* Remote side closes a channel. */
4593 unsigned i
= ssh_pkt_getuint32(pktin
);
4594 struct ssh_channel
*c
;
4595 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
4596 if (c
&& !c
->halfopen
) {
4599 (pktin
->type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
4601 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
4602 logevent("Forwarded X11 connection terminated");
4603 assert(c
->u
.x11
.s
!= NULL
);
4604 x11_close(c
->u
.x11
.s
);
4607 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
4608 logevent("Forwarded port closed");
4609 assert(c
->u
.pfd
.s
!= NULL
);
4610 pfd_close(c
->u
.pfd
.s
);
4614 c
->closes
|= (closetype
<< 2); /* seen this message */
4615 if (!(c
->closes
& closetype
)) {
4616 send_packet(ssh
, pktin
->type
, PKT_INT
, c
->remoteid
,
4618 c
->closes
|= closetype
; /* sent it too */
4621 if (c
->closes
== 15) {
4622 del234(ssh
->channels
, c
);
4626 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4627 pktin
->type
== SSH1_MSG_CHANNEL_CLOSE ?
"" :
4628 "_CONFIRMATION", c ?
"half-open" : "nonexistent",
4633 static void ssh1_msg_channel_data(Ssh ssh
, struct Packet
*pktin
)
4635 /* Data sent down one of our channels. */
4636 int i
= ssh_pkt_getuint32(pktin
);
4639 struct ssh_channel
*c
;
4641 ssh_pkt_getstring(pktin
, &p
, &len
);
4643 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
4648 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
4651 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
4654 /* Data for an agent message. Buffer it. */
4656 if (c
->u
.a
.lensofar
< 4) {
4657 unsigned int l
= min(4 - c
->u
.a
.lensofar
, (unsigned)len
);
4658 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
4662 c
->u
.a
.lensofar
+= l
;
4664 if (c
->u
.a
.lensofar
== 4) {
4666 4 + GET_32BIT(c
->u
.a
.msglen
);
4667 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
4669 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
4671 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
4673 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
4675 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
4679 c
->u
.a
.lensofar
+= l
;
4681 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
4684 if (agent_query(c
->u
.a
.message
,
4687 ssh_agentf_callback
, c
))
4688 ssh_agentf_callback(c
, reply
, replylen
);
4689 sfree(c
->u
.a
.message
);
4690 c
->u
.a
.lensofar
= 0;
4693 bufsize
= 0; /* agent channels never back up */
4696 if (!c
->v
.v1
.throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
4697 c
->v
.v1
.throttling
= 1;
4698 ssh1_throttle(ssh
, +1);
4703 static void ssh1_smsg_exit_status(Ssh ssh
, struct Packet
*pktin
)
4705 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
4706 logeventf(ssh
, "Server sent command exit status %d", ssh
->exitcode
);
4707 send_packet(ssh
, SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
4709 * In case `helpful' firewalls or proxies tack
4710 * extra human-readable text on the end of the
4711 * session which we might mistake for another
4712 * encrypted packet, we close the session once
4713 * we've sent EXIT_CONFIRMATION.
4715 ssh_disconnect(ssh
, NULL
, NULL
, 0, TRUE
);
4718 /* Helper function to deal with sending tty modes for REQUEST_PTY */
4719 static void ssh1_send_ttymode(void *data
, char *mode
, char *val
)
4721 struct Packet
*pktout
= (struct Packet
*)data
;
4723 unsigned int arg
= 0;
4724 while (strcmp(mode
, ssh_ttymodes
[i
].mode
) != 0) i
++;
4725 if (i
== lenof(ssh_ttymodes
)) return;
4726 switch (ssh_ttymodes
[i
].type
) {
4728 arg
= ssh_tty_parse_specchar(val
);
4731 arg
= ssh_tty_parse_boolean(val
);
4734 ssh2_pkt_addbyte(pktout
, ssh_ttymodes
[i
].opcode
);
4735 ssh2_pkt_addbyte(pktout
, arg
);
4739 static void do_ssh1_connection(Ssh ssh
, unsigned char *in
, int inlen
,
4740 struct Packet
*pktin
)
4742 crBegin(ssh
->do_ssh1_connection_crstate
);
4744 ssh
->packet_dispatch
[SSH1_SMSG_STDOUT_DATA
] =
4745 ssh
->packet_dispatch
[SSH1_SMSG_STDERR_DATA
] =
4746 ssh1_smsg_stdout_stderr_data
;
4748 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
] =
4749 ssh1_msg_channel_open_confirmation
;
4750 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_OPEN_FAILURE
] =
4751 ssh1_msg_channel_open_failure
;
4752 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_CLOSE
] =
4753 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
] =
4754 ssh1_msg_channel_close
;
4755 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_DATA
] = ssh1_msg_channel_data
;
4756 ssh
->packet_dispatch
[SSH1_SMSG_EXIT_STATUS
] = ssh1_smsg_exit_status
;
4758 if (ssh
->cfg
.agentfwd
&& agent_exists()) {
4759 logevent("Requesting agent forwarding");
4760 send_packet(ssh
, SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
4764 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4765 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4766 bombout(("Protocol confusion"));
4768 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4769 logevent("Agent forwarding refused");
4771 logevent("Agent forwarding enabled");
4772 ssh
->agentfwd_enabled
= TRUE
;
4773 ssh
->packet_dispatch
[SSH1_SMSG_AGENT_OPEN
] = ssh1_smsg_agent_open
;
4777 if (ssh
->cfg
.x11_forward
) {
4778 char proto
[20], data
[64];
4779 logevent("Requesting X11 forwarding");
4780 ssh
->x11auth
= x11_invent_auth(proto
, sizeof(proto
),
4781 data
, sizeof(data
), ssh
->cfg
.x11_auth
);
4782 x11_get_real_auth(ssh
->x11auth
, ssh
->cfg
.x11_display
);
4784 * Note that while we blank the X authentication data here, we don't
4785 * take any special action to blank the start of an X11 channel,
4786 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
4787 * without having session blanking enabled is likely to leak your
4788 * cookie into the log.
4790 if (ssh
->v1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
4791 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
4793 PKTT_PASSWORD
, PKT_STR
, data
, PKTT_OTHER
,
4794 PKT_INT
, x11_get_screen_number(ssh
->cfg
.x11_display
),
4797 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
4799 PKTT_PASSWORD
, PKT_STR
, data
, PKTT_OTHER
, PKT_END
);
4804 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4805 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4806 bombout(("Protocol confusion"));
4808 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4809 logevent("X11 forwarding refused");
4811 logevent("X11 forwarding enabled");
4812 ssh
->X11_fwd_enabled
= TRUE
;
4813 ssh
->packet_dispatch
[SSH1_SMSG_X11_OPEN
] = ssh1_smsg_x11_open
;
4817 ssh_setup_portfwd(ssh
, &ssh
->cfg
);
4818 ssh
->packet_dispatch
[SSH1_MSG_PORT_OPEN
] = ssh1_msg_port_open
;
4820 if (!ssh
->cfg
.nopty
) {
4822 /* Unpick the terminal-speed string. */
4823 /* XXX perhaps we should allow no speeds to be sent. */
4824 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
4825 sscanf(ssh
->cfg
.termspeed
, "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
4826 /* Send the pty request. */
4827 pkt
= ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY
);
4828 ssh_pkt_addstring(pkt
, ssh
->cfg
.termtype
);
4829 ssh_pkt_adduint32(pkt
, ssh
->term_height
);
4830 ssh_pkt_adduint32(pkt
, ssh
->term_width
);
4831 ssh_pkt_adduint32(pkt
, 0); /* width in pixels */
4832 ssh_pkt_adduint32(pkt
, 0); /* height in pixels */
4833 parse_ttymodes(ssh
, ssh
->cfg
.ttymodes
,
4834 ssh1_send_ttymode
, (void *)pkt
);
4835 ssh_pkt_addbyte(pkt
, SSH1_TTY_OP_ISPEED
);
4836 ssh_pkt_adduint32(pkt
, ssh
->ispeed
);
4837 ssh_pkt_addbyte(pkt
, SSH1_TTY_OP_OSPEED
);
4838 ssh_pkt_adduint32(pkt
, ssh
->ospeed
);
4839 ssh_pkt_addbyte(pkt
, SSH_TTY_OP_END
);
4841 ssh
->state
= SSH_STATE_INTERMED
;
4845 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4846 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4847 bombout(("Protocol confusion"));
4849 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4850 c_write_str(ssh
, "Server refused to allocate pty\r\n");
4851 ssh
->editing
= ssh
->echoing
= 1;
4853 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
4854 ssh
->ospeed
, ssh
->ispeed
);
4856 ssh
->editing
= ssh
->echoing
= 1;
4859 if (ssh
->cfg
.compression
) {
4860 send_packet(ssh
, SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
4864 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4865 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4866 bombout(("Protocol confusion"));
4868 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4869 c_write_str(ssh
, "Server refused to compress\r\n");
4871 logevent("Started compression");
4872 ssh
->v1_compressing
= TRUE
;
4873 ssh
->cs_comp_ctx
= zlib_compress_init();
4874 logevent("Initialised zlib (RFC1950) compression");
4875 ssh
->sc_comp_ctx
= zlib_decompress_init();
4876 logevent("Initialised zlib (RFC1950) decompression");
4880 * Start the shell or command.
4882 * Special case: if the first-choice command is an SSH-2
4883 * subsystem (hence not usable here) and the second choice
4884 * exists, we fall straight back to that.
4887 char *cmd
= ssh
->cfg
.remote_cmd_ptr
;
4889 if (!cmd
) cmd
= ssh
->cfg
.remote_cmd
;
4891 if (ssh
->cfg
.ssh_subsys
&& ssh
->cfg
.remote_cmd_ptr2
) {
4892 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
4893 ssh
->fallback_cmd
= TRUE
;
4896 send_packet(ssh
, SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
4898 send_packet(ssh
, SSH1_CMSG_EXEC_SHELL
, PKT_END
);
4899 logevent("Started session");
4902 ssh
->state
= SSH_STATE_SESSION
;
4903 if (ssh
->size_needed
)
4904 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
4905 if (ssh
->eof_needed
)
4906 ssh_special(ssh
, TS_EOF
);
4909 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
4911 ssh
->channels
= newtree234(ssh_channelcmp
);
4915 * By this point, most incoming packets are already being
4916 * handled by the dispatch table, and we need only pay
4917 * attention to the unusual ones.
4922 if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
4923 /* may be from EXEC_SHELL on some servers */
4924 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4925 /* may be from EXEC_SHELL on some servers
4926 * if no pty is available or in other odd cases. Ignore */
4928 bombout(("Strange packet received: type %d", pktin
->type
));
4933 int len
= min(inlen
, 512);
4934 send_packet(ssh
, SSH1_CMSG_STDIN_DATA
, PKTT_DATA
,
4935 PKT_INT
, len
, PKT_DATA
, in
, len
,
4936 PKTT_OTHER
, PKT_END
);
4947 * Handle the top-level SSH-2 protocol.
4949 static void ssh1_msg_debug(Ssh ssh
, struct Packet
*pktin
)
4954 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
4955 logeventf(ssh
, "Remote debug message: %.*s", msglen
, msg
);
4958 static void ssh1_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
4960 /* log reason code in disconnect message */
4964 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
4965 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen
, msg
));
4968 static void ssh_msg_ignore(Ssh ssh
, struct Packet
*pktin
)
4970 /* Do nothing, because we're ignoring it! Duhh. */
4973 static void ssh1_protocol_setup(Ssh ssh
)
4978 * Most messages are handled by the coroutines.
4980 for (i
= 0; i
< 256; i
++)
4981 ssh
->packet_dispatch
[i
] = NULL
;
4984 * These special message types we install handlers for.
4986 ssh
->packet_dispatch
[SSH1_MSG_DISCONNECT
] = ssh1_msg_disconnect
;
4987 ssh
->packet_dispatch
[SSH1_MSG_IGNORE
] = ssh_msg_ignore
;
4988 ssh
->packet_dispatch
[SSH1_MSG_DEBUG
] = ssh1_msg_debug
;
4991 static void ssh1_protocol(Ssh ssh
, void *vin
, int inlen
,
4992 struct Packet
*pktin
)
4994 unsigned char *in
=(unsigned char*)vin
;
4995 if (ssh
->state
== SSH_STATE_CLOSED
)
4998 if (pktin
&& ssh
->packet_dispatch
[pktin
->type
]) {
4999 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
5003 if (!ssh
->protocol_initial_phase_done
) {
5004 if (do_ssh1_login(ssh
, in
, inlen
, pktin
))
5005 ssh
->protocol_initial_phase_done
= TRUE
;
5010 do_ssh1_connection(ssh
, in
, inlen
, pktin
);
5014 * Utility routine for decoding comma-separated strings in KEXINIT.
5016 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
5019 if (!needle
|| !haystack
) /* protect against null pointers */
5021 needlen
= strlen(needle
);
5024 * Is it at the start of the string?
5026 if (haylen
>= needlen
&& /* haystack is long enough */
5027 !memcmp(needle
, haystack
, needlen
) && /* initial match */
5028 (haylen
== needlen
|| haystack
[needlen
] == ',')
5029 /* either , or EOS follows */
5033 * If not, search for the next comma and resume after that.
5034 * If no comma found, terminate.
5036 while (haylen
> 0 && *haystack
!= ',')
5037 haylen
--, haystack
++;
5040 haylen
--, haystack
++; /* skip over comma itself */
5045 * Similar routine for checking whether we have the first string in a list.
5047 static int first_in_commasep_string(char *needle
, char *haystack
, int haylen
)
5050 if (!needle
|| !haystack
) /* protect against null pointers */
5052 needlen
= strlen(needle
);
5054 * Is it at the start of the string?
5056 if (haylen
>= needlen
&& /* haystack is long enough */
5057 !memcmp(needle
, haystack
, needlen
) && /* initial match */
5058 (haylen
== needlen
|| haystack
[needlen
] == ',')
5059 /* either , or EOS follows */
5067 * SSH-2 key creation method.
5068 * (Currently assumes 2 lots of any hash are sufficient to generate
5069 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5071 #define SSH2_MKKEY_ITERS (2)
5072 static void ssh2_mkkey(Ssh ssh
, Bignum K
, unsigned char *H
, char chr
,
5073 unsigned char *keyspace
)
5075 const struct ssh_hash
*h
= ssh
->kex
->hash
;
5077 /* First hlen bytes. */
5079 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
5080 hash_mpint(h
, s
, K
);
5081 h
->bytes(s
, H
, h
->hlen
);
5082 h
->bytes(s
, &chr
, 1);
5083 h
->bytes(s
, ssh
->v2_session_id
, ssh
->v2_session_id_len
);
5084 h
->final(s
, keyspace
);
5085 /* Next hlen bytes. */
5087 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
5088 hash_mpint(h
, s
, K
);
5089 h
->bytes(s
, H
, h
->hlen
);
5090 h
->bytes(s
, keyspace
, h
->hlen
);
5091 h
->final(s
, keyspace
+ h
->hlen
);
5095 * Handle the SSH-2 transport layer.
5097 static int do_ssh2_transport(Ssh ssh
, void *vin
, int inlen
,
5098 struct Packet
*pktin
)
5100 unsigned char *in
= (unsigned char *)vin
;
5101 struct do_ssh2_transport_state
{
5102 int nbits
, pbits
, warn_kex
, warn_cscipher
, warn_sccipher
;
5103 Bignum p
, g
, e
, f
, K
;
5106 int kex_init_value
, kex_reply_value
;
5107 const struct ssh_mac
**maclist
;
5109 const struct ssh2_cipher
*cscipher_tobe
;
5110 const struct ssh2_cipher
*sccipher_tobe
;
5111 const struct ssh_mac
*csmac_tobe
;
5112 const struct ssh_mac
*scmac_tobe
;
5113 const struct ssh_compress
*cscomp_tobe
;
5114 const struct ssh_compress
*sccomp_tobe
;
5115 char *hostkeydata
, *sigdata
, *rsakeydata
, *keystr
, *fingerprint
;
5116 int hostkeylen
, siglen
, rsakeylen
;
5117 void *hkey
; /* actual host key */
5118 void *rsakey
; /* for RSA kex */
5119 unsigned char exchange_hash
[SSH2_KEX_MAX_HASH_LEN
];
5120 int n_preferred_kex
;
5121 const struct ssh_kexes
*preferred_kex
[KEX_MAX
];
5122 int n_preferred_ciphers
;
5123 const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
5124 const struct ssh_compress
*preferred_comp
;
5125 int got_session_id
, activated_authconn
;
5126 struct Packet
*pktout
;
5131 crState(do_ssh2_transport_state
);
5133 crBegin(ssh
->do_ssh2_transport_crstate
);
5135 s
->cscipher_tobe
= s
->sccipher_tobe
= NULL
;
5136 s
->csmac_tobe
= s
->scmac_tobe
= NULL
;
5137 s
->cscomp_tobe
= s
->sccomp_tobe
= NULL
;
5139 s
->got_session_id
= s
->activated_authconn
= FALSE
;
5142 * Be prepared to work around the buggy MAC problem.
5144 if (ssh
->remote_bugs
& BUG_SSH2_HMAC
)
5145 s
->maclist
= buggymacs
, s
->nmacs
= lenof(buggymacs
);
5147 s
->maclist
= macs
, s
->nmacs
= lenof(macs
);
5150 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_KEX_MASK
;
5152 int i
, j
, commalist_started
;
5155 * Set up the preferred key exchange. (NULL => warn below here)
5157 s
->n_preferred_kex
= 0;
5158 for (i
= 0; i
< KEX_MAX
; i
++) {
5159 switch (ssh
->cfg
.ssh_kexlist
[i
]) {
5161 s
->preferred_kex
[s
->n_preferred_kex
++] =
5162 &ssh_diffiehellman_gex
;
5165 s
->preferred_kex
[s
->n_preferred_kex
++] =
5166 &ssh_diffiehellman_group14
;
5169 s
->preferred_kex
[s
->n_preferred_kex
++] =
5170 &ssh_diffiehellman_group1
;
5173 s
->preferred_kex
[s
->n_preferred_kex
++] =
5177 /* Flag for later. Don't bother if it's the last in
5179 if (i
< KEX_MAX
- 1) {
5180 s
->preferred_kex
[s
->n_preferred_kex
++] = NULL
;
5187 * Set up the preferred ciphers. (NULL => warn below here)
5189 s
->n_preferred_ciphers
= 0;
5190 for (i
= 0; i
< CIPHER_MAX
; i
++) {
5191 switch (ssh
->cfg
.ssh_cipherlist
[i
]) {
5192 case CIPHER_BLOWFISH
:
5193 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_blowfish
;
5196 if (ssh
->cfg
.ssh2_des_cbc
) {
5197 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_des
;
5201 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_3des
;
5204 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_aes
;
5206 case CIPHER_ARCFOUR
:
5207 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_arcfour
;
5210 /* Flag for later. Don't bother if it's the last in
5212 if (i
< CIPHER_MAX
- 1) {
5213 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = NULL
;
5220 * Set up preferred compression.
5222 if (ssh
->cfg
.compression
)
5223 s
->preferred_comp
= &ssh_zlib
;
5225 s
->preferred_comp
= &ssh_comp_none
;
5228 * Enable queueing of outgoing auth- or connection-layer
5229 * packets while we are in the middle of a key exchange.
5231 ssh
->queueing
= TRUE
;
5234 * Flag that KEX is in progress.
5236 ssh
->kex_in_progress
= TRUE
;
5239 * Construct and send our key exchange packet.
5241 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEXINIT
);
5242 for (i
= 0; i
< 16; i
++)
5243 ssh2_pkt_addbyte(s
->pktout
, (unsigned char) random_byte());
5244 /* List key exchange algorithms. */
5245 ssh2_pkt_addstring_start(s
->pktout
);
5246 commalist_started
= 0;
5247 for (i
= 0; i
< s
->n_preferred_kex
; i
++) {
5248 const struct ssh_kexes
*k
= s
->preferred_kex
[i
];
5249 if (!k
) continue; /* warning flag */
5250 for (j
= 0; j
< k
->nkexes
; j
++) {
5251 if (commalist_started
)
5252 ssh2_pkt_addstring_str(s
->pktout
, ",");
5253 ssh2_pkt_addstring_str(s
->pktout
, k
->list
[j
]->name
);
5254 commalist_started
= 1;
5257 /* List server host key algorithms. */
5258 ssh2_pkt_addstring_start(s
->pktout
);
5259 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
5260 ssh2_pkt_addstring_str(s
->pktout
, hostkey_algs
[i
]->name
);
5261 if (i
< lenof(hostkey_algs
) - 1)
5262 ssh2_pkt_addstring_str(s
->pktout
, ",");
5264 /* List client->server encryption algorithms. */
5265 ssh2_pkt_addstring_start(s
->pktout
);
5266 commalist_started
= 0;
5267 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5268 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5269 if (!c
) continue; /* warning flag */
5270 for (j
= 0; j
< c
->nciphers
; j
++) {
5271 if (commalist_started
)
5272 ssh2_pkt_addstring_str(s
->pktout
, ",");
5273 ssh2_pkt_addstring_str(s
->pktout
, c
->list
[j
]->name
);
5274 commalist_started
= 1;
5277 /* List server->client encryption algorithms. */
5278 ssh2_pkt_addstring_start(s
->pktout
);
5279 commalist_started
= 0;
5280 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5281 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5282 if (!c
) continue; /* warning flag */
5283 for (j
= 0; j
< c
->nciphers
; j
++) {
5284 if (commalist_started
)
5285 ssh2_pkt_addstring_str(s
->pktout
, ",");
5286 ssh2_pkt_addstring_str(s
->pktout
, c
->list
[j
]->name
);
5287 commalist_started
= 1;
5290 /* List client->server MAC algorithms. */
5291 ssh2_pkt_addstring_start(s
->pktout
);
5292 for (i
= 0; i
< s
->nmacs
; i
++) {
5293 ssh2_pkt_addstring_str(s
->pktout
, s
->maclist
[i
]->name
);
5294 if (i
< s
->nmacs
- 1)
5295 ssh2_pkt_addstring_str(s
->pktout
, ",");
5297 /* List server->client MAC algorithms. */
5298 ssh2_pkt_addstring_start(s
->pktout
);
5299 for (i
= 0; i
< s
->nmacs
; i
++) {
5300 ssh2_pkt_addstring_str(s
->pktout
, s
->maclist
[i
]->name
);
5301 if (i
< s
->nmacs
- 1)
5302 ssh2_pkt_addstring_str(s
->pktout
, ",");
5304 /* List client->server compression algorithms. */
5305 ssh2_pkt_addstring_start(s
->pktout
);
5306 assert(lenof(compressions
) > 1);
5307 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_comp
->name
);
5308 for (i
= 0; i
< lenof(compressions
); i
++) {
5309 const struct ssh_compress
*c
= compressions
[i
];
5310 if (c
!= s
->preferred_comp
) {
5311 ssh2_pkt_addstring_str(s
->pktout
, ",");
5312 ssh2_pkt_addstring_str(s
->pktout
, c
->name
);
5315 /* List server->client compression algorithms. */
5316 ssh2_pkt_addstring_start(s
->pktout
);
5317 assert(lenof(compressions
) > 1);
5318 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_comp
->name
);
5319 for (i
= 0; i
< lenof(compressions
); i
++) {
5320 const struct ssh_compress
*c
= compressions
[i
];
5321 if (c
!= s
->preferred_comp
) {
5322 ssh2_pkt_addstring_str(s
->pktout
, ",");
5323 ssh2_pkt_addstring_str(s
->pktout
, c
->name
);
5326 /* List client->server languages. Empty list. */
5327 ssh2_pkt_addstring_start(s
->pktout
);
5328 /* List server->client languages. Empty list. */
5329 ssh2_pkt_addstring_start(s
->pktout
);
5330 /* First KEX packet does _not_ follow, because we're not that brave. */
5331 ssh2_pkt_addbool(s
->pktout
, FALSE
);
5333 ssh2_pkt_adduint32(s
->pktout
, 0);
5336 s
->our_kexinitlen
= s
->pktout
->length
- 5;
5337 s
->our_kexinit
= snewn(s
->our_kexinitlen
, unsigned char);
5338 memcpy(s
->our_kexinit
, s
->pktout
->data
+ 5, s
->our_kexinitlen
);
5340 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5346 * Now examine the other side's KEXINIT to see what we're up
5350 char *str
, *preferred
;
5353 if (pktin
->type
!= SSH2_MSG_KEXINIT
) {
5354 bombout(("expected key exchange packet from server"));
5358 ssh
->hostkey
= NULL
;
5359 s
->cscipher_tobe
= NULL
;
5360 s
->sccipher_tobe
= NULL
;
5361 s
->csmac_tobe
= NULL
;
5362 s
->scmac_tobe
= NULL
;
5363 s
->cscomp_tobe
= NULL
;
5364 s
->sccomp_tobe
= NULL
;
5365 s
->warn_kex
= s
->warn_cscipher
= s
->warn_sccipher
= FALSE
;
5367 pktin
->savedpos
+= 16; /* skip garbage cookie */
5368 ssh_pkt_getstring(pktin
, &str
, &len
); /* key exchange algorithms */
5371 for (i
= 0; i
< s
->n_preferred_kex
; i
++) {
5372 const struct ssh_kexes
*k
= s
->preferred_kex
[i
];
5376 for (j
= 0; j
< k
->nkexes
; j
++) {
5377 if (!preferred
) preferred
= k
->list
[j
]->name
;
5378 if (in_commasep_string(k
->list
[j
]->name
, str
, len
)) {
5379 ssh
->kex
= k
->list
[j
];
5388 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5389 str ? str
: "(null)"));
5393 * Note that the server's guess is considered wrong if it doesn't match
5394 * the first algorithm in our list, even if it's still the algorithm
5397 s
->guessok
= first_in_commasep_string(preferred
, str
, len
);
5398 ssh_pkt_getstring(pktin
, &str
, &len
); /* host key algorithms */
5399 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
5400 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
5401 ssh
->hostkey
= hostkey_algs
[i
];
5405 s
->guessok
= s
->guessok
&&
5406 first_in_commasep_string(hostkey_algs
[0]->name
, str
, len
);
5407 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server cipher */
5408 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5409 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5411 s
->warn_cscipher
= TRUE
;
5413 for (j
= 0; j
< c
->nciphers
; j
++) {
5414 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
5415 s
->cscipher_tobe
= c
->list
[j
];
5420 if (s
->cscipher_tobe
)
5423 if (!s
->cscipher_tobe
) {
5424 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5425 str ? str
: "(null)"));
5429 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client cipher */
5430 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5431 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5433 s
->warn_sccipher
= TRUE
;
5435 for (j
= 0; j
< c
->nciphers
; j
++) {
5436 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
5437 s
->sccipher_tobe
= c
->list
[j
];
5442 if (s
->sccipher_tobe
)
5445 if (!s
->sccipher_tobe
) {
5446 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5447 str ? str
: "(null)"));
5451 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server mac */
5452 for (i
= 0; i
< s
->nmacs
; i
++) {
5453 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
5454 s
->csmac_tobe
= s
->maclist
[i
];
5458 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client mac */
5459 for (i
= 0; i
< s
->nmacs
; i
++) {
5460 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
5461 s
->scmac_tobe
= s
->maclist
[i
];
5465 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server compression */
5466 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
5467 const struct ssh_compress
*c
=
5468 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
5469 if (in_commasep_string(c
->name
, str
, len
)) {
5474 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client compression */
5475 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
5476 const struct ssh_compress
*c
=
5477 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
5478 if (in_commasep_string(c
->name
, str
, len
)) {
5483 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server language */
5484 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client language */
5485 s
->ignorepkt
= ssh2_pkt_getbool(pktin
) && !s
->guessok
;
5488 ssh_set_frozen(ssh
, 1);
5489 s
->dlgret
= askalg(ssh
->frontend
, "key-exchange algorithm",
5491 ssh_dialog_callback
, ssh
);
5492 if (s
->dlgret
< 0) {
5496 bombout(("Unexpected data from server while"
5497 " waiting for user response"));
5500 } while (pktin
|| inlen
> 0);
5501 s
->dlgret
= ssh
->user_response
;
5503 ssh_set_frozen(ssh
, 0);
5504 if (s
->dlgret
== 0) {
5505 ssh_disconnect(ssh
, "User aborted at kex warning", NULL
,
5511 if (s
->warn_cscipher
) {
5512 ssh_set_frozen(ssh
, 1);
5513 s
->dlgret
= askalg(ssh
->frontend
,
5514 "client-to-server cipher",
5515 s
->cscipher_tobe
->name
,
5516 ssh_dialog_callback
, ssh
);
5517 if (s
->dlgret
< 0) {
5521 bombout(("Unexpected data from server while"
5522 " waiting for user response"));
5525 } while (pktin
|| inlen
> 0);
5526 s
->dlgret
= ssh
->user_response
;
5528 ssh_set_frozen(ssh
, 0);
5529 if (s
->dlgret
== 0) {
5530 ssh_disconnect(ssh
, "User aborted at cipher warning", NULL
,
5536 if (s
->warn_sccipher
) {
5537 ssh_set_frozen(ssh
, 1);
5538 s
->dlgret
= askalg(ssh
->frontend
,
5539 "server-to-client cipher",
5540 s
->sccipher_tobe
->name
,
5541 ssh_dialog_callback
, ssh
);
5542 if (s
->dlgret
< 0) {
5546 bombout(("Unexpected data from server while"
5547 " waiting for user response"));
5550 } while (pktin
|| inlen
> 0);
5551 s
->dlgret
= ssh
->user_response
;
5553 ssh_set_frozen(ssh
, 0);
5554 if (s
->dlgret
== 0) {
5555 ssh_disconnect(ssh
, "User aborted at cipher warning", NULL
,
5561 ssh
->exhash
= ssh
->kex
->hash
->init();
5562 hash_string(ssh
->kex
->hash
, ssh
->exhash
, ssh
->v_c
, strlen(ssh
->v_c
));
5563 hash_string(ssh
->kex
->hash
, ssh
->exhash
, ssh
->v_s
, strlen(ssh
->v_s
));
5564 hash_string(ssh
->kex
->hash
, ssh
->exhash
,
5565 s
->our_kexinit
, s
->our_kexinitlen
);
5566 sfree(s
->our_kexinit
);
5567 if (pktin
->length
> 5)
5568 hash_string(ssh
->kex
->hash
, ssh
->exhash
,
5569 pktin
->data
+ 5, pktin
->length
- 5);
5571 if (s
->ignorepkt
) /* first_kex_packet_follows */
5572 crWaitUntil(pktin
); /* Ignore packet */
5575 if (ssh
->kex
->main_type
== KEXTYPE_DH
) {
5577 * Work out the number of bits of key we will need from the
5578 * key exchange. We start with the maximum key length of
5584 csbits
= s
->cscipher_tobe
->keylen
;
5585 scbits
= s
->sccipher_tobe
->keylen
;
5586 s
->nbits
= (csbits
> scbits ? csbits
: scbits
);
5588 /* The keys only have hlen-bit entropy, since they're based on
5589 * a hash. So cap the key size at hlen bits. */
5590 if (s
->nbits
> ssh
->kex
->hash
->hlen
* 8)
5591 s
->nbits
= ssh
->kex
->hash
->hlen
* 8;
5594 * If we're doing Diffie-Hellman group exchange, start by
5595 * requesting a group.
5597 if (!ssh
->kex
->pdata
) {
5598 logevent("Doing Diffie-Hellman group exchange");
5599 ssh
->pkt_ctx
|= SSH2_PKTCTX_DHGEX
;
5601 * Work out how big a DH group we will need to allow that
5604 s
->pbits
= 512 << ((s
->nbits
- 1) / 64);
5605 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
5606 ssh2_pkt_adduint32(s
->pktout
, s
->pbits
);
5607 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5610 if (pktin
->type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
5611 bombout(("expected key exchange group packet from server"));
5614 s
->p
= ssh2_pkt_getmp(pktin
);
5615 s
->g
= ssh2_pkt_getmp(pktin
);
5616 if (!s
->p
|| !s
->g
) {
5617 bombout(("unable to read mp-ints from incoming group packet"));
5620 ssh
->kex_ctx
= dh_setup_gex(s
->p
, s
->g
);
5621 s
->kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
5622 s
->kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
5624 ssh
->pkt_ctx
|= SSH2_PKTCTX_DHGROUP
;
5625 ssh
->kex_ctx
= dh_setup_group(ssh
->kex
);
5626 s
->kex_init_value
= SSH2_MSG_KEXDH_INIT
;
5627 s
->kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
5628 logeventf(ssh
, "Using Diffie-Hellman with standard group \"%s\"",
5629 ssh
->kex
->groupname
);
5632 logeventf(ssh
, "Doing Diffie-Hellman key exchange with hash %s",
5633 ssh
->kex
->hash
->text_name
);
5635 * Now generate and send e for Diffie-Hellman.
5637 set_busy_status(ssh
->frontend
, BUSY_CPU
); /* this can take a while */
5638 s
->e
= dh_create_e(ssh
->kex_ctx
, s
->nbits
* 2);
5639 s
->pktout
= ssh2_pkt_init(s
->kex_init_value
);
5640 ssh2_pkt_addmp(s
->pktout
, s
->e
);
5641 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5643 set_busy_status(ssh
->frontend
, BUSY_WAITING
); /* wait for server */
5645 if (pktin
->type
!= s
->kex_reply_value
) {
5646 bombout(("expected key exchange reply packet from server"));
5649 set_busy_status(ssh
->frontend
, BUSY_CPU
); /* cogitate */
5650 ssh_pkt_getstring(pktin
, &s
->hostkeydata
, &s
->hostkeylen
);
5651 s
->hkey
= ssh
->hostkey
->newkey(s
->hostkeydata
, s
->hostkeylen
);
5652 s
->f
= ssh2_pkt_getmp(pktin
);
5654 bombout(("unable to parse key exchange reply packet"));
5657 ssh_pkt_getstring(pktin
, &s
->sigdata
, &s
->siglen
);
5659 s
->K
= dh_find_K(ssh
->kex_ctx
, s
->f
);
5661 /* We assume everything from now on will be quick, and it might
5662 * involve user interaction. */
5663 set_busy_status(ssh
->frontend
, BUSY_NOT
);
5665 hash_string(ssh
->kex
->hash
, ssh
->exhash
, s
->hostkeydata
, s
->hostkeylen
);
5666 if (!ssh
->kex
->pdata
) {
5667 hash_uint32(ssh
->kex
->hash
, ssh
->exhash
, s
->pbits
);
5668 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->p
);
5669 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->g
);
5671 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->e
);
5672 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->f
);
5674 dh_cleanup(ssh
->kex_ctx
);
5676 if (!ssh
->kex
->pdata
) {
5681 logeventf(ssh
, "Doing RSA key exchange with hash %s",
5682 ssh
->kex
->hash
->text_name
);
5683 ssh
->pkt_ctx
|= SSH2_PKTCTX_RSAKEX
;
5685 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
5689 if (pktin
->type
!= SSH2_MSG_KEXRSA_PUBKEY
) {
5690 bombout(("expected RSA public key packet from server"));
5694 ssh_pkt_getstring(pktin
, &s
->hostkeydata
, &s
->hostkeylen
);
5695 hash_string(ssh
->kex
->hash
, ssh
->exhash
,
5696 s
->hostkeydata
, s
->hostkeylen
);
5697 s
->hkey
= ssh
->hostkey
->newkey(s
->hostkeydata
, s
->hostkeylen
);
5701 ssh_pkt_getstring(pktin
, &keydata
, &s
->rsakeylen
);
5702 s
->rsakeydata
= snewn(s
->rsakeylen
, char);
5703 memcpy(s
->rsakeydata
, keydata
, s
->rsakeylen
);
5706 s
->rsakey
= ssh_rsakex_newkey(s
->rsakeydata
, s
->rsakeylen
);
5708 sfree(s
->rsakeydata
);
5709 bombout(("unable to parse RSA public key from server"));
5713 hash_string(ssh
->kex
->hash
, ssh
->exhash
, s
->rsakeydata
, s
->rsakeylen
);
5716 * Next, set up a shared secret K, of precisely KLEN -
5717 * 2*HLEN - 49 bits, where KLEN is the bit length of the
5718 * RSA key modulus and HLEN is the bit length of the hash
5722 int klen
= ssh_rsakex_klen(s
->rsakey
);
5723 int nbits
= klen
- (2*ssh
->kex
->hash
->hlen
*8 + 49);
5725 unsigned char *kstr1
, *kstr2
, *outstr
;
5726 int kstr1len
, kstr2len
, outstrlen
;
5728 s
->K
= bn_power_2(nbits
- 1);
5730 for (i
= 0; i
< nbits
; i
++) {
5732 byte
= random_byte();
5734 bignum_set_bit(s
->K
, i
, (byte
>> (i
& 7)) & 1);
5738 * Encode this as an mpint.
5740 kstr1
= ssh2_mpint_fmt(s
->K
, &kstr1len
);
5741 kstr2
= snewn(kstr2len
= 4 + kstr1len
, unsigned char);
5742 PUT_32BIT(kstr2
, kstr1len
);
5743 memcpy(kstr2
+ 4, kstr1
, kstr1len
);
5746 * Encrypt it with the given RSA key.
5748 outstrlen
= (klen
+ 7) / 8;
5749 outstr
= snewn(outstrlen
, unsigned char);
5750 ssh_rsakex_encrypt(ssh
->kex
->hash
, kstr2
, kstr2len
,
5751 outstr
, outstrlen
, s
->rsakey
);
5754 * And send it off in a return packet.
5756 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET
);
5757 ssh2_pkt_addstring_start(s
->pktout
);
5758 ssh2_pkt_addstring_data(s
->pktout
, outstr
, outstrlen
);
5759 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5761 hash_string(ssh
->kex
->hash
, ssh
->exhash
, outstr
, outstrlen
);
5768 ssh_rsakex_freekey(s
->rsakey
);
5771 if (pktin
->type
!= SSH2_MSG_KEXRSA_DONE
) {
5772 sfree(s
->rsakeydata
);
5773 bombout(("expected signature packet from server"));
5777 ssh_pkt_getstring(pktin
, &s
->sigdata
, &s
->siglen
);
5779 sfree(s
->rsakeydata
);
5782 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->K
);
5783 assert(ssh
->kex
->hash
->hlen
<= sizeof(s
->exchange_hash
));
5784 ssh
->kex
->hash
->final(ssh
->exhash
, s
->exchange_hash
);
5786 ssh
->kex_ctx
= NULL
;
5789 debug(("Exchange hash is:\n"));
5790 dmemdump(s
->exchange_hash
, ssh
->kex
->hash
->hlen
);
5794 !ssh
->hostkey
->verifysig(s
->hkey
, s
->sigdata
, s
->siglen
,
5795 (char *)s
->exchange_hash
,
5796 ssh
->kex
->hash
->hlen
)) {
5797 bombout(("Server's host key did not match the signature supplied"));
5802 * Authenticate remote host: verify host key. (We've already
5803 * checked the signature of the exchange hash.)
5805 s
->keystr
= ssh
->hostkey
->fmtkey(s
->hkey
);
5806 s
->fingerprint
= ssh
->hostkey
->fingerprint(s
->hkey
);
5807 ssh_set_frozen(ssh
, 1);
5808 s
->dlgret
= verify_ssh_host_key(ssh
->frontend
,
5809 ssh
->savedhost
, ssh
->savedport
,
5810 ssh
->hostkey
->keytype
, s
->keystr
,
5812 ssh_dialog_callback
, ssh
);
5813 if (s
->dlgret
< 0) {
5817 bombout(("Unexpected data from server while waiting"
5818 " for user host key response"));
5821 } while (pktin
|| inlen
> 0);
5822 s
->dlgret
= ssh
->user_response
;
5824 ssh_set_frozen(ssh
, 0);
5825 if (s
->dlgret
== 0) {
5826 ssh_disconnect(ssh
, "User aborted at host key verification", NULL
,
5830 if (!s
->got_session_id
) { /* don't bother logging this in rekeys */
5831 logevent("Host key fingerprint is:");
5832 logevent(s
->fingerprint
);
5834 sfree(s
->fingerprint
);
5836 ssh
->hostkey
->freekey(s
->hkey
);
5839 * The exchange hash from the very first key exchange is also
5840 * the session id, used in session key construction and
5843 if (!s
->got_session_id
) {
5844 assert(sizeof(s
->exchange_hash
) <= sizeof(ssh
->v2_session_id
));
5845 memcpy(ssh
->v2_session_id
, s
->exchange_hash
,
5846 sizeof(s
->exchange_hash
));
5847 ssh
->v2_session_id_len
= ssh
->kex
->hash
->hlen
;
5848 assert(ssh
->v2_session_id_len
<= sizeof(ssh
->v2_session_id
));
5849 s
->got_session_id
= TRUE
;
5853 * Send SSH2_MSG_NEWKEYS.
5855 s
->pktout
= ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
5856 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5857 ssh
->outgoing_data_size
= 0; /* start counting from here */
5860 * We've sent client NEWKEYS, so create and initialise
5861 * client-to-server session keys.
5863 if (ssh
->cs_cipher_ctx
)
5864 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
5865 ssh
->cscipher
= s
->cscipher_tobe
;
5866 ssh
->cs_cipher_ctx
= ssh
->cscipher
->make_context();
5868 if (ssh
->cs_mac_ctx
)
5869 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
5870 ssh
->csmac
= s
->csmac_tobe
;
5871 ssh
->cs_mac_ctx
= ssh
->csmac
->make_context();
5873 if (ssh
->cs_comp_ctx
)
5874 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
5875 ssh
->cscomp
= s
->cscomp_tobe
;
5876 ssh
->cs_comp_ctx
= ssh
->cscomp
->compress_init();
5879 * Set IVs on client-to-server keys. Here we use the exchange
5880 * hash from the _first_ key exchange.
5883 unsigned char keyspace
[SSH2_KEX_MAX_HASH_LEN
* SSH2_MKKEY_ITERS
];
5884 assert(sizeof(keyspace
) >= ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
5885 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'C',keyspace
);
5886 assert((ssh
->cscipher
->keylen
+7) / 8 <=
5887 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
5888 ssh
->cscipher
->setkey(ssh
->cs_cipher_ctx
, keyspace
);
5889 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'A',keyspace
);
5890 assert(ssh
->cscipher
->blksize
<=
5891 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
5892 ssh
->cscipher
->setiv(ssh
->cs_cipher_ctx
, keyspace
);
5893 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'E',keyspace
);
5894 assert(ssh
->csmac
->len
<=
5895 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
5896 ssh
->csmac
->setkey(ssh
->cs_mac_ctx
, keyspace
);
5897 memset(keyspace
, 0, sizeof(keyspace
));
5900 logeventf(ssh
, "Initialised %.200s client->server encryption",
5901 ssh
->cscipher
->text_name
);
5902 logeventf(ssh
, "Initialised %.200s client->server MAC algorithm",
5903 ssh
->csmac
->text_name
);
5904 if (ssh
->cscomp
->text_name
)
5905 logeventf(ssh
, "Initialised %s compression",
5906 ssh
->cscomp
->text_name
);
5909 * Now our end of the key exchange is complete, we can send all
5910 * our queued higher-layer packets.
5912 ssh
->queueing
= FALSE
;
5913 ssh2_pkt_queuesend(ssh
);
5916 * Expect SSH2_MSG_NEWKEYS from server.
5919 if (pktin
->type
!= SSH2_MSG_NEWKEYS
) {
5920 bombout(("expected new-keys packet from server"));
5923 ssh
->incoming_data_size
= 0; /* start counting from here */
5926 * We've seen server NEWKEYS, so create and initialise
5927 * server-to-client session keys.
5929 if (ssh
->sc_cipher_ctx
)
5930 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
5931 ssh
->sccipher
= s
->sccipher_tobe
;
5932 ssh
->sc_cipher_ctx
= ssh
->sccipher
->make_context();
5934 if (ssh
->sc_mac_ctx
)
5935 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
5936 ssh
->scmac
= s
->scmac_tobe
;
5937 ssh
->sc_mac_ctx
= ssh
->scmac
->make_context();
5939 if (ssh
->sc_comp_ctx
)
5940 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
5941 ssh
->sccomp
= s
->sccomp_tobe
;
5942 ssh
->sc_comp_ctx
= ssh
->sccomp
->decompress_init();
5945 * Set IVs on server-to-client keys. Here we use the exchange
5946 * hash from the _first_ key exchange.
5949 unsigned char keyspace
[SSH2_KEX_MAX_HASH_LEN
* SSH2_MKKEY_ITERS
];
5950 assert(sizeof(keyspace
) >= ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
5951 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'D',keyspace
);
5952 assert((ssh
->sccipher
->keylen
+7) / 8 <=
5953 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
5954 ssh
->sccipher
->setkey(ssh
->sc_cipher_ctx
, keyspace
);
5955 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'B',keyspace
);
5956 assert(ssh
->sccipher
->blksize
<=
5957 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
5958 ssh
->sccipher
->setiv(ssh
->sc_cipher_ctx
, keyspace
);
5959 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'F',keyspace
);
5960 assert(ssh
->scmac
->len
<=
5961 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
5962 ssh
->scmac
->setkey(ssh
->sc_mac_ctx
, keyspace
);
5963 memset(keyspace
, 0, sizeof(keyspace
));
5965 logeventf(ssh
, "Initialised %.200s server->client encryption",
5966 ssh
->sccipher
->text_name
);
5967 logeventf(ssh
, "Initialised %.200s server->client MAC algorithm",
5968 ssh
->scmac
->text_name
);
5969 if (ssh
->sccomp
->text_name
)
5970 logeventf(ssh
, "Initialised %s decompression",
5971 ssh
->sccomp
->text_name
);
5974 * Free shared secret.
5979 * Key exchange is over. Loop straight back round if we have a
5980 * deferred rekey reason.
5982 if (ssh
->deferred_rekey_reason
) {
5983 logevent(ssh
->deferred_rekey_reason
);
5985 ssh
->deferred_rekey_reason
= NULL
;
5986 goto begin_key_exchange
;
5990 * Otherwise, schedule a timer for our next rekey.
5992 ssh
->kex_in_progress
= FALSE
;
5993 ssh
->last_rekey
= GETTICKCOUNT();
5994 if (ssh
->cfg
.ssh_rekey_time
!= 0)
5995 ssh
->next_rekey
= schedule_timer(ssh
->cfg
.ssh_rekey_time
*60*TICKSPERSEC
,
5999 * If this is the first key exchange phase, we must pass the
6000 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
6001 * wants to see it but because it will need time to initialise
6002 * itself before it sees an actual packet. In subsequent key
6003 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
6004 * it would only confuse the layer above.
6006 if (s
->activated_authconn
) {
6009 s
->activated_authconn
= TRUE
;
6012 * Now we're encrypting. Begin returning 1 to the protocol main
6013 * function so that other things can run on top of the
6014 * transport. If we ever see a KEXINIT, we must go back to the
6017 * We _also_ go back to the start if we see pktin==NULL and
6018 * inlen==-1, because this is a special signal meaning
6019 * `initiate client-driven rekey', and `in' contains a message
6020 * giving the reason for the rekey.
6022 while (!((pktin
&& pktin
->type
== SSH2_MSG_KEXINIT
) ||
6023 (!pktin
&& inlen
== -1))) {
6028 logevent("Server initiated key re-exchange");
6031 * Special case: if the server bug is set that doesn't
6032 * allow rekeying, we give a different log message and
6033 * continue waiting. (If such a server _initiates_ a rekey,
6034 * we process it anyway!)
6036 if ((ssh
->remote_bugs
& BUG_SSH2_REKEY
)) {
6037 logeventf(ssh
, "Server bug prevents key re-exchange (%s)",
6039 /* Reset the counters, so that at least this message doesn't
6040 * hit the event log _too_ often. */
6041 ssh
->outgoing_data_size
= 0;
6042 ssh
->incoming_data_size
= 0;
6043 if (ssh
->cfg
.ssh_rekey_time
!= 0) {
6045 schedule_timer(ssh
->cfg
.ssh_rekey_time
*60*TICKSPERSEC
,
6048 goto wait_for_rekey
; /* this is utterly horrid */
6050 logeventf(ssh
, "Initiating key re-exchange (%s)", (char *)in
);
6053 goto begin_key_exchange
;
6059 * Add data to an SSH-2 channel output buffer.
6061 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
6064 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
6068 * Attempt to send data on an SSH-2 channel.
6070 static int ssh2_try_send(struct ssh_channel
*c
)
6073 struct Packet
*pktout
;
6075 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
6078 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
6079 if ((unsigned)len
> c
->v
.v2
.remwindow
)
6080 len
= c
->v
.v2
.remwindow
;
6081 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
6082 len
= c
->v
.v2
.remmaxpkt
;
6083 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
6084 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6085 dont_log_data(ssh
, pktout
, PKTLOG_OMIT
);
6086 ssh2_pkt_addstring_start(pktout
);
6087 ssh2_pkt_addstring_data(pktout
, data
, len
);
6088 end_log_omission(ssh
, pktout
);
6089 ssh2_pkt_send(ssh
, pktout
);
6090 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
6091 c
->v
.v2
.remwindow
-= len
;
6095 * After having sent as much data as we can, return the amount
6098 return bufchain_size(&c
->v
.v2
.outbuffer
);
6101 static void ssh2_try_send_and_unthrottle(struct ssh_channel
*c
)
6105 return; /* don't send on closing channels */
6106 bufsize
= ssh2_try_send(c
);
6109 case CHAN_MAINSESSION
:
6110 /* stdin need not receive an unthrottle
6111 * notification since it will be polled */
6114 x11_unthrottle(c
->u
.x11
.s
);
6117 /* agent sockets are request/response and need no
6118 * buffer management */
6121 pfd_unthrottle(c
->u
.pfd
.s
);
6128 * Potentially enlarge the window on an SSH-2 channel.
6130 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
)
6135 * Never send WINDOW_ADJUST for a channel that the remote side
6136 * already thinks it's closed; there's no point, since it won't
6137 * be sending any more data anyway.
6143 * Only send a WINDOW_ADJUST if there's significantly more window
6144 * available than the other end thinks there is. This saves us
6145 * sending a WINDOW_ADJUST for every character in a shell session.
6147 * "Significant" is arbitrarily defined as half the window size.
6149 if (newwin
> c
->v
.v2
.locwindow
* 2) {
6150 struct Packet
*pktout
;
6152 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
6153 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6154 ssh2_pkt_adduint32(pktout
, newwin
- c
->v
.v2
.locwindow
);
6155 ssh2_pkt_send(ssh
, pktout
);
6156 c
->v
.v2
.locwindow
= newwin
;
6160 static void ssh2_msg_channel_window_adjust(Ssh ssh
, struct Packet
*pktin
)
6162 unsigned i
= ssh_pkt_getuint32(pktin
);
6163 struct ssh_channel
*c
;
6164 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
6165 if (c
&& !c
->closes
) {
6166 c
->v
.v2
.remwindow
+= ssh_pkt_getuint32(pktin
);
6167 ssh2_try_send_and_unthrottle(c
);
6171 static void ssh2_msg_channel_data(Ssh ssh
, struct Packet
*pktin
)
6175 unsigned i
= ssh_pkt_getuint32(pktin
);
6176 struct ssh_channel
*c
;
6177 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
6179 return; /* nonexistent channel */
6180 if (pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
6181 ssh_pkt_getuint32(pktin
) != SSH2_EXTENDED_DATA_STDERR
)
6182 return; /* extended but not stderr */
6183 ssh_pkt_getstring(pktin
, &data
, &length
);
6186 c
->v
.v2
.locwindow
-= length
;
6188 case CHAN_MAINSESSION
:
6190 from_backend(ssh
->frontend
, pktin
->type
==
6191 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
6195 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
6198 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
6201 while (length
> 0) {
6202 if (c
->u
.a
.lensofar
< 4) {
6203 unsigned int l
= min(4 - c
->u
.a
.lensofar
,
6205 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
6209 c
->u
.a
.lensofar
+= l
;
6211 if (c
->u
.a
.lensofar
== 4) {
6213 4 + GET_32BIT(c
->u
.a
.msglen
);
6214 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
6216 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
6218 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
6220 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
6222 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
6226 c
->u
.a
.lensofar
+= l
;
6228 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
6231 if (agent_query(c
->u
.a
.message
,
6234 ssh_agentf_callback
, c
))
6235 ssh_agentf_callback(c
, reply
, replylen
);
6236 sfree(c
->u
.a
.message
);
6237 c
->u
.a
.lensofar
= 0;
6244 * If we are not buffering too much data,
6245 * enlarge the window again at the remote side.
6247 if (bufsize
< OUR_V2_WINSIZE
)
6248 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
6252 static void ssh2_msg_channel_eof(Ssh ssh
, struct Packet
*pktin
)
6254 unsigned i
= ssh_pkt_getuint32(pktin
);
6255 struct ssh_channel
*c
;
6257 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
6259 return; /* nonexistent channel */
6261 if (c
->type
== CHAN_X11
) {
6263 * Remote EOF on an X11 channel means we should
6264 * wrap up and close the channel ourselves.
6266 x11_close(c
->u
.x11
.s
);
6268 } else if (c
->type
== CHAN_AGENT
) {
6270 } else if (c
->type
== CHAN_SOCKDATA
) {
6271 pfd_close(c
->u
.pfd
.s
);
6276 static void ssh2_msg_channel_close(Ssh ssh
, struct Packet
*pktin
)
6278 unsigned i
= ssh_pkt_getuint32(pktin
);
6279 struct ssh_channel
*c
;
6280 struct Packet
*pktout
;
6282 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
6283 if (!c
|| c
->halfopen
) {
6284 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
6285 c ?
"half-open" : "nonexistent", i
));
6288 /* Do pre-close processing on the channel. */
6290 case CHAN_MAINSESSION
:
6291 ssh
->mainchan
= NULL
;
6292 update_specials_menu(ssh
->frontend
);
6295 if (c
->u
.x11
.s
!= NULL
)
6296 x11_close(c
->u
.x11
.s
);
6303 if (c
->u
.pfd
.s
!= NULL
)
6304 pfd_close(c
->u
.pfd
.s
);
6308 if (c
->closes
== 0) {
6309 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
6310 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6311 ssh2_pkt_send(ssh
, pktout
);
6313 del234(ssh
->channels
, c
);
6314 bufchain_clear(&c
->v
.v2
.outbuffer
);
6318 * See if that was the last channel left open.
6319 * (This is only our termination condition if we're
6320 * not running in -N mode.)
6322 if (!ssh
->cfg
.ssh_no_shell
&& count234(ssh
->channels
) == 0) {
6324 * We used to send SSH_MSG_DISCONNECT here,
6325 * because I'd believed that _every_ conforming
6326 * SSH-2 connection had to end with a disconnect
6327 * being sent by at least one side; apparently
6328 * I was wrong and it's perfectly OK to
6329 * unceremoniously slam the connection shut
6330 * when you're done, and indeed OpenSSH feels
6331 * this is more polite than sending a
6332 * DISCONNECT. So now we don't.
6334 ssh_disconnect(ssh
, "All channels closed", NULL
, 0, TRUE
);
6338 static void ssh2_msg_channel_open_confirmation(Ssh ssh
, struct Packet
*pktin
)
6340 unsigned i
= ssh_pkt_getuint32(pktin
);
6341 struct ssh_channel
*c
;
6342 struct Packet
*pktout
;
6344 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
6346 return; /* nonexistent channel */
6347 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
6348 return; /* dunno why they're confirming this */
6349 c
->remoteid
= ssh_pkt_getuint32(pktin
);
6350 c
->halfopen
= FALSE
;
6351 c
->type
= CHAN_SOCKDATA
;
6352 c
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
6353 c
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
6355 pfd_confirm(c
->u
.pfd
.s
);
6358 * We have a pending close on this channel,
6359 * which we decided on before the server acked
6360 * the channel open. So now we know the
6361 * remoteid, we can close it again.
6363 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
6364 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6365 ssh2_pkt_send(ssh
, pktout
);
6369 static void ssh2_msg_channel_open_failure(Ssh ssh
, struct Packet
*pktin
)
6371 static const char *const reasons
[] = {
6372 "<unknown reason code>",
6373 "Administratively prohibited",
6375 "Unknown channel type",
6376 "Resource shortage",
6378 unsigned i
= ssh_pkt_getuint32(pktin
);
6379 unsigned reason_code
;
6380 char *reason_string
;
6382 struct ssh_channel
*c
;
6383 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
6385 return; /* nonexistent channel */
6386 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
6387 return; /* dunno why they're failing this */
6389 reason_code
= ssh_pkt_getuint32(pktin
);
6390 if (reason_code
>= lenof(reasons
))
6391 reason_code
= 0; /* ensure reasons[reason_code] in range */
6392 ssh_pkt_getstring(pktin
, &reason_string
, &reason_length
);
6393 logeventf(ssh
, "Forwarded connection refused by server: %s [%.*s]",
6394 reasons
[reason_code
], reason_length
, reason_string
);
6396 pfd_close(c
->u
.pfd
.s
);
6398 del234(ssh
->channels
, c
);
6402 static void ssh2_msg_channel_request(Ssh ssh
, struct Packet
*pktin
)
6406 int typelen
, want_reply
;
6407 int reply
= SSH2_MSG_CHANNEL_FAILURE
; /* default */
6408 struct ssh_channel
*c
;
6409 struct Packet
*pktout
;
6411 localid
= ssh_pkt_getuint32(pktin
);
6412 ssh_pkt_getstring(pktin
, &type
, &typelen
);
6413 want_reply
= ssh2_pkt_getbool(pktin
);
6416 * First, check that the channel exists. Otherwise,
6417 * we can instantly disconnect with a rude message.
6419 c
= find234(ssh
->channels
, &localid
, ssh_channelfind
);
6421 char *buf
= dupprintf("Received channel request for nonexistent"
6422 " channel %d", localid
);
6423 ssh_disconnect(ssh
, NULL
, buf
, SSH2_DISCONNECT_PROTOCOL_ERROR
, FALSE
);
6429 * Having got the channel number, we now look at
6430 * the request type string to see if it's something
6433 if (c
== ssh
->mainchan
) {
6435 * We recognise "exit-status" and "exit-signal" on
6436 * the primary channel.
6438 if (typelen
== 11 &&
6439 !memcmp(type
, "exit-status", 11)) {
6441 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
6442 logeventf(ssh
, "Server sent command exit status %d",
6444 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
6446 } else if (typelen
== 11 &&
6447 !memcmp(type
, "exit-signal", 11)) {
6449 int is_plausible
= TRUE
, is_int
= FALSE
;
6450 char *fmt_sig
= "", *fmt_msg
= "";
6452 int msglen
= 0, core
= FALSE
;
6453 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
6454 * provide an `int' for the signal, despite its
6455 * having been a `string' in the drafts since at
6456 * least 2001. (Fixed in session.c 1.147.) Try to
6457 * infer which we can safely parse it as. */
6459 unsigned char *p
= pktin
->body
+
6461 long len
= pktin
->length
- pktin
->savedpos
;
6462 unsigned long num
= GET_32BIT(p
); /* what is it? */
6463 /* If it's 0, it hardly matters; assume string */
6467 int maybe_int
= FALSE
, maybe_str
= FALSE
;
6468 #define CHECK_HYPOTHESIS(offset, result) \
6471 if (q >= 0 && q+4 <= len) { \
6472 q = q + 4 + GET_32BIT(p+q); \
6473 if (q >= 0 && q+4 <= len && \
6474 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
6478 CHECK_HYPOTHESIS(4+1, maybe_int
);
6479 CHECK_HYPOTHESIS(4+num
+1, maybe_str
);
6480 #undef CHECK_HYPOTHESIS
6481 if (maybe_int
&& !maybe_str
)
6483 else if (!maybe_int
&& maybe_str
)
6486 /* Crikey. Either or neither. Panic. */
6487 is_plausible
= FALSE
;
6490 ssh
->exitcode
= 128; /* means `unknown signal' */
6493 /* Old non-standard OpenSSH. */
6494 int signum
= ssh_pkt_getuint32(pktin
);
6495 fmt_sig
= dupprintf(" %d", signum
);
6496 ssh
->exitcode
= 128 + signum
;
6498 /* As per the drafts. */
6501 ssh_pkt_getstring(pktin
, &sig
, &siglen
);
6502 /* Signal name isn't supposed to be blank, but
6503 * let's cope gracefully if it is. */
6505 fmt_sig
= dupprintf(" \"%.*s\"",
6510 * Really hideous method of translating the
6511 * signal description back into a locally
6512 * meaningful number.
6517 #define TRANSLATE_SIGNAL(s) \
6518 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
6519 ssh->exitcode = 128 + SIG ## s
6521 TRANSLATE_SIGNAL(ABRT
);
6524 TRANSLATE_SIGNAL(ALRM
);
6527 TRANSLATE_SIGNAL(FPE
);
6530 TRANSLATE_SIGNAL(HUP
);
6533 TRANSLATE_SIGNAL(ILL
);
6536 TRANSLATE_SIGNAL(INT
);
6539 TRANSLATE_SIGNAL(KILL
);
6542 TRANSLATE_SIGNAL(PIPE
);
6545 TRANSLATE_SIGNAL(QUIT
);
6548 TRANSLATE_SIGNAL(SEGV
);
6551 TRANSLATE_SIGNAL(TERM
);
6554 TRANSLATE_SIGNAL(USR1
);
6557 TRANSLATE_SIGNAL(USR2
);
6559 #undef TRANSLATE_SIGNAL
6561 ssh
->exitcode
= 128;
6563 core
= ssh2_pkt_getbool(pktin
);
6564 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
6566 fmt_msg
= dupprintf(" (\"%.*s\")", msglen
, msg
);
6568 /* ignore lang tag */
6569 } /* else don't attempt to parse */
6570 logeventf(ssh
, "Server exited on signal%s%s%s",
6571 fmt_sig
, core ?
" (core dumped)" : "",
6573 if (*fmt_sig
) sfree(fmt_sig
);
6574 if (*fmt_msg
) sfree(fmt_msg
);
6575 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
6580 * This is a channel request we don't know
6581 * about, so we now either ignore the request
6582 * or respond with CHANNEL_FAILURE, depending
6585 reply
= SSH2_MSG_CHANNEL_FAILURE
;
6588 pktout
= ssh2_pkt_init(reply
);
6589 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6590 ssh2_pkt_send(ssh
, pktout
);
6594 static void ssh2_msg_global_request(Ssh ssh
, struct Packet
*pktin
)
6597 int typelen
, want_reply
;
6598 struct Packet
*pktout
;
6600 ssh_pkt_getstring(pktin
, &type
, &typelen
);
6601 want_reply
= ssh2_pkt_getbool(pktin
);
6604 * We currently don't support any global requests
6605 * at all, so we either ignore the request or
6606 * respond with REQUEST_FAILURE, depending on
6610 pktout
= ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE
);
6611 ssh2_pkt_send(ssh
, pktout
);
6615 static void ssh2_msg_channel_open(Ssh ssh
, struct Packet
*pktin
)
6623 struct ssh_channel
*c
;
6624 unsigned remid
, winsize
, pktsize
;
6625 struct Packet
*pktout
;
6627 ssh_pkt_getstring(pktin
, &type
, &typelen
);
6628 c
= snew(struct ssh_channel
);
6631 remid
= ssh_pkt_getuint32(pktin
);
6632 winsize
= ssh_pkt_getuint32(pktin
);
6633 pktsize
= ssh_pkt_getuint32(pktin
);
6635 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
6638 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
6639 addrstr
= snewn(peeraddrlen
+1, char);
6640 memcpy(addrstr
, peeraddr
, peeraddrlen
);
6641 addrstr
[peeraddrlen
] = '\0';
6642 peerport
= ssh_pkt_getuint32(pktin
);
6644 logeventf(ssh
, "Received X11 connect request from %s:%d",
6647 if (!ssh
->X11_fwd_enabled
)
6648 error
= "X11 forwarding is not enabled";
6649 else if (x11_init(&c
->u
.x11
.s
, ssh
->cfg
.x11_display
, c
,
6650 ssh
->x11auth
, addrstr
, peerport
,
6651 &ssh
->cfg
) != NULL
) {
6652 error
= "Unable to open an X11 connection";
6654 logevent("Opening X11 forward connection succeeded");
6659 } else if (typelen
== 15 &&
6660 !memcmp(type
, "forwarded-tcpip", 15)) {
6661 struct ssh_rportfwd pf
, *realpf
;
6664 ssh_pkt_getstring(pktin
, &dummy
, &dummylen
);/* skip address */
6665 pf
.sport
= ssh_pkt_getuint32(pktin
);
6666 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
6667 peerport
= ssh_pkt_getuint32(pktin
);
6668 realpf
= find234(ssh
->rportfwds
, &pf
, NULL
);
6669 logeventf(ssh
, "Received remote port %d open request "
6670 "from %s:%d", pf
.sport
, peeraddr
, peerport
);
6671 if (realpf
== NULL
) {
6672 error
= "Remote port is not recognised";
6674 const char *e
= pfd_newconnect(&c
->u
.pfd
.s
,
6678 realpf
->pfrec
->addressfamily
);
6679 logeventf(ssh
, "Attempting to forward remote port to "
6680 "%s:%d", realpf
->dhost
, realpf
->dport
);
6682 logeventf(ssh
, "Port open failed: %s", e
);
6683 error
= "Port open failed";
6685 logevent("Forwarded port opened successfully");
6686 c
->type
= CHAN_SOCKDATA
;
6689 } else if (typelen
== 22 &&
6690 !memcmp(type
, "auth-agent@openssh.com", 22)) {
6691 if (!ssh
->agentfwd_enabled
)
6692 error
= "Agent forwarding is not enabled";
6694 c
->type
= CHAN_AGENT
; /* identify channel type */
6695 c
->u
.a
.lensofar
= 0;
6698 error
= "Unsupported channel type requested";
6701 c
->remoteid
= remid
;
6702 c
->halfopen
= FALSE
;
6704 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
6705 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6706 ssh2_pkt_adduint32(pktout
, SSH2_OPEN_CONNECT_FAILED
);
6707 ssh2_pkt_addstring(pktout
, error
);
6708 ssh2_pkt_addstring(pktout
, "en"); /* language tag */
6709 ssh2_pkt_send(ssh
, pktout
);
6710 logeventf(ssh
, "Rejected channel open: %s", error
);
6713 c
->localid
= alloc_channel_id(ssh
);
6715 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
6716 c
->v
.v2
.remwindow
= winsize
;
6717 c
->v
.v2
.remmaxpkt
= pktsize
;
6718 bufchain_init(&c
->v
.v2
.outbuffer
);
6719 add234(ssh
->channels
, c
);
6720 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
6721 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6722 ssh2_pkt_adduint32(pktout
, c
->localid
);
6723 ssh2_pkt_adduint32(pktout
, c
->v
.v2
.locwindow
);
6724 ssh2_pkt_adduint32(pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
6725 ssh2_pkt_send(ssh
, pktout
);
6730 * Buffer banner messages for later display at some convenient point.
6732 static void ssh2_msg_userauth_banner(Ssh ssh
, struct Packet
*pktin
)
6734 /* Arbitrary limit to prevent unbounded inflation of buffer */
6735 if (bufchain_size(&ssh
->banner
) <= 131072) {
6736 char *banner
= NULL
;
6738 ssh_pkt_getstring(pktin
, &banner
, &size
);
6740 bufchain_add(&ssh
->banner
, banner
, size
);
6744 /* Helper function to deal with sending tty modes for "pty-req" */
6745 static void ssh2_send_ttymode(void *data
, char *mode
, char *val
)
6747 struct Packet
*pktout
= (struct Packet
*)data
;
6749 unsigned int arg
= 0;
6750 while (strcmp(mode
, ssh_ttymodes
[i
].mode
) != 0) i
++;
6751 if (i
== lenof(ssh_ttymodes
)) return;
6752 switch (ssh_ttymodes
[i
].type
) {
6754 arg
= ssh_tty_parse_specchar(val
);
6757 arg
= ssh_tty_parse_boolean(val
);
6760 ssh2_pkt_addbyte(pktout
, ssh_ttymodes
[i
].opcode
);
6761 ssh2_pkt_adduint32(pktout
, arg
);
6765 * Handle the SSH-2 userauth and connection layers.
6767 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
,
6768 struct Packet
*pktin
)
6770 struct do_ssh2_authconn_state
{
6773 AUTH_TYPE_PUBLICKEY
,
6774 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
6775 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
6777 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
6778 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
6780 int done_service_req
;
6781 int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
6782 int tried_pubkey_config
, done_agent
;
6783 int kbd_inter_refused
;
6785 prompts_t
*cur_prompt
;
6790 void *publickey_blob
;
6791 int publickey_bloblen
;
6792 int publickey_encrypted
;
6793 char *publickey_algorithm
;
6794 char *publickey_comment
;
6795 unsigned char agent_request
[5], *agent_response
, *agentp
;
6796 int agent_responselen
;
6797 unsigned char *pkblob_in_agent
;
6799 char *pkblob
, *alg
, *commentp
;
6800 int pklen
, alglen
, commentlen
;
6801 int siglen
, retlen
, len
;
6802 char *q
, *agentreq
, *ret
;
6804 int num_env
, env_left
, env_ok
;
6805 struct Packet
*pktout
;
6807 crState(do_ssh2_authconn_state
);
6809 crBegin(ssh
->do_ssh2_authconn_crstate
);
6811 s
->done_service_req
= FALSE
;
6812 s
->we_are_in
= FALSE
;
6813 if (!ssh
->cfg
.ssh_no_userauth
) {
6815 * Request userauth protocol, and await a response to it.
6817 s
->pktout
= ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
6818 ssh2_pkt_addstring(s
->pktout
, "ssh-userauth");
6819 ssh2_pkt_send(ssh
, s
->pktout
);
6820 crWaitUntilV(pktin
);
6821 if (pktin
->type
== SSH2_MSG_SERVICE_ACCEPT
)
6822 s
->done_service_req
= TRUE
;
6824 if (!s
->done_service_req
) {
6826 * Request connection protocol directly, without authentication.
6828 s
->pktout
= ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
6829 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
6830 ssh2_pkt_send(ssh
, s
->pktout
);
6831 crWaitUntilV(pktin
);
6832 if (pktin
->type
== SSH2_MSG_SERVICE_ACCEPT
) {
6833 s
->we_are_in
= TRUE
; /* no auth required */
6835 bombout(("Server refused service request"));
6840 /* Arrange to be able to deal with any BANNERs that come in.
6841 * (We do this now as packets may come in during the next bit.) */
6842 bufchain_init(&ssh
->banner
);
6843 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] =
6844 ssh2_msg_userauth_banner
;
6847 * Misc one-time setup for authentication.
6849 s
->publickey_blob
= NULL
;
6850 if (!s
->we_are_in
) {
6853 * Load the public half of any configured public key file
6856 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
6858 logeventf(ssh
, "Reading private key file \"%.150s\"",
6859 filename_to_str(&ssh
->cfg
.keyfile
));
6860 keytype
= key_type(&ssh
->cfg
.keyfile
);
6861 if (keytype
== SSH_KEYTYPE_SSH2
) {
6864 ssh2_userkey_loadpub(&ssh
->cfg
.keyfile
,
6865 &s
->publickey_algorithm
,
6866 &s
->publickey_bloblen
,
6867 &s
->publickey_comment
, &error
);
6868 if (s
->publickey_blob
) {
6869 s
->publickey_encrypted
=
6870 ssh2_userkey_encrypted(&ssh
->cfg
.keyfile
, NULL
);
6873 logeventf(ssh
, "Unable to load private key (%s)",
6875 msgbuf
= dupprintf("Unable to load private key file "
6876 "\"%.150s\" (%s)\r\n",
6877 filename_to_str(&ssh
->cfg
.keyfile
),
6879 c_write_str(ssh
, msgbuf
);
6884 logeventf(ssh
, "Unable to use this key file (%s)",
6885 key_type_to_str(keytype
));
6886 msgbuf
= dupprintf("Unable to use key file \"%.150s\""
6888 filename_to_str(&ssh
->cfg
.keyfile
),
6889 key_type_to_str(keytype
));
6890 c_write_str(ssh
, msgbuf
);
6892 s
->publickey_blob
= NULL
;
6897 * Find out about any keys Pageant has (but if there's a
6898 * public key configured, filter out all others).
6901 s
->agent_response
= NULL
;
6902 s
->pkblob_in_agent
= NULL
;
6903 if (ssh
->cfg
.tryagent
&& agent_exists()) {
6907 logevent("Pageant is running. Requesting keys.");
6909 /* Request the keys held by the agent. */
6910 PUT_32BIT(s
->agent_request
, 1);
6911 s
->agent_request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
6912 if (!agent_query(s
->agent_request
, 5, &r
, &s
->agent_responselen
,
6913 ssh_agent_callback
, ssh
)) {
6917 bombout(("Unexpected data from server while"
6918 " waiting for agent response"));
6921 } while (pktin
|| inlen
> 0);
6922 r
= ssh
->agent_response
;
6923 s
->agent_responselen
= ssh
->agent_response_len
;
6925 s
->agent_response
= (unsigned char *) r
;
6926 if (s
->agent_response
&& s
->agent_responselen
>= 5 &&
6927 s
->agent_response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
6930 p
= s
->agent_response
+ 5;
6931 s
->nkeys
= GET_32BIT(p
);
6933 logeventf(ssh
, "Pageant has %d SSH-2 keys", s
->nkeys
);
6934 if (s
->publickey_blob
) {
6935 /* See if configured key is in agent. */
6936 for (keyi
= 0; keyi
< s
->nkeys
; keyi
++) {
6937 s
->pklen
= GET_32BIT(p
);
6938 if (s
->pklen
== s
->publickey_bloblen
&&
6939 !memcmp(p
+4, s
->publickey_blob
,
6940 s
->publickey_bloblen
)) {
6941 logeventf(ssh
, "Pageant key #%d matches "
6942 "configured key file", keyi
);
6944 s
->pkblob_in_agent
= p
;
6948 p
+= GET_32BIT(p
) + 4; /* comment */
6950 if (!s
->pkblob_in_agent
) {
6951 logevent("Configured key file not in Pageant");
6961 * We repeat this whole loop, including the username prompt,
6962 * until we manage a successful authentication. If the user
6963 * types the wrong _password_, they can be sent back to the
6964 * beginning to try another username, if this is configured on.
6965 * (If they specify a username in the config, they are never
6966 * asked, even if they do give a wrong password.)
6968 * I think this best serves the needs of
6970 * - the people who have no configuration, no keys, and just
6971 * want to try repeated (username,password) pairs until they
6972 * type both correctly
6974 * - people who have keys and configuration but occasionally
6975 * need to fall back to passwords
6977 * - people with a key held in Pageant, who might not have
6978 * logged in to a particular machine before; so they want to
6979 * type a username, and then _either_ their key will be
6980 * accepted, _or_ they will type a password. If they mistype
6981 * the username they will want to be able to get back and
6984 s
->username
[0] = '\0';
6985 s
->got_username
= FALSE
;
6986 while (!s
->we_are_in
) {
6990 if (s
->got_username
&& !ssh
->cfg
.change_username
) {
6992 * We got a username last time round this loop, and
6993 * with change_username turned off we don't try to get
6996 } else if (!*ssh
->cfg
.username
) {
6997 int ret
; /* need not be kept over crReturn */
6998 s
->cur_prompt
= new_prompts(ssh
->frontend
);
6999 s
->cur_prompt
->to_server
= TRUE
;
7000 s
->cur_prompt
->name
= dupstr("SSH login name");
7001 add_prompt(s
->cur_prompt
, dupstr("login as: "), TRUE
,
7002 lenof(s
->username
));
7003 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
7006 crWaitUntilV(!pktin
);
7007 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
7012 * get_userpass_input() failed to get a username.
7015 free_prompts(s
->cur_prompt
);
7016 ssh_disconnect(ssh
, "No username provided", NULL
, 0, TRUE
);
7019 memcpy(s
->username
, s
->cur_prompt
->prompts
[0]->result
,
7020 lenof(s
->username
));
7021 free_prompts(s
->cur_prompt
);
7024 strncpy(s
->username
, ssh
->cfg
.username
, sizeof(s
->username
));
7025 s
->username
[sizeof(s
->username
)-1] = '\0';
7026 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
7027 stuff
= dupprintf("Using username \"%s\".\r\n", s
->username
);
7028 c_write_str(ssh
, stuff
);
7032 s
->got_username
= TRUE
;
7035 * Send an authentication request using method "none": (a)
7036 * just in case it succeeds, and (b) so that we know what
7037 * authentication methods we can usefully try next.
7039 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
7041 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7042 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7043 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");/* service requested */
7044 ssh2_pkt_addstring(s
->pktout
, "none"); /* method */
7045 ssh2_pkt_send(ssh
, s
->pktout
);
7046 s
->type
= AUTH_TYPE_NONE
;
7048 s
->we_are_in
= FALSE
;
7050 s
->tried_pubkey_config
= FALSE
;
7051 s
->kbd_inter_refused
= FALSE
;
7053 /* Reset agent request state. */
7054 s
->done_agent
= FALSE
;
7055 if (s
->agent_response
) {
7056 if (s
->pkblob_in_agent
) {
7057 s
->agentp
= s
->pkblob_in_agent
;
7059 s
->agentp
= s
->agent_response
+ 5 + 4;
7066 * Wait for the result of the last authentication request.
7069 crWaitUntilV(pktin
);
7071 * Now is a convenient point to spew any banner material
7072 * that we've accumulated. (This should ensure that when
7073 * we exit the auth loop, we haven't any left to deal
7077 int size
= bufchain_size(&ssh
->banner
);
7079 * Don't show the banner if we're operating in
7080 * non-verbose non-interactive mode. (It's probably
7081 * a script, which means nobody will read the
7082 * banner _anyway_, and moreover the printing of
7083 * the banner will screw up processing on the
7084 * output of (say) plink.)
7086 if (size
&& (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
))) {
7087 char *banner
= snewn(size
, char);
7088 bufchain_fetch(&ssh
->banner
, banner
, size
);
7089 c_write_untrusted(ssh
, banner
, size
);
7092 bufchain_clear(&ssh
->banner
);
7094 if (pktin
->type
== SSH2_MSG_USERAUTH_SUCCESS
) {
7095 logevent("Access granted");
7096 s
->we_are_in
= TRUE
;
7100 if (pktin
->type
!= SSH2_MSG_USERAUTH_FAILURE
) {
7101 bombout(("Strange packet received during authentication: "
7102 "type %d", pktin
->type
));
7109 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7110 * we can look at the string in it and know what we can
7111 * helpfully try next.
7113 if (pktin
->type
== SSH2_MSG_USERAUTH_FAILURE
) {
7116 ssh_pkt_getstring(pktin
, &methods
, &methlen
);
7117 if (!ssh2_pkt_getbool(pktin
)) {
7119 * We have received an unequivocal Access
7120 * Denied. This can translate to a variety of
7123 * - if we'd just tried "none" authentication,
7124 * it's not worth printing anything at all
7126 * - if we'd just tried a public key _offer_,
7127 * the message should be "Server refused our
7128 * key" (or no message at all if the key
7129 * came from Pageant)
7131 * - if we'd just tried anything else, the
7132 * message really should be "Access denied".
7134 * Additionally, if we'd just tried password
7135 * authentication, we should break out of this
7136 * whole loop so as to go back to the username
7137 * prompt (iff we're configured to allow
7138 * username change attempts).
7140 if (s
->type
== AUTH_TYPE_NONE
) {
7142 } else if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
7143 s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
7144 if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
7145 c_write_str(ssh
, "Server refused our key\r\n");
7146 logevent("Server refused public key");
7147 } else if (s
->type
==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
7148 /* server declined keyboard-interactive; ignore */
7150 c_write_str(ssh
, "Access denied\r\n");
7151 logevent("Access denied");
7152 if (s
->type
== AUTH_TYPE_PASSWORD
&&
7153 ssh
->cfg
.change_username
) {
7154 /* XXX perhaps we should allow
7155 * keyboard-interactive to do this too? */
7156 s
->we_are_in
= FALSE
;
7161 c_write_str(ssh
, "Further authentication required\r\n");
7162 logevent("Further authentication required");
7166 in_commasep_string("publickey", methods
, methlen
);
7168 in_commasep_string("password", methods
, methlen
);
7169 s
->can_keyb_inter
= ssh
->cfg
.try_ki_auth
&&
7170 in_commasep_string("keyboard-interactive", methods
, methlen
);
7173 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
7175 if (s
->can_pubkey
&& !s
->done_agent
&& s
->nkeys
) {
7178 * Attempt public-key authentication using a key from Pageant.
7181 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
7182 ssh
->pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
7184 logeventf(ssh
, "Trying Pageant key #%d", s
->keyi
);
7186 /* Unpack key from agent response */
7187 s
->pklen
= GET_32BIT(s
->agentp
);
7189 s
->pkblob
= (char *)s
->agentp
;
7190 s
->agentp
+= s
->pklen
;
7191 s
->alglen
= GET_32BIT(s
->pkblob
);
7192 s
->alg
= s
->pkblob
+ 4;
7193 s
->commentlen
= GET_32BIT(s
->agentp
);
7195 s
->commentp
= (char *)s
->agentp
;
7196 s
->agentp
+= s
->commentlen
;
7197 /* s->agentp now points at next key, if any */
7199 /* See if server will accept it */
7200 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7201 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7202 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7203 /* service requested */
7204 ssh2_pkt_addstring(s
->pktout
, "publickey");
7206 ssh2_pkt_addbool(s
->pktout
, FALSE
); /* no signature included */
7207 ssh2_pkt_addstring_start(s
->pktout
);
7208 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
7209 ssh2_pkt_addstring_start(s
->pktout
);
7210 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
7211 ssh2_pkt_send(ssh
, s
->pktout
);
7212 s
->type
= AUTH_TYPE_PUBLICKEY_OFFER_QUIET
;
7214 crWaitUntilV(pktin
);
7215 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
7217 /* Offer of key refused. */
7224 if (flags
& FLAG_VERBOSE
) {
7225 c_write_str(ssh
, "Authenticating with "
7227 c_write(ssh
, s
->commentp
, s
->commentlen
);
7228 c_write_str(ssh
, "\" from agent\r\n");
7232 * Server is willing to accept the key.
7233 * Construct a SIGN_REQUEST.
7235 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7236 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7237 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7238 /* service requested */
7239 ssh2_pkt_addstring(s
->pktout
, "publickey");
7241 ssh2_pkt_addbool(s
->pktout
, TRUE
); /* signature included */
7242 ssh2_pkt_addstring_start(s
->pktout
);
7243 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
7244 ssh2_pkt_addstring_start(s
->pktout
);
7245 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
7247 /* Ask agent for signature. */
7248 s
->siglen
= s
->pktout
->length
- 5 + 4 +
7249 ssh
->v2_session_id_len
;
7250 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
7252 s
->len
= 1; /* message type */
7253 s
->len
+= 4 + s
->pklen
; /* key blob */
7254 s
->len
+= 4 + s
->siglen
; /* data to sign */
7255 s
->len
+= 4; /* flags */
7256 s
->agentreq
= snewn(4 + s
->len
, char);
7257 PUT_32BIT(s
->agentreq
, s
->len
);
7258 s
->q
= s
->agentreq
+ 4;
7259 *s
->q
++ = SSH2_AGENTC_SIGN_REQUEST
;
7260 PUT_32BIT(s
->q
, s
->pklen
);
7262 memcpy(s
->q
, s
->pkblob
, s
->pklen
);
7264 PUT_32BIT(s
->q
, s
->siglen
);
7266 /* Now the data to be signed... */
7267 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
7268 PUT_32BIT(s
->q
, ssh
->v2_session_id_len
);
7271 memcpy(s
->q
, ssh
->v2_session_id
,
7272 ssh
->v2_session_id_len
);
7273 s
->q
+= ssh
->v2_session_id_len
;
7274 memcpy(s
->q
, s
->pktout
->data
+ 5,
7275 s
->pktout
->length
- 5);
7276 s
->q
+= s
->pktout
->length
- 5;
7277 /* And finally the (zero) flags word. */
7279 if (!agent_query(s
->agentreq
, s
->len
+ 4,
7281 ssh_agent_callback
, ssh
)) {
7285 bombout(("Unexpected data from server"
7286 " while waiting for agent"
7290 } while (pktin
|| inlen
> 0);
7291 vret
= ssh
->agent_response
;
7292 s
->retlen
= ssh
->agent_response_len
;
7297 if (s
->ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
7298 logevent("Sending Pageant's response");
7299 ssh2_add_sigblob(ssh
, s
->pktout
,
7300 s
->pkblob
, s
->pklen
,
7302 GET_32BIT(s
->ret
+ 5));
7303 ssh2_pkt_send(ssh
, s
->pktout
);
7304 s
->type
= AUTH_TYPE_PUBLICKEY
;
7306 /* FIXME: less drastic response */
7307 bombout(("Pageant failed to answer challenge"));
7313 /* Do we have any keys left to try? */
7314 if (s
->pkblob_in_agent
) {
7315 s
->done_agent
= TRUE
;
7316 s
->tried_pubkey_config
= TRUE
;
7319 if (s
->keyi
>= s
->nkeys
)
7320 s
->done_agent
= TRUE
;
7323 } else if (s
->can_pubkey
&& s
->publickey_blob
&&
7324 !s
->tried_pubkey_config
) {
7326 struct ssh2_userkey
*key
; /* not live over crReturn */
7327 char *passphrase
; /* not live over crReturn */
7329 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
7330 ssh
->pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
7332 s
->tried_pubkey_config
= TRUE
;
7335 * Try the public key supplied in the configuration.
7337 * First, offer the public blob to see if the server is
7338 * willing to accept it.
7340 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7341 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7342 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7343 /* service requested */
7344 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
7345 ssh2_pkt_addbool(s
->pktout
, FALSE
);
7346 /* no signature included */
7347 ssh2_pkt_addstring(s
->pktout
, s
->publickey_algorithm
);
7348 ssh2_pkt_addstring_start(s
->pktout
);
7349 ssh2_pkt_addstring_data(s
->pktout
,
7350 (char *)s
->publickey_blob
,
7351 s
->publickey_bloblen
);
7352 ssh2_pkt_send(ssh
, s
->pktout
);
7353 logevent("Offered public key");
7355 crWaitUntilV(pktin
);
7356 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
7357 /* Key refused. Give up. */
7358 s
->gotit
= TRUE
; /* reconsider message next loop */
7359 s
->type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
7360 continue; /* process this new message */
7362 logevent("Offer of public key accepted");
7365 * Actually attempt a serious authentication using
7368 if (flags
& FLAG_VERBOSE
) {
7369 c_write_str(ssh
, "Authenticating with public key \"");
7370 c_write_str(ssh
, s
->publickey_comment
);
7371 c_write_str(ssh
, "\"\r\n");
7375 const char *error
; /* not live over crReturn */
7376 if (s
->publickey_encrypted
) {
7378 * Get a passphrase from the user.
7380 int ret
; /* need not be kept over crReturn */
7381 s
->cur_prompt
= new_prompts(ssh
->frontend
);
7382 s
->cur_prompt
->to_server
= FALSE
;
7383 s
->cur_prompt
->name
= dupstr("SSH key passphrase");
7384 add_prompt(s
->cur_prompt
,
7385 dupprintf("Passphrase for key \"%.100s\": ",
7386 s
->publickey_comment
),
7387 FALSE
, SSH_MAX_PASSWORD_LEN
);
7388 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
7391 crWaitUntilV(!pktin
);
7392 ret
= get_userpass_input(s
->cur_prompt
,
7397 /* Failed to get a passphrase. Terminate. */
7398 free_prompts(s
->cur_prompt
);
7399 ssh_disconnect(ssh
, NULL
,
7400 "Unable to authenticate",
7401 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER
,
7406 dupstr(s
->cur_prompt
->prompts
[0]->result
);
7407 free_prompts(s
->cur_prompt
);
7409 passphrase
= NULL
; /* no passphrase needed */
7413 * Try decrypting the key.
7415 key
= ssh2_load_userkey(&ssh
->cfg
.keyfile
, passphrase
,
7418 /* burn the evidence */
7419 memset(passphrase
, 0, strlen(passphrase
));
7422 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
7424 (key
== SSH2_WRONG_PASSPHRASE
)) {
7425 c_write_str(ssh
, "Wrong passphrase\r\n");
7427 /* and loop again */
7429 c_write_str(ssh
, "Unable to load private key (");
7430 c_write_str(ssh
, error
);
7431 c_write_str(ssh
, ")\r\n");
7433 break; /* try something else */
7439 unsigned char *pkblob
, *sigblob
, *sigdata
;
7440 int pkblob_len
, sigblob_len
, sigdata_len
;
7444 * We have loaded the private key and the server
7445 * has announced that it's willing to accept it.
7446 * Hallelujah. Generate a signature and send it.
7448 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7449 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7450 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7451 /* service requested */
7452 ssh2_pkt_addstring(s
->pktout
, "publickey");
7454 ssh2_pkt_addbool(s
->pktout
, TRUE
);
7455 /* signature follows */
7456 ssh2_pkt_addstring(s
->pktout
, key
->alg
->name
);
7457 pkblob
= key
->alg
->public_blob(key
->data
,
7459 ssh2_pkt_addstring_start(s
->pktout
);
7460 ssh2_pkt_addstring_data(s
->pktout
, (char *)pkblob
,
7464 * The data to be signed is:
7468 * followed by everything so far placed in the
7471 sigdata_len
= s
->pktout
->length
- 5 + 4 +
7472 ssh
->v2_session_id_len
;
7473 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
7475 sigdata
= snewn(sigdata_len
, unsigned char);
7477 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
7478 PUT_32BIT(sigdata
+p
, ssh
->v2_session_id_len
);
7481 memcpy(sigdata
+p
, ssh
->v2_session_id
,
7482 ssh
->v2_session_id_len
);
7483 p
+= ssh
->v2_session_id_len
;
7484 memcpy(sigdata
+p
, s
->pktout
->data
+ 5,
7485 s
->pktout
->length
- 5);
7486 p
+= s
->pktout
->length
- 5;
7487 assert(p
== sigdata_len
);
7488 sigblob
= key
->alg
->sign(key
->data
, (char *)sigdata
,
7489 sigdata_len
, &sigblob_len
);
7490 ssh2_add_sigblob(ssh
, s
->pktout
, pkblob
, pkblob_len
,
7491 sigblob
, sigblob_len
);
7496 ssh2_pkt_send(ssh
, s
->pktout
);
7497 s
->type
= AUTH_TYPE_PUBLICKEY
;
7498 key
->alg
->freekey(key
->data
);
7501 } else if (s
->can_keyb_inter
&& !s
->kbd_inter_refused
) {
7504 * Keyboard-interactive authentication.
7507 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
7509 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
7510 ssh
->pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
7512 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7513 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7514 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7515 /* service requested */
7516 ssh2_pkt_addstring(s
->pktout
, "keyboard-interactive");
7518 ssh2_pkt_addstring(s
->pktout
, ""); /* lang */
7519 ssh2_pkt_addstring(s
->pktout
, ""); /* submethods */
7520 ssh2_pkt_send(ssh
, s
->pktout
);
7522 crWaitUntilV(pktin
);
7523 if (pktin
->type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
7524 /* Server is not willing to do keyboard-interactive
7525 * at all (or, bizarrely but legally, accepts the
7526 * user without actually issuing any prompts).
7527 * Give up on it entirely. */
7529 if (pktin
->type
== SSH2_MSG_USERAUTH_FAILURE
)
7530 logevent("Keyboard-interactive authentication refused");
7531 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
7532 s
->kbd_inter_refused
= TRUE
; /* don't try it again */
7537 * Loop while the server continues to send INFO_REQUESTs.
7539 while (pktin
->type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
7541 char *name
, *inst
, *lang
;
7542 int name_len
, inst_len
, lang_len
;
7546 * We've got a fresh USERAUTH_INFO_REQUEST.
7547 * Get the preamble and start building a prompt.
7549 ssh_pkt_getstring(pktin
, &name
, &name_len
);
7550 ssh_pkt_getstring(pktin
, &inst
, &inst_len
);
7551 ssh_pkt_getstring(pktin
, &lang
, &lang_len
);
7552 s
->cur_prompt
= new_prompts(ssh
->frontend
);
7553 s
->cur_prompt
->to_server
= TRUE
;
7555 /* FIXME: better prefix to distinguish from
7557 s
->cur_prompt
->name
=
7558 dupprintf("SSH server: %.*s", name_len
, name
);
7559 s
->cur_prompt
->name_reqd
= TRUE
;
7561 s
->cur_prompt
->name
=
7562 dupstr("SSH server authentication");
7563 s
->cur_prompt
->name_reqd
= FALSE
;
7565 /* FIXME: ugly to print "Using..." in prompt _every_
7566 * time round. Can this be done more subtly? */
7567 s
->cur_prompt
->instruction
=
7568 dupprintf("Using keyboard-interactive authentication.%s%.*s",
7569 inst_len ?
"\n" : "", inst_len
, inst
);
7570 s
->cur_prompt
->instr_reqd
= TRUE
;
7573 * Get the prompts from the packet.
7575 s
->num_prompts
= ssh_pkt_getuint32(pktin
);
7576 for (i
= 0; i
< s
->num_prompts
; i
++) {
7580 static char noprompt
[] =
7581 "<server failed to send prompt>: ";
7583 ssh_pkt_getstring(pktin
, &prompt
, &prompt_len
);
7584 echo
= ssh2_pkt_getbool(pktin
);
7587 prompt_len
= lenof(noprompt
)-1;
7589 add_prompt(s
->cur_prompt
,
7590 dupprintf("%.*s", prompt_len
, prompt
),
7591 echo
, SSH_MAX_PASSWORD_LEN
);
7595 * Get the user's responses.
7597 if (s
->num_prompts
) {
7598 int ret
; /* not live over crReturn */
7599 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
7602 crWaitUntilV(!pktin
);
7603 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
7608 * Failed to get responses. Terminate.
7610 free_prompts(s
->cur_prompt
);
7611 ssh_disconnect(ssh
, NULL
, "Unable to authenticate",
7612 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER
,
7619 * Send the responses to the server.
7621 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
7622 ssh2_pkt_adduint32(s
->pktout
, s
->num_prompts
);
7623 for (i
=0; i
< s
->num_prompts
; i
++) {
7624 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
7625 ssh2_pkt_addstring(s
->pktout
,
7626 s
->cur_prompt
->prompts
[i
]->result
);
7627 end_log_omission(ssh
, s
->pktout
);
7629 ssh2_pkt_send_with_padding(ssh
, s
->pktout
, 256);
7632 * Get the next packet in case it's another
7635 crWaitUntilV(pktin
);
7640 * We should have SUCCESS or FAILURE now.
7644 } else if (s
->can_passwd
) {
7647 * Plain old password authentication.
7649 int ret
; /* not live over crReturn */
7650 int changereq_first_time
; /* not live over crReturn */
7652 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
7653 ssh
->pkt_ctx
|= SSH2_PKTCTX_PASSWORD
;
7655 s
->cur_prompt
= new_prompts(ssh
->frontend
);
7656 s
->cur_prompt
->to_server
= TRUE
;
7657 s
->cur_prompt
->name
= dupstr("SSH password");
7658 add_prompt(s
->cur_prompt
, dupprintf("%.90s@%.90s's password: ",
7661 FALSE
, SSH_MAX_PASSWORD_LEN
);
7663 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
7666 crWaitUntilV(!pktin
);
7667 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
7672 * Failed to get responses. Terminate.
7674 free_prompts(s
->cur_prompt
);
7675 ssh_disconnect(ssh
, NULL
, "Unable to authenticate",
7676 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER
,
7681 * Squirrel away the password. (We may need it later if
7682 * asked to change it.)
7684 s
->password
= dupstr(s
->cur_prompt
->prompts
[0]->result
);
7685 free_prompts(s
->cur_prompt
);
7688 * Send the password packet.
7690 * We pad out the password packet to 256 bytes to make
7691 * it harder for an attacker to find the length of the
7694 * Anyone using a password longer than 256 bytes
7695 * probably doesn't have much to worry about from
7696 * people who find out how long their password is!
7698 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7699 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7700 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7701 /* service requested */
7702 ssh2_pkt_addstring(s
->pktout
, "password");
7703 ssh2_pkt_addbool(s
->pktout
, FALSE
);
7704 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
7705 ssh2_pkt_addstring(s
->pktout
, s
->password
);
7706 end_log_omission(ssh
, s
->pktout
);
7707 ssh2_pkt_send_with_padding(ssh
, s
->pktout
, 256);
7708 logevent("Sent password");
7709 s
->type
= AUTH_TYPE_PASSWORD
;
7712 * Wait for next packet, in case it's a password change
7715 crWaitUntilV(pktin
);
7716 changereq_first_time
= TRUE
;
7718 while (pktin
->type
== SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
) {
7721 * We're being asked for a new password
7722 * (perhaps not for the first time).
7723 * Loop until the server accepts it.
7726 int got_new
= FALSE
; /* not live over crReturn */
7727 char *prompt
; /* not live over crReturn */
7728 int prompt_len
; /* not live over crReturn */
7732 if (changereq_first_time
)
7733 msg
= "Server requested password change";
7735 msg
= "Server rejected new password";
7737 c_write_str(ssh
, msg
);
7738 c_write_str(ssh
, "\r\n");
7741 ssh_pkt_getstring(pktin
, &prompt
, &prompt_len
);
7743 s
->cur_prompt
= new_prompts(ssh
->frontend
);
7744 s
->cur_prompt
->to_server
= TRUE
;
7745 s
->cur_prompt
->name
= dupstr("New SSH password");
7746 s
->cur_prompt
->instruction
=
7747 dupprintf("%.*s", prompt_len
, prompt
);
7748 s
->cur_prompt
->instr_reqd
= TRUE
;
7750 * There's no explicit requirement in the protocol
7751 * for the "old" passwords in the original and
7752 * password-change messages to be the same, and
7753 * apparently some Cisco kit supports password change
7754 * by the user entering a blank password originally
7755 * and the real password subsequently, so,
7756 * reluctantly, we prompt for the old password again.
7758 * (On the other hand, some servers don't even bother
7759 * to check this field.)
7761 add_prompt(s
->cur_prompt
,
7762 dupstr("Current password (blank for previously entered password): "),
7763 FALSE
, SSH_MAX_PASSWORD_LEN
);
7764 add_prompt(s
->cur_prompt
, dupstr("Enter new password: "),
7765 FALSE
, SSH_MAX_PASSWORD_LEN
);
7766 add_prompt(s
->cur_prompt
, dupstr("Confirm new password: "),
7767 FALSE
, SSH_MAX_PASSWORD_LEN
);
7770 * Loop until the user manages to enter the same
7775 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
7778 crWaitUntilV(!pktin
);
7779 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
7784 * Failed to get responses. Terminate.
7786 /* burn the evidence */
7787 free_prompts(s
->cur_prompt
);
7788 memset(s
->password
, 0, strlen(s
->password
));
7790 ssh_disconnect(ssh
, NULL
, "Unable to authenticate",
7791 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER
,
7797 * If the user specified a new original password
7798 * (IYSWIM), overwrite any previously specified
7800 * (A side effect is that the user doesn't have to
7801 * re-enter it if they louse up the new password.)
7803 if (s
->cur_prompt
->prompts
[0]->result
[0]) {
7804 memset(s
->password
, 0, strlen(s
->password
));
7805 /* burn the evidence */
7808 dupstr(s
->cur_prompt
->prompts
[0]->result
);
7812 * Check the two new passwords match.
7814 got_new
= (strcmp(s
->cur_prompt
->prompts
[1]->result
,
7815 s
->cur_prompt
->prompts
[2]->result
)
7818 /* They don't. Silly user. */
7819 c_write_str(ssh
, "Passwords do not match\r\n");
7824 * Send the new password (along with the old one).
7825 * (see above for padding rationale)
7827 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7828 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7829 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7830 /* service requested */
7831 ssh2_pkt_addstring(s
->pktout
, "password");
7832 ssh2_pkt_addbool(s
->pktout
, TRUE
);
7833 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
7834 ssh2_pkt_addstring(s
->pktout
, s
->password
);
7835 ssh2_pkt_addstring(s
->pktout
,
7836 s
->cur_prompt
->prompts
[1]->result
);
7837 free_prompts(s
->cur_prompt
);
7838 end_log_omission(ssh
, s
->pktout
);
7839 ssh2_pkt_send_with_padding(ssh
, s
->pktout
, 256);
7840 logevent("Sent new password");
7843 * Now see what the server has to say about it.
7844 * (If it's CHANGEREQ again, it's not happy with the
7847 crWaitUntilV(pktin
);
7848 changereq_first_time
= FALSE
;
7853 * We need to reexamine the current pktin at the top
7854 * of the loop. Either:
7855 * - we weren't asked to change password at all, in
7856 * which case it's a SUCCESS or FAILURE with the
7858 * - we sent a new password, and the server was
7859 * either OK with it (SUCCESS or FAILURE w/partial
7860 * success) or unhappy with the _old_ password
7861 * (FAILURE w/o partial success)
7862 * In any of these cases, we go back to the top of
7863 * the loop and start again.
7868 * We don't need the old password any more, in any
7869 * case. Burn the evidence.
7871 memset(s
->password
, 0, strlen(s
->password
));
7876 ssh_disconnect(ssh
, NULL
,
7877 "No supported authentication methods available",
7878 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE
,
7886 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] = NULL
;
7888 /* Clear up various bits and pieces from authentication. */
7889 if (s
->publickey_blob
) {
7890 sfree(s
->publickey_blob
);
7891 sfree(s
->publickey_comment
);
7893 if (s
->agent_response
)
7894 sfree(s
->agent_response
);
7897 * Now the connection protocol has started, one way or another.
7900 ssh
->channels
= newtree234(ssh_channelcmp
);
7903 * Set up handlers for some connection protocol messages, so we
7904 * don't have to handle them repeatedly in this coroutine.
7906 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] =
7907 ssh2_msg_channel_window_adjust
;
7908 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] =
7909 ssh2_msg_global_request
;
7912 * Create the main session channel.
7914 if (ssh
->cfg
.ssh_no_shell
) {
7915 ssh
->mainchan
= NULL
;
7916 } else if (*ssh
->cfg
.ssh_nc_host
) {
7918 * Just start a direct-tcpip channel and use it as the main
7921 ssh
->mainchan
= snew(struct ssh_channel
);
7922 ssh
->mainchan
->ssh
= ssh
;
7923 ssh
->mainchan
->localid
= alloc_channel_id(ssh
);
7925 "Opening direct-tcpip channel to %s:%d in place of session",
7926 ssh
->cfg
.ssh_nc_host
, ssh
->cfg
.ssh_nc_port
);
7927 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
7928 ssh2_pkt_addstring(s
->pktout
, "direct-tcpip");
7929 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->localid
);
7930 ssh
->mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
7931 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->v
.v2
.locwindow
);/* our window size */
7932 ssh2_pkt_adduint32(s
->pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
7933 ssh2_pkt_addstring(s
->pktout
, ssh
->cfg
.ssh_nc_host
);
7934 ssh2_pkt_adduint32(s
->pktout
, ssh
->cfg
.ssh_nc_port
);
7936 * There's nothing meaningful to put in the originator
7937 * fields, but some servers insist on syntactically correct
7940 ssh2_pkt_addstring(s
->pktout
, "0.0.0.0");
7941 ssh2_pkt_adduint32(s
->pktout
, 0);
7942 ssh2_pkt_send(ssh
, s
->pktout
);
7944 crWaitUntilV(pktin
);
7945 if (pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
7946 bombout(("Server refused to open a direct-tcpip channel"));
7948 /* FIXME: error data comes back in FAILURE packet */
7950 if (ssh_pkt_getuint32(pktin
) != ssh
->mainchan
->localid
) {
7951 bombout(("Server's channel confirmation cited wrong channel"));
7954 ssh
->mainchan
->remoteid
= ssh_pkt_getuint32(pktin
);
7955 ssh
->mainchan
->halfopen
= FALSE
;
7956 ssh
->mainchan
->type
= CHAN_MAINSESSION
;
7957 ssh
->mainchan
->closes
= 0;
7958 ssh
->mainchan
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
7959 ssh
->mainchan
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
7960 bufchain_init(&ssh
->mainchan
->v
.v2
.outbuffer
);
7961 add234(ssh
->channels
, ssh
->mainchan
);
7962 update_specials_menu(ssh
->frontend
);
7963 logevent("Opened direct-tcpip channel");
7966 ssh
->mainchan
= snew(struct ssh_channel
);
7967 ssh
->mainchan
->ssh
= ssh
;
7968 ssh
->mainchan
->localid
= alloc_channel_id(ssh
);
7969 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
7970 ssh2_pkt_addstring(s
->pktout
, "session");
7971 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->localid
);
7972 ssh
->mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
7973 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->v
.v2
.locwindow
);/* our window size */
7974 ssh2_pkt_adduint32(s
->pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
7975 ssh2_pkt_send(ssh
, s
->pktout
);
7976 crWaitUntilV(pktin
);
7977 if (pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
7978 bombout(("Server refused to open a session"));
7980 /* FIXME: error data comes back in FAILURE packet */
7982 if (ssh_pkt_getuint32(pktin
) != ssh
->mainchan
->localid
) {
7983 bombout(("Server's channel confirmation cited wrong channel"));
7986 ssh
->mainchan
->remoteid
= ssh_pkt_getuint32(pktin
);
7987 ssh
->mainchan
->halfopen
= FALSE
;
7988 ssh
->mainchan
->type
= CHAN_MAINSESSION
;
7989 ssh
->mainchan
->closes
= 0;
7990 ssh
->mainchan
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
7991 ssh
->mainchan
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
7992 bufchain_init(&ssh
->mainchan
->v
.v2
.outbuffer
);
7993 add234(ssh
->channels
, ssh
->mainchan
);
7994 update_specials_menu(ssh
->frontend
);
7995 logevent("Opened channel for session");
7996 ssh
->ncmode
= FALSE
;
8000 * Now we have a channel, make dispatch table entries for
8001 * general channel-based messages.
8003 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] =
8004 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] =
8005 ssh2_msg_channel_data
;
8006 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = ssh2_msg_channel_eof
;
8007 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = ssh2_msg_channel_close
;
8008 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] =
8009 ssh2_msg_channel_open_confirmation
;
8010 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] =
8011 ssh2_msg_channel_open_failure
;
8012 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_REQUEST
] =
8013 ssh2_msg_channel_request
;
8014 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] =
8015 ssh2_msg_channel_open
;
8018 * Potentially enable X11 forwarding.
8020 if (ssh
->mainchan
&& !ssh
->ncmode
&& ssh
->cfg
.x11_forward
) {
8021 char proto
[20], data
[64];
8022 logevent("Requesting X11 forwarding");
8023 ssh
->x11auth
= x11_invent_auth(proto
, sizeof(proto
),
8024 data
, sizeof(data
), ssh
->cfg
.x11_auth
);
8025 x11_get_real_auth(ssh
->x11auth
, ssh
->cfg
.x11_display
);
8026 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8027 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
8028 ssh2_pkt_addstring(s
->pktout
, "x11-req");
8029 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8030 ssh2_pkt_addbool(s
->pktout
, 0); /* many connections */
8031 ssh2_pkt_addstring(s
->pktout
, proto
);
8033 * Note that while we blank the X authentication data here, we don't
8034 * take any special action to blank the start of an X11 channel,
8035 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
8036 * without having session blanking enabled is likely to leak your
8037 * cookie into the log.
8039 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
8040 ssh2_pkt_addstring(s
->pktout
, data
);
8041 end_log_omission(ssh
, s
->pktout
);
8042 ssh2_pkt_adduint32(s
->pktout
, x11_get_screen_number(ssh
->cfg
.x11_display
));
8043 ssh2_pkt_send(ssh
, s
->pktout
);
8045 crWaitUntilV(pktin
);
8047 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
8048 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
8049 bombout(("Unexpected response to X11 forwarding request:"
8050 " packet type %d", pktin
->type
));
8053 logevent("X11 forwarding refused");
8055 logevent("X11 forwarding enabled");
8056 ssh
->X11_fwd_enabled
= TRUE
;
8061 * Enable port forwardings.
8063 ssh_setup_portfwd(ssh
, &ssh
->cfg
);
8066 * Potentially enable agent forwarding.
8068 if (ssh
->mainchan
&& !ssh
->ncmode
&& ssh
->cfg
.agentfwd
&& agent_exists()) {
8069 logevent("Requesting OpenSSH-style agent forwarding");
8070 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8071 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
8072 ssh2_pkt_addstring(s
->pktout
, "auth-agent-req@openssh.com");
8073 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8074 ssh2_pkt_send(ssh
, s
->pktout
);
8076 crWaitUntilV(pktin
);
8078 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
8079 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
8080 bombout(("Unexpected response to agent forwarding request:"
8081 " packet type %d", pktin
->type
));
8084 logevent("Agent forwarding refused");
8086 logevent("Agent forwarding enabled");
8087 ssh
->agentfwd_enabled
= TRUE
;
8092 * Now allocate a pty for the session.
8094 if (ssh
->mainchan
&& !ssh
->ncmode
&& !ssh
->cfg
.nopty
) {
8095 /* Unpick the terminal-speed string. */
8096 /* XXX perhaps we should allow no speeds to be sent. */
8097 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
8098 sscanf(ssh
->cfg
.termspeed
, "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
8099 /* Build the pty request. */
8100 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8101 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
); /* recipient channel */
8102 ssh2_pkt_addstring(s
->pktout
, "pty-req");
8103 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8104 ssh2_pkt_addstring(s
->pktout
, ssh
->cfg
.termtype
);
8105 ssh2_pkt_adduint32(s
->pktout
, ssh
->term_width
);
8106 ssh2_pkt_adduint32(s
->pktout
, ssh
->term_height
);
8107 ssh2_pkt_adduint32(s
->pktout
, 0); /* pixel width */
8108 ssh2_pkt_adduint32(s
->pktout
, 0); /* pixel height */
8109 ssh2_pkt_addstring_start(s
->pktout
);
8110 parse_ttymodes(ssh
, ssh
->cfg
.ttymodes
,
8111 ssh2_send_ttymode
, (void *)s
->pktout
);
8112 ssh2_pkt_addbyte(s
->pktout
, SSH2_TTY_OP_ISPEED
);
8113 ssh2_pkt_adduint32(s
->pktout
, ssh
->ispeed
);
8114 ssh2_pkt_addbyte(s
->pktout
, SSH2_TTY_OP_OSPEED
);
8115 ssh2_pkt_adduint32(s
->pktout
, ssh
->ospeed
);
8116 ssh2_pkt_addstring_data(s
->pktout
, "\0", 1); /* TTY_OP_END */
8117 ssh2_pkt_send(ssh
, s
->pktout
);
8118 ssh
->state
= SSH_STATE_INTERMED
;
8120 crWaitUntilV(pktin
);
8122 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
8123 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
8124 bombout(("Unexpected response to pty request:"
8125 " packet type %d", pktin
->type
));
8128 c_write_str(ssh
, "Server refused to allocate pty\r\n");
8129 ssh
->editing
= ssh
->echoing
= 1;
8131 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8132 ssh
->ospeed
, ssh
->ispeed
);
8135 ssh
->editing
= ssh
->echoing
= 1;
8139 * Send environment variables.
8141 * Simplest thing here is to send all the requests at once, and
8142 * then wait for a whole bunch of successes or failures.
8144 if (ssh
->mainchan
&& !ssh
->ncmode
&& *ssh
->cfg
.environmt
) {
8145 char *e
= ssh
->cfg
.environmt
;
8146 char *var
, *varend
, *val
;
8152 while (*e
&& *e
!= '\t') e
++;
8154 if (*e
== '\t') e
++;
8159 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8160 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
8161 ssh2_pkt_addstring(s
->pktout
, "env");
8162 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8163 ssh2_pkt_addstring_start(s
->pktout
);
8164 ssh2_pkt_addstring_data(s
->pktout
, var
, varend
-var
);
8165 ssh2_pkt_addstring(s
->pktout
, val
);
8166 ssh2_pkt_send(ssh
, s
->pktout
);
8171 logeventf(ssh
, "Sent %d environment variables", s
->num_env
);
8174 s
->env_left
= s
->num_env
;
8176 while (s
->env_left
> 0) {
8177 crWaitUntilV(pktin
);
8179 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
8180 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
8181 bombout(("Unexpected response to environment request:"
8182 " packet type %d", pktin
->type
));
8192 if (s
->env_ok
== s
->num_env
) {
8193 logevent("All environment variables successfully set");
8194 } else if (s
->env_ok
== 0) {
8195 logevent("All environment variables refused");
8196 c_write_str(ssh
, "Server refused to set environment variables\r\n");
8198 logeventf(ssh
, "%d environment variables refused",
8199 s
->num_env
- s
->env_ok
);
8200 c_write_str(ssh
, "Server refused to set all environment variables\r\n");
8205 * Start a shell or a remote command. We may have to attempt
8206 * this twice if the config data has provided a second choice
8209 if (ssh
->mainchan
&& !ssh
->ncmode
) while (1) {
8213 if (ssh
->fallback_cmd
) {
8214 subsys
= ssh
->cfg
.ssh_subsys2
;
8215 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
8217 subsys
= ssh
->cfg
.ssh_subsys
;
8218 cmd
= ssh
->cfg
.remote_cmd_ptr
;
8219 if (!cmd
) cmd
= ssh
->cfg
.remote_cmd
;
8222 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8223 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
); /* recipient channel */
8225 ssh2_pkt_addstring(s
->pktout
, "subsystem");
8226 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8227 ssh2_pkt_addstring(s
->pktout
, cmd
);
8229 ssh2_pkt_addstring(s
->pktout
, "exec");
8230 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8231 ssh2_pkt_addstring(s
->pktout
, cmd
);
8233 ssh2_pkt_addstring(s
->pktout
, "shell");
8234 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
8236 ssh2_pkt_send(ssh
, s
->pktout
);
8238 crWaitUntilV(pktin
);
8240 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
8241 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
8242 bombout(("Unexpected response to shell/command request:"
8243 " packet type %d", pktin
->type
));
8247 * We failed to start the command. If this is the
8248 * fallback command, we really are finished; if it's
8249 * not, and if the fallback command exists, try falling
8250 * back to it before complaining.
8252 if (!ssh
->fallback_cmd
&& ssh
->cfg
.remote_cmd_ptr2
!= NULL
) {
8253 logevent("Primary command failed; attempting fallback");
8254 ssh
->fallback_cmd
= TRUE
;
8257 bombout(("Server refused to start a shell/command"));
8260 logevent("Started a shell/command");
8265 ssh
->state
= SSH_STATE_SESSION
;
8266 if (ssh
->size_needed
)
8267 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
8268 if (ssh
->eof_needed
)
8269 ssh_special(ssh
, TS_EOF
);
8275 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
8280 s
->try_send
= FALSE
;
8284 * _All_ the connection-layer packets we expect to
8285 * receive are now handled by the dispatch table.
8286 * Anything that reaches here must be bogus.
8289 bombout(("Strange packet received: type %d", pktin
->type
));
8291 } else if (ssh
->mainchan
) {
8293 * We have spare data. Add it to the channel buffer.
8295 ssh2_add_channel_data(ssh
->mainchan
, (char *)in
, inlen
);
8300 struct ssh_channel
*c
;
8302 * Try to send data on all channels if we can.
8304 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++)
8305 ssh2_try_send_and_unthrottle(c
);
8313 * Handlers for SSH-2 messages that might arrive at any moment.
8315 static void ssh2_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
8317 /* log reason code in disconnect message */
8319 int nowlen
, reason
, msglen
;
8321 reason
= ssh_pkt_getuint32(pktin
);
8322 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
8324 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
8325 buf
= dupprintf("Received disconnect message (%s)",
8326 ssh2_disconnect_reasons
[reason
]);
8328 buf
= dupprintf("Received disconnect message (unknown"
8329 " type %d)", reason
);
8333 buf
= dupprintf("Disconnection message text: %n%.*s",
8334 &nowlen
, msglen
, msg
);
8336 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
8338 (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) ?
8339 ssh2_disconnect_reasons
[reason
] : "unknown",
8344 static void ssh2_msg_debug(Ssh ssh
, struct Packet
*pktin
)
8346 /* log the debug message */
8351 /* XXX maybe we should actually take notice of this */
8352 always_display
= ssh2_pkt_getbool(pktin
);
8353 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
8355 logeventf(ssh
, "Remote debug message: %.*s", msglen
, msg
);
8358 static void ssh2_msg_something_unimplemented(Ssh ssh
, struct Packet
*pktin
)
8360 struct Packet
*pktout
;
8361 pktout
= ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED
);
8362 ssh2_pkt_adduint32(pktout
, pktin
->sequence
);
8364 * UNIMPLEMENTED messages MUST appear in the same order as the
8365 * messages they respond to. Hence, never queue them.
8367 ssh2_pkt_send_noqueue(ssh
, pktout
);
8371 * Handle the top-level SSH-2 protocol.
8373 static void ssh2_protocol_setup(Ssh ssh
)
8378 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
8380 for (i
= 0; i
< 256; i
++)
8381 ssh
->packet_dispatch
[i
] = ssh2_msg_something_unimplemented
;
8384 * Any message we actually understand, we set to NULL so that
8385 * the coroutines will get it.
8387 ssh
->packet_dispatch
[SSH2_MSG_UNIMPLEMENTED
] = NULL
;
8388 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_REQUEST
] = NULL
;
8389 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_ACCEPT
] = NULL
;
8390 ssh
->packet_dispatch
[SSH2_MSG_KEXINIT
] = NULL
;
8391 ssh
->packet_dispatch
[SSH2_MSG_NEWKEYS
] = NULL
;
8392 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_INIT
] = NULL
;
8393 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_REPLY
] = NULL
;
8394 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
8395 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
8396 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_INIT
] = NULL
;
8397 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_REPLY
] = NULL
;
8398 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_REQUEST
] = NULL
;
8399 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_FAILURE
] = NULL
;
8400 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_SUCCESS
] = NULL
;
8401 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] = NULL
;
8402 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_PK_OK
] = NULL
;
8403 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
8404 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
8405 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_INFO_RESPONSE
] = NULL
;
8406 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] = NULL
;
8407 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_SUCCESS
] = NULL
;
8408 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_FAILURE
] = NULL
;
8409 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] = NULL
;
8410 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] = NULL
;
8411 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] = NULL
;
8412 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] = NULL
;
8413 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] = NULL
;
8414 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] = NULL
;
8415 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = NULL
;
8416 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = NULL
;
8417 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_REQUEST
] = NULL
;
8418 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_SUCCESS
] = NULL
;
8419 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_FAILURE
] = NULL
;
8422 * These special message types we install handlers for.
8424 ssh
->packet_dispatch
[SSH2_MSG_DISCONNECT
] = ssh2_msg_disconnect
;
8425 ssh
->packet_dispatch
[SSH2_MSG_IGNORE
] = ssh_msg_ignore
; /* shared with SSH-1 */
8426 ssh
->packet_dispatch
[SSH2_MSG_DEBUG
] = ssh2_msg_debug
;
8429 static void ssh2_timer(void *ctx
, long now
)
8433 if (ssh
->state
== SSH_STATE_CLOSED
)
8436 if (!ssh
->kex_in_progress
&& ssh
->cfg
.ssh_rekey_time
!= 0 &&
8437 now
- ssh
->next_rekey
>= 0) {
8438 do_ssh2_transport(ssh
, "timeout", -1, NULL
);
8442 static void ssh2_protocol(Ssh ssh
, void *vin
, int inlen
,
8443 struct Packet
*pktin
)
8445 unsigned char *in
= (unsigned char *)vin
;
8446 if (ssh
->state
== SSH_STATE_CLOSED
)
8450 ssh
->incoming_data_size
+= pktin
->encrypted_len
;
8451 if (!ssh
->kex_in_progress
&&
8452 ssh
->max_data_size
!= 0 &&
8453 ssh
->incoming_data_size
> ssh
->max_data_size
)
8454 do_ssh2_transport(ssh
, "too much data received", -1, NULL
);
8457 if (pktin
&& ssh
->packet_dispatch
[pktin
->type
]) {
8458 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
8462 if (!ssh
->protocol_initial_phase_done
||
8463 (pktin
&& pktin
->type
>= 20 && pktin
->type
< 50)) {
8464 if (do_ssh2_transport(ssh
, in
, inlen
, pktin
) &&
8465 !ssh
->protocol_initial_phase_done
) {
8466 ssh
->protocol_initial_phase_done
= TRUE
;
8468 * Allow authconn to initialise itself.
8470 do_ssh2_authconn(ssh
, NULL
, 0, NULL
);
8473 do_ssh2_authconn(ssh
, in
, inlen
, pktin
);
8478 * Called to set up the connection.
8480 * Returns an error message, or NULL on success.
8482 static const char *ssh_init(void *frontend_handle
, void **backend_handle
,
8484 char *host
, int port
, char **realhost
, int nodelay
,
8490 ssh
= snew(struct ssh_tag
);
8491 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
8492 ssh
->version
= 0; /* when not ready yet */
8495 ssh
->v1_cipher_ctx
= NULL
;
8496 ssh
->crcda_ctx
= NULL
;
8497 ssh
->cscipher
= NULL
;
8498 ssh
->cs_cipher_ctx
= NULL
;
8499 ssh
->sccipher
= NULL
;
8500 ssh
->sc_cipher_ctx
= NULL
;
8502 ssh
->cs_mac_ctx
= NULL
;
8504 ssh
->sc_mac_ctx
= NULL
;
8506 ssh
->cs_comp_ctx
= NULL
;
8508 ssh
->sc_comp_ctx
= NULL
;
8510 ssh
->kex_ctx
= NULL
;
8511 ssh
->hostkey
= NULL
;
8513 ssh
->close_expected
= FALSE
;
8514 ssh
->clean_exit
= FALSE
;
8515 ssh
->state
= SSH_STATE_PREPACKET
;
8516 ssh
->size_needed
= FALSE
;
8517 ssh
->eof_needed
= FALSE
;
8520 ssh
->deferred_send_data
= NULL
;
8521 ssh
->deferred_len
= 0;
8522 ssh
->deferred_size
= 0;
8523 ssh
->fallback_cmd
= 0;
8525 ssh
->x11auth
= NULL
;
8526 ssh
->v1_compressing
= FALSE
;
8527 ssh
->v2_outgoing_sequence
= 0;
8528 ssh
->ssh1_rdpkt_crstate
= 0;
8529 ssh
->ssh2_rdpkt_crstate
= 0;
8530 ssh
->do_ssh_init_crstate
= 0;
8531 ssh
->ssh_gotdata_crstate
= 0;
8532 ssh
->do_ssh1_connection_crstate
= 0;
8533 ssh
->do_ssh1_login_crstate
= 0;
8534 ssh
->do_ssh2_transport_crstate
= 0;
8535 ssh
->do_ssh2_authconn_crstate
= 0;
8536 ssh
->do_ssh_init_state
= NULL
;
8537 ssh
->do_ssh1_login_state
= NULL
;
8538 ssh
->do_ssh2_transport_state
= NULL
;
8539 ssh
->do_ssh2_authconn_state
= NULL
;
8542 ssh
->mainchan
= NULL
;
8543 ssh
->throttled_all
= 0;
8544 ssh
->v1_stdout_throttling
= 0;
8546 ssh
->queuelen
= ssh
->queuesize
= 0;
8547 ssh
->queueing
= FALSE
;
8548 ssh
->qhead
= ssh
->qtail
= NULL
;
8549 ssh
->deferred_rekey_reason
= NULL
;
8550 bufchain_init(&ssh
->queued_incoming_data
);
8551 ssh
->frozen
= FALSE
;
8553 *backend_handle
= ssh
;
8556 if (crypto_startup() == 0)
8557 return "Microsoft high encryption pack not installed!";
8560 ssh
->frontend
= frontend_handle
;
8561 ssh
->term_width
= ssh
->cfg
.width
;
8562 ssh
->term_height
= ssh
->cfg
.height
;
8564 ssh
->channels
= NULL
;
8565 ssh
->rportfwds
= NULL
;
8566 ssh
->portfwds
= NULL
;
8571 ssh
->v1_throttle_count
= 0;
8572 ssh
->overall_bufsize
= 0;
8573 ssh
->fallback_cmd
= 0;
8575 ssh
->protocol
= NULL
;
8577 ssh
->protocol_initial_phase_done
= FALSE
;
8581 ssh
->incoming_data_size
= ssh
->outgoing_data_size
=
8582 ssh
->deferred_data_size
= 0L;
8583 ssh
->max_data_size
= parse_blocksize(ssh
->cfg
.ssh_rekey_data
);
8584 ssh
->kex_in_progress
= FALSE
;
8586 p
= connect_to_host(ssh
, host
, port
, realhost
, nodelay
, keepalive
);
8595 static void ssh_free(void *handle
)
8597 Ssh ssh
= (Ssh
) handle
;
8598 struct ssh_channel
*c
;
8599 struct ssh_rportfwd
*pf
;
8601 if (ssh
->v1_cipher_ctx
)
8602 ssh
->cipher
->free_context(ssh
->v1_cipher_ctx
);
8603 if (ssh
->cs_cipher_ctx
)
8604 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
8605 if (ssh
->sc_cipher_ctx
)
8606 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
8607 if (ssh
->cs_mac_ctx
)
8608 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
8609 if (ssh
->sc_mac_ctx
)
8610 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
8611 if (ssh
->cs_comp_ctx
) {
8613 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
8615 zlib_compress_cleanup(ssh
->cs_comp_ctx
);
8617 if (ssh
->sc_comp_ctx
) {
8619 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
8621 zlib_decompress_cleanup(ssh
->sc_comp_ctx
);
8624 dh_cleanup(ssh
->kex_ctx
);
8625 sfree(ssh
->savedhost
);
8627 while (ssh
->queuelen
-- > 0)
8628 ssh_free_packet(ssh
->queue
[ssh
->queuelen
]);
8631 while (ssh
->qhead
) {
8632 struct queued_handler
*qh
= ssh
->qhead
;
8633 ssh
->qhead
= qh
->next
;
8636 ssh
->qhead
= ssh
->qtail
= NULL
;
8638 if (ssh
->channels
) {
8639 while ((c
= delpos234(ssh
->channels
, 0)) != NULL
) {
8642 if (c
->u
.x11
.s
!= NULL
)
8643 x11_close(c
->u
.x11
.s
);
8646 if (c
->u
.pfd
.s
!= NULL
)
8647 pfd_close(c
->u
.pfd
.s
);
8652 freetree234(ssh
->channels
);
8653 ssh
->channels
= NULL
;
8656 if (ssh
->rportfwds
) {
8657 while ((pf
= delpos234(ssh
->rportfwds
, 0)) != NULL
)
8659 freetree234(ssh
->rportfwds
);
8660 ssh
->rportfwds
= NULL
;
8662 sfree(ssh
->deferred_send_data
);
8664 x11_free_auth(ssh
->x11auth
);
8665 sfree(ssh
->do_ssh_init_state
);
8666 sfree(ssh
->do_ssh1_login_state
);
8667 sfree(ssh
->do_ssh2_transport_state
);
8668 sfree(ssh
->do_ssh2_authconn_state
);
8671 if (ssh
->crcda_ctx
) {
8672 crcda_free_context(ssh
->crcda_ctx
);
8673 ssh
->crcda_ctx
= NULL
;
8676 ssh_do_close(ssh
, TRUE
);
8677 expire_timer_context(ssh
);
8679 pinger_free(ssh
->pinger
);
8680 bufchain_clear(&ssh
->queued_incoming_data
);
8687 * Reconfigure the SSH backend.
8689 static void ssh_reconfig(void *handle
, Config
*cfg
)
8691 Ssh ssh
= (Ssh
) handle
;
8692 char *rekeying
= NULL
, rekey_mandatory
= FALSE
;
8693 unsigned long old_max_data_size
;
8695 pinger_reconfig(ssh
->pinger
, &ssh
->cfg
, cfg
);
8697 ssh_setup_portfwd(ssh
, cfg
);
8699 if (ssh
->cfg
.ssh_rekey_time
!= cfg
->ssh_rekey_time
&&
8700 cfg
->ssh_rekey_time
!= 0) {
8701 long new_next
= ssh
->last_rekey
+ cfg
->ssh_rekey_time
*60*TICKSPERSEC
;
8702 long now
= GETTICKCOUNT();
8704 if (new_next
- now
< 0) {
8705 rekeying
= "timeout shortened";
8707 ssh
->next_rekey
= schedule_timer(new_next
- now
, ssh2_timer
, ssh
);
8711 old_max_data_size
= ssh
->max_data_size
;
8712 ssh
->max_data_size
= parse_blocksize(cfg
->ssh_rekey_data
);
8713 if (old_max_data_size
!= ssh
->max_data_size
&&
8714 ssh
->max_data_size
!= 0) {
8715 if (ssh
->outgoing_data_size
> ssh
->max_data_size
||
8716 ssh
->incoming_data_size
> ssh
->max_data_size
)
8717 rekeying
= "data limit lowered";
8720 if (ssh
->cfg
.compression
!= cfg
->compression
) {
8721 rekeying
= "compression setting changed";
8722 rekey_mandatory
= TRUE
;
8725 if (ssh
->cfg
.ssh2_des_cbc
!= cfg
->ssh2_des_cbc
||
8726 memcmp(ssh
->cfg
.ssh_cipherlist
, cfg
->ssh_cipherlist
,
8727 sizeof(ssh
->cfg
.ssh_cipherlist
))) {
8728 rekeying
= "cipher settings changed";
8729 rekey_mandatory
= TRUE
;
8732 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
8735 if (!ssh
->kex_in_progress
) {
8736 do_ssh2_transport(ssh
, rekeying
, -1, NULL
);
8737 } else if (rekey_mandatory
) {
8738 ssh
->deferred_rekey_reason
= rekeying
;
8744 * Called to send data down the SSH connection.
8746 static int ssh_send(void *handle
, char *buf
, int len
)
8748 Ssh ssh
= (Ssh
) handle
;
8750 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
8753 ssh
->protocol(ssh
, (unsigned char *)buf
, len
, 0);
8755 return ssh_sendbuffer(ssh
);
8759 * Called to query the current amount of buffered stdin data.
8761 static int ssh_sendbuffer(void *handle
)
8763 Ssh ssh
= (Ssh
) handle
;
8766 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
8770 * If the SSH socket itself has backed up, add the total backup
8771 * size on that to any individual buffer on the stdin channel.
8774 if (ssh
->throttled_all
)
8775 override_value
= ssh
->overall_bufsize
;
8777 if (ssh
->version
== 1) {
8778 return override_value
;
8779 } else if (ssh
->version
== 2) {
8780 if (!ssh
->mainchan
|| ssh
->mainchan
->closes
> 0)
8781 return override_value
;
8783 return (override_value
+
8784 bufchain_size(&ssh
->mainchan
->v
.v2
.outbuffer
));
8791 * Called to set the size of the window from SSH's POV.
8793 static void ssh_size(void *handle
, int width
, int height
)
8795 Ssh ssh
= (Ssh
) handle
;
8796 struct Packet
*pktout
;
8798 ssh
->term_width
= width
;
8799 ssh
->term_height
= height
;
8801 switch (ssh
->state
) {
8802 case SSH_STATE_BEFORE_SIZE
:
8803 case SSH_STATE_PREPACKET
:
8804 case SSH_STATE_CLOSED
:
8805 break; /* do nothing */
8806 case SSH_STATE_INTERMED
:
8807 ssh
->size_needed
= TRUE
; /* buffer for later */
8809 case SSH_STATE_SESSION
:
8810 if (!ssh
->cfg
.nopty
) {
8811 if (ssh
->version
== 1) {
8812 send_packet(ssh
, SSH1_CMSG_WINDOW_SIZE
,
8813 PKT_INT
, ssh
->term_height
,
8814 PKT_INT
, ssh
->term_width
,
8815 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
8816 } else if (ssh
->mainchan
) {
8817 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8818 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
8819 ssh2_pkt_addstring(pktout
, "window-change");
8820 ssh2_pkt_addbool(pktout
, 0);
8821 ssh2_pkt_adduint32(pktout
, ssh
->term_width
);
8822 ssh2_pkt_adduint32(pktout
, ssh
->term_height
);
8823 ssh2_pkt_adduint32(pktout
, 0);
8824 ssh2_pkt_adduint32(pktout
, 0);
8825 ssh2_pkt_send(ssh
, pktout
);
8833 * Return a list of the special codes that make sense in this
8836 static const struct telnet_special
*ssh_get_specials(void *handle
)
8838 static const struct telnet_special ssh1_ignore_special
[] = {
8839 {"IGNORE message", TS_NOP
}
8841 static const struct telnet_special ssh2_transport_specials
[] = {
8842 {"IGNORE message", TS_NOP
},
8843 {"Repeat key exchange", TS_REKEY
},
8845 static const struct telnet_special ssh2_session_specials
[] = {
8848 /* These are the signal names defined by draft-ietf-secsh-connect-23.
8849 * They include all the ISO C signals, but are a subset of the POSIX
8850 * required signals. */
8851 {"SIGINT (Interrupt)", TS_SIGINT
},
8852 {"SIGTERM (Terminate)", TS_SIGTERM
},
8853 {"SIGKILL (Kill)", TS_SIGKILL
},
8854 {"SIGQUIT (Quit)", TS_SIGQUIT
},
8855 {"SIGHUP (Hangup)", TS_SIGHUP
},
8856 {"More signals", TS_SUBMENU
},
8857 {"SIGABRT", TS_SIGABRT
}, {"SIGALRM", TS_SIGALRM
},
8858 {"SIGFPE", TS_SIGFPE
}, {"SIGILL", TS_SIGILL
},
8859 {"SIGPIPE", TS_SIGPIPE
}, {"SIGSEGV", TS_SIGSEGV
},
8860 {"SIGUSR1", TS_SIGUSR1
}, {"SIGUSR2", TS_SIGUSR2
},
8863 static const struct telnet_special specials_end
[] = {
8866 /* XXX review this length for any changes: */
8867 static struct telnet_special ssh_specials
[lenof(ssh2_transport_specials
) +
8868 lenof(ssh2_session_specials
) +
8869 lenof(specials_end
)];
8870 Ssh ssh
= (Ssh
) handle
;
8872 #define ADD_SPECIALS(name) \
8874 assert((i + lenof(name)) <= lenof(ssh_specials)); \
8875 memcpy(&ssh_specials[i], name, sizeof name); \
8879 if (ssh
->version
== 1) {
8880 /* Don't bother offering IGNORE if we've decided the remote
8881 * won't cope with it, since we wouldn't bother sending it if
8883 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
8884 ADD_SPECIALS(ssh1_ignore_special
);
8885 } else if (ssh
->version
== 2) {
8886 ADD_SPECIALS(ssh2_transport_specials
);
8888 ADD_SPECIALS(ssh2_session_specials
);
8889 } /* else we're not ready yet */
8892 ADD_SPECIALS(specials_end
);
8893 return ssh_specials
;
8901 * Send special codes. TS_EOF is useful for `plink', so you
8902 * can send an EOF and collect resulting output (e.g. `plink
8905 static void ssh_special(void *handle
, Telnet_Special code
)
8907 Ssh ssh
= (Ssh
) handle
;
8908 struct Packet
*pktout
;
8910 if (code
== TS_EOF
) {
8911 if (ssh
->state
!= SSH_STATE_SESSION
) {
8913 * Buffer the EOF in case we are pre-SESSION, so we can
8914 * send it as soon as we reach SESSION.
8917 ssh
->eof_needed
= TRUE
;
8920 if (ssh
->version
== 1) {
8921 send_packet(ssh
, SSH1_CMSG_EOF
, PKT_END
);
8922 } else if (ssh
->mainchan
) {
8923 struct Packet
*pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
8924 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
8925 ssh2_pkt_send(ssh
, pktout
);
8926 ssh
->send_ok
= 0; /* now stop trying to read from stdin */
8928 logevent("Sent EOF message");
8929 } else if (code
== TS_PING
|| code
== TS_NOP
) {
8930 if (ssh
->state
== SSH_STATE_CLOSED
8931 || ssh
->state
== SSH_STATE_PREPACKET
) return;
8932 if (ssh
->version
== 1) {
8933 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
8934 send_packet(ssh
, SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
8936 pktout
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
8937 ssh2_pkt_addstring_start(pktout
);
8938 ssh2_pkt_send_noqueue(ssh
, pktout
);
8940 } else if (code
== TS_REKEY
) {
8941 if (!ssh
->kex_in_progress
&& ssh
->version
== 2) {
8942 do_ssh2_transport(ssh
, "at user request", -1, NULL
);
8944 } else if (code
== TS_BRK
) {
8945 if (ssh
->state
== SSH_STATE_CLOSED
8946 || ssh
->state
== SSH_STATE_PREPACKET
) return;
8947 if (ssh
->version
== 1) {
8948 logevent("Unable to send BREAK signal in SSH-1");
8949 } else if (ssh
->mainchan
) {
8950 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8951 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
8952 ssh2_pkt_addstring(pktout
, "break");
8953 ssh2_pkt_addbool(pktout
, 0);
8954 ssh2_pkt_adduint32(pktout
, 0); /* default break length */
8955 ssh2_pkt_send(ssh
, pktout
);
8958 /* Is is a POSIX signal? */
8959 char *signame
= NULL
;
8960 if (code
== TS_SIGABRT
) signame
= "ABRT";
8961 if (code
== TS_SIGALRM
) signame
= "ALRM";
8962 if (code
== TS_SIGFPE
) signame
= "FPE";
8963 if (code
== TS_SIGHUP
) signame
= "HUP";
8964 if (code
== TS_SIGILL
) signame
= "ILL";
8965 if (code
== TS_SIGINT
) signame
= "INT";
8966 if (code
== TS_SIGKILL
) signame
= "KILL";
8967 if (code
== TS_SIGPIPE
) signame
= "PIPE";
8968 if (code
== TS_SIGQUIT
) signame
= "QUIT";
8969 if (code
== TS_SIGSEGV
) signame
= "SEGV";
8970 if (code
== TS_SIGTERM
) signame
= "TERM";
8971 if (code
== TS_SIGUSR1
) signame
= "USR1";
8972 if (code
== TS_SIGUSR2
) signame
= "USR2";
8973 /* The SSH-2 protocol does in principle support arbitrary named
8974 * signals, including signame@domain, but we don't support those. */
8976 /* It's a signal. */
8977 if (ssh
->version
== 2 && ssh
->mainchan
) {
8978 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8979 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
8980 ssh2_pkt_addstring(pktout
, "signal");
8981 ssh2_pkt_addbool(pktout
, 0);
8982 ssh2_pkt_addstring(pktout
, signame
);
8983 ssh2_pkt_send(ssh
, pktout
);
8984 logeventf(ssh
, "Sent signal SIG%s", signame
);
8987 /* Never heard of it. Do nothing */
8992 void *new_sock_channel(void *handle
, Socket s
)
8994 Ssh ssh
= (Ssh
) handle
;
8995 struct ssh_channel
*c
;
8996 c
= snew(struct ssh_channel
);
9001 c
->localid
= alloc_channel_id(ssh
);
9003 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
9005 bufchain_init(&c
->v
.v2
.outbuffer
);
9006 add234(ssh
->channels
, c
);
9012 * This is called when stdout/stderr (the entity to which
9013 * from_backend sends data) manages to clear some backlog.
9015 static void ssh_unthrottle(void *handle
, int bufsize
)
9017 Ssh ssh
= (Ssh
) handle
;
9018 if (ssh
->version
== 1) {
9019 if (ssh
->v1_stdout_throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
9020 ssh
->v1_stdout_throttling
= 0;
9021 ssh1_throttle(ssh
, -1);
9024 ssh2_set_window(ssh
->mainchan
, OUR_V2_WINSIZE
- bufsize
);
9028 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
9030 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
9032 struct Packet
*pktout
;
9034 logeventf(ssh
, "Opening forwarded connection to %s:%d", hostname
, port
);
9036 if (ssh
->version
== 1) {
9037 send_packet(ssh
, SSH1_MSG_PORT_OPEN
,
9038 PKT_INT
, c
->localid
,
9041 /* PKT_STR, <org:orgport>, */
9044 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
9045 ssh2_pkt_addstring(pktout
, "direct-tcpip");
9046 ssh2_pkt_adduint32(pktout
, c
->localid
);
9047 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
9048 ssh2_pkt_adduint32(pktout
, c
->v
.v2
.locwindow
);/* our window size */
9049 ssh2_pkt_adduint32(pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
9050 ssh2_pkt_addstring(pktout
, hostname
);
9051 ssh2_pkt_adduint32(pktout
, port
);
9053 * We make up values for the originator data; partly it's
9054 * too much hassle to keep track, and partly I'm not
9055 * convinced the server should be told details like that
9056 * about my local network configuration.
9057 * The "originator IP address" is syntactically a numeric
9058 * IP address, and some servers (e.g., Tectia) get upset
9059 * if it doesn't match this syntax.
9061 ssh2_pkt_addstring(pktout
, "0.0.0.0");
9062 ssh2_pkt_adduint32(pktout
, 0);
9063 ssh2_pkt_send(ssh
, pktout
);
9067 static int ssh_connected(void *handle
)
9069 Ssh ssh
= (Ssh
) handle
;
9070 return ssh
->s
!= NULL
;
9073 static int ssh_sendok(void *handle
)
9075 Ssh ssh
= (Ssh
) handle
;
9076 return ssh
->send_ok
;
9079 static int ssh_ldisc(void *handle
, int option
)
9081 Ssh ssh
= (Ssh
) handle
;
9082 if (option
== LD_ECHO
)
9083 return ssh
->echoing
;
9084 if (option
== LD_EDIT
)
9085 return ssh
->editing
;
9089 static void ssh_provide_ldisc(void *handle
, void *ldisc
)
9091 Ssh ssh
= (Ssh
) handle
;
9095 static void ssh_provide_logctx(void *handle
, void *logctx
)
9097 Ssh ssh
= (Ssh
) handle
;
9098 ssh
->logctx
= logctx
;
9101 static int ssh_return_exitcode(void *handle
)
9103 Ssh ssh
= (Ssh
) handle
;
9107 return (ssh
->exitcode
>= 0 ? ssh
->exitcode
: INT_MAX
);
9111 * cfg_info for SSH is the currently running version of the
9112 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
9114 static int ssh_cfg_info(void *handle
)
9116 Ssh ssh
= (Ssh
) handle
;
9117 return ssh
->version
;
9121 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
9122 * that fails. This variable is the means by which scp.c can reach
9123 * into the SSH code and find out which one it got.
9125 extern int ssh_fallback_cmd(void *handle
)
9127 Ssh ssh
= (Ssh
) handle
;
9128 return ssh
->fallback_cmd
;
9131 Backend ssh_backend
= {
9141 ssh_return_exitcode
,