Ejemplo n.º 1
0
def parse_yaml(data):
    data_list = list()
    try :
        for i in data:
            for j in data[i]:
                    for k in data[i][j]:
                            data_dict = dict()
                            data_dict['--nm-zn']=i
                            data_dict['--nm'] = j
                            key = list(k.keys())
                            key = key[0]
                            data_dict['--type'] = key.upper()
                            data_dict['--ttl'] = k[key]['ttl']
                            data_dict['--nm-con'] = k[key]['content']
                            data_dict['--date'] = get_time()
                            if 'content-serial' in k[key]:
                                    data_dict['--nm-con-ser']=k[key]['content-serial']
                            data_list.append(data_dict)
        for i in data_list:
            if i['--type'] == 'SRV' or i['--type']=='MX':
                    if not '--nm-con-ser' in i:
                            data_list.remove(i)
            else :
                    if '--nm-con-ser' in i:
                            data_dict.remove(i)
        
        respon = generate_respons(True,'success',data_list)
    except Exception as e:
        respon = generate_respons(False,str(e))
    finally :
        return respon
Ejemplo n.º 2
0
    def test_create_record(self):
        mock_zone = ['testclis2.com', 'testclis.com']
        mock_type = ['tipe', 'CNAME']
        mock_ttl = ['2200', '7200']

        mock_data = list()
        passed = list()
        for zone in mock_zone:
            for tipe in mock_type:
                for ttl in mock_ttl:
                    mock_data.append({
                        '--nm-zn': zone,
                        '--type': tipe,
                        '--ttl': ttl,
                        '--nm': 'test',
                        '--nm-con': 'alias',
                        '--nm-con-ser': None
                    })

        mock_data.append({
            '--nm-zn': mock_zone[1],
            '--type': 'SRV',
            '--ttl': mock_ttl[1],
            '--nm': 'test',
            '--nm-con': 'alias',
            '--nm-con-ser': '80 80 80 80'
        })

        mock_data.append({
            '--nm-zn': mock_zone[1],
            '--type': 'MX',
            '--ttl': mock_ttl[1],
            '--nm': 'test',
            '--nm-con': 'alias',
            '--nm-con-ser': 'serialcontenttestdata'
        })
        for i in mock_data:
            if util.check_existence('zone', i['--nm-zn']):
                if (util.check_existence('type', i['--type'])
                        and util.check_existence('ttl', i['--ttl'])):
                    passed.append(i)
                    #print(i)
        for i in passed:
            i['--date'] = util.get_time()
            app.setRecord(i)
        record_list = ls.list_record([mock_zone[1]])
        record_list = util.convert(record_list['data'])
        clean = util.table_cleanup(record_list)
        check = True
        for i in record_list:
            for j in passed:
                if j['--type'] == i['nm_type']:
                    check = bool(check and bool(j['--nm-zn'] and i['nm_zone']))
                    check = bool(check and bool(j['--nm'] and i['nm_record']))
                    check = bool(check and bool(j['--ttl'] and i['nm_ttl']))
                    check = bool(check
                                 and bool(j['--nm-con'] and i['nm_content']))
        assert check == True
Ejemplo n.º 3
0
# Version: 1.0
#
# Copyright (c) 2020 - TalkaboutCyberSecurity (TABCS)
#

import time
import os
from libs.utils import initialization, write_file, get_json, get_time
from libs.init import config_file, possible, type_search
from libs.github import get_page_number, search_repository, handle_page
from libs.slack import send_message, send_list
from libs.rules import build_query

conf = initialization(config_file)
logs = get_json("{}/{}".format(conf['path_log'], "old_result"))
send_message(conf['msg_start'].format(get_time()), conf)
for r, d, f in os.walk(conf['path_rule']):
    for file in f:
        clone = {}
        rule_file = os.path.join(r, file)
        if rule_file[-5:] != ".yaml":
            continue
        queries, rule_id = build_query(rule_file)
        if rule_id not in logs:
            logs[rule_id] = {}
        if rule_id not in possible:
            possible[rule_id] = {}
        for typ in type_search:
            for query in queries:
                if typ != "code":
                    query = query.split(" ", 1)[0]
Ejemplo n.º 4
0
    def execute(self):
        if self.args['dns']:

            check = util.check_existence('zone', self.args['--nm'])
            if check['status']:
                print("ZONE ALREADY EXIST")
            else:
                if 'expired' in check['message']:
                    print(check['message'])
                else:
                    app.setDefaultDns(self.args['--nm'])

        elif self.args['record'] and not self.args['-f']:
            check = dict()
            skip = False
            nodata = ' '
            temp = check_zone_authorization([self.args['--nm-zn']])
            check['zone'] = temp['status']
            temp = util.check_existence('type', self.args['--type'].upper())
            check['type'] = temp['status']
            temp = util.check_existence('ttl', self.args['--ttl'])
            check['ttl'] = temp['status']
            print(check)

            if self.args['--type'].upper(
            ) == 'MX' or self.args['--type'].upper() == 'SRV':
                if self.args['--nm-con-ser'] is None:
                    util.log_warning(
                        "Record {} require serial content data".format(
                            self.args['--type'].upper()))
                    exit()
            for i in check:
                if not check[i]:
                    nodata = nodata + i + ', '
                    skip = True

            if skip is True:
                print(
                    "Value of " + nodata +
                    "doesn't exist. \nTry command ls to check available values"
                )
            else:
                self.args['--date'] = util.get_time()
                app.setRecord(self.args)
        elif self.args['record'] and self.args['-f']:
            path = self.args['-f']
            data = app.load_yaml(path)
            dnslist = list(data['data'].keys())
            check = check_zone_authorization(dnslist)
            sendlist = None
            if 'data' not in check:
                sendlist = dnslist

            else:
                for i in dnslist:
                    if i not in check['data']:
                        sendlist.append(i)

            if sendlist:
                print(
                    str(sendlist) +
                    " doesn't exist. Do you want to create these dns and continue? (Y/N)"
                )
                if util.assurance():
                    for i in sendlist:
                        app.setDefaultDns(i)
                else:
                    print("ABORT")
                    exit()

            data = app.parse_yaml(data['data'])

            send = data['data']
            for row in send:
                res = app.setRecord(row)
Ejemplo n.º 5
0
    def execute(self):
        if self.args['dns']:

            check = util.check_existence('zone', self.args['--nm'])
            if check['status']:
                print("ZONE ALREADY EXIST")
            else:
                if 'expired' in check['message']:
                    print(check['message'])
                else:
                    app.setDefaultDns(self.args['--nm'])

        elif self.args['record']:
            if not self.args['--nm'] and not self.args["-f"]:
                dns = list_dns()
                if 'data' not in dns:
                    print("You don't have any dns!")
                else:
                    dns = dns['data']
                    util.convert(dns)
                    show = list()
                    for row in dns:
                        show.append({"DNS NAME": row})
                    print("Your Domain List are ")
                    print(
                        tabulate(show,
                                 headers='keys',
                                 showindex='always',
                                 tablefmt="rst"))
                    print("Pick a zone for your record!")
                    value = input("Zone Name : ")
                    while value not in dns:
                        print(
                            "You are not authorized to access {}, or it doesn't exist!"
                            .format(value))
                        value = input("Zone Name : ")
                    self.args['--nm-zn'] = value
                    value = input("Record name : ")
                    while not value:
                        print("Record name can't be empty string")
                        value = input("Record name : ")
                    self.args['--nm'] = value
                    print("Choose Record Type")
                    rectype = listing_endpoint('type')
                    rectype = rectype.replace('SOA\t', '')
                    rectype = rectype.replace('NS\t', '')
                    print(rectype)
                    rectype = rectype.split('\t')
                    del rectype[-1]
                    value = input("Record type : ")
                    while value.upper() not in rectype:
                        print("Type doesn't exist")
                        value = input("")
                    self.args['--type'] = value.upper()
                    ttl = listing_endpoint('ttl')
                    print("Available TTL values are :")
                    print(ttl)
                    ttl = ttl.split('\t')
                    del ttl[-1]
                    value = input("TTL : ")
                    while value not in ttl:
                        print("TTL value doesn't exist")
                        value = input("TTL : ")
                    self.args['--ttl'] = value
                    value = input("Content data : ")
                    while not value:
                        print("Content data can not be empty ")
                        value = input("Content data : ")
                    self.args['--nm-con'] = value
                    if self.args['--type'] == 'MX' or self.args[
                            '--type'] == 'SRV':
                        value = input("Content serial data : ")
                        while not value:
                            print("Content serial data can not be empty ")
                            value = input("Content serial data : ")
                        self.args['--nm-con-ser'] = value
                    print(
                        "You are about to create new record with following details :"
                    )
                    if self.args['--nm-con-ser']:
                        print(
                            """Record Name : {}       Zone : {}       Type : {}       TTL : {}
Content data : {}       Content serial data :{}""".format(
                                self.args['--nm'], self.args['--nm-zn'],
                                self.args['--type'], self.args['--ttl'],
                                self.args['--nm-con'],
                                self.args['--nm-con-ser']))
                    else:
                        print(
                            """Record Name : {}       Zone : {}       Type : {}       TTL : {}
Content data : {}      """.format(self.args['--nm'], self.args['--nm-zn'],
                                  self.args['--type'], self.args['--ttl'],
                                  self.args['--nm-con']))
                    affirm = input("Are you sure ? (Y)")
                    if affirm.upper() == 'Y':
                        self.args['--date'] = util.get_time()
                        app.setRecord(self.args)
                    else:
                        print("Cancelled")
                        exit()

            elif self.args['--nm'] and not self.args['-f']:
                check = dict()
                skip = False
                nodata = ' '
                temp = check_zone_authorization([self.args['--nm-zn']])
                check['zone'] = temp['status']
                temp = util.check_existence('type',
                                            self.args['--type'].upper())
                check['type'] = temp['status']
                temp = util.check_existence('ttl', self.args['--ttl'])
                check['ttl'] = temp['status']

                if self.args['--type'].upper(
                ) == 'MX' or self.args['--type'].upper() == 'SRV':
                    if self.args['--nm-con-ser'] is None:
                        util.log_warning(
                            "Record {} require serial content data".format(
                                self.args['--type'].upper()))
                        exit()
                for i in check:
                    if not check[i]:
                        nodata = nodata + i + ', '
                        skip = True

                if skip is True:
                    print(
                        "Value of " + nodata +
                        "doesn't exist. \nTry command ls to check available values"
                    )
                else:
                    self.args['--date'] = util.get_time()
                    app.setRecord(self.args)
            elif self.args['-f']:
                path = self.args['-f']
                pbar = tqdm(total=100)
                step = (100 / 3)
                pbar.set_description("Loading YAML")
                data = app.load_yaml(path)
                dnslist = list(data['data'].keys())
                check = check_zone_authorization(dnslist)
                sendlist = list()
                pbar.update(step)
                pbar.set_description("Parsing YAML")
                if 'data' not in check:
                    sendlist = dnslist
                    pbar.update(step)

                else:
                    for i in dnslist:
                        pbar.update(step / (len(dnslist)))
                        if i not in check['data']:
                            sendlist.append(i)
                pct = (100 / 3)
                if sendlist:
                    print(
                        str(sendlist) +
                        " doesn't exist. Do you want to create these dns and continue? (Y/N)"
                    )
                    if util.assurance():
                        for i in sendlist:
                            pbar.set_description("Creating DNS {}".format(i))
                            app.setDefaultDns(i)
                            pbar.update(pct / (3 * len(sendlist)))
                        pct = (100 / 4)
                    else:
                        print("ABORT")
                        exit()

                data = app.parse_yaml(data['data'])
                send = data['data']
                print(tabulate(send, headers="keys", tablefmt="rst"))
                print("Create records above ? (Y) ")
                if util.assurance():
                    pbar.set_description(" Creating Record")
                    for row in send:
                        pbar.set_description(desc="Creating " +
                                             row['--nm-zn'] + " " +
                                             row['--nm'] + " " + row['--type'])
                        pbar.update(pct / (len(send)))
                        res = app.setRecord(row)
                    pbar.close()
                    print('\n')
                else:
                    print("ABORT")
                    exit()