HTTPS-Handy
view release on metacpan or search on metacpan
lib/HTTPS/Handy.pm view on Meta::CPAN
sub _resolve_certificate {
my (%opt) = @_;
my $domains = $opt{domains};
my $cert_dir = $opt{cert_dir} || '.https_handy_certs';
my $log = $opt{log};
if ($domains) {
my $domain = (ref($domains) eq 'ARRAY') ? $domains->[0] : $domains;
my $le_dir = "/etc/letsencrypt/live/$domain";
if (-f "$le_dir/fullchain.pem" && -f "$le_dir/privkey.pem") {
_log_message("Using the Let's Encrypt certificate for $domain") if $log;
return ("$le_dir/fullchain.pem", "$le_dir/privkey.pem");
}
_log_message("No certificate installed for $domain. "
. "Generating a self-signed one instead.") if $log;
}
return _generate_self_signed(%opt);
}
# _generate_self_signed - Create a self-signed certificate in Perl
#
# Self-signed certificates make a browser show a warning, but they
# need no certificate authority and no network, so a lesson can start
# with HTTPS working in the first minute. The key is an elliptic curve
# key, which takes about half a second to make here; an RSA key of
# comparable strength would take minutes of pure Perl. The pair is
# cached in cert_dir and reused on later runs.
sub _generate_self_signed {
my (%opt) = @_;
my $cert_dir = $opt{cert_dir} || '.https_handy_certs';
my $log = $opt{log};
my $key_file = "$cert_dir/selfsigned-key.pem";
my $cert_file = "$cert_dir/selfsigned-cert.pem";
if (-f $cert_file && -f $key_file) {
_log_message("Using existing self-signed certificate.") if $log;
return ($cert_file, $key_file);
}
mkdir $cert_dir, 0700 unless -d $cert_dir;
my @hosts = ('localhost', '127.0.0.1');
my $cn = 'localhost';
if ($opt{domains}) {
my @d = (ref($opt{domains}) eq 'ARRAY') ? @{ $opt{domains} } : ($opt{domains});
if (@d) {
$cn = $d[0];
@hosts = (@d, 'localhost', '127.0.0.1');
}
}
_log_message("Generating a P-256 key and a self-signed certificate for $cn ...") if $log;
my $key = HTTPS::Handy::EC::generate_key();
my $der = HTTPS::Handy::X509::make_self_signed(
key => $key,
cn => $cn,
hosts => [ @hosts ],
days => $CERT_DAYS,
);
_write_file($key_file, HTTPS::Handy::X509::private_key_to_pem_any($key));
_write_file($cert_file, HTTPS::Handy::X509::pem_wrap('CERTIFICATE', $der));
chmod 0600, $key_file;
_log_message("Self-signed certificate created at $cert_file") if $log;
return ($cert_file, $key_file);
}
# _load_context - Read the certificate chain and the private key
#
# The key may be an elliptic curve key (BEGIN EC PRIVATE KEY) or an
# RSA key (BEGIN RSA PRIVATE KEY), in either case unencrypted, and
# either may also arrive in the PKCS #8 wrapper that simply says
# BEGIN PRIVATE KEY.
sub _load_context {
my ($cert_file, $key_file) = @_;
my $cert_pem = _read_file($cert_file);
defined $cert_pem
or croak "HTTPS::Handy: Cannot read certificate file $cert_file: $!";
my @chain = HTTPS::Handy::X509::pem_blocks($cert_pem, 'CERTIFICATE');
@chain
or croak "HTTPS::Handy: No CERTIFICATE block found in $cert_file";
my $key_pem = _read_file($key_file);
defined $key_pem
or croak "HTTPS::Handy: Cannot read private key file $key_file: $!";
my $key;
my @ec = HTTPS::Handy::X509::pem_blocks($key_pem, 'EC PRIVATE KEY');
my @rsa = HTTPS::Handy::X509::pem_blocks($key_pem, 'RSA PRIVATE KEY');
my @p8 = HTTPS::Handy::X509::pem_blocks($key_pem, 'PRIVATE KEY');
if (@ec) {
$key = HTTPS::Handy::X509::ec_private_key_from_der($ec[0]);
}
elsif (@rsa) {
$key = HTTPS::Handy::X509::private_key_from_der($rsa[0]);
}
elsif (@p8) {
$key = HTTPS::Handy::X509::ec_private_key_from_der($p8[0]);
$key = HTTPS::Handy::X509::private_key_from_der($p8[0]) unless $key;
}
else {
croak "HTTPS::Handy: No PRIVATE KEY block found in $key_file";
}
$key
or croak "HTTPS::Handy: $key_file is not a P-256 or RSA private key this module can read";
return { 'cert_chain' => [ @chain ], 'key' => $key };
}
# _read_file - Slurp a file, or return undef
sub _read_file {
my ($path) = @_;
local *FH;
open(FH, "<$path") or return undef;
binmode FH;
local $/;
my $data = <FH>;
close FH;
return defined $data ? $data : '';
}
# _write_file - Write a file, or die
sub _write_file {
my ($path, $data) = @_;
local *FH;
open(FH, ">$path") or croak "HTTPS::Handy: Cannot write $path: $!";
binmode FH;
print FH $data;
close FH;
return 1;
}
# ----------------------------------------------------------------
# _handle_connection - Parse request and dispatch to app
# ----------------------------------------------------------------
# By the time this runs, the TLS handshake is over and $client is a
# HTTPS::Handy::TLS connection: read_line, read_bytes and write_data
# on it encrypt and decrypt without this code knowing anything about
# it. What is left is plain HTTP/1.0 -- a request line, some headers,
# an optional body -- and it is the same code as HTTP::Handy's, except
# for four keys in the PSGI environment:
# psgi.url_scheme => "https" (instead of "http")
# psgi.ssl => 1 (new key, indicates TLS is active)
# psgix.tls_cipher => the cipher suite this connection negotiated
# psgix.tls_resumed => 1 when the handshake was resumed, 0 when full
#
# The last two are there to be looked at: reload the demo page and watch
# psgix.tls_resumed turn from 0 into 1 as the session cache does its
# work. The "psgix." prefix is the conventional PSGI spelling for a
# key a particular server adds.
# ----------------------------------------------------------------
sub _handle_connection {
my ($client, $app, $log, $max_post_size, $server_port) = @_;
# Read request line
my $request_line = $client->read_line();
return unless defined $request_line && $request_line ne '';
$request_line =~ s/\r?\n$//;
lib/HTTPS/Handy.pm view on Meta::CPAN
}
return _der(0x06, $out);
}
# der_context - A context specific, constructed tag such as [0] or [3]
sub der_context {
my ($number, $contents) = @_;
return _der(0xA0 + $number, $contents);
}
# ----------------------------------------------------------------
# A very small DER reader, enough to walk a certificate or a key
# ----------------------------------------------------------------
# der_next - Read one TLV at $pos; returns (tag, contents, next position)
sub der_next {
my ($der, $pos) = @_;
return () if $pos + 2 > length($der);
my $tag = unpack('C', substr($der, $pos, 1));
my $b = unpack('C', substr($der, $pos + 1, 1));
my $len;
my $hdr = 2;
if ($b < 128) {
$len = $b;
}
else {
my $n = $b - 128;
$len = 0;
for (my $i = 0; $i < $n; $i++) {
$len = $len * 256 + unpack('C', substr($der, $pos + 2 + $i, 1));
}
$hdr = 2 + $n;
}
return ($tag, substr($der, $pos + $hdr, $len), $pos + $hdr + $len);
}
# ----------------------------------------------------------------
# PEM files
# ----------------------------------------------------------------
sub pem_wrap {
my ($label, $der) = @_;
return "-----BEGIN $label-----\n" . b64_encode($der) . "-----END $label-----\n";
}
# pem_blocks - Return every DER block of the given label found in $text
sub pem_blocks {
my ($text, $label) = @_;
my @out = ();
my $re = defined $label ? quotemeta($label) : '[A-Z0-9 ]+';
while ($text =~ /-----BEGIN ($re)-----(.*?)-----END \1-----/gs) {
push @out, b64_decode($2);
}
return @out;
}
# ----------------------------------------------------------------
# RSA private keys in PKCS #1 and PKCS #8 form
# ----------------------------------------------------------------
sub private_key_to_der {
my ($key) = @_;
return der_sequence(
der_integer("\x00"), # version 0
der_integer_big($key->{'n'}),
der_integer_big($key->{'e'}),
der_integer_big($key->{'d'}),
der_integer_big($key->{'p'}),
der_integer_big($key->{'q'}),
der_integer_big($key->{'dp'}),
der_integer_big($key->{'dq'}),
der_integer_big($key->{'qinv'}),
);
}
sub private_key_to_pem {
my ($key) = @_;
return pem_wrap('RSA PRIVATE KEY', private_key_to_der($key));
}
# private_key_from_der - Read a PKCS #1 (or PKCS #8 wrapped) RSA key
sub private_key_from_der {
my ($der) = @_;
my ($tag, $body) = der_next($der, 0);
return undef unless defined $tag && $tag == 0x30;
my @field = ();
my $pos = 0;
while (1) {
my ($t, $c, $next) = der_next($body, $pos);
last unless defined $t;
push @field, [ $t, $c ];
$pos = $next;
last if $pos >= length($body);
}
return undef unless scalar(@field) >= 3;
# PKCS #8: version, AlgorithmIdentifier, OCTET STRING with the key
if (($field[1][0] == 0x30) && ($field[2][0] == 0x04)) {
return private_key_from_der($field[2][1]);
}
return undef unless scalar(@field) >= 9;
my @v = map { HTTPS::Handy::BigInt::b_from_bin($_->[1]) } @field[1 .. 8];
return {
'type' => 'rsa',
'n' => $v[0],
'e' => $v[1],
'd' => $v[2],
'p' => $v[3],
'q' => $v[4],
'dp' => $v[5],
'dq' => $v[6],
'qinv' => $v[7],
'size' => length(HTTPS::Handy::BigInt::b_to_bin($v[0])),
};
}
# ----------------------------------------------------------------
# Elliptic curve keys (SEC 1, and PKCS #8 wrapped)
# ----------------------------------------------------------------
# Object identifiers used for P-256 keys and signatures
my $OID_EC_PUBLIC_KEY = '1.2.840.10045.2.1';
my $OID_PRIME256V1 = '1.2.840.10045.3.1.7';
my $OID_ECDSA_SHA256 = '1.2.840.10045.4.3.2';
my $OID_RSA_ENC = '1.2.840.113549.1.1.1';
my $OID_RSA_SHA256 = '1.2.840.113549.1.1.11';
sub ec_private_key_to_der {
my ($key) = @_;
my $point = HTTPS::Handy::EC::point_to_bin($key->{'x'}, $key->{'y'});
return der_sequence(
der_integer("\x01"), # version 1
der_octetstring(HTTPS::Handy::BigInt::b_to_bin($key->{'d'}, 32)),
der_context(0, der_oid($OID_PRIME256V1)),
der_context(1, der_bitstring($point)),
);
}
sub ec_private_key_to_pem {
my ($key) = @_;
return pem_wrap('EC PRIVATE KEY', ec_private_key_to_der($key));
}
# ec_private_key_from_der - Read a SEC 1 (or PKCS #8 wrapped) EC key
sub ec_private_key_from_der {
my ($der) = @_;
my ($tag, $body) = der_next($der, 0);
return undef unless defined $tag && ($tag == 0x30);
my @field = ();
my $pos = 0;
while ($pos < length($body)) {
my ($t, $c, $next) = der_next($body, $pos);
last unless defined $t;
push @field, [ $t, $c ];
$pos = $next;
}
return undef unless scalar(@field) >= 2;
# PKCS #8: version, AlgorithmIdentifier, OCTET STRING with the key
if (($field[1][0] == 0x30) && (scalar(@field) >= 3)
&& ($field[2][0] == 0x04)) {
return ec_private_key_from_der($field[2][1]);
}
return undef unless $field[1][0] == 0x04;
my $d = HTTPS::Handy::BigInt::b_from_bin($field[1][1]);
my ($x, $y) = HTTPS::Handy::EC::mul_generator($d);
return undef unless defined $x;
return { 'type' => 'ec', 'd' => $d, 'x' => $x, 'y' => $y };
}
# ----------------------------------------------------------------
# Public keys
# ----------------------------------------------------------------
# public_key_der - SubjectPublicKeyInfo, for either kind of key
sub public_key_der {
my ($key) = @_;
if ($key->{'type'} eq 'ec') {
return der_sequence(
der_sequence(der_oid($OID_EC_PUBLIC_KEY), der_oid($OID_PRIME256V1)),
der_bitstring(HTTPS::Handy::EC::point_to_bin($key->{'x'}, $key->{'y'})),
);
}
my $rsa = der_sequence(der_integer_big($key->{'n'}),
der_integer_big($key->{'e'}));
return der_sequence(
der_sequence(der_oid($OID_RSA_ENC), der_null()),
der_bitstring($rsa),
);
}
# signature_algorithm_der - The AlgorithmIdentifier a certificate signed
# with this key carries
sub signature_algorithm_der {
my ($key) = @_;
return der_sequence(der_oid($OID_ECDSA_SHA256)) if $key->{'type'} eq 'ec';
return der_sequence(der_oid($OID_RSA_SHA256), der_null());
}
# sign_data - Sign with SHA-256, whichever kind of key this is
sub sign_data {
my ($key, $data) = @_;
return HTTPS::Handy::EC::sign($key, $data) if $key->{'type'} eq 'ec';
return HTTPS::Handy::RSA::sign_pkcs1_sha256($key, $data);
}
# private_key_to_pem_any - PEM for either kind of key
sub private_key_to_pem_any {
my ($key) = @_;
return ec_private_key_to_pem($key) if $key->{'type'} eq 'ec';
return private_key_to_pem($key);
}
# ----------------------------------------------------------------
# Building a self-signed certificate
# ----------------------------------------------------------------
# _utctime - Format a time stamp as YYMMDDHHMMSSZ in UTC
sub _utctime {
my ($t) = @_;
my @g = gmtime($t);
return sprintf('%02d%02d%02d%02d%02d%02dZ',
$g[5] % 100, $g[4] + 1, $g[3], $g[2], $g[1], $g[0]);
}
# _name - An X.500 name holding a single common name
sub _name {
my ($cn) = @_;
return der_sequence(
der_set(der_sequence(der_oid('2.5.4.3'), der_printable($cn))));
}
# _subject_alt_name - The extension browsers use to match the host name
sub _subject_alt_name {
my (@host) = @_;
my $names = '';
for my $h (@host) {
if ($h =~ /^\d+\.\d+\.\d+\.\d+$/) {
# iPAddress [7]
$names .= _der(0x87, pack('C4', split(/\./, $h)));
}
else {
# dNSName [2]
$names .= _der(0x82, $h);
}
}
return der_sequence(der_oid('2.5.29.17'),
der_octetstring(der_sequence($names)));
}
# make_self_signed - Build a certificate and sign it with its own key
#
# key RSA key from HTTPS::Handy::RSA::generate_key
# cn common name, usually the host name
# hosts list of names or addresses for subjectAltName
# days validity in days
#
# Returns the certificate as DER.
sub make_self_signed {
my (%opt) = @_;
my $key = $opt{'key'};
my $cn = defined $opt{'cn'} ? $opt{'cn'} : 'localhost';
my $days = defined $opt{'days'} ? $opt{'days'} : 3650;
my @hosts = (defined $opt{'hosts'} && ref($opt{'hosts'}) eq 'ARRAY')
? @{ $opt{'hosts'} }
: ($cn);
my $now = time();
my $serial = HTTPS::Handy::Crypt::random_bytes(8);
substr($serial, 0, 1) = pack('C', unpack('C', substr($serial, 0, 1)) & 0x7F);
( run in 0.943 second using v1.01-cache-2.11-cpan-8379b9b8ec2 )