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