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