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;
236 while (done < st.size) {
237 if ((r = fread(buf, 1, sizeof(buf), remote)) < 1)
240 if (write(fd, buf, r) != r) {
247 if (now > last || done == st.size)
270 static struct fingerprint *
271 parse_fingerprint(yaml_document_t *doc, yaml_node_t *node)
273 yaml_node_pair_t *pair;
274 yaml_char_t *function, *fp;
275 struct fingerprint *f;
276 hash_t fct = HASH_UNKNOWN;
278 function = fp = NULL;
280 pair = node->data.mapping.pairs.start;
281 while (pair < node->data.mapping.pairs.top) {
282 yaml_node_t *key = yaml_document_get_node(doc, pair->key);
283 yaml_node_t *val = yaml_document_get_node(doc, pair->value);
285 if (key->data.scalar.length <= 0) {
290 if (val->type != YAML_SCALAR_NODE) {
295 if (strcasecmp(key->data.scalar.value, "function") == 0)
296 function = val->data.scalar.value;
297 else if (strcasecmp(key->data.scalar.value, "fingerprint")
299 fp = val->data.scalar.value;
305 if (fp == NULL || function == NULL)
308 if (strcasecmp(function, "sha256") == 0)
311 if (fct == HASH_UNKNOWN) {
312 fprintf(stderr, "Unsupported hashing function: %s\n", function);
316 f = calloc(1, sizeof(struct fingerprint));
318 strlcpy(f->hash, fp, sizeof(f->hash));
324 free_fingerprint_list(struct fingerprint_list* list)
326 struct fingerprint *fingerprint, *tmp;
328 STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
329 free(fingerprint->name);
335 static struct fingerprint *
336 load_fingerprint(const char *dir, const char *filename)
338 yaml_parser_t parser;
342 struct fingerprint *f;
343 char path[MAXPATHLEN];
347 snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
349 if ((fp = fopen(path, "r")) == NULL)
352 yaml_parser_initialize(&parser);
353 yaml_parser_set_input_file(&parser, fp);
354 yaml_parser_load(&parser, &doc);
356 node = yaml_document_get_root_node(&doc);
357 if (node == NULL || node->type != YAML_MAPPING_NODE)
360 f = parse_fingerprint(&doc, node);
361 f->name = strdup(filename);
364 yaml_document_delete(&doc);
365 yaml_parser_delete(&parser);
371 static struct fingerprint_list *
372 load_fingerprints(const char *path, int *count)
376 struct fingerprint *finger;
377 struct fingerprint_list *fingerprints;
381 fingerprints = calloc(1, sizeof(struct fingerprint_list));
382 if (fingerprints == NULL)
384 STAILQ_INIT(fingerprints);
386 if ((d = opendir(path)) == NULL)
389 while ((ent = readdir(d))) {
390 if (strcmp(ent->d_name, ".") == 0 ||
391 strcmp(ent->d_name, "..") == 0)
393 finger = load_fingerprint(path, ent->d_name);
394 if (finger != NULL) {
395 STAILQ_INSERT_TAIL(fingerprints, finger, next);
402 return (fingerprints);
406 sha256_hash(unsigned char hash[SHA256_DIGEST_LENGTH],
407 char out[SHA256_DIGEST_LENGTH * 2 + 1])
411 for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
412 sprintf(out + (i * 2), "%02x", hash[i]);
414 out[SHA256_DIGEST_LENGTH * 2] = '\0';
418 sha256_buf(char *buf, size_t len, char out[SHA256_DIGEST_LENGTH * 2 + 1])
420 unsigned char hash[SHA256_DIGEST_LENGTH];
425 SHA256_Init(&sha256);
426 SHA256_Update(&sha256, buf, len);
427 SHA256_Final(hash, &sha256);
428 sha256_hash(hash, out);
432 sha256_fd(int fd, char out[SHA256_DIGEST_LENGTH * 2 + 1])
437 unsigned char hash[SHA256_DIGEST_LENGTH];
449 /* Duplicate the fd so that fclose(3) does not close it. */
450 if ((my_fd = dup(fd)) == -1) {
455 if ((fp = fdopen(my_fd, "rb")) == NULL) {
460 SHA256_Init(&sha256);
462 while ((r = fread(buffer, 1, BUFSIZ, fp)) > 0)
463 SHA256_Update(&sha256, buffer, r);
465 if (ferror(fp) != 0) {
470 SHA256_Final(hash, &sha256);
471 sha256_hash(hash, out);
477 else if (my_fd != -1)
479 (void)lseek(fd, 0, SEEK_SET);
485 load_public_key_buf(const unsigned char *cert, int certlen)
491 bp = BIO_new_mem_buf(__DECONST(void *, cert), certlen);
493 if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
494 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
502 rsa_verify_cert(int fd, const unsigned char *key, int keylen,
503 unsigned char *sig, int siglen)
507 char sha256[(SHA256_DIGEST_LENGTH * 2) + 2];
515 /* Compute SHA256 of the package. */
516 if (lseek(fd, 0, 0) == -1) {
520 if ((sha256_fd(fd, sha256)) == -1) {
521 warnx("Error creating SHA256 hash for package");
525 if ((pkey = load_public_key_buf(key, keylen)) == NULL) {
526 warnx("Error reading public key");
530 /* Verify signature of the SHA256(pkg) is valid. */
531 if ((mdctx = EVP_MD_CTX_create()) == NULL) {
532 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
536 if (EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
537 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
540 if (EVP_DigestVerifyUpdate(mdctx, sha256, strlen(sha256)) != 1) {
541 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
545 if (EVP_DigestVerifyFinal(mdctx, sig, siglen) != 1) {
546 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
561 EVP_MD_CTX_destroy(mdctx);
567 static struct sig_cert *
572 struct sbuf *buf, *sig, *cert;
583 if (lseek(fd, 0, 0) == -1) {
588 /* Duplicate the fd so that fclose(3) does not close it. */
589 if ((my_fd = dup(fd)) == -1) {
594 if ((fp = fdopen(my_fd, "rb")) == NULL) {
600 sig = sbuf_new_auto();
601 cert = sbuf_new_auto();
603 while ((linelen = getline(&line, &linecap, fp)) > 0) {
604 if (strcmp(line, "SIGNATURE\n") == 0) {
607 } else if (strcmp(line, "CERT\n") == 0) {
610 } else if (strcmp(line, "END\n") == 0) {
614 sbuf_bcat(buf, line, linelen);
619 /* Trim out unrelated trailing newline */
620 sbuf_setpos(sig, sbuf_len(sig) - 1);
625 sc = calloc(1, sizeof(struct sig_cert));
626 sc->siglen = sbuf_len(sig);
627 sc->sig = calloc(1, sc->siglen);
628 memcpy(sc->sig, sbuf_data(sig), sc->siglen);
630 sc->certlen = sbuf_len(cert);
631 sc->cert = strdup(sbuf_data(cert));
640 verify_signature(int fd_pkg, int fd_sig)
642 struct fingerprint_list *trusted, *revoked;
643 struct fingerprint *fingerprint;
646 int trusted_count, revoked_count;
647 const char *fingerprints;
648 char path[MAXPATHLEN];
649 char hash[SHA256_DIGEST_LENGTH * 2 + 1];
652 trusted = revoked = NULL;
655 /* Read and parse fingerprints. */
656 if (config_string(FINGERPRINTS, &fingerprints) != 0) {
657 warnx("No CONFIG_FINGERPRINTS defined");
661 snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
662 if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
663 warnx("Error loading trusted certificates");
667 if (trusted_count == 0 || trusted == NULL) {
668 fprintf(stderr, "No trusted certificates found.\n");
672 snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
673 if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
674 warnx("Error loading revoked certificates");
678 /* Read certificate and signature in. */
679 if ((sc = parse_cert(fd_sig)) == NULL) {
680 warnx("Error parsing certificate");
683 /* Explicitly mark as non-trusted until proven otherwise. */
686 /* Parse signature and pubkey out of the certificate */
687 sha256_buf(sc->cert, sc->certlen, hash);
689 /* Check if this hash is revoked */
690 if (revoked != NULL) {
691 STAILQ_FOREACH(fingerprint, revoked, next) {
692 if (strcasecmp(fingerprint->hash, hash) == 0) {
693 fprintf(stderr, "The package was signed with "
694 "revoked certificate %s\n",
701 STAILQ_FOREACH(fingerprint, trusted, next) {
702 if (strcasecmp(fingerprint->hash, hash) == 0) {
704 sc->name = strdup(fingerprint->name);
709 if (sc->trusted == false) {
710 fprintf(stderr, "No trusted fingerprint found matching "
711 "package's certificate\n");
715 /* Verify the signature. */
716 printf("Verifying signature with trusted certificate %s... ", sc->name);
717 if (rsa_verify_cert(fd_pkg, sc->cert, sc->certlen, sc->sig,
718 sc->siglen) == false) {
719 fprintf(stderr, "Signature is not valid\n");
727 free_fingerprint_list(trusted);
729 free_fingerprint_list(revoked);
741 bootstrap_pkg(bool force)
745 char url[MAXPATHLEN];
746 char tmppkg[MAXPATHLEN];
747 char tmpsig[MAXPATHLEN];
748 const char *packagesite;
749 const char *signature_type;
750 char pkgstatic[MAXPATHLEN];
755 if (config_string(PACKAGESITE, &packagesite) != 0) {
756 warnx("No PACKAGESITE defined");
760 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
761 warnx("Error looking up SIGNATURE_TYPE");
765 printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
767 /* Support pkg+http:// for PACKAGESITE which is the new format
768 in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
770 if (strncmp(URL_SCHEME_PREFIX, packagesite,
771 strlen(URL_SCHEME_PREFIX)) == 0)
772 packagesite += strlen(URL_SCHEME_PREFIX);
773 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
775 snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
776 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
778 if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
781 if (signature_type != NULL &&
782 strcasecmp(signature_type, "FINGERPRINTS") == 0) {
783 snprintf(tmpsig, MAXPATHLEN, "%s/pkg.txz.sig.XXXXXX",
784 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
785 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.sig",
788 if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
789 fprintf(stderr, "Signature for pkg not available.\n");
793 if (verify_signature(fd_pkg, fd_sig) == false)
797 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
798 ret = install_pkg_static(pkgstatic, tmppkg, force);
803 warnx("Error fetching %s: %s", url, fetchLastErrString);
804 fprintf(stderr, "A pre-built version of pkg could not be found for "
806 fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
807 "ports: 'ports-mgmt/pkg'.\n");
820 static const char confirmation_message[] =
821 "The package management tool is not yet installed on your system.\n"
822 "Do you want to fetch and install it now? [y/N]: ";
825 pkg_query_yes_no(void)
831 if (c == 'y' || c == 'Y')
836 while (c != '\n' && c != EOF)
843 bootstrap_pkg_local(const char *pkgpath, bool force)
845 char path[MAXPATHLEN];
846 char pkgstatic[MAXPATHLEN];
847 const char *signature_type;
848 int fd_pkg, fd_sig, ret;
853 fd_pkg = open(pkgpath, O_RDONLY);
855 err(EXIT_FAILURE, "Unable to open %s", pkgpath);
857 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
858 warnx("Error looking up SIGNATURE_TYPE");
861 if (signature_type != NULL &&
862 strcasecmp(signature_type, "FINGERPRINTS") == 0) {
863 snprintf(path, sizeof(path), "%s.sig", pkgpath);
865 if ((fd_sig = open(path, O_RDONLY)) == -1) {
866 fprintf(stderr, "Signature for pkg not available.\n");
870 if (verify_signature(fd_pkg, fd_sig) == false)
874 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
875 ret = install_pkg_static(pkgstatic, pkgpath, force);
886 main(int argc, char *argv[])
888 char pkgpath[MAXPATHLEN];
890 bool bootstrap_only, force, yes;
892 bootstrap_only = false;
897 snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
898 getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
900 if (argc > 1 && strcmp(argv[1], "bootstrap") == 0) {
901 bootstrap_only = true;
902 if (argc == 3 && strcmp(argv[2], "-f") == 0)
906 if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
908 * To allow 'pkg -N' to be used as a reliable test for whether
909 * a system is configured to use pkg, don't bootstrap pkg
910 * when that argument is given as argv[1].
912 if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
913 errx(EXIT_FAILURE, "pkg is not installed");
917 if (argc > 1 && strcmp(argv[1], "add") == 0) {
918 if (argc > 2 && strcmp(argv[2], "-f") == 0) {
923 if (pkgarg == NULL) {
924 fprintf(stderr, "Path to pkg.txz required\n");
927 if (access(pkgarg, R_OK) == -1) {
928 fprintf(stderr, "No such file: %s\n", pkgarg);
931 if (bootstrap_pkg_local(pkgarg, force) != 0)
936 * Do not ask for confirmation if either of stdin or stdout is
937 * not tty. Check the environment to see if user has answer
938 * tucked in there already.
940 config_bool(ASSUME_ALWAYS_YES, &yes);
942 printf("%s", confirmation_message);
943 if (!isatty(fileno(stdin)))
946 if (pkg_query_yes_no() == 0)
949 if (bootstrap_pkg(force) != 0)
955 } else if (bootstrap_only) {
956 printf("pkg already bootstrapped at %s\n", pkgpath);
960 execv(pkgpath, argv);
963 return (EXIT_FAILURE);