(FM-7316) - i18n Process implemented and .pot file generated
[puppet-modules/puppetlabs-apt.git] / lib / puppet / provider / apt_key / apt_key.rb
1 require 'open-uri'
2 require 'net/ftp'
3 require 'tempfile'
4
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
11 end
12
13 Puppet::Type.type(:apt_key).provide(:apt_key) do
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
20     cli_args = ['adv', '--list-keys', '--with-colons', '--fingerprint', '--fixed-list-mode']
21
22     key_output = apt_key(cli_args).encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
23
24     pub_line, sub_line, fpr_line = nil
25
26     key_array = key_output.split("\n").map do |line|
27       if line.start_with?('pub')
28         pub_line = line
29         # reset fpr_line, to skip any previous subkeys which were collected
30         fpr_line = nil
31         sub_line = nil
32       elsif line.start_with?('sub')
33         sub_line = line
34       elsif line.start_with?('fpr')
35         fpr_line = line
36       end
37
38       if sub_line && fpr_line
39         sub_line, fpr_line = nil
40         next
41       end
42
43       next unless pub_line && fpr_line
44
45       line_hash = key_line_hash(pub_line, fpr_line)
46
47       # reset everything
48       pub_line, fpr_line = nil
49
50       expired = false
51
52       if line_hash[:key_expiry]
53         expired = Time.now >= line_hash[:key_expiry]
54       end
55
56       new(
57         name: line_hash[:key_fingerprint],
58         id: line_hash[:key_long],
59         fingerprint: line_hash[:key_fingerprint],
60         short: line_hash[:key_short],
61         long: line_hash[:key_long],
62         ensure: :present,
63         expired: expired,
64         expiry: line_hash[:key_expiry].nil? ? nil : line_hash[:key_expiry].strftime('%Y-%m-%d'),
65         size: line_hash[:key_size],
66         type: line_hash[:key_type],
67         created: line_hash[:key_created].strftime('%Y-%m-%d'),
68       )
69     end
70     key_array.compact!
71   end
72
73   def self.prefetch(resources)
74     apt_keys = instances
75     resources.each_key do |name|
76       if name.length == 40
77         provider = apt_keys.find { |key| key.fingerprint == name }
78         resources[name].provider = provider if provider
79       elsif name.length == 16
80         provider = apt_keys.find { |key| key.long == name }
81         resources[name].provider = provider if provider
82       elsif name.length == 8
83         provider = apt_keys.find { |key| key.short == name }
84         resources[name].provider = provider if provider
85       end
86     end
87   end
88
89   def self.key_line_hash(pub_line, fpr_line)
90     pub_split = pub_line.split(':')
91     fpr_split = fpr_line.split(':')
92
93     fingerprint = fpr_split.last
94     return_hash = {
95       key_fingerprint: fingerprint,
96       key_long: fingerprint[-16..-1], # last 16 characters of fingerprint
97       key_short: fingerprint[-8..-1], # last 8 characters of fingerprint
98       key_size: pub_split[2],
99       key_type: nil,
100       key_created: Time.at(pub_split[5].to_i),
101       key_expiry: pub_split[6].empty? ? nil : Time.at(pub_split[6].to_i),
102     }
103
104     # set key type based on types defined in /usr/share/doc/gnupg/DETAILS.gz
105     case pub_split[3]
106     when '1'
107       return_hash[:key_type] = :rsa
108     when '17'
109       return_hash[:key_type] = :dsa
110     when '18'
111       return_hash[:key_type] = :ecc
112     when '19'
113       return_hash[:key_type] = :ecdsa
114     end
115
116     return_hash
117   end
118
119   def source_to_file(value)
120     parsed_value = URI.parse(value)
121     if parsed_value.scheme.nil?
122       raise(_('The file %{_value} does not exist') % { _value: value }) unless File.exist?(value)
123       # Because the tempfile method has to return a live object to prevent GC
124       # of the underlying file from occuring too early, we also have to return
125       # a file object here.  The caller can still call the #path method on the
126       # closed file handle to get the path.
127       f = File.open(value, 'r')
128       f.close
129       f
130     else
131       begin
132         # Only send basic auth if URL contains userinfo
133         # Some webservers (e.g. Amazon S3) return code 400 if empty basic auth is sent
134         if parsed_value.userinfo.nil?
135           key = parsed_value.read
136         else
137           user_pass = parsed_value.userinfo.split(':')
138           parsed_value.userinfo = ''
139           key = open(parsed_value, http_basic_authentication: user_pass).read
140         end
141       rescue OpenURI::HTTPError, Net::FTPPermError => e
142         raise(_('%{_e} for %{_resource}') % { _e: e.message, _resource: resource[:source] })
143       rescue SocketError
144         raise(_('could not resolve %{_resource}') % { _resource: resource[:source] })
145       else
146         tempfile(key)
147       end
148     end
149   end
150
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')
156     file.write content
157     file.close
158     # confirm that the fingerprint from the file, matches the long key that is in the manifest
159     if name.size == 40
160       if File.executable? command(:gpg)
161         extracted_key = execute(["#{command(:gpg)} --with-fingerprint --with-colons #{file.path} | awk -F: '/^fpr:/ { print $10 }'"], failonfail: false)
162         extracted_key = extracted_key.chomp
163
164         found_match = false
165         extracted_key.each_line do |line|
166           if line.chomp == name
167             found_match = true
168           end
169         end
170         unless found_match
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.') % { _name: resource[:name] }) # rubocop:disable Metrics/LineLength
172         end
173       else
174         warning('/usr/bin/gpg cannot be found for verification of the id.')
175       end
176     end
177     file
178   end
179
180   def exists?
181     @property_hash[:ensure] == :present
182   end
183
184   def create
185     command = []
186     if resource[:source].nil? && resource[:content].nil?
187       # Breaking up the command like this is needed because it blows up
188       # if --recv-keys isn't the last argument.
189       command.push('adv', '--keyserver', resource[:server])
190       unless resource[:options].nil?
191         command.push('--keyserver-options', resource[:options])
192       end
193       command.push('--recv-keys', resource[:id])
194     elsif resource[:content]
195       key_file = tempfile(resource[:content])
196       command.push('add', key_file.path)
197     elsif resource[:source]
198       key_file = source_to_file(resource[:source])
199       command.push('add', key_file.path)
200     # In case we really screwed up, better safe than sorry.
201     else
202       raise(_('an unexpected condition occurred while trying to add the key: %{_resource}') % { _resource: resource[:id] })
203     end
204     apt_key(command)
205     @property_hash[:ensure] = :present
206   end
207
208   def destroy
209     loop do
210       apt_key('del', resource.provider.short)
211       r = execute(["#{command(:apt_key)} list | grep '/#{resource.provider.short}\s'"], failonfail: false)
212       break unless r.exitstatus.zero?
213     end
214     @property_hash.clear
215   end
216
217   def read_only(_value)
218     raise(_('This is a read-only property.'))
219   end
220
221   mk_resource_methods
222
223   # Needed until PUP-1470 is fixed and we can drop support for Puppet versions
224   # before that.
225   def expired
226     @property_hash[:expired]
227   end
228
229   # Alias the setters of read-only properties
230   # to the read_only function.
231   alias_method :created=, :read_only
232   alias_method :expired=, :read_only
233   alias_method :expiry=, :read_only
234   alias_method :size=, :read_only
235   alias_method :type=, :read_only
236 end