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>
54 #include <openssl/err.h>
55 #include <openssl/ssl.h>
57 #include "dns_utils.h"
78 STAILQ_ENTRY(fingerprint) next;
81 STAILQ_HEAD(fingerprint_list, fingerprint);
84 extract_pkg_static(int fd, char *p, int sz)
87 struct archive_entry *ae;
92 a = archive_read_new();
94 warn("archive_read_new");
97 archive_read_support_filter_all(a);
98 archive_read_support_format_tar(a);
100 if (lseek(fd, 0, 0) == -1) {
105 if (archive_read_open_fd(a, fd, 4096) != ARCHIVE_OK) {
106 warnx("archive_read_open_fd: %s", archive_error_string(a));
111 while ((r = archive_read_next_header(a, &ae)) == ARCHIVE_OK) {
112 end = strrchr(archive_entry_pathname(ae), '/');
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);
129 warnx("fail to extract pkg-static");
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;
182 char zone[MAXHOSTNAMELEN + 13];
183 static const char *mirror_type = NULL;
188 current = mirrors = NULL;
191 if (mirror_type == NULL && config_string(MIRROR_TYPE, &mirror_type)
193 warnx("No MIRROR_TYPE defined");
197 if ((fd = mkstemp(path)) == -1) {
204 u = fetchParseURL(url);
205 while (remote == NULL) {
206 if (retry == max_retry) {
207 if (strcmp(u->scheme, "file") != 0 &&
208 strcasecmp(mirror_type, "srv") == 0) {
209 snprintf(zone, sizeof(zone),
210 "_%s._tcp.%s", u->scheme, u->host);
211 mirrors = dns_getsrvinfo(zone);
216 if (mirrors != NULL) {
217 strlcpy(u->host, current->host, sizeof(u->host));
218 u->port = current->port;
221 remote = fetchXGet(u, &st, "");
222 if (remote == NULL) {
226 if (mirrors == NULL) {
229 current = current->next;
239 while (done < st.size) {
240 if ((r = fread(buf, 1, sizeof(buf), remote)) < 1)
243 if (write(fd, buf, r) != r) {
250 if (now > last || done == st.size)
273 static struct fingerprint *
274 parse_fingerprint(ucl_object_t *obj)
277 ucl_object_iter_t it = NULL;
278 const char *function, *fp, *key;
279 struct fingerprint *f;
280 hash_t fct = HASH_UNKNOWN;
282 function = fp = NULL;
284 while ((cur = ucl_iterate_object(obj, &it, true))) {
285 key = ucl_object_key(cur);
286 if (cur->type != UCL_STRING)
288 if (strcasecmp(key, "function") == 0) {
289 function = ucl_object_tostring(cur);
292 if (strcasecmp(key, "fingerprint") == 0) {
293 fp = ucl_object_tostring(cur);
298 if (fp == NULL || function == NULL)
301 if (strcasecmp(function, "sha256") == 0)
304 if (fct == HASH_UNKNOWN) {
305 warnx("Unsupported hashing function: %s", function);
309 f = calloc(1, sizeof(struct fingerprint));
311 strlcpy(f->hash, fp, sizeof(f->hash));
317 free_fingerprint_list(struct fingerprint_list* list)
319 struct fingerprint *fingerprint, *tmp;
321 STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
322 if (fingerprint->name)
323 free(fingerprint->name);
329 static struct fingerprint *
330 load_fingerprint(const char *dir, const char *filename)
332 ucl_object_t *obj = NULL;
333 struct ucl_parser *p = NULL;
334 struct fingerprint *f;
335 char path[MAXPATHLEN];
339 snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
341 p = ucl_parser_new(0);
342 if (!ucl_parser_add_file(p, path)) {
343 warnx("%s: %s", path, ucl_parser_get_error(p));
348 obj = ucl_parser_get_object(p);
350 if (obj->type == UCL_OBJECT)
351 f = parse_fingerprint(obj);
354 f->name = strdup(filename);
356 ucl_object_free(obj);
362 static struct fingerprint_list *
363 load_fingerprints(const char *path, int *count)
367 struct fingerprint *finger;
368 struct fingerprint_list *fingerprints;
372 fingerprints = calloc(1, sizeof(struct fingerprint_list));
373 if (fingerprints == NULL)
375 STAILQ_INIT(fingerprints);
377 if ((d = opendir(path)) == NULL)
380 while ((ent = readdir(d))) {
381 if (strcmp(ent->d_name, ".") == 0 ||
382 strcmp(ent->d_name, "..") == 0)
384 finger = load_fingerprint(path, ent->d_name);
385 if (finger != NULL) {
386 STAILQ_INSERT_TAIL(fingerprints, finger, next);
393 return (fingerprints);
397 sha256_hash(unsigned char hash[SHA256_DIGEST_LENGTH],
398 char out[SHA256_DIGEST_LENGTH * 2 + 1])
402 for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
403 sprintf(out + (i * 2), "%02x", hash[i]);
405 out[SHA256_DIGEST_LENGTH * 2] = '\0';
409 sha256_buf(char *buf, size_t len, char out[SHA256_DIGEST_LENGTH * 2 + 1])
411 unsigned char hash[SHA256_DIGEST_LENGTH];
416 SHA256_Init(&sha256);
417 SHA256_Update(&sha256, buf, len);
418 SHA256_Final(hash, &sha256);
419 sha256_hash(hash, out);
423 sha256_fd(int fd, char out[SHA256_DIGEST_LENGTH * 2 + 1])
428 unsigned char hash[SHA256_DIGEST_LENGTH];
440 /* Duplicate the fd so that fclose(3) does not close it. */
441 if ((my_fd = dup(fd)) == -1) {
446 if ((fp = fdopen(my_fd, "rb")) == NULL) {
451 SHA256_Init(&sha256);
453 while ((r = fread(buffer, 1, BUFSIZ, fp)) > 0)
454 SHA256_Update(&sha256, buffer, r);
456 if (ferror(fp) != 0) {
461 SHA256_Final(hash, &sha256);
462 sha256_hash(hash, out);
468 else if (my_fd != -1)
470 (void)lseek(fd, 0, SEEK_SET);
476 load_public_key_buf(const unsigned char *cert, int certlen)
482 bp = BIO_new_mem_buf(__DECONST(void *, cert), certlen);
484 if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
485 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
493 rsa_verify_cert(int fd, const unsigned char *key, int keylen,
494 unsigned char *sig, int siglen)
498 char sha256[(SHA256_DIGEST_LENGTH * 2) + 2];
506 /* Compute SHA256 of the package. */
507 if (lseek(fd, 0, 0) == -1) {
511 if ((sha256_fd(fd, sha256)) == -1) {
512 warnx("Error creating SHA256 hash for package");
516 if ((pkey = load_public_key_buf(key, keylen)) == NULL) {
517 warnx("Error reading public key");
521 /* Verify signature of the SHA256(pkg) is valid. */
522 if ((mdctx = EVP_MD_CTX_create()) == NULL) {
523 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
527 if (EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
528 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
531 if (EVP_DigestVerifyUpdate(mdctx, sha256, strlen(sha256)) != 1) {
532 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
536 if (EVP_DigestVerifyFinal(mdctx, sig, siglen) != 1) {
537 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
552 EVP_MD_CTX_destroy(mdctx);
558 static struct sig_cert *
563 struct sbuf *buf, *sig, *cert;
574 if (lseek(fd, 0, 0) == -1) {
579 /* Duplicate the fd so that fclose(3) does not close it. */
580 if ((my_fd = dup(fd)) == -1) {
585 if ((fp = fdopen(my_fd, "rb")) == NULL) {
591 sig = sbuf_new_auto();
592 cert = sbuf_new_auto();
594 while ((linelen = getline(&line, &linecap, fp)) > 0) {
595 if (strcmp(line, "SIGNATURE\n") == 0) {
598 } else if (strcmp(line, "CERT\n") == 0) {
601 } else if (strcmp(line, "END\n") == 0) {
605 sbuf_bcat(buf, line, linelen);
610 /* Trim out unrelated trailing newline */
611 sbuf_setpos(sig, sbuf_len(sig) - 1);
616 sc = calloc(1, sizeof(struct sig_cert));
617 sc->siglen = sbuf_len(sig);
618 sc->sig = calloc(1, sc->siglen);
619 memcpy(sc->sig, sbuf_data(sig), sc->siglen);
621 sc->certlen = sbuf_len(cert);
622 sc->cert = strdup(sbuf_data(cert));
631 verify_signature(int fd_pkg, int fd_sig)
633 struct fingerprint_list *trusted, *revoked;
634 struct fingerprint *fingerprint;
637 int trusted_count, revoked_count;
638 const char *fingerprints;
639 char path[MAXPATHLEN];
640 char hash[SHA256_DIGEST_LENGTH * 2 + 1];
643 trusted = revoked = NULL;
646 /* Read and parse fingerprints. */
647 if (config_string(FINGERPRINTS, &fingerprints) != 0) {
648 warnx("No CONFIG_FINGERPRINTS defined");
652 snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
653 if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
654 warnx("Error loading trusted certificates");
658 if (trusted_count == 0 || trusted == NULL) {
659 fprintf(stderr, "No trusted certificates found.\n");
663 snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
664 if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
665 warnx("Error loading revoked certificates");
669 /* Read certificate and signature in. */
670 if ((sc = parse_cert(fd_sig)) == NULL) {
671 warnx("Error parsing certificate");
674 /* Explicitly mark as non-trusted until proven otherwise. */
677 /* Parse signature and pubkey out of the certificate */
678 sha256_buf(sc->cert, sc->certlen, hash);
680 /* Check if this hash is revoked */
681 if (revoked != NULL) {
682 STAILQ_FOREACH(fingerprint, revoked, next) {
683 if (strcasecmp(fingerprint->hash, hash) == 0) {
684 fprintf(stderr, "The package was signed with "
685 "revoked certificate %s\n",
692 STAILQ_FOREACH(fingerprint, trusted, next) {
693 if (strcasecmp(fingerprint->hash, hash) == 0) {
695 sc->name = strdup(fingerprint->name);
700 if (sc->trusted == false) {
701 fprintf(stderr, "No trusted fingerprint found matching "
702 "package's certificate\n");
706 /* Verify the signature. */
707 printf("Verifying signature with trusted certificate %s... ", sc->name);
708 if (rsa_verify_cert(fd_pkg, sc->cert, sc->certlen, sc->sig,
709 sc->siglen) == false) {
710 fprintf(stderr, "Signature is not valid\n");
718 free_fingerprint_list(trusted);
720 free_fingerprint_list(revoked);
735 bootstrap_pkg(bool force)
739 char url[MAXPATHLEN];
740 char tmppkg[MAXPATHLEN];
741 char tmpsig[MAXPATHLEN];
742 const char *packagesite;
743 const char *signature_type;
744 char pkgstatic[MAXPATHLEN];
749 if (config_string(PACKAGESITE, &packagesite) != 0) {
750 warnx("No PACKAGESITE defined");
754 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
755 warnx("Error looking up SIGNATURE_TYPE");
759 printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
761 /* Support pkg+http:// for PACKAGESITE which is the new format
762 in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
764 if (strncmp(URL_SCHEME_PREFIX, packagesite,
765 strlen(URL_SCHEME_PREFIX)) == 0)
766 packagesite += strlen(URL_SCHEME_PREFIX);
767 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
769 snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
770 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
772 if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
775 if (signature_type != NULL &&
776 strcasecmp(signature_type, "FINGERPRINTS") == 0) {
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");
814 static const char confirmation_message[] =
815 "The package management tool is not yet installed on your system.\n"
816 "Do you want to fetch and install it now? [y/N]: ";
819 pkg_query_yes_no(void)
825 if (c == 'y' || c == 'Y')
830 while (c != '\n' && c != EOF)
837 bootstrap_pkg_local(const char *pkgpath, bool force)
839 char path[MAXPATHLEN];
840 char pkgstatic[MAXPATHLEN];
841 const char *signature_type;
842 int fd_pkg, fd_sig, ret;
847 fd_pkg = open(pkgpath, O_RDONLY);
849 err(EXIT_FAILURE, "Unable to open %s", pkgpath);
851 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
852 warnx("Error looking up SIGNATURE_TYPE");
855 if (signature_type != NULL &&
856 strcasecmp(signature_type, "FINGERPRINTS") == 0) {
857 snprintf(path, sizeof(path), "%s.sig", pkgpath);
859 if ((fd_sig = open(path, O_RDONLY)) == -1) {
860 fprintf(stderr, "Signature for pkg not available.\n");
864 if (verify_signature(fd_pkg, fd_sig) == false)
868 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
869 ret = install_pkg_static(pkgstatic, pkgpath, force);
880 main(__unused int argc, char *argv[])
882 char pkgpath[MAXPATHLEN];
884 bool bootstrap_only, force, yes;
886 bootstrap_only = false;
891 snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
892 getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
894 if (argc > 1 && strcmp(argv[1], "bootstrap") == 0) {
895 bootstrap_only = true;
896 if (argc == 3 && strcmp(argv[2], "-f") == 0)
900 if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
902 * To allow 'pkg -N' to be used as a reliable test for whether
903 * a system is configured to use pkg, don't bootstrap pkg
904 * when that argument is given as argv[1].
906 if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
907 errx(EXIT_FAILURE, "pkg is not installed");
911 if (argc > 1 && strcmp(argv[1], "add") == 0) {
912 if (argc > 2 && strcmp(argv[2], "-f") == 0) {
917 if (pkgarg == NULL) {
918 fprintf(stderr, "Path to pkg.txz required\n");
921 if (access(pkgarg, R_OK) == -1) {
922 fprintf(stderr, "No such file: %s\n", pkgarg);
925 if (bootstrap_pkg_local(pkgarg, force) != 0)
930 * Do not ask for confirmation if either of stdin or stdout is
931 * not tty. Check the environment to see if user has answer
932 * tucked in there already.
934 config_bool(ASSUME_ALWAYS_YES, &yes);
936 printf("%s", confirmation_message);
937 if (!isatty(fileno(stdin)))
940 if (pkg_query_yes_no() == 0)
943 if (bootstrap_pkg(force) != 0)
949 } else if (bootstrap_only) {
950 printf("pkg already bootstrapped at %s\n", pkgpath);
954 execv(pkgpath, argv);
957 return (EXIT_FAILURE);