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