1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 2012-2014 Baptiste Daroussin <[email protected]>
5 * Copyright (c) 2013 Bryan Drewery <[email protected]>
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
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.
16 *
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
27 * SUCH DAMAGE.
28 */
29
30 #include <sys/cdefs.h>
31 #include <sys/param.h>
32 #include <sys/queue.h>
33 #include <sys/types.h>
34 #include <sys/wait.h>
35
36 #include <archive.h>
37 #include <archive_entry.h>
38 #include <dirent.h>
39 #include <err.h>
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <fetch.h>
43 #include <getopt.h>
44 #include <libutil.h>
45 #include <paths.h>
46 #include <stdbool.h>
47 #include <stdlib.h>
48 #include <stdio.h>
49 #include <string.h>
50 #include <ucl.h>
51
52 #include <openssl/err.h>
53 #include <openssl/ssl.h>
54
55 #include "dns_utils.h"
56 #include "config.h"
57 #include "hash.h"
58
59 struct sig_cert {
60 char *name;
61 unsigned char *sig;
62 int siglen;
63 unsigned char *cert;
64 int certlen;
65 bool trusted;
66 };
67
68 struct pubkey {
69 unsigned char *sig;
70 int siglen;
71 };
72
73 typedef enum {
74 HASH_UNKNOWN,
75 HASH_SHA256,
76 } hash_t;
77
78 struct fingerprint {
79 hash_t type;
80 char *name;
81 char hash[BUFSIZ];
82 STAILQ_ENTRY(fingerprint) next;
83 };
84
85 static const char *bootstrap_names [] = {
86 "pkg.pkg",
87 "pkg.txz",
88 NULL
89 };
90
91 STAILQ_HEAD(fingerprint_list, fingerprint);
92
93 static int debug;
94
95 static int
extract_pkg_static(int fd,char * p,int sz)96 extract_pkg_static(int fd, char *p, int sz)
97 {
98 struct archive *a;
99 struct archive_entry *ae;
100 char *end;
101 int ret, r;
102
103 ret = -1;
104 a = archive_read_new();
105 if (a == NULL) {
106 warn("archive_read_new");
107 return (ret);
108 }
109 archive_read_support_filter_all(a);
110 archive_read_support_format_tar(a);
111
112 if (lseek(fd, 0, 0) == -1) {
113 warn("lseek");
114 goto cleanup;
115 }
116
117 if (archive_read_open_fd(a, fd, 4096) != ARCHIVE_OK) {
118 warnx("archive_read_open_fd: %s", archive_error_string(a));
119 goto cleanup;
120 }
121
122 ae = NULL;
123 while ((r = archive_read_next_header(a, &ae)) == ARCHIVE_OK) {
124 end = strrchr(archive_entry_pathname(ae), '/');
125 if (end == NULL)
126 continue;
127
128 if (strcmp(end, "/pkg-static") == 0) {
129 r = archive_read_extract(a, ae,
130 ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM |
131 ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_ACL |
132 ARCHIVE_EXTRACT_FFLAGS | ARCHIVE_EXTRACT_XATTR);
133 strlcpy(p, archive_entry_pathname(ae), sz);
134 break;
135 }
136 }
137
138 if (r == ARCHIVE_OK)
139 ret = 0;
140 else
141 warnx("failed to extract pkg-static: %s",
142 archive_error_string(a));
143
144 cleanup:
145 archive_read_free(a);
146 return (ret);
147
148 }
149
150 static int
install_pkg_static(const char * path,const char * pkgpath,bool force)151 install_pkg_static(const char *path, const char *pkgpath, bool force)
152 {
153 int pstat;
154 pid_t pid;
155
156 switch ((pid = fork())) {
157 case -1:
158 return (-1);
159 case 0:
160 if (force)
161 execl(path, "pkg-static", "add", "-f", pkgpath,
162 (char *)NULL);
163 else
164 execl(path, "pkg-static", "add", pkgpath,
165 (char *)NULL);
166 _exit(1);
167 default:
168 break;
169 }
170
171 while (waitpid(pid, &pstat, 0) == -1)
172 if (errno != EINTR)
173 return (-1);
174
175 if (WEXITSTATUS(pstat))
176 return (WEXITSTATUS(pstat));
177 else if (WIFSIGNALED(pstat))
178 return (128 & (WTERMSIG(pstat)));
179 return (pstat);
180 }
181
182 static int
fetch_to_fd(const char * url,char * path,const char * fetchOpts)183 fetch_to_fd(const char *url, char *path, const char *fetchOpts)
184 {
185 struct url *u;
186 struct dns_srvinfo *mirrors, *current;
187 struct url_stat st;
188 FILE *remote;
189 /* To store _https._tcp. + hostname + \0 */
190 int fd;
191 int retry, max_retry;
192 ssize_t r;
193 char buf[10240];
194 char zone[MAXHOSTNAMELEN + 13];
195 static const char *mirror_type = NULL;
196
197 max_retry = 3;
198 current = mirrors = NULL;
199 remote = NULL;
200
201 if (mirror_type == NULL && config_string(MIRROR_TYPE, &mirror_type)
202 != 0) {
203 warnx("No MIRROR_TYPE defined");
204 return (-1);
205 }
206
207 if ((fd = mkstemp(path)) == -1) {
208 warn("mkstemp()");
209 return (-1);
210 }
211
212 retry = max_retry;
213
214 if ((u = fetchParseURL(url)) == NULL) {
215 warn("fetchParseURL('%s')", url);
216 return (-1);
217 }
218
219 while (remote == NULL) {
220 if (retry == max_retry) {
221 if (strcmp(u->scheme, "file") != 0 &&
222 strcasecmp(mirror_type, "srv") == 0) {
223 snprintf(zone, sizeof(zone),
224 "_%s._tcp.%s", u->scheme, u->host);
225 mirrors = dns_getsrvinfo(zone);
226 current = mirrors;
227 }
228 }
229
230 if (mirrors != NULL) {
231 strlcpy(u->host, current->host, sizeof(u->host));
232 u->port = current->port;
233 }
234
235 remote = fetchXGet(u, &st, fetchOpts);
236 if (remote == NULL) {
237 --retry;
238 if (retry <= 0)
239 goto fetchfail;
240 if (mirrors != NULL) {
241 current = current->next;
242 if (current == NULL)
243 current = mirrors;
244 }
245 }
246 }
247
248 while ((r = fread(buf, 1, sizeof(buf), remote)) > 0) {
249 if (write(fd, buf, r) != r) {
250 warn("write()");
251 goto fetchfail;
252 }
253 }
254
255 if (r != 0) {
256 warn("An error occurred while fetching pkg(8)");
257 goto fetchfail;
258 }
259
260 if (ferror(remote))
261 goto fetchfail;
262
263 goto cleanup;
264
265 fetchfail:
266 if (fd != -1) {
267 close(fd);
268 fd = -1;
269 unlink(path);
270 }
271
272 cleanup:
273 if (remote != NULL)
274 fclose(remote);
275
276 return fd;
277 }
278
279 static struct fingerprint *
parse_fingerprint(ucl_object_t * obj)280 parse_fingerprint(ucl_object_t *obj)
281 {
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;
287
288 function = fp = NULL;
289
290 while ((cur = ucl_iterate_object(obj, &it, true))) {
291 key = ucl_object_key(cur);
292 if (cur->type != UCL_STRING)
293 continue;
294 if (strcasecmp(key, "function") == 0) {
295 function = ucl_object_tostring(cur);
296 continue;
297 }
298 if (strcasecmp(key, "fingerprint") == 0) {
299 fp = ucl_object_tostring(cur);
300 continue;
301 }
302 }
303
304 if (fp == NULL || function == NULL)
305 return (NULL);
306
307 if (strcasecmp(function, "sha256") == 0)
308 fct = HASH_SHA256;
309
310 if (fct == HASH_UNKNOWN) {
311 warnx("Unsupported hashing function: %s", function);
312 return (NULL);
313 }
314
315 f = calloc(1, sizeof(struct fingerprint));
316 f->type = fct;
317 strlcpy(f->hash, fp, sizeof(f->hash));
318
319 return (f);
320 }
321
322 static void
free_fingerprint_list(struct fingerprint_list * list)323 free_fingerprint_list(struct fingerprint_list* list)
324 {
325 struct fingerprint *fingerprint, *tmp;
326
327 STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
328 free(fingerprint->name);
329 free(fingerprint);
330 }
331 free(list);
332 }
333
334 static struct fingerprint *
load_fingerprint(const char * dir,const char * filename)335 load_fingerprint(const char *dir, const char *filename)
336 {
337 ucl_object_t *obj = NULL;
338 struct ucl_parser *p = NULL;
339 struct fingerprint *f;
340 char path[MAXPATHLEN];
341
342 f = NULL;
343
344 snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
345
346 p = ucl_parser_new(0);
347 if (!ucl_parser_add_file(p, path)) {
348 warnx("%s: %s", path, ucl_parser_get_error(p));
349 ucl_parser_free(p);
350 return (NULL);
351 }
352
353 obj = ucl_parser_get_object(p);
354
355 if (obj->type == UCL_OBJECT)
356 f = parse_fingerprint(obj);
357
358 if (f != NULL)
359 f->name = strdup(filename);
360
361 ucl_object_unref(obj);
362 ucl_parser_free(p);
363
364 return (f);
365 }
366
367 static struct fingerprint_list *
load_fingerprints(const char * path,int * count)368 load_fingerprints(const char *path, int *count)
369 {
370 DIR *d;
371 struct dirent *ent;
372 struct fingerprint *finger;
373 struct fingerprint_list *fingerprints;
374
375 *count = 0;
376
377 fingerprints = calloc(1, sizeof(struct fingerprint_list));
378 if (fingerprints == NULL)
379 return (NULL);
380 STAILQ_INIT(fingerprints);
381
382 if ((d = opendir(path)) == NULL) {
383 free(fingerprints);
384
385 return (NULL);
386 }
387
388 while ((ent = readdir(d))) {
389 if (strcmp(ent->d_name, ".") == 0 ||
390 strcmp(ent->d_name, "..") == 0)
391 continue;
392 finger = load_fingerprint(path, ent->d_name);
393 if (finger != NULL) {
394 STAILQ_INSERT_TAIL(fingerprints, finger, next);
395 ++(*count);
396 }
397 }
398
399 closedir(d);
400
401 return (fingerprints);
402 }
403
404 static EVP_PKEY *
load_public_key_file(const char * file)405 load_public_key_file(const char *file)
406 {
407 EVP_PKEY *pkey;
408 BIO *bp;
409 char errbuf[1024];
410
411 bp = BIO_new_file(file, "r");
412 if (!bp)
413 errx(EXIT_FAILURE, "Unable to read %s", file);
414
415 if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
416 warnx("ici: %s", ERR_error_string(ERR_get_error(), errbuf));
417
418 BIO_free(bp);
419
420 return (pkey);
421 }
422
423 static EVP_PKEY *
load_public_key_buf(const unsigned char * cert,int certlen)424 load_public_key_buf(const unsigned char *cert, int certlen)
425 {
426 EVP_PKEY *pkey;
427 BIO *bp;
428 char errbuf[1024];
429
430 bp = BIO_new_mem_buf(__DECONST(void *, cert), certlen);
431
432 if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
433 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
434
435 BIO_free(bp);
436
437 return (pkey);
438 }
439
440 static bool
rsa_verify_cert(int fd,const char * sigfile,const unsigned char * key,int keylen,unsigned char * sig,int siglen)441 rsa_verify_cert(int fd, const char *sigfile, const unsigned char *key,
442 int keylen, unsigned char *sig, int siglen)
443 {
444 EVP_MD_CTX *mdctx;
445 EVP_PKEY *pkey;
446 char *sha256;
447 char errbuf[1024];
448 bool ret;
449
450 sha256 = NULL;
451 pkey = NULL;
452 mdctx = NULL;
453 ret = false;
454
455 SSL_load_error_strings();
456
457 /* Compute SHA256 of the package. */
458 if (lseek(fd, 0, 0) == -1) {
459 warn("lseek");
460 goto cleanup;
461 }
462 if ((sha256 = sha256_fd(fd)) == NULL) {
463 warnx("Error creating SHA256 hash for package");
464 goto cleanup;
465 }
466
467 if (sigfile != NULL) {
468 if ((pkey = load_public_key_file(sigfile)) == NULL) {
469 warnx("Error reading public key");
470 goto cleanup;
471 }
472 } else {
473 if ((pkey = load_public_key_buf(key, keylen)) == NULL) {
474 warnx("Error reading public key");
475 goto cleanup;
476 }
477 }
478
479 /* Verify signature of the SHA256(pkg) is valid. */
480 if ((mdctx = EVP_MD_CTX_create()) == NULL) {
481 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
482 goto error;
483 }
484
485 if (EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
486 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
487 goto error;
488 }
489 if (EVP_DigestVerifyUpdate(mdctx, sha256, strlen(sha256)) != 1) {
490 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
491 goto error;
492 }
493
494 if (EVP_DigestVerifyFinal(mdctx, sig, siglen) != 1) {
495 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
496 goto error;
497 }
498
499 ret = true;
500 printf("done\n");
501 goto cleanup;
502
503 error:
504 printf("failed\n");
505
506 cleanup:
507 free(sha256);
508 if (pkey)
509 EVP_PKEY_free(pkey);
510 if (mdctx)
511 EVP_MD_CTX_destroy(mdctx);
512 ERR_free_strings();
513
514 return (ret);
515 }
516
517 static struct pubkey *
read_pubkey(int fd)518 read_pubkey(int fd)
519 {
520 struct pubkey *pk;
521 char *sigb;
522 size_t sigsz;
523 FILE *sig;
524 char buf[4096];
525 int r;
526
527 if (lseek(fd, 0, 0) == -1) {
528 warn("lseek");
529 return (NULL);
530 }
531
532 sigsz = 0;
533 sigb = NULL;
534 sig = open_memstream(&sigb, &sigsz);
535 if (sig == NULL)
536 err(EXIT_FAILURE, "open_memstream()");
537
538 while ((r = read(fd, buf, sizeof(buf))) >0) {
539 fwrite(buf, 1, r, sig);
540 }
541
542 fclose(sig);
543 pk = calloc(1, sizeof(struct pubkey));
544 pk->siglen = sigsz;
545 pk->sig = calloc(1, pk->siglen);
546 memcpy(pk->sig, sigb, pk->siglen);
547 free(sigb);
548
549 return (pk);
550 }
551
552 static struct sig_cert *
parse_cert(int fd)553 parse_cert(int fd) {
554 int my_fd;
555 struct sig_cert *sc;
556 FILE *fp, *sigfp, *certfp, *tmpfp;
557 char *line;
558 char *sig, *cert;
559 size_t linecap, sigsz, certsz;
560 ssize_t linelen;
561
562 sc = NULL;
563 line = NULL;
564 linecap = 0;
565 sig = cert = NULL;
566 sigfp = certfp = tmpfp = NULL;
567
568 if (lseek(fd, 0, 0) == -1) {
569 warn("lseek");
570 return (NULL);
571 }
572
573 /* Duplicate the fd so that fclose(3) does not close it. */
574 if ((my_fd = dup(fd)) == -1) {
575 warnx("dup");
576 return (NULL);
577 }
578
579 if ((fp = fdopen(my_fd, "rb")) == NULL) {
580 warn("fdopen");
581 close(my_fd);
582 return (NULL);
583 }
584
585 sigsz = certsz = 0;
586 sigfp = open_memstream(&sig, &sigsz);
587 if (sigfp == NULL)
588 err(EXIT_FAILURE, "open_memstream()");
589 certfp = open_memstream(&cert, &certsz);
590 if (certfp == NULL)
591 err(EXIT_FAILURE, "open_memstream()");
592
593 while ((linelen = getline(&line, &linecap, fp)) > 0) {
594 if (strcmp(line, "SIGNATURE\n") == 0) {
595 tmpfp = sigfp;
596 continue;
597 } else if (strcmp(line, "CERT\n") == 0) {
598 tmpfp = certfp;
599 continue;
600 } else if (strcmp(line, "END\n") == 0) {
601 break;
602 }
603 if (tmpfp != NULL)
604 fwrite(line, 1, linelen, tmpfp);
605 }
606
607 fclose(fp);
608 fclose(sigfp);
609 fclose(certfp);
610
611 sc = calloc(1, sizeof(struct sig_cert));
612 sc->siglen = sigsz -1; /* Trim out unrelated trailing newline */
613 sc->sig = sig;
614
615 sc->certlen = certsz;
616 sc->cert = cert;
617
618 return (sc);
619 }
620
621 static bool
verify_pubsignature(int fd_pkg,int fd_sig)622 verify_pubsignature(int fd_pkg, int fd_sig)
623 {
624 struct pubkey *pk;
625 const char *pubkey;
626 bool ret;
627
628 pk = NULL;
629 pubkey = NULL;
630 ret = false;
631 if (config_string(PUBKEY, &pubkey) != 0) {
632 warnx("No CONFIG_PUBKEY defined");
633 goto cleanup;
634 }
635
636 if ((pk = read_pubkey(fd_sig)) == NULL) {
637 warnx("Error reading signature");
638 goto cleanup;
639 }
640
641 /* Verify the signature. */
642 printf("Verifying signature with public key %s... ", pubkey);
643 if (rsa_verify_cert(fd_pkg, pubkey, NULL, 0, pk->sig,
644 pk->siglen) == false) {
645 fprintf(stderr, "Signature is not valid\n");
646 goto cleanup;
647 }
648
649 ret = true;
650
651 cleanup:
652 if (pk) {
653 free(pk->sig);
654 free(pk);
655 }
656
657 return (ret);
658 }
659
660 static bool
verify_signature(int fd_pkg,int fd_sig)661 verify_signature(int fd_pkg, int fd_sig)
662 {
663 struct fingerprint_list *trusted, *revoked;
664 struct fingerprint *fingerprint;
665 struct sig_cert *sc;
666 bool ret;
667 int trusted_count, revoked_count;
668 const char *fingerprints;
669 char path[MAXPATHLEN];
670 char *hash;
671
672 hash = NULL;
673 sc = NULL;
674 trusted = revoked = NULL;
675 ret = false;
676
677 /* Read and parse fingerprints. */
678 if (config_string(FINGERPRINTS, &fingerprints) != 0) {
679 warnx("No CONFIG_FINGERPRINTS defined");
680 goto cleanup;
681 }
682
683 snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
684 if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
685 warnx("Error loading trusted certificates");
686 goto cleanup;
687 }
688
689 if (trusted_count == 0 || trusted == NULL) {
690 fprintf(stderr, "No trusted certificates found.\n");
691 goto cleanup;
692 }
693
694 snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
695 if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
696 warnx("Error loading revoked certificates");
697 goto cleanup;
698 }
699
700 /* Read certificate and signature in. */
701 if ((sc = parse_cert(fd_sig)) == NULL) {
702 warnx("Error parsing certificate");
703 goto cleanup;
704 }
705 /* Explicitly mark as non-trusted until proven otherwise. */
706 sc->trusted = false;
707
708 /* Parse signature and pubkey out of the certificate */
709 hash = sha256_buf(sc->cert, sc->certlen);
710
711 /* Check if this hash is revoked */
712 if (revoked != NULL) {
713 STAILQ_FOREACH(fingerprint, revoked, next) {
714 if (strcasecmp(fingerprint->hash, hash) == 0) {
715 fprintf(stderr, "The package was signed with "
716 "revoked certificate %s\n",
717 fingerprint->name);
718 goto cleanup;
719 }
720 }
721 }
722
723 STAILQ_FOREACH(fingerprint, trusted, next) {
724 if (strcasecmp(fingerprint->hash, hash) == 0) {
725 sc->trusted = true;
726 sc->name = strdup(fingerprint->name);
727 break;
728 }
729 }
730
731 if (sc->trusted == false) {
732 fprintf(stderr, "No trusted fingerprint found matching "
733 "package's certificate\n");
734 goto cleanup;
735 }
736
737 /* Verify the signature. */
738 printf("Verifying signature with trusted certificate %s... ", sc->name);
739 if (rsa_verify_cert(fd_pkg, NULL, sc->cert, sc->certlen, sc->sig,
740 sc->siglen) == false) {
741 fprintf(stderr, "Signature is not valid\n");
742 goto cleanup;
743 }
744
745 ret = true;
746
747 cleanup:
748 free(hash);
749 if (trusted)
750 free_fingerprint_list(trusted);
751 if (revoked)
752 free_fingerprint_list(revoked);
753 if (sc) {
754 free(sc->cert);
755 free(sc->sig);
756 free(sc->name);
757 free(sc);
758 }
759
760 return (ret);
761 }
762
763 static int
bootstrap_pkg(bool force,const char * fetchOpts)764 bootstrap_pkg(bool force, const char *fetchOpts)
765 {
766 int fd_pkg, fd_sig;
767 int ret;
768 char url[MAXPATHLEN];
769 char tmppkg[MAXPATHLEN];
770 char tmpsig[MAXPATHLEN];
771 const char *packagesite;
772 const char *signature_type;
773 char pkgstatic[MAXPATHLEN];
774 const char *bootstrap_name;
775
776 fd_sig = -1;
777 ret = -1;
778
779 if (config_string(PACKAGESITE, &packagesite) != 0) {
780 warnx("No PACKAGESITE defined");
781 return (-1);
782 }
783
784 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
785 warnx("Error looking up SIGNATURE_TYPE");
786 return (-1);
787 }
788
789 printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
790
791 /* Support pkg+http:// for PACKAGESITE which is the new format
792 in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
793 no A record. */
794 if (strncmp(URL_SCHEME_PREFIX, packagesite,
795 strlen(URL_SCHEME_PREFIX)) == 0)
796 packagesite += strlen(URL_SCHEME_PREFIX);
797 for (int j = 0; bootstrap_names[j] != NULL; j++) {
798 bootstrap_name = bootstrap_names[j];
799
800 snprintf(url, MAXPATHLEN, "%s/Latest/%s", packagesite, bootstrap_name);
801 snprintf(tmppkg, MAXPATHLEN, "%s/%s.XXXXXX",
802 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP,
803 bootstrap_name);
804 if ((fd_pkg = fetch_to_fd(url, tmppkg, fetchOpts)) != -1)
805 break;
806 bootstrap_name = NULL;
807 }
808 if (bootstrap_name == NULL)
809 goto fetchfail;
810
811 if (signature_type != NULL &&
812 strcasecmp(signature_type, "NONE") != 0) {
813 if (strcasecmp(signature_type, "FINGERPRINTS") == 0) {
814
815 snprintf(tmpsig, MAXPATHLEN, "%s/%s.sig.XXXXXX",
816 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP,
817 bootstrap_name);
818 snprintf(url, MAXPATHLEN, "%s/Latest/%s.sig",
819 packagesite, bootstrap_name);
820
821 if ((fd_sig = fetch_to_fd(url, tmpsig, fetchOpts)) == -1) {
822 fprintf(stderr, "Signature for pkg not "
823 "available.\n");
824 goto fetchfail;
825 }
826
827 if (verify_signature(fd_pkg, fd_sig) == false)
828 goto cleanup;
829 } else if (strcasecmp(signature_type, "PUBKEY") == 0) {
830
831 snprintf(tmpsig, MAXPATHLEN,
832 "%s/%s.pubkeysig.XXXXXX",
833 getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP,
834 bootstrap_name);
835 snprintf(url, MAXPATHLEN, "%s/Latest/%s.pubkeysig",
836 packagesite, bootstrap_name);
837
838 if ((fd_sig = fetch_to_fd(url, tmpsig, fetchOpts)) == -1) {
839 fprintf(stderr, "Signature for pkg not "
840 "available.\n");
841 goto fetchfail;
842 }
843
844 if (verify_pubsignature(fd_pkg, fd_sig) == false)
845 goto cleanup;
846 } else {
847 warnx("Signature type %s is not supported for "
848 "bootstrapping.", signature_type);
849 goto cleanup;
850 }
851 }
852
853 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
854 ret = install_pkg_static(pkgstatic, tmppkg, force);
855
856 goto cleanup;
857
858 fetchfail:
859 for (int j = 0; bootstrap_names[j] != NULL; j++) {
860 warnx("Attempted to fetch %s/Latest/%s", packagesite,
861 bootstrap_names[j]);
862 }
863 warnx("Error: %s", fetchLastErrString);
864 if (fetchLastErrCode == FETCH_RESOLV) {
865 fprintf(stderr, "Address resolution failed for %s.\n", packagesite);
866 fprintf(stderr, "Consider changing PACKAGESITE.\n");
867 } else {
868 fprintf(stderr, "A pre-built version of pkg could not be found for "
869 "your system.\n");
870 fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
871 "ports: 'ports-mgmt/pkg'.\n");
872 }
873
874 cleanup:
875 if (fd_sig != -1) {
876 close(fd_sig);
877 unlink(tmpsig);
878 }
879
880 if (fd_pkg != -1) {
881 close(fd_pkg);
882 unlink(tmppkg);
883 }
884
885 return (ret);
886 }
887
888 static const char confirmation_message[] =
889 "The package management tool is not yet installed on your system.\n"
890 "Do you want to fetch and install it now? [y/N]: ";
891
892 static const char non_interactive_message[] =
893 "The package management tool is not yet installed on your system.\n"
894 "Please set ASSUME_ALWAYS_YES=yes environment variable to be able to bootstrap "
895 "in non-interactive (stdin not being a tty)\n";
896
897 static const char args_bootstrap_message[] =
898 "Too many arguments\n"
899 "Usage: pkg [-4|-6] bootstrap [-f] [-y]\n";
900
901 static const char args_add_message[] =
902 "Too many arguments\n"
903 "Usage: pkg add [-f] [-y] {pkg.pkg}\n";
904
905 static int
pkg_query_yes_no(void)906 pkg_query_yes_no(void)
907 {
908 int ret, c;
909
910 fflush(stdout);
911 c = getchar();
912
913 if (c == 'y' || c == 'Y')
914 ret = 1;
915 else
916 ret = 0;
917
918 while (c != '\n' && c != EOF)
919 c = getchar();
920
921 return (ret);
922 }
923
924 static int
bootstrap_pkg_local(const char * pkgpath,bool force)925 bootstrap_pkg_local(const char *pkgpath, bool force)
926 {
927 char path[MAXPATHLEN];
928 char pkgstatic[MAXPATHLEN];
929 const char *signature_type;
930 int fd_pkg, fd_sig, ret;
931
932 fd_sig = -1;
933 ret = -1;
934
935 fd_pkg = open(pkgpath, O_RDONLY);
936 if (fd_pkg == -1)
937 err(EXIT_FAILURE, "Unable to open %s", pkgpath);
938
939 if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
940 warnx("Error looking up SIGNATURE_TYPE");
941 goto cleanup;
942 }
943 if (signature_type != NULL &&
944 strcasecmp(signature_type, "NONE") != 0) {
945 if (strcasecmp(signature_type, "FINGERPRINTS") == 0) {
946
947 snprintf(path, sizeof(path), "%s.sig", pkgpath);
948
949 if ((fd_sig = open(path, O_RDONLY)) == -1) {
950 fprintf(stderr, "Signature for pkg not "
951 "available.\n");
952 goto cleanup;
953 }
954
955 if (verify_signature(fd_pkg, fd_sig) == false)
956 goto cleanup;
957
958 } else if (strcasecmp(signature_type, "PUBKEY") == 0) {
959
960 snprintf(path, sizeof(path), "%s.pubkeysig", pkgpath);
961
962 if ((fd_sig = open(path, O_RDONLY)) == -1) {
963 fprintf(stderr, "Signature for pkg not "
964 "available.\n");
965 goto cleanup;
966 }
967
968 if (verify_pubsignature(fd_pkg, fd_sig) == false)
969 goto cleanup;
970
971 } else {
972 warnx("Signature type %s is not supported for "
973 "bootstrapping.", signature_type);
974 goto cleanup;
975 }
976 }
977
978 if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
979 ret = install_pkg_static(pkgstatic, pkgpath, force);
980
981 cleanup:
982 close(fd_pkg);
983 if (fd_sig != -1)
984 close(fd_sig);
985
986 return (ret);
987 }
988
989 #define PKG_NAME "pkg"
990 #define PKG_DEVEL_NAME PKG_NAME "-devel"
991 #define PKG_PKG PKG_NAME "."
992
993 static bool
pkg_is_pkg_pkg(const char * pkg)994 pkg_is_pkg_pkg(const char *pkg)
995 {
996 char *vstart, *basename;
997 size_t namelen;
998
999 /* Strip path. */
1000 if ((basename = strrchr(pkg, '/')) != NULL)
1001 pkg = basename + 1;
1002
1003 /*
1004 * Chop off the final "-" (version delimiter) and check the name that
1005 * precedes it. If we didn't have a version delimiter, it must be the
1006 * pkg.$archive short form but we'll check it anyways. pkg-devel short
1007 * form will look like a pkg archive with 'devel' version, but that's
1008 * OK. We otherwise assumed that non-pkg packages will always have a
1009 * version component.
1010 */
1011 vstart = strrchr(pkg, '-');
1012 if (vstart == NULL) {
1013 return (strlen(pkg) > sizeof(PKG_PKG) - 1 &&
1014 strncmp(pkg, PKG_PKG, sizeof(PKG_PKG) - 1) == 0);
1015 }
1016
1017 namelen = vstart - pkg;
1018 if (namelen == sizeof(PKG_NAME) - 1 &&
1019 strncmp(pkg, PKG_NAME, sizeof(PKG_NAME) - 1) == 0)
1020 return (true);
1021 if (namelen == sizeof(PKG_DEVEL_NAME) - 1 &&
1022 strncmp(pkg, PKG_DEVEL_NAME, sizeof(PKG_DEVEL_NAME) - 1) == 0)
1023 return (true);
1024 return (false);
1025 }
1026
1027 int
main(int argc,char * argv[])1028 main(int argc, char *argv[])
1029 {
1030 char pkgpath[MAXPATHLEN];
1031 const char *pkgarg, *repo_name;
1032 bool activation_test, add_pkg, bootstrap_only, force, yes;
1033 signed char ch;
1034 const char *fetchOpts;
1035 char *command;
1036
1037 activation_test = false;
1038 add_pkg = false;
1039 bootstrap_only = false;
1040 command = NULL;
1041 fetchOpts = "";
1042 force = false;
1043 pkgarg = NULL;
1044 repo_name = NULL;
1045 yes = false;
1046
1047 struct option longopts[] = {
1048 { "debug", no_argument, NULL, 'd' },
1049 { "force", no_argument, NULL, 'f' },
1050 { "only-ipv4", no_argument, NULL, '4' },
1051 { "only-ipv6", no_argument, NULL, '6' },
1052 { "yes", no_argument, NULL, 'y' },
1053 { NULL, 0, NULL, 0 },
1054 };
1055
1056 snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg", getlocalbase());
1057
1058 while ((ch = getopt_long(argc, argv, "-:dfr::yN46", longopts, NULL)) != -1) {
1059 switch (ch) {
1060 case 'd':
1061 debug++;
1062 break;
1063 case 'f':
1064 force = true;
1065 break;
1066 case 'N':
1067 activation_test = true;
1068 break;
1069 case 'y':
1070 yes = true;
1071 break;
1072 case '4':
1073 fetchOpts = "4";
1074 break;
1075 case '6':
1076 fetchOpts = "6";
1077 break;
1078 case 'r':
1079 /*
1080 * The repository can only be specified for an explicit
1081 * bootstrap request at this time, so that we don't
1082 * confuse the user if they're trying to use a verb that
1083 * has some other conflicting meaning but we need to
1084 * bootstrap.
1085 *
1086 * For that reason, we specify that -r has an optional
1087 * argument above and process the next index ourselves.
1088 * This is mostly significant because getopt(3) will
1089 * otherwise eat the next argument, which could be
1090 * something we need to try and make sense of.
1091 *
1092 * At worst this gets us false positives that we ignore
1093 * in other contexts, and we have to do a little fudging
1094 * in order to support separating -r from the reponame
1095 * with a space since it's not actually optional in
1096 * the bootstrap/add sense.
1097 */
1098 if (add_pkg || bootstrap_only) {
1099 if (optarg != NULL) {
1100 repo_name = optarg;
1101 } else if (optind < argc) {
1102 repo_name = argv[optind];
1103 }
1104
1105 if (repo_name == NULL || *repo_name == '\0') {
1106 fprintf(stderr,
1107 "Must specify a repository with -r!\n");
1108 exit(EXIT_FAILURE);
1109 }
1110
1111 if (optarg == NULL) {
1112 /* Advance past repo name. */
1113 optreset = 1;
1114 optind++;
1115 }
1116 }
1117 break;
1118 case 1:
1119 // Non-option arguments, first one is the command
1120 if (command == NULL) {
1121 command = argv[optind-1];
1122 if (strcmp(command, "add") == 0) {
1123 add_pkg = true;
1124 }
1125 else if (strcmp(command, "bootstrap") == 0) {
1126 bootstrap_only = true;
1127 }
1128 }
1129 // bootstrap doesn't accept other arguments
1130 else if (bootstrap_only) {
1131 fprintf(stderr, args_bootstrap_message);
1132 exit(EXIT_FAILURE);
1133 }
1134 else if (add_pkg && pkgarg != NULL) {
1135 /*
1136 * Additional arguments also means it's not a
1137 * local bootstrap request.
1138 */
1139 add_pkg = false;
1140 }
1141 else if (add_pkg) {
1142 /*
1143 * If it's not a request for pkg or pkg-devel,
1144 * then we must assume they were trying to
1145 * install some other local package and we
1146 * should try to bootstrap from the repo.
1147 */
1148 if (!pkg_is_pkg_pkg(argv[optind-1])) {
1149 add_pkg = false;
1150 } else {
1151 pkgarg = argv[optind-1];
1152 }
1153 }
1154 break;
1155 default:
1156 break;
1157 }
1158 }
1159 if (debug > 1)
1160 fetchDebug = 1;
1161
1162 if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
1163 /*
1164 * To allow 'pkg -N' to be used as a reliable test for whether
1165 * a system is configured to use pkg, don't bootstrap pkg
1166 * when that option is passed.
1167 */
1168 if (activation_test)
1169 errx(EXIT_FAILURE, "pkg is not installed");
1170
1171 config_init(repo_name);
1172
1173 if (add_pkg) {
1174 if (pkgarg == NULL) {
1175 fprintf(stderr, "Path to pkg.pkg required\n");
1176 exit(EXIT_FAILURE);
1177 }
1178 if (access(pkgarg, R_OK) == -1) {
1179 fprintf(stderr, "No such file: %s\n", pkgarg);
1180 exit(EXIT_FAILURE);
1181 }
1182 if (bootstrap_pkg_local(pkgarg, force) != 0)
1183 exit(EXIT_FAILURE);
1184 exit(EXIT_SUCCESS);
1185 }
1186 /*
1187 * Do not ask for confirmation if either of stdin or stdout is
1188 * not tty. Check the environment to see if user has answer
1189 * tucked in there already.
1190 */
1191 if (!yes)
1192 config_bool(ASSUME_ALWAYS_YES, &yes);
1193 if (!yes) {
1194 if (!isatty(fileno(stdin))) {
1195 fprintf(stderr, non_interactive_message);
1196 exit(EXIT_FAILURE);
1197 }
1198
1199 printf("%s", confirmation_message);
1200 if (pkg_query_yes_no() == 0)
1201 exit(EXIT_FAILURE);
1202 }
1203 if (bootstrap_pkg(force, fetchOpts) != 0)
1204 exit(EXIT_FAILURE);
1205 config_finish();
1206
1207 if (bootstrap_only)
1208 exit(EXIT_SUCCESS);
1209 } else if (bootstrap_only) {
1210 printf("pkg already bootstrapped at %s\n", pkgpath);
1211 exit(EXIT_SUCCESS);
1212 }
1213
1214 execv(pkgpath, argv);
1215
1216 /* NOT REACHED */
1217 return (EXIT_FAILURE);
1218 }
1219