| 1 | # -*- perl -*- | ||
| 2 | |||
| 3 | # | ||
| 4 | # Author: Slaven Rezic | ||
| 5 | # | ||
| 6 | # Copyright (C) 2017,2018,2022 Slaven Rezic. All rights reserved. | ||
| 7 | # This package is free software; you can redistribute it and/or | ||
| 8 | # modify it under the same terms as Perl itself. | ||
| 9 | # | ||
| 10 | # Mail: slaven@rezic.de | ||
| 11 | # WWW: http://www.rezic.de/eserte/ | ||
| 12 | # | ||
| 13 | |||
| 14 | package Doit::Ssl; # Convention: all commands here should be prefixed with 'ssl_' | ||
| 15 | |||
| 16 | use strict; | ||
| 17 | use warnings; | ||
| 18 | our $VERSION = '0.012'; | ||
| 19 | |||
| 20 | use File::Basename 'basename'; | ||
| 21 | |||
| 22 | use Doit::Log; | ||
| 23 | |||
| 24 | sub new { bless {}, shift } | ||
| 25 | sub functions { qw(ssl_install_ca_certificate can_openssl) } | ||
| 26 | |||
| 27 | sub can_openssl { | ||
| 28 | my($self) = @_; | ||
| 29 | $self->which('openssl') ? 1 : 0; | ||
| 30 | } | ||
| 31 | |||
| 32 | sub ssl_install_ca_certificate { | ||
| 33 | my($self, %args) = @_; | ||
| 34 | my $ca_file = delete $args{ca_file} || error "Please specify ca_file"; | ||
| 35 | error "Unhandled options: " . join(" ", %args) if %args; | ||
| 36 | |||
| 37 | if (!$self->can_openssl) { | ||
| 38 | error "openssl is not available"; | ||
| 39 | } | ||
| 40 | |||
| 41 | my $fingerprint = $self->info_qx({quiet=>1}, qw(openssl x509 -noout -fingerprint -in), $ca_file); | ||
| 42 | |||
| 43 | my $cert_file = '/etc/ssl/certs/ca-certificates.crt'; # XXX what about non-Debians? | ||
| 44 | if (open my $fh, '<', $cert_file) { | ||
| 45 | my $buf; | ||
| 46 | while(<$fh>) { | ||
| 47 | if (/BEGIN CERTIFICATE/) { | ||
| 48 | $buf = $_; | ||
| 49 | } else { | ||
| 50 | $buf .= $_; | ||
| 51 | if (/END CERTIFICATE/) { | ||
| 52 | my $check_fingerprint = $self->info_open2({quiet=>1, instr=>$buf}, qw(openssl x509 -noout -fingerprint)); | ||
| 53 | if ($fingerprint eq $check_fingerprint) { | ||
| 54 | # Found certificate, nothing to do | ||
| 55 | return 0; | ||
| 56 | } | ||
| 57 | } | ||
| 58 | } | ||
| 59 | } | ||
| 60 | } else { | ||
| 61 | warning "No file '$cert_file' found --- is this the first certificate on this system?"; | ||
| 62 | } | ||
| 63 | |||
| 64 | my $dest_file = basename $ca_file; | ||
| 65 | if ($dest_file !~ m{\.crt$}) { | ||
| 66 | $dest_file .= '.crt'; | ||
| 67 | } | ||
| 68 | my $sudo = $< == 0 ? $self: $self->do_sudo; # unprivileged? -> upgrade to sudo | ||
| 69 | $sudo->copy($ca_file, "/usr/local/share/ca-certificates/$dest_file"); | ||
| 70 | if (!$sudo->is_dry_run) { | ||
| 71 | $sudo->system('update-ca-certificates'); | ||
| 72 | } else { | ||
| 73 | info "Would need to run update-ca-certificates"; | ||
| 74 | } | ||
| 75 | |||
| 76 | return 1; | ||
| 77 | } | ||
| 78 | |||
| 79 | 1; | ||
| 80 | |||
| 81 | __END__ |