2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2012-2014 Baptiste Daroussin <bapt@FreeBSD.org>
5 * Copyright (c) 2013 Bryan Drewery <bdrewery@FreeBSD.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
33 #include <sys/param.h>
34 #include <sys/queue.h>
35 #include <sys/types.h>
40 #include <archive_entry.h>
54 #include <openssl/err.h>
55 #include <openssl/ssl.h>
57 #include "dns_utils.h"
83 STAILQ_ENTRY(fingerprint) next;
86 STAILQ_HEAD(fingerprint_list, fingerprint);
89 extract_pkg_static(int fd, char *p, int sz)
92 struct archive_entry *ae;
97 a = archive_read_new();
99 warn("archive_read_new");
102 archive_read_support_filter_all(a);
103 archive_read_support_format_tar(a);
105 if (lseek(fd, 0, 0) == -1) {
110 if (archive_read_open_fd(a, fd, 4096) != ARCHIVE_OK) {
111 warnx("archive_read_open_fd: %s", archive_error_string(a));
116 while ((r = archive_read_next_header(a, &ae)) == ARCHIVE_OK) {
117 end = strrchr(archive_entry_pathname(ae), '/');
121 if (strcmp(end, "/pkg-static") == 0) {
122 r = archive_read_extract(a, ae,
123 ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM |
124 ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_ACL |
125 ARCHIVE_EXTRACT_FFLAGS | ARCHIVE_EXTRACT_XATTR);
126 strlcpy(p, archive_entry_pathname(ae), sz);
134 warnx("failed to extract pkg-static: %s",
135 archive_error_string(a));
138 archive_read_free(a);
144 install_pkg_static(const char *path, const char *pkgpath, bool force)
149 switch ((pid = fork())) {
154 execl(path, "pkg-static", "add", "-f", pkgpath,
157 execl(path, "pkg-static", "add", pkgpath,
164 while (waitpid(pid, &pstat, 0) == -1)
168 if (WEXITSTATUS(pstat))
169 return (WEXITSTATUS(pstat));
170 else if (WIFSIGNALED(pstat))
171 return (128 & (WTERMSIG(pstat)));
176 fetch_to_fd(const char *url, char *path)
179 struct dns_srvinfo *mirrors, *current;
182 /* To store _https._tcp. + hostname + \0 */
184 int retry, max_retry;
187 char zone[MAXHOSTNAMELEN + 13];
188 static const char *mirror_type = NULL;
191 current = mirrors = NULL;
194 if (mirror_type == NULL && config_string(MIRROR_TYPE, &mirror_type)
196 warnx("No MIRROR_TYPE defined");
200 if ((fd = mkstemp(path)) == -1) {
207 if ((u = fetchParseURL(url)) == NULL) {
208 warn("fetchParseURL('%s')", url);
212 while (remote == NULL) {
213 if (retry == max_retry) {
214 if (strcmp(u->scheme, "file") != 0 &&
215 strcasecmp(mirror_type, "srv") == 0) {
216 snprintf(zone, sizeof(zone),
217 "_%s._tcp.%s", u->scheme, u->host);
218 mirrors = dns_getsrvinfo(zone);
223 if (mirrors != NULL) {
224 strlcpy(u->host, current->host, sizeof(u->host));
225 u->port = current->port;
228 remote = fetchXGet(u, &st, "");
229 if (remote == NULL) {
233 if (mirrors == NULL) {
236 current = current->next;
243 while ((r = fread(buf, 1, sizeof(buf), remote)) > 0) {
244 if (write(fd, buf, r) != r) {
251 warn("An error occurred while fetching pkg(8)");
274 static struct fingerprint *
275 parse_fingerprint(ucl_object_t *obj)
277 const ucl_object_t *cur;
278 ucl_object_iter_t it = NULL;
279 const char *function, *fp, *key;
280 struct fingerprint *f;
281 hash_t fct = HASH_UNKNOWN;
283 function = fp = NULL;
285 while ((cur = ucl_iterate_object(obj, &it, true))) {
286 key = ucl_object_key(cur);
287 if (cur->type != UCL_STRING)
289 if (strcasecmp(key, "function") == 0) {
290 function = ucl_object_tostring(cur);
293 if (strcasecmp(key, "fingerprint") == 0) {
294 fp = ucl_object_tostring(cur);
299 if (fp == NULL || function == NULL)
302 if (strcasecmp(function, "sha256") == 0)
305 if (fct == HASH_UNKNOWN) {
306 warnx("Unsupported hashing function: %s", function);
310 f = calloc(1, sizeof(struct fingerprint));
312 strlcpy(f->hash, fp, sizeof(f->hash));
318 free_fingerprint_list(struct fingerprint_list* list)
320 struct fingerprint *fingerprint, *tmp;
322 STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
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_unref(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) {
383 while ((ent = readdir(d))) {
384 if (strcmp(ent->d_name, ".") == 0 ||
385 strcmp(ent->d_name, "..") == 0)
387 finger = load_fingerprint(path, ent->d_name);
388 if (finger != NULL) {
389 STAILQ_INSERT_TAIL(fingerprints, finger, next);
396 return (fingerprints);
400 sha256_hash(unsigned char hash[SHA256_DIGEST_LENGTH],
401 char out[SHA256_DIGEST_LENGTH * 2 + 1])
405 for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
406 sprintf(out + (i * 2), "%02x", hash[i]);
408 out[SHA256_DIGEST_LENGTH * 2] = '\0';
412 sha256_buf(char *buf, size_t len, char out[SHA256_DIGEST_LENGTH * 2 + 1])
414 unsigned char hash[SHA256_DIGEST_LENGTH];
419 SHA256_Init(&sha256);
420 SHA256_Update(&sha256, buf, len);
421 SHA256_Final(hash, &sha256);
422 sha256_hash(hash, out);
426 sha256_fd(int fd, char out[SHA256_DIGEST_LENGTH * 2 + 1])
431 unsigned char hash[SHA256_DIGEST_LENGTH];
443 /* Duplicate the fd so that fclose(3) does not close it. */
444 if ((my_fd = dup(fd)) == -1) {
449 if ((fp = fdopen(my_fd, "rb")) == NULL) {
454 SHA256_Init(&sha256);
456 while ((r = fread(buffer, 1, BUFSIZ, fp)) > 0)
457 SHA256_Update(&sha256, buffer, r);
459 if (ferror(fp) != 0) {
464 SHA256_Final(hash, &sha256);
465 sha256_hash(hash, out);
471 else if (my_fd != -1)
473 (void)lseek(fd, 0, SEEK_SET);
479 load_public_key_file(const char *file)
485 bp = BIO_new_file(file, "r");
487 errx(EXIT_FAILURE, "Unable to read %s", file);
489 if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
490 warnx("ici: %s", ERR_error_string(ERR_get_error(), errbuf));
498 load_public_key_buf(const unsigned char *cert, int certlen)
504 bp = BIO_new_mem_buf(__DECONST(void *, cert), certlen);
506 if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
507 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
515 rsa_verify_cert(int fd, const char *sigfile, const unsigned char *key,
516 int keylen, unsigned char *sig, int siglen)
520 char sha256[(SHA256_DIGEST_LENGTH * 2) + 2];
528 SSL_load_error_strings();
530 /* Compute SHA256 of the package. */
531 if (lseek(fd, 0, 0) == -1) {
535 if ((sha256_fd(fd, sha256)) == -1) {
536 warnx("Error creating SHA256 hash for package");
540 if (sigfile != NULL) {
541 if ((pkey = load_public_key_file(sigfile)) == NULL) {
542 warnx("Error reading public key");
546 if ((pkey = load_public_key_buf(key, keylen)) == NULL) {
547 warnx("Error reading public key");
552 /* Verify signature of the SHA256(pkg) is valid. */
553 if ((mdctx = EVP_MD_CTX_create()) == NULL) {
554 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
558 if (EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
559 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
562 if (EVP_DigestVerifyUpdate(mdctx, sha256, strlen(sha256)) != 1) {
563 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
567 if (EVP_DigestVerifyFinal(mdctx, sig, siglen) != 1) {
568 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
583 EVP_MD_CTX_destroy(mdctx);
589 static struct pubkey *
597 if (lseek(fd, 0, 0) == -1) {
602 sig = sbuf_new_auto();
604 while ((r = read(fd, buf, sizeof(buf))) >0) {
605 sbuf_bcat(sig, buf, r);
609 pk = calloc(1, sizeof(struct pubkey));
610 pk->siglen = sbuf_len(sig);
611 pk->sig = calloc(1, pk->siglen);
612 memcpy(pk->sig, sbuf_data(sig), pk->siglen);
618 static struct sig_cert *
623 struct sbuf *buf, *sig, *cert;
634 if (lseek(fd, 0, 0) == -1) {
639 /* Duplicate the fd so that fclose(3) does not close it. */
640 if ((my_fd = dup(fd)) == -1) {
645 if ((fp = fdopen(my_fd, "rb")) == NULL) {
651 sig = sbuf_new_auto();
652 cert = sbuf_new_auto();
654 while ((linelen = getline(&line, &linecap, fp)) > 0) {
655 if (strcmp(line, "SIGNATURE\n") == 0) {
658 } else if (strcmp(line, "CERT\n") == 0) {
661 } else if (strcmp(line, "END\n") == 0) {
665 sbuf_bcat(buf, line, linelen);
670 /* Trim out unrelated trailing newline */
671 sbuf_setpos(sig, sbuf_len(sig) - 1);
676 sc = calloc(1, sizeof(struct sig_cert));
677 sc->siglen = sbuf_len(sig);
678 sc->sig = calloc(1, sc->siglen);
679 memcpy(sc->sig, sbuf_data(sig), sc->siglen);
681 sc->certlen = sbuf_len(cert);
682 sc->cert = strdup(sbuf_data(cert));
691 verify_pubsignature(int fd_pkg, int fd_sig)
700 if (config_string(PUBKEY, &pubkey) != 0) {
701 warnx("No CONFIG_PUBKEY defined");
705 if ((pk = read_pubkey(fd_sig)) == NULL) {
706 warnx("Error reading signature");
710 /* Verify the signature. */
711 printf("Verifying signature with public key %s... ", pubkey);
712 if (rsa_verify_cert(fd_pkg, pubkey, NULL, 0, pk->sig,
713 pk->siglen) == false) {
714 fprintf(stderr, "Signature is not valid\n");
730 verify_signature(int fd_pkg, int fd_sig)
732 struct fingerprint_list *trusted, *revoked;
733 struct fingerprint *fingerprint;
736 int trusted_count, revoked_count;
737 const char *fingerprints;
738 char path[MAXPATHLEN];
739 char hash[SHA256_DIGEST_LENGTH * 2 + 1];
742 trusted = revoked = NULL;
745 /* Read and parse fingerprints. */
746 if (config_string(FINGERPRINTS, &fingerprints) != 0) {
747 warnx("No CONFIG_FINGERPRINTS defined");
751 snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
752 if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
753 warnx("Error loading trusted certificates");
757 if (trusted_count == 0 || trusted == NULL) {
758 fprintf(stderr, "No trusted certificates found.\n");
762 snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
763 if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
764 warnx("Error loading revoked certificates");
768 /* Read certificate and signature in. */
769 if ((sc = parse_cert(fd_sig)) == NULL) {
770 warnx("Error parsing certificate");
773 /* Explicitly mark as non-trusted until proven otherwise. */
776 /* Parse signature and pubkey out of the certificate */
777 sha256_buf(sc->cert, sc->certlen, hash);
779 /* Check if this hash is revoked */
780 if (revoked != NULL) {
781 STAILQ_FOREACH(fingerprint, revoked, next) {
782 if (strcasecmp(fingerprint->hash, hash) == 0) {
783 fprintf(stderr, "The package was signed with "
784 "revoked certificate %s\n",
791 STAILQ_FOREACH(fingerprint, trusted, next) {
792 if (strcasecmp(fingerprint->hash, hash) == 0) {
794 sc->name = strdup(fingerprint->name);
799 if (sc->trusted == false) {
800 fprintf(stderr, "No trusted fingerprint found matching "
801 "package's certificate\n");
805 /* Verify the signature. */
806 printf("Verifying signature with trusted certificate %s... ", sc->name);
807 if (rsa_verify_cert(fd_pkg, NULL, sc->cert, sc->certlen, sc->sig,
808 sc->siglen) == false) {
809 fprintf(stderr, "Signature is not valid\n");
817 free_fingerprint_list(trusted);
819 free_fingerprint_list(revoked);
831 bootstrap_pkg(bool force)
835 char url[MAXPATHLEN];
836 char tmppkg[MAXPATHLEN];
837 char tmpsig[MAXPATHLEN];
838 const char *packagesite;
839 const char *signature_type;
840 char pkgstatic[MAXPATHLEN];
845 if (config_string(PACKAGESITE, &packagesite) != 0) {
846 warnx("No PACKAGESITE defined");
850 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
851 warnx("Error looking up SIGNATURE_TYPE");
855 printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
857 /* Support pkg+http:// for PACKAGESITE which is the new format
858 in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
860 if (strncmp(URL_SCHEME_PREFIX, packagesite,
861 strlen(URL_SCHEME_PREFIX)) == 0)
862 packagesite += strlen(URL_SCHEME_PREFIX);
863 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
865 snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
866 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
868 if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
871 if (signature_type != NULL &&
872 strcasecmp(signature_type, "NONE") != 0) {
873 if (strcasecmp(signature_type, "FINGERPRINTS") == 0) {
875 snprintf(tmpsig, MAXPATHLEN, "%s/pkg.txz.sig.XXXXXX",
876 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
877 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.sig",
880 if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
881 fprintf(stderr, "Signature for pkg not "
886 if (verify_signature(fd_pkg, fd_sig) == false)
888 } else if (strcasecmp(signature_type, "PUBKEY") == 0) {
890 snprintf(tmpsig, MAXPATHLEN,
891 "%s/pkg.txz.pubkeysig.XXXXXX",
892 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
893 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.pubkeysig",
896 if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
897 fprintf(stderr, "Signature for pkg not "
902 if (verify_pubsignature(fd_pkg, fd_sig) == false)
905 warnx("Signature type %s is not supported for "
906 "bootstrapping.", signature_type);
911 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
912 ret = install_pkg_static(pkgstatic, tmppkg, force);
917 warnx("Error fetching %s: %s", url, fetchLastErrString);
918 fprintf(stderr, "A pre-built version of pkg could not be found for "
920 fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
921 "ports: 'ports-mgmt/pkg'.\n");
937 static const char confirmation_message[] =
938 "The package management tool is not yet installed on your system.\n"
939 "Do you want to fetch and install it now? [y/N]: ";
941 static const char non_interactive_message[] =
942 "The package management tool is not yet installed on your system.\n"
943 "Please set ASSUME_ALWAYS_YES=yes environment variable to be able to bootstrap "
944 "in non-interactive (stdin not being a tty)\n";
947 pkg_query_yes_no(void)
954 if (c == 'y' || c == 'Y')
959 while (c != '\n' && c != EOF)
966 bootstrap_pkg_local(const char *pkgpath, bool force)
968 char path[MAXPATHLEN];
969 char pkgstatic[MAXPATHLEN];
970 const char *signature_type;
971 int fd_pkg, fd_sig, ret;
976 fd_pkg = open(pkgpath, O_RDONLY);
978 err(EXIT_FAILURE, "Unable to open %s", pkgpath);
980 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
981 warnx("Error looking up SIGNATURE_TYPE");
984 if (signature_type != NULL &&
985 strcasecmp(signature_type, "NONE") != 0) {
986 if (strcasecmp(signature_type, "FINGERPRINTS") == 0) {
988 snprintf(path, sizeof(path), "%s.sig", pkgpath);
990 if ((fd_sig = open(path, O_RDONLY)) == -1) {
991 fprintf(stderr, "Signature for pkg not "
996 if (verify_signature(fd_pkg, fd_sig) == false)
999 } else if (strcasecmp(signature_type, "PUBKEY") == 0) {
1001 snprintf(path, sizeof(path), "%s.pubkeysig", pkgpath);
1003 if ((fd_sig = open(path, O_RDONLY)) == -1) {
1004 fprintf(stderr, "Signature for pkg not "
1009 if (verify_pubsignature(fd_pkg, fd_sig) == false)
1013 warnx("Signature type %s is not supported for "
1014 "bootstrapping.", signature_type);
1019 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
1020 ret = install_pkg_static(pkgstatic, pkgpath, force);
1031 main(int argc, char *argv[])
1033 char pkgpath[MAXPATHLEN];
1036 bool bootstrap_only, force, yes;
1038 bootstrap_only = false;
1043 snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
1044 getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
1046 if (argc > 1 && strcmp(argv[1], "bootstrap") == 0) {
1047 bootstrap_only = true;
1048 if (argc == 3 && strcmp(argv[2], "-f") == 0)
1052 if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
1054 * To allow 'pkg -N' to be used as a reliable test for whether
1055 * a system is configured to use pkg, don't bootstrap pkg
1056 * when that argument is given as argv[1].
1058 if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
1059 errx(EXIT_FAILURE, "pkg is not installed");
1063 if (argc > 1 && strcmp(argv[1], "add") == 0) {
1064 if (argc > 2 && strcmp(argv[2], "-f") == 0) {
1069 if (pkgarg == NULL) {
1070 fprintf(stderr, "Path to pkg.txz required\n");
1073 if (access(pkgarg, R_OK) == -1) {
1074 fprintf(stderr, "No such file: %s\n", pkgarg);
1077 if (bootstrap_pkg_local(pkgarg, force) != 0)
1082 * Do not ask for confirmation if either of stdin or stdout is
1083 * not tty. Check the environment to see if user has answer
1084 * tucked in there already.
1086 config_bool(ASSUME_ALWAYS_YES, &yes);
1088 for (i = 1; i < argc; i++) {
1089 if (strcmp(argv[i], "-y") == 0 ||
1090 strcmp(argv[i], "--yes") == 0) {
1097 if (!isatty(fileno(stdin))) {
1098 fprintf(stderr, non_interactive_message);
1102 printf("%s", confirmation_message);
1103 if (pkg_query_yes_no() == 0)
1106 if (bootstrap_pkg(force) != 0)
1112 } else if (bootstrap_only) {
1113 printf("pkg already bootstrapped at %s\n", pkgpath);
1117 execv(pkgpath, argv);
1120 return (EXIT_FAILURE);