5 * (c) 2018 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of the Trivial IP Encryption (TrIPE) Android app.
12 * TrIPE is free software: you can redistribute it and/or modify it under
13 * the terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 3 of the License, or (at your
15 * option) any later version.
17 * TrIPE is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22 * You should have received a copy of the GNU General Public License
23 * along with TrIPE. If not, see <https://www.gnu.org/licenses/>.
26 package uk.org.distorted.tripe; package object keys {
28 /*----- Imports -----------------------------------------------------------*/
30 import scala.collection.mutable.HashMap;
32 import java.io.{Closeable, File};
33 import java.net.{URL, URLConnection};
34 import java.util.zip.GZIPInputStream;
36 import sys.{SystemError, hashsz, runCommand};
37 import sys.Errno.EEXIST;
38 import sys.FileImplicits._;
40 import progress.{Eyecandy, SimpleModel, DataModel};
42 /*----- Useful regular expressions ----------------------------------------*/
44 private final val RX_COMMENT = """(?x) ^ \s* (?: \# .* )? $""".r;
45 private final val RX_KEYVAL = """(?x) ^ \s*
50 private final val RX_DOLLARSUBST = """(?x) \$ \{ ([-\w]+) \}""".r;
52 /*----- Things that go wrong ----------------------------------------------*/
54 class ConfigSyntaxError(val file: String, val lno: Int, val msg: String)
56 override def getMessage(): String = s"$file:$lno: $msg";
59 class ConfigDefaultFailed(val file: String, val dfltkey: String,
60 val badkey: String, val badval: String)
62 override def getMessage(): String =
63 s"$file: can't default `$dfltkey' because " +
64 s"`$badval' is not a recognized value for `$badkey'";
67 class DefaultFailed(val key: String) extends Exception;
69 /*----- Parsing a configuration -------------------------------------------*/
71 type Config = scala.collection.Map[String, String];
73 private val DEFAULTS: Seq[(String, Config => String)] =
74 Seq("repos-base" -> { _ => "tripe-keys.tar.gz" },
75 "sig-base" -> { _ => "tripe-keys.sig-<SEQ>" },
76 "repos-url" -> { conf => conf("base-url") + conf("repos-base") },
77 "sig-url" -> { conf => conf("base-url") + conf("sig-base") },
78 "kx" -> { _ => "dh" },
79 "kx-genalg" -> { conf => conf("kx") match {
80 case alg@("dh" | "ec" | "x25519" | "x448") => alg
81 case _ => throw new DefaultFailed("kx")
83 "kx-expire" -> { _ => "now + 1 year" },
84 "kx-warn-days" -> { _ => "28" },
85 "bulk" -> { _ => "iiv" },
86 "cipher" -> { conf => conf("bulk") match {
87 case "naclbox" => "salsa20"
88 case _ => "rijndael-cbc"
90 "hash" -> { _ => "sha256" },
91 "mgf" -> { conf => conf("hash") + "-mgf" },
92 "mac" -> { conf => conf("bulk") match {
93 case "naclbox" => "poly1305/128"
97 case -1 => throw new DefaultFailed("hash")
98 case hsz => s"${h}-hmac/${4*hsz}"
101 "sig" -> { conf => conf("kx") match {
104 case "x25519" => "ed25519"
105 case "x448" => "ed448"
106 case _ => throw new DefaultFailed("kx")
108 "sig-fresh" -> { _ => "always" },
109 "fingerprint-hash" -> { _("hash") });
111 private def readConfig(file: File): Config = {
113 /* Build the new configuration in a temporary place. */
114 var m = HashMap[String, String]();
116 /* Read the config file into our map. */
117 file.withReader { in =>
119 for (line <- lines(in)) {
121 case RX_COMMENT() => ok;
122 case RX_KEYVAL(key, value) => m += key -> value;
124 throw new ConfigSyntaxError(file.getPath, lno,
125 "failed to parse line");
131 /* Fill in defaults where things have been missed out. */
132 for ((key, dflt) <- DEFAULTS) {
133 if (!(m contains key)) {
134 try { m += key -> dflt(m); }
136 case e: DefaultFailed =>
137 throw new ConfigDefaultFailed(file.getPath, key,
143 /* And we're done. */
147 /*----- Managing a key repository -----------------------------------------*/
149 def downloadToFile(file: File, url: URL,
150 maxlen: Long = Long.MaxValue,
152 ic.job(new SimpleModel(s"connecting to `$url'", -1)) { jr =>
153 fetchURL(url, new URLFetchCallbacks {
154 val out = file.openForOutput();
155 private def toobig() {
156 throw new KeyConfigException(
157 s"remote file `$url' is suspiciously large");
159 var totlen: Long = 0;
160 override def preflight(conn: URLConnection) {
161 totlen = conn.getContentLength;
162 if (totlen > maxlen) toobig();
163 jr.change(new SimpleModel(s"downloading `$url'", totlen)
167 override def done(win: Boolean) { out.close(); }
168 def write(buf: Array[Byte], n: Int, len: Long) {
169 if (len + n > maxlen) toobig();
170 out.write(buf, 0, n);
181 * insert config file via URL or something
183 * -> pending (pending/tripe-keys.conf)
185 * verify master key fingerprint (against barcode?)
187 * -> confirmed (live/tripe-keys.conf; no live/repos)
197 * -> updating (live/...; new/...)
199 * rename old repository aside
201 * -> committing (old/...; new/...)
203 * rename verified repository
210 class RepositoryStateException(val state: Repository.State.Value,
212 extends Exception(msg);
214 class KeyConfigException(msg: String) extends Exception(msg);
216 private def launderFingerprint(fp: String): String =
217 fp filter { _.isLetterOrDigit };
219 private def fingerprintsEqual(a: String, b: String) =
220 launderFingerprint(a) == launderFingerprint(b);
222 private def keyFingerprint(kr: File, tag: String, hash: String): String = {
223 val (out, _) = runCommand("key", "-k", kr.getPath, "fingerprint",
224 "-a", hash, "-f", "-secret", tag);
225 nextToken(out) match {
226 case Some((fp, _)) => fp
228 throw new java.io.IOException("unexpected output from `key fingerprint");
233 object State extends Enumeration {
234 val Empty, Pending, Confirmed, Updating, Committing, Live = Value;
238 def checkConfigSanity(file: File, ic: Eyecandy) {
239 ic.operation("checking new configuration") { _ =>
241 /* Make sure we can read and understand the file. */
242 val conf = readConfig(file);
244 /* Make sure there are entries which we can use to update. This won't
245 * guarantee that we can reliably update, but it will help.
247 conf("repos-url"); conf("sig-url");
248 conf("fingerprint-hash"); conf("sig-fresh");
249 conf("master-sequence"); conf("hk-master");
253 class Repository(val root: File) extends Closeable {
254 import Repository.State.{Value => State, _};
256 /* Important directories and files. */
257 private[this] val livedir = root/"live";
258 private[this] val livereposdir = livedir/"repos";
259 private[this] val newdir = root/"new";
260 private[this] val olddir = root/"old";
261 private[this] val pendingdir = root/"pending";
262 private[this] val tmpdir = root/"tmp";
264 /* Take out a lock in case of other instances. */
265 private[this] val lock = {
266 try { root.mkdir_!(); }
267 catch { case SystemError(EEXIST, _) => ok; }
270 def close() { lock.close(); }
272 /* Maintain a cache of some repository state. */
273 private var _state: State = null;
274 private var _config: Config = null;
275 private def invalidate() {
281 /* Determine the current repository state. */
284 _state = if (livedir.isdir_!) {
285 if (!livereposdir.isdir_!) Confirmed
286 else if (newdir.isdir_!) Updating
289 if (newdir.isdir_!) Committing
290 else if (pendingdir.isdir_!) Pending
297 def checkState(wanted: State*) {
298 /* Ensure we're in a particular state. */
300 if (wanted.forall(_ != st)) {
301 throw new RepositoryStateException(st, s"Repository is $st, not " +
303 wanted.map(_.toString)));
309 /* If we're part-way through an update then back out or press forward. */
313 /* We have a new tree allegedly ready, but the current one is still
314 * in place. It seems safer to zap the new one here, but we could go
319 invalidate(); // should move back to `Live' or `Confirmed'
322 /* We have a new tree ready, and an old one moved aside. We're going
323 * to have to move one of them. Let's try committing the new tree.
326 newdir.rename_!(livedir); // should move on to `Live'
330 /* Other states are stable. */
334 /* Now work through the things in our area of the filesystem and zap the
335 * ones which don't belong. In particular, this will always erase
339 root.foreachFile { f => (f.getName, st) match {
340 case ("lk", _) => ok;
341 case ("live", Live | Confirmed) => ok;
342 case ("pending", Pending) => ok;
343 case (_, Updating | Committing) =>
344 unreachable(s"unexpectedly still in `$st' state");
345 case _ => f.rmTree();
349 def destroy(ic: Eyecandy) {
350 /* Clear out the entire repository. Everything. It's all gone. */
351 ic.operation("clearing configuration")
352 { _ => root.foreachFile { f => if (f.getName != "lk") f.rmTree(); } }
356 /* Arrange to have an empty `tmpdir'. */
361 def config: Config = {
362 /* Return the repository configuration. */
364 if (_config == null) {
366 /* Firstly, decide where to find the configuration file. */
368 val dir = state match {
369 case Live | Confirmed => livedir
370 case Pending => pendingdir
372 throw new RepositoryStateException(Empty, "repository is Empty");
375 /* And then read the configuration. */
376 _config = readConfig(dir/"tripe-keys.conf");
382 def fetchConfig(url: URL, ic: Eyecandy) {
383 /* Fetch an initial configuration file from a given URL. */
388 val conffile = tmpdir/"tripe-keys.conf";
389 downloadToFile(conffile, url, 16*1024, ic);
390 checkConfigSanity(conffile, ic);
391 ic.operation("committing configuration")
392 { _ => tmpdir.rename_!(pendingdir); }
393 invalidate(); // should move to `Pending'
396 def confirm(ic: Eyecandy) {
397 /* The user has approved the master key fingerprint in the `Pending'
398 * configuration. Advance to `Confirmed'.
402 ic.operation("confirming configuration")
403 { _ => pendingdir.rename_!(livedir); }
404 invalidate(); // should move to `Confirmed'
407 def update(ic: Eyecandy) {
408 /* Update the repository from the master.
410 * Fetch a (possibly new) archive; unpack it; verify the master key
411 * against the known fingerprint; and check the signature on the bundle.
414 checkState(Confirmed, Live);
418 /* First thing is to download the tarball and signature. */
419 val tarfile = tmpdir/"tripe-keys.tar.gz";
420 downloadToFile(tarfile, new URL(conf("repos-url")), 256*1024, ic);
421 val sigfile = tmpdir/"tripe-keys.sig";
422 val seq = conf("master-sequence");
423 downloadToFile(sigfile,
424 new URL(conf("sig-url").replaceAllLiterally("<SEQ>",
428 /* Unpack the tarball. Carefully. */
429 val unpkdir = tmpdir/"unpk";
430 ic.operation("unpacking archive") { or =>
432 withCleaner { clean =>
433 val tar = new TarFile(new GZIPInputStream(tarfile.open()));
434 clean { tar.close(); }
437 /* Check the filename to make sure it's not evil. */
438 if (e.name(0) == '/' || e.name.split('/').exists { _ == ".." })
439 throw new KeyConfigException("invalid path in tarball");
441 /* Report on progress. */
442 or.step(s"entry `${e.name}'");
444 /* Find out where this file points. */
445 val f = unpkdir/e.name;
449 /* A directory. Create it if it doesn't exist already. */
452 catch { case SystemError(EEXIST, _) => ok; }
453 } else if (e.isreg) {
454 /* A regular file. Write stuff to it. */
457 f.withOutput { out =>
458 for ((b, n) <- blocks(in)) out.write(b, 0, n);
462 /* Something else. Be paranoid and reject it. */
464 throw new KeyConfigException(
465 s"entry `${e.name}' has unexpected object type");
471 /* There ought to be a file in here called `repos/master.pub'. */
472 val reposdir = unpkdir/"repos";
473 val masterfile = reposdir/"master.pub";
475 if (!reposdir.isdir_!)
476 throw new KeyConfigException("missing `repos/' directory");
477 if (!masterfile.isreg_!)
478 throw new KeyConfigException("missing `repos/master.pub' file");
479 val mastertag = s"master-$seq";
481 /* Fetch the master key's fingerprint. */
482 ic.operation("checking master key fingerprint") { _ =>
483 val foundfp = keyFingerprint(masterfile, mastertag,
484 conf("fingerprint-hash"));
485 val wantfp = conf("hk-master");
486 if (!fingerprintsEqual(wantfp, foundfp)) {
487 throw new KeyConfigException(
488 s"master key #$seq has wrong fingerprint: " +
489 s"expected $wantfp but found $foundfp");
493 /* Check the archive signature. */
494 ic.operation("verifying archive signature") { or =>
495 runCommand("catsign", "-k", masterfile.getPath, "verify", "-aqC",
496 "-k", mastertag, "-t", conf("sig-fresh"),
497 sigfile.getPath, tarfile.getPath);
500 /* Confirm that the configuration in the new archive is sane. */
501 checkConfigSanity(unpkdir/"tripe-keys.conf", ic);
503 /* Now we just have to juggle the files about. */
504 ic.operation("committing new configuration") { _ =>
505 unpkdir.rename_!(newdir);
506 livedir.rename_!(olddir);
507 newdir.rename_!(livedir);
510 invalidate(); // should move to `Live'
514 /*----- That's all, folks -------------------------------------------------*/