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"
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;
188 char zone[MAXHOSTNAMELEN + 13];
189 static const char *mirror_type = NULL;
194 current = mirrors = NULL;
197 if (mirror_type == NULL && config_string(MIRROR_TYPE, &mirror_type)
199 warnx("No MIRROR_TYPE defined");
203 if ((fd = mkstemp(path)) == -1) {
210 u = fetchParseURL(url);
211 while (remote == NULL) {
212 if (retry == max_retry) {
213 if (strcmp(u->scheme, "file") != 0 &&
214 strcasecmp(mirror_type, "srv") == 0) {
215 snprintf(zone, sizeof(zone),
216 "_%s._tcp.%s", u->scheme, u->host);
217 mirrors = dns_getsrvinfo(zone);
222 if (mirrors != NULL) {
223 strlcpy(u->host, current->host, sizeof(u->host));
224 u->port = current->port;
227 remote = fetchXGet(u, &st, "");
228 if (remote == NULL) {
232 if (mirrors == NULL) {
235 current = current->next;
245 while (done < st.size) {
246 if ((r = fread(buf, 1, sizeof(buf), remote)) < 1)
249 if (write(fd, buf, r) != r) {
256 if (now > last || done == st.size)
279 static struct fingerprint *
280 parse_fingerprint(ucl_object_t *obj)
282 const ucl_object_t *cur;
283 ucl_object_iter_t it = NULL;
284 const char *function, *fp, *key;
285 struct fingerprint *f;
286 hash_t fct = HASH_UNKNOWN;
288 function = fp = NULL;
290 while ((cur = ucl_iterate_object(obj, &it, true))) {
291 key = ucl_object_key(cur);
292 if (cur->type != UCL_STRING)
294 if (strcasecmp(key, "function") == 0) {
295 function = ucl_object_tostring(cur);
298 if (strcasecmp(key, "fingerprint") == 0) {
299 fp = ucl_object_tostring(cur);
304 if (fp == NULL || function == NULL)
307 if (strcasecmp(function, "sha256") == 0)
310 if (fct == HASH_UNKNOWN) {
311 warnx("Unsupported hashing function: %s", function);
315 f = calloc(1, sizeof(struct fingerprint));
317 strlcpy(f->hash, fp, sizeof(f->hash));
323 free_fingerprint_list(struct fingerprint_list* list)
325 struct fingerprint *fingerprint, *tmp;
327 STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
328 if (fingerprint->name)
329 free(fingerprint->name);
335 static struct fingerprint *
336 load_fingerprint(const char *dir, const char *filename)
338 ucl_object_t *obj = NULL;
339 struct ucl_parser *p = NULL;
340 struct fingerprint *f;
341 char path[MAXPATHLEN];
345 snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
347 p = ucl_parser_new(0);
348 if (!ucl_parser_add_file(p, path)) {
349 warnx("%s: %s", path, ucl_parser_get_error(p));
354 obj = ucl_parser_get_object(p);
356 if (obj->type == UCL_OBJECT)
357 f = parse_fingerprint(obj);
360 f->name = strdup(filename);
362 ucl_object_unref(obj);
368 static struct fingerprint_list *
369 load_fingerprints(const char *path, int *count)
373 struct fingerprint *finger;
374 struct fingerprint_list *fingerprints;
378 fingerprints = calloc(1, sizeof(struct fingerprint_list));
379 if (fingerprints == NULL)
381 STAILQ_INIT(fingerprints);
383 if ((d = opendir(path)) == NULL)
386 while ((ent = readdir(d))) {
387 if (strcmp(ent->d_name, ".") == 0 ||
388 strcmp(ent->d_name, "..") == 0)
390 finger = load_fingerprint(path, ent->d_name);
391 if (finger != NULL) {
392 STAILQ_INSERT_TAIL(fingerprints, finger, next);
399 return (fingerprints);
403 sha256_hash(unsigned char hash[SHA256_DIGEST_LENGTH],
404 char out[SHA256_DIGEST_LENGTH * 2 + 1])
408 for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
409 sprintf(out + (i * 2), "%02x", hash[i]);
411 out[SHA256_DIGEST_LENGTH * 2] = '\0';
415 sha256_buf(char *buf, size_t len, char out[SHA256_DIGEST_LENGTH * 2 + 1])
417 unsigned char hash[SHA256_DIGEST_LENGTH];
422 SHA256_Init(&sha256);
423 SHA256_Update(&sha256, buf, len);
424 SHA256_Final(hash, &sha256);
425 sha256_hash(hash, out);
429 sha256_fd(int fd, char out[SHA256_DIGEST_LENGTH * 2 + 1])
434 unsigned char hash[SHA256_DIGEST_LENGTH];
446 /* Duplicate the fd so that fclose(3) does not close it. */
447 if ((my_fd = dup(fd)) == -1) {
452 if ((fp = fdopen(my_fd, "rb")) == NULL) {
457 SHA256_Init(&sha256);
459 while ((r = fread(buffer, 1, BUFSIZ, fp)) > 0)
460 SHA256_Update(&sha256, buffer, r);
462 if (ferror(fp) != 0) {
467 SHA256_Final(hash, &sha256);
468 sha256_hash(hash, out);
474 else if (my_fd != -1)
476 (void)lseek(fd, 0, SEEK_SET);
482 load_public_key_file(const char *file)
488 bp = BIO_new_file(file, "r");
490 errx(EXIT_FAILURE, "Unable to read %s", file);
492 if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
493 warnx("ici: %s", ERR_error_string(ERR_get_error(), errbuf));
501 load_public_key_buf(const unsigned char *cert, int certlen)
507 bp = BIO_new_mem_buf(__DECONST(void *, cert), certlen);
509 if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
510 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
518 rsa_verify_cert(int fd, const char *sigfile, const unsigned char *key,
519 int keylen, unsigned char *sig, int siglen)
523 char sha256[(SHA256_DIGEST_LENGTH * 2) + 2];
531 SSL_load_error_strings();
533 /* Compute SHA256 of the package. */
534 if (lseek(fd, 0, 0) == -1) {
538 if ((sha256_fd(fd, sha256)) == -1) {
539 warnx("Error creating SHA256 hash for package");
543 if (sigfile != NULL) {
544 if ((pkey = load_public_key_file(sigfile)) == NULL) {
545 warnx("Error reading public key");
549 if ((pkey = load_public_key_buf(key, keylen)) == NULL) {
550 warnx("Error reading public key");
555 /* Verify signature of the SHA256(pkg) is valid. */
556 if ((mdctx = EVP_MD_CTX_create()) == NULL) {
557 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
561 if (EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
562 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
565 if (EVP_DigestVerifyUpdate(mdctx, sha256, strlen(sha256)) != 1) {
566 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
570 if (EVP_DigestVerifyFinal(mdctx, sig, siglen) != 1) {
571 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
586 EVP_MD_CTX_destroy(mdctx);
592 static struct pubkey *
600 if (lseek(fd, 0, 0) == -1) {
605 sig = sbuf_new_auto();
607 while ((r = read(fd, buf, sizeof(buf))) >0) {
608 sbuf_bcat(sig, buf, r);
612 pk = calloc(1, sizeof(struct pubkey));
613 pk->siglen = sbuf_len(sig);
614 pk->sig = calloc(1, pk->siglen);
615 memcpy(pk->sig, sbuf_data(sig), pk->siglen);
621 static struct sig_cert *
626 struct sbuf *buf, *sig, *cert;
637 if (lseek(fd, 0, 0) == -1) {
642 /* Duplicate the fd so that fclose(3) does not close it. */
643 if ((my_fd = dup(fd)) == -1) {
648 if ((fp = fdopen(my_fd, "rb")) == NULL) {
654 sig = sbuf_new_auto();
655 cert = sbuf_new_auto();
657 while ((linelen = getline(&line, &linecap, fp)) > 0) {
658 if (strcmp(line, "SIGNATURE\n") == 0) {
661 } else if (strcmp(line, "CERT\n") == 0) {
664 } else if (strcmp(line, "END\n") == 0) {
668 sbuf_bcat(buf, line, linelen);
673 /* Trim out unrelated trailing newline */
674 sbuf_setpos(sig, sbuf_len(sig) - 1);
679 sc = calloc(1, sizeof(struct sig_cert));
680 sc->siglen = sbuf_len(sig);
681 sc->sig = calloc(1, sc->siglen);
682 memcpy(sc->sig, sbuf_data(sig), sc->siglen);
684 sc->certlen = sbuf_len(cert);
685 sc->cert = strdup(sbuf_data(cert));
694 verify_pubsignature(int fd_pkg, int fd_sig)
703 if (config_string(PUBKEY, &pubkey) != 0) {
704 warnx("No CONFIG_PUBKEY defined");
708 if ((pk = read_pubkey(fd_sig)) == NULL) {
709 warnx("Error reading signature");
713 /* Verify the signature. */
714 printf("Verifying signature with public key %s... ", pubkey);
715 if (rsa_verify_cert(fd_pkg, pubkey, NULL, 0, pk->sig,
716 pk->siglen) == false) {
717 fprintf(stderr, "Signature is not valid\n");
733 verify_signature(int fd_pkg, int fd_sig)
735 struct fingerprint_list *trusted, *revoked;
736 struct fingerprint *fingerprint;
739 int trusted_count, revoked_count;
740 const char *fingerprints;
741 char path[MAXPATHLEN];
742 char hash[SHA256_DIGEST_LENGTH * 2 + 1];
745 trusted = revoked = NULL;
748 /* Read and parse fingerprints. */
749 if (config_string(FINGERPRINTS, &fingerprints) != 0) {
750 warnx("No CONFIG_FINGERPRINTS defined");
754 snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
755 if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
756 warnx("Error loading trusted certificates");
760 if (trusted_count == 0 || trusted == NULL) {
761 fprintf(stderr, "No trusted certificates found.\n");
765 snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
766 if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
767 warnx("Error loading revoked certificates");
771 /* Read certificate and signature in. */
772 if ((sc = parse_cert(fd_sig)) == NULL) {
773 warnx("Error parsing certificate");
776 /* Explicitly mark as non-trusted until proven otherwise. */
779 /* Parse signature and pubkey out of the certificate */
780 sha256_buf(sc->cert, sc->certlen, hash);
782 /* Check if this hash is revoked */
783 if (revoked != NULL) {
784 STAILQ_FOREACH(fingerprint, revoked, next) {
785 if (strcasecmp(fingerprint->hash, hash) == 0) {
786 fprintf(stderr, "The package was signed with "
787 "revoked certificate %s\n",
794 STAILQ_FOREACH(fingerprint, trusted, next) {
795 if (strcasecmp(fingerprint->hash, hash) == 0) {
797 sc->name = strdup(fingerprint->name);
802 if (sc->trusted == false) {
803 fprintf(stderr, "No trusted fingerprint found matching "
804 "package's certificate\n");
808 /* Verify the signature. */
809 printf("Verifying signature with trusted certificate %s... ", sc->name);
810 if (rsa_verify_cert(fd_pkg, NULL, sc->cert, sc->certlen, sc->sig,
811 sc->siglen) == false) {
812 fprintf(stderr, "Signature is not valid\n");
820 free_fingerprint_list(trusted);
822 free_fingerprint_list(revoked);
837 bootstrap_pkg(bool force)
841 char url[MAXPATHLEN];
842 char tmppkg[MAXPATHLEN];
843 char tmpsig[MAXPATHLEN];
844 const char *packagesite;
845 const char *signature_type;
846 char pkgstatic[MAXPATHLEN];
851 if (config_string(PACKAGESITE, &packagesite) != 0) {
852 warnx("No PACKAGESITE defined");
856 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
857 warnx("Error looking up SIGNATURE_TYPE");
861 printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
863 /* Support pkg+http:// for PACKAGESITE which is the new format
864 in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
866 if (strncmp(URL_SCHEME_PREFIX, packagesite,
867 strlen(URL_SCHEME_PREFIX)) == 0)
868 packagesite += strlen(URL_SCHEME_PREFIX);
869 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
871 snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
872 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
874 if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
877 if (signature_type != NULL &&
878 strcasecmp(signature_type, "NONE") != 0) {
879 if (strcasecmp(signature_type, "FINGERPRINTS") == 0) {
881 snprintf(tmpsig, MAXPATHLEN, "%s/pkg.txz.sig.XXXXXX",
882 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
883 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.sig",
886 if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
887 fprintf(stderr, "Signature for pkg not "
892 if (verify_signature(fd_pkg, fd_sig) == false)
894 } else if (strcasecmp(signature_type, "PUBKEY") == 0) {
896 snprintf(tmpsig, MAXPATHLEN,
897 "%s/pkg.txz.pubkeysig.XXXXXX",
898 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
899 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.pubkeysig",
902 if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
903 fprintf(stderr, "Signature for pkg not "
908 if (verify_pubsignature(fd_pkg, fd_sig) == false)
911 warnx("Signature type %s is not supported for "
912 "bootstrapping.", signature_type);
917 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
918 ret = install_pkg_static(pkgstatic, tmppkg, force);
923 warnx("Error fetching %s: %s", url, fetchLastErrString);
924 fprintf(stderr, "A pre-built version of pkg could not be found for "
926 fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
927 "ports: 'ports-mgmt/pkg'.\n");
940 static const char confirmation_message[] =
941 "The package management tool is not yet installed on your system.\n"
942 "Do you want to fetch and install it now? [y/N]: ";
945 pkg_query_yes_no(void)
951 if (c == 'y' || c == 'Y')
956 while (c != '\n' && c != EOF)
963 bootstrap_pkg_local(const char *pkgpath, bool force)
965 char path[MAXPATHLEN];
966 char pkgstatic[MAXPATHLEN];
967 const char *signature_type;
968 int fd_pkg, fd_sig, ret;
973 fd_pkg = open(pkgpath, O_RDONLY);
975 err(EXIT_FAILURE, "Unable to open %s", pkgpath);
977 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
978 warnx("Error looking up SIGNATURE_TYPE");
981 if (signature_type != NULL &&
982 strcasecmp(signature_type, "NONE") != 0) {
983 if (strcasecmp(signature_type, "FINGERPRINTS") == 0) {
985 snprintf(path, sizeof(path), "%s.sig", pkgpath);
987 if ((fd_sig = open(path, O_RDONLY)) == -1) {
988 fprintf(stderr, "Signature for pkg not "
993 if (verify_signature(fd_pkg, fd_sig) == false)
996 } else if (strcasecmp(signature_type, "PUBKEY") == 0) {
998 snprintf(path, sizeof(path), "%s.pubkeysig", pkgpath);
1000 if ((fd_sig = open(path, O_RDONLY)) == -1) {
1001 fprintf(stderr, "Signature for pkg not "
1006 if (verify_pubsignature(fd_pkg, fd_sig) == false)
1010 warnx("Signature type %s is not supported for "
1011 "bootstrapping.", signature_type);
1016 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
1017 ret = install_pkg_static(pkgstatic, pkgpath, force);
1028 main(__unused int argc, char *argv[])
1030 char pkgpath[MAXPATHLEN];
1032 bool bootstrap_only, force, yes;
1034 bootstrap_only = false;
1039 snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
1040 getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
1042 if (argc > 1 && strcmp(argv[1], "bootstrap") == 0) {
1043 bootstrap_only = true;
1044 if (argc == 3 && strcmp(argv[2], "-f") == 0)
1048 if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
1050 * To allow 'pkg -N' to be used as a reliable test for whether
1051 * a system is configured to use pkg, don't bootstrap pkg
1052 * when that argument is given as argv[1].
1054 if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
1055 errx(EXIT_FAILURE, "pkg is not installed");
1059 if (argc > 1 && strcmp(argv[1], "add") == 0) {
1060 if (argc > 2 && strcmp(argv[2], "-f") == 0) {
1065 if (pkgarg == NULL) {
1066 fprintf(stderr, "Path to pkg.txz required\n");
1069 if (access(pkgarg, R_OK) == -1) {
1070 fprintf(stderr, "No such file: %s\n", pkgarg);
1073 if (bootstrap_pkg_local(pkgarg, force) != 0)
1078 * Do not ask for confirmation if either of stdin or stdout is
1079 * not tty. Check the environment to see if user has answer
1080 * tucked in there already.
1082 config_bool(ASSUME_ALWAYS_YES, &yes);
1084 printf("%s", confirmation_message);
1085 if (!isatty(fileno(stdin)))
1088 if (pkg_query_yes_no() == 0)
1091 if (bootstrap_pkg(force) != 0)
1097 } else if (bootstrap_only) {
1098 printf("pkg already bootstrapped at %s\n", pkgpath);
1102 execv(pkgpath, argv);
1105 return (EXIT_FAILURE);