1 # frozen_string_literal: true
7 Puppet::Type.type(:apt_key).provide(:apt_key) do
8 desc 'apt-key provider for apt_key resource'
10 confine osfamily: :debian
11 defaultfor osfamily: :debian
12 commands apt_key: 'apt-key'
13 commands gpg: '/usr/bin/gpg'
16 cli_args = ['adv', '--no-tty', '--list-keys', '--with-colons', '--fingerprint', '--fixed-list-mode']
18 key_output = apt_key(cli_args).encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
20 pub_line, sub_line, fpr_line = nil
22 key_array = key_output.split("\n").map do |line|
23 if line.start_with?('pub')
25 # reset fpr_line, to skip any previous subkeys which were collected
28 elsif line.start_with?('sub')
30 elsif line.start_with?('fpr')
34 if sub_line && fpr_line
35 sub_line, fpr_line = nil
39 next unless pub_line && fpr_line
41 line_hash = key_line_hash(pub_line, fpr_line)
44 pub_line, fpr_line = nil
48 if line_hash[:key_expiry]
49 expired = Time.now >= line_hash[:key_expiry]
53 name: line_hash[:key_fingerprint],
54 id: line_hash[:key_long],
55 fingerprint: line_hash[:key_fingerprint],
56 short: line_hash[:key_short],
57 long: line_hash[:key_long],
60 expiry: line_hash[:key_expiry].nil? ? nil : line_hash[:key_expiry].strftime('%Y-%m-%d'),
61 size: line_hash[:key_size],
62 type: line_hash[:key_type],
63 created: line_hash[:key_created].strftime('%Y-%m-%d'),
69 def self.prefetch(resources)
71 resources.each_key do |name|
73 provider = apt_keys.find { |key| key.fingerprint == name }
74 resources[name].provider = provider if provider
75 elsif name.length == 16
76 provider = apt_keys.find { |key| key.long == name }
77 resources[name].provider = provider if provider
78 elsif name.length == 8
79 provider = apt_keys.find { |key| key.short == name }
80 resources[name].provider = provider if provider
85 def self.key_line_hash(pub_line, fpr_line)
86 pub_split = pub_line.split(':')
87 fpr_split = fpr_line.split(':')
89 fingerprint = fpr_split.last
91 key_fingerprint: fingerprint,
92 key_long: fingerprint[-16..-1], # last 16 characters of fingerprint
93 key_short: fingerprint[-8..-1], # last 8 characters of fingerprint
94 key_size: pub_split[2],
96 key_created: Time.at(pub_split[5].to_i),
97 key_expiry: pub_split[6].empty? ? nil : Time.at(pub_split[6].to_i),
100 # set key type based on types defined in /usr/share/doc/gnupg/DETAILS.gz
103 return_hash[:key_type] = :rsa
105 return_hash[:key_type] = :dsa
107 return_hash[:key_type] = :ecc
109 return_hash[:key_type] = :ecdsa
115 def source_to_file(value)
116 parsed_value = URI.parse(value)
117 if parsed_value.scheme.nil?
118 raise(_('The file %{_value} does not exist') % { _value: value }) unless File.exist?(value)
119 # Because the tempfile method has to return a live object to prevent GC
120 # of the underlying file from occuring too early, we also have to return
121 # a file object here. The caller can still call the #path method on the
122 # closed file handle to get the path.
123 f = File.open(value, 'r')
128 # Only send basic auth if URL contains userinfo
129 # Some webservers (e.g. Amazon S3) return code 400 if empty basic auth is sent
130 if parsed_value.userinfo.nil?
131 key = if parsed_value.scheme == 'https' && resource[:weak_ssl] == true
132 open(parsed_value, ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE).read
137 user_pass = parsed_value.userinfo.split(':')
138 parsed_value.userinfo = ''
139 key = open(parsed_value, http_basic_authentication: user_pass).read
141 rescue OpenURI::HTTPError, Net::FTPPermError => e
142 raise(_('%{_e} for %{_resource}') % { _e: e.message, _resource: resource[:source] })
144 raise(_('could not resolve %{_resource}') % { _resource: resource[:source] })
151 # The tempfile method needs to return the tempfile object to the caller, so
152 # that it doesn't get deleted by the GC immediately after it returns. We
153 # want the caller to control when it goes out of scope.
154 def tempfile(content)
155 file = Tempfile.new('apt_key')
158 # confirm that the fingerprint from the file, matches the long key that is in the manifest
160 if File.executable? command(:gpg)
161 extracted_key = execute(["#{command(:gpg)} --no-tty --with-fingerprint --with-colons #{file.path} | awk -F: '/^fpr:/ { print $10 }'"], failonfail: false)
162 extracted_key = extracted_key.chomp
165 extracted_key.each_line do |line|
166 if line.chomp == name
171 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
174 warning('/usr/bin/gpg cannot be found for verification of the id.')
181 # report expired keys as non-existing when refresh => true
182 @property_hash[:ensure] == :present && !(resource[:refresh] && @property_hash[:expired])
187 if resource[:source].nil? && resource[:content].nil?
188 # Breaking up the command like this is needed because it blows up
189 # if --recv-keys isn't the last argument.
190 command.push('adv', '--no-tty', '--keyserver', resource[:server])
191 unless resource[:options].nil?
192 command.push('--keyserver-options', resource[:options])
194 command.push('--recv-keys', resource[:id])
195 elsif resource[:content]
196 key_file = tempfile(resource[:content])
197 command.push('add', key_file.path)
198 elsif resource[:source]
199 key_file = source_to_file(resource[:source])
200 command.push('add', key_file.path)
201 # In case we really screwed up, better safe than sorry.
203 raise(_('an unexpected condition occurred while trying to add the key: %{_resource}') % { _resource: resource[:id] })
206 @property_hash[:ensure] = :present
211 apt_key('del', resource.provider.short)
212 r = execute(["#{command(:apt_key)} list | grep '/#{resource.provider.short}\s'"], failonfail: false)
213 break unless r.exitstatus.zero?
218 def read_only(_value)
219 raise(_('This is a read-only property.'))
224 # Alias the setters of read-only properties
225 # to the read_only function.
226 alias_method :created=, :read_only
227 alias_method :expired=, :read_only
228 alias_method :expiry=, :read_only
229 alias_method :size=, :read_only
230 alias_method :type=, :read_only