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