Example #1
0
def GetCurrentSID():
    import win32api, win32security
    Sid = win32security.LookupAccountName(win32api.GetComputerName(),
                                          win32api.GetUserName())[0]
    return win32security.ConvertSidToStringSid(Sid)
Example #2
0
 def testEqual(self):
     self.failUnlessEqual(win32security.LookupAccountName('','Administrator')[0],
                          win32security.LookupAccountName('','Administrator')[0])
Example #3
0
 def user_rights_policy(self, policy):
     actual_users = []
     granted = []
     deleted = []
     for val in win32security.LsaEnumerateAccountsWithUserRight(win32security.LsaOpenPolicy("", 25), policy["right_type"]):
         actual_users.append(win32security.LookupAccountSid(None, val)[0])
     file_users = policy["value_data"]
     if (file_users == '' or file_users == "Undefined") and len(actual_users) != 0:
         for user in actual_users:
             try:
                 win32security.LsaRemoveAccountRights(win32security.LsaOpenPolicy("", 25), win32security.LookupAccountName(None, user)[0], 0, [policy["right_type"]])
                 deleted.append(user)
             except Exception as e:
                 continue
         return {"status": 0, "msg": {"granted": granted, "deleted": deleted}}
     
     file_users = file_users.replace("'", "").replace('"', '').split('&&')
     file_users = [user.strip() for user in file_users]
     for user in file_users:
         try:
             if user not in actual_users:
                 win32security.LsaAddAccountRights(win32security.LsaOpenPolicy("", 25), win32security.LookupAccountName(None, user)[0], [policy["right_type"]])
                 granted.append(user)
         except Exception as e:
             continue
     for user in actual_users:
         try:
             if user not in file_users:
                 win32security.LsaRemoveAccountRights(win32security.LsaOpenPolicy("", 25), win32security.LookupAccountName(None, user)[0], 0, [policy["right_type"]])
                 deleted.append(user)
         except Exception as e:
             continue
     return {"status": 0, "msg": {"granted": granted, "deleted": deleted}}
Example #4
0
## add Summary Information, which is stored as a separate stream
m = storagecon.STGM_READWRITE | storagecon.STGM_SHARE_EXCLUSIVE | storagecon.STGM_DIRECT
pss = pythoncom.StgOpenStorageEx(tempfile, m, storagecon.STGFMT_FILE, 0,
                                 pythoncom.IID_IPropertySetStorage, None)
ps = pss.Create(pythoncom.FMTID_SummaryInformation,
                pythoncom.IID_IPropertyStorage, 0,
                storagecon.STGM_READWRITE | storagecon.STGM_SHARE_EXCLUSIVE)
ps.WriteMultiple((storagecon.PIDSI_KEYWORDS, storagecon.PIDSI_COMMENTS),
                 ('keywords', 'comments'))
ps = None
pss = None

## add a custom security descriptor to make sure we don't
##   get a default that would always be the same for both files in temp dir
new_sd = pywintypes.SECURITY_DESCRIPTOR()
sid = win32security.LookupAccountName('', 'EveryOne')[0]
acl = pywintypes.ACL()
acl.AddAccessAllowedAce(1, win32con.GENERIC_READ, sid)
acl.AddAccessAllowedAce(1, ntsecuritycon.FILE_APPEND_DATA, sid)
acl.AddAccessAllowedAce(1, win32con.GENERIC_WRITE, sid)
acl.AddAccessAllowedAce(1, ntsecuritycon.FILE_ALL_ACCESS, sid)

new_sd.SetSecurityDescriptorDacl(True, acl, False)
win32security.SetFileSecurity(tempfile,
                              win32security.DACL_SECURITY_INFORMATION, new_sd)

sa = pywintypes.SECURITY_ATTRIBUTES()
sa.bInheritHandle = True
h = win32file.CreateFile(tempfile, win32con.GENERIC_ALL,
                         win32con.FILE_SHARE_READ, sa, win32con.OPEN_EXISTING,
                         win32file.FILE_FLAG_BACKUP_SEMANTICS, None)
Example #5
0
    def test_file_no_permission(self):
        """
        Checks that filebeat handles files without reading permission well
        """

        self.render_config_template(path=os.path.abspath(self.working_dir) +
                                    "/log/*", )
        os.mkdir(self.working_dir + "/log/")

        testfile = self.working_dir + "/log/test.log"
        file = open(testfile, 'w')

        iterations = 3
        for n in range(0, iterations):
            file.write("Hello World" + str(n))
            file.write("\n")

        file.close()

        # Remove reading rights from file
        os.chmod(testfile, 0o000)

        if os.name == "nt":

            raise SkipTest
            # TODO: Currently skipping this test on windows as it requires `pip install win32api`
            # which seems to have windows only dependencies.
            # To solve this problem a requirements_windows.txt could be introduced which would
            # then only be used on Windows.
            #
            # Below is some additional code to give some indication on how the implementation could
            # look like.

            from win32 import win32api
            import win32security
            import ntsecuritycon as con

            user, domain, type = win32security.LookupAccountName(
                "", win32api.GetUserName())
            sd = win32security.GetFileSecurity(
                testfile, win32security.DACL_SECURITY_INFORMATION)

            dacl = win32security.ACL()
            # Remove all access rights
            dacl.AddAccessAllowedAce(win32security.ACL_REVISION, 0, user)

            sd.SetSecurityDescriptorDacl(1, dacl, 0)
            win32security.SetFileSecurity(
                testfile, win32security.DACL_SECURITY_INFORMATION, sd)

        filebeat = self.start_beat()

        self.wait_until(lambda: self.log_contains("permission denied"),
                        max_timeout=15)

        filebeat.check_kill_and_wait()

        os.chmod(testfile, 0o755)

        assert False == os.path.isfile(
            os.path.join(self.working_dir, "output/filebeat"))
Example #6
0
def _get_current_user():
    account_name = win32api.GetUserNameEx(win32api.NameSamCompatible)
    return win32security.LookupAccountName(None, account_name)[0]
Example #7
0
 def setUp(self):
     self.pwr_sid = win32security.LookupAccountName('', 'Power Users')[0]
     self.admin_sid = win32security.LookupAccountName('',
                                                      'Administrator')[0]
Example #8
0
 def test_principal_sid(self):
     everyone, domain, type = win32security.LookupAccountName(
         None, "Everyone")
     assert accounts.principal(everyone).pyobject() == everyone
Example #9
0
 def test_principal_Principal(self):
     everyone, domain, type = win32security.LookupAccountName(
         None, "Everyone")
     principal = accounts.Principal(everyone)
     assert accounts.principal(principal) is principal
Example #10
0
        win32con.SE_PRIVILEGE_ENABLED,
    ),
    (
        win32security.LookupPrivilegeValue("", "SeEnableDelegationPrivilege"),
        win32con.SE_PRIVILEGE_ENABLED,
    ),  ##doesn't seem to be in ntsecuritycon.py ?
)

ph = win32api.GetCurrentProcess()
th = win32security.OpenProcessToken(
    ph, win32security.TOKEN_ALL_ACCESS)  ##win32con.TOKEN_ADJUST_PRIVILEGES)
win32security.AdjustTokenPrivileges(th, 0, new_privs)

policy_handle = win32security.GetPolicyHandle("",
                                              win32security.POLICY_ALL_ACCESS)
tmp_sid = win32security.LookupAccountName("", "tmp")[0]

privs = [
    ntsecuritycon.SE_DEBUG_NAME,
    ntsecuritycon.SE_TCB_NAME,
    ntsecuritycon.SE_RESTORE_NAME,
    ntsecuritycon.SE_REMOTE_SHUTDOWN_NAME,
]
win32security.LsaAddAccountRights(policy_handle, tmp_sid, privs)

privlist = win32security.LsaEnumerateAccountRights(policy_handle, tmp_sid)
for priv in privlist:
    print(priv)

privs = [ntsecuritycon.SE_DEBUG_NAME, ntsecuritycon.SE_TCB_NAME]
win32security.LsaRemoveAccountRights(policy_handle, tmp_sid, 0, privs)
Example #11
0
def make_private(path):
    """
    Make `path` accessible only by 'owner'.

    path: string
        Path to file or directory to be made private.

    .. note::

        On Windows this requires the pywin32 extension.

    """
    if sys.platform == 'win32':  #pragma no cover
        if not HAVE_PYWIN32:
            raise ImportError('No pywin32')

        # Find the SIDs for user and system.
        username = win32api.GetUserNameEx(win32con.NameSamCompatible)

        # Map Cygwin 'root' to 'Administrator'. Typically these are intended
        # to be identical, but /etc/passwd might configure them differently.
        if username.endswith('\\root'):
            username = username.replace('\\root', '\\Administrator')
        user, domain, type = win32security.LookupAccountName('', username)
        system, domain, type = win32security.LookupAccountName('', 'System')

        # Find the DACL part of the Security Descriptor for the file
        sd = win32security.GetFileSecurity(path,
                                        win32security.DACL_SECURITY_INFORMATION)

        # Create a blank DACL and add the ACEs we want.
        dacl = win32security.ACL()
        dacl.AddAccessAllowedAce(win32security.ACL_REVISION,
                                 ntsecuritycon.FILE_ALL_ACCESS, user)
        dacl.AddAccessAllowedAce(win32security.ACL_REVISION, 
                                 ntsecuritycon.FILE_ALL_ACCESS, system)

        # Put our new DACL into the Security Descriptor and update the file
        # with the updated SD.
        sd.SetSecurityDescriptorDacl(1, dacl, 0)
        win32security.SetFileSecurity(path,
                                      win32security.DACL_SECURITY_INFORMATION,
                                      sd)
    else:
        # Normal chmod() works on test machines with ACLs enabled, but a user
        # in the field reported a situation where it didn't. This code tries
        # using libacl if it can. Doesn't seem to cause any problems, not
        # verifed that it helps though.
        try:
            # From pylibacl, which requires 'libacl1-dev'.
            import posix1e
        except ImportError:
            mode = 0700 if os.path.isdir(path) else 0600
            os.chmod(path, mode)  # Read/Write/Execute
        else:
            if os.path.isdir(path):
                acl = posix1e.ACL(text='u::rwx,g::-,o::-')
            else:
                acl = posix1e.ACL(text='u::rw,g::-,o::-')
            acl.applyto(path)

    if not is_private(path):
        raise RuntimeError("Can't make %r private" % path)
Example #12
0
 def get_uid(self):
     if self.as_user == "@":
         return winsec.LookupAccountName('', self._myself)[0]
     else:
         return winsec.LookupAccountName('', self.as_user)[0]
Example #13
0
 def GetAccount(name, domain):
     return win32security.LookupAccountName(domain, name)
Example #14
0
import win32api
import win32security
uname = win32api.GetUserName()
print "You are", uname
sid, domain, atype = win32security.LookupAccountName(None, uname)
print "You have SID", str(sid).split(
    ':')[1], "on domain", domain, "with type", atype
Example #15
0
def runas_unpriv(cmd, username, password, cwd=None):
    '''
    Runas that works for non-priviledged users
    '''
    # Validate the domain and sid exist for the username
    username, domain = split_username(username)
    try:
        _, domain, _ = win32security.LookupAccountName(domain, username)
    except pywintypes.error as exc:
        message = win32api.FormatMessage(exc.winerror).rstrip('\n')
        raise CommandExecutionError(message)

    # Create a pipe to set as stdout in the child. The write handle needs to be
    # inheritable.
    c2pread, c2pwrite = salt.platform.win.CreatePipe(
        inherit_read=False,
        inherit_write=True,
    )
    errread, errwrite = salt.platform.win.CreatePipe(
        inherit_read=False,
        inherit_write=True,
    )

    # Create inheritable copy of the stdin
    stdin = salt.platform.win.kernel32.GetStdHandle(
        salt.platform.win.STD_INPUT_HANDLE, )
    dupin = salt.platform.win.DuplicateHandle(srchandle=stdin, inherit=True)

    # Get startup info structure
    startup_info = salt.platform.win.STARTUPINFO(
        dwFlags=win32con.STARTF_USESTDHANDLES,
        hStdInput=dupin,
        hStdOutput=c2pwrite,
        hStdError=errwrite,
    )

    try:
        # Run command and return process info structure
        process_info = salt.platform.win.CreateProcessWithLogonW(
            username=username,
            domain=domain,
            password=password,
            logonflags=salt.platform.win.LOGON_WITH_PROFILE,
            commandline=cmd,
            startupinfo=startup_info,
            currentdirectory=cwd)
        salt.platform.win.kernel32.CloseHandle(process_info.hThread)
    finally:
        salt.platform.win.kernel32.CloseHandle(dupin)
        salt.platform.win.kernel32.CloseHandle(c2pwrite)
        salt.platform.win.kernel32.CloseHandle(errwrite)

    # Initialize ret and set first element
    ret = {'pid': process_info.dwProcessId}

    # Get Standard Out
    fd_out = msvcrt.open_osfhandle(c2pread, os.O_RDONLY | os.O_TEXT)
    with os.fdopen(fd_out, 'r') as f_out:
        ret['stdout'] = f_out.read()

    # Get Standard Error
    fd_err = msvcrt.open_osfhandle(errread, os.O_RDONLY | os.O_TEXT)
    with os.fdopen(fd_err, 'r') as f_err:
        ret['stderr'] = f_err.read()

    # Get Return Code
    if salt.platform.win.kernel32.WaitForSingleObject(process_info.hProcess, win32event.INFINITE) == \
            win32con.WAIT_OBJECT_0:
        exitcode = salt.platform.win.wintypes.DWORD()
        salt.platform.win.kernel32.GetExitCodeProcess(process_info.hProcess,
                                                      ctypes.byref(exitcode))
        ret['retcode'] = exitcode.value

    # Close handle to process
    salt.platform.win.kernel32.CloseHandle(process_info.hProcess)

    return ret
Example #16
0
 def test_principal_string(self):
     everyone, domain, type = win32security.LookupAccountName(
         None, "Everyone")
     assert accounts.principal("Everyone") == everyone
Example #17
0
def runas(cmdLine, username, password=None, cwd=None):
    '''
    Run a command as another user. If the process is running as an admin or
    system account this method does not require a password. Other non
    privileged accounts need to provide a password for the user to runas.
    Commands are run in with the highest level privileges possible for the
    account provided.
    '''
    # Validate the domain and sid exist for the username
    username, domain = split_username(username)
    try:
        _, domain, _ = win32security.LookupAccountName(domain, username)
    except pywintypes.error as exc:
        message = win32api.FormatMessage(exc.winerror).rstrip('\n')
        raise CommandExecutionError(message)

    # Elevate the token from the current process
    access = (win32security.TOKEN_QUERY
              | win32security.TOKEN_ADJUST_PRIVILEGES)
    th = win32security.OpenProcessToken(win32api.GetCurrentProcess(), access)
    salt.platform.win.elevate_token(th)

    # Try to impersonate the SYSTEM user. This process needs to be running as a
    # user who as been granted the SeImpersonatePrivilege, Administrator
    # accounts have this permission by default.
    try:
        impersonation_token = salt.platform.win.impersonate_sid(
            salt.platform.win.SYSTEM_SID,
            session_id=0,
            privs=['SeTcbPrivilege'],
        )
    except WindowsError:  # pylint: disable=undefined-variable
        log.debug("Unable to impersonate SYSTEM user")
        impersonation_token = None
        win32api.CloseHandle(th)

    # Impersonation of the SYSTEM user failed. Fallback to an un-privileged
    # runas.
    if not impersonation_token:
        log.debug("No impersonation token, using unprivileged runas")
        return runas_unpriv(cmdLine, username, password, cwd)

    if domain == 'NT AUTHORITY':
        # Logon as a system level account, SYSTEM, LOCAL SERVICE, or NETWORK
        # SERVICE.
        user_token = win32security.LogonUser(
            username,
            domain,
            '',
            win32con.LOGON32_LOGON_SERVICE,
            win32con.LOGON32_PROVIDER_DEFAULT,
        )
    elif password:
        # Login with a password.
        user_token = win32security.LogonUser(
            username,
            domain,
            password,
            win32con.LOGON32_LOGON_INTERACTIVE,
            win32con.LOGON32_PROVIDER_DEFAULT,
        )
    else:
        # Login without a password. This always returns an elevated token.
        user_token = salt.platform.win.logon_msv1_s4u(username).Token

    # Get a linked user token to elevate if needed
    elevation_type = win32security.GetTokenInformation(
        user_token, win32security.TokenElevationType)
    if elevation_type > 1:
        user_token = win32security.GetTokenInformation(
            user_token, win32security.TokenLinkedToken)

    # Elevate the user token
    salt.platform.win.elevate_token(user_token)

    # Make sure the user's token has access to a windows station and desktop
    salt.platform.win.grant_winsta_and_desktop(user_token)

    # Create pipes for standard in, out and error streams
    security_attributes = win32security.SECURITY_ATTRIBUTES()
    security_attributes.bInheritHandle = 1

    stdin_read, stdin_write = win32pipe.CreatePipe(security_attributes, 0)
    stdin_read = salt.platform.win.make_inheritable(stdin_read)

    stdout_read, stdout_write = win32pipe.CreatePipe(security_attributes, 0)
    stdout_write = salt.platform.win.make_inheritable(stdout_write)

    stderr_read, stderr_write = win32pipe.CreatePipe(security_attributes, 0)
    stderr_write = salt.platform.win.make_inheritable(stderr_write)

    # Run the process without showing a window.
    creationflags = (win32process.CREATE_NO_WINDOW
                     | win32process.CREATE_NEW_CONSOLE
                     | win32process.CREATE_SUSPENDED)

    startup_info = salt.platform.win.STARTUPINFO(
        dwFlags=win32con.STARTF_USESTDHANDLES,
        hStdInput=stdin_read.handle,
        hStdOutput=stdout_write.handle,
        hStdError=stderr_write.handle,
    )

    # Create the environment for the user
    env = win32profile.CreateEnvironmentBlock(user_token, False)

    hProcess = None
    try:
        # Start the process in a suspended state.
        process_info = salt.platform.win.CreateProcessWithTokenW(
            int(user_token),
            logonflags=1,
            applicationname=None,
            commandline=cmdLine,
            currentdirectory=cwd,
            creationflags=creationflags,
            startupinfo=startup_info,
            environment=env,
        )

        hProcess = process_info.hProcess
        hThread = process_info.hThread
        dwProcessId = process_info.dwProcessId
        dwThreadId = process_info.dwThreadId

        # We don't use these so let's close the handle
        salt.platform.win.kernel32.CloseHandle(stdin_write.handle)
        salt.platform.win.kernel32.CloseHandle(stdout_write.handle)
        salt.platform.win.kernel32.CloseHandle(stderr_write.handle)

        ret = {'pid': dwProcessId}
        # Resume the process
        psutil.Process(dwProcessId).resume()

        # Wait for the process to exit and get it's return code.
        if win32event.WaitForSingleObject(
                hProcess, win32event.INFINITE) == win32con.WAIT_OBJECT_0:
            exitcode = win32process.GetExitCodeProcess(hProcess)
            ret['retcode'] = exitcode

        # Read standard out
        fd_out = msvcrt.open_osfhandle(stdout_read.handle,
                                       os.O_RDONLY | os.O_TEXT)
        with os.fdopen(fd_out, 'r') as f_out:
            stdout = f_out.read()
            ret['stdout'] = stdout

        # Read standard error
        fd_err = msvcrt.open_osfhandle(stderr_read.handle,
                                       os.O_RDONLY | os.O_TEXT)
        with os.fdopen(fd_err, 'r') as f_err:
            stderr = f_err.read()
            ret['stderr'] = stderr
    finally:
        if hProcess is not None:
            salt.platform.win.kernel32.CloseHandle(hProcess)
        win32api.CloseHandle(th)
        win32api.CloseHandle(user_token)
        if impersonation_token:
            win32security.RevertToSelf()
        win32api.CloseHandle(impersonation_token)

    return ret
Example #18
0
import os, sys
import operator

import win32api
import win32con
import win32security
import ntsecuritycon
import tempfile
from winsys._compat import unittest

from winsys.tests import utils as testutils
from winsys import accounts
from winsys._security import _aces, _acls

everyone, _, _ = win32security.LookupAccountName(None, "Everyone")
me, _, _ = win32security.LookupAccountName(
    None, win32api.GetUserNameEx(win32con.NameSamCompatible))


@unittest.skipUnless(testutils.i_am_admin(),
                     "These tests must be run as Administrator")
class TestACLs(unittest.TestCase):
    def test_acl_None(self):
        acl = _acls.acl(None)
        assert isinstance(acl, _acls.ACL) and acl.pyobject() is None

    def test_acl_PyACL(self):
        dacl = win32security.ACL()
        dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, 0,
                                   ntsecuritycon.FILE_READ_DATA, everyone)
Example #19
0
File: test.py Project: zhichaoh/ope
import win32gui
import win32ui
import win32con
import win32gui_struct
import win32ts
import PIL
import pyscreenshot as ImageGrab

ROOT_FOLDER = os.path.join(
    shell.SHGetFolderPath(0, shellcon.CSIDL_COMMON_APPDATA, None, 0), "ope")
TMP_FOLDER = os.path.join(ROOT_FOLDER, "tmp")
LOG_FOLDER = os.path.join(TMP_FOLDER, "log")
SCREEN_SHOTS_FOLDER = os.path.join(TMP_FOLDER, "screen_shots")
BINARIES_FOLDER = os.path.join(ROOT_FOLDER, "ope_laptop_binaries")

EVERYONE, domain, type = win32security.LookupAccountName("", "Everyone")
ADMINISTRATORS, domain, type = win32security.LookupAccountName(
    "", "Administrators")
# CURRENT_USER, domain, type = win32security.LookupAccountName("", win32api.GetUserName())
CURRENT_USER = None
try:
    CURRENT_USER, domain, type = win32security.LookupAccountName("", "huskers")
except:
    CURRENT_USER = None
if CURRENT_USER is None:
    try:
        CURRENT_USER, domain, type = win32security.LookupAccountName("", "ray")
    except:
        CURRENT_USER = None
SYSTEM_USER, domain, type = win32security.LookupAccountName("", "System")
def chown(path, user, group=None, pgroup=None, follow_symlinks=True):
    '''
    Chown a file, pass the file the desired user and group

    Under Windows, the group parameter will be ignored.

    This is because while files in Windows do have a 'primary group'
    property, this is rarely used.  It generally has no bearing on
    permissions unless intentionally configured and is most commonly used to
    provide Unix compatibility (e.g. Services For Unix, NFS services).

    If you do want to change the 'primary group' property and understand the
    implications, pass the Windows only parameter, pgroup, instead.

    To set the primary group to 'None', it must be specified in quotes.
    Otherwise Salt will interpret it as the Python value of None and no primary
    group changes will occur. See the example below.

    CLI Example:

    .. code-block:: bash

        salt '*' file.chown c:\\temp\\test.txt myusername
        salt '*' file.chown c:\\temp\\test.txt myusername pgroup=Administrators
        salt '*' file.chown c:\\temp\\test.txt myusername "pgroup='None'"
    '''
    # the group parameter is not used; only provided for API compatibility
    if group:
        func_name = '{0}.chown'.format(__virtualname__)
        if __opts__.get('fun', '') == func_name:
            log.info(
                'The group parameter has no effect when using {0} on Windows '
                'systems; see function docs for details.'.format(func_name))
        log.debug(
            'win_file.py {0} Ignoring the group parameter for {1}'.format(
                func_name, path))
        group = None

    err = ''
    # get SID object for user
    try:
        userSID, domainName, objectType = win32security.LookupAccountName(
            None, user)
    except pywinerror:
        err += 'User does not exist\n'

    if pgroup:
        # get SID object for group
        try:
            groupSID, domainName, objectType = win32security.LookupAccountName(
                None, pgroup)
        except pywinerror:
            err += 'Group does not exist\n'
    else:
        groupSID = None

    if not os.path.exists(path):
        err += 'File not found'
    if err:
        return err

    if follow_symlinks and sys.getwindowsversion().major >= 6:
        path = _resolve_symlink(path)

    privilege_enabled = False
    try:
        privilege_enabled = _enable_privilege(win32security.SE_RESTORE_NAME)
        if pgroup:
            # set owner and group
            win32security.SetNamedSecurityInfo(
                path, win32security.SE_FILE_OBJECT,
                win32security.OWNER_SECURITY_INFORMATION +
                win32security.GROUP_SECURITY_INFORMATION, userSID, groupSID,
                None, None)
        else:
            # set owner only
            win32security.SetNamedSecurityInfo(
                path, win32security.SE_FILE_OBJECT,
                win32security.OWNER_SECURITY_INFORMATION, userSID, None, None,
                None)
    finally:
        if privilege_enabled:
            _disable_privilege(win32security.SE_RESTORE_NAME)

    return None
Example #21
0
def info(name):
    """
    Get information about a service on the system

    Args:
        name (str): The name of the service. This is not the display name. Use
            ``get_service_name`` to find the service name.

    Returns:
        dict: A dictionary containing information about the service.

    CLI Example:

    .. code-block:: bash

        salt '*' service.info spooler
    """
    try:
        handle_scm = win32service.OpenSCManager(
            None, None, win32service.SC_MANAGER_CONNECT)
    except pywintypes.error as exc:
        raise CommandExecutionError("Failed to connect to the SCM: {0}".format(
            exc.strerror))

    try:
        handle_svc = win32service.OpenService(
            handle_scm,
            name,
            win32service.SERVICE_ENUMERATE_DEPENDENTS
            | win32service.SERVICE_INTERROGATE
            | win32service.SERVICE_QUERY_CONFIG
            | win32service.SERVICE_QUERY_STATUS,
        )
    except pywintypes.error as exc:
        raise CommandExecutionError("Failed To Open {0}: {1}".format(
            name, exc.strerror))

    try:
        config_info = win32service.QueryServiceConfig(handle_svc)
        status_info = win32service.QueryServiceStatusEx(handle_svc)

        try:
            description = win32service.QueryServiceConfig2(
                handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION)
        except pywintypes.error:
            description = "Failed to get description"

        delayed_start = win32service.QueryServiceConfig2(
            handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO)
    finally:
        win32service.CloseServiceHandle(handle_scm)
        win32service.CloseServiceHandle(handle_svc)

    ret = dict()
    try:
        sid = win32security.LookupAccountName(
            "", "NT Service\\{0}".format(name))[0]
        ret["sid"] = win32security.ConvertSidToStringSid(sid)
    except pywintypes.error:
        ret["sid"] = "Failed to get SID"

    ret["BinaryPath"] = config_info[3]
    ret["LoadOrderGroup"] = config_info[4]
    ret["TagID"] = config_info[5]
    ret["Dependencies"] = config_info[6]
    ret["ServiceAccount"] = config_info[7]
    ret["DisplayName"] = config_info[8]
    ret["Description"] = description
    ret["Status_ServiceCode"] = status_info["ServiceSpecificExitCode"]
    ret["Status_CheckPoint"] = status_info["CheckPoint"]
    ret["Status_WaitHint"] = status_info["WaitHint"]
    ret["StartTypeDelayed"] = delayed_start

    flags = list()
    for bit in SERVICE_TYPE:
        if isinstance(bit, int):
            if config_info[0] & bit:
                flags.append(SERVICE_TYPE[bit])

    ret["ServiceType"] = flags if flags else config_info[0]

    flags = list()
    for bit in SERVICE_CONTROLS:
        if status_info["ControlsAccepted"] & bit:
            flags.append(SERVICE_CONTROLS[bit])

    ret["ControlsAccepted"] = flags if flags else status_info[
        "ControlsAccepted"]

    try:
        ret["Status_ExitCode"] = SERVICE_ERRORS[status_info["Win32ExitCode"]]
    except KeyError:
        ret["Status_ExitCode"] = status_info["Win32ExitCode"]

    try:
        ret["StartType"] = SERVICE_START_TYPE[config_info[1]]
    except KeyError:
        ret["StartType"] = config_info[1]

    try:
        ret["ErrorControl"] = SERVICE_ERROR_CONTROL[config_info[2]]
    except KeyError:
        ret["ErrorControl"] = config_info[2]

    try:
        ret["Status"] = SERVICE_STATE[status_info["CurrentState"]]
    except KeyError:
        ret["Status"] = status_info["CurrentState"]

    return ret
Example #22
0
def info(name):
    '''
    Get information about a service on the system

    Args:
        name (str): The name of the service. This is not the display name. Use
        ``get_service_name`` to find the service name.

    Returns:
        dict: A dictionary containing information about the service.

    CLI Example:

    .. code-block:: bash

        salt '*' service.info spooler
    '''
    handle_scm = win32service.OpenSCManager(
        None, None, win32service.SC_MANAGER_CONNECT)

    try:
        handle_svc = win32service.OpenService(
            handle_scm, name,
            win32service.SERVICE_ENUMERATE_DEPENDENTS |
            win32service.SERVICE_INTERROGATE |
            win32service.SERVICE_QUERY_CONFIG |
            win32service.SERVICE_QUERY_STATUS)
    except pywintypes.error as exc:
        raise CommandExecutionError(
            'Failed To Open {0}: {1}'.format(name, exc[2]))

    try:
        config_info = win32service.QueryServiceConfig(handle_svc)
        status_info = win32service.QueryServiceStatusEx(handle_svc)
        description = win32service.QueryServiceConfig2(
            handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION)
        delayed_start = win32service.QueryServiceConfig2(
            handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO)
    finally:
        win32service.CloseServiceHandle(handle_scm)
        win32service.CloseServiceHandle(handle_svc)

    sid = win32security.LookupAccountName('', 'NT Service\\{0}'.format(name))[0]

    ret = dict()
    ret['BinaryPath'] = config_info[3]
    ret['LoadOrderGroup'] = config_info[4]
    ret['TagID'] = config_info[5]
    ret['Dependencies'] = config_info[6]
    ret['ServiceAccount'] = config_info[7]
    ret['DisplayName'] = config_info[8]
    ret['Description'] = description
    ret['sid'] = win32security.ConvertSidToStringSid(sid)
    ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode']
    ret['Status_CheckPoint'] = status_info['CheckPoint']
    ret['Status_WaitHint'] = status_info['WaitHint']
    ret['StartTypeDelayed'] = delayed_start

    flags = list()
    for bit in SERVICE_TYPE:
        if isinstance(bit, int):
            if config_info[0] & bit:
                flags.append(SERVICE_TYPE[bit])

    ret['ServiceType'] = flags if flags else config_info[0]

    flags = list()
    for bit in SERVICE_CONTROLS:
        if status_info['ControlsAccepted'] & bit:
            flags.append(SERVICE_CONTROLS[bit])

    ret['ControlsAccepted'] = flags if flags else status_info['ControlsAccepted']

    try:
        ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']]
    except KeyError:
        ret['Status_ExitCode'] = status_info['Win32ExitCode']

    try:
        ret['StartType'] = SERVICE_START_TYPE[config_info[1]]
    except KeyError:
        ret['StartType'] = config_info[1]

    try:
        ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]]
    except KeyError:
        ret['ErrorControl'] = config_info[2]

    try:
        ret['Status'] = SERVICE_STATE[status_info['CurrentState']]
    except KeyError:
        ret['Status'] = status_info['CurrentState']

    return ret
Example #23
0
import pywintypes, win32security
sa = pywintypes.SECURITY_ATTRIBUTES()
tmp_sid = win32security.LookupAccountName('', 'tmp')[0]
sa.SetSecurityDescriptorOwner(tmp_sid, 0)
sid = sa.SECURITY_DESCRIPTOR.GetSecurityDescriptorOwner()
print win32security.LookupAccountSid('', sid)
Example #24
0
all_security_info = (win32security.OWNER_SECURITY_INFORMATION
                     | win32security.GROUP_SECURITY_INFORMATION
                     | win32security.DACL_SECURITY_INFORMATION
                     | win32security.SACL_SECURITY_INFORMATION)

sd = win32security.GetFileSecurity(fname, all_security_info)

old_sacl = sd.GetSecurityDescriptorSacl()
if old_sacl == None:
    old_sacl = win32security.ACL()
old_dacl = sd.GetSecurityDescriptorDacl()
if old_dacl == None:
    old_dacl = win32security.ACL()

my_sid = win32security.GetTokenInformation(th, ntsecuritycon.TokenUser)[0]
tmp_sid = win32security.LookupAccountName("", "tmp")[0]
pwr_sid = win32security.LookupAccountName("", "Power Users")[0]

## MultipleTrustee,MultipleTrusteeOperation,TrusteeForm,TrusteeType,Identifier
## first two are ignored
my_trustee = {}
my_trustee["MultipleTrustee"] = None
my_trustee["MultipleTrusteeOperation"] = 0
my_trustee["TrusteeForm"] = TRUSTEE_FORM.TRUSTEE_IS_SID
my_trustee["TrusteeType"] = TRUSTEE_TYPE.TRUSTEE_IS_USER
my_trustee["Identifier"] = my_sid

tmp_trustee = {}
tmp_trustee["MultipleTrustee"] = None
tmp_trustee["MultipleTrusteeOperation"] = 0
tmp_trustee["TrusteeForm"] = TRUSTEE_FORM.TRUSTEE_IS_NAME
Example #25
0
                                        win32security.SE_SYSTEM_PROFILE_NAME),
     win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue(
         '',
         win32security.SE_LOCK_MEMORY_NAME), win32con.SE_PRIVILEGE_ENABLED))

all_info = win32security.OWNER_SECURITY_INFORMATION | win32security.GROUP_SECURITY_INFORMATION | \
           win32security.DACL_SECURITY_INFORMATION | win32security.SACL_SECURITY_INFORMATION

pid = win32api.GetCurrentProcessId()
ph = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, pid)
## PROCESS_ALL_ACCESS does not contain ACCESS_SYSTEM_SECURITY (neccessy to do SACLs)
th = win32security.OpenProcessToken(
    ph, win32security.TOKEN_ALL_ACCESS)  ##win32con.TOKEN_ADJUST_PRIVILEGES)
old_privs = win32security.AdjustTokenPrivileges(th, 0, new_privs)
my_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
pwr_sid = win32security.LookupAccountName('', 'Power Users')[0]
## reopen process with ACCESS_SYSTEM_SECURITY now that sufficent privs are enabled
ph = win32api.OpenProcess(
    win32con.PROCESS_ALL_ACCESS | win32con.ACCESS_SYSTEM_SECURITY, 0, pid)

sd = win32security.GetSecurityInfo(ph, win32security.SE_KERNEL_OBJECT,
                                   all_info)
dacl = sd.GetSecurityDescriptorDacl()
if dacl is None:
    dacl = win32security.ACL()
sacl = sd.GetSecurityDescriptorSacl()
if sacl is None:
    sacl = win32security.ACL()

dacl_ace_cnt = dacl.GetAceCount()
sacl_ace_cnt = sacl.GetAceCount()
Example #26
0
def define_trusted_principals(options):
    exploitable_by_fq = []
    ignore_principals = []
    if options.exploitable_by_list:
        exploitable_by_fq = options.exploitable_by_list
    if options.exploitable_by_file:
        try:
            exploitable_by_fq = exploitable_by_fq + [
                line.strip() for line in open(options.exploitable_by_file)
            ]
        except:
            print "[E] Error reading from file %s" % options.exploitablebyfile
            sys.exit()
    if options.ignore_principal_list:
        ignore_principals = options.ignore_principal_list
    if options.ignore_principal_file:
        try:
            ignore_principals = ignore_principals + [
                line.strip() for line in open(options.ignoreprincipalfile)
            ]
        except:
            print "[E] Error reading from file %s" % options.ignoreprincipalfile
            sys.exit()

    # examine token, populate exploitable_by
    if options.exploitable_by_me:
        try:
            p = process(os.getpid())
            wpc.conf.exploitable_by.append(p.get_token().get_token_owner())
            for g in p.get_token().get_token_groups():
                if "|".join(g[1]).find("USE_FOR_DENY_ONLY") == -1:
                    wpc.conf.exploitable_by.append(g[0])
        except:
            print "[E] Problem examining access token of current process"
            sys.exit()

    # check each of the supplied users in exploitable_by and exploitable_by resolve

    if exploitable_by_fq or wpc.conf.exploitable_by:
        wpc.conf.privesc_mode = "exploitable_by"
        for t in exploitable_by_fq:
            try:
                sid, _, _ = win32security.LookupAccountName(
                    wpc.conf.remote_server, t)
                if sid:
                    p = principal(sid)
                    #print "Trusted: %s (%s) [%s]" % (p.get_fq_name(), p.get_type_string(), p.is_group_type())
                    #print "[D] Added trusted principal %s.  is group? %s" % (p.get_fq_name(), p.is_group_type())
                    if p.is_group_type():
                        p = Group(p.get_sid())
                    #    for m in p.get_members():
                    #        print "Member: %s" % m.get_fq_name()
                    else:
                        p = user(p.get_sid())
                    #    print p.get_groups()

                    wpc.conf.exploitable_by.append(p)

                else:
                    print "[E] can't look up sid for " + t
            except:
                pass

        print "Only reporting privesc issues for these users/groups:"
        for p in wpc.conf.exploitable_by:
            print "* " + p.get_fq_name()
        return
    else:
        wpc.conf.privesc_mode = "report_untrusted"

    # if user has specified list of trusted users, use only their list
    if ignore_principals:
        if options.ignorenoone:
            wpc.conf.trusted_principals_fq = []
        wpc.conf.trusted_principals_fq = wpc.conf.trusted_principals_fq + ignore_principals
    else:
        # otherwise the user has not specified a list of trusted users.  we intelligently tweak the list.
        # Ignore "NT AUTHORITY\TERMINAL SERVER USER" if HKLM\System\CurrentControlSet\Control\Terminal Server\TSUserEnabled = 0 or doesn't exist
        # See http://support.microsoft.com/kb/238965 for details
        r = regkey(
            r"HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Terminal Server"
        )

        if r.is_present():
            v = r.get_value("TSUserEnabled")
            if v is None:
                print "[i] TSUserEnabled registry value is absent. Excluding TERMINAL SERVER USER"
            elif v != 0:
                print "[i] TSUserEnabled registry value is %s. Including TERMINAL SERVER USER" % v
                wpc.conf.trusted_principals_fq.append(
                    "NT AUTHORITY\TERMINAL SERVER USER")
            else:
                print "[i] TSUserEnabled registry value is 0. Excluding TERMINAL SERVER USER"
        else:
            print "[i] TSUserEnabled registry key is absent. Excluding TERMINAL SERVER USER"
        print

        # TODO we only want to ignore this if it doesn't resolve
        try:
            # Server Operators group
            #print "[D] converting string sid"
            #print "%s" % win32security.ConvertStringSidToSid("S-1-5-32-549")
            p = Group(win32security.ConvertStringSidToSid("S-1-5-32-549"))

        except:
            wpc.conf.trusted_principals.append(p)

        # TODO this always ignored power users.  not what we want.
        # only want to ignore when group doesn't exist.
        try:
            p = Group(win32security.ConvertStringSidToSid("S-1-5-32-547"))
            wpc.conf.trusted_principals.append(p)
        except:
            pass

    # populate wpc.conf.trusted_principals with the objects corresponding to trusted_principals_fq
    for t in wpc.conf.trusted_principals_fq:
        try:
            sid, _, _ = win32security.LookupAccountName(
                wpc.conf.remote_server, t)
            if sid:
                p = principal(sid)
                #print "Trusted: %s (%s) [%s]" % (p.get_fq_name(), p.get_type_string(), p.is_group_type())
                #print "[D] Added trusted principal %s.  is group? %s" % (p.get_fq_name(), p.is_group_type())
                if p.is_group_type():
                    p = Group(p.get_sid())
                #    for m in p.get_members():
                #        print "Member: %s" % m.get_fq_name()
                else:
                    p = user(p.get_sid())
                #    print p.get_groups()

                wpc.conf.trusted_principals.append(p)

            else:
                print "[E] can't look up sid for " + t
        except:
            pass

    print "Considering these users to be trusted:"
    for p in wpc.conf.trusted_principals:
        print "* " + p.get_fq_name()
    print
Example #27
0
 def testBuffer(self):
     self.failUnlessEqual(ob2memory(win32security.LookupAccountName('','Administrator')[0]),
                          ob2memory(win32security.LookupAccountName('','Administrator')[0]))
Example #28
0
def check_ace(path, objectType, user=None, permission=None, acetype=None, propagation=None, exactPermissionMatch=False):
    '''
    checks a path to verify the ACE (access control entry) specified exists
    returns 'Exists' true if the ACE exists, false if it does not

    path:  path to the file/reg key
    user:  user that the ACL is for
    permission:  permission to test for (READ, FULLCONTROl, etc)
    acetype:  the type of ACE (ALLOW or DENY)
    propagation:  the propagation type of the ACE (FILES, FOLDERS, KEY, KEY&SUBKEYS, SUBKEYS, etc)
    exactPermissionMatch:  the ACL must match exactly, IE if READ is specified, the user must have READ exactly and not FULLCONTROL (which also has the READ permission obviously)

    '''
    ret = {'result': False,
           'Exists': False,
           'comment': []}

    dc = daclConstants()
    objectTypeBit = dc.getObjectTypeBit(objectType)
    path = dc.processPath(path, objectTypeBit)

    permission = permission.upper()
    acetype = acetype.upper()
    propagation = propagation.upper()

    permissionbit = dc.getPermissionBit(objectTypeBit, permission)
    acetypebit = dc.getAceTypeBit(acetype)
    propagationbit = dc.getPropagationBit(objectTypeBit, propagation)

    try:
        userSid = win32security.LookupAccountName('', user)[0]
    except Exception as e:
        ret['result'] = False
        ret['comment'].append((
            'Unable to obtain the security identifier for {0}.  The exception was {1}'
            ).format(user, e))
        return ret

    dacls = _get_dacl(path, objectTypeBit)
    if dacls:
        if objectTypeBit == win32security.SE_FILE_OBJECT:
            if check_inheritance(path, objectType)['Inheritance']:
                if permission == 'FULLCONTROL':
                    # if inhertiance is enabled on an SE_FILE_OBJECT, then the SI_NO_ACL_PROTECT
                    # gets unset on FullControl which greys out the include inheritable permission
                    # checkbox on the advanced security settings gui page
                    permissionbit = permissionbit ^ ntsecuritycon.SI_NO_ACL_PROTECT
        for counter in range(0, dacls.GetAceCount()):
            ace = dacls.GetAce(counter)
            if ace[2] == userSid:
                if ace[0][0] == acetypebit:
                    if (ace[0][1] & propagationbit) == propagationbit:
                        if exactPermissionMatch:
                            if ace[1] == permissionbit:
                                ret['result'] = True
                                ret['Exists'] = True
                                return ret
                        else:
                            if (ace[1] & permissionbit) == permissionbit:
                                ret['result'] = True
                                ret['Exists'] = True
                                return ret
    else:
        ret['result'] = False
        ret['comment'].append(
            'Error obtaining DACL for object')
    ret['result'] = True
    return ret