Esempio n. 1
0
    def __str__(self):
        target_header = []
        target = []

        for (header, filter_name, terms) in self.ciscoasa_policies:

            target.append('clear configure access-list %s' % filter_name)

            # add the p4 tags
            target.extend(
                aclgenerator.AddRepositoryTags('access-list %s remark ' %
                                               filter_name))

            # add a header comment if one exists
            for comment in header.comment:
                for line in comment.split('\n'):
                    target.append('access-list %s remark %s' %
                                  (filter_name, line))

            # now add the terms
            for term in terms:
                target.append(str(term))

            # end for header, filter_name, filter_type...
            return '\n'.join(target)
Esempio n. 2
0
  def __str__(self):
    """Render the output of the PF policy into config."""
    target = []
    pretty_platform = '%s%s' % (self._PLATFORM[0].upper(), self._PLATFORM[1:])
    # Create address table.
    for name in sorted(self.address_book):
      entries = ',\\\n'.join(str(x) for x in
                             sorted(self.address_book[name], key=int))
      target.append('table <%s> {%s}' % (name, entries))
    # pylint: disable=unused-variable
    for (header, filter_name, filter_type, terms) in self.pf_policies:
      # Add comments for this filter
      target.append('# %s %s Policy' % (pretty_platform,
                                        header.FilterName(self._PLATFORM)))

      # reformat long text comments, if needed
      comments = aclgenerator.WrapWords(header.comment, 70)
      if comments and comments[0]:
        for line in comments:
          target.append('# %s' % line)
        target.append('#')
      # add the p4 tags
      target.extend(aclgenerator.AddRepositoryTags('# '))
      target.append('# ' + filter_type)

      # add the terms
      for term in terms:
        term_str = str(term)
        if term_str:
          target.append(term_str)
      target.append('')

    return '\n'.join(target)
Esempio n. 3
0
    def __str__(self):
        target_header = []
        target = []
        # add the p4 tags
        target.extend(aclgenerator.AddRepositoryTags('! '))

        for (header, filter_name, filter_list, terms,
             obj_target) in self.cisco_policies:
            for filter_type in filter_list:
                target.extend(
                    self._AppendTargetByFilterType(filter_name, filter_type))
                if filter_type == 'object-group':
                    obj_target.AddName(filter_name)

                # Add the Perforce Id/Date tags, these must come after
                # remove/re-create of the filter, otherwise config mode doesn't
                # know where to place these remarks in the configuration.
                if filter_type == 'standard' and filter_name.isdigit():
                    target.extend(
                        aclgenerator.AddRepositoryTags(
                            'access-list %s remark ' % filter_name,
                            date=False,
                            revision=False))
                else:
                    target.extend(
                        aclgenerator.AddRepositoryTags(' remark ',
                                                       date=False,
                                                       revision=False))

                # add a header comment if one exists
                for comment in header.comment:
                    for line in comment.split('\n'):
                        target.append(' remark %s' % line)

                # now add the terms
                for term in terms:
                    term_str = str(term)
                    if term_str:
                        target.append(term_str)

            if obj_target.valid:
                target = [str(obj_target)] + target
            # ensure that the header is always first
            target = target_header + target
            target += ['', 'exit', '']
        return '\n'.join(target)
    def testAddRepositoryTags(self):
        # Format print the '$' into the RCS tags in order prevent the tags from
        # being interpolated here.

        # Include all tags.
        self.assertItemsEqual([
            '%sId:%s' % ('$', '$'),
            '%sDate:%s' % ('$', '$'),
            '%sRevision:%s' % ('$', '$')
        ], aclgenerator.AddRepositoryTags())
        # Remove the revision tag.
        self.assertItemsEqual(
            ['%sId:%s' %
             ('$', '$'), '%sDate:%s' % ('$', '$')],
            aclgenerator.AddRepositoryTags(revision=False))
        # Only include the Id: tag.
        self.assertItemsEqual(['%sId:%s' % ('$', '$')],
                              aclgenerator.AddRepositoryTags(date=False,
                                                             revision=False))
Esempio n. 5
0
    def __str__(self):
        target = []

        for term in self.gce_policies:
            target.extend(term.ConvertToDict())

        out = '%s\n%s\n\n' % (
            '\n'.join(aclgenerator.AddRepositoryTags('# ')),
            json.dumps(
                target, indent=2, separators=(',', ': '), sort_keys=True))

        return out
Esempio n. 6
0
    def __str__(self):
        """Render the output of the JuniperSRX policy into config."""
        target = IndentList(self.INDENT)
        target.append('security {')

        # ADDRESSBOOK
        target.extend(self._GenerateAddressBook())

        # POLICIES
        target.IndentAppend(1, '/*')
        target.extend(aclgenerator.AddRepositoryTags(self.INDENT * 1))
        target.IndentAppend(1, '*/')

        target.IndentAppend(1, 'replace: policies {')

        for (header, terms, filter_options) in self.srx_policies:
            target.IndentAppend(2, '/*')
            target.extend([
                self.INDENT * 2 + line for line in aclgenerator.WrapWords(
                    header.comment, self._MAX_HEADER_COMMENT_LENGTH)
            ])
            target.IndentAppend(2, '*/')

            # ZONE DIRECTION
            if filter_options[1] == 'all' and filter_options[3] == 'all':
                target.IndentAppend(2, 'global {')
            else:
                target.IndentAppend(
                    2, 'from-zone ' + filter_options[1] + ' to-zone ' +
                    filter_options[3] + ' {')

            # GROUPS
            if header.apply_groups:
                target.IndentAppend(
                    3, JunipersrxList('apply-groups', header.apply_groups))
            # GROUPS EXCEPT
            if header.apply_groups_except:
                target.IndentAppend(
                    3,
                    JunipersrxList('apply-groups-except',
                                   header.apply_groups_except))
            for term in terms:
                str_result = str(term)
                if str_result:
                    target.append(str_result)
            target.IndentAppend(2, '}')
        target.IndentAppend(1, '}')
        target.append('}')

        # APPLICATIONS
        target.extend(self._GenerateApplications())

        return '\n'.join(target)
Esempio n. 7
0
    def __str__(self):
        """Render the output of the Nsxv policy."""

        target_header = []
        target = []

        # add the p4 tags
        target.append('<!--')
        target.extend(aclgenerator.AddRepositoryTags(' '))
        target.append('-->')

        for (header, _, _, terms) in self.nsxv_policies:
            # add a header comment if one exists
            section_name = ''
            for comment in header.comment:
                for line in comment.split('\n'):
                    section_name = '%s %s' % (section_name, line)

            # getting section id
            filter_options = header.FilterOptions(self._PLATFORM)
            section_id = 0
            if filter_options is not None and len(filter_options) > 1:
                section_id = filter_options[1]

            # check section id value
            if not section_id or section_id == 0:
                logging.warn(
                    'WARNING: Section-id is 0. A new Section is created for%s.'
                    ' If there is any existing section, it will remain '
                    'unreferenced and should be removed manually.',
                    section_name)
                target.append('<section name="%s">' %
                              (section_name.strip(' \t\n\r')))
            else:
                target.append('<section id="%s" name="%s">' %
                              (section_id, section_name.strip(' \t\n\r')))

            # now add the terms
            for term in terms:
                term_str = str(term)
                if term_str:
                    target.append(term_str)
            target.append('\n')

            # ensure that the header is always first
            target = target_header + target
            target.append('%s' % (_XML_TABLE.get('sectionEnd')))
            target.append('\n')
        return '\n'.join(target)
Esempio n. 8
0
    def __str__(self):
        target = []
        pretty_platform = '%s%s' % (self._PLATFORM[0].upper(),
                                    self._PLATFORM[1:])

        if self._RENDER_PREFIX:
            target.append(self._RENDER_PREFIX)

        for (header, filter_name, filter_type, default_action,
             terms) in self.iptables_policies:
            # Add comments for this filter
            target.append('# %s %s Policy' %
                          (pretty_platform, header.FilterName(self._PLATFORM)))

            # reformat long text comments, if needed
            comments = aclgenerator.WrapWords(header.comment, 70)
            if comments and comments[0]:
                for line in comments:
                    target.append('# %s' % line)
                target.append('#')
            # add the p4 tags
            target.extend(aclgenerator.AddRepositoryTags('# '))
            target.append('# ' + filter_type)

            if filter_name in self._GOOD_FILTERS:
                if default_action:
                    target.append(self._DEFAULTACTION_FORMAT %
                                  (filter_name, default_action))
                elif self._PLATFORM == 'speedway':
                    # always specify the default filter states for speedway,
                    # if default action policy not specified for iptables, do nothing.
                    target.append(self._DEFAULTACTION_FORMAT %
                                  (filter_name, self._DEFAULT_ACTION))
            else:
                # Custom chains have no concept of default policy.
                target.append(self._DEFAULTACTION_FORMAT_CUSTOM_CHAIN %
                              filter_name)
            # add the terms
            for term in terms:
                term_str = str(term)
                if term_str:
                    target.append(term_str)

        if self._RENDER_SUFFIX:
            target.append(self._RENDER_SUFFIX)

        target.append('')
        return '\n'.join(target)
Esempio n. 9
0
    def __str__(self):
        target = []

        # add the p4 tags
        target.extend(aclgenerator.AddRepositoryTags('! '))
        for filter_name, terms, ip_ver in self.aruba_policies:
            netdestination = 'netdestination'
            if ip_ver == 6:
                netdestination += '6'
            target.append('no %s %s' % (netdestination, filter_name))
            target.append('%s %s' % (netdestination, filter_name))

            # now add the terms
            for term in terms:
                target.append(str(term))

        if target:
            target.append('')
        return '\n'.join(target)
Esempio n. 10
0
    def __str__(self):
        """Render the output of the Nsxv policy."""

        target_header = []
        target = []

        # add the p4 tags
        target.append('<!--')
        target.extend(aclgenerator.AddRepositoryTags('\n'))
        target.append('\n')
        target.append('-->')

        for (_, _, _, terms) in self.nsxv_policies:
            section_name = self._FILTER_OPTIONS_DICT['section_name']
            # check section id value
            section_id = self._FILTER_OPTIONS_DICT['section_id']
            if not section_id or section_id == 0:
                logging.warn(
                    'WARNING: Section-id is 0. A new Section is created for%s.'
                    ' If there is any existing section, it will remain '
                    'unreferenced and should be removed manually.',
                    section_name)
                target.append('<section name="%s">' %
                              (section_name.strip(' \t\n\r')))
            else:
                target.append('<section id="%s" name="%s">' %
                              (section_id, section_name.strip(' \t\n\r')))

            # now add the terms
            for term in terms:
                term_str = str(term)
                if term_str:
                    target.append(term_str)

            # ensure that the header is always first
            target = target_header + target
            target.append('%s' % (_XML_TABLE.get('sectionEnd')))
            target.append('\n')

            target_as_xml = xml.dom.minidom.parseString(''.join(target))
        return target_as_xml.toprettyxml(indent="  ", encoding="UTF-8")
Esempio n. 11
0
    def __str__(self):
        target = []

        target.extend(aclgenerator.AddRepositoryTags('%s ' % _COMMENT_MARKER))

        for filter_name, terms, _ in self.aruba_policies:
            netdestinations = []
            term_strings = []

            for term in terms:
                term_strings.append(str(term))
                netdestinations.extend(term.netdestinations)

            target.extend(netdestinations)
            target.append('%s %s' % (self._ACL_LINE_HEADER, filter_name))
            target.extend(term_strings)
            target.extend(_TERMINATOR_MARKER)

        if target:
            target.append('')

        return '\n'.join(target)
Esempio n. 12
0
    def __str__(self):
        config = Config()

        for (header, filter_name, filter_type, interface_specific,
             terms) in self.juniper_policies:
            # add the header information
            config.Append('firewall {')
            config.Append('family %s {' % filter_type)
            config.Append('replace:')
            config.Append('/*')

            # we want the acl to contain id and date tags, but p4 will expand
            # the tags here when we submit the generator, so we have to trick
            # p4 into not knowing these words.  like taking c-a-n-d-y from a
            # baby.
            for line in aclgenerator.AddRepositoryTags('** '):
                config.Append(line)
            config.Append('**')

            for comment in header.comment:
                for line in comment.split('\n'):
                    config.Append('** ' + line)
            config.Append('*/')

            config.Append('filter %s {' % filter_name)
            if interface_specific:
                config.Append('interface-specific;')

            for term in terms:
                term_str = str(term)
                if term_str:
                    config.Append(term_str, verbatim=True)

            config.Append('}')  # filter { ... }
            config.Append('}')  # family inet { ... }
            config.Append('}')  # firewall { ... }

        return str(config) + '\n'
Esempio n. 13
0
    def __str__(self):
        target = []
        pretty_platform = '%s%s' % (self._PLATFORM[0].upper(),
                                    self._PLATFORM[1:])

        if self._RENDER_PREFIX:
            target.append(self._RENDER_PREFIX)

        for (header, filter_name, filter_type, default_action,
             terms) in self.windows_policies:
            # Add comments for this filter
            target.append(': %s %s Policy' %
                          (pretty_platform, header.FilterName(self._PLATFORM)))

            self._HandlePolicyHeader(header, target)

            # reformat long text comments, if needed
            comments = aclgenerator.WrapWords(header.comment, 70)
            if comments and comments[0]:
                for line in comments:
                    target.append(': %s' % line)
                target.append(':')
            # add the p4 tags
            target.extend(aclgenerator.AddRepositoryTags(': '))
            target.append(': ' + filter_type)

            if default_action:
                target.append(self._DEFAULTACTION_FORMAT %
                              (filter_name, default_action))
            # add the terms
            for term in terms:
                term_str = str(term)
                if term_str:
                    target.append(term_str)
                    self._HandleTermFooter(header, term, target)

        target.append('')
        return '\n'.join(target)