xref: /plan9-contrib/sys/src/9/boot/doauthenticate.c (revision 219b2ee8daee37f4aad58d63f21287faa8e4ffdc)
1 #include <u.h>
2 #include <libc.h>
3 #include <auth.h>
4 #include <../boot/boot.h>
5 
6 static char *pbmsg = "AS protocol botch";
7 static char *ccmsg = "can't connect to AS";
8 
9 int
10 readn(int fd, char *buf, int len)
11 {
12 	int m, n;
13 
14 	for(n = 0; n < len; n += m){
15 		m = read(fd, buf+n, len-n);
16 		if(m <= 0)
17 			return -1;
18 	}
19 	return n;
20 }
21 
22 static char*
23 fromauth(Method *mp, char *trbuf, char *tbuf)
24 {
25 	char t;
26 	char *msg;
27 	static char error[ERRLEN];
28 
29 	if(afd < 0){
30 		if(mp->auth == 0)
31 			fatal("no method for accessing auth server");
32 		afd = (*mp->auth)();
33 		if(afd < 0)
34 			return ccmsg;
35 	}
36 	if(write(afd, trbuf, TICKREQLEN) < 0 || read(afd, &t, 1) != 1){
37 		close(afd);
38 		afd = -1;
39 		return pbmsg;
40 	}
41 	switch(t){
42 	case AuthOK:
43 		msg = 0;
44 		if(readn(afd, tbuf, 2*TICKETLEN) < 0)
45 			msg = pbmsg;
46 		break;
47 	case AuthErr:
48 		if(readn(afd, error, ERRLEN) < 0)
49 			msg = pbmsg;
50 		else {
51 			error[ERRLEN-1] = 0;
52 			msg = error;
53 		}
54 		break;
55 	default:
56 		msg = pbmsg;
57 		break;
58 	}
59 	return msg;
60 }
61 
62 void
63 doauthenticate(int fd, Method *mp)
64 {
65 	char *msg;
66 	char trbuf[TICKREQLEN];
67 	char tbuf[2*TICKETLEN];
68 
69 	print("session...");
70 	if(fsession(fd, trbuf) < 0)
71 		fatal("session command failed");
72 
73 	/* no authentication required? */
74 	memset(tbuf, 0, 2*TICKETLEN);
75 	if(trbuf[0] == 0)
76 		return;
77 
78 	/* try getting to an auth server */
79 	msg = fromauth(mp, trbuf, tbuf);
80 	if(msg == 0)
81 		if(fauth(fd, tbuf) >= 0)
82 			return;
83 
84 	/* didn't work, go for the security hole */
85 	fprint(2, "no authentication server (%s), using your key as server key\n", msg);
86 }
87 
88 char*
89 checkkey(Method *mp, char *name, char *key)
90 {
91 	char *msg;
92 	Ticketreq tr;
93 	Ticket t;
94 	char trbuf[TICKREQLEN];
95 	char tbuf[TICKETLEN];
96 
97 	memset(&tr, 0, sizeof tr);
98 	tr.type = AuthTreq;
99 	strcpy(tr.authid, name);
100 	strcpy(tr.hostid, name);
101 	strcpy(tr.uid, name);
102 	convTR2M(&tr, trbuf);
103 	msg = fromauth(mp, trbuf, tbuf);
104 	if(msg == ccmsg){
105 		fprint(2, "boot: can't contact auth server, passwd unchecked\n");
106 		return 0;
107 	}
108 	if(msg)
109 		return msg;
110 	convM2T(tbuf, &t, key);
111 	if(t.num == AuthTc && strcmp(name, t.cuid)==0)
112 		return 0;
113 	return "no match";
114 }
115