xref: /freebsd/usr.sbin/pkg/pkg.c (revision 2b15cb3d0922bd70ea592f0da9b4a5b167f4d53f)
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 #define _WITH_GETLINE
38 #include <archive.h>
39 #include <archive_entry.h>
40 #include <dirent.h>
41 #include <err.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <fetch.h>
45 #include <paths.h>
46 #include <stdbool.h>
47 #include <stdlib.h>
48 #include <stdio.h>
49 #include <string.h>
50 #include <time.h>
51 #include <unistd.h>
52 #include <ucl.h>
53 
54 #include <openssl/err.h>
55 #include <openssl/ssl.h>
56 
57 #include "dns_utils.h"
58 #include "config.h"
59 
60 struct sig_cert {
61 	char *name;
62 	unsigned char *sig;
63 	int siglen;
64 	unsigned char *cert;
65 	int certlen;
66 	bool trusted;
67 };
68 
69 typedef enum {
70        HASH_UNKNOWN,
71        HASH_SHA256,
72 } hash_t;
73 
74 struct fingerprint {
75        hash_t type;
76        char *name;
77        char hash[BUFSIZ];
78        STAILQ_ENTRY(fingerprint) next;
79 };
80 
81 STAILQ_HEAD(fingerprint_list, fingerprint);
82 
83 static int
84 extract_pkg_static(int fd, char *p, int sz)
85 {
86 	struct archive *a;
87 	struct archive_entry *ae;
88 	char *end;
89 	int ret, r;
90 
91 	ret = -1;
92 	a = archive_read_new();
93 	if (a == NULL) {
94 		warn("archive_read_new");
95 		return (ret);
96 	}
97 	archive_read_support_filter_all(a);
98 	archive_read_support_format_tar(a);
99 
100 	if (lseek(fd, 0, 0) == -1) {
101 		warn("lseek");
102 		goto cleanup;
103 	}
104 
105 	if (archive_read_open_fd(a, fd, 4096) != ARCHIVE_OK) {
106 		warnx("archive_read_open_fd: %s", archive_error_string(a));
107 		goto cleanup;
108 	}
109 
110 	ae = NULL;
111 	while ((r = archive_read_next_header(a, &ae)) == ARCHIVE_OK) {
112 		end = strrchr(archive_entry_pathname(ae), '/');
113 		if (end == NULL)
114 			continue;
115 
116 		if (strcmp(end, "/pkg-static") == 0) {
117 			r = archive_read_extract(a, ae,
118 			    ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM |
119 			    ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_ACL |
120 			    ARCHIVE_EXTRACT_FFLAGS | ARCHIVE_EXTRACT_XATTR);
121 			strlcpy(p, archive_entry_pathname(ae), sz);
122 			break;
123 		}
124 	}
125 
126 	if (r == ARCHIVE_OK)
127 		ret = 0;
128 	else
129 		warnx("failed to extract pkg-static: %s",
130 		    archive_error_string(a));
131 
132 cleanup:
133 	archive_read_free(a);
134 	return (ret);
135 
136 }
137 
138 static int
139 install_pkg_static(const char *path, const char *pkgpath, bool force)
140 {
141 	int pstat;
142 	pid_t pid;
143 
144 	switch ((pid = fork())) {
145 	case -1:
146 		return (-1);
147 	case 0:
148 		if (force)
149 			execl(path, "pkg-static", "add", "-f", pkgpath,
150 			    (char *)NULL);
151 		else
152 			execl(path, "pkg-static", "add", pkgpath,
153 			    (char *)NULL);
154 		_exit(1);
155 	default:
156 		break;
157 	}
158 
159 	while (waitpid(pid, &pstat, 0) == -1)
160 		if (errno != EINTR)
161 			return (-1);
162 
163 	if (WEXITSTATUS(pstat))
164 		return (WEXITSTATUS(pstat));
165 	else if (WIFSIGNALED(pstat))
166 		return (128 & (WTERMSIG(pstat)));
167 	return (pstat);
168 }
169 
170 static int
171 fetch_to_fd(const char *url, char *path)
172 {
173 	struct url *u;
174 	struct dns_srvinfo *mirrors, *current;
175 	struct url_stat st;
176 	FILE *remote;
177 	/* To store _https._tcp. + hostname + \0 */
178 	int fd;
179 	int retry, max_retry;
180 	off_t done, r;
181 	time_t now, last;
182 	char buf[10240];
183 	char zone[MAXHOSTNAMELEN + 13];
184 	static const char *mirror_type = NULL;
185 
186 	done = 0;
187 	last = 0;
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 (done < st.size) {
242 		if ((r = fread(buf, 1, sizeof(buf), remote)) < 1)
243 			break;
244 
245 		if (write(fd, buf, r) != r) {
246 			warn("write()");
247 			goto fetchfail;
248 		}
249 
250 		done += r;
251 		now = time(NULL);
252 		if (now > last || done == st.size)
253 			last = now;
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_buf(const unsigned char *cert, int certlen)
481 {
482 	EVP_PKEY *pkey;
483 	BIO *bp;
484 	char errbuf[1024];
485 
486 	bp = BIO_new_mem_buf(__DECONST(void *, cert), certlen);
487 
488 	if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
489 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
490 
491 	BIO_free(bp);
492 
493 	return (pkey);
494 }
495 
496 static bool
497 rsa_verify_cert(int fd, const unsigned char *key, int keylen,
498     unsigned char *sig, int siglen)
499 {
500 	EVP_MD_CTX *mdctx;
501 	EVP_PKEY *pkey;
502 	char sha256[(SHA256_DIGEST_LENGTH * 2) + 2];
503 	char errbuf[1024];
504 	bool ret;
505 
506 	pkey = NULL;
507 	mdctx = NULL;
508 	ret = false;
509 
510 	/* Compute SHA256 of the package. */
511 	if (lseek(fd, 0, 0) == -1) {
512 		warn("lseek");
513 		goto cleanup;
514 	}
515 	if ((sha256_fd(fd, sha256)) == -1) {
516 		warnx("Error creating SHA256 hash for package");
517 		goto cleanup;
518 	}
519 
520 	if ((pkey = load_public_key_buf(key, keylen)) == NULL) {
521 		warnx("Error reading public key");
522 		goto cleanup;
523 	}
524 
525 	/* Verify signature of the SHA256(pkg) is valid. */
526 	if ((mdctx = EVP_MD_CTX_create()) == NULL) {
527 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
528 		goto error;
529 	}
530 
531 	if (EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
532 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
533 		goto error;
534 	}
535 	if (EVP_DigestVerifyUpdate(mdctx, sha256, strlen(sha256)) != 1) {
536 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
537 		goto error;
538 	}
539 
540 	if (EVP_DigestVerifyFinal(mdctx, sig, siglen) != 1) {
541 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
542 		goto error;
543 	}
544 
545 	ret = true;
546 	printf("done\n");
547 	goto cleanup;
548 
549 error:
550 	printf("failed\n");
551 
552 cleanup:
553 	if (pkey)
554 		EVP_PKEY_free(pkey);
555 	if (mdctx)
556 		EVP_MD_CTX_destroy(mdctx);
557 	ERR_free_strings();
558 
559 	return (ret);
560 }
561 
562 static struct sig_cert *
563 parse_cert(int fd) {
564 	int my_fd;
565 	struct sig_cert *sc;
566 	FILE *fp;
567 	struct sbuf *buf, *sig, *cert;
568 	char *line;
569 	size_t linecap;
570 	ssize_t linelen;
571 
572 	buf = NULL;
573 	my_fd = -1;
574 	sc = NULL;
575 	line = NULL;
576 	linecap = 0;
577 
578 	if (lseek(fd, 0, 0) == -1) {
579 		warn("lseek");
580 		return (NULL);
581 	}
582 
583 	/* Duplicate the fd so that fclose(3) does not close it. */
584 	if ((my_fd = dup(fd)) == -1) {
585 		warnx("dup");
586 		return (NULL);
587 	}
588 
589 	if ((fp = fdopen(my_fd, "rb")) == NULL) {
590 		warn("fdopen");
591 		close(my_fd);
592 		return (NULL);
593 	}
594 
595 	sig = sbuf_new_auto();
596 	cert = sbuf_new_auto();
597 
598 	while ((linelen = getline(&line, &linecap, fp)) > 0) {
599 		if (strcmp(line, "SIGNATURE\n") == 0) {
600 			buf = sig;
601 			continue;
602 		} else if (strcmp(line, "CERT\n") == 0) {
603 			buf = cert;
604 			continue;
605 		} else if (strcmp(line, "END\n") == 0) {
606 			break;
607 		}
608 		if (buf != NULL)
609 			sbuf_bcat(buf, line, linelen);
610 	}
611 
612 	fclose(fp);
613 
614 	/* Trim out unrelated trailing newline */
615 	sbuf_setpos(sig, sbuf_len(sig) - 1);
616 
617 	sbuf_finish(sig);
618 	sbuf_finish(cert);
619 
620 	sc = calloc(1, sizeof(struct sig_cert));
621 	sc->siglen = sbuf_len(sig);
622 	sc->sig = calloc(1, sc->siglen);
623 	memcpy(sc->sig, sbuf_data(sig), sc->siglen);
624 
625 	sc->certlen = sbuf_len(cert);
626 	sc->cert = strdup(sbuf_data(cert));
627 
628 	sbuf_delete(sig);
629 	sbuf_delete(cert);
630 
631 	return (sc);
632 }
633 
634 static bool
635 verify_signature(int fd_pkg, int fd_sig)
636 {
637 	struct fingerprint_list *trusted, *revoked;
638 	struct fingerprint *fingerprint;
639 	struct sig_cert *sc;
640 	bool ret;
641 	int trusted_count, revoked_count;
642 	const char *fingerprints;
643 	char path[MAXPATHLEN];
644 	char hash[SHA256_DIGEST_LENGTH * 2 + 1];
645 
646 	sc = NULL;
647 	trusted = revoked = NULL;
648 	ret = false;
649 
650 	/* Read and parse fingerprints. */
651 	if (config_string(FINGERPRINTS, &fingerprints) != 0) {
652 		warnx("No CONFIG_FINGERPRINTS defined");
653 		goto cleanup;
654 	}
655 
656 	snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
657 	if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
658 		warnx("Error loading trusted certificates");
659 		goto cleanup;
660 	}
661 
662 	if (trusted_count == 0 || trusted == NULL) {
663 		fprintf(stderr, "No trusted certificates found.\n");
664 		goto cleanup;
665 	}
666 
667 	snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
668 	if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
669 		warnx("Error loading revoked certificates");
670 		goto cleanup;
671 	}
672 
673 	/* Read certificate and signature in. */
674 	if ((sc = parse_cert(fd_sig)) == NULL) {
675 		warnx("Error parsing certificate");
676 		goto cleanup;
677 	}
678 	/* Explicitly mark as non-trusted until proven otherwise. */
679 	sc->trusted = false;
680 
681 	/* Parse signature and pubkey out of the certificate */
682 	sha256_buf(sc->cert, sc->certlen, hash);
683 
684 	/* Check if this hash is revoked */
685 	if (revoked != NULL) {
686 		STAILQ_FOREACH(fingerprint, revoked, next) {
687 			if (strcasecmp(fingerprint->hash, hash) == 0) {
688 				fprintf(stderr, "The package was signed with "
689 				    "revoked certificate %s\n",
690 				    fingerprint->name);
691 				goto cleanup;
692 			}
693 		}
694 	}
695 
696 	STAILQ_FOREACH(fingerprint, trusted, next) {
697 		if (strcasecmp(fingerprint->hash, hash) == 0) {
698 			sc->trusted = true;
699 			sc->name = strdup(fingerprint->name);
700 			break;
701 		}
702 	}
703 
704 	if (sc->trusted == false) {
705 		fprintf(stderr, "No trusted fingerprint found matching "
706 		    "package's certificate\n");
707 		goto cleanup;
708 	}
709 
710 	/* Verify the signature. */
711 	printf("Verifying signature with trusted certificate %s... ", sc->name);
712 	if (rsa_verify_cert(fd_pkg, sc->cert, sc->certlen, sc->sig,
713 	    sc->siglen) == false) {
714 		fprintf(stderr, "Signature is not valid\n");
715 		goto cleanup;
716 	}
717 
718 	ret = true;
719 
720 cleanup:
721 	if (trusted)
722 		free_fingerprint_list(trusted);
723 	if (revoked)
724 		free_fingerprint_list(revoked);
725 	if (sc) {
726 		free(sc->cert);
727 		free(sc->sig);
728 		free(sc->name);
729 		free(sc);
730 	}
731 
732 	return (ret);
733 }
734 
735 static int
736 bootstrap_pkg(bool force)
737 {
738 	int fd_pkg, fd_sig;
739 	int ret;
740 	char url[MAXPATHLEN];
741 	char tmppkg[MAXPATHLEN];
742 	char tmpsig[MAXPATHLEN];
743 	const char *packagesite;
744 	const char *signature_type;
745 	char pkgstatic[MAXPATHLEN];
746 
747 	fd_sig = -1;
748 	ret = -1;
749 
750 	if (config_string(PACKAGESITE, &packagesite) != 0) {
751 		warnx("No PACKAGESITE defined");
752 		return (-1);
753 	}
754 
755 	if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
756 		warnx("Error looking up SIGNATURE_TYPE");
757 		return (-1);
758 	}
759 
760 	printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
761 
762 	/* Support pkg+http:// for PACKAGESITE which is the new format
763 	   in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
764 	   no A record. */
765 	if (strncmp(URL_SCHEME_PREFIX, packagesite,
766 	    strlen(URL_SCHEME_PREFIX)) == 0)
767 		packagesite += strlen(URL_SCHEME_PREFIX);
768 	snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
769 
770 	snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
771 	    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
772 
773 	if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
774 		goto fetchfail;
775 
776 	if (signature_type != NULL &&
777 	    strcasecmp(signature_type, "FINGERPRINTS") == 0) {
778 		snprintf(tmpsig, MAXPATHLEN, "%s/pkg.txz.sig.XXXXXX",
779 		    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
780 		snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.sig",
781 		    packagesite);
782 
783 		if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
784 			fprintf(stderr, "Signature for pkg not available.\n");
785 			goto fetchfail;
786 		}
787 
788 		if (verify_signature(fd_pkg, fd_sig) == false)
789 			goto cleanup;
790 	}
791 
792 	if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
793 		ret = install_pkg_static(pkgstatic, tmppkg, force);
794 
795 	goto cleanup;
796 
797 fetchfail:
798 	warnx("Error fetching %s: %s", url, fetchLastErrString);
799 	fprintf(stderr, "A pre-built version of pkg could not be found for "
800 	    "your system.\n");
801 	fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
802 	    "ports: 'ports-mgmt/pkg'.\n");
803 
804 cleanup:
805 	if (fd_sig != -1) {
806 		close(fd_sig);
807 		unlink(tmpsig);
808 	}
809 
810 	if (fd_pkg != -1) {
811 		close(fd_pkg);
812 		unlink(tmppkg);
813 	}
814 
815 	return (ret);
816 }
817 
818 static const char confirmation_message[] =
819 "The package management tool is not yet installed on your system.\n"
820 "Do you want to fetch and install it now? [y/N]: ";
821 
822 static const char non_interactive_message[] =
823 "The package management tool is not yet installed on your system.\n"
824 "Please set ASSUME_ALWAYS_YES=yes environment variable to be able to bootstrap "
825 "in non-interactive (stdin not being a tty)\n";
826 
827 static int
828 pkg_query_yes_no(void)
829 {
830 	int ret, c;
831 
832 	c = getchar();
833 
834 	if (c == 'y' || c == 'Y')
835 		ret = 1;
836 	else
837 		ret = 0;
838 
839 	while (c != '\n' && c != EOF)
840 		c = getchar();
841 
842 	return (ret);
843 }
844 
845 static int
846 bootstrap_pkg_local(const char *pkgpath, bool force)
847 {
848 	char path[MAXPATHLEN];
849 	char pkgstatic[MAXPATHLEN];
850 	const char *signature_type;
851 	int fd_pkg, fd_sig, ret;
852 
853 	fd_sig = -1;
854 	ret = -1;
855 
856 	fd_pkg = open(pkgpath, O_RDONLY);
857 	if (fd_pkg == -1)
858 		err(EXIT_FAILURE, "Unable to open %s", pkgpath);
859 
860 	if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
861 		warnx("Error looking up SIGNATURE_TYPE");
862 		goto cleanup;
863 	}
864 	if (signature_type != NULL &&
865 	    strcasecmp(signature_type, "FINGERPRINTS") == 0) {
866 		snprintf(path, sizeof(path), "%s.sig", pkgpath);
867 
868 		if ((fd_sig = open(path, O_RDONLY)) == -1) {
869 			fprintf(stderr, "Signature for pkg not available.\n");
870 			goto cleanup;
871 		}
872 
873 		if (verify_signature(fd_pkg, fd_sig) == false)
874 			goto cleanup;
875 	}
876 
877 	if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
878 		ret = install_pkg_static(pkgstatic, pkgpath, force);
879 
880 cleanup:
881 	close(fd_pkg);
882 	if (fd_sig != -1)
883 		close(fd_sig);
884 
885 	return (ret);
886 }
887 
888 int
889 main(int argc, char *argv[])
890 {
891 	char pkgpath[MAXPATHLEN];
892 	const char *pkgarg;
893 	bool bootstrap_only, force, yes;
894 
895 	bootstrap_only = false;
896 	force = false;
897 	pkgarg = NULL;
898 	yes = false;
899 
900 	snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
901 	    getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
902 
903 	if (argc > 1 && strcmp(argv[1], "bootstrap") == 0) {
904 		bootstrap_only = true;
905 		if (argc == 3 && strcmp(argv[2], "-f") == 0)
906 			force = true;
907 	}
908 
909 	if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
910 		/*
911 		 * To allow 'pkg -N' to be used as a reliable test for whether
912 		 * a system is configured to use pkg, don't bootstrap pkg
913 		 * when that argument is given as argv[1].
914 		 */
915 		if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
916 			errx(EXIT_FAILURE, "pkg is not installed");
917 
918 		config_init();
919 
920 		if (argc > 1 && strcmp(argv[1], "add") == 0) {
921 			if (argc > 2 && strcmp(argv[2], "-f") == 0) {
922 				force = true;
923 				pkgarg = argv[3];
924 			} else
925 				pkgarg = argv[2];
926 			if (pkgarg == NULL) {
927 				fprintf(stderr, "Path to pkg.txz required\n");
928 				exit(EXIT_FAILURE);
929 			}
930 			if (access(pkgarg, R_OK) == -1) {
931 				fprintf(stderr, "No such file: %s\n", pkgarg);
932 				exit(EXIT_FAILURE);
933 			}
934 			if (bootstrap_pkg_local(pkgarg, force) != 0)
935 				exit(EXIT_FAILURE);
936 			exit(EXIT_SUCCESS);
937 		}
938 		/*
939 		 * Do not ask for confirmation if either of stdin or stdout is
940 		 * not tty. Check the environment to see if user has answer
941 		 * tucked in there already.
942 		 */
943 		config_bool(ASSUME_ALWAYS_YES, &yes);
944 		if (!yes) {
945 			if (!isatty(fileno(stdin))) {
946 				fprintf(stderr, non_interactive_message);
947 				exit(EXIT_FAILURE);
948 			}
949 
950 			printf("%s", confirmation_message);
951 			if (pkg_query_yes_no() == 0)
952 				exit(EXIT_FAILURE);
953 		}
954 		if (bootstrap_pkg(force) != 0)
955 			exit(EXIT_FAILURE);
956 		config_finish();
957 
958 		if (bootstrap_only)
959 			exit(EXIT_SUCCESS);
960 	} else if (bootstrap_only) {
961 		printf("pkg already bootstrapped at %s\n", pkgpath);
962 		exit(EXIT_SUCCESS);
963 	}
964 
965 	execv(pkgpath, argv);
966 
967 	/* NOT REACHED */
968 	return (EXIT_FAILURE);
969 }
970