Method: Puppet::Util::Windows::Security#set_privilege

Defined in:
lib/puppet/util/windows/security.rb

#set_privilege(privilege, enable) ⇒ Object

Enable or disable a privilege. Note this doesn’t add any privileges the user doesn’t already has, it just enables privileges that are disabled.



498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
# File 'lib/puppet/util/windows/security.rb', line 498

def set_privilege(privilege, enable)
  return unless Puppet.features.root?

  Puppet::Util::Windows::Process.with_process_token(TOKEN_ADJUST_PRIVILEGES) do |token|
    Puppet::Util::Windows::Process.lookup_privilege_value(privilege) do |luid|
      FFI::MemoryPointer.new(Puppet::Util::Windows::Process::LUID_AND_ATTRIBUTES.size) do |luid_and_attributes_ptr|
        # allocate unmanaged memory for structs that we clean up afterwards
        luid_and_attributes = Puppet::Util::Windows::Process::LUID_AND_ATTRIBUTES.new(luid_and_attributes_ptr)
        luid_and_attributes[:Luid] = luid
        luid_and_attributes[:Attributes] = enable ? SE_PRIVILEGE_ENABLED : 0

        FFI::MemoryPointer.new(Puppet::Util::Windows::Process::TOKEN_PRIVILEGES.size) do |token_privileges_ptr|
          token_privileges = Puppet::Util::Windows::Process::TOKEN_PRIVILEGES.new(token_privileges_ptr)
          token_privileges[:PrivilegeCount] = 1
          token_privileges[:Privileges][0] = luid_and_attributes

          # size is correct given we only have 1 LUID, otherwise would be:
          # [:PrivilegeCount].size + [:PrivilegeCount] * LUID_AND_ATTRIBUTES.size
          if AdjustTokenPrivileges(token, FFI::WIN32_FALSE,
              token_privileges, token_privileges.size,
              FFI::MemoryPointer::NULL, FFI::MemoryPointer::NULL) == FFI::WIN32_FALSE
            raise Puppet::Util::Windows::Error.new(_("Failed to adjust process privileges"))
          end
        end
      end
    end
  end

  # token / luid structs freed by this point, so return true as nothing raised
  true
end