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.



551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
# File 'lib/puppet/util/windows/security.rb', line 551

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, _("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