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