1 # frozen_string_literal: true
7 # Ruby 3.0 changed net-ftp to a default gem
11 Puppet::Type.type(:apt_key).provide(:apt_key) do # rubocop:disable Metrics/BlockLength
12 desc 'apt-key provider for apt_key resource'
14 confine osfamily: :debian
15 defaultfor osfamily: :debian
16 commands apt_key: 'apt-key'
17 commands gpg: '/usr/bin/gpg'
19 def self.instances # rubocop:disable Metrics/AbcSize
22 cli_args = ['adv', '--no-tty', '--list-keys', '--with-colons', '--fingerprint', '--fixed-list-mode']
24 key_output = apt_key(cli_args).encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
30 lines = key_output.split("\n")
32 lines.each_index do |i|
33 if lines[i].start_with?('pub')
35 # starting a new public key, so reset fpr_lines and sub_lines
38 elsif lines[i].start_with?('fpr')
40 elsif lines[i].start_with?('sub')
44 next unless (pub_line && !fpr_lines.empty?) && (!lines[i + 1] || lines[i + 1].start_with?('pub'))
46 line_hash = key_line_hash(pub_line, fpr_lines)
48 expired = line_hash[:key_expired] || subkeys_all_expired(sub_lines)
51 name: line_hash[:key_fingerprint],
52 id: line_hash[:key_long],
53 fingerprint: line_hash[:key_fingerprint],
54 short: line_hash[:key_short],
55 long: line_hash[:key_long],
58 expiry: line_hash[:key_expiry].nil? ? nil : line_hash[:key_expiry].strftime('%Y-%m-%d'),
59 size: line_hash[:key_size],
60 type: line_hash[:key_type],
61 created: line_hash[:key_created].strftime('%Y-%m-%d'),
67 def self.prefetch(resources)
69 resources.each_key do |name|
72 provider = apt_keys.find { |key| key.fingerprint == name }
73 resources[name].provider = provider if provider
75 provider = apt_keys.find { |key| key.long == name }
76 resources[name].provider = provider if provider
78 provider = apt_keys.find { |key| key.short == name }
79 resources[name].provider = provider if provider
84 def self.subkeys_all_expired(sub_lines)
85 return false if sub_lines.empty?
87 sub_lines.each do |line|
88 return false if line.split(':')[1] == '-'
93 def self.key_line_hash(pub_line, fpr_lines)
94 pub_split = pub_line.split(':')
95 fpr_split = fpr_lines.first.split(':')
97 fingerprint = fpr_split.last
99 key_fingerprint: fingerprint,
100 key_long: fingerprint[-16..], # last 16 characters of fingerprint
101 key_short: fingerprint[-8..], # last 8 characters of fingerprint
102 key_size: pub_split[2],
104 key_created: Time.at(pub_split[5].to_i),
105 key_expired: pub_split[1] == 'e',
106 key_expiry: pub_split[6].empty? ? nil : Time.at(pub_split[6].to_i)
109 # set key type based on types defined in /usr/share/doc/gnupg/DETAILS.gz
112 return_hash[:key_type] = :rsa
114 return_hash[:key_type] = :dsa
116 return_hash[:key_type] = :ecc
118 return_hash[:key_type] = :ecdsa
124 def source_to_file(value)
125 parsed_value = URI.parse(value)
126 if parsed_value.scheme.nil?
127 raise(_('The file %{_value} does not exist') % { _value: value }) unless File.exist?(value)
129 # Because the tempfile method has to return a live object to prevent GC
130 # of the underlying file from occuring too early, we also have to return
131 # a file object here. The caller can still call the #path method on the
132 # closed file handle to get the path.
133 f = File.open(value, 'r')
137 exceptions = [OpenURI::HTTPError]
138 exceptions << Net::FTPPermError if defined?(Net::FTPPermError)
141 # Only send basic auth if URL contains userinfo
142 # Some webservers (e.g. Amazon S3) return code 400 if empty basic auth is sent
143 if parsed_value.userinfo.nil?
144 key = if parsed_value.scheme == 'https' && resource[:weak_ssl] == true
145 URI.open(parsed_value, ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE).read
150 user_pass = parsed_value.userinfo.split(':')
151 parsed_value.userinfo = ''
152 key = URI.open(parsed_value, http_basic_authentication: user_pass).read
154 rescue *exceptions => e
155 raise(_('%{_e} for %{_resource}') % { _e: e.message, _resource: resource[:source] })
157 raise(_('could not resolve %{_resource}') % { _resource: resource[:source] })
164 # The tempfile method needs to return the tempfile object to the caller, so
165 # that it doesn't get deleted by the GC immediately after it returns. We
166 # want the caller to control when it goes out of scope.
167 def tempfile(content)
168 file = Tempfile.new('apt_key')
171 # confirm that the fingerprint from the file, matches the long key that is in the manifest
173 if File.executable? command(:gpg)
174 extracted_key = execute(["#{command(:gpg)} --no-tty --with-fingerprint --with-colons #{file.path} | awk -F: '/^fpr:/ { print $10 }'"], failonfail: false)
175 extracted_key = extracted_key.chomp
178 extracted_key.each_line do |line|
179 found_match = true if line.chomp == name
182 raise(_('The id in your manifest %{_resource} and the fingerprint from content/source don\'t match. Check for an error in the id and content/source is legitimate.') % { _resource: resource[:name] }) # rubocop:disable Layout/LineLength
185 warning('/usr/bin/gpg cannot be found for verification of the id.')
192 # report expired keys as non-existing when refresh => true
193 @property_hash[:ensure] == :present && !(resource[:refresh] && @property_hash[:expired])
198 if resource[:source].nil? && resource[:content].nil?
199 # Breaking up the command like this is needed because it blows up
200 # if --recv-keys isn't the last argument.
201 command.push('adv', '--no-tty', '--keyserver', resource[:server])
202 command.push('--keyserver-options', resource[:options]) unless resource[:options].nil?
203 command.push('--recv-keys', resource[:id])
204 elsif resource[:content]
205 key_file = tempfile(resource[:content])
206 command.push('add', key_file.path)
207 elsif resource[:source]
208 key_file = source_to_file(resource[:source])
209 command.push('add', key_file.path)
210 # In case we really screwed up, better safe than sorry.
212 raise(_('an unexpected condition occurred while trying to add the key: %{_resource}') % { _resource: resource[:id] })
215 @property_hash[:ensure] = :present
220 apt_key('del', resource.provider.short)
221 r = execute(["#{command(:apt_key)} list | grep '/#{resource.provider.short}\s'"], failonfail: false)
222 break unless r.exitstatus.zero?
227 def read_only(_value)
228 raise(_('This is a read-only property.'))
233 # Alias the setters of read-only properties
234 # to the read_only function.
235 alias_method :created=, :read_only
236 alias_method :expired=, :read_only
237 alias_method :expiry=, :read_only
238 alias_method :size=, :read_only
239 alias_method :type=, :read_only