pkg_signature.c revision 1.2
1/*	$NetBSD: pkg_signature.c,v 1.2 2013/09/11 12:59:19 khorben Exp $	*/
2
3#if HAVE_CONFIG_H
4#include "config.h"
5#endif
6#include <nbcompat.h>
7#if HAVE_SYS_CDEFS_H
8#include <sys/cdefs.h>
9#endif
10__RCSID("$NetBSD: pkg_signature.c,v 1.2 2013/09/11 12:59:19 khorben Exp $");
11
12/*-
13 * Copyright (c) 2008 Joerg Sonnenberger <joerg@NetBSD.org>.
14 * All rights reserved.
15 *
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
18 * are met:
19 *
20 * 1. Redistributions of source code must retain the above copyright
21 *    notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 *    notice, this list of conditions and the following disclaimer in
24 *    the documentation and/or other materials provided with the
25 *    distribution.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
30 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
31 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
33 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
34 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
35 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
36 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
37 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * SUCH DAMAGE.
39 */
40
41#if HAVE_SYS_WAIT_H
42#include <sys/wait.h>
43#endif
44#include <ctype.h>
45#if HAVE_ERR_H
46#include <err.h>
47#endif
48#include <errno.h>
49#include <fcntl.h>
50#include <stdlib.h>
51#ifndef NETBSD
52#include <nbcompat/sha2.h>
53#else
54#include <sha2.h>
55#endif
56#include <signal.h>
57#ifdef NETBSD
58#include <unistd.h>
59#else
60#include <nbcompat/unistd.h>
61#endif
62
63#include <archive.h>
64#include <archive_entry.h>
65
66#include "lib.h"
67
68#define HASH_FNAME "+PKG_HASH"
69#define SIGNATURE_FNAME "+PKG_SIGNATURE"
70#define GPG_SIGNATURE_FNAME "+PKG_GPG_SIGNATURE"
71
72struct signature_archive {
73	struct archive *archive;
74	off_t pkg_size;
75	size_t sign_block_len, sign_block_number, sign_cur_block;
76	char **sign_blocks;
77	unsigned char *sign_buf;
78};
79
80static void
81hash_block(unsigned char *buf, size_t buf_len,
82    char hash[SHA512_DIGEST_STRING_LENGTH])
83{
84	unsigned char digest[SHA512_DIGEST_LENGTH];
85	SHA512_CTX hash_ctx;
86	int i;
87
88	SHA512_Init(&hash_ctx);
89	SHA512_Update(&hash_ctx, buf, buf_len);
90	SHA512_Final(digest, &hash_ctx);
91	for (i = 0; i < SHA512_DIGEST_LENGTH; ++i) {
92		unsigned char c;
93
94		c = digest[i] / 16;
95		if (c < 10)
96			hash[2 * i] = '0' + c;
97		else
98			hash[2 * i] = 'a' - 10 + c;
99
100		c = digest[i] % 16;
101		if (c < 10)
102			hash[2 * i + 1] = '0' + c;
103		else
104			hash[2 * i + 1] = 'a' - 10 + c;
105	}
106	hash[2 * i] = '\0';
107}
108
109static ssize_t
110verify_signature_read_cb(struct archive *archive, void *cookie, const void **buf)
111{
112	struct signature_archive *state = cookie;
113	char hash[SHA512_DIGEST_STRING_LENGTH];
114	ssize_t len, expected;
115
116	if (state->sign_cur_block >= state->sign_block_number)
117		return 0;
118
119	/* The following works for sign_block_len > 1 */
120	if (state->sign_cur_block + 1 == state->sign_block_number)
121		expected = state->pkg_size % state->sign_block_len;
122	else
123		expected = state->sign_block_len;
124
125	len = archive_read_data(state->archive, state->sign_buf, expected);
126	if (len != expected) {
127		warnx("Short read from package");
128		return -1;
129	}
130
131	hash_block(state->sign_buf, len, hash);
132
133	if (strcmp(hash, state->sign_blocks[state->sign_cur_block]) != 0) {
134		warnx("Invalid signature of block %llu",
135		    (unsigned long long)state->sign_cur_block);
136		return -1;
137	}
138	++state->sign_cur_block;
139	*buf = state->sign_buf;
140	return len;
141}
142
143static void
144free_signature_int(struct signature_archive *state)
145{
146	size_t i;
147
148	if (state->sign_blocks != NULL) {
149		for (i = 0; i < state->sign_block_number; ++i)
150			free(state->sign_blocks[i]);
151	}
152	free(state->sign_blocks);
153	free(state->sign_buf);
154	free(state);
155}
156
157static int
158verify_signature_close_cb(struct archive *archive, void *cookie)
159{
160	struct signature_archive *state = cookie;
161
162	archive_read_finish(state->archive);
163	free_signature_int(state);
164	return 0;
165}
166
167static int
168read_file_from_archive(const char *archive_name, struct archive *archive,
169    struct archive_entry **entry,
170    const char *fname, char **content, size_t *len)
171{
172	int r;
173
174	*content = NULL;
175	*len = 0;
176
177retry:
178	if (*entry == NULL &&
179	    (r = archive_read_next_header(archive, entry)) != ARCHIVE_OK) {
180		if (r == ARCHIVE_FATAL) {
181			warnx("Cannot read from archive `%s': %s",
182			    archive_name, archive_error_string(archive));
183		} else {
184			warnx("Premature end of archive `%s'", archive_name);
185		}
186		*entry = NULL;
187		return -1;
188	}
189	if (strcmp(archive_entry_pathname(*entry), "//") == 0) {
190		archive_read_data_skip(archive);
191		*entry = NULL;
192		goto retry;
193	}
194
195	if (strcmp(fname, archive_entry_pathname(*entry)) != 0)
196		return 1;
197
198	if (archive_entry_size(*entry) > SSIZE_MAX - 1) {
199		warnx("Signature of archive `%s' too large to process",
200		    archive_name);
201		return 1;
202	}
203	*len = archive_entry_size(*entry);
204	*content = xmalloc(*len + 1);
205
206	if (archive_read_data(archive, *content, *len) != (ssize_t)*len) {
207		warnx("Cannot read complete %s from archive `%s'", fname,
208		    archive_name);
209		free(*content);
210		*len = 0;
211		*content = NULL;
212		return 1;
213	}
214	(*content)[*len] = '\0';
215	*entry = NULL;
216
217	return 0;
218}
219
220static int
221parse_hash_file(const char *hash_file, char **pkgname,
222    struct signature_archive *state)
223{
224	static const char block1[] = "pkgsrc signature\n\nversion: 1\npkgname: ";
225	static const char block2[] = "algorithm: SHA512\nblock size: ";
226	static const char block3[] = "file size: ";
227	static const char block4[] = "end pkgsrc signature\n";
228	char *next;
229	size_t i, len;
230
231	*pkgname = NULL;
232
233	if (strncmp(hash_file, block1, strlen(block1)) != 0)
234		goto cleanup;
235	hash_file += strlen(block1);
236
237	len = strcspn(hash_file, "\n");
238	*pkgname = xmalloc(len + 1);
239	memcpy(*pkgname, hash_file, len);
240	(*pkgname)[len] = '\0';
241	for (i = 0; i < len; ++i) {
242		if (!isgraph((unsigned char)(*pkgname)[i]))
243			goto cleanup;
244	}
245	hash_file += len + 1;
246
247	if (strncmp(hash_file, block2, strlen(block2)) != 0)
248		goto cleanup;
249	hash_file += strlen(block2);
250
251	errno = 0;
252	if (!isdigit((unsigned char)*hash_file))
253		goto cleanup;
254	state->sign_block_len = strtoul(hash_file, &next, 10);
255	hash_file = next;
256
257	/* Assert sane minimum block size of 1KB */
258	if (*hash_file++ != '\n' || errno == ERANGE || state->sign_block_len < 1024)
259		goto cleanup;
260
261	if (strncmp(hash_file, block3, strlen(block3)) != 0)
262		goto cleanup;
263	hash_file += strlen(block3);
264
265	errno = 0;
266	if (!isdigit((unsigned char)*hash_file))
267		goto cleanup;
268	if (/* CONSTCOND */sizeof(off_t) >= sizeof(long long))
269		state->pkg_size = strtoll(hash_file, &next, 10);
270	else
271		state->pkg_size = strtol(hash_file, &next, 10);
272	hash_file = next;
273	if (*hash_file++ != '\n' || errno == ERANGE || state->pkg_size < 1)
274		goto cleanup;
275
276	if (*hash_file++ != '\n')
277		goto cleanup;
278
279	if (state->pkg_size / state->sign_block_len > SSIZE_MAX)
280		goto cleanup;
281	state->sign_block_number = (state->pkg_size +
282	    state->sign_block_len - 1) / state->sign_block_len;
283
284	state->sign_buf = xmalloc(state->sign_block_len);
285	state->sign_blocks = xcalloc(state->sign_block_number, sizeof(char *));
286
287	for (i = 0; i < state->sign_block_number; ++i) {
288		len = strspn(hash_file, "01234567889abcdef");
289		if (len != SHA512_DIGEST_LENGTH * 2 || hash_file[len] != '\n')
290			goto cleanup_hashes;
291		state->sign_blocks[i] = xmalloc(len + 1);
292		memcpy(state->sign_blocks[i], hash_file, len);
293		state->sign_blocks[i][len] = '\0';
294		hash_file += len + 1;
295	}
296
297	if (strcmp(hash_file, block4) != 0)
298		goto cleanup_hashes;
299
300	return 0;
301
302cleanup_hashes:
303	for (i = 0; i < state->sign_block_number; ++i)
304		free(state->sign_blocks[i]);
305	free(state->sign_blocks);
306	state->sign_blocks = NULL;
307
308cleanup:
309	warnx("Unknown format of hash file");
310	free(*pkgname);
311	*pkgname = NULL;
312	return -1;
313}
314
315int
316pkg_verify_signature(const char *archive_name, struct archive **archive,
317    struct archive_entry **entry, char **pkgname)
318{
319	struct signature_archive *state;
320	struct archive_entry *my_entry;
321	struct archive *a;
322	char *hash_file, *signature_file;
323	size_t hash_len, signature_len;
324	int r, has_sig;
325
326	*pkgname = NULL;
327
328	state = xcalloc(sizeof(*state), 1);
329
330	r = read_file_from_archive(archive_name, *archive, entry, HASH_FNAME,
331	    &hash_file, &hash_len);
332	if (r == -1) {
333		archive_read_finish(*archive);
334		*archive = NULL;
335		free(state);
336		goto no_valid_signature;
337	} else if (r == 1) {
338		free(state);
339		goto no_valid_signature;
340	}
341
342	if (parse_hash_file(hash_file, pkgname, state))
343		goto no_valid_signature;
344
345	r = read_file_from_archive(archive_name, *archive, entry, SIGNATURE_FNAME,
346	    &signature_file, &signature_len);
347	if (r == -1) {
348		archive_read_finish(*archive);
349		*archive = NULL;
350		free(state);
351		free(hash_file);
352		goto no_valid_signature;
353	} else if (r != 0) {
354		if (*entry != NULL)
355			r = read_file_from_archive(archive_name, *archive,
356			    entry, GPG_SIGNATURE_FNAME,
357			    &signature_file, &signature_len);
358		if (r == -1) {
359			archive_read_finish(*archive);
360			*archive = NULL;
361			free(state);
362			free(hash_file);
363			goto no_valid_signature;
364		} else if (r != 0) {
365			free(hash_file);
366			free(state);
367			goto no_valid_signature;
368		}
369		has_sig = !detached_gpg_verify(hash_file, hash_len,
370		    signature_file, signature_len, gpg_keyring_verify);
371
372		free(signature_file);
373	} else {
374#ifdef HAVE_SSL
375		has_sig = !easy_pkcs7_verify(hash_file, hash_len, signature_file,
376		    signature_len, certs_packages, 1);
377
378		free(signature_file);
379#else
380		warnx("No OpenSSL support compiled in, skipping signature");
381		has_sig = 0;
382		free(signature_file);
383#endif
384	}
385
386	r = archive_read_next_header(*archive, &my_entry);
387	if (r != ARCHIVE_OK) {
388		warnx("Cannot read inner package: %s",
389		    archive_error_string(*archive));
390		free_signature_int(state);
391		goto no_valid_signature;
392	}
393
394	if (archive_entry_size(my_entry) != state->pkg_size) {
395		warnx("Package size doesn't match signature");
396		free_signature_int(state);
397		goto no_valid_signature;
398	}
399
400	state->archive = *archive;
401
402	a = archive_read_new();
403	archive_read_support_compression_all(a);
404	archive_read_support_format_all(a);
405	if (archive_read_open(a, state, NULL, verify_signature_read_cb,
406	    verify_signature_close_cb)) {
407		warnx("Can't open signed package file");
408		archive_read_finish(a);
409		goto no_valid_signature;
410	}
411	*archive = a;
412	*entry = NULL;
413
414	return has_sig ? 0 : -1;
415
416no_valid_signature:
417	return -1;
418}
419
420int
421pkg_full_signature_check(const char *archive_name, struct archive **archive)
422{
423	struct archive_entry *entry = NULL;
424	char *pkgname;
425	int r;
426
427	if (pkg_verify_signature(archive_name, archive, &entry, &pkgname))
428		return -1;
429	if (pkgname == NULL)
430		return 0;
431
432	/* XXX read PLIST and compare pkgname */
433	while ((r = archive_read_next_header(*archive, &entry)) == ARCHIVE_OK)
434		archive_read_data_skip(*archive);
435
436	free(pkgname);
437	return r == ARCHIVE_EOF ? 0 : -1;
438}
439
440static char *
441extract_pkgname(int fd)
442{
443	package_t plist;
444	plist_t *p;
445	struct archive *a;
446	struct archive_entry *entry;
447	char *buf;
448	ssize_t len;
449	int r;
450
451	a = archive_read_new();
452	archive_read_support_compression_all(a);
453	archive_read_support_format_all(a);
454	if (archive_read_open_fd(a, fd, 1024)) {
455		warnx("Cannot open binary package: %s",
456		    archive_error_string(a));
457		archive_read_finish(a);
458		return NULL;
459	}
460
461	r = archive_read_next_header(a, &entry);
462	if (r != ARCHIVE_OK) {
463		warnx("Cannot extract package name: %s",
464		    r == ARCHIVE_EOF ? "EOF" : archive_error_string(a));
465		archive_read_finish(a);
466		return NULL;
467	}
468	if (strcmp(archive_entry_pathname(entry), "+CONTENTS") != 0) {
469		warnx("Invalid binary package, doesn't start with +CONTENTS");
470		archive_read_finish(a);
471		return NULL;
472	}
473	if (archive_entry_size(entry) > SSIZE_MAX - 1) {
474		warnx("+CONTENTS too large to process");
475		archive_read_finish(a);
476		return NULL;
477	}
478
479	len = archive_entry_size(entry);
480	buf = xmalloc(len + 1);
481
482	if (archive_read_data(a, buf, len) != len) {
483		warnx("Short read when extracing +CONTENTS");
484		free(buf);
485		archive_read_finish(a);
486		return NULL;
487	}
488	buf[len] = '\0';
489
490	archive_read_finish(a);
491
492	parse_plist(&plist, buf);
493	free(buf);
494	p = find_plist(&plist, PLIST_NAME);
495	if (p != NULL) {
496		buf = xstrdup(p->name);
497	} else {
498		warnx("Invalid PLIST: missing @name");
499		buf = NULL;
500	}
501	free_plist(&plist);
502
503	if (lseek(fd, 0, SEEK_SET) != 0) {
504		warn("Cannot seek in archive");
505		free(buf);
506		return NULL;
507	}
508
509	return buf;
510}
511
512static const char hash_template[] =
513"pkgsrc signature\n"
514"\n"
515"version: 1\n"
516"pkgname: %s\n"
517"algorithm: SHA512\n"
518"block size: 65536\n"
519"file size: %lld\n"
520"\n";
521
522static const char hash_trailer[] = "end pkgsrc signature\n";
523
524#ifdef HAVE_SSL
525void
526pkg_sign_x509(const char *name, const char *output, const char *key_file, const char *cert_file)
527{
528	struct archive *pkg;
529	struct archive_entry *entry, *hash_entry, *sign_entry;
530	int fd;
531	struct stat sb;
532	char *hash_file, *signature_file, *tmp, *pkgname, hash[SHA512_DIGEST_STRING_LENGTH];
533	unsigned char block[65536];
534	off_t i, size;
535	size_t block_len, signature_len;
536
537	if ((fd = open(name, O_RDONLY)) == -1)
538		err(EXIT_FAILURE, "Cannot open binary package %s", name);
539	if (fstat(fd, &sb) == -1)
540		err(EXIT_FAILURE, "Cannot stat %s", name);
541
542	entry = archive_entry_new();
543	archive_entry_copy_stat(entry, &sb);
544
545	pkgname = extract_pkgname(fd);
546	hash_file = xasprintf(hash_template, pkgname,
547	    (long long)archive_entry_size(entry));
548	free(pkgname);
549
550	for (i = 0; i < archive_entry_size(entry); i += block_len) {
551		if (i + (off_t)sizeof(block) < archive_entry_size(entry))
552			block_len = sizeof(block);
553		else
554			block_len = archive_entry_size(entry) % sizeof(block);
555		if (read(fd, block, block_len) != (ssize_t)block_len)
556			err(2, "short read");
557		hash_block(block, block_len, hash);
558		tmp = xasprintf("%s%s\n", hash_file, hash);
559		free(hash_file);
560		hash_file = tmp;
561	}
562	tmp = xasprintf("%s%s", hash_file, hash_trailer);
563	free(hash_file);
564	hash_file = tmp;
565
566	if (easy_pkcs7_sign(hash_file, strlen(hash_file), &signature_file,
567	    &signature_len, key_file, cert_file))
568		err(EXIT_FAILURE, "Cannot sign hash file");
569
570	lseek(fd, 0, SEEK_SET);
571
572	sign_entry = archive_entry_clone(entry);
573	hash_entry = archive_entry_clone(entry);
574	pkgname = strrchr(name, '/');
575	archive_entry_set_pathname(entry, pkgname != NULL ? pkgname + 1 : name);
576	archive_entry_set_pathname(hash_entry, HASH_FNAME);
577	archive_entry_set_pathname(sign_entry, SIGNATURE_FNAME);
578	archive_entry_set_size(hash_entry, strlen(hash_file));
579	archive_entry_set_size(sign_entry, signature_len);
580
581	pkg = archive_write_new();
582	archive_write_set_compression_none(pkg);
583	archive_write_set_format_ar_bsd(pkg);
584	archive_write_open_filename(pkg, output);
585
586	archive_write_header(pkg, hash_entry);
587	archive_write_data(pkg, hash_file, strlen(hash_file));
588	archive_write_finish_entry(pkg);
589	archive_entry_free(hash_entry);
590
591	archive_write_header(pkg, sign_entry);
592	archive_write_data(pkg, signature_file, signature_len);
593	archive_write_finish_entry(pkg);
594	archive_entry_free(sign_entry);
595
596	size = archive_entry_size(entry);
597	archive_write_header(pkg, entry);
598
599	for (i = 0; i < size; i += block_len) {
600		if (i + (off_t)sizeof(block) < size)
601			block_len = sizeof(block);
602		else
603			block_len = size % sizeof(block);
604		if (read(fd, block, block_len) != (ssize_t)block_len)
605			err(2, "short read");
606		archive_write_data(pkg, block, block_len);
607	}
608	archive_write_finish_entry(pkg);
609	archive_entry_free(entry);
610
611	archive_write_finish(pkg);
612
613	close(fd);
614
615	exit(0);
616}
617#endif
618
619void
620pkg_sign_gpg(const char *name, const char *output)
621{
622	struct archive *pkg;
623	struct archive_entry *entry, *hash_entry, *sign_entry;
624	int fd;
625	struct stat sb;
626	char *hash_file, *signature_file, *tmp, *pkgname, hash[SHA512_DIGEST_STRING_LENGTH];
627	unsigned char block[65536];
628	off_t i, size;
629	size_t block_len, signature_len;
630
631	if ((fd = open(name, O_RDONLY)) == -1)
632		err(EXIT_FAILURE, "Cannot open binary package %s", name);
633	if (fstat(fd, &sb) == -1)
634		err(EXIT_FAILURE, "Cannot stat %s", name);
635
636	entry = archive_entry_new();
637	archive_entry_copy_stat(entry, &sb);
638
639	pkgname = extract_pkgname(fd);
640	hash_file = xasprintf(hash_template, pkgname,
641	    (long long)archive_entry_size(entry));
642	free(pkgname);
643
644	for (i = 0; i < archive_entry_size(entry); i += block_len) {
645		if (i + (off_t)sizeof(block) < archive_entry_size(entry))
646			block_len = sizeof(block);
647		else
648			block_len = archive_entry_size(entry) % sizeof(block);
649		if (read(fd, block, block_len) != (ssize_t)block_len)
650			err(2, "short read");
651		hash_block(block, block_len, hash);
652		tmp = xasprintf("%s%s\n", hash_file, hash);
653		free(hash_file);
654		hash_file = tmp;
655	}
656	tmp = xasprintf("%s%s", hash_file, hash_trailer);
657	free(hash_file);
658	hash_file = tmp;
659
660	if (detached_gpg_sign(hash_file, strlen(hash_file), &signature_file,
661	    &signature_len, gpg_keyring_sign, gpg_sign_as))
662		err(EXIT_FAILURE, "Cannot sign hash file");
663
664	lseek(fd, 0, SEEK_SET);
665
666	sign_entry = archive_entry_clone(entry);
667	hash_entry = archive_entry_clone(entry);
668	pkgname = strrchr(name, '/');
669	archive_entry_set_pathname(entry, pkgname != NULL ? pkgname + 1 : name);
670	archive_entry_set_pathname(hash_entry, HASH_FNAME);
671	archive_entry_set_pathname(sign_entry, GPG_SIGNATURE_FNAME);
672	archive_entry_set_size(hash_entry, strlen(hash_file));
673	archive_entry_set_size(sign_entry, signature_len);
674
675	pkg = archive_write_new();
676	archive_write_set_compression_none(pkg);
677	archive_write_set_format_ar_bsd(pkg);
678	archive_write_open_filename(pkg, output);
679
680	archive_write_header(pkg, hash_entry);
681	archive_write_data(pkg, hash_file, strlen(hash_file));
682	archive_write_finish_entry(pkg);
683	archive_entry_free(hash_entry);
684
685	archive_write_header(pkg, sign_entry);
686	archive_write_data(pkg, signature_file, signature_len);
687	archive_write_finish_entry(pkg);
688	archive_entry_free(sign_entry);
689
690	size = archive_entry_size(entry);
691	archive_write_header(pkg, entry);
692
693	for (i = 0; i < size; i += block_len) {
694		if (i + (off_t)sizeof(block) < size)
695			block_len = sizeof(block);
696		else
697			block_len = size % sizeof(block);
698		if (read(fd, block, block_len) != (ssize_t)block_len)
699			err(2, "short read");
700		archive_write_data(pkg, block, block_len);
701	}
702	archive_write_finish_entry(pkg);
703	archive_entry_free(entry);
704
705	archive_write_finish(pkg);
706
707	close(fd);
708
709	exit(0);
710}
711