Ejemplo n.º 1
0
 def testMemory(self):
     pwr_sid = self.pwr_sid
     admin_sid = self.admin_sid
     sd1 = win32security.SECURITY_DESCRIPTOR()
     sd2 = win32security.SECURITY_DESCRIPTOR()
     sd3 = win32security.SECURITY_DESCRIPTOR()
     dacl = win32security.ACL()
     dacl.AddAccessAllowedAce(win32security.ACL_REVISION,
                              win32con.GENERIC_READ, pwr_sid)
     if admin_sid is not None:
         dacl.AddAccessAllowedAce(win32security.ACL_REVISION,
                                  win32con.GENERIC_ALL, admin_sid)
     sd4 = win32security.SECURITY_DESCRIPTOR()
     sacl = win32security.ACL()
     if admin_sid is not None:
         sacl.AddAuditAccessAce(win32security.ACL_REVISION, win32con.DELETE,
                                admin_sid, 1, 1)
     sacl.AddAuditAccessAce(win32security.ACL_REVISION,
                            win32con.GENERIC_ALL, pwr_sid, 1, 1)
     for x in range(0, 200000):
         if admin_sid is not None:
             sd1.SetSecurityDescriptorOwner(admin_sid, 0)
         sd2.SetSecurityDescriptorGroup(pwr_sid, 0)
         sd3.SetSecurityDescriptorDacl(1, dacl, 0)
         sd4.SetSecurityDescriptorSacl(1, sacl, 0)
Ejemplo n.º 2
0
 def test_Security_set_sacl_none(self):
     s = security.security()
     s.sacl = None
     assert s.pyobject().GetSecurityDescriptorSacl() is None
     sd = win32security.SECURITY_DESCRIPTOR()
     sd.SetSecurityDescriptorSacl(1, None, 0)
     assert equal(sd, s)
Ejemplo n.º 3
0
  def change_acl_for_delete(path):
    """Zaps the SECURITY_DESCRIPTOR's DACL on a directory entry that is tedious
    to delete.

    This function is a heavy hammer. It discards the SECURITY_DESCRIPTOR and
    creates a new one with only one DACL set to user:FILE_ALL_ACCESS.

    Used as last resort.
    """
    STANDARD_RIGHTS_REQUIRED = 0xf0000
    SYNCHRONIZE = 0x100000
    FILE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3ff

    import win32security
    user, _domain, _type = win32security.LookupAccountName(
        '', getpass.getuser())
    sd = win32security.SECURITY_DESCRIPTOR()
    sd.Initialize()
    sd.SetSecurityDescriptorOwner(user, False)
    dacl = win32security.ACL()
    dacl.Initialize()
    dacl.AddAccessAllowedAce(
        win32security.ACL_REVISION_DS, FILE_ALL_ACCESS, user)
    sd.SetSecurityDescriptorDacl(1, dacl, 0)
    # Note that this assumes the object is either owned by the current user or
    # its group or that the current ACL permits this. Otherwise it will silently
    # fail.
    win32security.SetFileSecurity(
        fs.extend(path), win32security.DACL_SECURITY_INFORMATION, sd)
    # It's important to also look for the read only bit after, as it's possible
    # the set_read_only() call to remove the read only bit had silently failed
    # because there was no DACL for the user.
    if not (os.stat(path).st_mode & stat.S_IWUSR):
      os.chmod(path, 0777)
Ejemplo n.º 4
0
def change_acl_for_delete_win(path):
    """Zaps the SECURITY_DESCRIPTOR's DACL on a directory entry that is tedious to
  delete.

  This function is a heavy hammer. It discards the SECURITY_DESCRIPTOR and
  creates a new one with only one DACL set to user:FILE_ALL_ACCESS.

  Used as last resort.
  """
    assert isinstance(path, unicode), path
    STANDARD_RIGHTS_REQUIRED = 0xf0000
    SYNCHRONIZE = 0x100000
    FILE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3ff

    import win32security
    user, _domain, _type = win32security.LookupAccountName(
        '', getpass.getuser())
    sd = win32security.SECURITY_DESCRIPTOR()
    sd.Initialize()
    sd.SetSecurityDescriptorOwner(user, False)
    dacl = win32security.ACL()
    dacl.Initialize()
    dacl.AddAccessAllowedAce(win32security.ACL_REVISION_DS, FILE_ALL_ACCESS,
                             user)
    sd.SetSecurityDescriptorDacl(1, dacl, 0)
    win32security.SetFileSecurity(path,
                                  win32security.DACL_SECURITY_INFORMATION, sd)
Ejemplo n.º 5
0
 def test_Security_set_group(self):
     everyone = security.principal("Everyone")
     s = security.security()
     s.group = "Everyone"
     assert s.group == everyone
     sd = win32security.SECURITY_DESCRIPTOR()
     sd.SetSecurityDescriptorGroup(everyone.pyobject(), 0)
     assert equal(sd, s)
Ejemplo n.º 6
0
 def GetSecurity(self, requestedinfo, bdefault):
     """Requests the existing permissions for object"""
     if bdefault:
         return win32security.SECURITY_DESCRIPTOR()
     else:
         return win32security.GetNamedSecurityInfo(self.ServiceName,
                                                   win32security.SE_SERVICE,
                                                   requestedinfo)
Ejemplo n.º 7
0
 def test_Security_set_owner(self):
     administrator = security.principal("Administrator")
     s = security.security()
     s.owner = "Administrator"
     assert s.owner == administrator
     sd = win32security.SECURITY_DESCRIPTOR()
     sd.SetSecurityDescriptorOwner(administrator.pyobject(), 0)
     assert equal(sd, s)
Ejemplo n.º 8
0
 def test_Security_set_sacl_empty(self):
     s = security.security()
     s.sacl = []
     assert len(s.sacl) == 0
     assert s.pyobject().GetSecurityDescriptorSacl().GetAceCount() == 0
     sd = win32security.SECURITY_DESCRIPTOR()
     acl = win32security.ACL()
     sd.SetSecurityDescriptorSacl(1, acl, 0)
     assert equal(sd, s)
Ejemplo n.º 9
0
def updateACL(handle, acl):
    # Create a new security descriptor for handle and set its DACL.
    new_security_desc = win32security.SECURITY_DESCRIPTOR()
    new_security_desc.SetSecurityDescriptorDacl(True, acl, False)

    # Set the new security descriptor for winsta.
    win32security.SetUserObjectSecurity(handle,
                                        win32con.DACL_SECURITY_INFORMATION,
                                        new_security_desc)
Ejemplo n.º 10
0
def TakeOwnership(username, folder):
    try:
        account_sid = (win32security.LookupAccountName(None, username))[0]
        print("Setting " + username + " to owner on " + folder)
        sd = win32security.SECURITY_DESCRIPTOR()
        sd.SetSecurityDescriptorOwner(account_sid, 0)
        win32security.SetFileSecurity(folder,
                                      win32security.OWNER_SECURITY_INFORMATION,
                                      sd)
    except Exception as er:
        print("TakeOwnership Exception: %s" % type(er).__name__)
Ejemplo n.º 11
0
 def GetSecurity(self, requestedinfo, bdefault):
     """Requests the existing permissions for object"""
     if bdefault:
         ## This is invoked if the 'Default' button is pressed (only present if SI_RESET is passed
         ## with the flags in GetObjectInfo). Passing an empty SD with a NULL Dacl
         ##  should cause inherited ACL from parent dir or default dacl from user's token to be used
         return win32security.SECURITY_DESCRIPTOR()
     else:
         ## GetFileSecurity sometimes fails to return flags indicating that an ACE is inherited
         return win32security.GetNamedSecurityInfo(
             self.FileName, win32security.SE_FILE_OBJECT, requestedinfo)
Ejemplo n.º 12
0
def test_Security_add_to_sacl_simple():
    administrator = security.principal("Administrator")
    s = security.security()
    s.sacl = []
    s.sacl.append(("Administrator", "F", "SUCCESS"))
    sd = win32security.SECURITY_DESCRIPTOR()
    sacl = win32security.ACL()
    sacl.AddAuditAccessAceEx(win32security.ACL_REVISION_DS,
                             security.SACE.FLAGS, ntsecuritycon.GENERIC_ALL,
                             administrator.pyobject(), 1, 0)
    sd.SetSecurityDescriptorSacl(1, sacl, 0)
    assert equal(sd, s)
Ejemplo n.º 13
0
def test_Security_add_to_dacl_simple():
    administrator = security.principal("Administrator")
    s = security.security()
    s.dacl = []
    s.dacl.append(("Administrator", "F", "ALLOW"))
    sd = win32security.SECURITY_DESCRIPTOR()
    dacl = win32security.ACL()
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS,
                               security.DACE.FLAGS, ntsecuritycon.GENERIC_ALL,
                               administrator.pyobject())
    sd.SetSecurityDescriptorDacl(1, dacl, 0)
    assert equal(sd, s)
Ejemplo n.º 14
0
    def grantEveryoneFilePermission(self, dirpath, filepath=""):
        """Grant full control to the group I{Everyone} in this folder and all sub-folders

        This function grants full control to the Windows group I{Everyone} for files in the
        C{dirpath} its sub-folders.
        If a C{filepath} is specified, only the permissions of a specific file are updated.

        @type dirpath: string
        @param dirpath: The full path of the folder for which these permissions are set
        @type filepath: string
        @param filepath: The full path to a specific file.
        """

        # Execute command only on NTFS filesystem. Otherwise pass silently
        fullpath = os.path.abspath(dirpath)
        driveLetter = os.path.splitdrive(fullpath)[0]
        if not self.isNTFSVolume(driveLetter):
            pylabs.q.logger.log(
                "Skipped file permissions update - filesystem for [%s] is not NTFS"
                % dirpath, 6)
            return

        def _grantFile(fileName, securityDescriptor):
            '''Set security on a file'''
            pylabs.q.logger.log(
                "granting all access to everyone on %s" % fileName, 6)
            win32security.SetFileSecurity(
                fileName, win32security.DACL_SECURITY_INFORMATION,
                securityDescriptor)

        def _grantDir(dirpath, securityDescriptor):
            '''Set security on a folder'''
            for dir in pylabs.q.system.fs.listDirsInDir(dirpath):
                _grantDir(dir, securityDescriptor)
            for file in pylabs.q.system.fs.listFilesInDir(dirpath):
                _grantFile(file, securityDescriptor)
            win32security.SetFileSecurity(
                dirpath, win32security.DACL_SECURITY_INFORMATION,
                securityDescriptor)

        # create the security descriptor
        sd = win32security.SECURITY_DESCRIPTOR()
        # fill it:
        everyone = win32security.ConvertStringSidToSid('S-1-1-0')
        acl = win32security.ACL(128)
        acl.AddAccessAllowedAce(win32file.FILE_ALL_ACCESS, everyone)
        sd.SetSecurityDescriptorDacl(1, acl, 0)

        if filepath == "":  # it's a dir
            _grantDir(dirpath, sd)
        else:
            _grantFile(os.path.join(dirpath, filepath), sd)
Ejemplo n.º 15
0
def take_ownership(path: str, owner=None, force: bool = True) -> bool:
    """
    Set owner on NTFS & ReFS files / directories, see
    https://stackoverflow.com/a/61009508/2635443

    :param path: (str) path
    :param owner: (PySID) object that represents the security identifier.
                  If not set, current security identifier will be used
    :param force: (bool) Shall we force take ownership
    :return:
    """
    try:
        hToken = win32security.OpenThreadToken(
            win32api.GetCurrentThread(), win32security.TOKEN_ALL_ACCESS, True
        )

    except win32security.error:
        hToken = win32security.OpenProcessToken(
            win32api.GetCurrentProcess(), win32security.TOKEN_ALL_ACCESS
        )
    if owner is None:
        owner = win32security.GetTokenInformation(hToken, win32security.TokenOwner)
    prev_state = ()
    if force:
        new_state = [
            (
                win32security.LookupPrivilegeValue(None, name),
                win32security.SE_PRIVILEGE_ENABLED,
            )
            for name in (
                win32security.SE_TAKE_OWNERSHIP_NAME,
                win32security.SE_RESTORE_NAME,
            )
        ]
        prev_state = win32security.AdjustTokenPrivileges(hToken, False, new_state)
    try:
        sec_descriptor = win32security.SECURITY_DESCRIPTOR()
        sec_descriptor.SetSecurityDescriptorOwner(owner, False)
        win32security.SetFileSecurity(
            path, win32security.OWNER_SECURITY_INFORMATION, sec_descriptor
        )
    except pywintypes.error as exc:
        # Let's raise OSError so we don't need to import pywintypes in parent module to catch the exception
        raise OSError("Cannot take ownership of file: {0}. {1}.".format(path, exc))
    finally:
        if prev_state:
            win32security.AdjustTokenPrivileges(hToken, False, prev_state)
    return True
Ejemplo n.º 16
0
def CreateUserSecurityDescriptor(userName):
    sidUser = win32security.LookupAccountName(serverName, userName)[0]
    sd = win32security.SECURITY_DESCRIPTOR()

    # Create the "well known" SID for the administrators group
    subAuths = ntsecuritycon.SECURITY_BUILTIN_DOMAIN_RID, \
               ntsecuritycon.DOMAIN_ALIAS_RID_ADMINS
    sidAdmins = win32security.SID(ntsecuritycon.SECURITY_NT_AUTHORITY, subAuths)

    # Now set the ACL, giving user and admin full access.
    acl = win32security.ACL(128)
    acl.AddAccessAllowedAce(win32file.FILE_ALL_ACCESS, sidUser)
    acl.AddAccessAllowedAce(win32file.FILE_ALL_ACCESS, sidAdmins)

    sd.SetSecurityDescriptorDacl(1, acl, 0)
    return sd
Ejemplo n.º 17
0
 def test_undeleteable_owner(self):
   # Create a file and a directory with an empty ACL. Then try to delete it.
   dirpath = os.path.join(self.tempdir, 'd')
   filepath = os.path.join(dirpath, 'f')
   os.mkdir(dirpath)
   with open(filepath, 'w') as f:
     f.write('hi')
   import win32security
   user, _domain, _type = win32security.LookupAccountName(
       '', getpass.getuser())
   sd = win32security.SECURITY_DESCRIPTOR()
   sd.Initialize()
   sd.SetSecurityDescriptorOwner(user, False)
   # Create an empty DACL, which removes all rights.
   dacl = win32security.ACL()
   dacl.Initialize()
   sd.SetSecurityDescriptorDacl(1, dacl, 0)
   win32security.SetFileSecurity(
       fs.extend(filepath), win32security.DACL_SECURITY_INFORMATION, sd)
   win32security.SetFileSecurity(
       fs.extend(dirpath), win32security.DACL_SECURITY_INFORMATION, sd)
   file_path.rmtree(dirpath)
Ejemplo n.º 18
0
def DumpWnfData(WnfName, Data, DumpSd, DumpData):
    assert (WnfName != 0)
    MaxSize = "?"
    sd = None
    if Data != None:
        try:
            sd = win32security.SECURITY_DESCRIPTOR(Data)
        except:
            print(
                "\n[Error] Could not create a security descriptor out of the data for {:x}\n"
                .format(WnfName))

        if sd != None:
            if not sd.IsValid():
                print(
                    "[Error] Registry security descriptor invalid for {:x}\n".
                    format(WnfName))
                MaxSize = 0
                sd = None
            SdSize = sd.GetLength()
            MaxSize = unpack("L", Data[SdSize:SdSize + 4])[0]

    return PrintWnfRuntimeStatus(WnfName, sd, DumpSd, MaxSize, DumpData)
Ejemplo n.º 19
0
def get_security_descriptor_for_owner_only_perms():
    user_sid = get_user_pySID_object()
    security_descriptor = win32security.SECURITY_DESCRIPTOR()
    dacl = win32security.ACL()

    entries = [{
        "AccessMode":
        win32security.GRANT_ACCESS,
        "AccessPermissions":
        ntsecuritycon.FILE_ALL_ACCESS,
        "Inheritance":
        win32security.CONTAINER_INHERIT_ACE | win32security.OBJECT_INHERIT_ACE,
        "Trustee": {
            "TrusteeType": win32security.TRUSTEE_IS_USER,
            "TrusteeForm": win32security.TRUSTEE_IS_SID,
            "Identifier": user_sid,
        },
    }]
    dacl.SetEntriesInAcl(entries)

    security_descriptor.SetSecurityDescriptorDacl(1, dacl, 0)

    return security_descriptor
Ejemplo n.º 20
0
    def __init__(self, name, acquired=False, timeout=None):
        '''
        Create named mutex with given name, also acquiring mutex if acquired
        is True. Mutex names are case sensitive, and a filename (with
        slashes or backslashes in it) is not a valid mutex name. On an acquire
        timeout condition, will raise NamedMutexTimeoutException. Raises
        IOError on other errors.
        '''
        self.name = name
        self.acquired = False
        self.handle = None  # In case an exception is thrown below

        if is_windows():
            if '\\' not in name:
                name = 'Global\\' + name
            attr = win32security.SECURITY_ATTRIBUTES()  # pylint: disable=no-member
            attr.bInheritHandle = False
            desc = win32security.SECURITY_DESCRIPTOR()  # pylint: disable=no-member
            desc.SetSecurityDescriptorDacl(1, None, 0)
            attr.SECURITY_DESCRIPTOR = desc
            ret = win32event.CreateMutex(attr, False, name)  # pylint: disable=no-member
            if not ret:
                raise IOError(
                    'Failed to created named mutex "{0}". Error code: {1}'.
                    format(
                        self.name,
                        win32api.GetLastError()  # pylint: disable=no-member
                    ))
            self.handle = ret
        else:
            filename = name + '.lock'
            filename = os.path.join('/var/lock', filename)
            self.handle = open(filename, 'w')  # pylint: disable=resource-leakage

        if acquired:
            # self.acquire() will set 'self.acquired'
            self.acquire(timeout=timeout)
Ejemplo n.º 21
0
    def __init__(self, WnfName=0):
        # generic stuff
        self.StateName = ctypes.c_ulonglong(0)
        self.internalName = WNF_STATE_NAME_INTERNAL()
        self.verbose = True
        if WnfName != 0:
            self.SetStateName(WnfName)

        # callback for the listener
        self.callback_type = ctypes.CFUNCTYPE(ctypes.c_ulonglong,
                                              ctypes.c_ulonglong,
                                              ctypes.c_ulong, ctypes.c_void_p,
                                              ctypes.c_void_p, ctypes.c_void_p,
                                              ctypes.c_ulong)
        self.callback = self.callback_type(self.NotifyCallback)

        # security descriptor used for creating the server part
        everyoneSid = win32security.CreateWellKnownSid(1, None)
        acl = win32security.ACL()
        acl.AddAccessAllowedAce(win32security.ACL_REVISION, GENERIC_ALL,
                                everyoneSid)
        pySd = win32security.SECURITY_DESCRIPTOR()
        pySd.SetSecurityDescriptorDacl(True, acl, False)
        self.rawSd = ctypes.create_string_buffer(memoryview(pySd).tobytes())
Ejemplo n.º 22
0
     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)

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_dacl = sd.GetSecurityDescriptorDacl()
old_sacl = sd.GetSecurityDescriptorSacl()
old_group = sd.GetSecurityDescriptorGroup()

new_sd = win32security.SECURITY_DESCRIPTOR()
print("relative, valid, size: ", new_sd.IsSelfRelative(), new_sd.IsValid(),
      new_sd.GetLength())

my_sid = win32security.GetTokenInformation(th, ntsecuritycon.TokenUser)[0]
tmp_sid = win32security.LookupAccountName('', 'tmp')[0]

new_sd.SetSecurityDescriptorSacl(1, old_sacl, 1)
new_sd.SetSecurityDescriptorDacl(1, old_dacl, 1)
new_sd.SetSecurityDescriptorOwner(tmp_sid, 0)
new_sd.SetSecurityDescriptorGroup(old_group, 0)

win32security.SetFileSecurity(fname, all_security_info, new_sd)
Ejemplo n.º 23
0
    def run(self):

        import eg

        # This is where the permissions get created for the pipe
        eg.PrintDebugNotice('Pipe: Creating security descriptor')
        security_attributes = win32security.SECURITY_ATTRIBUTES()
        security_descriptor = win32security.SECURITY_DESCRIPTOR()
        security_descriptor.SetSecurityDescriptorDacl(1, None, 0)
        security_attributes.SECURITY_DESCRIPTOR = security_descriptor
        eg.PrintDebugNotice('Pipe 0: Creating Pipe')

        pipe = win32pipe.CreateNamedPipe(
            r'\\.\pipe\eventghost',
            PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE,
            PIPE_TYPE_MESSAGE | PIPE_WAIT | PIPE_READMODE_MESSAGE,
            PIPE_UNLIMITED_INSTANCES, 4096, 4096, 5, security_attributes)

        while True:
            self.is_waiting = True
            pipe_id = self.get_pipe_id()

            # creation of the pipe. once the pipe has been made it will sit
            # and wait for data to be written to the pipe. once data has been
            # written it will then read the data and close the pipe. then it
            # will parse the data sent and execute the command. It will loop
            # like this the entire time EG is running. The thread that handles
            # the pipe is a daemon thread and the thread will be terminated
            # when EG closes.

            win32pipe.ConnectNamedPipe(pipe, None)

            self.running_pipes += [self]

            if len(self.running_pipes) > 1:
                if not self.running_pipes[-1].is_waiting:
                    self.running_pipes += [
                        Pipe(self, self.get_pipe_id(), security_attributes)
                    ]
            else:
                self.running_pipes += [
                    Pipe(self, self.get_pipe_id(), security_attributes)
                ]

            data = win32file.ReadFile(pipe, 4096)
            self.is_waiting = False

            eg.PrintDebugNotice('Pipe {0}: Data received'.format(pipe_id))

            if data[0] == 0:
                event = threading.Event()
                res = ['']

                self.process_command.add(pipe_id, data[1], res, event)

                while not event.isSet():
                    pass

                win32file.WriteFile(pipe, str(repr(res[0])))
                win32pipe.DisconnectNamedPipe(pipe)

            else:
                try:
                    raise NamedPipeDataError(
                        'Pipe {0}: Unknown Error: {1}'.format(
                            pipe_id, str(data)))
                except NamedPipeDataError:
                    traceback.print_exc()
            self.running_pipes.remove(self)
Ejemplo n.º 24
0
    def _server_pipe_handle(self, first):
        # Return a wrapper for a new pipe handle.
        try:
            if self.closed():
                return None
        except AttributeError:
            if self._address is None:
                return None

        # Create a new SECURITY_ATTRIBUTES object to open up write permissions to non-elevated clients.
        # Get the SID of this process' owner to add to the new DACL
        owner_sid = win32security.GetTokenInformation(
            win32security.OpenProcessToken(win32api.GetCurrentProcess(),
                                           win32security.TOKEN_QUERY),
            win32security.TokenOwner)

        # Build the new ACL -- SYSTEM, built-in Administrators and the Owner get full control (like default)
        acl = win32security.ACL()  # Default buffer size of 64 OK
        acl.AddAccessAllowedAce(
            win32file.FILE_ALL_ACCESS,
            win32security.CreateWellKnownSid(win32security.WinLocalSystemSid))
        acl.AddAccessAllowedAce(
            win32file.FILE_ALL_ACCESS,
            win32security.CreateWellKnownSid(
                win32security.WinBuiltinAdministratorsSid))
        acl.AddAccessAllowedAce(win32file.FILE_ALL_ACCESS, owner_sid)

        # Allow all Users to both Read and Write to the pipe:
        # See http://stackoverflow.com/questions/29947524/c-let-user-process-write-to-local-system-named-pipe-custom-security-descrip
        acl.AddAccessAllowedAce(
            ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_WRITE_DATA,
            win32security.CreateWellKnownSid(win32security.WinBuiltinUsersSid))

        # Construct new SECUIRTY_ATTRIBUTES AND SECURITY_DESCRIPTOR objects
        new_sa = win32security.SECURITY_ATTRIBUTES()
        new_sd = win32security.SECURITY_DESCRIPTOR()

        # Add the ACL to the SECURITY_DESCRIPTOR:
        new_sd.SetDacl(True, acl, False)

        # Add the SECURITY_DESCRIPTOR to the SECURITY_ATTRIBUTES object and set the Inheritance flag
        new_sa.SECURITY_DESCRIPTOR = new_sd
        new_sa.bInheritHandle = False

        PIPE_REJECT_REMOTE_CLIENTS = 0x8
        flags = _winapi.PIPE_ACCESS_DUPLEX | _winapi.FILE_FLAG_OVERLAPPED
        if first:
            flags |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE

        py_pipe = win32pipe.CreateNamedPipe(
            self._address, flags,
            win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE
            | win32pipe.PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
            win32pipe.PIPE_UNLIMITED_INSTANCES, windows_utils.BUFSIZE,
            windows_utils.BUFSIZE, win32pipe.NMPWAIT_WAIT_FOREVER, new_sa)

        # Extract the handle number from the PyHandle Object and pass it the Aysncio PipeHandle constructor
        pipe = windows_utils.PipeHandle(py_pipe.handle)

        # IMPORTANT: Detach the handle from the PyHandle object so it is not auto-closed when py_pipe is destroyed!
        py_pipe.Detach()

        self._free_instances.add(pipe)

        return pipe
Ejemplo n.º 25
0
def create_named_pipe(pipename,
                      openMode=None,
                      pipeMode=None,
                      nMaxInstances=None,
                      nOutBufferSize=None,
                      nInBufferSize=None,
                      nDefaultTimeOut=None,
                      saAttr=-1):
    # Default values if parameters are not passed
    if openMode is None:
        openMode = win32con.PIPE_ACCESS_DUPLEX | win32con.FILE_FLAG_OVERLAPPED
    if pipeMode is None:
        pipeMode = (win32con.PIPE_TYPE_MESSAGE | win32con.PIPE_READMODE_BYTE
                    | win32con.PIPE_WAIT)
    if nMaxInstances is None:
        nMaxInstances = 64
    if nOutBufferSize is None:
        nOutBufferSize = 65000
    if nInBufferSize is None:
        nInBufferSize = 65000
    if nDefaultTimeOut is None:
        nDefaultTimeOut = 0
    if saAttr == -1:
        # saAttr can be None
        saAttr = win32security.SECURITY_ATTRIBUTES()

        # The identifier authority.
        sia = ntsecuritycon.SECURITY_NT_AUTHORITY

        # Initialize the SID.
        remoteAccessSid = win32security.SID()
        remoteAccessSid.Initialize(
            sia,  # The identifier authority.
            1)  # The number of sub authorities to allocate.
        # Disable access over network.
        remoteAccessSid.SetSubAuthority(
            0,  # The index of the sub authority to set
            ntsecuritycon.SECURITY_NETWORK_RID)

        allowedPsids = []
        # Allow Windows Services to access the Named Pipe.
        allowedPsid_0 = win32security.SID()
        allowedPsid_0.Initialize(
            sia,  # The identifier authority.
            1)  # The number of sub authorities to allocate.
        allowedPsid_0.SetSubAuthority(
            0,  # The index of the sub authority to set
            ntsecuritycon.SECURITY_LOCAL_SYSTEM_RID)
        # Allow Administrators to access the Named Pipe.
        allowedPsid_1 = win32security.SID()
        allowedPsid_1.Initialize(
            sia,  # The identifier authority.
            2)  # The number of sub authorities to allocate.
        allowedPsid_1.SetSubAuthority(
            0,  # The index of the sub authority to set
            ntsecuritycon.SECURITY_BUILTIN_DOMAIN_RID)
        allowedPsid_1.SetSubAuthority(
            1,  # The index of the sub authority to set
            ntsecuritycon.DOMAIN_ALIAS_RID_ADMINS)

        allowedPsids.append(allowedPsid_0)
        allowedPsids.append(allowedPsid_1)

        # Initialize an ACL.
        acl = win32security.ACL()
        acl.Initialize()
        # Add denied ACL.
        acl.AddAccessDeniedAce(win32security.ACL_REVISION,
                               ntsecuritycon.GENERIC_ALL, remoteAccessSid)
        # Add allowed ACLs.
        for allowedPsid in allowedPsids:
            acl.AddAccessAllowedAce(win32security.ACL_REVISION,
                                    ntsecuritycon.GENERIC_ALL, allowedPsid)

        # Initialize an SD.
        sd = win32security.SECURITY_DESCRIPTOR()
        sd.Initialize()
        # Set DACL.
        sd.SetSecurityDescriptorDacl(True, acl, False)

        saAttr.bInheritHandle = 1
        saAttr.SECURITY_DESCRIPTOR = sd

    try:
        npipe = win32pipe.CreateNamedPipe(pipename, openMode, pipeMode,
                                          nMaxInstances, nOutBufferSize,
                                          nInBufferSize, nDefaultTimeOut,
                                          saAttr)

        if npipe == win32file.INVALID_HANDLE_VALUE:
            return None

        return npipe
    except pywintypes.error:
        return None