Attack char * vs unsigned char * conversions. In most cases, I've just
[u/mdw/putty] / ssh.c
CommitLineData
374330e2 1#include <stdio.h>
2#include <stdlib.h>
fb09bf1c 3#include <stdarg.h>
4#include <assert.h>
374330e2 5
6#include "putty.h"
dacbd0e8 7#include "tree234.h"
fb09bf1c 8#include "ssh.h"
374330e2 9
10#ifndef FALSE
11#define FALSE 0
12#endif
13#ifndef TRUE
14#define TRUE 1
15#endif
16
32874aea 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 */
58
59#define SSH1_AUTH_TIS 5 /* 0x5 */
60#define SSH1_AUTH_CCARD 16 /* 0x10 */
61
62#define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
b96dc54c 63/* Mask for protoflags we will echo back to server if seen */
32874aea 64#define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
65
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 */
761187b6 86#define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
87#define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
32874aea 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 */
102
00db133f 103/*
104 * Packet type contexts, so that ssh2_pkt_type can correctly decode
105 * the ambiguous type numbers back into the correct type strings.
106 */
107#define SSH2_PKTCTX_DHGROUP1 0x0001
108#define SSH2_PKTCTX_DHGEX 0x0002
109#define SSH2_PKTCTX_PUBLICKEY 0x0010
110#define SSH2_PKTCTX_PASSWORD 0x0020
111#define SSH2_PKTCTX_KBDINTER 0x0040
112#define SSH2_PKTCTX_AUTH_MASK 0x00F0
113
32874aea 114#define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
115#define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
116#define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
117#define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
118#define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
119#define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
120#define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
121#define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
122#define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
123#define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
124#define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
125#define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
126#define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
127#define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
128#define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
38c4a8da 129
130static const char *const ssh2_disconnect_reasons[] = {
131 NULL,
132 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
133 "SSH_DISCONNECT_PROTOCOL_ERROR",
134 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
135 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
136 "SSH_DISCONNECT_MAC_ERROR",
137 "SSH_DISCONNECT_COMPRESSION_ERROR",
138 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
139 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
140 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
141 "SSH_DISCONNECT_CONNECTION_LOST",
142 "SSH_DISCONNECT_BY_APPLICATION",
143 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
144 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
145 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
146 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
147};
9005f3ba 148
32874aea 149#define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
150#define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
151#define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
152#define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
d211621f 153
32874aea 154#define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
fb09bf1c 155
7d503c31 156/*
157 * Various remote-bug flags.
158 */
159#define BUG_CHOKES_ON_SSH1_IGNORE 1
160#define BUG_SSH2_HMAC 2
bd358db1 161#define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
0df73905 162#define BUG_CHOKES_ON_RSA 8
1dd353b5 163#define BUG_SSH2_RSA_PADDING 16
088bde77 164#define BUG_SSH2_DERIVEKEY 32
8e975795 165#define BUG_SSH2_DH_GEX 64
bd358db1 166
00db133f 167#define translate(x) if (type == x) return #x
51470298 168#define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
00db133f 169char *ssh1_pkt_type(int type)
170{
171 translate(SSH1_MSG_DISCONNECT);
172 translate(SSH1_SMSG_PUBLIC_KEY);
173 translate(SSH1_CMSG_SESSION_KEY);
174 translate(SSH1_CMSG_USER);
175 translate(SSH1_CMSG_AUTH_RSA);
176 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
177 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
178 translate(SSH1_CMSG_AUTH_PASSWORD);
179 translate(SSH1_CMSG_REQUEST_PTY);
180 translate(SSH1_CMSG_WINDOW_SIZE);
181 translate(SSH1_CMSG_EXEC_SHELL);
182 translate(SSH1_CMSG_EXEC_CMD);
183 translate(SSH1_SMSG_SUCCESS);
184 translate(SSH1_SMSG_FAILURE);
185 translate(SSH1_CMSG_STDIN_DATA);
186 translate(SSH1_SMSG_STDOUT_DATA);
187 translate(SSH1_SMSG_STDERR_DATA);
188 translate(SSH1_CMSG_EOF);
189 translate(SSH1_SMSG_EXIT_STATUS);
190 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
191 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
192 translate(SSH1_MSG_CHANNEL_DATA);
193 translate(SSH1_MSG_CHANNEL_CLOSE);
194 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
195 translate(SSH1_SMSG_X11_OPEN);
196 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
197 translate(SSH1_MSG_PORT_OPEN);
198 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
199 translate(SSH1_SMSG_AGENT_OPEN);
200 translate(SSH1_MSG_IGNORE);
201 translate(SSH1_CMSG_EXIT_CONFIRMATION);
202 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
203 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
204 translate(SSH1_MSG_DEBUG);
205 translate(SSH1_CMSG_REQUEST_COMPRESSION);
206 translate(SSH1_CMSG_AUTH_TIS);
207 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
208 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
209 translate(SSH1_CMSG_AUTH_CCARD);
210 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
211 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
212 return "unknown";
213}
51470298 214char *ssh2_pkt_type(int pkt_ctx, int type)
00db133f 215{
216 translate(SSH2_MSG_DISCONNECT);
217 translate(SSH2_MSG_IGNORE);
218 translate(SSH2_MSG_UNIMPLEMENTED);
219 translate(SSH2_MSG_DEBUG);
220 translate(SSH2_MSG_SERVICE_REQUEST);
221 translate(SSH2_MSG_SERVICE_ACCEPT);
222 translate(SSH2_MSG_KEXINIT);
223 translate(SSH2_MSG_NEWKEYS);
224 translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP1);
225 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP1);
226 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
227 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
228 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
229 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
230 translate(SSH2_MSG_USERAUTH_REQUEST);
231 translate(SSH2_MSG_USERAUTH_FAILURE);
232 translate(SSH2_MSG_USERAUTH_SUCCESS);
233 translate(SSH2_MSG_USERAUTH_BANNER);
234 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
235 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
236 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
237 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
238 translate(SSH2_MSG_GLOBAL_REQUEST);
239 translate(SSH2_MSG_REQUEST_SUCCESS);
240 translate(SSH2_MSG_REQUEST_FAILURE);
241 translate(SSH2_MSG_CHANNEL_OPEN);
242 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
243 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
244 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
245 translate(SSH2_MSG_CHANNEL_DATA);
246 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
247 translate(SSH2_MSG_CHANNEL_EOF);
248 translate(SSH2_MSG_CHANNEL_CLOSE);
249 translate(SSH2_MSG_CHANNEL_REQUEST);
250 translate(SSH2_MSG_CHANNEL_SUCCESS);
251 translate(SSH2_MSG_CHANNEL_FAILURE);
252 return "unknown";
253}
254#undef translate
255#undef translatec
7d503c31 256
fb09bf1c 257#define GET_32BIT(cp) \
258 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
259 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
260 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
261 ((unsigned long)(unsigned char)(cp)[3]))
262
263#define PUT_32BIT(cp, value) { \
264 (cp)[0] = (unsigned char)((value) >> 24); \
265 (cp)[1] = (unsigned char)((value) >> 16); \
266 (cp)[2] = (unsigned char)((value) >> 8); \
267 (cp)[3] = (unsigned char)(value); }
268
7cca0d81 269enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
972a41c8 270
374330e2 271/* Coroutine mechanics for the sillier bits of the code */
51470298 272#define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
273#define crState(t) \
274 struct t *s; \
275 if (!ssh->t) ssh->t = smalloc(sizeof(struct t)); \
276 s = ssh->t;
277#define crFinish(z) } *crLine = 0; return (z); }
278#define crFinishV } *crLine = 0; return; }
374330e2 279#define crReturn(z) \
280 do {\
51470298 281 *crLine =__LINE__; return (z); case __LINE__:;\
374330e2 282 } while (0)
283#define crReturnV \
284 do {\
51470298 285 *crLine=__LINE__; return; case __LINE__:;\
374330e2 286 } while (0)
51470298 287#define crStop(z) do{ *crLine = 0; return (z); }while(0)
288#define crStopV do{ *crLine = 0; return; }while(0)
fb09bf1c 289#define crWaitUntil(c) do { crReturn(0); } while (!(c))
7cca0d81 290#define crWaitUntilV(c) do { crReturnV; } while (!(c))
374330e2 291
51470298 292typedef struct ssh_tag *Ssh;
293
302121de 294extern char *x11_init(Socket *, char *, void *, void *);
32874aea 295extern void x11_close(Socket);
5471d09a 296extern int x11_send(Socket, char *, int);
302121de 297extern void *x11_invent_auth(char *, int, char *, int);
5471d09a 298extern void x11_unthrottle(Socket s);
299extern void x11_override_throttle(Socket s, int enable);
421d6835 300extern int x11_get_screen_number(char *display);
9c964e85 301
d74d141c 302extern char *pfd_newconnect(Socket * s, char *hostname, int port, void *c);
6ee9b735 303extern char *pfd_addforward(char *desthost, int destport, char *srcaddr,
304 int port, void *backhandle);
d74d141c 305extern void pfd_close(Socket s);
5471d09a 306extern int pfd_send(Socket s, char *data, int len);
d74d141c 307extern void pfd_confirm(Socket s);
5471d09a 308extern void pfd_unthrottle(Socket s);
309extern void pfd_override_throttle(Socket s, int enable);
310
51470298 311static void ssh2_pkt_init(Ssh, int pkt_type);
312static void ssh2_pkt_addbool(Ssh, unsigned char value);
313static void ssh2_pkt_adduint32(Ssh, unsigned long value);
314static void ssh2_pkt_addstring_start(Ssh);
315static void ssh2_pkt_addstring_str(Ssh, char *data);
316static void ssh2_pkt_addstring_data(Ssh, char *data, int len);
317static void ssh2_pkt_addstring(Ssh, char *data);
d8baa528 318static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
51470298 319static void ssh2_pkt_addmp(Ssh, Bignum b);
320static int ssh2_pkt_construct(Ssh);
321static void ssh2_pkt_send(Ssh);
3d63ca2e 322
5471d09a 323/*
324 * Buffer management constants. There are several of these for
325 * various different purposes:
326 *
327 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
328 * on a local data stream before we throttle the whole SSH
329 * connection (in SSH1 only). Throttling the whole connection is
330 * pretty drastic so we set this high in the hope it won't
331 * happen very often.
332 *
333 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
334 * on the SSH connection itself before we defensively throttle
335 * _all_ local data streams. This is pretty drastic too (though
336 * thankfully unlikely in SSH2 since the window mechanism should
337 * ensure that the server never has any need to throttle its end
338 * of the connection), so we set this high as well.
339 *
340 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
341 * channels.
342 */
343
344#define SSH1_BUFFER_LIMIT 32768
345#define SSH_MAX_BACKLOG 32768
346#define OUR_V2_WINSIZE 16384
d74d141c 347
a92dd380 348const static struct ssh_kex *kex_algs[] = {
a92dd380 349 &ssh_diffiehellman_gex,
32874aea 350 &ssh_diffiehellman
351};
e5574168 352
85cc02bb 353const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
e5574168 354
e0e1a00d 355static void *nullmac_make_context(void)
356{
357 return NULL;
358}
359static void nullmac_free_context(void *handle)
360{
361}
362static void nullmac_key(void *handle, unsigned char *key)
32874aea 363{
364}
e0e1a00d 365static void nullmac_generate(void *handle, unsigned char *blk, int len,
32874aea 366 unsigned long seq)
367{
368}
e0e1a00d 369static int nullmac_verify(void *handle, unsigned char *blk, int len,
370 unsigned long seq)
32874aea 371{
372 return 1;
373}
57476f6b 374const static struct ssh_mac ssh_mac_none = {
e0e1a00d 375 nullmac_make_context, nullmac_free_context, nullmac_key,
376 nullmac_generate, nullmac_verify, "none", 0
e5574168 377};
8b2715b2 378const static struct ssh_mac *macs[] = {
32874aea 379 &ssh_sha1, &ssh_md5, &ssh_mac_none
380};
8b2715b2 381const static struct ssh_mac *buggymacs[] = {
32874aea 382 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
383};
e5574168 384
5366aed8 385static void *ssh_comp_none_init(void)
386{
387 return NULL;
388}
389static void ssh_comp_none_cleanup(void *handle)
32874aea 390{
391}
5366aed8 392static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
32874aea 393 unsigned char **outblock, int *outlen)
394{
395 return 0;
396}
5366aed8 397static int ssh_comp_none_disable(void *handle)
32874aea 398{
4ba9b64b 399 return 0;
400}
57476f6b 401const static struct ssh_compress ssh_comp_none = {
4ba9b64b 402 "none",
5366aed8 403 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
404 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
405 ssh_comp_none_disable, NULL
e5574168 406};
4ba9b64b 407extern const struct ssh_compress ssh_zlib;
408const static struct ssh_compress *compressions[] = {
32874aea 409 &ssh_zlib, &ssh_comp_none
410};
374330e2 411
32874aea 412enum { /* channel types */
783415f8 413 CHAN_MAINSESSION,
414 CHAN_X11,
415 CHAN_AGENT,
bc240b21 416 CHAN_SOCKDATA,
417 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
783415f8 418};
419
dacbd0e8 420/*
421 * 2-3-4 tree storing channels.
422 */
423struct ssh_channel {
51470298 424 Ssh ssh; /* pointer back to main context */
d211621f 425 unsigned remoteid, localid;
dacbd0e8 426 int type;
0357890f 427 /*
428 * In SSH1, this value contains four bits:
429 *
430 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
431 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
432 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
433 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
434 *
435 * A channel is completely finished with when all four bits are set.
436 */
dacbd0e8 437 int closes;
5471d09a 438 union {
439 struct ssh1_data_channel {
440 int throttling;
441 } v1;
442 struct ssh2_data_channel {
443 bufchain outbuffer;
444 unsigned remwindow, remmaxpkt;
445 unsigned locwindow;
446 } v2;
447 } v;
dacbd0e8 448 union {
32874aea 449 struct ssh_agent_channel {
450 unsigned char *message;
451 unsigned char msglen[4];
452 int lensofar, totallen;
453 } a;
454 struct ssh_x11_channel {
455 Socket s;
456 } x11;
d74d141c 457 struct ssh_pfd_channel {
458 Socket s;
459 } pfd;
dacbd0e8 460 } u;
461};
57476f6b 462
d74d141c 463/*
bc240b21 464 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
465 * 2 use this structure in different ways, reflecting SSH 2's
466 * altogether saner approach to port forwarding.
467 *
468 * In SSH 1, you arrange a remote forwarding by sending the server
469 * the remote port number, and the local destination host:port.
470 * When a connection comes in, the server sends you back that
471 * host:port pair, and you connect to it. This is a ready-made
472 * security hole if you're not on the ball: a malicious server
473 * could send you back _any_ host:port pair, so if you trustingly
474 * connect to the address it gives you then you've just opened the
475 * entire inside of your corporate network just by connecting
476 * through it to a dodgy SSH server. Hence, we must store a list of
477 * host:port pairs we _are_ trying to forward to, and reject a
478 * connection request from the server if it's not in the list.
479 *
480 * In SSH 2, each side of the connection minds its own business and
481 * doesn't send unnecessary information to the other. You arrange a
482 * remote forwarding by sending the server just the remote port
483 * number. When a connection comes in, the server tells you which
484 * of its ports was connected to; and _you_ have to remember what
485 * local host:port pair went with that port number.
486 *
487 * Hence: in SSH 1 this structure stores host:port pairs we intend
488 * to allow connections to, and is indexed by those host:port
489 * pairs. In SSH 2 it stores a mapping from source port to
490 * destination host:port pair, and is indexed by source port.
d74d141c 491 */
492struct ssh_rportfwd {
bc240b21 493 unsigned sport, dport;
494 char dhost[256];
d74d141c 495};
496
57476f6b 497struct Packet {
498 long length;
499 int type;
500 unsigned char *data;
501 unsigned char *body;
502 long savedpos;
503 long maxlen;
504};
505
51470298 506static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt);
507static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt);
508static void ssh_size(void *handle, int width, int height);
509static void ssh_special(void *handle, Telnet_Special);
5471d09a 510static int ssh2_try_send(struct ssh_channel *c);
51470298 511static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
512static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
5471d09a 513static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
51470298 514static int ssh_sendbuffer(void *handle);
57476f6b 515
51470298 516struct rdpkt1_state_tag {
57476f6b 517 long len, pad, biglen, to_read;
518 unsigned long realcrc, gotcrc;
519 unsigned char *p;
520 int i;
521 int chunk;
51470298 522};
57476f6b 523
51470298 524struct rdpkt2_state_tag {
960e736a 525 long len, pad, payload, packetlen, maclen;
526 int i;
527 int cipherblk;
528 unsigned long incoming_sequence;
51470298 529};
530
531struct ssh_tag {
532 const struct plug_function_table *fn;
533 /* the above field _must_ be first in the structure */
534
535 SHA_State exhash, exhashbase;
536
537 Socket s;
538
b9d7bcad 539 void *ldisc;
a8327734 540 void *logctx;
b9d7bcad 541
51470298 542 unsigned char session_key[32];
543 int v1_compressing;
544 int v1_remote_protoflags;
545 int v1_local_protoflags;
546 int agentfwd_enabled;
547 int X11_fwd_enabled;
548 int remote_bugs;
549 const struct ssh_cipher *cipher;
371e569c 550 void *v1_cipher_ctx;
0183b242 551 void *crcda_ctx;
51470298 552 const struct ssh2_cipher *cscipher, *sccipher;
371e569c 553 void *cs_cipher_ctx, *sc_cipher_ctx;
51470298 554 const struct ssh_mac *csmac, *scmac;
e0e1a00d 555 void *cs_mac_ctx, *sc_mac_ctx;
51470298 556 const struct ssh_compress *cscomp, *sccomp;
5366aed8 557 void *cs_comp_ctx, *sc_comp_ctx;
51470298 558 const struct ssh_kex *kex;
559 const struct ssh_signkey *hostkey;
560 unsigned char v2_session_id[20];
27cd7fc2 561 void *kex_ctx;
51470298 562
563 char *savedhost;
564 int savedport;
565 int send_ok;
566 int echoing, editing;
567
568 void *frontend;
569
570 int term_width, term_height;
571
572 tree234 *channels; /* indexed by local id */
573 struct ssh_channel *mainchan; /* primary session channel */
574 int exitcode;
575
576 tree234 *rportfwds;
577
578 enum {
579 SSH_STATE_PREPACKET,
580 SSH_STATE_BEFORE_SIZE,
581 SSH_STATE_INTERMED,
582 SSH_STATE_SESSION,
583 SSH_STATE_CLOSED
584 } state;
585
586 int size_needed, eof_needed;
587
588 struct Packet pktin;
589 struct Packet pktout;
590 unsigned char *deferred_send_data;
591 int deferred_len, deferred_size;
592
593 /*
594 * Gross hack: pscp will try to start SFTP but fall back to
595 * scp1 if that fails. This variable is the means by which
596 * scp.c can reach into the SSH code and find out which one it
597 * got.
598 */
599 int fallback_cmd;
600
601 /*
602 * Used for username and password input.
603 */
604 char *userpass_input_buffer;
605 int userpass_input_buflen;
606 int userpass_input_bufpos;
607 int userpass_input_echo;
608
609 char *portfwd_strptr;
610 int pkt_ctx;
611
302121de 612 void *x11auth;
613
51470298 614 int version;
615 int v1_throttle_count;
616 int overall_bufsize;
617 int throttled_all;
618 int v1_stdout_throttling;
619 int v2_outgoing_sequence;
620
621 int ssh1_rdpkt_crstate;
622 int ssh2_rdpkt_crstate;
623 int do_ssh_init_crstate;
624 int ssh_gotdata_crstate;
625 int ssh1_protocol_crstate;
626 int do_ssh1_login_crstate;
627 int do_ssh2_transport_crstate;
628 int do_ssh2_authconn_crstate;
629
630 void *do_ssh_init_state;
631 void *do_ssh1_login_state;
632 void *do_ssh2_transport_state;
633 void *do_ssh2_authconn_state;
634
635 struct rdpkt1_state_tag rdpkt1_state;
636 struct rdpkt2_state_tag rdpkt2_state;
637
638 void (*protocol) (Ssh ssh, unsigned char *in, int inlen, int ispkt);
639 int (*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
640};
960e736a 641
382908ad 642#define logevent(s) logevent(ssh->frontend, s)
a8327734 643
644/* logevent, only printf-formatted. */
645void logeventf(Ssh ssh, char *fmt, ...)
646{
647 va_list ap;
57356d63 648 char *buf;
a8327734 649
650 va_start(ap, fmt);
57356d63 651 buf = dupvprintf(fmt, ap);
a8327734 652 va_end(ap);
57356d63 653 logevent(buf);
57356d63 654 sfree(buf);
a8327734 655}
656
657#define bombout(msg) ( ssh->state = SSH_STATE_CLOSED, \
658 (ssh->s ? sk_close(ssh->s), ssh->s = NULL : 0), \
659 logeventf msg, connection_fatal msg )
660
32874aea 661static int ssh_channelcmp(void *av, void *bv)
662{
663 struct ssh_channel *a = (struct ssh_channel *) av;
664 struct ssh_channel *b = (struct ssh_channel *) bv;
665 if (a->localid < b->localid)
666 return -1;
667 if (a->localid > b->localid)
668 return +1;
dacbd0e8 669 return 0;
670}
32874aea 671static int ssh_channelfind(void *av, void *bv)
672{
673 unsigned *a = (unsigned *) av;
674 struct ssh_channel *b = (struct ssh_channel *) bv;
675 if (*a < b->localid)
676 return -1;
677 if (*a > b->localid)
678 return +1;
dacbd0e8 679 return 0;
680}
681
bc240b21 682static int ssh_rportcmp_ssh1(void *av, void *bv)
d74d141c 683{
684 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
685 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
686 int i;
bc240b21 687 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
d74d141c 688 return i < 0 ? -1 : +1;
bc240b21 689 if (a->dport > b->dport)
690 return +1;
691 if (a->dport < b->dport)
692 return -1;
693 return 0;
694}
695
696static int ssh_rportcmp_ssh2(void *av, void *bv)
697{
698 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
699 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
cdcbdf3b 700
bc240b21 701 if (a->sport > b->sport)
d74d141c 702 return +1;
bc240b21 703 if (a->sport < b->sport)
704 return -1;
d74d141c 705 return 0;
706}
707
51470298 708static int alloc_channel_id(Ssh ssh)
32874aea 709{
260f3dec 710 const unsigned CHANNEL_NUMBER_OFFSET = 256;
711 unsigned low, high, mid;
d2371c81 712 int tsize;
713 struct ssh_channel *c;
714
715 /*
716 * First-fit allocation of channel numbers: always pick the
717 * lowest unused one. To do this, binary-search using the
718 * counted B-tree to find the largest channel ID which is in a
719 * contiguous sequence from the beginning. (Precisely
720 * everything in that sequence must have ID equal to its tree
721 * index plus CHANNEL_NUMBER_OFFSET.)
722 */
51470298 723 tsize = count234(ssh->channels);
d2371c81 724
32874aea 725 low = -1;
726 high = tsize;
d2371c81 727 while (high - low > 1) {
728 mid = (high + low) / 2;
51470298 729 c = index234(ssh->channels, mid);
d2371c81 730 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
731 low = mid; /* this one is fine */
732 else
733 high = mid; /* this one is past it */
734 }
735 /*
736 * Now low points to either -1, or the tree index of the
737 * largest ID in the initial sequence.
738 */
739 {
740 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
51470298 741 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
d2371c81 742 }
743 return low + 1 + CHANNEL_NUMBER_OFFSET;
744}
745
51470298 746static void c_write(Ssh ssh, char *buf, int len)
32874aea 747{
67779be7 748 if ((flags & FLAG_STDERR)) {
32874aea 749 int i;
750 for (i = 0; i < len; i++)
751 if (buf[i] != '\r')
752 fputc(buf[i], stderr);
fb09bf1c 753 return;
754 }
51470298 755 from_backend(ssh->frontend, 1, buf, len);
3bdaf79d 756}
757
51470298 758static void c_write_untrusted(Ssh ssh, char *buf, int len)
32874aea 759{
a209e957 760 int i;
761 for (i = 0; i < len; i++) {
32874aea 762 if (buf[i] == '\n')
51470298 763 c_write(ssh, "\r\n", 2);
32874aea 764 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
51470298 765 c_write(ssh, buf + i, 1);
a209e957 766 }
767}
768
51470298 769static void c_write_str(Ssh ssh, char *buf)
32874aea 770{
51470298 771 c_write(ssh, buf, strlen(buf));
1408a877 772}
773
fb09bf1c 774/*
775 * Collect incoming data in the incoming packet buffer.
e5574168 776 * Decipher and verify the packet when it is completely read.
777 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
fb09bf1c 778 * Update the *data and *datalen variables.
779 * Return the additional nr of bytes needed, or 0 when
780 * a complete packet is available.
781 */
51470298 782static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
fb09bf1c 783{
51470298 784 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
374330e2 785
51470298 786 crBegin(ssh->ssh1_rdpkt_crstate);
374330e2 787
32874aea 788 next_packet:
37508af4 789
51470298 790 ssh->pktin.type = 0;
791 ssh->pktin.length = 0;
374330e2 792
57476f6b 793 for (st->i = st->len = 0; st->i < 4; st->i++) {
fb09bf1c 794 while ((*datalen) == 0)
32874aea 795 crReturn(4 - st->i);
57476f6b 796 st->len = (st->len << 8) + **data;
fb09bf1c 797 (*data)++, (*datalen)--;
798 }
374330e2 799
57476f6b 800 st->pad = 8 - (st->len % 8);
801 st->biglen = st->len + st->pad;
51470298 802 ssh->pktin.length = st->len - 5;
fb09bf1c 803
51470298 804 if (ssh->pktin.maxlen < st->biglen) {
805 ssh->pktin.maxlen = st->biglen;
806 ssh->pktin.data = srealloc(ssh->pktin.data, st->biglen + APIEXTRA);
fb09bf1c 807 }
374330e2 808
57476f6b 809 st->to_read = st->biglen;
51470298 810 st->p = ssh->pktin.data;
57476f6b 811 while (st->to_read > 0) {
32874aea 812 st->chunk = st->to_read;
fb09bf1c 813 while ((*datalen) == 0)
57476f6b 814 crReturn(st->to_read);
815 if (st->chunk > (*datalen))
816 st->chunk = (*datalen);
817 memcpy(st->p, *data, st->chunk);
818 *data += st->chunk;
819 *datalen -= st->chunk;
820 st->p += st->chunk;
821 st->to_read -= st->chunk;
fb09bf1c 822 }
374330e2 823
0183b242 824 if (ssh->cipher && detect_attack(ssh->crcda_ctx, ssh->pktin.data,
825 st->biglen, NULL)) {
a8327734 826 bombout((ssh,"Network attack (CRC compensation) detected!"));
9a3a93a5 827 crReturn(0);
828 }
829
51470298 830 if (ssh->cipher)
371e569c 831 ssh->cipher->decrypt(ssh->v1_cipher_ctx, ssh->pktin.data, st->biglen);
374330e2 832
51470298 833 st->realcrc = crc32(ssh->pktin.data, st->biglen - 4);
834 st->gotcrc = GET_32BIT(ssh->pktin.data + st->biglen - 4);
57476f6b 835 if (st->gotcrc != st->realcrc) {
a8327734 836 bombout((ssh,"Incorrect CRC received on packet"));
32874aea 837 crReturn(0);
fb09bf1c 838 }
572f871e 839
51470298 840 ssh->pktin.body = ssh->pktin.data + st->pad + 1;
4ba9b64b 841
51470298 842 if (ssh->v1_compressing) {
4ba9b64b 843 unsigned char *decompblk;
844 int decomplen;
5366aed8 845 zlib_decompress_block(ssh->sc_comp_ctx,
846 ssh->pktin.body - 1, ssh->pktin.length + 1,
4ba9b64b 847 &decompblk, &decomplen);
848
51470298 849 if (ssh->pktin.maxlen < st->pad + decomplen) {
850 ssh->pktin.maxlen = st->pad + decomplen;
851 ssh->pktin.data = srealloc(ssh->pktin.data,
852 ssh->pktin.maxlen + APIEXTRA);
853 ssh->pktin.body = ssh->pktin.data + st->pad + 1;
4ba9b64b 854 }
855
51470298 856 memcpy(ssh->pktin.body - 1, decompblk, decomplen);
dcbde236 857 sfree(decompblk);
51470298 858 ssh->pktin.length = decomplen - 1;
4ba9b64b 859 }
860
51470298 861 ssh->pktin.type = ssh->pktin.body[-1];
00db133f 862
a8327734 863 if (ssh->logctx)
864 log_packet(ssh->logctx,
865 PKT_INCOMING, ssh->pktin.type,
866 ssh1_pkt_type(ssh->pktin.type),
867 ssh->pktin.body, ssh->pktin.length);
00db133f 868
51470298 869 if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
870 ssh->pktin.type == SSH1_SMSG_STDERR_DATA ||
871 ssh->pktin.type == SSH1_MSG_DEBUG ||
872 ssh->pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
873 ssh->pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
874 long stringlen = GET_32BIT(ssh->pktin.body);
875 if (stringlen + 4 != ssh->pktin.length) {
a8327734 876 bombout((ssh,"Received data packet with bogus string length"));
32874aea 877 crReturn(0);
878 }
fb09bf1c 879 }
880
51470298 881 if (ssh->pktin.type == SSH1_MSG_DEBUG) {
fb09bf1c 882 /* log debug message */
eb4504cc 883 char buf[512];
51470298 884 int stringlen = GET_32BIT(ssh->pktin.body);
eb4504cc 885 strcpy(buf, "Remote debug message: ");
886 if (stringlen > 480)
887 stringlen = 480;
51470298 888 memcpy(buf + 8, ssh->pktin.body + 4, stringlen);
3d63ca2e 889 buf[8 + stringlen] = '\0';
fb09bf1c 890 logevent(buf);
891 goto next_packet;
51470298 892 } else if (ssh->pktin.type == SSH1_MSG_IGNORE) {
fb09bf1c 893 /* do nothing */
894 goto next_packet;
895 }
896
51470298 897 if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
38c4a8da 898 /* log reason code in disconnect message */
899 char buf[256];
51470298 900 unsigned msglen = GET_32BIT(ssh->pktin.body);
260f3dec 901 unsigned nowlen;
38c4a8da 902 strcpy(buf, "Remote sent disconnect: ");
903 nowlen = strlen(buf);
32874aea 904 if (msglen > sizeof(buf) - nowlen - 1)
905 msglen = sizeof(buf) - nowlen - 1;
51470298 906 memcpy(buf + nowlen, ssh->pktin.body + 4, msglen);
32874aea 907 buf[nowlen + msglen] = '\0';
247308b5 908 /* logevent(buf); (this is now done within the bombout macro) */
a8327734 909 bombout((ssh,"Server sent disconnect message:\n\"%s\"", buf+nowlen));
e14d0f19 910 crReturn(0);
38c4a8da 911 }
912
fb09bf1c 913 crFinish(0);
914}
915
51470298 916static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
e5574168 917{
51470298 918 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
e5574168 919
51470298 920 crBegin(ssh->ssh2_rdpkt_crstate);
e5574168 921
32874aea 922 next_packet:
51470298 923 ssh->pktin.type = 0;
924 ssh->pktin.length = 0;
925 if (ssh->sccipher)
926 st->cipherblk = ssh->sccipher->blksize;
e5574168 927 else
32874aea 928 st->cipherblk = 8;
960e736a 929 if (st->cipherblk < 8)
32874aea 930 st->cipherblk = 8;
960e736a 931
51470298 932 if (ssh->pktin.maxlen < st->cipherblk) {
933 ssh->pktin.maxlen = st->cipherblk;
934 ssh->pktin.data = srealloc(ssh->pktin.data, st->cipherblk + APIEXTRA);
e5574168 935 }
936
937 /*
938 * Acquire and decrypt the first block of the packet. This will
939 * contain the length and padding details.
940 */
32874aea 941 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
e5574168 942 while ((*datalen) == 0)
32874aea 943 crReturn(st->cipherblk - st->i);
51470298 944 ssh->pktin.data[st->i] = *(*data)++;
32874aea 945 (*datalen)--;
e5574168 946 }
4252c9cc 947
51470298 948 if (ssh->sccipher)
371e569c 949 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
950 ssh->pktin.data, st->cipherblk);
e5574168 951
952 /*
953 * Now get the length and padding figures.
954 */
51470298 955 st->len = GET_32BIT(ssh->pktin.data);
956 st->pad = ssh->pktin.data[4];
e5574168 957
958 /*
717dc483 959 * _Completely_ silly lengths should be stomped on before they
960 * do us any more damage.
961 */
962 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
a8327734 963 bombout((ssh,"Incoming packet was garbled on decryption"));
717dc483 964 crReturn(0);
965 }
966
967 /*
e5574168 968 * This enables us to deduce the payload length.
969 */
960e736a 970 st->payload = st->len - st->pad - 1;
e5574168 971
51470298 972 ssh->pktin.length = st->payload + 5;
e5574168 973
974 /*
975 * So now we can work out the total packet length.
976 */
960e736a 977 st->packetlen = st->len + 4;
51470298 978 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
e5574168 979
980 /*
981 * Adjust memory allocation if packet is too big.
982 */
51470298 983 if (ssh->pktin.maxlen < st->packetlen + st->maclen) {
984 ssh->pktin.maxlen = st->packetlen + st->maclen;
985 ssh->pktin.data = srealloc(ssh->pktin.data,
986 ssh->pktin.maxlen + APIEXTRA);
e5574168 987 }
988
989 /*
990 * Read and decrypt the remainder of the packet.
991 */
32874aea 992 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
993 st->i++) {
e5574168 994 while ((*datalen) == 0)
960e736a 995 crReturn(st->packetlen + st->maclen - st->i);
51470298 996 ssh->pktin.data[st->i] = *(*data)++;
32874aea 997 (*datalen)--;
e5574168 998 }
999 /* Decrypt everything _except_ the MAC. */
51470298 1000 if (ssh->sccipher)
371e569c 1001 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1002 ssh->pktin.data + st->cipherblk,
51470298 1003 st->packetlen - st->cipherblk);
e5574168 1004
1005 /*
1006 * Check the MAC.
1007 */
51470298 1008 if (ssh->scmac
e0e1a00d 1009 && !ssh->scmac->verify(ssh->sc_mac_ctx, ssh->pktin.data, st->len + 4,
51470298 1010 st->incoming_sequence)) {
a8327734 1011 bombout((ssh,"Incorrect MAC received on packet"));
32874aea 1012 crReturn(0);
8d5de777 1013 }
32874aea 1014 st->incoming_sequence++; /* whether or not we MACed */
e5574168 1015
4ba9b64b 1016 /*
1017 * Decompress packet payload.
1018 */
1019 {
1020 unsigned char *newpayload;
1021 int newlen;
51470298 1022 if (ssh->sccomp &&
5366aed8 1023 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1024 ssh->pktin.data + 5, ssh->pktin.length - 5,
51470298 1025 &newpayload, &newlen)) {
1026 if (ssh->pktin.maxlen < newlen + 5) {
1027 ssh->pktin.maxlen = newlen + 5;
1028 ssh->pktin.data = srealloc(ssh->pktin.data,
1029 ssh->pktin.maxlen + APIEXTRA);
4ba9b64b 1030 }
51470298 1031 ssh->pktin.length = 5 + newlen;
1032 memcpy(ssh->pktin.data + 5, newpayload, newlen);
dcbde236 1033 sfree(newpayload);
4ba9b64b 1034 }
1035 }
1036
51470298 1037 ssh->pktin.savedpos = 6;
1038 ssh->pktin.type = ssh->pktin.data[5];
e5574168 1039
a8327734 1040 if (ssh->logctx)
1041 log_packet(ssh->logctx, PKT_INCOMING, ssh->pktin.type,
1042 ssh2_pkt_type(ssh->pkt_ctx, ssh->pktin.type),
1043 ssh->pktin.data+6, ssh->pktin.length-6);
00db133f 1044
51470298 1045 switch (ssh->pktin.type) {
3d63ca2e 1046 /*
1047 * These packets we must handle instantly.
1048 */
1049 case SSH2_MSG_DISCONNECT:
1050 {
1051 /* log reason code in disconnect message */
57356d63 1052 char *buf;
1053 int nowlen;
51470298 1054 int reason = GET_32BIT(ssh->pktin.data + 6);
1055 unsigned msglen = GET_32BIT(ssh->pktin.data + 10);
57356d63 1056
3d63ca2e 1057 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
57356d63 1058 buf = dupprintf("Received disconnect message (%s)",
1059 ssh2_disconnect_reasons[reason]);
3d63ca2e 1060 } else {
57356d63 1061 buf = dupprintf("Received disconnect message (unknown"
1062 " type %d)", reason);
3d63ca2e 1063 }
1064 logevent(buf);
57356d63 1065 sfree(buf);
1066 buf = dupprintf("Disconnection message text: %n%.*s",
33b82b22 1067 &nowlen, msglen, ssh->pktin.data + 14);
3d63ca2e 1068 logevent(buf);
a8327734 1069 bombout((ssh,"Server sent disconnect message\ntype %d (%s):\n\"%s\"",
3d63ca2e 1070 reason,
1071 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
1072 ssh2_disconnect_reasons[reason] : "unknown",
1073 buf+nowlen));
57356d63 1074 sfree(buf);
3d63ca2e 1075 crReturn(0);
1076 }
1077 break;
1078 case SSH2_MSG_IGNORE:
1079 goto next_packet;
1080 case SSH2_MSG_DEBUG:
1081 {
1082 /* log the debug message */
1083 char buf[512];
51470298 1084 /* int display = ssh->pktin.body[6]; */
1085 int stringlen = GET_32BIT(ssh->pktin.data+7);
3d63ca2e 1086 int prefix;
1087 strcpy(buf, "Remote debug message: ");
1088 prefix = strlen(buf);
51470298 1089 if (stringlen > (int)(sizeof(buf)-prefix-1))
3d63ca2e 1090 stringlen = sizeof(buf)-prefix-1;
51470298 1091 memcpy(buf + prefix, ssh->pktin.data + 11, stringlen);
3d63ca2e 1092 buf[prefix + stringlen] = '\0';
1093 logevent(buf);
38c4a8da 1094 }
3d63ca2e 1095 goto next_packet; /* FIXME: print the debug message */
1096
1097 /*
1098 * These packets we need do nothing about here.
1099 */
1100 case SSH2_MSG_UNIMPLEMENTED:
1101 case SSH2_MSG_SERVICE_REQUEST:
1102 case SSH2_MSG_SERVICE_ACCEPT:
1103 case SSH2_MSG_KEXINIT:
1104 case SSH2_MSG_NEWKEYS:
1105 case SSH2_MSG_KEXDH_INIT:
1106 case SSH2_MSG_KEXDH_REPLY:
1107 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1108 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1109 case SSH2_MSG_KEX_DH_GEX_INIT:
1110 case SSH2_MSG_KEX_DH_GEX_REPLY:
1111 case SSH2_MSG_USERAUTH_REQUEST:
1112 case SSH2_MSG_USERAUTH_FAILURE:
1113 case SSH2_MSG_USERAUTH_SUCCESS:
1114 case SSH2_MSG_USERAUTH_BANNER:
1115 case SSH2_MSG_USERAUTH_PK_OK:
1116 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1117 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1118 case SSH2_MSG_USERAUTH_INFO_RESPONSE:
1119 case SSH2_MSG_GLOBAL_REQUEST:
1120 case SSH2_MSG_REQUEST_SUCCESS:
1121 case SSH2_MSG_REQUEST_FAILURE:
1122 case SSH2_MSG_CHANNEL_OPEN:
1123 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1124 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1125 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1126 case SSH2_MSG_CHANNEL_DATA:
1127 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1128 case SSH2_MSG_CHANNEL_EOF:
1129 case SSH2_MSG_CHANNEL_CLOSE:
1130 case SSH2_MSG_CHANNEL_REQUEST:
1131 case SSH2_MSG_CHANNEL_SUCCESS:
1132 case SSH2_MSG_CHANNEL_FAILURE:
1133 break;
1134
1135 /*
1136 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1137 */
1138 default:
51470298 1139 ssh2_pkt_init(ssh, SSH2_MSG_UNIMPLEMENTED);
1140 ssh2_pkt_adduint32(ssh, st->incoming_sequence - 1);
1141 ssh2_pkt_send(ssh);
3d63ca2e 1142 break;
38c4a8da 1143 }
1144
e5574168 1145 crFinish(0);
1146}
1147
51470298 1148static void ssh1_pktout_size(Ssh ssh, int len)
32874aea 1149{
374330e2 1150 int pad, biglen;
1151
1152 len += 5; /* type and CRC */
32874aea 1153 pad = 8 - (len % 8);
374330e2 1154 biglen = len + pad;
1155
51470298 1156 ssh->pktout.length = len - 5;
1157 if (ssh->pktout.maxlen < biglen) {
1158 ssh->pktout.maxlen = biglen;
8f203108 1159#ifdef MSCRYPTOAPI
fb09bf1c 1160 /* Allocate enough buffer space for extra block
8f203108 1161 * for MS CryptEncrypt() */
51470298 1162 ssh->pktout.data = srealloc(ssh->pktout.data, biglen + 12);
8f203108 1163#else
51470298 1164 ssh->pktout.data = srealloc(ssh->pktout.data, biglen + 4);
8f203108 1165#endif
374330e2 1166 }
51470298 1167 ssh->pktout.body = ssh->pktout.data + 4 + pad + 1;
4ba9b64b 1168}
374330e2 1169
51470298 1170static void s_wrpkt_start(Ssh ssh, int type, int len)
32874aea 1171{
51470298 1172 ssh1_pktout_size(ssh, len);
1173 ssh->pktout.type = type;
374330e2 1174}
1175
51470298 1176static int s_wrpkt_prepare(Ssh ssh)
32874aea 1177{
374330e2 1178 int pad, len, biglen, i;
1179 unsigned long crc;
1180
51470298 1181 ssh->pktout.body[-1] = ssh->pktout.type;
4ba9b64b 1182
a8327734 1183 if (ssh->logctx)
1184 log_packet(ssh->logctx, PKT_OUTGOING, ssh->pktout.type,
1185 ssh1_pkt_type(ssh->pktout.type),
1186 ssh->pktout.body, ssh->pktout.length);
00db133f 1187
51470298 1188 if (ssh->v1_compressing) {
4ba9b64b 1189 unsigned char *compblk;
1190 int complen;
5366aed8 1191 zlib_compress_block(ssh->cs_comp_ctx,
1192 ssh->pktout.body - 1, ssh->pktout.length + 1,
4ba9b64b 1193 &compblk, &complen);
51470298 1194 ssh1_pktout_size(ssh, complen - 1);
1195 memcpy(ssh->pktout.body - 1, compblk, complen);
dcbde236 1196 sfree(compblk);
4ba9b64b 1197 }
1198
51470298 1199 len = ssh->pktout.length + 5; /* type and CRC */
32874aea 1200 pad = 8 - (len % 8);
374330e2 1201 biglen = len + pad;
1202
32874aea 1203 for (i = 0; i < pad; i++)
51470298 1204 ssh->pktout.data[i + 4] = random_byte();
1205 crc = crc32(ssh->pktout.data + 4, biglen - 4);
1206 PUT_32BIT(ssh->pktout.data + biglen, crc);
1207 PUT_32BIT(ssh->pktout.data, len);
374330e2 1208
51470298 1209 if (ssh->cipher)
371e569c 1210 ssh->cipher->encrypt(ssh->v1_cipher_ctx, ssh->pktout.data + 4, biglen);
374330e2 1211
32874aea 1212 return biglen + 4;
39065bed 1213}
1214
51470298 1215static void s_wrpkt(Ssh ssh)
32874aea 1216{
5471d09a 1217 int len, backlog;
51470298 1218 len = s_wrpkt_prepare(ssh);
d8baa528 1219 backlog = sk_write(ssh->s, (char *)ssh->pktout.data, len);
5471d09a 1220 if (backlog > SSH_MAX_BACKLOG)
51470298 1221 ssh_throttle_all(ssh, 1, backlog);
39065bed 1222}
1223
51470298 1224static void s_wrpkt_defer(Ssh ssh)
32874aea 1225{
39065bed 1226 int len;
51470298 1227 len = s_wrpkt_prepare(ssh);
1228 if (ssh->deferred_len + len > ssh->deferred_size) {
1229 ssh->deferred_size = ssh->deferred_len + len + 128;
1230 ssh->deferred_send_data = srealloc(ssh->deferred_send_data,
1231 ssh->deferred_size);
39065bed 1232 }
51470298 1233 memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
1234 ssh->deferred_len += len;
374330e2 1235}
1236
fb09bf1c 1237/*
39065bed 1238 * Construct a packet with the specified contents.
fb09bf1c 1239 */
51470298 1240static void construct_packet(Ssh ssh, int pkttype, va_list ap1, va_list ap2)
fb09bf1c 1241{
fb09bf1c 1242 unsigned char *p, *argp, argchar;
1243 unsigned long argint;
1244 int pktlen, argtype, arglen;
7cca0d81 1245 Bignum bn;
fb09bf1c 1246
1247 pktlen = 0;
39065bed 1248 while ((argtype = va_arg(ap1, int)) != PKT_END) {
fb09bf1c 1249 switch (argtype) {
1250 case PKT_INT:
39065bed 1251 (void) va_arg(ap1, int);
fb09bf1c 1252 pktlen += 4;
1253 break;
1254 case PKT_CHAR:
1ec39246 1255 (void) va_arg(ap1, int);
fb09bf1c 1256 pktlen++;
1257 break;
1258 case PKT_DATA:
39065bed 1259 (void) va_arg(ap1, unsigned char *);
1260 arglen = va_arg(ap1, int);
fb09bf1c 1261 pktlen += arglen;
1262 break;
1263 case PKT_STR:
39065bed 1264 argp = va_arg(ap1, unsigned char *);
d8baa528 1265 arglen = strlen((char *)argp);
fb09bf1c 1266 pktlen += 4 + arglen;
1267 break;
7cca0d81 1268 case PKT_BIGNUM:
39065bed 1269 bn = va_arg(ap1, Bignum);
32874aea 1270 pktlen += ssh1_bignum_length(bn);
7cca0d81 1271 break;
fb09bf1c 1272 default:
1273 assert(0);
1274 }
1275 }
fb09bf1c 1276
51470298 1277 s_wrpkt_start(ssh, pkttype, pktlen);
1278 p = ssh->pktout.body;
fb09bf1c 1279
39065bed 1280 while ((argtype = va_arg(ap2, int)) != PKT_END) {
fb09bf1c 1281 switch (argtype) {
1282 case PKT_INT:
39065bed 1283 argint = va_arg(ap2, int);
fb09bf1c 1284 PUT_32BIT(p, argint);
1285 p += 4;
1286 break;
1287 case PKT_CHAR:
1ec39246 1288 argchar = (unsigned char) va_arg(ap2, int);
fb09bf1c 1289 *p = argchar;
1290 p++;
1291 break;
1292 case PKT_DATA:
39065bed 1293 argp = va_arg(ap2, unsigned char *);
1294 arglen = va_arg(ap2, int);
fb09bf1c 1295 memcpy(p, argp, arglen);
1296 p += arglen;
1297 break;
1298 case PKT_STR:
39065bed 1299 argp = va_arg(ap2, unsigned char *);
d8baa528 1300 arglen = strlen((char *)argp);
fb09bf1c 1301 PUT_32BIT(p, arglen);
1302 memcpy(p + 4, argp, arglen);
1303 p += 4 + arglen;
1304 break;
7cca0d81 1305 case PKT_BIGNUM:
39065bed 1306 bn = va_arg(ap2, Bignum);
32874aea 1307 p += ssh1_write_bignum(p, bn);
7cca0d81 1308 break;
fb09bf1c 1309 }
1310 }
39065bed 1311}
fb09bf1c 1312
51470298 1313static void send_packet(Ssh ssh, int pkttype, ...)
32874aea 1314{
39065bed 1315 va_list ap1, ap2;
1316 va_start(ap1, pkttype);
1317 va_start(ap2, pkttype);
51470298 1318 construct_packet(ssh, pkttype, ap1, ap2);
1319 s_wrpkt(ssh);
fb09bf1c 1320}
1321
51470298 1322static void defer_packet(Ssh ssh, int pkttype, ...)
32874aea 1323{
39065bed 1324 va_list ap1, ap2;
1325 va_start(ap1, pkttype);
1326 va_start(ap2, pkttype);
51470298 1327 construct_packet(ssh, pkttype, ap1, ap2);
1328 s_wrpkt_defer(ssh);
39065bed 1329}
1330
32874aea 1331static int ssh_versioncmp(char *a, char *b)
1332{
9697bfd2 1333 char *ae, *be;
1334 unsigned long av, bv;
1335
43aa02a7 1336 av = strtoul(a, &ae, 10);
1337 bv = strtoul(b, &be, 10);
32874aea 1338 if (av != bv)
1339 return (av < bv ? -1 : +1);
1340 if (*ae == '.')
1341 ae++;
1342 if (*be == '.')
1343 be++;
43aa02a7 1344 av = strtoul(ae, &ae, 10);
1345 bv = strtoul(be, &be, 10);
32874aea 1346 if (av != bv)
1347 return (av < bv ? -1 : +1);
9697bfd2 1348 return 0;
1349}
1350
e5574168 1351/*
a92dd380 1352 * Utility routines for putting an SSH-protocol `string' and
1353 * `uint32' into a SHA state.
e5574168 1354 */
1355#include <stdio.h>
32874aea 1356static void sha_string(SHA_State * s, void *str, int len)
1357{
e5574168 1358 unsigned char lenblk[4];
e5574168 1359 PUT_32BIT(lenblk, len);
e5574168 1360 SHA_Bytes(s, lenblk, 4);
e5574168 1361 SHA_Bytes(s, str, len);
1362}
1363
32874aea 1364static void sha_uint32(SHA_State * s, unsigned i)
1365{
a92dd380 1366 unsigned char intblk[4];
1367 PUT_32BIT(intblk, i);
1368 SHA_Bytes(s, intblk, 4);
1369}
1370
7cca0d81 1371/*
1372 * SSH2 packet construction functions.
1373 */
51470298 1374static void ssh2_pkt_ensure(Ssh ssh, int length)
32874aea 1375{
51470298 1376 if (ssh->pktout.maxlen < length) {
1377 ssh->pktout.maxlen = length + 256;
1378 ssh->pktout.data = srealloc(ssh->pktout.data,
1379 ssh->pktout.maxlen + APIEXTRA);
1380 if (!ssh->pktout.data)
32874aea 1381 fatalbox("Out of memory");
7cca0d81 1382 }
783415f8 1383}
51470298 1384static void ssh2_pkt_adddata(Ssh ssh, void *data, int len)
32874aea 1385{
51470298 1386 ssh->pktout.length += len;
1387 ssh2_pkt_ensure(ssh, ssh->pktout.length);
1388 memcpy(ssh->pktout.data + ssh->pktout.length - len, data, len);
7cca0d81 1389}
51470298 1390static void ssh2_pkt_addbyte(Ssh ssh, unsigned char byte)
32874aea 1391{
51470298 1392 ssh2_pkt_adddata(ssh, &byte, 1);
7cca0d81 1393}
51470298 1394static void ssh2_pkt_init(Ssh ssh, int pkt_type)
32874aea 1395{
51470298 1396 ssh->pktout.length = 5;
1397 ssh2_pkt_addbyte(ssh, (unsigned char) pkt_type);
7cca0d81 1398}
51470298 1399static void ssh2_pkt_addbool(Ssh ssh, unsigned char value)
32874aea 1400{
51470298 1401 ssh2_pkt_adddata(ssh, &value, 1);
7cca0d81 1402}
51470298 1403static void ssh2_pkt_adduint32(Ssh ssh, unsigned long value)
32874aea 1404{
7cca0d81 1405 unsigned char x[4];
1406 PUT_32BIT(x, value);
51470298 1407 ssh2_pkt_adddata(ssh, x, 4);
7cca0d81 1408}
51470298 1409static void ssh2_pkt_addstring_start(Ssh ssh)
32874aea 1410{
51470298 1411 ssh2_pkt_adduint32(ssh, 0);
1412 ssh->pktout.savedpos = ssh->pktout.length;
7cca0d81 1413}
51470298 1414static void ssh2_pkt_addstring_str(Ssh ssh, char *data)
32874aea 1415{
51470298 1416 ssh2_pkt_adddata(ssh, data, strlen(data));
1417 PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
1418 ssh->pktout.length - ssh->pktout.savedpos);
7cca0d81 1419}
51470298 1420static void ssh2_pkt_addstring_data(Ssh ssh, char *data, int len)
32874aea 1421{
51470298 1422 ssh2_pkt_adddata(ssh, data, len);
1423 PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
1424 ssh->pktout.length - ssh->pktout.savedpos);
7cca0d81 1425}
51470298 1426static void ssh2_pkt_addstring(Ssh ssh, char *data)
32874aea 1427{
51470298 1428 ssh2_pkt_addstring_start(ssh);
1429 ssh2_pkt_addstring_str(ssh, data);
7cca0d81 1430}
d8baa528 1431static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
32874aea 1432{
7cca0d81 1433 unsigned char *p;
32874aea 1434 int i, n = (bignum_bitcount(b) + 7) / 8;
3709bfe9 1435 p = smalloc(n + 1);
7cca0d81 1436 if (!p)
32874aea 1437 fatalbox("out of memory");
7cca0d81 1438 p[0] = 0;
3709bfe9 1439 for (i = 1; i <= n; i++)
32874aea 1440 p[i] = bignum_byte(b, n - i);
7cca0d81 1441 i = 0;
32874aea 1442 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1443 i++;
1444 memmove(p, p + i, n + 1 - i);
1445 *len = n + 1 - i;
7cca0d81 1446 return p;
1447}
51470298 1448static void ssh2_pkt_addmp(Ssh ssh, Bignum b)
32874aea 1449{
7cca0d81 1450 unsigned char *p;
1451 int len;
1452 p = ssh2_mpint_fmt(b, &len);
51470298 1453 ssh2_pkt_addstring_start(ssh);
d8baa528 1454 ssh2_pkt_addstring_data(ssh, (char *)p, len);
dcbde236 1455 sfree(p);
7cca0d81 1456}
b185170a 1457
1458/*
1459 * Construct an SSH2 final-form packet: compress it, encrypt it,
1460 * put the MAC on it. Final packet, ready to be sent, is stored in
51470298 1461 * ssh->pktout.data. Total length is returned.
b185170a 1462 */
51470298 1463static int ssh2_pkt_construct(Ssh ssh)
32874aea 1464{
7cca0d81 1465 int cipherblk, maclen, padding, i;
7cca0d81 1466
a8327734 1467 if (ssh->logctx)
1468 log_packet(ssh->logctx, PKT_OUTGOING, ssh->pktout.data[5],
1469 ssh2_pkt_type(ssh->pkt_ctx, ssh->pktout.data[5]),
1470 ssh->pktout.data + 6, ssh->pktout.length - 6);
00db133f 1471
7cca0d81 1472 /*
4ba9b64b 1473 * Compress packet payload.
1474 */
4ba9b64b 1475 {
1476 unsigned char *newpayload;
1477 int newlen;
51470298 1478 if (ssh->cscomp &&
5366aed8 1479 ssh->cscomp->compress(ssh->cs_comp_ctx, ssh->pktout.data + 5,
1480 ssh->pktout.length - 5,
51470298 1481 &newpayload, &newlen)) {
1482 ssh->pktout.length = 5;
1483 ssh2_pkt_adddata(ssh, newpayload, newlen);
dcbde236 1484 sfree(newpayload);
4ba9b64b 1485 }
1486 }
1487
1488 /*
7cca0d81 1489 * Add padding. At least four bytes, and must also bring total
1490 * length (minus MAC) up to a multiple of the block size.
1491 */
51470298 1492 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
32874aea 1493 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
7cca0d81 1494 padding = 4;
32874aea 1495 padding +=
51470298 1496 (cipherblk - (ssh->pktout.length + padding) % cipherblk) % cipherblk;
1497 maclen = ssh->csmac ? ssh->csmac->len : 0;
1498 ssh2_pkt_ensure(ssh, ssh->pktout.length + padding + maclen);
1499 ssh->pktout.data[4] = padding;
7cca0d81 1500 for (i = 0; i < padding; i++)
51470298 1501 ssh->pktout.data[ssh->pktout.length + i] = random_byte();
1502 PUT_32BIT(ssh->pktout.data, ssh->pktout.length + padding - 4);
1503 if (ssh->csmac)
e0e1a00d 1504 ssh->csmac->generate(ssh->cs_mac_ctx, ssh->pktout.data,
1505 ssh->pktout.length + padding,
51470298 1506 ssh->v2_outgoing_sequence);
1507 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1508
1509 if (ssh->cscipher)
371e569c 1510 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1511 ssh->pktout.data, ssh->pktout.length + padding);
51470298 1512
1513 /* Ready-to-send packet starts at ssh->pktout.data. We return length. */
1514 return ssh->pktout.length + padding + maclen;
b185170a 1515}
1516
1517/*
1518 * Construct and send an SSH2 packet immediately.
1519 */
51470298 1520static void ssh2_pkt_send(Ssh ssh)
32874aea 1521{
5471d09a 1522 int len;
1523 int backlog;
51470298 1524 len = ssh2_pkt_construct(ssh);
d8baa528 1525 backlog = sk_write(ssh->s, (char *)ssh->pktout.data, len);
5471d09a 1526 if (backlog > SSH_MAX_BACKLOG)
51470298 1527 ssh_throttle_all(ssh, 1, backlog);
b185170a 1528}
1529
1530/*
1531 * Construct an SSH2 packet and add it to a deferred data block.
1532 * Useful for sending multiple packets in a single sk_write() call,
1533 * to prevent a traffic-analysing listener from being able to work
1534 * out the length of any particular packet (such as the password
1535 * packet).
1536 *
1537 * Note that because SSH2 sequence-numbers its packets, this can
1538 * NOT be used as an m4-style `defer' allowing packets to be
1539 * constructed in one order and sent in another.
1540 */
51470298 1541static void ssh2_pkt_defer(Ssh ssh)
32874aea 1542{
51470298 1543 int len = ssh2_pkt_construct(ssh);
1544 if (ssh->deferred_len + len > ssh->deferred_size) {
1545 ssh->deferred_size = ssh->deferred_len + len + 128;
1546 ssh->deferred_send_data = srealloc(ssh->deferred_send_data,
1547 ssh->deferred_size);
b185170a 1548 }
51470298 1549 memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
1550 ssh->deferred_len += len;
b185170a 1551}
1552
1553/*
1554 * Send the whole deferred data block constructed by
39065bed 1555 * ssh2_pkt_defer() or SSH1's defer_packet().
b185170a 1556 */
51470298 1557static void ssh_pkt_defersend(Ssh ssh)
32874aea 1558{
5471d09a 1559 int backlog;
d8baa528 1560 backlog = sk_write(ssh->s, (char *)ssh->deferred_send_data,
1561 ssh->deferred_len);
51470298 1562 ssh->deferred_len = ssh->deferred_size = 0;
1563 sfree(ssh->deferred_send_data);
1564 ssh->deferred_send_data = NULL;
5471d09a 1565 if (backlog > SSH_MAX_BACKLOG)
51470298 1566 ssh_throttle_all(ssh, 1, backlog);
7cca0d81 1567}
1568
1569#if 0
32874aea 1570void bndebug(char *string, Bignum b)
1571{
7cca0d81 1572 unsigned char *p;
1573 int i, len;
1574 p = ssh2_mpint_fmt(b, &len);
1575 debug(("%s", string));
1576 for (i = 0; i < len; i++)
32874aea 1577 debug((" %02x", p[i]));
765c4200 1578 debug(("\n"));
dcbde236 1579 sfree(p);
7cca0d81 1580}
1581#endif
1582
32874aea 1583static void sha_mpint(SHA_State * s, Bignum b)
1584{
7cca0d81 1585 unsigned char *p;
1586 int len;
1587 p = ssh2_mpint_fmt(b, &len);
1588 sha_string(s, p, len);
dcbde236 1589 sfree(p);
7cca0d81 1590}
1591
1592/*
1593 * SSH2 packet decode functions.
1594 */
51470298 1595static unsigned long ssh2_pkt_getuint32(Ssh ssh)
32874aea 1596{
7cca0d81 1597 unsigned long value;
51470298 1598 if (ssh->pktin.length - ssh->pktin.savedpos < 4)
32874aea 1599 return 0; /* arrgh, no way to decline (FIXME?) */
51470298 1600 value = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
1601 ssh->pktin.savedpos += 4;
7cca0d81 1602 return value;
1603}
51470298 1604static int ssh2_pkt_getbool(Ssh ssh)
32874aea 1605{
65a22376 1606 unsigned long value;
51470298 1607 if (ssh->pktin.length - ssh->pktin.savedpos < 1)
32874aea 1608 return 0; /* arrgh, no way to decline (FIXME?) */
51470298 1609 value = ssh->pktin.data[ssh->pktin.savedpos] != 0;
1610 ssh->pktin.savedpos++;
65a22376 1611 return value;
1612}
51470298 1613static void ssh2_pkt_getstring(Ssh ssh, char **p, int *length)
32874aea 1614{
57356d63 1615 int len;
7cca0d81 1616 *p = NULL;
45068b27 1617 *length = 0;
51470298 1618 if (ssh->pktin.length - ssh->pktin.savedpos < 4)
32874aea 1619 return;
57356d63 1620 len = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
1621 if (len < 0)
1622 return;
1623 *length = len;
51470298 1624 ssh->pktin.savedpos += 4;
1625 if (ssh->pktin.length - ssh->pktin.savedpos < *length)
32874aea 1626 return;
d8baa528 1627 *p = (char *)(ssh->pktin.data + ssh->pktin.savedpos);
51470298 1628 ssh->pktin.savedpos += *length;
7cca0d81 1629}
51470298 1630static Bignum ssh2_pkt_getmp(Ssh ssh)
32874aea 1631{
7cca0d81 1632 char *p;
3709bfe9 1633 int length;
7cca0d81 1634 Bignum b;
1635
51470298 1636 ssh2_pkt_getstring(ssh, &p, &length);
7cca0d81 1637 if (!p)
32874aea 1638 return NULL;
8d5de777 1639 if (p[0] & 0x80) {
a8327734 1640 bombout((ssh,"internal error: Can't handle negative mpints"));
32874aea 1641 return NULL;
8d5de777 1642 }
d8baa528 1643 b = bignum_from_bytes((unsigned char *)p, length);
7cca0d81 1644 return b;
1645}
1646
7d503c31 1647/*
1dd353b5 1648 * Helper function to add an SSH2 signature blob to a packet.
1649 * Expects to be shown the public key blob as well as the signature
1650 * blob. Normally works just like ssh2_pkt_addstring, but will
1651 * fiddle with the signature packet if necessary for
1652 * BUG_SSH2_RSA_PADDING.
1653 */
51470298 1654static void ssh2_add_sigblob(Ssh ssh, void *pkblob_v, int pkblob_len,
1dd353b5 1655 void *sigblob_v, int sigblob_len)
1656{
1657 unsigned char *pkblob = (unsigned char *)pkblob_v;
1658 unsigned char *sigblob = (unsigned char *)sigblob_v;
1659
1660 /* dmemdump(pkblob, pkblob_len); */
1661 /* dmemdump(sigblob, sigblob_len); */
1662
1663 /*
1664 * See if this is in fact an ssh-rsa signature and a buggy
1665 * server; otherwise we can just do this the easy way.
1666 */
51470298 1667 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
1dd353b5 1668 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1669 int pos, len, siglen;
1670
1671 /*
1672 * Find the byte length of the modulus.
1673 */
1674
1675 pos = 4+7; /* skip over "ssh-rsa" */
1676 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
1677 len = GET_32BIT(pkblob+pos); /* find length of modulus */
1678 pos += 4; /* find modulus itself */
1679 while (len > 0 && pkblob[pos] == 0)
1680 len--, pos++;
1681 /* debug(("modulus length is %d\n", len)); */
1682
1683 /*
1684 * Now find the signature integer.
1685 */
1686 pos = 4+7; /* skip over "ssh-rsa" */
1687 siglen = GET_32BIT(sigblob+pos);
1688 /* debug(("signature length is %d\n", siglen)); */
1689
1690 if (len != siglen) {
1691 unsigned char newlen[4];
51470298 1692 ssh2_pkt_addstring_start(ssh);
d8baa528 1693 ssh2_pkt_addstring_data(ssh, (char *)sigblob, pos);
1dd353b5 1694 /* dmemdump(sigblob, pos); */
1695 pos += 4; /* point to start of actual sig */
1696 PUT_32BIT(newlen, len);
d8baa528 1697 ssh2_pkt_addstring_data(ssh, (char *)newlen, 4);
1dd353b5 1698 /* dmemdump(newlen, 4); */
1699 newlen[0] = 0;
1700 while (len-- > siglen) {
d8baa528 1701 ssh2_pkt_addstring_data(ssh, (char *)newlen, 1);
1dd353b5 1702 /* dmemdump(newlen, 1); */
1703 }
d8baa528 1704 ssh2_pkt_addstring_data(ssh, (char *)(sigblob+pos), siglen);
1dd353b5 1705 /* dmemdump(sigblob+pos, siglen); */
1706 return;
1707 }
1708
1709 /* Otherwise fall through and do it the easy way. */
1710 }
1711
51470298 1712 ssh2_pkt_addstring_start(ssh);
d8baa528 1713 ssh2_pkt_addstring_data(ssh, (char *)sigblob, sigblob_len);
1dd353b5 1714}
1715
1716/*
7d503c31 1717 * Examine the remote side's version string and compare it against
1718 * a list of known buggy implementations.
1719 */
51470298 1720static void ssh_detect_bugs(Ssh ssh, char *vstring)
32874aea 1721{
1722 char *imp; /* pointer to implementation part */
7d503c31 1723 imp = vstring;
1724 imp += strcspn(imp, "-");
bd358db1 1725 if (*imp) imp++;
7d503c31 1726 imp += strcspn(imp, "-");
bd358db1 1727 if (*imp) imp++;
7d503c31 1728
51470298 1729 ssh->remote_bugs = 0;
7d503c31 1730
2c9c6388 1731 if (cfg.sshbug_ignore1 == BUG_ON ||
1732 (cfg.sshbug_ignore1 == BUG_AUTO &&
1733 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1734 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1735 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25")))) {
32874aea 1736 /*
1737 * These versions don't support SSH1_MSG_IGNORE, so we have
1738 * to use a different defence against password length
1739 * sniffing.
1740 */
51470298 1741 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
32874aea 1742 logevent("We believe remote version has SSH1 ignore bug");
7d503c31 1743 }
1744
2c9c6388 1745 if (cfg.sshbug_plainpw1 == BUG_ON ||
1746 (cfg.sshbug_plainpw1 == BUG_AUTO &&
1747 (!strcmp(imp, "Cisco-1.25")))) {
bd358db1 1748 /*
1749 * These versions need a plain password sent; they can't
1750 * handle having a null and a random length of data after
1751 * the password.
1752 */
51470298 1753 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
bd358db1 1754 logevent("We believe remote version needs a plain SSH1 password");
1755 }
1756
2c9c6388 1757 if (cfg.sshbug_rsa1 == BUG_ON ||
1758 (cfg.sshbug_rsa1 == BUG_AUTO &&
1759 (!strcmp(imp, "Cisco-1.25")))) {
0df73905 1760 /*
1761 * These versions apparently have no clue whatever about
1762 * RSA authentication and will panic and die if they see
1763 * an AUTH_RSA message.
1764 */
51470298 1765 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
0df73905 1766 logevent("We believe remote version can't handle RSA authentication");
1767 }
1768
2c9c6388 1769 if (cfg.sshbug_hmac2 == BUG_ON ||
1770 (cfg.sshbug_hmac2 == BUG_AUTO &&
831301f6 1771 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
1772 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
1773 wc_match("2.1 *", imp)))) {
32874aea 1774 /*
1775 * These versions have the HMAC bug.
1776 */
51470298 1777 ssh->remote_bugs |= BUG_SSH2_HMAC;
32874aea 1778 logevent("We believe remote version has SSH2 HMAC bug");
7d503c31 1779 }
1dd353b5 1780
2c9c6388 1781 if (cfg.sshbug_derivekey2 == BUG_ON ||
1782 (cfg.sshbug_derivekey2 == BUG_AUTO &&
d6430b97 1783 (wc_match("2.0.0*", imp) || wc_match("2.0.1[01]*", imp) ))) {
088bde77 1784 /*
1785 * These versions have the key-derivation bug (failing to
1786 * include the literal shared secret in the hashes that
1787 * generate the keys).
1788 */
51470298 1789 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
088bde77 1790 logevent("We believe remote version has SSH2 key-derivation bug");
1791 }
1792
2c9c6388 1793 if (cfg.sshbug_rsapad2 == BUG_ON ||
1794 (cfg.sshbug_rsapad2 == BUG_AUTO &&
831301f6 1795 (wc_match("OpenSSH_2.[5-9]*", imp) ||
1796 wc_match("OpenSSH_3.[0-2]*", imp)))) {
1dd353b5 1797 /*
1798 * These versions have the SSH2 RSA padding bug.
1799 */
51470298 1800 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
1dd353b5 1801 logevent("We believe remote version has SSH2 RSA padding bug");
1802 }
8e975795 1803
1804 if (cfg.sshbug_dhgex2 == BUG_ON) {
1805 /*
831301f6 1806 * User specified the SSH2 DH GEX bug.
8e975795 1807 */
51470298 1808 ssh->remote_bugs |= BUG_SSH2_DH_GEX;
8e975795 1809 logevent("We believe remote version has SSH2 DH group exchange bug");
1810 }
7d503c31 1811}
1812
51470298 1813static int do_ssh_init(Ssh ssh, unsigned char c)
32874aea 1814{
51470298 1815 struct do_ssh_init_state {
1816 int vslen;
1817 char version[10];
1818 char *vstring;
1819 int vstrsize;
1820 int i;
1821 int proto1, proto2;
1822 };
1823 crState(do_ssh_init_state);
374330e2 1824
51470298 1825 crBegin(ssh->do_ssh_init_crstate);
8df7a775 1826
1827 /* Search for the string "SSH-" in the input. */
51470298 1828 s->i = 0;
8df7a775 1829 while (1) {
1830 static const int transS[] = { 1, 2, 2, 1 };
1831 static const int transH[] = { 0, 0, 3, 0 };
1832 static const int transminus[] = { 0, 0, 0, -1 };
32874aea 1833 if (c == 'S')
51470298 1834 s->i = transS[s->i];
32874aea 1835 else if (c == 'H')
51470298 1836 s->i = transH[s->i];
32874aea 1837 else if (c == '-')
51470298 1838 s->i = transminus[s->i];
32874aea 1839 else
51470298 1840 s->i = 0;
1841 if (s->i < 0)
8df7a775 1842 break;
1843 crReturn(1); /* get another character */
374330e2 1844 }
8df7a775 1845
51470298 1846 s->vstrsize = 16;
1847 s->vstring = smalloc(s->vstrsize);
1848 strcpy(s->vstring, "SSH-");
1849 s->vslen = 4;
1850 s->i = 0;
374330e2 1851 while (1) {
8df7a775 1852 crReturn(1); /* get another char */
51470298 1853 if (s->vslen >= s->vstrsize - 1) {
1854 s->vstrsize += 16;
1855 s->vstring = srealloc(s->vstring, s->vstrsize);
32874aea 1856 }
51470298 1857 s->vstring[s->vslen++] = c;
1858 if (s->i >= 0) {
374330e2 1859 if (c == '-') {
51470298 1860 s->version[s->i] = '\0';
1861 s->i = -1;
1862 } else if (s->i < sizeof(s->version) - 1)
1863 s->version[s->i++] = c;
32874aea 1864 } else if (c == '\n')
374330e2 1865 break;
1866 }
1867
51470298 1868 ssh->agentfwd_enabled = FALSE;
1869 ssh->rdpkt2_state.incoming_sequence = 0;
960e736a 1870
51470298 1871 s->vstring[s->vslen] = 0;
1872 s->vstring[strcspn(s->vstring, "\r\n")] = '\0';/* remove EOL chars */
1873 {
1874 char *vlog;
1875 vlog = smalloc(20 + s->vslen);
1876 sprintf(vlog, "Server version: %s", s->vstring);
1877 logevent(vlog);
1878 sfree(vlog);
1879 }
1880 ssh_detect_bugs(ssh, s->vstring);
c5e9c988 1881
adf799dd 1882 /*
38d228a2 1883 * Decide which SSH protocol version to support.
adf799dd 1884 */
38d228a2 1885
1886 /* Anything strictly below "2.0" means protocol 1 is supported. */
51470298 1887 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
38d228a2 1888 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
51470298 1889 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
38d228a2 1890
51470298 1891 if (cfg.sshprot == 0 && !s->proto1) {
a8327734 1892 bombout((ssh,"SSH protocol version 1 required by user but not provided by server"));
38d228a2 1893 crReturn(0);
1894 }
51470298 1895 if (cfg.sshprot == 3 && !s->proto2) {
a8327734 1896 bombout((ssh,"SSH protocol version 2 required by user but not provided by server"));
38d228a2 1897 crReturn(0);
1898 }
1899
51470298 1900 if (s->proto2 && (cfg.sshprot >= 2 || !s->proto1)) {
32874aea 1901 /*
38d228a2 1902 * Use v2 protocol.
32874aea 1903 */
1904 char verstring[80], vlog[100];
1905 sprintf(verstring, "SSH-2.0-%s", sshver);
51470298 1906 SHA_Init(&ssh->exhashbase);
32874aea 1907 /*
1908 * Hash our version string and their version string.
1909 */
51470298 1910 sha_string(&ssh->exhashbase, verstring, strlen(verstring));
1911 sha_string(&ssh->exhashbase, s->vstring, strcspn(s->vstring, "\r\n"));
32874aea 1912 sprintf(vlog, "We claim version: %s", verstring);
1913 logevent(vlog);
1914 strcat(verstring, "\n");
1915 logevent("Using SSH protocol version 2");
51470298 1916 sk_write(ssh->s, verstring, strlen(verstring));
1917 ssh->protocol = ssh2_protocol;
1918 ssh->version = 2;
1919 ssh->s_rdpkt = ssh2_rdpkt;
e5574168 1920 } else {
32874aea 1921 /*
38d228a2 1922 * Use v1 protocol.
32874aea 1923 */
1924 char verstring[80], vlog[100];
1925 sprintf(verstring, "SSH-%s-%s",
51470298 1926 (ssh_versioncmp(s->version, "1.5") <= 0 ? s->version : "1.5"),
32874aea 1927 sshver);
1928 sprintf(vlog, "We claim version: %s", verstring);
1929 logevent(vlog);
1930 strcat(verstring, "\n");
759712a6 1931
32874aea 1932 logevent("Using SSH protocol version 1");
51470298 1933 sk_write(ssh->s, verstring, strlen(verstring));
1934 ssh->protocol = ssh1_protocol;
1935 ssh->version = 1;
1936 ssh->s_rdpkt = ssh1_rdpkt;
e5574168 1937 }
51470298 1938 ssh->state = SSH_STATE_BEFORE_SIZE;
8df7a775 1939
51470298 1940 sfree(s->vstring);
50526e47 1941
8df7a775 1942 crFinish(0);
1943}
1944
51470298 1945static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
8df7a775 1946{
51470298 1947 crBegin(ssh->ssh_gotdata_crstate);
8df7a775 1948
1949 /*
1950 * To begin with, feed the characters one by one to the
1951 * protocol initialisation / selection function do_ssh_init().
1952 * When that returns 0, we're done with the initial greeting
1953 * exchange and can move on to packet discipline.
1954 */
1955 while (1) {
51470298 1956 int ret; /* need not be kept across crReturn */
8df7a775 1957 if (datalen == 0)
1958 crReturnV; /* more data please */
51470298 1959 ret = do_ssh_init(ssh, *data);
32874aea 1960 data++;
1961 datalen--;
8df7a775 1962 if (ret == 0)
1963 break;
1964 }
1965
1966 /*
1967 * We emerge from that loop when the initial negotiation is
1968 * over and we have selected an s_rdpkt function. Now pass
1969 * everything to s_rdpkt, and then pass the resulting packets
1970 * to the proper protocol handler.
1971 */
1972 if (datalen == 0)
1973 crReturnV;
1974 while (1) {
1975 while (datalen > 0) {
51470298 1976 if (ssh->s_rdpkt(ssh, &data, &datalen) == 0) {
1977 if (ssh->state == SSH_STATE_CLOSED) {
e14d0f19 1978 return;
1979 }
51470298 1980 ssh->protocol(ssh, NULL, 0, 1);
1981 if (ssh->state == SSH_STATE_CLOSED) {
8df7a775 1982 return;
1983 }
1984 }
1985 }
1986 crReturnV;
1987 }
1988 crFinishV;
1989}
1990
32874aea 1991static int ssh_closing(Plug plug, char *error_msg, int error_code,
1992 int calling_back)
1993{
51470298 1994 Ssh ssh = (Ssh) plug;
1995 ssh->state = SSH_STATE_CLOSED;
1996 if (ssh->s) {
1997 sk_close(ssh->s);
1998 ssh->s = NULL;
f3ab576e 1999 }
7e78000d 2000 if (error_msg) {
32874aea 2001 /* A socket error has occurred. */
247308b5 2002 logevent(error_msg);
a8327734 2003 connection_fatal(ssh->frontend, error_msg);
7e78000d 2004 } else {
2005 /* Otherwise, the remote side closed the connection normally. */
8df7a775 2006 }
7e78000d 2007 return 0;
2008}
2009
32874aea 2010static int ssh_receive(Plug plug, int urgent, char *data, int len)
2011{
51470298 2012 Ssh ssh = (Ssh) plug;
d8baa528 2013 ssh_gotdata(ssh, (unsigned char *)data, len);
51470298 2014 if (ssh->state == SSH_STATE_CLOSED) {
2015 if (ssh->s) {
2016 sk_close(ssh->s);
2017 ssh->s = NULL;
32874aea 2018 }
2019 return 0;
3257deae 2020 }
fef97f43 2021 return 1;
374330e2 2022}
2023
5471d09a 2024static void ssh_sent(Plug plug, int bufsize)
2025{
51470298 2026 Ssh ssh = (Ssh) plug;
5471d09a 2027 /*
2028 * If the send backlog on the SSH socket itself clears, we
2029 * should unthrottle the whole world if it was throttled.
2030 */
2031 if (bufsize < SSH_MAX_BACKLOG)
51470298 2032 ssh_throttle_all(ssh, 0, bufsize);
5471d09a 2033}
2034
fb09bf1c 2035/*
8df7a775 2036 * Connect to specified host and port.
2037 * Returns an error message, or NULL on success.
6e1ebb76 2038 * Also places the canonical host name into `realhost'. It must be
2039 * freed by the caller.
8df7a775 2040 */
51470298 2041static char *connect_to_host(Ssh ssh, char *host, int port,
2042 char **realhost, int nodelay)
8df7a775 2043{
51470298 2044 static const struct plug_function_table fn_table = {
7e78000d 2045 ssh_closing,
5471d09a 2046 ssh_receive,
2047 ssh_sent,
2048 NULL
51470298 2049 };
7e78000d 2050
8df7a775 2051 SockAddr addr;
2052 char *err;
8df7a775 2053
51470298 2054 ssh->savedhost = smalloc(1 + strlen(host));
2055 if (!ssh->savedhost)
8df7a775 2056 fatalbox("Out of memory");
51470298 2057 strcpy(ssh->savedhost, host);
8df7a775 2058
2059 if (port < 0)
2060 port = 22; /* default ssh port */
51470298 2061 ssh->savedport = port;
8df7a775 2062
2063 /*
2064 * Try to find host.
2065 */
57356d63 2066 logeventf(ssh, "Looking up host \"%s\"", host);
b7a189f3 2067 addr = name_lookup(host, port, realhost);
32874aea 2068 if ((err = sk_addr_error(addr)))
8df7a775 2069 return err;
2070
8df7a775 2071 /*
2072 * Open socket.
2073 */
3ad9d396 2074 {
57356d63 2075 char addrbuf[100];
3ad9d396 2076 sk_getaddr(addr, addrbuf, 100);
57356d63 2077 logeventf(ssh, "Connecting to %s port %d", addrbuf, port);
3ad9d396 2078 }
51470298 2079 ssh->fn = &fn_table;
2080 ssh->s = new_connection(addr, *realhost, port, 0, 1, nodelay, (Plug) ssh);
2081 if ((err = sk_socket_error(ssh->s))) {
2082 ssh->s = NULL;
8df7a775 2083 return err;
67c4ba2e 2084 }
8df7a775 2085
8df7a775 2086 return NULL;
2087}
2088
2089/*
5471d09a 2090 * Throttle or unthrottle the SSH connection.
2091 */
51470298 2092static void ssh1_throttle(Ssh ssh, int adjust)
5471d09a 2093{
51470298 2094 int old_count = ssh->v1_throttle_count;
2095 ssh->v1_throttle_count += adjust;
2096 assert(ssh->v1_throttle_count >= 0);
2097 if (ssh->v1_throttle_count && !old_count) {
2098 sk_set_frozen(ssh->s, 1);
2099 } else if (!ssh->v1_throttle_count && old_count) {
2100 sk_set_frozen(ssh->s, 0);
5471d09a 2101 }
2102}
2103
2104/*
2105 * Throttle or unthrottle _all_ local data streams (for when sends
2106 * on the SSH connection itself back up).
2107 */
51470298 2108static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
5471d09a 2109{
2110 int i;
2111 struct ssh_channel *c;
2112
51470298 2113 if (enable == ssh->throttled_all)
5471d09a 2114 return;
51470298 2115 ssh->throttled_all = enable;
2116 ssh->overall_bufsize = bufsize;
2117 if (!ssh->channels)
5471d09a 2118 return;
51470298 2119 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
5471d09a 2120 switch (c->type) {
2121 case CHAN_MAINSESSION:
2122 /*
2123 * This is treated separately, outside the switch.
2124 */
2125 break;
2126 case CHAN_X11:
2127 x11_override_throttle(c->u.x11.s, enable);
2128 break;
2129 case CHAN_AGENT:
2130 /* Agent channels require no buffer management. */
2131 break;
2132 case CHAN_SOCKDATA:
2133 pfd_override_throttle(c->u.x11.s, enable);
2134 break;
2135 }
2136 }
2137}
2138
2139/*
51470298 2140 * Username and password input, abstracted off into routines
2141 * reusable in several places - even between SSH1 and SSH2.
0405e71f 2142 */
0405e71f 2143
2144/* Set up a username or password input loop on a given buffer. */
51470298 2145void setup_userpass_input(Ssh ssh, char *buffer, int buflen, int echo)
0405e71f 2146{
51470298 2147 ssh->userpass_input_buffer = buffer;
2148 ssh->userpass_input_buflen = buflen;
2149 ssh->userpass_input_bufpos = 0;
2150 ssh->userpass_input_echo = echo;
0405e71f 2151}
2152
2153/*
2154 * Process some terminal data in the course of username/password
2155 * input. Returns >0 for success (line of input returned in
2156 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2157 * for inconclusive (keep waiting for more input please).
2158 */
51470298 2159int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
0405e71f 2160{
2161 char c;
2162
2163 while (inlen--) {
2164 switch (c = *in++) {
2165 case 10:
2166 case 13:
51470298 2167 ssh->userpass_input_buffer[ssh->userpass_input_bufpos] = 0;
2168 ssh->userpass_input_buffer[ssh->userpass_input_buflen-1] = 0;
0405e71f 2169 return +1;
2170 break;
2171 case 8:
2172 case 127:
51470298 2173 if (ssh->userpass_input_bufpos > 0) {
2174 if (ssh->userpass_input_echo)
2175 c_write_str(ssh, "\b \b");
2176 ssh->userpass_input_bufpos--;
0405e71f 2177 }
2178 break;
2179 case 21:
2180 case 27:
51470298 2181 while (ssh->userpass_input_bufpos > 0) {
2182 if (ssh->userpass_input_echo)
2183 c_write_str(ssh, "\b \b");
2184 ssh->userpass_input_bufpos--;
0405e71f 2185 }
2186 break;
2187 case 3:
2188 case 4:
2189 return -1;
2190 break;
2191 default:
2192 if (((c >= ' ' && c <= '~') ||
2193 ((unsigned char) c >= 160))
51470298 2194 && ssh->userpass_input_bufpos < ssh->userpass_input_buflen-1) {
2195 ssh->userpass_input_buffer[ssh->userpass_input_bufpos++] = c;
2196 if (ssh->userpass_input_echo)
2197 c_write(ssh, &c, 1);
0405e71f 2198 }
2199 break;
2200 }
2201 }
2202 return 0;
2203}
2204
2205/*
fb09bf1c 2206 * Handle the key exchange and user authentication phases.
2207 */
51470298 2208static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
fb09bf1c 2209{
2d466ffd 2210 int i, j;
374330e2 2211 unsigned char cookie[8];
2212 struct RSAKey servkey, hostkey;
2213 struct MD5Context md5c;
51470298 2214 struct do_ssh1_login_state {
2215 int len;
2216 unsigned char *rsabuf, *keystr1, *keystr2;
2217 unsigned long supported_ciphers_mask, supported_auths_mask;
2218 int tried_publickey, tried_agent;
2219 int tis_auth_refused, ccard_auth_refused;
2220 unsigned char session_id[16];
2221 int cipher_type;
2222 char username[100];
2223 void *publickey_blob;
2224 int publickey_bloblen;
2225 char password[100];
2226 char prompt[200];
2227 int pos;
2228 char c;
2229 int pwpkt_type;
2230 unsigned char request[5], *response, *p;
2231 int responselen;
2232 int keyi, nkeys;
2233 int authed;
2234 struct RSAKey key;
2235 Bignum challenge;
2236 char *commentp;
2237 int commentlen;
2238 };
2239 crState(do_ssh1_login_state);
2240
2241 crBegin(ssh->do_ssh1_login_crstate);
374330e2 2242
32874aea 2243 if (!ispkt)
2244 crWaitUntil(ispkt);
374330e2 2245
51470298 2246 if (ssh->pktin.type != SSH1_SMSG_PUBLIC_KEY) {
a8327734 2247 bombout((ssh,"Public key packet not received"));
32874aea 2248 crReturn(0);
8d5de777 2249 }
374330e2 2250
c5e9c988 2251 logevent("Received public keys");
374330e2 2252
51470298 2253 memcpy(cookie, ssh->pktin.body, 8);
374330e2 2254
51470298 2255 i = makekey(ssh->pktin.body + 8, &servkey, &s->keystr1, 0);
2256 j = makekey(ssh->pktin.body + 8 + i, &hostkey, &s->keystr2, 0);
374330e2 2257
c5e9c988 2258 /*
1c2a93c4 2259 * Log the host key fingerprint.
c5e9c988 2260 */
c5e9c988 2261 {
2262 char logmsg[80];
1c2a93c4 2263 logevent("Host key fingerprint is:");
c5e9c988 2264 strcpy(logmsg, " ");
32874aea 2265 hostkey.comment = NULL;
2266 rsa_fingerprint(logmsg + strlen(logmsg),
2267 sizeof(logmsg) - strlen(logmsg), &hostkey);
c5e9c988 2268 logevent(logmsg);
2269 }
2270
51470298 2271 ssh->v1_remote_protoflags = GET_32BIT(ssh->pktin.body + 8 + i + j);
2272 s->supported_ciphers_mask = GET_32BIT(ssh->pktin.body + 12 + i + j);
2273 s->supported_auths_mask = GET_32BIT(ssh->pktin.body + 16 + i + j);
bea1ef5f 2274
51470298 2275 ssh->v1_local_protoflags =
2276 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2277 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
b96dc54c 2278
c5e9c988 2279 MD5Init(&md5c);
51470298 2280 MD5Update(&md5c, s->keystr2, hostkey.bytes);
2281 MD5Update(&md5c, s->keystr1, servkey.bytes);
2282 MD5Update(&md5c, ssh->pktin.body, 8);
2283 MD5Final(s->session_id, &md5c);
374330e2 2284
32874aea 2285 for (i = 0; i < 32; i++)
51470298 2286 ssh->session_key[i] = random_byte();
374330e2 2287
51470298 2288 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
374330e2 2289
51470298 2290 s->rsabuf = smalloc(s->len);
2291 if (!s->rsabuf)
374330e2 2292 fatalbox("Out of memory");
2293
89ee5268 2294 /*
2295 * Verify the host key.
2296 */
2297 {
32874aea 2298 /*
2299 * First format the key into a string.
2300 */
2301 int len = rsastr_len(&hostkey);
2302 char fingerprint[100];
2303 char *keystr = smalloc(len);
2304 if (!keystr)
2305 fatalbox("Out of memory");
2306 rsastr_fmt(keystr, &hostkey);
2307 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
a8327734 2308 verify_ssh_host_key(ssh->frontend,
2309 ssh->savedhost, ssh->savedport, "rsa", keystr,
32874aea 2310 fingerprint);
2311 sfree(keystr);
2312 }
2313
2314 for (i = 0; i < 32; i++) {
51470298 2315 s->rsabuf[i] = ssh->session_key[i];
374330e2 2316 if (i < 16)
51470298 2317 s->rsabuf[i] ^= s->session_id[i];
374330e2 2318 }
2319
2320 if (hostkey.bytes > servkey.bytes) {
51470298 2321 rsaencrypt(s->rsabuf, 32, &servkey);
2322 rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
374330e2 2323 } else {
51470298 2324 rsaencrypt(s->rsabuf, 32, &hostkey);
2325 rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
374330e2 2326 }
2327
c5e9c988 2328 logevent("Encrypted session key");
2329
ca20bfcf 2330 {
2331 int cipher_chosen = 0, warn = 0;
2332 char *cipher_string = NULL;
51470298 2333 int i;
ca20bfcf 2334 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2335 int next_cipher = cfg.ssh_cipherlist[i];
2336 if (next_cipher == CIPHER_WARN) {
2337 /* If/when we choose a cipher, warn about it */
2338 warn = 1;
2339 } else if (next_cipher == CIPHER_AES) {
2340 /* XXX Probably don't need to mention this. */
2341 logevent("AES not supported in SSH1, skipping");
2342 } else {
2343 switch (next_cipher) {
51470298 2344 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
ca20bfcf 2345 cipher_string = "3DES"; break;
51470298 2346 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
ca20bfcf 2347 cipher_string = "Blowfish"; break;
51470298 2348 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
ca20bfcf 2349 cipher_string = "single-DES"; break;
2350 }
51470298 2351 if (s->supported_ciphers_mask & (1 << s->cipher_type))
ca20bfcf 2352 cipher_chosen = 1;
2353 }
2354 }
2355 if (!cipher_chosen) {
51470298 2356 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
a8327734 2357 bombout((ssh,"Server violates SSH 1 protocol by not "
ca20bfcf 2358 "supporting 3DES encryption"));
2359 else
2360 /* shouldn't happen */
a8327734 2361 bombout((ssh,"No supported ciphers found"));
a99a05c0 2362 crReturn(0);
2363 }
ca20bfcf 2364
2365 /* Warn about chosen cipher if necessary. */
2366 if (warn)
a8327734 2367 askcipher(ssh->frontend, cipher_string, 0);
bea1ef5f 2368 }
ca20bfcf 2369
51470298 2370 switch (s->cipher_type) {
32874aea 2371 case SSH_CIPHER_3DES:
2372 logevent("Using 3DES encryption");
2373 break;
2374 case SSH_CIPHER_DES:
2375 logevent("Using single-DES encryption");
2376 break;
2377 case SSH_CIPHER_BLOWFISH:
2378 logevent("Using Blowfish encryption");
2379 break;
c5e9c988 2380 }
bea1ef5f 2381
51470298 2382 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
2383 PKT_CHAR, s->cipher_type,
32874aea 2384 PKT_DATA, cookie, 8,
51470298 2385 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
2386 PKT_DATA, s->rsabuf, s->len,
2387 PKT_INT, ssh->v1_local_protoflags, PKT_END);
fb09bf1c 2388
c5e9c988 2389 logevent("Trying to enable encryption...");
374330e2 2390
51470298 2391 sfree(s->rsabuf);
374330e2 2392
51470298 2393 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2394 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
2395 &ssh_3des);
371e569c 2396 ssh->v1_cipher_ctx = ssh->cipher->make_context();
2397 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
57356d63 2398 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
374330e2 2399
0183b242 2400 ssh->crcda_ctx = crcda_make_context();
2401 logevent("Installing CRC compensation attack detector");
2402
fb09bf1c 2403 crWaitUntil(ispkt);
374330e2 2404
51470298 2405 if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
a8327734 2406 bombout((ssh,"Encryption not successfully enabled"));
32874aea 2407 crReturn(0);
8d5de777 2408 }
374330e2 2409
c5e9c988 2410 logevent("Successfully started encryption");
2411
374330e2 2412 fflush(stdout);
2413 {
67779be7 2414 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
c0a81592 2415 if (ssh_get_line && !ssh_getline_pw_only) {
32874aea 2416 if (!ssh_get_line("login as: ",
51470298 2417 s->username, sizeof(s->username), FALSE)) {
32874aea 2418 /*
2419 * get_line failed to get a username.
2420 * Terminate.
2421 */
2422 logevent("No username provided. Abandoning session.");
51470298 2423 ssh->state = SSH_STATE_CLOSED;
32874aea 2424 crReturn(1);
2425 }
2426 } else {
51470298 2427 int ret; /* need not be kept over crReturn */
2428 c_write_str(ssh, "login as: ");
2429 ssh->send_ok = 1;
0405e71f 2430
51470298 2431 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
0405e71f 2432 do {
32874aea 2433 crWaitUntil(!ispkt);
51470298 2434 ret = process_userpass_input(ssh, in, inlen);
0405e71f 2435 } while (ret == 0);
2436 if (ret < 0)
2437 cleanup_exit(0);
51470298 2438 c_write_str(ssh, "\r\n");
32874aea 2439 }
2440 } else {
51470298 2441 strncpy(s->username, cfg.username, sizeof(s->username));
2442 s->username[sizeof(s->username)-1] = '\0';
374330e2 2443 }
fb09bf1c 2444
51470298 2445 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
c5e9c988 2446 {
51470298 2447 char userlog[22 + sizeof(s->username)];
2448 sprintf(userlog, "Sent username \"%s\"", s->username);
c5e9c988 2449 logevent(userlog);
32874aea 2450 if (flags & FLAG_INTERACTIVE &&
2451 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3c8e959b 2452 strcat(userlog, "\r\n");
51470298 2453 c_write_str(ssh, userlog);
3c8e959b 2454 }
c5e9c988 2455 }
374330e2 2456 }
2457
fb09bf1c 2458 crWaitUntil(ispkt);
374330e2 2459
51470298 2460 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
0df73905 2461 /* We must not attempt PK auth. Pretend we've already tried it. */
51470298 2462 s->tried_publickey = s->tried_agent = 1;
0df73905 2463 } else {
51470298 2464 s->tried_publickey = s->tried_agent = 0;
0df73905 2465 }
51470298 2466 s->tis_auth_refused = s->ccard_auth_refused = 0;
396778f1 2467 /* Load the public half of cfg.keyfile so we notice if it's in Pageant */
2468 if (*cfg.keyfile) {
51470298 2469 if (!rsakey_pubblob(cfg.keyfile,
2470 &s->publickey_blob, &s->publickey_bloblen))
2471 s->publickey_blob = NULL;
396778f1 2472 } else
51470298 2473 s->publickey_blob = NULL;
7cca0d81 2474
51470298 2475 while (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2476 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
614a20a0 2477
51470298 2478 if (agent_exists() && !s->tried_agent) {
32874aea 2479 /*
2480 * Attempt RSA authentication using Pageant.
2481 */
32874aea 2482 void *r;
2483
51470298 2484 s->authed = FALSE;
2485 s->tried_agent = 1;
32874aea 2486 logevent("Pageant is running. Requesting keys.");
2487
2488 /* Request the keys held by the agent. */
51470298 2489 PUT_32BIT(s->request, 1);
2490 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2491 agent_query(s->request, 5, &r, &s->responselen);
2492 s->response = (unsigned char *) r;
2493 if (s->response && s->responselen >= 5 &&
2494 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2495 s->p = s->response + 5;
2496 s->nkeys = GET_32BIT(s->p);
2497 s->p += 4;
32874aea 2498 {
2499 char buf[64];
51470298 2500 sprintf(buf, "Pageant has %d SSH1 keys", s->nkeys);
32874aea 2501 logevent(buf);
2502 }
51470298 2503 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
32874aea 2504 {
2505 char buf[64];
51470298 2506 sprintf(buf, "Trying Pageant key #%d", s->keyi);
32874aea 2507 logevent(buf);
2508 }
51470298 2509 if (s->publickey_blob &&
2510 !memcmp(s->p, s->publickey_blob,
2511 s->publickey_bloblen)) {
396778f1 2512 logevent("This key matches configured key file");
51470298 2513 s->tried_publickey = 1;
396778f1 2514 }
51470298 2515 s->p += 4;
2516 s->p += ssh1_read_bignum(s->p, &s->key.exponent);
2517 s->p += ssh1_read_bignum(s->p, &s->key.modulus);
2518 s->commentlen = GET_32BIT(s->p);
2519 s->p += 4;
d8baa528 2520 s->commentp = (char *)s->p;
51470298 2521 s->p += s->commentlen;
2522 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2523 PKT_BIGNUM, s->key.modulus, PKT_END);
32874aea 2524 crWaitUntil(ispkt);
51470298 2525 if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
32874aea 2526 logevent("Key refused");
2527 continue;
2528 }
2529 logevent("Received RSA challenge");
51470298 2530 ssh1_read_bignum(ssh->pktin.body, &s->challenge);
32874aea 2531 {
2532 char *agentreq, *q, *ret;
2d466ffd 2533 void *vret;
32874aea 2534 int len, retlen;
2535 len = 1 + 4; /* message type, bit count */
51470298 2536 len += ssh1_bignum_length(s->key.exponent);
2537 len += ssh1_bignum_length(s->key.modulus);
2538 len += ssh1_bignum_length(s->challenge);
32874aea 2539 len += 16; /* session id */
2540 len += 4; /* response format */
2541 agentreq = smalloc(4 + len);
2542 PUT_32BIT(agentreq, len);
2543 q = agentreq + 4;
2544 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
51470298 2545 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
32874aea 2546 q += 4;
51470298 2547 q += ssh1_write_bignum(q, s->key.exponent);
2548 q += ssh1_write_bignum(q, s->key.modulus);
2549 q += ssh1_write_bignum(q, s->challenge);
2550 memcpy(q, s->session_id, 16);
32874aea 2551 q += 16;
2552 PUT_32BIT(q, 1); /* response format */
2d466ffd 2553 agent_query(agentreq, len + 4, &vret, &retlen);
2554 ret = vret;
32874aea 2555 sfree(agentreq);
2556 if (ret) {
2557 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2558 logevent("Sending Pageant's response");
51470298 2559 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
32874aea 2560 PKT_DATA, ret + 5, 16,
2561 PKT_END);
2562 sfree(ret);
2563 crWaitUntil(ispkt);
51470298 2564 if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
32874aea 2565 logevent
2566 ("Pageant's response accepted");
2567 if (flags & FLAG_VERBOSE) {
51470298 2568 c_write_str(ssh, "Authenticated using"
2569 " RSA key \"");
2570 c_write(ssh, s->commentp,
2571 s->commentlen);
2572 c_write_str(ssh, "\" from agent\r\n");
32874aea 2573 }
51470298 2574 s->authed = TRUE;
32874aea 2575 } else
2576 logevent
2577 ("Pageant's response not accepted");
2578 } else {
2579 logevent
2580 ("Pageant failed to answer challenge");
2581 sfree(ret);
2582 }
2583 } else {
2584 logevent("No reply received from Pageant");
2585 }
2586 }
51470298 2587 freebn(s->key.exponent);
2588 freebn(s->key.modulus);
2589 freebn(s->challenge);
2590 if (s->authed)
32874aea 2591 break;
2592 }
2593 }
51470298 2594 if (s->authed)
32874aea 2595 break;
2596 }
51470298 2597 if (*cfg.keyfile && !s->tried_publickey)
2598 s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
32874aea 2599
614a20a0 2600 if (cfg.try_tis_auth &&
51470298 2601 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
2602 !s->tis_auth_refused) {
2603 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
32874aea 2604 logevent("Requested TIS authentication");
51470298 2605 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
32874aea 2606 crWaitUntil(ispkt);
51470298 2607 if (ssh->pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
32874aea 2608 logevent("TIS authentication declined");
2609 if (flags & FLAG_INTERACTIVE)
51470298 2610 c_write_str(ssh, "TIS authentication refused.\r\n");
2611 s->tis_auth_refused = 1;
614a20a0 2612 continue;
32874aea 2613 } else {
51470298 2614 int challengelen = GET_32BIT(ssh->pktin.body);
32874aea 2615 logevent("Received TIS challenge");
51470298 2616 if (challengelen > sizeof(s->prompt) - 1)
2617 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
2618 memcpy(s->prompt, ssh->pktin.body + 4, challengelen);
614a20a0 2619 /* Prompt heuristic comes from OpenSSH */
51470298 2620 strncpy(s->prompt + challengelen,
2621 memchr(s->prompt, '\n', challengelen) ?
614a20a0 2622 "": "\r\nResponse: ",
51470298 2623 (sizeof s->prompt) - challengelen);
2624 s->prompt[(sizeof s->prompt) - 1] = '\0';
32874aea 2625 }
2626 }
614a20a0 2627 if (cfg.try_tis_auth &&
51470298 2628 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
2629 !s->ccard_auth_refused) {
2630 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
32874aea 2631 logevent("Requested CryptoCard authentication");
51470298 2632 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
32874aea 2633 crWaitUntil(ispkt);
51470298 2634 if (ssh->pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
32874aea 2635 logevent("CryptoCard authentication declined");
51470298 2636 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
2637 s->ccard_auth_refused = 1;
614a20a0 2638 continue;
32874aea 2639 } else {
51470298 2640 int challengelen = GET_32BIT(ssh->pktin.body);
32874aea 2641 logevent("Received CryptoCard challenge");
51470298 2642 if (challengelen > sizeof(s->prompt) - 1)
2643 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
2644 memcpy(s->prompt, ssh->pktin.body + 4, challengelen);
2645 strncpy(s->prompt + challengelen,
2646 memchr(s->prompt, '\n', challengelen) ?
614a20a0 2647 "" : "\r\nResponse: ",
51470298 2648 sizeof(s->prompt) - challengelen);
2649 s->prompt[sizeof(s->prompt) - 1] = '\0';
32874aea 2650 }
2651 }
51470298 2652 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2653 sprintf(s->prompt, "%.90s@%.90s's password: ",
2654 s->username, ssh->savedhost);
32874aea 2655 }
51470298 2656 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
32874aea 2657 char *comment = NULL;
231ee168 2658 int type;
2659 char msgbuf[256];
32874aea 2660 if (flags & FLAG_VERBOSE)
51470298 2661 c_write_str(ssh, "Trying public key authentication.\r\n");
57356d63 2662 logeventf(ssh, "Trying public key \"%s\"", cfg.keyfile);
231ee168 2663 type = key_type(cfg.keyfile);
2664 if (type != SSH_KEYTYPE_SSH1) {
2665 sprintf(msgbuf, "Key is of wrong type (%s)",
2666 key_type_to_str(type));
2667 logevent(msgbuf);
51470298 2668 c_write_str(ssh, msgbuf);
2669 c_write_str(ssh, "\r\n");
2670 s->tried_publickey = 1;
231ee168 2671 continue;
2672 }
32874aea 2673 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
2674 if (flags & FLAG_VERBOSE)
51470298 2675 c_write_str(ssh, "No passphrase required.\r\n");
32874aea 2676 goto tryauth;
2677 }
51470298 2678 sprintf(s->prompt, "Passphrase for key \"%.100s\": ", comment);
32874aea 2679 sfree(comment);
2680 }
a52f067e 2681
614a20a0 2682 /*
2683 * Show password prompt, having first obtained it via a TIS
2684 * or CryptoCard exchange if we're doing TIS or CryptoCard
2685 * authentication.
2686 */
fa17a66e 2687 if (ssh_get_line) {
51470298 2688 if (!ssh_get_line(s->prompt, s->password,
2689 sizeof(s->password), TRUE)) {
32874aea 2690 /*
2691 * get_line failed to get a password (for example
2692 * because one was supplied on the command line
2693 * which has already failed to work). Terminate.
2694 */
51470298 2695 send_packet(ssh, SSH1_MSG_DISCONNECT,
2bc6a386 2696 PKT_STR, "No more passwords available to try",
2697 PKT_END);
247308b5 2698 logevent("Unable to authenticate");
a8327734 2699 connection_fatal(ssh->frontend, "Unable to authenticate");
51470298 2700 ssh->state = SSH_STATE_CLOSED;
32874aea 2701 crReturn(1);
2702 }
fb09bf1c 2703 } else {
614a20a0 2704 /* Prompt may have come from server. We've munged it a bit, so
2705 * we know it to be zero-terminated at least once. */
51470298 2706 int ret; /* need not be saved over crReturn */
2707 c_write_untrusted(ssh, s->prompt, strlen(s->prompt));
2708 s->pos = 0;
0405e71f 2709
51470298 2710 setup_userpass_input(ssh, s->password, sizeof(s->password), 0);
0405e71f 2711 do {
32874aea 2712 crWaitUntil(!ispkt);
51470298 2713 ret = process_userpass_input(ssh, in, inlen);
0405e71f 2714 } while (ret == 0);
2715 if (ret < 0)
2716 cleanup_exit(0);
51470298 2717 c_write_str(ssh, "\r\n");
32874aea 2718 }
2719
2720 tryauth:
51470298 2721 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
32874aea 2722 /*
2723 * Try public key authentication with the specified
2724 * key file.
2725 */
51470298 2726 s->tried_publickey = 1;
2727
2728 {
2729 int ret = loadrsakey(cfg.keyfile, &s->key, s->password);
2730 if (ret == 0) {
2731 c_write_str(ssh, "Couldn't load private key from ");
2732 c_write_str(ssh, cfg.keyfile);
2733 c_write_str(ssh, ".\r\n");
2734 continue; /* go and try password */
2735 }
2736 if (ret == -1) {
2737 c_write_str(ssh, "Wrong passphrase.\r\n");
2738 s->tried_publickey = 0;
2739 continue; /* try again */
2740 }
32874aea 2741 }
2742
2743 /*
2744 * Send a public key attempt.
2745 */
51470298 2746 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2747 PKT_BIGNUM, s->key.modulus, PKT_END);
32874aea 2748
2749 crWaitUntil(ispkt);
51470298 2750 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2751 c_write_str(ssh, "Server refused our public key.\r\n");
32874aea 2752 continue; /* go and try password */
2753 }
51470298 2754 if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
a8327734 2755 bombout((ssh,"Bizarre response to offer of public key"));
32874aea 2756 crReturn(0);
2757 }
32874aea 2758
51470298 2759 {
2760 int i;
2761 unsigned char buffer[32];
2762 Bignum challenge, response;
2763
2764 ssh1_read_bignum(ssh->pktin.body, &challenge);
2765 response = rsadecrypt(challenge, &s->key);
2766 freebn(s->key.private_exponent);/* burn the evidence */
32874aea 2767
51470298 2768 for (i = 0; i < 32; i++) {
2769 buffer[i] = bignum_byte(response, 31 - i);
2770 }
2771
2772 MD5Init(&md5c);
2773 MD5Update(&md5c, buffer, 32);
2774 MD5Update(&md5c, s->session_id, 16);
2775 MD5Final(buffer, &md5c);
32874aea 2776
51470298 2777 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
2778 PKT_DATA, buffer, 16, PKT_END);
2779
2780 freebn(challenge);
2781 freebn(response);
2782 }
32874aea 2783
2784 crWaitUntil(ispkt);
51470298 2785 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
32874aea 2786 if (flags & FLAG_VERBOSE)
51470298 2787 c_write_str(ssh, "Failed to authenticate with"
2788 " our public key.\r\n");
32874aea 2789 continue; /* go and try password */
51470298 2790 } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
a8327734 2791 bombout((ssh,"Bizarre response to RSA authentication response"));
32874aea 2792 crReturn(0);
2793 }
2794
2795 break; /* we're through! */
2796 } else {
51470298 2797 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
32874aea 2798 /*
2799 * Defence against traffic analysis: we send a
2800 * whole bunch of packets containing strings of
2801 * different lengths. One of these strings is the
2802 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2803 * The others are all random data in
2804 * SSH1_MSG_IGNORE packets. This way a passive
2805 * listener can't tell which is the password, and
2806 * hence can't deduce the password length.
2807 *
2808 * Anybody with a password length greater than 16
2809 * bytes is going to have enough entropy in their
2810 * password that a listener won't find it _that_
2811 * much help to know how long it is. So what we'll
2812 * do is:
2813 *
2814 * - if password length < 16, we send 15 packets
2815 * containing string lengths 1 through 15
2816 *
2817 * - otherwise, we let N be the nearest multiple
2818 * of 8 below the password length, and send 8
2819 * packets containing string lengths N through
2820 * N+7. This won't obscure the order of
2821 * magnitude of the password length, but it will
2822 * introduce a bit of extra uncertainty.
2823 *
2824 * A few servers (the old 1.2.18 through 1.2.22)
2825 * can't deal with SSH1_MSG_IGNORE. For these
2826 * servers, we need an alternative defence. We make
2827 * use of the fact that the password is interpreted
2828 * as a C string: so we can append a NUL, then some
2829 * random data.
bd358db1 2830 *
2831 * One server (a Cisco one) can deal with neither
2832 * SSH1_MSG_IGNORE _nor_ a padded password string.
2833 * For this server we are left with no defences
2834 * against password length sniffing.
32874aea 2835 */
51470298 2836 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
b17c8428 2837 /*
2838 * The server can deal with SSH1_MSG_IGNORE, so
2839 * we can use the primary defence.
2840 */
32874aea 2841 int bottom, top, pwlen, i;
2842 char *randomstr;
2843
51470298 2844 pwlen = strlen(s->password);
32874aea 2845 if (pwlen < 16) {
2846 bottom = 0; /* zero length passwords are OK! :-) */
2847 top = 15;
2848 } else {
2849 bottom = pwlen & ~7;
2850 top = bottom + 7;
2851 }
2852
2853 assert(pwlen >= bottom && pwlen <= top);
2854
2855 randomstr = smalloc(top + 1);
2856
2857 for (i = bottom; i <= top; i++) {
2858 if (i == pwlen)
51470298 2859 defer_packet(ssh, s->pwpkt_type,
2860 PKT_STR, s->password, PKT_END);
32874aea 2861 else {
2862 for (j = 0; j < i; j++) {
2863 do {
2864 randomstr[j] = random_byte();
2865 } while (randomstr[j] == '\0');
2866 }
2867 randomstr[i] = '\0';
51470298 2868 defer_packet(ssh, SSH1_MSG_IGNORE,
32874aea 2869 PKT_STR, randomstr, PKT_END);
2870 }
2871 }
bd358db1 2872 logevent("Sending password with camouflage packets");
51470298 2873 ssh_pkt_defersend(ssh);
bd358db1 2874 }
51470298 2875 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
b17c8428 2876 /*
2877 * The server can't deal with SSH1_MSG_IGNORE
2878 * but can deal with padded passwords, so we
2879 * can use the secondary defence.
2880 */
bd358db1 2881 char string[64];
51470298 2882 char *ss;
bd358db1 2883 int len;
2884
51470298 2885 len = strlen(s->password);
bd358db1 2886 if (len < sizeof(string)) {
51470298 2887 ss = string;
2888 strcpy(string, s->password);
bd358db1 2889 len++; /* cover the zero byte */
2890 while (len < sizeof(string)) {
2891 string[len++] = (char) random_byte();
2892 }
2893 } else {
51470298 2894 ss = s->password;
bd358db1 2895 }
2896 logevent("Sending length-padded password");
51470298 2897 send_packet(ssh, s->pwpkt_type, PKT_INT, len,
2898 PKT_DATA, ss, len, PKT_END);
bd358db1 2899 } else {
2900 /*
2901 * The server has _both_
2902 * BUG_CHOKES_ON_SSH1_IGNORE and
2903 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2904 * therefore nothing we can do.
2905 */
2906 int len;
51470298 2907 len = strlen(s->password);
bd358db1 2908 logevent("Sending unpadded password");
51470298 2909 send_packet(ssh, s->pwpkt_type, PKT_INT, len,
2910 PKT_DATA, s->password, len, PKT_END);
32874aea 2911 }
2912 } else {
51470298 2913 send_packet(ssh, s->pwpkt_type, PKT_STR, s->password, PKT_END);
32874aea 2914 }
2915 }
c5e9c988 2916 logevent("Sent password");
51470298 2917 memset(s->password, 0, strlen(s->password));
fb09bf1c 2918 crWaitUntil(ispkt);
51470298 2919 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
32874aea 2920 if (flags & FLAG_VERBOSE)
51470298 2921 c_write_str(ssh, "Access denied\r\n");
c5e9c988 2922 logevent("Authentication refused");
51470298 2923 } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
a8327734 2924 bombout((ssh,"Strange packet received, type %d", ssh->pktin.type));
32874aea 2925 crReturn(0);
374330e2 2926 }
2927 }
2928
c5e9c988 2929 logevent("Authentication successful");
2930
fb09bf1c 2931 crFinish(1);
2932}
2933
32874aea 2934void sshfwd_close(struct ssh_channel *c)
2935{
51470298 2936 Ssh ssh = c->ssh;
2937
80e48603 2938 if (c && !c->closes) {
4ed34d25 2939 /*
2940 * If the channel's remoteid is -1, we have sent
2941 * CHANNEL_OPEN for this channel, but it hasn't even been
2942 * acknowledged by the server. So we must set a close flag
2943 * on it now, and then when the server acks the channel
2944 * open, we can close it then.
2945 */
36cac739 2946 if (((int)c->remoteid) != -1) {
51470298 2947 if (ssh->version == 1) {
2948 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4ed34d25 2949 PKT_END);
2950 } else {
51470298 2951 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
2952 ssh2_pkt_adduint32(ssh, c->remoteid);
2953 ssh2_pkt_send(ssh);
4ed34d25 2954 }
32874aea 2955 }
0357890f 2956 c->closes = 1; /* sent MSG_CLOSE */
32874aea 2957 if (c->type == CHAN_X11) {
2958 c->u.x11.s = NULL;
d74d141c 2959 logevent("Forwarded X11 connection terminated");
4ed34d25 2960 } else if (c->type == CHAN_SOCKDATA ||
2961 c->type == CHAN_SOCKDATA_DORMANT) {
d74d141c 2962 c->u.pfd.s = NULL;
2963 logevent("Forwarded port closed");
32874aea 2964 }
2965 }
2966}
2967
5471d09a 2968int sshfwd_write(struct ssh_channel *c, char *buf, int len)
32874aea 2969{
51470298 2970 Ssh ssh = c->ssh;
2971
2972 if (ssh->version == 1) {
2973 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
32874aea 2974 PKT_INT, c->remoteid,
2975 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
5471d09a 2976 /*
2977 * In SSH1 we can return 0 here - implying that forwarded
2978 * connections are never individually throttled - because
2979 * the only circumstance that can cause throttling will be
2980 * the whole SSH connection backing up, in which case
2981 * _everything_ will be throttled as a whole.
2982 */
2983 return 0;
783415f8 2984 } else {
32874aea 2985 ssh2_add_channel_data(c, buf, len);
5471d09a 2986 return ssh2_try_send(c);
2987 }
2988}
2989
2990void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
2991{
51470298 2992 Ssh ssh = c->ssh;
2993
2994 if (ssh->version == 1) {
5471d09a 2995 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
2996 c->v.v1.throttling = 0;
51470298 2997 ssh1_throttle(ssh, -1);
5471d09a 2998 }
2999 } else {
3000 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
783415f8 3001 }
9c964e85 3002}
3003
51470298 3004static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
32874aea 3005{
51470298 3006 crBegin(ssh->ssh1_protocol_crstate);
fb09bf1c 3007
3008 random_init();
3009
51470298 3010 while (!do_ssh1_login(ssh, in, inlen, ispkt)) {
fb09bf1c 3011 crReturnV;
85ee8208 3012 }
51470298 3013 if (ssh->state == SSH_STATE_CLOSED)
32874aea 3014 crReturnV;
fb09bf1c 3015
979310f1 3016 if (cfg.agentfwd && agent_exists()) {
32874aea 3017 logevent("Requesting agent forwarding");
51470298 3018 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
32874aea 3019 do {
3020 crReturnV;
3021 } while (!ispkt);
51470298 3022 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3023 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
a8327734 3024 bombout((ssh,"Protocol confusion"));
32874aea 3025 crReturnV;
51470298 3026 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
32874aea 3027 logevent("Agent forwarding refused");
3028 } else {
3029 logevent("Agent forwarding enabled");
51470298 3030 ssh->agentfwd_enabled = TRUE;
db7d555c 3031 }
dacbd0e8 3032 }
3033
9c964e85 3034 if (cfg.x11_forward) {
32874aea 3035 char proto[20], data[64];
3036 logevent("Requesting X11 forwarding");
302121de 3037 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
3038 data, sizeof(data));
51470298 3039 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
3040 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
32874aea 3041 PKT_STR, proto, PKT_STR, data,
421d6835 3042 PKT_INT, x11_get_screen_number(cfg.x11_display),
3043 PKT_END);
32874aea 3044 } else {
51470298 3045 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
32874aea 3046 PKT_STR, proto, PKT_STR, data, PKT_END);
3047 }
3048 do {
3049 crReturnV;
3050 } while (!ispkt);
51470298 3051 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3052 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
a8327734 3053 bombout((ssh,"Protocol confusion"));
32874aea 3054 crReturnV;
51470298 3055 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
32874aea 3056 logevent("X11 forwarding refused");
3057 } else {
3058 logevent("X11 forwarding enabled");
51470298 3059 ssh->X11_fwd_enabled = TRUE;
9c964e85 3060 }
3061 }
3062
d74d141c 3063 {
9bf696b1 3064 char type;
d74d141c 3065 int n;
a4fc0d74 3066 int sport,dport,sserv,dserv;
6ee9b735 3067 char sports[256], dports[256], saddr[256], host[256];
d74d141c 3068
51470298 3069 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
d74d141c 3070 /* Add port forwardings. */
51470298 3071 ssh->portfwd_strptr = cfg.portfwd;
3072 while (*ssh->portfwd_strptr) {
3073 type = *ssh->portfwd_strptr++;
6ee9b735 3074 saddr[0] = '\0';
d74d141c 3075 n = 0;
6ee9b735 3076 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t') {
3077 if (*ssh->portfwd_strptr == ':') {
3078 /*
3079 * We've seen a colon in the middle of the
3080 * source port number. This means that
3081 * everything we've seen until now is the
3082 * source _address_, so we'll move it into
3083 * saddr and start sports from the beginning
3084 * again.
3085 */
3086 ssh->portfwd_strptr++;
3087 sports[n] = '\0';
3088 strcpy(saddr, sports);
3089 n = 0;
3090 }
3091 if (n < 255) sports[n++] = *ssh->portfwd_strptr++;
3092 }
d74d141c 3093 sports[n] = 0;
51470298 3094 if (*ssh->portfwd_strptr == '\t')
3095 ssh->portfwd_strptr++;
d74d141c 3096 n = 0;
6ee9b735 3097 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
3098 if (n < 255) host[n++] = *ssh->portfwd_strptr++;
3099 }
d74d141c 3100 host[n] = 0;
51470298 3101 if (*ssh->portfwd_strptr == ':')
3102 ssh->portfwd_strptr++;
d74d141c 3103 n = 0;
6ee9b735 3104 while (*ssh->portfwd_strptr) {
3105 if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
3106 }
d74d141c 3107 dports[n] = 0;
51470298 3108 ssh->portfwd_strptr++;
d74d141c 3109 dport = atoi(dports);
a4fc0d74 3110 dserv = 0;
3111 if (dport == 0) {
3112 dserv = 1;
68a49acb 3113 dport = net_service_lookup(dports);
3114 if (!dport) {
57356d63 3115 logeventf(ssh, "Service lookup failed for"
3116 " destination port \"%s\"", dports);
a4fc0d74 3117 }
3118 }
d74d141c 3119 sport = atoi(sports);
a4fc0d74 3120 sserv = 0;
3121 if (sport == 0) {
3122 sserv = 1;
68a49acb 3123 sport = net_service_lookup(sports);
3124 if (!sport) {
57356d63 3125 logeventf(ssh, "Service lookup failed for source"
3126 " port \"%s\"", sports);
a4fc0d74 3127 }
3128 }
d74d141c 3129 if (sport && dport) {
3130 if (type == 'L') {
6ee9b735 3131 pfd_addforward(host, dport, *saddr ? saddr : NULL,
3132 sport, ssh);
3133 logeventf(ssh, "Local port %.*s%.*s%.*s%.*s%d%.*s"
3134 " forwarding to %s:%.*s%.*s%d%.*s",
3135 (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
3136 (int)(*saddr?1:0), ":",
57356d63 3137 (int)(sserv ? strlen(sports) : 0), sports,
3138 sserv, "(", sport, sserv, ")",
3139 host,
3140 (int)(dserv ? strlen(dports) : 0), dports,
3141 dserv, "(", dport, dserv, ")");
d74d141c 3142 } else {
3143 struct ssh_rportfwd *pf;
3144 pf = smalloc(sizeof(*pf));
bc240b21 3145 strcpy(pf->dhost, host);
3146 pf->dport = dport;
6ee9b735 3147 if (saddr) {
3148 logeventf(ssh,
3149 "SSH1 cannot handle source address spec \"%s:%d\"; ignoring",
3150 saddr, sport);
3151 }
51470298 3152 if (add234(ssh->rportfwds, pf) != pf) {
57356d63 3153 logeventf(ssh,
3154 "Duplicate remote port forwarding to %s:%d",
3155 host, dport);
bc240b21 3156 sfree(pf);
d74d141c 3157 } else {
57356d63 3158 logeventf(ssh, "Requesting remote port %.*s%.*s%d%.*s"
3159 " forward to %s:%.*s%.*s%d%.*s",
3160 (int)(sserv ? strlen(sports) : 0), sports,
3161 sserv, "(", sport, sserv, ")",
3162 host,
3163 (int)(dserv ? strlen(dports) : 0), dports,
3164 dserv, "(", dport, dserv, ")");
51470298 3165 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
d74d141c 3166 PKT_INT, sport,
3167 PKT_STR, host,
3168 PKT_INT, dport,
3169 PKT_END);
9bf696b1 3170 do {
3171 crReturnV;
3172 } while (!ispkt);
51470298 3173 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3174 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
a8327734 3175 bombout((ssh,"Protocol confusion"));
9bf696b1 3176 crReturnV;
51470298 3177 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3178 c_write_str(ssh, "Server refused port"
3179 " forwarding\r\n");
9bf696b1 3180 }
3181 logevent("Remote port forwarding enabled");
d74d141c 3182 }
3183 }
3184 }
3185 }
3186 }
3187
fef97f43 3188 if (!cfg.nopty) {
51470298 3189 send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
32874aea 3190 PKT_STR, cfg.termtype,
51470298 3191 PKT_INT, ssh->term_height,
3192 PKT_INT, ssh->term_width,
32874aea 3193 PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
51470298 3194 ssh->state = SSH_STATE_INTERMED;
32874aea 3195 do {
3196 crReturnV;
3197 } while (!ispkt);
51470298 3198 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3199 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
a8327734 3200 bombout((ssh,"Protocol confusion"));
32874aea 3201 crReturnV;
51470298 3202 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3203 c_write_str(ssh, "Server refused to allocate pty\r\n");
3204 ssh->editing = ssh->echoing = 1;
32874aea 3205 }
c5e9c988 3206 logevent("Allocated pty");
0965bee0 3207 } else {
51470298 3208 ssh->editing = ssh->echoing = 1;
374330e2 3209 }
3210
4ba9b64b 3211 if (cfg.compression) {
51470298 3212 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
32874aea 3213 do {
3214 crReturnV;
3215 } while (!ispkt);
51470298 3216 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3217 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
a8327734 3218 bombout((ssh,"Protocol confusion"));
32874aea 3219 crReturnV;
51470298 3220 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3221 c_write_str(ssh, "Server refused to compress\r\n");
32874aea 3222 }
4ba9b64b 3223 logevent("Started compression");
51470298 3224 ssh->v1_compressing = TRUE;
5366aed8 3225 ssh->cs_comp_ctx = zlib_compress_init();
3226 logevent("Initialised zlib (RFC1950) compression");
3227 ssh->sc_comp_ctx = zlib_decompress_init();
3228 logevent("Initialised zlib (RFC1950) decompression");
4ba9b64b 3229 }
3230
fd5e5847 3231 /*
3232 * Start the shell or command.
3233 *
3234 * Special case: if the first-choice command is an SSH2
3235 * subsystem (hence not usable here) and the second choice
3236 * exists, we fall straight back to that.
3237 */
3238 {
3239 char *cmd = cfg.remote_cmd_ptr;
3240
3241 if (cfg.ssh_subsys && cfg.remote_cmd_ptr2) {
3242 cmd = cfg.remote_cmd_ptr2;
51470298 3243 ssh->fallback_cmd = TRUE;
fd5e5847 3244 }
3245 if (*cmd)
51470298 3246 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
fd5e5847 3247 else
51470298 3248 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
fd5e5847 3249 logevent("Started session");
3250 }
374330e2 3251
51470298 3252 ssh->state = SSH_STATE_SESSION;
3253 if (ssh->size_needed)
3254 ssh_size(ssh, ssh->term_width, ssh->term_height);
3255 if (ssh->eof_needed)
3256 ssh_special(ssh, TS_EOF);
374330e2 3257
b9d7bcad 3258 if (ssh->ldisc)
3259 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
51470298 3260 ssh->send_ok = 1;
3261 ssh->channels = newtree234(ssh_channelcmp);
374330e2 3262 while (1) {
3263 crReturnV;
3264 if (ispkt) {
51470298 3265 if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
3266 ssh->pktin.type == SSH1_SMSG_STDERR_DATA) {
3267 long len = GET_32BIT(ssh->pktin.body);
5471d09a 3268 int bufsize =
51470298 3269 from_backend(ssh->frontend,
3270 ssh->pktin.type == SSH1_SMSG_STDERR_DATA,
d8baa528 3271 (char *)(ssh->pktin.body) + 4, len);
51470298 3272 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
3273 ssh->v1_stdout_throttling = 1;
3274 ssh1_throttle(ssh, +1);
5471d09a 3275 }
51470298 3276 } else if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
3277 ssh->state = SSH_STATE_CLOSED;
c5e9c988 3278 logevent("Received disconnect request");
32874aea 3279 crReturnV;
51470298 3280 } else if (ssh->pktin.type == SSH1_SMSG_X11_OPEN) {
32874aea 3281 /* Remote side is trying to open a channel to talk to our
3282 * X-Server. Give them back a local channel number. */
3283 struct ssh_channel *c;
9c964e85 3284
3285 logevent("Received X11 connect request");
3286 /* Refuse if X11 forwarding is disabled. */
51470298 3287 if (!ssh->X11_fwd_enabled) {
3288 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3289 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
9c964e85 3290 logevent("Rejected X11 connect request");
3291 } else {
9c964e85 3292 c = smalloc(sizeof(struct ssh_channel));
51470298 3293 c->ssh = ssh;
9c964e85 3294
302121de 3295 if (x11_init(&c->u.x11.s, cfg.x11_display, c,
3296 ssh->x11auth) != NULL) {
32874aea 3297 logevent("opening X11 forward connection failed");
3298 sfree(c);
51470298 3299 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3300 PKT_INT, GET_32BIT(ssh->pktin.body),
32874aea 3301 PKT_END);
9c964e85 3302 } else {
32874aea 3303 logevent
3304 ("opening X11 forward connection succeeded");
51470298 3305 c->remoteid = GET_32BIT(ssh->pktin.body);
3306 c->localid = alloc_channel_id(ssh);
32874aea 3307 c->closes = 0;
5471d09a 3308 c->v.v1.throttling = 0;
32874aea 3309 c->type = CHAN_X11; /* identify channel type */
51470298 3310 add234(ssh->channels, c);
3311 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
32874aea 3312 PKT_INT, c->remoteid, PKT_INT,
3313 c->localid, PKT_END);
3314 logevent("Opened X11 forward channel");
9c964e85 3315 }
3316 }
51470298 3317 } else if (ssh->pktin.type == SSH1_SMSG_AGENT_OPEN) {
32874aea 3318 /* Remote side is trying to open a channel to talk to our
3319 * agent. Give them back a local channel number. */
3320 struct ssh_channel *c;
db7d555c 3321
3322 /* Refuse if agent forwarding is disabled. */
51470298 3323 if (!ssh->agentfwd_enabled) {
3324 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3325 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
db7d555c 3326 } else {
dcbde236 3327 c = smalloc(sizeof(struct ssh_channel));
51470298 3328 c->ssh = ssh;
3329 c->remoteid = GET_32BIT(ssh->pktin.body);
3330 c->localid = alloc_channel_id(ssh);
db7d555c 3331 c->closes = 0;
5471d09a 3332 c->v.v1.throttling = 0;
32874aea 3333 c->type = CHAN_AGENT; /* identify channel type */
db7d555c 3334 c->u.a.lensofar = 0;
51470298 3335 add234(ssh->channels, c);
3336 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
db7d555c 3337 PKT_INT, c->remoteid, PKT_INT, c->localid,
3338 PKT_END);
3339 }
51470298 3340 } else if (ssh->pktin.type == SSH1_MSG_PORT_OPEN) {
d74d141c 3341 /* Remote side is trying to open a channel to talk to a
3342 * forwarded port. Give them back a local channel number. */
3343 struct ssh_channel *c;
3344 struct ssh_rportfwd pf;
3345 int hostsize, port;
3346 char host[256], buf[1024];
3347 char *p, *h, *e;
3348 c = smalloc(sizeof(struct ssh_channel));
51470298 3349 c->ssh = ssh;
d74d141c 3350
51470298 3351 hostsize = GET_32BIT(ssh->pktin.body+4);
d8baa528 3352 for (h = host, p = (char *)(ssh->pktin.body+8);
3353 hostsize != 0; hostsize--) {
d74d141c 3354 if (h+1 < host+sizeof(host))
3355 *h++ = *p;
95bc8819 3356 p++;
d74d141c 3357 }
3358 *h = 0;
3359 port = GET_32BIT(p);
3360
bc240b21 3361 strcpy(pf.dhost, host);
3362 pf.dport = port;
d74d141c 3363
51470298 3364 if (find234(ssh->rportfwds, &pf, NULL) == NULL) {
d74d141c 3365 sprintf(buf, "Rejected remote port open request for %s:%d",
3366 host, port);
3367 logevent(buf);
51470298 3368 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3369 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
d74d141c 3370 } else {
3371 sprintf(buf, "Received remote port open request for %s:%d",
3372 host, port);
3373 logevent(buf);
3374 e = pfd_newconnect(&c->u.pfd.s, host, port, c);
3375 if (e != NULL) {
3376 char buf[256];
3377 sprintf(buf, "Port open failed: %s", e);
3378 logevent(buf);
3379 sfree(c);
51470298 3380 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3381 PKT_INT, GET_32BIT(ssh->pktin.body),
d74d141c 3382 PKT_END);
3383 } else {
51470298 3384 c->remoteid = GET_32BIT(ssh->pktin.body);
3385 c->localid = alloc_channel_id(ssh);
d74d141c 3386 c->closes = 0;
5471d09a 3387 c->v.v1.throttling = 0;
d74d141c 3388 c->type = CHAN_SOCKDATA; /* identify channel type */
51470298 3389 add234(ssh->channels, c);
3390 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
d74d141c 3391 PKT_INT, c->remoteid, PKT_INT,
3392 c->localid, PKT_END);
3393 logevent("Forwarded port opened successfully");
3394 }
3395 }
3396
51470298 3397 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
3398 unsigned int remoteid = GET_32BIT(ssh->pktin.body);
3399 unsigned int localid = GET_32BIT(ssh->pktin.body+4);
bc240b21 3400 struct ssh_channel *c;
3401
51470298 3402 c = find234(ssh->channels, &remoteid, ssh_channelfind);
bc240b21 3403 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3404 c->remoteid = localid;
3405 c->type = CHAN_SOCKDATA;
7781f316 3406 c->v.v1.throttling = 0;
bc240b21 3407 pfd_confirm(c->u.pfd.s);
3408 }
d74d141c 3409
4ed34d25 3410 if (c && c->closes) {
3411 /*
3412 * We have a pending close on this channel,
3413 * which we decided on before the server acked
3414 * the channel open. So now we know the
3415 * remoteid, we can close it again.
3416 */
51470298 3417 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
3418 PKT_INT, c->remoteid, PKT_END);
4ed34d25 3419 }
3420
51470298 3421 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
3422 unsigned int remoteid = GET_32BIT(ssh->pktin.body);
724cface 3423 struct ssh_channel *c;
3424
51470298 3425 c = find234(ssh->channels, &remoteid, ssh_channelfind);
724cface 3426 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3427 logevent("Forwarded connection refused by server");
3428 pfd_close(c->u.pfd.s);
51470298 3429 del234(ssh->channels, c);
724cface 3430 sfree(c);
3431 }
3432
51470298 3433 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
3434 ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
32874aea 3435 /* Remote side closes a channel. */
51470298 3436 unsigned i = GET_32BIT(ssh->pktin.body);
32874aea 3437 struct ssh_channel *c;
51470298 3438 c = find234(ssh->channels, &i, ssh_channelfind);
d0d844c1 3439 if (c && ((int)c->remoteid) != -1) {
32874aea 3440 int closetype;
3441 closetype =
51470298 3442 (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
0357890f 3443
783415f8 3444 if ((c->closes == 0) && (c->type == CHAN_X11)) {
d74d141c 3445 logevent("Forwarded X11 connection terminated");
9c964e85 3446 assert(c->u.x11.s != NULL);
3447 x11_close(c->u.x11.s);
3448 c->u.x11.s = NULL;
3449 }
d74d141c 3450 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
3451 logevent("Forwarded port closed");
3452 assert(c->u.pfd.s != NULL);
3453 pfd_close(c->u.pfd.s);
3454 c->u.pfd.s = NULL;
3455 }
0357890f 3456
3457 c->closes |= (closetype << 2); /* seen this message */
3458 if (!(c->closes & closetype)) {
51470298 3459 send_packet(ssh, ssh->pktin.type, PKT_INT, c->remoteid,
0357890f 3460 PKT_END);
3461 c->closes |= closetype; /* sent it too */
3462 }
3463
3464 if (c->closes == 15) {
51470298 3465 del234(ssh->channels, c);
32874aea 3466 sfree(c);
3467 }
d0d844c1 3468 } else {
a8327734 3469 bombout((ssh,"Received CHANNEL_CLOSE%s for %s channel %d\n",
51470298 3470 ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? "" :
d0d844c1 3471 "_CONFIRMATION", c ? "half-open" : "nonexistent",
3472 i));
32874aea 3473 }
51470298 3474 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_DATA) {
32874aea 3475 /* Data sent down one of our channels. */
51470298 3476 int i = GET_32BIT(ssh->pktin.body);
3477 int len = GET_32BIT(ssh->pktin.body + 4);
3478 unsigned char *p = ssh->pktin.body + 8;
32874aea 3479 struct ssh_channel *c;
51470298 3480 c = find234(ssh->channels, &i, ssh_channelfind);
32874aea 3481 if (c) {
5471d09a 3482 int bufsize;
32874aea 3483 switch (c->type) {
3484 case CHAN_X11:
d8baa528 3485 bufsize = x11_send(c->u.x11.s, (char *)p, len);
9c964e85 3486 break;
d74d141c 3487 case CHAN_SOCKDATA:
d8baa528 3488 bufsize = pfd_send(c->u.pfd.s, (char *)p, len);
bc240b21 3489 break;
32874aea 3490 case CHAN_AGENT:
3491 /* Data for an agent message. Buffer it. */
3492 while (len > 0) {
3493 if (c->u.a.lensofar < 4) {
3494 int l = min(4 - c->u.a.lensofar, len);
3495 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
3496 l);
3497 p += l;
3498 len -= l;
3499 c->u.a.lensofar += l;
3500 }
3501 if (c->u.a.lensofar == 4) {
3502 c->u.a.totallen =
3503 4 + GET_32BIT(c->u.a.msglen);
3504 c->u.a.message = smalloc(c->u.a.totallen);
3505 memcpy(c->u.a.message, c->u.a.msglen, 4);
3506 }
3507 if (c->u.a.lensofar >= 4 && len > 0) {
3508 int l =
3509 min(c->u.a.totallen - c->u.a.lensofar,
3510 len);
3511 memcpy(c->u.a.message + c->u.a.lensofar, p,
3512 l);
3513 p += l;
3514 len -= l;
3515 c->u.a.lensofar += l;
3516 }
3517 if (c->u.a.lensofar == c->u.a.totallen) {
3518 void *reply, *sentreply;
3519 int replylen;
3520 agent_query(c->u.a.message,
3521 c->u.a.totallen, &reply,
3522 &replylen);
3523 if (reply)
3524 sentreply = reply;
3525 else {
3526 /* Fake SSH_AGENT_FAILURE. */
3527 sentreply = "\0\0\0\1\5";
3528 replylen = 5;
3529 }
51470298 3530 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
32874aea 3531 PKT_INT, c->remoteid,
3532 PKT_INT, replylen,
3533 PKT_DATA, sentreply, replylen,
3534 PKT_END);
3535 if (reply)
3536 sfree(reply);
3537 sfree(c->u.a.message);
3538 c->u.a.lensofar = 0;
3539 }
3540 }
5471d09a 3541 bufsize = 0; /* agent channels never back up */
32874aea 3542 break;
3543 }
90347b95 3544 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
5471d09a 3545 c->v.v1.throttling = 1;
51470298 3546 ssh1_throttle(ssh, +1);
5471d09a 3547 }
32874aea 3548 }
51470298 3549 } else if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
972a41c8 3550 /* may be from EXEC_SHELL on some servers */
51470298 3551 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
972a41c8 3552 /* may be from EXEC_SHELL on some servers
374330e2 3553 * if no pty is available or in other odd cases. Ignore */
51470298 3554 } else if (ssh->pktin.type == SSH1_SMSG_EXIT_STATUS) {
d8d6c7e5 3555 char buf[100];
51470298 3556 ssh->exitcode = GET_32BIT(ssh->pktin.body);
d8d6c7e5 3557 sprintf(buf, "Server sent command exit status %d",
51470298 3558 ssh->exitcode);
d8d6c7e5 3559 logevent(buf);
51470298 3560 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
4252c9cc 3561 /*
3562 * In case `helpful' firewalls or proxies tack
3563 * extra human-readable text on the end of the
3564 * session which we might mistake for another
3565 * encrypted packet, we close the session once
3566 * we've sent EXIT_CONFIRMATION.
3567 */
51470298 3568 ssh->state = SSH_STATE_CLOSED;
4252c9cc 3569 crReturnV;
374330e2 3570 } else {
a8327734 3571 bombout((ssh,"Strange packet received: type %d", ssh->pktin.type));
32874aea 3572 crReturnV;
374330e2 3573 }
3574 } else {
8df7a775 3575 while (inlen > 0) {
3576 int len = min(inlen, 512);
51470298 3577 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
8df7a775 3578 PKT_INT, len, PKT_DATA, in, len, PKT_END);
3579 in += len;
3580 inlen -= len;
3581 }
374330e2 3582 }
3583 }
3584
3585 crFinishV;
3586}
3587
3588/*
e5574168 3589 * Utility routine for decoding comma-separated strings in KEXINIT.
3590 */
32874aea 3591static int in_commasep_string(char *needle, char *haystack, int haylen)
3592{
57356d63 3593 int needlen;
3594 if (!needle || !haystack) /* protect against null pointers */
3595 return 0;
3596 needlen = strlen(needle);
e5574168 3597 while (1) {
32874aea 3598 /*
3599 * Is it at the start of the string?
3600 */
3601 if (haylen >= needlen && /* haystack is long enough */
3602 !memcmp(needle, haystack, needlen) && /* initial match */
3603 (haylen == needlen || haystack[needlen] == ',')
3604 /* either , or EOS follows */
3605 )
3606 return 1;
3607 /*
3608 * If not, search for the next comma and resume after that.
3609 * If no comma found, terminate.
3610 */
3611 while (haylen > 0 && *haystack != ',')
3612 haylen--, haystack++;
3613 if (haylen == 0)
3614 return 0;
3615 haylen--, haystack++; /* skip over comma itself */
e5574168 3616 }
3617}
3618
3619/*
d39f364a 3620 * SSH2 key creation method.
3621 */
d8baa528 3622static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
3623 unsigned char *sessid, char chr,
3624 unsigned char *keyspace)
32874aea 3625{
d39f364a 3626 SHA_State s;
3627 /* First 20 bytes. */
3628 SHA_Init(&s);
51470298 3629 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
088bde77 3630 sha_mpint(&s, K);
d39f364a 3631 SHA_Bytes(&s, H, 20);
3632 SHA_Bytes(&s, &chr, 1);
5e0d7cb8 3633 SHA_Bytes(&s, sessid, 20);
d39f364a 3634 SHA_Final(&s, keyspace);
3635 /* Next 20 bytes. */
3636 SHA_Init(&s);
51470298 3637 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
088bde77 3638 sha_mpint(&s, K);
d39f364a 3639 SHA_Bytes(&s, H, 20);
3640 SHA_Bytes(&s, keyspace, 20);
32874aea 3641 SHA_Final(&s, keyspace + 20);
d39f364a 3642}
3643
3644/*
7cca0d81 3645 * Handle the SSH2 transport layer.
e5574168 3646 */
51470298 3647static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
e5574168 3648{
51470298 3649 struct do_ssh2_transport_state {
3650 int nbits, pbits, warn;
3651 Bignum p, g, e, f, K;
3652 int kex_init_value, kex_reply_value;
3653 const struct ssh_mac **maclist;
3654 int nmacs;
3655 const struct ssh2_cipher *cscipher_tobe;
3656 const struct ssh2_cipher *sccipher_tobe;
3657 const struct ssh_mac *csmac_tobe;
3658 const struct ssh_mac *scmac_tobe;
3659 const struct ssh_compress *cscomp_tobe;
3660 const struct ssh_compress *sccomp_tobe;
3661 char *hostkeydata, *sigdata, *keystr, *fingerprint;
3662 int hostkeylen, siglen;
3663 void *hkey; /* actual host key */
3664 unsigned char exchange_hash[20];
3665 int n_preferred_ciphers;
3666 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
3667 const struct ssh_compress *preferred_comp;
3668 int first_kex;
3669 };
3670 crState(do_ssh2_transport_state);
3671
3672 crBegin(ssh->do_ssh2_transport_crstate);
3673
3674 s->cscipher_tobe = s->sccipher_tobe = NULL;
3675 s->csmac_tobe = s->scmac_tobe = NULL;
3676 s->cscomp_tobe = s->sccomp_tobe = NULL;
3677
7cca0d81 3678 random_init();
51470298 3679 s->first_kex = 1;
e5574168 3680
51470298 3681 {
3682 int i;
3683 /*
3684 * Set up the preferred ciphers. (NULL => warn below here)
3685 */
3686 s->n_preferred_ciphers = 0;
3687 for (i = 0; i < CIPHER_MAX; i++) {
3688 switch (cfg.ssh_cipherlist[i]) {
3689 case CIPHER_BLOWFISH:
3690 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
3691 break;
3692 case CIPHER_DES:
3693 if (cfg.ssh2_des_cbc) {
3694 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
3695 }
3696 break;
3697 case CIPHER_3DES:
3698 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
3699 break;
3700 case CIPHER_AES:
3701 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
3702 break;
3703 case CIPHER_WARN:
3704 /* Flag for later. Don't bother if it's the last in
3705 * the list. */
3706 if (i < CIPHER_MAX - 1) {
3707 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
3708 }
3709 break;
ca20bfcf 3710 }
ca20bfcf 3711 }
5e8358ad 3712 }
ca20bfcf 3713
3714 /*
3715 * Set up preferred compression.
3716 */
4ba9b64b 3717 if (cfg.compression)
51470298 3718 s->preferred_comp = &ssh_zlib;
4ba9b64b 3719 else
51470298 3720 s->preferred_comp = &ssh_comp_none;
5e8358ad 3721
7591b9ff 3722 /*
3723 * Be prepared to work around the buggy MAC problem.
3724 */
51470298 3725 if (ssh->remote_bugs & BUG_SSH2_HMAC)
3726 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
7591b9ff 3727 else
51470298 3728 s->maclist = macs, s->nmacs = lenof(macs);
7591b9ff 3729
32874aea 3730 begin_key_exchange:
51470298 3731 {
3732 int i, j, cipherstr_started;
3733
3734 /*
3735 * Construct and send our key exchange packet.
3736 */
3737 ssh2_pkt_init(ssh, SSH2_MSG_KEXINIT);
3738 for (i = 0; i < 16; i++)
3739 ssh2_pkt_addbyte(ssh, (unsigned char) random_byte());
3740 /* List key exchange algorithms. */
3741 ssh2_pkt_addstring_start(ssh);
3742 for (i = 0; i < lenof(kex_algs); i++) {
3743 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3744 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
3745 continue;
3746 ssh2_pkt_addstring_str(ssh, kex_algs[i]->name);
3747 if (i < lenof(kex_algs) - 1)
3748 ssh2_pkt_addstring_str(ssh, ",");
32874aea 3749 }
51470298 3750 /* List server host key algorithms. */
3751 ssh2_pkt_addstring_start(ssh);
3752 for (i = 0; i < lenof(hostkey_algs); i++) {
3753 ssh2_pkt_addstring_str(ssh, hostkey_algs[i]->name);
3754 if (i < lenof(hostkey_algs) - 1)
3755 ssh2_pkt_addstring_str(ssh, ",");
32874aea 3756 }
51470298 3757 /* List client->server encryption algorithms. */
3758 ssh2_pkt_addstring_start(ssh);
3759 cipherstr_started = 0;
3760 for (i = 0; i < s->n_preferred_ciphers; i++) {
3761 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3762 if (!c) continue; /* warning flag */
3763 for (j = 0; j < c->nciphers; j++) {
3764 if (cipherstr_started)
3765 ssh2_pkt_addstring_str(ssh, ",");
3766 ssh2_pkt_addstring_str(ssh, c->list[j]->name);
3767 cipherstr_started = 1;
3768 }
3769 }
3770 /* List server->client encryption algorithms. */
3771 ssh2_pkt_addstring_start(ssh);
3772 cipherstr_started = 0;
3773 for (i = 0; i < s->n_preferred_ciphers; i++) {
3774 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3775 if (!c) continue; /* warning flag */
3776 for (j = 0; j < c->nciphers; j++) {
3777 if (cipherstr_started)
3778 ssh2_pkt_addstring_str(ssh, ",");
3779 ssh2_pkt_addstring_str(ssh, c->list[j]->name);
3780 cipherstr_started = 1;
3781 }
3782 }
3783 /* List client->server MAC algorithms. */
3784 ssh2_pkt_addstring_start(ssh);
3785 for (i = 0; i < s->nmacs; i++) {
3786 ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
3787 if (i < s->nmacs - 1)
3788 ssh2_pkt_addstring_str(ssh, ",");
3789 }
3790 /* List server->client MAC algorithms. */
3791 ssh2_pkt_addstring_start(ssh);
3792 for (i = 0; i < s->nmacs; i++) {
3793 ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
3794 if (i < s->nmacs - 1)
3795 ssh2_pkt_addstring_str(ssh, ",");
3796 }
3797 /* List client->server compression algorithms. */
3798 ssh2_pkt_addstring_start(ssh);
3799 for (i = 0; i < lenof(compressions) + 1; i++) {
3800 const struct ssh_compress *c =
3801 i == 0 ? s->preferred_comp : compressions[i - 1];
3802 ssh2_pkt_addstring_str(ssh, c->name);
3803 if (i < lenof(compressions))
3804 ssh2_pkt_addstring_str(ssh, ",");
3805 }
3806 /* List server->client compression algorithms. */
3807 ssh2_pkt_addstring_start(ssh);
3808 for (i = 0; i < lenof(compressions) + 1; i++) {
3809 const struct ssh_compress *c =
3810 i == 0 ? s->preferred_comp : compressions[i - 1];
3811 ssh2_pkt_addstring_str(ssh, c->name);
3812 if (i < lenof(compressions))
3813 ssh2_pkt_addstring_str(ssh, ",");
3814 }
3815 /* List client->server languages. Empty list. */
3816 ssh2_pkt_addstring_start(ssh);
3817 /* List server->client languages. Empty list. */
3818 ssh2_pkt_addstring_start(ssh);
3819 /* First KEX packet does _not_ follow, because we're not that brave. */
3820 ssh2_pkt_addbool(ssh, FALSE);
3821 /* Reserved. */
3822 ssh2_pkt_adduint32(ssh, 0);
e5574168 3823 }
0db56f73 3824
51470298 3825 ssh->exhash = ssh->exhashbase;
3826 sha_string(&ssh->exhash, ssh->pktout.data + 5, ssh->pktout.length - 5);
0db56f73 3827
51470298 3828 ssh2_pkt_send(ssh);
e5574168 3829
32874aea 3830 if (!ispkt)
3831 crWaitUntil(ispkt);
57356d63 3832 if (ssh->pktin.length > 5)
3833 sha_string(&ssh->exhash, ssh->pktin.data + 5, ssh->pktin.length - 5);
e5574168 3834
3835 /*
3836 * Now examine the other side's KEXINIT to see what we're up
3837 * to.
3838 */
51470298 3839 {
3840 char *str;
3841 int i, j, len;
3842
3843 if (ssh->pktin.type != SSH2_MSG_KEXINIT) {
a8327734 3844 bombout((ssh,"expected key exchange packet from server"));
51470298 3845 crReturn(0);
32874aea 3846 }
51470298 3847 ssh->kex = NULL;
3848 ssh->hostkey = NULL;
3849 s->cscipher_tobe = NULL;
3850 s->sccipher_tobe = NULL;
3851 s->csmac_tobe = NULL;
3852 s->scmac_tobe = NULL;
3853 s->cscomp_tobe = NULL;
3854 s->sccomp_tobe = NULL;
3855 ssh->pktin.savedpos += 16; /* skip garbage cookie */
3856 ssh2_pkt_getstring(ssh, &str, &len); /* key exchange algorithms */
3857 for (i = 0; i < lenof(kex_algs); i++) {
3858 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3859 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
3860 continue;
3861 if (in_commasep_string(kex_algs[i]->name, str, len)) {
3862 ssh->kex = kex_algs[i];
3863 break;
3864 }
32874aea 3865 }
51470298 3866 ssh2_pkt_getstring(ssh, &str, &len); /* host key algorithms */
3867 for (i = 0; i < lenof(hostkey_algs); i++) {
3868 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3869 ssh->hostkey = hostkey_algs[i];
3870 break;
3871 }
3872 }
3873 ssh2_pkt_getstring(ssh, &str, &len); /* client->server cipher */
3874 s->warn = 0;
3875 for (i = 0; i < s->n_preferred_ciphers; i++) {
3876 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3877 if (!c) {
3878 s->warn = 1;
3879 } else {
3880 for (j = 0; j < c->nciphers; j++) {
3881 if (in_commasep_string(c->list[j]->name, str, len)) {
3882 s->cscipher_tobe = c->list[j];
3883 break;
3884 }
ca20bfcf 3885 }
32874aea 3886 }
51470298 3887 if (s->cscipher_tobe) {
3888 if (s->warn)
a8327734 3889 askcipher(ssh->frontend, s->cscipher_tobe->name, 1);
51470298 3890 break;
3891 }
32874aea 3892 }
51470298 3893 if (!s->cscipher_tobe) {
57356d63 3894 bombout((ssh,"Couldn't agree a client-to-server cipher (available: %s)",
3895 str ? str : "(null)"));
51470298 3896 crReturn(0);
ca20bfcf 3897 }
0ef8f407 3898
51470298 3899 ssh2_pkt_getstring(ssh, &str, &len); /* server->client cipher */
3900 s->warn = 0;
3901 for (i = 0; i < s->n_preferred_ciphers; i++) {
3902 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3903 if (!c) {
3904 s->warn = 1;
3905 } else {
3906 for (j = 0; j < c->nciphers; j++) {
3907 if (in_commasep_string(c->list[j]->name, str, len)) {
3908 s->sccipher_tobe = c->list[j];
3909 break;
3910 }
ca20bfcf 3911 }
32874aea 3912 }
51470298 3913 if (s->sccipher_tobe) {
3914 if (s->warn)
a8327734 3915 askcipher(ssh->frontend, s->sccipher_tobe->name, 2);
51470298 3916 break;
3917 }
32874aea 3918 }
51470298 3919 if (!s->sccipher_tobe) {
57356d63 3920 bombout((ssh,"Couldn't agree a server-to-client cipher (available: %s)",
3921 str ? str : "(null)"));
51470298 3922 crReturn(0);
ca20bfcf 3923 }
0ef8f407 3924
51470298 3925 ssh2_pkt_getstring(ssh, &str, &len); /* client->server mac */
3926 for (i = 0; i < s->nmacs; i++) {
3927 if (in_commasep_string(s->maclist[i]->name, str, len)) {
3928 s->csmac_tobe = s->maclist[i];
3929 break;
3930 }
32874aea 3931 }
51470298 3932 ssh2_pkt_getstring(ssh, &str, &len); /* server->client mac */
3933 for (i = 0; i < s->nmacs; i++) {
3934 if (in_commasep_string(s->maclist[i]->name, str, len)) {
3935 s->scmac_tobe = s->maclist[i];
3936 break;
3937 }
32874aea 3938 }
51470298 3939 ssh2_pkt_getstring(ssh, &str, &len); /* client->server compression */
3940 for (i = 0; i < lenof(compressions) + 1; i++) {
3941 const struct ssh_compress *c =
3942 i == 0 ? s->preferred_comp : compressions[i - 1];
3943 if (in_commasep_string(c->name, str, len)) {
3944 s->cscomp_tobe = c;
3945 break;
3946 }
32874aea 3947 }
51470298 3948 ssh2_pkt_getstring(ssh, &str, &len); /* server->client compression */
3949 for (i = 0; i < lenof(compressions) + 1; i++) {
3950 const struct ssh_compress *c =
3951 i == 0 ? s->preferred_comp : compressions[i - 1];
3952 if (in_commasep_string(c->name, str, len)) {
3953 s->sccomp_tobe = c;
3954 break;
3955 }
32874aea 3956 }
e5574168 3957 }
e5574168 3958
3959 /*
7bd5a860 3960 * Work out the number of bits of key we will need from the key
3961 * exchange. We start with the maximum key length of either
3962 * cipher...
3963 */
3964 {
32874aea 3965 int csbits, scbits;
7bd5a860 3966
51470298 3967 csbits = s->cscipher_tobe->keylen;
3968 scbits = s->sccipher_tobe->keylen;
3969 s->nbits = (csbits > scbits ? csbits : scbits);
7bd5a860 3970 }
3971 /* The keys only have 160-bit entropy, since they're based on
3972 * a SHA-1 hash. So cap the key size at 160 bits. */
51470298 3973 if (s->nbits > 160)
3974 s->nbits = 160;
7bd5a860 3975
3976 /*
a92dd380 3977 * If we're doing Diffie-Hellman group exchange, start by
3978 * requesting a group.
e5574168 3979 */
51470298 3980 if (ssh->kex == &ssh_diffiehellman_gex) {
32874aea 3981 logevent("Doing Diffie-Hellman group exchange");
51470298 3982 ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
32874aea 3983 /*
3984 * Work out how big a DH group we will need to allow that
3985 * much data.
7bd5a860 3986 */
51470298 3987 s->pbits = 512 << ((s->nbits - 1) / 64);
3988 ssh2_pkt_init(ssh, SSH2_MSG_KEX_DH_GEX_REQUEST);
3989 ssh2_pkt_adduint32(ssh, s->pbits);
3990 ssh2_pkt_send(ssh);
32874aea 3991
3992 crWaitUntil(ispkt);
51470298 3993 if (ssh->pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
a8327734 3994 bombout((ssh,"expected key exchange group packet from server"));
32874aea 3995 crReturn(0);
3996 }
51470298 3997 s->p = ssh2_pkt_getmp(ssh);
3998 s->g = ssh2_pkt_getmp(ssh);
27cd7fc2 3999 ssh->kex_ctx = dh_setup_group(s->p, s->g);
51470298 4000 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
4001 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
a92dd380 4002 } else {
51470298 4003 ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
27cd7fc2 4004 ssh->kex_ctx = dh_setup_group1();
51470298 4005 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
4006 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
8d5de777 4007 }
e5574168 4008
a92dd380 4009 logevent("Doing Diffie-Hellman key exchange");
e5574168 4010 /*
a92dd380 4011 * Now generate and send e for Diffie-Hellman.
e5574168 4012 */
27cd7fc2 4013 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
51470298 4014 ssh2_pkt_init(ssh, s->kex_init_value);
4015 ssh2_pkt_addmp(ssh, s->e);
4016 ssh2_pkt_send(ssh);
e5574168 4017
4018 crWaitUntil(ispkt);
51470298 4019 if (ssh->pktin.type != s->kex_reply_value) {
a8327734 4020 bombout((ssh,"expected key exchange reply packet from server"));
32874aea 4021 crReturn(0);
7cca0d81 4022 }
51470298 4023 ssh2_pkt_getstring(ssh, &s->hostkeydata, &s->hostkeylen);
4024 s->f = ssh2_pkt_getmp(ssh);
4025 ssh2_pkt_getstring(ssh, &s->sigdata, &s->siglen);
e5574168 4026
27cd7fc2 4027 s->K = dh_find_K(ssh->kex_ctx, s->f);
e5574168 4028
51470298 4029 sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
4030 if (ssh->kex == &ssh_diffiehellman_gex) {
4031 sha_uint32(&ssh->exhash, s->pbits);
4032 sha_mpint(&ssh->exhash, s->p);
4033 sha_mpint(&ssh->exhash, s->g);
a92dd380 4034 }
51470298 4035 sha_mpint(&ssh->exhash, s->e);
4036 sha_mpint(&ssh->exhash, s->f);
4037 sha_mpint(&ssh->exhash, s->K);
4038 SHA_Final(&ssh->exhash, s->exchange_hash);
e5574168 4039
27cd7fc2 4040 dh_cleanup(ssh->kex_ctx);
3709bfe9 4041
7cca0d81 4042#if 0
765c4200 4043 debug(("Exchange hash is:\n"));
51470298 4044 dmemdump(s->exchange_hash, 20);
7cca0d81 4045#endif
4046
51470298 4047 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
4048 if (!s->hkey ||
4049 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
d8baa528 4050 (char *)s->exchange_hash, 20)) {
a8327734 4051 bombout((ssh,"Server's host key did not match the signature supplied"));
32874aea 4052 crReturn(0);
8d5de777 4053 }
e5574168 4054
4055 /*
7cca0d81 4056 * Authenticate remote host: verify host key. (We've already
4057 * checked the signature of the exchange hash.)
e5574168 4058 */
51470298 4059 s->keystr = ssh->hostkey->fmtkey(s->hkey);
4060 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
a8327734 4061 verify_ssh_host_key(ssh->frontend,
4062 ssh->savedhost, ssh->savedport, ssh->hostkey->keytype,
51470298 4063 s->keystr, s->fingerprint);
4064 if (s->first_kex) { /* don't bother logging this in rekeys */
5e0d7cb8 4065 logevent("Host key fingerprint is:");
51470298 4066 logevent(s->fingerprint);
5e0d7cb8 4067 }
51470298 4068 sfree(s->fingerprint);
4069 sfree(s->keystr);
4070 ssh->hostkey->freekey(s->hkey);
d39f364a 4071
4072 /*
7cca0d81 4073 * Send SSH2_MSG_NEWKEYS.
d39f364a 4074 */
51470298 4075 ssh2_pkt_init(ssh, SSH2_MSG_NEWKEYS);
4076 ssh2_pkt_send(ssh);
d39f364a 4077
4078 /*
8406eaf9 4079 * Expect SSH2_MSG_NEWKEYS from server.
4080 */
4081 crWaitUntil(ispkt);
51470298 4082 if (ssh->pktin.type != SSH2_MSG_NEWKEYS) {
a8327734 4083 bombout((ssh,"expected new-keys packet from server"));
8406eaf9 4084 crReturn(0);
4085 }
4086
4087 /*
d39f364a 4088 * Create and initialise session keys.
4089 */
371e569c 4090 if (ssh->cs_cipher_ctx)
4091 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
51470298 4092 ssh->cscipher = s->cscipher_tobe;
371e569c 4093 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
e0e1a00d 4094
371e569c 4095 if (ssh->sc_cipher_ctx)
4096 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
51470298 4097 ssh->sccipher = s->sccipher_tobe;
371e569c 4098 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
e0e1a00d 4099
4100 if (ssh->cs_mac_ctx)
4101 ssh->csmac->free_context(ssh->cs_mac_ctx);
51470298 4102 ssh->csmac = s->csmac_tobe;
e0e1a00d 4103 ssh->cs_mac_ctx = ssh->csmac->make_context();
4104
4105 if (ssh->sc_mac_ctx)
4106 ssh->scmac->free_context(ssh->sc_mac_ctx);
51470298 4107 ssh->scmac = s->scmac_tobe;
e0e1a00d 4108 ssh->sc_mac_ctx = ssh->scmac->make_context();
4109
5366aed8 4110 if (ssh->cs_comp_ctx)
4111 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
51470298 4112 ssh->cscomp = s->cscomp_tobe;
5366aed8 4113 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
4114
4115 if (ssh->sc_comp_ctx)
4116 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
51470298 4117 ssh->sccomp = s->sccomp_tobe;
5366aed8 4118 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
4119
d39f364a 4120 /*
5e0d7cb8 4121 * Set IVs after keys. Here we use the exchange hash from the
4122 * _first_ key exchange.
d39f364a 4123 */
51470298 4124 {
4125 unsigned char keyspace[40];
4126 if (s->first_kex)
4127 memcpy(ssh->v2_session_id, s->exchange_hash,
4128 sizeof(s->exchange_hash));
4129 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
371e569c 4130 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
51470298 4131 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
371e569c 4132 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
51470298 4133 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
371e569c 4134 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
51470298 4135 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
371e569c 4136 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
51470298 4137 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
e0e1a00d 4138 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
51470298 4139 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
e0e1a00d 4140 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
51470298 4141 }
57356d63 4142 logeventf(ssh, "Initialised %.200s client->server encryption",
4143 ssh->cscipher->text_name);
4144 logeventf(ssh, "Initialised %.200s server->client encryption",
4145 ssh->sccipher->text_name);
4146 if (ssh->cscomp->text_name)
4147 logeventf(ssh, "Initialised %s compression",
4148 ssh->cscomp->text_name);
4149 if (ssh->sccomp->text_name)
4150 logeventf(ssh, "Initialised %s decompression",
4151 ssh->sccomp->text_name);
d39f364a 4152
033b4cef 4153 /*
0db56f73 4154 * If this is the first key exchange phase, we must pass the
4155 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
4156 * wants to see it but because it will need time to initialise
4157 * itself before it sees an actual packet. In subsequent key
4158 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
4159 * it would only confuse the layer above.
4160 */
51470298 4161 if (!s->first_kex) {
32874aea 4162 crReturn(0);
0db56f73 4163 }
51470298 4164 s->first_kex = 0;
0db56f73 4165
4166 /*
7cca0d81 4167 * Now we're encrypting. Begin returning 1 to the protocol main
4168 * function so that other things can run on top of the
4169 * transport. If we ever see a KEXINIT, we must go back to the
4170 * start.
033b4cef 4171 */
51470298 4172 while (!(ispkt && ssh->pktin.type == SSH2_MSG_KEXINIT)) {
32874aea 4173 crReturn(1);
e96adf72 4174 }
5e0d7cb8 4175 logevent("Server initiated key re-exchange");
7cca0d81 4176 goto begin_key_exchange;
e5574168 4177
4178 crFinish(1);
4179}
4180
7cca0d81 4181/*
783415f8 4182 * Add data to an SSH2 channel output buffer.
4183 */
32874aea 4184static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
4185 int len)
4186{
5471d09a 4187 bufchain_add(&c->v.v2.outbuffer, buf, len);
783415f8 4188}
4189
4190/*
4191 * Attempt to send data on an SSH2 channel.
4192 */
5471d09a 4193static int ssh2_try_send(struct ssh_channel *c)
32874aea 4194{
51470298 4195 Ssh ssh = c->ssh;
4196
5471d09a 4197 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
4198 int len;
4199 void *data;
4200 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
4201 if ((unsigned)len > c->v.v2.remwindow)
4202 len = c->v.v2.remwindow;
4203 if ((unsigned)len > c->v.v2.remmaxpkt)
4204 len = c->v.v2.remmaxpkt;
51470298 4205 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_DATA);
4206 ssh2_pkt_adduint32(ssh, c->remoteid);
4207 ssh2_pkt_addstring_start(ssh);
4208 ssh2_pkt_addstring_data(ssh, data, len);
4209 ssh2_pkt_send(ssh);
5471d09a 4210 bufchain_consume(&c->v.v2.outbuffer, len);
4211 c->v.v2.remwindow -= len;
4212 }
4213
4214 /*
4215 * After having sent as much data as we can, return the amount
4216 * still buffered.
4217 */
4218 return bufchain_size(&c->v.v2.outbuffer);
4219}
4220
4221/*
4222 * Potentially enlarge the window on an SSH2 channel.
4223 */
4224static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
4225{
51470298 4226 Ssh ssh = c->ssh;
4227
6b69f42e 4228 /*
4229 * Never send WINDOW_ADJUST for a channel that the remote side
4230 * already thinks it's closed; there's no point, since it won't
4231 * be sending any more data anyway.
4232 */
4233 if (c->closes != 0)
4234 return;
4235
5471d09a 4236 if (newwin > c->v.v2.locwindow) {
51470298 4237 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4238 ssh2_pkt_adduint32(ssh, c->remoteid);
4239 ssh2_pkt_adduint32(ssh, newwin - c->v.v2.locwindow);
4240 ssh2_pkt_send(ssh);
5471d09a 4241 c->v.v2.locwindow = newwin;
783415f8 4242 }
4243}
4244
4245/*
7cca0d81 4246 * Handle the SSH2 userauth and connection layers.
4247 */
51470298 4248static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
7cca0d81 4249{
51470298 4250 struct do_ssh2_authconn_state {
4251 enum {
4252 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
4253 AUTH_PASSWORD,
4254 AUTH_KEYBOARD_INTERACTIVE
4255 } method;
4256 enum {
4257 AUTH_TYPE_NONE,
4258 AUTH_TYPE_PUBLICKEY,
4259 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
4260 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
4261 AUTH_TYPE_PASSWORD,
4262 AUTH_TYPE_KEYBOARD_INTERACTIVE,
4263 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4264 } type;
4265 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
4266 int tried_pubkey_config, tried_agent, tried_keyb_inter;
4267 int kbd_inter_running;
4268 int we_are_in;
4269 int num_prompts, curr_prompt, echo;
4270 char username[100];
4271 int got_username;
4272 char pwprompt[200];
4273 char password[100];
4274 void *publickey_blob;
4275 int publickey_bloblen;
4276 unsigned char request[5], *response, *p;
4277 int responselen;
4278 int keyi, nkeys;
4279 int authed;
4280 char *pkblob, *alg, *commentp;
4281 int pklen, alglen, commentlen;
4282 int siglen, retlen, len;
4283 char *q, *agentreq, *ret;
4284 int try_send;
4285 };
4286 crState(do_ssh2_authconn_state);
4287
4288 crBegin(ssh->do_ssh2_authconn_crstate);
e5574168 4289
7cca0d81 4290 /*
4291 * Request userauth protocol, and await a response to it.
4292 */
51470298 4293 ssh2_pkt_init(ssh, SSH2_MSG_SERVICE_REQUEST);
4294 ssh2_pkt_addstring(ssh, "ssh-userauth");
4295 ssh2_pkt_send(ssh);
7cca0d81 4296 crWaitUntilV(ispkt);
51470298 4297 if (ssh->pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
a8327734 4298 bombout((ssh,"Server refused user authentication protocol"));
32874aea 4299 crReturnV;
8d5de777 4300 }
7cca0d81 4301
4302 /*
1408a877 4303 * We repeat this whole loop, including the username prompt,
4304 * until we manage a successful authentication. If the user
51470298 4305 * types the wrong _password_, they can be sent back to the
4306 * beginning to try another username, if this is configured on.
4307 * (If they specify a username in the config, they are never
4308 * asked, even if they do give a wrong password.)
1408a877 4309 *
4310 * I think this best serves the needs of
4311 *
4312 * - the people who have no configuration, no keys, and just
4313 * want to try repeated (username,password) pairs until they
4314 * type both correctly
4315 *
4316 * - people who have keys and configuration but occasionally
4317 * need to fall back to passwords
4318 *
4319 * - people with a key held in Pageant, who might not have
4320 * logged in to a particular machine before; so they want to
4321 * type a username, and then _either_ their key will be
4322 * accepted, _or_ they will type a password. If they mistype
4323 * the username they will want to be able to get back and
4324 * retype it!
7cca0d81 4325 */
51470298 4326 s->username[0] = '\0';
4327 s->got_username = FALSE;
1408a877 4328 do {
1408a877 4329 /*
4330 * Get a username.
4331 */
51470298 4332 if (s->got_username && !cfg.change_username) {
5bb641e1 4333 /*
4334 * We got a username last time round this loop, and
4335 * with change_username turned off we don't try to get
4336 * it again.
4337 */
4338 } else if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
c0a81592 4339 if (ssh_get_line && !ssh_getline_pw_only) {
32874aea 4340 if (!ssh_get_line("login as: ",
51470298 4341 s->username, sizeof(s->username), FALSE)) {
32874aea 4342 /*
4343 * get_line failed to get a username.
4344 * Terminate.
4345 */
4346 logevent("No username provided. Abandoning session.");
51470298 4347 ssh->state = SSH_STATE_CLOSED;
32874aea 4348 crReturnV;
4349 }
4350 } else {
51470298 4351 int ret; /* need not be saved across crReturn */
4352 c_write_str(ssh, "login as: ");
4353 ssh->send_ok = 1;
4354 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
0405e71f 4355 do {
32874aea 4356 crWaitUntilV(!ispkt);
51470298 4357 ret = process_userpass_input(ssh, in, inlen);
0405e71f 4358 } while (ret == 0);
4359 if (ret < 0)
4360 cleanup_exit(0);
4ca0c9d1 4361 c_write_str(ssh, "\r\n");
32874aea 4362 }
51470298 4363 s->username[strcspn(s->username, "\n\r")] = '\0';
7cca0d81 4364 } else {
57356d63 4365 char *stuff;
51470298 4366 strncpy(s->username, cfg.username, sizeof(s->username));
4367 s->username[sizeof(s->username)-1] = '\0';
65a22376 4368 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
57356d63 4369 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
51470298 4370 c_write_str(ssh, stuff);
57356d63 4371 sfree(stuff);
7cca0d81 4372 }
4373 }
51470298 4374 s->got_username = TRUE;
7cca0d81 4375
65a22376 4376 /*
1408a877 4377 * Send an authentication request using method "none": (a)
4378 * just in case it succeeds, and (b) so that we know what
4379 * authentication methods we can usefully try next.
65a22376 4380 */
51470298 4381 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4382
4383 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4384 ssh2_pkt_addstring(ssh, s->username);
4385 ssh2_pkt_addstring(ssh, "ssh-connection");/* service requested */
4386 ssh2_pkt_addstring(ssh, "none"); /* method */
4387 ssh2_pkt_send(ssh);
4388 s->type = AUTH_TYPE_NONE;
4389 s->gotit = FALSE;
4390 s->we_are_in = FALSE;
4391
4392 s->tried_pubkey_config = FALSE;
4393 s->tried_agent = FALSE;
4394 s->tried_keyb_inter = FALSE;
4395 s->kbd_inter_running = FALSE;
396778f1 4396 /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
4397 if (*cfg.keyfile) {
231ee168 4398 int keytype;
c2ad7d0d 4399 logeventf(ssh, "Reading private key file \"%.150s\"", cfg.keyfile);
231ee168 4400 keytype = key_type(cfg.keyfile);
51470298 4401 if (keytype == SSH_KEYTYPE_SSH2) {
4402 s->publickey_blob =
4403 ssh2_userkey_loadpub(cfg.keyfile, NULL,
4404 &s->publickey_bloblen);
4405 } else {
57356d63 4406 char *msgbuf;
c2ad7d0d 4407 logeventf(ssh, "Unable to use this key file (%s)",
a8327734 4408 key_type_to_str(keytype));
57356d63 4409 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4410 " (%s)\r\n", cfg.keyfile,
4411 key_type_to_str(keytype));
51470298 4412 c_write_str(ssh, msgbuf);
57356d63 4413 sfree(msgbuf);
51470298 4414 s->publickey_blob = NULL;
231ee168 4415 }
396778f1 4416 } else
51470298 4417 s->publickey_blob = NULL;
65a22376 4418
1408a877 4419 while (1) {
4420 /*
4421 * Wait for the result of the last authentication request.
4422 */
51470298 4423 if (!s->gotit)
1408a877 4424 crWaitUntilV(ispkt);
51470298 4425 while (ssh->pktin.type == SSH2_MSG_USERAUTH_BANNER) {
32874aea 4426 char *banner;
4427 int size;
4428 /*
4429 * Don't show the banner if we're operating in
4430 * non-verbose non-interactive mode. (It's probably
4431 * a script, which means nobody will read the
4432 * banner _anyway_, and moreover the printing of
4433 * the banner will screw up processing on the
4434 * output of (say) plink.)
4435 */
4436 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
51470298 4437 ssh2_pkt_getstring(ssh, &banner, &size);
32874aea 4438 if (banner)
51470298 4439 c_write_untrusted(ssh, banner, size);
32874aea 4440 }
1408a877 4441 crWaitUntilV(ispkt);
4442 }
51470298 4443 if (ssh->pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
1408a877 4444 logevent("Access granted");
51470298 4445 s->we_are_in = TRUE;
1408a877 4446 break;
4447 }
65a22376 4448
51470298 4449 if (s->kbd_inter_running &&
4450 ssh->pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
b3186d64 4451 /*
45068b27 4452 * This is either a further set-of-prompts packet
4453 * in keyboard-interactive authentication, or it's
4454 * the same one and we came back here with `gotit'
4455 * set. In the former case, we must reset the
4456 * curr_prompt variable.
b3186d64 4457 */
51470298 4458 if (!s->gotit)
4459 s->curr_prompt = 0;
4460 } else if (ssh->pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
a8327734 4461 bombout((ssh,"Strange packet received during authentication: type %d",
51470298 4462 ssh->pktin.type));
38c4a8da 4463 crReturnV;
65a22376 4464 }
4465
51470298 4466 s->gotit = FALSE;
65a22376 4467
1408a877 4468 /*
4469 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4470 * we can look at the string in it and know what we can
4471 * helpfully try next.
4472 */
51470298 4473 if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
1408a877 4474 char *methods;
4475 int methlen;
51470298 4476 ssh2_pkt_getstring(ssh, &methods, &methlen);
4477 s->kbd_inter_running = FALSE;
4478 if (!ssh2_pkt_getbool(ssh)) {
1408a877 4479 /*
4480 * We have received an unequivocal Access
4481 * Denied. This can translate to a variety of
4482 * messages:
4483 *
4484 * - if we'd just tried "none" authentication,
4485 * it's not worth printing anything at all
4486 *
4487 * - if we'd just tried a public key _offer_,
4488 * the message should be "Server refused our
4489 * key" (or no message at all if the key
4490 * came from Pageant)
4491 *
4492 * - if we'd just tried anything else, the
4493 * message really should be "Access denied".
4494 *
4495 * Additionally, if we'd just tried password
4496 * authentication, we should break out of this
4497 * whole loop so as to go back to the username
4498 * prompt.
4499 */
51470298 4500 if (s->type == AUTH_TYPE_NONE) {
1408a877 4501 /* do nothing */
51470298 4502 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
4503 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
4504 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
4505 c_write_str(ssh, "Server refused our key\r\n");
1408a877 4506 logevent("Server refused public key");
51470298 4507 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
4bdf7c46 4508 /* server declined keyboard-interactive; ignore */
1408a877 4509 } else {
51470298 4510 c_write_str(ssh, "Access denied\r\n");
1408a877 4511 logevent("Access denied");
51470298 4512 if (s->type == AUTH_TYPE_PASSWORD) {
4513 s->we_are_in = FALSE;
1408a877 4514 break;
4515 }
4516 }
4517 } else {
51470298 4518 c_write_str(ssh, "Further authentication required\r\n");
1408a877 4519 logevent("Further authentication required");
4520 }
65a22376 4521
51470298 4522 s->can_pubkey =
32874aea 4523 in_commasep_string("publickey", methods, methlen);
51470298 4524 s->can_passwd =
32874aea 4525 in_commasep_string("password", methods, methlen);
51470298 4526 s->can_keyb_inter = cfg.try_ki_auth &&
761187b6 4527 in_commasep_string("keyboard-interactive", methods, methlen);
1408a877 4528 }
65a22376 4529
51470298 4530 s->method = 0;
4531 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
65a22376 4532
0405e71f 4533 /*
4534 * Most password/passphrase prompts will be
4535 * non-echoing, so we set this to 0 by default.
4536 * Exception is that some keyboard-interactive prompts
4537 * can be echoing, in which case we'll set this to 1.
4538 */
51470298 4539 s->echo = 0;
0405e71f 4540
51470298 4541 if (!s->method && s->can_pubkey &&
4542 agent_exists() && !s->tried_agent) {
1983e559 4543 /*
4544 * Attempt public-key authentication using Pageant.
4545 */
1983e559 4546 void *r;
51470298 4547 s->authed = FALSE;
1983e559 4548
51470298 4549 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4550 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
00db133f 4551
51470298 4552 s->tried_agent = TRUE;
1983e559 4553
4554 logevent("Pageant is running. Requesting keys.");
4555
4556 /* Request the keys held by the agent. */
51470298 4557 PUT_32BIT(s->request, 1);
4558 s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
4559 agent_query(s->request, 5, &r, &s->responselen);
4560 s->response = (unsigned char *) r;
4561 if (s->response && s->responselen >= 5 &&
4562 s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
4563 s->p = s->response + 5;
4564 s->nkeys = GET_32BIT(s->p);
4565 s->p += 4;
32874aea 4566 {
4567 char buf[64];
51470298 4568 sprintf(buf, "Pageant has %d SSH2 keys", s->nkeys);
32874aea 4569 logevent(buf);
4570 }
51470298 4571 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
2d466ffd 4572 void *vret;
1983e559 4573
32874aea 4574 {
4575 char buf[64];
51470298 4576 sprintf(buf, "Trying Pageant key #%d", s->keyi);
32874aea 4577 logevent(buf);
4578 }
51470298 4579 s->pklen = GET_32BIT(s->p);
4580 s->p += 4;
4581 if (s->publickey_blob &&
4582 s->pklen == s->publickey_bloblen &&
4583 !memcmp(s->p, s->publickey_blob,
4584 s->publickey_bloblen)) {
396778f1 4585 logevent("This key matches configured key file");
51470298 4586 s->tried_pubkey_config = 1;
396778f1 4587 }
d8baa528 4588 s->pkblob = (char *)s->p;
51470298 4589 s->p += s->pklen;
4590 s->alglen = GET_32BIT(s->pkblob);
4591 s->alg = s->pkblob + 4;
4592 s->commentlen = GET_32BIT(s->p);
4593 s->p += 4;
d8baa528 4594 s->commentp = (char *)s->p;
51470298 4595 s->p += s->commentlen;
4596 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4597 ssh2_pkt_addstring(ssh, s->username);
4598 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4599 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4600 ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
4601 ssh2_pkt_addstring_start(ssh);
4602 ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
4603 ssh2_pkt_addstring_start(ssh);
4604 ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
4605 ssh2_pkt_send(ssh);
1983e559 4606
4607 crWaitUntilV(ispkt);
51470298 4608 if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
1983e559 4609 logevent("Key refused");
4610 continue;
4611 }
4612
32874aea 4613 if (flags & FLAG_VERBOSE) {
51470298 4614 c_write_str(ssh, "Authenticating with "
4615 "public key \"");
4616 c_write(ssh, s->commentp, s->commentlen);
4617 c_write_str(ssh, "\" from agent\r\n");
32874aea 4618 }
1983e559 4619
4620 /*
4621 * Server is willing to accept the key.
4622 * Construct a SIGN_REQUEST.
4623 */
51470298 4624 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4625 ssh2_pkt_addstring(ssh, s->username);
4626 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4627 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4628 ssh2_pkt_addbool(ssh, TRUE);
4629 ssh2_pkt_addstring_start(ssh);
4630 ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
4631 ssh2_pkt_addstring_start(ssh);
4632 ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
4633
4634 s->siglen = ssh->pktout.length - 5 + 4 + 20;
4635 s->len = 1; /* message type */
4636 s->len += 4 + s->pklen; /* key blob */
4637 s->len += 4 + s->siglen; /* data to sign */
4638 s->len += 4; /* flags */
4639 s->agentreq = smalloc(4 + s->len);
4640 PUT_32BIT(s->agentreq, s->len);
4641 s->q = s->agentreq + 4;
4642 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
4643 PUT_32BIT(s->q, s->pklen);
4644 s->q += 4;
4645 memcpy(s->q, s->pkblob, s->pklen);
4646 s->q += s->pklen;
4647 PUT_32BIT(s->q, s->siglen);
4648 s->q += 4;
1983e559 4649 /* Now the data to be signed... */
51470298 4650 PUT_32BIT(s->q, 20);
4651 s->q += 4;
4652 memcpy(s->q, ssh->v2_session_id, 20);
4653 s->q += 20;
4654 memcpy(s->q, ssh->pktout.data + 5,
4655 ssh->pktout.length - 5);
4656 s->q += ssh->pktout.length - 5;
1983e559 4657 /* And finally the (zero) flags word. */
51470298 4658 PUT_32BIT(s->q, 0);
4659 agent_query(s->agentreq, s->len + 4, &vret, &s->retlen);
4660 s->ret = vret;
4661 sfree(s->agentreq);
4662 if (s->ret) {
4663 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
1983e559 4664 logevent("Sending Pageant's response");
51470298 4665 ssh2_add_sigblob(ssh, s->pkblob, s->pklen,
4666 s->ret + 9,
4667 GET_32BIT(s->ret + 5));
4668 ssh2_pkt_send(ssh);
4669 s->authed = TRUE;
1983e559 4670 break;
4671 } else {
32874aea 4672 logevent
4673 ("Pageant failed to answer challenge");
51470298 4674 sfree(s->ret);
1983e559 4675 }
4676 }
4677 }
51470298 4678 if (s->authed)
1983e559 4679 continue;
4680 }
4681 }
4682
51470298 4683 if (!s->method && s->can_pubkey && s->publickey_blob
4684 && !s->tried_pubkey_config) {
1408a877 4685 unsigned char *pub_blob;
4686 char *algorithm, *comment;
4687 int pub_blob_len;
65a22376 4688
51470298 4689 s->tried_pubkey_config = TRUE;
65a22376 4690
51470298 4691 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4692 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
00db133f 4693
65a22376 4694 /*
1408a877 4695 * Try the public key supplied in the configuration.
4696 *
4697 * First, offer the public blob to see if the server is
4698 * willing to accept it.
65a22376 4699 */
d8baa528 4700 pub_blob =
4701 (unsigned char *)ssh2_userkey_loadpub(cfg.keyfile,
4702 &algorithm,
4703 &pub_blob_len);
1408a877 4704 if (pub_blob) {
51470298 4705 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4706 ssh2_pkt_addstring(ssh, s->username);
4707 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4708 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4709 ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
4710 ssh2_pkt_addstring(ssh, algorithm);
4711 ssh2_pkt_addstring_start(ssh);
d8baa528 4712 ssh2_pkt_addstring_data(ssh, (char *)pub_blob,
4713 pub_blob_len);
51470298 4714 ssh2_pkt_send(ssh);
32874aea 4715 logevent("Offered public key"); /* FIXME */
1408a877 4716
4717 crWaitUntilV(ispkt);
51470298 4718 if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4719 s->gotit = TRUE;
4720 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
32874aea 4721 continue; /* key refused; give up on it */
1408a877 4722 }
65a22376 4723
1408a877 4724 logevent("Offer of public key accepted");
65a22376 4725 /*
1408a877 4726 * Actually attempt a serious authentication using
4727 * the key.
65a22376 4728 */
1408a877 4729 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
51470298 4730 sprintf(s->pwprompt,
32874aea 4731 "Passphrase for key \"%.100s\": ",
4732 comment);
51470298 4733 s->need_pw = TRUE;
1408a877 4734 } else {
51470298 4735 s->need_pw = FALSE;
1408a877 4736 }
51470298 4737 c_write_str(ssh, "Authenticating with public key \"");
4738 c_write_str(ssh, comment);
4739 c_write_str(ssh, "\"\r\n");
4740 s->method = AUTH_PUBLICKEY_FILE;
65a22376 4741 }
1408a877 4742 }
4743
51470298 4744 if (!s->method && s->can_keyb_inter && !s->tried_keyb_inter) {
4745 s->method = AUTH_KEYBOARD_INTERACTIVE;
4746 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4747 s->tried_keyb_inter = TRUE;
af659722 4748
51470298 4749 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4750 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
00db133f 4751
51470298 4752 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4753 ssh2_pkt_addstring(ssh, s->username);
4754 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4755 ssh2_pkt_addstring(ssh, "keyboard-interactive"); /* method */
4756 ssh2_pkt_addstring(ssh, ""); /* lang */
4757 ssh2_pkt_addstring(ssh, "");
4758 ssh2_pkt_send(ssh);
af659722 4759
4760 crWaitUntilV(ispkt);
51470298 4761 if (ssh->pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
4762 if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE)
4763 s->gotit = TRUE;
af659722 4764 logevent("Keyboard-interactive authentication refused");
51470298 4765 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
af659722 4766 continue;
4767 }
4768
51470298 4769 s->kbd_inter_running = TRUE;
4770 s->curr_prompt = 0;
af659722 4771 }
4772
51470298 4773 if (s->kbd_inter_running) {
4774 s->method = AUTH_KEYBOARD_INTERACTIVE;
4775 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4776 s->tried_keyb_inter = TRUE;
af659722 4777
51470298 4778 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4779 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
00db133f 4780
51470298 4781 if (s->curr_prompt == 0) {
45068b27 4782 /*
4783 * We've got a fresh USERAUTH_INFO_REQUEST.
4784 * Display header data, and start going through
4785 * the prompts.
4786 */
4787 char *name, *inst, *lang;
4788 int name_len, inst_len, lang_len;
4789
51470298 4790 ssh2_pkt_getstring(ssh, &name, &name_len);
4791 ssh2_pkt_getstring(ssh, &inst, &inst_len);
4792 ssh2_pkt_getstring(ssh, &lang, &lang_len);
45068b27 4793 if (name_len > 0) {
51470298 4794 c_write_untrusted(ssh, name, name_len);
4795 c_write_str(ssh, "\r\n");
45068b27 4796 }
4797 if (inst_len > 0) {
51470298 4798 c_write_untrusted(ssh, inst, inst_len);
4799 c_write_str(ssh, "\r\n");
45068b27 4800 }
51470298 4801 s->num_prompts = ssh2_pkt_getuint32(ssh);
45068b27 4802 }
af659722 4803
45068b27 4804 /*
4805 * If there are prompts remaining in the packet,
4806 * display one and get a response.
4807 */
51470298 4808 if (s->curr_prompt < s->num_prompts) {
45068b27 4809 char *prompt;
4810 int prompt_len;
af659722 4811
51470298 4812 ssh2_pkt_getstring(ssh, &prompt, &prompt_len);
45068b27 4813 if (prompt_len > 0) {
51470298 4814 strncpy(s->pwprompt, prompt, sizeof(s->pwprompt));
4815 s->pwprompt[prompt_len < sizeof(s->pwprompt) ?
4816 prompt_len : sizeof(s->pwprompt)-1] = '\0';
45068b27 4817 } else {
51470298 4818 strcpy(s->pwprompt,
45068b27 4819 "<server failed to send prompt>: ");
4820 }
51470298 4821 s->echo = ssh2_pkt_getbool(ssh);
4822 s->need_pw = TRUE;
45068b27 4823 } else
51470298 4824 s->need_pw = FALSE;
af659722 4825 }
4826
51470298 4827 if (!s->method && s->can_passwd) {
4828 s->method = AUTH_PASSWORD;
4829 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4830 ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
4831 sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
4832 ssh->savedhost);
4833 s->need_pw = TRUE;
1408a877 4834 }
4835
51470298 4836 if (s->need_pw) {
fa17a66e 4837 if (ssh_get_line) {
51470298 4838 if (!ssh_get_line(s->pwprompt, s->password,
4839 sizeof(s->password), TRUE)) {
1408a877 4840 /*
fa17a66e 4841 * get_line failed to get a password (for
4842 * example because one was supplied on the
4843 * command line which has already failed to
4844 * work). Terminate.
1408a877 4845 */
51470298 4846 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
4847 ssh2_pkt_adduint32(ssh,SSH2_DISCONNECT_BY_APPLICATION);
4848 ssh2_pkt_addstring(ssh, "No more passwords available"
4849 " to try");
4850 ssh2_pkt_addstring(ssh, "en"); /* language tag */
4851 ssh2_pkt_send(ssh);
247308b5 4852 logevent("Unable to authenticate");
a8327734 4853 connection_fatal(ssh->frontend,
4854 "Unable to authenticate");
51470298 4855 ssh->state = SSH_STATE_CLOSED;
1408a877 4856 crReturnV;
4857 }
4858 } else {
51470298 4859 int ret; /* need not be saved across crReturn */
4860 c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
4861 ssh->send_ok = 1;
1408a877 4862
51470298 4863 setup_userpass_input(ssh, s->password,
4864 sizeof(s->password), s->echo);
0405e71f 4865 do {
1408a877 4866 crWaitUntilV(!ispkt);
51470298 4867 ret = process_userpass_input(ssh, in, inlen);
0405e71f 4868 } while (ret == 0);
4869 if (ret < 0)
4870 cleanup_exit(0);
51470298 4871 c_write_str(ssh, "\r\n");
65a22376 4872 }
65a22376 4873 }
65a22376 4874
51470298 4875 if (s->method == AUTH_PUBLICKEY_FILE) {
1408a877 4876 /*
4877 * We have our passphrase. Now try the actual authentication.
4878 */
4879 struct ssh2_userkey *key;
65a22376 4880
51470298 4881 key = ssh2_load_userkey(cfg.keyfile, s->password);
1408a877 4882 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4883 if (key == SSH2_WRONG_PASSPHRASE) {
51470298 4884 c_write_str(ssh, "Wrong passphrase\r\n");
4885 s->tried_pubkey_config = FALSE;
1408a877 4886 } else {
51470298 4887 c_write_str(ssh, "Unable to load private key\r\n");
4888 s->tried_pubkey_config = TRUE;
1408a877 4889 }
4890 /* Send a spurious AUTH_NONE to return to the top. */
51470298 4891 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4892 ssh2_pkt_addstring(ssh, s->username);
4893 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4894 ssh2_pkt_addstring(ssh, "none"); /* method */
4895 ssh2_pkt_send(ssh);
4896 s->type = AUTH_TYPE_NONE;
1408a877 4897 } else {
1dd353b5 4898 unsigned char *pkblob, *sigblob, *sigdata;
4899 int pkblob_len, sigblob_len, sigdata_len;
65a22376 4900
1408a877 4901 /*
4902 * We have loaded the private key and the server
4903 * has announced that it's willing to accept it.
4904 * Hallelujah. Generate a signature and send it.
4905 */
51470298 4906 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4907 ssh2_pkt_addstring(ssh, s->username);
4908 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4909 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4910 ssh2_pkt_addbool(ssh, TRUE);
4911 ssh2_pkt_addstring(ssh, key->alg->name);
1dd353b5 4912 pkblob = key->alg->public_blob(key->data, &pkblob_len);
51470298 4913 ssh2_pkt_addstring_start(ssh);
d8baa528 4914 ssh2_pkt_addstring_data(ssh, (char *)pkblob, pkblob_len);
1408a877 4915
4916 /*
4917 * The data to be signed is:
4918 *
4919 * string session-id
4920 *
4921 * followed by everything so far placed in the
4922 * outgoing packet.
4923 */
51470298 4924 sigdata_len = ssh->pktout.length - 5 + 4 + 20;
1408a877 4925 sigdata = smalloc(sigdata_len);
4926 PUT_32BIT(sigdata, 20);
51470298 4927 memcpy(sigdata + 4, ssh->v2_session_id, 20);
4928 memcpy(sigdata + 24, ssh->pktout.data + 5,
4929 ssh->pktout.length - 5);
d8baa528 4930 sigblob = key->alg->sign(key->data, (char *)sigdata,
1dd353b5 4931 sigdata_len, &sigblob_len);
51470298 4932 ssh2_add_sigblob(ssh, pkblob, pkblob_len,
1dd353b5 4933 sigblob, sigblob_len);
4934 sfree(pkblob);
4935 sfree(sigblob);
1408a877 4936 sfree(sigdata);
4937
51470298 4938 ssh2_pkt_send(ssh);
4939 s->type = AUTH_TYPE_PUBLICKEY;
1408a877 4940 }
51470298 4941 } else if (s->method == AUTH_PASSWORD) {
65a22376 4942 /*
1408a877 4943 * We send the password packet lumped tightly together with
4944 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4945 * string long enough to make the total length of the two
4946 * packets constant. This should ensure that a passive
4947 * listener doing traffic analyis can't work out the length
4948 * of the password.
4949 *
4950 * For this to work, we need an assumption about the
4951 * maximum length of the password packet. I think 256 is
4952 * pretty conservative. Anyone using a password longer than
4953 * that probably doesn't have much to worry about from
4954 * people who find out how long their password is!
65a22376 4955 */
51470298 4956 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4957 ssh2_pkt_addstring(ssh, s->username);
4958 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4959 ssh2_pkt_addstring(ssh, "password");
4960 ssh2_pkt_addbool(ssh, FALSE);
4961 ssh2_pkt_addstring(ssh, s->password);
4962 ssh2_pkt_defer(ssh);
65a22376 4963 /*
1408a877 4964 * We'll include a string that's an exact multiple of the
4965 * cipher block size. If the cipher is NULL for some
4966 * reason, we don't do this trick at all because we gain
4967 * nothing by it.
65a22376 4968 */
51470298 4969 if (ssh->cscipher) {
32874aea 4970 int stringlen, i;
4971
51470298 4972 stringlen = (256 - ssh->deferred_len);
4973 stringlen += ssh->cscipher->blksize - 1;
4974 stringlen -= (stringlen % ssh->cscipher->blksize);
4975 if (ssh->cscomp) {
32874aea 4976 /*
4977 * Temporarily disable actual compression,
4978 * so we can guarantee to get this string
4979 * exactly the length we want it. The
4980 * compression-disabling routine should
4981 * return an integer indicating how many
4982 * bytes we should adjust our string length
4983 * by.
4984 */
5366aed8 4985 stringlen -=
4986 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
32874aea 4987 }
51470298 4988 ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
4989 ssh2_pkt_addstring_start(ssh);
6e9e9520 4990 for (i = 0; i < stringlen; i++) {
32874aea 4991 char c = (char) random_byte();
51470298 4992 ssh2_pkt_addstring_data(ssh, &c, 1);
65a22376 4993 }
51470298 4994 ssh2_pkt_defer(ssh);
65a22376 4995 }
51470298 4996 ssh_pkt_defersend(ssh);
0d43337a 4997 logevent("Sent password");
51470298 4998 s->type = AUTH_TYPE_PASSWORD;
4999 } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
5000 if (s->curr_prompt == 0) {
5001 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE);
5002 ssh2_pkt_adduint32(ssh, s->num_prompts);
45068b27 5003 }
51470298 5004 if (s->need_pw) { /* only add pw if we just got one! */
5005 ssh2_pkt_addstring(ssh, s->password);
5006 memset(s->password, 0, sizeof(s->password));
5007 s->curr_prompt++;
45068b27 5008 }
51470298 5009 if (s->curr_prompt >= s->num_prompts) {
5010 ssh2_pkt_send(ssh);
45068b27 5011 } else {
5012 /*
5013 * If there are prompts remaining, we set
5014 * `gotit' so that we won't attempt to get
5015 * another packet. Then we go back round the
5016 * loop and will end up retrieving another
5017 * prompt out of the existing packet. Funky or
5018 * what?
5019 */
51470298 5020 s->gotit = TRUE;
45068b27 5021 }
51470298 5022 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
1408a877 5023 } else {
51470298 5024 c_write_str(ssh, "No supported authentication methods"
5025 " left to try!\r\n");
5026 logevent("No supported authentications offered."
5027 " Disconnecting");
5028 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5029 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5030 ssh2_pkt_addstring(ssh, "No supported authentication"
5031 " methods available");
5032 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5033 ssh2_pkt_send(ssh);
5034 ssh->state = SSH_STATE_CLOSED;
1408a877 5035 crReturnV;
65a22376 5036 }
65a22376 5037 }
51470298 5038 } while (!s->we_are_in);
7cca0d81 5039
5040 /*
5041 * Now we're authenticated for the connection protocol. The
5042 * connection protocol will automatically have started at this
5043 * point; there's no need to send SERVICE_REQUEST.
5044 */
5045
5046 /*
5047 * So now create a channel with a session in it.
5048 */
51470298 5049 ssh->channels = newtree234(ssh_channelcmp);
5050 ssh->mainchan = smalloc(sizeof(struct ssh_channel));
5051 ssh->mainchan->ssh = ssh;
5052 ssh->mainchan->localid = alloc_channel_id(ssh);
5053 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
5054 ssh2_pkt_addstring(ssh, "session");
5055 ssh2_pkt_adduint32(ssh, ssh->mainchan->localid);
5056 ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
5057 ssh2_pkt_adduint32(ssh, ssh->mainchan->v.v2.locwindow);/* our window size */
5058 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
5059 ssh2_pkt_send(ssh);
7cca0d81 5060 crWaitUntilV(ispkt);
51470298 5061 if (ssh->pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
a8327734 5062 bombout((ssh,"Server refused to open a session"));
32874aea 5063 crReturnV;
5064 /* FIXME: error data comes back in FAILURE packet */
7cca0d81 5065 }
51470298 5066 if (ssh2_pkt_getuint32(ssh) != ssh->mainchan->localid) {
a8327734 5067 bombout((ssh,"Server's channel confirmation cited wrong channel"));
32874aea 5068 crReturnV;
7cca0d81 5069 }
51470298 5070 ssh->mainchan->remoteid = ssh2_pkt_getuint32(ssh);
5071 ssh->mainchan->type = CHAN_MAINSESSION;
5072 ssh->mainchan->closes = 0;
5073 ssh->mainchan->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
5074 ssh->mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
5075 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
5076 add234(ssh->channels, ssh->mainchan);
7cca0d81 5077 logevent("Opened channel for session");
5078
5079 /*
783415f8 5080 * Potentially enable X11 forwarding.
5081 */
5082 if (cfg.x11_forward) {
32874aea 5083 char proto[20], data[64];
5084 logevent("Requesting X11 forwarding");
302121de 5085 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
5086 data, sizeof(data));
51470298 5087 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5088 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5089 ssh2_pkt_addstring(ssh, "x11-req");
5090 ssh2_pkt_addbool(ssh, 1); /* want reply */
5091 ssh2_pkt_addbool(ssh, 0); /* many connections */
5092 ssh2_pkt_addstring(ssh, proto);
5093 ssh2_pkt_addstring(ssh, data);
421d6835 5094 ssh2_pkt_adduint32(ssh, x11_get_screen_number(cfg.x11_display));
51470298 5095 ssh2_pkt_send(ssh);
32874aea 5096
5097 do {
5098 crWaitUntilV(ispkt);
51470298 5099 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5100 unsigned i = ssh2_pkt_getuint32(ssh);
32874aea 5101 struct ssh_channel *c;
51470298 5102 c = find234(ssh->channels, &i, ssh_channelfind);
32874aea 5103 if (!c)
5104 continue; /* nonexistent channel */
51470298 5105 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
32874aea 5106 }
51470298 5107 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
32874aea 5108
51470298 5109 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5110 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
a8327734 5111 bombout((ssh,"Unexpected response to X11 forwarding request:"
51470298 5112 " packet type %d", ssh->pktin.type));
32874aea 5113 crReturnV;
5114 }
5115 logevent("X11 forwarding refused");
5116 } else {
5117 logevent("X11 forwarding enabled");
51470298 5118 ssh->X11_fwd_enabled = TRUE;
32874aea 5119 }
783415f8 5120 }
5121
5122 /*
bc240b21 5123 * Enable port forwardings.
5124 */
5125 {
bc240b21 5126 char type;
5127 int n;
a4fc0d74 5128 int sport,dport,sserv,dserv;
6ee9b735 5129 char sports[256], dports[256], saddr[256], host[256];
bc240b21 5130
51470298 5131 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
bc240b21 5132 /* Add port forwardings. */
51470298 5133 ssh->portfwd_strptr = cfg.portfwd;
5134 while (*ssh->portfwd_strptr) {
5135 type = *ssh->portfwd_strptr++;
6ee9b735 5136 saddr[0] = '\0';
bc240b21 5137 n = 0;
6ee9b735 5138 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t') {
5139 if (*ssh->portfwd_strptr == ':') {
5140 /*
5141 * We've seen a colon in the middle of the
5142 * source port number. This means that
5143 * everything we've seen until now is the
5144 * source _address_, so we'll move it into
5145 * saddr and start sports from the beginning
5146 * again.
5147 */
5148 ssh->portfwd_strptr++;
5149 sports[n] = '\0';
5150 strcpy(saddr, sports);
5151 n = 0;
5152 }
5153 if (n < 255) sports[n++] = *ssh->portfwd_strptr++;
5154 }
bc240b21 5155 sports[n] = 0;
51470298 5156 if (*ssh->portfwd_strptr == '\t')
5157 ssh->portfwd_strptr++;
bc240b21 5158 n = 0;
6ee9b735 5159 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
5160 if (n < 255) host[n++] = *ssh->portfwd_strptr++;
5161 }
bc240b21 5162 host[n] = 0;
51470298 5163 if (*ssh->portfwd_strptr == ':')
5164 ssh->portfwd_strptr++;
bc240b21 5165 n = 0;
6ee9b735 5166 while (*ssh->portfwd_strptr) {
5167 if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
5168 }
bc240b21 5169 dports[n] = 0;
51470298 5170 ssh->portfwd_strptr++;
bc240b21 5171 dport = atoi(dports);
a4fc0d74 5172 dserv = 0;
5173 if (dport == 0) {
5174 dserv = 1;
68a49acb 5175 dport = net_service_lookup(dports);
5176 if (!dport) {
57356d63 5177 logeventf(ssh, "Service lookup failed for destination"
5178 " port \"%s\"", dports);
a4fc0d74 5179 }
5180 }
bc240b21 5181 sport = atoi(sports);
a4fc0d74 5182 sserv = 0;
5183 if (sport == 0) {
5184 sserv = 1;
68a49acb 5185 sport = net_service_lookup(sports);
5186 if (!sport) {
57356d63 5187 logeventf(ssh, "Service lookup failed for source"
5188 " port \"%s\"", sports);
a4fc0d74 5189 }
5190 }
bc240b21 5191 if (sport && dport) {
5192 if (type == 'L') {
6ee9b735 5193 pfd_addforward(host, dport, *saddr ? saddr : NULL,
5194 sport, ssh);
5195 logeventf(ssh, "Local port %.*s%.*s%.*s%.*s%d%.*s"
5196 " forwarding to %s:%.*s%.*s%d%.*s",
5197 (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
5198 (int)(*saddr?1:0), ":",
57356d63 5199 (int)(sserv ? strlen(sports) : 0), sports,
5200 sserv, "(", sport, sserv, ")",
5201 host,
5202 (int)(dserv ? strlen(dports) : 0), dports,
5203 dserv, "(", dport, dserv, ")");
bc240b21 5204 } else {
5205 struct ssh_rportfwd *pf;
5206 pf = smalloc(sizeof(*pf));
5207 strcpy(pf->dhost, host);
5208 pf->dport = dport;
5209 pf->sport = sport;
51470298 5210 if (add234(ssh->rportfwds, pf) != pf) {
57356d63 5211 logeventf(ssh, "Duplicate remote port forwarding"
5212 " to %s:%d", host, dport);
bc240b21 5213 sfree(pf);
5214 } else {
6ee9b735 5215 logeventf(ssh, "Requesting remote port "
5216 "%.*s%.*s%.*s%.*s%d%.*s"
57356d63 5217 " forward to %s:%.*s%.*s%d%.*s",
6ee9b735 5218 (int)(*saddr?strlen(saddr):0),
5219 *saddr?saddr:NULL,
5220 (int)(*saddr?1:0), ":",
57356d63 5221 (int)(sserv ? strlen(sports) : 0), sports,
5222 sserv, "(", sport, sserv, ")",
5223 host,
5224 (int)(dserv ? strlen(dports) : 0), dports,
5225 dserv, "(", dport, dserv, ")");
51470298 5226 ssh2_pkt_init(ssh, SSH2_MSG_GLOBAL_REQUEST);
5227 ssh2_pkt_addstring(ssh, "tcpip-forward");
5228 ssh2_pkt_addbool(ssh, 1);/* want reply */
6ee9b735 5229 if (*saddr)
5230 ssh2_pkt_addstring(ssh, saddr);
beefa433 5231 if (cfg.rport_acceptall)
51470298 5232 ssh2_pkt_addstring(ssh, "0.0.0.0");
beefa433 5233 else
51470298 5234 ssh2_pkt_addstring(ssh, "127.0.0.1");
5235 ssh2_pkt_adduint32(ssh, sport);
5236 ssh2_pkt_send(ssh);
bc240b21 5237
5238 do {
5239 crWaitUntilV(ispkt);
51470298 5240 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5241 unsigned i = ssh2_pkt_getuint32(ssh);
bc240b21 5242 struct ssh_channel *c;
51470298 5243 c = find234(ssh->channels, &i, ssh_channelfind);
bc240b21 5244 if (!c)
5245 continue;/* nonexistent channel */
51470298 5246 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
bc240b21 5247 }
51470298 5248 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
bc240b21 5249
51470298 5250 if (ssh->pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
5251 if (ssh->pktin.type != SSH2_MSG_REQUEST_FAILURE) {
a8327734 5252 bombout((ssh,"Unexpected response to port "
c9886e66 5253 "forwarding request: packet type %d",
51470298 5254 ssh->pktin.type));
bc240b21 5255 crReturnV;
5256 }
5257 logevent("Server refused this port forwarding");
5258 } else {
5259 logevent("Remote port forwarding enabled");
5260 }
5261 }
5262 }
5263 }
5264 }
5265 }
5266
5267 /*
36c2a3e9 5268 * Potentially enable agent forwarding.
5269 */
5270 if (cfg.agentfwd && agent_exists()) {
32874aea 5271 logevent("Requesting OpenSSH-style agent forwarding");
51470298 5272 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5273 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5274 ssh2_pkt_addstring(ssh, "auth-agent-req@openssh.com");
5275 ssh2_pkt_addbool(ssh, 1); /* want reply */
5276 ssh2_pkt_send(ssh);
32874aea 5277
5278 do {
5279 crWaitUntilV(ispkt);
51470298 5280 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5281 unsigned i = ssh2_pkt_getuint32(ssh);
32874aea 5282 struct ssh_channel *c;
51470298 5283 c = find234(ssh->channels, &i, ssh_channelfind);
32874aea 5284 if (!c)
5285 continue; /* nonexistent channel */
51470298 5286 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
32874aea 5287 }
51470298 5288 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
32874aea 5289
51470298 5290 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5291 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
a8327734 5292 bombout((ssh,"Unexpected response to agent forwarding request:"
51470298 5293 " packet type %d", ssh->pktin.type));
32874aea 5294 crReturnV;
5295 }
5296 logevent("Agent forwarding refused");
5297 } else {
5298 logevent("Agent forwarding enabled");
51470298 5299 ssh->agentfwd_enabled = TRUE;
32874aea 5300 }
36c2a3e9 5301 }
5302
5303 /*
7cca0d81 5304 * Now allocate a pty for the session.
5305 */
67779be7 5306 if (!cfg.nopty) {
51470298 5307 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5308 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
5309 ssh2_pkt_addstring(ssh, "pty-req");
5310 ssh2_pkt_addbool(ssh, 1); /* want reply */
5311 ssh2_pkt_addstring(ssh, cfg.termtype);
5312 ssh2_pkt_adduint32(ssh, ssh->term_width);
5313 ssh2_pkt_adduint32(ssh, ssh->term_height);
5314 ssh2_pkt_adduint32(ssh, 0); /* pixel width */
5315 ssh2_pkt_adduint32(ssh, 0); /* pixel height */
5316 ssh2_pkt_addstring_start(ssh);
5317 ssh2_pkt_addstring_data(ssh, "\0", 1); /* TTY_OP_END, no special options */
5318 ssh2_pkt_send(ssh);
5319 ssh->state = SSH_STATE_INTERMED;
32874aea 5320
5321 do {
5322 crWaitUntilV(ispkt);
51470298 5323 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5324 unsigned i = ssh2_pkt_getuint32(ssh);
32874aea 5325 struct ssh_channel *c;
51470298 5326 c = find234(ssh->channels, &i, ssh_channelfind);
32874aea 5327 if (!c)
5328 continue; /* nonexistent channel */
51470298 5329 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
32874aea 5330 }
51470298 5331 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
32874aea 5332
51470298 5333 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5334 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
a8327734 5335 bombout((ssh,"Unexpected response to pty request:"
51470298 5336 " packet type %d", ssh->pktin.type));
32874aea 5337 crReturnV;
5338 }
51470298 5339 c_write_str(ssh, "Server refused to allocate pty\r\n");
5340 ssh->editing = ssh->echoing = 1;
32874aea 5341 } else {
5342 logevent("Allocated pty");
5343 }
0965bee0 5344 } else {
51470298 5345 ssh->editing = ssh->echoing = 1;
7cca0d81 5346 }
5347
5348 /*
fd5e5847 5349 * Start a shell or a remote command. We may have to attempt
5350 * this twice if the config data has provided a second choice
5351 * of command.
7cca0d81 5352 */
fd5e5847 5353 while (1) {
5354 int subsys;
5355 char *cmd;
5356
51470298 5357 if (ssh->fallback_cmd) {
fd5e5847 5358 subsys = cfg.ssh_subsys2;
5359 cmd = cfg.remote_cmd_ptr2;
5360 } else {
5361 subsys = cfg.ssh_subsys;
5362 cmd = cfg.remote_cmd_ptr;
5363 }
5364
51470298 5365 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5366 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
fd5e5847 5367 if (subsys) {
51470298 5368 ssh2_pkt_addstring(ssh, "subsystem");
5369 ssh2_pkt_addbool(ssh, 1); /* want reply */
5370 ssh2_pkt_addstring(ssh, cmd);
fd5e5847 5371 } else if (*cmd) {
51470298 5372 ssh2_pkt_addstring(ssh, "exec");
5373 ssh2_pkt_addbool(ssh, 1); /* want reply */
5374 ssh2_pkt_addstring(ssh, cmd);
fd5e5847 5375 } else {
51470298 5376 ssh2_pkt_addstring(ssh, "shell");
5377 ssh2_pkt_addbool(ssh, 1); /* want reply */
32874aea 5378 }
51470298 5379 ssh2_pkt_send(ssh);
fd5e5847 5380 do {
5381 crWaitUntilV(ispkt);
51470298 5382 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5383 unsigned i = ssh2_pkt_getuint32(ssh);
fd5e5847 5384 struct ssh_channel *c;
51470298 5385 c = find234(ssh->channels, &i, ssh_channelfind);
fd5e5847 5386 if (!c)
5387 continue; /* nonexistent channel */
51470298 5388 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
fd5e5847 5389 }
51470298 5390 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5391 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5392 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
a8327734 5393 bombout((ssh,"Unexpected response to shell/command request:"
51470298 5394 " packet type %d", ssh->pktin.type));
fd5e5847 5395 crReturnV;
5396 }
5397 /*
5398 * We failed to start the command. If this is the
5399 * fallback command, we really are finished; if it's
5400 * not, and if the fallback command exists, try falling
5401 * back to it before complaining.
5402 */
51470298 5403 if (!ssh->fallback_cmd && cfg.remote_cmd_ptr2 != NULL) {
fd5e5847 5404 logevent("Primary command failed; attempting fallback");
51470298 5405 ssh->fallback_cmd = TRUE;
fd5e5847 5406 continue;
5407 }
a8327734 5408 bombout((ssh,"Server refused to start a shell/command"));
32874aea 5409 crReturnV;
fd5e5847 5410 } else {
5411 logevent("Started a shell/command");
32874aea 5412 }
fd5e5847 5413 break;
7cca0d81 5414 }
5415
51470298 5416 ssh->state = SSH_STATE_SESSION;
5417 if (ssh->size_needed)
5418 ssh_size(ssh, ssh->term_width, ssh->term_height);
5419 if (ssh->eof_needed)
5420 ssh_special(ssh, TS_EOF);
6e48c3fe 5421
7cca0d81 5422 /*
5423 * Transfer data!
5424 */
b9d7bcad 5425 if (ssh->ldisc)
5426 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
51470298 5427 ssh->send_ok = 1;
7cca0d81 5428 while (1) {
e5574168 5429 crReturnV;
51470298 5430 s->try_send = FALSE;
7cca0d81 5431 if (ispkt) {
51470298 5432 if (ssh->pktin.type == SSH2_MSG_CHANNEL_DATA ||
5433 ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
32874aea 5434 char *data;
5435 int length;
51470298 5436 unsigned i = ssh2_pkt_getuint32(ssh);
32874aea 5437 struct ssh_channel *c;
51470298 5438 c = find234(ssh->channels, &i, ssh_channelfind);
32874aea 5439 if (!c)
5440 continue; /* nonexistent channel */
51470298 5441 if (ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5442 ssh2_pkt_getuint32(ssh) != SSH2_EXTENDED_DATA_STDERR)
32874aea 5443 continue; /* extended but not stderr */
51470298 5444 ssh2_pkt_getstring(ssh, &data, &length);
32874aea 5445 if (data) {
5471d09a 5446 int bufsize;
5447 c->v.v2.locwindow -= length;
32874aea 5448 switch (c->type) {
5449 case CHAN_MAINSESSION:
5471d09a 5450 bufsize =
51470298 5451 from_backend(ssh->frontend, ssh->pktin.type ==
5471d09a 5452 SSH2_MSG_CHANNEL_EXTENDED_DATA,
5453 data, length);
32874aea 5454 break;
5455 case CHAN_X11:
5471d09a 5456 bufsize = x11_send(c->u.x11.s, data, length);
32874aea 5457 break;
d74d141c 5458 case CHAN_SOCKDATA:
5471d09a 5459 bufsize = pfd_send(c->u.pfd.s, data, length);
bc240b21 5460 break;
36c2a3e9 5461 case CHAN_AGENT:
32874aea 5462 while (length > 0) {
5463 if (c->u.a.lensofar < 4) {
5464 int l = min(4 - c->u.a.lensofar, length);
5465 memcpy(c->u.a.msglen + c->u.a.lensofar,
5466 data, l);
5467 data += l;
5468 length -= l;
5469 c->u.a.lensofar += l;
5470 }
5471 if (c->u.a.lensofar == 4) {
5472 c->u.a.totallen =
5473 4 + GET_32BIT(c->u.a.msglen);
5474 c->u.a.message = smalloc(c->u.a.totallen);
5475 memcpy(c->u.a.message, c->u.a.msglen, 4);
5476 }
5477 if (c->u.a.lensofar >= 4 && length > 0) {
5478 int l =
5479 min(c->u.a.totallen - c->u.a.lensofar,
5480 length);
5481 memcpy(c->u.a.message + c->u.a.lensofar,
5482 data, l);
5483 data += l;
5484 length -= l;
5485 c->u.a.lensofar += l;
5486 }
5487 if (c->u.a.lensofar == c->u.a.totallen) {
5488 void *reply, *sentreply;
5489 int replylen;
5490 agent_query(c->u.a.message,
5491 c->u.a.totallen, &reply,
5492 &replylen);
5493 if (reply)
5494 sentreply = reply;
5495 else {
5496 /* Fake SSH_AGENT_FAILURE. */
5497 sentreply = "\0\0\0\1\5";
5498 replylen = 5;
5499 }
51470298 5500 ssh2_add_channel_data(c, sentreply, replylen);
5501 s->try_send = TRUE;
32874aea 5502 if (reply)
5503 sfree(reply);
5504 sfree(c->u.a.message);
5505 c->u.a.lensofar = 0;
5506 }
5507 }
5471d09a 5508 bufsize = 0;
32874aea 5509 break;
5510 }
5511 /*
5471d09a 5512 * If we are not buffering too much data,
5513 * enlarge the window again at the remote side.
32874aea 5514 */
5471d09a 5515 if (bufsize < OUR_V2_WINSIZE)
5516 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
32874aea 5517 }
51470298 5518 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_EOF) {
5519 unsigned i = ssh2_pkt_getuint32(ssh);
32874aea 5520 struct ssh_channel *c;
5521
51470298 5522 c = find234(ssh->channels, &i, ssh_channelfind);
32874aea 5523 if (!c)
5524 continue; /* nonexistent channel */
5525
5526 if (c->type == CHAN_X11) {
5527 /*
5528 * Remote EOF on an X11 channel means we should
5529 * wrap up and close the channel ourselves.
5530 */
5531 x11_close(c->u.x11.s);
5532 sshfwd_close(c);
5533 } else if (c->type == CHAN_AGENT) {
36c2a3e9 5534 sshfwd_close(c);
d74d141c 5535 } else if (c->type == CHAN_SOCKDATA) {
bc240b21 5536 pfd_close(c->u.pfd.s);
5537 sshfwd_close(c);
36c2a3e9 5538 }
51470298 5539 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
5540 unsigned i = ssh2_pkt_getuint32(ssh);
32874aea 5541 struct ssh_channel *c;
5542
51470298 5543 c = find234(ssh->channels, &i, ssh_channelfind);
d0d844c1 5544 if (!c || ((int)c->remoteid) == -1) {
a8327734 5545 bombout((ssh,"Received CHANNEL_CLOSE for %s channel %d\n",
d0d844c1 5546 c ? "half-open" : "nonexistent", i));
5547 }
32874aea 5548 /* Do pre-close processing on the channel. */
5549 switch (c->type) {
5550 case CHAN_MAINSESSION:
5551 break; /* nothing to see here, move along */
5552 case CHAN_X11:
92f157bd 5553 if (c->u.x11.s != NULL)
5554 x11_close(c->u.x11.s);
5555 sshfwd_close(c);
32874aea 5556 break;
5557 case CHAN_AGENT:
92f157bd 5558 sshfwd_close(c);
32874aea 5559 break;
d74d141c 5560 case CHAN_SOCKDATA:
92f157bd 5561 if (c->u.pfd.s != NULL)
5562 pfd_close(c->u.pfd.s);
5563 sshfwd_close(c);
bc240b21 5564 break;
32874aea 5565 }
92f157bd 5566 if (c->closes == 0) {
51470298 5567 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
5568 ssh2_pkt_adduint32(ssh, c->remoteid);
5569 ssh2_pkt_send(ssh);
92f157bd 5570 }
51470298 5571 del234(ssh->channels, c);
5471d09a 5572 bufchain_clear(&c->v.v2.outbuffer);
32874aea 5573 sfree(c);
5574
5575 /*
5576 * See if that was the last channel left open.
5577 */
51470298 5578 if (count234(ssh->channels) == 0) {
ca2914d1 5579#if 0
5580 /*
5581 * We used to send SSH_MSG_DISCONNECT here,
5582 * because I'd believed that _every_ conforming
5583 * SSH2 connection had to end with a disconnect
5584 * being sent by at least one side; apparently
5585 * I was wrong and it's perfectly OK to
5586 * unceremoniously slam the connection shut
5587 * when you're done, and indeed OpenSSH feels
5588 * this is more polite than sending a
5589 * DISCONNECT. So now we don't.
5590 */
32874aea 5591 logevent("All channels closed. Disconnecting");
51470298 5592 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5593 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5594 ssh2_pkt_addstring(ssh, "All open channels closed");
5595 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5596 ssh2_pkt_send(ssh);
ca2914d1 5597#endif
51470298 5598 ssh->state = SSH_STATE_CLOSED;
32874aea 5599 crReturnV;
5600 }
5601 continue; /* remote sends close; ignore (FIXME) */
51470298 5602 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5603 unsigned i = ssh2_pkt_getuint32(ssh);
32874aea 5604 struct ssh_channel *c;
51470298 5605 c = find234(ssh->channels, &i, ssh_channelfind);
32874aea 5606 if (!c)
5607 continue; /* nonexistent channel */
51470298 5608 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5609 s->try_send = TRUE;
5610 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5611 unsigned i = ssh2_pkt_getuint32(ssh);
bc240b21 5612 struct ssh_channel *c;
51470298 5613 c = find234(ssh->channels, &i, ssh_channelfind);
bc240b21 5614 if (!c)
5615 continue; /* nonexistent channel */
5616 if (c->type != CHAN_SOCKDATA_DORMANT)
5617 continue; /* dunno why they're confirming this */
51470298 5618 c->remoteid = ssh2_pkt_getuint32(ssh);
bc240b21 5619 c->type = CHAN_SOCKDATA;
51470298 5620 c->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
5621 c->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
4ed34d25 5622 if (c->u.pfd.s)
5623 pfd_confirm(c->u.pfd.s);
5624 if (c->closes) {
5625 /*
5626 * We have a pending close on this channel,
5627 * which we decided on before the server acked
5628 * the channel open. So now we know the
5629 * remoteid, we can close it again.
5630 */
51470298 5631 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
5632 ssh2_pkt_adduint32(ssh, c->remoteid);
5633 ssh2_pkt_send(ssh);
4ed34d25 5634 }
51470298 5635 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
5636 unsigned i = ssh2_pkt_getuint32(ssh);
724cface 5637 struct ssh_channel *c;
51470298 5638 c = find234(ssh->channels, &i, ssh_channelfind);
724cface 5639 if (!c)
5640 continue; /* nonexistent channel */
5641 if (c->type != CHAN_SOCKDATA_DORMANT)
5642 continue; /* dunno why they're failing this */
5643
5644 logevent("Forwarded connection refused by server");
5645
5646 pfd_close(c->u.pfd.s);
5647
51470298 5648 del234(ssh->channels, c);
724cface 5649 sfree(c);
51470298 5650 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
ebb0a590 5651 unsigned localid;
5652 char *type;
5653 int typelen, want_reply;
5654 struct ssh_channel *c;
5655
51470298 5656 localid = ssh2_pkt_getuint32(ssh);
5657 ssh2_pkt_getstring(ssh, &type, &typelen);
5658 want_reply = ssh2_pkt_getbool(ssh);
ebb0a590 5659
5660 /*
5661 * First, check that the channel exists. Otherwise,
5662 * we can instantly disconnect with a rude message.
5663 */
51470298 5664 c = find234(ssh->channels, &localid, ssh_channelfind);
ebb0a590 5665 if (!c) {
5666 char buf[80];
5667 sprintf(buf, "Received channel request for nonexistent"
5668 " channel %d", localid);
5669 logevent(buf);
51470298 5670 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5671 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5672 ssh2_pkt_addstring(ssh, buf);
5673 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5674 ssh2_pkt_send(ssh);
247308b5 5675 connection_fatal("%s", buf);
51470298 5676 ssh->state = SSH_STATE_CLOSED;
ebb0a590 5677 crReturnV;
5678 }
5679
5680 /*
d8d6c7e5 5681 * Having got the channel number, we now look at
5682 * the request type string to see if it's something
5683 * we recognise.
ebb0a590 5684 */
d8d6c7e5 5685 if (typelen == 11 && !memcmp(type, "exit-status", 11) &&
51470298 5686 c == ssh->mainchan) {
d8d6c7e5 5687 /* We recognise "exit-status" on the primary channel. */
5688 char buf[100];
51470298 5689 ssh->exitcode = ssh2_pkt_getuint32(ssh);
d8d6c7e5 5690 sprintf(buf, "Server sent command exit status %d",
51470298 5691 ssh->exitcode);
d8d6c7e5 5692 logevent(buf);
5693 if (want_reply) {
51470298 5694 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_SUCCESS);
5695 ssh2_pkt_adduint32(ssh, c->remoteid);
5696 ssh2_pkt_send(ssh);
d8d6c7e5 5697 }
5698 } else {
5699 /*
5700 * This is a channel request we don't know
5701 * about, so we now either ignore the request
5702 * or respond with CHANNEL_FAILURE, depending
5703 * on want_reply.
5704 */
5705 if (want_reply) {
51470298 5706 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_FAILURE);
5707 ssh2_pkt_adduint32(ssh, c->remoteid);
5708 ssh2_pkt_send(ssh);
d8d6c7e5 5709 }
ebb0a590 5710 }
51470298 5711 } else if (ssh->pktin.type == SSH2_MSG_GLOBAL_REQUEST) {
697d4856 5712 char *type;
5713 int typelen, want_reply;
5714
51470298 5715 ssh2_pkt_getstring(ssh, &type, &typelen);
5716 want_reply = ssh2_pkt_getbool(ssh);
697d4856 5717
5718 /*
5719 * We currently don't support any global requests
5720 * at all, so we either ignore the request or
5721 * respond with REQUEST_FAILURE, depending on
5722 * want_reply.
5723 */
5724 if (want_reply) {
51470298 5725 ssh2_pkt_init(ssh, SSH2_MSG_REQUEST_FAILURE);
5726 ssh2_pkt_send(ssh);
697d4856 5727 }
51470298 5728 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN) {
32874aea 5729 char *type;
5730 int typelen;
5731 char *error = NULL;
5732 struct ssh_channel *c;
bc240b21 5733 unsigned remid, winsize, pktsize;
51470298 5734 ssh2_pkt_getstring(ssh, &type, &typelen);
32874aea 5735 c = smalloc(sizeof(struct ssh_channel));
51470298 5736 c->ssh = ssh;
32874aea 5737
51470298 5738 remid = ssh2_pkt_getuint32(ssh);
5739 winsize = ssh2_pkt_getuint32(ssh);
5740 pktsize = ssh2_pkt_getuint32(ssh);
bc240b21 5741
32874aea 5742 if (typelen == 3 && !memcmp(type, "x11", 3)) {
51470298 5743 if (!ssh->X11_fwd_enabled)
32874aea 5744 error = "X11 forwarding is not enabled";
302121de 5745 else if (x11_init(&c->u.x11.s, cfg.x11_display, c,
5746 ssh->x11auth) != NULL) {
32874aea 5747 error = "Unable to open an X11 connection";
5748 } else {
5749 c->type = CHAN_X11;
5750 }
bc240b21 5751 } else if (typelen == 15 &&
5752 !memcmp(type, "forwarded-tcpip", 15)) {
5753 struct ssh_rportfwd pf, *realpf;
5754 char *dummy;
5755 int dummylen;
51470298 5756 ssh2_pkt_getstring(ssh, &dummy, &dummylen);/* skip address */
5757 pf.sport = ssh2_pkt_getuint32(ssh);
5758 realpf = find234(ssh->rportfwds, &pf, NULL);
bc240b21 5759 if (realpf == NULL) {
5760 error = "Remote port is not recognised";
5761 } else {
5762 char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
5763 realpf->dport, c);
57356d63 5764 logeventf(ssh, "Received remote port open request"
5765 " for %s:%d", realpf->dhost, realpf->dport);
bc240b21 5766 if (e != NULL) {
57356d63 5767 logeventf(ssh, "Port open failed: %s", e);
bc240b21 5768 error = "Port open failed";
5769 } else {
5770 logevent("Forwarded port opened successfully");
5771 c->type = CHAN_SOCKDATA;
5772 }
5773 }
32874aea 5774 } else if (typelen == 22 &&
36c2a3e9 5775 !memcmp(type, "auth-agent@openssh.com", 3)) {
51470298 5776 if (!ssh->agentfwd_enabled)
32874aea 5777 error = "Agent forwarding is not enabled";
36c2a3e9 5778 else {
32874aea 5779 c->type = CHAN_AGENT; /* identify channel type */
36c2a3e9 5780 c->u.a.lensofar = 0;
32874aea 5781 }
5782 } else {
5783 error = "Unsupported channel type requested";
5784 }
5785
bc240b21 5786 c->remoteid = remid;
32874aea 5787 if (error) {
51470298 5788 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE);
5789 ssh2_pkt_adduint32(ssh, c->remoteid);
5790 ssh2_pkt_adduint32(ssh, SSH2_OPEN_CONNECT_FAILED);
5791 ssh2_pkt_addstring(ssh, error);
5792 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5793 ssh2_pkt_send(ssh);
32874aea 5794 sfree(c);
5795 } else {
51470298 5796 c->localid = alloc_channel_id(ssh);
32874aea 5797 c->closes = 0;
5471d09a 5798 c->v.v2.locwindow = OUR_V2_WINSIZE;
5799 c->v.v2.remwindow = winsize;
5800 c->v.v2.remmaxpkt = pktsize;
5801 bufchain_init(&c->v.v2.outbuffer);
51470298 5802 add234(ssh->channels, c);
5803 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5804 ssh2_pkt_adduint32(ssh, c->remoteid);
5805 ssh2_pkt_adduint32(ssh, c->localid);
5806 ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);
5807 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
5808 ssh2_pkt_send(ssh);
32874aea 5809 }
7cca0d81 5810 } else {
a8327734 5811 bombout((ssh,"Strange packet received: type %d", ssh->pktin.type));
32874aea 5812 crReturnV;
7cca0d81 5813 }
5814 } else {
32874aea 5815 /*
5816 * We have spare data. Add it to the channel buffer.
5817 */
d8baa528 5818 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
51470298 5819 s->try_send = TRUE;
32874aea 5820 }
51470298 5821 if (s->try_send) {
32874aea 5822 int i;
5823 struct ssh_channel *c;
5824 /*
5825 * Try to send data on all channels if we can.
5826 */
51470298 5827 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
5471d09a 5828 int bufsize = ssh2_try_send(c);
5829 if (bufsize == 0) {
5830 switch (c->type) {
5831 case CHAN_MAINSESSION:
5832 /* stdin need not receive an unthrottle
5833 * notification since it will be polled */
5834 break;
5835 case CHAN_X11:
5836 x11_unthrottle(c->u.x11.s);
5837 break;
5838 case CHAN_AGENT:
5839 /* agent sockets are request/response and need no
5840 * buffer management */
5841 break;
5842 case CHAN_SOCKDATA:
5843 pfd_unthrottle(c->u.pfd.s);
5844 break;
5845 }
5846 }
5847 }
7cca0d81 5848 }
e5574168 5849 }
5850
5851 crFinishV;
5852}
5853
5854/*
7cca0d81 5855 * Handle the top-level SSH2 protocol.
5856 */
51470298 5857static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
7cca0d81 5858{
51470298 5859 if (do_ssh2_transport(ssh, in, inlen, ispkt) == 0)
32874aea 5860 return;
51470298 5861 do_ssh2_authconn(ssh, in, inlen, ispkt);
7cca0d81 5862}
5863
5864/*
8df7a775 5865 * Called to set up the connection.
374330e2 5866 *
5867 * Returns an error message, or NULL on success.
374330e2 5868 */
51470298 5869static char *ssh_init(void *frontend_handle, void **backend_handle,
887035a5 5870 char *host, int port, char **realhost, int nodelay)
32874aea 5871{
fb09bf1c 5872 char *p;
51470298 5873 Ssh ssh;
5874
5875 ssh = smalloc(sizeof(*ssh));
5876 ssh->s = NULL;
5877 ssh->cipher = NULL;
371e569c 5878 ssh->v1_cipher_ctx = NULL;
0183b242 5879 ssh->crcda_ctx = NULL;
51470298 5880 ssh->cscipher = NULL;
371e569c 5881 ssh->cs_cipher_ctx = NULL;
51470298 5882 ssh->sccipher = NULL;
371e569c 5883 ssh->sc_cipher_ctx = NULL;
51470298 5884 ssh->csmac = NULL;
a8327734 5885 ssh->cs_mac_ctx = NULL;
51470298 5886 ssh->scmac = NULL;
e0e1a00d 5887 ssh->sc_mac_ctx = NULL;
51470298 5888 ssh->cscomp = NULL;
5366aed8 5889 ssh->cs_comp_ctx = NULL;
51470298 5890 ssh->sccomp = NULL;
5366aed8 5891 ssh->sc_comp_ctx = NULL;
51470298 5892 ssh->kex = NULL;
5893 ssh->hostkey = NULL;
5894 ssh->exitcode = -1;
5895 ssh->state = SSH_STATE_PREPACKET;
5896 ssh->size_needed = FALSE;
5897 ssh->eof_needed = FALSE;
b9d7bcad 5898 ssh->ldisc = NULL;
a8327734 5899 ssh->logctx = NULL;
51470298 5900 {
5901 static const struct Packet empty = { 0, 0, NULL, NULL, 0 };
5902 ssh->pktin = ssh->pktout = empty;
5903 }
5904 ssh->deferred_send_data = NULL;
5905 ssh->deferred_len = 0;
5906 ssh->deferred_size = 0;
5907 ssh->fallback_cmd = 0;
5908 ssh->pkt_ctx = 0;
302121de 5909 ssh->x11auth = NULL;
be738459 5910 ssh->v1_compressing = FALSE;
51470298 5911 ssh->v2_outgoing_sequence = 0;
5912 ssh->ssh1_rdpkt_crstate = 0;
5913 ssh->ssh2_rdpkt_crstate = 0;
5914 ssh->do_ssh_init_crstate = 0;
5915 ssh->ssh_gotdata_crstate = 0;
5916 ssh->ssh1_protocol_crstate = 0;
5917 ssh->do_ssh1_login_crstate = 0;
5918 ssh->do_ssh2_transport_crstate = 0;
5919 ssh->do_ssh2_authconn_crstate = 0;
5920 ssh->do_ssh_init_state = NULL;
5921 ssh->do_ssh1_login_state = NULL;
5922 ssh->do_ssh2_transport_state = NULL;
5923 ssh->do_ssh2_authconn_state = NULL;
6571dbfd 5924 ssh->mainchan = NULL;
968d2d92 5925 ssh->throttled_all = 0;
5926 ssh->v1_stdout_throttling = 0;
51470298 5927
5928 *backend_handle = ssh;
32874aea 5929
8f203108 5930#ifdef MSCRYPTOAPI
32874aea 5931 if (crypto_startup() == 0)
8f203108 5932 return "Microsoft high encryption pack not installed!";
5933#endif
374330e2 5934
51470298 5935 ssh->frontend = frontend_handle;
5936 ssh->term_width = cfg.width;
5937 ssh->term_height = cfg.height;
887035a5 5938
51470298 5939 ssh->send_ok = 0;
5940 ssh->editing = 0;
5941 ssh->echoing = 0;
5942 ssh->v1_throttle_count = 0;
5943 ssh->overall_bufsize = 0;
5944 ssh->fallback_cmd = 0;
8df7a775 5945
51470298 5946 p = connect_to_host(ssh, host, port, realhost, nodelay);
fb09bf1c 5947 if (p != NULL)
5948 return p;
374330e2 5949
374330e2 5950 return NULL;
5951}
5952
5953/*
374330e2 5954 * Called to send data down the Telnet connection.
5955 */
51470298 5956static int ssh_send(void *handle, char *buf, int len)
32874aea 5957{
51470298 5958 Ssh ssh = (Ssh) handle;
5959
5960 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
5471d09a 5961 return 0;
374330e2 5962
d8baa528 5963 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
5471d09a 5964
51470298 5965 return ssh_sendbuffer(ssh);
5471d09a 5966}
5967
5968/*
5969 * Called to query the current amount of buffered stdin data.
5970 */
51470298 5971static int ssh_sendbuffer(void *handle)
5471d09a 5972{
51470298 5973 Ssh ssh = (Ssh) handle;
5471d09a 5974 int override_value;
5975
51470298 5976 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
5471d09a 5977 return 0;
5978
5979 /*
5980 * If the SSH socket itself has backed up, add the total backup
5981 * size on that to any individual buffer on the stdin channel.
5982 */
5983 override_value = 0;
51470298 5984 if (ssh->throttled_all)
5985 override_value = ssh->overall_bufsize;
5471d09a 5986
51470298 5987 if (ssh->version == 1) {
5471d09a 5988 return override_value;
51470298 5989 } else if (ssh->version == 2) {
5990 if (!ssh->mainchan || ssh->mainchan->closes > 0)
5471d09a 5991 return override_value;
5992 else
51470298 5993 return (override_value +
5994 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
5471d09a 5995 }
5996
5997 return 0;
374330e2 5998}
5999
6000/*
6e48c3fe 6001 * Called to set the size of the window from SSH's POV.
374330e2 6002 */
51470298 6003static void ssh_size(void *handle, int width, int height)
32874aea 6004{
51470298 6005 Ssh ssh = (Ssh) handle;
6006
6007 ssh->term_width = width;
6008 ssh->term_height = height;
f278d6f8 6009
51470298 6010 switch (ssh->state) {
374330e2 6011 case SSH_STATE_BEFORE_SIZE:
3687d221 6012 case SSH_STATE_PREPACKET:
21248260 6013 case SSH_STATE_CLOSED:
374330e2 6014 break; /* do nothing */
6015 case SSH_STATE_INTERMED:
51470298 6016 ssh->size_needed = TRUE; /* buffer for later */
374330e2 6017 break;
6018 case SSH_STATE_SESSION:
32874aea 6019 if (!cfg.nopty) {
51470298 6020 if (ssh->version == 1) {
6021 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
6022 PKT_INT, ssh->term_height,
6023 PKT_INT, ssh->term_width,
32874aea 6024 PKT_INT, 0, PKT_INT, 0, PKT_END);
6025 } else {
51470298 6026 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
6027 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
6028 ssh2_pkt_addstring(ssh, "window-change");
6029 ssh2_pkt_addbool(ssh, 0);
6030 ssh2_pkt_adduint32(ssh, ssh->term_width);
6031 ssh2_pkt_adduint32(ssh, ssh->term_height);
6032 ssh2_pkt_adduint32(ssh, 0);
6033 ssh2_pkt_adduint32(ssh, 0);
6034 ssh2_pkt_send(ssh);
32874aea 6035 }
6036 }
6037 break;
374330e2 6038 }
6039}
6040
6041/*
6abbf9e3 6042 * Send Telnet special codes. TS_EOF is useful for `plink', so you
6043 * can send an EOF and collect resulting output (e.g. `plink
6044 * hostname sort').
374330e2 6045 */
51470298 6046static void ssh_special(void *handle, Telnet_Special code)
32874aea 6047{
51470298 6048 Ssh ssh = (Ssh) handle;
6049
6abbf9e3 6050 if (code == TS_EOF) {
51470298 6051 if (ssh->state != SSH_STATE_SESSION) {
32874aea 6052 /*
6053 * Buffer the EOF in case we are pre-SESSION, so we can
6054 * send it as soon as we reach SESSION.
6055 */
6056 if (code == TS_EOF)
51470298 6057 ssh->eof_needed = TRUE;
32874aea 6058 return;
6059 }
51470298 6060 if (ssh->version == 1) {
6061 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
32874aea 6062 } else {
51470298 6063 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_EOF);
6064 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
6065 ssh2_pkt_send(ssh);
32874aea 6066 }
6067 logevent("Sent EOF message");
ec55b220 6068 } else if (code == TS_PING) {
51470298 6069 if (ssh->state == SSH_STATE_CLOSED
6070 || ssh->state == SSH_STATE_PREPACKET) return;
6071 if (ssh->version == 1) {
6072 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
6073 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
32874aea 6074 } else {
51470298 6075 ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
6076 ssh2_pkt_addstring_start(ssh);
6077 ssh2_pkt_send(ssh);
32874aea 6078 }
6abbf9e3 6079 } else {
32874aea 6080 /* do nothing */
6abbf9e3 6081 }
374330e2 6082}
6083
51470298 6084void *new_sock_channel(void *handle, Socket s)
d74d141c 6085{
51470298 6086 Ssh ssh = (Ssh) handle;
d74d141c 6087 struct ssh_channel *c;
6088 c = smalloc(sizeof(struct ssh_channel));
51470298 6089 c->ssh = ssh;
d74d141c 6090
6091 if (c) {
bc240b21 6092 c->remoteid = -1; /* to be set when open confirmed */
51470298 6093 c->localid = alloc_channel_id(ssh);
d74d141c 6094 c->closes = 0;
bc240b21 6095 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
d74d141c 6096 c->u.pfd.s = s;
013dd8c0 6097 bufchain_init(&c->v.v2.outbuffer);
51470298 6098 add234(ssh->channels, c);
d74d141c 6099 }
6100 return c;
6101}
6102
5471d09a 6103/*
6104 * This is called when stdout/stderr (the entity to which
6105 * from_backend sends data) manages to clear some backlog.
6106 */
51470298 6107void ssh_unthrottle(void *handle, int bufsize)
5471d09a 6108{
51470298 6109 Ssh ssh = (Ssh) handle;
6110 if (ssh->version == 1) {
6111 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
6112 ssh->v1_stdout_throttling = 0;
6113 ssh1_throttle(ssh, -1);
5471d09a 6114 }
6115 } else {
51470298 6116 if (ssh->mainchan && ssh->mainchan->closes == 0)
6117 ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
5471d09a 6118 }
6119}
6120
6b78788a 6121void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
d74d141c 6122{
6123 struct ssh_channel *c = (struct ssh_channel *)channel;
6b78788a 6124 Ssh ssh = c->ssh;
d74d141c 6125
57356d63 6126 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
d74d141c 6127
51470298 6128 if (ssh->version == 1) {
6129 send_packet(ssh, SSH1_MSG_PORT_OPEN,
bc240b21 6130 PKT_INT, c->localid,
6131 PKT_STR, hostname,
6132 PKT_INT, port,
6133 //PKT_STR, <org:orgport>,
6134 PKT_END);
6135 } else {
51470298 6136 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
6137 ssh2_pkt_addstring(ssh, "direct-tcpip");
6138 ssh2_pkt_adduint32(ssh, c->localid);
5471d09a 6139 c->v.v2.locwindow = OUR_V2_WINSIZE;
51470298 6140 ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);/* our window size */
6141 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
6142 ssh2_pkt_addstring(ssh, hostname);
6143 ssh2_pkt_adduint32(ssh, port);
bc240b21 6144 /*
6145 * We make up values for the originator data; partly it's
6146 * too much hassle to keep track, and partly I'm not
6147 * convinced the server should be told details like that
6148 * about my local network configuration.
6149 */
51470298 6150 ssh2_pkt_addstring(ssh, "client-side-connection");
6151 ssh2_pkt_adduint32(ssh, 0);
6152 ssh2_pkt_send(ssh);
bc240b21 6153 }
d74d141c 6154}
6155
6156
51470298 6157static Socket ssh_socket(void *handle)
32874aea 6158{
51470298 6159 Ssh ssh = (Ssh) handle;
6160 return ssh->s;
32874aea 6161}
8ccc75b0 6162
51470298 6163static int ssh_sendok(void *handle)
32874aea 6164{
51470298 6165 Ssh ssh = (Ssh) handle;
6166 return ssh->send_ok;
32874aea 6167}
fb09bf1c 6168
51470298 6169static int ssh_ldisc(void *handle, int option)
32874aea 6170{
51470298 6171 Ssh ssh = (Ssh) handle;
32874aea 6172 if (option == LD_ECHO)
51470298 6173 return ssh->echoing;
32874aea 6174 if (option == LD_EDIT)
51470298 6175 return ssh->editing;
0965bee0 6176 return FALSE;
6177}
6178
b9d7bcad 6179static void ssh_provide_ldisc(void *handle, void *ldisc)
6180{
6181 Ssh ssh = (Ssh) handle;
6182 ssh->ldisc = ldisc;
6183}
6184
a8327734 6185static void ssh_provide_logctx(void *handle, void *logctx)
6186{
6187 Ssh ssh = (Ssh) handle;
6188 ssh->logctx = logctx;
6189}
6190
51470298 6191static int ssh_return_exitcode(void *handle)
6192{
6193 Ssh ssh = (Ssh) handle;
6194 return ssh->exitcode;
6195}
6196
6197/*
6198 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
6199 * that fails. This variable is the means by which scp.c can reach
6200 * into the SSH code and find out which one it got.
6201 */
6202extern int ssh_fallback_cmd(void *handle)
d8d6c7e5 6203{
51470298 6204 Ssh ssh = (Ssh) handle;
6205 return ssh->fallback_cmd;
d8d6c7e5 6206}
6207
374330e2 6208Backend ssh_backend = {
6209 ssh_init,
374330e2 6210 ssh_send,
5471d09a 6211 ssh_sendbuffer,
374330e2 6212 ssh_size,
4017be6d 6213 ssh_special,
8ccc75b0 6214 ssh_socket,
d8d6c7e5 6215 ssh_return_exitcode,
97db3be4 6216 ssh_sendok,
0965bee0 6217 ssh_ldisc,
b9d7bcad 6218 ssh_provide_ldisc,
a8327734 6219 ssh_provide_logctx,
5471d09a 6220 ssh_unthrottle,
97db3be4 6221 22
bc240b21 6222};