aboutsummaryrefslogtreecommitdiff
path: root/lib/facter/letsencrypt_directory.rb
blob: 6f6558d943998ae17475ec643c2d667c1850db67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# frozen_string_literal: true

# File taken from [puppet/letsencrypt v9.0.1][1]
# Licensed under Apache-2.0
# Copyright 2013 Gareth Rushgrove
#
# With minor modifications by me
# Copyright 2023 Hugo Hörnquist
#
# [1]: https://forge.puppet.com/modules/puppet/letsencrypt

require 'openssl'
require 'pathname'

Facter.add(:letsencrypt_directory) do
  confine kernel: ['FreeBSD', 'Linux', 'OpenBSD']

  setcode do
    certs = {}

    # locate the certificate repository
    livedir = ['/etc/letsencrypt/live', '/etc/certbot/live']
              .map { |path| Pathname.new path }
              .find(&:directory?)

    unless livedir.nil?
      Pathname.new(livedir).children.select(&:directory?).each do |path|
        pem = File.join(path, 'cert.pem')
        cert = OpenSSL::X509::Certificate.new(File.new(pem).read)
        san = cert.extensions.find { |e| e.oid == 'subjectAltName' }
        names = san.value.split(',').map { |entry| entry.split(':')[1] }
        names.each do |n|
          certs[n] = path.to_s
        end
      end
    end

    certs
  end
end