Ejemplo n.º 1
0
		def on_request(self, request):
			# Extract information from request
			print "Service received request payload: " + request.payload.decode()
			# Create the response message
			res = Response(request)
			try:
				s = request.payload.decode()
				cmd = subprocess.Popen(re.split(r'\s+', s), stdout=subprocess.PIPE)
				cmd_out = cmd.stdout.read()
				# Process output
				res.payload = cmd_out.encode()
			except OSError:
				res.payload = 'Invalid command'.encode()
			# Send the response
			client.send_response(res)
Ejemplo n.º 2
0
    def unknown_command(self, request, command):
        # Create the response
        response = Response(request)

        response.payload = ERROR_RESPONSE_PAYLOAD_PREFIX + command

        self._client.send_response(response)
Ejemplo n.º 3
0
        def on_request(self, request):
            # Parse cancel assessment message
            cam = CancelAssessmentMessage()
            cam.parse(request.payload.decode())
            logger.info("Manager received cancel assessment request: %s",
                        cam.to_s())

            # Check to make sure it came from the application
            # that originally requested the assessment. If it
            # is not, just ignore the message
            if cam.requestor_id in transactions.keys(
            ) and cam.transaction_id in transactions[cam.requestor_id]:
                assessment_requests.append(cam)
            # Cancel request didn't come from originating application so ignore
            else:
                logger.info("Ignoring cancel request " + cam.transaction_id +
                            " for application " + cam.requestor_id)

            # Send request acknowledgement message with the transaction
            # id that was cancelled
            res = Response(request)
            ram = RequestAcknowledgementMessage()
            ram.transaction_id = cam.transaction_id
            res.payload = (ram.to_json()).encode()
            client.send_response(res)
Ejemplo n.º 4
0
 def on_request(self, request):
     # type: (Request) -> None
     self.__monitor.register_request()
     response = Response(request)
     try:
         args = None
         if self.__args is not None:  # If input's expected, try parsing the incoming JSON
             args = json_format.Parse(request.payload, self.__args())
         grrr = self.__board.grr.SendRequest(self.__endpoint.name, args=args)
         if grrr is not None:
             response.payload = json_format.MessageToJson(grrr)
     except (json_format.ParseError, BuildError, grr_errors.Error) as e:
         # Failed to compose request or otherwise bad request
         response = ErrorResponse(request, 400, 'invalid request: {}'.format(str(e)))
     except Error as e:  # Connector error
         logger.error('error reaching the GRR instance: {}'.format(str(e)))
         response = ErrorResponse(request, 503, 'failed processing request: {}'.format(str(e)))
     except Exception as e:  # Generic internal error
         logger.exception('%s: %s', type(e).__name__, str(e))
         response = ErrorResponse(request, 500, 'failed processing request: {}'.format(str(e)))
     finally:
         if isinstance(response, ErrorResponse) and response.error_code >= 500:
             # Error count doesn't include client errors
             self.__monitor.register_error()
         else:
             self.__monitor.register_success()
         self.__board.dxlc.send_response(response)
Ejemplo n.º 5
0
        def on_request(self, request):
            try:
                # Extract information from request
                query = request.payload.decode(encoding="UTF-8")
                logger.info("Service received request payload: " + query)

                # Send HTTP request to OpenWeatherMap
                req = urllib2.Request(
                    CURRENT_WEATHER_URL.format(query, API_KEY), None,
                    {'Content-Type': 'text/json'})
                f = urllib2.urlopen(req)
                weather_response = f.read()
                f.close()

                # Create the response message
                response = Response(request)
                # Populate the response payload
                response.payload = weather_response.encode(encoding="UTF-8")
                # Send the response
                client.send_response(response)

            except Exception as ex:
                print str(ex)
                # Send error response
                client.send_response(
                    ErrorResponse(
                        request,
                        error_message=str(ex).encode(encoding="UTF-8")))
    def system_find_command(self, request):
        # Create the response
        response = Response(request)

        response.payload = MessageUtils.dict_to_json(SYSTEM_FIND_PAYLOAD)

        self._client.send_response(response)
Ejemplo n.º 7
0
    def system_find_command(self, request, params):
        # Create the response
        response = Response(request)

        response.payload = MessageUtils.dict_to_json(
            SYSTEM_FIND_PAYLOAD if params ==
            {"searchText": SYSTEM_FIND_OSTYPE_LINUX} else [])

        self._client.send_response(response)
 def on_request(self, request):
     # Extract
     print "Service recieved request payload: " + request.payload.decode(
     )
     # Create the response message
     res = Response(request)
     res.payload = "pong".encode()
     # Send the response
     client.send_event_response(res)
Ejemplo n.º 9
0
 def on_request(self, request):
     # Extract information from request
     print "Service received request payload: " + request.payload.decode(
     )
     # Create the response message
     res = Response(request)
     # Populate the response payload
     res.payload = "pong".encode()
     # Send the response
     client.send_response(res)
Ejemplo n.º 10
0
    def on_request(self, request):
        self.__monitor.register_request()
        response = Response(request)
        try:
            req = json.loads(request.payload)
            args = {
                'method': self.__config.type,
                'url': self.__construct_url(req)
            }

            # Determine how to treat the rest of the parameters based on the request type
            if self.__config.type == 'get':
                args['params'] = req
            else:
                args['json'] = req

            # Forward on the request and pass the response back
            upstream = self.__sess.request(**args)

            if upstream.status_code >= 400:
                response = ErrorResponse(request, upstream.status_code,
                                         upstream.text)
            else:
                try:
                    # Errors aren't always indicated with the proper HTTP status code, may need to inspect
                    res = upstream.json()
                    if res['error'] != 0:
                        response = ErrorResponse(request, res['error'],
                                                 upstream.text)
                    else:
                        response.payload = upstream.text
                except (ValueError, KeyError):
                    response = ErrorResponse(request, 504,
                                             'Invalid upstream response')
        except ValueError:
            response = ErrorResponse(
                request, 400,
                'request payload must be a well formed JSON string')
        except KeyError as e:
            response = ErrorResponse(
                request, 400,
                'missing required parameter {} from payload'.format(str(e)))
        except Exception as e:
            logger.exception('unknown exception of type %s: ' + str(e),
                             type(e).__name__)
            response = ErrorResponse(request, 500,
                                     'unknown internal error: ' + str(e))
        finally:
            if isinstance(response,
                          ErrorResponse) and 500 <= response.error_code < 600:
                # Error count doesn't include client errors
                self.__monitor.register_error()
            else:
                self.__monitor.register_success()
            self.__switch.dxl.send_response(response)
Ejemplo n.º 11
0
        def on_request(self, request):
            try:
                query = request.payload.decode()
                logger.info("Service received request payload: " + query)
                response = Response(request)
                response.payload = str(virustotal(jsonparse(query))).encode()
                client.send_response(response)
                print response

            except Exception as ex:
                print str(ex)
                client.send_response(
                    ErrorResponse(request, error_message=str(ex).encode()))
Ejemplo n.º 12
0
        def on_request(self, request):

            # Parse the query message and execute the query
            # against the repository
            qm = QueryMessage()
            qm.parse(request.payload.decode())
            results = execute_query(qm.query)

            # Send query result back to the requesting component
            response = Response(request)
            qrm = QueryResultMessage(qm.query, results)
            response.payload = (qrm.to_json()).encode()
            logger.info("Sending query results: " + qrm.to_s())
            client.send_response(response)
Ejemplo n.º 13
0
    def acknowledge_request(request):
        # Prepare response and assign a new transaction
        # id
        res = Response(request)
        rm = RequestAcknowledgementMessage()
        rm.transaction_id = str(uuid.uuid4())
        res.payload = (rm.to_json()).encode()

        # Send the request acknowledgement to the application
        # in reponse to the request and return the transaction
        # id
        logger.info("Sending request acknowlegement: %s", rm.to_s())
        client.send_response(res)
        return rm.transaction_id
Ejemplo n.º 14
0
    def on_request(self, request):
        """
        Invoked when a request is received

        :param request: The request that was received
        """
        try:
            # Build dictionary from the request payload
            req_dict = json.loads(request.payload.decode(encoding=self.UTF_8))

            # Determine the ePO command
            if self.CMD_NAME_KEY not in req_dict:
                raise Exception(
                    "A command name was not specified ('{0}')".format(
                        self.CMD_NAME_KEY))
            command = req_dict[self.CMD_NAME_KEY]

            # Determine the request parameters
            req_params = {}
            if self.PARAMS_KEY in req_dict:
                req_params = req_dict[self.PARAMS_KEY]

            # Determine the output format
            output = self.DEFAULT_OUTPUT
            if self.OUTPUT_KEY in req_dict:
                output = req_dict[self.OUTPUT_KEY]

            # Get the ePO server to invoke the command on
            epo = self._epo_by_topic[request.destination_topic]

            # Execute the ePO Remote Command
            result = epo.execute(command, output, req_params)

            # Create the response, set payload, and deliver
            response = Response(request)
            response.payload = result
            self._dxl_client.send_response(response)

        except Exception as ex:
            logger.exception("Error while processing request")
            # Send error response
            self._dxl_client.send_response(
                ErrorResponse(
                    request,
                    error_message=str(ex).encode(encoding=self.UTF_8)))
    def help_command(self, request):
        # Create the response
        response = Response(request)

        response.payload = ""

        for cmd in self.KNOWN_COMMANDS:

            cmd_string = cmd["name"] + " "

            for param in cmd["parameters"]:
                cmd_string += "[" + param + "] "

            cmd_string += "- " + cmd["description"]

            response.payload += cmd_string

        self._client.send_response(response)
Ejemplo n.º 16
0
    def help_command(self, request):
        # Create the response
        response = Response(request)

        cmd_array = []
        for cmd in self.KNOWN_COMMANDS:

            cmd_string = cmd["name"] + " "

            for param in cmd["parameters"]:
                cmd_string += "[" + param + "] "

            cmd_string += "- " + cmd["description"]

            cmd_array.append(cmd_string)

        response.payload = MessageUtils.dict_to_json(cmd_array)

        self._client.send_response(response)
Ejemplo n.º 17
0
                    def on_request(self, request):
                        dxl_message = JavaDxlMessage()
                        dxl_message.setTopic(request.destination_topic)
                        dxl_message.setMessageVersion(request.version)
                        dxl_message.setMessageId(request.message_id)
                        dxl_message.setClientId(request.source_client_id)
                        dxl_message.setBrokerId(request.source_broker_id)
                        dxl_message.setMessageType(request.message_type)
                        dxl_message.setBrokerIdList(request.broker_ids)
                        dxl_message.setClientIdList(request.client_ids)
                        dxl_message.setReplyTopic(request.reply_to_topic)
                        dxl_message.setServiceId(request.service_id)
                        dxl_message.setPayload(request.payload.decode())
                        dxl_message.setReplyTopic(request.reply_to_topic)
                        dxl_message.setServiceId(request.service_id)

                        response = Response(request)
                        resp = self.dxlCallback.callbackEvent(dxl_message)
                        response.payload = resp.encode()
                        client.send_response(response)
            def on_request(self, request):
                # Extract information from Response payload, in this sample we expect it is UTF-8 encoded
                logger.info(
                    "Service Provider - Request received:\n   Topic: %s\n   Request ID: %s\n   Payload: %s",
                    request.destination_topic, request.message_id,
                    request.payload.decode())

                # Create the Response message
                logger.info(
                    "Service Provider - Creating Response for Request ID %s on %s",
                    request.message_id, request.destination_topic)
                response = Response(request)

                # Encode string payload as UTF-8
                response.payload = "Sample Response Payload".encode()

                # Send the Response back
                logger.info(
                    "Service Provider - Sending Response to Request ID: %s on %s",
                    response.request_message_id, request.destination_topic)
                client.send_response(response)
Ejemplo n.º 19
0
    def on_request(self, request):
        try:
            # Build dictionary from the request payload
            req_dict = json.loads(request.payload.decode(encoding=self.UTF_8))

            response = Response(request)
            response.payload = '{"status": "failed (did not match any API call)"}'

            if request.destination_topic == self.vt_basic_test_topic:
                response.payload = self.basic_test()

            elif request.destination_topic == VirusTotalApiClient._REQ_TOPIC_DOMAIN_REPORT:
                response.payload = self.domain_report(req_dict)

            elif request.destination_topic == VirusTotalApiClient._REQ_TOPIC_FILE_REPORT:
                response.payload = self.file_report(req_dict)

            elif request.destination_topic == VirusTotalApiClient._REQ_TOPIC_FILE_RESCAN:
                response.payload = self.file_rescan(req_dict)

            elif request.destination_topic == VirusTotalApiClient._REQ_TOPIC_IP_ADDRESS_REPORT:
                response.payload = self.ip_report(req_dict)

            elif request.destination_topic == VirusTotalApiClient._REQ_TOPIC_URL_SCAN:
                response.payload = self.url_scan(req_dict)

            elif request.destination_topic == VirusTotalApiClient._REQ_TOPIC_URL_REPORT:
                response.payload = self.url_report(req_dict)

            self._client.send_response(response)

        except Exception as ex:
            # Send error response
            self._client.send_response(
                ErrorResponse(
                    request,
                    error_message=str(ex).encode(encoding=self.UTF_8)))
Ejemplo n.º 20
0
 def on_request(self, request):
     print "Received request %s" % request.payload
     res = Response(request)
     res.payload = openticket(request.payload)
     print "Received Response from Service: %s" % res.payload
     client.send_response(res)
Ejemplo n.º 21
0
    # Register PCE by sending registration event to the collector/PCX
    event = Event(EVENT_PCE_REGISTRATION_TOPIC)
    rm = RegistrationMessage(PCE_ID, "", "", ASSET, MAKE, MODEL, "", "", "",
                             "", "", SUPPORTED_CHECK_TYPES)
    event.payload = (rm.to_json()).encode()
    logger.info("Sending registration event: %s", rm.to_s())
    client.send_event(event)

    # Wait forever
    while True:
        # Process all collection requests that were received
        while collection_requests:
            request = collection_requests.pop()
            response = Response(request)

            # Cancel assessment if a cancel request. Otherwise,
            # perform the assessment
            if re.search("cancel_.*", request.payload.decode()):
                transaction_id = request.payload.decode().split("_")[1]
                logger.info("Canceling assessment " + transaction_id)
                response.payload = "".encode()
            else:
                response.payload = perform_collection(
                    request.payload.decode()).encode()

            # Send results back to the collector/PCX
            logger.info("Service sending: %s", response.payload.decode())
            client.send_response(response)

        time.sleep(1)