#!bin/python
#coding=utf-8
"""
Create by he
"""

import sys
import re
import string
import operator
from base import *
from globalEnv import *

#policy--match
policyPattern = re.compile(r'object-policy ip (?P<name>\S+)')
#rule
rulePattern = re.compile(r'rule (?P<id>\d+) (?P<action>drop|pass|inspect).*')
#rule-source-ip--search
sourceIpPattern = re.compile(r'source-ip (?P<sourceIp>\S+)')
#rule--destination-ip--search
destinationIpPattern = re.compile(r'destination-ip (?P<destinationIp>\S+)')
#rule--service--search
servicePattern = re.compile(r'service (?P<service>\S+)')
#rule--vrf--search
vrfPattern = re.compile(r'vrf (?P<vrf>\S+)')
#rule--timeRange--search
timeRangePattern = re.compile(r'time-range (?P<timeRange>\S+)')
#rule--can't Merge---disable track negative
disablePattern = re.compile(r'disable')
trackPattern = re.compile(r'track')
negativePattern = re.compile(r'negative')

#AddressObjectGroup--match
addObjGroupPattern = re.compile(r'object-group ip address (?P<name>\S+)')
#AddressObject
addObjHostIpPattern = re.compile(r'(?P<id>\d+) network host address (?P<ip>\S+)')
addObjHostNamePattern = re.compile(r'(?P<id>\d+) network host name (?P<name>\S+)')
addObjSubnetPattern = re.compile(r'(?P<id>\d+) network subnet (?P<ip>\S+) (?P<mask>\S+)')
addObjRangePattern = re.compile(r'(?P<id>\d+) network range (?P<ipStart>\S+) (?P<ipEnd>\S+)')
addObjGroPattern = re.compile(r'(?P<id>\d+) network group-object (?P<groupName>\S+)')

#ServiceObjectGroup--match
serObjGroupPattern = re.compile(r'object-group service (?P<name>\S+)')

#ServiceObject
serObjProtocolPattern = re.compile(r'(?P<id>\d+) service (?P<protocol>\S+) .*')
serObjGroPattern = re.compile(r'(?P<id>\d+) service group-object (?P<groupName>\S+)')



def splitFile(fileStr):
    if(fileStr==''):
        return
    lines.extend(fileStr.split('\n'))
    #return lines


def analyze():
    lineNum = 0
    while lineNum < len(lines):
        #print lineNum
        policy = isPolicy(lines[lineNum])
        if policy:
            n = getRules(lineNum+1,lines,policy)
            print n
            policyList.append(policy)
            lineNum = n
            continue
        addObjGroup = isAddObjGroup(lines[lineNum])
        if addObjGroup:
            print 'bbbbbbbbbbbbbbbbbbbbbbbb'
            print addObjGroup.addressObjects
            print 'bbbbbbbbbbbbbbbbbbbbbbbb'
            n = getAddObjs(lineNum+1,lines,addObjGroup)
            print n
            addObjGroupList.append(addObjGroup)
            lineNum = n
            continue
        serObjGroup = isSerObjGroup(lines[lineNum])
        if serObjGroup:
            n,serObjs = getSerObjs(lineNum+1,lines,serObjGroup)
            print n
            serObjGroupList.append(serObjGroup)
            lineNum = n
            continue
        lineNum = lineNum+1

def classify(policy,rule):
    join = rule.action+"^"+rule.vrf+"^"+rule.timeRange+"^"+rule.service
    condition = getCondition(rule)
    join = join+"^"+condition
    if policy.canMerge.has_key(join):
        policy.canMerge[join].append(rule)
    else:
        policy.canMerge[join] = [rule]

def getCondition(rule):
    ser = rule.service == "" or rule.service == "any"
    sIp = rule.sourceIp == "" or rule.sourceIp == "any"
    dIp = rule.destinationIp == "" or rule.destinationIp == "any"
    if (not sIp) and dIp and ser:
        return Conditions.ONE
    if (not dIp) and sIp and ser:
        return Conditions.TWO
    if (not sIp) and (not ser) and dIp:
        return Conditions.FOUR
    if (not dIp) and (not ser) and sIp:
        return Conditions.FIVE
    if (not sIp) and (not dIp) and (not ser):
        return Conditions.SEVEN
    

def isAddObjGroup(checked):
    group = None
    match = addObjGroupPattern.match(checked)
    if match:
        name = match.group('name')
        content = match.group()
        # ???   param : addressObjects=[]
        group = AddressObjectGroup(name,content,addressObjects=[])
        print 'wwwwwwwwwwwwwwwwwwwwwwwwww'
        print group.addressObjects
        print 'wwwwwwwwwwwwwwwwwwwwwwwwww'
        return group
    return group

def getAddObjs(start,lines,addObjGroup):
    print "start"+str(start)
    #print 'wwwwwwwwwwwwwwwwwwwwwwwwww'
    #print addObjGroup.addressObjects
    #print 'wwwwwwwwwwwwwwwwwwwwwwwwww'
    for lineNum in range(start,len(lines)):
        addObj = isAddObj(lines[lineNum])
        if addObj:
            addObjGroup.addressObjects.append(addObj)
            continue
        #print 'wwwwwwwwwwwwwwwwwwwwwwwwww'
        #print addObjGroup
        #print 'wwwwwwwwwwwwwwwwwwwwwwwwww'
        return lineNum

def isAddObj(checked):
    addObj= None
    addObjHostIpMatch = addObjHostIpPattern.search(checked)
    addObjHostNameMatch = addObjHostNamePattern.search(checked)
    addObjSubnetMatch = addObjSubnetPattern.search(checked)
    addObjRangeMatch = addObjRangePattern.search(checked)
    addObjGroMatch = addObjGroPattern.search(checked)
    if addObjHostIpMatch:
        addId = addObjHostIpMatch.group('id')
        ip = addObjHostIpMatch.group('ip')
        content = addObjHostIpMatch.group()
        mask = "255.255.255.255"        
        addObj = AddressObject(addId,content,AddressTypes.HOST,ip=ip,mask=mask)
    elif addObjHostNameMatch:
        addId = addObjHostMatch.group('id')
        ip = addObjHostMatch.group('name')
        content = addObjHostMatch.group()
        mask = "255.255.255.255"        
        addObj = AddressObject(addId,content,AddressTypes.HOST,hostName=name,ip=ip)
    elif addObjSubnetMatch:
        addId = addObjSubnetMatch.group('id')
        ip = addObjSubnetMatch.group('ip')
        mask = addObjSubnetMatch.group('mask')
        content = addObjSubnetMatch.group()
        addObj = AddressObject(addId,content,AddressTypes.SUBNET,ip=ip,mask=mask)
    elif addObjGroMatch:
        addId = addObjGroMatch.group('id')
        groupName = addObjGroMatch.group('groupName')
        content = addObjGroMatch.group()
        addObj = AddressObject(addId,content,AddressTypes.GROUP,groupName=groupName)
    elif addObjRangeMatch:
        addId = addObjRangeMatch.group('id')
        startIp = addObjRangeMatch.group('ipStart')
        endIp = addObjRangeMatch.group('ipEnd')
        addObj = AddressObject(addId,content,AddressTypes.RANGE,ipStart=startIp,ipEnd=endIp)
    print 'hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh'
    print addObj
    print 'hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh'
    return addObj
    
def isPolicy(checked):
    match = policyPattern.match(checked)
    if match:
        name = match.group('name')
        content = match.group()
        policy = Policy(name,content,rules=[])
        return policy
    return None


def getRules(start,lines,policy):
    for lineNum in range(start,len(lines)):
        rule = isRule(lines[lineNum])
        if rule:
            policy.rules.append(rule)
            if canNotMerge(rule):
                policy.canNotMerge.append(rule)
                continue
            classify(policy,rule)
            continue
        return lineNum
    
def isRule(checked):
    rule = None
    match = rulePattern.match(checked)
    if match:
        ruleId = match.group('id')
        action = match.group('action')
        vrf = getVRF(checked)
        timeRange = getTimeRange(checked)
        sourceIp = getSourceIp(checked)
        destinationIp = getDestinationIp(checked)
        service = getService(checked)
        content = match.group()
        rule = Rule(ruleId,action,vrf,timeRange,sourceIp,destinationIp,service,content)
    return rule

def canNotMerge(rule):
    #action:inspect
    if rule.action == "inspect":
        return True
    #with disable,track and negative
    if otherReason(rule):
        return True
    ser = rule.service == "" or rule.service == "any"
    sIp = rule.sourceIp == "" or rule.sourceIp == "any"
    dIp = rule.destinationIp == "" or rule.destinationIp == "any"
    #condition3
    if not ser and sIp and dIp:
        return True
    #condition6
    if not sIp and not dIp and ser:
        return True
    #sip dip ser was not configed
    if ser and sIp and dIp:
        return True

def getSourceIp(rule):
    match = sourceIpPattern.search(rule)
    if match:
        return match.group('sourceIp')
    return ''

def getDestinationIp(rule):
    match = destinationIpPattern.search(rule)
    if match:
        return match.group('destinationIp')
    return ''

def getService(rule):
    match = servicePattern.search(rule)
    if match:
        return match.group('service')
    return ''
   
def getVRF(rule):
    #print rule
    match = vrfPattern.search(rule)
    if match:
        return match.group('vrf')
    return ''

def getTimeRange(rule):
    match = timeRangePattern.search(rule)
    if match:
        return match.group('timeRange')
    return ''

def otherReason(rule):
    match1 = disablePattern.search(rule.content)
    match2 = trackPattern.search(rule.content)
    match3 = negativePattern.search(rule.content)
    if match1 or match2 or match3:
        return True
    return False

def isSerObjGroup(checked):
    match = serObjGroupPattern.match(checked)
    if match:
        name = match.group(name)
        content = match.group()        
        serObjGroup = ServiceObjectGroup(name,content)
        return serObjGroup
    return None

def isSerObj(checked):
    serObj= None
    serObjProtocolMatch = serObjProtocolPattern.match(checked)
    serObjGroMatch = serObjGroPattern.match(checked)
    if serObjProtocolMatch:
        serId = serObjProtocolMatch.group('id')
        protocol = serObjProtocolMatch.group('protocol')
        #type meitian
        serObj = ServiceObject(serId,protocol,"",content)
    elif serObjGroMatch:
        serId = serObjGroMatch.group('id')
        groupName = serObjGroMatch.group('groupName')
        serObj = serObjGroMatch(serId,"",groupName,content)
    return serObj

def getSerObjs(start,lines,serObjGroup):
    serObjs = []
    for lineNum in range(start,len(lines)):
        serObj = isSerObj(lines[lineNum])
        if serObj:
            serObjGroup.serviceObjects.append(addObj)
            continue
        return lineNum,serObjs

def initial():
    for policy in policyList:
        for rule in policy.rules:
            rule.getSipAddObjGroup(addObjGroupList)
            rule.getDipAddObjGroup(addObjGroupList)
            rule.getSerobjGroup(serObjGroupList)
        for key,value in policy.canMerge.items():
            if len(value) ==1:
                policy.canNotMerge.extend(value)
                del policy.canMerge[key]

    
t='''object-policy ip Trust-Untrust
rule 18 pass source-ip g_yidongzhifu
rule 35 pass source-ip gprs_traffic
rule 38 pass source-ip hb_smp
rule 19 pass destination-ip g_yidongzhifu
rule 36 pass destination-ip gprs_traffic
rule 39 pass destination-ip hb_smp

object-group ip address g_yidongzhifu
0 network group-object yidongzhifu_pt_server2   
10 network group-object yidongzhifu_pt_server1
20 network group-object yidongzhifu_pt_server3
30 network group-object yidongzhifu_pt_server4
40 network group-object yidongzhifu_pt_server6
        //地址对象内可能嵌套其它地址对象(如上蓝色),被嵌套使用的对象不能被删除

object-group ip address gprs_traffic
0 network host address 10.70.112.87
        
object-group ip address hb_smp
0 network host address 10.71.84.250


object-policy ip Trust-Untrust-s
rule 794 pass source-ip imep-10.70.85.64/27 service ftp
rule 2869 pass source-ip 无线网优10.212.42.115/32 service ftp
rule 2874 pass source-ip 无线网优10.70.72.246/32 service ftp

object-group ip address imep-10.70.85.64/27
 description "滨江5F imep系统"                             
 0 network subnet 10.70.85.64 255.255.255.224

object-group ip address 无线网优10.212.42.115/32
 0 network host address 10.212.42.115

object-group ip address 无线网优10.70.72.246/32
 0 network host address 10.70.72.246

object-policy ip Trust-Untrust-d
rule 795 pass destination-ip imep-10.70.85.64/27 service ftp
rule 2849 pass destination-ip 无线网优10.212.42.115/32 service ftp
rule 2884 pass destination-ip 无线网优10.70.72.246/32 service ftp

object-group ip address imep-10.70.85.64/27
 description "滨江5F imep系统"                             
 0 network subnet 10.70.85.64 255.255.255.224

object-group ip address 无线网优10.212.42.115/32
 0 network host address 10.212.42.115

object-group ip address 无线网优10.70.72.246/32
 0 network host address 10.70.72.246

'''

splitFile(t)
analyze()
initial()
for p in policyList:
    print '==================policy====================='
    print '-------------rules-------------'
    print p.rules
    print '-------------canMerge-------------'
    print p.canMerge
    print '-------------canNotMerge-------------'
    print p.canNotMerge

for group in addObjGroupList:
    print '==================group====================='
    print group
    print '-------------AddressObj-------------'
    print group.addressObjects


#print lines
print '======================================='
#print policyList[0].rules[0].action
#print addObjGroupList[1].addressObjects[0].content
print policyList
print addObjGroupList[1].addressObjects
print serObjGroupList
print'000000000000000000'
print addObjGroupList
print serObjGroupList
print policyList[0].rules[0].sourceIp
print policyList[0].rules[0].getSipAddObjGroup(addObjGroupList).addressObjects[0].ip
print policyList[0].rules[0].getSipAddObjGroup(addObjGroupList).addressObjects
print policyList[0].canMerge
print policyList[0].canNotMerge

 

posted on 2016-12-09 19:35  Mr.He多多指教  阅读(374)  评论(0编辑  收藏  举报