Ejemplo n.º 1
0
 def testRaisesTermErrorOnEgressTermMissingDestIP(self):
   """Test that an egress term without a destination IP raises an error."""
   with self.assertRaises(gcp.TermError):
     gcp_hf.HierarchicalFirewall(
         policy.ParsePolicy(HEADER_OPTION_EGRESS + BAD_TERM_NO_DEST_IP,
                            self.naming),
         EXP_INFO)
Ejemplo n.º 2
0
 def testDefaultDenyIngressCreation(self):
   """Test that the correct IP is correctly set on a deny all ingress term."""
   acl = gcp_hf.HierarchicalFirewall(
       policy.ParsePolicy(HEADER_NO_OPTIONS + TERM_DENY_INGRESS, self.naming),
       EXP_INFO)
   expected = json.loads(EXPECTED_DENY_INGRESS)
   self.assertEqual(expected, json.loads(self._StripAclHeaders(str(acl))))
Ejemplo n.º 3
0
 def testRaisesTermErrorOnIngressTermMissingSourceIP(self):
   """Test that an ingress term without a source IP raises an error."""
   self.naming.GetServiceByProto.side_effect = [['53']]
   with self.assertRaises(gcp.TermError):
     gcp_hf.HierarchicalFirewall(
         policy.ParsePolicy(HEADER_NO_OPTIONS + BAD_TERM_NO_SOURCE_IP,
                            self.naming),
         EXP_INFO)
Ejemplo n.º 4
0
 def testIgnorePolicyFromADifferentPlatform(self):
   """Test that a policy with a header from a different platform is ignored."""
   acl = gcp_hf.HierarchicalFirewall(
       policy.ParsePolicy(BAD_HEADER_WRONG_PLATFORM
                          + TERM_ALLOW_ALL_INTERNAL,
                          self.naming),
       EXP_INFO)
   self.assertEqual([], json.loads(self._StripAclHeaders(str(acl))))
Ejemplo n.º 5
0
 def testRaisesHeaderErrorOnInvalidMaxCost(self):
   """Test that a maximum default cost over 2^16 raises a HeaderError."""
   with self.assertRaises(gcp.HeaderError):
     gcp_hf.HierarchicalFirewall(
         policy.ParsePolicy(BAD_HEADER_INVALID_MAX_COST
                            + TERM_ALLOW_ALL_INTERNAL,
                            self.naming),
         EXP_INFO)
Ejemplo n.º 6
0
 def testRaisesHeaderErrorOnUnknownDirection(self):
   """Test that an unknown direction option raises a HeaderError."""
   with self.assertRaises(gcp.HeaderError):
     gcp_hf.HierarchicalFirewall(
         policy.ParsePolicy(BAD_HEADER_UNKNOWN_DIRECTION
                            + TERM_ALLOW_ALL_INTERNAL,
                            self.naming),
         EXP_INFO)
Ejemplo n.º 7
0
 def testRaisesExceededCostError(self):
   """Test that ExceededCostError is raised when policy exceeds max cost."""
   self.naming.GetNetAddr.side_effect = [TEST_IP]
   with self.assertRaises(gcp_hf.ExceededCostError):
     gcp_hf.HierarchicalFirewall(
         policy.ParsePolicy(HEADER_VERY_LOW_DEFAULT_MAX
                            + TERM_ALLOW_ALL_INTERNAL, self.naming),
         EXP_INFO)
Ejemplo n.º 8
0
  def testRaisesTermErrorOnTermWithOptions(self):
    """Test that a term with a source port raises Term error."""
    self.naming.GetNetAddr.return_value = TEST_IP

    with self.assertRaises(gcp.TermError):
      gcp_hf.HierarchicalFirewall(
          policy.ParsePolicy(HEADER_NO_OPTIONS + BAD_TERM_OPTIONS,
                             self.naming),
          EXP_INFO)
Ejemplo n.º 9
0
  def testRaisesTermErrorOnInvalidVPCName(self):
    """Test that an invalid VPC name on target resources raises Term error."""
    self.naming.GetNetAddr.return_value = TEST_IP

    with self.assertRaises(gcp.TermError):
      gcp_hf.HierarchicalFirewall(
          policy.ParsePolicy(HEADER_NO_OPTIONS + BAD_TERM_NON_VALID_VPC_NAME,
                             self.naming),
          EXP_INFO)
Ejemplo n.º 10
0
  def testRaisesTermErrorOnTermWithSourcePort(self):
    """Test that a term with a source port raises Term error."""
    self.naming.GetNetAddr.return_value = TEST_IP
    self.naming.GetServiceByProto.side_effect = [['53']]

    with self.assertRaises(gcp.TermError):
      gcp_hf.HierarchicalFirewall(
          policy.ParsePolicy(HEADER_NO_OPTIONS + BAD_TERM_SOURCE_PORT,
                             self.naming),
          EXP_INFO)
Ejemplo n.º 11
0
  def testOptionMaxAndAF(self):
    """Test a header with default maximum cost & address family is accepted."""
    self.naming.GetNetAddr.return_value = TEST_IP

    acl = gcp_hf.HierarchicalFirewall(
        policy.ParsePolicy(HEADER_OPTION_MAX_AND_AF + TERM_ALLOW_ALL_INTERNAL,
                           self.naming),
        EXP_INFO)
    expected = json.loads(EXPECTED_ONE_RULE_INGRESS)
    self.assertEqual(expected, json.loads(self._StripAclHeaders(str(acl))))
Ejemplo n.º 12
0
  def testOptionEgressAndAF(self):
    """Test a header with a direction and address family is accepted."""
    self.naming.GetNetAddr.return_value = TEST_IP

    acl = gcp_hf.HierarchicalFirewall(
        policy.ParsePolicy(HEADER_OPTION_EGRESS_AND_AF + TERM_RESTRICT_EGRESS,
                           self.naming),
        EXP_INFO)
    expected = json.loads(EXPECTED_ONE_RULE_EGRESS)
    self.assertEqual(expected, json.loads(self._StripAclHeaders(str(acl))))
Ejemplo n.º 13
0
  def testDefaultHeader(self):
    """Test that a header without options is accepted."""
    self.naming.GetNetAddr.return_value = TEST_IP

    acl = gcp_hf.HierarchicalFirewall(
        policy.ParsePolicy(HEADER_NO_OPTIONS + TERM_ALLOW_ALL_INTERNAL,
                           self.naming),
        EXP_INFO)
    expected = json.loads(EXPECTED_ONE_RULE_INGRESS)
    self.assertEqual(expected, json.loads(self._StripAclHeaders(str(acl))))
Ejemplo n.º 14
0
  def testSecondWayOfPassingTargetResources(self):
    """Test that the target resources is used correctly."""
    self.naming.GetNetAddr.return_value = [nacaddr.IP('0.0.0.0/0')]

    acl = gcp_hf.HierarchicalFirewall(
        policy.ParsePolicy(HEADER_NO_OPTIONS + TERM_WITH_TARGET_RESOURCES_2,
                           self.naming),
        EXP_INFO)
    expected = json.loads(EXPECTED_DENY_INGRESS_ON_TARGET)
    self.assertEqual(expected, json.loads(self._StripAclHeaders(str(acl))))
Ejemplo n.º 15
0
  def testRaisesTermErrorOnTermWithSourceTag(self):
    """Test that a term with a source tag raises an error.

    Tags are not supported in HF.
    """
    with self.assertRaises(gcp.TermError):
      gcp_hf.HierarchicalFirewall(
          policy.ParsePolicy(HEADER_NO_OPTIONS + BAD_TERM_USING_SOURCE_TAG,
                             self.naming),
          EXP_INFO)
Ejemplo n.º 16
0
  def testLogging(self):
    """Test that logging is used when it is set on a term."""
    self.naming.GetNetAddr.return_value = TEST_IP
    self.naming.GetServiceByProto.side_effect = [['53'], ['53']]

    acl = gcp_hf.HierarchicalFirewall(
        policy.ParsePolicy(HEADER_NO_OPTIONS + TERM_WITH_LOGGING, self.naming),
        EXP_INFO)
    expected = json.loads(EXPECTED_ONE_RULE_INGRESS_W_LOGGING)
    self.assertEqual(expected, json.loads(self._StripAclHeaders(str(acl))))
Ejemplo n.º 17
0
  def testPriority(self):
    """Test that priority is set based on terms' ordering."""
    self.naming.GetNetAddr.return_value = TEST_IP
    self.naming.GetServiceByProto.side_effect = [['53'], ['53']]

    acl = gcp_hf.HierarchicalFirewall(
        policy.ParsePolicy(HEADER_NO_OPTIONS + TERM_ALLOW_ALL_INTERNAL
                           + TERM_ALLOW_DNS, self.naming),
        EXP_INFO)
    expected = json.loads(EXPECTED_MULTIPLE_RULE_INGRESS)
    self.assertEqual(expected, json.loads(self._StripAclHeaders(str(acl))))
Ejemplo n.º 18
0
  def testPortRange(self):
    """Test that a port range is accepted and used correctly."""
    self.naming.GetNetAddr.return_value = TEST_IP
    self.naming.GetServiceByProto.side_effect = [['8000-9000']]

    acl = gcp_hf.HierarchicalFirewall(
        policy.ParsePolicy(HEADER_NO_OPTIONS + TERM_ALLOW_PORT_RANGE,
                           self.naming),
        EXP_INFO)
    expected = json.loads(EXPECTED_PORT_RANGE_INGRESS)
    self.assertEqual(expected, json.loads(self._StripAclHeaders(str(acl))))
Ejemplo n.º 19
0
  def testBuildTokens(self):
    """Test that _BuildTokens generates the expected list of tokens."""
    self.naming.GetNetAddr.side_effect = [TEST_IP]

    pol1 = gcp_hf.HierarchicalFirewall(
        policy.ParsePolicy(HEADER_NO_OPTIONS + TERM_ALLOW_ALL_INTERNAL,
                           self.naming),
        EXP_INFO)
    st, sst = pol1._BuildTokens()
    self.assertEqual(st, SUPPORTED_TOKENS)
    self.assertEqual(sst, SUPPORTED_SUB_TOKENS)
Ejemplo n.º 20
0
  def testTermLongComment(self):
    """Test that a term's long comment gets truncated."""
    self.naming.GetNetAddr.return_value = TEST_IP

    acl = gcp_hf.HierarchicalFirewall(
        policy.ParsePolicy(HEADER_NO_OPTIONS + TERM_LONG_COMMENT,
                           self.naming),
        EXP_INFO)
    comment_truncated = EXPECTED_ONE_RULE_INGRESS.replace(
        'Generic description',
        'This is a very long description, it is longer than sixty-four ch')
    expected = json.loads(comment_truncated)
    self.assertEqual(expected, json.loads(self._StripAclHeaders(str(acl))))
Ejemplo n.º 21
0
  def testMultiplePolicies(self):
    """Tests that both ingress and egress rules are included in one policy."""
    self.maxDiff = None
    self.naming.GetNetAddr.return_value = TEST_IP

    acl = gcp_hf.HierarchicalFirewall(
        policy.ParsePolicy(HEADER_NO_OPTIONS + TERM_ALLOW_ALL_INTERNAL +
                           TERM_DENY_INGRESS + HEADER_OPTION_EGRESS +
                           TERM_RESTRICT_EGRESS + TERM_DENY_EGRESS,
                           self.naming),
        EXP_INFO)
    expected = json.loads(EXPECTED_INGRESS_AND_EGRESS_W_DENY)
    self.assertEqual(expected, json.loads(self._StripAclHeaders(str(acl))))
Ejemplo n.º 22
0
 def testCostIsCorrectlyCalculatedWhenPassingACollapsableIPRange(self):
   """Test GetCost works as-expected with a term using collapsable IP range."""
   self.naming.GetNetAddr.return_value = [nacaddr.IP('10.1.1.0/25'),
                                          nacaddr.IP('10.1.1.128/25')]
   self.naming.GetServiceByProto.side_effect = [['80']]
   # Notice that:
   # - EXPECTED_COST_OF_ONE has 10.1.1.0/24 as source IP instead of
   # 10.1.1.0/25 and 10.1.1.128/25.
   # - HEADER_VERY_LOW_DEFAULT_MAX allows a maximum cost of 1, and that if the
   # IP ranges were not compressed, the total cost of the term TERM_ALLOW_PORT
   # would be 2 and this test would raise ExceededCostError.
   acl = gcp_hf.HierarchicalFirewall(
       policy.ParsePolicy(HEADER_VERY_LOW_DEFAULT_MAX + TERM_ALLOW_PORT,
                          self.naming),
       EXP_INFO)
   expected = json.loads(EXPECTED_COST_OF_ONE)
   self.assertEqual(expected, json.loads(self._StripAclHeaders(str(acl))))
Ejemplo n.º 23
0
def RenderFile(base_directory: str, input_file: pathlib.Path,
               output_directory: pathlib.Path, definitions: naming.Naming,
               exp_info: int, optimize: bool, shade_check: bool,
               write_files: WriteList):
    """Render a single file.

  Args:
    base_directory: The base directory to look for acls.
    input_file: the name of the input policy file.
    output_directory: the directory in which we place the rendered file.
    definitions: the definitions from naming.Naming().
    exp_info: print a info message when a term is set to expire in that many
      weeks.
    optimize: a boolean indicating if we should turn on optimization or not.
    shade_check: should we raise an error if a term is completely shaded
    write_files: a list of file tuples, (output_file, acl_text), to write
  """
    output_relative = input_file.relative_to(base_directory).parent.parent
    output_directory = output_directory / output_relative

    logging.debug('rendering file: %s into %s', input_file, output_directory)

    pol = None
    jcl = False
    acl = False
    atp = False
    asacl = False
    aacl = False
    bacl = False
    eacl = False
    gca = False
    gcefw = False
    gcphf = False
    ips = False
    ipt = False
    msmpc = False
    spd = False
    nsx = False
    pcap_accept = False
    pcap_deny = False
    pf = False
    srx = False
    jsl = False
    nft = False
    win_afw = False
    nxacl = False
    xacl = False
    paloalto = False

    try:
        with open(input_file) as f:
            conf = f.read()
            logging.debug('opened and read %s', input_file)
    except IOError as e:
        logging.warning('bad file: \n%s', e)
        raise

    try:
        pol = policy.ParsePolicy(conf,
                                 definitions,
                                 optimize=optimize,
                                 base_dir=base_directory,
                                 shade_check=shade_check)
    except policy.ShadingError as e:
        logging.warning('shading errors for %s:\n%s', input_file, e)
        return
    except (policy.Error, naming.Error):
        raise ACLParserError(
            'Error parsing policy file %s:\n%s%s' %
            (input_file, sys.exc_info()[0], sys.exc_info()[1]))

    platforms = set()
    for header in pol.headers:
        platforms.update(header.platforms)

    if 'juniper' in platforms:
        jcl = copy.deepcopy(pol)
    if 'cisco' in platforms:
        acl = copy.deepcopy(pol)
    if 'ciscoasa' in platforms:
        asacl = copy.deepcopy(pol)
    if 'brocade' in platforms:
        bacl = copy.deepcopy(pol)
    if 'arista' in platforms:
        eacl = copy.deepcopy(pol)
    if 'arista_tp' in platforms:
        atp = copy.deepcopy(pol)
    if 'aruba' in platforms:
        aacl = copy.deepcopy(pol)
    if 'ipset' in platforms:
        ips = copy.deepcopy(pol)
    if 'iptables' in platforms:
        ipt = copy.deepcopy(pol)
    if 'msmpc' in platforms:
        msmpc = copy.deepcopy(pol)
    if 'nsxv' in platforms:
        nsx = copy.deepcopy(pol)
    if 'packetfilter' in platforms:
        pf = copy.deepcopy(pol)
    if 'pcap' in platforms:
        pcap_accept = copy.deepcopy(pol)
        pcap_deny = copy.deepcopy(pol)
    if 'speedway' in platforms:
        spd = copy.deepcopy(pol)
    if 'srx' in platforms:
        srx = copy.deepcopy(pol)
    if 'srxlo' in platforms:
        jsl = copy.deepcopy(pol)
    if 'windows_advfirewall' in platforms:
        win_afw = copy.deepcopy(pol)
    if 'cisconx' in platforms:
        nxacl = copy.deepcopy(pol)
    if 'ciscoxr' in platforms:
        xacl = copy.deepcopy(pol)
    if 'nftables' in platforms:
        nft = copy.deepcopy(pol)
    if 'gce' in platforms:
        gcefw = copy.deepcopy(pol)
    if 'gcp_hf' in platforms:
        gcphf = copy.deepcopy(pol)
    if 'paloalto' in platforms:
        paloalto = copy.deepcopy(pol)
    if 'cloudarmor' in platforms:
        gca = copy.deepcopy(pol)

    acl_obj: aclgenerator.ACLGenerator

    try:
        if jcl:
            acl_obj = juniper.Juniper(jcl, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if msmpc:
            acl_obj = junipermsmpc.JuniperMSMPC(msmpc, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if srx:
            acl_obj = junipersrx.JuniperSRX(srx, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if acl:
            acl_obj = cisco.Cisco(acl, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if asacl:
            acl_obj = ciscoasa.CiscoASA(asacl, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if aacl:
            acl_obj = aruba.Aruba(aacl, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if bacl:
            acl_obj = brocade.Brocade(bacl, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if eacl:
            acl_obj = arista.Arista(eacl, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if atp:
            acl_obj = arista_tp.AristaTrafficPolicy(atp, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if ips:
            acl_obj = ipset.Ipset(ips, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if ipt:
            acl_obj = iptables.Iptables(ipt, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if nsx:
            acl_obj = nsxv.Nsxv(nsx, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if spd:
            acl_obj = speedway.Speedway(spd, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if pcap_accept:
            acl_obj = pcap.PcapFilter(pcap_accept, exp_info)
            RenderACL(str(acl_obj), '-accept' + acl_obj.SUFFIX,
                      output_directory, input_file, write_files)
        if pcap_deny:
            acl_obj = pcap.PcapFilter(pcap_deny, exp_info, invert=True)
            RenderACL(str(acl_obj), '-deny' + acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if pf:
            acl_obj = packetfilter.PacketFilter(pf, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if win_afw:
            acl_obj = windows_advfirewall.WindowsAdvFirewall(win_afw, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if jsl:
            acl_obj = srxlo.SRXlo(jsl, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if nxacl:
            acl_obj = cisconx.CiscoNX(nxacl, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if xacl:
            acl_obj = ciscoxr.CiscoXR(xacl, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if nft:
            acl_obj = nftables.Nftables(nft, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if gcefw:
            acl_obj = gce.GCE(gcefw, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if gcphf:
            acl_obj = gcp_hf.HierarchicalFirewall(gcphf, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)

        if paloalto:
            acl_obj = paloaltofw.PaloAltoFW(paloalto, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
        if gca:
            acl_obj = cloudarmor.CloudArmor(gca, exp_info)
            RenderACL(str(acl_obj), acl_obj.SUFFIX, output_directory,
                      input_file, write_files)
    # TODO(robankeny) add additional errors.
    except (juniper.Error, junipermsmpc.Error, junipersrx.Error, cisco.Error,
            ipset.Error, iptables.Error, speedway.Error, pcap.Error,
            aclgenerator.Error, aruba.Error, nftables.Error, gce.Error,
            cloudarmor.Error) as e:
        raise ACLGeneratorError('Error generating target ACL for %s:\n%s' %
                                (input_file, e))
Ejemplo n.º 24
0
 def testRaisesTermErrorOnTermWithUnsupportedProtocol(self):
   """Test that a term with an unsupported protocol raises an error."""
   with self.assertRaises(gcp.TermError):
     gcp_hf.HierarchicalFirewall(
         policy.ParsePolicy(HEADER_NO_OPTIONS + BAD_TERM_PROTO, self.naming),
         EXP_INFO)