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