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