687c99502efb8e0bdd5e630ceefa4113609d307f
[puppet-modules/puppetlabs-apt.git] / lib / puppet / provider / apt_key / apt_key.rb
1 require 'date'
2 require 'open-uri'
3 require 'net/ftp'
4 require 'tempfile'
5
6 if RUBY_VERSION == '1.8.7'
7   # Mothers cry, puppies die and Ruby 1.8.7's open-uri needs to be
8   # monkeypatched to support passing in :ftp_passive_mode.
9   require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..',
10                                     'puppet_x', 'apt_key', 'patch_openuri.rb'))
11   OpenURI::Options.merge!({:ftp_active_mode => false,})
12 end
13
14 Puppet::Type.type(:apt_key).provide(:apt_key) do
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']
23
24     if RUBY_VERSION > '1.8.7'
25       key_output = apt_key(cli_args).encode('UTF-8', 'binary', :invalid => :replace, :undef => :replace, :replace => '')
26     else
27       key_output = apt_key(cli_args)
28     end
29
30     pub_line, fpr_line = nil
31
32     key_array = key_output.split("\n").collect do |line|
33       if line.start_with?('pub')
34           pub_line = line
35       elsif line.start_with?('fpr')
36           fpr_line = line
37       end
38
39       next unless (pub_line and fpr_line)
40
41       line_hash = key_line_hash(pub_line, fpr_line)
42
43       # reset everything
44       pub_line, fpr_line = nil
45
46       expired = false
47
48       if line_hash[:key_expiry]
49         expired = Date.today > Date.parse(line_hash[:key_expiry])
50       end
51
52       new(
53         :name        => line_hash[:key_fingerprint],
54         :id          => line_hash[:key_long],
55         :fingerprint => line_hash[:key_fingerprint],
56         :short       => line_hash[:key_short],
57         :long        => line_hash[:key_long],
58         :ensure      => :present,
59         :expired     => expired,
60         :expiry      => line_hash[:key_expiry],
61         :size        => line_hash[:key_size],
62         :type        => line_hash[:key_type],
63         :created     => line_hash[:key_created]
64       )
65     end
66     key_array.compact!
67   end
68
69   def self.prefetch(resources)
70     apt_keys = instances
71     resources.keys.each do |name|
72       if name.length == 40
73         if provider = apt_keys.find{ |key| key.fingerprint == name }
74           resources[name].provider = provider
75         end
76       elsif name.length == 16
77         if provider = apt_keys.find{ |key| key.long == name }
78           resources[name].provider = provider
79         end
80       elsif name.length == 8
81         if provider = apt_keys.find{ |key| key.short == name }
82           resources[name].provider = provider
83         end
84       end
85     end
86   end
87
88   def self.key_line_hash(pub_line, fpr_line)
89     pub_split = pub_line.split(':')
90     fpr_split = fpr_line.split(':')
91
92     fingerprint = fpr_split.last
93     return_hash = {
94       :key_fingerprint => fingerprint,
95       :key_long        => fingerprint[-16..-1], # last 16 characters of fingerprint
96       :key_short       => fingerprint[-8..-1], # last 8 characters of fingerprint
97       :key_size        => pub_split[2],
98       :key_type        => nil,
99       :key_created     => pub_split[5],
100       :key_expiry      => pub_split[6].empty? ? nil : pub_split[6],
101     }
102
103     # set key type based on types defined in /usr/share/doc/gnupg/DETAILS.gz
104     case pub_split[3]
105     when "1"
106       return_hash[:key_type] = :rsa
107     when "17"
108       return_hash[:key_type] = :dsa
109     when "18"
110       return_hash[:key_type] = :ecc
111     when "19"
112       return_hash[:key_type] = :ecdsa
113     end
114
115     return return_hash
116   end
117
118   def source_to_file(value)
119     parsedValue = URI::parse(value)
120     if parsedValue.scheme.nil?
121       fail("The file #{value} does not exist") unless File.exists?(value)
122       value
123     else
124       begin
125         key = parsedValue.read
126       rescue OpenURI::HTTPError, Net::FTPPermError => e
127         fail("#{e.message} for #{resource[:source]}")
128       rescue SocketError
129         fail("could not resolve #{resource[:source]}")
130       else
131         tempfile(key)
132       end
133     end
134   end
135
136   def tempfile(content)
137     file = Tempfile.new('apt_key')
138     file.write content
139     file.close
140     #confirm that the fingerprint from the file, matches the long key that is in the manifest
141     if name.size == 40
142       if File.executable? command(:gpg)
143         extracted_key = execute(["#{command(:gpg)} --with-fingerprint --with-colons #{file.path} | awk -F: '/^fpr:/ { print $10 }'"], :failonfail => false)
144         extracted_key = extracted_key.chomp
145         if extracted_key != name
146           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.")
147         end
148       else
149         warning ('/usr/bin/gpg cannot be found for verification of the id.')
150       end 
151     end
152     file.path
153   end
154
155   def exists?
156     @property_hash[:ensure] == :present
157   end
158
159   def create
160     command = []
161     if resource[:source].nil? and resource[:content].nil?
162       # Breaking up the command like this is needed because it blows up
163       # if --recv-keys isn't the last argument.
164       command.push('adv', '--keyserver', resource[:server])
165       unless resource[:keyserver_options].nil?
166         command.push('--keyserver-options', resource[:keyserver_options])
167       end
168       command.push('--recv-keys', resource[:id])
169     elsif resource[:content]
170       command.push('add', tempfile(resource[:content]))
171     elsif resource[:source]
172       command.push('add', source_to_file(resource[:source]))
173     # In case we really screwed up, better safe than sorry.
174     else
175       fail("an unexpected condition occurred while trying to add the key: #{resource[:id]}")
176     end
177     apt_key(command)
178     @property_hash[:ensure] = :present
179   end
180
181   def destroy
182     begin
183       apt_key('del', resource.provider.short)
184       r = execute(["#{command(:apt_key)} list | grep '/#{resource.provider.short}\s'"], :failonfail => false)
185     end while r.exitstatus == 0
186     @property_hash.clear
187   end
188
189   def read_only(value)
190     fail('This is a read-only property.')
191   end
192
193   mk_resource_methods
194
195   # Needed until PUP-1470 is fixed and we can drop support for Puppet versions
196   # before that.
197   def expired
198     @property_hash[:expired]
199   end
200
201   # Alias the setters of read-only properties
202   # to the read_only function.
203   alias :created= :read_only
204   alias :expired= :read_only
205   alias :expiry=  :read_only
206   alias :size=    :read_only
207   alias :type=    :read_only
208 end