18 int update_authfile(const char *fn, const char *tokenid, const char *id,
19 const char *password, const char *nonce,
20 const unsigned char *secret, const int secsize,
21 const unsigned char *payload, const int paysize)
26 unsigned char key[20];
27 int keysize = sizeof(key);
28 unsigned char *mysecret = secret;
29 int mysecsize = secsize;
30 unsigned char *myload = payload;
31 int myloadsize = paysize;
32 unsigned char *authobj = NULL;
35 char *mytokenid = NULL;
38 char *hauthobj = NULL;
39 unsigned char *oldauthobj = NULL;
42 if ((fp = fopen(fn, "r"))) {
47 eprint("fstat \"%s\" (fd %d) error: %s",
48 fn, fd, strerror(errno));
51 if (st.st_size > 2047) st.st_size = 2047;
52 buf = alloca(st.st_size + 1);
53 if (fgets(buf, st.st_size + 1, fp)) {
56 p = &buf[strlen(buf) - 1];
57 while (*p == '\n' || *p == '\r') *p-- = '\0';
58 mytokenid = strtok(buf, ":");
59 myid = strtok(NULL, ":");
60 mynonce = strtok(NULL, ":");
61 hauthobj = strtok(NULL, ":");
63 eprint("error reading from %s: %s",
71 hlen = strlen(hauthobj);
73 eprint("error: auth string has wrong length");
75 strspn(hauthobj, "0123456789abcdefABCDEF")) {
76 eprint("error: auth string not hexadecimal");
79 oldauthobj = alloca(oldauthsize);
80 for (i = 0; i < oldauthsize; i++)
81 sscanf(&hauthobj[i*2], "%2hhx", &oldauthobj[i]);
86 unsigned char chal[64];
87 int csize = sizeof(chal);
90 if (!oldauthobj || !password) {
91 eprint("if no secret given, old auth file must"
92 " be present and password must be given");
95 rc = make_challenge(myid, password, mynonce, chal, &csize);
97 eprint("cannot make challenge");
100 rc = pcsc_cr(chal, csize, key, &keysize);
102 eprint("error querying token: %s", pcsc_errstr(rc));
105 mysecsize = oldauthsize;
106 mysecret = alloca(mysecsize);
107 myloadsize = oldauthsize;
108 myload = alloca(myloadsize);
109 rc = parse_authobj(key, keysize, oldauthobj, oldauthsize,
110 mysecret, &mysecsize, myload, &myloadsize);
112 eprint("cannot parse old authobj: %d", rc);
116 if (tokenid) mytokenid = tokenid;
118 if (nonce) mynonce = nonce;
120 unsigned int prev = atoi(mynonce);
121 mynonce = alloca(16);
122 sprintf(mynonce, "%d", prev + 1);
125 authsize = ((mysecsize + myloadsize + 16 + 4 * sizeof(short) - 1) /
127 authobj = alloca(authsize);
128 rc = make_authobj(myid, password, mynonce, mysecret, mysecsize,
129 myload, myloadsize, authobj, &authsize);
131 eprint("make_authobj error %d", rc);
135 if ((fp = fopen(fn, "w"))) {
136 if (fprintf(fp, "%s:%s:%s:", mytokenid, myid, mynonce) < 0) {
137 eprint("cannot write to \"%s\": %s",
138 fn, strerror(errno));
141 for (i = 0; i < authsize; i++)
142 if (fprintf(fp, "%02x", authobj[i]) < 0) {
143 eprint("cannot write to \"%s\": %s",
144 fn, strerror(errno));
148 if (fclose(fp) < 0) {
149 eprint("cannot close \"%s\": %s",
150 fn, strerror(errno));
154 eprint("cannot open \"%s\": %s",
155 fn, strerror(errno));