Class: Chef::Provider::User::Dscl

Inherits:
Chef::Provider::User show all
Defined in:
lib/chef/provider/user/dscl.rb

Overview

The most tricky bit of this provider is the way it deals with user passwords. Mac OS X has different password shadow calculations based on the version. < 10.7 => password shadow calculation format SALTED-SHA1

=> stored in: /var/db/shadow/hash/#{guid}
=> shadow binary length 68 bytes
=> First 4 bytes salt / Next 64 bytes shadow value

10.7 => password shadow calculation format SALTED-SHA512

=> stored in: /var/db/dslocal/nodes/Default/users/#{name}.plist
=> shadow binary length 68 bytes
=> First 4 bytes salt / Next 64 bytes shadow value

> 10.7 => password shadow calculation format SALTED-SHA512-PBKDF2

=> stored in: /var/db/dslocal/nodes/Default/users/#{name}.plist
=> shadow binary length 128 bytes
=> Salt / Iterations are stored separately in the same file

This provider only supports Mac OSX versions 10.7 and above

Constant Summary collapse

STAFF_GROUP_ID =

Just-in-case a recipe calls the user dscl provider without specifying a gid property. Avoids chown issues in move_home when the manage_home property is in use. #5393

20
DSCL_PROPERTY_MAP =

A simple map of Chef’s terms to DSCL’s terms.

{
  uid: "uid",
  gid: "gid",
  home: "home",
  shell: "shell",
  comment: "realname",
  password: "passwd",
  auth_authority: "authentication_authority",
  shadow_hash: "ShadowHashData",
}.freeze
USER_PLIST_DIRECTORY =

Directory where the user plist files are stored for versions 10.7 and above

"/var/db/dslocal/nodes/Default/users".freeze

Instance Attribute Summary collapse

Attributes inherited from Chef::Provider::User

#locked, #user_exists

Attributes inherited from Chef::Provider

#action, #current_resource, #logger, #new_resource, #recipe_name, #run_context

Instance Method Summary collapse

Methods inherited from Chef::Provider::User

#action_create, #action_lock, #action_manage, #action_modify, #action_remove, #action_unlock, #compare_user, #convert_group_name, #initialize

Methods inherited from Chef::Provider

action, #action_nothing, #check_resource_semantics!, #cleanup_after_converge, #compile_and_converge_action, #converge_by, #converge_if_changed, #cookbook_name, #description, #events, include_resource_dsl?, include_resource_dsl_module, #initialize, #introduced, #node, #process_resource_requirements, provides, provides?, #requirements, #resource_collection, #resource_updated?, #run_action, #set_updated_status, supports?, use_inline_resources, #whyrun_mode?, #whyrun_supported?

Methods included from Mixin::Provides

#provided_as, #provides, #provides?

Methods included from Mixin::DescendantsTracker

#descendants, descendants, direct_descendants, #direct_descendants, find_descendants_by_name, #find_descendants_by_name, #inherited, store_inherited

Methods included from Mixin::LazyModuleInclude

#descendants, #include, #included

Methods included from Mixin::NotifyingBlock

#notifying_block, #subcontext_block

Methods included from DSL::DeclareResource

#build_resource, #declare_resource, #delete_resource, #delete_resource!, #edit_resource, #edit_resource!, #find_resource, #find_resource!, #resources, #with_run_context

Methods included from Mixin::ShellOut

#a_to_s, #clean_array, #shell_out, #shell_out!, #shell_out_compact, #shell_out_compact!, #shell_out_compact_timeout, #shell_out_compact_timeout!, #shell_out_with_systems_locale, #shell_out_with_systems_locale!

Methods included from Mixin::PathSanity

#enforce_path_sanity, #sanitized_path

Methods included from Mixin::PowershellOut

#powershell_out, #powershell_out!

Methods included from Mixin::WindowsArchitectureHelper

#assert_valid_windows_architecture!, #disable_wow64_file_redirection, #forced_32bit_override_required?, #is_i386_process_on_x86_64_windows?, #node_supports_windows_architecture?, #node_windows_architecture, #restore_wow64_file_redirection, #valid_windows_architecture?, #with_os_architecture, #wow64_architecture_override_required?, #wow64_directory

Methods included from Mixin::PowershellExec

#powershell_exec

Methods included from DSL::PlatformIntrospection

#docker?, #platform?, #platform_family?, #value_for_platform, #value_for_platform_family

Constructor Details

This class inherits a constructor from Chef::Provider::User

Instance Attribute Details

#authentication_authorityObject

Returns the value of attribute authentication_authority.



48
49
50
# File 'lib/chef/provider/user/dscl.rb', line 48

def authentication_authority
  @authentication_authority
end

#password_shadow_conversion_algorithmObject

Returns the value of attribute password_shadow_conversion_algorithm.



49
50
51
# File 'lib/chef/provider/user/dscl.rb', line 49

def password_shadow_conversion_algorithm
  @password_shadow_conversion_algorithm
end

#user_infoObject

Returns the value of attribute user_info.



47
48
49
# File 'lib/chef/provider/user/dscl.rb', line 47

def 
  @user_info
end

Instance Method Details

#check_lockObject

This is the interface base User provider requires to provide idempotency.



487
488
489
# File 'lib/chef/provider/user/dscl.rb', line 487

def check_lock
  @locked = locked?
end

#convert_binary_plist_to_xml(binary_plist_string) ⇒ Object



674
675
676
# File 'lib/chef/provider/user/dscl.rb', line 674

def convert_binary_plist_to_xml(binary_plist_string)
  shell_out_compact("plutil", "-convert", "xml1", "-o", "-", "-", input: binary_plist_string).stdout
end

#convert_to_binary(string) ⇒ Object



678
679
680
# File 'lib/chef/provider/user/dscl.rb', line 678

def convert_to_binary(string)
  string.unpack("a2" * (string.size / 2)).collect { |i| i.hex.chr }.join
end

#create_userObject

Provider Actions



170
171
172
173
174
175
176
177
178
179
180
# File 'lib/chef/provider/user/dscl.rb', line 170

def create_user
  dscl_create_user
  # set_password modifies the plist file of the user directly. So update
  # the password first before making any modifications to the user.
  set_password
  dscl_create_comment
  dscl_set_uid
  dscl_set_gid
  dscl_set_home
  dscl_set_shell
end

#current_home_exists?Boolean

Returns:

  • (Boolean)


320
321
322
# File 'lib/chef/provider/user/dscl.rb', line 320

def current_home_exists?
  !!current_resource.home && ::File.exist?(current_resource.home)
end

#define_resource_requirementsObject



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/chef/provider/user/dscl.rb', line 59

def define_resource_requirements
  super

  requirements.assert(:all_actions) do |a|
    a.assertion { mac_osx_version_less_than_10_7? == false }
    a.failure_message(Chef::Exceptions::User, "Chef::Provider::User::Dscl only supports Mac OS X versions 10.7 and above.")
  end

  requirements.assert(:all_actions) do |a|
    a.assertion { ::File.exist?("/usr/bin/dscl") }
    a.failure_message(Chef::Exceptions::User, "Cannot find binary '/usr/bin/dscl' on the system for #{new_resource}!")
  end

  requirements.assert(:all_actions) do |a|
    a.assertion { ::File.exist?("/usr/bin/plutil") }
    a.failure_message(Chef::Exceptions::User, "Cannot find binary '/usr/bin/plutil' on the system for #{new_resource}!")
  end

  requirements.assert(:create, :modify, :manage) do |a|
    a.assertion do
      if new_resource.password && mac_osx_version_greater_than_10_7?
        # SALTED-SHA512 password shadow hashes are not supported on 10.8 and above.
        !salted_sha512?(new_resource.password)
      else
        true
      end
    end
    a.failure_message(Chef::Exceptions::User, "SALTED-SHA512 passwords are not supported on Mac 10.8 and above. \
If you want to set the user password using shadow info make sure you specify a SALTED-SHA512-PBKDF2 shadow hash \
in 'password', with the associated 'salt' and 'iterations'.")
  end

  requirements.assert(:create, :modify, :manage) do |a|
    a.assertion do
      if new_resource.password && mac_osx_version_greater_than_10_7? && salted_sha512_pbkdf2?(new_resource.password)
        # salt and iterations should be specified when
        # SALTED-SHA512-PBKDF2 password shadow hash is given
        !new_resource.salt.nil? && !new_resource.iterations.nil?
      else
        true
      end
    end
    a.failure_message(Chef::Exceptions::User, "SALTED-SHA512-PBKDF2 shadow hash is given without associated \
'salt' and 'iterations'. Please specify 'salt' and 'iterations' in order to set the user password using shadow hash.")
  end

  requirements.assert(:create, :modify, :manage) do |a|
    a.assertion do
      if new_resource.password && !mac_osx_version_greater_than_10_7?
        # On 10.7 SALTED-SHA512-PBKDF2 is not supported
        !salted_sha512_pbkdf2?(new_resource.password)
      else
        true
      end
    end
    a.failure_message(Chef::Exceptions::User, "SALTED-SHA512-PBKDF2 shadow hashes are not supported on \
Mac OS X version 10.7. Please specify a SALTED-SHA512 shadow hash in 'password' attribute to set the \
user password using shadow hash.")
  end
end

#ditto_homeObject



328
329
330
# File 'lib/chef/provider/user/dscl.rb', line 328

def ditto_home
  shell_out_compact!("/usr/sbin/createhomedir", "-c", "-u", "#{new_resource.username}")
end

#diverged?(parameter) ⇒ Boolean

Returns true if the system state and desired state is different for given attribute.

Returns:

  • (Boolean)


499
500
501
# File 'lib/chef/provider/user/dscl.rb', line 499

def diverged?(parameter)
  parameter_updated?(parameter) && !new_resource.send(parameter).nil?
end

#diverged_password?Boolean

We need a special check function for password since we support both plain text and shadow hash data.

Checks if password needs update based on platform version and the type of the password specified.

Returns:

  • (Boolean)


514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
# File 'lib/chef/provider/user/dscl.rb', line 514

def diverged_password?
  return false if new_resource.password.nil?

  # Dscl provider supports both plain text passwords and shadow hashes.
  if mac_osx_version_10_7?
    if salted_sha512?(new_resource.password)
      diverged?(:password)
    else
      !salted_sha512_password_match?
    end
  else
    # When a system is upgraded to a version 10.7+ shadow hashes of the users
    # will be updated when the user logs in. So it's possible that we will have
    # SALTED-SHA512 password in the current_resource. In that case we will force
    # password to be updated.
    return true if salted_sha512?(current_resource.password)

    # Some system users don't have salts; this can happen if the system is
    # upgraded and the user hasn't logged in yet. In this case, we will force
    # the password to be updated.
    return true if current_resource.salt.nil?

    if salted_sha512_pbkdf2?(new_resource.password)
      diverged?(:password) || diverged?(:salt) || diverged?(:iterations)
    else
      !salted_sha512_pbkdf2_password_match?
    end
  end
end

#dscl_create_commentObject

Saves the specified Chef user ‘comment` into RealName attribute of Mac user. If `comment` is not specified, it takes `username` value.



209
210
211
212
# File 'lib/chef/provider/user/dscl.rb', line 209

def dscl_create_comment
  comment = new_resource.comment || new_resource.username
  run_dscl("create", "/Users/#{new_resource.username}", "RealName", comment)
end

#dscl_create_userObject

Create a user using dscl



201
202
203
# File 'lib/chef/provider/user/dscl.rb', line 201

def dscl_create_user
  run_dscl("create", "/Users/#{new_resource.username}")
end

#dscl_get(user_hash, key) ⇒ Object

Gets a value from user information hash using Chef attributes as keys.



623
624
625
626
627
628
# File 'lib/chef/provider/user/dscl.rb', line 623

def dscl_get(user_hash, key)
  raise "Unknown dscl key #{key}" unless DSCL_PROPERTY_MAP.keys.include?(key)
  # DSCL values are set as arrays
  value = user_hash[DSCL_PROPERTY_MAP[key]]
  value.nil? ? value : value.first
end

#dscl_set(user_hash, key, value) ⇒ Object

Sets a value in user information hash using Chef attributes as keys.



614
615
616
617
618
# File 'lib/chef/provider/user/dscl.rb', line 614

def dscl_set(user_hash, key, value)
  raise "Unknown dscl key #{key}" unless DSCL_PROPERTY_MAP.keys.include?(key)
  user_hash[DSCL_PROPERTY_MAP[key]] = [ value ]
  user_hash
end

#dscl_set_gidObject

Sets the group id for the user using dscl. Fails if a group doesn’t exist on the system with given group id. If ‘gid` is not specified, it sets a default Mac user group “staff”, with id 20 using the CONSTANT



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/chef/provider/user/dscl.rb', line 274

def dscl_set_gid
  if new_resource.gid.nil?
    # XXX: mutates the new resource
    new_resource.gid(STAFF_GROUP_ID)
  elsif !new_resource.gid.to_s.match(/^\d+$/)
    begin
      possible_gid = run_dscl("read", "/Groups/#{new_resource.gid}", "PrimaryGroupID").split(" ").last
    rescue Chef::Exceptions::DsclCommandFailed
      raise Chef::Exceptions::GroupIDNotFound, "Group not found for #{new_resource.gid} when creating user #{new_resource.username}"
    end
    # XXX: mutates the new resource
    new_resource.gid(possible_gid) if possible_gid && possible_gid.match(/^\d+$/)
  end
  run_dscl("create", "/Users/#{new_resource.username}", "PrimaryGroupID", new_resource.gid)
end

#dscl_set_homeObject

Sets the home directory for the user. If ‘:manage_home` is set home directory is managed (moved / created) for the user.



294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/chef/provider/user/dscl.rb', line 294

def dscl_set_home
  if new_resource.home.nil? || new_resource.home.empty?
    run_dscl("delete", "/Users/#{new_resource.username}", "NFSHomeDirectory")
    return
  end

  if new_resource.manage_home
    validate_home_dir_specification!

    if (current_resource.home == new_resource.home) && !new_home_exists?
      ditto_home
    elsif !current_home_exists? && !new_home_exists?
      ditto_home
    elsif current_home_exists?
      move_home
    end
  end
  run_dscl("create", "/Users/#{new_resource.username}", "NFSHomeDirectory", new_resource.home)
end

#dscl_set_shellObject

Sets the shell for the user using dscl.



346
347
348
349
350
351
352
# File 'lib/chef/provider/user/dscl.rb', line 346

def dscl_set_shell
  if new_resource.shell
    run_dscl("create", "/Users/#{new_resource.username}", "UserShell", new_resource.shell)
  else
    run_dscl("create", "/Users/#{new_resource.username}", "UserShell", "/usr/bin/false")
  end
end

#dscl_set_uidObject

Sets the user id for the user using dscl. If a ‘uid` is not specified, it finds the next available one starting from 200 if `system` is set, 501 otherwise.



219
220
221
222
223
224
225
226
227
228
# File 'lib/chef/provider/user/dscl.rb', line 219

def dscl_set_uid
  # XXX: mutates the new resource
  new_resource.uid(get_free_uid) if new_resource.uid.nil? || new_resource.uid == ""

  if uid_used?(new_resource.uid)
    raise(Chef::Exceptions::RequestedUIDUnavailable, "uid #{new_resource.uid} is already in use")
  end

  run_dscl("create", "/Users/#{new_resource.username}", "UniqueID", new_resource.uid)
end

#get_free_uid(search_limit = 1000) ⇒ Object

Find the next available uid on the system. starting with 200 if ‘system` is set, 501 otherwise.



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/chef/provider/user/dscl.rb', line 234

def get_free_uid(search_limit = 1000)
  uid = nil
  base_uid = new_resource.system ? 200 : 501
  next_uid_guess = base_uid
  users_uids = run_dscl("list", "/Users", "uid")
  while next_uid_guess < search_limit + base_uid
    if users_uids =~ Regexp.new("#{Regexp.escape(next_uid_guess.to_s)}\n")
      next_uid_guess += 1
    else
      uid = next_uid_guess
      break
    end
  end
  uid || raise("uid not found. Exhausted. Searched #{search_limit} times")
end

#load_current_resourceObject



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/chef/provider/user/dscl.rb', line 120

def load_current_resource
  @current_resource = Chef::Resource::User.new(new_resource.username)
  current_resource.username(new_resource.username)

  @user_info = 
  if 
    current_resource.uid(dscl_get(, :uid))
    current_resource.gid(dscl_get(, :gid))
    current_resource.home(dscl_get(, :home))
    current_resource.shell(dscl_get(, :shell))
    current_resource.comment(dscl_get(, :comment))
    @authentication_authority = dscl_get(, :auth_authority)

    if new_resource.password && dscl_get(, :password) == "********"
      # A password is set. Let's get the password information from shadow file
      shadow_hash_binary = dscl_get(, :shadow_hash)

      # Calling shell_out directly since we want to give an input stream
      shadow_hash_xml = convert_binary_plist_to_xml(shadow_hash_binary.string)
      shadow_hash = Plist.parse_xml(shadow_hash_xml)

      if shadow_hash["SALTED-SHA512"]
        # Convert the shadow value from Base64 encoding to hex before consuming them
        @password_shadow_conversion_algorithm = "SALTED-SHA512"
        current_resource.password(shadow_hash["SALTED-SHA512"].string.unpack("H*").first)
      elsif shadow_hash["SALTED-SHA512-PBKDF2"]
        @password_shadow_conversion_algorithm = "SALTED-SHA512-PBKDF2"
        # Convert the entropy from Base64 encoding to hex before consuming them
        current_resource.password(shadow_hash["SALTED-SHA512-PBKDF2"]["entropy"].string.unpack("H*").first)
        current_resource.iterations(shadow_hash["SALTED-SHA512-PBKDF2"]["iterations"])
        # Convert the salt from Base64 encoding to hex before consuming them
        current_resource.salt(shadow_hash["SALTED-SHA512-PBKDF2"]["salt"].string.unpack("H*").first)
      else
        raise(Chef::Exceptions::User, "Unknown shadow_hash format: #{shadow_hash.keys.join(' ')}")
      end
    end

    convert_group_name if new_resource.gid
  else
    @user_exists = false
    logger.trace("#{new_resource} user does not exist")
  end

  current_resource
end

#lock_userObject

Locks the user.



461
462
463
# File 'lib/chef/provider/user/dscl.rb', line 461

def lock_user
  run_dscl("append", "/Users/#{new_resource.username}", "AuthenticationAuthority", ";DisabledUser;")
end

#locked?Boolean

Returns true if the user is locked, false otherwise.

Returns:

  • (Boolean)


476
477
478
479
480
481
482
# File 'lib/chef/provider/user/dscl.rb', line 476

def locked?
  if authentication_authority
    !!(authentication_authority =~ /DisabledUser/ )
  else
    false
  end
end

#mac_osx_versionObject

System Helpets



634
635
636
637
638
# File 'lib/chef/provider/user/dscl.rb', line 634

def mac_osx_version
  # This provider will only be invoked on node[:platform] == "mac_os_x"
  # We do not check or assert that here.
  node[:platform_version]
end

#mac_osx_version_10_7?Boolean

Returns:

  • (Boolean)


640
641
642
# File 'lib/chef/provider/user/dscl.rb', line 640

def mac_osx_version_10_7?
  mac_osx_version.start_with?("10.7.")
end

#mac_osx_version_greater_than_10_7?Boolean

Returns:

  • (Boolean)


650
651
652
653
654
# File 'lib/chef/provider/user/dscl.rb', line 650

def mac_osx_version_greater_than_10_7?
  versions = mac_osx_version.split(".")
  # Make integer comparison in order not to report 10.10 less than 10.7
  (versions[0].to_i >= 10 && versions[1].to_i > 7)
end

#mac_osx_version_less_than_10_7?Boolean

Returns:

  • (Boolean)


644
645
646
647
648
# File 'lib/chef/provider/user/dscl.rb', line 644

def mac_osx_version_less_than_10_7?
  versions = mac_osx_version.split(".")
  # Make integer comparison in order not to report 10.10 less than 10.7
  (versions[0].to_i <= 10 && versions[1].to_i < 7)
end

#manage_userObject



182
183
184
185
186
187
188
189
190
191
192
# File 'lib/chef/provider/user/dscl.rb', line 182

def manage_user
  # set_password modifies the plist file of the user directly. So update
  # the password first before making any modifications to the user.
  set_password        if diverged_password?
  dscl_create_user    if diverged?(:username)
  dscl_create_comment if diverged?(:comment)
  dscl_set_uid        if diverged?(:uid)
  dscl_set_gid        if diverged?(:gid)
  dscl_set_home       if diverged?(:home)
  dscl_set_shell      if diverged?(:shell)
end

#member_of_group?(group_name) ⇒ Boolean

Returns true if user is member of the specified group, false otherwise.

Returns:

  • (Boolean)


547
548
549
550
551
552
553
554
555
556
557
558
559
# File 'lib/chef/provider/user/dscl.rb', line 547

def member_of_group?(group_name)
  membership_info = ""
  begin
    membership_info = run_dscl("read", "/Groups/#{group_name}")
  rescue Chef::Exceptions::DsclCommandFailed
    # Raised if the group doesn't contain any members
  end
  # Output is something like:
  # GroupMembership: root admin etc
  members = membership_info.split(" ")
  members.shift # Get rid of GroupMembership: string
  members.include?(new_resource.username)
end

#move_homeObject



332
333
334
335
336
337
338
339
340
341
# File 'lib/chef/provider/user/dscl.rb', line 332

def move_home
  logger.trace("#{new_resource} moving #{self} home from #{current_resource.home} to #{new_resource.home}")
  new_resource.gid(STAFF_GROUP_ID) if new_resource.gid.nil?
  src = current_resource.home
  FileUtils.mkdir_p(new_resource.home)
  files = ::Dir.glob("#{Chef::Util::PathHelper.escape_glob_dir(src)}/*", ::File::FNM_DOTMATCH) - ["#{src}/.", "#{src}/.."]
  ::FileUtils.mv(files, new_resource.home, force: true)
  ::FileUtils.rmdir(src)
  ::FileUtils.chown_R(new_resource.username, new_resource.gid.to_s, new_resource.home)
end

#new_home_exists?Boolean

Returns:

  • (Boolean)


324
325
326
# File 'lib/chef/provider/user/dscl.rb', line 324

def new_home_exists?
  ::File.exist?(new_resource.home)
end

#parameter_updated?(parameter) ⇒ Boolean

Returns:

  • (Boolean)


503
504
505
# File 'lib/chef/provider/user/dscl.rb', line 503

def parameter_updated?(parameter)
  !(new_resource.send(parameter) == current_resource.send(parameter))
end

#prepare_password_shadow_infoObject

Prepares the password shadow info based on the platform version.



387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/chef/provider/user/dscl.rb', line 387

def prepare_password_shadow_info
  shadow_info = {}
  entropy = nil
  salt = nil
  iterations = nil

  if mac_osx_version_10_7?
    hash_value = if salted_sha512?(new_resource.password)
                   new_resource.password
                 else
                   # Create a random 4 byte salt
                   salt = OpenSSL::Random.random_bytes(4)
                   encoded_password = OpenSSL::Digest::SHA512.hexdigest(salt + new_resource.password)
                   salt.unpack("H*").first + encoded_password
                 end

    shadow_info["SALTED-SHA512"] = StringIO.new
    shadow_info["SALTED-SHA512"].string = convert_to_binary(hash_value)
    shadow_info
  else
    if salted_sha512_pbkdf2?(new_resource.password)
      entropy = convert_to_binary(new_resource.password)
      salt = convert_to_binary(new_resource.salt)
      iterations = new_resource.iterations
    else
      salt = OpenSSL::Random.random_bytes(32)
      iterations = new_resource.iterations # Use the default if not specified by the user

      entropy = OpenSSL::PKCS5.pbkdf2_hmac(
        new_resource.password,
        salt,
        iterations,
        128,
        OpenSSL::Digest::SHA512.new
      )
    end

    pbkdf_info = {}
    pbkdf_info["entropy"] = StringIO.new
    pbkdf_info["entropy"].string = entropy
    pbkdf_info["salt"] = StringIO.new
    pbkdf_info["salt"].string = salt
    pbkdf_info["iterations"] = iterations

    shadow_info["SALTED-SHA512-PBKDF2"] = pbkdf_info
  end

  shadow_info
end

#read_user_infoObject

Reads the user plist and returns a hash keyed with DSCL properties specified in DSCL_PROPERTY_MAP. Return nil if the user is not found.



584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
# File 'lib/chef/provider/user/dscl.rb', line 584

def 
   = nil

  # We flush the cache here in order to make sure that we read fresh information
  # for the user.
  shell_out_compact("dscacheutil", "-flushcache") # FIXME: this is MacOS version dependent

  begin
    user_plist_file = "#{USER_PLIST_DIRECTORY}/#{new_resource.username}.plist"
    user_plist_info = run_plutil("convert", "xml1", "-o", "-", user_plist_file)
     = Plist.parse_xml(user_plist_info)
  rescue Chef::Exceptions::PlistUtilCommandFailed
  end

  
end

#remove_userObject

Removes the user from the system after removing user from his groups and deleting home directory if needed.



441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# File 'lib/chef/provider/user/dscl.rb', line 441

def remove_user
  if new_resource.manage_home
    # Remove home directory
    FileUtils.rm_rf(current_resource.home)
  end

  # Remove the user from its groups
  run_dscl("list", "/Groups").each_line do |group|
    if member_of_group?(group.chomp)
      run_dscl("delete", "/Groups/#{group.chomp}", "GroupMembership", new_resource.username)
    end
  end

  # Remove user account
  run_dscl("delete", "/Users/#{new_resource.username}")
end

#run_dscl(*args) ⇒ Object



656
657
658
659
660
661
662
# File 'lib/chef/provider/user/dscl.rb', line 656

def run_dscl(*args)
  result = shell_out_compact("dscl", ".", "-#{args[0]}", args[1..-1])
  return "" if ( args.first =~ /^delete/ ) && ( result.exitstatus != 0 )
  raise(Chef::Exceptions::DsclCommandFailed, "dscl error: #{result.inspect}") unless result.exitstatus == 0
  raise(Chef::Exceptions::DsclCommandFailed, "dscl error: #{result.inspect}") if result.stdout =~ /No such key: /
  result.stdout
end

#run_plutil(*args) ⇒ Object



664
665
666
667
668
669
670
671
672
# File 'lib/chef/provider/user/dscl.rb', line 664

def run_plutil(*args)
  result = shell_out_compact("plutil", "-#{args[0]}", args[1..-1])
  raise(Chef::Exceptions::PlistUtilCommandFailed, "plutil error: #{result.inspect}") unless result.exitstatus == 0
  if result.stdout.encoding == Encoding::ASCII_8BIT
    result.stdout.encode("utf-8", "binary", undef: :replace, invalid: :replace, replace: "?")
  else
    result.stdout
  end
end

#salted_sha512?(string) ⇒ Boolean

Returns:

  • (Boolean)


682
683
684
# File 'lib/chef/provider/user/dscl.rb', line 682

def salted_sha512?(string)
  !!(string =~ /^[[:xdigit:]]{136}$/)
end

#salted_sha512_password_match?Boolean

Returns:

  • (Boolean)


686
687
688
689
690
691
# File 'lib/chef/provider/user/dscl.rb', line 686

def salted_sha512_password_match?
  # Salt is included in the first 4 bytes of shadow data
  salt = current_resource.password.slice(0, 8)
  shadow = OpenSSL::Digest::SHA512.hexdigest(convert_to_binary(salt) + new_resource.password)
  current_resource.password == salt + shadow
end

#salted_sha512_pbkdf2?(string) ⇒ Boolean

Returns:

  • (Boolean)


693
694
695
# File 'lib/chef/provider/user/dscl.rb', line 693

def salted_sha512_pbkdf2?(string)
  !!(string =~ /^[[:xdigit:]]{256}$/)
end

#salted_sha512_pbkdf2_password_match?Boolean

Returns:

  • (Boolean)


697
698
699
700
701
702
703
704
705
706
707
# File 'lib/chef/provider/user/dscl.rb', line 697

def salted_sha512_pbkdf2_password_match?
  salt = convert_to_binary(current_resource.salt)

  OpenSSL::PKCS5.pbkdf2_hmac(
    new_resource.password,
    salt,
    current_resource.iterations,
    128,
    OpenSSL::Digest::SHA512.new
  ).unpack("H*").first == current_resource.password
end

#save_user_info(user_info) ⇒ Object

Saves the given hash keyed with DSCL properties specified in DSCL_PROPERTY_MAP to the disk.



605
606
607
608
609
# File 'lib/chef/provider/user/dscl.rb', line 605

def ()
  user_plist_file = "#{USER_PLIST_DIRECTORY}/#{new_resource.username}.plist"
  Plist::Emit.save_plist(, user_plist_file)
  run_plutil("convert", "binary1", user_plist_file)
end

#set_passwordObject

Sets the password for the user based on given password parameters. Chef supports specifying plain-text passwords and password shadow hash data.



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# File 'lib/chef/provider/user/dscl.rb', line 359

def set_password
  # Return if there is no password to set
  return if new_resource.password.nil?

  shadow_info = prepare_password_shadow_info

  # Shadow info is saved as binary plist. Convert the info to binary plist.
  shadow_info_binary = StringIO.new
  shell_out_compact("plutil", "-convert", "binary1", "-o", "-", "-",
                    input: shadow_info.to_plist, live_stream: shadow_info_binary)

  if .nil?
    # User is  just created. read_user_info() will read the fresh information
    # for the user with a cache flush. However with experimentation we've seen
    # that dscl cache is not immediately updated after the creation of the user
    # This is odd and needs to be investigated further.
    sleep 3
    @user_info = 
  end

  # Replace the shadow info in user's plist
  dscl_set(, :shadow_hash, shadow_info_binary)
  ()
end

#uid_used?(uid) ⇒ Boolean

Returns true if uid is in use by a different account, false otherwise.

Returns:

  • (Boolean)


253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/chef/provider/user/dscl.rb', line 253

def uid_used?(uid)
  return false unless uid
  users_uids = run_dscl("list", "/Users", "uid").split("\n")
  uid_map = users_uids.each_with_object({}) do |tuid, tmap|
    x = tuid.split
    tmap[x[1]] = x[0]
    tmap
  end
  if uid_map[uid.to_s]
    unless uid_map[uid.to_s] == new_resource.username
      return true
    end
  end
  false
end

#unlock_userObject

Unlocks the user



468
469
470
471
# File 'lib/chef/provider/user/dscl.rb', line 468

def unlock_user
  auth_string = authentication_authority.gsub(/AuthenticationAuthority: /, "").gsub(/;DisabledUser;/, "").strip
  run_dscl("create", "/Users/#{new_resource.username}", "AuthenticationAuthority", auth_string)
end

#validate_home_dir_specification!Object



314
315
316
317
318
# File 'lib/chef/provider/user/dscl.rb', line 314

def validate_home_dir_specification!
  unless new_resource.home =~ /^\//
    raise(Chef::Exceptions::InvalidHomeDirectory, "invalid path spec for User: '#{new_resource.username}', home directory: '#{new_resource.home}'")
  end
end