Arrgh; yet again I make my security checking too draconian to
[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
ca20bfcf 1865 {
1866 int cipher_chosen = 0, warn = 0;
1867 char *cipher_string = NULL;
1868 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
1869 int next_cipher = cfg.ssh_cipherlist[i];
1870 if (next_cipher == CIPHER_WARN) {
1871 /* If/when we choose a cipher, warn about it */
1872 warn = 1;
1873 } else if (next_cipher == CIPHER_AES) {
1874 /* XXX Probably don't need to mention this. */
1875 logevent("AES not supported in SSH1, skipping");
1876 } else {
1877 switch (next_cipher) {
1878 case CIPHER_3DES: cipher_type = SSH_CIPHER_3DES;
1879 cipher_string = "3DES"; break;
1880 case CIPHER_BLOWFISH: cipher_type = SSH_CIPHER_BLOWFISH;
1881 cipher_string = "Blowfish"; break;
1882 case CIPHER_DES: cipher_type = SSH_CIPHER_DES;
1883 cipher_string = "single-DES"; break;
1884 }
1885 if (supported_ciphers_mask & (1 << cipher_type))
1886 cipher_chosen = 1;
1887 }
1888 }
1889 if (!cipher_chosen) {
1890 if ((supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
1891 bombout(("Server violates SSH 1 protocol by not "
1892 "supporting 3DES encryption"));
1893 else
1894 /* shouldn't happen */
1895 bombout(("No supported ciphers found"));
a99a05c0 1896 crReturn(0);
1897 }
ca20bfcf 1898
1899 /* Warn about chosen cipher if necessary. */
1900 if (warn)
1901 askcipher(cipher_string, 0);
bea1ef5f 1902 }
ca20bfcf 1903
c5e9c988 1904 switch (cipher_type) {
32874aea 1905 case SSH_CIPHER_3DES:
1906 logevent("Using 3DES encryption");
1907 break;
1908 case SSH_CIPHER_DES:
1909 logevent("Using single-DES encryption");
1910 break;
1911 case SSH_CIPHER_BLOWFISH:
1912 logevent("Using Blowfish encryption");
1913 break;
c5e9c988 1914 }
bea1ef5f 1915
e5574168 1916 send_packet(SSH1_CMSG_SESSION_KEY,
32874aea 1917 PKT_CHAR, cipher_type,
1918 PKT_DATA, cookie, 8,
1919 PKT_CHAR, (len * 8) >> 8, PKT_CHAR, (len * 8) & 0xFF,
1920 PKT_DATA, rsabuf, len,
1921 PKT_INT, ssh1_local_protoflags, PKT_END);
fb09bf1c 1922
c5e9c988 1923 logevent("Trying to enable encryption...");
374330e2 1924
dcbde236 1925 sfree(rsabuf);
374330e2 1926
5e8358ad 1927 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
32874aea 1928 cipher_type == SSH_CIPHER_DES ? &ssh_des : &ssh_3des;
374330e2 1929 cipher->sesskey(session_key);
1930
fb09bf1c 1931 crWaitUntil(ispkt);
374330e2 1932
8d5de777 1933 if (pktin.type != SSH1_SMSG_SUCCESS) {
1934 bombout(("Encryption not successfully enabled"));
32874aea 1935 crReturn(0);
8d5de777 1936 }
374330e2 1937
c5e9c988 1938 logevent("Successfully started encryption");
1939
374330e2 1940 fflush(stdout);
1941 {
374330e2 1942 static int pos = 0;
1943 static char c;
67779be7 1944 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
32874aea 1945 if (ssh_get_line) {
1946 if (!ssh_get_line("login as: ",
1947 username, sizeof(username), FALSE)) {
1948 /*
1949 * get_line failed to get a username.
1950 * Terminate.
1951 */
1952 logevent("No username provided. Abandoning session.");
1953 ssh_state = SSH_STATE_CLOSED;
1954 crReturn(1);
1955 }
1956 } else {
1957 c_write_str("login as: ");
1958 ssh_send_ok = 1;
1959 while (pos >= 0) {
1960 crWaitUntil(!ispkt);
1961 while (inlen--)
1962 switch (c = *in++) {
1963 case 10:
1964 case 13:
1965 username[pos] = 0;
1966 pos = -1;
1967 break;
1968 case 8:
1969 case 127:
1970 if (pos > 0) {
1971 c_write_str("\b \b");
1972 pos--;
1973 }
1974 break;
1975 case 21:
1976 case 27:
1977 while (pos > 0) {
1978 c_write_str("\b \b");
1979 pos--;
1980 }
1981 break;
1982 case 3:
1983 case 4:
1984 random_save_seed();
1985 exit(0);
1986 break;
1987 default:
1988 if (((c >= ' ' && c <= '~') ||
51b2fb65 1989 ((unsigned char) c >= 160))
1990 && pos < sizeof(username)-1) {
32874aea 1991 username[pos++] = c;
1992 c_write(&c, 1);
1993 }
1994 break;
1995 }
1996 }
1997 c_write_str("\r\n");
1998 username[strcspn(username, "\n\r")] = '\0';
1999 }
2000 } else {
374330e2 2001 strncpy(username, cfg.username, 99);
2002 username[99] = '\0';
374330e2 2003 }
fb09bf1c 2004
e5574168 2005 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
c5e9c988 2006 {
32874aea 2007 char userlog[22 + sizeof(username)];
c5e9c988 2008 sprintf(userlog, "Sent username \"%s\"", username);
2009 logevent(userlog);
32874aea 2010 if (flags & FLAG_INTERACTIVE &&
2011 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3c8e959b 2012 strcat(userlog, "\r\n");
32874aea 2013 c_write_str(userlog);
3c8e959b 2014 }
c5e9c988 2015 }
374330e2 2016 }
2017
fb09bf1c 2018 crWaitUntil(ispkt);
374330e2 2019
7cca0d81 2020 tried_publickey = 0;
2021
e5574168 2022 while (pktin.type == SSH1_SMSG_FAILURE) {
374330e2 2023 static char password[100];
a52f067e 2024 static char prompt[200];
374330e2 2025 static int pos;
2026 static char c;
32874aea 2027 static int pwpkt_type;
2028 /*
2029 * Show password prompt, having first obtained it via a TIS
2030 * or CryptoCard exchange if we're doing TIS or CryptoCard
2031 * authentication.
2032 */
2033 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2034 if (agent_exists()) {
2035 /*
2036 * Attempt RSA authentication using Pageant.
2037 */
2038 static unsigned char request[5], *response, *p;
2039 static int responselen;
2040 static int i, nkeys;
2041 static int authed = FALSE;
2042 void *r;
2043
2044 logevent("Pageant is running. Requesting keys.");
2045
2046 /* Request the keys held by the agent. */
2047 PUT_32BIT(request, 1);
2048 request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2049 agent_query(request, 5, &r, &responselen);
2050 response = (unsigned char *) r;
2051 if (response && responselen >= 5 &&
2052 response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2053 p = response + 5;
2054 nkeys = GET_32BIT(p);
2055 p += 4;
2056 {
2057 char buf[64];
2058 sprintf(buf, "Pageant has %d SSH1 keys", nkeys);
2059 logevent(buf);
2060 }
2061 for (i = 0; i < nkeys; i++) {
2062 static struct RSAKey key;
2063 static Bignum challenge;
2064 static char *commentp;
2065 static int commentlen;
2066
2067 {
2068 char buf[64];
2069 sprintf(buf, "Trying Pageant key #%d", i);
2070 logevent(buf);
2071 }
2072 p += 4;
2073 p += ssh1_read_bignum(p, &key.exponent);
2074 p += ssh1_read_bignum(p, &key.modulus);
2075 commentlen = GET_32BIT(p);
2076 p += 4;
2077 commentp = p;
2078 p += commentlen;
2079 send_packet(SSH1_CMSG_AUTH_RSA,
2080 PKT_BIGNUM, key.modulus, PKT_END);
2081 crWaitUntil(ispkt);
2082 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2083 logevent("Key refused");
2084 continue;
2085 }
2086 logevent("Received RSA challenge");
2087 ssh1_read_bignum(pktin.body, &challenge);
2088 {
2089 char *agentreq, *q, *ret;
2d466ffd 2090 void *vret;
32874aea 2091 int len, retlen;
2092 len = 1 + 4; /* message type, bit count */
2093 len += ssh1_bignum_length(key.exponent);
2094 len += ssh1_bignum_length(key.modulus);
2095 len += ssh1_bignum_length(challenge);
2096 len += 16; /* session id */
2097 len += 4; /* response format */
2098 agentreq = smalloc(4 + len);
2099 PUT_32BIT(agentreq, len);
2100 q = agentreq + 4;
2101 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2102 PUT_32BIT(q, bignum_bitcount(key.modulus));
2103 q += 4;
2104 q += ssh1_write_bignum(q, key.exponent);
2105 q += ssh1_write_bignum(q, key.modulus);
2106 q += ssh1_write_bignum(q, challenge);
2107 memcpy(q, session_id, 16);
2108 q += 16;
2109 PUT_32BIT(q, 1); /* response format */
2d466ffd 2110 agent_query(agentreq, len + 4, &vret, &retlen);
2111 ret = vret;
32874aea 2112 sfree(agentreq);
2113 if (ret) {
2114 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2115 logevent("Sending Pageant's response");
2116 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2117 PKT_DATA, ret + 5, 16,
2118 PKT_END);
2119 sfree(ret);
2120 crWaitUntil(ispkt);
2121 if (pktin.type == SSH1_SMSG_SUCCESS) {
2122 logevent
2123 ("Pageant's response accepted");
2124 if (flags & FLAG_VERBOSE) {
2125 c_write_str
2126 ("Authenticated using RSA key \"");
2127 c_write(commentp, commentlen);
2128 c_write_str("\" from agent\r\n");
2129 }
2130 authed = TRUE;
2131 } else
2132 logevent
2133 ("Pageant's response not accepted");
2134 } else {
2135 logevent
2136 ("Pageant failed to answer challenge");
2137 sfree(ret);
2138 }
2139 } else {
2140 logevent("No reply received from Pageant");
2141 }
2142 }
2143 freebn(key.exponent);
2144 freebn(key.modulus);
2145 freebn(challenge);
2146 if (authed)
2147 break;
2148 }
2149 }
2150 if (authed)
2151 break;
2152 }
2153 if (*cfg.keyfile && !tried_publickey)
2154 pwpkt_type = SSH1_CMSG_AUTH_RSA;
2155
2156 if (pktin.type == SSH1_SMSG_FAILURE &&
2157 cfg.try_tis_auth &&
2158 (supported_auths_mask & (1 << SSH1_AUTH_TIS))) {
2159 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
2160 logevent("Requested TIS authentication");
2161 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
2162 crWaitUntil(ispkt);
2163 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
2164 logevent("TIS authentication declined");
2165 if (flags & FLAG_INTERACTIVE)
2166 c_write_str("TIS authentication refused.\r\n");
2167 } else {
2168 int challengelen = ((pktin.body[0] << 24) |
2169 (pktin.body[1] << 16) |
2170 (pktin.body[2] << 8) |
2171 (pktin.body[3]));
2172 logevent("Received TIS challenge");
2173 if (challengelen > sizeof(prompt) - 1)
2174 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2175 memcpy(prompt, pktin.body + 4, challengelen);
2176 prompt[challengelen] = '\0';
2177 }
2178 }
2179 if (pktin.type == SSH1_SMSG_FAILURE &&
2180 cfg.try_tis_auth &&
2181 (supported_auths_mask & (1 << SSH1_AUTH_CCARD))) {
2182 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
2183 logevent("Requested CryptoCard authentication");
2184 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
2185 crWaitUntil(ispkt);
2186 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
2187 logevent("CryptoCard authentication declined");
2188 c_write_str("CryptoCard authentication refused.\r\n");
2189 } else {
2190 int challengelen = ((pktin.body[0] << 24) |
2191 (pktin.body[1] << 16) |
2192 (pktin.body[2] << 8) |
2193 (pktin.body[3]));
2194 logevent("Received CryptoCard challenge");
2195 if (challengelen > sizeof(prompt) - 1)
2196 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2197 memcpy(prompt, pktin.body + 4, challengelen);
2198 strncpy(prompt + challengelen, "\r\nResponse : ",
2199 sizeof(prompt) - challengelen);
2200 prompt[sizeof(prompt) - 1] = '\0';
2201 }
2202 }
2203 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2204 sprintf(prompt, "%.90s@%.90s's password: ",
2205 username, savedhost);
2206 }
2207 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2208 char *comment = NULL;
2209 if (flags & FLAG_VERBOSE)
2210 c_write_str("Trying public key authentication.\r\n");
2211 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
2212 if (flags & FLAG_VERBOSE)
2213 c_write_str("No passphrase required.\r\n");
2214 goto tryauth;
2215 }
2216 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
2217 sfree(comment);
2218 }
a52f067e 2219
fa17a66e 2220 if (ssh_get_line) {
2221 if (!ssh_get_line(prompt, password, sizeof(password), TRUE)) {
32874aea 2222 /*
2223 * get_line failed to get a password (for example
2224 * because one was supplied on the command line
2225 * which has already failed to work). Terminate.
2226 */
2bc6a386 2227 send_packet(SSH1_MSG_DISCONNECT,
2228 PKT_STR, "No more passwords available to try",
2229 PKT_END);
2230 connection_fatal("Unable to authenticate");
32874aea 2231 ssh_state = SSH_STATE_CLOSED;
2232 crReturn(1);
2233 }
fb09bf1c 2234 } else {
32874aea 2235 c_write_str(prompt);
2236 pos = 0;
2237 ssh_send_ok = 1;
2238 while (pos >= 0) {
2239 crWaitUntil(!ispkt);
2240 while (inlen--)
2241 switch (c = *in++) {
2242 case 10:
2243 case 13:
2244 password[pos] = 0;
2245 pos = -1;
2246 break;
2247 case 8:
2248 case 127:
2249 if (pos > 0)
2250 pos--;
2251 break;
2252 case 21:
2253 case 27:
2254 pos = 0;
2255 break;
2256 case 3:
2257 case 4:
2258 random_save_seed();
2259 exit(0);
2260 break;
2261 default:
51b2fb65 2262 if (pos < sizeof(password)-1)
32874aea 2263 password[pos++] = c;
2264 break;
2265 }
2266 }
2267 c_write_str("\r\n");
2268 }
2269
2270 tryauth:
7cca0d81 2271 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
32874aea 2272 /*
2273 * Try public key authentication with the specified
2274 * key file.
2275 */
2276 static struct RSAKey pubkey;
2277 static Bignum challenge, response;
2278 static int i;
2279 static unsigned char buffer[32];
2280
2281 tried_publickey = 1;
2282 i = loadrsakey(cfg.keyfile, &pubkey, password);
2283 if (i == 0) {
2284 c_write_str("Couldn't load public key from ");
2285 c_write_str(cfg.keyfile);
2286 c_write_str(".\r\n");
2287 continue; /* go and try password */
2288 }
2289 if (i == -1) {
2290 c_write_str("Wrong passphrase.\r\n");
2291 tried_publickey = 0;
2292 continue; /* try again */
2293 }
2294
2295 /*
2296 * Send a public key attempt.
2297 */
2298 send_packet(SSH1_CMSG_AUTH_RSA,
2299 PKT_BIGNUM, pubkey.modulus, PKT_END);
2300
2301 crWaitUntil(ispkt);
2302 if (pktin.type == SSH1_SMSG_FAILURE) {
2303 c_write_str("Server refused our public key.\r\n");
2304 continue; /* go and try password */
2305 }
2306 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2307 bombout(("Bizarre response to offer of public key"));
2308 crReturn(0);
2309 }
2310 ssh1_read_bignum(pktin.body, &challenge);
2311 response = rsadecrypt(challenge, &pubkey);
2312 freebn(pubkey.private_exponent); /* burn the evidence */
2313
2314 for (i = 0; i < 32; i++) {
2315 buffer[i] = bignum_byte(response, 31 - i);
2316 }
2317
2318 MD5Init(&md5c);
2319 MD5Update(&md5c, buffer, 32);
2320 MD5Update(&md5c, session_id, 16);
2321 MD5Final(buffer, &md5c);
2322
2323 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2324 PKT_DATA, buffer, 16, PKT_END);
2325
2326 crWaitUntil(ispkt);
2327 if (pktin.type == SSH1_SMSG_FAILURE) {
2328 if (flags & FLAG_VERBOSE)
2329 c_write_str
2330 ("Failed to authenticate with our public key.\r\n");
2331 continue; /* go and try password */
2332 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2333 bombout(
2334 ("Bizarre response to RSA authentication response"));
2335 crReturn(0);
2336 }
2337
2338 break; /* we're through! */
2339 } else {
2340 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2341 /*
2342 * Defence against traffic analysis: we send a
2343 * whole bunch of packets containing strings of
2344 * different lengths. One of these strings is the
2345 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2346 * The others are all random data in
2347 * SSH1_MSG_IGNORE packets. This way a passive
2348 * listener can't tell which is the password, and
2349 * hence can't deduce the password length.
2350 *
2351 * Anybody with a password length greater than 16
2352 * bytes is going to have enough entropy in their
2353 * password that a listener won't find it _that_
2354 * much help to know how long it is. So what we'll
2355 * do is:
2356 *
2357 * - if password length < 16, we send 15 packets
2358 * containing string lengths 1 through 15
2359 *
2360 * - otherwise, we let N be the nearest multiple
2361 * of 8 below the password length, and send 8
2362 * packets containing string lengths N through
2363 * N+7. This won't obscure the order of
2364 * magnitude of the password length, but it will
2365 * introduce a bit of extra uncertainty.
2366 *
2367 * A few servers (the old 1.2.18 through 1.2.22)
2368 * can't deal with SSH1_MSG_IGNORE. For these
2369 * servers, we need an alternative defence. We make
2370 * use of the fact that the password is interpreted
2371 * as a C string: so we can append a NUL, then some
2372 * random data.
2373 */
2374 if (ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) {
2375 char string[64];
2376 char *s;
2377 int len;
2378
2379 len = strlen(password);
2380 if (len < sizeof(string)) {
2381 s = string;
2382 strcpy(string, password);
2383 len++; /* cover the zero byte */
2384 while (len < sizeof(string)) {
2385 string[len++] = (char) random_byte();
2386 }
2387 } else {
2388 s = password;
2389 }
2390 send_packet(pwpkt_type, PKT_INT, len,
2391 PKT_DATA, s, len, PKT_END);
2392 } else {
2393 int bottom, top, pwlen, i;
2394 char *randomstr;
2395
2396 pwlen = strlen(password);
2397 if (pwlen < 16) {
2398 bottom = 0; /* zero length passwords are OK! :-) */
2399 top = 15;
2400 } else {
2401 bottom = pwlen & ~7;
2402 top = bottom + 7;
2403 }
2404
2405 assert(pwlen >= bottom && pwlen <= top);
2406
2407 randomstr = smalloc(top + 1);
2408
2409 for (i = bottom; i <= top; i++) {
2410 if (i == pwlen)
2411 defer_packet(pwpkt_type, PKT_STR, password,
2412 PKT_END);
2413 else {
2414 for (j = 0; j < i; j++) {
2415 do {
2416 randomstr[j] = random_byte();
2417 } while (randomstr[j] == '\0');
2418 }
2419 randomstr[i] = '\0';
2420 defer_packet(SSH1_MSG_IGNORE,
2421 PKT_STR, randomstr, PKT_END);
2422 }
2423 }
2424 ssh_pkt_defersend();
2425 }
2426 } else {
2427 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
2428 }
2429 }
c5e9c988 2430 logevent("Sent password");
374330e2 2431 memset(password, 0, strlen(password));
fb09bf1c 2432 crWaitUntil(ispkt);
e5574168 2433 if (pktin.type == SSH1_SMSG_FAILURE) {
32874aea 2434 if (flags & FLAG_VERBOSE)
2435 c_write_str("Access denied\r\n");
c5e9c988 2436 logevent("Authentication refused");
e5574168 2437 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
fb09bf1c 2438 logevent("Received disconnect request");
32874aea 2439 ssh_state = SSH_STATE_CLOSED;
85ee8208 2440 crReturn(1);
e5574168 2441 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
8d5de777 2442 bombout(("Strange packet received, type %d", pktin.type));
32874aea 2443 crReturn(0);
374330e2 2444 }
2445 }
2446
c5e9c988 2447 logevent("Authentication successful");
2448
fb09bf1c 2449 crFinish(1);
2450}
2451
32874aea 2452void sshfwd_close(struct ssh_channel *c)
2453{
80e48603 2454 if (c && !c->closes) {
32874aea 2455 if (ssh_version == 1) {
2456 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2457 PKT_END);
2458 } else {
2459 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2460 ssh2_pkt_adduint32(c->remoteid);
2461 ssh2_pkt_send();
2462 }
2463 c->closes = 1;
2464 if (c->type == CHAN_X11) {
2465 c->u.x11.s = NULL;
d74d141c 2466 logevent("Forwarded X11 connection terminated");
2467 } else if (c->type == CHAN_SOCKDATA) {
2468 c->u.pfd.s = NULL;
2469 logevent("Forwarded port closed");
32874aea 2470 }
2471 }
2472}
2473
5471d09a 2474int sshfwd_write(struct ssh_channel *c, char *buf, int len)
32874aea 2475{
783415f8 2476 if (ssh_version == 1) {
32874aea 2477 send_packet(SSH1_MSG_CHANNEL_DATA,
2478 PKT_INT, c->remoteid,
2479 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
5471d09a 2480 /*
2481 * In SSH1 we can return 0 here - implying that forwarded
2482 * connections are never individually throttled - because
2483 * the only circumstance that can cause throttling will be
2484 * the whole SSH connection backing up, in which case
2485 * _everything_ will be throttled as a whole.
2486 */
2487 return 0;
783415f8 2488 } else {
32874aea 2489 ssh2_add_channel_data(c, buf, len);
5471d09a 2490 return ssh2_try_send(c);
2491 }
2492}
2493
2494void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
2495{
2496 if (ssh_version == 1) {
2497 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
2498 c->v.v1.throttling = 0;
2499 ssh1_throttle(-1);
2500 }
2501 } else {
2502 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
783415f8 2503 }
9c964e85 2504}
2505
32874aea 2506static void ssh1_protocol(unsigned char *in, int inlen, int ispkt)
2507{
fb09bf1c 2508 crBegin;
2509
2510 random_init();
2511
e5574168 2512 while (!do_ssh1_login(in, inlen, ispkt)) {
fb09bf1c 2513 crReturnV;
85ee8208 2514 }
2515 if (ssh_state == SSH_STATE_CLOSED)
32874aea 2516 crReturnV;
fb09bf1c 2517
979310f1 2518 if (cfg.agentfwd && agent_exists()) {
32874aea 2519 logevent("Requesting agent forwarding");
2520 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
2521 do {
2522 crReturnV;
2523 } while (!ispkt);
2524 if (pktin.type != SSH1_SMSG_SUCCESS
2525 && pktin.type != SSH1_SMSG_FAILURE) {
2526 bombout(("Protocol confusion"));
2527 crReturnV;
2528 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2529 logevent("Agent forwarding refused");
2530 } else {
2531 logevent("Agent forwarding enabled");
db7d555c 2532 ssh_agentfwd_enabled = TRUE;
2533 }
dacbd0e8 2534 }
2535
9c964e85 2536 if (cfg.x11_forward) {
32874aea 2537 char proto[20], data[64];
2538 logevent("Requesting X11 forwarding");
2539 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2540 if (ssh1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
2541 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2542 PKT_STR, proto, PKT_STR, data,
2543 PKT_INT, 0, PKT_END);
2544 } else {
2545 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2546 PKT_STR, proto, PKT_STR, data, PKT_END);
2547 }
2548 do {
2549 crReturnV;
2550 } while (!ispkt);
2551 if (pktin.type != SSH1_SMSG_SUCCESS
2552 && pktin.type != SSH1_SMSG_FAILURE) {
2553 bombout(("Protocol confusion"));
2554 crReturnV;
2555 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2556 logevent("X11 forwarding refused");
2557 } else {
2558 logevent("X11 forwarding enabled");
9c964e85 2559 ssh_X11_fwd_enabled = TRUE;
2560 }
2561 }
2562
d74d141c 2563 {
2564 char type, *e;
2565 int n;
2566 int sport,dport;
2567 char sports[256], dports[256], host[256];
2568 char buf[1024];
2569
bc240b21 2570 ssh_rportfwds = newtree234(ssh_rportcmp_ssh1);
d74d141c 2571 /* Add port forwardings. */
2572 e = cfg.portfwd;
2573 while (*e) {
2574 type = *e++;
2575 n = 0;
2576 while (*e && *e != '\t')
2577 sports[n++] = *e++;
2578 sports[n] = 0;
2579 if (*e == '\t')
2580 e++;
2581 n = 0;
2582 while (*e && *e != ':')
2583 host[n++] = *e++;
2584 host[n] = 0;
2585 if (*e == ':')
2586 e++;
2587 n = 0;
2588 while (*e)
2589 dports[n++] = *e++;
2590 dports[n] = 0;
2591 e++;
2592 dport = atoi(dports);
2593 sport = atoi(sports);
2594 if (sport && dport) {
2595 if (type == 'L') {
2596 pfd_addforward(host, dport, sport);
2597 sprintf(buf, "Local port %d forwarding to %s:%d",
2598 sport, host, dport);
2599 logevent(buf);
2600 } else {
2601 struct ssh_rportfwd *pf;
2602 pf = smalloc(sizeof(*pf));
bc240b21 2603 strcpy(pf->dhost, host);
2604 pf->dport = dport;
d74d141c 2605 if (add234(ssh_rportfwds, pf) != pf) {
2606 sprintf(buf,
95bc8819 2607 "Duplicate remote port forwarding to %s:%d",
d74d141c 2608 host, dport);
2609 logevent(buf);
bc240b21 2610 sfree(pf);
d74d141c 2611 } else {
2612 sprintf(buf, "Requesting remote port %d forward to %s:%d",
2613 sport, host, dport);
2614 logevent(buf);
2615 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST,
2616 PKT_INT, sport,
2617 PKT_STR, host,
2618 PKT_INT, dport,
2619 PKT_END);
2620 }
2621 }
2622 }
2623 }
2624 }
2625
fef97f43 2626 if (!cfg.nopty) {
e5574168 2627 send_packet(SSH1_CMSG_REQUEST_PTY,
32874aea 2628 PKT_STR, cfg.termtype,
2629 PKT_INT, rows, PKT_INT, cols,
2630 PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
2631 ssh_state = SSH_STATE_INTERMED;
2632 do {
2633 crReturnV;
2634 } while (!ispkt);
2635 if (pktin.type != SSH1_SMSG_SUCCESS
2636 && pktin.type != SSH1_SMSG_FAILURE) {
2637 bombout(("Protocol confusion"));
2638 crReturnV;
2639 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2640 c_write_str("Server refused to allocate pty\r\n");
2641 ssh_editing = ssh_echoing = 1;
2642 }
c5e9c988 2643 logevent("Allocated pty");
0965bee0 2644 } else {
32874aea 2645 ssh_editing = ssh_echoing = 1;
374330e2 2646 }
2647
4ba9b64b 2648 if (cfg.compression) {
32874aea 2649 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
2650 do {
2651 crReturnV;
2652 } while (!ispkt);
2653 if (pktin.type != SSH1_SMSG_SUCCESS
2654 && pktin.type != SSH1_SMSG_FAILURE) {
2655 bombout(("Protocol confusion"));
2656 crReturnV;
2657 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2658 c_write_str("Server refused to compress\r\n");
2659 }
4ba9b64b 2660 logevent("Started compression");
2661 ssh1_compressing = TRUE;
2662 zlib_compress_init();
2663 zlib_decompress_init();
2664 }
2665
96621a84 2666 if (*cfg.remote_cmd_ptr)
32874aea 2667 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd_ptr,
2668 PKT_END);
6abbf9e3 2669 else
32874aea 2670 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
c5e9c988 2671 logevent("Started session");
374330e2 2672
2673 ssh_state = SSH_STATE_SESSION;
2674 if (size_needed)
2675 ssh_size();
3687d221 2676 if (eof_needed)
32874aea 2677 ssh_special(TS_EOF);
374330e2 2678
32874aea 2679 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
8ccc75b0 2680 ssh_send_ok = 1;
dacbd0e8 2681 ssh_channels = newtree234(ssh_channelcmp);
374330e2 2682 while (1) {
2683 crReturnV;
2684 if (ispkt) {
e5574168 2685 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
32874aea 2686 pktin.type == SSH1_SMSG_STDERR_DATA) {
fb09bf1c 2687 long len = GET_32BIT(pktin.body);
5471d09a 2688 int bufsize =
2689 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
2690 pktin.body + 4, len);
2691 if (bufsize > SSH1_BUFFER_LIMIT) {
2692 ssh1_stdout_throttling = 1;
2693 ssh1_throttle(+1);
2694 }
e5574168 2695 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
32874aea 2696 ssh_state = SSH_STATE_CLOSED;
c5e9c988 2697 logevent("Received disconnect request");
32874aea 2698 crReturnV;
2699 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
2700 /* Remote side is trying to open a channel to talk to our
2701 * X-Server. Give them back a local channel number. */
2702 struct ssh_channel *c;
9c964e85 2703
2704 logevent("Received X11 connect request");
2705 /* Refuse if X11 forwarding is disabled. */
2706 if (!ssh_X11_fwd_enabled) {
2707 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
32874aea 2708 PKT_INT, GET_32BIT(pktin.body), PKT_END);
9c964e85 2709 logevent("Rejected X11 connect request");
2710 } else {
9c964e85 2711 c = smalloc(sizeof(struct ssh_channel));
2712
32874aea 2713 if (x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL) {
2714 logevent("opening X11 forward connection failed");
2715 sfree(c);
2716 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2717 PKT_INT, GET_32BIT(pktin.body),
2718 PKT_END);
9c964e85 2719 } else {
32874aea 2720 logevent
2721 ("opening X11 forward connection succeeded");
2722 c->remoteid = GET_32BIT(pktin.body);
2723 c->localid = alloc_channel_id();
2724 c->closes = 0;
5471d09a 2725 c->v.v1.throttling = 0;
32874aea 2726 c->type = CHAN_X11; /* identify channel type */
2727 add234(ssh_channels, c);
2728 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2729 PKT_INT, c->remoteid, PKT_INT,
2730 c->localid, PKT_END);
2731 logevent("Opened X11 forward channel");
9c964e85 2732 }
2733 }
32874aea 2734 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
2735 /* Remote side is trying to open a channel to talk to our
2736 * agent. Give them back a local channel number. */
2737 struct ssh_channel *c;
db7d555c 2738
2739 /* Refuse if agent forwarding is disabled. */
2740 if (!ssh_agentfwd_enabled) {
2741 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
32874aea 2742 PKT_INT, GET_32BIT(pktin.body), PKT_END);
db7d555c 2743 } else {
dcbde236 2744 c = smalloc(sizeof(struct ssh_channel));
db7d555c 2745 c->remoteid = GET_32BIT(pktin.body);
d2371c81 2746 c->localid = alloc_channel_id();
db7d555c 2747 c->closes = 0;
5471d09a 2748 c->v.v1.throttling = 0;
32874aea 2749 c->type = CHAN_AGENT; /* identify channel type */
db7d555c 2750 c->u.a.lensofar = 0;
2751 add234(ssh_channels, c);
2752 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2753 PKT_INT, c->remoteid, PKT_INT, c->localid,
2754 PKT_END);
2755 }
d74d141c 2756 } else if (pktin.type == SSH1_MSG_PORT_OPEN) {
2757 /* Remote side is trying to open a channel to talk to a
2758 * forwarded port. Give them back a local channel number. */
2759 struct ssh_channel *c;
2760 struct ssh_rportfwd pf;
2761 int hostsize, port;
2762 char host[256], buf[1024];
2763 char *p, *h, *e;
2764 c = smalloc(sizeof(struct ssh_channel));
2765
2766 hostsize = GET_32BIT(pktin.body+4);
2767 for(h = host, p = pktin.body+8; hostsize != 0; hostsize--) {
2768 if (h+1 < host+sizeof(host))
2769 *h++ = *p;
95bc8819 2770 p++;
d74d141c 2771 }
2772 *h = 0;
2773 port = GET_32BIT(p);
2774
bc240b21 2775 strcpy(pf.dhost, host);
2776 pf.dport = port;
d74d141c 2777
2778 if (find234(ssh_rportfwds, &pf, NULL) == NULL) {
2779 sprintf(buf, "Rejected remote port open request for %s:%d",
2780 host, port);
2781 logevent(buf);
2782 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2783 PKT_INT, GET_32BIT(pktin.body), PKT_END);
2784 } else {
2785 sprintf(buf, "Received remote port open request for %s:%d",
2786 host, port);
2787 logevent(buf);
2788 e = pfd_newconnect(&c->u.pfd.s, host, port, c);
2789 if (e != NULL) {
2790 char buf[256];
2791 sprintf(buf, "Port open failed: %s", e);
2792 logevent(buf);
2793 sfree(c);
2794 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2795 PKT_INT, GET_32BIT(pktin.body),
2796 PKT_END);
2797 } else {
2798 c->remoteid = GET_32BIT(pktin.body);
2799 c->localid = alloc_channel_id();
2800 c->closes = 0;
5471d09a 2801 c->v.v1.throttling = 0;
d74d141c 2802 c->type = CHAN_SOCKDATA; /* identify channel type */
2803 add234(ssh_channels, c);
2804 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2805 PKT_INT, c->remoteid, PKT_INT,
2806 c->localid, PKT_END);
2807 logevent("Forwarded port opened successfully");
2808 }
2809 }
2810
2811 } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
bc240b21 2812 unsigned int remoteid = GET_32BIT(pktin.body);
2813 unsigned int localid = GET_32BIT(pktin.body+4);
2814 struct ssh_channel *c;
2815
2816 c = find234(ssh_channels, &remoteid, ssh_channelfind);
2817 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
2818 c->remoteid = localid;
2819 c->type = CHAN_SOCKDATA;
2820 pfd_confirm(c->u.pfd.s);
2821 }
d74d141c 2822
db7d555c 2823 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
2824 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
32874aea 2825 /* Remote side closes a channel. */
2826 unsigned i = GET_32BIT(pktin.body);
2827 struct ssh_channel *c;
2828 c = find234(ssh_channels, &i, ssh_channelfind);
2829 if (c) {
2830 int closetype;
2831 closetype =
2832 (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
2833 if (!(c->closes & closetype))
2834 send_packet(pktin.type, PKT_INT, c->remoteid,
2835 PKT_END);
783415f8 2836 if ((c->closes == 0) && (c->type == CHAN_X11)) {
d74d141c 2837 logevent("Forwarded X11 connection terminated");
9c964e85 2838 assert(c->u.x11.s != NULL);
2839 x11_close(c->u.x11.s);
2840 c->u.x11.s = NULL;
2841 }
d74d141c 2842 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
2843 logevent("Forwarded port closed");
2844 assert(c->u.pfd.s != NULL);
2845 pfd_close(c->u.pfd.s);
2846 c->u.pfd.s = NULL;
2847 }
32874aea 2848 c->closes |= closetype;
2849 if (c->closes == 3) {
2850 del234(ssh_channels, c);
2851 sfree(c);
2852 }
2853 }
2854 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
2855 /* Data sent down one of our channels. */
2856 int i = GET_32BIT(pktin.body);
2857 int len = GET_32BIT(pktin.body + 4);
2858 unsigned char *p = pktin.body + 8;
2859 struct ssh_channel *c;
2860 c = find234(ssh_channels, &i, ssh_channelfind);
2861 if (c) {
5471d09a 2862 int bufsize;
32874aea 2863 switch (c->type) {
2864 case CHAN_X11:
5471d09a 2865 bufsize = x11_send(c->u.x11.s, p, len);
9c964e85 2866 break;
d74d141c 2867 case CHAN_SOCKDATA:
5471d09a 2868 bufsize = pfd_send(c->u.pfd.s, p, len);
bc240b21 2869 break;
32874aea 2870 case CHAN_AGENT:
2871 /* Data for an agent message. Buffer it. */
2872 while (len > 0) {
2873 if (c->u.a.lensofar < 4) {
2874 int l = min(4 - c->u.a.lensofar, len);
2875 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
2876 l);
2877 p += l;
2878 len -= l;
2879 c->u.a.lensofar += l;
2880 }
2881 if (c->u.a.lensofar == 4) {
2882 c->u.a.totallen =
2883 4 + GET_32BIT(c->u.a.msglen);
2884 c->u.a.message = smalloc(c->u.a.totallen);
2885 memcpy(c->u.a.message, c->u.a.msglen, 4);
2886 }
2887 if (c->u.a.lensofar >= 4 && len > 0) {
2888 int l =
2889 min(c->u.a.totallen - c->u.a.lensofar,
2890 len);
2891 memcpy(c->u.a.message + c->u.a.lensofar, p,
2892 l);
2893 p += l;
2894 len -= l;
2895 c->u.a.lensofar += l;
2896 }
2897 if (c->u.a.lensofar == c->u.a.totallen) {
2898 void *reply, *sentreply;
2899 int replylen;
2900 agent_query(c->u.a.message,
2901 c->u.a.totallen, &reply,
2902 &replylen);
2903 if (reply)
2904 sentreply = reply;
2905 else {
2906 /* Fake SSH_AGENT_FAILURE. */
2907 sentreply = "\0\0\0\1\5";
2908 replylen = 5;
2909 }
2910 send_packet(SSH1_MSG_CHANNEL_DATA,
2911 PKT_INT, c->remoteid,
2912 PKT_INT, replylen,
2913 PKT_DATA, sentreply, replylen,
2914 PKT_END);
2915 if (reply)
2916 sfree(reply);
2917 sfree(c->u.a.message);
2918 c->u.a.lensofar = 0;
2919 }
2920 }
5471d09a 2921 bufsize = 0; /* agent channels never back up */
32874aea 2922 break;
2923 }
5471d09a 2924 if (bufsize > SSH1_BUFFER_LIMIT) {
2925 c->v.v1.throttling = 1;
2926 ssh1_throttle(+1);
2927 }
32874aea 2928 }
e5574168 2929 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
972a41c8 2930 /* may be from EXEC_SHELL on some servers */
e5574168 2931 } else if (pktin.type == SSH1_SMSG_FAILURE) {
972a41c8 2932 /* may be from EXEC_SHELL on some servers
374330e2 2933 * if no pty is available or in other odd cases. Ignore */
e5574168 2934 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2935 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
374330e2 2936 } else {
8d5de777 2937 bombout(("Strange packet received: type %d", pktin.type));
32874aea 2938 crReturnV;
374330e2 2939 }
2940 } else {
8df7a775 2941 while (inlen > 0) {
2942 int len = min(inlen, 512);
2943 send_packet(SSH1_CMSG_STDIN_DATA,
2944 PKT_INT, len, PKT_DATA, in, len, PKT_END);
2945 in += len;
2946 inlen -= len;
2947 }
374330e2 2948 }
2949 }
2950
2951 crFinishV;
2952}
2953
2954/*
e5574168 2955 * Utility routine for decoding comma-separated strings in KEXINIT.
2956 */
32874aea 2957static int in_commasep_string(char *needle, char *haystack, int haylen)
2958{
e5574168 2959 int needlen = strlen(needle);
2960 while (1) {
32874aea 2961 /*
2962 * Is it at the start of the string?
2963 */
2964 if (haylen >= needlen && /* haystack is long enough */
2965 !memcmp(needle, haystack, needlen) && /* initial match */
2966 (haylen == needlen || haystack[needlen] == ',')
2967 /* either , or EOS follows */
2968 )
2969 return 1;
2970 /*
2971 * If not, search for the next comma and resume after that.
2972 * If no comma found, terminate.
2973 */
2974 while (haylen > 0 && *haystack != ',')
2975 haylen--, haystack++;
2976 if (haylen == 0)
2977 return 0;
2978 haylen--, haystack++; /* skip over comma itself */
e5574168 2979 }
2980}
2981
2982/*
d39f364a 2983 * SSH2 key creation method.
2984 */
32874aea 2985static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr,
2986 char *keyspace)
2987{
d39f364a 2988 SHA_State s;
2989 /* First 20 bytes. */
2990 SHA_Init(&s);
2991 sha_mpint(&s, K);
2992 SHA_Bytes(&s, H, 20);
2993 SHA_Bytes(&s, &chr, 1);
5e0d7cb8 2994 SHA_Bytes(&s, sessid, 20);
d39f364a 2995 SHA_Final(&s, keyspace);
2996 /* Next 20 bytes. */
2997 SHA_Init(&s);
2998 sha_mpint(&s, K);
2999 SHA_Bytes(&s, H, 20);
3000 SHA_Bytes(&s, keyspace, 20);
32874aea 3001 SHA_Final(&s, keyspace + 20);
d39f364a 3002}
3003
3004/*
7cca0d81 3005 * Handle the SSH2 transport layer.
e5574168 3006 */
7cca0d81 3007static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
e5574168 3008{
ca20bfcf 3009 static int i, j, len, nbits, pbits, warn;
e5574168 3010 static char *str;
a92dd380 3011 static Bignum p, g, e, f, K;
3012 static int kex_init_value, kex_reply_value;
7591b9ff 3013 static const struct ssh_mac **maclist;
8b2715b2 3014 static int nmacs;
0a3f1d48 3015 static const struct ssh2_cipher *cscipher_tobe = NULL;
3016 static const struct ssh2_cipher *sccipher_tobe = NULL;
57476f6b 3017 static const struct ssh_mac *csmac_tobe = NULL;
3018 static const struct ssh_mac *scmac_tobe = NULL;
3019 static const struct ssh_compress *cscomp_tobe = NULL;
3020 static const struct ssh_compress *sccomp_tobe = NULL;
d5859615 3021 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
e5574168 3022 static int hostkeylen, siglen;
e055a386 3023 static void *hkey; /* actual host key */
e5574168 3024 static unsigned char exchange_hash[20];
d39f364a 3025 static unsigned char keyspace[40];
ca20bfcf 3026 static int n_preferred_ciphers;
3027 static const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
4ba9b64b 3028 static const struct ssh_compress *preferred_comp;
0db56f73 3029 static int first_kex;
e5574168 3030
3031 crBegin;
7cca0d81 3032 random_init();
0db56f73 3033 first_kex = 1;
e5574168 3034
5e8358ad 3035 /*
ca20bfcf 3036 * Set up the preferred ciphers. (NULL => warn below here)
5e8358ad 3037 */
ca20bfcf 3038 n_preferred_ciphers = 0;
3039 for (i = 0; i < CIPHER_MAX; i++) {
3040 switch (cfg.ssh_cipherlist[i]) {
3041 case CIPHER_BLOWFISH:
3042 preferred_ciphers[n_preferred_ciphers] = &ssh2_blowfish;
3043 n_preferred_ciphers++;
3044 break;
3045 case CIPHER_DES:
3046 /* Not supported in SSH2; silently drop */
3047 break;
3048 case CIPHER_3DES:
3049 preferred_ciphers[n_preferred_ciphers] = &ssh2_3des;
3050 n_preferred_ciphers++;
3051 break;
3052 case CIPHER_AES:
3053 preferred_ciphers[n_preferred_ciphers] = &ssh2_aes;
3054 n_preferred_ciphers++;
3055 break;
3056 case CIPHER_WARN:
3057 /* Flag for later. Don't bother if it's the last in
3058 * the list. */
3059 if (i < CIPHER_MAX - 1) {
3060 preferred_ciphers[n_preferred_ciphers] = NULL;
3061 n_preferred_ciphers++;
3062 }
3063 break;
3064 }
5e8358ad 3065 }
ca20bfcf 3066
3067 /*
3068 * Set up preferred compression.
3069 */
4ba9b64b 3070 if (cfg.compression)
3071 preferred_comp = &ssh_zlib;
3072 else
3073 preferred_comp = &ssh_comp_none;
5e8358ad 3074
7591b9ff 3075 /*
3076 * Be prepared to work around the buggy MAC problem.
3077 */
7d503c31 3078 if (cfg.buggymac || (ssh_remote_bugs & BUG_SSH2_HMAC))
32874aea 3079 maclist = buggymacs, nmacs = lenof(buggymacs);
7591b9ff 3080 else
32874aea 3081 maclist = macs, nmacs = lenof(macs);
7591b9ff 3082
32874aea 3083 begin_key_exchange:
e5574168 3084 /*
3085 * Construct and send our key exchange packet.
3086 */
3087 ssh2_pkt_init(SSH2_MSG_KEXINIT);
3088 for (i = 0; i < 16; i++)
32874aea 3089 ssh2_pkt_addbyte((unsigned char) random_byte());
e5574168 3090 /* List key exchange algorithms. */
3091 ssh2_pkt_addstring_start();
3092 for (i = 0; i < lenof(kex_algs); i++) {
32874aea 3093 ssh2_pkt_addstring_str(kex_algs[i]->name);
3094 if (i < lenof(kex_algs) - 1)
3095 ssh2_pkt_addstring_str(",");
e5574168 3096 }
3097 /* List server host key algorithms. */
3098 ssh2_pkt_addstring_start();
3099 for (i = 0; i < lenof(hostkey_algs); i++) {
32874aea 3100 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
3101 if (i < lenof(hostkey_algs) - 1)
3102 ssh2_pkt_addstring_str(",");
e5574168 3103 }
3104 /* List client->server encryption algorithms. */
3105 ssh2_pkt_addstring_start();
ca20bfcf 3106 for (i = 0; i < n_preferred_ciphers; i++) {
3107 const struct ssh2_ciphers *c = preferred_ciphers[i];
3108 if (!c) continue; /* warning flag */
32874aea 3109 for (j = 0; j < c->nciphers; j++) {
3110 ssh2_pkt_addstring_str(c->list[j]->name);
ca20bfcf 3111 if (i < n_preferred_ciphers || j < c->nciphers - 1)
32874aea 3112 ssh2_pkt_addstring_str(",");
3113 }
e5574168 3114 }
3115 /* List server->client encryption algorithms. */
3116 ssh2_pkt_addstring_start();
ca20bfcf 3117 for (i = 0; i < n_preferred_ciphers; i++) {
3118 const struct ssh2_ciphers *c = preferred_ciphers[i];
3119 if (!c) continue; /* warning flag */
32874aea 3120 for (j = 0; j < c->nciphers; j++) {
3121 ssh2_pkt_addstring_str(c->list[j]->name);
ca20bfcf 3122 if (i < n_preferred_ciphers || j < c->nciphers - 1)
32874aea 3123 ssh2_pkt_addstring_str(",");
3124 }
e5574168 3125 }
3126 /* List client->server MAC algorithms. */
3127 ssh2_pkt_addstring_start();
8b2715b2 3128 for (i = 0; i < nmacs; i++) {
32874aea 3129 ssh2_pkt_addstring_str(maclist[i]->name);
3130 if (i < nmacs - 1)
3131 ssh2_pkt_addstring_str(",");
e5574168 3132 }
3133 /* List server->client MAC algorithms. */
3134 ssh2_pkt_addstring_start();
8b2715b2 3135 for (i = 0; i < nmacs; i++) {
32874aea 3136 ssh2_pkt_addstring_str(maclist[i]->name);
3137 if (i < nmacs - 1)
3138 ssh2_pkt_addstring_str(",");
e5574168 3139 }
3140 /* List client->server compression algorithms. */
3141 ssh2_pkt_addstring_start();
32874aea 3142 for (i = 0; i < lenof(compressions) + 1; i++) {
3143 const struct ssh_compress *c =
3144 i == 0 ? preferred_comp : compressions[i - 1];
3145 ssh2_pkt_addstring_str(c->name);
3146 if (i < lenof(compressions))
3147 ssh2_pkt_addstring_str(",");
e5574168 3148 }
3149 /* List server->client compression algorithms. */
3150 ssh2_pkt_addstring_start();
32874aea 3151 for (i = 0; i < lenof(compressions) + 1; i++) {
3152 const struct ssh_compress *c =
3153 i == 0 ? preferred_comp : compressions[i - 1];
3154 ssh2_pkt_addstring_str(c->name);
3155 if (i < lenof(compressions))
3156 ssh2_pkt_addstring_str(",");
e5574168 3157 }
3158 /* List client->server languages. Empty list. */
3159 ssh2_pkt_addstring_start();
3160 /* List server->client languages. Empty list. */
3161 ssh2_pkt_addstring_start();
3162 /* First KEX packet does _not_ follow, because we're not that brave. */
3163 ssh2_pkt_addbool(FALSE);
3164 /* Reserved. */
3165 ssh2_pkt_adduint32(0);
0db56f73 3166
3167 exhash = exhashbase;
32874aea 3168 sha_string(&exhash, pktout.data + 5, pktout.length - 5);
0db56f73 3169
e5574168 3170 ssh2_pkt_send();
3171
32874aea 3172 if (!ispkt)
3173 crWaitUntil(ispkt);
3174 sha_string(&exhash, pktin.data + 5, pktin.length - 5);
e5574168 3175
3176 /*
3177 * Now examine the other side's KEXINIT to see what we're up
3178 * to.
3179 */
7cca0d81 3180 if (pktin.type != SSH2_MSG_KEXINIT) {
32874aea 3181 bombout(("expected key exchange packet from server"));
3182 crReturn(0);
7cca0d81 3183 }
32874aea 3184 kex = NULL;
3185 hostkey = NULL;
3186 cscipher_tobe = NULL;
3187 sccipher_tobe = NULL;
3188 csmac_tobe = NULL;
3189 scmac_tobe = NULL;
3190 cscomp_tobe = NULL;
3191 sccomp_tobe = NULL;
3192 pktin.savedpos += 16; /* skip garbage cookie */
e5574168 3193 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
3194 for (i = 0; i < lenof(kex_algs); i++) {
32874aea 3195 if (in_commasep_string(kex_algs[i]->name, str, len)) {
3196 kex = kex_algs[i];
3197 break;
3198 }
e5574168 3199 }
3200 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
3201 for (i = 0; i < lenof(hostkey_algs); i++) {
32874aea 3202 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3203 hostkey = hostkey_algs[i];
3204 break;
3205 }
e5574168 3206 }
3207 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
ca20bfcf 3208 warn = 0;
3209 for (i = 0; i < n_preferred_ciphers; i++) {
3210 const struct ssh2_ciphers *c = preferred_ciphers[i];
3211 if (!c) {
3212 warn = 1;
3213 } else {
3214 for (j = 0; j < c->nciphers; j++) {
3215 if (in_commasep_string(c->list[j]->name, str, len)) {
3216 cscipher_tobe = c->list[j];
3217 break;
3218 }
32874aea 3219 }
3220 }
ca20bfcf 3221 if (cscipher_tobe) {
3222 if (warn)
3223 askcipher(cscipher_tobe->name, 1);
32874aea 3224 break;
ca20bfcf 3225 }
e5574168 3226 }
3227 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
ca20bfcf 3228 warn = 0;
3229 for (i = 0; i < n_preferred_ciphers; i++) {
3230 const struct ssh2_ciphers *c = preferred_ciphers[i];
3231 if (!c) {
3232 warn = 1;
3233 } else {
3234 for (j = 0; j < c->nciphers; j++) {
3235 if (in_commasep_string(c->list[j]->name, str, len)) {
3236 sccipher_tobe = c->list[j];
3237 break;
3238 }
32874aea 3239 }
3240 }
ca20bfcf 3241 if (sccipher_tobe) {
3242 if (warn)
3243 askcipher(sccipher_tobe->name, 2);
32874aea 3244 break;
ca20bfcf 3245 }
e5574168 3246 }
3247 ssh2_pkt_getstring(&str, &len); /* client->server mac */
8b2715b2 3248 for (i = 0; i < nmacs; i++) {
32874aea 3249 if (in_commasep_string(maclist[i]->name, str, len)) {
3250 csmac_tobe = maclist[i];
3251 break;
3252 }
e5574168 3253 }
3254 ssh2_pkt_getstring(&str, &len); /* server->client mac */
8b2715b2 3255 for (i = 0; i < nmacs; i++) {
32874aea 3256 if (in_commasep_string(maclist[i]->name, str, len)) {
3257 scmac_tobe = maclist[i];
3258 break;
3259 }
e5574168 3260 }
3261 ssh2_pkt_getstring(&str, &len); /* client->server compression */
32874aea 3262 for (i = 0; i < lenof(compressions) + 1; i++) {
3263 const struct ssh_compress *c =
3264 i == 0 ? preferred_comp : compressions[i - 1];
3265 if (in_commasep_string(c->name, str, len)) {
3266 cscomp_tobe = c;
3267 break;
3268 }
e5574168 3269 }
3270 ssh2_pkt_getstring(&str, &len); /* server->client compression */
32874aea 3271 for (i = 0; i < lenof(compressions) + 1; i++) {
3272 const struct ssh_compress *c =
3273 i == 0 ? preferred_comp : compressions[i - 1];
3274 if (in_commasep_string(c->name, str, len)) {
3275 sccomp_tobe = c;
3276 break;
3277 }
e5574168 3278 }
e5574168 3279
3280 /*
7bd5a860 3281 * Work out the number of bits of key we will need from the key
3282 * exchange. We start with the maximum key length of either
3283 * cipher...
3284 */
3285 {
32874aea 3286 int csbits, scbits;
7bd5a860 3287
3288 csbits = cscipher_tobe->keylen;
3289 scbits = sccipher_tobe->keylen;
3290 nbits = (csbits > scbits ? csbits : scbits);
3291 }
3292 /* The keys only have 160-bit entropy, since they're based on
3293 * a SHA-1 hash. So cap the key size at 160 bits. */
32874aea 3294 if (nbits > 160)
3295 nbits = 160;
7bd5a860 3296
3297 /*
a92dd380 3298 * If we're doing Diffie-Hellman group exchange, start by
3299 * requesting a group.
e5574168 3300 */
a92dd380 3301 if (kex == &ssh_diffiehellman_gex) {
32874aea 3302 logevent("Doing Diffie-Hellman group exchange");
3303 /*
3304 * Work out how big a DH group we will need to allow that
3305 * much data.
7bd5a860 3306 */
32874aea 3307 pbits = 512 << ((nbits - 1) / 64);
3308 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
3309 ssh2_pkt_adduint32(pbits);
3310 ssh2_pkt_send();
3311
3312 crWaitUntil(ispkt);
3313 if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
3314 bombout(("expected key exchange group packet from server"));
3315 crReturn(0);
3316 }
3317 p = ssh2_pkt_getmp();
3318 g = ssh2_pkt_getmp();
3319 dh_setup_group(p, g);
3320 kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
3321 kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
a92dd380 3322 } else {
32874aea 3323 dh_setup_group1();
3324 kex_init_value = SSH2_MSG_KEXDH_INIT;
3325 kex_reply_value = SSH2_MSG_KEXDH_REPLY;
8d5de777 3326 }
e5574168 3327
a92dd380 3328 logevent("Doing Diffie-Hellman key exchange");
e5574168 3329 /*
a92dd380 3330 * Now generate and send e for Diffie-Hellman.
e5574168 3331 */
32874aea 3332 e = dh_create_e(nbits * 2);
a92dd380 3333 ssh2_pkt_init(kex_init_value);
e5574168 3334 ssh2_pkt_addmp(e);
3335 ssh2_pkt_send();
3336
3337 crWaitUntil(ispkt);
a92dd380 3338 if (pktin.type != kex_reply_value) {
32874aea 3339 bombout(("expected key exchange reply packet from server"));
3340 crReturn(0);
7cca0d81 3341 }
e5574168 3342 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
3343 f = ssh2_pkt_getmp();
e5574168 3344 ssh2_pkt_getstring(&sigdata, &siglen);
3345
3346 K = dh_find_K(f);
e5574168 3347
3348 sha_string(&exhash, hostkeydata, hostkeylen);
a92dd380 3349 if (kex == &ssh_diffiehellman_gex) {
32874aea 3350 sha_uint32(&exhash, pbits);
3351 sha_mpint(&exhash, p);
3352 sha_mpint(&exhash, g);
a92dd380 3353 }
e5574168 3354 sha_mpint(&exhash, e);
3355 sha_mpint(&exhash, f);
3356 sha_mpint(&exhash, K);
3357 SHA_Final(&exhash, exchange_hash);
3358
3709bfe9 3359 dh_cleanup();
3360
7cca0d81 3361#if 0
765c4200 3362 debug(("Exchange hash is:\n"));
3363 dmemdump(exchange_hash, 20);
7cca0d81 3364#endif
3365
e055a386 3366 hkey = hostkey->newkey(hostkeydata, hostkeylen);
f7259d10 3367 if (!hkey ||
3368 !hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
3369 bombout(("Server's host key did not match the signature supplied"));
32874aea 3370 crReturn(0);
8d5de777 3371 }
e5574168 3372
3373 /*
7cca0d81 3374 * Expect SSH2_MSG_NEWKEYS from server.
d39f364a 3375 */
7cca0d81 3376 crWaitUntil(ispkt);
8d5de777 3377 if (pktin.type != SSH2_MSG_NEWKEYS) {
32874aea 3378 bombout(("expected new-keys packet from server"));
3379 crReturn(0);
8d5de777 3380 }
d39f364a 3381
3382 /*
7cca0d81 3383 * Authenticate remote host: verify host key. (We've already
3384 * checked the signature of the exchange hash.)
e5574168 3385 */
e055a386 3386 keystr = hostkey->fmtkey(hkey);
3387 fingerprint = hostkey->fingerprint(hkey);
d4857987 3388 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
32874aea 3389 keystr, fingerprint);
3390 if (first_kex) { /* don't bother logging this in rekeys */
5e0d7cb8 3391 logevent("Host key fingerprint is:");
3392 logevent(fingerprint);
3393 }
dcbde236 3394 sfree(fingerprint);
3395 sfree(keystr);
e055a386 3396 hostkey->freekey(hkey);
d39f364a 3397
3398 /*
7cca0d81 3399 * Send SSH2_MSG_NEWKEYS.
d39f364a 3400 */
3401 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
3402 ssh2_pkt_send();
d39f364a 3403
3404 /*
3405 * Create and initialise session keys.
3406 */
3407 cscipher = cscipher_tobe;
3408 sccipher = sccipher_tobe;
3409 csmac = csmac_tobe;
3410 scmac = scmac_tobe;
3411 cscomp = cscomp_tobe;
3412 sccomp = sccomp_tobe;
4ba9b64b 3413 cscomp->compress_init();
3414 sccomp->decompress_init();
d39f364a 3415 /*
5e0d7cb8 3416 * Set IVs after keys. Here we use the exchange hash from the
3417 * _first_ key exchange.
d39f364a 3418 */
5e0d7cb8 3419 if (first_kex)
65a22376 3420 memcpy(ssh2_session_id, exchange_hash, sizeof(exchange_hash));
3421 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'C', keyspace);
5e0d7cb8 3422 cscipher->setcskey(keyspace);
65a22376 3423 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'D', keyspace);
5e0d7cb8 3424 sccipher->setsckey(keyspace);
65a22376 3425 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'A', keyspace);
5e0d7cb8 3426 cscipher->setcsiv(keyspace);
65a22376 3427 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'B', keyspace);
5e0d7cb8 3428 sccipher->setsciv(keyspace);
65a22376 3429 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'E', keyspace);
5e0d7cb8 3430 csmac->setcskey(keyspace);
65a22376 3431 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'F', keyspace);
5e0d7cb8 3432 scmac->setsckey(keyspace);
d39f364a 3433
033b4cef 3434 /*
0db56f73 3435 * If this is the first key exchange phase, we must pass the
3436 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3437 * wants to see it but because it will need time to initialise
3438 * itself before it sees an actual packet. In subsequent key
3439 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3440 * it would only confuse the layer above.
3441 */
3442 if (!first_kex) {
32874aea 3443 crReturn(0);
0db56f73 3444 }
3445 first_kex = 0;
3446
3447 /*
7cca0d81 3448 * Now we're encrypting. Begin returning 1 to the protocol main
3449 * function so that other things can run on top of the
3450 * transport. If we ever see a KEXINIT, we must go back to the
3451 * start.
033b4cef 3452 */
e96adf72 3453 while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
32874aea 3454 crReturn(1);
e96adf72 3455 }
5e0d7cb8 3456 logevent("Server initiated key re-exchange");
7cca0d81 3457 goto begin_key_exchange;
e5574168 3458
3459 crFinish(1);
3460}
3461
7cca0d81 3462/*
783415f8 3463 * Add data to an SSH2 channel output buffer.
3464 */
32874aea 3465static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
3466 int len)
3467{
5471d09a 3468 bufchain_add(&c->v.v2.outbuffer, buf, len);
783415f8 3469}
3470
3471/*
3472 * Attempt to send data on an SSH2 channel.
3473 */
5471d09a 3474static int ssh2_try_send(struct ssh_channel *c)
32874aea 3475{
5471d09a 3476 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
3477 int len;
3478 void *data;
3479 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
3480 if ((unsigned)len > c->v.v2.remwindow)
3481 len = c->v.v2.remwindow;
3482 if ((unsigned)len > c->v.v2.remmaxpkt)
3483 len = c->v.v2.remmaxpkt;
32874aea 3484 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
3485 ssh2_pkt_adduint32(c->remoteid);
3486 ssh2_pkt_addstring_start();
5471d09a 3487 ssh2_pkt_addstring_data(data, len);
32874aea 3488 ssh2_pkt_send();
5471d09a 3489 bufchain_consume(&c->v.v2.outbuffer, len);
3490 c->v.v2.remwindow -= len;
3491 }
3492
3493 /*
3494 * After having sent as much data as we can, return the amount
3495 * still buffered.
3496 */
3497 return bufchain_size(&c->v.v2.outbuffer);
3498}
3499
3500/*
3501 * Potentially enlarge the window on an SSH2 channel.
3502 */
3503static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
3504{
3505 if (newwin > c->v.v2.locwindow) {
3506 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3507 ssh2_pkt_adduint32(c->remoteid);
3508 ssh2_pkt_adduint32(newwin - c->v.v2.locwindow);
3509 ssh2_pkt_send();
3510 c->v.v2.locwindow = newwin;
783415f8 3511 }
3512}
3513
3514/*
7cca0d81 3515 * Handle the SSH2 userauth and connection layers.
3516 */
3517static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
3518{
65a22376 3519 static enum {
32874aea 3520 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
761187b6 3521 AUTH_PASSWORD,
3522 AUTH_KEYBOARD_INTERACTIVE
65a22376 3523 } method;
1408a877 3524 static enum {
32874aea 3525 AUTH_TYPE_NONE,
3526 AUTH_TYPE_PUBLICKEY,
3527 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
3528 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
761187b6 3529 AUTH_TYPE_PASSWORD,
4bdf7c46 3530 AUTH_TYPE_KEYBOARD_INTERACTIVE,
3531 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
1408a877 3532 } type;
761187b6 3533 static int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
3534 static int tried_pubkey_config, tried_agent, tried_keyb_inter;
b3186d64 3535 static int kbd_inter_running;
1408a877 3536 static int we_are_in;
761187b6 3537 static int num_prompts, echo;
65a22376 3538 static char username[100];
3539 static char pwprompt[200];
3540 static char password[100];
7cca0d81 3541
e5574168 3542 crBegin;
3543
7cca0d81 3544 /*
3545 * Request userauth protocol, and await a response to it.
3546 */
3547 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
3548 ssh2_pkt_addstring("ssh-userauth");
3549 ssh2_pkt_send();
3550 crWaitUntilV(ispkt);
8d5de777 3551 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
32874aea 3552 bombout(("Server refused user authentication protocol"));
3553 crReturnV;
8d5de777 3554 }
7cca0d81 3555
3556 /*
1408a877 3557 * We repeat this whole loop, including the username prompt,
3558 * until we manage a successful authentication. If the user
3559 * types the wrong _password_, they are sent back to the
3560 * beginning to try another username. (If they specify a
3561 * username in the config, they are never asked, even if they
3562 * do give a wrong password.)
3563 *
3564 * I think this best serves the needs of
3565 *
3566 * - the people who have no configuration, no keys, and just
3567 * want to try repeated (username,password) pairs until they
3568 * type both correctly
3569 *
3570 * - people who have keys and configuration but occasionally
3571 * need to fall back to passwords
3572 *
3573 * - people with a key held in Pageant, who might not have
3574 * logged in to a particular machine before; so they want to
3575 * type a username, and then _either_ their key will be
3576 * accepted, _or_ they will type a password. If they mistype
3577 * the username they will want to be able to get back and
3578 * retype it!
7cca0d81 3579 */
1408a877 3580 do {
3581 static int pos;
7cca0d81 3582 static char c;
e5574168 3583
1408a877 3584 /*
3585 * Get a username.
3586 */
3587 pos = 0;
67779be7 3588 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
32874aea 3589 if (ssh_get_line) {
3590 if (!ssh_get_line("login as: ",
3591 username, sizeof(username), FALSE)) {
3592 /*
3593 * get_line failed to get a username.
3594 * Terminate.
3595 */
3596 logevent("No username provided. Abandoning session.");
3597 ssh_state = SSH_STATE_CLOSED;
3598 crReturnV;
3599 }
3600 } else {
3601 c_write_str("login as: ");
3602 ssh_send_ok = 1;
3603 while (pos >= 0) {
3604 crWaitUntilV(!ispkt);
3605 while (inlen--)
3606 switch (c = *in++) {
3607 case 10:
3608 case 13:
3609 username[pos] = 0;
3610 pos = -1;
3611 break;
3612 case 8:
3613 case 127:
3614 if (pos > 0) {
3615 c_write_str("\b \b");
3616 pos--;
3617 }
3618 break;
3619 case 21:
3620 case 27:
3621 while (pos > 0) {
3622 c_write_str("\b \b");
3623 pos--;
3624 }
3625 break;
3626 case 3:
3627 case 4:
3628 random_save_seed();
3629 exit(0);
3630 break;
3631 default:
3632 if (((c >= ' ' && c <= '~') ||
51b2fb65 3633 ((unsigned char) c >= 160))
3634 && pos < sizeof(username)-1) {
32874aea 3635 username[pos++] = c;
3636 c_write(&c, 1);
3637 }
3638 break;
3639 }
3640 }
3641 }
1408a877 3642 c_write_str("\r\n");
7cca0d81 3643 username[strcspn(username, "\n\r")] = '\0';
3644 } else {
3645 char stuff[200];
3646 strncpy(username, cfg.username, 99);
3647 username[99] = '\0';
65a22376 3648 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7cca0d81 3649 sprintf(stuff, "Using username \"%s\".\r\n", username);
1408a877 3650 c_write_str(stuff);
7cca0d81 3651 }
3652 }
3653
65a22376 3654 /*
1408a877 3655 * Send an authentication request using method "none": (a)
3656 * just in case it succeeds, and (b) so that we know what
3657 * authentication methods we can usefully try next.
65a22376 3658 */
1408a877 3659 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3660 ssh2_pkt_addstring(username);
32874aea 3661 ssh2_pkt_addstring("ssh-connection"); /* service requested */
1408a877 3662 ssh2_pkt_addstring("none"); /* method */
3663 ssh2_pkt_send();
3664 type = AUTH_TYPE_NONE;
3665 gotit = FALSE;
3666 we_are_in = FALSE;
7cca0d81 3667
1408a877 3668 tried_pubkey_config = FALSE;
1983e559 3669 tried_agent = FALSE;
b3186d64 3670 tried_keyb_inter = FALSE;
3671 kbd_inter_running = FALSE;
65a22376 3672
1408a877 3673 while (1) {
3674 /*
3675 * Wait for the result of the last authentication request.
3676 */
3677 if (!gotit)
3678 crWaitUntilV(ispkt);
3679 while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
32874aea 3680 char *banner;
3681 int size;
3682 /*
3683 * Don't show the banner if we're operating in
3684 * non-verbose non-interactive mode. (It's probably
3685 * a script, which means nobody will read the
3686 * banner _anyway_, and moreover the printing of
3687 * the banner will screw up processing on the
3688 * output of (say) plink.)
3689 */
3690 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
3691 ssh2_pkt_getstring(&banner, &size);
3692 if (banner)
3693 c_write_untrusted(banner, size);
3694 }
1408a877 3695 crWaitUntilV(ispkt);
3696 }
3697 if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
3698 logevent("Access granted");
3699 we_are_in = TRUE;
3700 break;
3701 }
65a22376 3702
b3186d64 3703 if (kbd_inter_running &&
3704 pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
3705 /*
3706 * This is a further prompt in keyboard-interactive
3707 * authentication. Do nothing.
3708 */
6bb26b30 3709 } else if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
b3186d64 3710 bombout(("Strange packet received during authentication: type %d",
1408a877 3711 pktin.type));
38c4a8da 3712 crReturnV;
65a22376 3713 }
3714
1408a877 3715 gotit = FALSE;
65a22376 3716
1408a877 3717 /*
3718 * OK, we're now sitting on a USERAUTH_FAILURE message, so
3719 * we can look at the string in it and know what we can
3720 * helpfully try next.
3721 */
b3186d64 3722 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
1408a877 3723 char *methods;
3724 int methlen;
3725 ssh2_pkt_getstring(&methods, &methlen);
b3186d64 3726 kbd_inter_running = FALSE;
1408a877 3727 if (!ssh2_pkt_getbool()) {
3728 /*
3729 * We have received an unequivocal Access
3730 * Denied. This can translate to a variety of
3731 * messages:
3732 *
3733 * - if we'd just tried "none" authentication,
3734 * it's not worth printing anything at all
3735 *
3736 * - if we'd just tried a public key _offer_,
3737 * the message should be "Server refused our
3738 * key" (or no message at all if the key
3739 * came from Pageant)
3740 *
3741 * - if we'd just tried anything else, the
3742 * message really should be "Access denied".
3743 *
3744 * Additionally, if we'd just tried password
3745 * authentication, we should break out of this
3746 * whole loop so as to go back to the username
3747 * prompt.
3748 */
3749 if (type == AUTH_TYPE_NONE) {
3750 /* do nothing */
3751 } else if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
3752 type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
3753 if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
3754 c_write_str("Server refused our key\r\n");
3755 logevent("Server refused public key");
4bdf7c46 3756 } else if (type == AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
3757 /* server declined keyboard-interactive; ignore */
1408a877 3758 } else {
3759 c_write_str("Access denied\r\n");
3760 logevent("Access denied");
3761 if (type == AUTH_TYPE_PASSWORD) {
3762 we_are_in = FALSE;
3763 break;
3764 }
3765 }
3766 } else {
3767 c_write_str("Further authentication required\r\n");
3768 logevent("Further authentication required");
3769 }
65a22376 3770
32874aea 3771 can_pubkey =
3772 in_commasep_string("publickey", methods, methlen);
3773 can_passwd =
3774 in_commasep_string("password", methods, methlen);
761187b6 3775 can_passwd =
3776 in_commasep_string("password", methods, methlen);
3777 can_keyb_inter =
3778 in_commasep_string("keyboard-interactive", methods, methlen);
1408a877 3779 }
65a22376 3780
1408a877 3781 method = 0;
65a22376 3782
761187b6 3783 if (!method && can_keyb_inter && !tried_keyb_inter) {
3784 method = AUTH_KEYBOARD_INTERACTIVE;
3785 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
3786 tried_keyb_inter = TRUE;
3787
3788 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3789 ssh2_pkt_addstring(username);
3790 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3791 ssh2_pkt_addstring("keyboard-interactive"); /* method */
3792 ssh2_pkt_addstring(""); /* lang */
3793 ssh2_pkt_addstring("");
3794 ssh2_pkt_send();
3795
3796 crWaitUntilV(ispkt);
3797 if (pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
3798 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE)
3799 gotit = TRUE;
3800 logevent("Keyboard-interactive authentication refused");
4bdf7c46 3801 type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
761187b6 3802 continue;
3803 }
3804
b3186d64 3805 kbd_inter_running = TRUE;
3806 }
3807
3808 if (kbd_inter_running) {
3809 method = AUTH_KEYBOARD_INTERACTIVE;
3810 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
3811 tried_keyb_inter = TRUE;
3812
761187b6 3813 /* We've got packet with that "interactive" info
3814 dump banners, and set its prompt as ours */
3815 {
3816 char *name, *inst, *lang, *prompt;
3817 int name_len, inst_len, lang_len, prompt_len;
3818 ssh2_pkt_getstring(&name, &name_len);
3819 ssh2_pkt_getstring(&inst, &inst_len);
3820 ssh2_pkt_getstring(&lang, &lang_len);
3821 if (name_len > 0)
3822 c_write_untrusted(name, name_len);
3823 if (inst_len > 0)
3824 c_write_untrusted(inst, inst_len);
3825 num_prompts = ssh2_pkt_getuint32();
3826
3827 ssh2_pkt_getstring(&prompt, &prompt_len);
3828 strncpy(pwprompt, prompt, sizeof(pwprompt));
3829 need_pw = TRUE;
3830
3831 echo = ssh2_pkt_getbool();
3832 }
3833 }
3834
78afa559 3835 if (!method && can_pubkey && agent_exists() && !tried_agent) {
1983e559 3836 /*
3837 * Attempt public-key authentication using Pageant.
3838 */
3839 static unsigned char request[5], *response, *p;
3840 static int responselen;
3841 static int i, nkeys;
3842 static int authed = FALSE;
3843 void *r;
3844
3845 tried_agent = TRUE;
3846
3847 logevent("Pageant is running. Requesting keys.");
3848
3849 /* Request the keys held by the agent. */
3850 PUT_32BIT(request, 1);
3851 request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
3852 agent_query(request, 5, &r, &responselen);
32874aea 3853 response = (unsigned char *) r;
95797139 3854 if (response && responselen >= 5 &&
32874aea 3855 response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
1983e559 3856 p = response + 5;
32874aea 3857 nkeys = GET_32BIT(p);
3858 p += 4;
3859 {
3860 char buf[64];
3861 sprintf(buf, "Pageant has %d SSH2 keys", nkeys);
3862 logevent(buf);
3863 }
1983e559 3864 for (i = 0; i < nkeys; i++) {
3865 static char *pkblob, *alg, *commentp;
3866 static int pklen, alglen, commentlen;
3867 static int siglen, retlen, len;
3868 static char *q, *agentreq, *ret;
2d466ffd 3869 void *vret;
1983e559 3870
32874aea 3871 {
3872 char buf[64];
3873 sprintf(buf, "Trying Pageant key #%d", i);
3874 logevent(buf);
3875 }
3876 pklen = GET_32BIT(p);
3877 p += 4;
3878 pkblob = p;
3879 p += pklen;
1983e559 3880 alglen = GET_32BIT(pkblob);
3881 alg = pkblob + 4;
32874aea 3882 commentlen = GET_32BIT(p);
3883 p += 4;
3884 commentp = p;
3885 p += commentlen;
1983e559 3886 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3887 ssh2_pkt_addstring(username);
32874aea 3888 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3889 ssh2_pkt_addstring("publickey"); /* method */
3890 ssh2_pkt_addbool(FALSE); /* no signature included */
1983e559 3891 ssh2_pkt_addstring_start();
3892 ssh2_pkt_addstring_data(alg, alglen);
3893 ssh2_pkt_addstring_start();
3894 ssh2_pkt_addstring_data(pkblob, pklen);
3895 ssh2_pkt_send();
3896
3897 crWaitUntilV(ispkt);
3898 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
3899 logevent("Key refused");
3900 continue;
3901 }
3902
32874aea 3903 if (flags & FLAG_VERBOSE) {
3904 c_write_str
3905 ("Authenticating with public key \"");
3906 c_write(commentp, commentlen);
3907 c_write_str("\" from agent\r\n");
3908 }
1983e559 3909
3910 /*
3911 * Server is willing to accept the key.
3912 * Construct a SIGN_REQUEST.
3913 */
3914 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3915 ssh2_pkt_addstring(username);
32874aea 3916 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3917 ssh2_pkt_addstring("publickey"); /* method */
1983e559 3918 ssh2_pkt_addbool(TRUE);
3919 ssh2_pkt_addstring_start();
3920 ssh2_pkt_addstring_data(alg, alglen);
3921 ssh2_pkt_addstring_start();
3922 ssh2_pkt_addstring_data(pkblob, pklen);
3923
3924 siglen = pktout.length - 5 + 4 + 20;
32874aea 3925 len = 1; /* message type */
3926 len += 4 + pklen; /* key blob */
3927 len += 4 + siglen; /* data to sign */
3928 len += 4; /* flags */
1983e559 3929 agentreq = smalloc(4 + len);
3930 PUT_32BIT(agentreq, len);
3931 q = agentreq + 4;
3932 *q++ = SSH2_AGENTC_SIGN_REQUEST;
32874aea 3933 PUT_32BIT(q, pklen);
3934 q += 4;
3935 memcpy(q, pkblob, pklen);
3936 q += pklen;
3937 PUT_32BIT(q, siglen);
3938 q += 4;
1983e559 3939 /* Now the data to be signed... */
32874aea 3940 PUT_32BIT(q, 20);
3941 q += 4;
3942 memcpy(q, ssh2_session_id, 20);
3943 q += 20;
3944 memcpy(q, pktout.data + 5, pktout.length - 5);
3945 q += pktout.length - 5;
1983e559 3946 /* And finally the (zero) flags word. */
3947 PUT_32BIT(q, 0);
2d466ffd 3948 agent_query(agentreq, len + 4, &vret, &retlen);
3949 ret = vret;
1983e559 3950 sfree(agentreq);
3951 if (ret) {
3952 if (ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
3953 logevent("Sending Pageant's response");
3954 ssh2_pkt_addstring_start();
32874aea 3955 ssh2_pkt_addstring_data(ret + 9,
3956 GET_32BIT(ret +
3957 5));
1983e559 3958 ssh2_pkt_send();
3959 authed = TRUE;
3960 break;
3961 } else {
32874aea 3962 logevent
3963 ("Pageant failed to answer challenge");
1983e559 3964 sfree(ret);
3965 }
3966 }
3967 }
3968 if (authed)
3969 continue;
3970 }
3971 }
3972
32874aea 3973 if (!method && can_pubkey && *cfg.keyfile
3974 && !tried_pubkey_config) {
1408a877 3975 unsigned char *pub_blob;
3976 char *algorithm, *comment;
3977 int pub_blob_len;
65a22376 3978
1408a877 3979 tried_pubkey_config = TRUE;
65a22376 3980
65a22376 3981 /*
1408a877 3982 * Try the public key supplied in the configuration.
3983 *
3984 * First, offer the public blob to see if the server is
3985 * willing to accept it.
65a22376 3986 */
1408a877 3987 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
3988 &pub_blob_len);
3989 if (pub_blob) {
3990 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3991 ssh2_pkt_addstring(username);
32874aea 3992 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3993 ssh2_pkt_addstring("publickey"); /* method */
3994 ssh2_pkt_addbool(FALSE); /* no signature included */
1408a877 3995 ssh2_pkt_addstring(algorithm);
3996 ssh2_pkt_addstring_start();
3997 ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
3998 ssh2_pkt_send();
32874aea 3999 logevent("Offered public key"); /* FIXME */
1408a877 4000
4001 crWaitUntilV(ispkt);
4002 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4003 gotit = TRUE;
4004 type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
32874aea 4005 continue; /* key refused; give up on it */
1408a877 4006 }
65a22376 4007
1408a877 4008 logevent("Offer of public key accepted");
65a22376 4009 /*
1408a877 4010 * Actually attempt a serious authentication using
4011 * the key.
65a22376 4012 */
1408a877 4013 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
32874aea 4014 sprintf(pwprompt,
4015 "Passphrase for key \"%.100s\": ",
4016 comment);
1408a877 4017 need_pw = TRUE;
4018 } else {
4019 need_pw = FALSE;
4020 }
4021 c_write_str("Authenticating with public key \"");
4022 c_write_str(comment);
4023 c_write_str("\"\r\n");
4024 method = AUTH_PUBLICKEY_FILE;
65a22376 4025 }
1408a877 4026 }
4027
4028 if (!method && can_passwd) {
4029 method = AUTH_PASSWORD;
32874aea 4030 sprintf(pwprompt, "%.90s@%.90s's password: ", username,
4031 savedhost);
1408a877 4032 need_pw = TRUE;
4033 }
4034
4035 if (need_pw) {
fa17a66e 4036 if (ssh_get_line) {
4037 if (!ssh_get_line(pwprompt, password,
32874aea 4038 sizeof(password), TRUE)) {
1408a877 4039 /*
fa17a66e 4040 * get_line failed to get a password (for
4041 * example because one was supplied on the
4042 * command line which has already failed to
4043 * work). Terminate.
1408a877 4044 */
2bc6a386 4045 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4046 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4047 ssh2_pkt_addstring
4048 ("No more passwords available to try");
4049 ssh2_pkt_addstring("en"); /* language tag */
4050 ssh2_pkt_send();
4051 connection_fatal("Unable to authenticate");
1408a877 4052 ssh_state = SSH_STATE_CLOSED;
4053 crReturnV;
4054 }
4055 } else {
4056 static int pos = 0;
4057 static char c;
4058
761187b6 4059 c_write_untrusted(pwprompt, strlen(pwprompt));
1408a877 4060 ssh_send_ok = 1;
4061
4062 pos = 0;
4063 while (pos >= 0) {
4064 crWaitUntilV(!ispkt);
32874aea 4065 while (inlen--)
4066 switch (c = *in++) {
4067 case 10:
4068 case 13:
4069 password[pos] = 0;
4070 pos = -1;
4071 break;
4072 case 8:
4073 case 127:
4074 if (pos > 0)
4075 pos--;
4076 break;
4077 case 21:
4078 case 27:
4079 pos = 0;
4080 break;
4081 case 3:
4082 case 4:
4083 random_save_seed();
4084 exit(0);
4085 break;
4086 default:
51b2fb65 4087 if (pos < sizeof(password)-1)
32874aea 4088 password[pos++] = c;
4089 break;
4090 }
65a22376 4091 }
1408a877 4092 c_write_str("\r\n");
65a22376 4093 }
65a22376 4094 }
65a22376 4095
1408a877 4096 if (method == AUTH_PUBLICKEY_FILE) {
4097 /*
4098 * We have our passphrase. Now try the actual authentication.
4099 */
4100 struct ssh2_userkey *key;
65a22376 4101
1408a877 4102 key = ssh2_load_userkey(cfg.keyfile, password);
4103 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4104 if (key == SSH2_WRONG_PASSPHRASE) {
4105 c_write_str("Wrong passphrase\r\n");
4106 tried_pubkey_config = FALSE;
4107 } else {
4108 c_write_str("Unable to load private key\r\n");
4109 tried_pubkey_config = TRUE;
4110 }
4111 /* Send a spurious AUTH_NONE to return to the top. */
4112 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4113 ssh2_pkt_addstring(username);
32874aea 4114 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4115 ssh2_pkt_addstring("none"); /* method */
1408a877 4116 ssh2_pkt_send();
4117 type = AUTH_TYPE_NONE;
4118 } else {
4119 unsigned char *blob, *sigdata;
4120 int blob_len, sigdata_len;
65a22376 4121
1408a877 4122 /*
4123 * We have loaded the private key and the server
4124 * has announced that it's willing to accept it.
4125 * Hallelujah. Generate a signature and send it.
4126 */
4127 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4128 ssh2_pkt_addstring(username);
32874aea 4129 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4130 ssh2_pkt_addstring("publickey"); /* method */
1408a877 4131 ssh2_pkt_addbool(TRUE);
4132 ssh2_pkt_addstring(key->alg->name);
4133 blob = key->alg->public_blob(key->data, &blob_len);
4134 ssh2_pkt_addstring_start();
4135 ssh2_pkt_addstring_data(blob, blob_len);
4136 sfree(blob);
4137
4138 /*
4139 * The data to be signed is:
4140 *
4141 * string session-id
4142 *
4143 * followed by everything so far placed in the
4144 * outgoing packet.
4145 */
4146 sigdata_len = pktout.length - 5 + 4 + 20;
4147 sigdata = smalloc(sigdata_len);
4148 PUT_32BIT(sigdata, 20);
32874aea 4149 memcpy(sigdata + 4, ssh2_session_id, 20);
4150 memcpy(sigdata + 24, pktout.data + 5,
4151 pktout.length - 5);
4152 blob =
4153 key->alg->sign(key->data, sigdata, sigdata_len,
4154 &blob_len);
1408a877 4155 ssh2_pkt_addstring_start();
4156 ssh2_pkt_addstring_data(blob, blob_len);
4157 sfree(blob);
4158 sfree(sigdata);
4159
4160 ssh2_pkt_send();
4161 type = AUTH_TYPE_PUBLICKEY;
4162 }
4163 } else if (method == AUTH_PASSWORD) {
65a22376 4164 /*
1408a877 4165 * We send the password packet lumped tightly together with
4166 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4167 * string long enough to make the total length of the two
4168 * packets constant. This should ensure that a passive
4169 * listener doing traffic analyis can't work out the length
4170 * of the password.
4171 *
4172 * For this to work, we need an assumption about the
4173 * maximum length of the password packet. I think 256 is
4174 * pretty conservative. Anyone using a password longer than
4175 * that probably doesn't have much to worry about from
4176 * people who find out how long their password is!
65a22376 4177 */
4178 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4179 ssh2_pkt_addstring(username);
32874aea 4180 ssh2_pkt_addstring("ssh-connection"); /* service requested */
1408a877 4181 ssh2_pkt_addstring("password");
4182 ssh2_pkt_addbool(FALSE);
4183 ssh2_pkt_addstring(password);
4184 ssh2_pkt_defer();
65a22376 4185 /*
1408a877 4186 * We'll include a string that's an exact multiple of the
4187 * cipher block size. If the cipher is NULL for some
4188 * reason, we don't do this trick at all because we gain
4189 * nothing by it.
65a22376 4190 */
32874aea 4191 if (cscipher) {
4192 int stringlen, i;
4193
4194 stringlen = (256 - deferred_len);
4195 stringlen += cscipher->blksize - 1;
4196 stringlen -= (stringlen % cscipher->blksize);
4197 if (cscomp) {
4198 /*
4199 * Temporarily disable actual compression,
4200 * so we can guarantee to get this string
4201 * exactly the length we want it. The
4202 * compression-disabling routine should
4203 * return an integer indicating how many
4204 * bytes we should adjust our string length
4205 * by.
4206 */
4207 stringlen -= cscomp->disable_compression();
4208 }
1408a877 4209 ssh2_pkt_init(SSH2_MSG_IGNORE);
4210 ssh2_pkt_addstring_start();
6e9e9520 4211 for (i = 0; i < stringlen; i++) {
32874aea 4212 char c = (char) random_byte();
4213 ssh2_pkt_addstring_data(&c, 1);
65a22376 4214 }
1408a877 4215 ssh2_pkt_defer();
65a22376 4216 }
39065bed 4217 ssh_pkt_defersend();
0d43337a 4218 logevent("Sent password");
1408a877 4219 type = AUTH_TYPE_PASSWORD;
761187b6 4220 } else if (method == AUTH_KEYBOARD_INTERACTIVE) {
4221 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
4222 ssh2_pkt_adduint32(num_prompts);
4223 ssh2_pkt_addstring(password);
4224 memset(password, 0, sizeof(password));
4225 ssh2_pkt_send();
4226 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
1408a877 4227 } else {
32874aea 4228 c_write_str
4229 ("No supported authentication methods left to try!\r\n");
4230 logevent
4231 ("No supported authentications offered. Disconnecting");
1408a877 4232 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4233 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
32874aea 4234 ssh2_pkt_addstring
4235 ("No supported authentication methods available");
4236 ssh2_pkt_addstring("en"); /* language tag */
1408a877 4237 ssh2_pkt_send();
4238 ssh_state = SSH_STATE_CLOSED;
4239 crReturnV;
65a22376 4240 }
65a22376 4241 }
1408a877 4242 } while (!we_are_in);
7cca0d81 4243
4244 /*
4245 * Now we're authenticated for the connection protocol. The
4246 * connection protocol will automatically have started at this
4247 * point; there's no need to send SERVICE_REQUEST.
4248 */
4249
4250 /*
4251 * So now create a channel with a session in it.
4252 */
d2371c81 4253 ssh_channels = newtree234(ssh_channelcmp);
dcbde236 4254 mainchan = smalloc(sizeof(struct ssh_channel));
d2371c81 4255 mainchan->localid = alloc_channel_id();
7cca0d81 4256 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
4257 ssh2_pkt_addstring("session");
d211621f 4258 ssh2_pkt_adduint32(mainchan->localid);
5471d09a 4259 mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
4260 ssh2_pkt_adduint32(mainchan->v.v2.locwindow); /* our window size */
32874aea 4261 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
7cca0d81 4262 ssh2_pkt_send();
4263 crWaitUntilV(ispkt);
4264 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
32874aea 4265 bombout(("Server refused to open a session"));
4266 crReturnV;
4267 /* FIXME: error data comes back in FAILURE packet */
7cca0d81 4268 }
d211621f 4269 if (ssh2_pkt_getuint32() != mainchan->localid) {
32874aea 4270 bombout(("Server's channel confirmation cited wrong channel"));
4271 crReturnV;
7cca0d81 4272 }
d211621f 4273 mainchan->remoteid = ssh2_pkt_getuint32();
783415f8 4274 mainchan->type = CHAN_MAINSESSION;
4275 mainchan->closes = 0;
5471d09a 4276 mainchan->v.v2.remwindow = ssh2_pkt_getuint32();
4277 mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32();
4278 bufchain_init(&mainchan->v.v2.outbuffer);
783415f8 4279 add234(ssh_channels, mainchan);
7cca0d81 4280 logevent("Opened channel for session");
4281
4282 /*
783415f8 4283 * Potentially enable X11 forwarding.
4284 */
4285 if (cfg.x11_forward) {
32874aea 4286 char proto[20], data[64];
4287 logevent("Requesting X11 forwarding");
4288 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
4289 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4290 ssh2_pkt_adduint32(mainchan->remoteid);
4291 ssh2_pkt_addstring("x11-req");
4292 ssh2_pkt_addbool(1); /* want reply */
4293 ssh2_pkt_addbool(0); /* many connections */
4294 ssh2_pkt_addstring(proto);
4295 ssh2_pkt_addstring(data);
4296 ssh2_pkt_adduint32(0); /* screen number */
4297 ssh2_pkt_send();
4298
4299 do {
4300 crWaitUntilV(ispkt);
4301 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4302 unsigned i = ssh2_pkt_getuint32();
4303 struct ssh_channel *c;
4304 c = find234(ssh_channels, &i, ssh_channelfind);
4305 if (!c)
4306 continue; /* nonexistent channel */
5471d09a 4307 c->v.v2.remwindow += ssh2_pkt_getuint32();
32874aea 4308 }
4309 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4310
4311 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4312 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4313 bombout(("Server got confused by X11 forwarding request"));
4314 crReturnV;
4315 }
4316 logevent("X11 forwarding refused");
4317 } else {
4318 logevent("X11 forwarding enabled");
783415f8 4319 ssh_X11_fwd_enabled = TRUE;
32874aea 4320 }
783415f8 4321 }
4322
4323 /*
bc240b21 4324 * Enable port forwardings.
4325 */
4326 {
4327 static char *e; /* preserve across crReturn */
4328 char type;
4329 int n;
4330 int sport,dport;
4331 char sports[256], dports[256], host[256];
4332 char buf[1024];
4333
4334 ssh_rportfwds = newtree234(ssh_rportcmp_ssh2);
4335 /* Add port forwardings. */
4336 e = cfg.portfwd;
4337 while (*e) {
4338 type = *e++;
4339 n = 0;
4340 while (*e && *e != '\t')
4341 sports[n++] = *e++;
4342 sports[n] = 0;
4343 if (*e == '\t')
4344 e++;
4345 n = 0;
4346 while (*e && *e != ':')
4347 host[n++] = *e++;
4348 host[n] = 0;
4349 if (*e == ':')
4350 e++;
4351 n = 0;
4352 while (*e)
4353 dports[n++] = *e++;
4354 dports[n] = 0;
4355 e++;
4356 dport = atoi(dports);
4357 sport = atoi(sports);
4358 if (sport && dport) {
4359 if (type == 'L') {
4360 pfd_addforward(host, dport, sport);
4361 sprintf(buf, "Local port %d forwarding to %s:%d",
4362 sport, host, dport);
4363 logevent(buf);
4364 } else {
4365 struct ssh_rportfwd *pf;
4366 pf = smalloc(sizeof(*pf));
4367 strcpy(pf->dhost, host);
4368 pf->dport = dport;
4369 pf->sport = sport;
4370 if (add234(ssh_rportfwds, pf) != pf) {
4371 sprintf(buf,
95bc8819 4372 "Duplicate remote port forwarding to %s:%d",
bc240b21 4373 host, dport);
4374 logevent(buf);
4375 sfree(pf);
4376 } else {
4377 sprintf(buf, "Requesting remote port %d (forwarded to %s:%d)",
4378 sport, host, dport);
4379 logevent(buf);
4380 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4381 ssh2_pkt_addstring("tcpip-forward");
4382 ssh2_pkt_addbool(1);/* want reply */
4383 ssh2_pkt_addstring("127.0.0.1");
4384 ssh2_pkt_adduint32(sport);
4385 ssh2_pkt_send();
4386
4387 do {
4388 crWaitUntilV(ispkt);
4389 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4390 unsigned i = ssh2_pkt_getuint32();
4391 struct ssh_channel *c;
4392 c = find234(ssh_channels, &i, ssh_channelfind);
4393 if (!c)
4394 continue;/* nonexistent channel */
5471d09a 4395 c->v.v2.remwindow += ssh2_pkt_getuint32();
bc240b21 4396 }
4397 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4398
4399 if (pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
4400 if (pktin.type != SSH2_MSG_REQUEST_FAILURE) {
4401 bombout(("Server got confused by port forwarding request"));
4402 crReturnV;
4403 }
4404 logevent("Server refused this port forwarding");
4405 } else {
4406 logevent("Remote port forwarding enabled");
4407 }
4408 }
4409 }
4410 }
4411 }
4412 }
4413
4414 /*
36c2a3e9 4415 * Potentially enable agent forwarding.
4416 */
4417 if (cfg.agentfwd && agent_exists()) {
32874aea 4418 logevent("Requesting OpenSSH-style agent forwarding");
4419 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4420 ssh2_pkt_adduint32(mainchan->remoteid);
4421 ssh2_pkt_addstring("auth-agent-req@openssh.com");
4422 ssh2_pkt_addbool(1); /* want reply */
4423 ssh2_pkt_send();
4424
4425 do {
4426 crWaitUntilV(ispkt);
4427 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4428 unsigned i = ssh2_pkt_getuint32();
4429 struct ssh_channel *c;
4430 c = find234(ssh_channels, &i, ssh_channelfind);
4431 if (!c)
4432 continue; /* nonexistent channel */
5471d09a 4433 c->v.v2.remwindow += ssh2_pkt_getuint32();
32874aea 4434 }
4435 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4436
4437 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4438 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4439 bombout(
4440 ("Server got confused by agent forwarding request"));
4441 crReturnV;
4442 }
4443 logevent("Agent forwarding refused");
4444 } else {
4445 logevent("Agent forwarding enabled");
36c2a3e9 4446 ssh_agentfwd_enabled = TRUE;
32874aea 4447 }
36c2a3e9 4448 }
4449
4450 /*
7cca0d81 4451 * Now allocate a pty for the session.
4452 */
67779be7 4453 if (!cfg.nopty) {
32874aea 4454 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4455 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
4456 ssh2_pkt_addstring("pty-req");
4457 ssh2_pkt_addbool(1); /* want reply */
4458 ssh2_pkt_addstring(cfg.termtype);
4459 ssh2_pkt_adduint32(cols);
4460 ssh2_pkt_adduint32(rows);
4461 ssh2_pkt_adduint32(0); /* pixel width */
4462 ssh2_pkt_adduint32(0); /* pixel height */
4463 ssh2_pkt_addstring_start();
4464 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
4465 ssh2_pkt_send();
4466 ssh_state = SSH_STATE_INTERMED;
4467
4468 do {
4469 crWaitUntilV(ispkt);
4470 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4471 unsigned i = ssh2_pkt_getuint32();
4472 struct ssh_channel *c;
4473 c = find234(ssh_channels, &i, ssh_channelfind);
4474 if (!c)
4475 continue; /* nonexistent channel */
5471d09a 4476 c->v.v2.remwindow += ssh2_pkt_getuint32();
32874aea 4477 }
4478 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4479
4480 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4481 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4482 bombout(("Server got confused by pty request"));
4483 crReturnV;
4484 }
4485 c_write_str("Server refused to allocate pty\r\n");
4486 ssh_editing = ssh_echoing = 1;
4487 } else {
4488 logevent("Allocated pty");
4489 }
0965bee0 4490 } else {
32874aea 4491 ssh_editing = ssh_echoing = 1;
7cca0d81 4492 }
4493
4494 /*
67779be7 4495 * Start a shell or a remote command.
7cca0d81 4496 */
4497 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
32874aea 4498 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
4a8fc3c4 4499 if (cfg.ssh_subsys) {
32874aea 4500 ssh2_pkt_addstring("subsystem");
4501 ssh2_pkt_addbool(1); /* want reply */
4502 ssh2_pkt_addstring(cfg.remote_cmd_ptr);
96621a84 4503 } else if (*cfg.remote_cmd_ptr) {
32874aea 4504 ssh2_pkt_addstring("exec");
4505 ssh2_pkt_addbool(1); /* want reply */
4506 ssh2_pkt_addstring(cfg.remote_cmd_ptr);
67779be7 4507 } else {
32874aea 4508 ssh2_pkt_addstring("shell");
4509 ssh2_pkt_addbool(1); /* want reply */
67779be7 4510 }
7cca0d81 4511 ssh2_pkt_send();
d211621f 4512 do {
32874aea 4513 crWaitUntilV(ispkt);
4514 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4515 unsigned i = ssh2_pkt_getuint32();
4516 struct ssh_channel *c;
4517 c = find234(ssh_channels, &i, ssh_channelfind);
4518 if (!c)
4519 continue; /* nonexistent channel */
5471d09a 4520 c->v.v2.remwindow += ssh2_pkt_getuint32();
32874aea 4521 }
7cca0d81 4522 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4523 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
32874aea 4524 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4525 bombout(("Server got confused by shell/command request"));
4526 crReturnV;
4527 }
4528 bombout(("Server refused to start a shell/command"));
4529 crReturnV;
7cca0d81 4530 } else {
32874aea 4531 logevent("Started a shell/command");
7cca0d81 4532 }
4533
6e48c3fe 4534 ssh_state = SSH_STATE_SESSION;
4535 if (size_needed)
4536 ssh_size();
3687d221 4537 if (eof_needed)
32874aea 4538 ssh_special(TS_EOF);
6e48c3fe 4539
7cca0d81 4540 /*
4541 * Transfer data!
4542 */
32874aea 4543 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
8ccc75b0 4544 ssh_send_ok = 1;
7cca0d81 4545 while (1) {
32874aea 4546 static int try_send;
e5574168 4547 crReturnV;
32874aea 4548 try_send = FALSE;
7cca0d81 4549 if (ispkt) {
4550 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
32874aea 4551 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
4552 char *data;
4553 int length;
4554 unsigned i = ssh2_pkt_getuint32();
4555 struct ssh_channel *c;
4556 c = find234(ssh_channels, &i, ssh_channelfind);
4557 if (!c)
4558 continue; /* nonexistent channel */
4559 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
4560 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
4561 continue; /* extended but not stderr */
4562 ssh2_pkt_getstring(&data, &length);
4563 if (data) {
5471d09a 4564 int bufsize;
4565 c->v.v2.locwindow -= length;
32874aea 4566 switch (c->type) {
4567 case CHAN_MAINSESSION:
5471d09a 4568 bufsize =
4569 from_backend(pktin.type ==
4570 SSH2_MSG_CHANNEL_EXTENDED_DATA,
4571 data, length);
32874aea 4572 break;
4573 case CHAN_X11:
5471d09a 4574 bufsize = x11_send(c->u.x11.s, data, length);
32874aea 4575 break;
d74d141c 4576 case CHAN_SOCKDATA:
5471d09a 4577 bufsize = pfd_send(c->u.pfd.s, data, length);
bc240b21 4578 break;
36c2a3e9 4579 case CHAN_AGENT:
32874aea 4580 while (length > 0) {
4581 if (c->u.a.lensofar < 4) {
4582 int l = min(4 - c->u.a.lensofar, length);
4583 memcpy(c->u.a.msglen + c->u.a.lensofar,
4584 data, l);
4585 data += l;
4586 length -= l;
4587 c->u.a.lensofar += l;
4588 }
4589 if (c->u.a.lensofar == 4) {
4590 c->u.a.totallen =
4591 4 + GET_32BIT(c->u.a.msglen);
4592 c->u.a.message = smalloc(c->u.a.totallen);
4593 memcpy(c->u.a.message, c->u.a.msglen, 4);
4594 }
4595 if (c->u.a.lensofar >= 4 && length > 0) {
4596 int l =
4597 min(c->u.a.totallen - c->u.a.lensofar,
4598 length);
4599 memcpy(c->u.a.message + c->u.a.lensofar,
4600 data, l);
4601 data += l;
4602 length -= l;
4603 c->u.a.lensofar += l;
4604 }
4605 if (c->u.a.lensofar == c->u.a.totallen) {
4606 void *reply, *sentreply;
4607 int replylen;
4608 agent_query(c->u.a.message,
4609 c->u.a.totallen, &reply,
4610 &replylen);
4611 if (reply)
4612 sentreply = reply;
4613 else {
4614 /* Fake SSH_AGENT_FAILURE. */
4615 sentreply = "\0\0\0\1\5";
4616 replylen = 5;
4617 }
4618 ssh2_add_channel_data(c, sentreply,
4619 replylen);
36c2a3e9 4620 try_send = TRUE;
32874aea 4621 if (reply)
4622 sfree(reply);
4623 sfree(c->u.a.message);
4624 c->u.a.lensofar = 0;
4625 }
4626 }
5471d09a 4627 bufsize = 0;
32874aea 4628 break;
4629 }
4630 /*
5471d09a 4631 * If we are not buffering too much data,
4632 * enlarge the window again at the remote side.
32874aea 4633 */
5471d09a 4634 if (bufsize < OUR_V2_WINSIZE)
4635 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
32874aea 4636 }
7cca0d81 4637 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
32874aea 4638 ssh_state = SSH_STATE_CLOSED;
d211621f 4639 logevent("Received disconnect message");
32874aea 4640 crReturnV;
7cca0d81 4641 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
32874aea 4642 continue; /* exit status et al; ignore (FIXME?) */
d211621f 4643 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
32874aea 4644 unsigned i = ssh2_pkt_getuint32();
4645 struct ssh_channel *c;
4646
4647 c = find234(ssh_channels, &i, ssh_channelfind);
4648 if (!c)
4649 continue; /* nonexistent channel */
4650
4651 if (c->type == CHAN_X11) {
4652 /*
4653 * Remote EOF on an X11 channel means we should
4654 * wrap up and close the channel ourselves.
4655 */
4656 x11_close(c->u.x11.s);
4657 sshfwd_close(c);
4658 } else if (c->type == CHAN_AGENT) {
36c2a3e9 4659 sshfwd_close(c);
d74d141c 4660 } else if (c->type == CHAN_SOCKDATA) {
bc240b21 4661 pfd_close(c->u.pfd.s);
4662 sshfwd_close(c);
36c2a3e9 4663 }
d211621f 4664 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
32874aea 4665 unsigned i = ssh2_pkt_getuint32();
4666 struct ssh_channel *c;
4667
4668 c = find234(ssh_channels, &i, ssh_channelfind);
4669 if (!c)
4670 continue; /* nonexistent channel */
4671 if (c->closes == 0) {
4672 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4673 ssh2_pkt_adduint32(c->remoteid);
4674 ssh2_pkt_send();
4675 }
4676 /* Do pre-close processing on the channel. */
4677 switch (c->type) {
4678 case CHAN_MAINSESSION:
4679 break; /* nothing to see here, move along */
4680 case CHAN_X11:
4681 break;
4682 case CHAN_AGENT:
4683 break;
d74d141c 4684 case CHAN_SOCKDATA:
bc240b21 4685 break;
32874aea 4686 }
4687 del234(ssh_channels, c);
5471d09a 4688 bufchain_clear(&c->v.v2.outbuffer);
32874aea 4689 sfree(c);
4690
4691 /*
4692 * See if that was the last channel left open.
4693 */
4694 if (count234(ssh_channels) == 0) {
4695 logevent("All channels closed. Disconnecting");
4696 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4697 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4698 ssh2_pkt_addstring("All open channels closed");
4699 ssh2_pkt_addstring("en"); /* language tag */
4700 ssh2_pkt_send();
4701 ssh_state = SSH_STATE_CLOSED;
4702 crReturnV;
4703 }
4704 continue; /* remote sends close; ignore (FIXME) */
7cca0d81 4705 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
32874aea 4706 unsigned i = ssh2_pkt_getuint32();
4707 struct ssh_channel *c;
4708 c = find234(ssh_channels, &i, ssh_channelfind);
4709 if (!c)
4710 continue; /* nonexistent channel */
5471d09a 4711 c->v.v2.remwindow += ssh2_pkt_getuint32();
32874aea 4712 try_send = TRUE;
bc240b21 4713 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
4714 unsigned i = ssh2_pkt_getuint32();
4715 struct ssh_channel *c;
4716 c = find234(ssh_channels, &i, ssh_channelfind);
4717 if (!c)
4718 continue; /* nonexistent channel */
4719 if (c->type != CHAN_SOCKDATA_DORMANT)
4720 continue; /* dunno why they're confirming this */
4721 c->remoteid = ssh2_pkt_getuint32();
4722 c->type = CHAN_SOCKDATA;
4723 c->closes = 0;
5471d09a 4724 c->v.v2.remwindow = ssh2_pkt_getuint32();
4725 c->v.v2.remmaxpkt = ssh2_pkt_getuint32();
4726 bufchain_init(&c->v.v2.outbuffer);
bc240b21 4727 pfd_confirm(c->u.pfd.s);
783415f8 4728 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
32874aea 4729 char *type;
4730 int typelen;
4731 char *error = NULL;
4732 struct ssh_channel *c;
bc240b21 4733 unsigned remid, winsize, pktsize;
32874aea 4734 ssh2_pkt_getstring(&type, &typelen);
4735 c = smalloc(sizeof(struct ssh_channel));
4736
bc240b21 4737 remid = ssh2_pkt_getuint32();
4738 winsize = ssh2_pkt_getuint32();
4739 pktsize = ssh2_pkt_getuint32();
4740
32874aea 4741 if (typelen == 3 && !memcmp(type, "x11", 3)) {
4742 if (!ssh_X11_fwd_enabled)
4743 error = "X11 forwarding is not enabled";
4744 else if (x11_init(&c->u.x11.s, cfg.x11_display, c) !=
4745 NULL) {
4746 error = "Unable to open an X11 connection";
4747 } else {
4748 c->type = CHAN_X11;
4749 }
bc240b21 4750 } else if (typelen == 15 &&
4751 !memcmp(type, "forwarded-tcpip", 15)) {
4752 struct ssh_rportfwd pf, *realpf;
4753 char *dummy;
4754 int dummylen;
4755 ssh2_pkt_getstring(&dummy, &dummylen);/* skip address */
4756 pf.sport = ssh2_pkt_getuint32();
4757 realpf = find234(ssh_rportfwds, &pf, NULL);
4758 if (realpf == NULL) {
4759 error = "Remote port is not recognised";
4760 } else {
4761 char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
4762 realpf->dport, c);
4763 char buf[1024];
4764 sprintf(buf, "Received remote port open request for %s:%d",
4765 realpf->dhost, realpf->dport);
4766 logevent(buf);
4767 if (e != NULL) {
4768 sprintf(buf, "Port open failed: %s", e);
4769 logevent(buf);
4770 error = "Port open failed";
4771 } else {
4772 logevent("Forwarded port opened successfully");
4773 c->type = CHAN_SOCKDATA;
4774 }
4775 }
32874aea 4776 } else if (typelen == 22 &&
36c2a3e9 4777 !memcmp(type, "auth-agent@openssh.com", 3)) {
32874aea 4778 if (!ssh_agentfwd_enabled)
4779 error = "Agent forwarding is not enabled";
36c2a3e9 4780 else {
32874aea 4781 c->type = CHAN_AGENT; /* identify channel type */
36c2a3e9 4782 c->u.a.lensofar = 0;
32874aea 4783 }
4784 } else {
4785 error = "Unsupported channel type requested";
4786 }
4787
bc240b21 4788 c->remoteid = remid;
32874aea 4789 if (error) {
4790 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
4791 ssh2_pkt_adduint32(c->remoteid);
4792 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
4793 ssh2_pkt_addstring(error);
4794 ssh2_pkt_addstring("en"); /* language tag */
4795 ssh2_pkt_send();
4796 sfree(c);
4797 } else {
4798 c->localid = alloc_channel_id();
4799 c->closes = 0;
5471d09a 4800 c->v.v2.locwindow = OUR_V2_WINSIZE;
4801 c->v.v2.remwindow = winsize;
4802 c->v.v2.remmaxpkt = pktsize;
4803 bufchain_init(&c->v.v2.outbuffer);
32874aea 4804 add234(ssh_channels, c);
4805 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
4806 ssh2_pkt_adduint32(c->remoteid);
4807 ssh2_pkt_adduint32(c->localid);
5471d09a 4808 ssh2_pkt_adduint32(c->v.v2.locwindow);
32874aea 4809 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
4810 ssh2_pkt_send();
4811 }
7cca0d81 4812 } else {
8d5de777 4813 bombout(("Strange packet received: type %d", pktin.type));
32874aea 4814 crReturnV;
7cca0d81 4815 }
4816 } else {
32874aea 4817 /*
4818 * We have spare data. Add it to the channel buffer.
4819 */
4820 ssh2_add_channel_data(mainchan, in, inlen);
4821 try_send = TRUE;
4822 }
4823 if (try_send) {
4824 int i;
4825 struct ssh_channel *c;
4826 /*
4827 * Try to send data on all channels if we can.
4828 */
5471d09a 4829 for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
4830 int bufsize = ssh2_try_send(c);
4831 if (bufsize == 0) {
4832 switch (c->type) {
4833 case CHAN_MAINSESSION:
4834 /* stdin need not receive an unthrottle
4835 * notification since it will be polled */
4836 break;
4837 case CHAN_X11:
4838 x11_unthrottle(c->u.x11.s);
4839 break;
4840 case CHAN_AGENT:
4841 /* agent sockets are request/response and need no
4842 * buffer management */
4843 break;
4844 case CHAN_SOCKDATA:
4845 pfd_unthrottle(c->u.pfd.s);
4846 break;
4847 }
4848 }
4849 }
7cca0d81 4850 }
e5574168 4851 }
4852
4853 crFinishV;
4854}
4855
4856/*
7cca0d81 4857 * Handle the top-level SSH2 protocol.
4858 */
4859static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
4860{
4861 if (do_ssh2_transport(in, inlen, ispkt) == 0)
32874aea 4862 return;
7cca0d81 4863 do_ssh2_authconn(in, inlen, ispkt);
4864}
4865
4866/*
8df7a775 4867 * Called to set up the connection.
374330e2 4868 *
4869 * Returns an error message, or NULL on success.
374330e2 4870 */
32874aea 4871static char *ssh_init(char *host, int port, char **realhost)
4872{
fb09bf1c 4873 char *p;
32874aea 4874
8f203108 4875#ifdef MSCRYPTOAPI
32874aea 4876 if (crypto_startup() == 0)
8f203108 4877 return "Microsoft high encryption pack not installed!";
4878#endif
374330e2 4879
8df7a775 4880 ssh_send_ok = 0;
0965bee0 4881 ssh_editing = 0;
4882 ssh_echoing = 0;
5471d09a 4883 ssh1_throttle_count = 0;
4884 ssh_overall_bufsize = 0;
8df7a775 4885
fb09bf1c 4886 p = connect_to_host(host, port, realhost);
4887 if (p != NULL)
4888 return p;
374330e2 4889
374330e2 4890 return NULL;
4891}
4892
4893/*
374330e2 4894 * Called to send data down the Telnet connection.
4895 */
5471d09a 4896static int ssh_send(char *buf, int len)
32874aea 4897{
f78051a1 4898 if (s == NULL || ssh_protocol == NULL)
5471d09a 4899 return 0;
374330e2 4900
4901 ssh_protocol(buf, len, 0);
5471d09a 4902
4903 return ssh_sendbuffer();
4904}
4905
4906/*
4907 * Called to query the current amount of buffered stdin data.
4908 */
4909static int ssh_sendbuffer(void)
4910{
4911 int override_value;
4912
4913 if (s == NULL || ssh_protocol == NULL)
4914 return 0;
4915
4916 /*
4917 * If the SSH socket itself has backed up, add the total backup
4918 * size on that to any individual buffer on the stdin channel.
4919 */
4920 override_value = 0;
4921 if (ssh_throttled_all)
4922 override_value = ssh_overall_bufsize;
4923
4924 if (ssh_version == 1) {
4925 return override_value;
4926 } else if (ssh_version == 2) {
4927 if (!mainchan || mainchan->closes > 0)
4928 return override_value;
4929 else
4930 return override_value + bufchain_size(&mainchan->v.v2.outbuffer);
4931 }
4932
4933 return 0;
374330e2 4934}
4935
4936/*
6e48c3fe 4937 * Called to set the size of the window from SSH's POV.
374330e2 4938 */
32874aea 4939static void ssh_size(void)
4940{
374330e2 4941 switch (ssh_state) {
4942 case SSH_STATE_BEFORE_SIZE:
3687d221 4943 case SSH_STATE_PREPACKET:
21248260 4944 case SSH_STATE_CLOSED:
374330e2 4945 break; /* do nothing */
4946 case SSH_STATE_INTERMED:
4947 size_needed = TRUE; /* buffer for later */
4948 break;
4949 case SSH_STATE_SESSION:
32874aea 4950 if (!cfg.nopty) {
4951 if (ssh_version == 1) {
4952 send_packet(SSH1_CMSG_WINDOW_SIZE,
4953 PKT_INT, rows, PKT_INT, cols,
4954 PKT_INT, 0, PKT_INT, 0, PKT_END);
4955 } else {
4956 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4957 ssh2_pkt_adduint32(mainchan->remoteid);
4958 ssh2_pkt_addstring("window-change");
4959 ssh2_pkt_addbool(0);
4960 ssh2_pkt_adduint32(cols);
4961 ssh2_pkt_adduint32(rows);
4962 ssh2_pkt_adduint32(0);
4963 ssh2_pkt_adduint32(0);
4964 ssh2_pkt_send();
4965 }
4966 }
4967 break;
374330e2 4968 }
4969}
4970
4971/*
6abbf9e3 4972 * Send Telnet special codes. TS_EOF is useful for `plink', so you
4973 * can send an EOF and collect resulting output (e.g. `plink
4974 * hostname sort').
374330e2 4975 */
32874aea 4976static void ssh_special(Telnet_Special code)
4977{
6abbf9e3 4978 if (code == TS_EOF) {
32874aea 4979 if (ssh_state != SSH_STATE_SESSION) {
4980 /*
4981 * Buffer the EOF in case we are pre-SESSION, so we can
4982 * send it as soon as we reach SESSION.
4983 */
4984 if (code == TS_EOF)
4985 eof_needed = TRUE;
4986 return;
4987 }
4988 if (ssh_version == 1) {
4989 send_packet(SSH1_CMSG_EOF, PKT_END);
4990 } else {
4991 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4992 ssh2_pkt_adduint32(mainchan->remoteid);
4993 ssh2_pkt_send();
4994 }
4995 logevent("Sent EOF message");
ec55b220 4996 } else if (code == TS_PING) {
32874aea 4997 if (ssh_state == SSH_STATE_CLOSED
4998 || ssh_state == SSH_STATE_PREPACKET) return;
4999 if (ssh_version == 1) {
5000 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
5001 } else {
5002 ssh2_pkt_init(SSH2_MSG_IGNORE);
5003 ssh2_pkt_addstring_start();
5004 ssh2_pkt_send();
5005 }
6abbf9e3 5006 } else {
32874aea 5007 /* do nothing */
6abbf9e3 5008 }
374330e2 5009}
5010
d74d141c 5011void *new_sock_channel(Socket s)
5012{
5013 struct ssh_channel *c;
5014 c = smalloc(sizeof(struct ssh_channel));
5015
5016 if (c) {
bc240b21 5017 c->remoteid = -1; /* to be set when open confirmed */
d74d141c 5018 c->localid = alloc_channel_id();
5019 c->closes = 0;
bc240b21 5020 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
d74d141c 5021 c->u.pfd.s = s;
5022 add234(ssh_channels, c);
5023 }
5024 return c;
5025}
5026
5471d09a 5027/*
5028 * This is called when stdout/stderr (the entity to which
5029 * from_backend sends data) manages to clear some backlog.
5030 */
5031void ssh_unthrottle(int bufsize)
5032{
5033 if (ssh_version == 1) {
5034 if (bufsize < SSH1_BUFFER_LIMIT) {
5035 ssh1_stdout_throttling = 0;
5036 ssh1_throttle(-1);
5037 }
5038 } else {
5039 if (mainchan && mainchan->closes == 0)
5040 ssh2_set_window(mainchan, OUR_V2_WINSIZE - bufsize);
5041 }
5042}
5043
d74d141c 5044void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
5045{
5046 struct ssh_channel *c = (struct ssh_channel *)channel;
5047 char buf[1024];
5048
5049 sprintf(buf, "Opening forwarded connection to %.512s:%d", hostname, port);
5050 logevent(buf);
5051
bc240b21 5052 if (ssh_version == 1) {
5053 send_packet(SSH1_MSG_PORT_OPEN,
5054 PKT_INT, c->localid,
5055 PKT_STR, hostname,
5056 PKT_INT, port,
5057 //PKT_STR, <org:orgport>,
5058 PKT_END);
5059 } else {
5060 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
5061 ssh2_pkt_addstring("direct-tcpip");
5062 ssh2_pkt_adduint32(c->localid);
5471d09a 5063 c->v.v2.locwindow = OUR_V2_WINSIZE;
5064 ssh2_pkt_adduint32(c->v.v2.locwindow);/* our window size */
bc240b21 5065 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
5066 ssh2_pkt_addstring(hostname);
5067 ssh2_pkt_adduint32(port);
5068 /*
5069 * We make up values for the originator data; partly it's
5070 * too much hassle to keep track, and partly I'm not
5071 * convinced the server should be told details like that
5072 * about my local network configuration.
5073 */
5074 ssh2_pkt_addstring("client-side-connection");
5075 ssh2_pkt_adduint32(0);
5076 ssh2_pkt_send();
5077 }
d74d141c 5078}
5079
5080
32874aea 5081static Socket ssh_socket(void)
5082{
5083 return s;
5084}
8ccc75b0 5085
32874aea 5086static int ssh_sendok(void)
5087{
5088 return ssh_send_ok;
5089}
fb09bf1c 5090
32874aea 5091static int ssh_ldisc(int option)
5092{
5093 if (option == LD_ECHO)
5094 return ssh_echoing;
5095 if (option == LD_EDIT)
5096 return ssh_editing;
0965bee0 5097 return FALSE;
5098}
5099
374330e2 5100Backend ssh_backend = {
5101 ssh_init,
374330e2 5102 ssh_send,
5471d09a 5103 ssh_sendbuffer,
374330e2 5104 ssh_size,
4017be6d 5105 ssh_special,
8ccc75b0 5106 ssh_socket,
97db3be4 5107 ssh_sendok,
0965bee0 5108 ssh_ldisc,
5471d09a 5109 ssh_unthrottle,
97db3be4 5110 22
bc240b21 5111};