xref: /freebsd/usr.sbin/pkg/pkg.c (revision 5596f836e7e04a272113e57b3a80f1f67c0fec7f)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2012-2014 Baptiste Daroussin <bapt@FreeBSD.org>
5  * Copyright (c) 2013 Bryan Drewery <bdrewery@FreeBSD.org>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include <sys/param.h>
34 #include <sys/queue.h>
35 #include <sys/types.h>
36 #include <sys/sbuf.h>
37 #include <sys/wait.h>
38 
39 #include <archive.h>
40 #include <archive_entry.h>
41 #include <dirent.h>
42 #include <err.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <fetch.h>
46 #include <libutil.h>
47 #include <paths.h>
48 #include <stdbool.h>
49 #include <stdlib.h>
50 #include <stdio.h>
51 #include <string.h>
52 #include <unistd.h>
53 #include <ucl.h>
54 
55 #include <openssl/err.h>
56 #include <openssl/ssl.h>
57 
58 #include "dns_utils.h"
59 #include "config.h"
60 
61 struct sig_cert {
62 	char *name;
63 	unsigned char *sig;
64 	int siglen;
65 	unsigned char *cert;
66 	int certlen;
67 	bool trusted;
68 };
69 
70 struct pubkey {
71 	unsigned char *sig;
72 	int siglen;
73 };
74 
75 typedef enum {
76 	HASH_UNKNOWN,
77 	HASH_SHA256,
78 } hash_t;
79 
80 struct fingerprint {
81 	hash_t type;
82 	char *name;
83 	char hash[BUFSIZ];
84 	STAILQ_ENTRY(fingerprint) next;
85 };
86 
87 STAILQ_HEAD(fingerprint_list, fingerprint);
88 
89 static int
90 extract_pkg_static(int fd, char *p, int sz)
91 {
92 	struct archive *a;
93 	struct archive_entry *ae;
94 	char *end;
95 	int ret, r;
96 
97 	ret = -1;
98 	a = archive_read_new();
99 	if (a == NULL) {
100 		warn("archive_read_new");
101 		return (ret);
102 	}
103 	archive_read_support_filter_all(a);
104 	archive_read_support_format_tar(a);
105 
106 	if (lseek(fd, 0, 0) == -1) {
107 		warn("lseek");
108 		goto cleanup;
109 	}
110 
111 	if (archive_read_open_fd(a, fd, 4096) != ARCHIVE_OK) {
112 		warnx("archive_read_open_fd: %s", archive_error_string(a));
113 		goto cleanup;
114 	}
115 
116 	ae = NULL;
117 	while ((r = archive_read_next_header(a, &ae)) == ARCHIVE_OK) {
118 		end = strrchr(archive_entry_pathname(ae), '/');
119 		if (end == NULL)
120 			continue;
121 
122 		if (strcmp(end, "/pkg-static") == 0) {
123 			r = archive_read_extract(a, ae,
124 			    ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM |
125 			    ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_ACL |
126 			    ARCHIVE_EXTRACT_FFLAGS | ARCHIVE_EXTRACT_XATTR);
127 			strlcpy(p, archive_entry_pathname(ae), sz);
128 			break;
129 		}
130 	}
131 
132 	if (r == ARCHIVE_OK)
133 		ret = 0;
134 	else
135 		warnx("failed to extract pkg-static: %s",
136 		    archive_error_string(a));
137 
138 cleanup:
139 	archive_read_free(a);
140 	return (ret);
141 
142 }
143 
144 static int
145 install_pkg_static(const char *path, const char *pkgpath, bool force)
146 {
147 	int pstat;
148 	pid_t pid;
149 
150 	switch ((pid = fork())) {
151 	case -1:
152 		return (-1);
153 	case 0:
154 		if (force)
155 			execl(path, "pkg-static", "add", "-f", pkgpath,
156 			    (char *)NULL);
157 		else
158 			execl(path, "pkg-static", "add", pkgpath,
159 			    (char *)NULL);
160 		_exit(1);
161 	default:
162 		break;
163 	}
164 
165 	while (waitpid(pid, &pstat, 0) == -1)
166 		if (errno != EINTR)
167 			return (-1);
168 
169 	if (WEXITSTATUS(pstat))
170 		return (WEXITSTATUS(pstat));
171 	else if (WIFSIGNALED(pstat))
172 		return (128 & (WTERMSIG(pstat)));
173 	return (pstat);
174 }
175 
176 static int
177 fetch_to_fd(const char *url, char *path)
178 {
179 	struct url *u;
180 	struct dns_srvinfo *mirrors, *current;
181 	struct url_stat st;
182 	FILE *remote;
183 	/* To store _https._tcp. + hostname + \0 */
184 	int fd;
185 	int retry, max_retry;
186 	ssize_t r;
187 	char buf[10240];
188 	char zone[MAXHOSTNAMELEN + 13];
189 	static const char *mirror_type = NULL;
190 
191 	max_retry = 3;
192 	current = mirrors = NULL;
193 	remote = NULL;
194 
195 	if (mirror_type == NULL && config_string(MIRROR_TYPE, &mirror_type)
196 	    != 0) {
197 		warnx("No MIRROR_TYPE defined");
198 		return (-1);
199 	}
200 
201 	if ((fd = mkstemp(path)) == -1) {
202 		warn("mkstemp()");
203 		return (-1);
204 	}
205 
206 	retry = max_retry;
207 
208 	if ((u = fetchParseURL(url)) == NULL) {
209 		warn("fetchParseURL('%s')", url);
210 		return (-1);
211 	}
212 
213 	while (remote == NULL) {
214 		if (retry == max_retry) {
215 			if (strcmp(u->scheme, "file") != 0 &&
216 			    strcasecmp(mirror_type, "srv") == 0) {
217 				snprintf(zone, sizeof(zone),
218 				    "_%s._tcp.%s", u->scheme, u->host);
219 				mirrors = dns_getsrvinfo(zone);
220 				current = mirrors;
221 			}
222 		}
223 
224 		if (mirrors != NULL) {
225 			strlcpy(u->host, current->host, sizeof(u->host));
226 			u->port = current->port;
227 		}
228 
229 		remote = fetchXGet(u, &st, "");
230 		if (remote == NULL) {
231 			--retry;
232 			if (retry <= 0)
233 				goto fetchfail;
234 			if (mirrors == NULL) {
235 				sleep(1);
236 			} else {
237 				current = current->next;
238 				if (current == NULL)
239 					current = mirrors;
240 			}
241 		}
242 	}
243 
244 	while ((r = fread(buf, 1, sizeof(buf), remote)) > 0) {
245 		if (write(fd, buf, r) != r) {
246 			warn("write()");
247 			goto fetchfail;
248 		}
249 	}
250 
251 	if (r != 0) {
252 		warn("An error occurred while fetching pkg(8)");
253 		goto fetchfail;
254 	}
255 
256 	if (ferror(remote))
257 		goto fetchfail;
258 
259 	goto cleanup;
260 
261 fetchfail:
262 	if (fd != -1) {
263 		close(fd);
264 		fd = -1;
265 		unlink(path);
266 	}
267 
268 cleanup:
269 	if (remote != NULL)
270 		fclose(remote);
271 
272 	return fd;
273 }
274 
275 static struct fingerprint *
276 parse_fingerprint(ucl_object_t *obj)
277 {
278 	const ucl_object_t *cur;
279 	ucl_object_iter_t it = NULL;
280 	const char *function, *fp, *key;
281 	struct fingerprint *f;
282 	hash_t fct = HASH_UNKNOWN;
283 
284 	function = fp = NULL;
285 
286 	while ((cur = ucl_iterate_object(obj, &it, true))) {
287 		key = ucl_object_key(cur);
288 		if (cur->type != UCL_STRING)
289 			continue;
290 		if (strcasecmp(key, "function") == 0) {
291 			function = ucl_object_tostring(cur);
292 			continue;
293 		}
294 		if (strcasecmp(key, "fingerprint") == 0) {
295 			fp = ucl_object_tostring(cur);
296 			continue;
297 		}
298 	}
299 
300 	if (fp == NULL || function == NULL)
301 		return (NULL);
302 
303 	if (strcasecmp(function, "sha256") == 0)
304 		fct = HASH_SHA256;
305 
306 	if (fct == HASH_UNKNOWN) {
307 		warnx("Unsupported hashing function: %s", function);
308 		return (NULL);
309 	}
310 
311 	f = calloc(1, sizeof(struct fingerprint));
312 	f->type = fct;
313 	strlcpy(f->hash, fp, sizeof(f->hash));
314 
315 	return (f);
316 }
317 
318 static void
319 free_fingerprint_list(struct fingerprint_list* list)
320 {
321 	struct fingerprint *fingerprint, *tmp;
322 
323 	STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
324 		free(fingerprint->name);
325 		free(fingerprint);
326 	}
327 	free(list);
328 }
329 
330 static struct fingerprint *
331 load_fingerprint(const char *dir, const char *filename)
332 {
333 	ucl_object_t *obj = NULL;
334 	struct ucl_parser *p = NULL;
335 	struct fingerprint *f;
336 	char path[MAXPATHLEN];
337 
338 	f = NULL;
339 
340 	snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
341 
342 	p = ucl_parser_new(0);
343 	if (!ucl_parser_add_file(p, path)) {
344 		warnx("%s: %s", path, ucl_parser_get_error(p));
345 		ucl_parser_free(p);
346 		return (NULL);
347 	}
348 
349 	obj = ucl_parser_get_object(p);
350 
351 	if (obj->type == UCL_OBJECT)
352 		f = parse_fingerprint(obj);
353 
354 	if (f != NULL)
355 		f->name = strdup(filename);
356 
357 	ucl_object_unref(obj);
358 	ucl_parser_free(p);
359 
360 	return (f);
361 }
362 
363 static struct fingerprint_list *
364 load_fingerprints(const char *path, int *count)
365 {
366 	DIR *d;
367 	struct dirent *ent;
368 	struct fingerprint *finger;
369 	struct fingerprint_list *fingerprints;
370 
371 	*count = 0;
372 
373 	fingerprints = calloc(1, sizeof(struct fingerprint_list));
374 	if (fingerprints == NULL)
375 		return (NULL);
376 	STAILQ_INIT(fingerprints);
377 
378 	if ((d = opendir(path)) == NULL) {
379 		free(fingerprints);
380 
381 		return (NULL);
382 	}
383 
384 	while ((ent = readdir(d))) {
385 		if (strcmp(ent->d_name, ".") == 0 ||
386 		    strcmp(ent->d_name, "..") == 0)
387 			continue;
388 		finger = load_fingerprint(path, ent->d_name);
389 		if (finger != NULL) {
390 			STAILQ_INSERT_TAIL(fingerprints, finger, next);
391 			++(*count);
392 		}
393 	}
394 
395 	closedir(d);
396 
397 	return (fingerprints);
398 }
399 
400 static void
401 sha256_hash(unsigned char hash[SHA256_DIGEST_LENGTH],
402     char out[SHA256_DIGEST_LENGTH * 2 + 1])
403 {
404 	int i;
405 
406 	for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
407 		sprintf(out + (i * 2), "%02x", hash[i]);
408 
409 	out[SHA256_DIGEST_LENGTH * 2] = '\0';
410 }
411 
412 static void
413 sha256_buf(char *buf, size_t len, char out[SHA256_DIGEST_LENGTH * 2 + 1])
414 {
415 	unsigned char hash[SHA256_DIGEST_LENGTH];
416 	SHA256_CTX sha256;
417 
418 	out[0] = '\0';
419 
420 	SHA256_Init(&sha256);
421 	SHA256_Update(&sha256, buf, len);
422 	SHA256_Final(hash, &sha256);
423 	sha256_hash(hash, out);
424 }
425 
426 static int
427 sha256_fd(int fd, char out[SHA256_DIGEST_LENGTH * 2 + 1])
428 {
429 	int my_fd;
430 	FILE *fp;
431 	char buffer[BUFSIZ];
432 	unsigned char hash[SHA256_DIGEST_LENGTH];
433 	size_t r;
434 	int ret;
435 	SHA256_CTX sha256;
436 
437 	my_fd = -1;
438 	fp = NULL;
439 	r = 0;
440 	ret = 1;
441 
442 	out[0] = '\0';
443 
444 	/* Duplicate the fd so that fclose(3) does not close it. */
445 	if ((my_fd = dup(fd)) == -1) {
446 		warnx("dup");
447 		goto cleanup;
448 	}
449 
450 	if ((fp = fdopen(my_fd, "rb")) == NULL) {
451 		warnx("fdopen");
452 		goto cleanup;
453 	}
454 
455 	SHA256_Init(&sha256);
456 
457 	while ((r = fread(buffer, 1, BUFSIZ, fp)) > 0)
458 		SHA256_Update(&sha256, buffer, r);
459 
460 	if (ferror(fp) != 0) {
461 		warnx("fread");
462 		goto cleanup;
463 	}
464 
465 	SHA256_Final(hash, &sha256);
466 	sha256_hash(hash, out);
467 	ret = 0;
468 
469 cleanup:
470 	if (fp != NULL)
471 		fclose(fp);
472 	else if (my_fd != -1)
473 		close(my_fd);
474 	(void)lseek(fd, 0, SEEK_SET);
475 
476 	return (ret);
477 }
478 
479 static EVP_PKEY *
480 load_public_key_file(const char *file)
481 {
482 	EVP_PKEY *pkey;
483 	BIO *bp;
484 	char errbuf[1024];
485 
486 	bp = BIO_new_file(file, "r");
487 	if (!bp)
488 		errx(EXIT_FAILURE, "Unable to read %s", file);
489 
490 	if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
491 		warnx("ici: %s", ERR_error_string(ERR_get_error(), errbuf));
492 
493 	BIO_free(bp);
494 
495 	return (pkey);
496 }
497 
498 static EVP_PKEY *
499 load_public_key_buf(const unsigned char *cert, int certlen)
500 {
501 	EVP_PKEY *pkey;
502 	BIO *bp;
503 	char errbuf[1024];
504 
505 	bp = BIO_new_mem_buf(__DECONST(void *, cert), certlen);
506 
507 	if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
508 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
509 
510 	BIO_free(bp);
511 
512 	return (pkey);
513 }
514 
515 static bool
516 rsa_verify_cert(int fd, const char *sigfile, const unsigned char *key,
517     int keylen, unsigned char *sig, int siglen)
518 {
519 	EVP_MD_CTX *mdctx;
520 	EVP_PKEY *pkey;
521 	char sha256[(SHA256_DIGEST_LENGTH * 2) + 2];
522 	char errbuf[1024];
523 	bool ret;
524 
525 	pkey = NULL;
526 	mdctx = NULL;
527 	ret = false;
528 
529 	SSL_load_error_strings();
530 
531 	/* Compute SHA256 of the package. */
532 	if (lseek(fd, 0, 0) == -1) {
533 		warn("lseek");
534 		goto cleanup;
535 	}
536 	if ((sha256_fd(fd, sha256)) == -1) {
537 		warnx("Error creating SHA256 hash for package");
538 		goto cleanup;
539 	}
540 
541 	if (sigfile != NULL) {
542 		if ((pkey = load_public_key_file(sigfile)) == NULL) {
543 			warnx("Error reading public key");
544 			goto cleanup;
545 		}
546 	} else {
547 		if ((pkey = load_public_key_buf(key, keylen)) == NULL) {
548 			warnx("Error reading public key");
549 			goto cleanup;
550 		}
551 	}
552 
553 	/* Verify signature of the SHA256(pkg) is valid. */
554 	if ((mdctx = EVP_MD_CTX_create()) == NULL) {
555 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
556 		goto error;
557 	}
558 
559 	if (EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
560 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
561 		goto error;
562 	}
563 	if (EVP_DigestVerifyUpdate(mdctx, sha256, strlen(sha256)) != 1) {
564 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
565 		goto error;
566 	}
567 
568 	if (EVP_DigestVerifyFinal(mdctx, sig, siglen) != 1) {
569 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
570 		goto error;
571 	}
572 
573 	ret = true;
574 	printf("done\n");
575 	goto cleanup;
576 
577 error:
578 	printf("failed\n");
579 
580 cleanup:
581 	if (pkey)
582 		EVP_PKEY_free(pkey);
583 	if (mdctx)
584 		EVP_MD_CTX_destroy(mdctx);
585 	ERR_free_strings();
586 
587 	return (ret);
588 }
589 
590 static struct pubkey *
591 read_pubkey(int fd)
592 {
593 	struct pubkey *pk;
594 	struct sbuf *sig;
595 	char buf[4096];
596 	int r;
597 
598 	if (lseek(fd, 0, 0) == -1) {
599 		warn("lseek");
600 		return (NULL);
601 	}
602 
603 	sig = sbuf_new_auto();
604 
605 	while ((r = read(fd, buf, sizeof(buf))) >0) {
606 		sbuf_bcat(sig, buf, r);
607 	}
608 
609 	sbuf_finish(sig);
610 	pk = calloc(1, sizeof(struct pubkey));
611 	pk->siglen = sbuf_len(sig);
612 	pk->sig = calloc(1, pk->siglen);
613 	memcpy(pk->sig, sbuf_data(sig), pk->siglen);
614 	sbuf_delete(sig);
615 
616 	return (pk);
617 }
618 
619 static struct sig_cert *
620 parse_cert(int fd) {
621 	int my_fd;
622 	struct sig_cert *sc;
623 	FILE *fp;
624 	struct sbuf *buf, *sig, *cert;
625 	char *line;
626 	size_t linecap;
627 	ssize_t linelen;
628 
629 	buf = NULL;
630 	my_fd = -1;
631 	sc = NULL;
632 	line = NULL;
633 	linecap = 0;
634 
635 	if (lseek(fd, 0, 0) == -1) {
636 		warn("lseek");
637 		return (NULL);
638 	}
639 
640 	/* Duplicate the fd so that fclose(3) does not close it. */
641 	if ((my_fd = dup(fd)) == -1) {
642 		warnx("dup");
643 		return (NULL);
644 	}
645 
646 	if ((fp = fdopen(my_fd, "rb")) == NULL) {
647 		warn("fdopen");
648 		close(my_fd);
649 		return (NULL);
650 	}
651 
652 	sig = sbuf_new_auto();
653 	cert = sbuf_new_auto();
654 
655 	while ((linelen = getline(&line, &linecap, fp)) > 0) {
656 		if (strcmp(line, "SIGNATURE\n") == 0) {
657 			buf = sig;
658 			continue;
659 		} else if (strcmp(line, "CERT\n") == 0) {
660 			buf = cert;
661 			continue;
662 		} else if (strcmp(line, "END\n") == 0) {
663 			break;
664 		}
665 		if (buf != NULL)
666 			sbuf_bcat(buf, line, linelen);
667 	}
668 
669 	fclose(fp);
670 
671 	/* Trim out unrelated trailing newline */
672 	sbuf_setpos(sig, sbuf_len(sig) - 1);
673 
674 	sbuf_finish(sig);
675 	sbuf_finish(cert);
676 
677 	sc = calloc(1, sizeof(struct sig_cert));
678 	sc->siglen = sbuf_len(sig);
679 	sc->sig = calloc(1, sc->siglen);
680 	memcpy(sc->sig, sbuf_data(sig), sc->siglen);
681 
682 	sc->certlen = sbuf_len(cert);
683 	sc->cert = strdup(sbuf_data(cert));
684 
685 	sbuf_delete(sig);
686 	sbuf_delete(cert);
687 
688 	return (sc);
689 }
690 
691 static bool
692 verify_pubsignature(int fd_pkg, int fd_sig)
693 {
694 	struct pubkey *pk;
695 	const char *pubkey;
696 	bool ret;
697 
698 	pk = NULL;
699 	pubkey = NULL;
700 	ret = false;
701 	if (config_string(PUBKEY, &pubkey) != 0) {
702 		warnx("No CONFIG_PUBKEY defined");
703 		goto cleanup;
704 	}
705 
706 	if ((pk = read_pubkey(fd_sig)) == NULL) {
707 		warnx("Error reading signature");
708 		goto cleanup;
709 	}
710 
711 	/* Verify the signature. */
712 	printf("Verifying signature with public key %s... ", pubkey);
713 	if (rsa_verify_cert(fd_pkg, pubkey, NULL, 0, pk->sig,
714 	    pk->siglen) == false) {
715 		fprintf(stderr, "Signature is not valid\n");
716 		goto cleanup;
717 	}
718 
719 	ret = true;
720 
721 cleanup:
722 	if (pk) {
723 		free(pk->sig);
724 		free(pk);
725 	}
726 
727 	return (ret);
728 }
729 
730 static bool
731 verify_signature(int fd_pkg, int fd_sig)
732 {
733 	struct fingerprint_list *trusted, *revoked;
734 	struct fingerprint *fingerprint;
735 	struct sig_cert *sc;
736 	bool ret;
737 	int trusted_count, revoked_count;
738 	const char *fingerprints;
739 	char path[MAXPATHLEN];
740 	char hash[SHA256_DIGEST_LENGTH * 2 + 1];
741 
742 	sc = NULL;
743 	trusted = revoked = NULL;
744 	ret = false;
745 
746 	/* Read and parse fingerprints. */
747 	if (config_string(FINGERPRINTS, &fingerprints) != 0) {
748 		warnx("No CONFIG_FINGERPRINTS defined");
749 		goto cleanup;
750 	}
751 
752 	snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
753 	if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
754 		warnx("Error loading trusted certificates");
755 		goto cleanup;
756 	}
757 
758 	if (trusted_count == 0 || trusted == NULL) {
759 		fprintf(stderr, "No trusted certificates found.\n");
760 		goto cleanup;
761 	}
762 
763 	snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
764 	if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
765 		warnx("Error loading revoked certificates");
766 		goto cleanup;
767 	}
768 
769 	/* Read certificate and signature in. */
770 	if ((sc = parse_cert(fd_sig)) == NULL) {
771 		warnx("Error parsing certificate");
772 		goto cleanup;
773 	}
774 	/* Explicitly mark as non-trusted until proven otherwise. */
775 	sc->trusted = false;
776 
777 	/* Parse signature and pubkey out of the certificate */
778 	sha256_buf(sc->cert, sc->certlen, hash);
779 
780 	/* Check if this hash is revoked */
781 	if (revoked != NULL) {
782 		STAILQ_FOREACH(fingerprint, revoked, next) {
783 			if (strcasecmp(fingerprint->hash, hash) == 0) {
784 				fprintf(stderr, "The package was signed with "
785 				    "revoked certificate %s\n",
786 				    fingerprint->name);
787 				goto cleanup;
788 			}
789 		}
790 	}
791 
792 	STAILQ_FOREACH(fingerprint, trusted, next) {
793 		if (strcasecmp(fingerprint->hash, hash) == 0) {
794 			sc->trusted = true;
795 			sc->name = strdup(fingerprint->name);
796 			break;
797 		}
798 	}
799 
800 	if (sc->trusted == false) {
801 		fprintf(stderr, "No trusted fingerprint found matching "
802 		    "package's certificate\n");
803 		goto cleanup;
804 	}
805 
806 	/* Verify the signature. */
807 	printf("Verifying signature with trusted certificate %s... ", sc->name);
808 	if (rsa_verify_cert(fd_pkg, NULL, sc->cert, sc->certlen, sc->sig,
809 	    sc->siglen) == false) {
810 		fprintf(stderr, "Signature is not valid\n");
811 		goto cleanup;
812 	}
813 
814 	ret = true;
815 
816 cleanup:
817 	if (trusted)
818 		free_fingerprint_list(trusted);
819 	if (revoked)
820 		free_fingerprint_list(revoked);
821 	if (sc) {
822 		free(sc->cert);
823 		free(sc->sig);
824 		free(sc->name);
825 		free(sc);
826 	}
827 
828 	return (ret);
829 }
830 
831 static int
832 bootstrap_pkg(bool force)
833 {
834 	int fd_pkg, fd_sig;
835 	int ret;
836 	char url[MAXPATHLEN];
837 	char tmppkg[MAXPATHLEN];
838 	char tmpsig[MAXPATHLEN];
839 	const char *packagesite;
840 	const char *signature_type;
841 	char pkgstatic[MAXPATHLEN];
842 
843 	fd_sig = -1;
844 	ret = -1;
845 
846 	if (config_string(PACKAGESITE, &packagesite) != 0) {
847 		warnx("No PACKAGESITE defined");
848 		return (-1);
849 	}
850 
851 	if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
852 		warnx("Error looking up SIGNATURE_TYPE");
853 		return (-1);
854 	}
855 
856 	printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
857 
858 	/* Support pkg+http:// for PACKAGESITE which is the new format
859 	   in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
860 	   no A record. */
861 	if (strncmp(URL_SCHEME_PREFIX, packagesite,
862 	    strlen(URL_SCHEME_PREFIX)) == 0)
863 		packagesite += strlen(URL_SCHEME_PREFIX);
864 	snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
865 
866 	snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
867 	    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
868 
869 	if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
870 		goto fetchfail;
871 
872 	if (signature_type != NULL &&
873 	    strcasecmp(signature_type, "NONE") != 0) {
874 		if (strcasecmp(signature_type, "FINGERPRINTS") == 0) {
875 
876 			snprintf(tmpsig, MAXPATHLEN, "%s/pkg.txz.sig.XXXXXX",
877 			    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
878 			snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.sig",
879 			    packagesite);
880 
881 			if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
882 				fprintf(stderr, "Signature for pkg not "
883 				    "available.\n");
884 				goto fetchfail;
885 			}
886 
887 			if (verify_signature(fd_pkg, fd_sig) == false)
888 				goto cleanup;
889 		} else if (strcasecmp(signature_type, "PUBKEY") == 0) {
890 
891 			snprintf(tmpsig, MAXPATHLEN,
892 			    "%s/pkg.txz.pubkeysig.XXXXXX",
893 			    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
894 			snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.pubkeysig",
895 			    packagesite);
896 
897 			if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
898 				fprintf(stderr, "Signature for pkg not "
899 				    "available.\n");
900 				goto fetchfail;
901 			}
902 
903 			if (verify_pubsignature(fd_pkg, fd_sig) == false)
904 				goto cleanup;
905 		} else {
906 			warnx("Signature type %s is not supported for "
907 			    "bootstrapping.", signature_type);
908 			goto cleanup;
909 		}
910 	}
911 
912 	if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
913 		ret = install_pkg_static(pkgstatic, tmppkg, force);
914 
915 	goto cleanup;
916 
917 fetchfail:
918 	warnx("Error fetching %s: %s", url, fetchLastErrString);
919 	if (fetchLastErrCode == FETCH_RESOLV) {
920 		fprintf(stderr, "Address resolution failed for %s.\n", packagesite);
921 		fprintf(stderr, "Consider changing PACKAGESITE.\n");
922 	} else {
923 		fprintf(stderr, "A pre-built version of pkg could not be found for "
924 		    "your system.\n");
925 		fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
926 		    "ports: 'ports-mgmt/pkg'.\n");
927 	}
928 
929 cleanup:
930 	if (fd_sig != -1) {
931 		close(fd_sig);
932 		unlink(tmpsig);
933 	}
934 
935 	if (fd_pkg != -1) {
936 		close(fd_pkg);
937 		unlink(tmppkg);
938 	}
939 
940 	return (ret);
941 }
942 
943 static const char confirmation_message[] =
944 "The package management tool is not yet installed on your system.\n"
945 "Do you want to fetch and install it now? [y/N]: ";
946 
947 static const char non_interactive_message[] =
948 "The package management tool is not yet installed on your system.\n"
949 "Please set ASSUME_ALWAYS_YES=yes environment variable to be able to bootstrap "
950 "in non-interactive (stdin not being a tty)\n";
951 
952 static int
953 pkg_query_yes_no(void)
954 {
955 	int ret, c;
956 
957 	fflush(stdout);
958 	c = getchar();
959 
960 	if (c == 'y' || c == 'Y')
961 		ret = 1;
962 	else
963 		ret = 0;
964 
965 	while (c != '\n' && c != EOF)
966 		c = getchar();
967 
968 	return (ret);
969 }
970 
971 static int
972 bootstrap_pkg_local(const char *pkgpath, bool force)
973 {
974 	char path[MAXPATHLEN];
975 	char pkgstatic[MAXPATHLEN];
976 	const char *signature_type;
977 	int fd_pkg, fd_sig, ret;
978 
979 	fd_sig = -1;
980 	ret = -1;
981 
982 	fd_pkg = open(pkgpath, O_RDONLY);
983 	if (fd_pkg == -1)
984 		err(EXIT_FAILURE, "Unable to open %s", pkgpath);
985 
986 	if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
987 		warnx("Error looking up SIGNATURE_TYPE");
988 		goto cleanup;
989 	}
990 	if (signature_type != NULL &&
991 	    strcasecmp(signature_type, "NONE") != 0) {
992 		if (strcasecmp(signature_type, "FINGERPRINTS") == 0) {
993 
994 			snprintf(path, sizeof(path), "%s.sig", pkgpath);
995 
996 			if ((fd_sig = open(path, O_RDONLY)) == -1) {
997 				fprintf(stderr, "Signature for pkg not "
998 				    "available.\n");
999 				goto cleanup;
1000 			}
1001 
1002 			if (verify_signature(fd_pkg, fd_sig) == false)
1003 				goto cleanup;
1004 
1005 		} else if (strcasecmp(signature_type, "PUBKEY") == 0) {
1006 
1007 			snprintf(path, sizeof(path), "%s.pubkeysig", pkgpath);
1008 
1009 			if ((fd_sig = open(path, O_RDONLY)) == -1) {
1010 				fprintf(stderr, "Signature for pkg not "
1011 				    "available.\n");
1012 				goto cleanup;
1013 			}
1014 
1015 			if (verify_pubsignature(fd_pkg, fd_sig) == false)
1016 				goto cleanup;
1017 
1018 		} else {
1019 			warnx("Signature type %s is not supported for "
1020 			    "bootstrapping.", signature_type);
1021 			goto cleanup;
1022 		}
1023 	}
1024 
1025 	if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
1026 		ret = install_pkg_static(pkgstatic, pkgpath, force);
1027 
1028 cleanup:
1029 	close(fd_pkg);
1030 	if (fd_sig != -1)
1031 		close(fd_sig);
1032 
1033 	return (ret);
1034 }
1035 
1036 int
1037 main(int argc, char *argv[])
1038 {
1039 	char pkgpath[MAXPATHLEN];
1040 	const char *pkgarg;
1041 	size_t len;
1042 	int i;
1043 	bool bootstrap_only, force, yes;
1044 
1045 	bootstrap_only = false;
1046 	force = false;
1047 	pkgarg = NULL;
1048 	yes = false;
1049 
1050 	if ((len = getlocalbase(pkgpath, MAXPATHLEN)) != 0) {
1051 		fprintf(stderr, "Cannot determine local path\n");
1052 		exit(EXIT_FAILURE);
1053 	}
1054 	strlcat(pkgpath, "/sbin/pkg", MAXPATHLEN - len);
1055 
1056 	if (argc > 1 && strcmp(argv[1], "bootstrap") == 0) {
1057 		bootstrap_only = true;
1058 		if (argc > 3) {
1059 			fprintf(stderr, "Too many arguments\nUsage: pkg bootstrap [-f]\n");
1060 			exit(EXIT_FAILURE);
1061 		}
1062 		if (argc == 3 && strcmp(argv[2], "-f") == 0) {
1063 			force = true;
1064 		} else if (argc == 3) {
1065 			fprintf(stderr, "Invalid argument specified\nUsage: pkg bootstrap [-f]\n");
1066 			exit(EXIT_FAILURE);
1067 		}
1068 	}
1069 
1070 	if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
1071 		/*
1072 		 * To allow 'pkg -N' to be used as a reliable test for whether
1073 		 * a system is configured to use pkg, don't bootstrap pkg
1074 		 * when that argument is given as argv[1].
1075 		 */
1076 		if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
1077 			errx(EXIT_FAILURE, "pkg is not installed");
1078 
1079 		config_init();
1080 
1081 		if (argc > 1 && strcmp(argv[1], "add") == 0) {
1082 			if (argc > 2 && strcmp(argv[2], "-f") == 0) {
1083 				force = true;
1084 				pkgarg = argv[3];
1085 			} else
1086 				pkgarg = argv[2];
1087 			if (pkgarg == NULL) {
1088 				fprintf(stderr, "Path to pkg.txz required\n");
1089 				exit(EXIT_FAILURE);
1090 			}
1091 			if (access(pkgarg, R_OK) == -1) {
1092 				fprintf(stderr, "No such file: %s\n", pkgarg);
1093 				exit(EXIT_FAILURE);
1094 			}
1095 			if (bootstrap_pkg_local(pkgarg, force) != 0)
1096 				exit(EXIT_FAILURE);
1097 			exit(EXIT_SUCCESS);
1098 		}
1099 		/*
1100 		 * Do not ask for confirmation if either of stdin or stdout is
1101 		 * not tty. Check the environment to see if user has answer
1102 		 * tucked in there already.
1103 		 */
1104 		config_bool(ASSUME_ALWAYS_YES, &yes);
1105 		if (!yes) {
1106 			for (i = 1; i < argc; i++) {
1107 				if (strcmp(argv[i], "-y") == 0 ||
1108 				    strcmp(argv[i], "--yes") == 0) {
1109 					yes = true;
1110 					break;
1111 				}
1112 			}
1113 		}
1114 		if (!yes) {
1115 			if (!isatty(fileno(stdin))) {
1116 				fprintf(stderr, non_interactive_message);
1117 				exit(EXIT_FAILURE);
1118 			}
1119 
1120 			printf("%s", confirmation_message);
1121 			if (pkg_query_yes_no() == 0)
1122 				exit(EXIT_FAILURE);
1123 		}
1124 		if (bootstrap_pkg(force) != 0)
1125 			exit(EXIT_FAILURE);
1126 		config_finish();
1127 
1128 		if (bootstrap_only)
1129 			exit(EXIT_SUCCESS);
1130 	} else if (bootstrap_only) {
1131 		printf("pkg already bootstrapped at %s\n", pkgpath);
1132 		exit(EXIT_SUCCESS);
1133 	}
1134 
1135 	execv(pkgpath, argv);
1136 
1137 	/* NOT REACHED */
1138 	return (EXIT_FAILURE);
1139 }
1140