Release prep v9.1.0
[puppet-modules/puppetlabs-apt.git] / lib / puppet / provider / apt_key / apt_key.rb
1 # frozen_string_literal: true
2
3 require 'open-uri'
4 begin
5   require 'net/ftp'
6 rescue LoadError
7   # Ruby 3.0 changed net-ftp to a default gem
8 end
9 require 'tempfile'
10
11 Puppet::Type.type(:apt_key).provide(:apt_key) do # rubocop:disable Metrics/BlockLength
12   desc 'apt-key provider for apt_key resource'
13
14   confine    osfamily: :debian
15   defaultfor osfamily: :debian
16   commands   apt_key: 'apt-key'
17   commands   gpg: '/usr/bin/gpg'
18
19   def self.instances # rubocop:disable Metrics/AbcSize
20     key_array = []
21
22     cli_args = ['adv', '--no-tty', '--list-keys', '--with-colons', '--fingerprint', '--fixed-list-mode']
23
24     key_output = apt_key(cli_args).encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
25
26     pub_line = nil
27     fpr_lines = []
28     sub_lines = []
29
30     lines = key_output.split("\n")
31
32     lines.each_index do |i|
33       if lines[i].start_with?('pub')
34         pub_line = lines[i]
35         # starting a new public key, so reset fpr_lines and sub_lines
36         fpr_lines = []
37         sub_lines = []
38       elsif lines[i].start_with?('fpr')
39         fpr_lines << lines[i]
40       elsif lines[i].start_with?('sub')
41         sub_lines << lines[i]
42       end
43
44       next unless (pub_line && !fpr_lines.empty?) && (!lines[i + 1] || lines[i + 1].start_with?('pub'))
45
46       line_hash = key_line_hash(pub_line, fpr_lines)
47
48       expired = line_hash[:key_expired] || subkeys_all_expired(sub_lines)
49
50       key_array << new(
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],
56         ensure: :present,
57         expired: expired,
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'),
62       )
63     end
64     key_array
65   end
66
67   def self.prefetch(resources)
68     apt_keys = instances
69     resources.each_key do |name|
70       case name.length
71       when 40
72         provider = apt_keys.find { |key| key.fingerprint == name }
73         resources[name].provider = provider if provider
74       when 16
75         provider = apt_keys.find { |key| key.long == name }
76         resources[name].provider = provider if provider
77       when 8
78         provider = apt_keys.find { |key| key.short == name }
79         resources[name].provider = provider if provider
80       end
81     end
82   end
83
84   def self.subkeys_all_expired(sub_lines)
85     return false if sub_lines.empty?
86
87     sub_lines.each do |line|
88       return false if line.split(':')[1] == '-'
89     end
90     true
91   end
92
93   def self.key_line_hash(pub_line, fpr_lines)
94     pub_split = pub_line.split(':')
95     fpr_split = fpr_lines.first.split(':')
96
97     fingerprint = fpr_split.last
98     return_hash = {
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],
103       key_type: nil,
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)
107     }
108
109     # set key type based on types defined in /usr/share/doc/gnupg/DETAILS.gz
110     case pub_split[3]
111     when '1'
112       return_hash[:key_type] = :rsa
113     when '17'
114       return_hash[:key_type] = :dsa
115     when '18'
116       return_hash[:key_type] = :ecc
117     when '19'
118       return_hash[:key_type] = :ecdsa
119     end
120
121     return_hash
122   end
123
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)
128
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')
134       f.close
135       f
136     else
137       exceptions = [OpenURI::HTTPError]
138       exceptions << Net::FTPPermError if defined?(Net::FTPPermError)
139
140       begin
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
146                 else
147                   parsed_value.read
148                 end
149         else
150           user_pass = parsed_value.userinfo.split(':')
151           parsed_value.userinfo = ''
152           key = URI.open(parsed_value, http_basic_authentication: user_pass).read
153         end
154       rescue *exceptions => e
155         raise(_('%{_e} for %{_resource}') % { _e: e.message, _resource: resource[:source] })
156       rescue SocketError
157         raise(_('could not resolve %{_resource}') % { _resource: resource[:source] })
158       else
159         tempfile(key)
160       end
161     end
162   end
163
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')
169     file.write content
170     file.close
171     # confirm that the fingerprint from the file, matches the long key that is in the manifest
172     if name.size == 40
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
176
177         found_match = false
178         extracted_key.each_line do |line|
179           found_match = true if line.chomp == name
180         end
181         unless found_match
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
183         end
184       else
185         warning('/usr/bin/gpg cannot be found for verification of the id.')
186       end
187     end
188     file
189   end
190
191   def exists?
192     # report expired keys as non-existing when refresh => true
193     @property_hash[:ensure] == :present && !(resource[:refresh] && @property_hash[:expired])
194   end
195
196   def create
197     command = []
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.
211     else
212       raise(_('an unexpected condition occurred while trying to add the key: %{_resource}') % { _resource: resource[:id] })
213     end
214     apt_key(command)
215     @property_hash[:ensure] = :present
216   end
217
218   def destroy
219     loop do
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?
223     end
224     @property_hash.clear
225   end
226
227   def read_only(_value)
228     raise(_('This is a read-only property.'))
229   end
230
231   mk_resource_methods
232
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
240 end