xref: /freebsd/usr.sbin/pkg/pkg.c (revision 46c599340f187db577b9212ab18022f3c7380c68)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
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/param.h>
31 #include <sys/queue.h>
32 #include <sys/types.h>
33 #include <sys/wait.h>
34 
35 #include <archive.h>
36 #include <archive_entry.h>
37 #include <dirent.h>
38 #include <err.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <fetch.h>
42 #include <getopt.h>
43 #include <libutil.h>
44 #include <paths.h>
45 #include <stdbool.h>
46 #include <stdlib.h>
47 #include <stdio.h>
48 #include <string.h>
49 #include <ucl.h>
50 
51 #include <openssl/err.h>
52 #include <openssl/ssl.h>
53 
54 #include "dns_utils.h"
55 #include "config.h"
56 #include "hash.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 static const char *bootstrap_names []  = {
85 	"pkg.pkg",
86 	"pkg.txz",
87 	NULL
88 };
89 
90 STAILQ_HEAD(fingerprint_list, fingerprint);
91 
92 static int debug;
93 
94 static int
95 extract_pkg_static(int fd, char *p, int sz)
96 {
97 	struct archive *a;
98 	struct archive_entry *ae;
99 	char *end;
100 	int ret, r;
101 
102 	ret = -1;
103 	a = archive_read_new();
104 	if (a == NULL) {
105 		warn("archive_read_new");
106 		return (ret);
107 	}
108 	archive_read_support_filter_all(a);
109 	archive_read_support_format_tar(a);
110 
111 	if (lseek(fd, 0, 0) == -1) {
112 		warn("lseek");
113 		goto cleanup;
114 	}
115 
116 	if (archive_read_open_fd(a, fd, 4096) != ARCHIVE_OK) {
117 		warnx("archive_read_open_fd: %s", archive_error_string(a));
118 		goto cleanup;
119 	}
120 
121 	ae = NULL;
122 	while ((r = archive_read_next_header(a, &ae)) == ARCHIVE_OK) {
123 		end = strrchr(archive_entry_pathname(ae), '/');
124 		if (end == NULL)
125 			continue;
126 
127 		if (strcmp(end, "/pkg-static") == 0) {
128 			r = archive_read_extract(a, ae,
129 			    ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM |
130 			    ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_ACL |
131 			    ARCHIVE_EXTRACT_FFLAGS | ARCHIVE_EXTRACT_XATTR);
132 			strlcpy(p, archive_entry_pathname(ae), sz);
133 			break;
134 		}
135 	}
136 
137 	if (r == ARCHIVE_OK)
138 		ret = 0;
139 	else
140 		warnx("failed to extract pkg-static: %s",
141 		    archive_error_string(a));
142 
143 cleanup:
144 	archive_read_free(a);
145 	return (ret);
146 
147 }
148 
149 static int
150 install_pkg_static(const char *path, const char *pkgpath, bool force)
151 {
152 	int pstat;
153 	pid_t pid;
154 
155 	switch ((pid = fork())) {
156 	case -1:
157 		return (-1);
158 	case 0:
159 		if (force)
160 			execl(path, "pkg-static", "add", "-f", pkgpath,
161 			    (char *)NULL);
162 		else
163 			execl(path, "pkg-static", "add", pkgpath,
164 			    (char *)NULL);
165 		_exit(1);
166 	default:
167 		break;
168 	}
169 
170 	while (waitpid(pid, &pstat, 0) == -1)
171 		if (errno != EINTR)
172 			return (-1);
173 
174 	if (WEXITSTATUS(pstat))
175 		return (WEXITSTATUS(pstat));
176 	else if (WIFSIGNALED(pstat))
177 		return (128 & (WTERMSIG(pstat)));
178 	return (pstat);
179 }
180 
181 static int
182 fetch_to_fd(const char *url, char *path, const char *fetchOpts)
183 {
184 	struct url *u;
185 	struct dns_srvinfo *mirrors, *current;
186 	struct url_stat st;
187 	FILE *remote;
188 	/* To store _https._tcp. + hostname + \0 */
189 	int fd;
190 	int retry, max_retry;
191 	ssize_t r;
192 	char buf[10240];
193 	char zone[MAXHOSTNAMELEN + 13];
194 	static const char *mirror_type = NULL;
195 
196 	max_retry = 3;
197 	current = mirrors = NULL;
198 	remote = NULL;
199 
200 	if (mirror_type == NULL && config_string(MIRROR_TYPE, &mirror_type)
201 	    != 0) {
202 		warnx("No MIRROR_TYPE defined");
203 		return (-1);
204 	}
205 
206 	if ((fd = mkstemp(path)) == -1) {
207 		warn("mkstemp()");
208 		return (-1);
209 	}
210 
211 	retry = max_retry;
212 
213 	if ((u = fetchParseURL(url)) == NULL) {
214 		warn("fetchParseURL('%s')", url);
215 		return (-1);
216 	}
217 
218 	while (remote == NULL) {
219 		if (retry == max_retry) {
220 			if (strcmp(u->scheme, "file") != 0 &&
221 			    strcasecmp(mirror_type, "srv") == 0) {
222 				snprintf(zone, sizeof(zone),
223 				    "_%s._tcp.%s", u->scheme, u->host);
224 				mirrors = dns_getsrvinfo(zone);
225 				current = mirrors;
226 			}
227 		}
228 
229 		if (mirrors != NULL) {
230 			strlcpy(u->host, current->host, sizeof(u->host));
231 			u->port = current->port;
232 		}
233 
234 		remote = fetchXGet(u, &st, fetchOpts);
235 		if (remote == NULL) {
236 			--retry;
237 			if (retry <= 0)
238 				goto fetchfail;
239 			if (mirrors != NULL) {
240 				current = current->next;
241 				if (current == NULL)
242 					current = mirrors;
243 			}
244 		}
245 	}
246 
247 	while ((r = fread(buf, 1, sizeof(buf), remote)) > 0) {
248 		if (write(fd, buf, r) != r) {
249 			warn("write()");
250 			goto fetchfail;
251 		}
252 	}
253 
254 	if (r != 0) {
255 		warn("An error occurred while fetching pkg(8)");
256 		goto fetchfail;
257 	}
258 
259 	if (ferror(remote))
260 		goto fetchfail;
261 
262 	goto cleanup;
263 
264 fetchfail:
265 	if (fd != -1) {
266 		close(fd);
267 		fd = -1;
268 		unlink(path);
269 	}
270 
271 cleanup:
272 	if (remote != NULL)
273 		fclose(remote);
274 
275 	return fd;
276 }
277 
278 static struct fingerprint *
279 parse_fingerprint(ucl_object_t *obj)
280 {
281 	const ucl_object_t *cur;
282 	ucl_object_iter_t it = NULL;
283 	const char *function, *fp, *key;
284 	struct fingerprint *f;
285 	hash_t fct = HASH_UNKNOWN;
286 
287 	function = fp = NULL;
288 
289 	while ((cur = ucl_iterate_object(obj, &it, true))) {
290 		key = ucl_object_key(cur);
291 		if (cur->type != UCL_STRING)
292 			continue;
293 		if (strcasecmp(key, "function") == 0) {
294 			function = ucl_object_tostring(cur);
295 			continue;
296 		}
297 		if (strcasecmp(key, "fingerprint") == 0) {
298 			fp = ucl_object_tostring(cur);
299 			continue;
300 		}
301 	}
302 
303 	if (fp == NULL || function == NULL)
304 		return (NULL);
305 
306 	if (strcasecmp(function, "sha256") == 0)
307 		fct = HASH_SHA256;
308 
309 	if (fct == HASH_UNKNOWN) {
310 		warnx("Unsupported hashing function: %s", function);
311 		return (NULL);
312 	}
313 
314 	f = calloc(1, sizeof(struct fingerprint));
315 	f->type = fct;
316 	strlcpy(f->hash, fp, sizeof(f->hash));
317 
318 	return (f);
319 }
320 
321 static void
322 free_fingerprint_list(struct fingerprint_list* list)
323 {
324 	struct fingerprint *fingerprint, *tmp;
325 
326 	STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
327 		free(fingerprint->name);
328 		free(fingerprint);
329 	}
330 	free(list);
331 }
332 
333 static struct fingerprint *
334 load_fingerprint(const char *dir, const char *filename)
335 {
336 	ucl_object_t *obj = NULL;
337 	struct ucl_parser *p = NULL;
338 	struct fingerprint *f;
339 	char path[MAXPATHLEN];
340 
341 	f = NULL;
342 
343 	snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
344 
345 	p = ucl_parser_new(0);
346 	if (!ucl_parser_add_file(p, path)) {
347 		warnx("%s: %s", path, ucl_parser_get_error(p));
348 		ucl_parser_free(p);
349 		return (NULL);
350 	}
351 
352 	obj = ucl_parser_get_object(p);
353 
354 	if (obj->type == UCL_OBJECT)
355 		f = parse_fingerprint(obj);
356 
357 	if (f != NULL)
358 		f->name = strdup(filename);
359 
360 	ucl_object_unref(obj);
361 	ucl_parser_free(p);
362 
363 	return (f);
364 }
365 
366 static struct fingerprint_list *
367 load_fingerprints(const char *path, int *count)
368 {
369 	DIR *d;
370 	struct dirent *ent;
371 	struct fingerprint *finger;
372 	struct fingerprint_list *fingerprints;
373 
374 	*count = 0;
375 
376 	fingerprints = calloc(1, sizeof(struct fingerprint_list));
377 	if (fingerprints == NULL)
378 		return (NULL);
379 	STAILQ_INIT(fingerprints);
380 
381 	if ((d = opendir(path)) == NULL) {
382 		free(fingerprints);
383 
384 		return (NULL);
385 	}
386 
387 	while ((ent = readdir(d))) {
388 		if (strcmp(ent->d_name, ".") == 0 ||
389 		    strcmp(ent->d_name, "..") == 0)
390 			continue;
391 		finger = load_fingerprint(path, ent->d_name);
392 		if (finger != NULL) {
393 			STAILQ_INSERT_TAIL(fingerprints, finger, next);
394 			++(*count);
395 		}
396 	}
397 
398 	closedir(d);
399 
400 	return (fingerprints);
401 }
402 
403 static EVP_PKEY *
404 load_public_key_file(const char *file)
405 {
406 	EVP_PKEY *pkey;
407 	BIO *bp;
408 	char errbuf[1024];
409 
410 	bp = BIO_new_file(file, "r");
411 	if (!bp)
412 		errx(EXIT_FAILURE, "Unable to read %s", file);
413 
414 	if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
415 		warnx("ici: %s", ERR_error_string(ERR_get_error(), errbuf));
416 
417 	BIO_free(bp);
418 
419 	return (pkey);
420 }
421 
422 static EVP_PKEY *
423 load_public_key_buf(const unsigned char *cert, int certlen)
424 {
425 	EVP_PKEY *pkey;
426 	BIO *bp;
427 	char errbuf[1024];
428 
429 	bp = BIO_new_mem_buf(__DECONST(void *, cert), certlen);
430 
431 	if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
432 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
433 
434 	BIO_free(bp);
435 
436 	return (pkey);
437 }
438 
439 static bool
440 rsa_verify_cert(int fd, const char *sigfile, const unsigned char *key,
441     int keylen, unsigned char *sig, int siglen)
442 {
443 	EVP_MD_CTX *mdctx;
444 	EVP_PKEY *pkey;
445 	char *sha256;
446 	char errbuf[1024];
447 	bool ret;
448 
449 	sha256 = NULL;
450 	pkey = NULL;
451 	mdctx = NULL;
452 	ret = false;
453 
454 	SSL_load_error_strings();
455 
456 	/* Compute SHA256 of the package. */
457 	if (lseek(fd, 0, 0) == -1) {
458 		warn("lseek");
459 		goto cleanup;
460 	}
461 	if ((sha256 = sha256_fd(fd)) == NULL) {
462 		warnx("Error creating SHA256 hash for package");
463 		goto cleanup;
464 	}
465 
466 	if (sigfile != NULL) {
467 		if ((pkey = load_public_key_file(sigfile)) == NULL) {
468 			warnx("Error reading public key");
469 			goto cleanup;
470 		}
471 	} else {
472 		if ((pkey = load_public_key_buf(key, keylen)) == NULL) {
473 			warnx("Error reading public key");
474 			goto cleanup;
475 		}
476 	}
477 
478 	/* Verify signature of the SHA256(pkg) is valid. */
479 	if ((mdctx = EVP_MD_CTX_create()) == NULL) {
480 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
481 		goto error;
482 	}
483 
484 	if (EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
485 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
486 		goto error;
487 	}
488 	if (EVP_DigestVerifyUpdate(mdctx, sha256, strlen(sha256)) != 1) {
489 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
490 		goto error;
491 	}
492 
493 	if (EVP_DigestVerifyFinal(mdctx, sig, siglen) != 1) {
494 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
495 		goto error;
496 	}
497 
498 	ret = true;
499 	printf("done\n");
500 	goto cleanup;
501 
502 error:
503 	printf("failed\n");
504 
505 cleanup:
506 	free(sha256);
507 	if (pkey)
508 		EVP_PKEY_free(pkey);
509 	if (mdctx)
510 		EVP_MD_CTX_destroy(mdctx);
511 	ERR_free_strings();
512 
513 	return (ret);
514 }
515 
516 static struct pubkey *
517 read_pubkey(int fd)
518 {
519 	struct pubkey *pk;
520 	char *sigb;
521 	size_t sigsz;
522 	FILE *sig;
523 	char buf[4096];
524 	int r;
525 
526 	if (lseek(fd, 0, 0) == -1) {
527 		warn("lseek");
528 		return (NULL);
529 	}
530 
531 	sigsz = 0;
532 	sigb = NULL;
533 	sig = open_memstream(&sigb, &sigsz);
534 	if (sig == NULL)
535 		err(EXIT_FAILURE, "open_memstream()");
536 
537 	while ((r = read(fd, buf, sizeof(buf))) >0) {
538 		fwrite(buf, 1, r, sig);
539 	}
540 
541 	fclose(sig);
542 	pk = calloc(1, sizeof(struct pubkey));
543 	pk->siglen = sigsz;
544 	pk->sig = calloc(1, pk->siglen);
545 	memcpy(pk->sig, sigb, pk->siglen);
546 	free(sigb);
547 
548 	return (pk);
549 }
550 
551 static struct sig_cert *
552 parse_cert(int fd) {
553 	int my_fd;
554 	struct sig_cert *sc;
555 	FILE *fp, *sigfp, *certfp, *tmpfp;
556 	char *line;
557 	char *sig, *cert;
558 	size_t linecap, sigsz, certsz;
559 	ssize_t linelen;
560 
561 	sc = NULL;
562 	line = NULL;
563 	linecap = 0;
564 	sig = cert = NULL;
565 	sigfp = certfp = tmpfp = NULL;
566 
567 	if (lseek(fd, 0, 0) == -1) {
568 		warn("lseek");
569 		return (NULL);
570 	}
571 
572 	/* Duplicate the fd so that fclose(3) does not close it. */
573 	if ((my_fd = dup(fd)) == -1) {
574 		warnx("dup");
575 		return (NULL);
576 	}
577 
578 	if ((fp = fdopen(my_fd, "rb")) == NULL) {
579 		warn("fdopen");
580 		close(my_fd);
581 		return (NULL);
582 	}
583 
584 	sigsz = certsz = 0;
585 	sigfp = open_memstream(&sig, &sigsz);
586 	if (sigfp == NULL)
587 		err(EXIT_FAILURE, "open_memstream()");
588 	certfp = open_memstream(&cert, &certsz);
589 	if (certfp == NULL)
590 		err(EXIT_FAILURE, "open_memstream()");
591 
592 	while ((linelen = getline(&line, &linecap, fp)) > 0) {
593 		if (strcmp(line, "SIGNATURE\n") == 0) {
594 			tmpfp = sigfp;
595 			continue;
596 		} else if (strcmp(line, "CERT\n") == 0) {
597 			tmpfp = certfp;
598 			continue;
599 		} else if (strcmp(line, "END\n") == 0) {
600 			break;
601 		}
602 		if (tmpfp != NULL)
603 			fwrite(line, 1, linelen, tmpfp);
604 	}
605 
606 	fclose(fp);
607 	fclose(sigfp);
608 	fclose(certfp);
609 
610 	sc = calloc(1, sizeof(struct sig_cert));
611 	sc->siglen = sigsz -1; /* Trim out unrelated trailing newline */
612 	sc->sig = sig;
613 
614 	sc->certlen = certsz;
615 	sc->cert = cert;
616 
617 	return (sc);
618 }
619 
620 static bool
621 verify_pubsignature(int fd_pkg, int fd_sig)
622 {
623 	struct pubkey *pk;
624 	const char *pubkey;
625 	bool ret;
626 
627 	pk = NULL;
628 	pubkey = NULL;
629 	ret = false;
630 	if (config_string(PUBKEY, &pubkey) != 0) {
631 		warnx("No CONFIG_PUBKEY defined");
632 		goto cleanup;
633 	}
634 
635 	if ((pk = read_pubkey(fd_sig)) == NULL) {
636 		warnx("Error reading signature");
637 		goto cleanup;
638 	}
639 
640 	/* Verify the signature. */
641 	printf("Verifying signature with public key %s... ", pubkey);
642 	if (rsa_verify_cert(fd_pkg, pubkey, NULL, 0, pk->sig,
643 	    pk->siglen) == false) {
644 		fprintf(stderr, "Signature is not valid\n");
645 		goto cleanup;
646 	}
647 
648 	ret = true;
649 
650 cleanup:
651 	if (pk) {
652 		free(pk->sig);
653 		free(pk);
654 	}
655 
656 	return (ret);
657 }
658 
659 static bool
660 verify_signature(int fd_pkg, int fd_sig)
661 {
662 	struct fingerprint_list *trusted, *revoked;
663 	struct fingerprint *fingerprint;
664 	struct sig_cert *sc;
665 	bool ret;
666 	int trusted_count, revoked_count;
667 	const char *fingerprints;
668 	char path[MAXPATHLEN];
669 	char *hash;
670 
671 	hash = NULL;
672 	sc = NULL;
673 	trusted = revoked = NULL;
674 	ret = false;
675 
676 	/* Read and parse fingerprints. */
677 	if (config_string(FINGERPRINTS, &fingerprints) != 0) {
678 		warnx("No CONFIG_FINGERPRINTS defined");
679 		goto cleanup;
680 	}
681 
682 	snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
683 	if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
684 		warnx("Error loading trusted certificates");
685 		goto cleanup;
686 	}
687 
688 	if (trusted_count == 0 || trusted == NULL) {
689 		fprintf(stderr, "No trusted certificates found.\n");
690 		goto cleanup;
691 	}
692 
693 	snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
694 	if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
695 		warnx("Error loading revoked certificates");
696 		goto cleanup;
697 	}
698 
699 	/* Read certificate and signature in. */
700 	if ((sc = parse_cert(fd_sig)) == NULL) {
701 		warnx("Error parsing certificate");
702 		goto cleanup;
703 	}
704 	/* Explicitly mark as non-trusted until proven otherwise. */
705 	sc->trusted = false;
706 
707 	/* Parse signature and pubkey out of the certificate */
708 	hash = sha256_buf(sc->cert, sc->certlen);
709 
710 	/* Check if this hash is revoked */
711 	if (revoked != NULL) {
712 		STAILQ_FOREACH(fingerprint, revoked, next) {
713 			if (strcasecmp(fingerprint->hash, hash) == 0) {
714 				fprintf(stderr, "The package was signed with "
715 				    "revoked certificate %s\n",
716 				    fingerprint->name);
717 				goto cleanup;
718 			}
719 		}
720 	}
721 
722 	STAILQ_FOREACH(fingerprint, trusted, next) {
723 		if (strcasecmp(fingerprint->hash, hash) == 0) {
724 			sc->trusted = true;
725 			sc->name = strdup(fingerprint->name);
726 			break;
727 		}
728 	}
729 
730 	if (sc->trusted == false) {
731 		fprintf(stderr, "No trusted fingerprint found matching "
732 		    "package's certificate\n");
733 		goto cleanup;
734 	}
735 
736 	/* Verify the signature. */
737 	printf("Verifying signature with trusted certificate %s... ", sc->name);
738 	if (rsa_verify_cert(fd_pkg, NULL, sc->cert, sc->certlen, sc->sig,
739 	    sc->siglen) == false) {
740 		fprintf(stderr, "Signature is not valid\n");
741 		goto cleanup;
742 	}
743 
744 	ret = true;
745 
746 cleanup:
747 	free(hash);
748 	if (trusted)
749 		free_fingerprint_list(trusted);
750 	if (revoked)
751 		free_fingerprint_list(revoked);
752 	if (sc) {
753 		free(sc->cert);
754 		free(sc->sig);
755 		free(sc->name);
756 		free(sc);
757 	}
758 
759 	return (ret);
760 }
761 
762 static int
763 bootstrap_pkg(bool force, const char *fetchOpts)
764 {
765 	int fd_pkg, fd_sig;
766 	int ret;
767 	char url[MAXPATHLEN];
768 	char tmppkg[MAXPATHLEN];
769 	char tmpsig[MAXPATHLEN];
770 	const char *packagesite;
771 	const char *signature_type;
772 	char pkgstatic[MAXPATHLEN];
773 	const char *bootstrap_name;
774 
775 	fd_sig = -1;
776 	ret = -1;
777 
778 	if (config_string(PACKAGESITE, &packagesite) != 0) {
779 		warnx("No PACKAGESITE defined");
780 		return (-1);
781 	}
782 
783 	if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
784 		warnx("Error looking up SIGNATURE_TYPE");
785 		return (-1);
786 	}
787 
788 	printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
789 
790 	/* Support pkg+http:// for PACKAGESITE which is the new format
791 	   in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
792 	   no A record. */
793 	if (strncmp(URL_SCHEME_PREFIX, packagesite,
794 	    strlen(URL_SCHEME_PREFIX)) == 0)
795 		packagesite += strlen(URL_SCHEME_PREFIX);
796 	for (int j = 0; bootstrap_names[j] != NULL; j++) {
797 		bootstrap_name = bootstrap_names[j];
798 
799 		snprintf(url, MAXPATHLEN, "%s/Latest/%s", packagesite, bootstrap_name);
800 		snprintf(tmppkg, MAXPATHLEN, "%s/%s.XXXXXX",
801 		    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP,
802 		    bootstrap_name);
803 		if ((fd_pkg = fetch_to_fd(url, tmppkg, fetchOpts)) != -1)
804 			break;
805 		bootstrap_name = NULL;
806 	}
807 	if (bootstrap_name == NULL)
808 		goto fetchfail;
809 
810 	if (signature_type != NULL &&
811 	    strcasecmp(signature_type, "NONE") != 0) {
812 		if (strcasecmp(signature_type, "FINGERPRINTS") == 0) {
813 
814 			snprintf(tmpsig, MAXPATHLEN, "%s/%s.sig.XXXXXX",
815 			    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP,
816 			    bootstrap_name);
817 			snprintf(url, MAXPATHLEN, "%s/Latest/%s.sig",
818 			    packagesite, bootstrap_name);
819 
820 			if ((fd_sig = fetch_to_fd(url, tmpsig, fetchOpts)) == -1) {
821 				fprintf(stderr, "Signature for pkg not "
822 				    "available.\n");
823 				goto fetchfail;
824 			}
825 
826 			if (verify_signature(fd_pkg, fd_sig) == false)
827 				goto cleanup;
828 		} else if (strcasecmp(signature_type, "PUBKEY") == 0) {
829 
830 			snprintf(tmpsig, MAXPATHLEN,
831 			    "%s/%s.pubkeysig.XXXXXX",
832 			    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP,
833 			    bootstrap_name);
834 			snprintf(url, MAXPATHLEN, "%s/Latest/%s.pubkeysig",
835 			    packagesite, bootstrap_name);
836 
837 			if ((fd_sig = fetch_to_fd(url, tmpsig, fetchOpts)) == -1) {
838 				fprintf(stderr, "Signature for pkg not "
839 				    "available.\n");
840 				goto fetchfail;
841 			}
842 
843 			if (verify_pubsignature(fd_pkg, fd_sig) == false)
844 				goto cleanup;
845 		} else {
846 			warnx("Signature type %s is not supported for "
847 			    "bootstrapping.", signature_type);
848 			goto cleanup;
849 		}
850 	}
851 
852 	if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
853 		ret = install_pkg_static(pkgstatic, tmppkg, force);
854 
855 	goto cleanup;
856 
857 fetchfail:
858 	warnx("Error fetching %s: %s", url, fetchLastErrString);
859 	if (fetchLastErrCode == FETCH_RESOLV) {
860 		fprintf(stderr, "Address resolution failed for %s.\n", packagesite);
861 		fprintf(stderr, "Consider changing PACKAGESITE.\n");
862 	} else {
863 		fprintf(stderr, "A pre-built version of pkg could not be found for "
864 		    "your system.\n");
865 		fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
866 		    "ports: 'ports-mgmt/pkg'.\n");
867 	}
868 
869 cleanup:
870 	if (fd_sig != -1) {
871 		close(fd_sig);
872 		unlink(tmpsig);
873 	}
874 
875 	if (fd_pkg != -1) {
876 		close(fd_pkg);
877 		unlink(tmppkg);
878 	}
879 
880 	return (ret);
881 }
882 
883 static const char confirmation_message[] =
884 "The package management tool is not yet installed on your system.\n"
885 "Do you want to fetch and install it now? [y/N]: ";
886 
887 static const char non_interactive_message[] =
888 "The package management tool is not yet installed on your system.\n"
889 "Please set ASSUME_ALWAYS_YES=yes environment variable to be able to bootstrap "
890 "in non-interactive (stdin not being a tty)\n";
891 
892 static const char args_bootstrap_message[] =
893 "Too many arguments\n"
894 "Usage: pkg [-4|-6] bootstrap [-f] [-y]\n";
895 
896 static const char args_add_message[] =
897 "Too many arguments\n"
898 "Usage: pkg add [-f] [-y] {pkg.txz}\n";
899 
900 static int
901 pkg_query_yes_no(void)
902 {
903 	int ret, c;
904 
905 	fflush(stdout);
906 	c = getchar();
907 
908 	if (c == 'y' || c == 'Y')
909 		ret = 1;
910 	else
911 		ret = 0;
912 
913 	while (c != '\n' && c != EOF)
914 		c = getchar();
915 
916 	return (ret);
917 }
918 
919 static int
920 bootstrap_pkg_local(const char *pkgpath, bool force)
921 {
922 	char path[MAXPATHLEN];
923 	char pkgstatic[MAXPATHLEN];
924 	const char *signature_type;
925 	int fd_pkg, fd_sig, ret;
926 
927 	fd_sig = -1;
928 	ret = -1;
929 
930 	fd_pkg = open(pkgpath, O_RDONLY);
931 	if (fd_pkg == -1)
932 		err(EXIT_FAILURE, "Unable to open %s", pkgpath);
933 
934 	if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
935 		warnx("Error looking up SIGNATURE_TYPE");
936 		goto cleanup;
937 	}
938 	if (signature_type != NULL &&
939 	    strcasecmp(signature_type, "NONE") != 0) {
940 		if (strcasecmp(signature_type, "FINGERPRINTS") == 0) {
941 
942 			snprintf(path, sizeof(path), "%s.sig", pkgpath);
943 
944 			if ((fd_sig = open(path, O_RDONLY)) == -1) {
945 				fprintf(stderr, "Signature for pkg not "
946 				    "available.\n");
947 				goto cleanup;
948 			}
949 
950 			if (verify_signature(fd_pkg, fd_sig) == false)
951 				goto cleanup;
952 
953 		} else if (strcasecmp(signature_type, "PUBKEY") == 0) {
954 
955 			snprintf(path, sizeof(path), "%s.pubkeysig", pkgpath);
956 
957 			if ((fd_sig = open(path, O_RDONLY)) == -1) {
958 				fprintf(stderr, "Signature for pkg not "
959 				    "available.\n");
960 				goto cleanup;
961 			}
962 
963 			if (verify_pubsignature(fd_pkg, fd_sig) == false)
964 				goto cleanup;
965 
966 		} else {
967 			warnx("Signature type %s is not supported for "
968 			    "bootstrapping.", signature_type);
969 			goto cleanup;
970 		}
971 	}
972 
973 	if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
974 		ret = install_pkg_static(pkgstatic, pkgpath, force);
975 
976 cleanup:
977 	close(fd_pkg);
978 	if (fd_sig != -1)
979 		close(fd_sig);
980 
981 	return (ret);
982 }
983 
984 #define	PKG_NAME	"pkg"
985 #define	PKG_DEVEL_NAME	PKG_NAME "-devel"
986 #define	PKG_PKG		PKG_NAME "."
987 
988 static bool
989 pkg_is_pkg_pkg(const char *pkg)
990 {
991 	char *vstart, *basename;
992 	size_t namelen;
993 
994 	/* Strip path. */
995 	if ((basename = strrchr(pkg, '/')) != NULL)
996 		pkg = basename + 1;
997 
998 	/*
999 	 * Chop off the final "-" (version delimiter) and check the name that
1000 	 * precedes it.  If we didn't have a version delimiter, it must be the
1001 	 * pkg.$archive short form but we'll check it anyways.  pkg-devel short
1002 	 * form will look like a pkg archive with 'devel' version, but that's
1003 	 * OK.  We otherwise assumed that non-pkg packages will always have a
1004 	 * version component.
1005 	 */
1006 	vstart = strrchr(pkg, '-');
1007 	if (vstart == NULL) {
1008 		return (strlen(pkg) > sizeof(PKG_PKG) - 1 &&
1009 		    strncmp(pkg, PKG_PKG, sizeof(PKG_PKG) - 1) == 0);
1010 	}
1011 
1012 	namelen = vstart - pkg;
1013 	if (namelen == sizeof(PKG_NAME) - 1 &&
1014 	    strncmp(pkg, PKG_NAME, sizeof(PKG_NAME) - 1) == 0)
1015 		return (true);
1016 	if (namelen == sizeof(PKG_DEVEL_NAME) - 1 &&
1017 	    strncmp(pkg, PKG_DEVEL_NAME, sizeof(PKG_DEVEL_NAME) - 1) == 0)
1018 		return (true);
1019 	return (false);
1020 }
1021 
1022 int
1023 main(int argc, char *argv[])
1024 {
1025 	char pkgpath[MAXPATHLEN];
1026 	const char *pkgarg, *repo_name;
1027 	bool activation_test, add_pkg, bootstrap_only, force, yes;
1028 	signed char ch;
1029 	const char *fetchOpts;
1030 	char *command;
1031 
1032 	activation_test = false;
1033 	add_pkg = false;
1034 	bootstrap_only = false;
1035 	command = NULL;
1036 	fetchOpts = "";
1037 	force = false;
1038 	pkgarg = NULL;
1039 	repo_name = NULL;
1040 	yes = false;
1041 
1042 	struct option longopts[] = {
1043 		{ "debug",		no_argument,		NULL,	'd' },
1044 		{ "force",		no_argument,		NULL,	'f' },
1045 		{ "only-ipv4",		no_argument,		NULL,	'4' },
1046 		{ "only-ipv6",		no_argument,		NULL,	'6' },
1047 		{ "yes",		no_argument,		NULL,	'y' },
1048 		{ NULL,			0,			NULL,	0   },
1049 	};
1050 
1051 	snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg", getlocalbase());
1052 
1053 	while ((ch = getopt_long(argc, argv, "-:dfr::yN46", longopts, NULL)) != -1) {
1054 		switch (ch) {
1055 		case 'd':
1056 			debug++;
1057 			break;
1058 		case 'f':
1059 			force = true;
1060 			break;
1061 		case 'N':
1062 			activation_test = true;
1063 			break;
1064 		case 'y':
1065 			yes = true;
1066 			break;
1067 		case '4':
1068 			fetchOpts = "4";
1069 			break;
1070 		case '6':
1071 			fetchOpts = "6";
1072 			break;
1073 		case 'r':
1074 			/*
1075 			 * The repository can only be specified for an explicit
1076 			 * bootstrap request at this time, so that we don't
1077 			 * confuse the user if they're trying to use a verb that
1078 			 * has some other conflicting meaning but we need to
1079 			 * bootstrap.
1080 			 *
1081 			 * For that reason, we specify that -r has an optional
1082 			 * argument above and process the next index ourselves.
1083 			 * This is mostly significant because getopt(3) will
1084 			 * otherwise eat the next argument, which could be
1085 			 * something we need to try and make sense of.
1086 			 *
1087 			 * At worst this gets us false positives that we ignore
1088 			 * in other contexts, and we have to do a little fudging
1089 			 * in order to support separating -r from the reponame
1090 			 * with a space since it's not actually optional in
1091 			 * the bootstrap/add sense.
1092 			 */
1093 			if (add_pkg || bootstrap_only) {
1094 				if (optarg != NULL) {
1095 					repo_name = optarg;
1096 				} else if (optind < argc) {
1097 					repo_name = argv[optind];
1098 				}
1099 
1100 				if (repo_name == NULL || *repo_name == '\0') {
1101 					fprintf(stderr,
1102 					    "Must specify a repository with -r!\n");
1103 					exit(EXIT_FAILURE);
1104 				}
1105 
1106 				if (optarg == NULL) {
1107 					/* Advance past repo name. */
1108 					optreset = 1;
1109 					optind++;
1110 				}
1111 			}
1112 			break;
1113 		case 1:
1114 			// Non-option arguments, first one is the command
1115 			if (command == NULL) {
1116 				command = argv[optind-1];
1117 				if (strcmp(command, "add") == 0) {
1118 					add_pkg = true;
1119 				}
1120 				else if (strcmp(command, "bootstrap") == 0) {
1121 					bootstrap_only = true;
1122 				}
1123 			}
1124 			// bootstrap doesn't accept other arguments
1125 			else if (bootstrap_only) {
1126 				fprintf(stderr, args_bootstrap_message);
1127 				exit(EXIT_FAILURE);
1128 			}
1129 			else if (add_pkg && pkgarg != NULL) {
1130 				/*
1131 				 * Additional arguments also means it's not a
1132 				 * local bootstrap request.
1133 				 */
1134 				add_pkg = false;
1135 			}
1136 			else if (add_pkg) {
1137 				/*
1138 				 * If it's not a request for pkg or pkg-devel,
1139 				 * then we must assume they were trying to
1140 				 * install some other local package and we
1141 				 * should try to bootstrap from the repo.
1142 				 */
1143 				if (!pkg_is_pkg_pkg(argv[optind-1])) {
1144 					add_pkg = false;
1145 				} else {
1146 					pkgarg = argv[optind-1];
1147 				}
1148 			}
1149 			break;
1150 		default:
1151 			break;
1152 		}
1153 	}
1154 	if (debug > 1)
1155 		fetchDebug = 1;
1156 
1157 	if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
1158 		/*
1159 		 * To allow 'pkg -N' to be used as a reliable test for whether
1160 		 * a system is configured to use pkg, don't bootstrap pkg
1161 		 * when that option is passed.
1162 		 */
1163 		if (activation_test)
1164 			errx(EXIT_FAILURE, "pkg is not installed");
1165 
1166 		config_init(repo_name);
1167 
1168 		if (add_pkg) {
1169 			if (pkgarg == NULL) {
1170 				fprintf(stderr, "Path to pkg.txz required\n");
1171 				exit(EXIT_FAILURE);
1172 			}
1173 			if (access(pkgarg, R_OK) == -1) {
1174 				fprintf(stderr, "No such file: %s\n", pkgarg);
1175 				exit(EXIT_FAILURE);
1176 			}
1177 			if (bootstrap_pkg_local(pkgarg, force) != 0)
1178 				exit(EXIT_FAILURE);
1179 			exit(EXIT_SUCCESS);
1180 		}
1181 		/*
1182 		 * Do not ask for confirmation if either of stdin or stdout is
1183 		 * not tty. Check the environment to see if user has answer
1184 		 * tucked in there already.
1185 		 */
1186 		if (!yes)
1187 			config_bool(ASSUME_ALWAYS_YES, &yes);
1188 		if (!yes) {
1189 			if (!isatty(fileno(stdin))) {
1190 				fprintf(stderr, non_interactive_message);
1191 				exit(EXIT_FAILURE);
1192 			}
1193 
1194 			printf("%s", confirmation_message);
1195 			if (pkg_query_yes_no() == 0)
1196 				exit(EXIT_FAILURE);
1197 		}
1198 		if (bootstrap_pkg(force, fetchOpts) != 0)
1199 			exit(EXIT_FAILURE);
1200 		config_finish();
1201 
1202 		if (bootstrap_only)
1203 			exit(EXIT_SUCCESS);
1204 	} else if (bootstrap_only) {
1205 		printf("pkg already bootstrapped at %s\n", pkgpath);
1206 		exit(EXIT_SUCCESS);
1207 	}
1208 
1209 	execv(pkgpath, argv);
1210 
1211 	/* NOT REACHED */
1212 	return (EXIT_FAILURE);
1213 }
1214