Skip to content

Commit 0fdf4da

Browse files
committed
Support cryptographically signed binary caches
NAR info files in binary caches can now have a cryptographic signature that Nix will verify before using the corresponding NAR file. To create a private/public key pair for signing and verifying a binary cache, do: $ openssl genrsa -out ./cache-key.sec 2048 $ openssl rsa -in ./cache-key.sec -pubout > ./cache-key.pub You should also come up with a symbolic name for the key, such as "cache.example.org-1". This will be used by clients to look up the public key. (It's a good idea to number keys, in case you ever need to revoke/replace one.) To create a binary cache signed with the private key: $ nix-push --dest /path/to/binary-cache --key ./cache-key.sec --key-name cache.example.org-1 The public key (cache-key.pub) should be distributed to the clients. They should have a nix.conf should contain something like: signed-binary-caches = * binary-cache-public-key-cache.example.org-1 = /path/to/cache-key.pub If all works well, then if Nix fetches something from the signed binary cache, you will see a message like: *** Downloading ‘http://cache.example.org/nar/7dppcj5sc1nda7l54rjc0g5l1hamj09j-subversion-1.7.11’ (signed by ‘cache.example.org-1’) to ‘/nix/store/7dppcj5sc1nda7l54rjc0g5l1hamj09j-subversion-1.7.11’... On the other hand, if the signature is wrong, you get a message like NAR info file `http://cache.example.org/7dppcj5sc1nda7l54rjc0g5l1hamj09j.narinfo' has an invalid signature; ignoring Signatures are implemented as a single line appended to the NAR info file, which looks like this: Signature: 1;cache.example.org-1;HQ9Xzyanq9iV...muQ== Thus the signature has 3 fields: a version (currently "1"), the ID of key, and the base64-encoded signature of the SHA-256 hash of the contents of the NAR info file up to but not including the Signature line. Issue #75.
1 parent 405434e commit 0fdf4da

File tree

8 files changed

+126
-12
lines changed

8 files changed

+126
-12
lines changed

perl/Makefile.am

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
PERL_MODULES = lib/Nix/Store.pm lib/Nix/Manifest.pm lib/Nix/GeneratePatches.pm lib/Nix/SSH.pm lib/Nix/CopyClosure.pm lib/Nix/Config.pm.in lib/Nix/Utils.pm
1+
PERL_MODULES = lib/Nix/Store.pm lib/Nix/Manifest.pm lib/Nix/GeneratePatches.pm lib/Nix/SSH.pm lib/Nix/CopyClosure.pm lib/Nix/Config.pm.in lib/Nix/Utils.pm lib/Nix/Crypto.pm
22

33
all: $(PERL_MODULES:.in=)
44

perl/lib/Nix/Config.pm.in

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ $storeDir = $ENV{"NIX_STORE_DIR"} || "@storedir@";
1313
$bzip2 = "@bzip2@";
1414
$xz = "@xz@";
1515
$curl = "@curl@";
16+
$openssl = "@openssl@";
1617

1718
$useBindings = "@perlbindings@" eq "yes";
1819

@@ -32,7 +33,7 @@ sub readConfig {
3233

3334
open CONFIG, "<$config" or die "cannot open `$config'";
3435
while (<CONFIG>) {
35-
/^\s*([\w|-]+)\s*=\s*(.*)$/ or next;
36+
/^\s*([\w\-\.]+)\s*=\s*(.*)$/ or next;
3637
$config{$1} = $2;
3738
}
3839
close CONFIG;

perl/lib/Nix/Crypto.pm

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package Nix::Crypto;
2+
3+
use strict;
4+
use MIME::Base64;
5+
use Nix::Store;
6+
use Nix::Config;
7+
use IPC::Open2;
8+
9+
our @ISA = qw(Exporter);
10+
our @EXPORT = qw(signString isValidSignature);
11+
12+
sub signString {
13+
my ($privateKeyFile, $s) = @_;
14+
my $hash = hashString("sha256", 0, $s);
15+
my ($from, $to);
16+
my $pid = open2($from, $to, $Nix::Config::openssl, "rsautl", "-sign", "-inkey", $privateKeyFile);
17+
print $to $hash;
18+
close $to;
19+
local $/ = undef;
20+
my $sig = <$from>;
21+
close $from;
22+
waitpid($pid, 0);
23+
die "$0: OpenSSL returned exit code $? while signing hash\n" if $? != 0;
24+
my $sig64 = encode_base64($sig, "");
25+
return $sig64;
26+
}
27+
28+
sub isValidSignature {
29+
my ($publicKeyFile, $sig64, $s) = @_;
30+
my ($from, $to);
31+
my $pid = open2($from, $to, $Nix::Config::openssl, "rsautl", "-verify", "-inkey", $publicKeyFile, "-pubin");
32+
print $to decode_base64($sig64);
33+
close $to;
34+
my $decoded = <$from>;
35+
close $from;
36+
waitpid($pid, 0);
37+
return 0 if $? != 0;
38+
my $hash = hashString("sha256", 0, $s);
39+
return $decoded eq $hash;
40+
}
41+
42+
1;

perl/lib/Nix/Manifest.pm

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use File::stat;
88
use File::Path;
99
use Fcntl ':flock';
1010
use Nix::Config;
11+
use Nix::Crypto;
1112

1213
our @ISA = qw(Exporter);
1314
our @EXPORT = qw(readManifest writeManifest updateManifestDB addPatch deleteOldManifests parseNARInfo);
@@ -394,9 +395,10 @@ sub deleteOldManifests {
394395

395396
# Parse a NAR info file.
396397
sub parseNARInfo {
397-
my ($storePath, $content) = @_;
398+
my ($storePath, $content, $requireValidSig, $location) = @_;
398399

399-
my ($storePath2, $url, $fileHash, $fileSize, $narHash, $narSize, $deriver, $system);
400+
my ($storePath2, $url, $fileHash, $fileSize, $narHash, $narSize, $deriver, $system, $sig);
401+
my $signedData = "";
400402
my $compression = "bzip2";
401403
my @refs;
402404

@@ -412,11 +414,13 @@ sub parseNARInfo {
412414
elsif ($1 eq "References") { @refs = split / /, $2; }
413415
elsif ($1 eq "Deriver") { $deriver = $2; }
414416
elsif ($1 eq "System") { $system = $2; }
417+
elsif ($1 eq "Signature") { $sig = $2; last; }
418+
$signedData .= "$line\n";
415419
}
416420

417421
return undef if $storePath ne $storePath2 || !defined $url || !defined $narHash;
418422

419-
return
423+
my $res =
420424
{ url => $url
421425
, compression => $compression
422426
, fileHash => $fileHash
@@ -427,6 +431,36 @@ sub parseNARInfo {
427431
, deriver => $deriver
428432
, system => $system
429433
};
434+
435+
if ($requireValidSig) {
436+
if (!defined $sig) {
437+
warn "NAR info file `$location' lacks a signature; ignoring\n";
438+
return undef;
439+
}
440+
my ($sigVersion, $keyName, $sig64) = split ";", $sig;
441+
$sigVersion //= 0;
442+
if ($sigVersion != 1) {
443+
warn "NAR info file `$location' has unsupported version $sigVersion; ignoring\n";
444+
return undef;
445+
}
446+
return undef unless defined $keyName && defined $sig64;
447+
my $publicKeyFile = $Nix::Config::config{"binary-cache-public-key-$keyName"};
448+
if (!defined $publicKeyFile) {
449+
warn "NAR info file `$location' is signed by unknown key `$keyName'; ignoring\n";
450+
return undef;
451+
}
452+
if (! -f $publicKeyFile) {
453+
die "binary cache public key file `$publicKeyFile' does not exist\n";
454+
return undef;
455+
}
456+
if (!isValidSignature($publicKeyFile, $sig64, $signedData)) {
457+
warn "NAR info file `$location' has an invalid signature; ignoring\n";
458+
return undef;
459+
}
460+
$res->{signedBy} = $keyName;
461+
}
462+
463+
return $res;
430464
}
431465

432466

scripts/download-from-binary-cache.pl.in

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ my $caBundle = $ENV{"CURL_CA_BUNDLE"} // $ENV{"OPENSSL_X509_CERT_FILE"};
4242

4343
my $userName = getpwuid($<) or die "cannot figure out user name";
4444

45+
my $requireSignedBinaryCaches = ($Nix::Config::config{"signed-binary-caches"} // "0") ne "0";
46+
4547

4648
sub addRequest {
4749
my ($storePath, $url, $head) = @_;
@@ -120,9 +122,10 @@ sub processRequests {
120122

121123

122124
sub initCache {
123-
my $dbPath = "$Nix::Config::stateDir/binary-cache-v2.sqlite";
125+
my $dbPath = "$Nix::Config::stateDir/binary-cache-v3.sqlite";
124126

125127
unlink "$Nix::Config::stateDir/binary-cache-v1.sqlite";
128+
unlink "$Nix::Config::stateDir/binary-cache-v2.sqlite";
126129

127130
# Open/create the database.
128131
$dbh = DBI->connect("dbi:SQLite:dbname=$dbPath", "", "")
@@ -159,7 +162,7 @@ EOF
159162
narSize integer,
160163
refs text,
161164
deriver text,
162-
system text,
165+
signedBy text,
163166
timestamp integer not null,
164167
primary key (cache, storePath),
165168
foreign key (cache) references BinaryCaches(id) on delete cascade
@@ -183,7 +186,7 @@ EOF
183186

184187
$insertNAR = $dbh->prepare(
185188
"insert or replace into NARs(cache, storePath, url, compression, fileHash, fileSize, narHash, " .
186-
"narSize, refs, deriver, system, timestamp) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") or die;
189+
"narSize, refs, deriver, signedBy, timestamp) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") or die;
187190

188191
$queryNAR = $dbh->prepare("select * from NARs where cache = ? and storePath = ?") or die;
189192

@@ -309,14 +312,16 @@ sub processNARInfo {
309312
return undef;
310313
}
311314

312-
my $narInfo = parseNARInfo($storePath, $request->{content});
315+
my $narInfo = parseNARInfo($storePath, $request->{content}, $requireSignedBinaryCaches, $request->{url});
313316
return undef unless defined $narInfo;
314317

318+
die if $requireSignedBinaryCaches && !defined $narInfo->{signedBy};
319+
315320
# Cache the result.
316321
$insertNAR->execute(
317322
$cache->{id}, basename($storePath), $narInfo->{url}, $narInfo->{compression},
318323
$narInfo->{fileHash}, $narInfo->{fileSize}, $narInfo->{narHash}, $narInfo->{narSize},
319-
join(" ", @{$narInfo->{refs}}), $narInfo->{deriver}, $narInfo->{system}, time())
324+
join(" ", @{$narInfo->{refs}}), $narInfo->{deriver}, $narInfo->{signedBy}, time())
320325
if shouldCache $request->{url};
321326

322327
return $narInfo;
@@ -330,6 +335,10 @@ sub getCachedInfoFrom {
330335
my $res = $queryNAR->fetchrow_hashref();
331336
return undef unless defined $res;
332337

338+
# We may previously have cached this info when signature checking
339+
# was disabled. In that case, ignore the cached info.
340+
return undef if $requireSignedBinaryCaches && !defined $res->{signedBy};
341+
333342
return
334343
{ url => $res->{url}
335344
, compression => $res->{compression}
@@ -339,6 +348,7 @@ sub getCachedInfoFrom {
339348
, narSize => $res->{narSize}
340349
, refs => [ split " ", $res->{refs} ]
341350
, deriver => $res->{deriver}
351+
, signedBy => $res->{signedBy}
342352
} if defined $res;
343353
}
344354

@@ -522,14 +532,16 @@ sub downloadBinary {
522532
next;
523533
}
524534
my $url = "$cache->{url}/$info->{url}"; # FIXME: handle non-relative URLs
525-
print STDERR "\n*** Downloading ‘$url’ to ‘$storePath’...\n";
535+
die if $requireSignedBinaryCaches && !defined $info->{signedBy};
536+
print STDERR "\n*** Downloading ‘$url’ ", ($requireSignedBinaryCaches ? "(signed by ‘$info->{signedBy}’) " : ""), "to ‘$storePath’...\n";
526537
checkURL $url;
527538
if (system("$Nix::Config::curl --fail --location --insecure '$url' $decompressor | $Nix::Config::binDir/nix-store --restore $destPath") != 0) {
528539
warn "download of `$url' failed" . ($! ? ": $!" : "") . "\n";
529540
next;
530541
}
531542

532543
# Tell Nix about the expected hash so it can verify it.
544+
die unless defined $info->{narHash} && $info->{narHash} ne "";
533545
print "$info->{narHash}\n";
534546

535547
print STDERR "\n";

scripts/nix-push.in

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use Nix::Config;
1010
use Nix::Store;
1111
use Nix::Manifest;
1212
use Nix::Utils;
13+
use Nix::Crypto;
1314

1415
my $tmpDir = tempdir("nix-push.XXXXXX", CLEANUP => 1, TMPDIR => 1)
1516
or die "cannot create a temporary directory";
@@ -25,6 +26,8 @@ my $writeManifest = 0;
2526
my $manifestPath;
2627
my $archivesURL;
2728
my $link = 0;
29+
my $privateKeyFile;
30+
my $keyName;
2831
my @roots;
2932

3033
for (my $n = 0; $n < scalar @ARGV; $n++) {
@@ -57,6 +60,14 @@ for (my $n = 0; $n < scalar @ARGV; $n++) {
5760
$archivesURL = $ARGV[$n];
5861
} elsif ($arg eq "--link") {
5962
$link = 1;
63+
} elsif ($arg eq "--key") {
64+
$n++;
65+
die "$0: `$arg' requires an argument\n" unless $n < scalar @ARGV;
66+
$privateKeyFile = $ARGV[$n];
67+
} elsif ($arg eq "--key-name") {
68+
$n++;
69+
die "$0: `$arg' requires an argument\n" unless $n < scalar @ARGV;
70+
$keyName = $ARGV[$n];
6071
} elsif (substr($arg, 0, 1) eq "-") {
6172
die "$0: unknown flag `$arg'\n";
6273
} else {
@@ -99,7 +110,7 @@ foreach my $storePath (@storePaths) {
99110
my $pathHash = substr(basename($storePath), 0, 32);
100111
my $narInfoFile = "$destDir/$pathHash.narinfo";
101112
if (-e $narInfoFile) {
102-
my $narInfo = parseNARInfo($storePath, readFile($narInfoFile));
113+
my $narInfo = parseNARInfo($storePath, readFile($narInfoFile), 0, $narInfoFile) or die "cannot read `$narInfoFile'\n";
103114
my $narFile = "$destDir/$narInfo->{url}";
104115
if (-e $narFile) {
105116
print STDERR "skipping existing $storePath\n";
@@ -245,6 +256,11 @@ for (my $n = 0; $n < scalar @storePaths2; $n++) {
245256
}
246257
}
247258

259+
if (defined $privateKeyFile && defined $keyName) {
260+
my $sig = signString($privateKeyFile, $info);
261+
$info .= "Signature: 1;$keyName;$sig\n";
262+
}
263+
248264
my $pathHash = substr(basename($storePath), 0, 32);
249265

250266
$dst = "$destDir/$pathHash.narinfo";

substitute.mk

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
-e "s^@version\@^$(VERSION)^g" \
3636
-e "s^@perlbindings\@^$(perlbindings)^g" \
3737
-e "s^@testPath\@^$(coreutils):$$(dirname $$(type -p expr))^g" \
38+
-e "s^@openssl\@^$(openssl_prog)^g" \
3839
< $< > $@ || rm $@
3940
if test -x $<; then chmod +x $@; fi
4041

tests/binary-cache.sh

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,14 @@ nix-store --check-validity $outPath
4040
nix-store -qR $outPath | grep input-2
4141

4242

43+
# Test whether this unsigned cache is rejected if the user requires signed caches.
44+
clearStore
45+
46+
rm -f $NIX_STATE_DIR/binary-cache*
47+
48+
nix-store --option binary-caches "file://$cacheDir" --option signed-binary-caches 1 -r $outPath
49+
50+
4351
# Test whether fallback works if we have cached info but the
4452
# corresponding NAR has disappeared.
4553
clearStore

0 commit comments

Comments
 (0)