xref: /plan9-contrib/sys/src/cmd/auth/wrkey.c (revision 219b2ee8daee37f4aad58d63f21287faa8e4ffdc)
1 #include <u.h>
2 #include <libc.h>
3 #include <auth.h>
4 #include "authsrv.h"
5 
6 int
7 getsafe(char *field, int len, uchar *sum, char *file)
8 {
9 	char buf[64];
10 
11 	if(nvcsum(field, len) != *sum){
12 		if(readfile(file, buf, sizeof(buf)) < 0){
13 			memset(field, 0, len);
14 			return -1;
15 		}
16 	}
17 	return 0;
18 }
19 
20 void
21 outin(char *prompt, char *buf, int len)
22 {
23 	int n;
24 	char b[64];
25 
26 	if(len >= sizeof(b))
27 		len = sizeof(b) - 1;
28 	print("%s[%s]: ", prompt, buf);
29 	n = read(0, b, len);
30 	if(n <= 0)
31 		exits(0);
32 	b[n-1] = 0;
33 	if(n > 1)
34 		strcpy(buf, b);
35 }
36 
37 void
38 main(void)
39 {
40 	int fd;
41 	Nvrsafe safe;
42 
43 	fd = open("#r/nvram", ORDWR);
44 	if(fd < 0
45 	|| seek(fd, 1024+900, 0) < 0
46 	|| read(fd, &safe, sizeof safe) != sizeof safe){
47 		memset(&safe, 0, sizeof(safe));
48 		fprint(2, "wrkey: can't read nvram: %r\n\n");
49 	}
50 
51 	if(getsafe(safe.machkey, DESKEYLEN, &safe.machsum, "#c/key") < 0)
52 		fprint(2, "wrkey: bad nvram key\n");
53 	if(getsafe(safe.authid, NAMELEN, &safe.authidsum, "#c/hostowner") < 0)
54 		fprint(2, "wrkey: bad authentication id\n");
55 	if(getsafe(safe.authdom, DOMLEN, &safe.authdomsum, "#c/hostdomain") < 0)
56 		fprint(2, "wrkey: bad authentication domain\n");
57 
58 	getpass(safe.machkey, 1);
59 	outin("authid", safe.authid, sizeof(safe.authid));
60 	outin("authdom", safe.authdom, sizeof(safe.authdom));
61 
62 	safe.machsum = nvcsum(safe.machkey, DESKEYLEN);
63 	safe.authidsum = nvcsum(safe.authid, sizeof(safe.authid));
64 	safe.authdomsum = nvcsum(safe.authdom, sizeof(safe.authdom));
65 	if(seek(fd, 1024+900, 0) < 0
66 	|| write(fd, &safe, sizeof safe) != sizeof safe)
67 		fprint(2, "wrkey: can't write nvram: %r\n");
68 	close(fd);
69 
70 	/* set host's key */
71 	if(writefile("#c/key", safe.machkey, DESKEYLEN) < 0)
72 		fprint(2, "wrkey: writing #c/key: %r\n");
73 
74 	/* set host's owner (and uid of current process) */
75 	if(writefile("#c/hostowner", safe.authid, strlen(safe.authid)) < 0)
76 		fprint(2, "wrkey: writing #c/hostowner: %r\n");
77 
78 	/* set host's domain */
79 	if(writefile("#c/hostdomain", safe.authdom, strlen(safe.authdom)) < 0)
80 		fprint(2, "wrkey: writing #c/hostdomain: %r\n");
81 	exits(0);
82 }
83