]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - usr.sbin/pkg/pkg.c
MFC r289577:
[FreeBSD/stable/9.git] / usr.sbin / pkg / pkg.c
1 /*-
2  * Copyright (c) 2012-2014 Baptiste Daroussin <bapt@FreeBSD.org>
3  * Copyright (c) 2013 Bryan Drewery <bdrewery@FreeBSD.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
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.
14  * 
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
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 #include <sys/param.h>
32 #include <sys/queue.h>
33 #include <sys/types.h>
34 #include <sys/sbuf.h>
35 #include <sys/wait.h>
36
37 #define _WITH_GETLINE
38 #include <archive.h>
39 #include <archive_entry.h>
40 #include <dirent.h>
41 #include <err.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <fetch.h>
45 #include <paths.h>
46 #include <stdbool.h>
47 #include <stdlib.h>
48 #include <stdio.h>
49 #include <string.h>
50 #include <unistd.h>
51 #include <ucl.h>
52
53 #include <openssl/err.h>
54 #include <openssl/ssl.h>
55
56 #include "dns_utils.h"
57 #include "config.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 STAILQ_HEAD(fingerprint_list, fingerprint);
86
87 static int
88 extract_pkg_static(int fd, char *p, int sz)
89 {
90         struct archive *a;
91         struct archive_entry *ae;
92         char *end;
93         int ret, r;
94
95         ret = -1;
96         a = archive_read_new();
97         if (a == NULL) {
98                 warn("archive_read_new");
99                 return (ret);
100         }
101         archive_read_support_compression_all(a);
102         archive_read_support_format_tar(a);
103
104         if (lseek(fd, 0, 0) == -1) {
105                 warn("lseek");
106                 goto cleanup;
107         }
108
109         if (archive_read_open_fd(a, fd, 4096) != ARCHIVE_OK) {
110                 warnx("archive_read_open_fd: %s", archive_error_string(a));
111                 goto cleanup;
112         }
113
114         ae = NULL;
115         while ((r = archive_read_next_header(a, &ae)) == ARCHIVE_OK) {
116                 end = strrchr(archive_entry_pathname(ae), '/');
117                 if (end == NULL)
118                         continue;
119
120                 if (strcmp(end, "/pkg-static") == 0) {
121                         r = archive_read_extract(a, ae,
122                             ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM |
123                             ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_ACL |
124                             ARCHIVE_EXTRACT_FFLAGS | ARCHIVE_EXTRACT_XATTR);
125                         strlcpy(p, archive_entry_pathname(ae), sz);
126                         break;
127                 }
128         }
129
130         if (r == ARCHIVE_OK)
131                 ret = 0;
132         else
133                 warnx("failed to extract pkg-static: %s",
134                     archive_error_string(a));
135
136 cleanup:
137         archive_read_free(a);
138         return (ret);
139
140 }
141
142 static int
143 install_pkg_static(const char *path, const char *pkgpath, bool force)
144 {
145         int pstat;
146         pid_t pid;
147
148         switch ((pid = fork())) {
149         case -1:
150                 return (-1);
151         case 0:
152                 if (force)
153                         execl(path, "pkg-static", "add", "-f", pkgpath,
154                             (char *)NULL);
155                 else
156                         execl(path, "pkg-static", "add", pkgpath,
157                             (char *)NULL);
158                 _exit(1);
159         default:
160                 break;
161         }
162
163         while (waitpid(pid, &pstat, 0) == -1)
164                 if (errno != EINTR)
165                         return (-1);
166
167         if (WEXITSTATUS(pstat))
168                 return (WEXITSTATUS(pstat));
169         else if (WIFSIGNALED(pstat))
170                 return (128 & (WTERMSIG(pstat)));
171         return (pstat);
172 }
173
174 static int
175 fetch_to_fd(const char *url, char *path)
176 {
177         struct url *u;
178         struct dns_srvinfo *mirrors, *current;
179         struct url_stat st;
180         FILE *remote;
181         /* To store _https._tcp. + hostname + \0 */
182         int fd;
183         int retry, max_retry;
184         ssize_t r;
185         char buf[10240];
186         char zone[MAXHOSTNAMELEN + 13];
187         static const char *mirror_type = NULL;
188
189         max_retry = 3;
190         current = mirrors = NULL;
191         remote = NULL;
192
193         if (mirror_type == NULL && config_string(MIRROR_TYPE, &mirror_type)
194             != 0) {
195                 warnx("No MIRROR_TYPE defined");
196                 return (-1);
197         }
198
199         if ((fd = mkstemp(path)) == -1) {
200                 warn("mkstemp()");
201                 return (-1);
202         }
203
204         retry = max_retry;
205
206         u = fetchParseURL(url);
207         while (remote == NULL) {
208                 if (retry == max_retry) {
209                         if (strcmp(u->scheme, "file") != 0 &&
210                             strcasecmp(mirror_type, "srv") == 0) {
211                                 snprintf(zone, sizeof(zone),
212                                     "_%s._tcp.%s", u->scheme, u->host);
213                                 mirrors = dns_getsrvinfo(zone);
214                                 current = mirrors;
215                         }
216                 }
217
218                 if (mirrors != NULL) {
219                         strlcpy(u->host, current->host, sizeof(u->host));
220                         u->port = current->port;
221                 }
222
223                 remote = fetchXGet(u, &st, "");
224                 if (remote == NULL) {
225                         --retry;
226                         if (retry <= 0)
227                                 goto fetchfail;
228                         if (mirrors == NULL) {
229                                 sleep(1);
230                         } else {
231                                 current = current->next;
232                                 if (current == NULL)
233                                         current = mirrors;
234                         }
235                 }
236         }
237
238         while ((r = fread(buf, 1, sizeof(buf), remote)) > 0) {
239                 if (write(fd, buf, r) != r) {
240                         warn("write()");
241                         goto fetchfail;
242                 }
243         }
244
245         if (r != 0) {
246                 warn("An error occurred while fetching pkg(8)");
247                 goto fetchfail;
248         }
249
250         if (ferror(remote))
251                 goto fetchfail;
252
253         goto cleanup;
254
255 fetchfail:
256         if (fd != -1) {
257                 close(fd);
258                 fd = -1;
259                 unlink(path);
260         }
261
262 cleanup:
263         if (remote != NULL)
264                 fclose(remote);
265
266         return fd;
267 }
268
269 static struct fingerprint *
270 parse_fingerprint(ucl_object_t *obj)
271 {
272         const ucl_object_t *cur;
273         ucl_object_iter_t it = NULL;
274         const char *function, *fp, *key;
275         struct fingerprint *f;
276         hash_t fct = HASH_UNKNOWN;
277
278         function = fp = NULL;
279
280         while ((cur = ucl_iterate_object(obj, &it, true))) {
281                 key = ucl_object_key(cur);
282                 if (cur->type != UCL_STRING)
283                         continue;
284                 if (strcasecmp(key, "function") == 0) {
285                         function = ucl_object_tostring(cur);
286                         continue;
287                 }
288                 if (strcasecmp(key, "fingerprint") == 0) {
289                         fp = ucl_object_tostring(cur);
290                         continue;
291                 }
292         }
293
294         if (fp == NULL || function == NULL)
295                 return (NULL);
296
297         if (strcasecmp(function, "sha256") == 0)
298                 fct = HASH_SHA256;
299
300         if (fct == HASH_UNKNOWN) {
301                 warnx("Unsupported hashing function: %s", function);
302                 return (NULL);
303         }
304
305         f = calloc(1, sizeof(struct fingerprint));
306         f->type = fct;
307         strlcpy(f->hash, fp, sizeof(f->hash));
308
309         return (f);
310 }
311
312 static void
313 free_fingerprint_list(struct fingerprint_list* list)
314 {
315         struct fingerprint *fingerprint, *tmp;
316
317         STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
318                 free(fingerprint->name);
319                 free(fingerprint);
320         }
321         free(list);
322 }
323
324 static struct fingerprint *
325 load_fingerprint(const char *dir, const char *filename)
326 {
327         ucl_object_t *obj = NULL;
328         struct ucl_parser *p = NULL;
329         struct fingerprint *f;
330         char path[MAXPATHLEN];
331
332         f = NULL;
333
334         snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
335
336         p = ucl_parser_new(0);
337         if (!ucl_parser_add_file(p, path)) {
338                 warnx("%s: %s", path, ucl_parser_get_error(p));
339                 ucl_parser_free(p);
340                 return (NULL);
341         }
342
343         obj = ucl_parser_get_object(p);
344
345         if (obj->type == UCL_OBJECT)
346                 f = parse_fingerprint(obj);
347
348         if (f != NULL)
349                 f->name = strdup(filename);
350
351         ucl_object_unref(obj);
352         ucl_parser_free(p);
353
354         return (f);
355 }
356
357 static struct fingerprint_list *
358 load_fingerprints(const char *path, int *count)
359 {
360         DIR *d;
361         struct dirent *ent;
362         struct fingerprint *finger;
363         struct fingerprint_list *fingerprints;
364
365         *count = 0;
366
367         fingerprints = calloc(1, sizeof(struct fingerprint_list));
368         if (fingerprints == NULL)
369                 return (NULL);
370         STAILQ_INIT(fingerprints);
371
372         if ((d = opendir(path)) == NULL)
373                 return (NULL);
374
375         while ((ent = readdir(d))) {
376                 if (strcmp(ent->d_name, ".") == 0 ||
377                     strcmp(ent->d_name, "..") == 0)
378                         continue;
379                 finger = load_fingerprint(path, ent->d_name);
380                 if (finger != NULL) {
381                         STAILQ_INSERT_TAIL(fingerprints, finger, next);
382                         ++(*count);
383                 }
384         }
385
386         closedir(d);
387
388         return (fingerprints);
389 }
390
391 static void
392 sha256_hash(unsigned char hash[SHA256_DIGEST_LENGTH],
393     char out[SHA256_DIGEST_LENGTH * 2 + 1])
394 {
395         int i;
396
397         for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
398                 sprintf(out + (i * 2), "%02x", hash[i]);
399
400         out[SHA256_DIGEST_LENGTH * 2] = '\0';
401 }
402
403 static void
404 sha256_buf_bin(char *buf, size_t len, char hash[SHA256_DIGEST_LENGTH])
405 {
406         SHA256_CTX sha256;
407
408         SHA256_Init(&sha256);
409         SHA256_Update(&sha256, buf, len);
410         SHA256_Final(hash, &sha256);
411 }
412
413
414 static void
415 sha256_buf(char *buf, size_t len, char out[SHA256_DIGEST_LENGTH * 2 + 1])
416 {
417         unsigned char hash[SHA256_DIGEST_LENGTH];
418         SHA256_CTX sha256;
419
420         out[0] = '\0';
421
422         SHA256_Init(&sha256);
423         SHA256_Update(&sha256, buf, len);
424         SHA256_Final(hash, &sha256);
425         sha256_hash(hash, out);
426 }
427
428 static int
429 sha256_fd(int fd, char out[SHA256_DIGEST_LENGTH * 2 + 1])
430 {
431         int my_fd;
432         FILE *fp;
433         char buffer[BUFSIZ];
434         unsigned char hash[SHA256_DIGEST_LENGTH];
435         size_t r;
436         int ret;
437         SHA256_CTX sha256;
438
439         my_fd = -1;
440         fp = NULL;
441         r = 0;
442         ret = 1;
443
444         out[0] = '\0';
445
446         /* Duplicate the fd so that fclose(3) does not close it. */
447         if ((my_fd = dup(fd)) == -1) {
448                 warnx("dup");
449                 goto cleanup;
450         }
451
452         if ((fp = fdopen(my_fd, "rb")) == NULL) {
453                 warnx("fdopen");
454                 goto cleanup;
455         }
456
457         SHA256_Init(&sha256);
458
459         while ((r = fread(buffer, 1, BUFSIZ, fp)) > 0)
460                 SHA256_Update(&sha256, buffer, r);
461
462         if (ferror(fp) != 0) {
463                 warnx("fread");
464                 goto cleanup;
465         }
466
467         SHA256_Final(hash, &sha256);
468         sha256_hash(hash, out);
469         ret = 0;
470
471 cleanup:
472         if (fp != NULL)
473                 fclose(fp);
474         else if (my_fd != -1)
475                 close(my_fd);
476         (void)lseek(fd, 0, SEEK_SET);
477
478         return (ret);
479 }
480
481 static RSA *
482 load_rsa_public_key_file(const char *file)
483 {
484         RSA *rsa = NULL;
485         BIO *bp;
486         char errbuf[1024];
487
488         bp = BIO_new_file(file, "r");
489         if (!bp)
490                 errx(EXIT_FAILURE, "Unable to read %s", file);
491
492         if (!PEM_read_bio_RSA_PUBKEY(bp, &rsa, NULL, NULL)) {
493                 warn("error reading public key: %s",
494                     ERR_error_string(ERR_get_error(), errbuf));
495                 BIO_free(bp);
496                 return (NULL);
497         }
498
499         BIO_free(bp);
500
501         return (rsa);
502 }
503
504 static RSA *
505 load_rsa_public_key_buf(unsigned char *cert, int certlen)
506 {
507         RSA *rsa = NULL;
508         BIO *bp;
509         char errbuf[1024];
510
511         bp = BIO_new_mem_buf((void *)cert, certlen);
512         if (!PEM_read_bio_RSA_PUBKEY(bp, &rsa, NULL, NULL)) {
513                 warn("error reading public key: %s",
514                     ERR_error_string(ERR_get_error(), errbuf));
515                 BIO_free(bp);
516                 return (NULL);
517         }
518         BIO_free(bp);
519         return (rsa);
520 }
521
522
523 static bool
524 rsa_verify_cert(int fd, const char *sigfile, unsigned char *key,
525     int keylen, unsigned char *sig, int siglen)
526 {
527         char sha256[SHA256_DIGEST_LENGTH *2 +1];
528         char hash[SHA256_DIGEST_LENGTH];
529         char errbuf[1024];
530         RSA *rsa = NULL;
531         int ret;
532
533         lseek(fd, 0, SEEK_SET);
534         sha256_fd(fd, sha256);
535
536         SSL_load_error_strings();
537         OpenSSL_add_all_algorithms();
538         OpenSSL_add_all_ciphers();
539
540         sha256_buf_bin(sha256, strlen(sha256), hash);
541
542         if (sigfile != NULL) {
543                 rsa = load_rsa_public_key_file(sigfile);
544         } else {
545                 rsa = load_rsa_public_key_buf(key, keylen);
546         }
547         if (rsa == NULL)
548                 return (false);
549         ret = RSA_verify(NID_sha256, hash, sizeof(hash), sig, siglen, rsa);
550         if (ret == 0) {
551                 warnx("%s: %s", key, ERR_error_string(ERR_get_error(), errbuf));
552                 return (false);
553         }
554
555         RSA_free(rsa);
556         ERR_free_strings();
557
558         return (true);
559 }
560
561 static struct pubkey *
562 read_pubkey(int fd)
563 {
564         struct pubkey *pk;
565         struct sbuf *sig;
566         char buf[4096];
567         int r;
568
569         if (lseek(fd, 0, 0) == -1) {
570                 warn("lseek");
571                 return (NULL);
572         }
573
574         sig = sbuf_new_auto();
575
576         while ((r = read(fd, buf, sizeof(buf))) >0) {
577                 sbuf_bcat(sig, buf, r);
578         }
579
580         sbuf_finish(sig);
581         pk = calloc(1, sizeof(struct pubkey));
582         pk->siglen = sbuf_len(sig);
583         pk->sig = calloc(1, pk->siglen);
584         memcpy(pk->sig, sbuf_data(sig), pk->siglen);
585         sbuf_delete(sig);
586
587         return (pk);
588 }
589
590 static struct sig_cert *
591 parse_cert(int fd) {
592         int my_fd;
593         struct sig_cert *sc;
594         FILE *fp;
595         struct sbuf *buf, *sig, *cert;
596         char *line;
597         size_t linecap;
598         ssize_t linelen;
599
600         buf = NULL;
601         my_fd = -1;
602         sc = NULL;
603         line = NULL;
604         linecap = 0;
605
606         if (lseek(fd, 0, 0) == -1) {
607                 warn("lseek");
608                 return (NULL);
609         }
610
611         /* Duplicate the fd so that fclose(3) does not close it. */
612         if ((my_fd = dup(fd)) == -1) {
613                 warnx("dup");
614                 return (NULL);
615         }
616
617         if ((fp = fdopen(my_fd, "rb")) == NULL) {
618                 warn("fdopen");
619                 close(my_fd);
620                 return (NULL);
621         }
622
623         sig = sbuf_new_auto();
624         cert = sbuf_new_auto();
625
626         while ((linelen = getline(&line, &linecap, fp)) > 0) {
627                 if (strcmp(line, "SIGNATURE\n") == 0) {
628                         buf = sig;
629                         continue;
630                 } else if (strcmp(line, "CERT\n") == 0) {
631                         buf = cert;
632                         continue;
633                 } else if (strcmp(line, "END\n") == 0) {
634                         break;
635                 }
636                 if (buf != NULL)
637                         sbuf_bcat(buf, line, linelen);
638         }
639
640         fclose(fp);
641
642         /* Trim out unrelated trailing newline */
643         sbuf_setpos(sig, sbuf_len(sig) - 1);
644
645         sbuf_finish(sig);
646         sbuf_finish(cert);
647
648         sc = calloc(1, sizeof(struct sig_cert));
649         sc->siglen = sbuf_len(sig);
650         sc->sig = calloc(1, sc->siglen);
651         memcpy(sc->sig, sbuf_data(sig), sc->siglen);
652
653         sc->certlen = sbuf_len(cert);
654         sc->cert = strdup(sbuf_data(cert));
655
656         sbuf_delete(sig);
657         sbuf_delete(cert);
658
659         return (sc);
660 }
661
662 static bool
663 verify_pubsignature(int fd_pkg, int fd_sig)
664 {
665         struct pubkey *pk;
666         const char *pubkey;
667         bool ret;
668
669         pk = NULL;
670         pubkey = NULL;
671         ret = false;
672         if (config_string(PUBKEY, &pubkey) != 0) {
673                 warnx("No CONFIG_PUBKEY defined");
674                 goto cleanup;
675         }
676
677         if ((pk = read_pubkey(fd_sig)) == NULL) {
678                 warnx("Error reading signature");
679                 goto cleanup;
680         }
681
682         /* Verify the signature. */
683         printf("Verifying signature with public key %s... ", pubkey);
684         if (rsa_verify_cert(fd_pkg, pubkey, NULL, 0, pk->sig,
685             pk->siglen) == false) {
686                 fprintf(stderr, "Signature is not valid\n");
687                 goto cleanup;
688         }
689
690         ret = true;
691
692 cleanup:
693         if (pk) {
694                 free(pk->sig);
695                 free(pk);
696         }
697
698         return (ret);
699 }
700
701 static bool
702 verify_signature(int fd_pkg, int fd_sig)
703 {
704         struct fingerprint_list *trusted, *revoked;
705         struct fingerprint *fingerprint;
706         struct sig_cert *sc;
707         bool ret;
708         int trusted_count, revoked_count;
709         const char *fingerprints;
710         char path[MAXPATHLEN];
711         char hash[SHA256_DIGEST_LENGTH * 2 + 1];
712
713         sc = NULL;
714         trusted = revoked = NULL;
715         ret = false;
716
717         /* Read and parse fingerprints. */
718         if (config_string(FINGERPRINTS, &fingerprints) != 0) {
719                 warnx("No CONFIG_FINGERPRINTS defined");
720                 goto cleanup;
721         }
722
723         snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
724         if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
725                 warnx("Error loading trusted certificates");
726                 goto cleanup;
727         }
728
729         if (trusted_count == 0 || trusted == NULL) {
730                 fprintf(stderr, "No trusted certificates found.\n");
731                 goto cleanup;
732         }
733
734         snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
735         if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
736                 warnx("Error loading revoked certificates");
737                 goto cleanup;
738         }
739
740         /* Read certificate and signature in. */
741         if ((sc = parse_cert(fd_sig)) == NULL) {
742                 warnx("Error parsing certificate");
743                 goto cleanup;
744         }
745         /* Explicitly mark as non-trusted until proven otherwise. */
746         sc->trusted = false;
747
748         /* Parse signature and pubkey out of the certificate */
749         sha256_buf(sc->cert, sc->certlen, hash);
750
751         /* Check if this hash is revoked */
752         if (revoked != NULL) {
753                 STAILQ_FOREACH(fingerprint, revoked, next) {
754                         if (strcasecmp(fingerprint->hash, hash) == 0) {
755                                 fprintf(stderr, "The package was signed with "
756                                     "revoked certificate %s\n",
757                                     fingerprint->name);
758                                 goto cleanup;
759                         }
760                 }
761         }
762
763         STAILQ_FOREACH(fingerprint, trusted, next) {
764                 if (strcasecmp(fingerprint->hash, hash) == 0) {
765                         sc->trusted = true;
766                         sc->name = strdup(fingerprint->name);
767                         break;
768                 }
769         }
770
771         if (sc->trusted == false) {
772                 fprintf(stderr, "No trusted fingerprint found matching "
773                     "package's certificate\n");
774                 goto cleanup;
775         }
776
777         /* Verify the signature. */
778         printf("Verifying signature with trusted certificate %s... ", sc->name);
779         if (rsa_verify_cert(fd_pkg, NULL, sc->cert, sc->certlen, sc->sig,
780             sc->siglen) == false) {
781                 printf("failed\n");
782                 fprintf(stderr, "Signature is not valid\n");
783                 goto cleanup;
784         }
785         printf("done\n");
786
787         ret = true;
788
789 cleanup:
790         if (trusted)
791                 free_fingerprint_list(trusted);
792         if (revoked)
793                 free_fingerprint_list(revoked);
794         if (sc) {
795                 free(sc->cert);
796                 free(sc->sig);
797                 free(sc->name);
798                 free(sc);
799         }
800
801         return (ret);
802 }
803
804 static int
805 bootstrap_pkg(bool force)
806 {
807         int fd_pkg, fd_sig;
808         int ret;
809         char url[MAXPATHLEN];
810         char tmppkg[MAXPATHLEN];
811         char tmpsig[MAXPATHLEN];
812         const char *packagesite;
813         const char *signature_type;
814         char pkgstatic[MAXPATHLEN];
815
816         fd_sig = -1;
817         ret = -1;
818
819         if (config_string(PACKAGESITE, &packagesite) != 0) {
820                 warnx("No PACKAGESITE defined");
821                 return (-1);
822         }
823
824         if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
825                 warnx("Error looking up SIGNATURE_TYPE");
826                 return (-1);
827         }
828
829         printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
830
831         /* Support pkg+http:// for PACKAGESITE which is the new format
832            in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
833            no A record. */
834         if (strncmp(URL_SCHEME_PREFIX, packagesite,
835             strlen(URL_SCHEME_PREFIX)) == 0)
836                 packagesite += strlen(URL_SCHEME_PREFIX);
837         snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
838
839         snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
840             getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
841
842         if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
843                 goto fetchfail;
844
845         if (signature_type != NULL &&
846             strcasecmp(signature_type, "NONE") != 0) {
847                 if (strcasecmp(signature_type, "FINGERPRINTS") == 0) {
848
849                         snprintf(tmpsig, MAXPATHLEN, "%s/pkg.txz.sig.XXXXXX",
850                             getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
851                         snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.sig",
852                             packagesite);
853
854                         if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
855                                 fprintf(stderr, "Signature for pkg not "
856                                     "available.\n");
857                                 goto fetchfail;
858                         }
859
860                         if (verify_signature(fd_pkg, fd_sig) == false)
861                                 goto cleanup;
862                 } else if (strcasecmp(signature_type, "PUBKEY") == 0) {
863
864                         snprintf(tmpsig, MAXPATHLEN,
865                             "%s/pkg.txz.pubkeysig.XXXXXX",
866                             getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
867                         snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.pubkeysig",
868                             packagesite);
869
870                         if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
871                                 fprintf(stderr, "Signature for pkg not "
872                                     "available.\n");
873                                 goto fetchfail;
874                         }
875
876                         if (verify_pubsignature(fd_pkg, fd_sig) == false)
877                                 goto cleanup;
878                 } else {
879                         warnx("Signature type %s is not supported for "
880                             "bootstrapping.", signature_type);
881                         goto cleanup;
882                 }
883         }
884
885         if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
886                 ret = install_pkg_static(pkgstatic, tmppkg, force);
887
888         goto cleanup;
889
890 fetchfail:
891         warnx("Error fetching %s: %s", url, fetchLastErrString);
892         fprintf(stderr, "A pre-built version of pkg could not be found for "
893             "your system.\n");
894         fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
895             "ports: 'ports-mgmt/pkg'.\n");
896
897 cleanup:
898         if (fd_sig != -1) {
899                 close(fd_sig);
900                 unlink(tmpsig);
901         }
902         close(fd_pkg);
903         unlink(tmppkg);
904
905         return (ret);
906 }
907
908 static const char confirmation_message[] =
909 "The package management tool is not yet installed on your system.\n"
910 "Do you want to fetch and install it now? [y/N]: ";
911
912 static const char non_interactive_message[] =
913 "The package management tool is not yet installed on your system.\n"
914 "Please set ASSUME_ALWAYS_YES=yes environment variable to be able to bootstrap "
915 "in non-interactive (stdin not being a tty)\n";
916
917 static int
918 pkg_query_yes_no(void)
919 {
920         int ret, c;
921
922         c = getchar();
923
924         if (c == 'y' || c == 'Y')
925                 ret = 1;
926         else
927                 ret = 0;
928
929         while (c != '\n' && c != EOF)
930                 c = getchar();
931
932         return (ret);
933 }
934
935 static int
936 bootstrap_pkg_local(const char *pkgpath, bool force)
937 {
938         char path[MAXPATHLEN];
939         char pkgstatic[MAXPATHLEN];
940         const char *signature_type;
941         int fd_pkg, fd_sig, ret;
942
943         fd_sig = -1;
944         ret = -1;
945
946         fd_pkg = open(pkgpath, O_RDONLY);
947         if (fd_pkg == -1)
948                 err(EXIT_FAILURE, "Unable to open %s", pkgpath);
949
950         if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
951                 warnx("Error looking up SIGNATURE_TYPE");
952                 return (-1);
953         }
954         if (signature_type != NULL &&
955             strcasecmp(signature_type, "NONE") != 0) {
956                 if (strcasecmp(signature_type, "FINGERPRINTS") == 0) {
957
958                         snprintf(path, sizeof(path), "%s.sig", pkgpath);
959
960                         if ((fd_sig = open(path, O_RDONLY)) == -1) {
961                                 fprintf(stderr, "Signature for pkg not "
962                                     "available.\n");
963                                 goto cleanup;
964                         }
965
966                         if (verify_signature(fd_pkg, fd_sig) == false)
967                                 goto cleanup;
968
969                 } else if (strcasecmp(signature_type, "PUBKEY") == 0) {
970
971                         snprintf(path, sizeof(path), "%s.pubkeysig", pkgpath);
972
973                         if ((fd_sig = open(path, O_RDONLY)) == -1) {
974                                 fprintf(stderr, "Signature for pkg not "
975                                     "available.\n");
976                                 goto cleanup;
977                         }
978
979                         if (verify_pubsignature(fd_pkg, fd_sig) == false)
980                                 goto cleanup;
981
982                 } else {
983                         warnx("Signature type %s is not supported for "
984                             "bootstrapping.", signature_type);
985                         goto cleanup;
986                 }
987         }
988
989         if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
990                 ret = install_pkg_static(pkgstatic, pkgpath, force);
991
992 cleanup:
993         close(fd_pkg);
994         if (fd_sig != -1)
995                 close(fd_sig);
996
997         return (ret);
998 }
999
1000 int
1001 main(int argc, char *argv[])
1002 {
1003         char pkgpath[MAXPATHLEN];
1004         const char *pkgarg;
1005         bool bootstrap_only, force, yes;
1006
1007         bootstrap_only = false;
1008         force = false;
1009         pkgarg = NULL;
1010         yes = false;
1011
1012         snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
1013             getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
1014
1015         if (argc > 1 && strcmp(argv[1], "bootstrap") == 0) {
1016                 bootstrap_only = true;
1017                 if (argc == 3 && strcmp(argv[2], "-f") == 0)
1018                         force = true;
1019         }
1020
1021         if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
1022                 /* 
1023                  * To allow 'pkg -N' to be used as a reliable test for whether
1024                  * a system is configured to use pkg, don't bootstrap pkg
1025                  * when that argument is given as argv[1].
1026                  */
1027                 if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
1028                         errx(EXIT_FAILURE, "pkg is not installed");
1029
1030                 config_init();
1031
1032                 if (argc > 1 && strcmp(argv[1], "add") == 0) {
1033                         if (argc > 2 && strcmp(argv[2], "-f") == 0) {
1034                                 force = true;
1035                                 pkgarg = argv[3];
1036                         } else
1037                                 pkgarg = argv[2];
1038                         if (pkgarg == NULL) {
1039                                 fprintf(stderr, "Path to pkg.txz required\n");
1040                                 exit(EXIT_FAILURE);
1041                         }
1042                         if (access(pkgarg, R_OK) == -1) {
1043                                 fprintf(stderr, "No such file: %s\n", pkgarg);
1044                                 exit(EXIT_FAILURE);
1045                         }
1046                         if (bootstrap_pkg_local(pkgarg, force) != 0)
1047                                 exit(EXIT_FAILURE);
1048                         exit(EXIT_SUCCESS);
1049                 }
1050                 /*
1051                  * Do not ask for confirmation if either of stdin or stdout is
1052                  * not tty. Check the environment to see if user has answer
1053                  * tucked in there already.
1054                  */
1055                 config_bool(ASSUME_ALWAYS_YES, &yes);
1056                 if (!yes) {
1057                         if (!isatty(fileno(stdin))) {
1058                                 fprintf(stderr, non_interactive_message);
1059                                 exit(EXIT_FAILURE);
1060                         }
1061
1062                         printf("%s", confirmation_message);
1063                         if (pkg_query_yes_no() == 0)
1064                                 exit(EXIT_FAILURE);
1065                 }
1066                 if (bootstrap_pkg(force) != 0)
1067                         exit(EXIT_FAILURE);
1068                 config_finish();
1069
1070                 if (bootstrap_only)
1071                         exit(EXIT_SUCCESS);
1072         } else if (bootstrap_only) {
1073                 printf("pkg already bootstrapped at %s\n", pkgpath);
1074                 exit(EXIT_SUCCESS);
1075         }
1076
1077         execv(pkgpath, argv);
1078
1079         /* NOT REACHED */
1080         return (EXIT_FAILURE);
1081 }