def app_download(hostname,api_key,api_secret,dest,validate_certs):
    result = {"ansible_facts": {}}
    api_endpoint = 'https://{0}'.format(hostname)
    restclient = RestClient(api_endpoint, api_key=api_key, api_secret=api_secret, verify=validate_certs)
    resp = restclient.get('/openapi/v1/applications')
    if not resp.status_code == 200:
        return (1, "Error {0}: {1} during connection attempt to {2}/openapi/v1/applications. \n".format(resp.status_code,
                                                                           resp.reason,api_endpoint))
    apps = json.loads(resp.content)
    resp = restclient.get('/openapi/v1/app_scopes')
    if not resp.status_code == 200:
        return (1, "Error {0}: {1} during connection attempt to {2}/openapi/v1/app_scopes. \n".format(resp.status_code,
                                                                           resp.reason,api_endpoint))
    scopes = json.loads(resp.content)

    with open(dest, 'w') as f:
        for app in apps:
            print('Retrieving details for app {0}'.format(app['name']))
            resp = restclient.get('/openapi/v1/applications/{0}/details'.format(app['id']))
            if not resp.status_code == 200:
                return (1, "Error {0}: {1} during connection attempt to {2}/openapi/v1/applications/{3}/details.\n".format(
                    resp.status_code,
                    resp.reason,
                    api_endpoint,
                    app['id']))
            app_details = json.loads(resp.content)
            app_details['app_scope_name'] = [x['name'] for x in scopes if x['id'] == app['app_scope_id']][0]
            f.write('---\n')
            oyaml.dump(app_details, f, allow_unicode=True, encoding='utf-8')
            f.write('\n')

    result["ansible_facts"] = {'Output':os.path.join(os.getcwd(),dest)}
    result['changed'] = False
    return (0, result)
Exemplo n.º 2
0
def dump_applications(endpoint):
    restclient = RestClient(endpoint + '/',
                            credentials_file='api_cred.json',
                            verify=False)
    apps = []
    resp = restclient.get('/applications')
    if resp.status_code == 200:
        respbody = json.loads(resp.text)
        with open('public/data/all.json', 'w+') as appf:
            appf.write(resp.text)
            respbody = json.loads(resp.text)
            for app in respbody:
                appnames = {}
                appnames['id'] = str(app['id'])
                appnames['name'] = str(app['name'])
                #version changed after 2.3+
                try:
                    appnames['version'] = str(app['version'])
                except KeyError as ke:
                    appnames['version'] = str(app['latest_adm_version'])
                apps.append(appnames)

    for app in apps:
        resp = restclient.get('/applications/%s/details' % (app['id']))
        if resp.status_code == 200:
            try:
                os.mkdir('public/data/%s' % (app['id']))
            except:
                pass
            with open('public/data/%s.json' % (app['id']), "w+") as outf:
                outf.write(resp.text)
            with open('public/data/%s/%s.json' % (app['id'], app['version']),
                      "w+") as outf2:
                outf2.write(resp.text)
Exemplo n.º 3
0
def get_applications(
        host=env.TET.get("host"), api_key=env.TET_API_KEY,
        api_sec=env.TET_SEC):

    # Build URL
    url = f"https://{host}"

    restclient = RestClient(url,
                            api_key=api_key,
                            api_secret=api_sec,
                            verify=True)

    # HTTP Get Request
    response = restclient.get("/applications")

    # If response code is 200, then return the json response
    if response.status_code == 200:
        # JSON Response
        applications = response.json()

        return applications

    # If response code is anything but 200, print error message with response code
    else:
        print(
            f"Unable to find any Applications. Error code {response.status_code}."
        )
Exemplo n.º 4
0
def get_sensors(
        host=env.TET.get("host"), api_key=env.TET_API_KEY,
        api_sec=env.TET_SEC):

    # Build URL
    url = f"https://{host}"

    restclient = RestClient(url,
                            api_key=api_key,
                            api_secret=api_sec,
                            verify=True)

    # HTTP Get Request
    response = restclient.get("/sensors")

    # If successful response code return list sensors
    if response.status_code == 200:
        # print(json.dumps(response.json(), indent=2))
        return response.json()

    # If response code is anything but 200, print error message with response code
    else:
        print(
            f"Error code: {response.status_code} getting sensors: {response.content}"
        )
Exemplo n.º 5
0
class Environment(object):
    def __init__(self,tetCluster,tetCreds):
        self._primaryApps = {}
        self._adjacentApps = {}
        self._scopes = {}
        self._restclient = RestClient(tetCluster,
                        credentials_file=tetCreds,
                        verify=False)

    @property
    def primaryApps(self):
        return self._primaryApps

    @property
    def adjacentApps(self):
        return self._adjacentApps

    @property
    def tetClient(self):
        return self._restclient

    @property
    def scopes(self):
        return self._scopes

    def addScope(self, scope_id):
        self._scopes['scope']=scope_id

    def loadPolicy(self, appIDs):
        #Load Policy JSON
        for appID in appIDs:
            appDetails = self._restclient.get('/openapi/v1/applications/%s/details'%appID).json()
            print('\nProcessing "%s"...'%appDetails['name'])
            self._primaryApps[appID] = App(environment=self,app_def=appDetails)
Exemplo n.º 6
0
def selectTetrationApps(endpoint, credentials):

    restclient = RestClient(endpoint,
                            credentials_file=credentials,
                            verify=False)

    requests.packages.urllib3.disable_warnings()
    resp = restclient.get('/openapi/v1/applications')

    if not resp:
        sys.exit("No data returned for Tetration Apps! HTTP {}".format(
            resp.status_code))

    app_table = []
    app_table.append(['Number', 'Name', 'Author', 'Primary'])
    print('\nApplications: ')
    for i, app in enumerate(resp.json()):
        app_table.append([i + 1, app['name'], app['author'], app['primary']])
        print('%i: %s' % (i + 1, app['name']))


#    print(AsciiTable(app_table).table)
    choice = raw_input('\nSelect Tetration App: ')

    choice = choice.split(',')
    appIDs = []
    for app in choice:
        if '-' in app:
            for app in range(int(app.split('-')[0]),
                             int(app.split('-')[1]) + 1):
                appIDs.append(resp.json()[int(app) - 1]['id'])
        else:
            appIDs.append(resp.json()[int(app) - 1]['id'])

    return appIDs
Exemplo n.º 7
0
def test_tetration():
    '''
    Function attempts to connect to Tetration. Arguments are retrieved from
    environment variables. The bulk of the work in this function is error
    handling. It returns a tuple that has a status code and an error message
    (which will be an empty string if there are no errors)
    '''
    requests.packages.urllib3.disable_warnings()
    status = 200
    return_msg = "Tetration connectivity verified."

    restclient = RestClient(os.environ['TETRATION_ENDPOINT'],
                            api_key=os.environ['TETRATION_API_KEY'],
                            api_secret=os.environ['TETRATION_API_SECRET'],
                            verify=False)

    try:
        resp = restclient.get('/filters/inventories')

    # most likely a DNS issue
    except requests.exceptions.ConnectionError:
        status = 404
        return_msg = "Error connecting to Tetration endpoint"
    except:
        status = 400
        return_msg = "Unknown error connecting to Tetration"
    else:
        status = resp.status_code
        # this doesn't work if the Tetration endpoint is specified as a valid
        # website (but not a TA endpoint) because it returns all of the HTML
        # for the whole website
        if resp.status_code >= 400:
            return_msg = "Tetration " + str(resp.text).rstrip()

    return (status, return_msg)
def scope_download(hostname, api_key, api_secret, dest, validate_certs):
    result = {"ansible_facts": {}}
    api_endpoint = 'https://{0}'.format(hostname)
    restclient = RestClient(api_endpoint,
                            api_key=api_key,
                            api_secret=api_secret,
                            verify=validate_certs)
    resp = restclient.get('/openapi/v1/app_scopes')
    if not resp.status_code == 200:
        return (
            1,
            "Error {0}: {1} during connection attempt to {2}/openapi/v1/app_scopes. \n"
            .format(resp.status_code, resp.reason, api_endpoint))
    scopes = json.loads(resp.content)
    shortened_scope_list = []
    for i in range(len(scopes) - 1, 0, -1):
        shortened_scope_list.append(
            dict(short_name=scopes[i]['short_name'],
                 short_query=scopes[i]['short_query'],
                 parent_app_scope_name=scope_name_lookup(
                     scopes, scopes[i]['parent_app_scope_id'])))
    with open(dest, 'w') as f:
        for scope in shortened_scope_list:
            f.write('---\n')
            oyaml.dump(scope, f, allow_unicode=True, encoding='utf-8')
            f.write('\n')

    result["ansible_facts"] = {'Output': os.path.join(os.getcwd(), dest)}
    result['changed'] = False
    return (0, result)
Exemplo n.º 9
0
def get_app_scope(
        scope_id,
    host=env.TET.get("host"),
    api_key=env.TET_API_KEY,
        api_sec=env.TET_SEC
):

    # Build URL
    url = f"https://{host}"

    restclient = RestClient(url,
                            api_key=api_key,
                            api_secret=api_sec,
                            verify=True)

    # HTTP Get Request
    response = restclient.get(f"/app_scopes/{scope_id}")

    # If response code is 200, then return the json response
    if response.status_code == 200:
        # JSON Response
        application_scope = response.json()

        return application_scope

    # If response code is anything but 200, print error message with response code
    else:
        print(f"Application Scope ID {scope_id} can not be found. Error code {response.status_code}.")
Exemplo n.º 10
0
def get_reg_token():

    OUTPUT_TOKEN_FILE = 'registration.token'
    print("")
    app_scope = input(
        " Enter application scope name for this agent to register with: ")

    host = env.TET.get("host")
    api_key = env.TET_API_KEY
    api_sec = env.TET_SEC

    # Build URL
    url = f"https://{host}"

    restclient = RestClient(url,
                            api_key=api_key,
                            api_secret=api_sec,
                            verify=True)

    resp = restclient.get('/secureconnector/name/{}/token'.format(app_scope))

    if resp.status_code != 200:
        print("Error ({}): {}".format(resp.status_code, resp.content.decode()))
        sys.exit(1)
    else:
        with open(OUTPUT_TOKEN_FILE, 'w') as f:
            token_str = str(resp.content.decode())
            f.write(token_str)

    print(" Agent registration token retrieved. Filename: " +
          OUTPUT_TOKEN_FILE)
Exemplo n.º 11
0
def get_tet_json(request_str,
                 host=env.TET.get("host"),
                 api_key=env.TET_API_KEY,
                 api_sec=env.TET_SEC):

    # Build URL
    url = f"https://{host}"

    restclient = RestClient(url,
                            api_key=api_key,
                            api_secret=api_sec,
                            verify=False)

    # Get Request
    response = restclient.get(request_str)

    # If successful response code return list sensors
    if response.status_code == 200:
        #print ("DEBUG GET:", json.dumps(response.json(), indent=2))
        return response.json()

    # If response code is anything but 200, print error message with response code
    else:
        #print(f"Error processing GET request on {request_str}. Error code: {response.status_code}.")
        return None
def dump_application_revisions( endpoint, username, password):
    restclient = RestClient( endpoint +'/',
                    credentials_file='api_cred.json',
                    verify=False)
    apps = []
    resp = restclient.get('/applications')
    if resp.status_code == 200 :
        respbody = json.loads(resp.text)
        with open('public/data/all.json', 'w+') as appf:
            appf.write( resp.text)
            respbody = json.loads( resp.text)
            for app in respbody:
                appnames = {}
                appnames['id'] = str(app['id'])
                appnames['name'] = str(app['name'])
                #version changed after 2.3+
                try:
                    appnames['version'] = str(app['version'])
                except KeyError as ke:
                    appnames['version'] = str(app['latest_adm_version'])
                apps.append( appnames)


    # go to the tetration login page
    driver.get(endpoint)
    ids = ['h4_user_email', 'h4_user_password']
    vals = [ username, password]
    for idx, eid in enumerate(ids):
        element = driver.find_element_by_id( eid) 
        element.send_keys( vals[idx])
    submit_btn = driver.find_element_by_name('commit')
    submit_btn.click()
    # just give a time to get data
    time.sleep(10)

    el = driver.find_element_by_name('csrf-token')
    newheader = {'X-CSRF-Token': el.get_attribute('content'), 'Referer': endpoint +'/'}
    scookie = driver.get_cookies()
    newcookies = {}
    for x in scookie:
        newcookies[ x['name']] = x['value']
    payload= {'clusters_only': 'false'}
    # extract all revision data fro each application 
    for app in apps:
        for x in range(1, int(app['version'])):
            resp = requests.post('{0}/api/data_sets/{1}/download.json?version={2}'.format(endpoint, app['id'], x), headers = newheader, cookies=newcookies, json=payload, verify=False)
            newcookies = resp.cookies 
            json_body = resp.json()
            with open('public/data/{0}/{1}.json'.format(app['id'], x), "w+") as outf:
                outf.write( json.dumps(json_body))
Exemplo n.º 13
0
def app_upload(hostname, api_key, api_secret, source, validate_certs):
    result = {"ansible_facts": {'result': []}}
    api_endpoint = 'https://{0}'.format(hostname)
    restclient = RestClient(api_endpoint,
                            api_key=api_key,
                            api_secret=api_secret,
                            verify=validate_certs)

    app_list = []
    with open(source, 'r') as f:
        for data in oyaml.load_all(f):
            app_list.append(data)

    for i, app in enumerate(app_list):
        exists = False
        if scope['parent_app_scope_name']:
            resp = restclient.get('/openapi/v1/app_scopes')
            if not resp.status_code == 200:
                return (
                    1,
                    "Error {0}: {1} during connection attempt to {2}/openapi/v1/app_scopes. \n"
                    .format(resp.status_code, resp.reason, api_endpoint))
            current_scopes = json.loads(resp.content)
            for current_scope in current_scopes:
                if current_scope['short_name'] == scope['short_name']:
                    exists = True
            if not exists:
                scope['parent_app_scope_id'] = ParentIDLookup(
                    current_scopes, scope['parent_app_scope_name'])
                scope.pop('parent_app_scope_name')
                print('Posting scope {0} to the cluster'.format(
                    scope['short_name']))
                resp = restclient.post('/openapi/v1/app_scopes',
                                       json_body=json.dumps(scope))
                if not resp.status_code == 200:
                    return (1,
                            "Error {0}: {1} creating scope {2}. \n{3}".format(
                                resp.status_code, resp.reason,
                                scope['short_name'], resp.json()))
                result['ansible_facts']['result'].append(resp.json())

    if result['ansible_facts']['result']:
        result['changed'] = True
    else:
        result['changed'] = False
    return (0, result)
def get_key_capability(url, api_key, api_secret):
    """ Returns the capabilities of a given API key as a list

    Keyword arguments:
    url -- https url of the Tetration GUI
    api_key -- Tetration API key to be tested
    api_secret -- Tetration API secret for given API key
    """

    # Each API 'capability' is a key in the following dict and the value for
    # each key is *one* API endpoint that requires *only* that capability to
    # return a successful status code.

    api_map = {
        "user_role_scope_management": "/openapi/v1/roles",
        "flow_inventory_query": "/openapi/v1/flowsearch/dimensions",
        "hw_sensor_management": "/openapi/v1/switches",
        "app_policy_management": "/openapi/v1/applications",
        "sensor_management": "/openapi/v1/sensors",
        "user_data_upload": "/openapi/v1/assets/cmdb/download"
    }

    restclient = RestClient(url,
                            api_key=api_key,
                            api_secret=api_secret,
                            verify=False)

    requests.packages.urllib3.disable_warnings()

    # step through each capability and test the API endpoint associated with
    # it; if we get a status_code of 200, then add it to the list of
    # capabilities of the API key we are testing

    return_list = []
    for capability, endpoint in api_map.iteritems():

        try:
            resp = restclient.get(endpoint)
            if resp.status_code == 200:
                return_list.append(capability)
        except:
            pass

    return [str(x) for x in return_list]
def download(hostname, api_key, api_secret, dest, validate_certs):
    result = {"ansible_facts": {}}
    api_endpoint = 'https://{0}'.format(hostname)
    restclient = RestClient(api_endpoint,
                            api_key=api_key,
                            api_secret=api_secret,
                            verify=validate_certs)
    resp = restclient.get('/openapi/v1/filters/inventories')
    if not resp.status_code == 200:
        return (
            1,
            "Error {0}: {1} during connection attempt to {2}/openapi/v1/filters/inventories. \n"
            .format(resp.status_code, resp.reason, api_endpoint))
    filters = json.loads(resp.content)

    with open(dest, 'w') as f:
        for filter in filters:
            f.write('---\n')
            oyaml.dump(filter, f, allow_unicode=True, encoding='utf-8')
            f.write('\n')

    result["ansible_facts"] = {'Output': os.path.join(os.getcwd(), dest)}
    result['changed'] = False
    return (0, result)
Exemplo n.º 16
0
def tetration_test(
        host=env.TET.get("host"), api_key=env.TET_API_KEY,
        api_sec=env.TET_SEC):

    # Build URL
    url = f"https://{host}"

    restclient = RestClient(url,
                            api_key=api_key,
                            api_secret=api_sec,
                            verify=True)

    # HTTP Get Request
    response = restclient.get("/applications")

    # If response code is 200, Test Successful
    if response.status_code == 200:
        print("Test Successful....Woo Hoo!")

        # return applications

    # If response code is anything but 200, print error message with response code
    else:
        print(f"Test Failed....DOE!" f"\nError Code {response.status_code}")
Exemplo n.º 17
0
def main():
    """
    Main execution routine
    """
    parser = argparse.ArgumentParser(description='Tetration Policy to XLS')
    parser.add_argument('--maxlogfiles',
                        type=int,
                        default=10,
                        help='Maximum number of log files (default is 10)')
    parser.add_argument('--debug',
                        nargs='?',
                        choices=['verbose', 'warnings', 'critical'],
                        const='critical',
                        help='Enable debug messages.')
    parser.add_argument('--config', default=None, help='Configuration file')
    args = parser.parse_args()
    apps = []
    if args.config is None:
        print '%% No configuration file given - connecting directly to Tetration'
        try:
            restclient = RestClient(API_ENDPOINT,
                                    credentials_file=API_CREDS,
                                    verify=False)
            appIDs = selectTetrationApps(endpoint=API_ENDPOINT,
                                         credentials=API_CREDS)
            for appID in appIDs:
                print('Downloading app details for ' + appID)
                apps.append(
                    restclient.get('/openapi/v1/applications/%s/details' %
                                   appID).json())
        except:
            print('Error connecting to Tetration')
    else:
        # Load in the configuration
        try:
            with open(args.config) as config_file:
                apps.append(json.load(config_file))
        except IOError:
            print '%% Could not load configuration file'
            return
        except ValueError:
            print 'Could not load improperly formatted configuration file'
            return

    protocols = {}
    try:
        with open('protocol-numbers-1.csv') as protocol_file:
            reader = csv.DictReader(protocol_file)
            for row in reader:
                protocols[row['Decimal']] = row
    except IOError:
        print '%% Could not load protocols file'
        return
    except ValueError:
        print 'Could not load improperly formatted protocols file'
        return

    port_labels = {}
    try:
        with open('common-ports.csv') as protocol_file:
            reader = csv.DictReader(protocol_file)
            for row in reader:
                port_labels[row['Port']] = row
    except IOError:
        print '%% Could not load protocols file'
        return
    except ValueError:
        print 'Could not load improperly formatted protocols file'
        return

    showPorts = raw_input(
        '\nWould you like to include ports and protocols in the diagram? [Y,N]: '
    )

    if showPorts.upper() == 'Y':
        showPorts = True
    elif showPorts.upper() == 'N':
        showPorts = False
    else:
        print('Invalid input.')
        return

    for appDetails in apps:
        graph = pydot.Dot(graph_type='digraph',
                          name=appDetails['name'],
                          label='Application Name: ' + appDetails['name'])
        print('\nPreparing "%s"...' % appDetails['name'])
        if 'clusters' in appDetails.keys():
            for cluster in appDetails['clusters']:
                node_names = cluster['name'] + ':'
                for node in cluster['nodes']:
                    node_names = node_names + '\n' + node['name']
                graph.add_node(
                    pydot.Node(cluster['id'],
                               label=node_names,
                               shape='rectangle',
                               style='filled',
                               fontcolor='white',
                               fillcolor='royalblue4'))
        if 'inventory_filters' in appDetails.keys():
            for invfilter in appDetails['inventory_filters']:
                graph.add_node(
                    pydot.Node(invfilter['id'],
                               label='"' + invfilter['name'] + '"',
                               shape='rectangle',
                               style='filled',
                               fontcolor='white',
                               fillcolor='orange2'))
        if 'default_policies' in appDetails.keys():
            for policy in appDetails['default_policies']:
                pols = None
                if showPorts:
                    pols = {}
                    #print(json.dumps(policy, indent=4))
                    for rule in policy['l4_params']:
                        if 'port' not in rule:
                            continue
                        if rule['port'][0] == rule['port'][1]:
                            port = str(rule['port'][0])
                            if port in port_labels.keys():
                                port = port + '(%s)' % port_labels[port]['Name']
                        else:
                            port = str(rule['port'][0]) + '-' + str(
                                rule['port'][1])

                        if protocols[str(
                                rule['proto'])]['Keyword'] in pols.keys():
                            pols[protocols[str(
                                rule['proto'])]['Keyword']].append(port)
                        else:
                            pols[protocols[str(
                                rule['proto'])]['Keyword']] = [port]

                    pols = '\n'.join("%s=%r" % (key, ', '.join(val))
                                     for (key, val) in pols.iteritems())

                if pols:
                    graph.add_edge(
                        pydot.Edge(policy['consumer_filter_id'],
                                   policy['provider_filter_id'],
                                   label=pols))
                else:
                    graph.add_edge(
                        pydot.Edge(policy['consumer_filter_id'],
                                   policy['provider_filter_id']))

        f = open(appDetails['name'] + '.dot', 'w')
        f.write(graph.to_string())
Exemplo n.º 18
0
def main():
    """
    Main execution routine
    """
    protocols = {}
    try:
        with open('protocol-numbers-1.csv') as protocol_file:
            reader = csv.DictReader(protocol_file)
            for row in reader:
                protocols[row['Decimal']] = row
    except IOError:
        print '%% Could not load protocols file'
        return
    except ValueError:
        print 'Could not load improperly formatted protocols file'
        return

    appIDs = selectTetrationApps(endpoint=API_ENDPOINT, credentials=API_CREDS)

    showPorts = raw_input(
        '\nWould you like to include ports and protocols in the diagram? [Y,N]: '
    )

    if showPorts.upper() == 'Y':
        showPorts = True
    elif showPorts.upper() == 'N':
        showPorts = False
    else:
        print('Invalid input.')
        return

    restclient = RestClient(API_ENDPOINT,
                            credentials_file=API_CREDS,
                            verify=False)

    for appID in appIDs:
        print appID
        appDetails = restclient.get('/openapi/v1/applications/%s/details' %
                                    appID).json()

        #with open('./SQL-DVA-v8-policies.json') as config_file:
        #    appDetails = json.load(config_file)

        #graph = pgv.AGraph(directed=True, rankdir="LR", name=appDetails['name'])
        graph = pydot.Dot(graph_type='digraph', name=appDetails['name'])
        print('\nPreparing "%s"...' % appDetails['name'])
        for cluster in appDetails['clusters']:
            node_names = cluster['name'] + ':'
            for node in cluster['nodes']:
                node_names = node_names + '\n' + node['name']
            #graph.add_node(cluster['id'],
            #                    label=node_names)
            graph.add_node(pydot.Node(cluster['id'], label=node_names))
        for invfilter in appDetails['inventory_filters']:
            #graph.add_node(invfilter['id'],
            #                    label=invfilter['name'],style='filled', color='lightblue')
            graph.add_node(
                pydot.Node(invfilter['id'],
                           label='"' + invfilter['name'] + '"',
                           style='filled',
                           fillcolor='lightblue'))
        for policy in appDetails['default_policies']:

            if showPorts:
                policies = {}
                #Sort ports and protocols
                for port_range in policy['l4_params']:

                    if port_range['port'][0] == port_range['port'][1]:
                        port = str(port_range['port'][0])
                    else:
                        port = str(port_range['port'][0]) + '-' + str(
                            port_range['port'][1])

                    if protocols[str(port_range['proto']
                                     )]['Keyword'] in policies.keys():
                        policies[protocols[str(
                            port_range['proto'])]['Keyword']].append(port)
                    else:
                        policies[protocols[str(
                            port_range['proto'])]['Keyword']] = [port]

                #Stringify policies
                ports = '\n'.join("%s=%r" % (key, val)
                                  for (key, val) in policies.iteritems())
                ports = policy['consumer_filter_name'] + '-->' + policy[
                    'provider_filter_name'] + ':\n' + ports
                #pol_node = graph.add_node(policy['consumer_filter_id']+policy['provider_filter_id'],
                #                    label=ports, shape='box',
                #                    style='filled', color='lightgray')
                pol_node = graph.add_node(
                    pydot.Node(policy['consumer_filter_id'] +
                               policy['provider_filter_id'],
                               label=ports,
                               shape='box',
                               style='filled',
                               color='lightgray'))
                #graph.add_edge(policy['consumer_filter_id'],policy['consumer_filter_id']+policy['provider_filter_id'])
                #graph.add_edge(policy['consumer_filter_id']+policy['provider_filter_id'],policy['provider_filter_id'])
                graph.add_edge(
                    pydot.Edge(
                        policy['consumer_filter_id'],
                        policy['consumer_filter_id'] +
                        policy['provider_filter_id']))
                graph.add_edge(
                    pydot.Edge(
                        policy['consumer_filter_id'] +
                        policy['provider_filter_id'],
                        policy['provider_filter_id']))

            else:
                if policy[
                        'consumer_filter_id'] == '5959528c755f024cb6d32189' and policy[
                            'provider_filter_id'] == '5959528c755f024cb6d3218c':
                    print('I think this is right')
                graph.add_edge(
                    pydot.Edge(policy['consumer_filter_id'],
                               policy['provider_filter_id']))

        f = open(appDetails['name'] + '.dot', 'w')
        #f.write(graph.string())
        f.write(graph.to_string())
Exemplo n.º 19
0
""""
Sample Code - Housley Communications
- Agent/Sensor list
These APIs are only available to site admin users.
"""
from tetpyclient import RestClient
import requests.packages.urllib3
from pprint import pprint
import json

# set variables
server = "oz.tet.hl.dns"
creds = "./api_credentials.json"

# open connection class
client = RestClient(server, credentials_file=creds, verify=False)

# suppress warning message
requests.packages.urllib3.disable_warnings()

# GET the list of agents
sensors = client.get('/sensors')

# Convert Text to json
json_output = json.loads(sensors.text)

# print Json in format output
pprint(json_output)
import json

scopeid = []
api_ep = "https://tetcluster.xxx.xxx"

tet_headers = {
    'Content-Type': "application/json",
    'Accept': "application/json"
}

restclient = RestClient(
    api_ep,
    headers=tet_headers,
    credentials_file='/home/xxx/cisco_tet/api_credentials.json',
    verify=False)
resp = restclient.get('/app_scopes')

jdata_load = json.loads(resp.text)
#jdata_scope = json.dumps(jdata_load, sort_keys=True, indent=True)
for ep in jdata_load:
    scopeid.append(ep['id'])

#for x in scopeid:
#    print x

for id in scopeid:
    restclient = RestClient(
        api_ep,
        headers=tet_headers,
        credentials_file='/home/xxxx/cisco_tet/api_credentials.json',
        verify=False)
        config_file = config_file.readlines()
        fw.loadConfig(config_file)
except IOError:
    print('%% Could not load ASA Config file')
except ValueError:
    print('Could not load improperly formatted ASA Config file')

print('Connecting to Tetration')
restclient = RestClient(TET_API_ENDPOINT,
                        credentials_file=TET_API_CREDS,
                        verify=False)
print('Connected Successfully')
requests.packages.urllib3.disable_warnings()

#Get the Default scope ID
resp = restclient.get('/openapi/v1/app_scopes').json()
default_scope_id = [x for x in resp if x['name'] == scopeName][0]['id']

inventory_filters = {}
print("Creating Firewall Objects as Tetration Filters...")
if not args.f:
    for key in tqdm(fw.networkObjects.keys()):
        filters = []
        for ip in fw.networkObjects[key].ipSet():
            filters.append({"field": "ip", "type": "eq", "value": ip})
        post_data = {
            "name": 'fw_obj_' + key,
            "query": {
                "type": "or",
                "filters": filters
            },
"""
Main execution routine
"""
parser = argparse.ArgumentParser(
    description='Secure Workload PoV Helper - DNS Get Top Talkers - RUN FIRST')
parser.add_argument('--tet_url', help='Tetration URL', type=str,required=True)
parser.add_argument('--tet_creds', type=str,
                    help='Tetration API Credentials File',required=True)
parser.add_argument('--workspace', type=str, default=None,
                    help='Name of the Target Workspace for Conversations. If multiple workspaces have the same name, this may be random.  If not provided, it will default to a workspace for the root scope')
parser.add_argument('--subnets', type=str, default=None,
                    help='Additional subnets other than RFC1918 addresses where resolution is needed, ex: customer-owned public IP space.  Provide in a comma separated list in CIDR notation.')
args = parser.parse_args()

rc = RestClient(args.tet_url, credentials_file=args.tet_creds, verify=True)
root_scope = rc.get('/openapi/v1/app_scopes').json()[0]['root_app_scope_id']
workspaces = rc.get('/openapi/v1/applications').json()
global_workspace = [x for x in rc.get(
    '/openapi/v1/applications').json() if x['app_scope_id'] == root_scope]

workspace = None
if args.workspace != None:
    workspace = [x for x in workspaces if x['name'] == args.workspace]
    if len(workspace) > 0:
        workspace = workspace[0]
    else:
        print('No workspace named {} found.  Looking for a compatible global workspace.'.format(
            args.workspace))

if workspace == None and len(global_workspace) > 0:
    workspace = global_workspace[0]
import sys
from tetpyclient import RestClient
import json
import pandas as pd
from tabulate import tabulate
import requests.packages.urllib3

requests.packages.urllib3.disable_warnings()

API_ENDPOINT="https://{Your cluster's ip or FQDN}"

rc = RestClient(API_ENDPOINT,credentials_file='credentials.json', verify=False)

resp = rc.get('/applications')
app = resp.json()

a_list = []
b_list = []
for i in app:
    app_name = i['name']
    id = i['id']
    a_list.append(app_name)
    b_list.append(id)

app_list = list(enumerate(a_list, start=1))
id_list = list(enumerate(b_list, start=1))

print()
print('-' * 10, 'アプリケーションの一覧を表示します', '-' * 10)
print()
Exemplo n.º 24
0
# FORMATTING
import pprint
import json

# Tetration Keys
API_SECRET = <secret agent man>
API_KEY = <friends don't let friends do key-to> #wahwah lol

# This /applications resource is defined on the OpenAPI documentation
CURRENT_GET_ENDPOINT = '/applications'

# Create the Tetration REST Client 
API_ENDPOINT = 'https://tetbdc.myco.int/openapi/v1'
rc = RestClient(API_ENDPOINT, api_secret=API_SECRET, api_key=API_KEY, verify=False)

resp = rc.get(CURRENT_GET_ENDPOINT)

# make sure we get a good response from the request
if resp.status_code != 200:
   print("Unsuccessful request returned code: {} , \
       response: {}".format(resp.status_code,resp.reason))
results = resp.json()

pprint.pprint(results[0])

#---------------------------------------------------------------------------------------

# Delete Application Workspace

# Create the Tetration REST Client 
rc = RestClient(API_ENDPOINT, api_secret=API_SECRET, api_key=API_KEY, verify=False)
Exemplo n.º 25
0
#!/usr/bin/env python

from tetpyclient import RestClient
import requests.packages.urllib3
import json

CLUSTER_URL = "https://andromeda-aus.cisco.com"
CRED_FILE = "./cred.json"

MY_APP = "Siwapp Prod"

requests.packages.urllib3.disable_warnings()
rc = RestClient(CLUSTER_URL, credentials_file=CRED_FILE, verify=False)

resp = rc.get("/openapi/v1/applications")

if resp.status_code == 200:
    for app in json.loads(resp.content):
        if app['name'] == MY_APP:
            my_app_id = app['id']

    if not 'my_app_id' in vars():
        print(MY_APP + " Not found!")
    else:
        resp_policy = rc.get("/openapi/v1/applications/" + my_app_id +
                             "/details")
        if resp_policy.status_code == 200:
            print(
                json.dumps(json.loads(resp_policy.content),
                           indent=4,
                           sort_keys=True))
Exemplo n.º 26
0
import sys
import json
from tetpyclient import RestClient
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

#Tetration IP address
API_ENDPOINT = "https://x.x.x.x"
searchString = str(sys.argv[1])
#auth using credentials.json file
restclient = RestClient(API_ENDPOINT,
                        credentials_file='credentials.json',
                        verify=False)
#GET
appScopes = restclient.get('/app_scopes').json()
#Iterate through JSON response for SearchStright and Print name and short_name, id, and query are also options among other
for s in appScopes:
    if searchString in s["name"]:
        req_payload = {
            "scopeName": s["name"],  # optional
            "filter": {
                "type":
                "and",
                "filters": [
                    {
                        "type": "subnet",
                        "field": "ip",
                        "value": "0.0.0.0/0"
                    },
                ]
            }
def main():
    module = AnsibleModule(
        argument_spec=dict(
            api_key=dict(type='str', required=True),
            api_secret=dict(type='str', required=True),
            host=dict(type='str', required=True),
            api_version=dict(type='str', default='v1'),
            name=dict(type='str', required=True),
            method=dict(type='str', required=True, choices=['delete', 'get', 'post', 'put']),
            payload=dict(type='dict', required=False),
            params=dict(type='dict', required=False),
        ),
        # we can't predict if the proposed API call will make a change to the system
        supports_check_mode=False
    )

    # if tetpyclient is not available, our only option is to fail
    try:
        import json
        import tetpyclient
        from tetpyclient import RestClient
    except ImportError:
        module.fail_json(msg="Some module dependencies are missing.")

    method = module.params['method']
    api_name = '/openapi/' + module.params['api_version'] + '/' + module.params['name']
    req_payload = module.params['payload']

    restclient = RestClient(
        module.params['host'],
        api_key=module.params['api_key'],
        api_secret=module.params['api_secret'],
        verify=False
    )
    
    # Do our best to provide "changed" status accurately, but it's not possible
    # as different Tetration APIs react differently to operations like creating
    # an element that already exists.
    changed = False
    if method == 'get':
        response = restclient.get(api_name, params=module.params['params'])
    elif method == 'delete':
        response = restclient.delete(api_name)
        changed = True if response.status_code / 100 == 2 else False
    elif method == 'post':
        response = restclient.post(api_name, json_body=json.dumps(req_payload))
        changed = True if response.status_code / 100 == 2 else False
    elif method == 'put':
        response = restclient.put(api_name, json_body=json.dumps(req_payload))
        changed = True if response.status_code / 100 == 2 else False


    # Put status_code in the return JSON. If the status_code is not 200, we
    # add the text that came from the REST call and the payload to make
    # debugging easier.
    result = {}
    result['status_code'] = response.status_code
    result['ok'] = response.ok
    result['reason'] = response.reason
    if int(response.status_code) / 100 == 2:
        result['json'] = response.json()
    else:
        result['text'] = response.text

    module.exit_json(changed=changed, **result)
Exemplo n.º 28
0
from pprint import pprint
import sys
import json
from tetpyclient import RestClient

#Tetration IP address
API_ENDPOINT = "https://10.0.76.4"
searchString = str(sys.argv[1])
#auth
restclient = RestClient(API_ENDPOINT,
                        credentials_file='credentials.json',
                        verify=False)
#GET
resp = restclient.get('/app_scopes')
#Turn Resp into python list
parsed_resp = resp.json()

#Iterate through JSON response for searchString and Print name and short_name, id, and query are also options among others
for s in range(len(parsed_resp)):
    if searchString in parsed_resp[s]["name"]:
        print(parsed_resp[s]["name"] + ' ID: ' + parsed_resp[s]["id"])
Exemplo n.º 29
0
    required=True,
    help=
    'Name of the Target Workspace for Conversations. If multiple workspaces have the same name, this may be random.  If not provided, it will default to a workspace for the root scope'
)
parser.add_argument(
    '--exclude_ephemeral_ports',
    action='store_true',
    default=False,
    help=
    'Filters out conversations with ports in the standard Windows ephemeral port range.  Only ports less than 49152 will be included.'
)
args = parser.parse_args()
rc = RestClient(args.tet_url, credentials_file=args.tet_creds, verify=True)

# Find workspace target for exporting conversations
workspaces = rc.get('/openapi/v1/applications').json()
workspace = None
if args.workspace != None:
    workspace = [x for x in workspaces if x['name'] == args.workspace]
    if len(workspace) > 0:
        workspace = workspace[0]
    else:
        print('No workspace named {} found.'.format(args.workspace))
        exit()

if workspace['latest_adm_version'] == 0:
    print(
        'Please run an ADM target workspace or in the global workspace with Deep Policy Generation checked prior to running this script.'
    )
    exit()
Exemplo n.º 30
0
                    type=str,
                    help='Comma Separate List of Important Annotation Fields',
                    required=True)
parser.add_argument(
    "--upload",
    type=str2bool,
    nargs='?',
    const=True,
    default=False,
    help=
    "If set, the script will also upload the reduced annotations file to Tetration."
)
args = parser.parse_args()

rc = RestClient(args.tet_url, credentials_file=args.tet_creds, verify=True)
root_scope = rc.get('/openapi/v1/app_scopes').json()[0]['root_app_scope_id']
global_workspace = [
    x for x in rc.get('/openapi/v1/applications').json()
    if x['app_scope_id'] == root_scope
]

if len(global_workspace) > 0:
    global_workspace = global_workspace[0]
else:
    print(
        'No global workspace found.  Please create a workspace in the root scope and run an ADM with Deep Policy Generation checked.  Then attempt to run this script again.'
    )
    exit()

if global_workspace['latest_adm_version'] == 0:
    print(