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