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