2 * Copyright (c) 2012-2014 Baptiste Daroussin <bapt@FreeBSD.org>
3 * Copyright (c) 2013 Bryan Drewery <bdrewery@FreeBSD.org>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
31 #include <sys/param.h>
32 #include <sys/queue.h>
33 #include <sys/types.h>
39 #include <archive_entry.h>
53 #include <openssl/err.h>
54 #include <openssl/ssl.h>
56 #include "dns_utils.h"
77 STAILQ_ENTRY(fingerprint) next;
80 STAILQ_HEAD(fingerprint_list, fingerprint);
83 extract_pkg_static(int fd, char *p, int sz)
86 struct archive_entry *ae;
91 a = archive_read_new();
93 warn("archive_read_new");
96 archive_read_support_filter_all(a);
97 archive_read_support_format_tar(a);
99 if (lseek(fd, 0, 0) == -1) {
104 if (archive_read_open_fd(a, fd, 4096) != ARCHIVE_OK) {
105 warnx("archive_read_open_fd: %s", archive_error_string(a));
110 while ((r = archive_read_next_header(a, &ae)) == ARCHIVE_OK) {
111 end = strrchr(archive_entry_pathname(ae), '/');
115 if (strcmp(end, "/pkg-static") == 0) {
116 r = archive_read_extract(a, ae,
117 ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM |
118 ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_ACL |
119 ARCHIVE_EXTRACT_FFLAGS | ARCHIVE_EXTRACT_XATTR);
120 strlcpy(p, archive_entry_pathname(ae), sz);
128 warnx("failed to extract pkg-static: %s",
129 archive_error_string(a));
132 archive_read_free(a);
138 install_pkg_static(const char *path, const char *pkgpath, bool force)
143 switch ((pid = fork())) {
148 execl(path, "pkg-static", "add", "-f", pkgpath,
151 execl(path, "pkg-static", "add", pkgpath,
158 while (waitpid(pid, &pstat, 0) == -1)
162 if (WEXITSTATUS(pstat))
163 return (WEXITSTATUS(pstat));
164 else if (WIFSIGNALED(pstat))
165 return (128 & (WTERMSIG(pstat)));
170 fetch_to_fd(const char *url, char *path)
173 struct dns_srvinfo *mirrors, *current;
176 /* To store _https._tcp. + hostname + \0 */
178 int retry, max_retry;
181 char zone[MAXHOSTNAMELEN + 13];
182 static const char *mirror_type = NULL;
185 current = mirrors = NULL;
188 if (mirror_type == NULL && config_string(MIRROR_TYPE, &mirror_type)
190 warnx("No MIRROR_TYPE defined");
194 if ((fd = mkstemp(path)) == -1) {
201 if ((u = fetchParseURL(url)) == NULL) {
202 warn("fetchParseURL('%s')", url);
206 while (remote == NULL) {
207 if (retry == max_retry) {
208 if (strcmp(u->scheme, "file") != 0 &&
209 strcasecmp(mirror_type, "srv") == 0) {
210 snprintf(zone, sizeof(zone),
211 "_%s._tcp.%s", u->scheme, u->host);
212 mirrors = dns_getsrvinfo(zone);
217 if (mirrors != NULL) {
218 strlcpy(u->host, current->host, sizeof(u->host));
219 u->port = current->port;
222 remote = fetchXGet(u, &st, "");
223 if (remote == NULL) {
227 if (mirrors == NULL) {
230 current = current->next;
237 while ((r = fread(buf, 1, sizeof(buf), remote)) > 0) {
238 if (write(fd, buf, r) != r) {
245 warn("An error occurred while fetching pkg(8)");
268 static struct fingerprint *
269 parse_fingerprint(ucl_object_t *obj)
271 const ucl_object_t *cur;
272 ucl_object_iter_t it = NULL;
273 const char *function, *fp, *key;
274 struct fingerprint *f;
275 hash_t fct = HASH_UNKNOWN;
277 function = fp = NULL;
279 while ((cur = ucl_iterate_object(obj, &it, true))) {
280 key = ucl_object_key(cur);
281 if (cur->type != UCL_STRING)
283 if (strcasecmp(key, "function") == 0) {
284 function = ucl_object_tostring(cur);
287 if (strcasecmp(key, "fingerprint") == 0) {
288 fp = ucl_object_tostring(cur);
293 if (fp == NULL || function == NULL)
296 if (strcasecmp(function, "sha256") == 0)
299 if (fct == HASH_UNKNOWN) {
300 warnx("Unsupported hashing function: %s", function);
304 f = calloc(1, sizeof(struct fingerprint));
306 strlcpy(f->hash, fp, sizeof(f->hash));
312 free_fingerprint_list(struct fingerprint_list* list)
314 struct fingerprint *fingerprint, *tmp;
316 STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
317 free(fingerprint->name);
323 static struct fingerprint *
324 load_fingerprint(const char *dir, const char *filename)
326 ucl_object_t *obj = NULL;
327 struct ucl_parser *p = NULL;
328 struct fingerprint *f;
329 char path[MAXPATHLEN];
333 snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
335 p = ucl_parser_new(0);
336 if (!ucl_parser_add_file(p, path)) {
337 warnx("%s: %s", path, ucl_parser_get_error(p));
342 obj = ucl_parser_get_object(p);
344 if (obj->type == UCL_OBJECT)
345 f = parse_fingerprint(obj);
348 f->name = strdup(filename);
350 ucl_object_unref(obj);
356 static struct fingerprint_list *
357 load_fingerprints(const char *path, int *count)
361 struct fingerprint *finger;
362 struct fingerprint_list *fingerprints;
366 fingerprints = calloc(1, sizeof(struct fingerprint_list));
367 if (fingerprints == NULL)
369 STAILQ_INIT(fingerprints);
371 if ((d = opendir(path)) == NULL) {
377 while ((ent = readdir(d))) {
378 if (strcmp(ent->d_name, ".") == 0 ||
379 strcmp(ent->d_name, "..") == 0)
381 finger = load_fingerprint(path, ent->d_name);
382 if (finger != NULL) {
383 STAILQ_INSERT_TAIL(fingerprints, finger, next);
390 return (fingerprints);
394 sha256_hash(unsigned char hash[SHA256_DIGEST_LENGTH],
395 char out[SHA256_DIGEST_LENGTH * 2 + 1])
399 for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
400 sprintf(out + (i * 2), "%02x", hash[i]);
402 out[SHA256_DIGEST_LENGTH * 2] = '\0';
406 sha256_buf(char *buf, size_t len, char out[SHA256_DIGEST_LENGTH * 2 + 1])
408 unsigned char hash[SHA256_DIGEST_LENGTH];
413 SHA256_Init(&sha256);
414 SHA256_Update(&sha256, buf, len);
415 SHA256_Final(hash, &sha256);
416 sha256_hash(hash, out);
420 sha256_fd(int fd, char out[SHA256_DIGEST_LENGTH * 2 + 1])
425 unsigned char hash[SHA256_DIGEST_LENGTH];
437 /* Duplicate the fd so that fclose(3) does not close it. */
438 if ((my_fd = dup(fd)) == -1) {
443 if ((fp = fdopen(my_fd, "rb")) == NULL) {
448 SHA256_Init(&sha256);
450 while ((r = fread(buffer, 1, BUFSIZ, fp)) > 0)
451 SHA256_Update(&sha256, buffer, r);
453 if (ferror(fp) != 0) {
458 SHA256_Final(hash, &sha256);
459 sha256_hash(hash, out);
465 else if (my_fd != -1)
467 (void)lseek(fd, 0, SEEK_SET);
473 load_public_key_buf(const unsigned char *cert, int certlen)
479 bp = BIO_new_mem_buf(__DECONST(void *, cert), certlen);
481 if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
482 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
490 rsa_verify_cert(int fd, const unsigned char *key, int keylen,
491 unsigned char *sig, int siglen)
495 char sha256[(SHA256_DIGEST_LENGTH * 2) + 2];
503 /* Compute SHA256 of the package. */
504 if (lseek(fd, 0, 0) == -1) {
508 if ((sha256_fd(fd, sha256)) == -1) {
509 warnx("Error creating SHA256 hash for package");
513 if ((pkey = load_public_key_buf(key, keylen)) == NULL) {
514 warnx("Error reading public key");
518 /* Verify signature of the SHA256(pkg) is valid. */
519 if ((mdctx = EVP_MD_CTX_create()) == NULL) {
520 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
524 if (EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
525 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
528 if (EVP_DigestVerifyUpdate(mdctx, sha256, strlen(sha256)) != 1) {
529 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
533 if (EVP_DigestVerifyFinal(mdctx, sig, siglen) != 1) {
534 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
549 EVP_MD_CTX_destroy(mdctx);
555 static struct sig_cert *
560 struct sbuf *buf, *sig, *cert;
571 if (lseek(fd, 0, 0) == -1) {
576 /* Duplicate the fd so that fclose(3) does not close it. */
577 if ((my_fd = dup(fd)) == -1) {
582 if ((fp = fdopen(my_fd, "rb")) == NULL) {
588 sig = sbuf_new_auto();
589 cert = sbuf_new_auto();
591 while ((linelen = getline(&line, &linecap, fp)) > 0) {
592 if (strcmp(line, "SIGNATURE\n") == 0) {
595 } else if (strcmp(line, "CERT\n") == 0) {
598 } else if (strcmp(line, "END\n") == 0) {
602 sbuf_bcat(buf, line, linelen);
607 /* Trim out unrelated trailing newline */
608 sbuf_setpos(sig, sbuf_len(sig) - 1);
613 sc = calloc(1, sizeof(struct sig_cert));
614 sc->siglen = sbuf_len(sig);
615 sc->sig = calloc(1, sc->siglen);
616 memcpy(sc->sig, sbuf_data(sig), sc->siglen);
618 sc->certlen = sbuf_len(cert);
619 sc->cert = strdup(sbuf_data(cert));
628 verify_signature(int fd_pkg, int fd_sig)
630 struct fingerprint_list *trusted, *revoked;
631 struct fingerprint *fingerprint;
634 int trusted_count, revoked_count;
635 const char *fingerprints;
636 char path[MAXPATHLEN];
637 char hash[SHA256_DIGEST_LENGTH * 2 + 1];
640 trusted = revoked = NULL;
643 /* Read and parse fingerprints. */
644 if (config_string(FINGERPRINTS, &fingerprints) != 0) {
645 warnx("No CONFIG_FINGERPRINTS defined");
649 snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
650 if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
651 warnx("Error loading trusted certificates");
655 if (trusted_count == 0 || trusted == NULL) {
656 fprintf(stderr, "No trusted certificates found.\n");
660 snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
661 if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
662 warnx("Error loading revoked certificates");
666 /* Read certificate and signature in. */
667 if ((sc = parse_cert(fd_sig)) == NULL) {
668 warnx("Error parsing certificate");
671 /* Explicitly mark as non-trusted until proven otherwise. */
674 /* Parse signature and pubkey out of the certificate */
675 sha256_buf(sc->cert, sc->certlen, hash);
677 /* Check if this hash is revoked */
678 if (revoked != NULL) {
679 STAILQ_FOREACH(fingerprint, revoked, next) {
680 if (strcasecmp(fingerprint->hash, hash) == 0) {
681 fprintf(stderr, "The package was signed with "
682 "revoked certificate %s\n",
689 STAILQ_FOREACH(fingerprint, trusted, next) {
690 if (strcasecmp(fingerprint->hash, hash) == 0) {
692 sc->name = strdup(fingerprint->name);
697 if (sc->trusted == false) {
698 fprintf(stderr, "No trusted fingerprint found matching "
699 "package's certificate\n");
703 /* Verify the signature. */
704 printf("Verifying signature with trusted certificate %s... ", sc->name);
705 if (rsa_verify_cert(fd_pkg, sc->cert, sc->certlen, sc->sig,
706 sc->siglen) == false) {
707 fprintf(stderr, "Signature is not valid\n");
715 free_fingerprint_list(trusted);
717 free_fingerprint_list(revoked);
729 bootstrap_pkg(bool force)
733 char url[MAXPATHLEN];
734 char tmppkg[MAXPATHLEN];
735 char tmpsig[MAXPATHLEN];
736 const char *packagesite;
737 const char *signature_type;
738 char pkgstatic[MAXPATHLEN];
743 if (config_string(PACKAGESITE, &packagesite) != 0) {
744 warnx("No PACKAGESITE defined");
748 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
749 warnx("Error looking up SIGNATURE_TYPE");
753 printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
755 /* Support pkg+http:// for PACKAGESITE which is the new format
756 in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
758 if (strncmp(URL_SCHEME_PREFIX, packagesite,
759 strlen(URL_SCHEME_PREFIX)) == 0)
760 packagesite += strlen(URL_SCHEME_PREFIX);
761 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
763 snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
764 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
766 if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
769 if (signature_type != NULL &&
770 strcasecmp(signature_type, "NONE") != 0) {
771 if (strcasecmp(signature_type, "FINGERPRINTS") != 0) {
772 warnx("Signature type %s is not supported for "
773 "bootstrapping.", signature_type);
777 snprintf(tmpsig, MAXPATHLEN, "%s/pkg.txz.sig.XXXXXX",
778 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
779 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.sig",
782 if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
783 fprintf(stderr, "Signature for pkg not available.\n");
787 if (verify_signature(fd_pkg, fd_sig) == false)
791 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
792 ret = install_pkg_static(pkgstatic, tmppkg, force);
797 warnx("Error fetching %s: %s", url, fetchLastErrString);
798 fprintf(stderr, "A pre-built version of pkg could not be found for "
800 fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
801 "ports: 'ports-mgmt/pkg'.\n");
817 static const char confirmation_message[] =
818 "The package management tool is not yet installed on your system.\n"
819 "Do you want to fetch and install it now? [y/N]: ";
821 static const char non_interactive_message[] =
822 "The package management tool is not yet installed on your system.\n"
823 "Please set ASSUME_ALWAYS_YES=yes environment variable to be able to bootstrap "
824 "in non-interactive (stdin not being a tty)\n";
827 pkg_query_yes_no(void)
833 if (c == 'y' || c == 'Y')
838 while (c != '\n' && c != EOF)
845 bootstrap_pkg_local(const char *pkgpath, bool force)
847 char path[MAXPATHLEN];
848 char pkgstatic[MAXPATHLEN];
849 const char *signature_type;
850 int fd_pkg, fd_sig, ret;
855 fd_pkg = open(pkgpath, O_RDONLY);
857 err(EXIT_FAILURE, "Unable to open %s", pkgpath);
859 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
860 warnx("Error looking up SIGNATURE_TYPE");
863 if (signature_type != NULL &&
864 strcasecmp(signature_type, "NONE") != 0) {
865 if (strcasecmp(signature_type, "FINGERPRINTS") != 0) {
866 warnx("Signature type %s is not supported for "
867 "bootstrapping.", signature_type);
871 snprintf(path, sizeof(path), "%s.sig", pkgpath);
873 if ((fd_sig = open(path, O_RDONLY)) == -1) {
874 fprintf(stderr, "Signature for pkg not available.\n");
878 if (verify_signature(fd_pkg, fd_sig) == false)
882 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
883 ret = install_pkg_static(pkgstatic, pkgpath, force);
894 main(int argc, char *argv[])
896 char pkgpath[MAXPATHLEN];
898 bool bootstrap_only, force, yes;
900 bootstrap_only = false;
905 snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
906 getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
908 if (argc > 1 && strcmp(argv[1], "bootstrap") == 0) {
909 bootstrap_only = true;
910 if (argc == 3 && strcmp(argv[2], "-f") == 0)
914 if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
916 * To allow 'pkg -N' to be used as a reliable test for whether
917 * a system is configured to use pkg, don't bootstrap pkg
918 * when that argument is given as argv[1].
920 if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
921 errx(EXIT_FAILURE, "pkg is not installed");
925 if (argc > 1 && strcmp(argv[1], "add") == 0) {
926 if (argc > 2 && strcmp(argv[2], "-f") == 0) {
931 if (pkgarg == NULL) {
932 fprintf(stderr, "Path to pkg.txz required\n");
935 if (access(pkgarg, R_OK) == -1) {
936 fprintf(stderr, "No such file: %s\n", pkgarg);
939 if (bootstrap_pkg_local(pkgarg, force) != 0)
944 * Do not ask for confirmation if either of stdin or stdout is
945 * not tty. Check the environment to see if user has answer
946 * tucked in there already.
948 config_bool(ASSUME_ALWAYS_YES, &yes);
950 if (!isatty(fileno(stdin))) {
951 fprintf(stderr, non_interactive_message);
955 printf("%s", confirmation_message);
956 if (pkg_query_yes_no() == 0)
959 if (bootstrap_pkg(force) != 0)
965 } else if (bootstrap_only) {
966 printf("pkg already bootstrapped at %s\n", pkgpath);
970 execv(pkgpath, argv);
973 return (EXIT_FAILURE);