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