Exemple #1
0
 def _RepositoryTagsHelper(self, target=None, filter_type='', filter_name=''):
   if target is None:
     target = []
   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))
   return target
Exemple #2
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 self.verbose:
                    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 aclgenerator.WrapWords(
                            header.comment, _COMMENT_MAX_WIDTH):
                        for line in comment.split('\n'):
                            if (self._PLATFORM == 'cisco'
                                    and filter_type == 'standard'
                                    and filter_name.isdigit()):
                                target.append('access-list %s remark %s' %
                                              (filter_name, line))
                            else:
                                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)
Exemple #3
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):
            v4 = sorted([x for x in self.address_book[name] if x.version == 4])
            v6 = sorted([x for x in self.address_book[name] if x.version == 6])
            entries = ',\\\n'.join(str(x) for x in v4 + v6)
            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)
Exemple #4
0
    def __str__(self):
        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)
Exemple #5
0
 def _RepositoryTagsHelper(self,
                           target=None,
                           filter_type='',
                           filter_name=''):
     if target is None:
         target = []
     target.extend(
         aclgenerator.AddRepositoryTags(' remark ', rid=False, wrap=True))
     return target
Exemple #6
0
    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))
Exemple #7
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:
            if self._NOVERBOSE not in filter_options[4:]:
                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)
Exemple #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)
Exemple #9
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 = six.ensure_str(
                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.warning(
                    '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))
        # TODO(robankeny) utf encoding with refactoring after migration to py3
        return target_as_xml.toprettyxml(indent='  ')
Exemple #10
0
  def __str__(self):
    config = Config()

    for (header, filter_name,
         filter_type, interface_specific,
         repository_revision,
         repository_date, repository_rid,
         terms) in self.juniper_policies:
      # add the header information
      config.Append('firewall {')
      config.Append('family %s {' % filter_type)
      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('** ', rid=repository_rid, date=repository_date, revision=repository_revision):
        config.Append(line)
      config.Append('**')

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

      config.Append('replace: 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'
Exemple #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)
Exemple #12
0
  def __str__(self):
    target = juniper.Config()
    for (header, filter_name, filter_direction,
         terms) in self.junipermsmpc_policies:
      target.Append('groups {')
      target.Append('replace:')
      target.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('** '):
        target.Append(line)
      target.Append('**')

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

      target.Append('%s {' % filter_name)
      target.Append('services {')
      target.Append('stateful-firewall {')
      target.Append('rule %s {' % filter_name)
      target.Append('match-direction %s;' % filter_direction)
      for term in terms:
        term_str = str(term)
        if term_str:
          target.Append(term_str, verbatim=True)
      target.Append('}')  # rule { ... }
      target.Append('}')  # stateful-firewall { ... }
      target.Append('}')  # services { ... }
      for line in self._GenerateApplications(filter_name):
        target.Append(line)
      target.Append('}')  # filter_name { ... }
      target.Append('}')  # groups { ... }
      target.Append('apply-groups %s;' % filter_name)
    return str(target) + '\n'
Exemple #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_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:
                raise aclgenerator.UnsupportedTargetOptionError(
                    'Windows generator does not support default actions')

            # 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)