Skip to content

Commit 846aef4

Browse files
committed
create_key: use all random bits; add some error handling
1 parent 1f786e2 commit 846aef4

File tree

1 file changed

+24
-7
lines changed

1 file changed

+24
-7
lines changed

csync2.c

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -237,9 +237,11 @@ int create_keyfile(const char *filename)
237237
int fd = open(filename, O_WRONLY|O_CREAT|O_EXCL, 0600);
238238
int rand = open("/dev/urandom", O_RDONLY);
239239
char matrix[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._";
240-
unsigned char n;
241-
int i;
240+
unsigned char key[64 /* plus newline */ +1];
241+
unsigned char key_bin[48 /* (sizeof(key)*8)/6 */];
242+
int i, j;
242243
int rc;
244+
243245
assert(sizeof(matrix) == 65);
244246
if ( fd == -1 ) {
245247
fprintf(stderr, "Can't create key file: %s\n", strerror(errno));
@@ -249,13 +251,28 @@ int create_keyfile(const char *filename)
249251
fprintf(stderr, "Can't open /dev/urandom: %s\n", strerror(errno));
250252
return 1;
251253
}
252-
for (i=0; i<64; i++) {
253-
rc = read(rand, &n, 1);
254-
rc = write(fd, matrix+(n&63), 1);
254+
rc = read(rand, key_bin, sizeof(key_bin));
255+
if (rc != sizeof(key_bin)) {
256+
fprintf(stderr, "Failed to read %zu bytes from /dev/urandom: %s\n",
257+
sizeof(key_bin),
258+
rc == -1 ? strerror(errno) : "short read?");
259+
return -1;
255260
}
256-
rc = write(fd, "\n", 1);
257261
close(rand);
258-
close(fd);
262+
for (i = j = 0; i < sizeof(key)/4*4; i+=4, j+=3) {
263+
key[i+0] = matrix[ key_bin[j] & 63];
264+
key[i+1] = matrix[((key_bin[j] >> 6)|(key_bin[j+1] <<2)) & 63];
265+
key[i+2] = matrix[((key_bin[j+1] >> 4)|(key_bin[j+2] <<4)) & 63];
266+
key[i+3] = matrix[ (key_bin[j+2] >> 2) & 63];
267+
}
268+
key[sizeof(key) -1] = '\n';
269+
errno = 0;
270+
rc = write(fd, key, sizeof(key));
271+
if (close(fd) || rc != sizeof(key)) {
272+
fprintf(stderr, "Failed to write out keyfile: %s\n",
273+
errno ? strerror(errno) : "short write?");
274+
unlink(filename);
275+
}
259276
return 0;
260277
}
261278

0 commit comments

Comments
 (0)