Example #1
0
def u_configuration(args):
    output = 'Update site {0} with configuration param={1} and value={2}.'.format(
        args.site_id, args.param, args.value)
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    print(output)
    # param = {
    #     "api_id": args.api_id,
    #     "api_key": args.api_key,
    #     "site_id": args.site_id,
    #     "param": args.param,
    #     "value": args.value
    # }
    param = vars(args)
    result = update(param)

    if int(result.get('res')) != 0:
        err = IncapError(result)
        err.log()
        return err
    else:
        resp = IncapResponse(result)
        print('Updated Site ID: {} {} configuration to {}'.format(
            args.site_id, args.param.replace('_', ' '), args.value))
        resp.log()
        return resp
Example #2
0
def c_account(args):
    output = 'With API_ID{0}, API Key={1} lets add {2}!'. format(args.api_id, args.api_key, args.account_name)
    logging.basicConfig(format='%(levelname)s - %(message)s',  level=getattr(logging, args.log.upper()))
    logging.info(output)

    param = {
        "api_id": args.api_id,
        "api_key": args.api_key,
        "email": args.email,
        "parent_id": args.parent_id,
        "ref_id": args.ref_id,
        "user_name": args.user_name,
        "plan_id": args.plan_id,
        "log_level": args.log_level,
        "logs_account_id": args.logs_account_id,
        "account_name": args.account_name
    }
    result = create(param)

    if result.get('res') != 0:
        err = IncapError(result)
        err.log()
    else:
        account = Account(result)
        print(account.log())
Example #3
0
def u_cachemode(args):
    output = 'Update cache setting on {0} to be {1}.'.format(
        args.site_id, args.cache_mode)
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    print(output)
    param = {
        "api_id": args.api_id,
        "api_key": args.api_key,
        "site_id": args.site_id,
        "cache_mode": args.cache_mode,
        "dynamic_cache_duration": args.dynamic_cache_duration,
        "aggressive_cache_duration": args.aggressive_cache_duration
    }
    result = update(param)

    if result.get('res') != 0:
        err = IncapError(result)
        err.log()
    else:
        resp = IncapResponse(result)
        print('Updated cache mode to {}'.format(
            param.get('cache_mode').replace('_', ' ')))
        if param.get('dynamic_cache_duration') != '':
            print('Setting dynamic cache duration to {}'.format(
                param.get('dynamic_cache_duration').replace('_', ' ')))
        if param.get('aggressive_cache_duration') != '':
            print('Setting aggressive cache duration to {}'.format(
                param.get('aggressive_cache_duration').replace('_', ' ')))
        resp.log()
        return resp
Example #4
0
def r_sites(args):
    output = 'Getting site list.'
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    print(output)
    param = {
        "api_id": args.api_id,
        "api_key": args.api_key,
        "account_id": args.account_id,
        "page_size": args.page_size,
        "page_num": args.page_num,
    }

    result = read(param)

    if result.get('res') != 0:
        err = IncapError(result)
        err.log()
        return err
    else:
        for site in result['sites']:
            print(
                'FQDN: %s - Status: %s - Site ID: %s' %
                (site.get('domain'), site.get('status'), site.get('site_id')))
        if args.export:
            config = IncapConfigurations()
            if args.path is None:
                path = config.get_repo()
            else:
                path = args.path
            filename = args.filename
            export_site(result, path, filename, param)
        return result.get('res_message')
Example #5
0
def u_cacherule(args):
    output = 'Update cache rules on {0}.'.format(args.site_id)
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    print(output)
    param = {
        "api_id": args.api_id,
        "api_key": args.api_key,
        "site_id": args.site_id,
        "always_cache_resource_url": args.always_cache_resource_url,
        "always_cache_resource_pattern": args.always_cache_resource_pattern,
        "always_cache_resource_duration": args.always_cache_resource_duration,
        "never_cache_resource_url": args.never_cache_resource_url,
        "never_cache_resource_pattern": args.never_cache_resource_pattern,
        "cache_headers": args.cache_headers,
        "clear_always_cache_rules": args.clear_always_cache_rules,
        "clear_never_cache_rules": args.clear_never_cache_rules,
        "clear_cache_headers_rules": args.clear_cache_headers_rules
    }
    result = update(param)

    if int(result.get('res')) != 0:
        err = IncapError(result)
        err.log()
    else:
        resp = IncapResponse(result)
        print('Updated cache rule(s) on site ID: {}'.format(
            param.get('site_id')))
        for k, v in param.items():

            if len(k) > 10 and len(v) > 0:
                print('Setting {} to {}'.format(k.replace('_', ' '), v))
        resp.log()
        return resp
Example #6
0
def u_certificate(args):
    output = 'Upload Certificate to: {0}'.format(args.site_id)
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    print(output)

    param = {
        "api_id": args.api_id,
        "api_key": args.api_key,
        "site_id": args.site_id,
        "certificate": args.certificate,
        "private_key": args.private_key,
        "passphrase": args.passphrase
    }

    result = upload(param)

    if result.get('res') != 0:
        err = IncapError(result)
        err.log()
        return err
    else:
        cert = IncapResponse(result)
        print('Added certificate to site ID: {} '.format(args.site_id))
        cert.log()
        return cert
Example #7
0
def c_site(args):
    output = 'Creating site: {0}'. format(args.domain)
    logging.basicConfig(format='%(levelname)s - %(message)s',  level=getattr(logging, args.log.upper()))
    print(output)

    param = {
        "api_id": args.api_id,
        "api_key": args.api_key,
        "account_id": args.account_id,
        "force_ssl": args.force_ssl,
        "ref_id": args.ref_id,
        "send_site_setup_emails": args.send_site_setup_emails,
        "site_ip": args.site_ip,
        "log_level": args.log_level,
        "logs_account_id": args.logs_account_id,
        "domain": args.domain
    }

    result = create(param)

    if result.get('res') != 0:
        err = IncapError(result)
        err.log()
        return err
    else:
        site = Site(result)
        print('Created: %s, ID: %s ' % (site.get_domain(), str(site.get_id())))
        return site
Example #8
0
def r_audit(args):
    output = 'Get account audit events.'
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    print(output)
    param = vars(args)

    # param = {
    #     "api_id": args.api_id,
    #     "api_key": args.api_key,
    #     "account_id": args.account_id,
    #     "time_range": args.time_range,
    #     "start": args.start,
    #     "end": args.end,
    #     "type": args.type,
    #     "page_size": args.page_size,
    #     "page_num": args.page_num
    # }

    result = read(param)

    if int(result.get('res')) != 0:
        err = IncapError(result)
        err.log()
    elif 'audit_events' in result:
        print('Account audit events following:\n')
        for events in result.get('audit_events'):
            audit = Audit(events)
            print(audit.log())
Example #9
0
def c_incaprule(args):
    output = 'Create incapRule = {0} for site: {1}'. format(args.name, args.site_id)
    logging.basicConfig(format='%(levelname)s - %(message)s',  level=getattr(logging, args.log.upper()))
    print(output)
    param = {
        "api_id": args.api_id,
        "api_key": args.api_key,
        "site_id": args.site_id,
        "name": args.name,
        "action": args.action,
        "filter": args.filter,
        "response_code": args.response_code,
        "protocol": args.protocol,
        "add_missing": args.add_missing,
        "from": args.origin,
        "to": args.to,
        "rewrite_name": args.rewrite_name,
        "dc_id": args.dc_id,
        "is_test_mode": args.is_test_mode,
        "lb_algorithm": args.lb_algorithm
    }

    result = create(param)
    if result.get('res') != '0':
        err = IncapError(result)
        err.log()
    else:
        resp = IncapResponse(result)
        print('Created IncapRule ID: {}'.format(resp.get_rule_id()))
        resp.log()
        return resp
Example #10
0
def recover_site(file, params):
    old_site = Site(json.load(file))
    if params['domain'] is None:
        print('Restoring {0}'.format(old_site.domain))
        params['domain'] = old_site.domain
    else:
        print('Creating {0} from {1} template'.format(params['domain'],
                                                      old_site.domain))
        result = create(params)
        if int(result.get('res')) != 0:
            logging.error('%s was not created, please review logs.' %
                          params['domain'])
            err = IncapError(result)
            err.log()
        else:
            new_site = Site(result) or None
            print('Created: %s, ID: %s ' %
                  (new_site.get_domain(), str(new_site.get_id())))
            acl = ACL(old_site.security, new_site.site_id)
            acl.update()
            sec = Security(old_site.security, new_site.site_id)
            sec.update()
            if old_site.incap_rules is not []:
                for rule in old_site.incap_rules:
                    logging.debug('Incap Rule JSON Response: {}'.format(
                        json.dumps(rule, indent=4)))
                    incap_rule = IncapRule(rule)
                    incap_rule_params = incap_rule.set_param(new_site.site_id)
                    incap_rule.create_incap_rule(incap_rule_params)
Example #11
0
 def _execute(result, action):
     if result.get('res') != '0':
         err = IncapError(result)
         err.log()
         return err
     else:
         print('{} successful on server ID: {}'.format(
             action[0].upper() + action[1:], result['server_id']))
Example #12
0
 def _list(result):
     if int(result.get('res')) != 0:
         err = IncapError(result)
         err.log()
         return err
     else:
         for dcs in result['DCs']:
             DataCenter.print_data_center([dcs])
Example #13
0
 def _execute(result, action):
     if int(result.get('res')) != 0:
         err = IncapError(result)
         err.log()
         return err
     else:
         print('{} successful on IncapRule {}'.format(
             action[0].upper() + action[1:],
             result.get('rule_id') or ''))
Example #14
0
def r_incaprule(args):
    output = 'Get incapRules for site: {0}'.format(args.site_id)
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    print(output)
    param = {
        "api_id": args.api_id,
        "api_key": args.api_key,
        "site_id": args.site_id,
        "include_ad_rules": args.include_ad_rules,
        "include_incap_rules": args.include_incap_rules,
        "page_size": args.page_size,
        "page_num": args.page_num
    }

    result = read(param)
    logging.debug('JSON Response: {}'.format(json.dumps(result, indent=4)))

    if int(result.get('res')) != 0:
        err = IncapError(result)
        err.log()
    else:
        if 'incap_rules' in result:
            if 'All' in result['incap_rules']:
                for rule in result['incap_rules']['All']:
                    incap_rule = IncapRule(rule)
                    print(incap_rule.log())
            else:
                logging.info('You have no IncapRules!!!')

        if 'delivery_rules' in result:
            if 'Redirect' in result['delivery_rules']:
                for rule in result['delivery_rules']['Redirect']:
                    print("RULE: {}".format(rule))
                    adr_rule = ADRuleRedirect(rule)
                    print(adr_rule.log())
            else:
                logging.info('You have no Redirect Rules!!!')

            if 'Forward' in result['delivery_rules']:
                for rule in result['delivery_rules']['Forward']:
                    adr_rule = ADRuleForward(rule)
                    print(adr_rule.log())
            else:
                logging.info('You have no Forward Rules!!!')

            if 'Rewrite' in result['delivery_rules']:
                for rule in result['delivery_rules']['Rewrite']:
                    print("RULE: {}".format(rule))
                    adr_rule = ADRuleRewrite(rule)
                    print(adr_rule.log())
            else:
                logging.info('You have no Rewrite Rules!!!')
    return result
Example #15
0
def u_security(args):
    param = vars(args)
    #action = param['do']
    output = 'Update site {0} security configuration.'.format(args.site_id)
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    print(output)

    if args.rule_id == 'ddos' and args.activation_mode == '':
        logging.warning(
            'Activation mode param is required:\n'
            'activation_mode=api.threats.ddos.activation_mode.auto\n'
            'activation_mode=api.threats.ddos.activation_mode.off\n'
            'activation_mode=api.threats.ddos.activation_mode.on')
        exit(0)

    activation_mode = ''
    rule_id = ''
    security_rule_action = ''

    if args.activation_mode:
        activation_mode = 'api.threats.ddos.activation_mode.' + args.activation_mode
    if args.rule_id:
        rule_id = 'api.threats.' + args.rule_id
    if args.security_rule_action:
        security_rule_action = 'api.threats.action.' + args.security_rule_action

    param['rule_id'] = rule_id
    param['activation_mode'] = activation_mode
    param['security_rule_action'] = security_rule_action
    # param = {"api_id": args.api_id,
    #     "api_key": args.api_key,
    #     "site_id": args.site_id,
    #     "rule_id": rule_id,
    #     "block_bad_bots": args.block_bad_bots,
    #     "challenge_suspected_bots": args.challenge_suspected_bots,
    #     "activation_mode": activation_mode,
    #     "security_rule_action": security_rule_action,
    #     "quarantined_urls": args.quarantined_urls,
    #     "ddos_traffic_threshold": args.ddos_traffic_threshold
    # }

    result = update(param)

    if int(result.get('res')) != 0:
        err = IncapError(result)
        err.log()
    else:
        site = Site(result)
        print('Updated {} Security(WAF) Rule for {}.'.format(
            args.rule_id.replace('_', ' '), site.domain))
        return site
Example #16
0
def get_update_file(filename, param, cl_id):
    try:
        result = read(param)
        with open(filename, 'w') as outfile:
            if int(result.get('res')) != 0:
                err = IncapError(result)
                err.log()
            else:
                json.dump(result, outfile)
                return result['clientAppTypes'][
                    cl_id] + ' with client name ' + result['clientApps'][cl_id]
    except OSError as e:
        logging.error(e.strerror)
Example #17
0
def r_account(args):
    output = 'Get account status!'
    param = vars(args)
    logging.basicConfig(format='%(levelname)s - %(message)s', level=getattr(logging, args.log.upper()))
    logging.info(output)

    result = read(param)

    if int(result.get('res')) != 0:
        err = IncapError(result)
        err.log()
    else:
        account = Account(result)
        print(account.log())
Example #18
0
def u_whitelist(args):
    output = 'Update whitelist rule ID={0}.'.format(args.rule_id)
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    print(output)

    rule_id = ''
    if "listed" in args.rule_id:
        rule_id = 'api.acl.' + args.rule_id
    else:
        rule_id = 'api.threats.' + args.rule_id

    param = {
        "api_id": args.api_id,
        "api_key": args.api_key,
        "site_id": args.site_id,
        "rule_id": rule_id,
        "urls": args.urls,
        "countries": args.countries,
        "continents": args.continents,
        "ips": args.ips,
        "whitelist_id": args.whitelist_id,
        "delete_whitelist": args.delete_whitelist,
        "client_app_types": args.client_app_types,
        "client_apps": args.client_apps,
        "parameters": args.parameters,
        "user_agents": args.user_agents
    }

    result = update(param)

    if result.get('res') != 0:
        err = IncapError(result)
        err.log()
        return err
    else:
        site = Site(result)
        # for rule in site.waf_rules:
        #     logging.debug('Rule JSON: {}'.format(rule, indent=4))
        #     if rule['id'] == args.rule_id:
        #         logging.debug('WAF Rules: {}'.format(site.get_waf_rules()))
        #         print('WAF Rule Name: {} has the following exceptions:'.format(rule['name']))
        #         for exceptions in rule['exceptions']:
        #             logging.debug('Exception ID: {}'.format(exceptions['id']))
        #             for exception in exceptions['values']:
        #                 value = IncapException(exception)
        #                 print("Exception Type: {}".format(value.id.replace('api.rule_exception_type.', '').replace('_', ' ')))
        #logging.debug('WAF Rules: {}'.format(site.get_waf_rules()))
        print('Updated successful')
        return site
Example #19
0
    def _copy(result, ):
        if int(result.get('res')) != 0:
            err = IncapError(result)
            err.log()
        else:
            if 'incap_rules' in result:
                if 'All' in result['incap_rules']:
                    for rule in result['incap_rules']['All']:
                        incap_rule = IncapRule(rule)
                        print(incap_rule.log())
                else:
                    logging.info('You have no IncapRules!!!')

            if 'delivery_rules' in result:
                if 'Redirect' in result['delivery_rules']:
                    for rule in result['delivery_rules']['Redirect']:
                        adr_rule = ADRuleRedirect(rule)
                        print(adr_rule.log())
                else:
                    logging.info('You have no Redirect Rules!!!')

                if 'Forward' in result['delivery_rules']:
                    for rule in result['delivery_rules']['Forward']:
                        adr_rule = ADRuleForward(rule)
                        print(adr_rule.log())
                else:
                    logging.info('You have no Forward Rules!!!')

                if 'Rewrite' in result['delivery_rules']:
                    for rule in result['delivery_rules']['Rewrite']:
                        data = ""
                        del rule["id"]
                        del rule["enabled"]
                        del rule["priority"]
                        del rule["allow_caching"]
                        del rule["last_7_days_requests_count"]

                        for k, v in rule.items():
                            if k == "filter" and v == "":
                                data += 'URL contains "^/"'
                            elif k == "filter" and v is not "":
                                data += "--{}='{}' ".format(k, v)
                            else:
                                data += '--{}="{}" '.format(k, v)

                        adr_rule = ADRuleRewrite(rule)
                        print(adr_rule.log())
                else:
                    logging.info('You have no Rewrite Rules!!!')
Example #20
0
def r_subscription(args):
    output = 'Get account subscription!'
    param = vars(args)
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    logging.info(output)

    result = read(param)

    if int(result.get('res')) != 0:
        err = IncapError(result)
        err.log()
    else:
        logging.info('Subscription Response: {}'.format(
            json.dumps(result, indent=4)))
Example #21
0
def r_sites(args):
    output = 'Getting site list.'
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    print(output)
    param = vars(args)

    result = read(param)
    if int(result.get('res')) != 0:
        err = IncapError(result)
        err.log()
        return err
    else:
        format_site = TableFormatter(headers=['domain', 'status', 'site_id'],
                                     data=result['sites'])
        PrintTable(label='Sites', data=format_site.headers).print_all()
Example #22
0
def c_account(args):
    output = 'With API_ID{0}, API Key={1} lets add {2}!'.format(
        args.api_id, args.api_key, args.account_name)
    param = vars(args)
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    logging.info(output)

    result = create(param)

    if int(result.get('res')) != 0:
        err = IncapError(result)
        err.log()
    else:
        account = Account(result)
        print(account.log())
Example #23
0
def r_subaccount(args):
    output = 'Get sub accounts!'
    param = vars(args)
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    logging.info(output)

    result = read(param)
    logging.debug('JSON Response: {}'.format(json.dumps(result, indent=4)))

    if int(result.get('res')) != 0:
        err = IncapError(result)
        err.log()
    else:
        for accounts in result['resultList']:
            account = SubAccount(accounts)
            print(account.log())
Example #24
0
def r_account(args):
    output = 'Get account status!'
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    logging.info(output)
    param = {
        "api_id": args.api_id,
        "api_key": args.api_key,
        "account_id": args.account_id
    }
    result = read(param)

    if result.get('res') != 0:
        err = IncapError(result)
        err.log()
    else:
        account = Account(result)
        print(account.log())
Example #25
0
def d_site(args):
    output = 'Delete site ID = {0}!'.format(args.site_id)
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    print(output)
    param = {
        "api_id": args.api_id,
        "api_key": args.api_key,
        "site_id": args.site_id
    }
    result = delete(param)

    if result.get('res') != 0:
        err = IncapError(result)
        err.log()
        return err
    else:
        resp = IncapResponse(result)
        resp.log()
        return resp
Example #26
0
def d_incaprule(args):
    output = 'Delete incapRule ID = {0}'.format(args.rule_id)
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    print(output)
    param = {
        "api_id": args.api_id,
        "api_key": args.api_key,
        "rule_id": args.rule_id
    }

    result = delete(param)

    if result.get('res') != '0':
        err = IncapError(result)
        err.log()
    else:
        print('Deleted IncapRule ID:{}'.format(param.get('rule_id')))
        resp = IncapResponse(result)
        resp.log()
        return resp
Example #27
0
def r_accounts(args):
    output = 'Get accounts!'
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    print(output)
    param = {
        "api_id": args.api_id,
        "api_key": args.api_key,
        "account_id": args.account_id,
        "page_size": args.page_size,
        "page_num": args.page_num
    }
    result = read(param)

    if result.get('res') != 0:
        err = IncapError(result)
        err.log()
    else:
        for accounts in result['accounts']:
            account = Account(accounts)
            print(account.log())
Example #28
0
def r_site(args):
    output = 'Get site status for ID = {0}'.format(args.site_id)
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    print(output)
    param = {
        "api_id": args.api_id,
        "api_key": args.api_key,
        "tests": args.tests,
        "site_id": args.site_id
    }

    result = read(param)

    if result.get('res') != 0:
        err = IncapError(result)
        err.log()
        return err
    else:
        site = Site(result)
        site.log()
        return site
Example #29
0
def r_site(args):
    output = 'Get site status for ID = {0}'.format(args.site_id)
    logging.basicConfig(format='%(levelname)s - %(message)s',
                        level=getattr(logging, args.log.upper()))
    print(output)
    param = vars(args)

    result = read(param)

    if int(result.get('res')) != 0:
        err = IncapError(result)
        err.log()
        return err
    else:
        #
        # format_site = TableFormatter(headers=['domain', 'status', 'site_id', 'account_id',
        #                                       'acceleration_level', 'site_creation_date', 'active',
        #                                       'support_all_tls_versions', 'extended_ddos', 'log_level']
        #                              , data=[result])
        # PrintTable(label='Sites', data=format_site.headers).print_all()
        site = Site(result)
        site.log()
        return site
Example #30
0
def r_clapps():
    logging.debug('Retrieving client apps list for client_app_id to Client Application Name.')
    param = {
        "api_id": None,
        "api_key": None
    }

    result = read(param)
    try:
        home = os.path.expanduser('~')
        filename = home + '/.incap/exports'
        if not os.path.exists(filename):
            os.makedirs(filename)
        with open(filename + '/clapps.json', 'w') as outfile:
            json.dump(result, outfile)
    except OSError as e:
        logging.error(e.strerror)

    if result.get('res') != 0:
        err = IncapError(result)
        err.log()
    else:
        return result