5 if RUBY_VERSION == '1.8.7'
6 # Mothers cry, puppies die and Ruby 1.8.7's open-uri needs to be
7 # monkeypatched to support passing in :ftp_passive_mode.
8 require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..',
9 'puppet_x', 'apt_key', 'patch_openuri.rb'))
10 OpenURI::Options[:ftp_active_mode] = false
13 Puppet::Type.type(:apt_key).provide(:apt_key) do
14 desc 'apt-key provider for apt_key resource'
16 confine osfamily: :debian
17 defaultfor osfamily: :debian
18 commands apt_key: 'apt-key'
19 commands gpg: '/usr/bin/gpg'
22 cli_args = ['adv', '--list-keys', '--with-colons', '--fingerprint', '--fixed-list-mode']
24 key_output = apt_key(cli_args).encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
26 pub_line, sub_line, fpr_line = nil
28 key_array = key_output.split("\n").map do |line|
29 if line.start_with?('pub')
31 # reset fpr_line, to skip any previous subkeys which were collected
34 elsif line.start_with?('sub')
36 elsif line.start_with?('fpr')
40 if sub_line && fpr_line
41 sub_line, fpr_line = nil
45 next unless pub_line && fpr_line
47 line_hash = key_line_hash(pub_line, fpr_line)
50 pub_line, fpr_line = nil
54 if line_hash[:key_expiry]
55 expired = Time.now >= line_hash[:key_expiry]
59 name: line_hash[:key_fingerprint],
60 id: line_hash[:key_long],
61 fingerprint: line_hash[:key_fingerprint],
62 short: line_hash[:key_short],
63 long: line_hash[:key_long],
66 expiry: line_hash[:key_expiry].nil? ? nil : line_hash[:key_expiry].strftime('%Y-%m-%d'),
67 size: line_hash[:key_size],
68 type: line_hash[:key_type],
69 created: line_hash[:key_created].strftime('%Y-%m-%d'),
75 def self.prefetch(resources)
77 resources.each_key do |name|
79 provider = apt_keys.find { |key| key.fingerprint == name }
80 resources[name].provider = provider if provider
81 elsif name.length == 16
82 provider = apt_keys.find { |key| key.long == name }
83 resources[name].provider = provider if provider
84 elsif name.length == 8
85 provider = apt_keys.find { |key| key.short == name }
86 resources[name].provider = provider if provider
91 def self.key_line_hash(pub_line, fpr_line)
92 pub_split = pub_line.split(':')
93 fpr_split = fpr_line.split(':')
95 fingerprint = fpr_split.last
97 key_fingerprint: fingerprint,
98 key_long: fingerprint[-16..-1], # last 16 characters of fingerprint
99 key_short: fingerprint[-8..-1], # last 8 characters of fingerprint
100 key_size: pub_split[2],
102 key_created: Time.at(pub_split[5].to_i),
103 key_expiry: pub_split[6].empty? ? nil : Time.at(pub_split[6].to_i),
106 # set key type based on types defined in /usr/share/doc/gnupg/DETAILS.gz
109 return_hash[:key_type] = :rsa
111 return_hash[:key_type] = :dsa
113 return_hash[:key_type] = :ecc
115 return_hash[:key_type] = :ecdsa
121 def source_to_file(value)
122 parsed_value = URI.parse(value)
123 if parsed_value.scheme.nil?
124 raise(_('The file %{_value} does not exist') % { _value: value }) unless File.exist?(value)
125 # Because the tempfile method has to return a live object to prevent GC
126 # of the underlying file from occuring too early, we also have to return
127 # a file object here. The caller can still call the #path method on the
128 # closed file handle to get the path.
129 f = File.open(value, 'r')
134 # Only send basic auth if URL contains userinfo
135 # Some webservers (e.g. Amazon S3) return code 400 if empty basic auth is sent
136 if parsed_value.userinfo.nil?
137 key = parsed_value.read
139 user_pass = parsed_value.userinfo.split(':')
140 parsed_value.userinfo = ''
141 key = open(parsed_value, http_basic_authentication: user_pass).read
143 rescue OpenURI::HTTPError, Net::FTPPermError => e
144 raise(_('%{_e} for %{_resource}') % { _e: e.message, _resource: resource[:source] })
146 raise(_('could not resolve %{_resource}') % { _resource: resource[:source] })
153 # The tempfile method needs to return the tempfile object to the caller, so
154 # that it doesn't get deleted by the GC immediately after it returns. We
155 # want the caller to control when it goes out of scope.
156 def tempfile(content)
157 file = Tempfile.new('apt_key')
160 # confirm that the fingerprint from the file, matches the long key that is in the manifest
162 if File.executable? command(:gpg)
163 extracted_key = execute(["#{command(:gpg)} --with-fingerprint --with-colons #{file.path} | awk -F: '/^fpr:/ { print $10 }'"], failonfail: false)
164 extracted_key = extracted_key.chomp
167 extracted_key.each_line do |line|
168 if line.chomp == name
173 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 Metrics/LineLength
176 warning('/usr/bin/gpg cannot be found for verification of the id.')
182 # Update a key if it is expired
183 def update_expired_key
184 # Return without doing anything if refresh or expired is false
185 return unless resource[:refresh] == true && resource[:expired] == true
187 # Execute command to update key
190 unless resource[:source].nil? && resource[:content].nil?
191 raise(_('an unexpected condition occurred while trying to add the key: %{_resource}') % { _resource: resource[:id] })
194 # Breaking up the command like this is needed because it blows up
195 # if --recv-keys isn't the last argument.
196 command.push('adv', '--keyserver', resource[:server])
197 unless resource[:options].nil?
198 command.push('--keyserver-options', resource[:options])
200 command.push('--recv-keys', resource[:id])
205 # report expired keys as non-existing when refresh => true
206 @property_hash[:ensure] == :present && !(resource[:refresh] && @property_hash[:expired])
211 if resource[:source].nil? && resource[:content].nil?
212 # Breaking up the command like this is needed because it blows up
213 # if --recv-keys isn't the last argument.
214 command.push('adv', '--keyserver', resource[:server])
215 unless resource[:options].nil?
216 command.push('--keyserver-options', resource[:options])
218 command.push('--recv-keys', resource[:id])
219 elsif resource[:content]
220 key_file = tempfile(resource[:content])
221 command.push('add', key_file.path)
222 elsif resource[:source]
223 key_file = source_to_file(resource[:source])
224 command.push('add', key_file.path)
225 # In case we really screwed up, better safe than sorry.
227 raise(_('an unexpected condition occurred while trying to add the key: %{_resource}') % { _resource: resource[:id] })
230 @property_hash[:ensure] = :present
235 apt_key('del', resource.provider.short)
236 r = execute(["#{command(:apt_key)} list | grep '/#{resource.provider.short}\s'"], failonfail: false)
237 break unless r.exitstatus.zero?
242 def read_only(_value)
243 raise(_('This is a read-only property.'))
248 # Needed until PUP-1470 is fixed and we can drop support for Puppet versions
251 @property_hash[:expired]
254 # Alias the setters of read-only properties
255 # to the read_only function.
256 alias_method :created=, :read_only
257 alias_method :expired=, :read_only
258 alias_method :expiry=, :read_only
259 alias_method :size=, :read_only
260 alias_method :type=, :read_only