Exemplo n.º 1
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)
Exemplo n.º 2
0
  def _TranslatePolicy(self, pol, exp_info):
    self.pf_policies = []
    self.address_book = {}
    self.def_short_to_long = {}
    current_date = datetime.datetime.utcnow().date()
    exp_info_date = current_date + datetime.timedelta(weeks=exp_info)

    good_afs = ['inet', 'inet6', 'mixed']
    good_options = ['in', 'out', 'nostate']
    all_protocols_stateful = True

    for header, terms in pol.filters:
      filter_type = None
      if self._PLATFORM not in header.platforms:
        continue

      filter_options = header.FilterOptions(self._PLATFORM)[1:]
      filter_name = header.FilterName(self._PLATFORM)
      direction = ''

      # ensure all options after the filter name are expected
      for opt in filter_options:
        if opt not in good_afs + good_options:
          raise aclgenerator.UnsupportedTargetOptionError('%s %s %s %s' % (
              '\nUnsupported option found in', self._PLATFORM,
              'target definition:', opt))

      # pf will automatically add 'keep state flags S/SA' to all TCP connections
      # by default.
      if 'nostate' in filter_options:
        all_protocols_stateful = False

      if 'in' in filter_options:
        direction = 'in'
      elif 'out' in filter_options:
        direction = 'out'

      # Check for matching af
      for address_family in good_afs:
        if address_family in filter_options:
          # should not specify more than one AF in options
          if filter_type is not None:
            raise aclgenerator.UnsupportedFilterError('%s %s %s %s' % (
                '\nMay only specify one of', good_afs, 'in filter options:',
                filter_options))
          filter_type = address_family
      if filter_type is None:
        filter_type = 'inet'

      # add the terms
      new_terms = []
      term_names = set()

      for term in terms:
        term.name = self.FixTermLength(term.name)
        if term.name in term_names:
          raise DuplicateTermError(
              'You have a duplicate term: %s' % term.name)
        term_names.add(term.name)

        for source_addr in term.source_address:
          src_token = source_addr.parent_token[:self._DEF_MAX_LENGTH]

          if (src_token in self.def_short_to_long and
              self.def_short_to_long[src_token] != source_addr.parent_token):
            raise DuplicateShortenedTableName(
                'There is a shortened name conflict between names %s and %s '
                '(different named objects would conflict when shortened to %s)'
                % (self.def_short_to_long[src_token],
                   source_addr.parent_token,
                   src_token))
          else:
            self.def_short_to_long[src_token] = source_addr.parent_token

          if src_token not in self.address_book:
            self.address_book[src_token] = set([source_addr])
          else:
            self.address_book[src_token].add(source_addr)

        for dest_addr in term.destination_address:
          dst_token = dest_addr.parent_token[:self._DEF_MAX_LENGTH]

          if (dst_token in self.def_short_to_long and
              self.def_short_to_long[dst_token] != dest_addr.parent_token):
            raise DuplicateShortenedTableName(
                'There is a shortened name conflict between names %s and %s '
                '(different named objects would conflict when shortened to %s)'
                %(self.def_short_to_long[dst_token],
                  dest_addr.parent_token,
                  dst_token))
          else:
            self.def_short_to_long[dst_token] = dest_addr.parent_token

          if dst_token not in self.address_book:
            self.address_book[dst_token] = set([dest_addr])
          else:
            self.address_book[dst_token].add(dest_addr)

        if not term:
          continue

        if term.expiration:
          if term.expiration <= exp_info_date:
            logging.info('INFO: Term %s in policy %s expires '
                         'in less than two weeks.', term.name, filter_name)
          if term.expiration <= current_date:
            logging.warning('WARNING: Term %s in policy %s is expired and '
                            'will not be rendered.', term.name, filter_name)
            continue

        new_terms.append(self._TERM(term, filter_name, all_protocols_stateful,
                                    filter_type, direction))

      self.pf_policies.append((header, filter_name, filter_type, new_terms))
Exemplo n.º 3
0
    def _TranslatePolicy(self, pol, exp_info):
        """Translate a policy from objects into strings."""
        self.windows_policies = []
        current_date = datetime.datetime.utcnow().date()
        exp_info_date = current_date + datetime.timedelta(weeks=exp_info)

        default_action = None
        good_default_actions = ['permit', 'block']
        good_options = []

        for header, terms in pol.filters:
            filter_type = None
            if self._PLATFORM not in header.platforms:
                continue

            filter_options = header.FilterOptions(self._PLATFORM)[1:]
            filter_name = header.FilterName(self._PLATFORM)

            # ensure all options after the filter name are expected
            for opt in filter_options:
                if opt not in good_default_actions + self._GOOD_AFS + good_options:
                    raise aclgenerator.UnsupportedTargetOptionError(
                        '%s %s %s %s' %
                        ('\nUnsupported option found in', self._PLATFORM,
                         'target definition:', opt))

            # Check for matching af
            for address_family in self._GOOD_AFS:
                if address_family in filter_options:
                    # should not specify more than one AF in options
                    if filter_type is not None:
                        raise aclgenerator.UnsupportedFilterError(
                            '%s %s %s %s' %
                            ('\nMay only specify one of', self._GOOD_AFS,
                             'in filter options:', filter_options))
                    filter_type = address_family
            if filter_type is None:
                filter_type = 'inet'

            # does this policy override the default filter actions?
            for next_target in header.target:
                if next_target.platform == self._PLATFORM:
                    if len(next_target.options) > 1:
                        for arg in next_target.options:
                            if arg in good_default_actions:
                                default_action = arg
            if default_action and default_action not in good_default_actions:
                raise aclgenerator.UnsupportedTargetOptionError(
                    '%s %s %s %s %s' %
                    ('\nOnly', ', '.join(good_default_actions),
                     'default filter action allowed;', default_action,
                     'used.'))

            # add the terms
            new_terms = []
            term_names = set()
            for term in terms:
                if term.name in term_names:
                    raise aclgenerator.DuplicateTermError(
                        'You have a duplicate term: %s' % term.name)
                term_names.add(term.name)

                if term.expiration:
                    if term.expiration <= exp_info_date:
                        logging.info(
                            'INFO: Term %s in policy %s expires '
                            'in less than two weeks.', term.name, filter_name)
                    if term.expiration <= current_date:
                        logging.warning(
                            'WARNING: Term %s in policy %s is expired and '
                            'will not be rendered.', term.name, filter_name)
                        continue
                if 'established' in term.option or 'tcp-established' in term.option:
                    continue
                new_terms.append(
                    self._TERM(term, filter_name, default_action, filter_type))

            self.windows_policies.append(
                (header, filter_name, filter_type, default_action, new_terms))