class Puppet::Provider::NameService::DirectoryService

Attributes

ds_path[W]

JJM: This allows us to pass information when calling

    Puppet::Type.type
e.g. Puppet::Type.type(:user).provide :directoryservice, :ds_path => "Users"
This is referenced in the get_ds_path class method

Public Class Methods

convert_binary_to_hash(plist_data) click to toggle source

This method will accept a binary plist (as a string) and convert it to a hash.

    # File lib/puppet/provider/nameservice/directoryservice.rb
272 def self.convert_binary_to_hash(plist_data)
273   Puppet.debug('Converting binary plist to hash')
274   Puppet::Util::Plist.parse_plist(plist_data)
275 end
convert_hash_to_binary(plist_data) click to toggle source

This method will accept a hash and convert it to a binary plist (string value).

    # File lib/puppet/provider/nameservice/directoryservice.rb
266 def self.convert_hash_to_binary(plist_data)
267   Puppet.debug('Converting plist hash to binary')
268   Puppet::Util::Plist.dump_plist(plist_data, :binary)
269 end
ds_to_ns_attribute_map() click to toggle source
   # File lib/puppet/provider/nameservice/directoryservice.rb
39 def self.ds_to_ns_attribute_map
40   {
41     'RecordName' => :name,
42     'PrimaryGroupID' => :gid,
43     'NFSHomeDirectory' => :home,
44     'UserShell' => :shell,
45     'UniqueID' => :uid,
46     'RealName' => :comment,
47     'Password' => :password,
48     'GeneratedUID' => :guid,
49     'IPAddress'    => :ip_address,
50     'ENetAddress'  => :en_address,
51     'GroupMembership' => :members,
52   }
53 end
generate_attribute_hash(input_hash, *type_properties) click to toggle source
    # File lib/puppet/provider/nameservice/directoryservice.rb
111 def self.generate_attribute_hash(input_hash, *type_properties)
112   attribute_hash = {}
113   input_hash.each_key do |key|
114     ds_attribute = key.sub("dsAttrTypeStandard:", "")
115     next unless (ds_to_ns_attribute_map.keys.include?(ds_attribute) and type_properties.include? ds_to_ns_attribute_map[ds_attribute])
116     ds_value = input_hash[key]
117     case ds_to_ns_attribute_map[ds_attribute]
118       when :members
119         ds_value = ds_value # only members uses arrays so far
120       when :gid, :uid
121         # OS X stores objects like uid/gid as strings.
122         # Try casting to an integer for these cases to be
123         # consistent with the other providers and the group type
124         # validation
125         begin
126           ds_value = Integer(ds_value[0])
127         rescue ArgumentError
128           ds_value = ds_value[0]
129         end
130       else ds_value = ds_value[0]
131     end
132     attribute_hash[ds_to_ns_attribute_map[ds_attribute]] = ds_value
133   end
134 
135   # NBK: need to read the existing password here as it's not actually
136   # stored in the user record. It is stored at a path that involves the
137   # UUID of the user record for non-Mobile local accounts.
138   # Mobile Accounts are out of scope for this provider for now
139   attribute_hash[:password] = self.get_password(attribute_hash[:guid], attribute_hash[:name]) if @resource_type.validproperties.include?(:password) and Puppet.features.root?
140   attribute_hash
141 end
get_ds_path() click to toggle source
   # File lib/puppet/provider/nameservice/directoryservice.rb
82 def self.get_ds_path
83   # JJM: 2007-07-24 This method dynamically returns the DS path we're concerned with.
84   #      For example, if we're working with an user type, this will be /Users
85   #      with a group type, this will be /Groups.
86   #   @ds_path is an attribute of the class itself.
87   return @ds_path if defined?(@ds_path)
88   # JJM: "Users" or "Groups" etc ...  (Based on the Puppet::Type)
89   #       Remember this is a class method, so self.class is Class
90   #       Also, @resource_type seems to be the reference to the
91   #       Puppet::Type this class object is providing for.
92   @resource_type.name.to_s.capitalize + "s"
93 end
get_exec_preamble(ds_action, resource_name = nil) click to toggle source
    # File lib/puppet/provider/nameservice/directoryservice.rb
168 def self.get_exec_preamble(ds_action, resource_name = nil)
169   # JJM 2007-07-24
170   #     DSCL commands are often repetitive and contain the same positional
171   #     arguments over and over. See https://developer.apple.com/documentation/Porting/Conceptual/PortingUnix/additionalfeatures/chapter_10_section_9.html
172   #     for an example of what I mean.
173   #     This method spits out proper DSCL commands for us.
174   #     We EXPECT name to be @resource[:name] when called from an instance object.
175 
176   command_vector = [ command(:dscl), "-plist", "." ]
177 
178   # JJM: The actual action to perform. See "man dscl".
179   #      Common actions: -create, -delete, -merge, -append, -passwd
180   command_vector << ds_action
181   # JJM: get_ds_path will spit back "Users" or "Groups",
182   # etc...  Depending on the Puppet::Type of our self.
183   if resource_name
184     command_vector << "/#{get_ds_path}/#{resource_name}"
185   else
186     command_vector << "/#{get_ds_path}"
187   end
188   # JJM:  This returns most of the preamble of the command.
189   #       e.g. 'dscl / -create /Users/mccune'
190   command_vector
191 end
get_password(guid, username) click to toggle source
    # File lib/puppet/provider/nameservice/directoryservice.rb
240 def self.get_password(guid, username)
241   plist_file = "#{users_plist_dir}/#{username}.plist"
242   if Puppet::FileSystem.exist?(plist_file)
243     # If a plist exists in /var/db/dslocal/nodes/Default/users, we will
244     # extract the binary plist from the 'ShadowHashData' key, decode the
245     # salted-SHA512 password hash, and then return it.
246     users_plist = Puppet::Util::Plist.read_plist_file(plist_file)
247 
248     if users_plist['ShadowHashData']
249       # users_plist['ShadowHashData'][0] is actually a binary plist
250       # that's nested INSIDE the user's plist (which itself is a binary
251       # plist).
252       password_hash_plist = users_plist['ShadowHashData'][0]
253       converted_hash_plist = convert_binary_to_hash(password_hash_plist)
254 
255       # converted_hash_plist['SALTED-SHA512'] is a Base64 encoded
256       # string. The password_hash provided as a resource attribute is a
257       # hex value. We need to convert the Base64 encoded string to a
258       # hex value and provide it back to Puppet.
259       password_hash = converted_hash_plist['SALTED-SHA512'].unpack("H*")[0]
260       password_hash
261     end
262   end
263 end
instances() click to toggle source
   # File lib/puppet/provider/nameservice/directoryservice.rb
69 def self.instances
70   # JJM Class method that provides an array of instance objects of this
71   #     type.
72   # JJM: Properties are dependent on the Puppet::Type we're managing.
73   type_property_array = [:name] + @resource_type.validproperties
74 
75   # Create a new instance of this Puppet::Type for each object present
76   #    on the system.
77   list_all_present.collect do |name_string|
78     self.new(single_report(name_string, *type_property_array))
79   end
80 end
list_all_present() click to toggle source
    # File lib/puppet/provider/nameservice/directoryservice.rb
 95 def self.list_all_present
 96   @all_present ||= begin
 97     # JJM: List all objects of this Puppet::Type already present on the system.
 98     begin
 99       dscl_output = execute(get_exec_preamble("-list"))
100     rescue Puppet::ExecutionFailure
101       fail(_("Could not get %{resource} list from DirectoryService") % { resource: @resource_type.name })
102     end
103     dscl_output.split("\n")
104   end
105 end
next_system_id(id_type, min_id=20) click to toggle source

Unlike most other *nixes, OS X doesn't provide built in functionality for automatically assigning uids and gids to accounts, so we set up these methods for consumption by functionality like –mkusers By default we restrict to a reasonably sane range for system accounts

    # File lib/puppet/provider/nameservice/directoryservice.rb
281 def self.next_system_id(id_type, min_id=20)
282   dscl_args = ['.', '-list']
283   if id_type == 'uid'
284     dscl_args << '/Users' << 'uid'
285   elsif id_type == 'gid'
286     dscl_args << '/Groups' << 'gid'
287   else
288     fail(_("Invalid id_type %{id_type}. Only 'uid' and 'gid' supported") % { id_type: id_type })
289   end
290   dscl_out = dscl(dscl_args)
291   # We're ok with throwing away negative uids here.
292   ids = dscl_out.split.compact.collect { |l| l.to_i if l =~ /^\d+$/ }
293   ids.compact!.sort! { |a,b| a.to_f <=> b.to_f }
294   # We're just looking for an unused id in our sorted array.
295   ids.each_index do |i|
296     next_id = ids[i] + 1
297     return next_id if ids[i+1] != next_id and next_id >= min_id
298   end
299 end
ns_to_ds_attribute_map() click to toggle source
   # File lib/puppet/provider/nameservice/directoryservice.rb
57 def self.ns_to_ds_attribute_map
58   @ns_to_ds_attribute_map ||= ds_to_ns_attribute_map.invert
59 end
parse_dscl_plist_data(dscl_output) click to toggle source
    # File lib/puppet/provider/nameservice/directoryservice.rb
107 def self.parse_dscl_plist_data(dscl_output)
108   Puppet::Util::Plist.parse_plist(dscl_output)
109 end
password_hash_dir() click to toggle source
   # File lib/puppet/provider/nameservice/directoryservice.rb
61 def self.password_hash_dir
62   '/var/db/shadow/hash'
63 end
post_resource_eval() click to toggle source

There is no generalized mechanism for provider cache management, but we can use post_resource_eval, which will be run for each suitable provider at the end of each transaction. Use this to clear @all_present after each run.

   # File lib/puppet/provider/nameservice/directoryservice.rb
28 def self.post_resource_eval
29   @all_present = nil
30 end
set_password(resource_name, guid, password_hash) click to toggle source
    # File lib/puppet/provider/nameservice/directoryservice.rb
193 def self.set_password(resource_name, guid, password_hash)
194   # 10.7 uses salted SHA512 password hashes which are 128 characters plus
195   # an 8 character salt. Previous versions used a SHA1 hash padded with
196   # zeroes. If someone attempts to use a password hash that worked with
197   # a previous version of OS X, we will fail early and warn them.
198   if password_hash.length != 136
199     #TRANSLATORS 'OS X 10.7' is an operating system and should not be translated, 'Salted SHA512' is the name of a hashing algorithm
200     fail(_("OS X 10.7 requires a Salted SHA512 hash password of 136 characters.") +
201          ' ' + _("Please check your password and try again."))
202   end
203 
204   plist_file = "#{users_plist_dir}/#{resource_name}.plist"
205   if Puppet::FileSystem.exist?(plist_file)
206     # If a plist already exists in /var/db/dslocal/nodes/Default/users, then
207     # we will need to extract the binary plist from the 'ShadowHashData'
208     # key, log the new password into the resultant plist's 'SALTED-SHA512'
209     # key, and then save the entire structure back.
210     users_plist = Puppet::Util::Plist.read_plist_file(plist_file)
211 
212     # users_plist['ShadowHashData'][0] is actually a binary plist
213     # that's nested INSIDE the user's plist (which itself is a binary
214     # plist). If we encounter a user plist that DOESN'T have a
215     # ShadowHashData field, create one.
216     if users_plist['ShadowHashData']
217       password_hash_plist = users_plist['ShadowHashData'][0]
218       converted_hash_plist = convert_binary_to_hash(password_hash_plist)
219     else
220       users_plist['ShadowHashData'] = ''
221       converted_hash_plist = {'SALTED-SHA512' => ''}
222     end
223 
224     # converted_hash_plist['SALTED-SHA512'] expects a Base64 encoded
225     # string. The password_hash provided as a resource attribute is a
226     # hex value. We need to convert the provided hex value to a Base64
227     # encoded string to nest it in the converted hash plist.
228     converted_hash_plist['SALTED-SHA512'] = \
229       password_hash.unpack('a2'*(password_hash.size/2)).collect { |i| i.hex.chr }.join
230 
231     # Finally, we can convert the nested plist back to binary, embed it
232     # into the user's plist, and convert the resultant plist back to
233     # a binary plist.
234     changed_plist = convert_hash_to_binary(converted_hash_plist)
235     users_plist['ShadowHashData'][0] = changed_plist
236     Puppet::Util::Plist.write_plist_file(users_plist, plist_file, :binary)
237   end
238 end
single_report(resource_name, *type_properties) click to toggle source
    # File lib/puppet/provider/nameservice/directoryservice.rb
143 def self.single_report(resource_name, *type_properties)
144   # JJM 2007-07-24:
145   #     Given a the name of an object and a list of properties of that
146   #     object, return all property values in a hash.
147   #
148   #     This class method returns nil if the object doesn't exist
149   #     Otherwise, it returns a hash of the object properties.
150 
151   all_present_str_array = list_all_present
152 
153   # NBK: shortcut the process if the resource is missing
154   return nil unless all_present_str_array.include? resource_name
155 
156   dscl_vector = get_exec_preamble("-read", resource_name)
157   begin
158     dscl_output = execute(dscl_vector)
159   rescue Puppet::ExecutionFailure
160     fail(_("Could not get report.  command execution failed."))
161   end
162 
163   dscl_plist = self.parse_dscl_plist_data(dscl_output)
164 
165   self.generate_attribute_hash(dscl_plist, *type_properties)
166 end
users_plist_dir() click to toggle source
   # File lib/puppet/provider/nameservice/directoryservice.rb
65 def self.users_plist_dir
66   '/var/db/dslocal/nodes/Default/users'
67 end

Public Instance Methods

add_members(current_members, new_members) click to toggle source
    # File lib/puppet/provider/nameservice/directoryservice.rb
452 def add_members(current_members, new_members)
453   new_members.flatten.each do |new_member|
454     if current_members.nil? or not current_members.include?(new_member)
455       cmd = [:dseditgroup, "-o", "edit", "-n", ".", "-a", new_member, @resource[:name]]
456       begin
457         execute(cmd)
458       rescue Puppet::ExecutionFailure => detail
459         fail(_("Could not add %{new_member} to group: %{name}, %{detail}") % { new_member: new_member, name: @resource.name, detail: detail })
460       end
461     end
462   end
463 end
create() click to toggle source

NBK: we override @parent.create as we need to execute a series of commands to create objects with dscl, rather than the single command nameservice.rb expects to be returned by addcmd. Thus we don't bother defining addcmd.

    # File lib/puppet/provider/nameservice/directoryservice.rb
377 def create
378   if exists?
379     info _("already exists")
380     return nil
381   end
382 
383   # NBK: First we create the object with a known guid so we can set the contents
384   # of the password hash if required
385   # Shelling out sucks, but for a single use case it doesn't seem worth
386   # requiring people install a UUID library that doesn't come with the system.
387   # This should be revisited if Puppet starts managing UUIDs for other platform
388   # user records.
389   guid = %x{/usr/bin/uuidgen}.chomp
390 
391   exec_arg_vector = self.class.get_exec_preamble("-create", @resource[:name])
392   exec_arg_vector << ns_to_ds_attribute_map[:guid] << guid
393   begin
394     execute(exec_arg_vector)
395   rescue Puppet::ExecutionFailure => detail
396     fail(_("Could not set GeneratedUID for %{resource} %{name}: %{detail}") % { resource: @resource.class.name, name: @resource.name, detail: detail })
397   end
398 
399   value = @resource.should(:password)
400   if value && value != ""
401     self.class.set_password(@resource[:name], guid, value)
402   end
403 
404   # Now we create all the standard properties
405   Puppet::Type.type(@resource.class.name).validproperties.each do |property|
406     next if property == :ensure
407     value = @resource.should(property)
408     if property == :gid and value.nil?
409       value = self.class.next_system_id('gid')
410     end
411     if property == :uid and value.nil?
412       value = self.class.next_system_id('uid')
413     end
414     if value != "" and not value.nil?
415       if property == :members
416         add_members(nil, value)
417       else
418         exec_arg_vector = self.class.get_exec_preamble("-create", @resource[:name])
419         exec_arg_vector << ns_to_ds_attribute_map[property.intern]
420         next if property == :password  # skip setting the password here
421         exec_arg_vector << value.to_s
422         begin
423           execute(exec_arg_vector)
424         rescue Puppet::ExecutionFailure => detail
425           fail(_("Could not create %{resource} %{name}: %{detail}") % { resource: @resource.class.name, name: @resource.name, detail: detail })
426         end
427       end
428     end
429   end
430 end
deletecmd() click to toggle source
    # File lib/puppet/provider/nameservice/directoryservice.rb
465 def deletecmd
466   # JJM: Like addcmd, only called when deleting the object itself
467   #    Note, this isn't used to delete properties of the object,
468   #    at least that's how I understand it...
469   self.class.get_exec_preamble("-delete", @resource[:name])
470 end
ds_to_ns_attribute_map() click to toggle source

JJM 2007-07-25: This map is used to map NameService attributes to their

corresponding DirectoryService attribute names.
See: http://images.apple.com/server/docs.Open_Directory_v10.4.pdf

JJM: Note, this is de-coupled from the Puppet::Type, and must

be actively maintained.  There may also be collisions with different
types (Users, Groups, Mounts, Hosts, etc...)
   # File lib/puppet/provider/nameservice/directoryservice.rb
38 def ds_to_ns_attribute_map; self.class.ds_to_ns_attribute_map; end
ensure=(ensure_value) click to toggle source
Calls superclass method
    # File lib/puppet/provider/nameservice/directoryservice.rb
302 def ensure=(ensure_value)
303   super
304   # We need to loop over all valid properties for the type we're
305   # managing and call the method which sets that property value
306   # dscl can't create everything at once unfortunately.
307   if ensure_value == :present
308     @resource.class.validproperties.each do |name|
309       next if name == :ensure
310       # LAK: We use property.sync here rather than directly calling
311       # the settor method because the properties might do some kind
312       # of conversion.  In particular, the user gid property might
313       # have a string and need to convert it to a number
314       if @resource.should(name)
315         @resource.property(name).sync
316       else
317         value = autogen(name)
318         if value
319           self.send(name.to_s + "=", value)
320         else
321           next
322         end
323       end
324     end
325   end
326 end
getinfo(refresh = false) click to toggle source
    # File lib/puppet/provider/nameservice/directoryservice.rb
472 def getinfo(refresh = false)
473   # JJM 2007-07-24:
474   #      Override the getinfo method, which is also defined in nameservice.rb
475   #      This method returns and sets @infohash
476   # I'm not re-factoring the name "getinfo" because this method will be
477   # most likely called by nameservice.rb, which I didn't write.
478   if refresh or (! defined?(@property_value_cache_hash) or ! @property_value_cache_hash)
479     # JJM 2007-07-24: OK, there's a bit of magic that's about to
480     # happen... Let's see how strong my grip has become... =)
481     #
482     # self is a provider instance of some Puppet::Type, like
483     # Puppet::Type::User::ProviderDirectoryservice for the case of the
484     # user type and this provider.
485     #
486     # self.class looks like "user provider directoryservice", if that
487     # helps you ...
488     #
489     # self.class.resource_type is a reference to the Puppet::Type class,
490     # probably Puppet::Type::User or Puppet::Type::Group, etc...
491     #
492     # self.class.resource_type.validproperties is a class method,
493     # returning an Array of the valid properties of that specific
494     # Puppet::Type.
495     #
496     # So... something like [:comment, :home, :password, :shell, :uid,
497     # :groups, :ensure, :gid]
498     #
499     # Ultimately, we add :name to the list, delete :ensure from the
500     # list, then report on the remaining list. Pretty whacky, ehh?
501     type_properties = [:name] + self.class.resource_type.validproperties
502     type_properties.delete(:ensure) if type_properties.include? :ensure
503     type_properties << :guid  # append GeneratedUID so we just get the report here
504     @property_value_cache_hash = self.class.single_report(@resource[:name], *type_properties)
505     [:uid, :gid].each do |param|
506       @property_value_cache_hash[param] = @property_value_cache_hash[param].to_i if @property_value_cache_hash and @property_value_cache_hash.include?(param)
507     end
508   end
509   @property_value_cache_hash
510 end
ns_to_ds_attribute_map() click to toggle source

JJM The same table as above, inverted.

   # File lib/puppet/provider/nameservice/directoryservice.rb
56 def ns_to_ds_attribute_map; self.class.ns_to_ds_attribute_map end
password=(passphrase) click to toggle source
    # File lib/puppet/provider/nameservice/directoryservice.rb
328 def password=(passphrase)
329   exec_arg_vector = self.class.get_exec_preamble("-read", @resource.name)
330   exec_arg_vector << ns_to_ds_attribute_map[:guid]
331   begin
332     guid_output = execute(exec_arg_vector)
333     guid_plist = Puppet::Util::Plist.parse_plist(guid_output)
334     # Although GeneratedUID like all DirectoryService values can be multi-valued
335     # according to the schema, in practice user accounts cannot have multiple UUIDs
336     # otherwise Bad Things Happen, so we just deal with the first value.
337     guid = guid_plist["dsAttrTypeStandard:#{ns_to_ds_attribute_map[:guid]}"][0]
338     self.class.set_password(@resource.name, guid, passphrase)
339   rescue Puppet::ExecutionFailure => detail
340     fail(_("Could not set %{param} on %{resource}[%{name}]: %{detail}") % { param: param, resource: @resource.class.name, name: @resource.name, detail: detail })
341   end
342 end
remove_unwanted_members(current_members, new_members) click to toggle source
    # File lib/puppet/provider/nameservice/directoryservice.rb
432 def remove_unwanted_members(current_members, new_members)
433   current_members.each do |member|
434     if not new_members.flatten.include?(member)
435       cmd = [:dseditgroup, "-o", "edit", "-n", ".", "-d", member, @resource[:name]]
436       begin
437         execute(cmd)
438       rescue Puppet::ExecutionFailure
439         # TODO: We're falling back to removing the member using dscl due to rdar://8481241
440         # This bug causes dseditgroup to fail to remove a member if that member doesn't exist
441         cmd = [:dscl, ".", "-delete", "/Groups/#{@resource.name}", "GroupMembership", member]
442         begin
443           execute(cmd)
444         rescue Puppet::ExecutionFailure => detail
445           fail(_("Could not remove %{member} from group: %{resource}, %{detail}") % { member: member, resource: @resource.name, detail: detail })
446         end
447       end
448     end
449   end
450 end
set(param, value) click to toggle source

NBK: we override @parent.set as we need to execute a series of commands to deal with array values, rather than the single command nameservice.rb expects to be returned by modifycmd. Thus we don't bother defining modifycmd.

    # File lib/puppet/provider/nameservice/directoryservice.rb
348 def set(param, value)
349   self.class.validate(param, value)
350   current_members = @property_value_cache_hash[:members]
351   if param == :members
352     # If we are meant to be authoritative for the group membership
353     # then remove all existing members who haven't been specified
354     # in the manifest.
355     remove_unwanted_members(current_members, value) if @resource[:auth_membership] and not current_members.nil?
356 
357     # if they're not a member, make them one.
358     add_members(current_members, value)
359   else
360     exec_arg_vector = self.class.get_exec_preamble("-create", @resource[:name])
361     # JJM: The following line just maps the NS name to the DS name
362     #      e.g. { :uid => 'UniqueID' }
363     exec_arg_vector << ns_to_ds_attribute_map[param.intern]
364     # JJM: The following line sends the actual value to set the property to
365     exec_arg_vector << value.to_s
366     begin
367       execute(exec_arg_vector)
368     rescue Puppet::ExecutionFailure => detail
369       fail(_("Could not set %{param} on %{resource}[%{name}]: %{detail}") % { param: param, resource: @resource.class.name, name: @resource.name, detail: detail })
370     end
371   end
372 end