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_compression_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(ucl_object_t *obj)
274 ucl_object_iter_t it = NULL;
275 const char *function, *fp, *key;
276 struct fingerprint *f;
277 hash_t fct = HASH_UNKNOWN;
279 function = fp = NULL;
281 while ((cur = ucl_iterate_object(obj, &it, true))) {
282 key = ucl_object_key(cur);
283 if (cur->type != UCL_STRING)
285 if (strcasecmp(key, "function") == 0) {
286 function = ucl_object_tostring(cur);
289 if (strcasecmp(key, "fingerprint") == 0) {
290 fp = ucl_object_tostring(cur);
295 if (fp == NULL || function == NULL)
298 if (strcasecmp(function, "sha256") == 0)
301 if (fct == HASH_UNKNOWN) {
302 warnx("Unsupported hashing function: %s", function);
306 f = calloc(1, sizeof(struct fingerprint));
308 strlcpy(f->hash, fp, sizeof(f->hash));
314 free_fingerprint_list(struct fingerprint_list* list)
316 struct fingerprint *fingerprint, *tmp;
318 STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
319 free(fingerprint->name);
325 static struct fingerprint *
326 load_fingerprint(const char *dir, const char *filename)
328 ucl_object_t *obj = NULL;
329 struct ucl_parser *p = NULL;
330 struct fingerprint *f;
331 char path[MAXPATHLEN];
335 snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
337 p = ucl_parser_new(0);
338 if (!ucl_parser_add_file(p, path)) {
339 warnx("%s: %s", path, ucl_parser_get_error(p));
344 obj = ucl_parser_get_object(p);
346 if (obj->type == UCL_OBJECT)
347 f = parse_fingerprint(obj);
350 f->name = strdup(filename);
352 ucl_object_free(obj);
358 static struct fingerprint_list *
359 load_fingerprints(const char *path, int *count)
363 struct fingerprint *finger;
364 struct fingerprint_list *fingerprints;
368 fingerprints = calloc(1, sizeof(struct fingerprint_list));
369 if (fingerprints == NULL)
371 STAILQ_INIT(fingerprints);
373 if ((d = opendir(path)) == NULL)
376 while ((ent = readdir(d))) {
377 if (strcmp(ent->d_name, ".") == 0 ||
378 strcmp(ent->d_name, "..") == 0)
380 finger = load_fingerprint(path, ent->d_name);
381 if (finger != NULL) {
382 STAILQ_INSERT_TAIL(fingerprints, finger, next);
389 return (fingerprints);
393 sha256_hash(unsigned char hash[SHA256_DIGEST_LENGTH],
394 char out[SHA256_DIGEST_LENGTH * 2 + 1])
398 for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
399 sprintf(out + (i * 2), "%02x", hash[i]);
401 out[SHA256_DIGEST_LENGTH * 2] = '\0';
405 sha256_buf_bin(char *buf, size_t len, char hash[SHA256_DIGEST_LENGTH])
409 SHA256_Init(&sha256);
410 SHA256_Update(&sha256, buf, len);
411 SHA256_Final(hash, &sha256);
416 sha256_buf(char *buf, size_t len, char out[SHA256_DIGEST_LENGTH * 2 + 1])
418 unsigned char hash[SHA256_DIGEST_LENGTH];
423 SHA256_Init(&sha256);
424 SHA256_Update(&sha256, buf, len);
425 SHA256_Final(hash, &sha256);
426 sha256_hash(hash, out);
430 sha256_fd(int fd, char out[SHA256_DIGEST_LENGTH * 2 + 1])
435 unsigned char hash[SHA256_DIGEST_LENGTH];
447 /* Duplicate the fd so that fclose(3) does not close it. */
448 if ((my_fd = dup(fd)) == -1) {
453 if ((fp = fdopen(my_fd, "rb")) == NULL) {
458 SHA256_Init(&sha256);
460 while ((r = fread(buffer, 1, BUFSIZ, fp)) > 0)
461 SHA256_Update(&sha256, buffer, r);
463 if (ferror(fp) != 0) {
468 SHA256_Final(hash, &sha256);
469 sha256_hash(hash, out);
475 else if (my_fd != -1)
477 (void)lseek(fd, 0, SEEK_SET);
483 load_rsa_public_key_buf(unsigned char *cert, int certlen)
489 bp = BIO_new_mem_buf((void *)cert, certlen);
490 if (!PEM_read_bio_RSA_PUBKEY(bp, &rsa, NULL, NULL)) {
491 warn("error reading public key: %s",
492 ERR_error_string(ERR_get_error(), errbuf));
502 rsa_verify_cert(int fd, unsigned char *key, int keylen,
503 unsigned char *sig, int siglen)
505 char sha256[SHA256_DIGEST_LENGTH *2 +1];
506 char hash[SHA256_DIGEST_LENGTH];
511 lseek(fd, 0, SEEK_SET);
512 sha256_fd(fd, sha256);
514 SSL_load_error_strings();
515 OpenSSL_add_all_algorithms();
516 OpenSSL_add_all_ciphers();
518 sha256_buf_bin(sha256, strlen(sha256), hash);
520 rsa = load_rsa_public_key_buf(key, keylen);
523 ret = RSA_verify(NID_sha256, hash, sizeof(hash), sig, siglen, rsa);
525 warnx("%s: %s", key, ERR_error_string(ERR_get_error(), errbuf));
535 static struct sig_cert *
540 struct sbuf *buf, *sig, *cert;
551 if (lseek(fd, 0, 0) == -1) {
556 /* Duplicate the fd so that fclose(3) does not close it. */
557 if ((my_fd = dup(fd)) == -1) {
562 if ((fp = fdopen(my_fd, "rb")) == NULL) {
568 sig = sbuf_new_auto();
569 cert = sbuf_new_auto();
571 while ((linelen = getline(&line, &linecap, fp)) > 0) {
572 if (strcmp(line, "SIGNATURE\n") == 0) {
575 } else if (strcmp(line, "CERT\n") == 0) {
578 } else if (strcmp(line, "END\n") == 0) {
582 sbuf_bcat(buf, line, linelen);
587 /* Trim out unrelated trailing newline */
588 sbuf_setpos(sig, sbuf_len(sig) - 1);
593 sc = calloc(1, sizeof(struct sig_cert));
594 sc->siglen = sbuf_len(sig);
595 sc->sig = calloc(1, sc->siglen);
596 memcpy(sc->sig, sbuf_data(sig), sc->siglen);
598 sc->certlen = sbuf_len(cert);
599 sc->cert = strdup(sbuf_data(cert));
608 verify_signature(int fd_pkg, int fd_sig)
610 struct fingerprint_list *trusted, *revoked;
611 struct fingerprint *fingerprint;
614 int trusted_count, revoked_count;
615 const char *fingerprints;
616 char path[MAXPATHLEN];
617 char hash[SHA256_DIGEST_LENGTH * 2 + 1];
620 trusted = revoked = NULL;
623 /* Read and parse fingerprints. */
624 if (config_string(FINGERPRINTS, &fingerprints) != 0) {
625 warnx("No CONFIG_FINGERPRINTS defined");
629 snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
630 if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
631 warnx("Error loading trusted certificates");
635 if (trusted_count == 0 || trusted == NULL) {
636 fprintf(stderr, "No trusted certificates found.\n");
640 snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
641 if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
642 warnx("Error loading revoked certificates");
646 /* Read certificate and signature in. */
647 if ((sc = parse_cert(fd_sig)) == NULL) {
648 warnx("Error parsing certificate");
651 /* Explicitly mark as non-trusted until proven otherwise. */
654 /* Parse signature and pubkey out of the certificate */
655 sha256_buf(sc->cert, sc->certlen, hash);
657 /* Check if this hash is revoked */
658 if (revoked != NULL) {
659 STAILQ_FOREACH(fingerprint, revoked, next) {
660 if (strcasecmp(fingerprint->hash, hash) == 0) {
661 fprintf(stderr, "The package was signed with "
662 "revoked certificate %s\n",
669 STAILQ_FOREACH(fingerprint, trusted, next) {
670 if (strcasecmp(fingerprint->hash, hash) == 0) {
672 sc->name = strdup(fingerprint->name);
677 if (sc->trusted == false) {
678 fprintf(stderr, "No trusted fingerprint found matching "
679 "package's certificate\n");
683 /* Verify the signature. */
684 printf("Verifying signature with trusted certificate %s... ", sc->name);
685 if (rsa_verify_cert(fd_pkg, sc->cert, sc->certlen, sc->sig,
686 sc->siglen) == false) {
688 fprintf(stderr, "Signature is not valid\n");
697 free_fingerprint_list(trusted);
699 free_fingerprint_list(revoked);
711 bootstrap_pkg(bool force)
715 char url[MAXPATHLEN];
716 char tmppkg[MAXPATHLEN];
717 char tmpsig[MAXPATHLEN];
718 const char *packagesite;
719 const char *signature_type;
720 char pkgstatic[MAXPATHLEN];
725 if (config_string(PACKAGESITE, &packagesite) != 0) {
726 warnx("No PACKAGESITE defined");
730 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
731 warnx("Error looking up SIGNATURE_TYPE");
735 printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
737 /* Support pkg+http:// for PACKAGESITE which is the new format
738 in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
740 if (strncmp(URL_SCHEME_PREFIX, packagesite,
741 strlen(URL_SCHEME_PREFIX)) == 0)
742 packagesite += strlen(URL_SCHEME_PREFIX);
743 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
745 snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
746 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
748 if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
751 if (signature_type != NULL &&
752 strcasecmp(signature_type, "NONE") != 0) {
753 if (strcasecmp(signature_type, "FINGERPRINTS") != 0) {
754 warnx("Signature type %s is not supported for "
755 "bootstrapping.", signature_type);
759 snprintf(tmpsig, MAXPATHLEN, "%s/pkg.txz.sig.XXXXXX",
760 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
761 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.sig",
764 if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
765 fprintf(stderr, "Signature for pkg not available.\n");
769 if (verify_signature(fd_pkg, fd_sig) == false)
773 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
774 ret = install_pkg_static(pkgstatic, tmppkg, force);
779 warnx("Error fetching %s: %s", url, fetchLastErrString);
780 fprintf(stderr, "A pre-built version of pkg could not be found for "
782 fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
783 "ports: 'ports-mgmt/pkg'.\n");
796 static const char confirmation_message[] =
797 "The package management tool is not yet installed on your system.\n"
798 "Do you want to fetch and install it now? [y/N]: ";
800 static const char non_interactive_message[] =
801 "The package management tool is not yet installed on your system.\n"
802 "Please set ASSUME_ALWAYS_YES=yes environment variable to be able to bootstrap "
803 "in non-interactive (stdin not being a tty)\n";
806 pkg_query_yes_no(void)
812 if (c == 'y' || c == 'Y')
817 while (c != '\n' && c != EOF)
824 bootstrap_pkg_local(const char *pkgpath, bool force)
826 char path[MAXPATHLEN];
827 char pkgstatic[MAXPATHLEN];
828 const char *signature_type;
829 int fd_pkg, fd_sig, ret;
834 fd_pkg = open(pkgpath, O_RDONLY);
836 err(EXIT_FAILURE, "Unable to open %s", pkgpath);
838 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
839 warnx("Error looking up SIGNATURE_TYPE");
842 if (signature_type != NULL &&
843 strcasecmp(signature_type, "NONE") != 0) {
844 if (strcasecmp(signature_type, "FINGERPRINTS") != 0) {
845 warnx("Signature type %s is not supported for "
846 "bootstrapping.", signature_type);
850 snprintf(path, sizeof(path), "%s.sig", pkgpath);
852 if ((fd_sig = open(path, O_RDONLY)) == -1) {
853 fprintf(stderr, "Signature for pkg not available.\n");
857 if (verify_signature(fd_pkg, fd_sig) == false)
861 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
862 ret = install_pkg_static(pkgstatic, pkgpath, force);
873 main(int argc, char *argv[])
875 char pkgpath[MAXPATHLEN];
877 bool bootstrap_only, force, yes;
879 bootstrap_only = false;
884 snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
885 getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
887 if (argc > 1 && strcmp(argv[1], "bootstrap") == 0) {
888 bootstrap_only = true;
889 if (argc == 3 && strcmp(argv[2], "-f") == 0)
893 if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
895 * To allow 'pkg -N' to be used as a reliable test for whether
896 * a system is configured to use pkg, don't bootstrap pkg
897 * when that argument is given as argv[1].
899 if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
900 errx(EXIT_FAILURE, "pkg is not installed");
904 if (argc > 1 && strcmp(argv[1], "add") == 0) {
905 if (argc > 2 && strcmp(argv[2], "-f") == 0) {
910 if (pkgarg == NULL) {
911 fprintf(stderr, "Path to pkg.txz required\n");
914 if (access(pkgarg, R_OK) == -1) {
915 fprintf(stderr, "No such file: %s\n", pkgarg);
918 if (bootstrap_pkg_local(pkgarg, force) != 0)
923 * Do not ask for confirmation if either of stdin or stdout is
924 * not tty. Check the environment to see if user has answer
925 * tucked in there already.
927 config_bool(ASSUME_ALWAYS_YES, &yes);
929 if (!isatty(fileno(stdin))) {
930 fprintf(stderr, non_interactive_message);
934 printf("%s", confirmation_message);
935 if (pkg_query_yes_no() == 0)
938 if (bootstrap_pkg(force) != 0)
944 } else if (bootstrap_only) {
945 printf("pkg already bootstrapped at %s\n", pkgpath);
949 execv(pkgpath, argv);
952 return (EXIT_FAILURE);