2 * Copyright (c) 2012-2013 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(yaml_document_t *doc, yaml_node_t *node)
276 yaml_node_pair_t *pair;
277 yaml_char_t *function, *fp;
278 struct fingerprint *f;
279 hash_t fct = HASH_UNKNOWN;
281 function = fp = NULL;
283 pair = node->data.mapping.pairs.start;
284 while (pair < node->data.mapping.pairs.top) {
285 yaml_node_t *key = yaml_document_get_node(doc, pair->key);
286 yaml_node_t *val = yaml_document_get_node(doc, pair->value);
288 if (key->data.scalar.length <= 0) {
293 if (val->type != YAML_SCALAR_NODE) {
298 if (strcasecmp(key->data.scalar.value, "function") == 0)
299 function = val->data.scalar.value;
300 else if (strcasecmp(key->data.scalar.value, "fingerprint")
302 fp = val->data.scalar.value;
308 if (fp == NULL || function == NULL)
311 if (strcasecmp(function, "sha256") == 0)
314 if (fct == HASH_UNKNOWN) {
315 fprintf(stderr, "Unsupported hashing function: %s\n", function);
319 f = calloc(1, sizeof(struct fingerprint));
321 strlcpy(f->hash, fp, sizeof(f->hash));
327 free_fingerprint_list(struct fingerprint_list* list)
329 struct fingerprint *fingerprint, *tmp;
331 STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
332 if (fingerprint->name)
333 free(fingerprint->name);
339 static struct fingerprint *
340 load_fingerprint(const char *dir, const char *filename)
342 yaml_parser_t parser;
346 struct fingerprint *f;
347 char path[MAXPATHLEN];
351 snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
353 if ((fp = fopen(path, "r")) == NULL)
356 yaml_parser_initialize(&parser);
357 yaml_parser_set_input_file(&parser, fp);
358 yaml_parser_load(&parser, &doc);
360 node = yaml_document_get_root_node(&doc);
361 if (node == NULL || node->type != YAML_MAPPING_NODE)
364 f = parse_fingerprint(&doc, node);
365 f->name = strdup(filename);
368 yaml_document_delete(&doc);
369 yaml_parser_delete(&parser);
375 static struct fingerprint_list *
376 load_fingerprints(const char *path, int *count)
380 struct fingerprint *finger;
381 struct fingerprint_list *fingerprints;
385 fingerprints = calloc(1, sizeof(struct fingerprint_list));
386 if (fingerprints == NULL)
388 STAILQ_INIT(fingerprints);
390 if ((d = opendir(path)) == NULL)
393 while ((ent = readdir(d))) {
394 if (strcmp(ent->d_name, ".") == 0 ||
395 strcmp(ent->d_name, "..") == 0)
397 finger = load_fingerprint(path, ent->d_name);
398 if (finger != NULL) {
399 STAILQ_INSERT_TAIL(fingerprints, finger, next);
406 return (fingerprints);
410 sha256_hash(unsigned char hash[SHA256_DIGEST_LENGTH],
411 char out[SHA256_DIGEST_LENGTH * 2 + 1])
415 for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
416 sprintf(out + (i * 2), "%02x", hash[i]);
418 out[SHA256_DIGEST_LENGTH * 2] = '\0';
422 sha256_buf(char *buf, size_t len, char out[SHA256_DIGEST_LENGTH * 2 + 1])
424 unsigned char hash[SHA256_DIGEST_LENGTH];
429 SHA256_Init(&sha256);
430 SHA256_Update(&sha256, buf, len);
431 SHA256_Final(hash, &sha256);
432 sha256_hash(hash, out);
436 sha256_fd(int fd, char out[SHA256_DIGEST_LENGTH * 2 + 1])
441 unsigned char hash[SHA256_DIGEST_LENGTH];
453 /* Duplicate the fd so that fclose(3) does not close it. */
454 if ((my_fd = dup(fd)) == -1) {
459 if ((fp = fdopen(my_fd, "rb")) == NULL) {
464 SHA256_Init(&sha256);
466 while ((r = fread(buffer, 1, BUFSIZ, fp)) > 0)
467 SHA256_Update(&sha256, buffer, r);
469 if (ferror(fp) != 0) {
474 SHA256_Final(hash, &sha256);
475 sha256_hash(hash, out);
481 else if (my_fd != -1)
483 (void)lseek(fd, 0, SEEK_SET);
489 load_public_key_buf(const unsigned char *cert, int certlen)
495 bp = BIO_new_mem_buf(__DECONST(void *, cert), certlen);
497 if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
498 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
506 rsa_verify_cert(int fd, const unsigned char *key, int keylen,
507 unsigned char *sig, int siglen)
511 char sha256[(SHA256_DIGEST_LENGTH * 2) + 2];
519 /* Compute SHA256 of the package. */
520 if (lseek(fd, 0, 0) == -1) {
524 if ((sha256_fd(fd, sha256)) == -1) {
525 warnx("Error creating SHA256 hash for package");
529 if ((pkey = load_public_key_buf(key, keylen)) == NULL) {
530 warnx("Error reading public key");
534 /* Verify signature of the SHA256(pkg) is valid. */
535 if ((mdctx = EVP_MD_CTX_create()) == NULL) {
536 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
540 if (EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
541 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
544 if (EVP_DigestVerifyUpdate(mdctx, sha256, strlen(sha256)) != 1) {
545 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
549 if (EVP_DigestVerifyFinal(mdctx, sig, siglen) != 1) {
550 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
565 EVP_MD_CTX_destroy(mdctx);
571 static struct sig_cert *
576 struct sbuf *buf, *sig, *cert;
587 if (lseek(fd, 0, 0) == -1) {
592 /* Duplicate the fd so that fclose(3) does not close it. */
593 if ((my_fd = dup(fd)) == -1) {
598 if ((fp = fdopen(my_fd, "rb")) == NULL) {
604 sig = sbuf_new_auto();
605 cert = sbuf_new_auto();
607 while ((linelen = getline(&line, &linecap, fp)) > 0) {
608 if (strcmp(line, "SIGNATURE\n") == 0) {
611 } else if (strcmp(line, "CERT\n") == 0) {
614 } else if (strcmp(line, "END\n") == 0) {
618 sbuf_bcat(buf, line, linelen);
623 /* Trim out unrelated trailing newline */
624 sbuf_setpos(sig, sbuf_len(sig) - 1);
629 sc = calloc(1, sizeof(struct sig_cert));
630 sc->siglen = sbuf_len(sig);
631 sc->sig = calloc(1, sc->siglen);
632 memcpy(sc->sig, sbuf_data(sig), sc->siglen);
634 sc->certlen = sbuf_len(cert);
635 sc->cert = strdup(sbuf_data(cert));
644 verify_signature(int fd_pkg, int fd_sig)
646 struct fingerprint_list *trusted, *revoked;
647 struct fingerprint *fingerprint;
650 int trusted_count, revoked_count;
651 const char *fingerprints;
652 char path[MAXPATHLEN];
653 char hash[SHA256_DIGEST_LENGTH * 2 + 1];
656 trusted = revoked = NULL;
659 /* Read and parse fingerprints. */
660 if (config_string(FINGERPRINTS, &fingerprints) != 0) {
661 warnx("No CONFIG_FINGERPRINTS defined");
665 snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
666 if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
667 warnx("Error loading trusted certificates");
671 if (trusted_count == 0 || trusted == NULL) {
672 fprintf(stderr, "No trusted certificates found.\n");
676 snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
677 if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
678 warnx("Error loading revoked certificates");
682 /* Read certificate and signature in. */
683 if ((sc = parse_cert(fd_sig)) == NULL) {
684 warnx("Error parsing certificate");
687 /* Explicitly mark as non-trusted until proven otherwise. */
690 /* Parse signature and pubkey out of the certificate */
691 sha256_buf(sc->cert, sc->certlen, hash);
693 /* Check if this hash is revoked */
694 if (revoked != NULL) {
695 STAILQ_FOREACH(fingerprint, revoked, next) {
696 if (strcasecmp(fingerprint->hash, hash) == 0) {
697 fprintf(stderr, "The package was signed with "
698 "revoked certificate %s\n",
705 STAILQ_FOREACH(fingerprint, trusted, next) {
706 if (strcasecmp(fingerprint->hash, hash) == 0) {
708 sc->name = strdup(fingerprint->name);
713 if (sc->trusted == false) {
714 fprintf(stderr, "No trusted fingerprint found matching "
715 "package's certificate\n");
719 /* Verify the signature. */
720 printf("Verifying signature with trusted certificate %s... ", sc->name);
721 if (rsa_verify_cert(fd_pkg, sc->cert, sc->certlen, sc->sig,
722 sc->siglen) == false) {
723 fprintf(stderr, "Signature is not valid\n");
731 free_fingerprint_list(trusted);
733 free_fingerprint_list(revoked);
748 bootstrap_pkg(bool force)
752 char url[MAXPATHLEN];
753 char tmppkg[MAXPATHLEN];
754 char tmpsig[MAXPATHLEN];
755 const char *packagesite;
756 const char *signature_type;
757 char pkgstatic[MAXPATHLEN];
762 if (config_string(PACKAGESITE, &packagesite) != 0) {
763 warnx("No PACKAGESITE defined");
767 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
768 warnx("Error looking up SIGNATURE_TYPE");
772 printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
774 /* Support pkg+http:// for PACKAGESITE which is the new format
775 in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
777 if (strncmp(URL_SCHEME_PREFIX, packagesite,
778 strlen(URL_SCHEME_PREFIX)) == 0)
779 packagesite += strlen(URL_SCHEME_PREFIX);
780 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
782 snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
783 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
785 if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
788 if (signature_type != NULL &&
789 strcasecmp(signature_type, "FINGERPRINTS") == 0) {
790 snprintf(tmpsig, MAXPATHLEN, "%s/pkg.txz.sig.XXXXXX",
791 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
792 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.sig",
795 if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
796 fprintf(stderr, "Signature for pkg not available.\n");
800 if (verify_signature(fd_pkg, fd_sig) == false)
804 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
805 ret = install_pkg_static(pkgstatic, tmppkg, force);
810 warnx("Error fetching %s: %s", url, fetchLastErrString);
811 fprintf(stderr, "A pre-built version of pkg could not be found for "
813 fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
814 "ports: 'ports-mgmt/pkg'.\n");
827 static const char confirmation_message[] =
828 "The package management tool is not yet installed on your system.\n"
829 "Do you want to fetch and install it now? [y/N]: ";
832 pkg_query_yes_no(void)
838 if (c == 'y' || c == 'Y')
843 while (c != '\n' && c != EOF)
850 bootstrap_pkg_local(const char *pkgpath, bool force)
852 char path[MAXPATHLEN];
853 char pkgstatic[MAXPATHLEN];
854 const char *signature_type;
855 int fd_pkg, fd_sig, ret;
860 fd_pkg = open(pkgpath, O_RDONLY);
862 err(EXIT_FAILURE, "Unable to open %s", pkgpath);
864 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
865 warnx("Error looking up SIGNATURE_TYPE");
868 if (signature_type != NULL &&
869 strcasecmp(signature_type, "FINGERPRINTS") == 0) {
870 snprintf(path, sizeof(path), "%s.sig", pkgpath);
872 if ((fd_sig = open(path, O_RDONLY)) == -1) {
873 fprintf(stderr, "Signature for pkg not available.\n");
877 if (verify_signature(fd_pkg, fd_sig) == false)
881 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
882 ret = install_pkg_static(pkgstatic, pkgpath, force);
893 main(__unused int argc, char *argv[])
895 char pkgpath[MAXPATHLEN];
897 bool bootstrap_only, force, yes;
899 bootstrap_only = false;
904 snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
905 getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
907 if (argc > 1 && strcmp(argv[1], "bootstrap") == 0) {
908 bootstrap_only = true;
909 if (argc == 3 && strcmp(argv[2], "-f") == 0)
913 if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
915 * To allow 'pkg -N' to be used as a reliable test for whether
916 * a system is configured to use pkg, don't bootstrap pkg
917 * when that argument is given as argv[1].
919 if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
920 errx(EXIT_FAILURE, "pkg is not installed");
924 if (argc > 1 && strcmp(argv[1], "add") == 0) {
925 if (argc > 2 && strcmp(argv[2], "-f") == 0) {
930 if (pkgarg == NULL) {
931 fprintf(stderr, "Path to pkg.txz required\n");
934 if (access(pkgarg, R_OK) == -1) {
935 fprintf(stderr, "No such file: %s\n", pkgarg);
938 if (bootstrap_pkg_local(pkgarg, force) != 0)
943 * Do not ask for confirmation if either of stdin or stdout is
944 * not tty. Check the environment to see if user has answer
945 * tucked in there already.
947 config_bool(ASSUME_ALWAYS_YES, &yes);
949 printf("%s", confirmation_message);
950 if (!isatty(fileno(stdin)))
953 if (pkg_query_yes_no() == 0)
956 if (bootstrap_pkg(force) != 0)
962 } else if (bootstrap_only) {
963 printf("pkg already bootstrapped at %s\n", pkgpath);
967 execv(pkgpath, argv);
970 return (EXIT_FAILURE);