예제 #1
0
fauxapi_apikey = sys.argv[2]
fauxapi_apisecret = sys.argv[3]
rule_category = sys.argv[4]
rule_action = sys.argv[5]

FauxapiLib = FauxapiLib(fauxapi_host,
                        fauxapi_apikey,
                        fauxapi_apisecret,
                        debug=False)

# Get the current set of filters
filters = FauxapiLib.config_get('filter')

# Iterate through and find 'KinderControl' rules, find enable/disable
i = 0
for rule in filters['rule']:
    if (rule['descr'].startswith(rule_prefix)):
        if (rule_category in rule['descr']):
            if (rule_action == "enable"):
                del filters['rule'][i]['disabled']
                print("Rule {} enabled.".format(rule['descr']))
            elif (rule_action == "disable"):
                filters['rule'][i]['disabled'] = ""
                print("Rule {} disabled.".format(rule['descr']))
    i = i + 1

# Push the config back to pfSense
filters = FauxapiLib.config_set(filters, 'filter')

# Reload the config
FauxapiLib.send_event("filter reload")
class UpdateAwsAliasesFauxapi():

    fauxapi_host = None
    fauxapi_apikey = None
    fauxapi_apisecret = None

    system_config= None
    aws_ipranges_uri = 'https://ip-ranges.amazonaws.com/ip-ranges.json'

    FauxapiLib = None

    def __init__(self, fauxapi_host, fauxapi_apikey, fauxapi_apisecret, debug=False):
        self.FauxapiLib = FauxapiLib(fauxapi_host, fauxapi_apikey, fauxapi_apisecret, debug)

    def update(self, regions_match='*', services_match='*', ipv4=True, ipv6=True):

        # Use FauxapiLib to load the remote system config into memory
        self.system_config = self.FauxapiLib.config_get()

        # download ip-ranges.json parse and iterate
        for name, data in sorted(self.get_aws_ipranges().items()):
            if regions_match == '*' or regions_match.replace('*','').replace('-','').lower() in name:
                if services_match == '*' or services_match.replace('*', '').replace('_', '').lower() in name:
                    addresses = []
                    if ipv4 is True and len(data['ipv4']) > 0:
                        addresses += data['ipv4']
                    if ipv6 is True and len(data['ipv6']) > 0:
                        addresses += data['ipv6']
                    self.update_alias_in_config(
                        name=name,
                        description=data['description'],
                        addresses=addresses,
                        aws_create_date=data['aws_create_date']
                    )

        # Use FauxapiLib to save to the remote system the new edited config
        result = self.FauxapiLib.config_set(self.system_config)
        print(json.dumps(result))

    def update_alias_in_config(self, name, description, addresses, aws_create_date):

        addresses.sort()

        # candidate alias to apply
        alias_data = {
            'name': name,
            'type': 'network',
            'address': ' '.join(addresses),
            'descr': description,
            'detail': '||'.join(['ip-ranges.json createDate: {}'.format(aws_create_date)] * len(addresses))
        }

        if 'aliases' not in self.system_config or type(self.system_config['aliases']) is not dict:
            self.system_config['aliases'] = {}

        if 'alias' not in self.system_config['aliases'] or type(self.system_config['aliases']['alias']) is not list:
            self.system_config['aliases']['alias'] = []

        alias_found = False
        for index, alias in enumerate(self.system_config['aliases']['alias']):
            if alias['name'] == name:
                alias_found = True
                if alias['address'] != alias_data['address']:
                    self.system_config['aliases']['alias'][index] = alias_data

        if alias_found is False:
            self.system_config['aliases']['alias'].append(alias_data)

    def get_aws_ipranges(self):

        with urllib.request.urlopen(self.aws_ipranges_uri) as response:
            aws_ipranges_data = json.loads(response.read())

        ipranges = {}
        for prefix in aws_ipranges_data['prefixes'] + aws_ipranges_data['ipv6_prefixes']:

            name = 'aws_{}_{}'.format(
                prefix['region'].replace('-','').lower(),
                prefix['service'].replace('_','').lower()
            )[:32]

            if name not in ipranges:
                ipranges[name] = {
                    'ipv4': [],
                    'ipv6': [],
                    'description': 'AWS {region} {service}'.format(region=prefix['region'], service=prefix['service']),
                    'aws_create_date': aws_ipranges_data['createDate']
                }

            if 'ip_prefix' in prefix and len(prefix['ip_prefix']) > 0:
                ipranges[name]['ipv4'].append(prefix['ip_prefix'])

            if 'ipv6_prefix' in prefix and len(prefix['ipv6_prefix']) > 0:
                ipranges[name]['ipv6'].append(prefix['ipv6_prefix'])

        return ipranges
예제 #3
0
FauxapiLib = FauxapiLib(fauxapi_host,
                        fauxapi_apikey,
                        fauxapi_apisecret,
                        debug=False)

# config get the full configuration and simply print to console
# =============================================================================
config = FauxapiLib.config_get()
print(json.dumps(config))

# config set the full configuration
# =============================================================================
# NB: nothing amazing is happening here, we are simply writing back the same (full) configuration again, the developer
# most likely wants to make changes to `config` before calling the config_set function again here
print(json.dumps(FauxapiLib.config_set(config)))

# config_get, config_set by section
# =============================================================================
# perform a second config_get > config_set this time within the 'aliases' section only
# NB: again, nothing amazing happening in this example, we are are again only writing back the same (section)
# configuration, the developer more likely wants to perform some kind of operation on `config_aliases` before calling
# the config_set function again.
config_aliases = FauxapiLib.config_get('aliases')
print(json.dumps(FauxapiLib.config_set(config_aliases, 'aliases')))

# config_patch
# =============================================================================
# in this example we patch a specific set of configuration parameters and then revert them back to what they were
config_patch = {
    'system': {