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