Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def grammar():
# terminals ----------------------------------
colon = Literal(":")
equal = Suppress("=")
slash = Suppress("/")
open_paren = Suppress("(")
close_paren = Suppress(")")
open_brace = Suppress("{")
close_brace = Suppress("}")
# np:tagName ---------------------------------
nspfx = Word(alphas)
local_name = Word(alphanums)
tagname = Combine(nspfx + colon + local_name)
# np:attr_name=attr_val ----------------------
attr_name = Word(alphas + ":")
attr_val = Word(alphanums + " %-./:_")
attr_def = Group(attr_name + equal + attr_val)
attr_list = open_brace + delimitedList(attr_def) + close_brace
text = dblQuotedString.setParseAction(removeQuotes)
float_number = pp.Regex(r'(\-)?(\d+)?(\.)(\d*)?([eE][\-\+]\d+)?')
skipLine = pp.Suppress(skipSupress('\n'))
comment = pp.Suppress(pp.Literal(';')) + skipLine
optional_comment = pp.ZeroOrMore(comment)
word = pp.Word(pp.alphanums + "*")
line = pp.Group(
pp.OneOrMore(float_number | word) + pp.Optional(comment))
lines = pp.Group(pp.OneOrMore(line))
brackets = pp.Suppress("[") + word + pp.Suppress("]")
# High level parsers
section = brackets + optional_comment + lines
many_sections = pp.Group(pp.OneOrMore(section))
# Parser for itp files
itp_parser = optional_comment + many_sections
# Parser for the atom section of mol2 files
header_mol2 = skipSupress(pp.Literal("@ATOM")) + skipLine
parser_atoms_mol2 = header_mol2 + pp.Group(pp.OneOrMore(line + skipLine))
ML_COMMENT = cStyleComment
WS = OneOrMore(Suppress(' ') | Suppress('\t') | (Optional(Suppress('\r')) + Literal('\n')))
WS_LOOP = ZeroOrMore(SL_COMMENT | ML_COMMENT)
NESTED_ARG_ACTION = Forward()
NESTED_ARG_ACTION << Suppress('[') + ZeroOrMore(NESTED_ARG_ACTION | ACTION_STRING_LITERAL | ACTION_CHAR_LITERAL) + Suppress(']')
ARG_ACTION = NESTED_ARG_ACTION
NESTED_ACTION = Forward()
NESTED_ACTION << Suppress('{') + ZeroOrMore(NESTED_ACTION | SL_COMMENT | ML_COMMENT | ACTION_STRING_LITERAL | ACTION_CHAR_LITERAL) + Suppress('}')
ACTION = NESTED_ACTION + Optional('?')
SCOPE = Suppress('scope')
OPTIONS = Suppress('options') + Suppress('{') # + WS_LOOP + Suppress('{')
TOKENS = Suppress('tokens') + Suppress('{') # + WS_LOOP + Suppress('{')
FRAGMENT = 'fragment';
TREE_BEGIN = Suppress('^(')
ROOT = Suppress('^')
BANG = Suppress('!')
RANGE = Suppress('..')
REWRITE = Suppress('->')
# General Parser Definitions
# Grammar heading
optionValue = id | STRING_LITERAL | CHAR_LITERAL | INT | Literal('*').setName("s")
option = Group(id("id") + Suppress('=') + optionValue("value"))("option")
optionsSpec = OPTIONS + Group(OneOrMore(option + Suppress(';')))("options") + Suppress('}')
tokenSpec = Group(TOKEN_REF("token_ref") + (Suppress('=') + (STRING_LITERAL | CHAR_LITERAL)("lit")))("token") + Suppress(';')
tokensSpec = TOKENS + Group(OneOrMore(tokenSpec))("tokens") + Suppress('}')
attrScope = Suppress('scope') + id + ACTION
grammarType = Keyword('lexer') + Keyword('parser') + Keyword('tree')
actionScopeName = id | Keyword('lexer')("l") | Keyword('parser')("p")
action = Suppress('@') + Optional(actionScopeName + Suppress('::')) + id + ACTION
# ***AP*** Seq: 0xD34C30CE Ack: 0x6B1F7D18 Win: 0x2000 TcpLen: 32
#
# Note: This format is known to change over versions.
# Works with Snort version 2.9.2 IPv6 GRE (Build 78)
header = (
pyp.Suppress("[**] [")
+ pyp.Combine(integer + ":" + integer + ":" + integer)
+ pyp.Suppress("]")
)
signature = (
pyp.Combine(pyp.SkipTo("[**]", include=False))
)
classif = (
pyp.Suppress("[**]")
+ pyp.Suppress(pyp.Optional(pyp.Literal("[Classification:")))
+ pyp.Regex("[^]]*") + pyp.Suppress(']')
)
pri = pyp.Suppress("[Priority:") + integer + pyp.Suppress("]")
date = pyp.Combine(
integer + "/" + integer + '-' + integer + ':' + integer + ':' + integer + '.' + integer
)
src_ip = ip_addr + pyp.Suppress(port + "->")
dest_ip = ip_addr
dest_port = port
bnf = header + signature + classif + pri + date + src_ip + dest_ip + dest_port
alerts = []
with open(logfile) as snort_logfile:
for has_content, grp in groupby(
snort_logfile, key = lambda x: bool(x.strip())):
if has_content:
ConditionalAndExpression)).setParseAction(
refer_component(components.ParsedConditionalAndExpressionList))
if DEBUG:
ConditionalOrExpression.setName('ConditionalOrExpression')
Expression << ConditionalOrExpression
# Constraint (used only in Filter):
Constraint = ((BrackettedExpression.copy()).setParseAction(
refer_component(components.ParsedExpressionFilter)) |
(BuiltInCall | FunctionCall).setParseAction(
refer_component(components.ParsedFunctionFilter)))
if DEBUG:
Constraint.setName('Constraint')
# Filter:
FILTER = Suppress(CaselessKeyword('FILTER'))
Filter = (FILTER + Constraint).setName('Filter')
# GraphNode is recursively defined in terms of Collection, ObjectList,
# PropertyListNotEmpty, and TriplesNode.
GraphNode = Forward()
if DEBUG:
GraphNode.setName('GraphNode')
# Collection:
Collection = (LP + Group(OneOrMore(GraphNode)) + RP).setParseAction(
refer_component(components.ParsedCollection))
if DEBUG:
Collection.setName('Collection')
# ObjectList:
from json import load
import util
import parsing_checks
from parsing_checks import *
iface_local = {}
parse_iface = Suppress('interface ') + restOfLine
iface_global = {}
parse_active_service = Suppress('service ') + restOfLine
parse_disable_service = Suppress('no service ') + restOfLine
parse_version = Suppress('version ') + restOfLine
parse_model = Suppress('boot system flash bootflash:') + restOfLine
parse_ipv6 = Suppress('ipv6 ') + restOfLine
parse_ipv6_sourceguard = Suppress('source-guard ') + restOfLine
parse_ipv6_snooping = Suppress('snooping ') + restOfLine
parse_ipv6_raguard = Suppress('nd raguard ') + restOfLine
parse_ipv6_destinationguard = Suppress('destination-guard ') + restOfLine
parse_ipv6_dhcpguard = Suppress('dhcp guard ') + restOfLine
parse_lldp = Suppress('lldp ') + restOfLine
parse_username = Suppress('username ') + restOfLine
parse_aaa = Suppress('aaa ') + restOfLine
parse_stp = Suppress('spanning-tree ') + restOfLine
# parse_vtp = Suppress('vtp ') + restOfLine
parse_line = Suppress('line ') + restOfLine
parse_ip_ssh = Suppress('ip ssh ') + restOfLine
parse_arp_proxy = Suppress('ip arp proxy ') + restOfLine
parse_vstack = Suppress('no') + 'vstack'
parse_enable_password = Suppress('enable') + MatchFirst(['secret', 'password']) + Optional(Word(nums) + Suppress(White(exact=1))) + Suppress(restOfLine)
def parseATL(spec):
"""Parse the spec and return the list of possible ASTs."""
global __atl
if __atl is None:
true = Literal("True")
true.setParseAction(lambda tokens: TrueExp())
false = Literal("False")
false.setParseAction(lambda tokens: FalseExp())
atom = "'" + SkipTo("'") + "'"
atom.setParseAction(lambda tokens: Atom(tokens[1]))
agent = atom
group = Group(ZeroOrMore(agent + Suppress(",")) + agent)
proposition = true | false | atom
__atl = Forward()
notproposition = "~" + proposition
notproposition.setParseAction(lambda tokens: Not(tokens[1]))
formula = (proposition | notproposition |
Suppress("(") + __atl + Suppress(")"))
logical = Forward()
cax = Literal("[") + group + "]" + "X" + logical
cax.setParseAction(lambda tokens: CAX(tokens[1], tokens[4]))
cex = Literal("<") + group + ">" + "X" + logical
### B.2.4 Component Clause
### B.2.5 Modification
### B.2.6 Equations
ForIndices.ebnf(
syntax = delimitedList(ForIndex.names('indices'), delim=','),
)
ForIndex.ebnf(
syntax = IDENT.name("identifier") + Optional(Suppress('in') + Expression.name('expression')),
)
### B.2.7 Expressions
Name.ebnf(
syntax = delimitedList(IDENT.names('names'), delim='.')
)
ComponentReference.ebnf(
syntax = delimitedList(IDENT.names('names') + Optional(ArraySubscripts.names('subscripts')), delim='.')
)
FunctionCallArgs.ebnf(
syntax = Suppress('(') + Optional(FunctionArguments.name('arguments')) + Suppress(')')
)
assigned_identifier = Suppress(Optional(object_identifier_value
| (defined_value + ~(comma | FROM))))
global_module_reference = (module_reference + assigned_identifier)
reference <<= (type_reference
| value_reference
| object_class_reference
| object_reference
| object_set_reference)
symbol = (parameterized_reference
| reference)
symbol_list = Group(delimitedList(symbol))
symbols_from_module = (symbol_list
+ FROM
+ global_module_reference)
symbols_imported = ZeroOrMore(Group(symbols_from_module))
imports = Optional(Suppress(IMPORTS)
- symbols_imported
- Suppress(semi_colon))
symbols_exported = OneOrMore(symbol_list)
exports = Suppress(Optional(EXPORTS
- (ALL | symbols_exported) + semi_colon))
assignment = (parameterized_object_set_assignment
| parameterized_object_assignment
| parameterized_object_class_assignment
| parameterized_type_assignment
| parameterized_value_assignment)
assignment_list = ZeroOrMore(assignment)
module_body = (exports + imports + assignment_list)
definitive_name_and_number_form = (identifier
+ Suppress(left_parenthesis)
- definitive_number_form
- Suppress(right_parenthesis))
function_call = originalTextFor(ZeroOrMore(ident + ".") + ident + nestedExpr('(', ')'))
python_allowed_expr << (ident ^ dict_def ^ list_def ^ dict_access ^ list_access ^ function_call ^ restOfLine)\
.setResultsName("value", listAllMatches=True)
persistent_identifier = (Suppress("@persistent_identifier") + nestedExpr("(", ")"))\
.setResultsName("persistent_identifier")
legacy = (Suppress("@legacy") + originalTextFor(nestedExpr("(", ")")))\
.setResultsName("legacy", listAllMatches=True)
only_if = (Suppress("@only_if") + originalTextFor(nestedExpr("(", ")")))\
.setResultsName("only_if")
only_if_master_value = (Suppress("@only_if_value") + originalTextFor(nestedExpr("(", ")")))\
.setResultsName("only_if_master_value")
depends_on = (Suppress("@depends_on") + originalTextFor(nestedExpr("(", ")")))\
.setResultsName("depends_on")
parse_first = (Suppress("@parse_first") + originalTextFor(nestedExpr("(", ")")))\
.setResultsName("parse_first")
do_not_cache = (Suppress("@") + "do_not_cache")\
.setResultsName("do_not_cache")
field_decorator = parse_first ^ depends_on ^ only_if ^ only_if_master_value ^ do_not_cache ^ legacy
#Independent decorators
inherit_from = (Suppress("@inherit_from") + originalTextFor(nestedExpr("(", ")")))\
.setResultsName("inherit_from")
override = (Suppress("@") + "override")\
.setResultsName("override")
extend = (Suppress("@") + "extend")\
.setResultsName("extend")
master_format = (Suppress("@master_format") + originalTextFor(nestedExpr("(", ")")))\
.setResultsName("master_format")