(FM-7318) - Added Puppet Strings formatting to documentation
[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   desc 'apt-key provider for apt_key resource'
15
16   confine    osfamily: :debian
17   defaultfor osfamily: :debian
18   commands   apt_key: 'apt-key'
19   commands   gpg: '/usr/bin/gpg'
20
21   def self.instances
22     cli_args = ['adv', '--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, sub_line, fpr_line = nil
27
28     key_array = key_output.split("\n").map do |line|
29       if line.start_with?('pub')
30         pub_line = line
31         # reset fpr_line, to skip any previous subkeys which were collected
32         fpr_line = nil
33         sub_line = nil
34       elsif line.start_with?('sub')
35         sub_line = line
36       elsif line.start_with?('fpr')
37         fpr_line = line
38       end
39
40       if sub_line && fpr_line
41         sub_line, fpr_line = nil
42         next
43       end
44
45       next unless pub_line && fpr_line
46
47       line_hash = key_line_hash(pub_line, fpr_line)
48
49       # reset everything
50       pub_line, fpr_line = nil
51
52       expired = false
53
54       if line_hash[:key_expiry]
55         expired = Time.now >= line_hash[:key_expiry]
56       end
57
58       new(
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],
64         ensure: :present,
65         expired: expired,
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'),
70       )
71     end
72     key_array.compact!
73   end
74
75   def self.prefetch(resources)
76     apt_keys = instances
77     resources.each_key do |name|
78       if name.length == 40
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
87       end
88     end
89   end
90
91   def self.key_line_hash(pub_line, fpr_line)
92     pub_split = pub_line.split(':')
93     fpr_split = fpr_line.split(':')
94
95     fingerprint = fpr_split.last
96     return_hash = {
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],
101       key_type: nil,
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),
104     }
105
106     # set key type based on types defined in /usr/share/doc/gnupg/DETAILS.gz
107     case pub_split[3]
108     when '1'
109       return_hash[:key_type] = :rsa
110     when '17'
111       return_hash[:key_type] = :dsa
112     when '18'
113       return_hash[:key_type] = :ecc
114     when '19'
115       return_hash[:key_type] = :ecdsa
116     end
117
118     return_hash
119   end
120
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") 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')
130       f.close
131       f
132     else
133       begin
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
138         else
139           user_pass = parsed_value.userinfo.split(':')
140           parsed_value.userinfo = ''
141           key = open(parsed_value, http_basic_authentication: user_pass).read
142         end
143       rescue OpenURI::HTTPError, Net::FTPPermError => e
144         raise("#{e.message} for #{resource[:source]}")
145       rescue SocketError
146         raise("could not resolve #{resource[:source]}")
147       else
148         tempfile(key)
149       end
150     end
151   end
152
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')
158     file.write content
159     file.close
160     # confirm that the fingerprint from the file, matches the long key that is in the manifest
161     if name.size == 40
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
165
166         found_match = false
167         extracted_key.each_line do |line|
168           if line.chomp == name
169             found_match = true
170           end
171         end
172         unless found_match
173           raise("The id in your manifest #{resource[:name]} and the fingerprint from content/source don't match. Check for an error in the id and content/source is legitimate.")
174         end
175       else
176         warning('/usr/bin/gpg cannot be found for verification of the id.')
177       end
178     end
179     file
180   end
181
182   def exists?
183     @property_hash[:ensure] == :present
184   end
185
186   def create
187     command = []
188     if resource[:source].nil? && resource[:content].nil?
189       # Breaking up the command like this is needed because it blows up
190       # if --recv-keys isn't the last argument.
191       command.push('adv', '--keyserver', resource[:server])
192       unless resource[:options].nil?
193         command.push('--keyserver-options', resource[:options])
194       end
195       command.push('--recv-keys', resource[:id])
196     elsif resource[:content]
197       key_file = tempfile(resource[:content])
198       command.push('add', key_file.path)
199     elsif resource[:source]
200       key_file = source_to_file(resource[:source])
201       command.push('add', key_file.path)
202     # In case we really screwed up, better safe than sorry.
203     else
204       raise("an unexpected condition occurred while trying to add the key: #{resource[:id]}")
205     end
206     apt_key(command)
207     @property_hash[:ensure] = :present
208   end
209
210   def destroy
211     loop do
212       apt_key('del', resource.provider.short)
213       r = execute(["#{command(:apt_key)} list | grep '/#{resource.provider.short}\s'"], failonfail: false)
214       break unless r.exitstatus.zero?
215     end
216     @property_hash.clear
217   end
218
219   def read_only(_value)
220     raise('This is a read-only property.')
221   end
222
223   mk_resource_methods
224
225   # Needed until PUP-1470 is fixed and we can drop support for Puppet versions
226   # before that.
227   def expired
228     @property_hash[:expired]
229   end
230
231   # Alias the setters of read-only properties
232   # to the read_only function.
233   alias_method :created=, :read_only
234   alias_method :expired=, :read_only
235   alias_method :expiry=, :read_only
236   alias_method :size=, :read_only
237   alias_method :type=, :read_only
238 end