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