Beispiel #1
0
def set_file_readable(filename):
    import win32api
    import win32security
    import ntsecuritycon as con

    WinBuiltinUsersSid = 27  # not exported by win32security. according to WELL_KNOWN_SID_TYPE enumeration from http://msdn.microsoft.com/en-us/library/windows/desktop/aa379650%28v=vs.85%29.aspx
    users = win32security.CreateWellKnownSid(WinBuiltinUsersSid)
    WinBuiltinAdministratorsSid = 26  # not exported by win32security. according to WELL_KNOWN_SID_TYPE enumeration from http://msdn.microsoft.com/en-us/library/windows/desktop/aa379650%28v=vs.85%29.aspx
    admins = win32security.CreateWellKnownSid(WinBuiltinAdministratorsSid)
    user, domain, type = win32security.LookupAccountName(
        "", win32api.GetUserName())

    sd = win32security.GetFileSecurity(filename,
                                       win32security.DACL_SECURITY_INFORMATION)

    dacl = win32security.ACL()
    dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS,
                             users)
    dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS,
                             user)
    dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS,
                             admins)
    sd.SetSecurityDescriptorDacl(1, dacl, 0)
    win32security.SetFileSecurity(filename,
                                  win32security.DACL_SECURITY_INFORMATION, sd)
Beispiel #2
0
def win32_restrict_file_to_user(fname):
    """Secure a windows file to read-only access for the user.
    Follows guidance from win32 library creator:
    http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html

    This method should be executed against an already generated file which
    has no secrets written to it yet.

    Parameters
    ----------

    fname : unicode
        The path to the file to secure
    """
    import win32api
    import win32security
    import ntsecuritycon as con

    # everyone, _domain, _type = win32security.LookupAccountName("", "Everyone")
    admins = win32security.CreateWellKnownSid(win32security.WinBuiltinAdministratorsSid)
    user, _domain, _type = win32security.LookupAccountName("", win32api.GetUserName())

    sd = win32security.GetFileSecurity(fname, win32security.DACL_SECURITY_INFORMATION)

    dacl = win32security.ACL()
    # dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, everyone)
    dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_GENERIC_READ | con.FILE_GENERIC_WRITE, user)
    dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, admins)

    sd.SetSecurityDescriptorDacl(1, dacl, 0)
    win32security.SetFileSecurity(fname, win32security.DACL_SECURITY_INFORMATION, sd)
def removeReadOnlyAccess(path=None):
    try:
        if os.path.exists(path):
            everyone = win32security.CreateWellKnownSid(
                win32security.WinWorldSid)
            #Delete ace
            sd = win32security.GetNamedSecurityInfo(
                path, win32security.SE_FILE_OBJECT,
                win32security.DACL_SECURITY_INFORMATION)
            dacl = sd.GetSecurityDescriptorDacl(
            )  # instead of dacl = win32security.ACL()
            #print("Ace count=",dacl.GetAceCount())
            num_delete = 0
            for index in range(0, dacl.GetAceCount()):
                ace = dacl.GetAce(index)

            for index in range(0, dacl.GetAceCount()):
                ace = dacl.GetAce(index - num_delete)
                if ace[2] == everyone:
                    dacl.DeleteAce(index - num_delete)
                    num_delete += 1

            sd.SetSecurityDescriptorDacl(1, dacl, 0)
            win32security.SetNamedSecurityInfo(
                path, win32security.SE_FILE_OBJECT,
                win32security.DACL_SECURITY_INFORMATION, None, None, dacl,
                None)
    except Exception as err:
        print("exeption {}".format(str(err)))
Beispiel #4
0
def is_root():
    """Gets whether the current user is root"""
    if os.name == 'nt':
        sid = win32security.CreateWellKnownSid(win32security.WinLocalSystemSid,
                                               None)
        return win32security.CheckTokenMembership(None, sid)
    else:
        return os.geteuid() == 0
Beispiel #5
0
def is_user_admin():
    # import ctypes
    # return ctypes.windll.shell32.IsUserAnAdmin() != 0
    import win32security

    WinBuiltinAdministratorsSid = 26  # not exported by win32security. according to WELL_KNOWN_SID_TYPE enumeration from http://msdn.microsoft.com/en-us/library/windows/desktop/aa379650%28v=vs.85%29.aspx
    admins = win32security.CreateWellKnownSid(WinBuiltinAdministratorsSid)

    return win32security.CheckTokenMembership(None, admins)
def is_admin():
    """@return: True if the current user is an 'Admin' whatever that
    means (root on Unix), otherwise False.

    Warning: The inner function fails unless you have Windows XP SP2 or
    higher. The failure causes a traceback to be printed and this
    function to return False.
    """

    import win32security
    # WARNING: requires Windows XP SP2 or higher!
    try:
        adminSid = win32security.CreateWellKnownSid(
            win32security.WinBuiltinAdministratorsSid, None)
        return win32security.CheckTokenMembership(None, adminSid)
    except:
        traceback.print_exc()
        print("Admin check failed, assuming not an admin.")
        return False
Beispiel #7
0
def isUserAdmin():

    if os.name == 'nt':
        import ctypes
        import win32security
        # WARNING: requires Windows XP SP2 or higher!
        try:
            adminSid = win32security.CreateWellKnownSid(
                win32security.WinBuiltinAdministratorsSid, None)
            return win32security.CheckTokenMembership(None, adminSid)
            #return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            traceback.print_exc()
            print("Admin check failed, assuming not an admin.")
            return False
    elif os.name == 'posix':
        # Check for root on Posix
        return os.getuid() == 0
    else:
        raise RuntimeError("Unsupported operating system for this module: %s" %
                           (os.name, ))
Beispiel #8
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())
    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