コード例 #1
0
ファイル: ngfw.py プロジェクト: gabstopper/stonesoft-aws
def validate(firewall_policy=None,
             vpn=None,
             antivirus=None,
             gti=None,
             dns=None,
             **kwargs):
    """
    Validate that settings provided are valid objects in SMC before anything
    is kicked off to AWS. If Firewall Policy is not provided, bypass the 
    checks that it exists. When instance spins up, a new policy will be 
    created called "Default_AWS". if the policy exists, it will be re-used.
    """
    if firewall_policy is not None:
        obtain_fwpolicy(firewall_policy)
    if vpn is not None:
        try:
            vpn_policy = vpn['vpn_policy']
            obtain_vpnpolicy(vpn_policy)
        except KeyError:
            raise MissingRequiredInput(
                'VPN setting present but missing vpn_policy.')
    # Make sure DNS is provided or SMC will reject AV/GTI
    if (antivirus or gti) and not dns:
        raise MissingRequiredInput(
            'Anti-Virus and GTI require that DNS servers '
            'be specified')
コード例 #2
0
 def create(self, name, sources=None, destinations=None, 
            services=None, action='allow', is_disabled=False, 
            vpn_policy=None, **kwargs):
     """ 
     Create a layer 3 firewall rule
         
     :param str name: name of rule
     :param list source: source/s for rule, in href format
     :param list destination: destinations, in href format
     :param list service: service/s, in href format
     :param str action: allow|continue|discard|refuse|enforce_vpn|apply_vpn|blacklist 
            (default: allow)
     :param str: vpn_policy: vpn policy name; required for enforce_vpn and apply_vpn 
            actions 
     :raises: :py:class:`smc.api.exceptions.MissingRequiredInput` when options are
              specified the need additional setting, i.e. use_vpn action requires a
              vpn policy be specified.
     :raises: :py:class:`smc.api.exceptions.CreateRuleFailed`: rule creation failure
     :return: str href: href of new rule
     """
     rule_values = _rule_common(sources, destinations, services)
     rule_values.update(name=name)
    
     rule_action = Action(actions=self.actions)
     rule_action.action = action
     
     if rule_action.action in ['apply_vpn', 'enforce_vpn', 'forward_vpn']:
         if vpn_policy is None:
             raise MissingRequiredInput('A VPN policy must be specified when '
                                        'rule action has a VPN action')
         try:
             vpn = VPNPolicy(vpn_policy).href
             rule_action.vpn = vpn
         except ElementNotFound:
             raise MissingRequiredInput('Cannot find VPN policy specified: {}, '
                                        .format(vpn_policy))
     
     rule_values.update(rule_action())
     
     log_options = LogOptions()    
     auth_options = AuthenticationOptions()
     
     rule_values.update(log_options())
     rule_values.update(auth_options())
     rule_values.update(is_disabled=is_disabled)
     
     return prepared_request(CreateRuleFailed,
                             href=self.href,
                             json=rule_values).create().href
コード例 #3
0
def validate_aws(awscfg, vpc_create=False):
    """
    Validate AWS settings. For any add or create operations, the
    keypair and AMI are required. If this is for a VPC create, then
    also verify the subnets are provided.
    
    :raises: InvalidKeyPair.NotFound, InvalidAMIId.NotFound, 
             smc.api.exceptions.MissingRequiredInput
    """
    # Verify the AWS key pair exists, raises InvalidKeyPair.NotFound
    ec2.meta.client.describe_key_pairs(KeyNames=[awscfg.aws_keypair])
    # Verify AMI is valid; raises InvalidAMIID.NotFound
    ec2.meta.client.describe_images(ImageIds=[awscfg.ngfw_ami])

    if vpc_create:
        missing = []
        if not awscfg.vpc_subnet:
            missing.append('vpc_subnet')
        if not awscfg.vpc_private:
            missing.append('vpc_private')
        if not awscfg.vpc_public:
            missing.append('vpc_public')
        if awscfg.aws_client_ami:
            ec2.meta.client.describe_images(ImageIds=[awscfg.aws_client_ami])
        if missing:
            raise MissingRequiredInput(
                'Missing required settings in configuration: {}'.format(
                    missing))
コード例 #4
0
    def download(self, filename=None, as_type="zip"):
        """
        Download the IPList. List format can be either zip, text or
        json. For large lists, it is recommended to use zip encoding.
        Filename is required for zip downloads.

        :param str filename: Name of file to save to (required for zip)
        :param str as_type: type of format to download in: txt,json,zip (default: zip)
        :raises IOError: problem writing to destination filename
        :return: None
        """
        headers = None
        if as_type in ["zip", "txt", "json"]:
            if as_type == "zip":
                if filename is None:
                    raise MissingRequiredInput(
                        "Filename must be specified when " "downloading IPList as a zip file."
                    )
                filename = "{}".format(filename)
            elif as_type == "txt":
                headers = {"accept": "text/plain"}
            elif as_type == "json":
                headers = {"accept": "application/json"}

            result = self.make_request(
                FetchElementFailed,
                raw_result=True,
                resource="ip_address_list",
                filename=filename,
                headers=headers,
            )

            return result.json if as_type == "json" else result.content
コード例 #5
0
ファイル: network.py プロジェクト: shibumi/smc-python
    def download(self, filename=None, as_type='zip'):
        """
        Download the IPList. List format can be either zip, text or
        json. For large lists, it is recommended to use zip encoding.
        Filename is required for zip downloads.

        :param str filename: Name of file to save to (required for zip)
        :param str as_type: type of format to download in: txt,json,zip (default: zip)
        :raises IOError: problem writing to destination filename
        :return: None
        """
        headers = None
        if as_type in ['zip', 'txt', 'json']:
            if as_type == 'zip':
                if filename is None:
                    raise MissingRequiredInput(
                        'Filename must be specified when '
                        'downloading IPList as a zip file.')
                filename = '{}'.format(filename)
            elif as_type == 'txt':
                headers = {'accept': 'text/plain'}
            elif as_type == 'json':
                headers = {'accept': 'application/json'}

            result = self.make_request(FetchElementFailed,
                                       raw_result=True,
                                       resource='ip_address_list',
                                       filename=filename,
                                       headers=headers)

            return result.json if as_type == 'json' else result.content
コード例 #6
0
def multilink_member(netlink,
                     nat_range,
                     netlink_network=None,
                     netlink_role='active'):
    """
    :param StaticNetlink netlink: netlink element for multilink member
    :param str nat_range: ip address range to use for NAT. This needs
        to be a range in the same network defined in the netlink
    :param str,Element netlink_network: netlink network when multiple
        networks are defined within a netlink. Only one network can be
        defined for each multilink member.
    :param str netlink_role: role for this netlink member. Values can
        be 'active' or 'standby' (default: 'active')
    :raises ElementNotFound: if provided netlink or netlink_network is
        not found.
    :return: member dict required for calling Multilink create
    :rtype: dict
    """
    member = {}
    member.update(netlink_ref=netlink.href)
    if len(netlink.networks) > 1:
        if not netlink_network:
            raise MissingRequiredInput(
                'Netlink %r has more than one network defined. You must '
                'specify which network to use with the netlink_network '
                'parameter' % netlink.name)
        netlink_network = element_resolver(netlink_network)
        member.update(network_ref=netlink_network)
    else:
        member.update(network_ref=netlink.networks[0].href)

    member.update(ip_range=nat_range, netlink_role=netlink_role)
    return member
コード例 #7
0
ファイル: network.py プロジェクト: m4h3/smc-python
 def download(self, filename=None, as_type='zip'):
     """
     Download the IPList. List format can be either zip, text or
     json. For large lists, it is recommended to use zip encoding.
     Filename is required for zip downloads.
     
     :param str filename: Name of file to save to (required for zip)
     :param str as_type: type of format to download in: txt,json,zip (default: zip)
     :raises: IOError if problem writing to destination filename
     :return: None
     """
     headers=None
     if as_type in ['zip', 'txt', 'json']:
         if as_type == 'zip':
             if filename is None:
                 raise MissingRequiredInput('Filename must be specified when '
                                            'downloading IPList as a zip file.')
             filename = '{}'.format(filename)
         elif as_type == 'txt':
             headers={'accept':'text/plain'}
         elif as_type == 'json':
             headers = {'accept': 'application/json'}
         
         prepared_request(href=self._link('ip_address_list'), 
                          filename=filename,
                          headers=headers).read()
コード例 #8
0
def validate(firewall_policy, vpn=None, antivirus=None, 
             gti=None, dns=None, **kwargs):
    """
    Validate that settings provided are valid objects in SMC before anything
    is kicked off to AWS
    """
    obtain_fwpolicy(firewall_policy)
    if vpn is not None:
        try:
            vpn_policy = vpn['vpn_policy']
            obtain_vpnpolicy(vpn_policy)
        except KeyError:
            raise MissingRequiredInput('VPN setting present but missing vpn_policy.')
    # Make sure DNS is provided or SMC will reject AV/GTI
    if (antivirus or gti) and not dns:
        raise MissingRequiredInput('Anti-Virus and GTI require that DNS servers '
                                   'be specified')
コード例 #9
0
def obtain_vpnpolicy(vpn_policy=None):
    """
    Return available VPN policies
    
    :return: list available VPN Policies
    """
    policy = [vpn.name for vpn in describe_vpn()]
    if vpn_policy is None:
        return policy
    else:
        if not vpn_policy in policy:
            raise MissingRequiredInput('VPN policy not found, name provided: '
                                        '{}. Available policies: {}'
                                        .format(vpn_policy, policy))
コード例 #10
0
    def update_logical_if(self, logical_interfaces):
        e = {}
        if logical_interfaces is None:
            e.update(logical_interfaces={"any": True})
        else:
            try:
                logicals = []
                for interface in logical_interfaces:
                    logicals.append(LogicalInterface(interface).href)
                e.update(logical_interfaces={"logical_interface": logicals})

            except ElementNotFound:
                raise MissingRequiredInput(
                    "Cannot find Logical interface specified "
                    ": {}".format(logical_interfaces))
        return e
コード例 #11
0
def obtain_fwpolicy(firewall_policy=None):
    """
    Return layer 3 firewall policies
    
    :return: list available layer 3 firewall policies
    """
    policy = [policy.name for policy in describe_fw_policy()]
    if firewall_policy is None:
        return policy
    else:
        if not firewall_policy in policy:
            raise MissingRequiredInput('Firewall policy not found, name provided: '
                                       '{}. Available policies: {}'
                                       .format(firewall_policy, policy))
            
    return [policy.name for policy in describe_fw_policy()]
コード例 #12
0
ファイル: ngfw.py プロジェクト: gabstopper/stonesoft-aws
def obtain_fwpolicy(firewall_policy=None):
    """
    Return layer 3 firewall policies
    
    :param firewall_policy: when called from command line menu, we
        only need the list of options so firewall_policy will be none
    :return: list available layer 3 firewall policies
    """
    policy = [policy.name for policy in list(FirewallPolicy.objects.all())
              ]  # @UndefinedVariable
    if firewall_policy is None:
        return policy
    else:
        if not firewall_policy in policy:
            raise MissingRequiredInput(
                'Firewall policy not found, name provided: {}. Available policies: {}'
                .format(firewall_policy, policy))
コード例 #13
0
def _rule_l2_common(logical_interfaces):
        """
        Common values for layer 2 ethernet / IPS rule parameters.
        In particular, logical interfaces are an additional parameter that 
        can be used as a rule match parameter.
        """
        rule_values = {}
        if logical_interfaces is None:
            rule_values.update(logical_interfaces={'any': True})
        else:
            try:
                logicals=[]
                for interface in logical_interfaces:
                    logicals.append(LogicalInterface(interface).href)
                rule_values.update(logical_interfaces=
                                            {'logical_interface': logicals})
            except ElementNotFound:
                raise MissingRequiredInput('Cannot find Logical interface specified '
                                           ': {}'.format(logical_interfaces))
        return rule_values
コード例 #14
0
    def create(self,
               name,
               sources=None,
               destinations=None,
               services=None,
               action="allow",
               log_options=None,
               authentication_options=None,
               match_vpn_options=None,
               connection_tracking=None,
               is_disabled=False,
               vpn_policy=None,
               mobile_vpn=False,
               add_pos=None,
               after=None,
               before=None,
               sub_policy=None,
               comment=None,
               validate=True,
               **kw):
        """
        Create a layer 3 firewall rule

        .. versionchanged:: 0.7.0
            Action field now requires a list of actions as strings when using SMC
            version >= 6.6.0

        :param str name: name of rule
        :param sources: source/s for rule
        :type sources: list[str, Element]
        :param destinations: destination/s for rule
        :type destinations: list[str, Element]
        :param services: service/s for rule
        :type services: list[str, Element]
        :param action: allow,continue,discard,refuse,enforce_vpn,
            apply_vpn,forward_vpn, blacklist (default: allow)
        :type action: Action,str,list[str]
        :param LogOptions log_options: LogOptions object
        :param ConnectionTracking connection_tracking: custom connection tracking settings
        :param AuthenticationOptions authentication_options: options for auth if any
        :param SourceVpn match_vpn_options: rule matches traffic from specific VPNs
        :param PolicyVPN,str vpn_policy: policy element or str href; required for
            enforce_vpn, use_vpn and apply_vpn actions
        :param bool mobile_vpn: if using a vpn action, you can set mobile_vpn to True and
            omit the vpn_policy setting if you want this VPN to apply to any mobile VPN based
            on the policy VPN associated with the engine
        :param str,Element sub_policy: sub policy required when rule has an action of 'jump'.
            Can be the FirewallSubPolicy element or href.
        :param int add_pos: position to insert the rule, starting with position 1. If
            the position value is greater than the number of rules, the rule is inserted at
            the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually
            exclusive with ``after`` and ``before`` params.
        :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos``
            and ``before`` params.
        :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos``
            and ``after`` params.
        :param str comment: optional comment for this rule
        :param bool validate: validate the inspection policy during rule creation. Default: True
        :raises MissingRequiredInput: when options are specified the need additional
            setting, i.e. use_vpn action requires a vpn policy be specified.
        :raises CreateRuleFailed: rule creation failure
        :return: the created ipv4 rule
        :rtype: IPv4Rule
        """
        rule_values = self.update_targets(sources, destinations, services)

        rule_action = self._get_action(action)

        if any(vpn in rule_action.action
               for vpn in ("apply_vpn", "enforce_vpn", "forward_vpn")):
            if vpn_policy is None and not mobile_vpn:
                raise MissingRequiredInput(
                    "You must either specify a vpn_policy or set "
                    "mobile_vpn when using a rule with a VPN action")
            if mobile_vpn:
                rule_action.mobile_vpn = True
            else:
                try:
                    vpn = element_resolver(vpn_policy)  # VPNPolicy
                    rule_action.vpn = vpn
                except ElementNotFound:
                    raise MissingRequiredInput(
                        "Cannot find VPN policy specified: {}, ".format(
                            vpn_policy))

        elif "jump" in rule_action.action:
            try:
                rule_action.sub_policy = element_resolver(sub_policy)
            except ElementNotFound:
                raise MissingRequiredInput(
                    "Cannot find sub policy specified: {} ".format(sub_policy))

        log_options = LogOptions() if not log_options else log_options

        if connection_tracking is not None:
            rule_action.connection_tracking_options.update(
                **connection_tracking)

        auth_options = (AuthenticationOptions() if not authentication_options
                        else authentication_options)

        match_vpn_data = None if not match_vpn_options else match_vpn_options.data

        rule_values.update(name=name,
                           comment=comment,
                           action=rule_action.data,
                           options=log_options.data,
                           authentication_options=auth_options.data,
                           match_vpn_options=match_vpn_data,
                           is_disabled=is_disabled,
                           **kw)

        params = {"validate": False} if not validate else {}
        href = self.href
        if add_pos is not None:
            href = self.add_at_position(add_pos)
        elif before or after:
            params.update(**self.add_before_after(before, after))

        return ElementCreator(self.__class__,
                              exception=CreateRuleFailed,
                              href=href,
                              params=params,
                              json=rule_values)
コード例 #15
0
    def create(self,
               name,
               sources=None,
               destinations=None,
               services=None,
               action='allow',
               log_options=None,
               authentication_options=None,
               connection_tracking=None,
               is_disabled=False,
               vpn_policy=None,
               mobile_vpn=False,
               add_pos=None,
               after=None,
               before=None,
               sub_policy=None,
               comment=None,
               **kw):
        """ 
        Create a layer 3 firewall rule

        :param str name: name of rule
        :param sources: source/s for rule
        :type sources: list[str, Element]
        :param destinations: destination/s for rule
        :type destinations: list[str, Element]
        :param services: service/s for rule
        :type services: list[str, Element]
        :param action: allow,continue,discard,refuse,enforce_vpn,
            apply_vpn,forward_vpn, blacklist (default: allow)
        :type action: Action or str
        :param LogOptions log_options: LogOptions object
        :param ConnectionTracking connection_tracking: custom connection tracking settings
        :param AuthenticationOptions authentication_options: options for auth if any
        :param PolicyVPN,str vpn_policy: policy element or str href; required for
            enforce_vpn, use_vpn and apply_vpn actions
        :param bool mobile_vpn: if using a vpn action, you can set mobile_vpn to True and
            omit the vpn_policy setting if you want this VPN to apply to any mobile VPN based
            on the policy VPN associated with the engine
        :param str,Element sub_policy: sub policy required when rule has an action of 'jump'.
            Can be the FirewallSubPolicy element or href.
        :param int add_pos: position to insert the rule, starting with position 1. If
            the position value is greater than the number of rules, the rule is inserted at
            the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually
            exclusive with ``after`` and ``before`` params.
        :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos``
            and ``before`` params.
        :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos``
            and ``after`` params.
        :param str comment: optional comment for this rule
        :raises MissingRequiredInput: when options are specified the need additional 
            setting, i.e. use_vpn action requires a vpn policy be specified.
        :raises CreateRuleFailed: rule creation failure
        :return: the created ipv4 rule
        :rtype: IPv4Rule
        """
        rule_values = self.update_targets(sources, destinations, services)
        rule_values.update(name=name, comment=comment)

        if isinstance(action, Action):
            rule_action = action
        else:
            rule_action = Action()
            rule_action.action = action

        if not rule_action.action in self._actions:
            raise CreateRuleFailed('Action specified is not valid for this '
                                   'rule type; action: {}'.format(
                                       rule_action.action))

        if rule_action.action in ('apply_vpn', 'enforce_vpn', 'forward_vpn'):
            if vpn_policy is None and not mobile_vpn:
                raise MissingRequiredInput(
                    'You must either specify a vpn_policy or set '
                    'mobile_vpn when using a rule with a VPN action')
            if mobile_vpn:
                rule_action.mobile_vpn = True
            else:
                try:
                    vpn = element_resolver(vpn_policy)  # VPNPolicy
                    rule_action.vpn = vpn
                except ElementNotFound:
                    raise MissingRequiredInput(
                        'Cannot find VPN policy specified: {}, '.format(
                            vpn_policy))

        elif rule_action.action == 'jump':
            try:
                rule_action.sub_policy = element_resolver(sub_policy)
            except ElementNotFound:
                raise MissingRequiredInput(
                    'Cannot find sub policy specified: {} '.format(sub_policy))

        #rule_values.update(action=rule_action.data)

        log_options = LogOptions() if not log_options else log_options

        if connection_tracking is not None:
            rule_action.connection_tracking_options.update(
                **connection_tracking)

        auth_options = AuthenticationOptions() if not authentication_options \
            else authentication_options

        rule_values.update(action=rule_action.data,
                           options=log_options.data,
                           authentication_options=auth_options.data,
                           is_disabled=is_disabled)

        params = None
        href = self.href
        if add_pos is not None:
            href = self.add_at_position(add_pos)
        elif before or after:
            params = self.add_before_after(before, after)

        return ElementCreator(self.__class__,
                              exception=CreateRuleFailed,
                              href=href,
                              params=params,
                              json=rule_values)
コード例 #16
0
    def create(self,
               name,
               sources=None,
               destinations=None,
               services=None,
               action='allow',
               log_options=None,
               is_disabled=False,
               vpn_policy=None,
               add_pos=None,
               after=None,
               before=None,
               sub_policy=None,
               comment=None,
               **kw):
        """ 
        Create a layer 3 firewall rule

        :param str name: name of rule
        :param sources: source/s for rule
        :type sources: list[str, Element]
        :param destinations: destination/s for rule
        :type destinations: list[str, Element]
        :param services: service/s for rule
        :type services: list[str, Element]
        :param action: allow,continue,discard,refuse,enforce_vpn,
            apply_vpn,blacklist (default: allow)
        :type action: Action or str
        :param LogOptions log_options: LogOptions object
        :param str: vpn_policy: vpn policy name; required for enforce_vpn and apply_vpn 
               actions
        :param str,Element sub_policy: sub policy required when rule has an action of 'jump'.
            Can be the FirewallSubPolicy element or href.
        :param int add_pos: position to insert the rule, starting with position 1. If
            the position value is greater than the number of rules, the rule is inserted at
            the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually
            exclusive with ``after`` and ``before`` params.
        :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos``
            and ``before`` params.
        :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos``
            and ``after`` params.
        :param str comment: optional comment for this rule
        :raises MissingRequiredInput: when options are specified the need additional 
            setting, i.e. use_vpn action requires a vpn policy be specified.
        :raises CreateRuleFailed: rule creation failure
        :return: the created ipv4 rule
        :rtype: IPv4Rule
        """
        rule_values = self.update_targets(sources, destinations, services)
        rule_values.update(name=name, comment=comment)

        if isinstance(action, Action):
            rule_action = action
        else:
            rule_action = Action()
            rule_action.action = action

        if not rule_action.action in self._actions:
            raise CreateRuleFailed('Action specified is not valid for this '
                                   'rule type; action: {}'.format(
                                       rule_action.action))

        if rule_action.action in ['apply_vpn', 'enforce_vpn', 'forward_vpn']:
            if vpn_policy is None:
                raise MissingRequiredInput(
                    'A VPN policy must be specified when '
                    'rule action has a VPN action')
            try:
                vpn = PolicyVPN(vpn_policy).href
                rule_action.vpn = vpn
            except ElementNotFound:
                raise MissingRequiredInput(
                    'Cannot find VPN policy specified: {}, '.format(
                        vpn_policy))
        elif rule_action.action in ['jump']:
            try:
                rule_action.sub_policy = element_resolver(sub_policy)
            except ElementNotFound:
                raise MissingRequiredInput(
                    'Cannot find sub policy specified: {} '.format(sub_policy))

        rule_values.update(action=rule_action.data)

        if log_options is None:
            log_options = LogOptions()

        auth_options = AuthenticationOptions()

        rule_values.update(options=log_options.data)
        rule_values.update(authentication_options=auth_options.data)
        rule_values.update(is_disabled=is_disabled)

        params = None
        href = self.href
        if add_pos is not None:
            href = self.add_at_position(add_pos)
        elif before or after:
            params = self.add_before_after(before, after)

        return SubElementCreator(self.__class__,
                                 CreateRuleFailed,
                                 href=href,
                                 params=params,
                                 json=rule_values)