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