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