pkg.c revision 283787
1219820Sjeff/*-
2219820Sjeff * Copyright (c) 2012-2014 Baptiste Daroussin <bapt@FreeBSD.org>
3219820Sjeff * Copyright (c) 2013 Bryan Drewery <bdrewery@FreeBSD.org>
4219820Sjeff * All rights reserved.
5271127Shselasky *
6219820Sjeff * Redistribution and use in source and binary forms, with or without
7219820Sjeff * modification, are permitted provided that the following conditions
8219820Sjeff * are met:
9219820Sjeff * 1. Redistributions of source code must retain the above copyright
10219820Sjeff *    notice, this list of conditions and the following disclaimer.
11219820Sjeff * 2. Redistributions in binary form must reproduce the above copyright
12219820Sjeff *    notice, this list of conditions and the following disclaimer in the
13219820Sjeff *    documentation and/or other materials provided with the distribution.
14219820Sjeff *
15219820Sjeff * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16219820Sjeff * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17219820Sjeff * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18219820Sjeff * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19219820Sjeff * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20219820Sjeff * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21219820Sjeff * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22219820Sjeff * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23219820Sjeff * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24219820Sjeff * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25219820Sjeff * SUCH DAMAGE.
26219820Sjeff */
27219820Sjeff
28219820Sjeff#include <sys/cdefs.h>
29219820Sjeff__FBSDID("$FreeBSD: stable/10/usr.sbin/pkg/pkg.c 283787 2015-05-30 21:23:41Z bapt $");
30219820Sjeff
31219820Sjeff#include <sys/param.h>
32219820Sjeff#include <sys/queue.h>
33219820Sjeff#include <sys/types.h>
34219820Sjeff#include <sys/sbuf.h>
35219820Sjeff#include <sys/wait.h>
36219820Sjeff
37219820Sjeff#define _WITH_GETLINE
38219820Sjeff#include <archive.h>
39219820Sjeff#include <archive_entry.h>
40219820Sjeff#include <dirent.h>
41219820Sjeff#include <err.h>
42222813Sattilio#include <errno.h>
43276744Srodrigc#include <fcntl.h>
44219820Sjeff#include <fetch.h>
45219820Sjeff#include <paths.h>
46219820Sjeff#include <stdbool.h>
47219820Sjeff#include <stdlib.h>
48219820Sjeff#include <stdio.h>
49219820Sjeff#include <string.h>
50219820Sjeff#include <time.h>
51219820Sjeff#include <unistd.h>
52219820Sjeff#include <ucl.h>
53219820Sjeff
54219820Sjeff#include <openssl/err.h>
55219820Sjeff#include <openssl/ssl.h>
56276744Srodrigc
57219820Sjeff#include "dns_utils.h"
58219820Sjeff#include "config.h"
59219820Sjeff
60277139Shselaskystruct sig_cert {
61219820Sjeff	char *name;
62219820Sjeff	unsigned char *sig;
63219820Sjeff	int siglen;
64219820Sjeff	unsigned char *cert;
65219820Sjeff	int certlen;
66219820Sjeff	bool trusted;
67219820Sjeff};
68219820Sjeff
69219820Sjefftypedef enum {
70219820Sjeff       HASH_UNKNOWN,
71219820Sjeff       HASH_SHA256,
72219820Sjeff} hash_t;
73219820Sjeff
74219820Sjeffstruct fingerprint {
75219820Sjeff       hash_t type;
76219820Sjeff       char *name;
77219820Sjeff       char hash[BUFSIZ];
78219820Sjeff       STAILQ_ENTRY(fingerprint) next;
79219820Sjeff};
80219820Sjeff
81219820SjeffSTAILQ_HEAD(fingerprint_list, fingerprint);
82219820Sjeff
83219820Sjeffstatic int
84219820Sjeffextract_pkg_static(int fd, char *p, int sz)
85219820Sjeff{
86219820Sjeff	struct archive *a;
87219820Sjeff	struct archive_entry *ae;
88219820Sjeff	char *end;
89219820Sjeff	int ret, r;
90219820Sjeff
91219820Sjeff	ret = -1;
92219820Sjeff	a = archive_read_new();
93219820Sjeff	if (a == NULL) {
94219820Sjeff		warn("archive_read_new");
95219820Sjeff		return (ret);
96219820Sjeff	}
97219820Sjeff	archive_read_support_filter_all(a);
98219820Sjeff	archive_read_support_format_tar(a);
99219820Sjeff
100219820Sjeff	if (lseek(fd, 0, 0) == -1) {
101219820Sjeff		warn("lseek");
102219820Sjeff		goto cleanup;
103219820Sjeff	}
104219820Sjeff
105219820Sjeff	if (archive_read_open_fd(a, fd, 4096) != ARCHIVE_OK) {
106219820Sjeff		warnx("archive_read_open_fd: %s", archive_error_string(a));
107219820Sjeff		goto cleanup;
108219820Sjeff	}
109219820Sjeff
110219820Sjeff	ae = NULL;
111219820Sjeff	while ((r = archive_read_next_header(a, &ae)) == ARCHIVE_OK) {
112219820Sjeff		end = strrchr(archive_entry_pathname(ae), '/');
113219820Sjeff		if (end == NULL)
114219820Sjeff			continue;
115219820Sjeff
116219820Sjeff		if (strcmp(end, "/pkg-static") == 0) {
117219820Sjeff			r = archive_read_extract(a, ae,
118255932Salfred			    ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM |
119255932Salfred			    ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_ACL |
120255932Salfred			    ARCHIVE_EXTRACT_FFLAGS | ARCHIVE_EXTRACT_XATTR);
121219820Sjeff			strlcpy(p, archive_entry_pathname(ae), sz);
122219820Sjeff			break;
123219820Sjeff		}
124219820Sjeff	}
125219820Sjeff
126219820Sjeff	if (r == ARCHIVE_OK)
127219820Sjeff		ret = 0;
128219820Sjeff	else
129219820Sjeff		warnx("failed to extract pkg-static: %s",
130219820Sjeff		    archive_error_string(a));
131219820Sjeff
132219820Sjeffcleanup:
133219820Sjeff	archive_read_free(a);
134219820Sjeff	return (ret);
135219820Sjeff
136219820Sjeff}
137219820Sjeff
138219820Sjeffstatic int
139219820Sjeffinstall_pkg_static(const char *path, const char *pkgpath, bool force)
140219820Sjeff{
141219820Sjeff	int pstat;
142219820Sjeff	pid_t pid;
143219820Sjeff
144219820Sjeff	switch ((pid = fork())) {
145219820Sjeff	case -1:
146219820Sjeff		return (-1);
147219820Sjeff	case 0:
148219820Sjeff		if (force)
149219820Sjeff			execl(path, "pkg-static", "add", "-f", pkgpath,
150219820Sjeff			    (char *)NULL);
151219820Sjeff		else
152219820Sjeff			execl(path, "pkg-static", "add", pkgpath,
153219820Sjeff			    (char *)NULL);
154219820Sjeff		_exit(1);
155219820Sjeff	default:
156219820Sjeff		break;
157219820Sjeff	}
158219820Sjeff
159219820Sjeff	while (waitpid(pid, &pstat, 0) == -1)
160219820Sjeff		if (errno != EINTR)
161219820Sjeff			return (-1);
162219820Sjeff
163219820Sjeff	if (WEXITSTATUS(pstat))
164219820Sjeff		return (WEXITSTATUS(pstat));
165219820Sjeff	else if (WIFSIGNALED(pstat))
166219820Sjeff		return (128 & (WTERMSIG(pstat)));
167219820Sjeff	return (pstat);
168219820Sjeff}
169219820Sjeff
170219820Sjeffstatic int
171219820Sjefffetch_to_fd(const char *url, char *path)
172219820Sjeff{
173219820Sjeff	struct url *u;
174219820Sjeff	struct dns_srvinfo *mirrors, *current;
175219820Sjeff	struct url_stat st;
176219820Sjeff	FILE *remote;
177219820Sjeff	/* To store _https._tcp. + hostname + \0 */
178219820Sjeff	int fd;
179219820Sjeff	int retry, max_retry;
180219820Sjeff	off_t done, r;
181219820Sjeff	time_t now, last;
182219820Sjeff	char buf[10240];
183219820Sjeff	char zone[MAXHOSTNAMELEN + 13];
184219820Sjeff	static const char *mirror_type = NULL;
185219820Sjeff
186219820Sjeff	done = 0;
187219820Sjeff	last = 0;
188219820Sjeff	max_retry = 3;
189219820Sjeff	current = mirrors = NULL;
190219820Sjeff	remote = NULL;
191219820Sjeff
192219820Sjeff	if (mirror_type == NULL && config_string(MIRROR_TYPE, &mirror_type)
193219820Sjeff	    != 0) {
194219820Sjeff		warnx("No MIRROR_TYPE defined");
195219820Sjeff		return (-1);
196219820Sjeff	}
197219820Sjeff
198219820Sjeff	if ((fd = mkstemp(path)) == -1) {
199219820Sjeff		warn("mkstemp()");
200219820Sjeff		return (-1);
201219820Sjeff	}
202219820Sjeff
203219820Sjeff	retry = max_retry;
204219820Sjeff
205219820Sjeff	if ((u = fetchParseURL(url)) == NULL) {
206219820Sjeff		warn("fetchParseURL('%s')", url);
207219820Sjeff		return (-1);
208219820Sjeff	}
209219820Sjeff
210219820Sjeff	while (remote == NULL) {
211219820Sjeff		if (retry == max_retry) {
212219820Sjeff			if (strcmp(u->scheme, "file") != 0 &&
213219820Sjeff			    strcasecmp(mirror_type, "srv") == 0) {
214219820Sjeff				snprintf(zone, sizeof(zone),
215219820Sjeff				    "_%s._tcp.%s", u->scheme, u->host);
216219820Sjeff				mirrors = dns_getsrvinfo(zone);
217219820Sjeff				current = mirrors;
218219820Sjeff			}
219219820Sjeff		}
220219820Sjeff
221219820Sjeff		if (mirrors != NULL) {
222219820Sjeff			strlcpy(u->host, current->host, sizeof(u->host));
223219820Sjeff			u->port = current->port;
224219820Sjeff		}
225219820Sjeff
226219820Sjeff		remote = fetchXGet(u, &st, "");
227219820Sjeff		if (remote == NULL) {
228219820Sjeff			--retry;
229219820Sjeff			if (retry <= 0)
230219820Sjeff				goto fetchfail;
231219820Sjeff			if (mirrors == NULL) {
232219820Sjeff				sleep(1);
233219820Sjeff			} else {
234219820Sjeff				current = current->next;
235219820Sjeff				if (current == NULL)
236219820Sjeff					current = mirrors;
237219820Sjeff			}
238219820Sjeff		}
239219820Sjeff	}
240219820Sjeff
241219820Sjeff	while (done < st.size) {
242219820Sjeff		if ((r = fread(buf, 1, sizeof(buf), remote)) < 1)
243219820Sjeff			break;
244219820Sjeff
245219820Sjeff		if (write(fd, buf, r) != r) {
246219820Sjeff			warn("write()");
247219820Sjeff			goto fetchfail;
248219820Sjeff		}
249219820Sjeff
250219820Sjeff		done += r;
251219820Sjeff		now = time(NULL);
252219820Sjeff		if (now > last || done == st.size)
253219820Sjeff			last = now;
254219820Sjeff	}
255219820Sjeff
256219820Sjeff	if (ferror(remote))
257219820Sjeff		goto fetchfail;
258219820Sjeff
259219820Sjeff	goto cleanup;
260219820Sjeff
261219820Sjefffetchfail:
262219820Sjeff	if (fd != -1) {
263219820Sjeff		close(fd);
264219820Sjeff		fd = -1;
265219820Sjeff		unlink(path);
266219820Sjeff	}
267219820Sjeff
268219820Sjeffcleanup:
269219820Sjeff	if (remote != NULL)
270219820Sjeff		fclose(remote);
271219820Sjeff
272219820Sjeff	return fd;
273219820Sjeff}
274219820Sjeff
275219820Sjeffstatic struct fingerprint *
276219820Sjeffparse_fingerprint(ucl_object_t *obj)
277219820Sjeff{
278219820Sjeff	const ucl_object_t *cur;
279219820Sjeff	ucl_object_iter_t it = NULL;
280219820Sjeff	const char *function, *fp, *key;
281219820Sjeff	struct fingerprint *f;
282219820Sjeff	hash_t fct = HASH_UNKNOWN;
283219820Sjeff
284219820Sjeff	function = fp = NULL;
285219820Sjeff
286219820Sjeff	while ((cur = ucl_iterate_object(obj, &it, true))) {
287219820Sjeff		key = ucl_object_key(cur);
288219820Sjeff		if (cur->type != UCL_STRING)
289219820Sjeff			continue;
290219820Sjeff		if (strcasecmp(key, "function") == 0) {
291219820Sjeff			function = ucl_object_tostring(cur);
292219820Sjeff			continue;
293219820Sjeff		}
294219820Sjeff		if (strcasecmp(key, "fingerprint") == 0) {
295219820Sjeff			fp = ucl_object_tostring(cur);
296219820Sjeff			continue;
297219820Sjeff		}
298219820Sjeff	}
299219820Sjeff
300219820Sjeff	if (fp == NULL || function == NULL)
301219820Sjeff		return (NULL);
302219820Sjeff
303219820Sjeff	if (strcasecmp(function, "sha256") == 0)
304219820Sjeff		fct = HASH_SHA256;
305219820Sjeff
306219820Sjeff	if (fct == HASH_UNKNOWN) {
307219820Sjeff		warnx("Unsupported hashing function: %s", function);
308219820Sjeff		return (NULL);
309219820Sjeff	}
310219820Sjeff
311219820Sjeff	f = calloc(1, sizeof(struct fingerprint));
312219820Sjeff	f->type = fct;
313219820Sjeff	strlcpy(f->hash, fp, sizeof(f->hash));
314271127Shselasky
315271127Shselasky	return (f);
316271127Shselasky}
317271127Shselasky
318271127Shselaskystatic void
319271127Shselaskyfree_fingerprint_list(struct fingerprint_list* list)
320271127Shselasky{
321271127Shselasky	struct fingerprint *fingerprint, *tmp;
322271127Shselasky
323271127Shselasky	STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
324271127Shselasky		if (fingerprint->name)
325271127Shselasky			free(fingerprint->name);
326271127Shselasky		free(fingerprint);
327271127Shselasky	}
328271127Shselasky	free(list);
329271127Shselasky}
330271127Shselasky
331271127Shselaskystatic struct fingerprint *
332271127Shselaskyload_fingerprint(const char *dir, const char *filename)
333271127Shselasky{
334271127Shselasky	ucl_object_t *obj = NULL;
335271127Shselasky	struct ucl_parser *p = NULL;
336271127Shselasky	struct fingerprint *f;
337271127Shselasky	char path[MAXPATHLEN];
338271127Shselasky
339271127Shselasky	f = NULL;
340271127Shselasky
341271127Shselasky	snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
342271127Shselasky
343271127Shselasky	p = ucl_parser_new(0);
344271127Shselasky	if (!ucl_parser_add_file(p, path)) {
345271127Shselasky		warnx("%s: %s", path, ucl_parser_get_error(p));
346271127Shselasky		ucl_parser_free(p);
347271127Shselasky		return (NULL);
348271127Shselasky	}
349271127Shselasky
350271127Shselasky	obj = ucl_parser_get_object(p);
351271127Shselasky
352271127Shselasky	if (obj->type == UCL_OBJECT)
353271127Shselasky		f = parse_fingerprint(obj);
354271127Shselasky
355271127Shselasky	if (f != NULL)
356271127Shselasky		f->name = strdup(filename);
357271127Shselasky
358271127Shselasky	ucl_object_unref(obj);
359271127Shselasky	ucl_parser_free(p);
360271127Shselasky
361271127Shselasky	return (f);
362271127Shselasky}
363271127Shselasky
364271127Shselaskystatic struct fingerprint_list *
365271127Shselaskyload_fingerprints(const char *path, int *count)
366271127Shselasky{
367271127Shselasky	DIR *d;
368271127Shselasky	struct dirent *ent;
369271127Shselasky	struct fingerprint *finger;
370271127Shselasky	struct fingerprint_list *fingerprints;
371271127Shselasky
372271127Shselasky	*count = 0;
373271127Shselasky
374219820Sjeff	fingerprints = calloc(1, sizeof(struct fingerprint_list));
375219820Sjeff	if (fingerprints == NULL)
376219820Sjeff		return (NULL);
377219820Sjeff	STAILQ_INIT(fingerprints);
378219820Sjeff
379219820Sjeff	if ((d = opendir(path)) == NULL) {
380219820Sjeff		free(fingerprints);
381219820Sjeff
382219820Sjeff		return (NULL);
383219820Sjeff	}
384219820Sjeff
385219820Sjeff	while ((ent = readdir(d))) {
386219820Sjeff		if (strcmp(ent->d_name, ".") == 0 ||
387219820Sjeff		    strcmp(ent->d_name, "..") == 0)
388219820Sjeff			continue;
389219820Sjeff		finger = load_fingerprint(path, ent->d_name);
390219820Sjeff		if (finger != NULL) {
391219820Sjeff			STAILQ_INSERT_TAIL(fingerprints, finger, next);
392219820Sjeff			++(*count);
393219820Sjeff		}
394271127Shselasky	}
395271127Shselasky
396271127Shselasky	closedir(d);
397271127Shselasky
398271127Shselasky	return (fingerprints);
399219820Sjeff}
400219820Sjeff
401static void
402sha256_hash(unsigned char hash[SHA256_DIGEST_LENGTH],
403    char out[SHA256_DIGEST_LENGTH * 2 + 1])
404{
405	int i;
406
407	for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
408		sprintf(out + (i * 2), "%02x", hash[i]);
409
410	out[SHA256_DIGEST_LENGTH * 2] = '\0';
411}
412
413static void
414sha256_buf(char *buf, size_t len, char out[SHA256_DIGEST_LENGTH * 2 + 1])
415{
416	unsigned char hash[SHA256_DIGEST_LENGTH];
417	SHA256_CTX sha256;
418
419	out[0] = '\0';
420
421	SHA256_Init(&sha256);
422	SHA256_Update(&sha256, buf, len);
423	SHA256_Final(hash, &sha256);
424	sha256_hash(hash, out);
425}
426
427static int
428sha256_fd(int fd, char out[SHA256_DIGEST_LENGTH * 2 + 1])
429{
430	int my_fd;
431	FILE *fp;
432	char buffer[BUFSIZ];
433	unsigned char hash[SHA256_DIGEST_LENGTH];
434	size_t r;
435	int ret;
436	SHA256_CTX sha256;
437
438	my_fd = -1;
439	fp = NULL;
440	r = 0;
441	ret = 1;
442
443	out[0] = '\0';
444
445	/* Duplicate the fd so that fclose(3) does not close it. */
446	if ((my_fd = dup(fd)) == -1) {
447		warnx("dup");
448		goto cleanup;
449	}
450
451	if ((fp = fdopen(my_fd, "rb")) == NULL) {
452		warnx("fdopen");
453		goto cleanup;
454	}
455
456	SHA256_Init(&sha256);
457
458	while ((r = fread(buffer, 1, BUFSIZ, fp)) > 0)
459		SHA256_Update(&sha256, buffer, r);
460
461	if (ferror(fp) != 0) {
462		warnx("fread");
463		goto cleanup;
464	}
465
466	SHA256_Final(hash, &sha256);
467	sha256_hash(hash, out);
468	ret = 0;
469
470cleanup:
471	if (fp != NULL)
472		fclose(fp);
473	else if (my_fd != -1)
474		close(my_fd);
475	(void)lseek(fd, 0, SEEK_SET);
476
477	return (ret);
478}
479
480static EVP_PKEY *
481load_public_key_buf(const unsigned char *cert, int certlen)
482{
483	EVP_PKEY *pkey;
484	BIO *bp;
485	char errbuf[1024];
486
487	bp = BIO_new_mem_buf(__DECONST(void *, cert), certlen);
488
489	if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
490		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
491
492	BIO_free(bp);
493
494	return (pkey);
495}
496
497static bool
498rsa_verify_cert(int fd, const unsigned char *key, int keylen,
499    unsigned char *sig, int siglen)
500{
501	EVP_MD_CTX *mdctx;
502	EVP_PKEY *pkey;
503	char sha256[(SHA256_DIGEST_LENGTH * 2) + 2];
504	char errbuf[1024];
505	bool ret;
506
507	pkey = NULL;
508	mdctx = NULL;
509	ret = false;
510
511	/* Compute SHA256 of the package. */
512	if (lseek(fd, 0, 0) == -1) {
513		warn("lseek");
514		goto cleanup;
515	}
516	if ((sha256_fd(fd, sha256)) == -1) {
517		warnx("Error creating SHA256 hash for package");
518		goto cleanup;
519	}
520
521	if ((pkey = load_public_key_buf(key, keylen)) == NULL) {
522		warnx("Error reading public key");
523		goto cleanup;
524	}
525
526	/* Verify signature of the SHA256(pkg) is valid. */
527	if ((mdctx = EVP_MD_CTX_create()) == NULL) {
528		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
529		goto error;
530	}
531
532	if (EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
533		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
534		goto error;
535	}
536	if (EVP_DigestVerifyUpdate(mdctx, sha256, strlen(sha256)) != 1) {
537		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
538		goto error;
539	}
540
541	if (EVP_DigestVerifyFinal(mdctx, sig, siglen) != 1) {
542		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
543		goto error;
544	}
545
546	ret = true;
547	printf("done\n");
548	goto cleanup;
549
550error:
551	printf("failed\n");
552
553cleanup:
554	if (pkey)
555		EVP_PKEY_free(pkey);
556	if (mdctx)
557		EVP_MD_CTX_destroy(mdctx);
558	ERR_free_strings();
559
560	return (ret);
561}
562
563static struct sig_cert *
564parse_cert(int fd) {
565	int my_fd;
566	struct sig_cert *sc;
567	FILE *fp;
568	struct sbuf *buf, *sig, *cert;
569	char *line;
570	size_t linecap;
571	ssize_t linelen;
572
573	buf = NULL;
574	my_fd = -1;
575	sc = NULL;
576	line = NULL;
577	linecap = 0;
578
579	if (lseek(fd, 0, 0) == -1) {
580		warn("lseek");
581		return (NULL);
582	}
583
584	/* Duplicate the fd so that fclose(3) does not close it. */
585	if ((my_fd = dup(fd)) == -1) {
586		warnx("dup");
587		return (NULL);
588	}
589
590	if ((fp = fdopen(my_fd, "rb")) == NULL) {
591		warn("fdopen");
592		close(my_fd);
593		return (NULL);
594	}
595
596	sig = sbuf_new_auto();
597	cert = sbuf_new_auto();
598
599	while ((linelen = getline(&line, &linecap, fp)) > 0) {
600		if (strcmp(line, "SIGNATURE\n") == 0) {
601			buf = sig;
602			continue;
603		} else if (strcmp(line, "CERT\n") == 0) {
604			buf = cert;
605			continue;
606		} else if (strcmp(line, "END\n") == 0) {
607			break;
608		}
609		if (buf != NULL)
610			sbuf_bcat(buf, line, linelen);
611	}
612
613	fclose(fp);
614
615	/* Trim out unrelated trailing newline */
616	sbuf_setpos(sig, sbuf_len(sig) - 1);
617
618	sbuf_finish(sig);
619	sbuf_finish(cert);
620
621	sc = calloc(1, sizeof(struct sig_cert));
622	sc->siglen = sbuf_len(sig);
623	sc->sig = calloc(1, sc->siglen);
624	memcpy(sc->sig, sbuf_data(sig), sc->siglen);
625
626	sc->certlen = sbuf_len(cert);
627	sc->cert = strdup(sbuf_data(cert));
628
629	sbuf_delete(sig);
630	sbuf_delete(cert);
631
632	return (sc);
633}
634
635static bool
636verify_signature(int fd_pkg, int fd_sig)
637{
638	struct fingerprint_list *trusted, *revoked;
639	struct fingerprint *fingerprint;
640	struct sig_cert *sc;
641	bool ret;
642	int trusted_count, revoked_count;
643	const char *fingerprints;
644	char path[MAXPATHLEN];
645	char hash[SHA256_DIGEST_LENGTH * 2 + 1];
646
647	sc = NULL;
648	trusted = revoked = NULL;
649	ret = false;
650
651	/* Read and parse fingerprints. */
652	if (config_string(FINGERPRINTS, &fingerprints) != 0) {
653		warnx("No CONFIG_FINGERPRINTS defined");
654		goto cleanup;
655	}
656
657	snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
658	if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
659		warnx("Error loading trusted certificates");
660		goto cleanup;
661	}
662
663	if (trusted_count == 0 || trusted == NULL) {
664		fprintf(stderr, "No trusted certificates found.\n");
665		goto cleanup;
666	}
667
668	snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
669	if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
670		warnx("Error loading revoked certificates");
671		goto cleanup;
672	}
673
674	/* Read certificate and signature in. */
675	if ((sc = parse_cert(fd_sig)) == NULL) {
676		warnx("Error parsing certificate");
677		goto cleanup;
678	}
679	/* Explicitly mark as non-trusted until proven otherwise. */
680	sc->trusted = false;
681
682	/* Parse signature and pubkey out of the certificate */
683	sha256_buf(sc->cert, sc->certlen, hash);
684
685	/* Check if this hash is revoked */
686	if (revoked != NULL) {
687		STAILQ_FOREACH(fingerprint, revoked, next) {
688			if (strcasecmp(fingerprint->hash, hash) == 0) {
689				fprintf(stderr, "The package was signed with "
690				    "revoked certificate %s\n",
691				    fingerprint->name);
692				goto cleanup;
693			}
694		}
695	}
696
697	STAILQ_FOREACH(fingerprint, trusted, next) {
698		if (strcasecmp(fingerprint->hash, hash) == 0) {
699			sc->trusted = true;
700			sc->name = strdup(fingerprint->name);
701			break;
702		}
703	}
704
705	if (sc->trusted == false) {
706		fprintf(stderr, "No trusted fingerprint found matching "
707		    "package's certificate\n");
708		goto cleanup;
709	}
710
711	/* Verify the signature. */
712	printf("Verifying signature with trusted certificate %s... ", sc->name);
713	if (rsa_verify_cert(fd_pkg, sc->cert, sc->certlen, sc->sig,
714	    sc->siglen) == false) {
715		fprintf(stderr, "Signature is not valid\n");
716		goto cleanup;
717	}
718
719	ret = true;
720
721cleanup:
722	if (trusted)
723		free_fingerprint_list(trusted);
724	if (revoked)
725		free_fingerprint_list(revoked);
726	if (sc) {
727		if (sc->cert)
728			free(sc->cert);
729		if (sc->sig)
730			free(sc->sig);
731		if (sc->name)
732			free(sc->name);
733		free(sc);
734	}
735
736	return (ret);
737}
738
739static int
740bootstrap_pkg(bool force)
741{
742	int fd_pkg, fd_sig;
743	int ret;
744	char url[MAXPATHLEN];
745	char tmppkg[MAXPATHLEN];
746	char tmpsig[MAXPATHLEN];
747	const char *packagesite;
748	const char *signature_type;
749	char pkgstatic[MAXPATHLEN];
750
751	fd_sig = -1;
752	ret = -1;
753
754	if (config_string(PACKAGESITE, &packagesite) != 0) {
755		warnx("No PACKAGESITE defined");
756		return (-1);
757	}
758
759	if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
760		warnx("Error looking up SIGNATURE_TYPE");
761		return (-1);
762	}
763
764	printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
765
766	/* Support pkg+http:// for PACKAGESITE which is the new format
767	   in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
768	   no A record. */
769	if (strncmp(URL_SCHEME_PREFIX, packagesite,
770	    strlen(URL_SCHEME_PREFIX)) == 0)
771		packagesite += strlen(URL_SCHEME_PREFIX);
772	snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
773
774	snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
775	    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
776
777	if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
778		goto fetchfail;
779
780	if (signature_type != NULL &&
781	    strcasecmp(signature_type, "FINGERPRINTS") == 0) {
782		snprintf(tmpsig, MAXPATHLEN, "%s/pkg.txz.sig.XXXXXX",
783		    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
784		snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.sig",
785		    packagesite);
786
787		if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
788			fprintf(stderr, "Signature for pkg not available.\n");
789			goto fetchfail;
790		}
791
792		if (verify_signature(fd_pkg, fd_sig) == false)
793			goto cleanup;
794	}
795
796	if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
797		ret = install_pkg_static(pkgstatic, tmppkg, force);
798
799	goto cleanup;
800
801fetchfail:
802	warnx("Error fetching %s: %s", url, fetchLastErrString);
803	fprintf(stderr, "A pre-built version of pkg could not be found for "
804	    "your system.\n");
805	fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
806	    "ports: 'ports-mgmt/pkg'.\n");
807
808cleanup:
809	if (fd_sig != -1) {
810		close(fd_sig);
811		unlink(tmpsig);
812	}
813
814	if (fd_pkg != -1) {
815		close(fd_pkg);
816		unlink(tmppkg);
817	}
818
819	return (ret);
820}
821
822static const char confirmation_message[] =
823"The package management tool is not yet installed on your system.\n"
824"Do you want to fetch and install it now? [y/N]: ";
825
826static int
827pkg_query_yes_no(void)
828{
829	int ret, c;
830
831	c = getchar();
832
833	if (c == 'y' || c == 'Y')
834		ret = 1;
835	else
836		ret = 0;
837
838	while (c != '\n' && c != EOF)
839		c = getchar();
840
841	return (ret);
842}
843
844static int
845bootstrap_pkg_local(const char *pkgpath, bool force)
846{
847	char path[MAXPATHLEN];
848	char pkgstatic[MAXPATHLEN];
849	const char *signature_type;
850	int fd_pkg, fd_sig, ret;
851
852	fd_sig = -1;
853	ret = -1;
854
855	fd_pkg = open(pkgpath, O_RDONLY);
856	if (fd_pkg == -1)
857		err(EXIT_FAILURE, "Unable to open %s", pkgpath);
858
859	if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
860		warnx("Error looking up SIGNATURE_TYPE");
861		goto cleanup;
862	}
863	if (signature_type != NULL &&
864	    strcasecmp(signature_type, "FINGERPRINTS") == 0) {
865		snprintf(path, sizeof(path), "%s.sig", pkgpath);
866
867		if ((fd_sig = open(path, O_RDONLY)) == -1) {
868			fprintf(stderr, "Signature for pkg not available.\n");
869			goto cleanup;
870		}
871
872		if (verify_signature(fd_pkg, fd_sig) == false)
873			goto cleanup;
874	}
875
876	if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
877		ret = install_pkg_static(pkgstatic, pkgpath, force);
878
879cleanup:
880	close(fd_pkg);
881	if (fd_sig != -1)
882		close(fd_sig);
883
884	return (ret);
885}
886
887int
888main(__unused int argc, char *argv[])
889{
890	char pkgpath[MAXPATHLEN];
891	const char *pkgarg;
892	bool bootstrap_only, force, yes;
893
894	bootstrap_only = false;
895	force = false;
896	pkgarg = NULL;
897	yes = false;
898
899	snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
900	    getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
901
902	if (argc > 1 && strcmp(argv[1], "bootstrap") == 0) {
903		bootstrap_only = true;
904		if (argc == 3 && strcmp(argv[2], "-f") == 0)
905			force = true;
906	}
907
908	if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
909		/*
910		 * To allow 'pkg -N' to be used as a reliable test for whether
911		 * a system is configured to use pkg, don't bootstrap pkg
912		 * when that argument is given as argv[1].
913		 */
914		if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
915			errx(EXIT_FAILURE, "pkg is not installed");
916
917		config_init();
918
919		if (argc > 1 && strcmp(argv[1], "add") == 0) {
920			if (argc > 2 && strcmp(argv[2], "-f") == 0) {
921				force = true;
922				pkgarg = argv[3];
923			} else
924				pkgarg = argv[2];
925			if (pkgarg == NULL) {
926				fprintf(stderr, "Path to pkg.txz required\n");
927				exit(EXIT_FAILURE);
928			}
929			if (access(pkgarg, R_OK) == -1) {
930				fprintf(stderr, "No such file: %s\n", pkgarg);
931				exit(EXIT_FAILURE);
932			}
933			if (bootstrap_pkg_local(pkgarg, force) != 0)
934				exit(EXIT_FAILURE);
935			exit(EXIT_SUCCESS);
936		}
937		/*
938		 * Do not ask for confirmation if either of stdin or stdout is
939		 * not tty. Check the environment to see if user has answer
940		 * tucked in there already.
941		 */
942		config_bool(ASSUME_ALWAYS_YES, &yes);
943		if (!yes) {
944			printf("%s", confirmation_message);
945			if (!isatty(fileno(stdin)))
946				exit(EXIT_FAILURE);
947
948			if (pkg_query_yes_no() == 0)
949				exit(EXIT_FAILURE);
950		}
951		if (bootstrap_pkg(force) != 0)
952			exit(EXIT_FAILURE);
953		config_finish();
954
955		if (bootstrap_only)
956			exit(EXIT_SUCCESS);
957	} else if (bootstrap_only) {
958		printf("pkg already bootstrapped at %s\n", pkgpath);
959		exit(EXIT_SUCCESS);
960	}
961
962	execv(pkgpath, argv);
963
964	/* NOT REACHED */
965	return (EXIT_FAILURE);
966}
967