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