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("failed to extract pkg-static: %s",
130 archive_error_string(a));
133 archive_read_free(a);
139 install_pkg_static(const char *path, const char *pkgpath, bool force)
144 switch ((pid = fork())) {
149 execl(path, "pkg-static", "add", "-f", pkgpath,
152 execl(path, "pkg-static", "add", pkgpath,
159 while (waitpid(pid, &pstat, 0) == -1)
163 if (WEXITSTATUS(pstat))
164 return (WEXITSTATUS(pstat));
165 else if (WIFSIGNALED(pstat))
166 return (128 & (WTERMSIG(pstat)));
171 fetch_to_fd(const char *url, char *path)
174 struct dns_srvinfo *mirrors, *current;
177 /* To store _https._tcp. + hostname + \0 */
179 int retry, max_retry;
183 char zone[MAXHOSTNAMELEN + 13];
184 static const char *mirror_type = NULL;
189 current = mirrors = NULL;
192 if (mirror_type == NULL && config_string(MIRROR_TYPE, &mirror_type)
194 warnx("No MIRROR_TYPE defined");
198 if ((fd = mkstemp(path)) == -1) {
205 if ((u = fetchParseURL(url)) == NULL) {
206 warn("fetchParseURL('%s')", url);
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);
221 if (mirrors != NULL) {
222 strlcpy(u->host, current->host, sizeof(u->host));
223 u->port = current->port;
226 remote = fetchXGet(u, &st, "");
227 if (remote == NULL) {
231 if (mirrors == NULL) {
234 current = current->next;
241 while (done < st.size) {
242 if ((r = fread(buf, 1, sizeof(buf), remote)) < 1)
245 if (write(fd, buf, r) != r) {
252 if (now > last || done == st.size)
275 static struct fingerprint *
276 parse_fingerprint(ucl_object_t *obj)
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;
284 function = fp = NULL;
286 while ((cur = ucl_iterate_object(obj, &it, true))) {
287 key = ucl_object_key(cur);
288 if (cur->type != UCL_STRING)
290 if (strcasecmp(key, "function") == 0) {
291 function = ucl_object_tostring(cur);
294 if (strcasecmp(key, "fingerprint") == 0) {
295 fp = ucl_object_tostring(cur);
300 if (fp == NULL || function == NULL)
303 if (strcasecmp(function, "sha256") == 0)
306 if (fct == HASH_UNKNOWN) {
307 warnx("Unsupported hashing function: %s", function);
311 f = calloc(1, sizeof(struct fingerprint));
313 strlcpy(f->hash, fp, sizeof(f->hash));
319 free_fingerprint_list(struct fingerprint_list* list)
321 struct fingerprint *fingerprint, *tmp;
323 STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
324 free(fingerprint->name);
330 static struct fingerprint *
331 load_fingerprint(const char *dir, const char *filename)
333 ucl_object_t *obj = NULL;
334 struct ucl_parser *p = NULL;
335 struct fingerprint *f;
336 char path[MAXPATHLEN];
340 snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
342 p = ucl_parser_new(0);
343 if (!ucl_parser_add_file(p, path)) {
344 warnx("%s: %s", path, ucl_parser_get_error(p));
349 obj = ucl_parser_get_object(p);
351 if (obj->type == UCL_OBJECT)
352 f = parse_fingerprint(obj);
355 f->name = strdup(filename);
357 ucl_object_unref(obj);
363 static struct fingerprint_list *
364 load_fingerprints(const char *path, int *count)
368 struct fingerprint *finger;
369 struct fingerprint_list *fingerprints;
373 fingerprints = calloc(1, sizeof(struct fingerprint_list));
374 if (fingerprints == NULL)
376 STAILQ_INIT(fingerprints);
378 if ((d = opendir(path)) == NULL) {
384 while ((ent = readdir(d))) {
385 if (strcmp(ent->d_name, ".") == 0 ||
386 strcmp(ent->d_name, "..") == 0)
388 finger = load_fingerprint(path, ent->d_name);
389 if (finger != NULL) {
390 STAILQ_INSERT_TAIL(fingerprints, finger, next);
397 return (fingerprints);
401 sha256_hash(unsigned char hash[SHA256_DIGEST_LENGTH],
402 char out[SHA256_DIGEST_LENGTH * 2 + 1])
406 for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
407 sprintf(out + (i * 2), "%02x", hash[i]);
409 out[SHA256_DIGEST_LENGTH * 2] = '\0';
413 sha256_buf(char *buf, size_t len, char out[SHA256_DIGEST_LENGTH * 2 + 1])
415 unsigned char hash[SHA256_DIGEST_LENGTH];
420 SHA256_Init(&sha256);
421 SHA256_Update(&sha256, buf, len);
422 SHA256_Final(hash, &sha256);
423 sha256_hash(hash, out);
427 sha256_fd(int fd, char out[SHA256_DIGEST_LENGTH * 2 + 1])
432 unsigned char hash[SHA256_DIGEST_LENGTH];
444 /* Duplicate the fd so that fclose(3) does not close it. */
445 if ((my_fd = dup(fd)) == -1) {
450 if ((fp = fdopen(my_fd, "rb")) == NULL) {
455 SHA256_Init(&sha256);
457 while ((r = fread(buffer, 1, BUFSIZ, fp)) > 0)
458 SHA256_Update(&sha256, buffer, r);
460 if (ferror(fp) != 0) {
465 SHA256_Final(hash, &sha256);
466 sha256_hash(hash, out);
472 else if (my_fd != -1)
474 (void)lseek(fd, 0, SEEK_SET);
480 load_public_key_buf(const unsigned char *cert, int certlen)
486 bp = BIO_new_mem_buf(__DECONST(void *, cert), certlen);
488 if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
489 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
497 rsa_verify_cert(int fd, const unsigned char *key, int keylen,
498 unsigned char *sig, int siglen)
502 char sha256[(SHA256_DIGEST_LENGTH * 2) + 2];
510 /* Compute SHA256 of the package. */
511 if (lseek(fd, 0, 0) == -1) {
515 if ((sha256_fd(fd, sha256)) == -1) {
516 warnx("Error creating SHA256 hash for package");
520 if ((pkey = load_public_key_buf(key, keylen)) == NULL) {
521 warnx("Error reading public key");
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));
531 if (EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
532 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
535 if (EVP_DigestVerifyUpdate(mdctx, sha256, strlen(sha256)) != 1) {
536 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
540 if (EVP_DigestVerifyFinal(mdctx, sig, siglen) != 1) {
541 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
556 EVP_MD_CTX_destroy(mdctx);
562 static struct sig_cert *
567 struct sbuf *buf, *sig, *cert;
578 if (lseek(fd, 0, 0) == -1) {
583 /* Duplicate the fd so that fclose(3) does not close it. */
584 if ((my_fd = dup(fd)) == -1) {
589 if ((fp = fdopen(my_fd, "rb")) == NULL) {
595 sig = sbuf_new_auto();
596 cert = sbuf_new_auto();
598 while ((linelen = getline(&line, &linecap, fp)) > 0) {
599 if (strcmp(line, "SIGNATURE\n") == 0) {
602 } else if (strcmp(line, "CERT\n") == 0) {
605 } else if (strcmp(line, "END\n") == 0) {
609 sbuf_bcat(buf, line, linelen);
614 /* Trim out unrelated trailing newline */
615 sbuf_setpos(sig, sbuf_len(sig) - 1);
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);
625 sc->certlen = sbuf_len(cert);
626 sc->cert = strdup(sbuf_data(cert));
635 verify_signature(int fd_pkg, int fd_sig)
637 struct fingerprint_list *trusted, *revoked;
638 struct fingerprint *fingerprint;
641 int trusted_count, revoked_count;
642 const char *fingerprints;
643 char path[MAXPATHLEN];
644 char hash[SHA256_DIGEST_LENGTH * 2 + 1];
647 trusted = revoked = NULL;
650 /* Read and parse fingerprints. */
651 if (config_string(FINGERPRINTS, &fingerprints) != 0) {
652 warnx("No CONFIG_FINGERPRINTS defined");
656 snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
657 if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
658 warnx("Error loading trusted certificates");
662 if (trusted_count == 0 || trusted == NULL) {
663 fprintf(stderr, "No trusted certificates found.\n");
667 snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
668 if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
669 warnx("Error loading revoked certificates");
673 /* Read certificate and signature in. */
674 if ((sc = parse_cert(fd_sig)) == NULL) {
675 warnx("Error parsing certificate");
678 /* Explicitly mark as non-trusted until proven otherwise. */
681 /* Parse signature and pubkey out of the certificate */
682 sha256_buf(sc->cert, sc->certlen, hash);
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",
696 STAILQ_FOREACH(fingerprint, trusted, next) {
697 if (strcasecmp(fingerprint->hash, hash) == 0) {
699 sc->name = strdup(fingerprint->name);
704 if (sc->trusted == false) {
705 fprintf(stderr, "No trusted fingerprint found matching "
706 "package's certificate\n");
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");
722 free_fingerprint_list(trusted);
724 free_fingerprint_list(revoked);
736 bootstrap_pkg(bool force)
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];
750 if (config_string(PACKAGESITE, &packagesite) != 0) {
751 warnx("No PACKAGESITE defined");
755 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
756 warnx("Error looking up SIGNATURE_TYPE");
760 printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
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
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);
770 snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
771 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
773 if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
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",
783 if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
784 fprintf(stderr, "Signature for pkg not available.\n");
788 if (verify_signature(fd_pkg, fd_sig) == false)
792 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
793 ret = install_pkg_static(pkgstatic, tmppkg, force);
798 warnx("Error fetching %s: %s", url, fetchLastErrString);
799 fprintf(stderr, "A pre-built version of pkg could not be found for "
801 fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
802 "ports: 'ports-mgmt/pkg'.\n");
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]: ";
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";
828 pkg_query_yes_no(void)
834 if (c == 'y' || c == 'Y')
839 while (c != '\n' && c != EOF)
846 bootstrap_pkg_local(const char *pkgpath, bool force)
848 char path[MAXPATHLEN];
849 char pkgstatic[MAXPATHLEN];
850 const char *signature_type;
851 int fd_pkg, fd_sig, ret;
856 fd_pkg = open(pkgpath, O_RDONLY);
858 err(EXIT_FAILURE, "Unable to open %s", pkgpath);
860 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
861 warnx("Error looking up SIGNATURE_TYPE");
864 if (signature_type != NULL &&
865 strcasecmp(signature_type, "FINGERPRINTS") == 0) {
866 snprintf(path, sizeof(path), "%s.sig", pkgpath);
868 if ((fd_sig = open(path, O_RDONLY)) == -1) {
869 fprintf(stderr, "Signature for pkg not available.\n");
873 if (verify_signature(fd_pkg, fd_sig) == false)
877 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
878 ret = install_pkg_static(pkgstatic, pkgpath, force);
889 main(int argc, char *argv[])
891 char pkgpath[MAXPATHLEN];
893 bool bootstrap_only, force, yes;
895 bootstrap_only = false;
900 snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
901 getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
903 if (argc > 1 && strcmp(argv[1], "bootstrap") == 0) {
904 bootstrap_only = true;
905 if (argc == 3 && strcmp(argv[2], "-f") == 0)
909 if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
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].
915 if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
916 errx(EXIT_FAILURE, "pkg is not installed");
920 if (argc > 1 && strcmp(argv[1], "add") == 0) {
921 if (argc > 2 && strcmp(argv[2], "-f") == 0) {
926 if (pkgarg == NULL) {
927 fprintf(stderr, "Path to pkg.txz required\n");
930 if (access(pkgarg, R_OK) == -1) {
931 fprintf(stderr, "No such file: %s\n", pkgarg);
934 if (bootstrap_pkg_local(pkgarg, force) != 0)
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.
943 config_bool(ASSUME_ALWAYS_YES, &yes);
945 if (!isatty(fileno(stdin))) {
946 fprintf(stderr, non_interactive_message);
950 printf("%s", confirmation_message);
951 if (pkg_query_yes_no() == 0)
954 if (bootstrap_pkg(force) != 0)
960 } else if (bootstrap_only) {
961 printf("pkg already bootstrapped at %s\n", pkgpath);
965 execv(pkgpath, argv);
968 return (EXIT_FAILURE);