def __session(self): session = getattr(self.__local, 'session', None) if not session: session = requests.Session() session.auth = EdgeGridAuth(**self.__auth) self.__local.session = session return session
def runTest(self): auth = EdgeGridAuth( client_token=self.testdata['client_token'], client_secret=self.testdata['client_secret'], access_token=self.testdata['access_token'], ) params = { 'extended': 'true', } data = { 'key': 'value', } request = requests.Request( method='POST', url=urljoin(self.testdata['base_url'], '/testapi/v1/t3'), params=params, json=data, ) auth_header = auth.make_auth_header(request.prepare(), self.testdata['timestamp'], self.testdata['nonce']) self.assertEqual(auth_header, self.testdata['jsontest_hash'])
def __init__(self, log=None, section_name="papi"): self.log = log self.session = requests.Session() self.debug = False self.verbose = False self.section_name = section_name self.account = None # If all parameters are set already, use them. Otherwise # use the config self.config = EdgeGridConfig({}, self.section_name) if hasattr(self.config, "debug") and self.config.debug: self.debug = True if hasattr(self.config, "verbose") and self.config.verbose: self.verbose = True # Set the config options self.session.auth = EdgeGridAuth( client_token=self.config.client_token, client_secret=self.config.client_secret, access_token=self.config.access_token) if hasattr(self.config, 'headers'): self.session.headers.update(self.config.headers) self.baseurl = '%s://%s/' % ('https', self.config.host) self.httpCaller = EdgeGridHttpCaller(self.session, self.debug, self.verbose, self.baseurl, self.log)
def _get_dns_info(self, rrecord): aka_cust_object = MISPObject('misc') tagInfo=["source:AkamaiETP"] _text = "" dimensions = ['deviceId','site'] for dimension in dimensions: #_result = self._run_custom_request(self, rrecord, dimension) session = requests.Session() session.auth = EdgeGridAuth( client_token = self.ctoken, client_secret = self.csecret, access_token = self.atoken ) confID = self.configID epoch_time = int(time.time()) last_30_days = epoch_time - 3600 * 24 * 30 # last month by default for now url = f'/etp-report/v2/configs/{str(confID)}' + \ f'/dns-activities/aggregate?cardinality=2500&dimension={dimension}&endTimeSec={epoch_time}&filters' + \ f'=%7B%22domain%22:%7B%22in%22:%5B%22{rrecord}%22%5D%7D%7D&startTimeSec={last_30_days}' _result = session.get(urljoin(self.baseurl, url)).json() if _result['dimension']['total'] != 0: _text += dimension + ' involved\n\n' if 'aggregations' in _result: for el in _result['aggregations']: name = el['name'] _text += f"{name} : {el['total']} connections \n" aka_cust_object.add_attribute('Customer Attribution', type='text', value=str(_text), Tag=tagInfo, disable_correlation=True) self.incident_flag = "true" self.misp_event.add_object(**aka_cust_object)
def purgeCPCode(CP=None): #Fetch Credentials from Env Variables from AWS AO_ACCESS_TOKEN = os.environ['AO_ACCESS_TOKEN'] AO_CLIENT_SECRET = os.environ['AO_CLIENT_SECRET'] AO_API_HOST = os.environ['AO_API_HOST'] AO_CLIENT_TOKEN = os.environ['AO_CLIENT_TOKEN'] apiRequest = requests.Session() apiRequest.auth = EdgeGridAuth( client_token=AO_CLIENT_TOKEN, client_secret=AO_CLIENT_SECRET, access_token=AO_ACCESS_TOKEN ) apiBaseUrl = "https://"+AO_API_HOST apiEndpoint = apiBaseUrl+ "/ccu/v3/invalidate/cpcode/staging" # Change Path for production network Purge #apiEndpoint = apiBaseUrl+ "/ccu/v3/invalidate/cpcode/production" postbody = '{"objects": ["' + str(CP) + '"]}' response = apiRequest.post(apiEndpoint, postbody, headers={"Content-Type": "application/json"}) return { 'status':response.status_code, 'body': json.dumps(response.text) }
def api_record_create(zone: str, name: str, type: str, host: str, client_secret: str, access_token: str, client_token: str, switchkey: str, ip_list: list, ttl: int): url = 'https://' + host + '/config-dns/v2/zones/' + zone + '/names/' + name + '/types/' + type + '?accountSwitchKey=' + switchkey #print(url) # creating a http request http_request = requests.Session() # post request headers http_request.auth = EdgeGridAuth(client_token, client_secret, access_token) headers = {} headers['Content-type'] = "application/json" http_request.headers = headers # defining body of post request body = {} body['name'] = name body['type'] = type body['ttl'] = ttl body['rdata'] = ip_list #print(body) json_body = json.dumps(body) #print(json_body) #http_request.data = json_body http_response = http_request.post(url, data=json_body) return (http_response)
def runTest(self): auth = EdgeGridAuth(client_token=self.testdata['client_token'], client_secret=self.testdata['client_secret'], access_token=self.testdata['access_token'], headers_to_sign=self.testdata['headers_to_sign'], max_body=self.testdata['max_body']) headers = {} if 'headers' in self.testcase['request']: for h in self.testcase['request']['headers']: for k, v in h.items(): headers[k] = v request = requests.Request( method=self.testcase['request']['method'], url=urljoin(self.testdata['base_url'],self.testcase['request']['path']), headers=headers, data=self.testcase['request'].get('data') if self.testcase['request'].get('data') \ else None ) try: auth_header = auth.make_auth_header(request.prepare(), self.testdata['timestamp'], self.testdata['nonce']) except Exception as e: logger.debug('Got exception from make_auth_header', exc_info=True) self.assertEquals(str(e), self.testcase['failsWithMessage']) return self.assertEqual(auth_header, self.testcase['expectedAuthorization'])
def __init__(self, baseurl, client_token, client_secret, access_token): self.baseurl = baseurl self.session = requests.Session() self.session.auth = EdgeGridAuth(client_token=client_token, client_secret=client_secret, access_token=access_token, max_body=128 * 1024)
def __init__(self, edgedns_creds): logger.debug("creating _EdgeDNSClient") pathhost = "" if EDGEGRID_CREDS["edgerc_path"]: section = 'default' if EDGEGRID_CREDS["edgerc_section"]: section = EDGEGRID_CREDS["edgerc_section"] pathhost = EdgeRc(EDGEGRID_CREDS["edgerc_path"]).get(section, 'host') self.edgegrid_auth = EdgeGridAuth.from_edgerc(EDGEGRID_CREDS["edgerc_path"], section) else: pathhost = EDGEGRID_CREDS["host"] self.edgegrid_auth = EdgeGridAuth(client_token = EDGEGRID_CREDS["client_token"], client_secret = EDGEGRID_CREDS["client_secret"], access_token = EDGEGRID_CREDS["access_token"]) # Error checking the .edgerc file if pathhost.find('://') > 0: raise errors.PluginError('{0}: You have specified an invalid host entry ' 'Please remove the http(s):// at the beginning.' ) root_path = self.BASEURL.format(pathhost) self.EDGEDNSROOTURL = urljoin(root_path, "/config-dns/v2/") self.EDGEDNSZONESURL = self.EDGEDNSROOTURL + "zones/" self.EDGEDNSCHANGESURL = self.EDGEDNSROOTURL + "changelists" self.recordset_semaphore = threading.Semaphore() return
def main(): params = demisto.params() client = Client(base_url=urljoin(params.get('host'), '/siem/v1/configs'), verify=not params.get('insecure', False), proxy=params.get('proxy'), auth=EdgeGridAuth( client_token=params.get('clientToken'), access_token=params.get('accessToken'), client_secret=params.get('clientSecret'))) commands = { f"test-module": test_module_command, f"{INTEGRATION_COMMAND_NAME}-get-events": get_events_command } command = demisto.command() demisto.debug(f'Command being called is {command}') try: if command == 'fetch-incidents': incidents, new_last_run = fetch_incidents_command( client, fetch_time=params.get('fetchTime'), fetch_limit=params.get('fetchLimit'), config_ids=params.get('configIds'), last_run=demisto.getLastRun().get('lastRun')) demisto.incidents(incidents) demisto.setLastRun(new_last_run) else: human_readable, entry_context, raw_response = commands[command]( client, **demisto.args()) return_outputs(human_readable, entry_context, raw_response) except Exception as e: err_msg = f'Error in {INTEGRATION_NAME} Integration [{e}]' return_error(err_msg, error=e)
def purge(self, url): auth = EdgeGridAuth( client_token=self.client_token, client_secret=self.client_secret, access_token=self.access_token ) headers = {'content-type': 'application/json'} payload = { 'action': 'invalidate', 'objects': [url] } resp = requests.post( self.fast_purge_url, headers=headers, data=json.dumps(payload), auth=auth ) logger.info( u'Attempted to invalidate page {url}, ' 'got back response {message}'.format( url=url, message=resp.text ) ) resp.raise_for_status()
def create_session(): session = requests.Session() # Set the config options session.auth = EdgeGridAuth( client_token=os.environ['ETP_CLIENT_TOKEN'].strip(), client_secret=os.environ['ETP_CLIENT_SECRET'].strip(), access_token=os.environ['ETP_ACCESS_TOKEN'].strip()) return session
def Akamai_report(self): s = requests.Session() s.auth = EdgeGridAuth(client_token='xxxxxxxxxxxxxxxxxxx', client_secret='xxxxxxxxxxxxxxxxxxx', access_token='xxxxxxxxxxxxxxxxxxx') baseurl = 'https://xxxxxxxxxxxxxxxxxxx.luna.akamaiapis.net/' credentials_list = [s, baseurl] return credentials_list
def get_session(): s = requests.Session() s.auth = EdgeGridAuth( client_token=os.environ['AK_CLIENT_TOKEN'], client_secret=os.environ['AK_CLIENT_SECRET'], access_token=os.environ['AK_ACCESS_TOKEN'], ) return s
def __init__(self, credentials, user_agent): self.base_url = credentials['baseUrl'] self.headers = {'Accept': 'application/json', 'User-Agent': user_agent} self.session = requests.Session() self.session.auth = EdgeGridAuth( client_token=credentials['clientToken'], client_secret=credentials['clientSecret'], access_token=credentials['accessToken'])
def edge_session(env, config): s = requests.Session() s.auth = EdgeGridAuth( # This is akamai credential client_token=config.get(env, 'client_token'), client_secret=config.get(env, 'client_secret'), access_token=config.get(env, 'access_token')) return s
def __init__(self, client_secret, host, access_token, client_token): self.base = "https://" + host + "/config-dns/v2/" sess = Session() sess.auth = EdgeGridAuth(client_token=client_token, client_secret=client_secret, access_token=access_token) self._sess = sess
def AkamaiEdgeGridSession_Setup(AkamaiEdgeGridConfig): session = requests.Session() session.auth = EdgeGridAuth( client_token=AkamaiEdgeGridConfig['client_token'], client_secret=AkamaiEdgeGridConfig['client_secret'], access_token=AkamaiEdgeGridConfig['access_token'] ) return session
def create_caller(): # Set the config options session.auth = EdgeGridAuth( client_token=os.environ['ETP_CLIENT_TOKEN'].strip(), client_secret=os.environ['ETP_CLIENT_SECRET'].strip(), access_token=os.environ['ETP_ACCESS_TOKEN'].strip()) baseurl = '%s://%s/' % ('https', args.server.strip()) httpCaller = EdgeGridHttpCaller(session, baseurl, args.debug) return httpCaller
def __init__(self, edgerc, section, switch_key=None, **kwargs): super(Session, self).__init__(**kwargs) self.edgerc = EdgeRc(edgerc) self.section = section self.switch_key = switch_key self.auth = EdgeGridAuth( client_token=self.edgerc.get(section, "client_token"), client_secret=self.edgerc.get(section, "client_secret"), access_token=self.edgerc.get(section, "access_token"), )
def __init__(self, host, access_token, client_token, client_secret): self.headers = {'Content-Type': 'application/json'} self.TIMEOUT = 180 self.session = requests.Session() self.session.auth = EdgeGridAuth(client_token=client_token, client_secret=client_secret, access_token=access_token, max_body=131072) self.baseurl = 'https://%s' % host
def submit_request(testurl, payload, method, headers): """ Function to submit Akamai API """ logger.debug("Requesting Method: %s URL %s with payload: %s with Headers %s", \ method, testurl, payload, headers) my_headers = headers logger.debug(my_headers) req_session = requests.Session() req_session.trust_env = False req_session.auth = EdgeGridAuth(client_secret=client_secret, access_token=access_token, client_token=client_token) try: if method == "GET": if len(payload) > 0: response = req_session.get(testurl,params=payload, headers=my_headers, \ allow_redirects=False, verify=False) else: response = req_session.get(testurl, headers=my_headers, \ allow_redirects=False, verify=False) elif method == "POST": if len(payload) > 0: logger.debug("Using Post with Payload") response = req_session.post(testurl,data=json.dumps(payload), headers=my_headers, \ allow_redirects=False, verify=False) else: logger.debug("Using Post without Payload") response = req_session.post(testurl, headers=my_headers, \ allow_redirects=False, verify=False) logger.debug(response.url) logger.debug(response.headers) return (response.status_code, response) except requests.exceptions.HTTPError as my_errh: logger.critical("Http Error: %s", my_errh) return_message = "Failure" return (response.status_code, return_message, my_errh) except requests.exceptions.ConnectionError as my_errc: logger.critical("Error Connecting: %s", my_errc) return_status = 500 return_message = "Failure" return (return_status, return_message, my_errc) except requests.exceptions.Timeout as my_errt: logger.critical("Timeout Error:%s ", my_errt) return_status = 500 return_message = "Failure" return (return_status, return_message, my_errt) except requests.exceptions.RequestException as my_eree: ## catastrophic error. bail. logger.critical("Your Request had an error:%s ", my_eree) logger.critical("Check parameters") logger.critical("Your Request had an error with Status %s", response.status_code) return_status = 500 return_message = "Failure" return (response.status_code, return_message, my_eree)
def __init__(self, baseUrl, clientToken, clientSecret, accessToken): self.baseUrl = baseUrl self.clientToken = clientToken self.clientSecret = clientSecret self.accessToken = accessToken self.session = requests.Session() self.session.auth = EdgeGridAuth(client_token=self.clientToken, client_secret=self.clientSecret, access_token=self.accessToken, max_body=128 * 1024) self.headers = {'Content-Type': 'application/json'}
def lambda_handler(event, context): invalidation_items = event['invalidation_items'] if event['source'] == "Akamai": import requests, json from http_calls import EdgeGridHttpCaller from akamai.edgegrid import EdgeGridAuth creds = event['credentials'] session = requests.Session() debug = False verbose = False section_name = "default" # Set the config options session.auth = EdgeGridAuth(client_token=creds['client_token'], client_secret=creds['client_secret'], access_token=creds['access_token']) baseurl = '%s://%s/' % ('https', creds['host']) httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl) purge_obj = { "objects": invalidation_items, "hostname": "", "action": "remove", "type": "arl", "domain": "production" } purge_post_result = httpCaller.postResult('/ccu/v3/invalidate/url', json.dumps(purge_obj)) return {"success": True, "message": purge_post_result} else: if "distribution_id" in event and "credentials" in event: distribution_id = event['distribution_id'] quantity = event['quantity'] creds = event['credentials'] if distribution_id: client = boto3.client( 'cloudfront', aws_access_key_id=creds["aws_access_key_id"], aws_secret_access_key=creds['aws_secret_access_key']) invalidation = client.create_invalidation( DistributionId=distribution_id, InvalidationBatch={ 'Paths': { 'Quantity': quantity, 'Items': invalidation_items }, 'CallerReference': str(time.time()) }) return {"success": True, "message": invalidation}
def initEdgeGridAuth(path="~/.edgerc"): # If the config file is defined in the env vars, use that edgerc_path = getEnvVar("EDGERCPATH") if edgerc_path != "": path = edgerc_path config = configparser.RawConfigParser() config.read(os.path.expanduser(path)) s.auth = EdgeGridAuth(client_token=config.get("default", "client_token"), client_secret=config.get("default", "client_secret"), access_token=config.get("default", "access_token"))
def api_record_del(zone: str, name: str, type: str, host: str, client_secret: str, access_token: str, client_token: str, switchkey: str): url = 'https://' + host + '/config-dns/v2/zones/' + zone + '/names/' + name + '/types/' + type + '?accountSwitchKey=' + switchkey #print(url) # creating a http request http_request = requests.Session() http_request.auth = EdgeGridAuth(client_token, client_secret, access_token) http_response = http_request.delete(url) #print(http_response.status_code) #print(http_response.content) return (http_response)
def initEdgeGridAuth(path="~/.edgerc"): # If the config file was passed in, use that. if len(sys.argv) > 1: path = sys.argv[1] config = configparser.RawConfigParser() config.read(os.path.expanduser(path)) # TODO: We might actually be able to authenticate without EdgeGridAuth, # which would reduce the number of dependencies. s.auth = EdgeGridAuth(client_token=config.get("default", "client_token"), client_secret=config.get("default", "client_secret"), access_token=config.get("default", "access_token"))
def __init__(self, base_url, client_token, client_secret, access_token): """Authentication""" self.base_url = base_url self.client_token = client_token self.client_secret = client_secret self.access_token = access_token self.session = requests.Session() self.session.auth = EdgeGridAuth(client_token=self.client_token, client_secret=self.client_secret, access_token=self.access_token, max_body=128 * 1024) self.check_next = True self.default_origin = {} self.custom_origin = {}
def _make_rest_call(self, endpoint, action_result, method="get", **kwargs): # **kwargs can be any additional parameters that requests.request accepts resp_json = None try: request_func = getattr(requests, method) except AttributeError: return RetVal( action_result.set_status(phantom.APP_ERROR, "Invalid method: {0}".format(method)), resp_json) # Create a URL to connect to url = "{}{}{}".format(self._base_url, AKAMAI_API_PATH, endpoint) try: r = requests.Session() r.auth = EdgeGridAuth(client_token=self._client_token, client_secret=self._client_secret, access_token=self._access_token) print(vars(r)) r = request_func(url, auth=r.auth, **kwargs) except requests.exceptions.InvalidSchema: error_message = 'Error connecting to server. No connection adapters were found for %s' % ( url) return RetVal( action_result.set_status(phantom.APP_ERROR, error_message), resp_json) except requests.exceptions.InvalidURL: error_message = 'Error connecting to server. Invalid URL %s' % ( url) return RetVal( action_result.set_status(phantom.APP_ERROR, error_message), resp_json) except requests.exceptions.ConnectionError: error_message = "Error Details: Connection Refused from the Server" return RetVal( action_result.set_status(phantom.APP_ERROR, error_message), resp_json) except Exception as e: err = self._get_error_message_from_exception(e) return RetVal( action_result.set_status( phantom.APP_ERROR, "Error Connecting to server. Details: {0}".format(err)), resp_json) return self._process_response(r, action_result)
def __init__(self, edgerc, section, switch_key=None, **kwargs): try: super(Session, self).__init__(**kwargs) self.edgerc = EdgeRc(edgerc) self.section = section self.switch_key = switch_key self.auth = EdgeGridAuth( client_token=self.edgerc.get(section, "client_token"), client_secret=self.edgerc.get(section, "client_secret"), access_token=self.edgerc.get(section, "access_token"), ) except NoSectionError as e: raise EdgegridError(e.message) except NoOptionError as e: raise EdgegridError(e.message)