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