]> git.lizzy.rs Git - plan9front.git/blob - sys/src/cmd/ssh.c
rio, kbdfs: increase read buffer for high latency kbdfs support
[plan9front.git] / sys / src / cmd / ssh.c
1 #include <u.h>
2 #include <libc.h>
3 #include <mp.h>
4 #include <libsec.h>
5 #include <auth.h>
6 #include <authsrv.h>
7
8 enum {
9         MSG_DISCONNECT = 1,
10         MSG_IGNORE,
11         MSG_UNIMPLEMENTED,
12         MSG_DEBUG,
13         MSG_SERVICE_REQUEST,
14         MSG_SERVICE_ACCEPT,
15
16         MSG_KEXINIT = 20,
17         MSG_NEWKEYS,
18
19         MSG_ECDH_INIT = 30,
20         MSG_ECDH_REPLY,
21
22         MSG_USERAUTH_REQUEST = 50,
23         MSG_USERAUTH_FAILURE,
24         MSG_USERAUTH_SUCCESS,
25         MSG_USERAUTH_BANNER,
26
27         MSG_USERAUTH_PK_OK = 60,
28         MSG_USERAUTH_INFO_REQUEST = 60,
29         MSG_USERAUTH_INFO_RESPONSE = 61,
30
31         MSG_GLOBAL_REQUEST = 80,
32         MSG_REQUEST_SUCCESS,
33         MSG_REQUEST_FAILURE,
34
35         MSG_CHANNEL_OPEN = 90,
36         MSG_CHANNEL_OPEN_CONFIRMATION,
37         MSG_CHANNEL_OPEN_FAILURE,
38         MSG_CHANNEL_WINDOW_ADJUST,
39         MSG_CHANNEL_DATA,
40         MSG_CHANNEL_EXTENDED_DATA,
41         MSG_CHANNEL_EOF,
42         MSG_CHANNEL_CLOSE,
43         MSG_CHANNEL_REQUEST,
44         MSG_CHANNEL_SUCCESS,
45         MSG_CHANNEL_FAILURE,
46 };
47
48
49 enum {
50         Overhead = 256,         // enougth for MSG_CHANNEL_DATA header
51         MaxPacket = 1<<15,
52         WinPackets = 8,         // (1<<15) * 8 = 256K
53 };
54
55 int MaxPwTries = 3; // retry this often for keyboard-interactive
56
57 typedef struct
58 {
59         u32int          seq;
60         u32int          kex;
61         u32int          chan;
62
63         int             win;
64         int             pkt;
65         int             eof;
66
67         Chachastate     cs1;
68         Chachastate     cs2;
69
70         uchar           *r;
71         uchar           *w;
72         uchar           b[Overhead + MaxPacket];
73
74         char            *v;
75         int             pid;
76         Rendez;
77 } Oneway;
78
79 int nsid;
80 uchar sid[256];
81 char thumb[2*SHA2_256dlen+1], *thumbfile;
82
83 int fd, intr, raw, port, mux, debug;
84 char *user, *service, *status, *host, *remote, *cmd;
85
86 Oneway recv, send;
87 void dispatch(void);
88
89 void
90 shutdown(void)
91 {
92         recv.eof = send.eof = 1;
93         if(send.pid > 0)
94                 postnote(PNPROC, send.pid, "shutdown");
95 }
96
97 void
98 catch(void*, char *msg)
99 {
100         if(strcmp(msg, "interrupt") == 0){
101                 intr = 1;
102                 noted(NCONT);
103         }
104         noted(NDFLT);
105 }
106
107 int
108 wasintr(void)
109 {
110         char err[ERRMAX];
111         int r;
112
113         memset(err, 0, sizeof(err));
114         errstr(err, sizeof(err));
115         r = strcmp(err, "interrupted") == 0;
116         errstr(err, sizeof(err));
117         return r;
118 }
119
120 #define PUT4(p, u) (p)[0] = (u)>>24, (p)[1] = (u)>>16, (p)[2] = (u)>>8, (p)[3] = (u)
121 #define GET4(p) (u32int)(p)[3] | (u32int)(p)[2]<<8 | (u32int)(p)[1]<<16 | (u32int)(p)[0]<<24
122
123 int
124 vpack(uchar *p, int n, char *fmt, va_list a)
125 {
126         uchar *p0 = p, *e = p+n;
127         u32int u;
128         mpint *m;
129         void *s;
130         int c;
131
132         for(;;){
133                 switch(c = *fmt++){
134                 case '\0':
135                         return p - p0;
136                 case '_':
137                         if(++p > e) goto err;
138                         break;
139                 case '.':
140                         *va_arg(a, void**) = p;
141                         break;
142                 case 'b':
143                         if(p >= e) goto err;
144                         *p++ = va_arg(a, int);
145                         break;
146                 case 'm':
147                         m = va_arg(a, mpint*);
148                         u = (mpsignif(m)+8)/8;
149                         if(p+4 > e) goto err;
150                         PUT4(p, u), p += 4;
151                         if(u > e-p) goto err;
152                         mptober(m, p, u), p += u;
153                         break;
154                 case '[':
155                 case 's':
156                         s = va_arg(a, void*);
157                         u = va_arg(a, int);
158                         if(c == 's'){
159                                 if(p+4 > e) goto err;
160                                 PUT4(p, u), p += 4;
161                         }
162                         if(u > e-p) goto err;
163                         memmove(p, s, u);
164                         p += u;
165                         break;
166                 case 'u':
167                         u = va_arg(a, int);
168                         if(p+4 > e) goto err;
169                         PUT4(p, u), p += 4;
170                         break;
171                 }
172         }
173 err:
174         return -1;
175 }
176
177 int
178 vunpack(uchar *p, int n, char *fmt, va_list a)
179 {
180         uchar *p0 = p, *e = p+n;
181         u32int u;
182         mpint *m;
183         void *s;
184
185         for(;;){
186                 switch(*fmt++){
187                 case '\0':
188                         return p - p0;
189                 case '_':
190                         if(++p > e) goto err;
191                         break;
192                 case '.':
193                         *va_arg(a, void**) = p;
194                         break;
195                 case 'b':
196                         if(p >= e) goto err;
197                         *va_arg(a, int*) = *p++;
198                         break;
199                 case 'm':
200                         if(p+4 > e) goto err;
201                         u = GET4(p), p += 4;
202                         if(u > e-p) goto err;
203                         m = va_arg(a, mpint*);
204                         betomp(p, u, m), p += u;
205                         break;
206                 case 's':
207                         if(p+4 > e) goto err;
208                         u = GET4(p), p += 4;
209                         if(u > e-p) goto err;
210                         *va_arg(a, void**) = p;
211                         *va_arg(a, int*) = u;
212                         p += u;
213                         break;
214                 case '[':
215                         s = va_arg(a, void*);
216                         u = va_arg(a, int);
217                         if(u > e-p) goto err;
218                         memmove(s, p, u);
219                         p += u;
220                         break;
221                 case 'u':
222                         if(p+4 > e) goto err;
223                         u = GET4(p);
224                         *va_arg(a, int*) = u;
225                         p += 4;
226                         break;
227                 }
228         }
229 err:
230         return -1;
231 }
232
233 int
234 pack(uchar *p, int n, char *fmt, ...)
235 {
236         va_list a;
237         va_start(a, fmt);
238         n = vpack(p, n, fmt, a);
239         va_end(a);
240         return n;
241 }
242 int
243 unpack(uchar *p, int n, char *fmt, ...)
244 {
245         va_list a;
246         va_start(a, fmt);
247         n = vunpack(p, n, fmt, a);
248         va_end(a);
249         return n;
250 }
251
252 void
253 setupcs(Oneway *c, uchar otk[32])
254 {
255         uchar iv[8];
256
257         memset(otk, 0, 32);
258         pack(iv, sizeof(iv), "uu", 0, c->seq);
259         chacha_setiv(&c->cs1, iv);
260         chacha_setiv(&c->cs2, iv);
261         chacha_setblock(&c->cs1, 0);
262         chacha_setblock(&c->cs2, 0);
263         chacha_encrypt(otk, 32, &c->cs2);
264 }
265
266 void
267 sendpkt(char *fmt, ...)
268 {
269         static uchar buf[sizeof(send.b)];
270         int n, pad;
271         va_list a;
272
273         va_start(a, fmt);
274         n = vpack(send.b, sizeof(send.b), fmt, a);
275         va_end(a);
276         if(n < 0) {
277 toobig:         sysfatal("sendpkt: message too big");
278                 return;
279         }
280         send.r = send.b;
281         send.w = send.b+n;
282
283 if(debug > 1)
284         fprint(2, "sendpkt: (%d) %.*H\n", send.r[0], (int)(send.w-send.r), send.r);
285
286         if(nsid){
287                 /* undocumented */
288                 pad = ChachaBsize - ((5+n) % ChachaBsize) + 4;
289         } else {
290                 for(pad=4; (5+n+pad) % 8; pad++)
291                         ;
292         }
293         prng(send.w, pad);
294         n = pack(buf, sizeof(buf)-16, "ub[[", 1+n+pad, pad, send.b, n, send.w, pad);
295         if(n < 0) goto toobig;
296         if(nsid){
297                 uchar otk[32];
298
299                 setupcs(&send, otk);
300                 chacha_encrypt(buf, 4, &send.cs1);
301                 chacha_encrypt(buf+4, n-4, &send.cs2);
302                 poly1305(buf, n, otk, sizeof(otk), buf+n, nil);
303                 n += 16;
304         }
305
306         if(write(fd, buf, n) != n)
307                 sysfatal("write: %r");
308
309         send.seq++;
310 }
311
312 int
313 readall(int fd, uchar *data, int len)
314 {
315         int n, tot;
316
317         for(tot = 0; tot < len; tot += n){
318                 n = read(fd, data+tot, len-tot);
319                 if(n <= 0){
320                         if(n < 0 && wasintr()){
321                                 n = 0;
322                                 continue;
323                         } else if(n == 0)
324                                 werrstr("eof");
325                         break;
326                 }
327         }
328         return tot;
329 }
330
331 int
332 recvpkt(void)
333 {
334         uchar otk[32], tag[16];
335         DigestState *ds = nil;
336         int n;
337
338         if(readall(fd, recv.b, 4) != 4)
339                 sysfatal("read1: %r");
340         if(nsid){
341                 setupcs(&recv, otk);
342                 ds = poly1305(recv.b, 4, otk, sizeof(otk), nil, nil);
343                 chacha_encrypt(recv.b, 4, &recv.cs1);
344                 unpack(recv.b, 4, "u", &n);
345                 n += 16;
346         } else {
347                 unpack(recv.b, 4, "u", &n);
348         }
349         if(n < 8 || n > sizeof(recv.b)){
350 badlen:         sysfatal("bad length %d", n);
351         }
352         if(readall(fd, recv.b, n) != n)
353                 sysfatal("read2: %r");
354         if(nsid){
355                 n -= 16;
356                 if(n < 0) goto badlen;
357                 poly1305(recv.b, n, otk, sizeof(otk), tag, ds);
358                 if(tsmemcmp(tag, recv.b+n, 16) != 0)
359                         sysfatal("bad tag");
360                 chacha_encrypt(recv.b, n, &recv.cs2);
361         }
362         n -= recv.b[0]+1;
363         if(n < 1) goto badlen;
364
365         recv.r = recv.b + 1;
366         recv.w = recv.r + n;
367         recv.seq++;
368
369 if(debug > 1)
370         fprint(2, "recvpkt: (%d) %.*H\n", recv.r[0], (int)(recv.w-recv.r), recv.r);
371
372         return recv.r[0];
373 }
374
375 static char sshrsa[] = "ssh-rsa";
376
377 int
378 rsapub2ssh(RSApub *rsa, uchar *data, int len)
379 {
380         return pack(data, len, "smm", sshrsa, sizeof(sshrsa)-1, rsa->ek, rsa->n);
381 }
382
383 RSApub*
384 ssh2rsapub(uchar *data, int len)
385 {
386         RSApub *pub;
387         char *s;
388         int n;
389
390         pub = rsapuballoc();
391         pub->n = mpnew(0);
392         pub->ek = mpnew(0);
393         if(unpack(data, len, "smm", &s, &n, pub->ek, pub->n) < 0
394         || n != sizeof(sshrsa)-1 || memcmp(s, sshrsa, n) != 0){
395                 rsapubfree(pub);
396                 return nil;
397         }
398         return pub;
399 }
400
401 int
402 rsasig2ssh(RSApub *pub, mpint *S, uchar *data, int len)
403 {
404         int l = (mpsignif(pub->n)+7)/8;
405         if(4+7+4+l > len)
406                 return -1;
407         mptober(S, data+4+7+4, l);
408         return pack(data, len, "ss", sshrsa, sizeof(sshrsa)-1, data+4+7+4, l);
409 }
410
411 mpint*
412 ssh2rsasig(uchar *data, int len)
413 {
414         mpint *m;
415         char *s;
416         int n;
417
418         m = mpnew(0);
419         if(unpack(data, len, "sm", &s, &n, m) < 0
420         || n != sizeof(sshrsa)-1 || memcmp(s, sshrsa, n) != 0){
421                 mpfree(m);
422                 return nil;
423         }
424         return m;
425 }
426
427 mpint*
428 pkcs1digest(uchar *data, int len, RSApub *pub)
429 {
430         uchar digest[SHA1dlen], buf[256];
431
432         sha1(data, len, digest, nil);
433         return pkcs1padbuf(buf, asn1encodedigest(sha1, digest, buf, sizeof(buf)), pub->n, 1);
434 }
435
436 int
437 pkcs1verify(uchar *data, int len, RSApub *pub, mpint *S)
438 {
439         mpint *V;
440         int ret;
441
442         V = pkcs1digest(data, len, pub);
443         ret = V != nil;
444         if(ret){
445                 rsaencrypt(pub, S, S);
446                 ret = mpcmp(V, S) == 0;
447                 mpfree(V);
448         }
449         return ret;
450 }
451
452 DigestState*
453 hashstr(void *data, ulong len, DigestState *ds)
454 {
455         uchar l[4];
456         pack(l, 4, "u", len);
457         return sha2_256((uchar*)data, len, nil, sha2_256(l, 4, nil, ds));
458 }
459
460 void
461 kdf(uchar *k, int nk, uchar *h, char x, uchar *out, int len)
462 {
463         uchar digest[SHA2_256dlen], *out0;
464         DigestState *ds;
465         int n;
466
467         ds = hashstr(k, nk, nil);
468         ds = sha2_256(h, sizeof(digest), nil, ds);
469         ds = sha2_256((uchar*)&x, 1, nil, ds);
470         sha2_256(sid, nsid, digest, ds);
471         for(out0=out;;){
472                 n = len;
473                 if(n > sizeof(digest))
474                         n = sizeof(digest);
475                 memmove(out, digest, n);
476                 len -= n;
477                 if(len == 0)
478                         break;
479                 out += n;
480                 ds = hashstr(k, nk, nil);
481                 ds = sha2_256(h, sizeof(digest), nil, ds);
482                 sha2_256(out0, out-out0, digest, ds);
483         }
484 }
485
486 void
487 kex(int gotkexinit)
488 {
489         static char kexalgs[] = "curve25519-sha256,curve25519-sha256@libssh.org";
490         static char cipheralgs[] = "chacha20-poly1305@openssh.com";
491         static char zipalgs[] = "none";
492         static char macalgs[] = "hmac-sha1";    /* work around for github.com */
493         static char langs[] = "";
494
495         uchar cookie[16], x[32], yc[32], z[32], k[32+1], h[SHA2_256dlen], *ys, *ks, *sig;
496         uchar k12[2*ChachaKeylen];
497         int i, nk, nys, nks, nsig;
498         DigestState *ds;
499         mpint *S, *K;
500         RSApub *pub;
501
502         ds = hashstr(send.v, strlen(send.v), nil);      
503         ds = hashstr(recv.v, strlen(recv.v), ds);
504
505         genrandom(cookie, sizeof(cookie));
506         sendpkt("b[ssssssssssbu", MSG_KEXINIT,
507                 cookie, sizeof(cookie),
508                 kexalgs, sizeof(kexalgs)-1,
509                 sshrsa, sizeof(sshrsa)-1,
510                 cipheralgs, sizeof(cipheralgs)-1,
511                 cipheralgs, sizeof(cipheralgs)-1,
512                 macalgs, sizeof(macalgs)-1,
513                 macalgs, sizeof(macalgs)-1,
514                 zipalgs, sizeof(zipalgs)-1,
515                 zipalgs, sizeof(zipalgs)-1,
516                 langs, sizeof(langs)-1,
517                 langs, sizeof(langs)-1,
518                 0,
519                 0);
520         ds = hashstr(send.r, send.w-send.r, ds);
521
522         if(!gotkexinit){
523         Next0:  switch(recvpkt()){
524                 default:
525                         dispatch();
526                         goto Next0;
527                 case MSG_KEXINIT:
528                         break;
529                 }
530         }
531         ds = hashstr(recv.r, recv.w-recv.r, ds);
532
533         if(debug){
534                 char *tab[] = {
535                         "kexalgs", "hostalgs",
536                         "cipher1", "cipher2",
537                         "mac1", "mac2",
538                         "zip1", "zip2",
539                         "lang1", "lang2",
540                         nil,
541                 }, **t, *s;
542                 uchar *p = recv.r+17;
543                 int n;
544                 for(t=tab; *t != nil; t++){
545                         if(unpack(p, recv.w-p, "s.", &s, &n, &p) < 0)
546                                 break;
547                         fprint(2, "%s: %.*s\n", *t, utfnlen(s, n), s);
548                 }
549         }
550
551         curve25519_dh_new(x, yc);
552         yc[31] &= ~0x80;
553
554         sendpkt("bs", MSG_ECDH_INIT, yc, sizeof(yc));
555 Next1:  switch(recvpkt()){
556         default:
557                 dispatch();
558                 goto Next1;
559         case MSG_KEXINIT:
560                 sysfatal("inception");
561         case MSG_ECDH_REPLY:
562                 if(unpack(recv.r, recv.w-recv.r, "_sss", &ks, &nks, &ys, &nys, &sig, &nsig) < 0)
563                         sysfatal("bad ECDH_REPLY");
564                 break;
565         }
566
567         if(nys != 32)
568                 sysfatal("bad server ECDH ephermal public key length");
569
570         ds = hashstr(ks, nks, ds);
571         ds = hashstr(yc, 32, ds);
572         ds = hashstr(ys, 32, ds);
573
574         if(thumb[0] == 0){
575                 Thumbprint *ok;
576
577                 sha2_256(ks, nks, h, nil);
578                 i = enc64(thumb, sizeof(thumb), h, sizeof(h));
579                 while(i > 0 && thumb[i-1] == '=')
580                         i--;
581                 thumb[i] = '\0';
582
583                 if(debug)
584                         fprint(2, "host fingerprint: %s\n", thumb);
585
586                 ok = initThumbprints(thumbfile, nil, "ssh");
587                 if(ok == nil || !okThumbprint(h, sizeof(h), ok)){
588                         if(ok != nil) werrstr("unknown host");
589                         fprint(2, "%s: %r\n", argv0);
590                         fprint(2, "verify hostkey: %s %.*[\n", sshrsa, nks, ks);
591                         fprint(2, "add thumbprint after verification:\n");
592                         fprint(2, "\techo 'ssh sha256=%s server=%s' >> %q\n", thumb, host, thumbfile);
593                         sysfatal("checking hostkey failed: %r");
594                 }
595                 freeThumbprints(ok);
596         }
597
598         if((pub = ssh2rsapub(ks, nks)) == nil)
599                 sysfatal("bad server public key");
600         if((S = ssh2rsasig(sig, nsig)) == nil)
601                 sysfatal("bad server signature");
602
603         curve25519_dh_finish(x, ys, z);
604
605         K = betomp(z, 32, nil);
606         nk = (mpsignif(K)+8)/8;
607         mptober(K, k, nk);
608         mpfree(K);
609
610         ds = hashstr(k, nk, ds);
611         sha2_256(nil, 0, h, ds);
612         if(!pkcs1verify(h, sizeof(h), pub, S))
613                 sysfatal("server verification failed");
614         mpfree(S);
615         rsapubfree(pub);
616
617         sendpkt("b", MSG_NEWKEYS);
618 Next2:  switch(recvpkt()){
619         default:
620                 dispatch();
621                 goto Next2;
622         case MSG_KEXINIT:
623                 sysfatal("inception");
624         case MSG_NEWKEYS:
625                 break;
626         }
627
628         /* next key exchange */
629         recv.kex = recv.seq + 100000;
630         send.kex = send.seq + 100000;
631
632         if(nsid == 0)
633                 memmove(sid, h, nsid = sizeof(h));
634
635         kdf(k, nk, h, 'C', k12, sizeof(k12));
636         setupChachastate(&send.cs1, k12+1*ChachaKeylen, ChachaKeylen, nil, 64/8, 20);
637         setupChachastate(&send.cs2, k12+0*ChachaKeylen, ChachaKeylen, nil, 64/8, 20);
638
639         kdf(k, nk, h, 'D', k12, sizeof(k12));
640         setupChachastate(&recv.cs1, k12+1*ChachaKeylen, ChachaKeylen, nil, 64/8, 20);
641         setupChachastate(&recv.cs2, k12+0*ChachaKeylen, ChachaKeylen, nil, 64/8, 20);
642 }
643
644 static char *authnext;
645
646 int
647 authok(char *meth)
648 {
649         int ok = authnext == nil || strstr(authnext, meth) != nil;
650 if(debug)
651         fprint(2, "userauth %s %s\n", meth, ok ? "ok" : "skipped");
652         return ok;
653 }
654
655 int
656 authfailure(char *meth)
657 {
658         char *s;
659         int n, partial;
660
661         if(unpack(recv.r, recv.w-recv.r, "_sb", &s, &n, &partial) < 0)
662                 sysfatal("bad auth failure response");
663         free(authnext);
664         authnext = smprint("%.*s", utfnlen(s, n), s);
665 if(debug)
666         fprint(2, "userauth %s failed: partial=%d, next=%s\n", meth, partial, authnext);
667         return partial != 0 || !authok(meth);
668 }
669
670 int
671 noneauth(void)
672 {
673         static char authmeth[] = "none";
674
675         if(!authok(authmeth))
676                 return -1;
677
678         sendpkt("bsss", MSG_USERAUTH_REQUEST,
679                 user, strlen(user),
680                 service, strlen(service),
681                 authmeth, sizeof(authmeth)-1);
682
683 Next0:  switch(recvpkt()){
684         default:
685                 dispatch();
686                 goto Next0;
687         case MSG_USERAUTH_FAILURE:
688                 werrstr("authentication needed");
689                 authfailure(authmeth);
690                 return -1;
691         case MSG_USERAUTH_SUCCESS:
692                 return 0;
693         }
694 }
695
696 int
697 pubkeyauth(void)
698 {
699         static char authmeth[] = "publickey";
700
701         uchar pk[4096], sig[4096];
702         int npk, nsig;
703
704         int afd, n;
705         char *s;
706         mpint *S;
707         AuthRpc *rpc;
708         RSApub *pub;
709
710         if(!authok(authmeth))
711                 return -1;
712
713         if((afd = open("/mnt/factotum/rpc", ORDWR)) < 0)
714                 return -1;
715         if((rpc = auth_allocrpc(afd)) == nil){
716                 close(afd);
717                 return -1;
718         }
719
720         s = "proto=rsa service=ssh role=client";
721         if(auth_rpc(rpc, "start", s, strlen(s)) != ARok){
722                 auth_freerpc(rpc);
723                 close(afd);
724                 return -1;
725         }
726
727         pub = rsapuballoc();
728         pub->n = mpnew(0);
729         pub->ek = mpnew(0);
730
731         while(auth_rpc(rpc, "read", nil, 0) == ARok){
732                 s = rpc->arg;
733                 if(strtomp(s, &s, 16, pub->n) == nil)
734                         break;
735                 if(*s++ != ' ')
736                         continue;
737                 if(strtomp(s, nil, 16, pub->ek) == nil)
738                         continue;
739                 npk = rsapub2ssh(pub, pk, sizeof(pk));
740
741                 sendpkt("bsssbss", MSG_USERAUTH_REQUEST,
742                         user, strlen(user),
743                         service, strlen(service),
744                         authmeth, sizeof(authmeth)-1,
745                         0,
746                         sshrsa, sizeof(sshrsa)-1,
747                         pk, npk);
748 Next1:          switch(recvpkt()){
749                 default:
750                         dispatch();
751                         goto Next1;
752                 case MSG_USERAUTH_FAILURE:
753                         if(authfailure(authmeth))
754                                 goto Failed;
755                         continue;
756                 case MSG_USERAUTH_SUCCESS:
757                 case MSG_USERAUTH_PK_OK:
758                         break;
759                 }
760
761                 /* sign sid and the userauth request */
762                 n = pack(send.b, sizeof(send.b), "sbsssbss",
763                         sid, nsid,
764                         MSG_USERAUTH_REQUEST,
765                         user, strlen(user),
766                         service, strlen(service),
767                         authmeth, sizeof(authmeth)-1,
768                         1,
769                         sshrsa, sizeof(sshrsa)-1,
770                         pk, npk);
771                 S = pkcs1digest(send.b, n, pub);
772                 n = snprint((char*)send.b, sizeof(send.b), "%B", S);
773                 mpfree(S);
774
775                 if(auth_rpc(rpc, "write", (char*)send.b, n) != ARok)
776                         break;
777                 if(auth_rpc(rpc, "read", nil, 0) != ARok)
778                         break;
779
780                 S = strtomp(rpc->arg, nil, 16, nil);
781                 nsig = rsasig2ssh(pub, S, sig, sizeof(sig));
782                 mpfree(S);
783
784                 /* send final userauth request with the signature */
785                 sendpkt("bsssbsss", MSG_USERAUTH_REQUEST,
786                         user, strlen(user),
787                         service, strlen(service),
788                         authmeth, sizeof(authmeth)-1,
789                         1,
790                         sshrsa, sizeof(sshrsa)-1,
791                         pk, npk,
792                         sig, nsig);
793 Next2:          switch(recvpkt()){
794                 default:
795                         dispatch();
796                         goto Next2;
797                 case MSG_USERAUTH_FAILURE:
798                         if(authfailure(authmeth))
799                                 goto Failed;
800                         continue;
801                 case MSG_USERAUTH_SUCCESS:
802                         break;
803                 }
804                 rsapubfree(pub);
805                 auth_freerpc(rpc);
806                 close(afd);
807                 return 0;
808         }
809 Failed:
810         rsapubfree(pub);
811         auth_freerpc(rpc);
812         close(afd);
813         return -1;      
814 }
815
816 int
817 passauth(void)
818 {
819         static char authmeth[] = "password";
820         UserPasswd *up;
821
822         if(!authok(authmeth))
823                 return -1;
824
825         up = auth_getuserpasswd(auth_getkey, "proto=pass service=ssh user=%q server=%q thumb=%q",
826                 user, host, thumb);
827         if(up == nil)
828                 return -1;
829
830         sendpkt("bsssbs", MSG_USERAUTH_REQUEST,
831                 user, strlen(user),
832                 service, strlen(service),
833                 authmeth, sizeof(authmeth)-1,
834                 0,
835                 up->passwd, strlen(up->passwd));
836
837         memset(up->passwd, 0, strlen(up->passwd));
838         free(up);
839
840 Next0:  switch(recvpkt()){
841         default:
842                 dispatch();
843                 goto Next0;
844         case MSG_USERAUTH_FAILURE:
845                 werrstr("wrong password");
846                 authfailure(authmeth);
847                 return -1;
848         case MSG_USERAUTH_SUCCESS:
849                 return 0;
850         }
851 }
852
853 int
854 kbintauth(void)
855 {
856         static char authmeth[] = "keyboard-interactive";
857         int tries;
858
859         char *name, *inst, *s, *a;
860         int fd, i, n, m;
861         int nquest, echo;
862         uchar *ans, *answ;
863         tries = 0;
864
865         if(!authok(authmeth))
866                 return -1;
867
868 Loop:
869         if(++tries > MaxPwTries)
870                 return -1;
871                 
872         sendpkt("bsssss", MSG_USERAUTH_REQUEST,
873                 user, strlen(user),
874                 service, strlen(service),
875                 authmeth, sizeof(authmeth)-1,
876                 "", 0,
877                 "", 0);
878
879 Next0:  switch(recvpkt()){
880         default:
881                 dispatch();
882                 goto Next0;
883         case MSG_USERAUTH_FAILURE:
884                 werrstr("keyboard-interactive failed");
885                 if(authfailure(authmeth))
886                         return -1;
887                 goto Loop;
888         case MSG_USERAUTH_SUCCESS:
889                 return 0;
890         case MSG_USERAUTH_INFO_REQUEST:
891                 break;
892         }
893 Retry:
894         if((fd = open("/dev/cons", OWRITE)) < 0)
895                 return -1;
896
897         if(unpack(recv.r, recv.w-recv.r, "_ss.", &name, &n, &inst, &m, &recv.r) < 0)
898                 sysfatal("bad info request: name, inst");
899
900         while(n > 0 && strchr("\r\n\t ", name[n-1]) != nil)
901                 n--;
902         while(m > 0 && strchr("\r\n\t ", inst[m-1]) != nil)
903                 m--;
904
905         if(n > 0)
906                 fprint(fd, "%.*s\n", utfnlen(name, n), name);
907         if(m > 0)
908                 fprint(fd, "%.*s\n", utfnlen(inst, m), inst);
909
910         /* lang, nprompt */
911         if(unpack(recv.r, recv.w-recv.r, "su.", &s, &n, &nquest, &recv.r) < 0)
912                 sysfatal("bad info request: lang, #quest");
913
914         ans = answ = nil;
915         for(i = 0; i < nquest; i++){
916                 if(unpack(recv.r, recv.w-recv.r, "sb.", &s, &n, &echo, &recv.r) < 0)
917                         sysfatal("bad info request: question [%d]", i);
918
919                 while(n > 0 && strchr("\r\n\t :", s[n-1]) != nil)
920                         n--;
921                 s[n] = '\0';
922
923                 if((a = readcons(s, nil, !echo)) == nil)
924                         sysfatal("readcons: %r");
925
926                 n = answ - ans;
927                 m = strlen(a)+4;
928                 if((s = realloc(ans, n + m)) == nil)
929                         sysfatal("realloc: %r");
930                 ans = (uchar*)s;
931                 answ = ans+n;
932                 answ += pack(answ, m, "s", a, m-4);
933         }
934
935         sendpkt("bu[", MSG_USERAUTH_INFO_RESPONSE, i, ans, answ - ans);
936         free(ans);
937         close(fd);
938
939 Next1:  switch(recvpkt()){
940         default:
941                 dispatch();
942                 goto Next1;
943         case MSG_USERAUTH_INFO_REQUEST:
944                 goto Retry;
945         case MSG_USERAUTH_FAILURE:
946                 werrstr("keyboard-interactive failed");
947                 if(authfailure(authmeth))
948                         return -1;
949                 goto Loop;
950         case MSG_USERAUTH_SUCCESS:
951                 return 0;
952         }
953 }
954
955 void
956 dispatch(void)
957 {
958         char *s;
959         uchar *p;
960         int n, b, c;
961
962         switch(recv.r[0]){
963         case MSG_IGNORE:
964                 return;
965         case MSG_GLOBAL_REQUEST:
966                 if(unpack(recv.r, recv.w-recv.r, "_sb", &s, &n, &b) < 0)
967                         break;
968                 if(debug)
969                         fprint(2, "%s: global request: %.*s\n",
970                                 argv0, utfnlen(s, n), s);
971                 if(b != 0)
972                         sendpkt("b", MSG_REQUEST_FAILURE);
973                 return;
974         case MSG_DISCONNECT:
975                 if(unpack(recv.r, recv.w-recv.r, "_us", &c, &s, &n) < 0)
976                         break;
977                 sysfatal("disconnect: (%d) %.*s", c, utfnlen(s, n), s);
978                 return;
979         case MSG_DEBUG:
980                 if(unpack(recv.r, recv.w-recv.r, "__sb", &s, &n, &c) < 0)
981                         break;
982                 if(c != 0 || debug)
983                         fprint(2, "%s: %.*s\n", argv0, utfnlen(s, n), s);
984                 return;
985         case MSG_USERAUTH_BANNER:
986                 if(unpack(recv.r, recv.w-recv.r, "_s", &s, &n) < 0)
987                         break;
988                 if(raw) write(2, s, n);
989                 return;
990         case MSG_KEXINIT:
991                 kex(1);
992                 return;
993         }
994
995         if(mux){
996                 n = recv.w - recv.r;
997                 if(write(1, recv.r, n) != n)
998                         sysfatal("write out: %r");
999                 return;
1000         }
1001
1002         switch(recv.r[0]){
1003         case MSG_CHANNEL_DATA:
1004                 if(unpack(recv.r, recv.w-recv.r, "_us", &c, &s, &n) < 0)
1005                         break;
1006                 if(c != recv.chan)
1007                         break;
1008                 if(write(1, s, n) != n)
1009                         sysfatal("write out: %r");
1010         Winadjust:
1011                 recv.win -= n;
1012                 if(recv.win < recv.pkt){
1013                         n = WinPackets*recv.pkt;
1014                         recv.win += n;
1015                         sendpkt("buu", MSG_CHANNEL_WINDOW_ADJUST, send.chan, n);
1016                 }
1017                 return;
1018         case MSG_CHANNEL_EXTENDED_DATA:
1019                 if(unpack(recv.r, recv.w-recv.r, "_uus", &c, &b, &s, &n) < 0)
1020                         break;
1021                 if(c != recv.chan)
1022                         break;
1023                 if(b == 1) write(2, s, n);
1024                 goto Winadjust;
1025         case MSG_CHANNEL_WINDOW_ADJUST:
1026                 if(unpack(recv.r, recv.w-recv.r, "_uu", &c, &n) < 0)
1027                         break;
1028                 if(c != recv.chan)
1029                         break;
1030                 send.win += n;
1031                 if(send.win >= send.pkt)
1032                         rwakeup(&send);
1033                 return;
1034         case MSG_CHANNEL_REQUEST:
1035                 if(unpack(recv.r, recv.w-recv.r, "_usb.", &c, &s, &n, &b, &p) < 0)
1036                         break;
1037                 if(c != recv.chan)
1038                         break;
1039                 if(n == 11 && memcmp(s, "exit-signal", n) == 0){
1040                         if(unpack(p, recv.w-p, "s", &s, &n) < 0)
1041                                 break;
1042                         if(n != 0 && status == nil)
1043                                 status = smprint("%.*s", utfnlen(s, n), s);
1044                         c = MSG_CHANNEL_SUCCESS;
1045                 } else if(n == 11 && memcmp(s, "exit-status", n) == 0){
1046                         if(unpack(p, recv.w-p, "u", &n) < 0)
1047                                 break;
1048                         if(n != 0 && status == nil)
1049                                 status = smprint("%d", n);
1050                         c = MSG_CHANNEL_SUCCESS;
1051                 } else {
1052                         if(debug)
1053                                 fprint(2, "%s: channel request: %.*s\n",
1054                                         argv0, utfnlen(s, n), s);
1055                         c = MSG_CHANNEL_FAILURE;
1056                 }
1057                 if(b != 0)
1058                         sendpkt("bu", c, recv.chan);
1059                 return;
1060         case MSG_CHANNEL_EOF:
1061                 recv.eof = 1;
1062                 if(!raw) write(1, "", 0);
1063                 return;
1064         case MSG_CHANNEL_CLOSE:
1065                 shutdown();
1066                 return;
1067         }
1068         sysfatal("got: %.*H", (int)(recv.w - recv.r), recv.r);
1069 }
1070
1071 char*
1072 readline(void)
1073 {
1074         uchar *p;
1075
1076         for(p = send.b; p < &send.b[sizeof(send.b)-1]; p++){
1077                 *p = '\0';
1078                 if(read(fd, p, 1) != 1 || *p == '\n')
1079                         break;
1080         }
1081         while(p >= send.b && (*p == '\n' || *p == '\r'))
1082                 *p-- = '\0';
1083         return (char*)send.b;
1084 }
1085
1086 static struct {
1087         char    *term;
1088         int     xpixels;
1089         int     ypixels;
1090         int     lines;
1091         int     cols;
1092 } tty;
1093
1094 void
1095 getdim(void)
1096 {
1097         char *s;
1098
1099         if(s = getenv("XPIXELS")){
1100                 tty.xpixels = atoi(s);
1101                 free(s);
1102         }
1103         if(s = getenv("YPIXELS")){
1104                 tty.ypixels = atoi(s);
1105                 free(s);
1106         }
1107         if(s = getenv("LINES")){
1108                 tty.lines = atoi(s);
1109                 free(s);
1110         }
1111         if(s = getenv("COLS")){
1112                 tty.cols = atoi(s);
1113                 free(s);
1114         }
1115 }
1116
1117 void
1118 rawon(void)
1119 {
1120         int ctl;
1121
1122         close(0);
1123         if(open("/dev/cons", OREAD) != 0)
1124                 sysfatal("open: %r");
1125         close(1);
1126         if(open("/dev/cons", OWRITE) != 1)
1127                 sysfatal("open: %r");
1128         dup(1, 2);
1129         if((ctl = open("/dev/consctl", OWRITE)) >= 0){
1130                 write(ctl, "rawon", 5);
1131                 write(ctl, "winchon", 7);       /* vt(1): interrupt note on window change */
1132         }
1133         getdim();
1134 }
1135
1136 #pragma    varargck    type  "k"   char*
1137
1138 kfmt(Fmt *f)
1139 {
1140         char *s, *p;
1141         int n;
1142
1143         s = va_arg(f->args, char*);
1144         n = fmtstrcpy(f, "'");
1145         while((p = strchr(s, '\'')) != nil){
1146                 *p = '\0';
1147                 n += fmtstrcpy(f, s);
1148                 *p = '\'';
1149                 n += fmtstrcpy(f, "'\\''");
1150                 s = p+1;
1151         }
1152         n += fmtstrcpy(f, s);
1153         n += fmtstrcpy(f, "'");
1154         return n;
1155 }
1156
1157 void
1158 usage(void)
1159 {
1160         fprint(2, "usage: %s [-dR] [-t thumbfile] [-T tries] [-u user] [-h] [user@]host [-W remote!port] [cmd args...]\n", argv0);
1161         exits("usage");
1162 }
1163
1164 void
1165 main(int argc, char *argv[])
1166 {
1167         static QLock sl;
1168         int b, n, c;
1169         char *s;
1170
1171         quotefmtinstall();
1172         fmtinstall('B', mpfmt);
1173         fmtinstall('H', encodefmt);
1174         fmtinstall('[', encodefmt);
1175         fmtinstall('k', kfmt);
1176
1177         tty.term = getenv("TERM");
1178         if(tty.term == nil)
1179                 tty.term = "";
1180         raw = *tty.term != 0;
1181
1182         ARGBEGIN {
1183         case 'd':
1184                 debug++;
1185                 break;
1186         case 'W':
1187                 remote = EARGF(usage());
1188                 s = strrchr(remote, '!');
1189                 if(s == nil)
1190                         s = strrchr(remote, ':');
1191                 if(s == nil)
1192                         usage();
1193                 *s++ = 0;
1194                 port = atoi(s);
1195                 raw = 0;
1196                 break;
1197         case 'R':
1198                 raw = 0;
1199                 break;
1200         case 'r':
1201                 raw = 2; /* bloody */
1202                 break;
1203         case 'u':
1204                 user = EARGF(usage());
1205                 break;
1206         case 'h':
1207                 host = EARGF(usage());
1208                 break;
1209         case 't':
1210                 thumbfile = EARGF(usage());
1211                 break;
1212         case 'T':
1213                 MaxPwTries = strtol(EARGF(usage()), &s, 0);
1214                 if(*s != 0) usage();
1215                 break;
1216         case 'X':
1217                 mux = 1;
1218                 raw = 0;
1219                 break;
1220         default:
1221                 usage();
1222         } ARGEND;
1223
1224         if(host == nil){
1225                 if(argc == 0)
1226                         usage();
1227                 host = *argv++;
1228         }
1229
1230         if(user == nil){
1231                 s = strchr(host, '@');
1232                 if(s != nil){
1233                         *s++ = '\0';
1234                         user = host;
1235                         host = s;
1236                 }
1237         }
1238
1239         for(cmd = nil; *argv != nil; argv++){
1240                 if(cmd == nil){
1241                         cmd = strdup(*argv);
1242                         if(raw == 1)
1243                                 raw = 0;
1244                 }else{
1245                         s = smprint("%s %k", cmd, *argv);
1246                         free(cmd);
1247                         cmd = s;
1248                 }
1249         }
1250
1251         if(remote != nil && cmd != nil)
1252                 usage();
1253
1254         if((fd = dial(netmkaddr(host, nil, "ssh"), nil, nil, nil)) < 0)
1255                 sysfatal("dial: %r");
1256
1257         send.v = "SSH-2.0-(9)";
1258         fprint(fd, "%s\r\n", send.v);
1259         recv.v = readline();
1260         if(debug)
1261                 fprint(2, "server verison: %s\n", recv.v);
1262         if(strncmp("SSH-2.0-", recv.v, 8) != 0)
1263                 sysfatal("bad server version: %s", recv.v);
1264         recv.v = strdup(recv.v);
1265
1266         send.l = recv.l = &sl;
1267
1268         if(user == nil)
1269                 user = getuser();
1270         if(thumbfile == nil)
1271                 thumbfile = smprint("%s/lib/sshthumbs", getenv("home"));
1272
1273         kex(0);
1274
1275         sendpkt("bs", MSG_SERVICE_REQUEST, "ssh-userauth", 12);
1276 Next0:  switch(recvpkt()){
1277         default:
1278                 dispatch();
1279                 goto Next0;
1280         case MSG_SERVICE_ACCEPT:
1281                 break;
1282         }
1283
1284         service = "ssh-connection";
1285         if(noneauth() < 0 && pubkeyauth() < 0 && passauth() < 0 && kbintauth() < 0)
1286                 sysfatal("auth: %r");
1287
1288         recv.pkt = send.pkt = MaxPacket;
1289         recv.win = send.win =  WinPackets*recv.pkt;
1290         recv.chan = send.win = 0;
1291
1292         if(mux)
1293                 goto Mux;
1294
1295         /* open hailing frequencies */
1296         if(remote != nil){
1297                 NetConnInfo *nci = getnetconninfo(nil, fd);
1298                 if(nci == nil)
1299                         sysfatal("can't get netconninfo: %r");
1300                 sendpkt("bsuuususu", MSG_CHANNEL_OPEN,
1301                         "direct-tcpip", 12,
1302                         recv.chan,
1303                         recv.win,
1304                         recv.pkt,
1305                         remote, strlen(remote),
1306                         port,
1307                         nci->laddr, strlen(nci->laddr),
1308                         atoi(nci->lserv));
1309                 free(nci);
1310         } else {
1311                 sendpkt("bsuuu", MSG_CHANNEL_OPEN,
1312                         "session", 7,
1313                         recv.chan,
1314                         recv.win,
1315                         recv.pkt);
1316         }
1317 Next1:  switch(recvpkt()){
1318         default:
1319                 dispatch();
1320                 goto Next1;
1321         case MSG_CHANNEL_OPEN_FAILURE:
1322                 if(unpack(recv.r, recv.w-recv.r, "_uus", &c, &b, &s, &n) < 0)
1323                         n = strlen(s = "???");
1324                 sysfatal("channel open failure: (%d) %.*s", b, utfnlen(s, n), s);
1325         case MSG_CHANNEL_OPEN_CONFIRMATION:
1326                 break;
1327         }
1328
1329         if(unpack(recv.r, recv.w-recv.r, "_uuuu", &recv.chan, &send.chan, &send.win, &send.pkt) < 0)
1330                 sysfatal("bad channel open confirmation");
1331         if(send.pkt <= 0 || send.pkt > MaxPacket)
1332                 send.pkt = MaxPacket;
1333
1334         if(remote != nil)
1335                 goto Mux;
1336
1337         if(raw) {
1338                 rawon();
1339                 sendpkt("busbsuuuus", MSG_CHANNEL_REQUEST,
1340                         send.chan,
1341                         "pty-req", 7,
1342                         0,
1343                         tty.term, strlen(tty.term),
1344                         tty.cols,
1345                         tty.lines,
1346                         tty.xpixels,
1347                         tty.ypixels,
1348                         "", 0);
1349         }
1350         if(cmd == nil){
1351                 sendpkt("busb", MSG_CHANNEL_REQUEST,
1352                         send.chan,
1353                         "shell", 5,
1354                         0);
1355         } else if(*cmd == '#') {
1356                 sendpkt("busbs", MSG_CHANNEL_REQUEST,
1357                         send.chan,
1358                         "subsystem", 9,
1359                         0,
1360                         cmd+1, strlen(cmd)-1);
1361         } else {
1362                 sendpkt("busbs", MSG_CHANNEL_REQUEST,
1363                         send.chan,
1364                         "exec", 4,
1365                         0,
1366                         cmd, strlen(cmd));
1367         }
1368
1369 Mux:
1370         notify(catch);
1371         atexit(shutdown);
1372
1373         recv.pid = getpid();
1374         n = rfork(RFPROC|RFMEM);
1375         if(n < 0)
1376                 sysfatal("fork: %r");
1377
1378         /* parent reads and dispatches packets */
1379         if(n > 0) {
1380                 send.pid = n;
1381                 while(recv.eof == 0){
1382                         recvpkt();
1383                         qlock(&sl);                                     
1384                         dispatch();
1385                         if((int)(send.kex - send.seq) <= 0 || (int)(recv.kex - recv.seq) <= 0)
1386                                 kex(0);
1387                         qunlock(&sl);
1388                 }
1389                 exits(status);
1390         }
1391
1392         /* child reads input and sends packets */
1393         qlock(&sl);
1394         for(;;){
1395                 static uchar buf[MaxPacket];
1396                 qunlock(&sl);
1397                 n = read(0, buf, send.pkt);
1398                 qlock(&sl);
1399                 if(send.eof)
1400                         break;
1401                 if(n < 0 && wasintr())
1402                         intr = 1;
1403                 if(intr){
1404                         if(!raw) break;
1405                         getdim();
1406                         sendpkt("busbuuuu", MSG_CHANNEL_REQUEST,
1407                                 send.chan,
1408                                 "window-change", 13,
1409                                 0,
1410                                 tty.cols,
1411                                 tty.lines,
1412                                 tty.xpixels,
1413                                 tty.ypixels);
1414                         sendpkt("busbs", MSG_CHANNEL_REQUEST,
1415                                 send.chan,
1416                                 "signal", 6,
1417                                 0,
1418                                 "INT", 3);
1419                         intr = 0;
1420                         continue;
1421                 }
1422                 if(n <= 0)
1423                         break;
1424                 if(mux){
1425                         sendpkt("[", buf, n);
1426                         continue;
1427                 }
1428                 send.win -= n;
1429                 while(send.win < 0)
1430                         rsleep(&send);
1431                 sendpkt("bus", MSG_CHANNEL_DATA,
1432                         send.chan,
1433                         buf, n);
1434         }
1435         if(send.eof++ == 0 && !mux)
1436                 sendpkt("bu", raw ? MSG_CHANNEL_CLOSE : MSG_CHANNEL_EOF, send.chan);
1437         else if(recv.pid > 0 && mux)
1438                 postnote(PNPROC, recv.pid, "shutdown");
1439         qunlock(&sl);
1440
1441         exits(nil);
1442 }