17 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
18 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
19 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
20 #define SSH1_CMSG_USER 4 /* 0x4 */
21 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
22 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
23 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
24 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
25 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
26 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
27 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
28 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
29 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
30 #define SSH1_SMSG_FAILURE 15 /* 0xf */
31 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
32 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
33 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
34 #define SSH1_CMSG_EOF 19 /* 0x13 */
35 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
36 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
37 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
38 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
39 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
40 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
41 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
42 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
43 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
44 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
45 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
46 #define SSH1_MSG_IGNORE 32 /* 0x20 */
47 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
48 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
49 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
50 #define SSH1_MSG_DEBUG 36 /* 0x24 */
51 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
52 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
53 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
54 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
55 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
56 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
57 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
59 #define SSH1_AUTH_TIS 5 /* 0x5 */
60 #define SSH1_AUTH_CCARD 16 /* 0x10 */
62 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
63 /* Mask for protoflags we will echo back to server if seen */
64 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
66 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
67 #define SSH2_MSG_IGNORE 2 /* 0x2 */
68 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
69 #define SSH2_MSG_DEBUG 4 /* 0x4 */
70 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
71 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
72 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
73 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
74 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
75 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
76 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
77 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
78 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
79 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
80 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
81 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
82 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
83 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
84 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
85 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
86 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
87 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
88 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
89 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
90 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
91 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
92 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
93 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
94 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
95 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
96 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
97 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
98 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
99 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
100 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
101 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
104 * Packet type contexts, so that ssh2_pkt_type can correctly decode
105 * the ambiguous type numbers back into the correct type strings.
107 #define SSH2_PKTCTX_DHGROUP 0x0001
108 #define SSH2_PKTCTX_DHGEX 0x0002
109 #define SSH2_PKTCTX_KEX_MASK 0x000F
110 #define SSH2_PKTCTX_PUBLICKEY 0x0010
111 #define SSH2_PKTCTX_PASSWORD 0x0020
112 #define SSH2_PKTCTX_KBDINTER 0x0040
113 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
115 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
116 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
117 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
118 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
119 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
120 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
121 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
122 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
123 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
124 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
125 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
126 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
127 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
128 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
129 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
131 static const char *const ssh2_disconnect_reasons
[] = {
133 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
134 "SSH_DISCONNECT_PROTOCOL_ERROR",
135 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
136 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
137 "SSH_DISCONNECT_MAC_ERROR",
138 "SSH_DISCONNECT_COMPRESSION_ERROR",
139 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
140 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
141 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
142 "SSH_DISCONNECT_CONNECTION_LOST",
143 "SSH_DISCONNECT_BY_APPLICATION",
144 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
145 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
146 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
147 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
150 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
151 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
152 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
153 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
155 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
158 * Various remote-bug flags.
160 #define BUG_CHOKES_ON_SSH1_IGNORE 1
161 #define BUG_SSH2_HMAC 2
162 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
163 #define BUG_CHOKES_ON_RSA 8
164 #define BUG_SSH2_RSA_PADDING 16
165 #define BUG_SSH2_DERIVEKEY 32
166 #define BUG_SSH2_REKEY 64
167 #define BUG_SSH2_PK_SESSIONID 128
170 * Codes for terminal modes.
171 * Most of these are the same in SSH-1 and SSH-2.
172 * This list is derived from draft-ietf-secsh-connect-25 and
175 static const struct {
176 const char* const mode
;
178 enum { TTY_OP_CHAR
, TTY_OP_BOOL
} type
;
180 /* "V" prefix discarded for special characters relative to SSH specs */
181 { "INTR", 1, TTY_OP_CHAR
},
182 { "QUIT", 2, TTY_OP_CHAR
},
183 { "ERASE", 3, TTY_OP_CHAR
},
184 { "KILL", 4, TTY_OP_CHAR
},
185 { "EOF", 5, TTY_OP_CHAR
},
186 { "EOL", 6, TTY_OP_CHAR
},
187 { "EOL2", 7, TTY_OP_CHAR
},
188 { "START", 8, TTY_OP_CHAR
},
189 { "STOP", 9, TTY_OP_CHAR
},
190 { "SUSP", 10, TTY_OP_CHAR
},
191 { "DSUSP", 11, TTY_OP_CHAR
},
192 { "REPRINT", 12, TTY_OP_CHAR
},
193 { "WERASE", 13, TTY_OP_CHAR
},
194 { "LNEXT", 14, TTY_OP_CHAR
},
195 { "FLUSH", 15, TTY_OP_CHAR
},
196 { "SWTCH", 16, TTY_OP_CHAR
},
197 { "STATUS", 17, TTY_OP_CHAR
},
198 { "DISCARD", 18, TTY_OP_CHAR
},
199 { "IGNPAR", 30, TTY_OP_BOOL
},
200 { "PARMRK", 31, TTY_OP_BOOL
},
201 { "INPCK", 32, TTY_OP_BOOL
},
202 { "ISTRIP", 33, TTY_OP_BOOL
},
203 { "INLCR", 34, TTY_OP_BOOL
},
204 { "IGNCR", 35, TTY_OP_BOOL
},
205 { "ICRNL", 36, TTY_OP_BOOL
},
206 { "IUCLC", 37, TTY_OP_BOOL
},
207 { "IXON", 38, TTY_OP_BOOL
},
208 { "IXANY", 39, TTY_OP_BOOL
},
209 { "IXOFF", 40, TTY_OP_BOOL
},
210 { "IMAXBEL", 41, TTY_OP_BOOL
},
211 { "ISIG", 50, TTY_OP_BOOL
},
212 { "ICANON", 51, TTY_OP_BOOL
},
213 { "XCASE", 52, TTY_OP_BOOL
},
214 { "ECHO", 53, TTY_OP_BOOL
},
215 { "ECHOE", 54, TTY_OP_BOOL
},
216 { "ECHOK", 55, TTY_OP_BOOL
},
217 { "ECHONL", 56, TTY_OP_BOOL
},
218 { "NOFLSH", 57, TTY_OP_BOOL
},
219 { "TOSTOP", 58, TTY_OP_BOOL
},
220 { "IEXTEN", 59, TTY_OP_BOOL
},
221 { "ECHOCTL", 60, TTY_OP_BOOL
},
222 { "ECHOKE", 61, TTY_OP_BOOL
},
223 { "PENDIN", 62, TTY_OP_BOOL
}, /* XXX is this a real mode? */
224 { "OPOST", 70, TTY_OP_BOOL
},
225 { "OLCUC", 71, TTY_OP_BOOL
},
226 { "ONLCR", 72, TTY_OP_BOOL
},
227 { "OCRNL", 73, TTY_OP_BOOL
},
228 { "ONOCR", 74, TTY_OP_BOOL
},
229 { "ONLRET", 75, TTY_OP_BOOL
},
230 { "CS7", 90, TTY_OP_BOOL
},
231 { "CS8", 91, TTY_OP_BOOL
},
232 { "PARENB", 92, TTY_OP_BOOL
},
233 { "PARODD", 93, TTY_OP_BOOL
}
236 /* Miscellaneous other tty-related constants. */
237 #define SSH_TTY_OP_END 0
238 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
239 #define SSH1_TTY_OP_ISPEED 192
240 #define SSH1_TTY_OP_OSPEED 193
241 #define SSH2_TTY_OP_ISPEED 128
242 #define SSH2_TTY_OP_OSPEED 129
244 /* Helper functions for parsing tty-related config. */
245 static unsigned int ssh_tty_parse_specchar(char *s
)
250 ret
= ctrlparse(s
, &next
);
251 if (!next
) ret
= s
[0];
253 ret
= 255; /* special value meaning "don't set" */
257 static unsigned int ssh_tty_parse_boolean(char *s
)
259 if (stricmp(s
, "yes") == 0 ||
260 stricmp(s
, "on") == 0 ||
261 stricmp(s
, "true") == 0 ||
262 stricmp(s
, "+") == 0)
264 else if (stricmp(s
, "no") == 0 ||
265 stricmp(s
, "off") == 0 ||
266 stricmp(s
, "false") == 0 ||
267 stricmp(s
, "-") == 0)
268 return 0; /* false */
270 return (atoi(s
) != 0);
273 #define translate(x) if (type == x) return #x
274 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
275 static char *ssh1_pkt_type(int type
)
277 translate(SSH1_MSG_DISCONNECT
);
278 translate(SSH1_SMSG_PUBLIC_KEY
);
279 translate(SSH1_CMSG_SESSION_KEY
);
280 translate(SSH1_CMSG_USER
);
281 translate(SSH1_CMSG_AUTH_RSA
);
282 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE
);
283 translate(SSH1_CMSG_AUTH_RSA_RESPONSE
);
284 translate(SSH1_CMSG_AUTH_PASSWORD
);
285 translate(SSH1_CMSG_REQUEST_PTY
);
286 translate(SSH1_CMSG_WINDOW_SIZE
);
287 translate(SSH1_CMSG_EXEC_SHELL
);
288 translate(SSH1_CMSG_EXEC_CMD
);
289 translate(SSH1_SMSG_SUCCESS
);
290 translate(SSH1_SMSG_FAILURE
);
291 translate(SSH1_CMSG_STDIN_DATA
);
292 translate(SSH1_SMSG_STDOUT_DATA
);
293 translate(SSH1_SMSG_STDERR_DATA
);
294 translate(SSH1_CMSG_EOF
);
295 translate(SSH1_SMSG_EXIT_STATUS
);
296 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
);
297 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE
);
298 translate(SSH1_MSG_CHANNEL_DATA
);
299 translate(SSH1_MSG_CHANNEL_CLOSE
);
300 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
);
301 translate(SSH1_SMSG_X11_OPEN
);
302 translate(SSH1_CMSG_PORT_FORWARD_REQUEST
);
303 translate(SSH1_MSG_PORT_OPEN
);
304 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING
);
305 translate(SSH1_SMSG_AGENT_OPEN
);
306 translate(SSH1_MSG_IGNORE
);
307 translate(SSH1_CMSG_EXIT_CONFIRMATION
);
308 translate(SSH1_CMSG_X11_REQUEST_FORWARDING
);
309 translate(SSH1_CMSG_AUTH_RHOSTS_RSA
);
310 translate(SSH1_MSG_DEBUG
);
311 translate(SSH1_CMSG_REQUEST_COMPRESSION
);
312 translate(SSH1_CMSG_AUTH_TIS
);
313 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE
);
314 translate(SSH1_CMSG_AUTH_TIS_RESPONSE
);
315 translate(SSH1_CMSG_AUTH_CCARD
);
316 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE
);
317 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE
);
320 static char *ssh2_pkt_type(int pkt_ctx
, int type
)
322 translate(SSH2_MSG_DISCONNECT
);
323 translate(SSH2_MSG_IGNORE
);
324 translate(SSH2_MSG_UNIMPLEMENTED
);
325 translate(SSH2_MSG_DEBUG
);
326 translate(SSH2_MSG_SERVICE_REQUEST
);
327 translate(SSH2_MSG_SERVICE_ACCEPT
);
328 translate(SSH2_MSG_KEXINIT
);
329 translate(SSH2_MSG_NEWKEYS
);
330 translatec(SSH2_MSG_KEXDH_INIT
, SSH2_PKTCTX_DHGROUP
);
331 translatec(SSH2_MSG_KEXDH_REPLY
, SSH2_PKTCTX_DHGROUP
);
332 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST
, SSH2_PKTCTX_DHGEX
);
333 translatec(SSH2_MSG_KEX_DH_GEX_GROUP
, SSH2_PKTCTX_DHGEX
);
334 translatec(SSH2_MSG_KEX_DH_GEX_INIT
, SSH2_PKTCTX_DHGEX
);
335 translatec(SSH2_MSG_KEX_DH_GEX_REPLY
, SSH2_PKTCTX_DHGEX
);
336 translate(SSH2_MSG_USERAUTH_REQUEST
);
337 translate(SSH2_MSG_USERAUTH_FAILURE
);
338 translate(SSH2_MSG_USERAUTH_SUCCESS
);
339 translate(SSH2_MSG_USERAUTH_BANNER
);
340 translatec(SSH2_MSG_USERAUTH_PK_OK
, SSH2_PKTCTX_PUBLICKEY
);
341 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
, SSH2_PKTCTX_PASSWORD
);
342 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST
, SSH2_PKTCTX_KBDINTER
);
343 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE
, SSH2_PKTCTX_KBDINTER
);
344 translate(SSH2_MSG_GLOBAL_REQUEST
);
345 translate(SSH2_MSG_REQUEST_SUCCESS
);
346 translate(SSH2_MSG_REQUEST_FAILURE
);
347 translate(SSH2_MSG_CHANNEL_OPEN
);
348 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
349 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
350 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
351 translate(SSH2_MSG_CHANNEL_DATA
);
352 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA
);
353 translate(SSH2_MSG_CHANNEL_EOF
);
354 translate(SSH2_MSG_CHANNEL_CLOSE
);
355 translate(SSH2_MSG_CHANNEL_REQUEST
);
356 translate(SSH2_MSG_CHANNEL_SUCCESS
);
357 translate(SSH2_MSG_CHANNEL_FAILURE
);
363 /* Enumeration values for fields in SSH-1 packets */
365 PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
,
366 /* These values are for communicating relevant semantics of
367 * fields to the packet logging code. */
368 PKTT_OTHER
, PKTT_PASSWORD
, PKTT_DATA
372 * Coroutine mechanics for the sillier bits of the code. If these
373 * macros look impenetrable to you, you might find it helpful to
376 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
378 * which explains the theory behind these macros.
380 * In particular, if you are getting `case expression not constant'
381 * errors when building with MS Visual Studio, this is because MS's
382 * Edit and Continue debugging feature causes their compiler to
383 * violate ANSI C. To disable Edit and Continue debugging:
385 * - right-click ssh.c in the FileView
387 * - select the C/C++ tab and the General category
388 * - under `Debug info:', select anything _other_ than `Program
389 * Database for Edit and Continue'.
391 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
394 if (!ssh->t) ssh->t = snew(struct t); \
396 #define crFinish(z) } *crLine = 0; return (z); }
397 #define crFinishV } *crLine = 0; return; }
398 #define crReturn(z) \
400 *crLine =__LINE__; return (z); case __LINE__:;\
404 *crLine=__LINE__; return; case __LINE__:;\
406 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
407 #define crStopV do{ *crLine = 0; return; }while(0)
408 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
409 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
411 typedef struct ssh_tag
*Ssh
;
414 static struct Packet
*ssh1_pkt_init(int pkt_type
);
415 static struct Packet
*ssh2_pkt_init(int pkt_type
);
416 static void ssh_pkt_ensure(struct Packet
*, int length
);
417 static void ssh_pkt_adddata(struct Packet
*, void *data
, int len
);
418 static void ssh_pkt_addbyte(struct Packet
*, unsigned char value
);
419 static void ssh2_pkt_addbool(struct Packet
*, unsigned char value
);
420 static void ssh_pkt_adduint32(struct Packet
*, unsigned long value
);
421 static void ssh_pkt_addstring_start(struct Packet
*);
422 static void ssh_pkt_addstring_str(struct Packet
*, char *data
);
423 static void ssh_pkt_addstring_data(struct Packet
*, char *data
, int len
);
424 static void ssh_pkt_addstring(struct Packet
*, char *data
);
425 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
);
426 static void ssh1_pkt_addmp(struct Packet
*, Bignum b
);
427 static void ssh2_pkt_addmp(struct Packet
*, Bignum b
);
428 static int ssh2_pkt_construct(Ssh
, struct Packet
*);
429 static void ssh2_pkt_send(Ssh
, struct Packet
*);
430 static void ssh2_pkt_send_noqueue(Ssh
, struct Packet
*);
431 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
,
432 struct Packet
*pktin
);
433 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
,
434 struct Packet
*pktin
);
437 * Buffer management constants. There are several of these for
438 * various different purposes:
440 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
441 * on a local data stream before we throttle the whole SSH
442 * connection (in SSH-1 only). Throttling the whole connection is
443 * pretty drastic so we set this high in the hope it won't
446 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
447 * on the SSH connection itself before we defensively throttle
448 * _all_ local data streams. This is pretty drastic too (though
449 * thankfully unlikely in SSH-2 since the window mechanism should
450 * ensure that the server never has any need to throttle its end
451 * of the connection), so we set this high as well.
453 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
457 #define SSH1_BUFFER_LIMIT 32768
458 #define SSH_MAX_BACKLOG 32768
459 #define OUR_V2_WINSIZE 16384
460 #define OUR_V2_MAXPKT 0x4000UL
462 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
464 const static struct ssh_mac
*macs
[] = {
465 &ssh_hmac_sha1
, &ssh_hmac_md5
467 const static struct ssh_mac
*buggymacs
[] = {
468 &ssh_hmac_sha1_buggy
, &ssh_hmac_md5
471 static void *ssh_comp_none_init(void)
475 static void ssh_comp_none_cleanup(void *handle
)
478 static int ssh_comp_none_block(void *handle
, unsigned char *block
, int len
,
479 unsigned char **outblock
, int *outlen
)
483 static int ssh_comp_none_disable(void *handle
)
487 const static struct ssh_compress ssh_comp_none
= {
489 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
490 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
491 ssh_comp_none_disable
, NULL
493 extern const struct ssh_compress ssh_zlib
;
494 const static struct ssh_compress
*compressions
[] = {
495 &ssh_zlib
, &ssh_comp_none
498 enum { /* channel types */
503 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
507 * 2-3-4 tree storing channels.
510 Ssh ssh
; /* pointer back to main context */
511 unsigned remoteid
, localid
;
513 /* True if we opened this channel but server hasn't confirmed. */
516 * In SSH-1, this value contains four bits:
518 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
519 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
520 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
521 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
523 * A channel is completely finished with when all four bits are set.
527 struct ssh1_data_channel
{
530 struct ssh2_data_channel
{
532 unsigned remwindow
, remmaxpkt
;
537 struct ssh_agent_channel
{
538 unsigned char *message
;
539 unsigned char msglen
[4];
540 unsigned lensofar
, totallen
;
542 struct ssh_x11_channel
{
545 struct ssh_pfd_channel
{
552 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
553 * use this structure in different ways, reflecting SSH-2's
554 * altogether saner approach to port forwarding.
556 * In SSH-1, you arrange a remote forwarding by sending the server
557 * the remote port number, and the local destination host:port.
558 * When a connection comes in, the server sends you back that
559 * host:port pair, and you connect to it. This is a ready-made
560 * security hole if you're not on the ball: a malicious server
561 * could send you back _any_ host:port pair, so if you trustingly
562 * connect to the address it gives you then you've just opened the
563 * entire inside of your corporate network just by connecting
564 * through it to a dodgy SSH server. Hence, we must store a list of
565 * host:port pairs we _are_ trying to forward to, and reject a
566 * connection request from the server if it's not in the list.
568 * In SSH-2, each side of the connection minds its own business and
569 * doesn't send unnecessary information to the other. You arrange a
570 * remote forwarding by sending the server just the remote port
571 * number. When a connection comes in, the server tells you which
572 * of its ports was connected to; and _you_ have to remember what
573 * local host:port pair went with that port number.
575 * Hence, in SSH-1 this structure is indexed by destination
576 * host:port pair, whereas in SSH-2 it is indexed by source port.
578 struct ssh_portfwd
; /* forward declaration */
580 struct ssh_rportfwd
{
581 unsigned sport
, dport
;
584 struct ssh_portfwd
*pfrec
;
586 #define free_rportfwd(pf) ( \
587 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
590 * Separately to the rportfwd tree (which is for looking up port
591 * open requests from the server), a tree of _these_ structures is
592 * used to keep track of all the currently open port forwardings,
593 * so that we can reconfigure in mid-session if the user requests
597 enum { DESTROY
, KEEP
, CREATE
} status
;
599 unsigned sport
, dport
;
602 struct ssh_rportfwd
*remote
;
606 #define free_portfwd(pf) ( \
607 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
608 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
611 long length
; /* length of `data' actually used */
612 long forcepad
; /* SSH-2: force padding to at least this length */
613 int type
; /* only used for incoming packets */
614 unsigned long sequence
; /* SSH-2 incoming sequence number */
615 unsigned char *data
; /* allocated storage */
616 unsigned char *body
; /* offset of payload within `data' */
617 long savedpos
; /* temporary index into `data' (for strings) */
618 long maxlen
; /* amount of storage allocated for `data' */
619 long encrypted_len
; /* for SSH-2 total-size counting */
622 * State associated with packet logging
626 struct logblank_t
*blanks
;
629 static void ssh1_protocol(Ssh ssh
, void *vin
, int inlen
,
630 struct Packet
*pktin
);
631 static void ssh2_protocol(Ssh ssh
, void *vin
, int inlen
,
632 struct Packet
*pktin
);
633 static void ssh1_protocol_setup(Ssh ssh
);
634 static void ssh2_protocol_setup(Ssh ssh
);
635 static void ssh_size(void *handle
, int width
, int height
);
636 static void ssh_special(void *handle
, Telnet_Special
);
637 static int ssh2_try_send(struct ssh_channel
*c
);
638 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
);
639 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
);
640 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
);
641 static int ssh_sendbuffer(void *handle
);
642 static int ssh_do_close(Ssh ssh
, int notify_exit
);
643 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
);
644 static int ssh2_pkt_getbool(struct Packet
*pkt
);
645 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
);
646 static void ssh2_timer(void *ctx
, long now
);
647 static int do_ssh2_transport(Ssh ssh
, void *vin
, int inlen
,
648 struct Packet
*pktin
);
650 struct rdpkt1_state_tag
{
651 long len
, pad
, biglen
, to_read
;
652 unsigned long realcrc
, gotcrc
;
656 struct Packet
*pktin
;
659 struct rdpkt2_state_tag
{
660 long len
, pad
, payload
, packetlen
, maclen
;
663 unsigned long incoming_sequence
;
664 struct Packet
*pktin
;
667 typedef void (*handler_fn_t
)(Ssh ssh
, struct Packet
*pktin
);
668 typedef void (*chandler_fn_t
)(Ssh ssh
, struct Packet
*pktin
, void *ctx
);
670 struct queued_handler
;
671 struct queued_handler
{
673 chandler_fn_t handler
;
675 struct queued_handler
*next
;
679 const struct plug_function_table
*fn
;
680 /* the above field _must_ be first in the structure */
690 unsigned char session_key
[32];
692 int v1_remote_protoflags
;
693 int v1_local_protoflags
;
694 int agentfwd_enabled
;
697 const struct ssh_cipher
*cipher
;
700 const struct ssh2_cipher
*cscipher
, *sccipher
;
701 void *cs_cipher_ctx
, *sc_cipher_ctx
;
702 const struct ssh_mac
*csmac
, *scmac
;
703 void *cs_mac_ctx
, *sc_mac_ctx
;
704 const struct ssh_compress
*cscomp
, *sccomp
;
705 void *cs_comp_ctx
, *sc_comp_ctx
;
706 const struct ssh_kex
*kex
;
707 const struct ssh_signkey
*hostkey
;
708 unsigned char v2_session_id
[20];
709 int v2_session_id_len
;
715 int echoing
, editing
;
719 int ospeed
, ispeed
; /* temporaries */
720 int term_width
, term_height
;
722 tree234
*channels
; /* indexed by local id */
723 struct ssh_channel
*mainchan
; /* primary session channel */
728 tree234
*rportfwds
, *portfwds
;
732 SSH_STATE_BEFORE_SIZE
,
738 int size_needed
, eof_needed
;
740 struct Packet
**queue
;
741 int queuelen
, queuesize
;
743 unsigned char *deferred_send_data
;
744 int deferred_len
, deferred_size
;
747 * Gross hack: pscp will try to start SFTP but fall back to
748 * scp1 if that fails. This variable is the means by which
749 * scp.c can reach into the SSH code and find out which one it
754 bufchain banner
; /* accumulates banners during do_ssh2_authconn */
756 * Used for username and password input.
758 char *userpass_input_buffer
;
759 int userpass_input_buflen
;
760 int userpass_input_bufpos
;
761 int userpass_input_echo
;
768 int v1_throttle_count
;
771 int v1_stdout_throttling
;
772 unsigned long v2_outgoing_sequence
;
774 int ssh1_rdpkt_crstate
;
775 int ssh2_rdpkt_crstate
;
776 int do_ssh_init_crstate
;
777 int ssh_gotdata_crstate
;
778 int do_ssh1_login_crstate
;
779 int do_ssh1_connection_crstate
;
780 int do_ssh2_transport_crstate
;
781 int do_ssh2_authconn_crstate
;
783 void *do_ssh_init_state
;
784 void *do_ssh1_login_state
;
785 void *do_ssh2_transport_state
;
786 void *do_ssh2_authconn_state
;
788 struct rdpkt1_state_tag rdpkt1_state
;
789 struct rdpkt2_state_tag rdpkt2_state
;
791 /* SSH-1 and SSH-2 use this for different things, but both use it */
792 int protocol_initial_phase_done
;
794 void (*protocol
) (Ssh ssh
, void *vin
, int inlen
,
796 struct Packet
*(*s_rdpkt
) (Ssh ssh
, unsigned char **data
, int *datalen
);
799 * We maintain a full _copy_ of a Config structure here, not
800 * merely a pointer to it. That way, when we're passed a new
801 * one for reconfiguration, we can check the differences and
802 * potentially reconfigure port forwardings etc in mid-session.
807 * Used to transfer data back from async callbacks.
809 void *agent_response
;
810 int agent_response_len
;
814 * The SSH connection can be set as `frozen', meaning we are
815 * not currently accepting incoming data from the network. This
816 * is slightly more serious than setting the _socket_ as
817 * frozen, because we may already have had data passed to us
818 * from the network which we need to delay processing until
819 * after the freeze is lifted, so we also need a bufchain to
823 bufchain queued_incoming_data
;
826 * Dispatch table for packet types that we may have to deal
829 handler_fn_t packet_dispatch
[256];
832 * Queues of one-off handler functions for success/failure
833 * indications from a request.
835 struct queued_handler
*qhead
, *qtail
;
838 * This module deals with sending keepalives.
843 * Track incoming and outgoing data sizes and time, for
846 unsigned long incoming_data_size
, outgoing_data_size
, deferred_data_size
;
847 unsigned long max_data_size
;
849 long next_rekey
, last_rekey
;
850 char *deferred_rekey_reason
; /* points to STATIC string; don't free */
853 #define logevent(s) logevent(ssh->frontend, s)
855 /* logevent, only printf-formatted. */
856 static void logeventf(Ssh ssh
, const char *fmt
, ...)
862 buf
= dupvprintf(fmt
, ap
);
868 #define bombout(msg) \
870 char *text = dupprintf msg; \
871 ssh_do_close(ssh, FALSE); \
873 connection_fatal(ssh->frontend, "%s", text); \
877 /* Functions to leave bits out of the SSH packet log file. */
879 static void dont_log_password(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
881 if (ssh
->cfg
.logomitpass
)
882 pkt
->logmode
= blanktype
;
885 static void dont_log_data(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
887 if (ssh
->cfg
.logomitdata
)
888 pkt
->logmode
= blanktype
;
891 static void end_log_omission(Ssh ssh
, struct Packet
*pkt
)
893 pkt
->logmode
= PKTLOG_EMIT
;
896 /* Helper function for common bits of parsing cfg.ttymodes. */
897 static void parse_ttymodes(Ssh ssh
, char *modes
,
898 void (*do_mode
)(void *data
, char *mode
, char *val
),
902 char *t
= strchr(modes
, '\t');
903 char *m
= snewn(t
-modes
+1, char);
905 strncpy(m
, modes
, t
-modes
);
908 val
= get_ttymode(ssh
->frontend
, m
);
912 do_mode(data
, m
, val
);
915 modes
+= strlen(modes
) + 1;
919 static int ssh_channelcmp(void *av
, void *bv
)
921 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
922 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
923 if (a
->localid
< b
->localid
)
925 if (a
->localid
> b
->localid
)
929 static int ssh_channelfind(void *av
, void *bv
)
931 unsigned *a
= (unsigned *) av
;
932 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
940 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
942 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
943 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
945 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
946 return i
< 0 ?
-1 : +1;
947 if (a
->dport
> b
->dport
)
949 if (a
->dport
< b
->dport
)
954 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
956 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
957 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
959 if (a
->sport
> b
->sport
)
961 if (a
->sport
< b
->sport
)
967 * Special form of strcmp which can cope with NULL inputs. NULL is
968 * defined to sort before even the empty string.
970 static int nullstrcmp(const char *a
, const char *b
)
972 if (a
== NULL
&& b
== NULL
)
981 static int ssh_portcmp(void *av
, void *bv
)
983 struct ssh_portfwd
*a
= (struct ssh_portfwd
*) av
;
984 struct ssh_portfwd
*b
= (struct ssh_portfwd
*) bv
;
986 if (a
->type
> b
->type
)
988 if (a
->type
< b
->type
)
990 if (a
->addressfamily
> b
->addressfamily
)
992 if (a
->addressfamily
< b
->addressfamily
)
994 if ( (i
= nullstrcmp(a
->saddr
, b
->saddr
)) != 0)
995 return i
< 0 ?
-1 : +1;
996 if (a
->sport
> b
->sport
)
998 if (a
->sport
< b
->sport
)
1000 if (a
->type
!= 'D') {
1001 if ( (i
= nullstrcmp(a
->daddr
, b
->daddr
)) != 0)
1002 return i
< 0 ?
-1 : +1;
1003 if (a
->dport
> b
->dport
)
1005 if (a
->dport
< b
->dport
)
1011 static int alloc_channel_id(Ssh ssh
)
1013 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
1014 unsigned low
, high
, mid
;
1016 struct ssh_channel
*c
;
1019 * First-fit allocation of channel numbers: always pick the
1020 * lowest unused one. To do this, binary-search using the
1021 * counted B-tree to find the largest channel ID which is in a
1022 * contiguous sequence from the beginning. (Precisely
1023 * everything in that sequence must have ID equal to its tree
1024 * index plus CHANNEL_NUMBER_OFFSET.)
1026 tsize
= count234(ssh
->channels
);
1030 while (high
- low
> 1) {
1031 mid
= (high
+ low
) / 2;
1032 c
= index234(ssh
->channels
, mid
);
1033 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
1034 low
= mid
; /* this one is fine */
1036 high
= mid
; /* this one is past it */
1039 * Now low points to either -1, or the tree index of the
1040 * largest ID in the initial sequence.
1043 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
1044 assert(NULL
== find234(ssh
->channels
, &i
, ssh_channelfind
));
1046 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
1049 static void c_write(Ssh ssh
, const char *buf
, int len
)
1051 if ((flags
& FLAG_STDERR
)) {
1053 for (i
= 0; i
< len
; i
++)
1055 fputc(buf
[i
], stderr
);
1058 from_backend(ssh
->frontend
, 1, buf
, len
);
1061 static void c_write_untrusted(Ssh ssh
, const char *buf
, int len
)
1064 for (i
= 0; i
< len
; i
++) {
1066 c_write(ssh
, "\r\n", 2);
1067 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
1068 c_write(ssh
, buf
+ i
, 1);
1072 static void c_write_str(Ssh ssh
, const char *buf
)
1074 c_write(ssh
, buf
, strlen(buf
));
1077 static void ssh_free_packet(struct Packet
*pkt
)
1082 static struct Packet
*ssh_new_packet(void)
1084 struct Packet
*pkt
= snew(struct Packet
);
1086 pkt
->body
= pkt
->data
= NULL
;
1088 pkt
->logmode
= PKTLOG_EMIT
;
1096 * Collect incoming data in the incoming packet buffer.
1097 * Decipher and verify the packet when it is completely read.
1098 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1099 * Update the *data and *datalen variables.
1100 * Return a Packet structure when a packet is completed.
1102 static struct Packet
*ssh1_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
1104 struct rdpkt1_state_tag
*st
= &ssh
->rdpkt1_state
;
1106 crBegin(ssh
->ssh1_rdpkt_crstate
);
1108 st
->pktin
= ssh_new_packet();
1110 st
->pktin
->type
= 0;
1111 st
->pktin
->length
= 0;
1113 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
1114 while ((*datalen
) == 0)
1116 st
->len
= (st
->len
<< 8) + **data
;
1117 (*data
)++, (*datalen
)--;
1120 st
->pad
= 8 - (st
->len
% 8);
1121 st
->biglen
= st
->len
+ st
->pad
;
1122 st
->pktin
->length
= st
->len
- 5;
1124 if (st
->biglen
< 0) {
1125 bombout(("Extremely large packet length from server suggests"
1126 " data stream corruption"));
1127 ssh_free_packet(st
->pktin
);
1131 st
->pktin
->maxlen
= st
->biglen
;
1132 st
->pktin
->data
= snewn(st
->biglen
+ APIEXTRA
, unsigned char);
1134 st
->to_read
= st
->biglen
;
1135 st
->p
= st
->pktin
->data
;
1136 while (st
->to_read
> 0) {
1137 st
->chunk
= st
->to_read
;
1138 while ((*datalen
) == 0)
1140 if (st
->chunk
> (*datalen
))
1141 st
->chunk
= (*datalen
);
1142 memcpy(st
->p
, *data
, st
->chunk
);
1144 *datalen
-= st
->chunk
;
1146 st
->to_read
-= st
->chunk
;
1149 if (ssh
->cipher
&& detect_attack(ssh
->crcda_ctx
, st
->pktin
->data
,
1150 st
->biglen
, NULL
)) {
1151 bombout(("Network attack (CRC compensation) detected!"));
1152 ssh_free_packet(st
->pktin
);
1157 ssh
->cipher
->decrypt(ssh
->v1_cipher_ctx
, st
->pktin
->data
, st
->biglen
);
1159 st
->realcrc
= crc32_compute(st
->pktin
->data
, st
->biglen
- 4);
1160 st
->gotcrc
= GET_32BIT(st
->pktin
->data
+ st
->biglen
- 4);
1161 if (st
->gotcrc
!= st
->realcrc
) {
1162 bombout(("Incorrect CRC received on packet"));
1163 ssh_free_packet(st
->pktin
);
1167 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
1168 st
->pktin
->savedpos
= 0;
1170 if (ssh
->v1_compressing
) {
1171 unsigned char *decompblk
;
1173 if (!zlib_decompress_block(ssh
->sc_comp_ctx
,
1174 st
->pktin
->body
- 1, st
->pktin
->length
+ 1,
1175 &decompblk
, &decomplen
)) {
1176 bombout(("Zlib decompression encountered invalid data"));
1177 ssh_free_packet(st
->pktin
);
1181 if (st
->pktin
->maxlen
< st
->pad
+ decomplen
) {
1182 st
->pktin
->maxlen
= st
->pad
+ decomplen
;
1183 st
->pktin
->data
= sresize(st
->pktin
->data
,
1184 st
->pktin
->maxlen
+ APIEXTRA
,
1186 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
1189 memcpy(st
->pktin
->body
- 1, decompblk
, decomplen
);
1191 st
->pktin
->length
= decomplen
- 1;
1194 st
->pktin
->type
= st
->pktin
->body
[-1];
1197 * Log incoming packet, possibly omitting sensitive fields.
1201 struct logblank_t blank
;
1202 if (ssh
->cfg
.logomitdata
) {
1203 int do_blank
= FALSE
, blank_prefix
= 0;
1204 /* "Session data" packets - omit the data field */
1205 if ((st
->pktin
->type
== SSH1_SMSG_STDOUT_DATA
) ||
1206 (st
->pktin
->type
== SSH1_SMSG_STDERR_DATA
)) {
1207 do_blank
= TRUE
; blank_prefix
= 0;
1208 } else if (st
->pktin
->type
== SSH1_MSG_CHANNEL_DATA
) {
1209 do_blank
= TRUE
; blank_prefix
= 4;
1212 blank
.offset
= blank_prefix
;
1213 blank
.len
= st
->pktin
->length
;
1214 blank
.type
= PKTLOG_OMIT
;
1218 log_packet(ssh
->logctx
,
1219 PKT_INCOMING
, st
->pktin
->type
,
1220 ssh1_pkt_type(st
->pktin
->type
),
1221 st
->pktin
->body
, st
->pktin
->length
,
1225 crFinish(st
->pktin
);
1228 static struct Packet
*ssh2_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
1230 struct rdpkt2_state_tag
*st
= &ssh
->rdpkt2_state
;
1232 crBegin(ssh
->ssh2_rdpkt_crstate
);
1234 st
->pktin
= ssh_new_packet();
1236 st
->pktin
->type
= 0;
1237 st
->pktin
->length
= 0;
1239 st
->cipherblk
= ssh
->sccipher
->blksize
;
1242 if (st
->cipherblk
< 8)
1245 st
->pktin
->data
= snewn(st
->cipherblk
+ APIEXTRA
, unsigned char);
1248 * Acquire and decrypt the first block of the packet. This will
1249 * contain the length and padding details.
1251 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
1252 while ((*datalen
) == 0)
1254 st
->pktin
->data
[st
->i
] = *(*data
)++;
1259 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1260 st
->pktin
->data
, st
->cipherblk
);
1263 * Now get the length and padding figures.
1265 st
->len
= GET_32BIT(st
->pktin
->data
);
1266 st
->pad
= st
->pktin
->data
[4];
1269 * _Completely_ silly lengths should be stomped on before they
1270 * do us any more damage.
1272 if (st
->len
< 0 || st
->len
> 35000 || st
->pad
< 4 ||
1273 st
->len
- st
->pad
< 1 || (st
->len
+ 4) % st
->cipherblk
!= 0) {
1274 bombout(("Incoming packet was garbled on decryption"));
1275 ssh_free_packet(st
->pktin
);
1280 * This enables us to deduce the payload length.
1282 st
->payload
= st
->len
- st
->pad
- 1;
1284 st
->pktin
->length
= st
->payload
+ 5;
1287 * So now we can work out the total packet length.
1289 st
->packetlen
= st
->len
+ 4;
1290 st
->maclen
= ssh
->scmac ? ssh
->scmac
->len
: 0;
1293 * Allocate memory for the rest of the packet.
1295 st
->pktin
->maxlen
= st
->packetlen
+ st
->maclen
;
1296 st
->pktin
->data
= sresize(st
->pktin
->data
,
1297 st
->pktin
->maxlen
+ APIEXTRA
,
1301 * Read and decrypt the remainder of the packet.
1303 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
1305 while ((*datalen
) == 0)
1307 st
->pktin
->data
[st
->i
] = *(*data
)++;
1310 /* Decrypt everything _except_ the MAC. */
1312 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1313 st
->pktin
->data
+ st
->cipherblk
,
1314 st
->packetlen
- st
->cipherblk
);
1316 st
->pktin
->encrypted_len
= st
->packetlen
;
1322 && !ssh
->scmac
->verify(ssh
->sc_mac_ctx
, st
->pktin
->data
, st
->len
+ 4,
1323 st
->incoming_sequence
)) {
1324 bombout(("Incorrect MAC received on packet"));
1325 ssh_free_packet(st
->pktin
);
1329 st
->pktin
->sequence
= st
->incoming_sequence
++;
1332 * Decompress packet payload.
1335 unsigned char *newpayload
;
1338 ssh
->sccomp
->decompress(ssh
->sc_comp_ctx
,
1339 st
->pktin
->data
+ 5, st
->pktin
->length
- 5,
1340 &newpayload
, &newlen
)) {
1341 if (st
->pktin
->maxlen
< newlen
+ 5) {
1342 st
->pktin
->maxlen
= newlen
+ 5;
1343 st
->pktin
->data
= sresize(st
->pktin
->data
,
1344 st
->pktin
->maxlen
+ APIEXTRA
,
1347 st
->pktin
->length
= 5 + newlen
;
1348 memcpy(st
->pktin
->data
+ 5, newpayload
, newlen
);
1353 st
->pktin
->savedpos
= 6;
1354 st
->pktin
->body
= st
->pktin
->data
;
1355 st
->pktin
->type
= st
->pktin
->data
[5];
1358 * Log incoming packet, possibly omitting sensitive fields.
1362 struct logblank_t blank
;
1363 if (ssh
->cfg
.logomitdata
) {
1364 int do_blank
= FALSE
, blank_prefix
= 0;
1365 /* "Session data" packets - omit the data field */
1366 if (st
->pktin
->type
== SSH2_MSG_CHANNEL_DATA
) {
1367 do_blank
= TRUE
; blank_prefix
= 4;
1368 } else if (st
->pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
1369 do_blank
= TRUE
; blank_prefix
= 8;
1372 blank
.offset
= blank_prefix
;
1373 blank
.len
= (st
->pktin
->length
-6) - blank_prefix
;
1374 blank
.type
= PKTLOG_OMIT
;
1378 log_packet(ssh
->logctx
, PKT_INCOMING
, st
->pktin
->type
,
1379 ssh2_pkt_type(ssh
->pkt_ctx
, st
->pktin
->type
),
1380 st
->pktin
->data
+6, st
->pktin
->length
-6,
1384 crFinish(st
->pktin
);
1387 static int s_wrpkt_prepare(Ssh ssh
, struct Packet
*pkt
, int *offset_p
)
1389 int pad
, biglen
, i
, pktoffs
;
1393 * XXX various versions of SC (including 8.8.4) screw up the
1394 * register allocation in this function and use the same register
1395 * (D6) for len and as a temporary, with predictable results. The
1396 * following sledgehammer prevents this.
1403 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->data
[12],
1404 ssh1_pkt_type(pkt
->data
[12]),
1405 pkt
->body
, pkt
->length
- (pkt
->body
- pkt
->data
),
1406 pkt
->nblanks
, pkt
->blanks
);
1407 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1410 if (ssh
->v1_compressing
) {
1411 unsigned char *compblk
;
1413 zlib_compress_block(ssh
->cs_comp_ctx
,
1414 pkt
->data
+ 12, pkt
->length
- 12,
1415 &compblk
, &complen
);
1416 memcpy(pkt
->data
+ 12, compblk
, complen
);
1418 pkt
->length
= complen
+ 12;
1421 ssh_pkt_ensure(pkt
, pkt
->length
+ 4); /* space for CRC */
1423 len
= pkt
->length
- 4 - 8; /* len(type+data+CRC) */
1424 pad
= 8 - (len
% 8);
1426 biglen
= len
+ pad
; /* len(padding+type+data+CRC) */
1428 for (i
= pktoffs
; i
< 4+8; i
++)
1429 pkt
->data
[i
] = random_byte();
1430 crc
= crc32_compute(pkt
->data
+ pktoffs
+ 4, biglen
- 4); /* all ex len */
1431 PUT_32BIT(pkt
->data
+ pktoffs
+ 4 + biglen
- 4, crc
);
1432 PUT_32BIT(pkt
->data
+ pktoffs
, len
);
1435 ssh
->cipher
->encrypt(ssh
->v1_cipher_ctx
,
1436 pkt
->data
+ pktoffs
+ 4, biglen
);
1438 if (offset_p
) *offset_p
= pktoffs
;
1439 return biglen
+ 4; /* len(length+padding+type+data+CRC) */
1442 static void s_wrpkt(Ssh ssh
, struct Packet
*pkt
)
1444 int len
, backlog
, offset
;
1445 len
= s_wrpkt_prepare(ssh
, pkt
, &offset
);
1446 backlog
= sk_write(ssh
->s
, (char *)pkt
->data
+ offset
, len
);
1447 if (backlog
> SSH_MAX_BACKLOG
)
1448 ssh_throttle_all(ssh
, 1, backlog
);
1449 ssh_free_packet(pkt
);
1452 static void s_wrpkt_defer(Ssh ssh
, struct Packet
*pkt
)
1455 len
= s_wrpkt_prepare(ssh
, pkt
, &offset
);
1456 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1457 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1458 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
1462 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
,
1463 pkt
->data
+ offset
, len
);
1464 ssh
->deferred_len
+= len
;
1465 ssh_free_packet(pkt
);
1469 * Construct a SSH-1 packet with the specified contents.
1470 * (This all-at-once interface used to be the only one, but now SSH-1
1471 * packets can also be constructed incrementally.)
1473 static struct Packet
*construct_packet(Ssh ssh
, int pkttype
, va_list ap
)
1479 pkt
= ssh1_pkt_init(pkttype
);
1481 while ((argtype
= va_arg(ap
, int)) != PKT_END
) {
1482 unsigned char *argp
, argchar
;
1483 unsigned long argint
;
1486 /* Actual fields in the packet */
1488 argint
= va_arg(ap
, int);
1489 ssh_pkt_adduint32(pkt
, argint
);
1492 argchar
= (unsigned char) va_arg(ap
, int);
1493 ssh_pkt_addbyte(pkt
, argchar
);
1496 argp
= va_arg(ap
, unsigned char *);
1497 arglen
= va_arg(ap
, int);
1498 ssh_pkt_adddata(pkt
, argp
, arglen
);
1501 argp
= va_arg(ap
, unsigned char *);
1502 ssh_pkt_addstring(pkt
, argp
);
1505 bn
= va_arg(ap
, Bignum
);
1506 ssh1_pkt_addmp(pkt
, bn
);
1508 /* Tokens for modifications to packet logging */
1510 dont_log_password(ssh
, pkt
, PKTLOG_BLANK
);
1513 dont_log_data(ssh
, pkt
, PKTLOG_OMIT
);
1516 end_log_omission(ssh
, pkt
);
1524 static void send_packet(Ssh ssh
, int pkttype
, ...)
1528 va_start(ap
, pkttype
);
1529 pkt
= construct_packet(ssh
, pkttype
, ap
);
1534 static void defer_packet(Ssh ssh
, int pkttype
, ...)
1538 va_start(ap
, pkttype
);
1539 pkt
= construct_packet(ssh
, pkttype
, ap
);
1541 s_wrpkt_defer(ssh
, pkt
);
1544 static int ssh_versioncmp(char *a
, char *b
)
1547 unsigned long av
, bv
;
1549 av
= strtoul(a
, &ae
, 10);
1550 bv
= strtoul(b
, &be
, 10);
1552 return (av
< bv ?
-1 : +1);
1557 av
= strtoul(ae
, &ae
, 10);
1558 bv
= strtoul(be
, &be
, 10);
1560 return (av
< bv ?
-1 : +1);
1565 * Utility routines for putting an SSH-protocol `string' and
1566 * `uint32' into a hash state.
1568 static void hash_string(const struct ssh_hash
*h
, void *s
, void *str
, int len
)
1570 unsigned char lenblk
[4];
1571 PUT_32BIT(lenblk
, len
);
1572 h
->bytes(s
, lenblk
, 4);
1573 h
->bytes(s
, str
, len
);
1576 static void hash_uint32(const struct ssh_hash
*h
, void *s
, unsigned i
)
1578 unsigned char intblk
[4];
1579 PUT_32BIT(intblk
, i
);
1580 h
->bytes(s
, intblk
, 4);
1584 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1586 static void ssh_pkt_ensure(struct Packet
*pkt
, int length
)
1588 if (pkt
->maxlen
< length
) {
1589 unsigned char *body
= pkt
->body
;
1590 int offset
= body ? pkt
->data
- body
: 0;
1591 pkt
->maxlen
= length
+ 256;
1592 pkt
->data
= sresize(pkt
->data
, pkt
->maxlen
+ APIEXTRA
, unsigned char);
1593 if (body
) pkt
->body
= pkt
->data
+ offset
;
1596 static void ssh_pkt_adddata(struct Packet
*pkt
, void *data
, int len
)
1598 if (pkt
->logmode
!= PKTLOG_EMIT
) {
1600 pkt
->blanks
= sresize(pkt
->blanks
, pkt
->nblanks
, struct logblank_t
);
1602 pkt
->blanks
[pkt
->nblanks
-1].offset
= pkt
->length
-
1603 (pkt
->body
- pkt
->data
);
1604 pkt
->blanks
[pkt
->nblanks
-1].len
= len
;
1605 pkt
->blanks
[pkt
->nblanks
-1].type
= pkt
->logmode
;
1608 ssh_pkt_ensure(pkt
, pkt
->length
);
1609 memcpy(pkt
->data
+ pkt
->length
- len
, data
, len
);
1611 static void ssh_pkt_addbyte(struct Packet
*pkt
, unsigned char byte
)
1613 ssh_pkt_adddata(pkt
, &byte
, 1);
1615 static void ssh2_pkt_addbool(struct Packet
*pkt
, unsigned char value
)
1617 ssh_pkt_adddata(pkt
, &value
, 1);
1619 static void ssh_pkt_adduint32(struct Packet
*pkt
, unsigned long value
)
1622 PUT_32BIT(x
, value
);
1623 ssh_pkt_adddata(pkt
, x
, 4);
1625 static void ssh_pkt_addstring_start(struct Packet
*pkt
)
1627 ssh_pkt_adduint32(pkt
, 0);
1628 pkt
->savedpos
= pkt
->length
;
1630 static void ssh_pkt_addstring_str(struct Packet
*pkt
, char *data
)
1632 ssh_pkt_adddata(pkt
, data
, strlen(data
));
1633 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1635 static void ssh_pkt_addstring_data(struct Packet
*pkt
, char *data
, int len
)
1637 ssh_pkt_adddata(pkt
, data
, len
);
1638 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1640 static void ssh_pkt_addstring(struct Packet
*pkt
, char *data
)
1642 ssh_pkt_addstring_start(pkt
);
1643 ssh_pkt_addstring_str(pkt
, data
);
1645 static void ssh1_pkt_addmp(struct Packet
*pkt
, Bignum b
)
1647 int len
= ssh1_bignum_length(b
);
1648 unsigned char *data
= snewn(len
, char);
1649 (void) ssh1_write_bignum(data
, b
);
1650 ssh_pkt_adddata(pkt
, data
, len
);
1653 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
)
1656 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1657 p
= snewn(n
+ 1, unsigned char);
1659 for (i
= 1; i
<= n
; i
++)
1660 p
[i
] = bignum_byte(b
, n
- i
);
1662 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1664 memmove(p
, p
+ i
, n
+ 1 - i
);
1668 static void ssh2_pkt_addmp(struct Packet
*pkt
, Bignum b
)
1672 p
= ssh2_mpint_fmt(b
, &len
);
1673 ssh_pkt_addstring_start(pkt
);
1674 ssh_pkt_addstring_data(pkt
, (char *)p
, len
);
1678 static struct Packet
*ssh1_pkt_init(int pkt_type
)
1680 struct Packet
*pkt
= ssh_new_packet();
1681 pkt
->length
= 4 + 8; /* space for length + max padding */
1682 ssh_pkt_addbyte(pkt
, pkt_type
);
1683 pkt
->body
= pkt
->data
+ pkt
->length
;
1687 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1688 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1689 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1690 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1691 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1692 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1693 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1694 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1695 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1697 static struct Packet
*ssh2_pkt_init(int pkt_type
)
1699 struct Packet
*pkt
= ssh_new_packet();
1702 ssh_pkt_addbyte(pkt
, (unsigned char) pkt_type
);
1703 pkt
->body
= pkt
->data
+ pkt
->length
;
1708 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1709 * put the MAC on it. Final packet, ready to be sent, is stored in
1710 * pkt->data. Total length is returned.
1712 static int ssh2_pkt_construct(Ssh ssh
, struct Packet
*pkt
)
1714 int cipherblk
, maclen
, padding
, i
;
1717 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->data
[5],
1718 ssh2_pkt_type(ssh
->pkt_ctx
, pkt
->data
[5]),
1719 pkt
->body
, pkt
->length
- (pkt
->body
- pkt
->data
),
1720 pkt
->nblanks
, pkt
->blanks
);
1721 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1725 * Compress packet payload.
1728 unsigned char *newpayload
;
1731 ssh
->cscomp
->compress(ssh
->cs_comp_ctx
, pkt
->data
+ 5,
1733 &newpayload
, &newlen
)) {
1735 ssh2_pkt_adddata(pkt
, newpayload
, newlen
);
1741 * Add padding. At least four bytes, and must also bring total
1742 * length (minus MAC) up to a multiple of the block size.
1743 * If pkt->forcepad is set, make sure the packet is at least that size
1746 cipherblk
= ssh
->cscipher ? ssh
->cscipher
->blksize
: 8; /* block size */
1747 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1749 if (pkt
->length
+ padding
< pkt
->forcepad
)
1750 padding
= pkt
->forcepad
- pkt
->length
;
1752 (cipherblk
- (pkt
->length
+ padding
) % cipherblk
) % cipherblk
;
1753 assert(padding
<= 255);
1754 maclen
= ssh
->csmac ? ssh
->csmac
->len
: 0;
1755 ssh2_pkt_ensure(pkt
, pkt
->length
+ padding
+ maclen
);
1756 pkt
->data
[4] = padding
;
1757 for (i
= 0; i
< padding
; i
++)
1758 pkt
->data
[pkt
->length
+ i
] = random_byte();
1759 PUT_32BIT(pkt
->data
, pkt
->length
+ padding
- 4);
1761 ssh
->csmac
->generate(ssh
->cs_mac_ctx
, pkt
->data
,
1762 pkt
->length
+ padding
,
1763 ssh
->v2_outgoing_sequence
);
1764 ssh
->v2_outgoing_sequence
++; /* whether or not we MACed */
1767 ssh
->cscipher
->encrypt(ssh
->cs_cipher_ctx
,
1768 pkt
->data
, pkt
->length
+ padding
);
1770 pkt
->encrypted_len
= pkt
->length
+ padding
;
1772 /* Ready-to-send packet starts at pkt->data. We return length. */
1773 return pkt
->length
+ padding
+ maclen
;
1777 * Routines called from the main SSH code to send packets. There
1778 * are quite a few of these, because we have two separate
1779 * mechanisms for delaying the sending of packets:
1781 * - In order to send an IGNORE message and a password message in
1782 * a single fixed-length blob, we require the ability to
1783 * concatenate the encrypted forms of those two packets _into_ a
1784 * single blob and then pass it to our <network.h> transport
1785 * layer in one go. Hence, there's a deferment mechanism which
1786 * works after packet encryption.
1788 * - In order to avoid sending any connection-layer messages
1789 * during repeat key exchange, we have to queue up any such
1790 * outgoing messages _before_ they are encrypted (and in
1791 * particular before they're allocated sequence numbers), and
1792 * then send them once we've finished.
1794 * I call these mechanisms `defer' and `queue' respectively, so as
1795 * to distinguish them reasonably easily.
1797 * The functions send_noqueue() and defer_noqueue() free the packet
1798 * structure they are passed. Every outgoing packet goes through
1799 * precisely one of these functions in its life; packets passed to
1800 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1801 * these or get queued, and then when the queue is later emptied
1802 * the packets are all passed to defer_noqueue().
1804 * When using a CBC-mode cipher, it's necessary to ensure that an
1805 * attacker can't provide data to be encrypted using an IV that they
1806 * know. We ensure this by prefixing each packet that might contain
1807 * user data with an SSH_MSG_IGNORE. This is done using the deferral
1808 * mechanism, so in this case send_noqueue() ends up redirecting to
1809 * defer_noqueue(). If you don't like this inefficiency, don't use
1813 static void ssh2_pkt_defer_noqueue(Ssh
, struct Packet
*, int);
1814 static void ssh_pkt_defersend(Ssh
);
1817 * Send an SSH-2 packet immediately, without queuing or deferring.
1819 static void ssh2_pkt_send_noqueue(Ssh ssh
, struct Packet
*pkt
)
1823 if (ssh
->cscipher
!= NULL
&& (ssh
->cscipher
->flags
& SSH_CIPHER_IS_CBC
)) {
1824 /* We need to send two packets, so use the deferral mechanism. */
1825 ssh2_pkt_defer_noqueue(ssh
, pkt
, FALSE
);
1826 ssh_pkt_defersend(ssh
);
1829 len
= ssh2_pkt_construct(ssh
, pkt
);
1830 backlog
= sk_write(ssh
->s
, (char *)pkt
->data
, len
);
1831 if (backlog
> SSH_MAX_BACKLOG
)
1832 ssh_throttle_all(ssh
, 1, backlog
);
1834 ssh
->outgoing_data_size
+= pkt
->encrypted_len
;
1835 if (!ssh
->kex_in_progress
&&
1836 ssh
->max_data_size
!= 0 &&
1837 ssh
->outgoing_data_size
> ssh
->max_data_size
)
1838 do_ssh2_transport(ssh
, "too much data sent", -1, NULL
);
1840 ssh_free_packet(pkt
);
1844 * Defer an SSH-2 packet.
1846 static void ssh2_pkt_defer_noqueue(Ssh ssh
, struct Packet
*pkt
, int noignore
)
1849 if (ssh
->cscipher
!= NULL
&& (ssh
->cscipher
->flags
& SSH_CIPHER_IS_CBC
) &&
1850 ssh
->deferred_len
== 0 && !noignore
) {
1852 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
1853 * get encrypted with a known IV.
1855 struct Packet
*ipkt
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
1856 ssh2_pkt_defer_noqueue(ssh
, ipkt
, TRUE
);
1858 len
= ssh2_pkt_construct(ssh
, pkt
);
1859 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1860 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1861 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
1865 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
, pkt
->data
, len
);
1866 ssh
->deferred_len
+= len
;
1867 ssh
->deferred_data_size
+= pkt
->encrypted_len
;
1868 ssh_free_packet(pkt
);
1872 * Queue an SSH-2 packet.
1874 static void ssh2_pkt_queue(Ssh ssh
, struct Packet
*pkt
)
1876 assert(ssh
->queueing
);
1878 if (ssh
->queuelen
>= ssh
->queuesize
) {
1879 ssh
->queuesize
= ssh
->queuelen
+ 32;
1880 ssh
->queue
= sresize(ssh
->queue
, ssh
->queuesize
, struct Packet
*);
1883 ssh
->queue
[ssh
->queuelen
++] = pkt
;
1887 * Either queue or send a packet, depending on whether queueing is
1890 static void ssh2_pkt_send(Ssh ssh
, struct Packet
*pkt
)
1893 ssh2_pkt_queue(ssh
, pkt
);
1895 ssh2_pkt_send_noqueue(ssh
, pkt
);
1900 * Either queue or defer a packet, depending on whether queueing is
1903 static void ssh2_pkt_defer(Ssh ssh
, struct Packet
*pkt
)
1906 ssh2_pkt_queue(ssh
, pkt
);
1908 ssh2_pkt_defer_noqueue(ssh
, pkt
, FALSE
);
1913 * Send the whole deferred data block constructed by
1914 * ssh2_pkt_defer() or SSH-1's defer_packet().
1916 * The expected use of the defer mechanism is that you call
1917 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
1918 * not currently queueing, this simply sets up deferred_send_data
1919 * and then sends it. If we _are_ currently queueing, the calls to
1920 * ssh2_pkt_defer() put the deferred packets on to the queue
1921 * instead, and therefore ssh_pkt_defersend() has no deferred data
1922 * to send. Hence, there's no need to make it conditional on
1925 static void ssh_pkt_defersend(Ssh ssh
)
1928 backlog
= sk_write(ssh
->s
, (char *)ssh
->deferred_send_data
,
1930 ssh
->deferred_len
= ssh
->deferred_size
= 0;
1931 sfree(ssh
->deferred_send_data
);
1932 ssh
->deferred_send_data
= NULL
;
1933 if (backlog
> SSH_MAX_BACKLOG
)
1934 ssh_throttle_all(ssh
, 1, backlog
);
1936 ssh
->outgoing_data_size
+= ssh
->deferred_data_size
;
1937 if (!ssh
->kex_in_progress
&&
1938 ssh
->max_data_size
!= 0 &&
1939 ssh
->outgoing_data_size
> ssh
->max_data_size
)
1940 do_ssh2_transport(ssh
, "too much data sent", -1, NULL
);
1941 ssh
->deferred_data_size
= 0;
1945 * Send all queued SSH-2 packets. We send them by means of
1946 * ssh2_pkt_defer_noqueue(), in case they included a pair of
1947 * packets that needed to be lumped together.
1949 static void ssh2_pkt_queuesend(Ssh ssh
)
1953 assert(!ssh
->queueing
);
1955 for (i
= 0; i
< ssh
->queuelen
; i
++)
1956 ssh2_pkt_defer_noqueue(ssh
, ssh
->queue
[i
], FALSE
);
1959 ssh_pkt_defersend(ssh
);
1963 void bndebug(char *string
, Bignum b
)
1967 p
= ssh2_mpint_fmt(b
, &len
);
1968 debug(("%s", string
));
1969 for (i
= 0; i
< len
; i
++)
1970 debug((" %02x", p
[i
]));
1976 static void hash_mpint(const struct ssh_hash
*h
, void *s
, Bignum b
)
1980 p
= ssh2_mpint_fmt(b
, &len
);
1981 hash_string(h
, s
, p
, len
);
1986 * Packet decode functions for both SSH-1 and SSH-2.
1988 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
)
1990 unsigned long value
;
1991 if (pkt
->length
- pkt
->savedpos
< 4)
1992 return 0; /* arrgh, no way to decline (FIXME?) */
1993 value
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
1997 static int ssh2_pkt_getbool(struct Packet
*pkt
)
1999 unsigned long value
;
2000 if (pkt
->length
- pkt
->savedpos
< 1)
2001 return 0; /* arrgh, no way to decline (FIXME?) */
2002 value
= pkt
->body
[pkt
->savedpos
] != 0;
2006 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
)
2011 if (pkt
->length
- pkt
->savedpos
< 4)
2013 len
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
2018 if (pkt
->length
- pkt
->savedpos
< *length
)
2020 *p
= (char *)(pkt
->body
+ pkt
->savedpos
);
2021 pkt
->savedpos
+= *length
;
2023 static void *ssh_pkt_getdata(struct Packet
*pkt
, int length
)
2025 if (pkt
->length
- pkt
->savedpos
< length
)
2027 pkt
->savedpos
+= length
;
2028 return pkt
->body
+ (pkt
->savedpos
- length
);
2030 static int ssh1_pkt_getrsakey(struct Packet
*pkt
, struct RSAKey
*key
,
2031 unsigned char **keystr
)
2035 j
= makekey(pkt
->body
+ pkt
->savedpos
,
2036 pkt
->length
- pkt
->savedpos
,
2043 assert(pkt
->savedpos
< pkt
->length
);
2047 static Bignum
ssh1_pkt_getmp(struct Packet
*pkt
)
2052 j
= ssh1_read_bignum(pkt
->body
+ pkt
->savedpos
,
2053 pkt
->length
- pkt
->savedpos
, &b
);
2061 static Bignum
ssh2_pkt_getmp(struct Packet
*pkt
)
2067 ssh_pkt_getstring(pkt
, &p
, &length
);
2072 b
= bignum_from_bytes((unsigned char *)p
, length
);
2077 * Helper function to add an SSH-2 signature blob to a packet.
2078 * Expects to be shown the public key blob as well as the signature
2079 * blob. Normally works just like ssh2_pkt_addstring, but will
2080 * fiddle with the signature packet if necessary for
2081 * BUG_SSH2_RSA_PADDING.
2083 static void ssh2_add_sigblob(Ssh ssh
, struct Packet
*pkt
,
2084 void *pkblob_v
, int pkblob_len
,
2085 void *sigblob_v
, int sigblob_len
)
2087 unsigned char *pkblob
= (unsigned char *)pkblob_v
;
2088 unsigned char *sigblob
= (unsigned char *)sigblob_v
;
2090 /* dmemdump(pkblob, pkblob_len); */
2091 /* dmemdump(sigblob, sigblob_len); */
2094 * See if this is in fact an ssh-rsa signature and a buggy
2095 * server; otherwise we can just do this the easy way.
2097 if ((ssh
->remote_bugs
& BUG_SSH2_RSA_PADDING
) &&
2098 (GET_32BIT(pkblob
) == 7 && !memcmp(pkblob
+4, "ssh-rsa", 7))) {
2099 int pos
, len
, siglen
;
2102 * Find the byte length of the modulus.
2105 pos
= 4+7; /* skip over "ssh-rsa" */
2106 pos
+= 4 + GET_32BIT(pkblob
+pos
); /* skip over exponent */
2107 len
= GET_32BIT(pkblob
+pos
); /* find length of modulus */
2108 pos
+= 4; /* find modulus itself */
2109 while (len
> 0 && pkblob
[pos
] == 0)
2111 /* debug(("modulus length is %d\n", len)); */
2114 * Now find the signature integer.
2116 pos
= 4+7; /* skip over "ssh-rsa" */
2117 siglen
= GET_32BIT(sigblob
+pos
);
2118 /* debug(("signature length is %d\n", siglen)); */
2120 if (len
!= siglen
) {
2121 unsigned char newlen
[4];
2122 ssh2_pkt_addstring_start(pkt
);
2123 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, pos
);
2124 /* dmemdump(sigblob, pos); */
2125 pos
+= 4; /* point to start of actual sig */
2126 PUT_32BIT(newlen
, len
);
2127 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 4);
2128 /* dmemdump(newlen, 4); */
2130 while (len
-- > siglen
) {
2131 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 1);
2132 /* dmemdump(newlen, 1); */
2134 ssh2_pkt_addstring_data(pkt
, (char *)(sigblob
+pos
), siglen
);
2135 /* dmemdump(sigblob+pos, siglen); */
2139 /* Otherwise fall through and do it the easy way. */
2142 ssh2_pkt_addstring_start(pkt
);
2143 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, sigblob_len
);
2147 * Examine the remote side's version string and compare it against
2148 * a list of known buggy implementations.
2150 static void ssh_detect_bugs(Ssh ssh
, char *vstring
)
2152 char *imp
; /* pointer to implementation part */
2154 imp
+= strcspn(imp
, "-");
2156 imp
+= strcspn(imp
, "-");
2159 ssh
->remote_bugs
= 0;
2161 if (ssh
->cfg
.sshbug_ignore1
== FORCE_ON
||
2162 (ssh
->cfg
.sshbug_ignore1
== AUTO
&&
2163 (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
2164 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
2165 !strcmp(imp
, "1.2.22") || !strcmp(imp
, "Cisco-1.25") ||
2166 !strcmp(imp
, "OSU_1.4alpha3") || !strcmp(imp
, "OSU_1.5alpha4")))) {
2168 * These versions don't support SSH1_MSG_IGNORE, so we have
2169 * to use a different defence against password length
2172 ssh
->remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
2173 logevent("We believe remote version has SSH-1 ignore bug");
2176 if (ssh
->cfg
.sshbug_plainpw1
== FORCE_ON
||
2177 (ssh
->cfg
.sshbug_plainpw1
== AUTO
&&
2178 (!strcmp(imp
, "Cisco-1.25") || !strcmp(imp
, "OSU_1.4alpha3")))) {
2180 * These versions need a plain password sent; they can't
2181 * handle having a null and a random length of data after
2184 ssh
->remote_bugs
|= BUG_NEEDS_SSH1_PLAIN_PASSWORD
;
2185 logevent("We believe remote version needs a plain SSH-1 password");
2188 if (ssh
->cfg
.sshbug_rsa1
== FORCE_ON
||
2189 (ssh
->cfg
.sshbug_rsa1
== AUTO
&&
2190 (!strcmp(imp
, "Cisco-1.25")))) {
2192 * These versions apparently have no clue whatever about
2193 * RSA authentication and will panic and die if they see
2194 * an AUTH_RSA message.
2196 ssh
->remote_bugs
|= BUG_CHOKES_ON_RSA
;
2197 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2200 if (ssh
->cfg
.sshbug_hmac2
== FORCE_ON
||
2201 (ssh
->cfg
.sshbug_hmac2
== AUTO
&&
2202 !wc_match("* VShell", imp
) &&
2203 (wc_match("2.1.0*", imp
) || wc_match("2.0.*", imp
) ||
2204 wc_match("2.2.0*", imp
) || wc_match("2.3.0*", imp
) ||
2205 wc_match("2.1 *", imp
)))) {
2207 * These versions have the HMAC bug.
2209 ssh
->remote_bugs
|= BUG_SSH2_HMAC
;
2210 logevent("We believe remote version has SSH-2 HMAC bug");
2213 if (ssh
->cfg
.sshbug_derivekey2
== FORCE_ON
||
2214 (ssh
->cfg
.sshbug_derivekey2
== AUTO
&&
2215 !wc_match("* VShell", imp
) &&
2216 (wc_match("2.0.0*", imp
) || wc_match("2.0.10*", imp
) ))) {
2218 * These versions have the key-derivation bug (failing to
2219 * include the literal shared secret in the hashes that
2220 * generate the keys).
2222 ssh
->remote_bugs
|= BUG_SSH2_DERIVEKEY
;
2223 logevent("We believe remote version has SSH-2 key-derivation bug");
2226 if (ssh
->cfg
.sshbug_rsapad2
== FORCE_ON
||
2227 (ssh
->cfg
.sshbug_rsapad2
== AUTO
&&
2228 (wc_match("OpenSSH_2.[5-9]*", imp
) ||
2229 wc_match("OpenSSH_3.[0-2]*", imp
)))) {
2231 * These versions have the SSH-2 RSA padding bug.
2233 ssh
->remote_bugs
|= BUG_SSH2_RSA_PADDING
;
2234 logevent("We believe remote version has SSH-2 RSA padding bug");
2237 if (ssh
->cfg
.sshbug_pksessid2
== FORCE_ON
||
2238 (ssh
->cfg
.sshbug_pksessid2
== AUTO
&&
2239 wc_match("OpenSSH_2.[0-2]*", imp
))) {
2241 * These versions have the SSH-2 session-ID bug in
2242 * public-key authentication.
2244 ssh
->remote_bugs
|= BUG_SSH2_PK_SESSIONID
;
2245 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2248 if (ssh
->cfg
.sshbug_rekey2
== FORCE_ON
||
2249 (ssh
->cfg
.sshbug_rekey2
== AUTO
&&
2250 (wc_match("DigiSSH_2.0", imp
) ||
2251 wc_match("OpenSSH_2.[0-4]*", imp
) ||
2252 wc_match("OpenSSH_2.5.[0-3]*", imp
) ||
2253 wc_match("Sun_SSH_1.0", imp
) ||
2254 wc_match("Sun_SSH_1.0.1", imp
) ||
2255 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2256 wc_match("WeOnlyDo-*", imp
)))) {
2258 * These versions have the SSH-2 rekey bug.
2260 ssh
->remote_bugs
|= BUG_SSH2_REKEY
;
2261 logevent("We believe remote version has SSH-2 rekey bug");
2266 * The `software version' part of an SSH version string is required
2267 * to contain no spaces or minus signs.
2269 static void ssh_fix_verstring(char *str
)
2271 /* Eat "SSH-<protoversion>-". */
2272 assert(*str
== 'S'); str
++;
2273 assert(*str
== 'S'); str
++;
2274 assert(*str
== 'H'); str
++;
2275 assert(*str
== '-'); str
++;
2276 while (*str
&& *str
!= '-') str
++;
2277 assert(*str
== '-'); str
++;
2279 /* Convert minus signs and spaces in the remaining string into
2282 if (*str
== '-' || *str
== ' ')
2288 static int do_ssh_init(Ssh ssh
, unsigned char c
)
2290 struct do_ssh_init_state
{
2298 crState(do_ssh_init_state
);
2300 crBegin(ssh
->do_ssh_init_crstate
);
2302 /* Search for a line beginning with the string "SSH-" in the input. */
2304 if (c
!= 'S') goto no
;
2306 if (c
!= 'S') goto no
;
2308 if (c
!= 'H') goto no
;
2310 if (c
!= '-') goto no
;
2319 s
->vstring
= snewn(s
->vstrsize
, char);
2320 strcpy(s
->vstring
, "SSH-");
2324 crReturn(1); /* get another char */
2325 if (s
->vslen
>= s
->vstrsize
- 1) {
2327 s
->vstring
= sresize(s
->vstring
, s
->vstrsize
, char);
2329 s
->vstring
[s
->vslen
++] = c
;
2332 s
->version
[s
->i
] = '\0';
2334 } else if (s
->i
< sizeof(s
->version
) - 1)
2335 s
->version
[s
->i
++] = c
;
2336 } else if (c
== '\012')
2340 ssh
->agentfwd_enabled
= FALSE
;
2341 ssh
->rdpkt2_state
.incoming_sequence
= 0;
2343 s
->vstring
[s
->vslen
] = 0;
2344 s
->vstring
[strcspn(s
->vstring
, "\015\012")] = '\0';/* remove EOL chars */
2345 logeventf(ssh
, "Server version: %s", s
->vstring
);
2346 ssh_detect_bugs(ssh
, s
->vstring
);
2349 * Decide which SSH protocol version to support.
2352 /* Anything strictly below "2.0" means protocol 1 is supported. */
2353 s
->proto1
= ssh_versioncmp(s
->version
, "2.0") < 0;
2354 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2355 s
->proto2
= ssh_versioncmp(s
->version
, "1.99") >= 0;
2357 if (ssh
->cfg
.sshprot
== 0 && !s
->proto1
) {
2358 bombout(("SSH protocol version 1 required by user but not provided by server"));
2361 if (ssh
->cfg
.sshprot
== 3 && !s
->proto2
) {
2362 bombout(("SSH protocol version 2 required by user but not provided by server"));
2369 if (s
->proto2
&& (ssh
->cfg
.sshprot
>= 2 || !s
->proto1
)) {
2371 * Construct a v2 version string.
2373 verstring
= dupprintf("SSH-2.0-%s\015\012", sshver
);
2377 * Construct a v1 version string.
2379 verstring
= dupprintf("SSH-%s-%s\012",
2380 (ssh_versioncmp(s
->version
, "1.5") <= 0 ?
2381 s
->version
: "1.5"),
2386 ssh_fix_verstring(verstring
);
2388 if (ssh
->version
== 2) {
2391 * Hash our version string and their version string.
2393 len
= strcspn(verstring
, "\015\012");
2394 ssh
->v_c
= snewn(len
+ 1, char);
2395 memcpy(ssh
->v_c
, verstring
, len
);
2397 len
= strcspn(s
->vstring
, "\015\012");
2398 ssh
->v_s
= snewn(len
+ 1, char);
2399 memcpy(ssh
->v_s
, s
->vstring
, len
);
2403 * Initialise SSH-2 protocol.
2405 ssh
->protocol
= ssh2_protocol
;
2406 ssh2_protocol_setup(ssh
);
2407 ssh
->s_rdpkt
= ssh2_rdpkt
;
2410 * Initialise SSH-1 protocol.
2412 ssh
->protocol
= ssh1_protocol
;
2413 ssh1_protocol_setup(ssh
);
2414 ssh
->s_rdpkt
= ssh1_rdpkt
;
2416 logeventf(ssh
, "We claim version: %.*s",
2417 strcspn(verstring
, "\015\012"), verstring
);
2418 sk_write(ssh
->s
, verstring
, strlen(verstring
));
2420 if (ssh
->version
== 2)
2421 do_ssh2_transport(ssh
, NULL
, -1, NULL
);
2424 logeventf(ssh
, "Using SSH protocol version %d", ssh
->version
);
2426 update_specials_menu(ssh
->frontend
);
2427 ssh
->state
= SSH_STATE_BEFORE_SIZE
;
2428 ssh
->pinger
= pinger_new(&ssh
->cfg
, &ssh_backend
, ssh
);
2435 static void ssh_process_incoming_data(Ssh ssh
,
2436 unsigned char **data
, int *datalen
)
2438 struct Packet
*pktin
= ssh
->s_rdpkt(ssh
, data
, datalen
);
2440 ssh
->protocol(ssh
, NULL
, 0, pktin
);
2441 ssh_free_packet(pktin
);
2445 static void ssh_queue_incoming_data(Ssh ssh
,
2446 unsigned char **data
, int *datalen
)
2448 bufchain_add(&ssh
->queued_incoming_data
, *data
, *datalen
);
2453 static void ssh_process_queued_incoming_data(Ssh ssh
)
2456 unsigned char *data
;
2459 while (!ssh
->frozen
&& bufchain_size(&ssh
->queued_incoming_data
)) {
2460 bufchain_prefix(&ssh
->queued_incoming_data
, &vdata
, &len
);
2464 while (!ssh
->frozen
&& len
> 0)
2465 ssh_process_incoming_data(ssh
, &data
, &len
);
2468 bufchain_consume(&ssh
->queued_incoming_data
, origlen
- len
);
2472 static void ssh_set_frozen(Ssh ssh
, int frozen
)
2475 sk_set_frozen(ssh
->s
, frozen
);
2476 ssh
->frozen
= frozen
;
2479 static void ssh_gotdata(Ssh ssh
, unsigned char *data
, int datalen
)
2481 crBegin(ssh
->ssh_gotdata_crstate
);
2484 * To begin with, feed the characters one by one to the
2485 * protocol initialisation / selection function do_ssh_init().
2486 * When that returns 0, we're done with the initial greeting
2487 * exchange and can move on to packet discipline.
2490 int ret
; /* need not be kept across crReturn */
2492 crReturnV
; /* more data please */
2493 ret
= do_ssh_init(ssh
, *data
);
2501 * We emerge from that loop when the initial negotiation is
2502 * over and we have selected an s_rdpkt function. Now pass
2503 * everything to s_rdpkt, and then pass the resulting packets
2504 * to the proper protocol handler.
2508 while (bufchain_size(&ssh
->queued_incoming_data
) > 0 || datalen
> 0) {
2510 ssh_queue_incoming_data(ssh
, &data
, &datalen
);
2511 /* This uses up all data and cannot cause anything interesting
2512 * to happen; indeed, for anything to happen at all, we must
2513 * return, so break out. */
2515 } else if (bufchain_size(&ssh
->queued_incoming_data
) > 0) {
2516 /* This uses up some or all data, and may freeze the
2518 ssh_process_queued_incoming_data(ssh
);
2520 /* This uses up some or all data, and may freeze the
2522 ssh_process_incoming_data(ssh
, &data
, &datalen
);
2524 /* FIXME this is probably EBW. */
2525 if (ssh
->state
== SSH_STATE_CLOSED
)
2528 /* We're out of data. Go and get some more. */
2534 static int ssh_do_close(Ssh ssh
, int notify_exit
)
2537 struct ssh_channel
*c
;
2539 ssh
->state
= SSH_STATE_CLOSED
;
2540 expire_timer_context(ssh
);
2545 notify_remote_exit(ssh
->frontend
);
2550 * Now we must shut down any port- and X-forwarded channels going
2551 * through this connection.
2553 if (ssh
->channels
) {
2554 while (NULL
!= (c
= index234(ssh
->channels
, 0))) {
2557 x11_close(c
->u
.x11
.s
);
2560 pfd_close(c
->u
.pfd
.s
);
2563 del234(ssh
->channels
, c
); /* moving next one to index 0 */
2564 if (ssh
->version
== 2)
2565 bufchain_clear(&c
->v
.v2
.outbuffer
);
2570 * Go through port-forwardings, and close any associated
2571 * listening sockets.
2573 if (ssh
->portfwds
) {
2574 struct ssh_portfwd
*pf
;
2575 while (NULL
!= (pf
= index234(ssh
->portfwds
, 0))) {
2576 /* Dispose of any listening socket. */
2578 pfd_terminate(pf
->local
);
2579 del234(ssh
->portfwds
, pf
); /* moving next one to index 0 */
2587 static void ssh_log(Plug plug
, int type
, SockAddr addr
, int port
,
2588 const char *error_msg
, int error_code
)
2590 Ssh ssh
= (Ssh
) plug
;
2591 char addrbuf
[256], *msg
;
2593 sk_getaddr(addr
, addrbuf
, lenof(addrbuf
));
2596 msg
= dupprintf("Connecting to %s port %d", addrbuf
, port
);
2598 msg
= dupprintf("Failed to connect to %s: %s", addrbuf
, error_msg
);
2604 static int ssh_closing(Plug plug
, const char *error_msg
, int error_code
,
2607 Ssh ssh
= (Ssh
) plug
;
2608 int need_notify
= ssh_do_close(ssh
, FALSE
);
2611 if (!ssh
->close_expected
)
2612 error_msg
= "Server unexpectedly closed network connection";
2614 error_msg
= "Server closed network connection";
2618 notify_remote_exit(ssh
->frontend
);
2621 logevent(error_msg
);
2622 if (!ssh
->close_expected
|| !ssh
->clean_exit
)
2623 connection_fatal(ssh
->frontend
, "%s", error_msg
);
2627 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
2629 Ssh ssh
= (Ssh
) plug
;
2630 ssh_gotdata(ssh
, (unsigned char *)data
, len
);
2631 if (ssh
->state
== SSH_STATE_CLOSED
) {
2632 ssh_do_close(ssh
, TRUE
);
2638 static void ssh_sent(Plug plug
, int bufsize
)
2640 Ssh ssh
= (Ssh
) plug
;
2642 * If the send backlog on the SSH socket itself clears, we
2643 * should unthrottle the whole world if it was throttled.
2645 if (bufsize
< SSH_MAX_BACKLOG
)
2646 ssh_throttle_all(ssh
, 0, bufsize
);
2650 * Connect to specified host and port.
2651 * Returns an error message, or NULL on success.
2652 * Also places the canonical host name into `realhost'. It must be
2653 * freed by the caller.
2655 static const char *connect_to_host(Ssh ssh
, char *host
, int port
,
2656 char **realhost
, int nodelay
, int keepalive
)
2658 static const struct plug_function_table fn_table
= {
2669 ssh
->savedhost
= snewn(1 + strlen(host
), char);
2670 strcpy(ssh
->savedhost
, host
);
2673 port
= 22; /* default ssh port */
2674 ssh
->savedport
= port
;
2679 logeventf(ssh
, "Looking up host \"%s\"%s", host
,
2680 (ssh
->cfg
.addressfamily
== ADDRTYPE_IPV4 ?
" (IPv4)" :
2681 (ssh
->cfg
.addressfamily
== ADDRTYPE_IPV6 ?
" (IPv6)" : "")));
2682 addr
= name_lookup(host
, port
, realhost
, &ssh
->cfg
,
2683 ssh
->cfg
.addressfamily
);
2684 if ((err
= sk_addr_error(addr
)) != NULL
) {
2692 ssh
->fn
= &fn_table
;
2693 ssh
->s
= new_connection(addr
, *realhost
, port
,
2694 0, 1, nodelay
, keepalive
, (Plug
) ssh
, &ssh
->cfg
);
2695 if ((err
= sk_socket_error(ssh
->s
)) != NULL
) {
2697 notify_remote_exit(ssh
->frontend
);
2705 * Throttle or unthrottle the SSH connection.
2707 static void ssh1_throttle(Ssh ssh
, int adjust
)
2709 int old_count
= ssh
->v1_throttle_count
;
2710 ssh
->v1_throttle_count
+= adjust
;
2711 assert(ssh
->v1_throttle_count
>= 0);
2712 if (ssh
->v1_throttle_count
&& !old_count
) {
2713 ssh_set_frozen(ssh
, 1);
2714 } else if (!ssh
->v1_throttle_count
&& old_count
) {
2715 ssh_set_frozen(ssh
, 0);
2720 * Throttle or unthrottle _all_ local data streams (for when sends
2721 * on the SSH connection itself back up).
2723 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
)
2726 struct ssh_channel
*c
;
2728 if (enable
== ssh
->throttled_all
)
2730 ssh
->throttled_all
= enable
;
2731 ssh
->overall_bufsize
= bufsize
;
2734 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
2736 case CHAN_MAINSESSION
:
2738 * This is treated separately, outside the switch.
2742 x11_override_throttle(c
->u
.x11
.s
, enable
);
2745 /* Agent channels require no buffer management. */
2748 pfd_override_throttle(c
->u
.pfd
.s
, enable
);
2755 * Username and password input, abstracted off into routines
2756 * reusable in several places - even between SSH-1 and SSH-2.
2759 /* Set up a username or password input loop on a given buffer. */
2760 static void setup_userpass_input(Ssh ssh
, char *buffer
, int buflen
, int echo
)
2762 ssh
->userpass_input_buffer
= buffer
;
2763 ssh
->userpass_input_buflen
= buflen
;
2764 ssh
->userpass_input_bufpos
= 0;
2765 ssh
->userpass_input_echo
= echo
;
2769 * Process some terminal data in the course of username/password
2770 * input. Returns >0 for success (line of input returned in
2771 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2772 * for inconclusive (keep waiting for more input please).
2774 static int process_userpass_input(Ssh ssh
, unsigned char *in
, int inlen
)
2779 switch (c
= *in
++) {
2782 ssh
->userpass_input_buffer
[ssh
->userpass_input_bufpos
] = 0;
2783 ssh
->userpass_input_buffer
[ssh
->userpass_input_buflen
-1] = 0;
2788 if (ssh
->userpass_input_bufpos
> 0) {
2789 if (ssh
->userpass_input_echo
)
2790 c_write_str(ssh
, "\b \b");
2791 ssh
->userpass_input_bufpos
--;
2796 while (ssh
->userpass_input_bufpos
> 0) {
2797 if (ssh
->userpass_input_echo
)
2798 c_write_str(ssh
, "\b \b");
2799 ssh
->userpass_input_bufpos
--;
2808 * This simplistic check for printability is disabled
2809 * when we're doing password input, because some people
2810 * have control characters in their passwords.o
2812 if ((!ssh
->userpass_input_echo
||
2813 (c
>= ' ' && c
<= '~') ||
2814 ((unsigned char) c
>= 160))
2815 && ssh
->userpass_input_bufpos
< ssh
->userpass_input_buflen
-1) {
2816 ssh
->userpass_input_buffer
[ssh
->userpass_input_bufpos
++] = c
;
2817 if (ssh
->userpass_input_echo
)
2818 c_write(ssh
, &c
, 1);
2826 static void ssh_agent_callback(void *sshv
, void *reply
, int replylen
)
2828 Ssh ssh
= (Ssh
) sshv
;
2830 ssh
->agent_response
= reply
;
2831 ssh
->agent_response_len
= replylen
;
2833 if (ssh
->version
== 1)
2834 do_ssh1_login(ssh
, NULL
, -1, NULL
);
2836 do_ssh2_authconn(ssh
, NULL
, -1, NULL
);
2839 static void ssh_dialog_callback(void *sshv
, int ret
)
2841 Ssh ssh
= (Ssh
) sshv
;
2843 ssh
->user_response
= ret
;
2845 if (ssh
->version
== 1)
2846 do_ssh1_login(ssh
, NULL
, -1, NULL
);
2848 do_ssh2_transport(ssh
, NULL
, -1, NULL
);
2851 * This may have unfrozen the SSH connection, so do a
2854 ssh_process_queued_incoming_data(ssh
);
2857 static void ssh_agentf_callback(void *cv
, void *reply
, int replylen
)
2859 struct ssh_channel
*c
= (struct ssh_channel
*)cv
;
2861 void *sentreply
= reply
;
2864 /* Fake SSH_AGENT_FAILURE. */
2865 sentreply
= "\0\0\0\1\5";
2868 if (ssh
->version
== 2) {
2869 ssh2_add_channel_data(c
, sentreply
, replylen
);
2872 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
2873 PKT_INT
, c
->remoteid
,
2876 PKT_DATA
, sentreply
, replylen
,
2885 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
2886 * non-NULL, otherwise just close the connection. `client_reason' == NULL
2887 * => log `wire_reason'.
2889 static void ssh_disconnect(Ssh ssh
, char *client_reason
, char *wire_reason
,
2890 int code
, int clean_exit
)
2894 client_reason
= wire_reason
;
2896 error
= dupprintf("Disconnected: %s", client_reason
);
2898 error
= dupstr("Disconnected");
2900 if (ssh
->version
== 1) {
2901 send_packet(ssh
, SSH1_MSG_DISCONNECT
, PKT_STR
, wire_reason
,
2903 } else if (ssh
->version
== 2) {
2904 struct Packet
*pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
2905 ssh2_pkt_adduint32(pktout
, code
);
2906 ssh2_pkt_addstring(pktout
, wire_reason
);
2907 ssh2_pkt_addstring(pktout
, "en"); /* language tag */
2908 ssh2_pkt_send_noqueue(ssh
, pktout
);
2911 ssh
->close_expected
= TRUE
;
2912 ssh
->clean_exit
= clean_exit
;
2913 ssh_closing((Plug
)ssh
, error
, 0, 0);
2918 * Handle the key exchange and user authentication phases.
2920 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
,
2921 struct Packet
*pktin
)
2924 unsigned char cookie
[8], *ptr
;
2925 struct RSAKey servkey
, hostkey
;
2926 struct MD5Context md5c
;
2927 struct do_ssh1_login_state
{
2929 unsigned char *rsabuf
, *keystr1
, *keystr2
;
2930 unsigned long supported_ciphers_mask
, supported_auths_mask
;
2931 int tried_publickey
, tried_agent
;
2932 int tis_auth_refused
, ccard_auth_refused
;
2933 unsigned char session_id
[16];
2936 void *publickey_blob
;
2937 int publickey_bloblen
;
2943 unsigned char request
[5], *response
, *p
;
2953 crState(do_ssh1_login_state
);
2955 crBegin(ssh
->do_ssh1_login_crstate
);
2960 if (pktin
->type
!= SSH1_SMSG_PUBLIC_KEY
) {
2961 bombout(("Public key packet not received"));
2965 logevent("Received public keys");
2967 ptr
= ssh_pkt_getdata(pktin
, 8);
2969 bombout(("SSH-1 public key packet stopped before random cookie"));
2972 memcpy(cookie
, ptr
, 8);
2974 if (!ssh1_pkt_getrsakey(pktin
, &servkey
, &s
->keystr1
) ||
2975 !ssh1_pkt_getrsakey(pktin
, &hostkey
, &s
->keystr2
)) {
2976 bombout(("Failed to read SSH-1 public keys from public key packet"));
2981 * Log the host key fingerprint.
2985 logevent("Host key fingerprint is:");
2986 strcpy(logmsg
, " ");
2987 hostkey
.comment
= NULL
;
2988 rsa_fingerprint(logmsg
+ strlen(logmsg
),
2989 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
2993 ssh
->v1_remote_protoflags
= ssh_pkt_getuint32(pktin
);
2994 s
->supported_ciphers_mask
= ssh_pkt_getuint32(pktin
);
2995 s
->supported_auths_mask
= ssh_pkt_getuint32(pktin
);
2997 ssh
->v1_local_protoflags
=
2998 ssh
->v1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
2999 ssh
->v1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
3002 MD5Update(&md5c
, s
->keystr2
, hostkey
.bytes
);
3003 MD5Update(&md5c
, s
->keystr1
, servkey
.bytes
);
3004 MD5Update(&md5c
, cookie
, 8);
3005 MD5Final(s
->session_id
, &md5c
);
3007 for (i
= 0; i
< 32; i
++)
3008 ssh
->session_key
[i
] = random_byte();
3011 * Verify that the `bits' and `bytes' parameters match.
3013 if (hostkey
.bits
> hostkey
.bytes
* 8 ||
3014 servkey
.bits
> servkey
.bytes
* 8) {
3015 bombout(("SSH-1 public keys were badly formatted"));
3019 s
->len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
3021 s
->rsabuf
= snewn(s
->len
, unsigned char);
3024 * Verify the host key.
3028 * First format the key into a string.
3030 int len
= rsastr_len(&hostkey
);
3031 char fingerprint
[100];
3032 char *keystr
= snewn(len
, char);
3033 rsastr_fmt(keystr
, &hostkey
);
3034 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
3036 ssh_set_frozen(ssh
, 1);
3037 s
->dlgret
= verify_ssh_host_key(ssh
->frontend
,
3038 ssh
->savedhost
, ssh
->savedport
,
3039 "rsa", keystr
, fingerprint
,
3040 ssh_dialog_callback
, ssh
);
3042 if (s
->dlgret
< 0) {
3046 bombout(("Unexpected data from server while waiting"
3047 " for user host key response"));
3050 } while (pktin
|| inlen
> 0);
3051 s
->dlgret
= ssh
->user_response
;
3053 ssh_set_frozen(ssh
, 0);
3055 if (s
->dlgret
== 0) {
3056 ssh_disconnect(ssh
, "User aborted at host key verification",
3062 for (i
= 0; i
< 32; i
++) {
3063 s
->rsabuf
[i
] = ssh
->session_key
[i
];
3065 s
->rsabuf
[i
] ^= s
->session_id
[i
];
3068 if (hostkey
.bytes
> servkey
.bytes
) {
3069 ret
= rsaencrypt(s
->rsabuf
, 32, &servkey
);
3071 ret
= rsaencrypt(s
->rsabuf
, servkey
.bytes
, &hostkey
);
3073 ret
= rsaencrypt(s
->rsabuf
, 32, &hostkey
);
3075 ret
= rsaencrypt(s
->rsabuf
, hostkey
.bytes
, &servkey
);
3078 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3082 logevent("Encrypted session key");
3085 int cipher_chosen
= 0, warn
= 0;
3086 char *cipher_string
= NULL
;
3088 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
3089 int next_cipher
= ssh
->cfg
.ssh_cipherlist
[i
];
3090 if (next_cipher
== CIPHER_WARN
) {
3091 /* If/when we choose a cipher, warn about it */
3093 } else if (next_cipher
== CIPHER_AES
) {
3094 /* XXX Probably don't need to mention this. */
3095 logevent("AES not supported in SSH-1, skipping");
3097 switch (next_cipher
) {
3098 case CIPHER_3DES
: s
->cipher_type
= SSH_CIPHER_3DES
;
3099 cipher_string
= "3DES"; break;
3100 case CIPHER_BLOWFISH
: s
->cipher_type
= SSH_CIPHER_BLOWFISH
;
3101 cipher_string
= "Blowfish"; break;
3102 case CIPHER_DES
: s
->cipher_type
= SSH_CIPHER_DES
;
3103 cipher_string
= "single-DES"; break;
3105 if (s
->supported_ciphers_mask
& (1 << s
->cipher_type
))
3109 if (!cipher_chosen
) {
3110 if ((s
->supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
3111 bombout(("Server violates SSH-1 protocol by not "
3112 "supporting 3DES encryption"));
3114 /* shouldn't happen */
3115 bombout(("No supported ciphers found"));
3119 /* Warn about chosen cipher if necessary. */
3121 ssh_set_frozen(ssh
, 1);
3122 s
->dlgret
= askalg(ssh
->frontend
, "cipher", cipher_string
,
3123 ssh_dialog_callback
, ssh
);
3124 if (s
->dlgret
< 0) {
3128 bombout(("Unexpected data from server while waiting"
3129 " for user response"));
3132 } while (pktin
|| inlen
> 0);
3133 s
->dlgret
= ssh
->user_response
;
3135 ssh_set_frozen(ssh
, 0);
3136 if (s
->dlgret
== 0) {
3137 ssh_disconnect(ssh
, "User aborted at cipher warning", NULL
,
3144 switch (s
->cipher_type
) {
3145 case SSH_CIPHER_3DES
:
3146 logevent("Using 3DES encryption");
3148 case SSH_CIPHER_DES
:
3149 logevent("Using single-DES encryption");
3151 case SSH_CIPHER_BLOWFISH
:
3152 logevent("Using Blowfish encryption");
3156 send_packet(ssh
, SSH1_CMSG_SESSION_KEY
,
3157 PKT_CHAR
, s
->cipher_type
,
3158 PKT_DATA
, cookie
, 8,
3159 PKT_CHAR
, (s
->len
* 8) >> 8, PKT_CHAR
, (s
->len
* 8) & 0xFF,
3160 PKT_DATA
, s
->rsabuf
, s
->len
,
3161 PKT_INT
, ssh
->v1_local_protoflags
, PKT_END
);
3163 logevent("Trying to enable encryption...");
3167 ssh
->cipher
= (s
->cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
3168 s
->cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
3170 ssh
->v1_cipher_ctx
= ssh
->cipher
->make_context();
3171 ssh
->cipher
->sesskey(ssh
->v1_cipher_ctx
, ssh
->session_key
);
3172 logeventf(ssh
, "Initialised %s encryption", ssh
->cipher
->text_name
);
3174 ssh
->crcda_ctx
= crcda_make_context();
3175 logevent("Installing CRC compensation attack detector");
3177 if (servkey
.modulus
) {
3178 sfree(servkey
.modulus
);
3179 servkey
.modulus
= NULL
;
3181 if (servkey
.exponent
) {
3182 sfree(servkey
.exponent
);
3183 servkey
.exponent
= NULL
;
3185 if (hostkey
.modulus
) {
3186 sfree(hostkey
.modulus
);
3187 hostkey
.modulus
= NULL
;
3189 if (hostkey
.exponent
) {
3190 sfree(hostkey
.exponent
);
3191 hostkey
.exponent
= NULL
;
3195 if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3196 bombout(("Encryption not successfully enabled"));
3200 logevent("Successfully started encryption");
3204 if (!*ssh
->cfg
.username
) {
3205 if (ssh_get_line
&& !ssh_getline_pw_only
) {
3206 if (!ssh_get_line("login as: ",
3207 s
->username
, sizeof(s
->username
), FALSE
)) {
3209 * get_line failed to get a username.
3212 ssh_disconnect(ssh
, "No username provided", NULL
, 0, TRUE
);
3216 int ret
; /* need not be kept over crReturn */
3217 c_write_str(ssh
, "login as: ");
3220 setup_userpass_input(ssh
, s
->username
, sizeof(s
->username
), 1);
3222 crWaitUntil(!pktin
);
3223 ret
= process_userpass_input(ssh
, in
, inlen
);
3227 c_write_str(ssh
, "\r\n");
3230 strncpy(s
->username
, ssh
->cfg
.username
, sizeof(s
->username
));
3231 s
->username
[sizeof(s
->username
)-1] = '\0';
3234 send_packet(ssh
, SSH1_CMSG_USER
, PKT_STR
, s
->username
, PKT_END
);
3236 char userlog
[22 + sizeof(s
->username
)];
3237 sprintf(userlog
, "Sent username \"%s\"", s
->username
);
3239 if (flags
& FLAG_INTERACTIVE
&&
3240 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
3241 strcat(userlog
, "\r\n");
3242 c_write_str(ssh
, userlog
);
3249 if ((ssh
->remote_bugs
& BUG_CHOKES_ON_RSA
)) {
3250 /* We must not attempt PK auth. Pretend we've already tried it. */
3251 s
->tried_publickey
= s
->tried_agent
= 1;
3253 s
->tried_publickey
= s
->tried_agent
= 0;
3255 s
->tis_auth_refused
= s
->ccard_auth_refused
= 0;
3256 /* Load the public half of ssh->cfg.keyfile so we notice if it's in Pageant */
3257 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
3258 if (!rsakey_pubblob(&ssh
->cfg
.keyfile
,
3259 &s
->publickey_blob
, &s
->publickey_bloblen
, NULL
))
3260 s
->publickey_blob
= NULL
;
3262 s
->publickey_blob
= NULL
;
3264 while (pktin
->type
== SSH1_SMSG_FAILURE
) {
3265 s
->pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
3267 if (agent_exists() && !s
->tried_agent
) {
3269 * Attempt RSA authentication using Pageant.
3275 logevent("Pageant is running. Requesting keys.");
3277 /* Request the keys held by the agent. */
3278 PUT_32BIT(s
->request
, 1);
3279 s
->request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
3280 if (!agent_query(s
->request
, 5, &r
, &s
->responselen
,
3281 ssh_agent_callback
, ssh
)) {
3285 bombout(("Unexpected data from server while waiting"
3286 " for agent response"));
3289 } while (pktin
|| inlen
> 0);
3290 r
= ssh
->agent_response
;
3291 s
->responselen
= ssh
->agent_response_len
;
3293 s
->response
= (unsigned char *) r
;
3294 if (s
->response
&& s
->responselen
>= 5 &&
3295 s
->response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
3296 s
->p
= s
->response
+ 5;
3297 s
->nkeys
= GET_32BIT(s
->p
);
3299 logeventf(ssh
, "Pageant has %d SSH-1 keys", s
->nkeys
);
3300 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
3301 logeventf(ssh
, "Trying Pageant key #%d", s
->keyi
);
3302 if (s
->publickey_blob
&&
3303 !memcmp(s
->p
, s
->publickey_blob
,
3304 s
->publickey_bloblen
)) {
3305 logevent("This key matches configured key file");
3306 s
->tried_publickey
= 1;
3311 do { /* do while (0) to make breaking easy */
3312 n
= ssh1_read_bignum
3313 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
3318 n
= ssh1_read_bignum
3319 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
3324 if (s
->responselen
- (s
->p
-s
->response
) < 4)
3326 s
->commentlen
= GET_32BIT(s
->p
);
3328 if (s
->responselen
- (s
->p
-s
->response
) <
3331 s
->commentp
= (char *)s
->p
;
3332 s
->p
+= s
->commentlen
;
3336 logevent("Pageant key list packet was truncated");
3340 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
3341 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
3343 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
3344 logevent("Key refused");
3347 logevent("Received RSA challenge");
3348 if ((s
->challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
3349 bombout(("Server's RSA challenge was badly formatted"));
3354 char *agentreq
, *q
, *ret
;
3357 len
= 1 + 4; /* message type, bit count */
3358 len
+= ssh1_bignum_length(s
->key
.exponent
);
3359 len
+= ssh1_bignum_length(s
->key
.modulus
);
3360 len
+= ssh1_bignum_length(s
->challenge
);
3361 len
+= 16; /* session id */
3362 len
+= 4; /* response format */
3363 agentreq
= snewn(4 + len
, char);
3364 PUT_32BIT(agentreq
, len
);
3366 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
3367 PUT_32BIT(q
, bignum_bitcount(s
->key
.modulus
));
3369 q
+= ssh1_write_bignum(q
, s
->key
.exponent
);
3370 q
+= ssh1_write_bignum(q
, s
->key
.modulus
);
3371 q
+= ssh1_write_bignum(q
, s
->challenge
);
3372 memcpy(q
, s
->session_id
, 16);
3374 PUT_32BIT(q
, 1); /* response format */
3375 if (!agent_query(agentreq
, len
+ 4, &vret
, &retlen
,
3376 ssh_agent_callback
, ssh
)) {
3381 bombout(("Unexpected data from server"
3382 " while waiting for agent"
3386 } while (pktin
|| inlen
> 0);
3387 vret
= ssh
->agent_response
;
3388 retlen
= ssh
->agent_response_len
;
3393 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
3394 logevent("Sending Pageant's response");
3395 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
3396 PKT_DATA
, ret
+ 5, 16,
3400 if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
3402 ("Pageant's response accepted");
3403 if (flags
& FLAG_VERBOSE
) {
3404 c_write_str(ssh
, "Authenticated using"
3406 c_write(ssh
, s
->commentp
,
3408 c_write_str(ssh
, "\" from agent\r\n");
3413 ("Pageant's response not accepted");
3416 ("Pageant failed to answer challenge");
3420 logevent("No reply received from Pageant");
3423 freebn(s
->key
.exponent
);
3424 freebn(s
->key
.modulus
);
3425 freebn(s
->challenge
);
3434 if (!filename_is_null(ssh
->cfg
.keyfile
) && !s
->tried_publickey
)
3435 s
->pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
3437 if (ssh
->cfg
.try_tis_auth
&&
3438 (s
->supported_auths_mask
& (1 << SSH1_AUTH_TIS
)) &&
3439 !s
->tis_auth_refused
) {
3440 s
->pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
3441 logevent("Requested TIS authentication");
3442 send_packet(ssh
, SSH1_CMSG_AUTH_TIS
, PKT_END
);
3444 if (pktin
->type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
3445 logevent("TIS authentication declined");
3446 if (flags
& FLAG_INTERACTIVE
)
3447 c_write_str(ssh
, "TIS authentication refused.\r\n");
3448 s
->tis_auth_refused
= 1;
3454 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
3456 bombout(("TIS challenge packet was badly formed"));
3459 c_write_str(ssh
, "Using TIS authentication.\r\n");
3460 logevent("Received TIS challenge");
3461 if (challengelen
> sizeof(s
->prompt
) - 1)
3462 challengelen
= sizeof(s
->prompt
) - 1;/* prevent overrun */
3463 memcpy(s
->prompt
, challenge
, challengelen
);
3464 /* Prompt heuristic comes from OpenSSH */
3465 strncpy(s
->prompt
+ challengelen
,
3466 memchr(s
->prompt
, '\n', challengelen
) ?
3467 "": "\r\nResponse: ",
3468 (sizeof s
->prompt
) - challengelen
);
3469 s
->prompt
[(sizeof s
->prompt
) - 1] = '\0';
3472 if (ssh
->cfg
.try_tis_auth
&&
3473 (s
->supported_auths_mask
& (1 << SSH1_AUTH_CCARD
)) &&
3474 !s
->ccard_auth_refused
) {
3475 s
->pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
3476 logevent("Requested CryptoCard authentication");
3477 send_packet(ssh
, SSH1_CMSG_AUTH_CCARD
, PKT_END
);
3479 if (pktin
->type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
3480 logevent("CryptoCard authentication declined");
3481 c_write_str(ssh
, "CryptoCard authentication refused.\r\n");
3482 s
->ccard_auth_refused
= 1;
3488 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
3490 bombout(("CryptoCard challenge packet was badly formed"));
3493 c_write_str(ssh
, "Using CryptoCard authentication.\r\n");
3494 logevent("Received CryptoCard challenge");
3495 if (challengelen
> sizeof(s
->prompt
) - 1)
3496 challengelen
= sizeof(s
->prompt
) - 1;/* prevent overrun */
3497 memcpy(s
->prompt
, challenge
, challengelen
);
3498 strncpy(s
->prompt
+ challengelen
,
3499 memchr(s
->prompt
, '\n', challengelen
) ?
3500 "" : "\r\nResponse: ",
3501 sizeof(s
->prompt
) - challengelen
);
3502 s
->prompt
[sizeof(s
->prompt
) - 1] = '\0';
3505 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
3506 sprintf(s
->prompt
, "%.90s@%.90s's password: ",
3507 s
->username
, ssh
->savedhost
);
3509 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
3510 char *comment
= NULL
;
3512 if (flags
& FLAG_VERBOSE
)
3513 c_write_str(ssh
, "Trying public key authentication.\r\n");
3514 logeventf(ssh
, "Trying public key \"%s\"",
3515 filename_to_str(&ssh
->cfg
.keyfile
));
3516 type
= key_type(&ssh
->cfg
.keyfile
);
3517 if (type
!= SSH_KEYTYPE_SSH1
) {
3518 char *msg
= dupprintf("Key is of wrong type (%s)",
3519 key_type_to_str(type
));
3521 c_write_str(ssh
, msg
);
3522 c_write_str(ssh
, "\r\n");
3524 s
->tried_publickey
= 1;
3527 if (!rsakey_encrypted(&ssh
->cfg
.keyfile
, &comment
)) {
3528 if (flags
& FLAG_VERBOSE
)
3529 c_write_str(ssh
, "No passphrase required.\r\n");
3532 sprintf(s
->prompt
, "Passphrase for key \"%.100s\": ", comment
);
3537 * Show password prompt, having first obtained it via a TIS
3538 * or CryptoCard exchange if we're doing TIS or CryptoCard
3542 if (!ssh_get_line(s
->prompt
, s
->password
,
3543 sizeof(s
->password
), TRUE
)) {
3545 * get_line failed to get a password (for example
3546 * because one was supplied on the command line
3547 * which has already failed to work). Terminate.
3549 ssh_disconnect(ssh
, NULL
, "Unable to authenticate", 0, FALSE
);
3553 /* Prompt may have come from server. We've munged it a bit, so
3554 * we know it to be zero-terminated at least once. */
3555 int ret
; /* need not be saved over crReturn */
3556 c_write_untrusted(ssh
, s
->prompt
, strlen(s
->prompt
));
3559 setup_userpass_input(ssh
, s
->password
, sizeof(s
->password
), 0);
3561 crWaitUntil(!pktin
);
3562 ret
= process_userpass_input(ssh
, in
, inlen
);
3566 c_write_str(ssh
, "\r\n");
3570 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
3572 * Try public key authentication with the specified
3575 s
->tried_publickey
= 1;
3578 const char *error
= NULL
;
3579 int ret
= loadrsakey(&ssh
->cfg
.keyfile
, &s
->key
, s
->password
,
3582 c_write_str(ssh
, "Couldn't load private key from ");
3583 c_write_str(ssh
, filename_to_str(&ssh
->cfg
.keyfile
));
3584 c_write_str(ssh
, " (");
3585 c_write_str(ssh
, error
);
3586 c_write_str(ssh
, ").\r\n");
3587 continue; /* go and try password */
3590 c_write_str(ssh
, "Wrong passphrase.\r\n");
3591 s
->tried_publickey
= 0;
3592 continue; /* try again */
3597 * Send a public key attempt.
3599 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
3600 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
3603 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3604 c_write_str(ssh
, "Server refused our public key.\r\n");
3605 continue; /* go and try password */
3607 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
3608 bombout(("Bizarre response to offer of public key"));
3614 unsigned char buffer
[32];
3615 Bignum challenge
, response
;
3617 if ((challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
3618 bombout(("Server's RSA challenge was badly formatted"));
3621 response
= rsadecrypt(challenge
, &s
->key
);
3622 freebn(s
->key
.private_exponent
);/* burn the evidence */
3624 for (i
= 0; i
< 32; i
++) {
3625 buffer
[i
] = bignum_byte(response
, 31 - i
);
3629 MD5Update(&md5c
, buffer
, 32);
3630 MD5Update(&md5c
, s
->session_id
, 16);
3631 MD5Final(buffer
, &md5c
);
3633 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
3634 PKT_DATA
, buffer
, 16, PKT_END
);
3641 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3642 if (flags
& FLAG_VERBOSE
)
3643 c_write_str(ssh
, "Failed to authenticate with"
3644 " our public key.\r\n");
3645 continue; /* go and try password */
3646 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3647 bombout(("Bizarre response to RSA authentication response"));
3651 break; /* we're through! */
3653 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
3655 * Defence against traffic analysis: we send a
3656 * whole bunch of packets containing strings of
3657 * different lengths. One of these strings is the
3658 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3659 * The others are all random data in
3660 * SSH1_MSG_IGNORE packets. This way a passive
3661 * listener can't tell which is the password, and
3662 * hence can't deduce the password length.
3664 * Anybody with a password length greater than 16
3665 * bytes is going to have enough entropy in their
3666 * password that a listener won't find it _that_
3667 * much help to know how long it is. So what we'll
3670 * - if password length < 16, we send 15 packets
3671 * containing string lengths 1 through 15
3673 * - otherwise, we let N be the nearest multiple
3674 * of 8 below the password length, and send 8
3675 * packets containing string lengths N through
3676 * N+7. This won't obscure the order of
3677 * magnitude of the password length, but it will
3678 * introduce a bit of extra uncertainty.
3680 * A few servers (the old 1.2.18 through 1.2.22)
3681 * can't deal with SSH1_MSG_IGNORE. For these
3682 * servers, we need an alternative defence. We make
3683 * use of the fact that the password is interpreted
3684 * as a C string: so we can append a NUL, then some
3687 * One server (a Cisco one) can deal with neither
3688 * SSH1_MSG_IGNORE _nor_ a padded password string.
3689 * For this server we are left with no defences
3690 * against password length sniffing.
3692 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
)) {
3694 * The server can deal with SSH1_MSG_IGNORE, so
3695 * we can use the primary defence.
3697 int bottom
, top
, pwlen
, i
;
3700 pwlen
= strlen(s
->password
);
3702 bottom
= 0; /* zero length passwords are OK! :-) */
3705 bottom
= pwlen
& ~7;
3709 assert(pwlen
>= bottom
&& pwlen
<= top
);
3711 randomstr
= snewn(top
+ 1, char);
3713 for (i
= bottom
; i
<= top
; i
++) {
3715 defer_packet(ssh
, s
->pwpkt_type
,
3716 PKTT_PASSWORD
, PKT_STR
, s
->password
,
3717 PKTT_OTHER
, PKT_END
);
3719 for (j
= 0; j
< i
; j
++) {
3721 randomstr
[j
] = random_byte();
3722 } while (randomstr
[j
] == '\0');
3724 randomstr
[i
] = '\0';
3725 defer_packet(ssh
, SSH1_MSG_IGNORE
,
3726 PKT_STR
, randomstr
, PKT_END
);
3729 logevent("Sending password with camouflage packets");
3730 ssh_pkt_defersend(ssh
);
3733 else if (!(ssh
->remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
3735 * The server can't deal with SSH1_MSG_IGNORE
3736 * but can deal with padded passwords, so we
3737 * can use the secondary defence.
3743 len
= strlen(s
->password
);
3744 if (len
< sizeof(string
)) {
3746 strcpy(string
, s
->password
);
3747 len
++; /* cover the zero byte */
3748 while (len
< sizeof(string
)) {
3749 string
[len
++] = (char) random_byte();
3754 logevent("Sending length-padded password");
3755 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
3756 PKT_INT
, len
, PKT_DATA
, ss
, len
,
3757 PKTT_OTHER
, PKT_END
);
3760 * The server has _both_
3761 * BUG_CHOKES_ON_SSH1_IGNORE and
3762 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
3763 * therefore nothing we can do.
3766 len
= strlen(s
->password
);
3767 logevent("Sending unpadded password");
3768 send_packet(ssh
, s
->pwpkt_type
,
3769 PKTT_PASSWORD
, PKT_INT
, len
,
3770 PKT_DATA
, s
->password
, len
,
3771 PKTT_OTHER
, PKT_END
);
3774 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
3775 PKT_STR
, s
->password
, PKTT_OTHER
, PKT_END
);
3778 logevent("Sent password");
3779 memset(s
->password
, 0, strlen(s
->password
));
3781 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3782 if (flags
& FLAG_VERBOSE
)
3783 c_write_str(ssh
, "Access denied\r\n");
3784 logevent("Authentication refused");
3785 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3786 bombout(("Strange packet received, type %d", pktin
->type
));
3791 logevent("Authentication successful");
3796 void sshfwd_close(struct ssh_channel
*c
)
3800 if (ssh
->state
== SSH_STATE_CLOSED
)
3803 if (c
&& !c
->closes
) {
3805 * If halfopen is true, we have sent
3806 * CHANNEL_OPEN for this channel, but it hasn't even been
3807 * acknowledged by the server. So we must set a close flag
3808 * on it now, and then when the server acks the channel
3809 * open, we can close it then.
3812 if (ssh
->version
== 1) {
3813 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
3816 struct Packet
*pktout
;
3817 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
3818 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
3819 ssh2_pkt_send(ssh
, pktout
);
3822 c
->closes
= 1; /* sent MSG_CLOSE */
3823 if (c
->type
== CHAN_X11
) {
3825 logevent("Forwarded X11 connection terminated");
3826 } else if (c
->type
== CHAN_SOCKDATA
||
3827 c
->type
== CHAN_SOCKDATA_DORMANT
) {
3829 logevent("Forwarded port closed");
3834 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
3838 if (ssh
->state
== SSH_STATE_CLOSED
)
3841 if (ssh
->version
== 1) {
3842 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
3843 PKT_INT
, c
->remoteid
,
3845 PKT_INT
, len
, PKT_DATA
, buf
, len
,
3846 PKTT_OTHER
, PKT_END
);
3848 * In SSH-1 we can return 0 here - implying that forwarded
3849 * connections are never individually throttled - because
3850 * the only circumstance that can cause throttling will be
3851 * the whole SSH connection backing up, in which case
3852 * _everything_ will be throttled as a whole.
3856 ssh2_add_channel_data(c
, buf
, len
);
3857 return ssh2_try_send(c
);
3861 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
3865 if (ssh
->state
== SSH_STATE_CLOSED
)
3868 if (ssh
->version
== 1) {
3869 if (c
->v
.v1
.throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
3870 c
->v
.v1
.throttling
= 0;
3871 ssh1_throttle(ssh
, -1);
3874 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
3878 static void ssh_queueing_handler(Ssh ssh
, struct Packet
*pktin
)
3880 struct queued_handler
*qh
= ssh
->qhead
;
3884 assert(pktin
->type
== qh
->msg1
|| pktin
->type
== qh
->msg2
);
3887 assert(ssh
->packet_dispatch
[qh
->msg1
] == ssh_queueing_handler
);
3888 ssh
->packet_dispatch
[qh
->msg1
] = NULL
;
3891 assert(ssh
->packet_dispatch
[qh
->msg2
] == ssh_queueing_handler
);
3892 ssh
->packet_dispatch
[qh
->msg2
] = NULL
;
3896 ssh
->qhead
= qh
->next
;
3898 if (ssh
->qhead
->msg1
> 0) {
3899 assert(ssh
->packet_dispatch
[ssh
->qhead
->msg1
] == NULL
);
3900 ssh
->packet_dispatch
[ssh
->qhead
->msg1
] = ssh_queueing_handler
;
3902 if (ssh
->qhead
->msg2
> 0) {
3903 assert(ssh
->packet_dispatch
[ssh
->qhead
->msg2
] == NULL
);
3904 ssh
->packet_dispatch
[ssh
->qhead
->msg2
] = ssh_queueing_handler
;
3907 ssh
->qhead
= ssh
->qtail
= NULL
;
3908 ssh
->packet_dispatch
[pktin
->type
] = NULL
;
3911 qh
->handler(ssh
, pktin
, qh
->ctx
);
3916 static void ssh_queue_handler(Ssh ssh
, int msg1
, int msg2
,
3917 chandler_fn_t handler
, void *ctx
)
3919 struct queued_handler
*qh
;
3921 qh
= snew(struct queued_handler
);
3924 qh
->handler
= handler
;
3928 if (ssh
->qtail
== NULL
) {
3932 assert(ssh
->packet_dispatch
[qh
->msg1
] == NULL
);
3933 ssh
->packet_dispatch
[qh
->msg1
] = ssh_queueing_handler
;
3936 assert(ssh
->packet_dispatch
[qh
->msg2
] == NULL
);
3937 ssh
->packet_dispatch
[qh
->msg2
] = ssh_queueing_handler
;
3940 ssh
->qtail
->next
= qh
;
3945 static void ssh_rportfwd_succfail(Ssh ssh
, struct Packet
*pktin
, void *ctx
)
3947 struct ssh_rportfwd
*rpf
, *pf
= (struct ssh_rportfwd
*)ctx
;
3949 if (pktin
->type
== (ssh
->version
== 1 ? SSH1_SMSG_SUCCESS
:
3950 SSH2_MSG_REQUEST_SUCCESS
)) {
3951 logeventf(ssh
, "Remote port forwarding from %s enabled",
3954 logeventf(ssh
, "Remote port forwarding from %s refused",
3957 rpf
= del234(ssh
->rportfwds
, pf
);
3963 static void ssh_setup_portfwd(Ssh ssh
, const Config
*cfg
)
3965 const char *portfwd_strptr
= cfg
->portfwd
;
3966 struct ssh_portfwd
*epf
;
3969 if (!ssh
->portfwds
) {
3970 ssh
->portfwds
= newtree234(ssh_portcmp
);
3973 * Go through the existing port forwardings and tag them
3974 * with status==DESTROY. Any that we want to keep will be
3975 * re-enabled (status==KEEP) as we go through the
3976 * configuration and find out which bits are the same as
3979 struct ssh_portfwd
*epf
;
3981 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
3982 epf
->status
= DESTROY
;
3985 while (*portfwd_strptr
) {
3986 char address_family
, type
;
3987 int sport
,dport
,sserv
,dserv
;
3988 char sports
[256], dports
[256], saddr
[256], host
[256];
3991 address_family
= 'A';
3993 if (*portfwd_strptr
== 'A' ||
3994 *portfwd_strptr
== '4' ||
3995 *portfwd_strptr
== '6')
3996 address_family
= *portfwd_strptr
++;
3997 if (*portfwd_strptr
== 'L' ||
3998 *portfwd_strptr
== 'R' ||
3999 *portfwd_strptr
== 'D')
4000 type
= *portfwd_strptr
++;
4005 while (*portfwd_strptr
&& *portfwd_strptr
!= '\t') {
4006 if (*portfwd_strptr
== ':') {
4008 * We've seen a colon in the middle of the
4009 * source port number. This means that
4010 * everything we've seen until now is the
4011 * source _address_, so we'll move it into
4012 * saddr and start sports from the beginning
4017 if (ssh
->version
== 1 && type
== 'R') {
4018 logeventf(ssh
, "SSH-1 cannot handle remote source address "
4019 "spec \"%s\"; ignoring", sports
);
4021 strcpy(saddr
, sports
);
4024 if (n
< lenof(sports
)-1) sports
[n
++] = *portfwd_strptr
++;
4028 if (*portfwd_strptr
== '\t')
4031 while (*portfwd_strptr
&& *portfwd_strptr
!= ':') {
4032 if (n
< lenof(host
)-1) host
[n
++] = *portfwd_strptr
++;
4035 if (*portfwd_strptr
== ':')
4038 while (*portfwd_strptr
) {
4039 if (n
< lenof(dports
)-1) dports
[n
++] = *portfwd_strptr
++;
4043 dport
= atoi(dports
);
4047 dport
= net_service_lookup(dports
);
4049 logeventf(ssh
, "Service lookup failed for destination"
4050 " port \"%s\"", dports
);
4054 while (*portfwd_strptr
) portfwd_strptr
++;
4058 portfwd_strptr
++; /* eat the NUL and move to next one */
4060 sport
= atoi(sports
);
4064 sport
= net_service_lookup(sports
);
4066 logeventf(ssh
, "Service lookup failed for source"
4067 " port \"%s\"", sports
);
4070 if (sport
&& dport
) {
4071 /* Set up a description of the source port. */
4072 struct ssh_portfwd
*pfrec
, *epfrec
;
4074 pfrec
= snew(struct ssh_portfwd
);
4076 pfrec
->saddr
= *saddr ?
dupstr(saddr
) : NULL
;
4077 pfrec
->sserv
= sserv ?
dupstr(sports
) : NULL
;
4078 pfrec
->sport
= sport
;
4079 pfrec
->daddr
= *host ?
dupstr(host
) : NULL
;
4080 pfrec
->dserv
= dserv ?
dupstr(dports
) : NULL
;
4081 pfrec
->dport
= dport
;
4082 pfrec
->local
= NULL
;
4083 pfrec
->remote
= NULL
;
4084 pfrec
->addressfamily
= (address_family
== '4' ? ADDRTYPE_IPV4
:
4085 address_family
== '6' ? ADDRTYPE_IPV6
:
4088 epfrec
= add234(ssh
->portfwds
, pfrec
);
4089 if (epfrec
!= pfrec
) {
4091 * We already have a port forwarding with precisely
4092 * these parameters. Hence, no need to do anything;
4093 * simply tag the existing one as KEEP.
4095 epfrec
->status
= KEEP
;
4096 free_portfwd(pfrec
);
4098 pfrec
->status
= CREATE
;
4104 * Now go through and destroy any port forwardings which were
4107 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
4108 if (epf
->status
== DESTROY
) {
4111 message
= dupprintf("%s port forwarding from %s%s%d",
4112 epf
->type
== 'L' ?
"local" :
4113 epf
->type
== 'R' ?
"remote" : "dynamic",
4114 epf
->saddr ? epf
->saddr
: "",
4115 epf
->saddr ?
":" : "",
4118 if (epf
->type
!= 'D') {
4119 char *msg2
= dupprintf("%s to %s:%d", message
,
4120 epf
->daddr
, epf
->dport
);
4125 logeventf(ssh
, "Cancelling %s", message
);
4129 struct ssh_rportfwd
*rpf
= epf
->remote
;
4130 struct Packet
*pktout
;
4133 * Cancel the port forwarding at the server
4136 if (ssh
->version
== 1) {
4138 * We cannot cancel listening ports on the
4139 * server side in SSH-1! There's no message
4140 * to support it. Instead, we simply remove
4141 * the rportfwd record from the local end
4142 * so that any connections the server tries
4143 * to make on it are rejected.
4146 pktout
= ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4147 ssh2_pkt_addstring(pktout
, "cancel-tcpip-forward");
4148 ssh2_pkt_addbool(pktout
, 0);/* _don't_ want reply */
4150 ssh2_pkt_addstring(pktout
, epf
->saddr
);
4151 } else if (ssh
->cfg
.rport_acceptall
) {
4152 /* XXX: ssh->cfg.rport_acceptall may not represent
4153 * what was used to open the original connection,
4154 * since it's reconfigurable. */
4155 ssh2_pkt_addstring(pktout
, "0.0.0.0");
4157 ssh2_pkt_addstring(pktout
, "127.0.0.1");
4159 ssh2_pkt_adduint32(pktout
, epf
->sport
);
4160 ssh2_pkt_send(ssh
, pktout
);
4163 del234(ssh
->rportfwds
, rpf
);
4165 } else if (epf
->local
) {
4166 pfd_terminate(epf
->local
);
4169 delpos234(ssh
->portfwds
, i
);
4171 i
--; /* so we don't skip one in the list */
4175 * And finally, set up any new port forwardings (status==CREATE).
4177 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
4178 if (epf
->status
== CREATE
) {
4179 char *sportdesc
, *dportdesc
;
4180 sportdesc
= dupprintf("%s%s%s%s%d%s",
4181 epf
->saddr ? epf
->saddr
: "",
4182 epf
->saddr ?
":" : "",
4183 epf
->sserv ? epf
->sserv
: "",
4184 epf
->sserv ?
"(" : "",
4186 epf
->sserv ?
")" : "");
4187 if (epf
->type
== 'D') {
4190 dportdesc
= dupprintf("%s:%s%s%d%s",
4192 epf
->dserv ? epf
->dserv
: "",
4193 epf
->dserv ?
"(" : "",
4195 epf
->dserv ?
")" : "");
4198 if (epf
->type
== 'L') {
4199 const char *err
= pfd_addforward(epf
->daddr
, epf
->dport
,
4200 epf
->saddr
, epf
->sport
,
4203 epf
->addressfamily
);
4205 logeventf(ssh
, "Local %sport %s forwarding to %s%s%s",
4206 epf
->addressfamily
== ADDRTYPE_IPV4 ?
"IPv4 " :
4207 epf
->addressfamily
== ADDRTYPE_IPV6 ?
"IPv6 " : "",
4208 sportdesc
, dportdesc
,
4209 err ?
" failed: " : "", err ? err
: "");
4210 } else if (epf
->type
== 'D') {
4211 const char *err
= pfd_addforward(NULL
, -1,
4212 epf
->saddr
, epf
->sport
,
4215 epf
->addressfamily
);
4217 logeventf(ssh
, "Local %sport %s SOCKS dynamic forwarding%s%s",
4218 epf
->addressfamily
== ADDRTYPE_IPV4 ?
"IPv4 " :
4219 epf
->addressfamily
== ADDRTYPE_IPV6 ?
"IPv6 " : "",
4221 err ?
" failed: " : "", err ? err
: "");
4223 struct ssh_rportfwd
*pf
;
4226 * Ensure the remote port forwardings tree exists.
4228 if (!ssh
->rportfwds
) {
4229 if (ssh
->version
== 1)
4230 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh1
);
4232 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh2
);
4235 pf
= snew(struct ssh_rportfwd
);
4236 strncpy(pf
->dhost
, epf
->daddr
, lenof(pf
->dhost
)-1);
4237 pf
->dhost
[lenof(pf
->dhost
)-1] = '\0';
4238 pf
->dport
= epf
->dport
;
4239 pf
->sport
= epf
->sport
;
4240 if (add234(ssh
->rportfwds
, pf
) != pf
) {
4241 logeventf(ssh
, "Duplicate remote port forwarding to %s:%d",
4242 epf
->daddr
, epf
->dport
);
4245 logeventf(ssh
, "Requesting remote port %s"
4246 " forward to %s", sportdesc
, dportdesc
);
4248 pf
->sportdesc
= sportdesc
;
4253 if (ssh
->version
== 1) {
4254 send_packet(ssh
, SSH1_CMSG_PORT_FORWARD_REQUEST
,
4255 PKT_INT
, epf
->sport
,
4256 PKT_STR
, epf
->daddr
,
4257 PKT_INT
, epf
->dport
,
4259 ssh_queue_handler(ssh
, SSH1_SMSG_SUCCESS
,
4261 ssh_rportfwd_succfail
, pf
);
4263 struct Packet
*pktout
;
4264 pktout
= ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4265 ssh2_pkt_addstring(pktout
, "tcpip-forward");
4266 ssh2_pkt_addbool(pktout
, 1);/* want reply */
4268 ssh2_pkt_addstring(pktout
, epf
->saddr
);
4269 } else if (cfg
->rport_acceptall
) {
4270 ssh2_pkt_addstring(pktout
, "0.0.0.0");
4272 ssh2_pkt_addstring(pktout
, "127.0.0.1");
4274 ssh2_pkt_adduint32(pktout
, epf
->sport
);
4275 ssh2_pkt_send(ssh
, pktout
);
4277 ssh_queue_handler(ssh
, SSH2_MSG_REQUEST_SUCCESS
,
4278 SSH2_MSG_REQUEST_FAILURE
,
4279 ssh_rportfwd_succfail
, pf
);
4288 static void ssh1_smsg_stdout_stderr_data(Ssh ssh
, struct Packet
*pktin
)
4291 int stringlen
, bufsize
;
4293 ssh_pkt_getstring(pktin
, &string
, &stringlen
);
4294 if (string
== NULL
) {
4295 bombout(("Incoming terminal data packet was badly formed"));
4299 bufsize
= from_backend(ssh
->frontend
, pktin
->type
== SSH1_SMSG_STDERR_DATA
,
4301 if (!ssh
->v1_stdout_throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
4302 ssh
->v1_stdout_throttling
= 1;
4303 ssh1_throttle(ssh
, +1);
4307 static void ssh1_smsg_x11_open(Ssh ssh
, struct Packet
*pktin
)
4309 /* Remote side is trying to open a channel to talk to our
4310 * X-Server. Give them back a local channel number. */
4311 struct ssh_channel
*c
;
4312 int remoteid
= ssh_pkt_getuint32(pktin
);
4314 logevent("Received X11 connect request");
4315 /* Refuse if X11 forwarding is disabled. */
4316 if (!ssh
->X11_fwd_enabled
) {
4317 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4318 PKT_INT
, remoteid
, PKT_END
);
4319 logevent("Rejected X11 connect request");
4321 c
= snew(struct ssh_channel
);
4324 if (x11_init(&c
->u
.x11
.s
, ssh
->cfg
.x11_display
, c
,
4325 ssh
->x11auth
, NULL
, -1, &ssh
->cfg
) != NULL
) {
4326 logevent("Opening X11 forward connection failed");
4328 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4329 PKT_INT
, remoteid
, PKT_END
);
4332 ("Opening X11 forward connection succeeded");
4333 c
->remoteid
= remoteid
;
4334 c
->halfopen
= FALSE
;
4335 c
->localid
= alloc_channel_id(ssh
);
4337 c
->v
.v1
.throttling
= 0;
4338 c
->type
= CHAN_X11
; /* identify channel type */
4339 add234(ssh
->channels
, c
);
4340 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4341 PKT_INT
, c
->remoteid
, PKT_INT
,
4342 c
->localid
, PKT_END
);
4343 logevent("Opened X11 forward channel");
4348 static void ssh1_smsg_agent_open(Ssh ssh
, struct Packet
*pktin
)
4350 /* Remote side is trying to open a channel to talk to our
4351 * agent. Give them back a local channel number. */
4352 struct ssh_channel
*c
;
4353 int remoteid
= ssh_pkt_getuint32(pktin
);
4355 /* Refuse if agent forwarding is disabled. */
4356 if (!ssh
->agentfwd_enabled
) {
4357 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4358 PKT_INT
, remoteid
, PKT_END
);
4360 c
= snew(struct ssh_channel
);
4362 c
->remoteid
= remoteid
;
4363 c
->halfopen
= FALSE
;
4364 c
->localid
= alloc_channel_id(ssh
);
4366 c
->v
.v1
.throttling
= 0;
4367 c
->type
= CHAN_AGENT
; /* identify channel type */
4368 c
->u
.a
.lensofar
= 0;
4369 add234(ssh
->channels
, c
);
4370 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4371 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
4376 static void ssh1_msg_port_open(Ssh ssh
, struct Packet
*pktin
)
4378 /* Remote side is trying to open a channel to talk to a
4379 * forwarded port. Give them back a local channel number. */
4380 struct ssh_channel
*c
;
4381 struct ssh_rportfwd pf
, *pfp
;
4386 c
= snew(struct ssh_channel
);
4389 remoteid
= ssh_pkt_getuint32(pktin
);
4390 ssh_pkt_getstring(pktin
, &host
, &hostsize
);
4391 port
= ssh_pkt_getuint32(pktin
);
4393 if (hostsize
>= lenof(pf
.dhost
))
4394 hostsize
= lenof(pf
.dhost
)-1;
4395 memcpy(pf
.dhost
, host
, hostsize
);
4396 pf
.dhost
[hostsize
] = '\0';
4398 pfp
= find234(ssh
->rportfwds
, &pf
, NULL
);
4401 logeventf(ssh
, "Rejected remote port open request for %s:%d",
4403 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4404 PKT_INT
, remoteid
, PKT_END
);
4406 logeventf(ssh
, "Received remote port open request for %s:%d",
4408 e
= pfd_newconnect(&c
->u
.pfd
.s
, pf
.dhost
, port
,
4409 c
, &ssh
->cfg
, pfp
->pfrec
->addressfamily
);
4411 logeventf(ssh
, "Port open failed: %s", e
);
4413 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4414 PKT_INT
, remoteid
, PKT_END
);
4416 c
->remoteid
= remoteid
;
4417 c
->halfopen
= FALSE
;
4418 c
->localid
= alloc_channel_id(ssh
);
4420 c
->v
.v1
.throttling
= 0;
4421 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
4422 add234(ssh
->channels
, c
);
4423 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4424 PKT_INT
, c
->remoteid
, PKT_INT
,
4425 c
->localid
, PKT_END
);
4426 logevent("Forwarded port opened successfully");
4431 static void ssh1_msg_channel_open_confirmation(Ssh ssh
, struct Packet
*pktin
)
4433 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
4434 unsigned int localid
= ssh_pkt_getuint32(pktin
);
4435 struct ssh_channel
*c
;
4437 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
4438 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
4439 c
->remoteid
= localid
;
4440 c
->halfopen
= FALSE
;
4441 c
->type
= CHAN_SOCKDATA
;
4442 c
->v
.v1
.throttling
= 0;
4443 pfd_confirm(c
->u
.pfd
.s
);
4446 if (c
&& c
->closes
) {
4448 * We have a pending close on this channel,
4449 * which we decided on before the server acked
4450 * the channel open. So now we know the
4451 * remoteid, we can close it again.
4453 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
,
4454 PKT_INT
, c
->remoteid
, PKT_END
);
4458 static void ssh1_msg_channel_open_failure(Ssh ssh
, struct Packet
*pktin
)
4460 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
4461 struct ssh_channel
*c
;
4463 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
4464 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
4465 logevent("Forwarded connection refused by server");
4466 pfd_close(c
->u
.pfd
.s
);
4467 del234(ssh
->channels
, c
);
4472 static void ssh1_msg_channel_close(Ssh ssh
, struct Packet
*pktin
)
4474 /* Remote side closes a channel. */
4475 unsigned i
= ssh_pkt_getuint32(pktin
);
4476 struct ssh_channel
*c
;
4477 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
4478 if (c
&& !c
->halfopen
) {
4481 (pktin
->type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
4483 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
4484 logevent("Forwarded X11 connection terminated");
4485 assert(c
->u
.x11
.s
!= NULL
);
4486 x11_close(c
->u
.x11
.s
);
4489 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
4490 logevent("Forwarded port closed");
4491 assert(c
->u
.pfd
.s
!= NULL
);
4492 pfd_close(c
->u
.pfd
.s
);
4496 c
->closes
|= (closetype
<< 2); /* seen this message */
4497 if (!(c
->closes
& closetype
)) {
4498 send_packet(ssh
, pktin
->type
, PKT_INT
, c
->remoteid
,
4500 c
->closes
|= closetype
; /* sent it too */
4503 if (c
->closes
== 15) {
4504 del234(ssh
->channels
, c
);
4508 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4509 pktin
->type
== SSH1_MSG_CHANNEL_CLOSE ?
"" :
4510 "_CONFIRMATION", c ?
"half-open" : "nonexistent",
4515 static void ssh1_msg_channel_data(Ssh ssh
, struct Packet
*pktin
)
4517 /* Data sent down one of our channels. */
4518 int i
= ssh_pkt_getuint32(pktin
);
4521 struct ssh_channel
*c
;
4523 ssh_pkt_getstring(pktin
, &p
, &len
);
4525 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
4530 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
4533 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
4536 /* Data for an agent message. Buffer it. */
4538 if (c
->u
.a
.lensofar
< 4) {
4539 unsigned int l
= min(4 - c
->u
.a
.lensofar
, len
);
4540 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
4544 c
->u
.a
.lensofar
+= l
;
4546 if (c
->u
.a
.lensofar
== 4) {
4548 4 + GET_32BIT(c
->u
.a
.msglen
);
4549 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
4551 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
4553 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
4555 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
4557 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
4561 c
->u
.a
.lensofar
+= l
;
4563 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
4566 if (agent_query(c
->u
.a
.message
,
4569 ssh_agentf_callback
, c
))
4570 ssh_agentf_callback(c
, reply
, replylen
);
4571 sfree(c
->u
.a
.message
);
4572 c
->u
.a
.lensofar
= 0;
4575 bufsize
= 0; /* agent channels never back up */
4578 if (!c
->v
.v1
.throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
4579 c
->v
.v1
.throttling
= 1;
4580 ssh1_throttle(ssh
, +1);
4585 static void ssh1_smsg_exit_status(Ssh ssh
, struct Packet
*pktin
)
4587 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
4588 logeventf(ssh
, "Server sent command exit status %d", ssh
->exitcode
);
4589 send_packet(ssh
, SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
4591 * In case `helpful' firewalls or proxies tack
4592 * extra human-readable text on the end of the
4593 * session which we might mistake for another
4594 * encrypted packet, we close the session once
4595 * we've sent EXIT_CONFIRMATION.
4597 ssh_disconnect(ssh
, NULL
, NULL
, 0, TRUE
);
4600 /* Helper function to deal with sending tty modes for REQUEST_PTY */
4601 static void ssh1_send_ttymode(void *data
, char *mode
, char *val
)
4603 struct Packet
*pktout
= (struct Packet
*)data
;
4605 unsigned int arg
= 0;
4606 while (strcmp(mode
, ssh_ttymodes
[i
].mode
) != 0) i
++;
4607 if (i
== lenof(ssh_ttymodes
)) return;
4608 switch (ssh_ttymodes
[i
].type
) {
4610 arg
= ssh_tty_parse_specchar(val
);
4613 arg
= ssh_tty_parse_boolean(val
);
4616 ssh2_pkt_addbyte(pktout
, ssh_ttymodes
[i
].opcode
);
4617 ssh2_pkt_addbyte(pktout
, arg
);
4621 static void do_ssh1_connection(Ssh ssh
, unsigned char *in
, int inlen
,
4622 struct Packet
*pktin
)
4624 crBegin(ssh
->do_ssh1_connection_crstate
);
4626 ssh
->packet_dispatch
[SSH1_SMSG_STDOUT_DATA
] =
4627 ssh
->packet_dispatch
[SSH1_SMSG_STDERR_DATA
] =
4628 ssh1_smsg_stdout_stderr_data
;
4630 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
] =
4631 ssh1_msg_channel_open_confirmation
;
4632 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_OPEN_FAILURE
] =
4633 ssh1_msg_channel_open_failure
;
4634 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_CLOSE
] =
4635 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
] =
4636 ssh1_msg_channel_close
;
4637 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_DATA
] = ssh1_msg_channel_data
;
4638 ssh
->packet_dispatch
[SSH1_SMSG_EXIT_STATUS
] = ssh1_smsg_exit_status
;
4640 if (ssh
->cfg
.agentfwd
&& agent_exists()) {
4641 logevent("Requesting agent forwarding");
4642 send_packet(ssh
, SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
4646 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4647 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4648 bombout(("Protocol confusion"));
4650 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4651 logevent("Agent forwarding refused");
4653 logevent("Agent forwarding enabled");
4654 ssh
->agentfwd_enabled
= TRUE
;
4655 ssh
->packet_dispatch
[SSH1_SMSG_AGENT_OPEN
] = ssh1_smsg_agent_open
;
4659 if (ssh
->cfg
.x11_forward
) {
4660 char proto
[20], data
[64];
4661 logevent("Requesting X11 forwarding");
4662 ssh
->x11auth
= x11_invent_auth(proto
, sizeof(proto
),
4663 data
, sizeof(data
), ssh
->cfg
.x11_auth
);
4664 x11_get_real_auth(ssh
->x11auth
, ssh
->cfg
.x11_display
);
4666 * Note that while we blank the X authentication data here, we don't
4667 * take any special action to blank the start of an X11 channel,
4668 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
4669 * without having session blanking enabled is likely to leak your
4670 * cookie into the log.
4672 if (ssh
->v1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
4673 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
4675 PKTT_PASSWORD
, PKT_STR
, data
, PKTT_OTHER
,
4676 PKT_INT
, x11_get_screen_number(ssh
->cfg
.x11_display
),
4679 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
4681 PKTT_PASSWORD
, PKT_STR
, data
, PKTT_OTHER
, PKT_END
);
4686 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4687 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4688 bombout(("Protocol confusion"));
4690 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4691 logevent("X11 forwarding refused");
4693 logevent("X11 forwarding enabled");
4694 ssh
->X11_fwd_enabled
= TRUE
;
4695 ssh
->packet_dispatch
[SSH1_SMSG_X11_OPEN
] = ssh1_smsg_x11_open
;
4699 ssh_setup_portfwd(ssh
, &ssh
->cfg
);
4700 ssh
->packet_dispatch
[SSH1_MSG_PORT_OPEN
] = ssh1_msg_port_open
;
4702 if (!ssh
->cfg
.nopty
) {
4704 /* Unpick the terminal-speed string. */
4705 /* XXX perhaps we should allow no speeds to be sent. */
4706 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
4707 sscanf(ssh
->cfg
.termspeed
, "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
4708 /* Send the pty request. */
4709 pkt
= ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY
);
4710 ssh_pkt_addstring(pkt
, ssh
->cfg
.termtype
);
4711 ssh_pkt_adduint32(pkt
, ssh
->term_height
);
4712 ssh_pkt_adduint32(pkt
, ssh
->term_width
);
4713 ssh_pkt_adduint32(pkt
, 0); /* width in pixels */
4714 ssh_pkt_adduint32(pkt
, 0); /* height in pixels */
4715 parse_ttymodes(ssh
, ssh
->cfg
.ttymodes
,
4716 ssh1_send_ttymode
, (void *)pkt
);
4717 ssh_pkt_addbyte(pkt
, SSH1_TTY_OP_ISPEED
);
4718 ssh_pkt_adduint32(pkt
, ssh
->ispeed
);
4719 ssh_pkt_addbyte(pkt
, SSH1_TTY_OP_OSPEED
);
4720 ssh_pkt_adduint32(pkt
, ssh
->ospeed
);
4721 ssh_pkt_addbyte(pkt
, SSH_TTY_OP_END
);
4723 ssh
->state
= SSH_STATE_INTERMED
;
4727 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4728 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4729 bombout(("Protocol confusion"));
4731 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4732 c_write_str(ssh
, "Server refused to allocate pty\r\n");
4733 ssh
->editing
= ssh
->echoing
= 1;
4735 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
4736 ssh
->ospeed
, ssh
->ispeed
);
4738 ssh
->editing
= ssh
->echoing
= 1;
4741 if (ssh
->cfg
.compression
) {
4742 send_packet(ssh
, SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
4746 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4747 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4748 bombout(("Protocol confusion"));
4750 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4751 c_write_str(ssh
, "Server refused to compress\r\n");
4753 logevent("Started compression");
4754 ssh
->v1_compressing
= TRUE
;
4755 ssh
->cs_comp_ctx
= zlib_compress_init();
4756 logevent("Initialised zlib (RFC1950) compression");
4757 ssh
->sc_comp_ctx
= zlib_decompress_init();
4758 logevent("Initialised zlib (RFC1950) decompression");
4762 * Start the shell or command.
4764 * Special case: if the first-choice command is an SSH-2
4765 * subsystem (hence not usable here) and the second choice
4766 * exists, we fall straight back to that.
4769 char *cmd
= ssh
->cfg
.remote_cmd_ptr
;
4771 if (!cmd
) cmd
= ssh
->cfg
.remote_cmd
;
4773 if (ssh
->cfg
.ssh_subsys
&& ssh
->cfg
.remote_cmd_ptr2
) {
4774 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
4775 ssh
->fallback_cmd
= TRUE
;
4778 send_packet(ssh
, SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
4780 send_packet(ssh
, SSH1_CMSG_EXEC_SHELL
, PKT_END
);
4781 logevent("Started session");
4784 ssh
->state
= SSH_STATE_SESSION
;
4785 if (ssh
->size_needed
)
4786 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
4787 if (ssh
->eof_needed
)
4788 ssh_special(ssh
, TS_EOF
);
4791 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
4793 ssh
->channels
= newtree234(ssh_channelcmp
);
4797 * By this point, most incoming packets are already being
4798 * handled by the dispatch table, and we need only pay
4799 * attention to the unusual ones.
4804 if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
4805 /* may be from EXEC_SHELL on some servers */
4806 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4807 /* may be from EXEC_SHELL on some servers
4808 * if no pty is available or in other odd cases. Ignore */
4810 bombout(("Strange packet received: type %d", pktin
->type
));
4815 int len
= min(inlen
, 512);
4816 send_packet(ssh
, SSH1_CMSG_STDIN_DATA
, PKTT_DATA
,
4817 PKT_INT
, len
, PKT_DATA
, in
, len
,
4818 PKTT_OTHER
, PKT_END
);
4829 * Handle the top-level SSH-2 protocol.
4831 static void ssh1_msg_debug(Ssh ssh
, struct Packet
*pktin
)
4836 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
4837 logeventf(ssh
, "Remote debug message: %.*s", msglen
, msg
);
4840 static void ssh1_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
4842 /* log reason code in disconnect message */
4846 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
4847 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen
, msg
));
4850 static void ssh_msg_ignore(Ssh ssh
, struct Packet
*pktin
)
4852 /* Do nothing, because we're ignoring it! Duhh. */
4855 static void ssh1_protocol_setup(Ssh ssh
)
4860 * Most messages are handled by the coroutines.
4862 for (i
= 0; i
< 256; i
++)
4863 ssh
->packet_dispatch
[i
] = NULL
;
4866 * These special message types we install handlers for.
4868 ssh
->packet_dispatch
[SSH1_MSG_DISCONNECT
] = ssh1_msg_disconnect
;
4869 ssh
->packet_dispatch
[SSH1_MSG_IGNORE
] = ssh_msg_ignore
;
4870 ssh
->packet_dispatch
[SSH1_MSG_DEBUG
] = ssh1_msg_debug
;
4873 static void ssh1_protocol(Ssh ssh
, void *vin
, int inlen
,
4874 struct Packet
*pktin
)
4876 unsigned char *in
=(unsigned char*)vin
;
4877 if (ssh
->state
== SSH_STATE_CLOSED
)
4880 if (pktin
&& ssh
->packet_dispatch
[pktin
->type
]) {
4881 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
4885 if (!ssh
->protocol_initial_phase_done
) {
4886 if (do_ssh1_login(ssh
, in
, inlen
, pktin
))
4887 ssh
->protocol_initial_phase_done
= TRUE
;
4892 do_ssh1_connection(ssh
, in
, inlen
, pktin
);
4896 * Utility routine for decoding comma-separated strings in KEXINIT.
4898 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
4901 if (!needle
|| !haystack
) /* protect against null pointers */
4903 needlen
= strlen(needle
);
4906 * Is it at the start of the string?
4908 if (haylen
>= needlen
&& /* haystack is long enough */
4909 !memcmp(needle
, haystack
, needlen
) && /* initial match */
4910 (haylen
== needlen
|| haystack
[needlen
] == ',')
4911 /* either , or EOS follows */
4915 * If not, search for the next comma and resume after that.
4916 * If no comma found, terminate.
4918 while (haylen
> 0 && *haystack
!= ',')
4919 haylen
--, haystack
++;
4922 haylen
--, haystack
++; /* skip over comma itself */
4927 * Similar routine for checking whether we have the first string in a list.
4929 static int first_in_commasep_string(char *needle
, char *haystack
, int haylen
)
4932 if (!needle
|| !haystack
) /* protect against null pointers */
4934 needlen
= strlen(needle
);
4936 * Is it at the start of the string?
4938 if (haylen
>= needlen
&& /* haystack is long enough */
4939 !memcmp(needle
, haystack
, needlen
) && /* initial match */
4940 (haylen
== needlen
|| haystack
[needlen
] == ',')
4941 /* either , or EOS follows */
4949 * SSH-2 key creation method.
4951 static void ssh2_mkkey(Ssh ssh
, Bignum K
, unsigned char *H
, char chr
,
4952 unsigned char *keyspace
)
4954 const struct ssh_hash
*h
= ssh
->kex
->hash
;
4956 /* First hlen bytes. */
4958 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
4959 hash_mpint(h
, s
, K
);
4960 h
->bytes(s
, H
, h
->hlen
);
4961 h
->bytes(s
, &chr
, 1);
4962 h
->bytes(s
, ssh
->v2_session_id
, ssh
->v2_session_id_len
);
4963 h
->final(s
, keyspace
);
4964 /* Next hlen bytes. */
4966 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
4967 hash_mpint(h
, s
, K
);
4968 h
->bytes(s
, H
, h
->hlen
);
4969 h
->bytes(s
, keyspace
, h
->hlen
);
4970 h
->final(s
, keyspace
+ h
->hlen
);
4974 * Handle the SSH-2 transport layer.
4976 static int do_ssh2_transport(Ssh ssh
, void *vin
, int inlen
,
4977 struct Packet
*pktin
)
4979 unsigned char *in
= (unsigned char *)vin
;
4980 struct do_ssh2_transport_state
{
4981 int nbits
, pbits
, warn_kex
, warn_cscipher
, warn_sccipher
;
4982 Bignum p
, g
, e
, f
, K
;
4985 int kex_init_value
, kex_reply_value
;
4986 const struct ssh_mac
**maclist
;
4988 const struct ssh2_cipher
*cscipher_tobe
;
4989 const struct ssh2_cipher
*sccipher_tobe
;
4990 const struct ssh_mac
*csmac_tobe
;
4991 const struct ssh_mac
*scmac_tobe
;
4992 const struct ssh_compress
*cscomp_tobe
;
4993 const struct ssh_compress
*sccomp_tobe
;
4994 char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
4995 int hostkeylen
, siglen
;
4996 void *hkey
; /* actual host key */
4997 unsigned char exchange_hash
[20];
4998 int n_preferred_kex
;
4999 const struct ssh_kex
*preferred_kex
[KEX_MAX
];
5000 int n_preferred_ciphers
;
5001 const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
5002 const struct ssh_compress
*preferred_comp
;
5003 int got_session_id
, activated_authconn
;
5004 struct Packet
*pktout
;
5009 crState(do_ssh2_transport_state
);
5011 crBegin(ssh
->do_ssh2_transport_crstate
);
5013 s
->cscipher_tobe
= s
->sccipher_tobe
= NULL
;
5014 s
->csmac_tobe
= s
->scmac_tobe
= NULL
;
5015 s
->cscomp_tobe
= s
->sccomp_tobe
= NULL
;
5017 s
->got_session_id
= s
->activated_authconn
= FALSE
;
5020 * Be prepared to work around the buggy MAC problem.
5022 if (ssh
->remote_bugs
& BUG_SSH2_HMAC
)
5023 s
->maclist
= buggymacs
, s
->nmacs
= lenof(buggymacs
);
5025 s
->maclist
= macs
, s
->nmacs
= lenof(macs
);
5028 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_KEX_MASK
;
5030 int i
, j
, commalist_started
;
5033 * Set up the preferred key exchange. (NULL => warn below here)
5035 s
->n_preferred_kex
= 0;
5036 for (i
= 0; i
< KEX_MAX
; i
++) {
5037 switch (ssh
->cfg
.ssh_kexlist
[i
]) {
5039 s
->preferred_kex
[s
->n_preferred_kex
++] =
5040 &ssh_diffiehellman_gex
;
5043 s
->preferred_kex
[s
->n_preferred_kex
++] =
5044 &ssh_diffiehellman_group14
;
5047 s
->preferred_kex
[s
->n_preferred_kex
++] =
5048 &ssh_diffiehellman_group1
;
5051 /* Flag for later. Don't bother if it's the last in
5053 if (i
< KEX_MAX
- 1) {
5054 s
->preferred_kex
[s
->n_preferred_kex
++] = NULL
;
5061 * Set up the preferred ciphers. (NULL => warn below here)
5063 s
->n_preferred_ciphers
= 0;
5064 for (i
= 0; i
< CIPHER_MAX
; i
++) {
5065 switch (ssh
->cfg
.ssh_cipherlist
[i
]) {
5066 case CIPHER_BLOWFISH
:
5067 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_blowfish
;
5070 if (ssh
->cfg
.ssh2_des_cbc
) {
5071 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_des
;
5075 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_3des
;
5078 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_aes
;
5080 case CIPHER_ARCFOUR
:
5081 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_arcfour
;
5084 /* Flag for later. Don't bother if it's the last in
5086 if (i
< CIPHER_MAX
- 1) {
5087 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = NULL
;
5094 * Set up preferred compression.
5096 if (ssh
->cfg
.compression
)
5097 s
->preferred_comp
= &ssh_zlib
;
5099 s
->preferred_comp
= &ssh_comp_none
;
5102 * Enable queueing of outgoing auth- or connection-layer
5103 * packets while we are in the middle of a key exchange.
5105 ssh
->queueing
= TRUE
;
5108 * Flag that KEX is in progress.
5110 ssh
->kex_in_progress
= TRUE
;
5113 * Construct and send our key exchange packet.
5115 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEXINIT
);
5116 for (i
= 0; i
< 16; i
++)
5117 ssh2_pkt_addbyte(s
->pktout
, (unsigned char) random_byte());
5118 /* List key exchange algorithms. */
5119 ssh2_pkt_addstring_start(s
->pktout
);
5120 commalist_started
= 0;
5121 for (i
= 0; i
< s
->n_preferred_kex
; i
++) {
5122 const struct ssh_kex
*k
= s
->preferred_kex
[i
];
5123 if (!k
) continue; /* warning flag */
5124 if (commalist_started
)
5125 ssh2_pkt_addstring_str(s
->pktout
, ",");
5126 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_kex
[i
]->name
);
5127 commalist_started
= 1;
5129 /* List server host key algorithms. */
5130 ssh2_pkt_addstring_start(s
->pktout
);
5131 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
5132 ssh2_pkt_addstring_str(s
->pktout
, hostkey_algs
[i
]->name
);
5133 if (i
< lenof(hostkey_algs
) - 1)
5134 ssh2_pkt_addstring_str(s
->pktout
, ",");
5136 /* List client->server encryption algorithms. */
5137 ssh2_pkt_addstring_start(s
->pktout
);
5138 commalist_started
= 0;
5139 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5140 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5141 if (!c
) continue; /* warning flag */
5142 for (j
= 0; j
< c
->nciphers
; j
++) {
5143 if (commalist_started
)
5144 ssh2_pkt_addstring_str(s
->pktout
, ",");
5145 ssh2_pkt_addstring_str(s
->pktout
, c
->list
[j
]->name
);
5146 commalist_started
= 1;
5149 /* List server->client encryption algorithms. */
5150 ssh2_pkt_addstring_start(s
->pktout
);
5151 commalist_started
= 0;
5152 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5153 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5154 if (!c
) continue; /* warning flag */
5155 for (j
= 0; j
< c
->nciphers
; j
++) {
5156 if (commalist_started
)
5157 ssh2_pkt_addstring_str(s
->pktout
, ",");
5158 ssh2_pkt_addstring_str(s
->pktout
, c
->list
[j
]->name
);
5159 commalist_started
= 1;
5162 /* List client->server MAC algorithms. */
5163 ssh2_pkt_addstring_start(s
->pktout
);
5164 for (i
= 0; i
< s
->nmacs
; i
++) {
5165 ssh2_pkt_addstring_str(s
->pktout
, s
->maclist
[i
]->name
);
5166 if (i
< s
->nmacs
- 1)
5167 ssh2_pkt_addstring_str(s
->pktout
, ",");
5169 /* List server->client MAC algorithms. */
5170 ssh2_pkt_addstring_start(s
->pktout
);
5171 for (i
= 0; i
< s
->nmacs
; i
++) {
5172 ssh2_pkt_addstring_str(s
->pktout
, s
->maclist
[i
]->name
);
5173 if (i
< s
->nmacs
- 1)
5174 ssh2_pkt_addstring_str(s
->pktout
, ",");
5176 /* List client->server compression algorithms. */
5177 ssh2_pkt_addstring_start(s
->pktout
);
5178 assert(lenof(compressions
) > 1);
5179 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_comp
->name
);
5180 for (i
= 0; i
< lenof(compressions
); i
++) {
5181 const struct ssh_compress
*c
= compressions
[i
];
5182 if (c
!= s
->preferred_comp
) {
5183 ssh2_pkt_addstring_str(s
->pktout
, ",");
5184 ssh2_pkt_addstring_str(s
->pktout
, c
->name
);
5187 /* List server->client compression algorithms. */
5188 ssh2_pkt_addstring_start(s
->pktout
);
5189 assert(lenof(compressions
) > 1);
5190 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_comp
->name
);
5191 for (i
= 0; i
< lenof(compressions
); i
++) {
5192 const struct ssh_compress
*c
= compressions
[i
];
5193 if (c
!= s
->preferred_comp
) {
5194 ssh2_pkt_addstring_str(s
->pktout
, ",");
5195 ssh2_pkt_addstring_str(s
->pktout
, c
->name
);
5198 /* List client->server languages. Empty list. */
5199 ssh2_pkt_addstring_start(s
->pktout
);
5200 /* List server->client languages. Empty list. */
5201 ssh2_pkt_addstring_start(s
->pktout
);
5202 /* First KEX packet does _not_ follow, because we're not that brave. */
5203 ssh2_pkt_addbool(s
->pktout
, FALSE
);
5205 ssh2_pkt_adduint32(s
->pktout
, 0);
5208 s
->our_kexinitlen
= s
->pktout
->length
- 5;
5209 s
->our_kexinit
= snewn(s
->our_kexinitlen
, unsigned char);
5210 memcpy(s
->our_kexinit
, s
->pktout
->data
+ 5, s
->our_kexinitlen
);
5212 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5218 * Now examine the other side's KEXINIT to see what we're up
5222 char *str
, *preferred
;
5225 if (pktin
->type
!= SSH2_MSG_KEXINIT
) {
5226 bombout(("expected key exchange packet from server"));
5230 ssh
->hostkey
= NULL
;
5231 s
->cscipher_tobe
= NULL
;
5232 s
->sccipher_tobe
= NULL
;
5233 s
->csmac_tobe
= NULL
;
5234 s
->scmac_tobe
= NULL
;
5235 s
->cscomp_tobe
= NULL
;
5236 s
->sccomp_tobe
= NULL
;
5237 s
->warn_kex
= s
->warn_cscipher
= s
->warn_sccipher
= FALSE
;
5239 pktin
->savedpos
+= 16; /* skip garbage cookie */
5240 ssh_pkt_getstring(pktin
, &str
, &len
); /* key exchange algorithms */
5243 for (i
= 0; i
< s
->n_preferred_kex
; i
++) {
5244 const struct ssh_kex
*k
= s
->preferred_kex
[i
];
5248 if (!preferred
) preferred
= k
->name
;
5249 if (in_commasep_string(k
->name
, str
, len
))
5256 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5257 str ? str
: "(null)"));
5261 * Note that the server's guess is considered wrong if it doesn't match
5262 * the first algorithm in our list, even if it's still the algorithm
5265 s
->guessok
= first_in_commasep_string(preferred
, str
, len
);
5266 ssh_pkt_getstring(pktin
, &str
, &len
); /* host key algorithms */
5267 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
5268 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
5269 ssh
->hostkey
= hostkey_algs
[i
];
5273 s
->guessok
= s
->guessok
&&
5274 first_in_commasep_string(hostkey_algs
[0]->name
, str
, len
);
5275 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server cipher */
5276 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5277 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5279 s
->warn_cscipher
= TRUE
;
5281 for (j
= 0; j
< c
->nciphers
; j
++) {
5282 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
5283 s
->cscipher_tobe
= c
->list
[j
];
5288 if (s
->cscipher_tobe
)
5291 if (!s
->cscipher_tobe
) {
5292 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5293 str ? str
: "(null)"));
5297 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client cipher */
5298 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5299 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5301 s
->warn_sccipher
= TRUE
;
5303 for (j
= 0; j
< c
->nciphers
; j
++) {
5304 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
5305 s
->sccipher_tobe
= c
->list
[j
];
5310 if (s
->sccipher_tobe
)
5313 if (!s
->sccipher_tobe
) {
5314 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5315 str ? str
: "(null)"));
5319 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server mac */
5320 for (i
= 0; i
< s
->nmacs
; i
++) {
5321 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
5322 s
->csmac_tobe
= s
->maclist
[i
];
5326 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client mac */
5327 for (i
= 0; i
< s
->nmacs
; i
++) {
5328 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
5329 s
->scmac_tobe
= s
->maclist
[i
];
5333 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server compression */
5334 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
5335 const struct ssh_compress
*c
=
5336 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
5337 if (in_commasep_string(c
->name
, str
, len
)) {
5342 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client compression */
5343 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
5344 const struct ssh_compress
*c
=
5345 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
5346 if (in_commasep_string(c
->name
, str
, len
)) {
5351 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server language */
5352 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client language */
5353 s
->ignorepkt
= ssh2_pkt_getbool(pktin
) && !s
->guessok
;
5356 ssh_set_frozen(ssh
, 1);
5357 s
->dlgret
= askalg(ssh
->frontend
, "key-exchange algorithm",
5359 ssh_dialog_callback
, ssh
);
5360 if (s
->dlgret
< 0) {
5364 bombout(("Unexpected data from server while"
5365 " waiting for user response"));
5368 } while (pktin
|| inlen
> 0);
5369 s
->dlgret
= ssh
->user_response
;
5371 ssh_set_frozen(ssh
, 0);
5372 if (s
->dlgret
== 0) {
5373 ssh_disconnect(ssh
, "User aborted at kex warning", NULL
,
5379 if (s
->warn_cscipher
) {
5380 ssh_set_frozen(ssh
, 1);
5381 s
->dlgret
= askalg(ssh
->frontend
,
5382 "client-to-server cipher",
5383 s
->cscipher_tobe
->name
,
5384 ssh_dialog_callback
, ssh
);
5385 if (s
->dlgret
< 0) {
5389 bombout(("Unexpected data from server while"
5390 " waiting for user response"));
5393 } while (pktin
|| inlen
> 0);
5394 s
->dlgret
= ssh
->user_response
;
5396 ssh_set_frozen(ssh
, 0);
5397 if (s
->dlgret
== 0) {
5398 ssh_disconnect(ssh
, "User aborted at cipher warning", NULL
,
5404 if (s
->warn_sccipher
) {
5405 ssh_set_frozen(ssh
, 1);
5406 s
->dlgret
= askalg(ssh
->frontend
,
5407 "server-to-client cipher",
5408 s
->sccipher_tobe
->name
,
5409 ssh_dialog_callback
, ssh
);
5410 if (s
->dlgret
< 0) {
5414 bombout(("Unexpected data from server while"
5415 " waiting for user response"));
5418 } while (pktin
|| inlen
> 0);
5419 s
->dlgret
= ssh
->user_response
;
5421 ssh_set_frozen(ssh
, 0);
5422 if (s
->dlgret
== 0) {
5423 ssh_disconnect(ssh
, "User aborted at cipher warning", NULL
,
5429 ssh
->exhash
= ssh
->kex
->hash
->init();
5430 hash_string(ssh
->kex
->hash
, ssh
->exhash
, ssh
->v_c
, strlen(ssh
->v_c
));
5431 hash_string(ssh
->kex
->hash
, ssh
->exhash
, ssh
->v_s
, strlen(ssh
->v_s
));
5432 hash_string(ssh
->kex
->hash
, ssh
->exhash
,
5433 s
->our_kexinit
, s
->our_kexinitlen
);
5434 sfree(s
->our_kexinit
);
5435 if (pktin
->length
> 5)
5436 hash_string(ssh
->kex
->hash
, ssh
->exhash
,
5437 pktin
->data
+ 5, pktin
->length
- 5);
5439 if (s
->ignorepkt
) /* first_kex_packet_follows */
5440 crWaitUntil(pktin
); /* Ignore packet */
5444 * Work out the number of bits of key we will need from the key
5445 * exchange. We start with the maximum key length of either
5451 csbits
= s
->cscipher_tobe
->keylen
;
5452 scbits
= s
->sccipher_tobe
->keylen
;
5453 s
->nbits
= (csbits
> scbits ? csbits
: scbits
);
5455 /* The keys only have hlen-bit entropy, since they're based on
5456 * a hash. So cap the key size at hlen bits. */
5457 if (s
->nbits
> ssh
->kex
->hash
->hlen
* 8)
5458 s
->nbits
= ssh
->kex
->hash
->hlen
* 8;
5461 * If we're doing Diffie-Hellman group exchange, start by
5462 * requesting a group.
5464 if (!ssh
->kex
->pdata
) {
5465 logevent("Doing Diffie-Hellman group exchange");
5466 ssh
->pkt_ctx
|= SSH2_PKTCTX_DHGEX
;
5468 * Work out how big a DH group we will need to allow that
5471 s
->pbits
= 512 << ((s
->nbits
- 1) / 64);
5472 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
5473 ssh2_pkt_adduint32(s
->pktout
, s
->pbits
);
5474 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5477 if (pktin
->type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
5478 bombout(("expected key exchange group packet from server"));
5481 s
->p
= ssh2_pkt_getmp(pktin
);
5482 s
->g
= ssh2_pkt_getmp(pktin
);
5483 if (!s
->p
|| !s
->g
) {
5484 bombout(("unable to read mp-ints from incoming group packet"));
5487 ssh
->kex_ctx
= dh_setup_gex(s
->p
, s
->g
);
5488 s
->kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
5489 s
->kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
5491 ssh
->pkt_ctx
|= SSH2_PKTCTX_DHGROUP
;
5492 ssh
->kex_ctx
= dh_setup_group(ssh
->kex
);
5493 s
->kex_init_value
= SSH2_MSG_KEXDH_INIT
;
5494 s
->kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
5495 logeventf(ssh
, "Using Diffie-Hellman with standard group \"%s\"",
5496 ssh
->kex
->groupname
);
5499 logevent("Doing Diffie-Hellman key exchange");
5501 * Now generate and send e for Diffie-Hellman.
5503 set_busy_status(ssh
->frontend
, BUSY_CPU
); /* this can take a while */
5504 s
->e
= dh_create_e(ssh
->kex_ctx
, s
->nbits
* 2);
5505 s
->pktout
= ssh2_pkt_init(s
->kex_init_value
);
5506 ssh2_pkt_addmp(s
->pktout
, s
->e
);
5507 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5509 set_busy_status(ssh
->frontend
, BUSY_WAITING
); /* wait for server */
5511 if (pktin
->type
!= s
->kex_reply_value
) {
5512 bombout(("expected key exchange reply packet from server"));
5515 set_busy_status(ssh
->frontend
, BUSY_CPU
); /* cogitate */
5516 ssh_pkt_getstring(pktin
, &s
->hostkeydata
, &s
->hostkeylen
);
5517 s
->f
= ssh2_pkt_getmp(pktin
);
5519 bombout(("unable to parse key exchange reply packet"));
5522 ssh_pkt_getstring(pktin
, &s
->sigdata
, &s
->siglen
);
5524 s
->K
= dh_find_K(ssh
->kex_ctx
, s
->f
);
5526 /* We assume everything from now on will be quick, and it might
5527 * involve user interaction. */
5528 set_busy_status(ssh
->frontend
, BUSY_NOT
);
5530 hash_string(ssh
->kex
->hash
, ssh
->exhash
, s
->hostkeydata
, s
->hostkeylen
);
5531 if (ssh
->kex
== &ssh_diffiehellman_gex
) {
5532 hash_uint32(ssh
->kex
->hash
, ssh
->exhash
, s
->pbits
);
5533 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->p
);
5534 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->g
);
5536 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->e
);
5537 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->f
);
5538 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->K
);
5539 assert(ssh
->kex
->hash
->hlen
<= sizeof(s
->exchange_hash
));
5540 ssh
->kex
->hash
->final(ssh
->exhash
, s
->exchange_hash
);
5542 dh_cleanup(ssh
->kex_ctx
);
5543 ssh
->kex_ctx
= NULL
;
5546 debug(("Exchange hash is:\n"));
5547 dmemdump(s
->exchange_hash
, ssh
->kex
->hash
->hlen
);
5550 s
->hkey
= ssh
->hostkey
->newkey(s
->hostkeydata
, s
->hostkeylen
);
5552 !ssh
->hostkey
->verifysig(s
->hkey
, s
->sigdata
, s
->siglen
,
5553 (char *)s
->exchange_hash
,
5554 ssh
->kex
->hash
->hlen
)) {
5555 bombout(("Server's host key did not match the signature supplied"));
5560 * Authenticate remote host: verify host key. (We've already
5561 * checked the signature of the exchange hash.)
5563 s
->keystr
= ssh
->hostkey
->fmtkey(s
->hkey
);
5564 s
->fingerprint
= ssh
->hostkey
->fingerprint(s
->hkey
);
5565 ssh_set_frozen(ssh
, 1);
5566 s
->dlgret
= verify_ssh_host_key(ssh
->frontend
,
5567 ssh
->savedhost
, ssh
->savedport
,
5568 ssh
->hostkey
->keytype
, s
->keystr
,
5570 ssh_dialog_callback
, ssh
);
5571 if (s
->dlgret
< 0) {
5575 bombout(("Unexpected data from server while waiting"
5576 " for user host key response"));
5579 } while (pktin
|| inlen
> 0);
5580 s
->dlgret
= ssh
->user_response
;
5582 ssh_set_frozen(ssh
, 0);
5583 if (s
->dlgret
== 0) {
5584 ssh_disconnect(ssh
, "User aborted at host key verification", NULL
,
5588 if (!s
->got_session_id
) { /* don't bother logging this in rekeys */
5589 logevent("Host key fingerprint is:");
5590 logevent(s
->fingerprint
);
5592 sfree(s
->fingerprint
);
5594 ssh
->hostkey
->freekey(s
->hkey
);
5597 * The exchange hash from the very first key exchange is also
5598 * the session id, used in session key construction and
5601 if (!s
->got_session_id
) {
5602 assert(sizeof(s
->exchange_hash
) <= sizeof(ssh
->v2_session_id
));
5603 memcpy(ssh
->v2_session_id
, s
->exchange_hash
,
5604 sizeof(s
->exchange_hash
));
5605 assert(ssh
->v2_session_id_len
<= sizeof(ssh
->v2_session_id
));
5606 ssh
->v2_session_id_len
= ssh
->kex
->hash
->hlen
;
5607 s
->got_session_id
= TRUE
;
5611 * Send SSH2_MSG_NEWKEYS.
5613 s
->pktout
= ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
5614 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5615 ssh
->outgoing_data_size
= 0; /* start counting from here */
5618 * We've sent client NEWKEYS, so create and initialise
5619 * client-to-server session keys.
5621 if (ssh
->cs_cipher_ctx
)
5622 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
5623 ssh
->cscipher
= s
->cscipher_tobe
;
5624 ssh
->cs_cipher_ctx
= ssh
->cscipher
->make_context();
5626 if (ssh
->cs_mac_ctx
)
5627 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
5628 ssh
->csmac
= s
->csmac_tobe
;
5629 ssh
->cs_mac_ctx
= ssh
->csmac
->make_context();
5631 if (ssh
->cs_comp_ctx
)
5632 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
5633 ssh
->cscomp
= s
->cscomp_tobe
;
5634 ssh
->cs_comp_ctx
= ssh
->cscomp
->compress_init();
5637 * Set IVs on client-to-server keys. Here we use the exchange
5638 * hash from the _first_ key exchange.
5641 unsigned char keyspace
[40];
5642 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'C',keyspace
);
5643 ssh
->cscipher
->setkey(ssh
->cs_cipher_ctx
, keyspace
);
5644 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'A',keyspace
);
5645 ssh
->cscipher
->setiv(ssh
->cs_cipher_ctx
, keyspace
);
5646 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'E',keyspace
);
5647 ssh
->csmac
->setkey(ssh
->cs_mac_ctx
, keyspace
);
5650 logeventf(ssh
, "Initialised %.200s client->server encryption",
5651 ssh
->cscipher
->text_name
);
5652 logeventf(ssh
, "Initialised %.200s client->server MAC algorithm",
5653 ssh
->csmac
->text_name
);
5654 if (ssh
->cscomp
->text_name
)
5655 logeventf(ssh
, "Initialised %s compression",
5656 ssh
->cscomp
->text_name
);
5659 * Now our end of the key exchange is complete, we can send all
5660 * our queued higher-layer packets.
5662 ssh
->queueing
= FALSE
;
5663 ssh2_pkt_queuesend(ssh
);
5666 * Expect SSH2_MSG_NEWKEYS from server.
5669 if (pktin
->type
!= SSH2_MSG_NEWKEYS
) {
5670 bombout(("expected new-keys packet from server"));
5673 ssh
->incoming_data_size
= 0; /* start counting from here */
5676 * We've seen server NEWKEYS, so create and initialise
5677 * server-to-client session keys.
5679 if (ssh
->sc_cipher_ctx
)
5680 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
5681 ssh
->sccipher
= s
->sccipher_tobe
;
5682 ssh
->sc_cipher_ctx
= ssh
->sccipher
->make_context();
5684 if (ssh
->sc_mac_ctx
)
5685 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
5686 ssh
->scmac
= s
->scmac_tobe
;
5687 ssh
->sc_mac_ctx
= ssh
->scmac
->make_context();
5689 if (ssh
->sc_comp_ctx
)
5690 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
5691 ssh
->sccomp
= s
->sccomp_tobe
;
5692 ssh
->sc_comp_ctx
= ssh
->sccomp
->decompress_init();
5695 * Set IVs on server-to-client keys. Here we use the exchange
5696 * hash from the _first_ key exchange.
5699 unsigned char keyspace
[40];
5700 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'D',keyspace
);
5701 ssh
->sccipher
->setkey(ssh
->sc_cipher_ctx
, keyspace
);
5702 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'B',keyspace
);
5703 ssh
->sccipher
->setiv(ssh
->sc_cipher_ctx
, keyspace
);
5704 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'F',keyspace
);
5705 ssh
->scmac
->setkey(ssh
->sc_mac_ctx
, keyspace
);
5707 logeventf(ssh
, "Initialised %.200s server->client encryption",
5708 ssh
->sccipher
->text_name
);
5709 logeventf(ssh
, "Initialised %.200s server->client MAC algorithm",
5710 ssh
->scmac
->text_name
);
5711 if (ssh
->sccomp
->text_name
)
5712 logeventf(ssh
, "Initialised %s decompression",
5713 ssh
->sccomp
->text_name
);
5716 * Free key exchange data.
5720 if (ssh
->kex
== &ssh_diffiehellman_gex
) {
5726 * Key exchange is over. Loop straight back round if we have a
5727 * deferred rekey reason.
5729 if (ssh
->deferred_rekey_reason
) {
5730 logevent(ssh
->deferred_rekey_reason
);
5732 ssh
->deferred_rekey_reason
= NULL
;
5733 goto begin_key_exchange
;
5737 * Otherwise, schedule a timer for our next rekey.
5739 ssh
->kex_in_progress
= FALSE
;
5740 ssh
->last_rekey
= GETTICKCOUNT();
5741 if (ssh
->cfg
.ssh_rekey_time
!= 0)
5742 ssh
->next_rekey
= schedule_timer(ssh
->cfg
.ssh_rekey_time
*60*TICKSPERSEC
,
5746 * If this is the first key exchange phase, we must pass the
5747 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
5748 * wants to see it but because it will need time to initialise
5749 * itself before it sees an actual packet. In subsequent key
5750 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
5751 * it would only confuse the layer above.
5753 if (s
->activated_authconn
) {
5756 s
->activated_authconn
= TRUE
;
5759 * Now we're encrypting. Begin returning 1 to the protocol main
5760 * function so that other things can run on top of the
5761 * transport. If we ever see a KEXINIT, we must go back to the
5764 * We _also_ go back to the start if we see pktin==NULL and
5765 * inlen==-1, because this is a special signal meaning
5766 * `initiate client-driven rekey', and `in' contains a message
5767 * giving the reason for the rekey.
5769 while (!((pktin
&& pktin
->type
== SSH2_MSG_KEXINIT
) ||
5770 (!pktin
&& inlen
== -1))) {
5775 logevent("Server initiated key re-exchange");
5778 * Special case: if the server bug is set that doesn't
5779 * allow rekeying, we give a different log message and
5780 * continue waiting. (If such a server _initiates_ a rekey,
5781 * we process it anyway!)
5783 if ((ssh
->remote_bugs
& BUG_SSH2_REKEY
)) {
5784 logeventf(ssh
, "Server bug prevents key re-exchange (%s)",
5786 /* Reset the counters, so that at least this message doesn't
5787 * hit the event log _too_ often. */
5788 ssh
->outgoing_data_size
= 0;
5789 ssh
->incoming_data_size
= 0;
5790 if (ssh
->cfg
.ssh_rekey_time
!= 0) {
5792 schedule_timer(ssh
->cfg
.ssh_rekey_time
*60*TICKSPERSEC
,
5795 goto wait_for_rekey
; /* this is utterly horrid */
5797 logeventf(ssh
, "Initiating key re-exchange (%s)", (char *)in
);
5800 goto begin_key_exchange
;
5806 * Add data to an SSH-2 channel output buffer.
5808 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
5811 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
5815 * Attempt to send data on an SSH-2 channel.
5817 static int ssh2_try_send(struct ssh_channel
*c
)
5820 struct Packet
*pktout
;
5822 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
5825 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
5826 if ((unsigned)len
> c
->v
.v2
.remwindow
)
5827 len
= c
->v
.v2
.remwindow
;
5828 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
5829 len
= c
->v
.v2
.remmaxpkt
;
5830 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
5831 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5832 dont_log_data(ssh
, pktout
, PKTLOG_OMIT
);
5833 ssh2_pkt_addstring_start(pktout
);
5834 ssh2_pkt_addstring_data(pktout
, data
, len
);
5835 end_log_omission(ssh
, pktout
);
5836 ssh2_pkt_send(ssh
, pktout
);
5837 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
5838 c
->v
.v2
.remwindow
-= len
;
5842 * After having sent as much data as we can, return the amount
5845 return bufchain_size(&c
->v
.v2
.outbuffer
);
5848 static void ssh2_try_send_and_unthrottle(struct ssh_channel
*c
)
5852 return; /* don't send on closing channels */
5853 bufsize
= ssh2_try_send(c
);
5856 case CHAN_MAINSESSION
:
5857 /* stdin need not receive an unthrottle
5858 * notification since it will be polled */
5861 x11_unthrottle(c
->u
.x11
.s
);
5864 /* agent sockets are request/response and need no
5865 * buffer management */
5868 pfd_unthrottle(c
->u
.pfd
.s
);
5875 * Potentially enlarge the window on an SSH-2 channel.
5877 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
)
5882 * Never send WINDOW_ADJUST for a channel that the remote side
5883 * already thinks it's closed; there's no point, since it won't
5884 * be sending any more data anyway.
5890 * Only send a WINDOW_ADJUST if there's significantly more window
5891 * available than the other end thinks there is. This saves us
5892 * sending a WINDOW_ADJUST for every character in a shell session.
5894 * "Significant" is arbitrarily defined as half the window size.
5896 if (newwin
> c
->v
.v2
.locwindow
* 2) {
5897 struct Packet
*pktout
;
5899 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5900 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5901 ssh2_pkt_adduint32(pktout
, newwin
- c
->v
.v2
.locwindow
);
5902 ssh2_pkt_send(ssh
, pktout
);
5903 c
->v
.v2
.locwindow
= newwin
;
5907 static void ssh2_msg_channel_window_adjust(Ssh ssh
, struct Packet
*pktin
)
5909 unsigned i
= ssh_pkt_getuint32(pktin
);
5910 struct ssh_channel
*c
;
5911 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5912 if (c
&& !c
->closes
) {
5913 c
->v
.v2
.remwindow
+= ssh_pkt_getuint32(pktin
);
5914 ssh2_try_send_and_unthrottle(c
);
5918 static void ssh2_msg_channel_data(Ssh ssh
, struct Packet
*pktin
)
5922 unsigned i
= ssh_pkt_getuint32(pktin
);
5923 struct ssh_channel
*c
;
5924 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5926 return; /* nonexistent channel */
5927 if (pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
5928 ssh_pkt_getuint32(pktin
) != SSH2_EXTENDED_DATA_STDERR
)
5929 return; /* extended but not stderr */
5930 ssh_pkt_getstring(pktin
, &data
, &length
);
5933 c
->v
.v2
.locwindow
-= length
;
5935 case CHAN_MAINSESSION
:
5937 from_backend(ssh
->frontend
, pktin
->type
==
5938 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
5942 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
5945 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
5948 while (length
> 0) {
5949 if (c
->u
.a
.lensofar
< 4) {
5950 unsigned int l
= min(4 - c
->u
.a
.lensofar
, length
);
5951 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
5955 c
->u
.a
.lensofar
+= l
;
5957 if (c
->u
.a
.lensofar
== 4) {
5959 4 + GET_32BIT(c
->u
.a
.msglen
);
5960 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
5962 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
5964 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
5966 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
5968 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
5972 c
->u
.a
.lensofar
+= l
;
5974 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
5977 if (agent_query(c
->u
.a
.message
,
5980 ssh_agentf_callback
, c
))
5981 ssh_agentf_callback(c
, reply
, replylen
);
5982 sfree(c
->u
.a
.message
);
5983 c
->u
.a
.lensofar
= 0;
5990 * If we are not buffering too much data,
5991 * enlarge the window again at the remote side.
5993 if (bufsize
< OUR_V2_WINSIZE
)
5994 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
5998 static void ssh2_msg_channel_eof(Ssh ssh
, struct Packet
*pktin
)
6000 unsigned i
= ssh_pkt_getuint32(pktin
);
6001 struct ssh_channel
*c
;
6003 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
6005 return; /* nonexistent channel */
6007 if (c
->type
== CHAN_X11
) {
6009 * Remote EOF on an X11 channel means we should
6010 * wrap up and close the channel ourselves.
6012 x11_close(c
->u
.x11
.s
);
6014 } else if (c
->type
== CHAN_AGENT
) {
6016 } else if (c
->type
== CHAN_SOCKDATA
) {
6017 pfd_close(c
->u
.pfd
.s
);
6022 static void ssh2_msg_channel_close(Ssh ssh
, struct Packet
*pktin
)
6024 unsigned i
= ssh_pkt_getuint32(pktin
);
6025 struct ssh_channel
*c
;
6026 struct Packet
*pktout
;
6028 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
6029 if (!c
|| c
->halfopen
) {
6030 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
6031 c ?
"half-open" : "nonexistent", i
));
6034 /* Do pre-close processing on the channel. */
6036 case CHAN_MAINSESSION
:
6037 ssh
->mainchan
= NULL
;
6038 update_specials_menu(ssh
->frontend
);
6041 if (c
->u
.x11
.s
!= NULL
)
6042 x11_close(c
->u
.x11
.s
);
6049 if (c
->u
.pfd
.s
!= NULL
)
6050 pfd_close(c
->u
.pfd
.s
);
6054 if (c
->closes
== 0) {
6055 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
6056 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6057 ssh2_pkt_send(ssh
, pktout
);
6059 del234(ssh
->channels
, c
);
6060 bufchain_clear(&c
->v
.v2
.outbuffer
);
6064 * See if that was the last channel left open.
6065 * (This is only our termination condition if we're
6066 * not running in -N mode.)
6068 if (!ssh
->cfg
.ssh_no_shell
&& count234(ssh
->channels
) == 0) {
6070 * We used to send SSH_MSG_DISCONNECT here,
6071 * because I'd believed that _every_ conforming
6072 * SSH-2 connection had to end with a disconnect
6073 * being sent by at least one side; apparently
6074 * I was wrong and it's perfectly OK to
6075 * unceremoniously slam the connection shut
6076 * when you're done, and indeed OpenSSH feels
6077 * this is more polite than sending a
6078 * DISCONNECT. So now we don't.
6080 ssh_disconnect(ssh
, "All channels closed", NULL
, 0, TRUE
);
6084 static void ssh2_msg_channel_open_confirmation(Ssh ssh
, struct Packet
*pktin
)
6086 unsigned i
= ssh_pkt_getuint32(pktin
);
6087 struct ssh_channel
*c
;
6088 struct Packet
*pktout
;
6090 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
6092 return; /* nonexistent channel */
6093 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
6094 return; /* dunno why they're confirming this */
6095 c
->remoteid
= ssh_pkt_getuint32(pktin
);
6096 c
->halfopen
= FALSE
;
6097 c
->type
= CHAN_SOCKDATA
;
6098 c
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
6099 c
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
6101 pfd_confirm(c
->u
.pfd
.s
);
6104 * We have a pending close on this channel,
6105 * which we decided on before the server acked
6106 * the channel open. So now we know the
6107 * remoteid, we can close it again.
6109 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
6110 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6111 ssh2_pkt_send(ssh
, pktout
);
6115 static void ssh2_msg_channel_open_failure(Ssh ssh
, struct Packet
*pktin
)
6117 static const char *const reasons
[] = {
6118 "<unknown reason code>",
6119 "Administratively prohibited",
6121 "Unknown channel type",
6122 "Resource shortage",
6124 unsigned i
= ssh_pkt_getuint32(pktin
);
6125 unsigned reason_code
;
6126 char *reason_string
;
6128 struct ssh_channel
*c
;
6129 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
6131 return; /* nonexistent channel */
6132 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
6133 return; /* dunno why they're failing this */
6135 reason_code
= ssh_pkt_getuint32(pktin
);
6136 if (reason_code
>= lenof(reasons
))
6137 reason_code
= 0; /* ensure reasons[reason_code] in range */
6138 ssh_pkt_getstring(pktin
, &reason_string
, &reason_length
);
6139 logeventf(ssh
, "Forwarded connection refused by server: %s [%.*s]",
6140 reasons
[reason_code
], reason_length
, reason_string
);
6142 pfd_close(c
->u
.pfd
.s
);
6144 del234(ssh
->channels
, c
);
6148 static void ssh2_msg_channel_request(Ssh ssh
, struct Packet
*pktin
)
6152 int typelen
, want_reply
;
6153 int reply
= SSH2_MSG_CHANNEL_FAILURE
; /* default */
6154 struct ssh_channel
*c
;
6155 struct Packet
*pktout
;
6157 localid
= ssh_pkt_getuint32(pktin
);
6158 ssh_pkt_getstring(pktin
, &type
, &typelen
);
6159 want_reply
= ssh2_pkt_getbool(pktin
);
6162 * First, check that the channel exists. Otherwise,
6163 * we can instantly disconnect with a rude message.
6165 c
= find234(ssh
->channels
, &localid
, ssh_channelfind
);
6167 char *buf
= dupprintf("Received channel request for nonexistent"
6168 " channel %d", localid
);
6169 ssh_disconnect(ssh
, NULL
, buf
, SSH2_DISCONNECT_PROTOCOL_ERROR
, FALSE
);
6175 * Having got the channel number, we now look at
6176 * the request type string to see if it's something
6179 if (c
== ssh
->mainchan
) {
6181 * We recognise "exit-status" and "exit-signal" on
6182 * the primary channel.
6184 if (typelen
== 11 &&
6185 !memcmp(type
, "exit-status", 11)) {
6187 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
6188 logeventf(ssh
, "Server sent command exit status %d",
6190 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
6192 } else if (typelen
== 11 &&
6193 !memcmp(type
, "exit-signal", 11)) {
6195 int is_plausible
= TRUE
, is_int
= FALSE
;
6196 char *fmt_sig
= "", *fmt_msg
= "";
6198 int msglen
= 0, core
= FALSE
;
6199 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
6200 * provide an `int' for the signal, despite its
6201 * having been a `string' in the drafts since at
6202 * least 2001. (Fixed in session.c 1.147.) Try to
6203 * infer which we can safely parse it as. */
6205 unsigned char *p
= pktin
->body
+
6207 long len
= pktin
->length
- pktin
->savedpos
;
6208 unsigned long num
= GET_32BIT(p
); /* what is it? */
6209 /* If it's 0, it hardly matters; assume string */
6213 int maybe_int
= FALSE
, maybe_str
= FALSE
;
6214 #define CHECK_HYPOTHESIS(offset, result) \
6217 if (q >= 0 && q+4 <= len) { \
6218 q = q + 4 + GET_32BIT(p+q); \
6219 if (q >= 0 && q+4 <= len && \
6220 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
6224 CHECK_HYPOTHESIS(4+1, maybe_int
);
6225 CHECK_HYPOTHESIS(4+num
+1, maybe_str
);
6226 #undef CHECK_HYPOTHESIS
6227 if (maybe_int
&& !maybe_str
)
6229 else if (!maybe_int
&& maybe_str
)
6232 /* Crikey. Either or neither. Panic. */
6233 is_plausible
= FALSE
;
6238 /* Old non-standard OpenSSH. */
6239 int signum
= ssh_pkt_getuint32(pktin
);
6240 fmt_sig
= dupprintf(" %d", signum
);
6242 /* As per the drafts. */
6245 ssh_pkt_getstring(pktin
, &sig
, &siglen
);
6246 /* Signal name isn't supposed to be blank, but
6247 * let's cope gracefully if it is. */
6249 fmt_sig
= dupprintf(" \"%.*s\"",
6253 core
= ssh2_pkt_getbool(pktin
);
6254 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
6256 fmt_msg
= dupprintf(" (\"%.*s\")", msglen
, msg
);
6258 /* ignore lang tag */
6259 } /* else don't attempt to parse */
6260 logeventf(ssh
, "Server exited on signal%s%s%s",
6261 fmt_sig
, core ?
" (core dumped)" : "",
6263 if (*fmt_sig
) sfree(fmt_sig
);
6264 if (*fmt_msg
) sfree(fmt_msg
);
6265 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
6270 * This is a channel request we don't know
6271 * about, so we now either ignore the request
6272 * or respond with CHANNEL_FAILURE, depending
6275 reply
= SSH2_MSG_CHANNEL_FAILURE
;
6278 pktout
= ssh2_pkt_init(reply
);
6279 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6280 ssh2_pkt_send(ssh
, pktout
);
6284 static void ssh2_msg_global_request(Ssh ssh
, struct Packet
*pktin
)
6287 int typelen
, want_reply
;
6288 struct Packet
*pktout
;
6290 ssh_pkt_getstring(pktin
, &type
, &typelen
);
6291 want_reply
= ssh2_pkt_getbool(pktin
);
6294 * We currently don't support any global requests
6295 * at all, so we either ignore the request or
6296 * respond with REQUEST_FAILURE, depending on
6300 pktout
= ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE
);
6301 ssh2_pkt_send(ssh
, pktout
);
6305 static void ssh2_msg_channel_open(Ssh ssh
, struct Packet
*pktin
)
6313 struct ssh_channel
*c
;
6314 unsigned remid
, winsize
, pktsize
;
6315 struct Packet
*pktout
;
6317 ssh_pkt_getstring(pktin
, &type
, &typelen
);
6318 c
= snew(struct ssh_channel
);
6321 remid
= ssh_pkt_getuint32(pktin
);
6322 winsize
= ssh_pkt_getuint32(pktin
);
6323 pktsize
= ssh_pkt_getuint32(pktin
);
6325 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
6328 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
6329 addrstr
= snewn(peeraddrlen
+1, char);
6330 memcpy(addrstr
, peeraddr
, peeraddrlen
);
6331 addrstr
[peeraddrlen
] = '\0';
6332 peerport
= ssh_pkt_getuint32(pktin
);
6334 logeventf(ssh
, "Received X11 connect request from %s:%d",
6337 if (!ssh
->X11_fwd_enabled
)
6338 error
= "X11 forwarding is not enabled";
6339 else if (x11_init(&c
->u
.x11
.s
, ssh
->cfg
.x11_display
, c
,
6340 ssh
->x11auth
, addrstr
, peerport
,
6341 &ssh
->cfg
) != NULL
) {
6342 error
= "Unable to open an X11 connection";
6344 logevent("Opening X11 forward connection succeeded");
6349 } else if (typelen
== 15 &&
6350 !memcmp(type
, "forwarded-tcpip", 15)) {
6351 struct ssh_rportfwd pf
, *realpf
;
6354 ssh_pkt_getstring(pktin
, &dummy
, &dummylen
);/* skip address */
6355 pf
.sport
= ssh_pkt_getuint32(pktin
);
6356 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
6357 peerport
= ssh_pkt_getuint32(pktin
);
6358 realpf
= find234(ssh
->rportfwds
, &pf
, NULL
);
6359 logeventf(ssh
, "Received remote port %d open request "
6360 "from %s:%d", pf
.sport
, peeraddr
, peerport
);
6361 if (realpf
== NULL
) {
6362 error
= "Remote port is not recognised";
6364 const char *e
= pfd_newconnect(&c
->u
.pfd
.s
,
6368 realpf
->pfrec
->addressfamily
);
6369 logeventf(ssh
, "Attempting to forward remote port to "
6370 "%s:%d", realpf
->dhost
, realpf
->dport
);
6372 logeventf(ssh
, "Port open failed: %s", e
);
6373 error
= "Port open failed";
6375 logevent("Forwarded port opened successfully");
6376 c
->type
= CHAN_SOCKDATA
;
6379 } else if (typelen
== 22 &&
6380 !memcmp(type
, "auth-agent@openssh.com", 22)) {
6381 if (!ssh
->agentfwd_enabled
)
6382 error
= "Agent forwarding is not enabled";
6384 c
->type
= CHAN_AGENT
; /* identify channel type */
6385 c
->u
.a
.lensofar
= 0;
6388 error
= "Unsupported channel type requested";
6391 c
->remoteid
= remid
;
6392 c
->halfopen
= FALSE
;
6394 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
6395 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6396 ssh2_pkt_adduint32(pktout
, SSH2_OPEN_CONNECT_FAILED
);
6397 ssh2_pkt_addstring(pktout
, error
);
6398 ssh2_pkt_addstring(pktout
, "en"); /* language tag */
6399 ssh2_pkt_send(ssh
, pktout
);
6400 logeventf(ssh
, "Rejected channel open: %s", error
);
6403 c
->localid
= alloc_channel_id(ssh
);
6405 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
6406 c
->v
.v2
.remwindow
= winsize
;
6407 c
->v
.v2
.remmaxpkt
= pktsize
;
6408 bufchain_init(&c
->v
.v2
.outbuffer
);
6409 add234(ssh
->channels
, c
);
6410 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
6411 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6412 ssh2_pkt_adduint32(pktout
, c
->localid
);
6413 ssh2_pkt_adduint32(pktout
, c
->v
.v2
.locwindow
);
6414 ssh2_pkt_adduint32(pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
6415 ssh2_pkt_send(ssh
, pktout
);
6420 * Buffer banner messages for later display at some convenient point.
6422 static void ssh2_msg_userauth_banner(Ssh ssh
, struct Packet
*pktin
)
6424 /* Arbitrary limit to prevent unbounded inflation of buffer */
6425 if (bufchain_size(&ssh
->banner
) <= 131072) {
6426 char *banner
= NULL
;
6428 ssh_pkt_getstring(pktin
, &banner
, &size
);
6430 bufchain_add(&ssh
->banner
, banner
, size
);
6434 /* Helper function to deal with sending tty modes for "pty-req" */
6435 static void ssh2_send_ttymode(void *data
, char *mode
, char *val
)
6437 struct Packet
*pktout
= (struct Packet
*)data
;
6439 unsigned int arg
= 0;
6440 while (strcmp(mode
, ssh_ttymodes
[i
].mode
) != 0) i
++;
6441 if (i
== lenof(ssh_ttymodes
)) return;
6442 switch (ssh_ttymodes
[i
].type
) {
6444 arg
= ssh_tty_parse_specchar(val
);
6447 arg
= ssh_tty_parse_boolean(val
);
6450 ssh2_pkt_addbyte(pktout
, ssh_ttymodes
[i
].opcode
);
6451 ssh2_pkt_adduint32(pktout
, arg
);
6455 * Handle the SSH-2 userauth and connection layers.
6457 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
,
6458 struct Packet
*pktin
)
6460 struct do_ssh2_authconn_state
{
6462 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
6464 AUTH_KEYBOARD_INTERACTIVE
6468 AUTH_TYPE_PUBLICKEY
,
6469 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
6470 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
6472 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
6473 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
6475 int done_service_req
;
6476 int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
6477 int tried_pubkey_config
, tried_agent
;
6478 int kbd_inter_running
, kbd_inter_refused
;
6480 int num_prompts
, curr_prompt
, echo
;
6485 void *publickey_blob
;
6486 int publickey_bloblen
;
6487 unsigned char request
[5], *response
, *p
;
6491 char *pkblob
, *alg
, *commentp
;
6492 int pklen
, alglen
, commentlen
;
6493 int siglen
, retlen
, len
;
6494 char *q
, *agentreq
, *ret
;
6496 int num_env
, env_left
, env_ok
;
6497 struct Packet
*pktout
;
6499 crState(do_ssh2_authconn_state
);
6501 crBegin(ssh
->do_ssh2_authconn_crstate
);
6503 s
->done_service_req
= FALSE
;
6504 s
->we_are_in
= FALSE
;
6505 if (!ssh
->cfg
.ssh_no_userauth
) {
6507 * Request userauth protocol, and await a response to it.
6509 s
->pktout
= ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
6510 ssh2_pkt_addstring(s
->pktout
, "ssh-userauth");
6511 ssh2_pkt_send(ssh
, s
->pktout
);
6512 crWaitUntilV(pktin
);
6513 if (pktin
->type
== SSH2_MSG_SERVICE_ACCEPT
)
6514 s
->done_service_req
= TRUE
;
6516 if (!s
->done_service_req
) {
6518 * Request connection protocol directly, without authentication.
6520 s
->pktout
= ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
6521 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
6522 ssh2_pkt_send(ssh
, s
->pktout
);
6523 crWaitUntilV(pktin
);
6524 if (pktin
->type
== SSH2_MSG_SERVICE_ACCEPT
) {
6525 s
->we_are_in
= TRUE
; /* no auth required */
6527 bombout(("Server refused service request"));
6533 * We repeat this whole loop, including the username prompt,
6534 * until we manage a successful authentication. If the user
6535 * types the wrong _password_, they can be sent back to the
6536 * beginning to try another username, if this is configured on.
6537 * (If they specify a username in the config, they are never
6538 * asked, even if they do give a wrong password.)
6540 * I think this best serves the needs of
6542 * - the people who have no configuration, no keys, and just
6543 * want to try repeated (username,password) pairs until they
6544 * type both correctly
6546 * - people who have keys and configuration but occasionally
6547 * need to fall back to passwords
6549 * - people with a key held in Pageant, who might not have
6550 * logged in to a particular machine before; so they want to
6551 * type a username, and then _either_ their key will be
6552 * accepted, _or_ they will type a password. If they mistype
6553 * the username they will want to be able to get back and
6556 s
->username
[0] = '\0';
6557 s
->got_username
= FALSE
;
6558 bufchain_init(&ssh
->banner
);
6559 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] =
6560 ssh2_msg_userauth_banner
;
6561 while (!s
->we_are_in
) {
6565 if (s
->got_username
&& !ssh
->cfg
.change_username
) {
6567 * We got a username last time round this loop, and
6568 * with change_username turned off we don't try to get
6571 } else if (!*ssh
->cfg
.username
) {
6572 if (ssh_get_line
&& !ssh_getline_pw_only
) {
6573 if (!ssh_get_line("login as: ",
6574 s
->username
, sizeof(s
->username
), FALSE
)) {
6576 * get_line failed to get a username.
6579 ssh_disconnect(ssh
, "No username provided", NULL
, 0, TRUE
);
6583 int ret
; /* need not be saved across crReturn */
6584 c_write_str(ssh
, "login as: ");
6586 setup_userpass_input(ssh
, s
->username
, sizeof(s
->username
), 1);
6588 crWaitUntilV(!pktin
);
6589 ret
= process_userpass_input(ssh
, in
, inlen
);
6593 c_write_str(ssh
, "\r\n");
6595 s
->username
[strcspn(s
->username
, "\n\r")] = '\0';
6598 strncpy(s
->username
, ssh
->cfg
.username
, sizeof(s
->username
));
6599 s
->username
[sizeof(s
->username
)-1] = '\0';
6600 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
6601 stuff
= dupprintf("Using username \"%s\".\r\n", s
->username
);
6602 c_write_str(ssh
, stuff
);
6606 s
->got_username
= TRUE
;
6609 * Send an authentication request using method "none": (a)
6610 * just in case it succeeds, and (b) so that we know what
6611 * authentication methods we can usefully try next.
6613 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6615 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6616 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6617 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");/* service requested */
6618 ssh2_pkt_addstring(s
->pktout
, "none"); /* method */
6619 ssh2_pkt_send(ssh
, s
->pktout
);
6620 s
->type
= AUTH_TYPE_NONE
;
6622 s
->we_are_in
= FALSE
;
6624 s
->tried_pubkey_config
= FALSE
;
6625 s
->tried_agent
= FALSE
;
6626 s
->kbd_inter_running
= FALSE
;
6627 s
->kbd_inter_refused
= FALSE
;
6628 /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
6629 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
6631 logeventf(ssh
, "Reading private key file \"%.150s\"",
6632 filename_to_str(&ssh
->cfg
.keyfile
));
6633 keytype
= key_type(&ssh
->cfg
.keyfile
);
6634 if (keytype
== SSH_KEYTYPE_SSH2
) {
6636 ssh2_userkey_loadpub(&ssh
->cfg
.keyfile
, NULL
,
6637 &s
->publickey_bloblen
, NULL
);
6640 logeventf(ssh
, "Unable to use this key file (%s)",
6641 key_type_to_str(keytype
));
6642 msgbuf
= dupprintf("Unable to use key file \"%.150s\""
6644 filename_to_str(&ssh
->cfg
.keyfile
),
6645 key_type_to_str(keytype
));
6646 c_write_str(ssh
, msgbuf
);
6648 s
->publickey_blob
= NULL
;
6651 s
->publickey_blob
= NULL
;
6655 * Wait for the result of the last authentication request.
6658 crWaitUntilV(pktin
);
6660 * Now is a convenient point to spew any banner material
6661 * that we've accumulated. (This should ensure that when
6662 * we exit the auth loop, we haven't any left to deal
6666 int size
= bufchain_size(&ssh
->banner
);
6668 * Don't show the banner if we're operating in
6669 * non-verbose non-interactive mode. (It's probably
6670 * a script, which means nobody will read the
6671 * banner _anyway_, and moreover the printing of
6672 * the banner will screw up processing on the
6673 * output of (say) plink.)
6675 if (size
&& (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
))) {
6676 char *banner
= snewn(size
, char);
6677 bufchain_fetch(&ssh
->banner
, banner
, size
);
6678 c_write_untrusted(ssh
, banner
, size
);
6681 bufchain_clear(&ssh
->banner
);
6683 if (pktin
->type
== SSH2_MSG_USERAUTH_SUCCESS
) {
6684 logevent("Access granted");
6685 s
->we_are_in
= TRUE
;
6689 if (s
->kbd_inter_running
&&
6690 pktin
->type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
6692 * This is either a further set-of-prompts packet
6693 * in keyboard-interactive authentication, or it's
6694 * the same one and we came back here with `gotit'
6695 * set. In the former case, we must reset the
6696 * curr_prompt variable.
6700 } else if (pktin
->type
== SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
) {
6701 /* FIXME: perhaps we should support this? */
6702 bombout(("PASSWD_CHANGEREQ not yet supported"));
6704 } else if (pktin
->type
!= SSH2_MSG_USERAUTH_FAILURE
) {
6705 bombout(("Strange packet received during authentication: type %d",
6713 * OK, we're now sitting on a USERAUTH_FAILURE message, so
6714 * we can look at the string in it and know what we can
6715 * helpfully try next.
6717 if (pktin
->type
== SSH2_MSG_USERAUTH_FAILURE
) {
6720 ssh_pkt_getstring(pktin
, &methods
, &methlen
);
6721 s
->kbd_inter_running
= FALSE
;
6722 if (!ssh2_pkt_getbool(pktin
)) {
6724 * We have received an unequivocal Access
6725 * Denied. This can translate to a variety of
6728 * - if we'd just tried "none" authentication,
6729 * it's not worth printing anything at all
6731 * - if we'd just tried a public key _offer_,
6732 * the message should be "Server refused our
6733 * key" (or no message at all if the key
6734 * came from Pageant)
6736 * - if we'd just tried anything else, the
6737 * message really should be "Access denied".
6739 * Additionally, if we'd just tried password
6740 * authentication, we should break out of this
6741 * whole loop so as to go back to the username
6742 * prompt (iff we're configured to allow
6743 * username change attempts).
6745 if (s
->type
== AUTH_TYPE_NONE
) {
6747 } else if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
6748 s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
6749 if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
6750 c_write_str(ssh
, "Server refused our key\r\n");
6751 logevent("Server refused public key");
6752 } else if (s
->type
==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
6753 /* server declined keyboard-interactive; ignore */
6755 c_write_str(ssh
, "Access denied\r\n");
6756 logevent("Access denied");
6757 if (s
->type
== AUTH_TYPE_PASSWORD
&&
6758 ssh
->cfg
.change_username
) {
6759 /* XXX perhaps we should allow
6760 * keyboard-interactive to do this too? */
6761 s
->we_are_in
= FALSE
;
6766 c_write_str(ssh
, "Further authentication required\r\n");
6767 logevent("Further authentication required");
6771 in_commasep_string("publickey", methods
, methlen
);
6773 in_commasep_string("password", methods
, methlen
);
6774 s
->can_keyb_inter
= ssh
->cfg
.try_ki_auth
&&
6775 in_commasep_string("keyboard-interactive", methods
, methlen
);
6779 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6783 * Most password/passphrase prompts will be
6784 * non-echoing, so we set this to 0 by default.
6785 * Exception is that some keyboard-interactive prompts
6786 * can be echoing, in which case we'll set this to 1.
6790 if (!s
->method
&& s
->can_pubkey
&&
6791 agent_exists() && !s
->tried_agent
) {
6793 * Attempt public-key authentication using Pageant.
6798 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6799 ssh
->pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
6801 s
->tried_agent
= TRUE
;
6803 logevent("Pageant is running. Requesting keys.");
6805 /* Request the keys held by the agent. */
6806 PUT_32BIT(s
->request
, 1);
6807 s
->request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
6808 if (!agent_query(s
->request
, 5, &r
, &s
->responselen
,
6809 ssh_agent_callback
, ssh
)) {
6813 bombout(("Unexpected data from server while"
6814 " waiting for agent response"));
6817 } while (pktin
|| inlen
> 0);
6818 r
= ssh
->agent_response
;
6819 s
->responselen
= ssh
->agent_response_len
;
6821 s
->response
= (unsigned char *) r
;
6822 if (s
->response
&& s
->responselen
>= 5 &&
6823 s
->response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
6824 s
->p
= s
->response
+ 5;
6825 s
->nkeys
= GET_32BIT(s
->p
);
6827 logeventf(ssh
, "Pageant has %d SSH-2 keys", s
->nkeys
);
6828 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
6831 logeventf(ssh
, "Trying Pageant key #%d", s
->keyi
);
6832 s
->pklen
= GET_32BIT(s
->p
);
6834 if (s
->publickey_blob
&&
6835 s
->pklen
== s
->publickey_bloblen
&&
6836 !memcmp(s
->p
, s
->publickey_blob
,
6837 s
->publickey_bloblen
)) {
6838 logevent("This key matches configured key file");
6839 s
->tried_pubkey_config
= 1;
6841 s
->pkblob
= (char *)s
->p
;
6843 s
->alglen
= GET_32BIT(s
->pkblob
);
6844 s
->alg
= s
->pkblob
+ 4;
6845 s
->commentlen
= GET_32BIT(s
->p
);
6847 s
->commentp
= (char *)s
->p
;
6848 s
->p
+= s
->commentlen
;
6849 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6850 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6851 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6852 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
6853 ssh2_pkt_addbool(s
->pktout
, FALSE
); /* no signature included */
6854 ssh2_pkt_addstring_start(s
->pktout
);
6855 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
6856 ssh2_pkt_addstring_start(s
->pktout
);
6857 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
6858 ssh2_pkt_send(ssh
, s
->pktout
);
6860 crWaitUntilV(pktin
);
6861 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
6862 logevent("Key refused");
6866 if (flags
& FLAG_VERBOSE
) {
6867 c_write_str(ssh
, "Authenticating with "
6869 c_write(ssh
, s
->commentp
, s
->commentlen
);
6870 c_write_str(ssh
, "\" from agent\r\n");
6874 * Server is willing to accept the key.
6875 * Construct a SIGN_REQUEST.
6877 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6878 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6879 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6880 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
6881 ssh2_pkt_addbool(s
->pktout
, TRUE
);
6882 ssh2_pkt_addstring_start(s
->pktout
);
6883 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
6884 ssh2_pkt_addstring_start(s
->pktout
);
6885 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
6887 s
->siglen
= s
->pktout
->length
- 5 + 4 +
6888 ssh
->v2_session_id_len
;
6889 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
6891 s
->len
= 1; /* message type */
6892 s
->len
+= 4 + s
->pklen
; /* key blob */
6893 s
->len
+= 4 + s
->siglen
; /* data to sign */
6894 s
->len
+= 4; /* flags */
6895 s
->agentreq
= snewn(4 + s
->len
, char);
6896 PUT_32BIT(s
->agentreq
, s
->len
);
6897 s
->q
= s
->agentreq
+ 4;
6898 *s
->q
++ = SSH2_AGENTC_SIGN_REQUEST
;
6899 PUT_32BIT(s
->q
, s
->pklen
);
6901 memcpy(s
->q
, s
->pkblob
, s
->pklen
);
6903 PUT_32BIT(s
->q
, s
->siglen
);
6905 /* Now the data to be signed... */
6906 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
6907 PUT_32BIT(s
->q
, ssh
->v2_session_id_len
);
6910 memcpy(s
->q
, ssh
->v2_session_id
,
6911 ssh
->v2_session_id_len
);
6912 s
->q
+= ssh
->v2_session_id_len
;
6913 memcpy(s
->q
, s
->pktout
->data
+ 5,
6914 s
->pktout
->length
- 5);
6915 s
->q
+= s
->pktout
->length
- 5;
6916 /* And finally the (zero) flags word. */
6918 if (!agent_query(s
->agentreq
, s
->len
+ 4,
6920 ssh_agent_callback
, ssh
)) {
6924 bombout(("Unexpected data from server"
6925 " while waiting for agent"
6929 } while (pktin
|| inlen
> 0);
6930 vret
= ssh
->agent_response
;
6931 s
->retlen
= ssh
->agent_response_len
;
6936 if (s
->ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
6937 logevent("Sending Pageant's response");
6938 ssh2_add_sigblob(ssh
, s
->pktout
,
6939 s
->pkblob
, s
->pklen
,
6941 GET_32BIT(s
->ret
+ 5));
6942 ssh2_pkt_send(ssh
, s
->pktout
);
6947 ("Pageant failed to answer challenge");
6958 if (!s
->method
&& s
->can_pubkey
&& s
->publickey_blob
6959 && !s
->tried_pubkey_config
) {
6960 unsigned char *pub_blob
;
6961 char *algorithm
, *comment
;
6964 s
->tried_pubkey_config
= TRUE
;
6966 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6967 ssh
->pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
6970 * Try the public key supplied in the configuration.
6972 * First, offer the public blob to see if the server is
6973 * willing to accept it.
6976 (unsigned char *)ssh2_userkey_loadpub(&ssh
->cfg
.keyfile
,
6981 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6982 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6983 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6984 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
6985 ssh2_pkt_addbool(s
->pktout
, FALSE
); /* no signature included */
6986 ssh2_pkt_addstring(s
->pktout
, algorithm
);
6987 ssh2_pkt_addstring_start(s
->pktout
);
6988 ssh2_pkt_addstring_data(s
->pktout
, (char *)pub_blob
,
6990 ssh2_pkt_send(ssh
, s
->pktout
);
6991 logevent("Offered public key");
6993 crWaitUntilV(pktin
);
6994 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
6996 s
->type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
6997 continue; /* key refused; give up on it */
7000 logevent("Offer of public key accepted");
7002 * Actually attempt a serious authentication using
7005 if (ssh2_userkey_encrypted(&ssh
->cfg
.keyfile
, &comment
)) {
7006 sprintf(s
->pwprompt
,
7007 "Passphrase for key \"%.100s\": ",
7013 if (flags
& FLAG_VERBOSE
) {
7014 c_write_str(ssh
, "Authenticating with public key \"");
7015 c_write_str(ssh
, comment
);
7016 c_write_str(ssh
, "\"\r\n");
7018 s
->method
= AUTH_PUBLICKEY_FILE
;
7022 if (!s
->method
&& s
->can_keyb_inter
&& !s
->kbd_inter_refused
&&
7023 !s
->kbd_inter_running
) {
7024 s
->method
= AUTH_KEYBOARD_INTERACTIVE
;
7025 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
7027 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
7028 ssh
->pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
7030 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7031 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7032 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
7033 ssh2_pkt_addstring(s
->pktout
, "keyboard-interactive"); /* method */
7034 ssh2_pkt_addstring(s
->pktout
, ""); /* lang */
7035 ssh2_pkt_addstring(s
->pktout
, "");
7036 ssh2_pkt_send(ssh
, s
->pktout
);
7038 crWaitUntilV(pktin
);
7039 if (pktin
->type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
7040 if (pktin
->type
== SSH2_MSG_USERAUTH_FAILURE
)
7042 logevent("Keyboard-interactive authentication refused");
7043 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
7044 s
->kbd_inter_refused
= TRUE
; /* don't try it again */
7048 c_write_str(ssh
, "Using keyboard-interactive authentication.\r\n");
7049 s
->kbd_inter_running
= TRUE
;
7053 if (s
->kbd_inter_running
) {
7054 s
->method
= AUTH_KEYBOARD_INTERACTIVE
;
7055 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
7057 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
7058 ssh
->pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
7060 if (s
->curr_prompt
== 0) {
7062 * We've got a fresh USERAUTH_INFO_REQUEST.
7063 * Display header data, and start going through
7066 char *name
, *inst
, *lang
;
7067 int name_len
, inst_len
, lang_len
;
7069 ssh_pkt_getstring(pktin
, &name
, &name_len
);
7070 ssh_pkt_getstring(pktin
, &inst
, &inst_len
);
7071 ssh_pkt_getstring(pktin
, &lang
, &lang_len
);
7073 c_write_untrusted(ssh
, name
, name_len
);
7074 c_write_str(ssh
, "\r\n");
7077 c_write_untrusted(ssh
, inst
, inst_len
);
7078 c_write_str(ssh
, "\r\n");
7080 s
->num_prompts
= ssh_pkt_getuint32(pktin
);
7084 * If there are prompts remaining in the packet,
7085 * display one and get a response.
7087 if (s
->curr_prompt
< s
->num_prompts
) {
7091 ssh_pkt_getstring(pktin
, &prompt
, &prompt_len
);
7092 if (prompt_len
> 0) {
7093 static const char trunc
[] = "<prompt truncated>: ";
7094 static const int prlen
= sizeof(s
->pwprompt
) -
7096 if (prompt_len
> prlen
) {
7097 memcpy(s
->pwprompt
, prompt
, prlen
);
7098 strcpy(s
->pwprompt
+ prlen
, trunc
);
7100 memcpy(s
->pwprompt
, prompt
, prompt_len
);
7101 s
->pwprompt
[prompt_len
] = '\0';
7105 "<server failed to send prompt>: ");
7107 s
->echo
= ssh2_pkt_getbool(pktin
);
7113 if (!s
->method
&& s
->can_passwd
) {
7114 s
->method
= AUTH_PASSWORD
;
7115 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
7116 ssh
->pkt_ctx
|= SSH2_PKTCTX_PASSWORD
;
7117 sprintf(s
->pwprompt
, "%.90s@%.90s's password: ", s
->username
,
7124 if (!ssh_get_line(s
->pwprompt
, s
->password
,
7125 sizeof(s
->password
), TRUE
)) {
7127 * get_line failed to get a password (for
7128 * example because one was supplied on the
7129 * command line which has already failed to
7132 ssh_disconnect(ssh
, NULL
, "Unable to authenticate",
7133 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER
,
7138 int ret
; /* need not be saved across crReturn */
7139 c_write_untrusted(ssh
, s
->pwprompt
, strlen(s
->pwprompt
));
7142 setup_userpass_input(ssh
, s
->password
,
7143 sizeof(s
->password
), s
->echo
);
7145 crWaitUntilV(!pktin
);
7146 ret
= process_userpass_input(ssh
, in
, inlen
);
7150 c_write_str(ssh
, "\r\n");
7154 if (s
->method
== AUTH_PUBLICKEY_FILE
) {
7156 * We have our passphrase. Now try the actual authentication.
7158 struct ssh2_userkey
*key
;
7159 const char *error
= NULL
;
7161 key
= ssh2_load_userkey(&ssh
->cfg
.keyfile
, s
->password
,
7163 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
7164 if (key
== SSH2_WRONG_PASSPHRASE
) {
7165 c_write_str(ssh
, "Wrong passphrase\r\n");
7166 s
->tried_pubkey_config
= FALSE
;
7168 c_write_str(ssh
, "Unable to load private key (");
7169 c_write_str(ssh
, error
);
7170 c_write_str(ssh
, ")\r\n");
7171 s
->tried_pubkey_config
= TRUE
;
7173 /* Send a spurious AUTH_NONE to return to the top. */
7174 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7175 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7176 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
7177 ssh2_pkt_addstring(s
->pktout
, "none"); /* method */
7178 ssh2_pkt_send(ssh
, s
->pktout
);
7179 s
->type
= AUTH_TYPE_NONE
;
7181 unsigned char *pkblob
, *sigblob
, *sigdata
;
7182 int pkblob_len
, sigblob_len
, sigdata_len
;
7186 * We have loaded the private key and the server
7187 * has announced that it's willing to accept it.
7188 * Hallelujah. Generate a signature and send it.
7190 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7191 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7192 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
7193 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
7194 ssh2_pkt_addbool(s
->pktout
, TRUE
);
7195 ssh2_pkt_addstring(s
->pktout
, key
->alg
->name
);
7196 pkblob
= key
->alg
->public_blob(key
->data
, &pkblob_len
);
7197 ssh2_pkt_addstring_start(s
->pktout
);
7198 ssh2_pkt_addstring_data(s
->pktout
, (char *)pkblob
, pkblob_len
);
7201 * The data to be signed is:
7205 * followed by everything so far placed in the
7208 sigdata_len
= s
->pktout
->length
- 5 + 4 +
7209 ssh
->v2_session_id_len
;
7210 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
7212 sigdata
= snewn(sigdata_len
, unsigned char);
7214 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
7215 PUT_32BIT(sigdata
+p
, ssh
->v2_session_id_len
);
7218 memcpy(sigdata
+p
, ssh
->v2_session_id
,
7219 ssh
->v2_session_id_len
);
7220 p
+= ssh
->v2_session_id_len
;
7221 memcpy(sigdata
+p
, s
->pktout
->data
+ 5,
7222 s
->pktout
->length
- 5);
7223 p
+= s
->pktout
->length
- 5;
7224 assert(p
== sigdata_len
);
7225 sigblob
= key
->alg
->sign(key
->data
, (char *)sigdata
,
7226 sigdata_len
, &sigblob_len
);
7227 ssh2_add_sigblob(ssh
, s
->pktout
, pkblob
, pkblob_len
,
7228 sigblob
, sigblob_len
);
7233 ssh2_pkt_send(ssh
, s
->pktout
);
7234 s
->type
= AUTH_TYPE_PUBLICKEY
;
7235 key
->alg
->freekey(key
->data
);
7237 } else if (s
->method
== AUTH_PASSWORD
) {
7239 * We pad out the password packet to 256 bytes to make
7240 * it harder for an attacker to find the length of the
7243 * Anyone using a password longer than 256 bytes
7244 * probably doesn't have much to worry about from
7245 * people who find out how long their password is!
7247 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7248 s
->pktout
->forcepad
= 256;
7249 ssh2_pkt_addstring(s
->pktout
, s
->username
);
7250 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
7251 ssh2_pkt_addstring(s
->pktout
, "password");
7252 ssh2_pkt_addbool(s
->pktout
, FALSE
);
7253 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
7254 ssh2_pkt_addstring(s
->pktout
, s
->password
);
7255 memset(s
->password
, 0, sizeof(s
->password
));
7256 end_log_omission(ssh
, s
->pktout
);
7257 ssh2_pkt_send(ssh
, s
->pktout
);
7258 logevent("Sent password");
7259 s
->type
= AUTH_TYPE_PASSWORD
;
7260 } else if (s
->method
== AUTH_KEYBOARD_INTERACTIVE
) {
7261 if (s
->curr_prompt
== 0) {
7262 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
7263 s
->pktout
->forcepad
= 256;
7264 ssh2_pkt_adduint32(s
->pktout
, s
->num_prompts
);
7266 if (s
->need_pw
) { /* only add pw if we just got one! */
7267 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
7268 ssh2_pkt_addstring(s
->pktout
, s
->password
);
7269 memset(s
->password
, 0, sizeof(s
->password
));
7270 end_log_omission(ssh
, s
->pktout
);
7273 if (s
->curr_prompt
>= s
->num_prompts
) {
7274 ssh2_pkt_send(ssh
, s
->pktout
);
7277 * If there are prompts remaining, we set
7278 * `gotit' so that we won't attempt to get
7279 * another packet. Then we go back round the
7280 * loop and will end up retrieving another
7281 * prompt out of the existing packet. Funky or
7286 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
7288 ssh_disconnect(ssh
, NULL
,
7289 "No supported authentication methods available",
7290 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE
,
7296 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] = NULL
;
7299 * Now the connection protocol has started, one way or another.
7302 ssh
->channels
= newtree234(ssh_channelcmp
);
7305 * Set up handlers for some connection protocol messages, so we
7306 * don't have to handle them repeatedly in this coroutine.
7308 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] =
7309 ssh2_msg_channel_window_adjust
;
7310 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] =
7311 ssh2_msg_global_request
;
7314 * Create the main session channel.
7316 if (!ssh
->cfg
.ssh_no_shell
) {
7317 ssh
->mainchan
= snew(struct ssh_channel
);
7318 ssh
->mainchan
->ssh
= ssh
;
7319 ssh
->mainchan
->localid
= alloc_channel_id(ssh
);
7320 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
7321 ssh2_pkt_addstring(s
->pktout
, "session");
7322 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->localid
);
7323 ssh
->mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
7324 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->v
.v2
.locwindow
);/* our window size */
7325 ssh2_pkt_adduint32(s
->pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
7326 ssh2_pkt_send(ssh
, s
->pktout
);
7327 crWaitUntilV(pktin
);
7328 if (pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
7329 bombout(("Server refused to open a session"));
7331 /* FIXME: error data comes back in FAILURE packet */
7333 if (ssh_pkt_getuint32(pktin
) != ssh
->mainchan
->localid
) {
7334 bombout(("Server's channel confirmation cited wrong channel"));
7337 ssh
->mainchan
->remoteid
= ssh_pkt_getuint32(pktin
);
7338 ssh
->mainchan
->halfopen
= FALSE
;
7339 ssh
->mainchan
->type
= CHAN_MAINSESSION
;
7340 ssh
->mainchan
->closes
= 0;
7341 ssh
->mainchan
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
7342 ssh
->mainchan
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
7343 bufchain_init(&ssh
->mainchan
->v
.v2
.outbuffer
);
7344 add234(ssh
->channels
, ssh
->mainchan
);
7345 update_specials_menu(ssh
->frontend
);
7346 logevent("Opened channel for session");
7348 ssh
->mainchan
= NULL
;
7351 * Now we have a channel, make dispatch table entries for
7352 * general channel-based messages.
7354 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] =
7355 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] =
7356 ssh2_msg_channel_data
;
7357 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = ssh2_msg_channel_eof
;
7358 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = ssh2_msg_channel_close
;
7359 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] =
7360 ssh2_msg_channel_open_confirmation
;
7361 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] =
7362 ssh2_msg_channel_open_failure
;
7363 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_REQUEST
] =
7364 ssh2_msg_channel_request
;
7365 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] =
7366 ssh2_msg_channel_open
;
7369 * Potentially enable X11 forwarding.
7371 if (ssh
->mainchan
&& ssh
->cfg
.x11_forward
) {
7372 char proto
[20], data
[64];
7373 logevent("Requesting X11 forwarding");
7374 ssh
->x11auth
= x11_invent_auth(proto
, sizeof(proto
),
7375 data
, sizeof(data
), ssh
->cfg
.x11_auth
);
7376 x11_get_real_auth(ssh
->x11auth
, ssh
->cfg
.x11_display
);
7377 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7378 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
7379 ssh2_pkt_addstring(s
->pktout
, "x11-req");
7380 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7381 ssh2_pkt_addbool(s
->pktout
, 0); /* many connections */
7382 ssh2_pkt_addstring(s
->pktout
, proto
);
7384 * Note that while we blank the X authentication data here, we don't
7385 * take any special action to blank the start of an X11 channel,
7386 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
7387 * without having session blanking enabled is likely to leak your
7388 * cookie into the log.
7390 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
7391 ssh2_pkt_addstring(s
->pktout
, data
);
7392 end_log_omission(ssh
, s
->pktout
);
7393 ssh2_pkt_adduint32(s
->pktout
, x11_get_screen_number(ssh
->cfg
.x11_display
));
7394 ssh2_pkt_send(ssh
, s
->pktout
);
7396 crWaitUntilV(pktin
);
7398 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
7399 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
7400 bombout(("Unexpected response to X11 forwarding request:"
7401 " packet type %d", pktin
->type
));
7404 logevent("X11 forwarding refused");
7406 logevent("X11 forwarding enabled");
7407 ssh
->X11_fwd_enabled
= TRUE
;
7412 * Enable port forwardings.
7414 ssh_setup_portfwd(ssh
, &ssh
->cfg
);
7417 * Potentially enable agent forwarding.
7419 if (ssh
->mainchan
&& ssh
->cfg
.agentfwd
&& agent_exists()) {
7420 logevent("Requesting OpenSSH-style agent forwarding");
7421 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7422 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
7423 ssh2_pkt_addstring(s
->pktout
, "auth-agent-req@openssh.com");
7424 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7425 ssh2_pkt_send(ssh
, s
->pktout
);
7427 crWaitUntilV(pktin
);
7429 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
7430 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
7431 bombout(("Unexpected response to agent forwarding request:"
7432 " packet type %d", pktin
->type
));
7435 logevent("Agent forwarding refused");
7437 logevent("Agent forwarding enabled");
7438 ssh
->agentfwd_enabled
= TRUE
;
7443 * Now allocate a pty for the session.
7445 if (ssh
->mainchan
&& !ssh
->cfg
.nopty
) {
7446 /* Unpick the terminal-speed string. */
7447 /* XXX perhaps we should allow no speeds to be sent. */
7448 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
7449 sscanf(ssh
->cfg
.termspeed
, "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
7450 /* Build the pty request. */
7451 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7452 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
); /* recipient channel */
7453 ssh2_pkt_addstring(s
->pktout
, "pty-req");
7454 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7455 ssh2_pkt_addstring(s
->pktout
, ssh
->cfg
.termtype
);
7456 ssh2_pkt_adduint32(s
->pktout
, ssh
->term_width
);
7457 ssh2_pkt_adduint32(s
->pktout
, ssh
->term_height
);
7458 ssh2_pkt_adduint32(s
->pktout
, 0); /* pixel width */
7459 ssh2_pkt_adduint32(s
->pktout
, 0); /* pixel height */
7460 ssh2_pkt_addstring_start(s
->pktout
);
7461 parse_ttymodes(ssh
, ssh
->cfg
.ttymodes
,
7462 ssh2_send_ttymode
, (void *)s
->pktout
);
7463 ssh2_pkt_addbyte(s
->pktout
, SSH2_TTY_OP_ISPEED
);
7464 ssh2_pkt_adduint32(s
->pktout
, ssh
->ispeed
);
7465 ssh2_pkt_addbyte(s
->pktout
, SSH2_TTY_OP_OSPEED
);
7466 ssh2_pkt_adduint32(s
->pktout
, ssh
->ospeed
);
7467 ssh2_pkt_addstring_data(s
->pktout
, "\0", 1); /* TTY_OP_END */
7468 ssh2_pkt_send(ssh
, s
->pktout
);
7469 ssh
->state
= SSH_STATE_INTERMED
;
7471 crWaitUntilV(pktin
);
7473 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
7474 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
7475 bombout(("Unexpected response to pty request:"
7476 " packet type %d", pktin
->type
));
7479 c_write_str(ssh
, "Server refused to allocate pty\r\n");
7480 ssh
->editing
= ssh
->echoing
= 1;
7482 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
7483 ssh
->ospeed
, ssh
->ispeed
);
7486 ssh
->editing
= ssh
->echoing
= 1;
7490 * Send environment variables.
7492 * Simplest thing here is to send all the requests at once, and
7493 * then wait for a whole bunch of successes or failures.
7495 if (ssh
->mainchan
&& *ssh
->cfg
.environmt
) {
7496 char *e
= ssh
->cfg
.environmt
;
7497 char *var
, *varend
, *val
;
7503 while (*e
&& *e
!= '\t') e
++;
7505 if (*e
== '\t') e
++;
7510 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7511 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
7512 ssh2_pkt_addstring(s
->pktout
, "env");
7513 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7514 ssh2_pkt_addstring_start(s
->pktout
);
7515 ssh2_pkt_addstring_data(s
->pktout
, var
, varend
-var
);
7516 ssh2_pkt_addstring(s
->pktout
, val
);
7517 ssh2_pkt_send(ssh
, s
->pktout
);
7522 logeventf(ssh
, "Sent %d environment variables", s
->num_env
);
7525 s
->env_left
= s
->num_env
;
7527 while (s
->env_left
> 0) {
7528 crWaitUntilV(pktin
);
7530 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
7531 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
7532 bombout(("Unexpected response to environment request:"
7533 " packet type %d", pktin
->type
));
7543 if (s
->env_ok
== s
->num_env
) {
7544 logevent("All environment variables successfully set");
7545 } else if (s
->env_ok
== 0) {
7546 logevent("All environment variables refused");
7547 c_write_str(ssh
, "Server refused to set environment variables\r\n");
7549 logeventf(ssh
, "%d environment variables refused",
7550 s
->num_env
- s
->env_ok
);
7551 c_write_str(ssh
, "Server refused to set all environment variables\r\n");
7556 * Start a shell or a remote command. We may have to attempt
7557 * this twice if the config data has provided a second choice
7560 if (ssh
->mainchan
) while (1) {
7564 if (ssh
->fallback_cmd
) {
7565 subsys
= ssh
->cfg
.ssh_subsys2
;
7566 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
7568 subsys
= ssh
->cfg
.ssh_subsys
;
7569 cmd
= ssh
->cfg
.remote_cmd_ptr
;
7570 if (!cmd
) cmd
= ssh
->cfg
.remote_cmd
;
7573 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7574 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
); /* recipient channel */
7576 ssh2_pkt_addstring(s
->pktout
, "subsystem");
7577 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7578 ssh2_pkt_addstring(s
->pktout
, cmd
);
7580 ssh2_pkt_addstring(s
->pktout
, "exec");
7581 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7582 ssh2_pkt_addstring(s
->pktout
, cmd
);
7584 ssh2_pkt_addstring(s
->pktout
, "shell");
7585 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7587 ssh2_pkt_send(ssh
, s
->pktout
);
7589 crWaitUntilV(pktin
);
7591 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
7592 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
7593 bombout(("Unexpected response to shell/command request:"
7594 " packet type %d", pktin
->type
));
7598 * We failed to start the command. If this is the
7599 * fallback command, we really are finished; if it's
7600 * not, and if the fallback command exists, try falling
7601 * back to it before complaining.
7603 if (!ssh
->fallback_cmd
&& ssh
->cfg
.remote_cmd_ptr2
!= NULL
) {
7604 logevent("Primary command failed; attempting fallback");
7605 ssh
->fallback_cmd
= TRUE
;
7608 bombout(("Server refused to start a shell/command"));
7611 logevent("Started a shell/command");
7616 ssh
->state
= SSH_STATE_SESSION
;
7617 if (ssh
->size_needed
)
7618 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
7619 if (ssh
->eof_needed
)
7620 ssh_special(ssh
, TS_EOF
);
7626 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
7631 s
->try_send
= FALSE
;
7635 * _All_ the connection-layer packets we expect to
7636 * receive are now handled by the dispatch table.
7637 * Anything that reaches here must be bogus.
7640 bombout(("Strange packet received: type %d", pktin
->type
));
7642 } else if (ssh
->mainchan
) {
7644 * We have spare data. Add it to the channel buffer.
7646 ssh2_add_channel_data(ssh
->mainchan
, (char *)in
, inlen
);
7651 struct ssh_channel
*c
;
7653 * Try to send data on all channels if we can.
7655 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++)
7656 ssh2_try_send_and_unthrottle(c
);
7664 * Handlers for SSH-2 messages that might arrive at any moment.
7666 static void ssh2_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
7668 /* log reason code in disconnect message */
7670 int nowlen
, reason
, msglen
;
7672 reason
= ssh_pkt_getuint32(pktin
);
7673 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
7675 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
7676 buf
= dupprintf("Received disconnect message (%s)",
7677 ssh2_disconnect_reasons
[reason
]);
7679 buf
= dupprintf("Received disconnect message (unknown"
7680 " type %d)", reason
);
7684 buf
= dupprintf("Disconnection message text: %n%.*s",
7685 &nowlen
, msglen
, msg
);
7687 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
7689 (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) ?
7690 ssh2_disconnect_reasons
[reason
] : "unknown",
7695 static void ssh2_msg_debug(Ssh ssh
, struct Packet
*pktin
)
7697 /* log the debug message */
7702 /* XXX maybe we should actually take notice of this */
7703 always_display
= ssh2_pkt_getbool(pktin
);
7704 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
7706 logeventf(ssh
, "Remote debug message: %.*s", msglen
, msg
);
7709 static void ssh2_msg_something_unimplemented(Ssh ssh
, struct Packet
*pktin
)
7711 struct Packet
*pktout
;
7712 pktout
= ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED
);
7713 ssh2_pkt_adduint32(pktout
, pktin
->sequence
);
7715 * UNIMPLEMENTED messages MUST appear in the same order as the
7716 * messages they respond to. Hence, never queue them.
7718 ssh2_pkt_send_noqueue(ssh
, pktout
);
7722 * Handle the top-level SSH-2 protocol.
7724 static void ssh2_protocol_setup(Ssh ssh
)
7729 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
7731 for (i
= 0; i
< 256; i
++)
7732 ssh
->packet_dispatch
[i
] = ssh2_msg_something_unimplemented
;
7735 * Any message we actually understand, we set to NULL so that
7736 * the coroutines will get it.
7738 ssh
->packet_dispatch
[SSH2_MSG_UNIMPLEMENTED
] = NULL
;
7739 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_REQUEST
] = NULL
;
7740 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_ACCEPT
] = NULL
;
7741 ssh
->packet_dispatch
[SSH2_MSG_KEXINIT
] = NULL
;
7742 ssh
->packet_dispatch
[SSH2_MSG_NEWKEYS
] = NULL
;
7743 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_INIT
] = NULL
;
7744 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_REPLY
] = NULL
;
7745 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
7746 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
7747 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_INIT
] = NULL
;
7748 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_REPLY
] = NULL
;
7749 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_REQUEST
] = NULL
;
7750 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_FAILURE
] = NULL
;
7751 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_SUCCESS
] = NULL
;
7752 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] = NULL
;
7753 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_PK_OK
] = NULL
;
7754 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
7755 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
7756 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_INFO_RESPONSE
] = NULL
;
7757 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] = NULL
;
7758 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_SUCCESS
] = NULL
;
7759 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_FAILURE
] = NULL
;
7760 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] = NULL
;
7761 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] = NULL
;
7762 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] = NULL
;
7763 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] = NULL
;
7764 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] = NULL
;
7765 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] = NULL
;
7766 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = NULL
;
7767 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = NULL
;
7768 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_REQUEST
] = NULL
;
7769 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_SUCCESS
] = NULL
;
7770 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_FAILURE
] = NULL
;
7773 * These special message types we install handlers for.
7775 ssh
->packet_dispatch
[SSH2_MSG_DISCONNECT
] = ssh2_msg_disconnect
;
7776 ssh
->packet_dispatch
[SSH2_MSG_IGNORE
] = ssh_msg_ignore
; /* shared with SSH-1 */
7777 ssh
->packet_dispatch
[SSH2_MSG_DEBUG
] = ssh2_msg_debug
;
7780 static void ssh2_timer(void *ctx
, long now
)
7784 if (ssh
->state
== SSH_STATE_CLOSED
)
7787 if (!ssh
->kex_in_progress
&& ssh
->cfg
.ssh_rekey_time
!= 0 &&
7788 now
- ssh
->next_rekey
>= 0) {
7789 do_ssh2_transport(ssh
, "timeout", -1, NULL
);
7793 static void ssh2_protocol(Ssh ssh
, void *vin
, int inlen
,
7794 struct Packet
*pktin
)
7796 unsigned char *in
= (unsigned char *)vin
;
7797 if (ssh
->state
== SSH_STATE_CLOSED
)
7801 ssh
->incoming_data_size
+= pktin
->encrypted_len
;
7802 if (!ssh
->kex_in_progress
&&
7803 ssh
->max_data_size
!= 0 &&
7804 ssh
->incoming_data_size
> ssh
->max_data_size
)
7805 do_ssh2_transport(ssh
, "too much data received", -1, NULL
);
7808 if (pktin
&& ssh
->packet_dispatch
[pktin
->type
]) {
7809 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
7813 if (!ssh
->protocol_initial_phase_done
||
7814 (pktin
&& pktin
->type
>= 20 && pktin
->type
< 50)) {
7815 if (do_ssh2_transport(ssh
, in
, inlen
, pktin
) &&
7816 !ssh
->protocol_initial_phase_done
) {
7817 ssh
->protocol_initial_phase_done
= TRUE
;
7819 * Allow authconn to initialise itself.
7821 do_ssh2_authconn(ssh
, NULL
, 0, NULL
);
7824 do_ssh2_authconn(ssh
, in
, inlen
, pktin
);
7829 * Called to set up the connection.
7831 * Returns an error message, or NULL on success.
7833 static const char *ssh_init(void *frontend_handle
, void **backend_handle
,
7835 char *host
, int port
, char **realhost
, int nodelay
,
7841 ssh
= snew(struct ssh_tag
);
7842 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
7843 ssh
->version
= 0; /* when not ready yet */
7846 ssh
->v1_cipher_ctx
= NULL
;
7847 ssh
->crcda_ctx
= NULL
;
7848 ssh
->cscipher
= NULL
;
7849 ssh
->cs_cipher_ctx
= NULL
;
7850 ssh
->sccipher
= NULL
;
7851 ssh
->sc_cipher_ctx
= NULL
;
7853 ssh
->cs_mac_ctx
= NULL
;
7855 ssh
->sc_mac_ctx
= NULL
;
7857 ssh
->cs_comp_ctx
= NULL
;
7859 ssh
->sc_comp_ctx
= NULL
;
7861 ssh
->kex_ctx
= NULL
;
7862 ssh
->hostkey
= NULL
;
7864 ssh
->close_expected
= FALSE
;
7865 ssh
->clean_exit
= FALSE
;
7866 ssh
->state
= SSH_STATE_PREPACKET
;
7867 ssh
->size_needed
= FALSE
;
7868 ssh
->eof_needed
= FALSE
;
7871 ssh
->deferred_send_data
= NULL
;
7872 ssh
->deferred_len
= 0;
7873 ssh
->deferred_size
= 0;
7874 ssh
->fallback_cmd
= 0;
7876 ssh
->x11auth
= NULL
;
7877 ssh
->v1_compressing
= FALSE
;
7878 ssh
->v2_outgoing_sequence
= 0;
7879 ssh
->ssh1_rdpkt_crstate
= 0;
7880 ssh
->ssh2_rdpkt_crstate
= 0;
7881 ssh
->do_ssh_init_crstate
= 0;
7882 ssh
->ssh_gotdata_crstate
= 0;
7883 ssh
->do_ssh1_connection_crstate
= 0;
7884 ssh
->do_ssh1_login_crstate
= 0;
7885 ssh
->do_ssh2_transport_crstate
= 0;
7886 ssh
->do_ssh2_authconn_crstate
= 0;
7887 ssh
->do_ssh_init_state
= NULL
;
7888 ssh
->do_ssh1_login_state
= NULL
;
7889 ssh
->do_ssh2_transport_state
= NULL
;
7890 ssh
->do_ssh2_authconn_state
= NULL
;
7893 ssh
->mainchan
= NULL
;
7894 ssh
->throttled_all
= 0;
7895 ssh
->v1_stdout_throttling
= 0;
7897 ssh
->queuelen
= ssh
->queuesize
= 0;
7898 ssh
->queueing
= FALSE
;
7899 ssh
->qhead
= ssh
->qtail
= NULL
;
7900 ssh
->deferred_rekey_reason
= NULL
;
7901 bufchain_init(&ssh
->queued_incoming_data
);
7902 ssh
->frozen
= FALSE
;
7904 *backend_handle
= ssh
;
7907 if (crypto_startup() == 0)
7908 return "Microsoft high encryption pack not installed!";
7911 ssh
->frontend
= frontend_handle
;
7912 ssh
->term_width
= ssh
->cfg
.width
;
7913 ssh
->term_height
= ssh
->cfg
.height
;
7915 ssh
->channels
= NULL
;
7916 ssh
->rportfwds
= NULL
;
7917 ssh
->portfwds
= NULL
;
7922 ssh
->v1_throttle_count
= 0;
7923 ssh
->overall_bufsize
= 0;
7924 ssh
->fallback_cmd
= 0;
7926 ssh
->protocol
= NULL
;
7928 ssh
->protocol_initial_phase_done
= FALSE
;
7932 ssh
->incoming_data_size
= ssh
->outgoing_data_size
=
7933 ssh
->deferred_data_size
= 0L;
7934 ssh
->max_data_size
= parse_blocksize(ssh
->cfg
.ssh_rekey_data
);
7935 ssh
->kex_in_progress
= FALSE
;
7937 p
= connect_to_host(ssh
, host
, port
, realhost
, nodelay
, keepalive
);
7946 static void ssh_free(void *handle
)
7948 Ssh ssh
= (Ssh
) handle
;
7949 struct ssh_channel
*c
;
7950 struct ssh_rportfwd
*pf
;
7952 if (ssh
->v1_cipher_ctx
)
7953 ssh
->cipher
->free_context(ssh
->v1_cipher_ctx
);
7954 if (ssh
->cs_cipher_ctx
)
7955 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
7956 if (ssh
->sc_cipher_ctx
)
7957 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
7958 if (ssh
->cs_mac_ctx
)
7959 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
7960 if (ssh
->sc_mac_ctx
)
7961 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
7962 if (ssh
->cs_comp_ctx
) {
7964 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
7966 zlib_compress_cleanup(ssh
->cs_comp_ctx
);
7968 if (ssh
->sc_comp_ctx
) {
7970 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
7972 zlib_decompress_cleanup(ssh
->sc_comp_ctx
);
7975 dh_cleanup(ssh
->kex_ctx
);
7976 sfree(ssh
->savedhost
);
7978 while (ssh
->queuelen
-- > 0)
7979 ssh_free_packet(ssh
->queue
[ssh
->queuelen
]);
7982 while (ssh
->qhead
) {
7983 struct queued_handler
*qh
= ssh
->qhead
;
7984 ssh
->qhead
= qh
->next
;
7987 ssh
->qhead
= ssh
->qtail
= NULL
;
7989 if (ssh
->channels
) {
7990 while ((c
= delpos234(ssh
->channels
, 0)) != NULL
) {
7993 if (c
->u
.x11
.s
!= NULL
)
7994 x11_close(c
->u
.x11
.s
);
7997 if (c
->u
.pfd
.s
!= NULL
)
7998 pfd_close(c
->u
.pfd
.s
);
8003 freetree234(ssh
->channels
);
8004 ssh
->channels
= NULL
;
8007 if (ssh
->rportfwds
) {
8008 while ((pf
= delpos234(ssh
->rportfwds
, 0)) != NULL
)
8010 freetree234(ssh
->rportfwds
);
8011 ssh
->rportfwds
= NULL
;
8013 sfree(ssh
->deferred_send_data
);
8015 x11_free_auth(ssh
->x11auth
);
8016 sfree(ssh
->do_ssh_init_state
);
8017 sfree(ssh
->do_ssh1_login_state
);
8018 sfree(ssh
->do_ssh2_transport_state
);
8019 sfree(ssh
->do_ssh2_authconn_state
);
8022 if (ssh
->crcda_ctx
) {
8023 crcda_free_context(ssh
->crcda_ctx
);
8024 ssh
->crcda_ctx
= NULL
;
8027 ssh_do_close(ssh
, TRUE
);
8028 expire_timer_context(ssh
);
8030 pinger_free(ssh
->pinger
);
8031 bufchain_clear(&ssh
->queued_incoming_data
);
8038 * Reconfigure the SSH backend.
8040 static void ssh_reconfig(void *handle
, Config
*cfg
)
8042 Ssh ssh
= (Ssh
) handle
;
8043 char *rekeying
= NULL
, rekey_mandatory
= FALSE
;
8044 unsigned long old_max_data_size
;
8046 pinger_reconfig(ssh
->pinger
, &ssh
->cfg
, cfg
);
8048 ssh_setup_portfwd(ssh
, cfg
);
8050 if (ssh
->cfg
.ssh_rekey_time
!= cfg
->ssh_rekey_time
&&
8051 cfg
->ssh_rekey_time
!= 0) {
8052 long new_next
= ssh
->last_rekey
+ cfg
->ssh_rekey_time
*60*TICKSPERSEC
;
8053 long now
= GETTICKCOUNT();
8055 if (new_next
- now
< 0) {
8056 rekeying
= "timeout shortened";
8058 ssh
->next_rekey
= schedule_timer(new_next
- now
, ssh2_timer
, ssh
);
8062 old_max_data_size
= ssh
->max_data_size
;
8063 ssh
->max_data_size
= parse_blocksize(cfg
->ssh_rekey_data
);
8064 if (old_max_data_size
!= ssh
->max_data_size
&&
8065 ssh
->max_data_size
!= 0) {
8066 if (ssh
->outgoing_data_size
> ssh
->max_data_size
||
8067 ssh
->incoming_data_size
> ssh
->max_data_size
)
8068 rekeying
= "data limit lowered";
8071 if (ssh
->cfg
.compression
!= cfg
->compression
) {
8072 rekeying
= "compression setting changed";
8073 rekey_mandatory
= TRUE
;
8076 if (ssh
->cfg
.ssh2_des_cbc
!= cfg
->ssh2_des_cbc
||
8077 memcmp(ssh
->cfg
.ssh_cipherlist
, cfg
->ssh_cipherlist
,
8078 sizeof(ssh
->cfg
.ssh_cipherlist
))) {
8079 rekeying
= "cipher settings changed";
8080 rekey_mandatory
= TRUE
;
8083 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
8086 if (!ssh
->kex_in_progress
) {
8087 do_ssh2_transport(ssh
, rekeying
, -1, NULL
);
8088 } else if (rekey_mandatory
) {
8089 ssh
->deferred_rekey_reason
= rekeying
;
8095 * Called to send data down the SSH connection.
8097 static int ssh_send(void *handle
, char *buf
, int len
)
8099 Ssh ssh
= (Ssh
) handle
;
8101 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
8104 ssh
->protocol(ssh
, (unsigned char *)buf
, len
, 0);
8106 return ssh_sendbuffer(ssh
);
8110 * Called to query the current amount of buffered stdin data.
8112 static int ssh_sendbuffer(void *handle
)
8114 Ssh ssh
= (Ssh
) handle
;
8117 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
8121 * If the SSH socket itself has backed up, add the total backup
8122 * size on that to any individual buffer on the stdin channel.
8125 if (ssh
->throttled_all
)
8126 override_value
= ssh
->overall_bufsize
;
8128 if (ssh
->version
== 1) {
8129 return override_value
;
8130 } else if (ssh
->version
== 2) {
8131 if (!ssh
->mainchan
|| ssh
->mainchan
->closes
> 0)
8132 return override_value
;
8134 return (override_value
+
8135 bufchain_size(&ssh
->mainchan
->v
.v2
.outbuffer
));
8142 * Called to set the size of the window from SSH's POV.
8144 static void ssh_size(void *handle
, int width
, int height
)
8146 Ssh ssh
= (Ssh
) handle
;
8147 struct Packet
*pktout
;
8149 ssh
->term_width
= width
;
8150 ssh
->term_height
= height
;
8152 switch (ssh
->state
) {
8153 case SSH_STATE_BEFORE_SIZE
:
8154 case SSH_STATE_PREPACKET
:
8155 case SSH_STATE_CLOSED
:
8156 break; /* do nothing */
8157 case SSH_STATE_INTERMED
:
8158 ssh
->size_needed
= TRUE
; /* buffer for later */
8160 case SSH_STATE_SESSION
:
8161 if (!ssh
->cfg
.nopty
) {
8162 if (ssh
->version
== 1) {
8163 send_packet(ssh
, SSH1_CMSG_WINDOW_SIZE
,
8164 PKT_INT
, ssh
->term_height
,
8165 PKT_INT
, ssh
->term_width
,
8166 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
8167 } else if (ssh
->mainchan
) {
8168 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8169 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
8170 ssh2_pkt_addstring(pktout
, "window-change");
8171 ssh2_pkt_addbool(pktout
, 0);
8172 ssh2_pkt_adduint32(pktout
, ssh
->term_width
);
8173 ssh2_pkt_adduint32(pktout
, ssh
->term_height
);
8174 ssh2_pkt_adduint32(pktout
, 0);
8175 ssh2_pkt_adduint32(pktout
, 0);
8176 ssh2_pkt_send(ssh
, pktout
);
8184 * Return a list of the special codes that make sense in this
8187 static const struct telnet_special
*ssh_get_specials(void *handle
)
8189 static const struct telnet_special ssh1_ignore_special
[] = {
8190 {"IGNORE message", TS_NOP
}
8192 static const struct telnet_special ssh2_transport_specials
[] = {
8193 {"IGNORE message", TS_NOP
},
8194 {"Repeat key exchange", TS_REKEY
},
8196 static const struct telnet_special ssh2_session_specials
[] = {
8199 /* These are the signal names defined by draft-ietf-secsh-connect-23.
8200 * They include all the ISO C signals, but are a subset of the POSIX
8201 * required signals. */
8202 {"SIGINT (Interrupt)", TS_SIGINT
},
8203 {"SIGTERM (Terminate)", TS_SIGTERM
},
8204 {"SIGKILL (Kill)", TS_SIGKILL
},
8205 {"SIGQUIT (Quit)", TS_SIGQUIT
},
8206 {"SIGHUP (Hangup)", TS_SIGHUP
},
8207 {"More signals", TS_SUBMENU
},
8208 {"SIGABRT", TS_SIGABRT
}, {"SIGALRM", TS_SIGALRM
},
8209 {"SIGFPE", TS_SIGFPE
}, {"SIGILL", TS_SIGILL
},
8210 {"SIGPIPE", TS_SIGPIPE
}, {"SIGSEGV", TS_SIGSEGV
},
8211 {"SIGUSR1", TS_SIGUSR1
}, {"SIGUSR2", TS_SIGUSR2
},
8214 static const struct telnet_special specials_end
[] = {
8217 /* XXX review this length for any changes: */
8218 static struct telnet_special ssh_specials
[lenof(ssh2_transport_specials
) +
8219 lenof(ssh2_session_specials
) +
8220 lenof(specials_end
)];
8221 Ssh ssh
= (Ssh
) handle
;
8223 #define ADD_SPECIALS(name) \
8225 assert((i + lenof(name)) <= lenof(ssh_specials)); \
8226 memcpy(&ssh_specials[i], name, sizeof name); \
8230 if (ssh
->version
== 1) {
8231 /* Don't bother offering IGNORE if we've decided the remote
8232 * won't cope with it, since we wouldn't bother sending it if
8234 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
8235 ADD_SPECIALS(ssh1_ignore_special
);
8236 } else if (ssh
->version
== 2) {
8237 ADD_SPECIALS(ssh2_transport_specials
);
8239 ADD_SPECIALS(ssh2_session_specials
);
8240 } /* else we're not ready yet */
8243 ADD_SPECIALS(specials_end
);
8244 return ssh_specials
;
8252 * Send special codes. TS_EOF is useful for `plink', so you
8253 * can send an EOF and collect resulting output (e.g. `plink
8256 static void ssh_special(void *handle
, Telnet_Special code
)
8258 Ssh ssh
= (Ssh
) handle
;
8259 struct Packet
*pktout
;
8261 if (code
== TS_EOF
) {
8262 if (ssh
->state
!= SSH_STATE_SESSION
) {
8264 * Buffer the EOF in case we are pre-SESSION, so we can
8265 * send it as soon as we reach SESSION.
8268 ssh
->eof_needed
= TRUE
;
8271 if (ssh
->version
== 1) {
8272 send_packet(ssh
, SSH1_CMSG_EOF
, PKT_END
);
8273 } else if (ssh
->mainchan
) {
8274 struct Packet
*pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
8275 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
8276 ssh2_pkt_send(ssh
, pktout
);
8277 ssh
->send_ok
= 0; /* now stop trying to read from stdin */
8279 logevent("Sent EOF message");
8280 } else if (code
== TS_PING
|| code
== TS_NOP
) {
8281 if (ssh
->state
== SSH_STATE_CLOSED
8282 || ssh
->state
== SSH_STATE_PREPACKET
) return;
8283 if (ssh
->version
== 1) {
8284 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
8285 send_packet(ssh
, SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
8287 pktout
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
8288 ssh2_pkt_addstring_start(pktout
);
8289 ssh2_pkt_send_noqueue(ssh
, pktout
);
8291 } else if (code
== TS_REKEY
) {
8292 if (!ssh
->kex_in_progress
&& ssh
->version
== 2) {
8293 do_ssh2_transport(ssh
, "at user request", -1, NULL
);
8295 } else if (code
== TS_BRK
) {
8296 if (ssh
->state
== SSH_STATE_CLOSED
8297 || ssh
->state
== SSH_STATE_PREPACKET
) return;
8298 if (ssh
->version
== 1) {
8299 logevent("Unable to send BREAK signal in SSH-1");
8300 } else if (ssh
->mainchan
) {
8301 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8302 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
8303 ssh2_pkt_addstring(pktout
, "break");
8304 ssh2_pkt_addbool(pktout
, 0);
8305 ssh2_pkt_adduint32(pktout
, 0); /* default break length */
8306 ssh2_pkt_send(ssh
, pktout
);
8309 /* Is is a POSIX signal? */
8310 char *signame
= NULL
;
8311 if (code
== TS_SIGABRT
) signame
= "ABRT";
8312 if (code
== TS_SIGALRM
) signame
= "ALRM";
8313 if (code
== TS_SIGFPE
) signame
= "FPE";
8314 if (code
== TS_SIGHUP
) signame
= "HUP";
8315 if (code
== TS_SIGILL
) signame
= "ILL";
8316 if (code
== TS_SIGINT
) signame
= "INT";
8317 if (code
== TS_SIGKILL
) signame
= "KILL";
8318 if (code
== TS_SIGPIPE
) signame
= "PIPE";
8319 if (code
== TS_SIGQUIT
) signame
= "QUIT";
8320 if (code
== TS_SIGSEGV
) signame
= "SEGV";
8321 if (code
== TS_SIGTERM
) signame
= "TERM";
8322 if (code
== TS_SIGUSR1
) signame
= "USR1";
8323 if (code
== TS_SIGUSR2
) signame
= "USR2";
8324 /* The SSH-2 protocol does in principle support arbitrary named
8325 * signals, including signame@domain, but we don't support those. */
8327 /* It's a signal. */
8328 if (ssh
->version
== 2 && ssh
->mainchan
) {
8329 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8330 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
8331 ssh2_pkt_addstring(pktout
, "signal");
8332 ssh2_pkt_addbool(pktout
, 0);
8333 ssh2_pkt_addstring(pktout
, signame
);
8334 ssh2_pkt_send(ssh
, pktout
);
8335 logeventf(ssh
, "Sent signal SIG%s", signame
);
8338 /* Never heard of it. Do nothing */
8343 void *new_sock_channel(void *handle
, Socket s
)
8345 Ssh ssh
= (Ssh
) handle
;
8346 struct ssh_channel
*c
;
8347 c
= snew(struct ssh_channel
);
8352 c
->localid
= alloc_channel_id(ssh
);
8354 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
8356 bufchain_init(&c
->v
.v2
.outbuffer
);
8357 add234(ssh
->channels
, c
);
8363 * This is called when stdout/stderr (the entity to which
8364 * from_backend sends data) manages to clear some backlog.
8366 static void ssh_unthrottle(void *handle
, int bufsize
)
8368 Ssh ssh
= (Ssh
) handle
;
8369 if (ssh
->version
== 1) {
8370 if (ssh
->v1_stdout_throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
8371 ssh
->v1_stdout_throttling
= 0;
8372 ssh1_throttle(ssh
, -1);
8375 if (ssh
->mainchan
&& ssh
->mainchan
->closes
== 0)
8376 ssh2_set_window(ssh
->mainchan
, OUR_V2_WINSIZE
- bufsize
);
8380 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
8382 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
8384 struct Packet
*pktout
;
8386 logeventf(ssh
, "Opening forwarded connection to %s:%d", hostname
, port
);
8388 if (ssh
->version
== 1) {
8389 send_packet(ssh
, SSH1_MSG_PORT_OPEN
,
8390 PKT_INT
, c
->localid
,
8393 /* PKT_STR, <org:orgport>, */
8396 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
8397 ssh2_pkt_addstring(pktout
, "direct-tcpip");
8398 ssh2_pkt_adduint32(pktout
, c
->localid
);
8399 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
8400 ssh2_pkt_adduint32(pktout
, c
->v
.v2
.locwindow
);/* our window size */
8401 ssh2_pkt_adduint32(pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
8402 ssh2_pkt_addstring(pktout
, hostname
);
8403 ssh2_pkt_adduint32(pktout
, port
);
8405 * We make up values for the originator data; partly it's
8406 * too much hassle to keep track, and partly I'm not
8407 * convinced the server should be told details like that
8408 * about my local network configuration.
8410 ssh2_pkt_addstring(pktout
, "client-side-connection");
8411 ssh2_pkt_adduint32(pktout
, 0);
8412 ssh2_pkt_send(ssh
, pktout
);
8416 static Socket
ssh_socket(void *handle
)
8418 Ssh ssh
= (Ssh
) handle
;
8422 static int ssh_sendok(void *handle
)
8424 Ssh ssh
= (Ssh
) handle
;
8425 return ssh
->send_ok
;
8428 static int ssh_ldisc(void *handle
, int option
)
8430 Ssh ssh
= (Ssh
) handle
;
8431 if (option
== LD_ECHO
)
8432 return ssh
->echoing
;
8433 if (option
== LD_EDIT
)
8434 return ssh
->editing
;
8438 static void ssh_provide_ldisc(void *handle
, void *ldisc
)
8440 Ssh ssh
= (Ssh
) handle
;
8444 static void ssh_provide_logctx(void *handle
, void *logctx
)
8446 Ssh ssh
= (Ssh
) handle
;
8447 ssh
->logctx
= logctx
;
8450 static int ssh_return_exitcode(void *handle
)
8452 Ssh ssh
= (Ssh
) handle
;
8456 return (ssh
->exitcode
>= 0 ? ssh
->exitcode
: 0);
8460 * cfg_info for SSH is the currently running version of the
8461 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
8463 static int ssh_cfg_info(void *handle
)
8465 Ssh ssh
= (Ssh
) handle
;
8466 return ssh
->version
;
8470 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
8471 * that fails. This variable is the means by which scp.c can reach
8472 * into the SSH code and find out which one it got.
8474 extern int ssh_fallback_cmd(void *handle
)
8476 Ssh ssh
= (Ssh
) handle
;
8477 return ssh
->fallback_cmd
;
8480 Backend ssh_backend
= {
8490 ssh_return_exitcode
,