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("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 u = fetchParseURL(url);
206 while (remote == NULL) {
207 if (retry == max_retry) {
208 if (strcmp(u->scheme, "file") != 0 &&
209 strcasecmp(mirror_type, "srv") == 0) {
210 snprintf(zone, sizeof(zone),
211 "_%s._tcp.%s", u->scheme, u->host);
212 mirrors = dns_getsrvinfo(zone);
217 if (mirrors != NULL) {
218 strlcpy(u->host, current->host, sizeof(u->host));
219 u->port = current->port;
222 remote = fetchXGet(u, &st, "");
223 if (remote == NULL) {
227 if (mirrors == NULL) {
230 current = current->next;
237 while (done < st.size) {
238 if ((r = fread(buf, 1, sizeof(buf), remote)) < 1)
241 if (write(fd, buf, r) != r) {
248 if (now > last || done == st.size)
271 static struct fingerprint *
272 parse_fingerprint(ucl_object_t *obj)
274 const ucl_object_t *cur;
275 ucl_object_iter_t it = NULL;
276 const char *function, *fp, *key;
277 struct fingerprint *f;
278 hash_t fct = HASH_UNKNOWN;
280 function = fp = NULL;
282 while ((cur = ucl_iterate_object(obj, &it, true))) {
283 key = ucl_object_key(cur);
284 if (cur->type != UCL_STRING)
286 if (strcasecmp(key, "function") == 0) {
287 function = ucl_object_tostring(cur);
290 if (strcasecmp(key, "fingerprint") == 0) {
291 fp = ucl_object_tostring(cur);
296 if (fp == NULL || function == NULL)
299 if (strcasecmp(function, "sha256") == 0)
302 if (fct == HASH_UNKNOWN) {
303 warnx("Unsupported hashing function: %s", function);
307 f = calloc(1, sizeof(struct fingerprint));
309 strlcpy(f->hash, fp, sizeof(f->hash));
315 free_fingerprint_list(struct fingerprint_list* list)
317 struct fingerprint *fingerprint, *tmp;
319 STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
320 free(fingerprint->name);
326 static struct fingerprint *
327 load_fingerprint(const char *dir, const char *filename)
329 ucl_object_t *obj = NULL;
330 struct ucl_parser *p = NULL;
331 struct fingerprint *f;
332 char path[MAXPATHLEN];
336 snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
338 p = ucl_parser_new(0);
339 if (!ucl_parser_add_file(p, path)) {
340 warnx("%s: %s", path, ucl_parser_get_error(p));
345 obj = ucl_parser_get_object(p);
347 if (obj->type == UCL_OBJECT)
348 f = parse_fingerprint(obj);
351 f->name = strdup(filename);
353 ucl_object_unref(obj);
359 static struct fingerprint_list *
360 load_fingerprints(const char *path, int *count)
364 struct fingerprint *finger;
365 struct fingerprint_list *fingerprints;
369 fingerprints = calloc(1, sizeof(struct fingerprint_list));
370 if (fingerprints == NULL)
372 STAILQ_INIT(fingerprints);
374 if ((d = opendir(path)) == NULL)
377 while ((ent = readdir(d))) {
378 if (strcmp(ent->d_name, ".") == 0 ||
379 strcmp(ent->d_name, "..") == 0)
381 finger = load_fingerprint(path, ent->d_name);
382 if (finger != NULL) {
383 STAILQ_INSERT_TAIL(fingerprints, finger, next);
390 return (fingerprints);
394 sha256_hash(unsigned char hash[SHA256_DIGEST_LENGTH],
395 char out[SHA256_DIGEST_LENGTH * 2 + 1])
399 for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
400 sprintf(out + (i * 2), "%02x", hash[i]);
402 out[SHA256_DIGEST_LENGTH * 2] = '\0';
406 sha256_buf_bin(char *buf, size_t len, char hash[SHA256_DIGEST_LENGTH])
410 SHA256_Init(&sha256);
411 SHA256_Update(&sha256, buf, len);
412 SHA256_Final(hash, &sha256);
417 sha256_buf(char *buf, size_t len, char out[SHA256_DIGEST_LENGTH * 2 + 1])
419 unsigned char hash[SHA256_DIGEST_LENGTH];
424 SHA256_Init(&sha256);
425 SHA256_Update(&sha256, buf, len);
426 SHA256_Final(hash, &sha256);
427 sha256_hash(hash, out);
431 sha256_fd(int fd, char out[SHA256_DIGEST_LENGTH * 2 + 1])
436 unsigned char hash[SHA256_DIGEST_LENGTH];
448 /* Duplicate the fd so that fclose(3) does not close it. */
449 if ((my_fd = dup(fd)) == -1) {
454 if ((fp = fdopen(my_fd, "rb")) == NULL) {
459 SHA256_Init(&sha256);
461 while ((r = fread(buffer, 1, BUFSIZ, fp)) > 0)
462 SHA256_Update(&sha256, buffer, r);
464 if (ferror(fp) != 0) {
469 SHA256_Final(hash, &sha256);
470 sha256_hash(hash, out);
476 else if (my_fd != -1)
478 (void)lseek(fd, 0, SEEK_SET);
484 load_rsa_public_key_buf(unsigned char *cert, int certlen)
490 bp = BIO_new_mem_buf((void *)cert, certlen);
491 if (!PEM_read_bio_RSA_PUBKEY(bp, &rsa, NULL, NULL)) {
492 warn("error reading public key: %s",
493 ERR_error_string(ERR_get_error(), errbuf));
503 rsa_verify_cert(int fd, unsigned char *key, int keylen,
504 unsigned char *sig, int siglen)
506 char sha256[SHA256_DIGEST_LENGTH *2 +1];
507 char hash[SHA256_DIGEST_LENGTH];
512 lseek(fd, 0, SEEK_SET);
513 sha256_fd(fd, sha256);
515 SSL_load_error_strings();
516 OpenSSL_add_all_algorithms();
517 OpenSSL_add_all_ciphers();
519 sha256_buf_bin(sha256, strlen(sha256), hash);
521 rsa = load_rsa_public_key_buf(key, keylen);
524 ret = RSA_verify(NID_sha256, hash, sizeof(hash), sig, siglen, rsa);
526 warnx("%s: %s", key, ERR_error_string(ERR_get_error(), errbuf));
536 static struct sig_cert *
541 struct sbuf *buf, *sig, *cert;
552 if (lseek(fd, 0, 0) == -1) {
557 /* Duplicate the fd so that fclose(3) does not close it. */
558 if ((my_fd = dup(fd)) == -1) {
563 if ((fp = fdopen(my_fd, "rb")) == NULL) {
569 sig = sbuf_new_auto();
570 cert = sbuf_new_auto();
572 while ((linelen = getline(&line, &linecap, fp)) > 0) {
573 if (strcmp(line, "SIGNATURE\n") == 0) {
576 } else if (strcmp(line, "CERT\n") == 0) {
579 } else if (strcmp(line, "END\n") == 0) {
583 sbuf_bcat(buf, line, linelen);
588 /* Trim out unrelated trailing newline */
589 sbuf_setpos(sig, sbuf_len(sig) - 1);
594 sc = calloc(1, sizeof(struct sig_cert));
595 sc->siglen = sbuf_len(sig);
596 sc->sig = calloc(1, sc->siglen);
597 memcpy(sc->sig, sbuf_data(sig), sc->siglen);
599 sc->certlen = sbuf_len(cert);
600 sc->cert = strdup(sbuf_data(cert));
609 verify_signature(int fd_pkg, int fd_sig)
611 struct fingerprint_list *trusted, *revoked;
612 struct fingerprint *fingerprint;
615 int trusted_count, revoked_count;
616 const char *fingerprints;
617 char path[MAXPATHLEN];
618 char hash[SHA256_DIGEST_LENGTH * 2 + 1];
621 trusted = revoked = NULL;
624 /* Read and parse fingerprints. */
625 if (config_string(FINGERPRINTS, &fingerprints) != 0) {
626 warnx("No CONFIG_FINGERPRINTS defined");
630 snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
631 if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
632 warnx("Error loading trusted certificates");
636 if (trusted_count == 0 || trusted == NULL) {
637 fprintf(stderr, "No trusted certificates found.\n");
641 snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
642 if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
643 warnx("Error loading revoked certificates");
647 /* Read certificate and signature in. */
648 if ((sc = parse_cert(fd_sig)) == NULL) {
649 warnx("Error parsing certificate");
652 /* Explicitly mark as non-trusted until proven otherwise. */
655 /* Parse signature and pubkey out of the certificate */
656 sha256_buf(sc->cert, sc->certlen, hash);
658 /* Check if this hash is revoked */
659 if (revoked != NULL) {
660 STAILQ_FOREACH(fingerprint, revoked, next) {
661 if (strcasecmp(fingerprint->hash, hash) == 0) {
662 fprintf(stderr, "The package was signed with "
663 "revoked certificate %s\n",
670 STAILQ_FOREACH(fingerprint, trusted, next) {
671 if (strcasecmp(fingerprint->hash, hash) == 0) {
673 sc->name = strdup(fingerprint->name);
678 if (sc->trusted == false) {
679 fprintf(stderr, "No trusted fingerprint found matching "
680 "package's certificate\n");
684 /* Verify the signature. */
685 printf("Verifying signature with trusted certificate %s... ", sc->name);
686 if (rsa_verify_cert(fd_pkg, sc->cert, sc->certlen, sc->sig,
687 sc->siglen) == false) {
689 fprintf(stderr, "Signature is not valid\n");
698 free_fingerprint_list(trusted);
700 free_fingerprint_list(revoked);
712 bootstrap_pkg(bool force)
716 char url[MAXPATHLEN];
717 char tmppkg[MAXPATHLEN];
718 char tmpsig[MAXPATHLEN];
719 const char *packagesite;
720 const char *signature_type;
721 char pkgstatic[MAXPATHLEN];
726 if (config_string(PACKAGESITE, &packagesite) != 0) {
727 warnx("No PACKAGESITE defined");
731 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
732 warnx("Error looking up SIGNATURE_TYPE");
736 printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
738 /* Support pkg+http:// for PACKAGESITE which is the new format
739 in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
741 if (strncmp(URL_SCHEME_PREFIX, packagesite,
742 strlen(URL_SCHEME_PREFIX)) == 0)
743 packagesite += strlen(URL_SCHEME_PREFIX);
744 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
746 snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
747 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
749 if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
752 if (signature_type != NULL &&
753 strcasecmp(signature_type, "FINGERPRINTS") == 0) {
754 snprintf(tmpsig, MAXPATHLEN, "%s/pkg.txz.sig.XXXXXX",
755 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
756 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.sig",
759 if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
760 fprintf(stderr, "Signature for pkg not available.\n");
764 if (verify_signature(fd_pkg, fd_sig) == false)
768 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
769 ret = install_pkg_static(pkgstatic, tmppkg, force);
774 warnx("Error fetching %s: %s", url, fetchLastErrString);
775 fprintf(stderr, "A pre-built version of pkg could not be found for "
777 fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
778 "ports: 'ports-mgmt/pkg'.\n");
791 static const char confirmation_message[] =
792 "The package management tool is not yet installed on your system.\n"
793 "Do you want to fetch and install it now? [y/N]: ";
795 static const char non_interactive_message[] =
796 "The package management tool is not yet installed on your system.\n"
797 "Please set ASSUME_ALWAYS_YES=yes environment variable to be able to bootstrap "
798 "in non-interactive (stdin not being a tty)\n";
801 pkg_query_yes_no(void)
807 if (c == 'y' || c == 'Y')
812 while (c != '\n' && c != EOF)
819 bootstrap_pkg_local(const char *pkgpath, bool force)
821 char path[MAXPATHLEN];
822 char pkgstatic[MAXPATHLEN];
823 const char *signature_type;
824 int fd_pkg, fd_sig, ret;
829 fd_pkg = open(pkgpath, O_RDONLY);
831 err(EXIT_FAILURE, "Unable to open %s", pkgpath);
833 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
834 warnx("Error looking up SIGNATURE_TYPE");
837 if (signature_type != NULL &&
838 strcasecmp(signature_type, "FINGERPRINTS") == 0) {
839 snprintf(path, sizeof(path), "%s.sig", pkgpath);
841 if ((fd_sig = open(path, O_RDONLY)) == -1) {
842 fprintf(stderr, "Signature for pkg not available.\n");
846 if (verify_signature(fd_pkg, fd_sig) == false)
850 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
851 ret = install_pkg_static(pkgstatic, pkgpath, force);
862 main(int argc, char *argv[])
864 char pkgpath[MAXPATHLEN];
866 bool bootstrap_only, force, yes;
868 bootstrap_only = false;
873 snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
874 getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
876 if (argc > 1 && strcmp(argv[1], "bootstrap") == 0) {
877 bootstrap_only = true;
878 if (argc == 3 && strcmp(argv[2], "-f") == 0)
882 if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
884 * To allow 'pkg -N' to be used as a reliable test for whether
885 * a system is configured to use pkg, don't bootstrap pkg
886 * when that argument is given as argv[1].
888 if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
889 errx(EXIT_FAILURE, "pkg is not installed");
893 if (argc > 1 && strcmp(argv[1], "add") == 0) {
894 if (argc > 2 && strcmp(argv[2], "-f") == 0) {
899 if (pkgarg == NULL) {
900 fprintf(stderr, "Path to pkg.txz required\n");
903 if (access(pkgarg, R_OK) == -1) {
904 fprintf(stderr, "No such file: %s\n", pkgarg);
907 if (bootstrap_pkg_local(pkgarg, force) != 0)
912 * Do not ask for confirmation if either of stdin or stdout is
913 * not tty. Check the environment to see if user has answer
914 * tucked in there already.
916 config_bool(ASSUME_ALWAYS_YES, &yes);
918 if (!isatty(fileno(stdin))) {
919 fprintf(stderr, non_interactive_message);
923 printf("%s", confirmation_message);
924 if (pkg_query_yes_no() == 0)
927 if (bootstrap_pkg(force) != 0)
933 } else if (bootstrap_only) {
934 printf("pkg already bootstrapped at %s\n", pkgpath);
938 execv(pkgpath, argv);
941 return (EXIT_FAILURE);