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