Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
sign-file 12.16 KiB
#!/usr/bin/perl -w
#
# Sign a module file using the given key.
#

my $USAGE =
"Usage: scripts/sign-file [-v] <hash algo> <key> <x509> <module> [<dest>]\n" .
"       scripts/sign-file [-v] -s <raw sig> <hash algo> <x509> <module> [<dest>]\n";

use strict;
use FileHandle;
use IPC::Open2;
use Getopt::Std;

my %opts;
getopts('vs:', \%opts) or die $USAGE;
my $verbose = $opts{'v'};
my $signature_file = $opts{'s'};

die $USAGE if ($#ARGV > 4);
die $USAGE if (!$signature_file && $#ARGV < 3 || $signature_file && $#ARGV < 2);

my $dgst = shift @ARGV;
my $private_key;
if (!$signature_file) {
	$private_key = shift @ARGV;
}
my $x509 = shift @ARGV;
my $module = shift @ARGV;
my ($dest, $keep_orig);
if (@ARGV) {
	$dest = $ARGV[0];
	$keep_orig = 1;
} else {
	$dest = $module . "~";
}

die "Can't read private key\n" if (!$signature_file && !-r $private_key);
die "Can't read signature file\n" if ($signature_file && !-r $signature_file);
die "Can't read X.509 certificate\n" unless (-r $x509);
die "Can't read module\n" unless (-r $module);

#
# Function to read the contents of a file into a variable.
#
sub read_file($)
{
    my ($file) = @_;
    my $contents;
    my $len;

    open(FD, "<$file") || die $file;
    binmode FD;
    my @st = stat(FD);
    die $file if (!@st);
    $len = read(FD, $contents, $st[7]) || die $file;
    close(FD) || die $file;
    die "$file: Wanted length ", $st[7], ", got ", $len, "\n"
	if ($len != $st[7]);
    return $contents;
}

###############################################################################
#
# First of all, we have to parse the X.509 certificate to find certain details
# about it.
#
# We read the DER-encoded X509 certificate and parse it to extract the Subject
# name and Subject Key Identifier.  Theis provides the data we need to build
# the certificate identifier.