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