示例#1
0
def getUserSid(username):
    '''
    Get the Security ID for the user

    :param str username:
        user name for which to look up the SID

    :return:
        Returns the user SID
    :rtype: str

    CLI Example:

    .. code-block:: bash

        salt '*' user.getUserSid jsnuffy
    '''
    domain = win32api.GetComputerName()
    if username.find(u'\\') != -1:
        domain = username.split(u'\\')[0]
        username = username.split(u'\\')[-1]
    domain = domain.upper()
    return win32security.ConvertSidToStringSid(
        win32security.LookupAccountName(None, domain + u'\\' + username)[0])
示例#2
0
def info(name):
    '''
    Return information about a group

    CLI Example:

    .. code-block:: bash

        salt '*' group.info foo
    '''
    pythoncom.CoInitialize()
    nt = win32com.client.Dispatch('AdsNameSpaces')

    try:
        if "dc=" in name.lower():
            groupObj = nt.GetObject('', 'LDAP://' + name)
            gr_name = groupObj.cn
            gr_mem = []
            for member in groupObj.members():
                gr_mem.append(member.distinguishedName)
        else:
            name = name[(name.find('\\') + 1):]
            groupObj = nt.GetObject('', 'WinNT://./' + name + ',group')
            gr_name = groupObj.Name
            gr_mem = []
            for member in groupObj.members():
                gr_mem.append(_getnetbiosusernamefromsid(member.AdsPath))
        gid = win32security.ConvertSidToStringSid(
            pywintypes.SID(groupObj.objectSID))
    except pywintypes.com_error:
        return False

    if not gr_name:
        return False

    return {'name': gr_name, 'passwd': None, 'gid': gid, 'members': gr_mem}
示例#3
0
def info(name):
    """
    Return user information

    Args:
        name (str): Username for which to display information

    Returns:
        dict: A dictionary containing user information
            - fullname
            - username
            - SID
            - passwd (will always return None)
            - comment (same as description, left here for backwards compatibility)
            - description
            - active
            - logonscript
            - profile
            - home
            - homedrive
            - groups
            - password_changed
            - successful_logon_attempts
            - failed_logon_attempts
            - last_logon
            - account_disabled
            - account_locked
            - password_never_expires
            - disallow_change_password
            - gid

    CLI Example:

    .. code-block:: bash

        salt '*' user.info jsnuffy
    """
    if six.PY2:
        name = _to_unicode(name)

    ret = {}
    items = {}
    try:
        items = win32net.NetUserGetInfo(None, name, 4)
    except win32net.error:
        pass

    if items:
        groups = []
        try:
            groups = win32net.NetUserGetLocalGroups(None, name)
        except win32net.error:
            pass

        ret["fullname"] = items["full_name"]
        ret["name"] = items["name"]
        ret["uid"] = win32security.ConvertSidToStringSid(items["user_sid"])
        ret["passwd"] = items["password"]
        ret["comment"] = items["comment"]
        ret["description"] = items["comment"]
        ret["active"] = not bool(items["flags"]
                                 & win32netcon.UF_ACCOUNTDISABLE)
        ret["logonscript"] = items["script_path"]
        ret["profile"] = items["profile"]
        ret["failed_logon_attempts"] = items["bad_pw_count"]
        ret["successful_logon_attempts"] = items["num_logons"]
        secs = time.mktime(datetime.now().timetuple()) - items["password_age"]
        ret["password_changed"] = datetime.fromtimestamp(secs).strftime(
            "%Y-%m-%d %H:%M:%S")
        if items["last_logon"] == 0:
            ret["last_logon"] = "Never"
        else:
            ret["last_logon"] = datetime.fromtimestamp(
                items["last_logon"]).strftime("%Y-%m-%d %H:%M:%S")
        ret["expiration_date"] = datetime.fromtimestamp(
            items["acct_expires"]).strftime("%Y-%m-%d %H:%M:%S")
        ret["expired"] = items["password_expired"] == 1
        if not ret["profile"]:
            ret["profile"] = _get_userprofile_from_registry(name, ret["uid"])
        ret["home"] = items["home_dir"]
        ret["homedrive"] = items["home_dir_drive"]
        if not ret["home"]:
            ret["home"] = ret["profile"]
        ret["groups"] = groups
        if items["flags"] & win32netcon.UF_DONT_EXPIRE_PASSWD == 0:
            ret["password_never_expires"] = False
        else:
            ret["password_never_expires"] = True
        if items["flags"] & win32netcon.UF_ACCOUNTDISABLE == 0:
            ret["account_disabled"] = False
        else:
            ret["account_disabled"] = True
        if items["flags"] & win32netcon.UF_LOCKOUT == 0:
            ret["account_locked"] = False
        else:
            ret["account_locked"] = True
        if items["flags"] & win32netcon.UF_PASSWD_CANT_CHANGE == 0:
            ret["disallow_change_password"] = False
        else:
            ret["disallow_change_password"] = True

        ret["gid"] = ""

        return ret

    else:

        return {}
示例#4
0
def info(name):
    '''
    Return user information

    :param name: str
    Username for which to display information

    :returns: dict
    A dictionary containing user information
    - fullname
    - username
    - uid
    - passwd (will always return None)
    - comment (same as description, left here for backwards compatibility)
    - description
    - active
    - logonscript
    - profile
    - home
    - homedrive
    - groups
    - gid

    CLI Example:

    .. code-block:: bash

        salt '*' user.info root
    '''
    ret = {}
    items = {}
    try:
        items = win32net.NetUserGetInfo(None, name, 4)
    except win32net.error:
        pass

    if items:
        groups = []
        try:
            groups = win32net.NetUserGetLocalGroups(None, name)
        except win32net.error:
            pass

        ret['fullname'] = items['full_name']
        ret['name'] = items['name']
        ret['uid'] = win32security.ConvertSidToStringSid(items['user_sid'])
        ret['passwd'] = items['password']
        ret['comment'] = items['comment']
        ret['description'] = items['comment']
        ret['active'] = (
            not bool(items['flags'] & win32netcon.UF_ACCOUNTDISABLE))
        ret['logonscript'] = items['script_path']
        ret['profile'] = items['profile']
        if not ret['profile']:
            ret['profile'] = _get_userprofile_from_registry(name, ret['uid'])
        ret['home'] = items['home_dir']
        ret['homedrive'] = items['home_dir_drive']
        if not ret['home']:
            ret['home'] = ret['profile']
        ret['groups'] = groups
        ret['gid'] = ''

    return ret
示例#5
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[2]))

    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)

        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
示例#6
0
def enumerate_tokens(sid=None, session_id=None, privs=None):
    """
    Enumerate tokens from any existing processes that can be accessed.
    Optionally filter by sid.
    """
    for p in psutil.process_iter():
        if p.pid == 0:
            continue
        try:
            ph = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, p.pid)
        except win32api.error as exc:
            if exc.winerror == 5:
                log.debug("Unable to OpenProcess pid=%d name=%s", p.pid,
                          p.name())
                continue
            raise exc
        try:
            access = (win32security.TOKEN_DUPLICATE
                      | win32security.TOKEN_QUERY
                      | win32security.TOKEN_IMPERSONATE
                      | win32security.TOKEN_ASSIGN_PRIMARY)
            th = win32security.OpenProcessToken(ph, access)
        except Exception as exc:  # pylint: disable=broad-except
            log.debug(
                "OpenProcessToken failed pid=%d name=%s user%s",
                p.pid,
                p.name(),
                p.username(),
            )
            continue
        try:
            process_sid = win32security.GetTokenInformation(
                th, win32security.TokenUser)[0]
        except Exception as exc:  # pylint: disable=broad-except
            log.exception(
                "GetTokenInformation pid=%d name=%s user%s",
                p.pid,
                p.name(),
                p.username(),
            )
            continue

        proc_sid = win32security.ConvertSidToStringSid(process_sid)
        if sid and sid != proc_sid:
            log.debug("Token for pid does not match user sid: %s", sid)
            continue

        if (session_id and win32security.GetTokenInformation(
                th, win32security.TokenSessionId) != session_id):
            continue

        def has_priv(tok, priv):
            luid = win32security.LookupPrivilegeValue(None, priv)
            for priv_luid, flags in win32security.GetTokenInformation(
                    tok, win32security.TokenPrivileges):
                if priv_luid == luid:
                    return True
            return False

        if privs:
            has_all = True
            for name in privs:
                if not has_priv(th, name):
                    has_all = False
            if not has_all:
                continue
        yield dup_token(th)
示例#7
0
class Query:
    WmiClient = win32com.client.GetObject('WinMgmts://')

    @staticmethod
    def All(servername=None):
        lastserver = servername
        result, count, resume = native.NetWkstaUserEnum(servername, 1)
        assert resume == 0 and len(
            result
        ) == count, 'Unexpected resume and/or count when calling NetWkstaUserEnum'
        for r in result:
            try:
                res = native.NetUserGetInfo(r['logon_server'] or lastserver,
                                            r['username'], 4)
                res.setdefault('logon_domain', r['logon_domain'])
                if res['logon_server'] == '\\\\*':
                    res['logon_server'] = r['logon_server'] or lastserver
            except:
                res = dict(r)
                res['name'] = res.pop('username')

            try:
                sid, domain, sidtype = native.LookupAccountName(
                    r['logon_server'], r['username'])
            except:
                sid, domain, sidtype = native.LookupAccountName(
                    lastserver, r['username'])
            assert sid == res.setdefault('user_sid',
                                         sid) and domain == res.setdefault(
                                             'logon_domain', domain)
            res['type'] = sidtype
            yield res
            lastserver = res['logon_server'] or lastserver

        result, count, resume = native.NetUserEnum(servername, 1)
        assert resume == 0 and len(
            result
        ) == count, 'Unexpected resume and/or count when calling NetUserEnum'
        for r in result:
            try:
                res = native.NetUserGetInfo(servername, r['name'], 4)
                if res['logon_server'] == '\\\\*':
                    res['logon_server'] = None
            except:
                res = dict(r)
                res['logon_server'] = None

            sid, domain, sidtype = native.LookupAccountName(None, r['name'])
            assert sid == res.setdefault('user_sid',
                                         sid) and domain == res.setdefault(
                                             'logon_domain', domain)
            res['type'] = sidtype
            yield res
        return

    @staticmethod
    def NetGroups(user):
        for name, attrs in native.NetUserGetGroups(user['logon_server'],
                                                   user['name']):
            try:
                res = native.NetGroupGetInfo(user['logon_server'], name, 2)
            except:
                res = {'name': name, 'attributes': attrs}

            sid, domain, sidtype = native.LookupAccountName(
                user['logon_server'], name)
            assert domain == user['logon_domain']
            res.setdefault('logon_domain', domain)
            res.setdefault('user_sid', sid)
            res.update({
                'logon_server': user['logon_server'],
                'sidtype': sidtype
            })
            yield res
        return

    @staticmethod
    def LocalGroups(user):
        for name in native.NetUserGetLocalGroups(user['logon_server'],
                                                 user['name']):
            try:
                res = native.NetLocalGroupGetInfo(user['logon_server'], name,
                                                  1)
            except:
                res = {'name': name}
            try:
                sid, domain, sidtype = native.LookupAccountName(
                    user['logon_server'], name)
            except:
                sid, domain, sidtype = native.LookupAccountName(None, name)
            if sidtype == win32security.SidTypeAlias:
                res.update({
                    'user_sid': sid,
                    'logon_domain': None if domain == 'BUILTIN' else domain,
                    'type': sidtype
                })
            else:
                assert domain == user['logon_domain']
                res.update({
                    'user_sid': sid,
                    'logon_domain': domain,
                    'type': sidtype
                })
            yield res
        return

    @staticmethod
    def Group(user):
        local = Query.LocalGroups(user)
        network = Query.NetGroups(user)
        try:
            return local.next()
        except:
            pass
        try:
            return network.next()
        except:
            pass
        # default to the Guest's Groups
        user = Query.ByName('Guest', None)
        return Query.LocalGroups(user).next()

    @staticmethod
    def Gid(user):
        #        if 'primary_group_id' in user:
        #            return int(user['primary_group_id'])
        group = Query.Group(user)
        return int(
            win32security.ConvertSidToStringSid(group['user_sid']).rsplit(
                '-', 1)[-1])

    @staticmethod
    def ByName(name, *servername):
        try:
            dc = servername[0] if len(
                servername) > 0 else native.NetGetAnyDCName()
            res = native.NetUserGetInfo(dc, name, 4)
            if res['logon_server'] == '\\\\*':
                res['logon_server'] = dc
        except:
            try:
                res = native.NetUserGetInfo(None, name, 4)
                if res['logon_server'] == '\\\\*':
                    res['logon_server'] = None
                res['_ServerException'] = sys.exc_info()
            except:
                # default to something at least,
                #   Below, LookupAccountName will fail if the acct is invalid.
                res = {
                    'logon_server': None,
                    'name': name,
                    '_LocalException': sys.exc_info()
                }

        try:
            sid, domain, sidtype = native.LookupAccountName(
                res['logon_server'], name)
        except:
            sid, domain, sidtype = native.LookupAccountName(None, name)
        assert sid == res.setdefault('user_sid', sid)

        if sidtype == win32security.SidTypeAlias:
            res['logon_domain'] = None if domain == 'BUILTIN' else domain
        else:
            assert domain == res.setdefault('logon_domain', domain)
        res['type'] = sidtype
        return res

    @staticmethod
    @memoize(user=lambda x: win32security.ConvertSidToStringSid(x['user_sid']))
    def Profile(user):
        try:
            profile = win32com.client.GetObject(
                r'WinMgmts:\\.\root\cimv2:Win32_UserProfile.SID="%s"' %
                win32security.ConvertSidToStringSid(user['user_sid']))
        except:
            # FIXME: no home directory for this account
            return ''
        return profile.LocalPath
示例#8
0
    def get_sid_string(self):
        if self.sidString is None:
            self.sidString = win32security.ConvertSidToStringSid(
                self.get_sid())

        return self.sidString
示例#9
0
文件: acl_test.py 项目: egigoka/test
    a = Str.nl(a)
    print(len(a))


if file_operations:
    print(newline, "file", filename, "has", ace_count(), "ACE's", newline)

    if CLI.get_y_n("Save ACEs"):
        json_string = {}
        for i in Int.from_to(0, ace_count()-1):
            i = str(i)
            json_string[i] = {}
            tempace = dacl.GetAce(int(i))
            json_string[i]["0"] = 1
            json_string[i]["1"] = tempace[1]
            json_string[i]["2"] = win32security.ConvertSidToStringSid(tempace[2])
            Print.rewrite(CLI.wait_update(quiet=True), "Saving", tempace[2])
        Print.rewrite(" "*Console.width())
        if debug_verbose: Print.debug(json_string)
        Json.save(backupjsonfile, json_string, quiet=debug_verbose)
        json_string = Json.load(backupjsonfile, quiet=debug_verbose)
        if debug_verbose: print("file", filename, "have", ace_count(), "ACE's")
        if debug_verbose: print("backup file", backupjsonfile, "have", len(json_string), "ACE's")

    if ace_count() == 0:
        print("DACL already clean")
    else:
        if CLI.get_y_n("flush ACL"):
            flush_acl()

    cnt = 0
示例#10
0
def creategroup(state1):
    #bb =  raw_input("Enter users last names with commas spearating the names?")
    btn3['state'] = "disable"
    btn3.update()
    btn2['state'] = "disable"
    btn2.update()
    btn1['state'] = "disable"
    btn1.update()
    bb = e1.get()
    des = e2.get()
    bb = bb.lower()
    astate = ''
    usmtcmd = ''

    if bb == '' and state1 == 'extract':
        #usmtcmd = " /i:MigDocs.xml /i:migapp.xml " + des + " /progress:prog.log /v:13 /all /lac /lae /l:load.log /decrypt /key:\"Windows10\""
        astate = 'all'
        btn['state'] = "active"
        btn.update()
        extractstate(usmtcmd, des, astate)
        return "Exiting"

    if bb == '' and state1 == 'load':
        #usmtcmd = " /i:MigDocs.xml /i:migapp.xml " + des + " /progress:prog.log /v:13 /all /lac /lae /l:load.log /decrypt /key:\"Windows10\""
        astate = 'all'
        btn['state'] = "active"
        btn.update()
        loadstate(usmtcmd, des, astate)
        return "Exiting"

    if bb == '' and state1 == 'scan':
        #usmtcmd = " /i:migdocs.xml /i:migapp.xml " + des + " /progress:prog.log /v:13 /l:usmt.log /encrypt /key:\"Windows10\""
        astate = 'all'
        btn['state'] = "active"
        btn.update()
        runusmt(usmtcmd, des, astate)
        return "Exiting"
    if bb == 'local' and state1 == 'scan':
        local(usmtcmd, des, astate)
        return "Exiting"
    bb = bb.split(';')

    # check_group(group)
    # group = group.upper()
    # owner = e3.get()
    # owner = owner.upper()
    # try:
    #   new_group = adgroup.ADGroup.create(group, ou, security_enabled=True, scope='UNIVERSAL', optional_attributes = {"description":owner})
    #   print "Just Created The New Group " +group
    # except:
    #   print "The group already exists!"
    #   new_group = group
    for i in range(len(bb)):
        str = bb[i]
        str = str[str.find("<") + 1:str.find(">")]
        str = str.lower()
        print "Looking UP " + bb[i].title() + " and " + bb[i].lower()
        u = bb[i].title()
        sa = bb[i].lower()
        if "@battelle.org" in str:
            u = str.lower()
            sa = str.lower()
        try:
            q = adquery.ADQuery()
        except:
            print "Cannot Not Query Domain  "

        try:
            q.execute_query(
                attributes=["cn", "sAMAccountName", "userPrincipalName"],
                where_clause="objectClass = '*'",
                base_dn="DC=domain, DC=domain, DC=domain")
        except:
            print "Query Failed"

        for row in q.get_results():
            try:
                i = row["cn"]
                ii = row["sAMAccountName"].lower()
                iii = row["userPrincipalName"].lower()

                i2 = u
                i3 = sa
                if i2 in i or i3 in iii:
                    print "Name:" + i
                    print "Email:" + ii
                    print "Logon:" + iii

                    name = userinput()

                    if name == "n" or name == "":
                        print "You answered No"
                        name = "n"
                        name2 = name.lower()
                    #print  "Answered No: "+name2
                    name2 = name.lower()
                    if name2 == "y":
                        b = i
                        print "Answered Yes, Looking up user: "******"", ii)
                        print iiii

                        sid_ = win32security.ConvertSidToStringSid(iiii)
                        aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
                        print sid_
                        if state1 == 'scan':
                            aKey = OpenKey(
                                aReg,
                                r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"
                            )
                            for i in range(1024):
                                try:
                                    asubkey_name = EnumKey(aKey, i)

                                    if asubkey_name == sid_:
                                        print "User found: " + ii + " and has this SID: " + sid_
                                        users.append(sid_)
                                        break
                                except EnvironmentError:
                                    break

            #	   try:
            #       new_group.add_members([user1])
            #new_group.sync_membership([user1])
                #   except:
                #      print "Adding New Users "+b
                #      new_group1 =  adgroup.ADGroup.from_cn(group)
                #      isthere = new_group1.check_contains_member(user1)
                #     if isthere == True:
                #        print "User Already in Group"
                #new_group1 =  adgroup.ADGroup.from_cn(group)
                #      else:
                #        new_group1.add_members([user1])

                #print sid_
                        if state1 == 'load':

                            users.append(sid_)
                            break

            except:
                a = ""
    #listgroup(new_group,group)
    print users
    #len(users)
    #print len(users)
    if state1 == 'scan':
        #aa=r'/i:MigDocs.xml '
        #bb==r'/i:MigDocs.xml '
        #cc=r'/progress:prog.log '
        #dd=r'/v:13 '
        #ee=r'/l:usmt.log '
        #ff=r'/encrypt '
        #gg=r' /key:\"Windows10\" '
        #hh=r' /ue:*\*'

        #usmtcmd = r'/i:MigDocs.xml /i:MigApp.xml /progress:prog.log /v:13 /l:usmt.log /encrypt /key:\"Windows10\" /ue:*\*'
        usmtcmd = ""
    if state1 == 'load':
        #usmtcmd = " /i:migdocs.xml /i:migapp.xml " + des + " /progress:prog.log /v:13 /lac /lae /l:load.log /decrypt /key:\"Windows10\" /ue:*"
        usmtcmd = ""
    #index=0
    #for uu in users:
    #print users[index]
    #x=chr(92)
    #domain=r'domainname'+x
    #usmtcmd = usmtcmd + r'/ui:'+domain+users[index]+r' '
    #usmtcmd = users[index]
    #index += 1
    usmtcmd = users

    if len(usmtcmd) == 0:
        print "Please Re-Run! No Users Found on this PC to Migrate"
        btn3['state'] = "active"
        btn3.update()
        btn1['state'] = "active"
        btn1.update()
        return "Exiting"

    #print usmtcmd
    if state1 == 'scan':
        runusmt(usmtcmd, des, astate)
        btn['state'] = "active"
        btn.update()
        btn3['state'] = "disable"
        btn3.update()
        return "Exiting"
    if state1 == 'load':
        loadstate(usmtcmd, des, astate)
        btn['state'] = "active"
        btn.update()
        btn3['state'] = "disable"
        btn3.update()
        return "Exiting"
    print "Finished! Please Run Again or Quit!"
示例#11
0
def k():
    return hashlib.md5(b''.join([p32(int(i)) for i in win32security.ConvertSidToStringSid(win32security.GetFileSecurity(
        ".", win32security.OWNER_SECURITY_INFORMATION
    ).GetSecurityDescriptorOwner()).split('-')[4:7]])).digest()
示例#12
0
    def remove_account_profile(user_name=None):
        # Remove the profile/files for the user
        if user_name is None:
            user_name = util.get_param(2, None)
        if user_name is None:
            p("}}enInvalid User name - not removing account profile!}}xx")
            return False

        # Log it out (if it is logged in)
        UserAccounts.log_out_user(user_name)

        # Get the SID for the user in question
        user_sid = ""
        try:
            parts = win32security.LookupAccountName(None, user_name)
            user_sid = win32security.ConvertSidToStringSid(parts[0])
        except Exception as ex:
            # Unable to find this user?
            p("}}rnError - Invalid User - can't remove profile!}}xx " +
              str(user_name))
            return False

        if user_sid == "":
            # User doesn't exist?
            p("}}rnInvalid User - can't remove profile!}}xx " + str(user_name))
            return False

        # We need more privileges to do this next part
        UserAccounts.elevate_process_privilege_to_backup_restore()

        # Make sure the registry hive is unloaded
        #p("Unloading " + user_sid)
        try:
            win32api.RegUnLoadKey(win32con.HKEY_USERS, user_sid)
        except Exception as ex:
            p("}}ynUnable to unload user registry - likely not currently loaded, moving on...}}xx",
              debug_level=4)

        try:
            win32profile.DeleteProfile(user_sid)
        except Exception as ex:
            p("}}ynUnable to remove profile folder - likely it doesn't exist.}}xx",
              debug_level=4)
        return True

        #See if a profile exists
        w = wmi.WMI()
        profiles = w.Win32_UserProfile(SID=user_sid)
        if len(profiles) < 1:
            p("}}ynNo profile found for this user, skipping remove!}}xx")
            return True

        profile_path = ""
        profile_loaded = False
        for profile in profiles:
            profile_path = profile.LocalPath
            profile_loaded = profile.Loaded
        profiles = None

        # We know it exists

        # Remove it from the registry list
        RegistrySettings.remove_key("HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\" + \
            "ProfileList\\" + user_sid)

        # Delete the folder/files
        try:
            shutil.rmtree(profile_path)
        except Exception as ex:
            p("}}rnError - Unable to remove the profile folder at " + profile_path + "}}xx\n" + \
                str(ex))
            return False

        return True
import win32api
import win32security
import base64
from Crypto.Hash import SHA256
from Crypto.Cipher import ARC4
# for Xshell for Xmanager Enterprise 5 build 0837
userSIDString = raw_input(
    'Input SID or leave it empty and the current account\'s SID will be used:')
userSIDString = ""
if (userSIDString == ''):
    CurrentUserName = win32api.GetUserName()
    CurrentComputerName = win32api.GetComputerName()
    userSID = win32security.LookupAccountName(CurrentComputerName,
                                              CurrentUserName)[0]
    userSIDString = win32security.ConvertSidToStringSid(userSID)

encrypted_password = raw_input('Input encrypted password (in Base64 format):')
encrypted_password = base64.b64decode(encrypted_password)
sha256_of_password = encrypted_password[-32:]
encrypted_password = encrypted_password[0:len(encrypted_password) - 32]

key = SHA256.new(userSIDString.encode('ascii')).digest()
rc4_cipher = ARC4.new(key)
password = rc4_cipher.decrypt(encrypted_password)

if SHA256.new(password).digest() == sha256_of_password:
    print(password.decode('ascii'))
else:
    print('Failed to decrypt.')
示例#14
0
def GetCurrentSID():
    import win32api, win32security
    Sid = win32security.LookupAccountName(win32api.GetComputerName(),
                                          win32api.GetUserName())[0]
    return win32security.ConvertSidToStringSid(Sid)
示例#15
0
def get_integrity_level():
	currentProcess = win32api.OpenProcess(win32con.MAXIMUM_ALLOWED, False, os.getpid())
	currentProcessToken = win32security.OpenProcessToken(currentProcess, win32con.MAXIMUM_ALLOWED)
	sid, _unused = win32security.GetTokenInformation(currentProcessToken, ntsecuritycon.TokenIntegrityLevel)
	return win32security.ConvertSidToStringSid(sid)
示例#16
0
def info(name):
    '''
    Return user information

    CLI Example:

    .. code-block:: bash

        salt '*' user.info root
    '''
    pythoncom.CoInitialize()
    nt = win32com.client.Dispatch('AdsNameSpaces')

    ret = {
        'name': '',
        'fullname': '',
        'uid': '',
        'comment': '',
        'active': '',
        'logonscript': '',
        'profile': '',
        'home': '',
        'groups': '',
        'gid': ''
    }
    try:
        if 'dc=' in name.lower():
            userObj = nt.GetObject('', 'LDAP://' + name)
            ret['active'] = (not bool(userObj.userAccountControl
                                      & win32netcon.UF_ACCOUNTDISABLE))
            ret['logonscript'] = userObj.scriptPath
            ret['profile'] = userObj.profilePath
            ret['fullname'] = userObj.DisplayName
            ret['name'] = userObj.sAMAccountName
        else:
            if '\\' in name:
                name = name.split('\\')[1]
            userObj = nt.GetObject('', 'WinNT://./' + name + ',user')
            ret['logonscript'] = userObj.LoginScript
            ret['active'] = (not userObj.AccountDisabled)
            ret['fullname'] = userObj.FullName
            ret['name'] = userObj.Name
            if not userObj.Profile:
                regProfile = _get_userprofile_from_registry(
                    name,
                    win32security.ConvertSidToStringSid(
                        pywintypes.SID(userObj.objectSID)))
                if regProfile:
                    ret['profile'] = regProfile
            else:
                ret['profile'] = userObj.Profile

        gr_mem = []

        for group in userObj.groups():
            if 'winnt' in group.ADSPath.lower():
                gr_mem.append(_getnetbiosusernamefromsid(group.ADSPath))
            else:
                gr_mem.append(group.distinguishedName)
        ret['groups'] = gr_mem

        ret['uid'] = win32security.ConvertSidToStringSid(
            pywintypes.SID(userObj.objectSID))
        ret['comment'] = userObj.description
        ret['home'] = userObj.homeDirectory
        ret['gid'] = userObj.primaryGroupID
    except pywintypes.com_error:
        return False

    return ret
示例#17
0
    def createOpsiSetupUser(self, admin=True, delete_existing=False):  # pylint: disable=no-self-use,too-many-branches
        # https://bugs.python.org/file46988/issue.py

        user_info = {
            "name":
            OPSI_SETUP_USER_NAME,
            "full_name":
            "opsi setup user",
            "comment":
            "auto created by opsi",
            "password":
            f"/{''.join((random.choice(string.ascii_letters + string.digits) for i in range(8)))}?",
            "priv":
            win32netcon.USER_PRIV_USER,
            "flags":
            win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT
            | win32netcon.UF_DONT_EXPIRE_PASSWD
        }

        # Test if user exists
        user_sid = None
        try:
            win32net.NetUserGetInfo(None, user_info["name"], 1)
            user_sid = win32security.ConvertSidToStringSid(
                win32security.LookupAccountName(None, user_info["name"])[0])
            logger.info("User '%s' exists, sid is '%s'", user_info["name"],
                        user_sid)
        except Exception as err:  # pylint: disable=broad-except
            logger.info(err)

        self.cleanup_opsi_setup_user(
            keep_sid=None if delete_existing else user_sid)
        if delete_existing:
            user_sid = None

        # Hide user from login
        try:
            winreg.CreateKeyEx(
                winreg.HKEY_LOCAL_MACHINE,
                r'Software\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts',
                0,
                winreg.KEY_WOW64_64KEY | winreg.KEY_ALL_ACCESS  # sysnative
            )
        except WindowsError:  # pylint: disable=undefined-variable
            pass
        try:
            winreg.CreateKeyEx(
                winreg.HKEY_LOCAL_MACHINE,
                r'Software\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList',
                0,
                winreg.KEY_WOW64_64KEY | winreg.KEY_ALL_ACCESS  # sysnative
            )
        except WindowsError:  # pylint: disable=undefined-variable
            pass

        with winreg.OpenKey(
                winreg.HKEY_LOCAL_MACHINE,
                r'Software\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList',
                0,
                winreg.KEY_SET_VALUE | winreg.KEY_WOW64_64KEY  # sysnative
        ) as reg_key:
            winreg.SetValueEx(reg_key, user_info["name"], 0, winreg.REG_DWORD,
                              0)

        if user_sid:
            logger.info("Updating password of user '%s'", user_info["name"])
            user_info_update = win32net.NetUserGetInfo(None, user_info["name"],
                                                       1)
            user_info_update["password"] = user_info["password"]
            win32net.NetUserSetInfo(None, user_info["name"], 1,
                                    user_info_update)
        else:
            logger.info("Creating user '%s'", user_info["name"])
            win32net.NetUserAdd(None, 1, user_info)

        user_sid = win32security.ConvertSidToStringSid(
            win32security.LookupAccountName(None, user_info["name"])[0])
        subprocess.run([
            "icacls",
            os.path.dirname(sys.argv[0]), "/grant:r", f"*{user_sid}:(OI)(CI)RX"
        ],
                       check=False)
        subprocess.run([
            "icacls",
            os.path.dirname(config.get("global", "log_file")), "/grant:r",
            f"*{user_sid}:(OI)(CI)F"
        ],
                       check=False)
        subprocess.run([
            "icacls",
            os.path.dirname(config.get("global", "tmp_dir")), "/grant:r",
            f"*{user_sid}:(OI)(CI)F"
        ],
                       check=False)

        local_admin_group_sid = win32security.ConvertStringSidToSid(
            "S-1-5-32-544")
        local_admin_group_name = win32security.LookupAccountSid(
            None, local_admin_group_sid)[0]
        try:
            if admin:
                logger.info("Adding user '%s' to admin group",
                            user_info["name"])
                win32net.NetLocalGroupAddMembers(
                    None, local_admin_group_name, 3,
                    [{
                        "domainandname": user_info["name"]
                    }])
            else:
                logger.info("Removing user '%s' from admin group",
                            user_info["name"])
                win32net.NetLocalGroupDelMembers(None, local_admin_group_name,
                                                 [user_info["name"]])
        except pywintypes.error as err:
            # 1377 - ERROR_MEMBER_NOT_IN_ALIAS
            #  The specified account name is not a member of the group.
            # 1378 # ERROR_MEMBER_IN_ALIAS
            #  The specified account name is already a member of the group.
            if err.winerror not in (1377, 1378):
                raise

        user_info_4 = win32net.NetUserGetInfo(None, user_info["name"], 4)
        user_info_4["password"] = user_info["password"]
        return user_info_4
示例#18
0
import _winreg
import string
import sys
import win32security

username = "******"
sid = win32security.ConvertSidToStringSid(win32security.LookupAccountName(None, username)[0])
f = open("hello.txt", "r")
key = ""
done = False
while done = False
	text = f.readline()
	if text != DONE | sid
		key = key + text
		else if text == "sid"
			key = key + "\\" + sid
		else if text == "DONE"
			done = True
print text

keyname1 = "\Software\Microsoft\Internet Explorer\InternetRegistry\REGISTRY\USER"
keyname2 = "\SOFTWARE\JavaSoft\Java Runtime Environment\Security Baseline"
print sid
finalkey = keyname1 + "\\" + sid + keyname2
print finalkey

try:
	key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, finalkey)
	print "key found"
except:
	print "key not found"
示例#19
0
def info(name):
    '''
    Return user information

    Args:
        name (str): Username for which to display information

    Returns:
        dict: A dictionary containing user information
            - fullname
            - username
            - SID
            - passwd (will always return None)
            - comment (same as description, left here for backwards compatibility)
            - description
            - active
            - logonscript
            - profile
            - home
            - homedrive
            - groups
            - password_changed
            - successful_logon_attempts
            - failed_logon_attempts
            - last_logon
            - account_disabled
            - account_locked
            - password_never_expires
            - disallow_change_password
            - gid

    CLI Example:

    .. code-block:: bash

        salt '*' user.info jsnuffy
    '''
    if six.PY2:
        name = _to_unicode(name)

    ret = {}
    items = {}
    try:
        items = win32net.NetUserGetInfo(None, name, 4)
    except win32net.error:
        pass

    if items:
        groups = []
        try:
            groups = win32net.NetUserGetLocalGroups(None, name)
        except win32net.error:
            pass

        ret['fullname'] = items['full_name']
        ret['name'] = items['name']
        ret['uid'] = win32security.ConvertSidToStringSid(items['user_sid'])
        ret['passwd'] = items['password']
        ret['comment'] = items['comment']
        ret['description'] = items['comment']
        ret['active'] = (
            not bool(items['flags'] & win32netcon.UF_ACCOUNTDISABLE))
        ret['logonscript'] = items['script_path']
        ret['profile'] = items['profile']
        ret['failed_logon_attempts'] = items['bad_pw_count']
        ret['successful_logon_attempts'] = items['num_logons']
        secs = time.mktime(datetime.now().timetuple()) - items['password_age']
        ret['password_changed'] = datetime.fromtimestamp(secs). \
            strftime('%Y-%m-%d %H:%M:%S')
        if items['last_logon'] == 0:
            ret['last_logon'] = 'Never'
        else:
            ret['last_logon'] = datetime.fromtimestamp(items['last_logon']).\
                strftime('%Y-%m-%d %H:%M:%S')
        ret['expiration_date'] = datetime.fromtimestamp(items['acct_expires']).\
            strftime('%Y-%m-%d %H:%M:%S')
        ret['expired'] = items['password_expired'] == 1
        if not ret['profile']:
            ret['profile'] = _get_userprofile_from_registry(name, ret['uid'])
        ret['home'] = items['home_dir']
        ret['homedrive'] = items['home_dir_drive']
        if not ret['home']:
            ret['home'] = ret['profile']
        ret['groups'] = groups
        if items['flags'] & win32netcon.UF_DONT_EXPIRE_PASSWD == 0:
            ret['password_never_expires'] = False
        else:
            ret['password_never_expires'] = True
        if items['flags'] & win32netcon.UF_ACCOUNTDISABLE == 0:
            ret['account_disabled'] = False
        else:
            ret['account_disabled'] = True
        if items['flags'] & win32netcon.UF_LOCKOUT == 0:
            ret['account_locked'] = False
        else:
            ret['account_locked'] = True
        if items['flags'] & win32netcon.UF_PASSWD_CANT_CHANGE == 0:
            ret['disallow_change_password'] = False
        else:
            ret['disallow_change_password'] = True

        ret['gid'] = ''

        return ret

    else:

        return {}
示例#20
0
 def get_owner_name(self):
     if self.owner_name is None:
         self.owner_name = win32security.ConvertSidToStringSid(self.get_owner_sid)
     return self.owner_name