0% found this document useful (0 votes)
8 views

Break Fx Nat Kavya.py

Uploaded by

gokul nath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Break Fx Nat Kavya.py

Uploaded by

gokul nath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 76

import ast

from pprint import pformat


import yaml
from pyats import aetest
from pyats.aetest.steps import Steps
import lib.commons.commons as ftltest
from pyats.log.utils import banner
from lib.services.data.store import store
from lib.constants import TestBedConstants
from lib.models.devices.device_management.high_availability.constants import
HATaskStatus,UpdateHAActions
from lib.models.devices.device_management.high_availability.model import
HighAvailability
from lib.models.devices.device_management.device.static_route.model import
StaticRoute
from lib.models.health.health_alerts.model import *
from lib.services.users.fmc_users import *
from lib.services.api_service import APIService
from lib.models.deploy.configrollback.model import RollbackRequest
from tests.feature.ftd.tests.ftd_policy_integration.utility import createHaSetup
from lib.models.messaging.tasks.model import *
from lib.models.devices.device_management.device.out_of_band.model import *
# from lib.models.devices.device_management.device.out_of_band.model import *
from lib.models.workflow.systemconfiguration.model import *
from lib.models.workflow.tickets.model import *
from
lib.ui.fmc.webui.devices.device_management.page.routing.OSPF.interface.interface
import *
from
lib.ui.fmc.webui.devices.device_management.page.routing.OSPFv3.interface.interface
import *
from tests.feature.ftd.tests.BGPV4_RouteLeaking_VRF.routemap_prefixlist_ui import *
from tests.feature.ftd.tests.BGPV4_RouteLeaking_VRF.utility import *
from tests.feature.ftd.tests.vti_integration_scripts.route_map_ui import *
# from tests.feature.ftd.tests.ftd_policy_integration.utility import *
from tests.feature.ftd.utils.cluster_utils import ClusterUtility
from tests.system.testcases.test_utils.router_config import *
from lib.services.config_provider import ConfigProvider
from tests.feature.ftd.tests.ftd_policy_integration.static_configs import cfg
from lib.models.devices.device_management.device.model import Device
from lib.models.alerts.status.model import StatusModel
from lib.ui.fmc.webui.devices.device_management.actions.devices_management_page
import *
from pyats.log import ScreenHandler, TaskLogHandler
from
lib.models.policies.access_control.default_action.access_policy_default_action.mode
l import \
AccessPolicyDefaultAction
from tests.feature.ftd.tests.Breakfix.breakfix_utils import BreakfixUtils
from lib.models.devices.device_management.device.out_of_band.model import OutOfBand
from lib.models.messaging.tasks.model import TaskMessage
from
lib.models.devices.device_management.device.interfaces.physical_interface.model
import PhysicalInterface
from lib.features_constants import Features77
from lib.utils.functions import set_testcase_feature, set_tims_testcase
from lib.models.devices.device_management.wa_cluster.model import WaCluster
from tests.feature.ftd.tests.breakfix_nat_2.breakfix_nat_utils import
BreakfixNatUtils
from lib.models.objects.network.network_object.model import NetworkObject
from lib.models.objects.network.network_group.model import NetworkGroup
from lib.models.objects.port.port_object.model import ProtocolPortObject
from lib.models.objects.interface.security_zone.model import SecurityZoneObject
from lib.models.policies.access_control.access_control.access_policy.model import
AccessPolicy
from lib.models.devices.ftdnat.model import FtdNatPolicy
from
lib.models.policies.access_control.access_control.access_policy.policy_assignment.m
odel import PolicyAssignment
from lib.models.devices.ftdnat.nat_rules.manual_nat_rules.model import
ManualNatRule
from lib.models.devices.ftdnat.nat_rules.auto_nat_rules.model import AutoNatRule
from lib.models.fragments.device.ftdnat.pat.model import FtdPatFragment
from lib.services.communicator.rest.urls import RestApiURL
from lib.services.communicator.rest.urls import API_PREFIX

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# creating a handler
screen_handler = ScreenHandler()
tasklog_handler = TaskLogHandler('/tmp/Breakfix-nat.log')
# attach to your logger
logger.addHandler(screen_handler)
logger.addHandler(tasklog_handler)
# set log level to show everything

cfg = {}
DATA_PATH = "data/breakfix_nat_data.yaml"

def get_from_store(name):
""" Get model from data file config using store.get """
base_dir = os.path.dirname(os.path.abspath(__file__))
DATA_FILE_PATH = base_dir + "/" + DATA_PATH
return store.get('file:' + DATA_FILE_PATH, root_object=name)

def create_manual_nat_with_query_params(fmc1, nat_policy, object_name_in_data_yaml,


section_value=None,
targetIndex_value=None):
""" Creates NAT url with query parameters"""
manual_nat_obj = ManualNatRule()
query_params_url = None
if section_value is not None:
query_params_url = "?" + "section=" + section_value
elif targetIndex_value is not None:
query_params_url = "?" + "targetIndex=" + targetIndex_value
manual_nat_url = str(RestApiURL.ManualNatRule.value["FtdNatPolicy"]). \
format(container_id=nat_policy.id) + query_params_url
api_url = "{api_prefix}/{api_url}".format(api_prefix=API_PREFIX,
api_url=manual_nat_url)
object_data = get_from_store(object_name_in_data_yaml)
response_data = fmc1.rest_connection.post(api_url, object_data.serialized())

query_param_response =
manual_nat_obj.deserializer.deserialize_create_response(manual_nat_obj,
response_data)
print(str(query_param_response))
return query_param_response

class ScriptCommonSetup(ftltest.CommonSetup):
@aetest.subsection
def initialise_easypy(self, api_service_fmc1:APIService):
import argparse, os
base_dir = os.path.dirname(__file__)
DATA_FILE = "data/breakfix_nat_data.yaml"
DATA_FILE_PATH = os.path.join(base_dir, DATA_FILE)
parser = argparse.ArgumentParser(description="Break fix NAT feature
AUTOMATION")
parser.add_argument('--datayaml', type=str, default=DATA_FILE_PATH)
# parser.add_argument('--nameIfNames', action='append', default=['inside',
'outside'])
parser.add_argument('--hasetup', action="store_true", default=True)
parser.add_argument('--haname', type=str, default='Breakfix-HA')
parser.add_argument('--failoverLinkName', action='append',
default=['failover'])
parser.add_argument('--seczone', action='append', default=['outside',
'inside'])
# parser.add_argument('--clustersetup', action="store_true", default=False)
# parser.add_argument('--clustername', type=str, default='vFTD_Cluster')
# parser.add_argument('--ccl_interface', dest='ccl_interface',
default='GigabitEthernet0/5')
args = parser.parse_known_args()[0]
self.parameters.update(args=args)
self.parent.parameters.update({
'datayaml': args.datayaml,
# 'nameIfNames': args.nameIfNames,
'hasetup': args.hasetup,
'haname': args.haname,
'failoverLinkName': args.failoverLinkName,
'seczone':args.seczone
})

# Add all the network objects to add here


network_obj_host = [['obj_1','1.1.1.1'],
['obj_2','2.2.2.2'],
['obj_3','3.3.3.3'],
['obj_4','4.4.4.4'],
]

network_obj_range = [['obj_range_1', '7.7.7.2', '7.7.7.50'],


['obj_range_2', '8.8.8.2', '8.8.8.50'],
['obj_range_3','6.6.6.2','6.6.6.50'],
['obj_range_4','5.5.5.2','5.5.5.50']
]

network_obj_subnet = [['obj_subnet_1', '11.11.11.0', '255.255.255.0'],


['obj_subnet_2', '12.12.12.0', '255.255.255.0'],
['obj_subnet_3', '13.13.13.0', '255.255.255.0'],
['obj_subnet_4', '13.13.13.0', '255.255.255.0']
]
network_obj_grp = [['obj_grp_1', 'obj_5', 'obj_range_5'],
['obj_grp_2', 'obj_6', 'obj_range_6'],
['obj_grp_3', 'obj_7', 'obj_range_7'],
]
nat_detail_dict = {
'before_nat': ["Section 1",r"Manual NAT Policies \(Section 1\)(.*?)(?=\
n\n|\Z)"],
'auto_nat' : ["Section 2",r"Auto NAT Policies \(Section 2\)(.*?)(?=\n\
n|\Z)"],
'after_nat': ["Section 3",r"Manual NAT Policies \(Section 3\)(.*?)(?=\
n\n|\Z)"]
}
# add all the show commands here to validate
show_commands = ['show running-config nat',
'show nat detail',
'show startup-config | grep nat',
'show nat']

cfg.update({"api_service_fmc1":api_service_fmc1,
'fmc1': self.parent.parameters.get('fmc1'),
# 'ccl_interface': args.ccl_interface,
# 'clustername': args.clustername,
# 'clustersetup': args.clustersetup,
'network_obj_host':network_obj_host,
'network_obj_range':network_obj_range,
'network_obj_subnet':network_obj_subnet,
'network_obj_grp':network_obj_grp,
'nat_detail_dict':nat_detail_dict,
'show_commands':show_commands
})

#@aetest.subsection
def register_smart_license(self, steps, api_service_fmc1, datayaml):
try:
with steps.start("Registering smart license"):
register_with_token_config = store.get('file:{}'.format(datayaml),

root_object='smart_license.register_token_breakfix')
register_with_token_config_find =
api_service_fmc1.find_one_by_record(register_with_token_config)
if register_with_token_config_find.license_status != '(null)':
api_service_fmc1.delete(register_with_token_config)
api_service_fmc1.create(register_with_token_config)
registered_license =
api_service_fmc1.find_one_by_record(register_with_token_config)
if not registered_license:
self.failed("Unable to register smart license",
goto=["common_cleanup"])
except Exception as e:
self.failed('Registering smart license failed due to {}'.format(e),
goto=["common_cleanup"])

#@aetest.subsection
def create_ac_policy_for_registration(self, api_service_fmc1: APIService):
try:
name = "registration_policy"
ac_policy = api_service_fmc1.find_one(AccessPolicy,
condition=lambda obj: obj.name ==
name)
if ac_policy:
log.warning("{} already exists".format(name))
else:
ac_policy_cfg = AccessPolicy(name=name,
defaultAction=AccessPolicyDefaultAction(action="BLOCK"))
ac_policy = api_service_fmc1.create(ac_policy_cfg)

assert ac_policy
assert ac_policy.id
assert ac_policy.name == ac_policy_cfg.name
cfg.update({'ac_policy': ac_policy})

except Exception as e:
self.failed('Failed due to {}'.format(e), goto=["common_cleanup"])

# @aetest.subsection
def device_registration(self,testbed, api_service_fmc1):
steps = Steps()
breakfix_lib = BreakfixUtils()
brkfx_nat_lib = BreakfixNatUtils()
ssh_conn = []
fmc_ip = testbed.devices['fmc1'].custom.fmc_ip
regkey = testbed.devices['sensor2'].custom.reg_key
nat_id = testbed.devices['sensor2'].custom.nat_id
ftd1 = ConfigProvider(testbed, TestBedConstants.sensor1.value)
ftd1_ssh = ftd1.get_ssh_connection()
ssh_conn.append(ftd1_ssh)
ftd2 = ConfigProvider(testbed, TestBedConstants.sensor2.value)
ftd2_ssh = ftd2.get_ssh_connection()
ssh_conn.append(ftd2_ssh)
ac_policy = cfg.get('ac_policy')
sensors = ['sensor1', 'sensor2']
try:
with steps.start("Validating any other FMC is registered to the
devices"):
breakfix_lib.manager_validation_in_fmc(ssh_conn[0], log)
breakfix_lib.manager_validation_in_fmc(ssh_conn[1], log)

with steps.start("Configuring Manager On FTD"):


ftd1_ssh.register_device(fmc_ip, key=regkey, nat_id=nat_id)
ftd2_ssh.register_device(fmc_ip, key=regkey, nat_id=nat_id)

with steps.start("Registering FTD in the FMC"):


for device in sensors:
device_ip = testbed.devices[device].custom.device_ip
regkey = testbed.devices[device].custom.reg_key
nat_id = testbed.devices[device].custom.nat_id
log.info(f"Registering device {device_ip}")
brkfx_nat_lib.register_ftd_in_fmc(
device_ip,
api_service_fmc1,
device_ip,
regkey,
nat_id,
ac_policy)
log.info("Registered successfully")
time.sleep(30)
except Exception as e:
self.failed('Failed due to {}'.format(e), goto=["common_cleanup"])
finally:
log.info("Disconnecting the ftd handles")
for ftd_handles in ssh_conn:
ftd_handles.conn.disconnect()

@aetest.subsection
def create_ha_setup(self, testbed, api_service_fmc1, haname, failoverLinkName,
hasetup, datayaml):
steps = Steps()
breakfix_lib = BreakfixUtils()
brkfx_nat_lib = BreakfixNatUtils()

try:
# with steps.start(f"Configuring physical interface for both the
sensors") as substep:
# devices = api_service_fmc1.find_all(Device)
# deviceObjDict = {}
# for device in range(len(devices)):
# deviceObjDict[devices[device].name] = devices[device]
# for sensor in ['sensor1', 'sensor2']:
# device_ip = testbed.devices[sensor].custom.device_ip
# data_interface =
testbed.devices[sensor].custom.data_interface
# data_interface_name =
testbed.devices[sensor].custom.data_interface_name
# data_interface_ipv4 =
testbed.devices[sensor].custom.data_interface_ipv4_address
# data_interface_netmask =
testbed.devices[sensor].custom.data_interface_netmask
# with substep.start(f"Configuring {data_interface} in
{sensor}"):
#
breakfix_lib.delete_physical_interface_ipv4(primary_device=deviceObjDict[device_ip]
,
#
interfacename=data_interface,
#
nameif=data_interface_name,
#
description=data_interface_name, enabled=True,
#
api_service_fmc1=api_service_fmc1,
#
ipv4addr=data_interface_ipv4,
#
ipv4mask=data_interface_netmask
# )
# log.info(f"Deploying the changes in {device_ip}")
# breakfix_lib.deploy_on_ftd(api_service_fmc1,
ftd=deviceObjDict[device_ip])
# time.sleep(15)
# log.info("Physcial interface configured successfully")

with steps.start("HA Formation"):


hadevice = api_service_fmc1.find_one(HighAvailability,
condition=lambda device_obj:
device_obj.name == haname)
devices = api_service_fmc1.find_all(Device)
deviceList = []
if hadevice is None:
for device in range(len(devices)):
deviceList.append(devices[device].name)
# update the sensor list to parent
deviceList.sort()
self.parent.parameters.update({'sensorList': deviceList})

if len(deviceList) > 1 and hasetup:


returnDict = createHaSetup(testbed=testbed,
api_service_fmc1=api_service_fmc1,
haname=haname,
sensorList=deviceList,
datayaml=datayaml,

failoverLinkName=failoverLinkName)
self.parent.parameters.update({
'parentDevice': returnDict.get('parentDevice'),
'primaryDevice': returnDict.get('primaryDevice'),
'secondaryDevice': returnDict.get('secondaryDevice'),
'returnDict': returnDict,
})
cfg.update({
'parentDevice': returnDict.get('parentDevice'),
'primaryDevice': returnDict.get('primaryDevice'),
'secondaryDevice': returnDict.get('secondaryDevice'),
'returnDict': returnDict,
})
else:
log.info('hasetup flag is not true, hence detect the first
ftd as primary device in '
'sensorlist')
sensorList = self.parent.parameters.get('sensorList')
parentDevice = api_service_fmc1.find_one(Device,
condition=lambda
device_obj: device_obj.name ==

sensorList[

0])
primaryDevice = parentDevice
secondaryDevice = parentDevice
self.parent.parameters.update({
'parentDevice': parentDevice,
'primaryDevice': primaryDevice,
'secondaryDevice': secondaryDevice,
})
log.info(banner("HA Formed Successfully"))
else:
returnDict = createHaSetup(testbed=testbed,
api_service_fmc1=api_service_fmc1,
haname=haname,
sensorList=deviceList,
datayaml=datayaml,
failoverLinkName=failoverLinkName)
self.parent.parameters.update({
'parentDevice': returnDict.get('parentDevice'),
'primaryDevice': returnDict.get('primaryDevice'),
'secondaryDevice': returnDict.get('secondaryDevice'),
'returnDict': returnDict,
})
cfg.update({
'parentDevice': returnDict.get('parentDevice'),
'primaryDevice': returnDict.get('primaryDevice'),
'secondaryDevice': returnDict.get('secondaryDevice'),
'returnDict': returnDict,
})
log.info(banner(f"Already HA setup is found with name
{haname}"))
time.sleep(10)
log.info(banner("HA formed successfully"))

with steps.start("Validate HA Formation"):


primaryDevice = cfg.get('primaryDevice')
primaryconf = ConfigProvider(testbed, primaryDevice.name)
primary_ssh = primaryconf.get_ssh_connection()
primarydevice_status, secondarydevice_status =
brkfx_nat_lib.get_ha_status_from_primary_device(ftd_ssh=primary_ssh)
log.info(banner(f"Primary device status : {primarydevice_status} |
Secondary device Status : {secondarydevice_status}" ))
primary_ssh.conn.disconnect()

except Exception as e:
self.failed('Failed due to {}'.format(e), goto=["common_cleanup"])

# @aetest.subsection
def configure_interface_and_nat_fmc(self,testbed,api_service_fmc1,datayaml):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
brkfx_nat_lib = BreakfixNatUtils()
parentDevice = cfg.get('parentDevice')
primary_ip = cfg.get('primaryDevice').name
primary_sensor =
brkfx_nat_lib.get_primary_ip_sensor(primary_ip=primary_ip,testbed=testbed)
data_interface_netmask =
testbed.devices[primary_sensor].custom.data_interface_netmask
try:
with steps.start("Configuring interfaces and zones") as substep:

with substep.start("Configuring the outside interface"):


data_interface_name1 =
testbed.devices[primary_sensor].custom.data_interface_name
data_interface1 =
testbed.devices[primary_sensor].custom.data_interface
data_interface_ipv4_address1 =
testbed.devices[primary_sensor].custom.data_interface_ipv4_address

breakfix_lib.update_physical_interface_ipv4(primary_device=deviceObjDict[primary_ip
],
interfacename=data_interface1,
nameif=data_interface_name1,

description=data_interface_name1, enabled=True,

api_service_fmc1=api_service_fmc1,

ipv4addr=data_interface_ipv4_address1,
ipv4mask=data_interface_netmask,
)

with substep.start("Configuring the inside interface"):


data_interface_name2 =
testbed.devices[primary_sensor].custom.data_interface_name_1
data_interface2 =
testbed.devices[primary_sensor].custom.data_interface_1
data_interface_ipv4_address2 =
testbed.devices[primary_sensor].custom.data_interface_ipv4_address_1

breakfix_lib.update_physical_interface_ipv4(primary_device=deviceObjDict[primary_ip
],

interfacename=data_interface2,

nameif=data_interface_name2,

description=data_interface_name2, enabled=True,

api_service_fmc1=api_service_fmc1,

ipv4addr=data_interface_ipv4_address2,

ipv4mask=data_interface_netmask,
)

log.info("Deploying the changes in FMC")


breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=[parentDevice])
log.info("Deployment completed")
time.sleep(15)

with substep.start("Configuring zone for the outside interface"):


outzone = store.get('file:{}'.format(datayaml),
root_object='security_zones.outside')
phyIntf1 = api_service_fmc1.find_one(PhysicalInterface,
condition=lambda intfname:
intfname.name == data_interface1,

container_id=deviceObjDict[primary_ip].id)
outzone.interfaces = [phyIntf1]
api_service_fmc1.create(outzone)

assert outzone is not None


self.parent.parameters.update({'outzone':outzone})

with substep.start("Confiugring zone for the inside interface"):


inzone = store.get('file:{}'.format(datayaml),
root_object='security_zones.inside')
phyIntf2 = api_service_fmc1.find_one(PhysicalInterface,
condition=lambda intfname:
intfname.name == data_interface2,

container_id=deviceObjDict[primary_ip].id)
inzone.interfaces = [phyIntf2]
api_service_fmc1.create(inzone)

assert inzone is not None


self.parent.parameters.update({'inzone': inzone})

log.info("Deploying the changes in FMC")


breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=[parentDevice])
log.info("Deployment completed")
time.sleep(15)

with steps.start("Configuring NAT policy in FMC"):


nat_policy_config = store.get("file:{}".format(datayaml),
root_object='nat_policies.natpolicy')
nat_policy = api_service_fmc1.create(nat_policy_config)
created_nat_policy = api_service_fmc1.find_one(FtdNatPolicy, lambda
obj: obj.name == nat_policy.name)
assert nat_policy.id == created_nat_policy.id
policy_assignment = PolicyAssignment()
policy_assignment.targets = [parentDevice]
policy_assignment.policy = nat_policy
api_service_fmc1.create(policy_assignment)
self.parent.parameters.update(nat_policy=nat_policy)

log.info("Deploying the changes in FMC")


breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=[parentDevice])
log.info("Deployment completed")
time.sleep(5)

except Exception as e:
self.failed('Failed due to {}'.format(e), goto=["common_cleanup"])

class TC_StaticNatCombinations():

"""
TC 1: [STATIC_source addrs_translation_manual_NAT] To configure static nat with
real and mapped interfaces as any & real and mapped src_addresses as any
TC 2: [STATIC_source addrs_translation_manual_NAT] To configure static nat with
real and mapped interfaces as any & real and mapped src_addresses as objects
TC 3: [STATIC_source _dst addrs_translation_manual_NAT] To configure static nat
with real and mapped interfaces as any . Real and mapped src_addresses as any .
Mapped and real destination as objects.
TC 4: [STATIC_source _dst addrs_translation_manual_NAT] To configure static nat
with real and mapped interfaces as any & real and mapped src_addresses as any and
objects respectively. Mapped and real destinations as objects and any respectively.
TC 5: [STATIC_source _dst addrs_translation_manual_NAT] To configure static nat
with real and mapped interfaces as any & real and mapped src_addresses as objects
and any respectively.
"""

#@aetest.setup
def setup(self):
set_testcase_feature([Features77.feature4.value])
set_tims_testcase("Txw16474602r,Txw16474626r,Txw16474604r")

@aetest.test
def static_nat(self,testbed, api_service_fmc1,datayaml):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
brkfx_nat_lib = BreakfixNatUtils()
parentDevice = cfg.get('parentDevice')
primaryDevice = cfg.get('primaryDevice')
primary_ip = cfg.get('primaryDevice').name
primaryconf = ConfigProvider(testbed, primaryDevice.name)
primary_ssh = primaryconf.get_ssh_connection()
cfg.update({'primary_ssh':primary_ssh})
network_obj_host = cfg.get('network_obj_host')
cli_regex_dict = {'nat source static any any':
r"source\s+static\s+any\s+any",
f'nat source static {network_obj_host[0][0]}
{network_obj_host[0][0]}':
rf"source\s+static\s+{network_obj_host[0][0]}\s+
{network_obj_host[0][0]}",
f'nat source static any any destination static
{network_obj_host[1][0]} {network_obj_host[1][0]}':
rf"source\s+static\s+any\s+any\s+destination\s+static\
s+{network_obj_host[1][0]}\s+{network_obj_host[1][0]}",
f'nat source static any {network_obj_host[2][0]}
destination static {network_obj_host[2][0]} any':
rf"source\s+static\s+any\s+{network_obj_host[2][0]}\
s+destination\s+static\s+{network_obj_host[2][0]}\s+any",
f'nat source static {network_obj_host[3][0]}
{network_obj_host[3][0]} destination static {network_obj_host[3][0]} any':
rf"source\s+static\s+{network_obj_host[3][0]}\s+
{network_obj_host[3][0]}\s+destination\s+static\s+{network_obj_host[3][0]}\s+any"
}
nat_detail_dict = cfg.get('nat_detail_dict')
breakfix_cli_args = [cli for cli in cli_regex_dict.keys()]

with steps.start("Executing the breakfix CLI change"):


try:
breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)
log.info("Creating all the network objects - Host")
for obj_host in network_obj_host:
primary_ssh.conn.execute(f'object network {obj_host[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'host {obj_host[1]}', prompt='>|#',
timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)

# log.info("Creating all the network objects - Range")


# for obj_range in network_obj_range:
# primary_ssh.conn.execute(f'object network {obj_range[0]}',
prompt='>|#', timeout=120)
# primary_ssh.conn.execute(f'range {obj_range[1]}
{obj_range[2]}', prompt='>|#', timeout=120)
# primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
# time.sleep(2)
log.info("Network objects created successfully")

for cli in breakfix_cli_args:


log.info(banner(f"Executing the nat cli - {cli}"))
primary_ssh.conn.execute(f'{cli}', prompt='>|#',timeout=120)
time.sleep(2)
primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute("Y", prompt='#')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')
except Exception as err:
self.failed(err)

with steps.start("Validating the OOB file present in FTD"):


try:
oob_file_result =
breakfix_lib.OOB_file_validation(ftd_ssh=primary_ssh)
if oob_file_result != True:
log.error("OOB file not Generated Properly")
self.failed("OOB file not Generated Properly")
except Exception as err:
self.failed(err)

with steps.start("Validating the show commands in FTD") as substep:


try:
show_commands = ['show running-config nat',
'show nat detail',
'show startup-config | grep nat',
'show nat']
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name='before_nat',

nat_detail=nat_detail_dict['before_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

except Exception as err:


self.failed(err)

with steps.start("Detect Out of Band changes"):


try:
outof_change = store.get("file:{}".format(datayaml),
root_object='outofband.change1')
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is Detected"))
except Exception as err:
self.failed(err)

with steps.start("Acknowledging the Out of Band of changes in FMC"):


try:
outof_change.oobaction = 'ACKNOWLEDGE_OUT_OF_BAND_CHANGES'
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is acknowledged"))
except Exception as err:
self.failed(err)
with steps.start("Configuring the same breakfix changes in FMC") as
substep:
try:
breakfix_nat_policy = api_service_fmc1.find_one(FtdNatPolicy,
lambda obj: obj.name == 'Breakfix_Nat')

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[0]}' "):
cfg.update({'breakfix_nat_policy':breakfix_nat_policy})
originalSource = api_service_fmc1.find_one(NetworkObject,
lambda network: network.name
== 'any-ipv4')
translatedSource = api_service_fmc1.find_one(NetworkObject,
lambda network: network.name
== 'any-ipv4')
nat_rule1 = ManualNatRule()
nat_rule1.enabled = 'True'
nat_rule1.natType = 'STATIC'
nat_rule1.originalSource = originalSource
nat_rule1.translatedSource = translatedSource
api_service_fmc1.create(copy.deepcopy(nat_rule1),
container_id=breakfix_nat_policy.id)

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[1]}' "):
log.info("Creating a network object 'obj_1' ")
nw_obj_1 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_1')
api_service_fmc1.create(nw_obj_1)
originalSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_1')
translatedSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_1')
nat_rule2 = ManualNatRule()
nat_rule2.enabled = 'True'
nat_rule2.natType = 'STATIC'
nat_rule2.originalSource = originalSource
nat_rule2.translatedSource = translatedSource
api_service_fmc1.create(copy.deepcopy(nat_rule2),
container_id=breakfix_nat_policy.id)
assert nat_rule2
cfg.update({'tc_21_data':nat_rule2})

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[2]}' "):
log.info("Creating a network object 'obj_2' ")
nw_obj_2 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_2')
api_service_fmc1.create(nw_obj_2)
originalSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'any-ipv4')
translatedSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'any-ipv4')
originalDestination = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_2')
translatedDestination =
api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_2')
nat_rule3 = ManualNatRule()
nat_rule3.enabled = 'True'
nat_rule3.natType = 'STATIC'
nat_rule3.originalSource = originalSource
nat_rule3.translatedSource = translatedSource
nat_rule3.originalDestination = originalDestination
nat_rule3.translatedDestination = translatedDestination
api_service_fmc1.create(copy.deepcopy(nat_rule3),
container_id=breakfix_nat_policy.id)

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[3]}' "):
log.info("Creating a network object 'obj_3' ")
nw_obj_3 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_3')
api_service_fmc1.create(nw_obj_3)
originalSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'any-ipv4')
translatedSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_3')
originalDestination = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_3')
translatedDestination =
api_service_fmc1.find_one(NetworkObject,
lambda
network: network.name == 'any-ipv4')
nat_rule3 = ManualNatRule()
nat_rule3.enabled = 'True'
nat_rule3.natType = 'STATIC'
nat_rule3.originalSource = originalSource
nat_rule3.translatedSource = translatedSource
nat_rule3.originalDestination = originalDestination
nat_rule3.translatedDestination = translatedDestination
api_service_fmc1.create(copy.deepcopy(nat_rule3),
container_id=breakfix_nat_policy.id)

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[4]}' "):
log.info("Creating a network object 'obj_4' ")
nw_obj_4 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_4')
api_service_fmc1.create(nw_obj_4)
originalSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_4')
translatedSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_4')
originalDestination = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_4')
translatedDestination =
api_service_fmc1.find_one(NetworkObject,
lambda
network: network.name == 'any-ipv4')
nat_rule4 = ManualNatRule()
nat_rule4.enabled = 'True'
nat_rule4.natType = 'STATIC'
nat_rule4.originalSource = originalSource
nat_rule4.translatedSource = translatedSource
nat_rule4.originalDestination = originalDestination
nat_rule4.translatedDestination = translatedDestination
api_service_fmc1.create(copy.deepcopy(nat_rule4),
container_id=breakfix_nat_policy.id)

log.info(banner("Deploying the changes in FMC"))


breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=parentDevice)
log.info(banner("Deployment completed"))
time.sleep(3)

except Exception as err:


self.failed(err)

with steps.start("Validating the show commands in FTD after deployment") as


substep:
try:
show_commands = cfg.get('show_commands')
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name='before_nat',

nat_detail=nat_detail_dict['before_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

with substep.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
xlate_op = primary_ssh.conn.execute('show xlate detail')
# brkfx_nat_lib.validate_xlate(xlate_op=xlate_op)

except Exception as err:


self.failed(err)

@aetest.cleanup
def cleanup(self):
primary_ssh = cfg.get('primary_ssh')
try:
log.info("Disconnecting the SSH handle")
primary_ssh.conn.disconnect()
except Exception as err:
self.failed(err)
class TC_DynamicNatCombinations():
"""
TC 6: [DYNAMIC_source_dst_addrs_translation_manual_NAT] To configure
dynamic nat with real and mapped interfaces as any. Real src & mapped src addresses
as any and objects respectively. Destination mapped and real addresses as objects /
object-groups and any respectively.
TC 7: [DYNAMIC_source addrs_translation_manual_NAT] To configure dynamic
nat with real and mapped interfaces as any & real src & mapped src addresses as
object / object-group respectively
TC 8: [DYNAMIC_source addrs_translation_manual_NAT] To configure dynamic
nat with real and mapped interfaces as any & real src & mapped src addresses as pat
pool and objects respectively
"""

#@aetest.setup
def setup(self):
set_testcase_feature([Features77.feature4.value])
set_tims_testcase("Txw16474602r,Txw16474626r,Txw16474604r")

@aetest.test
def dynamic_nat(self, testbed, api_service_fmc1, datayaml):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
brkfx_nat_lib = BreakfixNatUtils()
parentDevice = cfg.get('parentDevice')
primaryDevice = cfg.get('primaryDevice')
primary_ip = cfg.get('primaryDevice').name
primaryconf = ConfigProvider(testbed, primaryDevice.name)
primary_ssh = primaryconf.get_ssh_connection()
cfg.update({'primary_ssh': primary_ssh})
network_obj_host = cfg.get('network_obj_host')
network_obj_range = cfg.get('network_obj_range')
network_obj_subnet = cfg.get('network_obj_subnet')
nat_detail_dict = cfg.get('nat_detail_dict')

cli_regex_dict = {f'nat source dynamic any {network_obj_range[0][0]}


destination static {network_obj_range[1][0]} any':
rf"source\s+dynamic\s+any\s+{network_obj_range[0]
[0]}\s+destination\s+static\s+{network_obj_range[1][0]}\s+any",
f'nat source dynamic {network_obj_range[1][0]}
{network_obj_host[2][0]}':
rf"source\s+dynamic\s+{network_obj_range[1][0]}\s+
{network_obj_host[2][0]}",
f'nat source dynamic any pat-pool {network_obj_range[2]
[0]}':
rf"source\s+dynamic\s+any\s+pat-pool\s+
{network_obj_range[2][0]}"
}
subnet_cli = f"nat source dynamic any pat-pool {network_obj_subnet[0][0]}"
breakfix_cli_args = [cli for cli in cli_regex_dict.keys()]

with steps.start("Executing the breakfix CLI change"):


try:
breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)
log.info("Creating all the network objects - Range")
for obj_range in network_obj_range:
primary_ssh.conn.execute(f'object network {obj_range[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'range {obj_range[1]}
{obj_range[2]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)

log.info("Network objects range created successfully")

for subnet in network_obj_subnet:


log.info(f"Creating all the network objects - {subnet[0]}")
primary_ssh.conn.execute(f'object network {subnet[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'subnet {subnet[1]} {subnet[2]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)

log.info("Network objects subnet created successfully")

for cli in breakfix_cli_args:


log.info(banner(f"Executing the nat cli - {cli}"))
primary_ssh.conn.execute(f'{cli}', prompt='>|#', timeout=120)
time.sleep(2)

log.info(banner(f"Validating the subnet option not supported to


dynamic nat for mapped source interface"))
err_op = primary_ssh.conn.execute(f'{subnet_cli}', prompt='>|#',
timeout=120)
if "ERROR: Subnet can not be used as mapped source in dynamic NAT
policy" in err_op:
log.info(banner("Subnet can not be used as mapped source in
dynamic NAT policy"))
else:
log.error("Subnet is accepting for dynamic nat source")
self.failed("Subnet is accepting for dynamic nat source")

primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute("Y", prompt='#')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')

except Exception as err:


self.failed(err)

with steps.start("Validating the OOB file present in FTD"):


try:
oob_file_result =
breakfix_lib.OOB_file_validation(ftd_ssh=primary_ssh)
if oob_file_result != True:
log.error("OOB file not Generated Properly")
self.failed("OOB file not Generated Properly")
except Exception as err:
self.failed(err)

with steps.start("Validating the show commands in FTD") as substep:


try:
show_commands = ['show running-config nat',
'show nat detail',
'show startup-config | grep nat',
'show nat']
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name='before_nat',

nat_detail=nat_detail_dict['before_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

except Exception as err:


self.failed(err)

with steps.start("Detect Out of Band changes"):


try:
outof_change = store.get("file:{}".format(datayaml),
root_object='outofband.change2')
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is Detected"))
except Exception as err:
self.failed(err)

with steps.start("Acknowledging the Out of Band of changes in FMC"):


try:
outof_change.oobaction = 'ACKNOWLEDGE_OUT_OF_BAND_CHANGES'
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is acknowledged"))
except Exception as err:
self.failed(err)

with steps.start("Configuring the same breakfix changes in FMC") as


substep:
try:
breakfix_nat_policy = api_service_fmc1.find_one(FtdNatPolicy,
lambda obj: obj.name == 'Breakfix_Nat')

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[0]}' "):
log.info("Creating a network object ranges 'obj_range_1'")
nw_obj_range_1 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_range_1')
api_service_fmc1.create(nw_obj_range_1)
log.info("Creating a network object ranges 'obj_range_2'")
nw_obj_range_2 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_range_2')
api_service_fmc1.create(nw_obj_range_2)
originalSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'any-ipv4')
translatedSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_range_1')

originalDestination = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_range_2')
translatedDestination =
api_service_fmc1.find_one(NetworkObject,
lambda
network: network.name == 'any-ipv4')
nat_rule1 = ManualNatRule()
nat_rule1.enabled = 'True'
nat_rule1.natType = 'DYNAMIC'
nat_rule1.unidirectional = True
nat_rule1.originalSource = originalSource
nat_rule1.translatedSource = translatedSource
nat_rule1.originalDestination = originalDestination
nat_rule1.translatedDestination = translatedDestination
api_service_fmc1.create(copy.deepcopy(nat_rule1),
container_id=breakfix_nat_policy.id)

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[1]}' "):

originalSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_range_2')
translatedSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_3')
nat_rule2 = ManualNatRule()
nat_rule2.enabled = 'True'
nat_rule2.natType = 'DYNAMIC'
nat_rule2.unidirectional = True
nat_rule2.originalSource = originalSource
nat_rule2.translatedSource = translatedSource

api_service_fmc1.create(copy.deepcopy(nat_rule2),
container_id=breakfix_nat_policy.id)

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[2]}' "):
log.info("Creating a network object ranges 'obj_range_3'")
nw_obj_range_3 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_range_3')
api_service_fmc1.create(nw_obj_range_3)

log.info(f"Creating a pat-pool any nat rule


'{breakfix_cli_args[2]}'")
nat_rul3 = store.get('file:{}'.format(datayaml),

root_object='manual_nat_rules.dynamic_rule_any_with_pat')
api_service_fmc1.create(copy.deepcopy(nat_rul3),
container_id=breakfix_nat_policy.id)
log.info(banner("Deploying the changes in FMC"))
breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=parentDevice)
log.info(banner("Deployment completed"))
time.sleep(3)

except Exception as err:


self.failed(err)

with steps.start("Validating the show commands in FTD after deployment") as


substep:
try:
show_commands = cfg.get('show_commands')
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name='before_nat',

nat_detail=nat_detail_dict['before_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

with substep.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
xlate_op = primary_ssh.conn.execute('show xlate detail')
# brkfx_nat_lib.validate_xlate(xlate_op=xlate_op)

except Exception as err:


self.failed(err)

@aetest.cleanup
def cleanup(self):
primary_ssh = cfg.get('primary_ssh')
try:
log.info("Disconnecting the SSH handle")
primary_ssh.conn.disconnect()
except Exception as err:
self.failed(err)

class TC_AfterNatCombinations():
"""
TC:9 [STATIC_source addrs_translation_after_auto] To configure static nat
with real and mapped interfaces as any & real and mapped src_addresses as any
TC:10 [STATIC_source addrs_translation_after_auto] To configure static nat
with real and mapped interfaces as any & real and mapped src_addresses as objects
TC:11 [STATIC_source _dst addrs_translation_after_auto] To configure static
nat with real and mapped interfaces as any . Real and mapped src_addresses as
any . Mapped and real destination as objects.
TC:12 [STATIC_source _dst addrs_translation_manual_NAT_after_auto] To
configure static nat with real and mapped interfaces as any & real and mapped
src_addresses as any and objects respectively. Mapped and real destinations as
objects and any respectively.
TC:13 [STATIC_source_dst_addrs_translation_after_auto] To configure static
nat with real and mapped interfaces as any & real and mapped src_addresses as
objects and any respectively.
TC:14 [DYNAMIC_source_dst_addrs_translation_manual_NAT] To configure
dynamic nat with real and mapped interfaces as any. Real src & mapped src addresses
as any and objects respectively. Destination mapped and real addresses as objects /
object-groups and any respectively.
"""

#@aetest.setup
def setup(self):
set_testcase_feature([Features77.feature4.value])
set_tims_testcase("Txw16474602r,Txw16474626r,Txw16474604r")

@aetest.test
def after_auto_nat(self, testbed, api_service_fmc1, datayaml,fmc1):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
brkfx_nat_lib = BreakfixNatUtils()
parentDevice = cfg.get('parentDevice')
primaryDevice = cfg.get('primaryDevice')
primary_ip = cfg.get('primaryDevice').name
primaryconf = ConfigProvider(testbed, primaryDevice.name)
primary_ssh = primaryconf.get_ssh_connection()
cfg.update({'primary_ssh': primary_ssh})
network_obj_host = cfg.get('network_obj_host')
network_obj_range = cfg.get('network_obj_range')
network_obj_subnet = cfg.get('network_obj_subnet')
network_obj_grp = cfg.get('network_obj_grp')
nat_detail_dict = cfg.get('nat_detail_dict')
show_commands = cfg.get('show_commands')
cli_regex_dict = {
f'nat after-auto source static any {network_obj_subnet[0][0]}':
rf'source\s+static\s+any\s+{network_obj_subnet[0][0]}',
f'nat after-auto source static {network_obj_subnet[1][0]}
{network_obj_subnet[2][0]} ':
rf'source\s+static\s+{network_obj_subnet[1][0]}\s+
{network_obj_subnet[2][0]}',
f'nat after-auto source static any any destination static
{network_obj_subnet[3][0]} {network_obj_subnet[0][0]}':
rf'source\s+static\s+any\s+any\s+destination\s+static\s+
{network_obj_subnet[3][0]}\s+{network_obj_subnet[0][0]}',
f'nat after-auto source static any {network_obj_grp[0][0]} destination
static {network_obj_grp[1][0]} any':
rf"source\s+static\s+any\s+{network_obj_grp[0][0]}\s+destination\
s+static\s+{network_obj_grp[1][0]}\s+any",
f'nat after-auto source static {network_obj_subnet[3][0]}
{network_obj_grp[2][0]} destination static {network_obj_subnet[3][0]} any':
rf"source\s+static\s+{network_obj_subnet[3][0]}\s+
{network_obj_grp[2][0]}\s+destination\s+static\s+{network_obj_subnet[3][0]}\s+any",
f'nat after-auto source dynamic any {network_obj_grp[0][0]} destination
static {network_obj_grp[2][0]} any':
rf"source\s+dynamic\s+any\s+{network_obj_grp[0][0]}\s+destination\
s+static\s+{network_obj_grp[2][0]}\s+any"
}

breakfix_cli_args = [cli for cli in cli_regex_dict.keys()]

with steps.start("Executing the breakfix CLI change"):


try:
breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)

for host in [['obj_5','15.1.1.1'],


['obj_6','16.1.1.1'],
['obj_7','17.1.1.1']]:
log.info(f"Creating the host network objects - {host[0]}")
primary_ssh.conn.execute(f'object network {host[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'host {host[1]}', prompt='>|#',
timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
cfg['network_obj_host'].append(host)
time.sleep(2)
log.info("Network objects host created successfully")

for obj_range in [
['obj_range_5', '15.15.15.2', '15.15.15.50'],
['obj_range_6', '16.16.16.2', '16.16.16.50'],
['obj_range_7', '17.17.17.2', '17.17.17.50']]:
primary_ssh.conn.execute(f'object network {obj_range[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'range {obj_range[1]}
{obj_range[2]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
cfg['network_obj_range'].append(obj_range)
time.sleep(2)
log.info("Network objects range created successfully")

for subnet in network_obj_subnet:


log.info(f"Creating the subnet network objects - {subnet[0]}")
primary_ssh.conn.execute(f'object network {subnet[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'subnet {subnet[1]} {subnet[2]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info("Network objects subnet created successfully")

for obj_grp in network_obj_grp:


log.info(f"Creating the object grp - {obj_grp[0]}")
primary_ssh.conn.execute(f'object-group network {obj_grp[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'network-object object {obj_grp[1]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'network-object object {obj_grp[2]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info("Network objects groups created successfully")

for cli in breakfix_cli_args:


log.info(banner(f"Executing the nat cli - {cli}"))
primary_ssh.conn.execute(f'{cli}', prompt='>|#', timeout=120)
time.sleep(2)

primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute("Y", prompt='#')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')

except Exception as err:


self.failed(err)

with steps.start("Validating the OOB file present in FTD"):


try:
oob_file_result =
breakfix_lib.OOB_file_validation(ftd_ssh=primary_ssh)
if oob_file_result != True:
log.error("OOB file not Generated Properly")
self.failed("OOB file not Generated Properly")
except Exception as err:
self.failed(err)

with steps.start("Validating the show commands in FTD") as substep:


try:
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name='after_nat',

nat_detail=nat_detail_dict['after_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

with substep.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
xlate_op = primary_ssh.conn.execute('show xlate detail')
# brkfx_nat_lib.validate_xlate(xlate_op=xlate_op)

except Exception as err:


self.failed(err)

with steps.start("Detect Out of Band changes"):


try:
outof_change = store.get("file:{}".format(datayaml),
root_object='outofband.change3')
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is Detected"))
except Exception as err:
self.failed(err)

with steps.start("Acknowledging the Out of Band of changes in FMC"):


try:
outof_change.oobaction = 'ACKNOWLEDGE_OUT_OF_BAND_CHANGES'
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is acknowledged"))
except Exception as err:
self.failed(err)

with steps.start("Configuring the same breakfix changes in FMC") as


substep:
try:
breakfix_nat_policy = api_service_fmc1.find_one(FtdNatPolicy,
lambda obj: obj.name == 'Breakfix_Nat')

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[0]}' "):
log.info("Creating a network object subnet 'obj_subnet_1'")
obj_subnet_1 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_subnet_1')
api_service_fmc1.create(obj_subnet_1)

any_ipv4 = store.get('file:{}'.format(datayaml),
root_object='networks.any_ipv4')
cfg.update({'any_ipv4':any_ipv4})
api_service_fmc1.create(any_ipv4)

after_nat_rule1 =
create_manual_nat_with_query_params(fmc1=fmc1, nat_policy=breakfix_nat_policy,

object_name_in_data_yaml=

"manual_nat_rules.tc9_rule",

section_value="after_auto")
assert after_nat_rule1

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[1]}' "):
log.info("Creating a network object subnet 'obj_subnet_2'")
obj_subnet_2 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_subnet_2')
api_service_fmc1.create(obj_subnet_2)

log.info("Creating a network object subnet 'obj_subnet_3'")


obj_subnet_3 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_subnet_3')
api_service_fmc1.create(obj_subnet_3)

after_nat_rule2 =
create_manual_nat_with_query_params(fmc1=fmc1, nat_policy=breakfix_nat_policy,

object_name_in_data_yaml=

"manual_nat_rules.tc10_rule",

section_value="after_auto")
assert after_nat_rule2

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[2]}' "):
log.info("Creating a network object subnet 'obj_subnet_4'")
obj_subnet_4 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_subnet_4')
api_service_fmc1.create(obj_subnet_4)

after_nat_rule3 =
create_manual_nat_with_query_params(fmc1=fmc1, nat_policy=breakfix_nat_policy,

object_name_in_data_yaml=

"manual_nat_rules.tc11_rule",

section_value="after_auto")
assert after_nat_rule3

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[3]}' "):
log.info("Creating a network object group 'obj_grp_1'")
obj_grp_1 = store.get('file:{}'.format(datayaml),
root_object='NetworkGroup.obj_grp_1')
api_service_fmc1.create(obj_grp_1)

log.info("Creating a network object group 'obj_grp_1'")


obj_grp_2 = store.get('file:{}'.format(datayaml),
root_object='NetworkGroup.obj_grp_2')
api_service_fmc1.create(obj_grp_2)

after_nat_rule4 =
create_manual_nat_with_query_params(fmc1=fmc1, nat_policy=breakfix_nat_policy,

object_name_in_data_yaml=

"manual_nat_rules.tc12_rule",

section_value="after_auto")
assert after_nat_rule4

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[4]}' "):
log.info("Creating a network object subnet 'obj_subnet_4'")
obj_subnet_4 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_subnet_4')
api_service_fmc1.create(obj_subnet_4)

log.info("Creating a network object group 'obj_grp_3'")


obj_grp_3 = store.get('file:{}'.format(datayaml),
root_object='NetworkGroup.obj_grp_3')
api_service_fmc1.create(obj_grp_3)

after_nat_rule5 =
create_manual_nat_with_query_params(fmc1=fmc1, nat_policy=breakfix_nat_policy,

object_name_in_data_yaml=

"manual_nat_rules.tc13_rule",

section_value="after_auto")
assert after_nat_rule5
with substep.start(f"Configuring the NAT rule in FMC for
'{breakfix_cli_args[5]}' "):

after_nat_rule6 =
create_manual_nat_with_query_params(fmc1=fmc1, nat_policy=breakfix_nat_policy,

object_name_in_data_yaml=

"manual_nat_rules.tc14_rule",

section_value="after_auto")
assert after_nat_rule6

log.info(banner("Deploying the changes in FMC"))


breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=parentDevice)
log.info(banner("Deployment completed"))
time.sleep(3)
except Exception as err:
self.failed(err)

with steps.start("Validating the show commands in FTD after deployment") as


substep:
try:
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name='after_nat',

nat_detail=nat_detail_dict['after_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

with substep.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
xlate_op = primary_ssh.conn.execute('show xlate detail')
# brkfx_nat_lib.validate_xlate(xlate_op=xlate_op)

except Exception as err:


self.failed(err)

@aetest.cleanup
def cleanup(self):
primary_ssh = cfg.get('primary_ssh')
try:
log.info("Disconnecting the SSH handle")
primary_ssh.conn.disconnect()
except Exception as err:
self.failed(err)

class TC_AutoNatStaticDynamicCombinations():
"""
TC:15 [static_pat_auto_nat] To create auto NAT rule with the mapped IP address
TC:16 [static_auto_nat] To create auto NAT rule with the mapped network
object/object-group name (subnet,host,range)
TC:17 [dynamic_pat_auto_nat] To create auto NAT rule with the mapped IP address
TC:18 [dynamic_auto_nat] To create auto NAT rule with the mapped network
object/object-group name (subnet,host,range)
"""

# @aetest.setup
def setup(self):
set_testcase_feature([Features77.feature4.value])
set_tims_testcase("Txw16474602r,Txw16474626r,Txw16474604r")

@aetest.test
def auto_nat_static_dynamic(self, testbed, api_service_fmc1, datayaml):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
brkfx_nat_lib = BreakfixNatUtils()
parentDevice = cfg.get('parentDevice')
primaryDevice = cfg.get('primaryDevice')
primary_ip = cfg.get('primaryDevice').name
primaryconf = ConfigProvider(testbed, primaryDevice.name)
primary_ssh = primaryconf.get_ssh_connection()
nat_detail_dict = cfg.get('nat_detail_dict')
show_commands = cfg.get('show_commands')
cfg.update({'primary_ssh': primary_ssh})

network_obj = [['obj_8', '8.8.12.1'],


['obj_9', '9.9.12.1'],
['obj_10', '10.10.2.1'],
['obj_11', '11.11.2.1'],
['obj_12', '12.12.2.1'],

['obj_range_8', '8.8.12.2', '8.8.12.40'],


['obj_range_9', '9.9.12.2', '9.9.12.40'],
['obj_range_10', '10.10.12.2', '10.10.12.40'],

['obj_subnet_5', '3.3.2.0', '255.255.255.0'],


['obj_grp_4', 'obj_12', 'obj_range_10'],
]

cli_regex_dict = {
f'nat static {network_obj[1][0]}':
rf"source\s+static\s+{network_obj[0][0]}\s+{network_obj[1][0]}"
rf"| object\s+network\s+{network_obj[0][0]}\s*nat\s*\(any,any\)\
s*static\s*{network_obj[1][0]}"
rf"| nat\s+\(any,any\)\s+static\s+{network_obj[1][0]}",
f'nat static {network_obj[2][0]}':
rf"source\s+static\s+{network_obj[5][0]}\s+{network_obj[2][0]}"
rf"| object\s+network\s+{network_obj[5][0]}\s*nat\s*\(any,any\)\
s*static\s*{network_obj[2][0]}"
rf"| nat\s+\(any,any\)\s+static\s+{network_obj[2][0]}",
f'nat dynamic {network_obj[3][0]}':
rf"source\s+dynamic\s+{network_obj[6][0]}\s+{network_obj[3][0]}"
rf"| object\s+network\s+{network_obj[6][0]}\s*nat\s*\(any,any\)\
s*dynamcic\s*{network_obj[3][0]}"
rf"| nat\s+\(any,any\)\s+dynamic\s+{network_obj[3][0]}",
f'nat dynamic {network_obj[9][0]}':
rf"source\s+dynamic\s+{network_obj[8][0]}\s+{network_obj[9][0]}"
rf"| object\s+network\s+{network_obj[8][0]}\s*nat\s*\(any,any\)\
s*dynamcic\s*{network_obj[9][0]}"
rf"| nat\s+\(any,any\)\s+dynamic\s+{network_obj[9][0]}",
}

breakfix_cli_args = [cli for cli in cli_regex_dict.keys()]

auto_nat_objs =
[network_obj[0],network_obj[5],network_obj[6],network_obj[8]]

with steps.start("Executing the breakfix CLI change"):


try:
breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)

for host in network_obj[0:5]:


log.info(f"Creating the host network objects - {host[0]}")
primary_ssh.conn.execute(f'object network {host[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'host {host[1]}', prompt='>|#',
timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
cfg['network_obj_host'].append(host)
time.sleep(2)
log.info("Network objects host created successfully")

for obj_range in network_obj[5:8]:


log.info(f"Creating the host network objects - {obj_range[0]}")
primary_ssh.conn.execute(f'object network {obj_range[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'range {obj_range[1]}
{obj_range[2]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
cfg['network_obj_range'].append(obj_range)
time.sleep(2)
log.info("Network objects range created successfully")

log.info("Creating all the network subnet objects")


primary_ssh.conn.execute(f'object network {network_obj[8][0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'subnet {network_obj[8][1]}
{network_obj[8][2]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info(f"Network subnet object {network_obj[8][0]} created
successfully")

log.info("Creating all the network group")


primary_ssh.conn.execute(f'object-group network {network_obj[9]
[0]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'network-object object {network_obj[9]
[1]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'network-object object {network_obj[9]
[2]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info(f"Network object group {network_obj[7][0]} created
successfully")

for objs, cli in zip(auto_nat_objs, breakfix_cli_args):


log.info(banner(f"Executing the auto-nat cli - {cli}"))
primary_ssh.conn.execute(f' object network {objs[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'{cli}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)

primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute("Y", prompt='#')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')

except Exception as err:


self.failed(err)

with steps.start("Validating the OOB file present in FTD"):


try:
oob_file_result =
breakfix_lib.OOB_file_validation(ftd_ssh=primary_ssh)
if oob_file_result != True:
log.error("OOB file not Generated Properly")
self.failed("OOB file not Generated Properly")
except Exception as err:
self.failed(err)

with steps.start("Validating the show commands in FTD") as substep:


try:
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name='auto_nat',

nat_detail=nat_detail_dict['auto_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

with substep.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
xlate_op = primary_ssh.conn.execute('show xlate detail')
# brkfx_nat_lib.validate_xlate(xlate_op=xlate_op)

except Exception as err:


self.failed(err)

with steps.start("Detect Out of Band changes"):


try:
outof_change = store.get("file:{}".format(datayaml),
root_object='outofband.change4')
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is Detected"))
except Exception as err:
self.failed(err)

with steps.start("Acknowledging the Out of Band of changes in FMC"):


try:
outof_change.oobaction = 'ACKNOWLEDGE_OUT_OF_BAND_CHANGES'
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is acknowledged"))
except Exception as err:
self.failed(err)

with steps.start("Configuring the same breakfix changes in FMC") as


substep:
try:
breakfix_nat_policy = api_service_fmc1.find_one(FtdNatPolicy,
lambda obj: obj.name == 'Breakfix_Nat')

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[0]}' "):
log.info("Creating a network object 'obj_8' ")
nw_obj_8 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_8')
api_service_fmc1.create(nw_obj_8)
log.info("Creating a network range object 'obj_9' ")
nw_obj_9 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_9')
api_service_fmc1.create(nw_obj_9)

originalNetwork = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_8')
translatedNetwork = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_9')

auto_nat_1 = AutoNatRule()
auto_nat_1.natType = 'STATIC'
auto_nat_1.originalNetwork = originalNetwork
auto_nat_1.translatedNetwork = translatedNetwork
api_service_fmc1.create(copy.deepcopy(auto_nat_1),
container_id=breakfix_nat_policy.id)

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[1]}' "):
log.info("Creating a network object 'obj_range_8' ")
nw_range_8 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_range_8')
api_service_fmc1.create(nw_range_8)
log.info("Creating a network range object 'obj_10' ")
nw_obj_10 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_10')
api_service_fmc1.create(nw_obj_10)

originalNetwork = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_range_8')
translatedNetwork = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_10')

auto_nat_2 = AutoNatRule()
auto_nat_2.natType = 'STATIC'
auto_nat_2.originalNetwork = originalNetwork
auto_nat_2.translatedNetwork = translatedNetwork
api_service_fmc1.create(copy.deepcopy(auto_nat_2),
container_id=breakfix_nat_policy.id)

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[2]}' "):
log.info("Creating a network object 'obj_range_9' ")
nw_range_9 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_range_9')
api_service_fmc1.create(nw_range_9)
log.info("Creating a network range object 'obj_11' ")
nw_obj_11 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_11')
api_service_fmc1.create(nw_obj_11)

originalNetwork = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_range_9')
translatedNetwork = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_11')
auto_nat_3 = AutoNatRule()
auto_nat_3.natType = 'DYNAMIC'
auto_nat_3.originalNetwork = originalNetwork
auto_nat_3.translatedNetwork = translatedNetwork
api_service_fmc1.create(copy.deepcopy(auto_nat_3),
container_id=breakfix_nat_policy.id)

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[3]}' "):
log.info("Creating a network subnet object 'obj_subnet_5' ")
nw_subnet_5 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_subnet_5')
api_service_fmc1.create(nw_subnet_5)
log.info("Creating a network group object 'obj_grp_4' ")
nw_obj_grp_4 = store.get('file:{}'.format(datayaml),
root_object='NetworkGroup.obj_grp_4')
api_service_fmc1.create(nw_obj_grp_4)

originalNetwork = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_subnet_5')
translatedNetwork = api_service_fmc1.find_one(NetworkGroup,
lambda network:
network.name == 'obj_grp_4')

auto_nat_4 = AutoNatRule()
auto_nat_4.natType = 'DYNAMIC'
auto_nat_4.originalNetwork = originalNetwork
auto_nat_4.translatedNetwork = translatedNetwork
api_service_fmc1.create(copy.deepcopy(auto_nat_4),
container_id=breakfix_nat_policy.id)

log.info(banner("Deploying the changes in FMC"))


breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=parentDevice)
log.info(banner("Deployment completed"))
time.sleep(3)
except Exception as err:
self.failed(err)

with steps.start("Validating the show commands in FTD after deployment") as


substep:
try:
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name = 'auto_nat',

nat_detail=nat_detail_dict['auto_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

with substep.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
xlate_op = primary_ssh.conn.execute('show xlate detail')

except Exception as err:


self.failed(err)

@aetest.cleanup
def cleanup(self):
primary_ssh = cfg.get('primary_ssh')
try:
log.info("Disconnecting the SSH handle")
primary_ssh.conn.disconnect()
except Exception as err:
self.failed(err)

class TC_RenameNetworkObjectValidation():

"""
TC :19 To rename the object / service-objects names and check if the
used/mapped objects are preserved in the NAT rule.
"""

# @aetest.setup
def setup(self):
set_testcase_feature([Features77.feature4.value])
set_tims_testcase("Txw16474602r,Txw16474626r,Txw16474604r")

@aetest.test
def rename_network_object_validate(self, testbed, api_service_fmc1, datayaml):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
parentDevice = cfg.get('parentDevice')
primaryDevice = cfg.get('primaryDevice')
primary_ip = cfg.get('primaryDevice').name
primaryconf = ConfigProvider(testbed, primaryDevice.name)
primary_ssh = primaryconf.get_ssh_connection()
cfg.update({'primary_ssh': primary_ssh})
network_obj_host = cfg.get('network_obj_host')
host_obj = network_obj_host[0][0]
obj_rename= 'obj_rename'

with steps.start("Executing the breakfix CLI change"):


try:
log.info(banner(f"Validating the id of the created object
'{host_obj}'"))
primary_ssh.conn.go_to('fireos_state')
id_output = primary_ssh.conn.execute(f"show running-config object
id {host_obj}",timeout=120)
if re.search(host_obj,id_output,re.IGNORECASE) and \
re.search(network_obj_host[0][1],id_output,re.IGNORECASE):
log.info(id_output)

breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)
primary_ssh.conn.execute(f"object network {host_obj} rename
{obj_rename}", prompt='>|#', timeout=120)
primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute("Y", prompt='#')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')
else:
self.failed("Object details not showing properly")

except Exception as err:


self.failed(err)

with steps.start("Validating the OOB file present in FTD"):


try:
oob_file_result =
breakfix_lib.OOB_file_validation(ftd_ssh=primary_ssh)
if oob_file_result != True:
log.error("OOB file not Generated Properly")
self.failed("OOB file not Generated Properly")
except Exception as err:
self.failed(err)

with steps.start("Validating the changes in FTD") as substep:


try:
primary_ssh.conn.go_to('fireos_state')

with substep.start("Validating the obj id with old name"):


error_op = primary_ssh.conn.execute(f'show running-config
object id {host_obj}', timeout=120)
if re.search("ERROR", error_op, re.IGNORECASE):
log.info(banner("Old object name is renamed successfully"))
else:
self.failed("Old object name not removed properly")

with substep.start("Validating the obj id with new renamed"):


host_op = primary_ssh.conn.execute(f'show running-config object
id {obj_rename}', timeout=120)
if re.search(obj_rename, host_op, re.IGNORECASE) and \
re.search(network_obj_host[0][1], host_op,
re.IGNORECASE):
log.info(banner("New renamed object name is shown
properly"))
else:
self.failed("Old object name not removed properly")

with substep.start("Validating the changes in show nat commands"):


for cmd in ['show running-config nat',
'show nat detail']:
cmd_op = primary_ssh.conn.execute(cmd,timeout=120)
if re.search(obj_rename, cmd_op, re.IGNORECASE):
log.info(banner(f"New renamed object name is shown
properly in '{cmd}' command"))
else:
self.failed("Old object name not removed properly")
except Exception as err:
self.failed(err)

with steps.start("Detect Out of Band changes"):


try:
outof_change = store.get("file:{}".format(datayaml),
root_object='outofband.change5')
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is Detected"))
except Exception as err:
self.failed(err)

with steps.start("Acknowledging the Out of Band of changes in FMC"):


try:
outof_change.oobaction = 'ACKNOWLEDGE_OUT_OF_BAND_CHANGES'
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is acknowledged"))
except Exception as err:
self.failed(err)

with steps.start("Configuring the same changes in FMC"):


try:
obj = api_service_fmc1.find_one(NetworkObject, lambda network:
network.name == host_obj)
obj.name = obj_rename
api_service_fmc1.update(obj)

log.info(banner("Deploying the changes in FMC"))


breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=parentDevice)
log.info(banner("Deployment completed"))
time.sleep(3)
except Exception as err:
self.failed(err)
with steps.start("Validating the changes in FTD") as substep:
try:
primary_ssh.conn.go_to('fireos_state')

with substep.start("Validating the obj id with new renamed"):


host_op = primary_ssh.conn.execute(f'show running-config object
id {obj_rename}', timeout=120)
if re.search(obj_rename, host_op, re.IGNORECASE) and \
re.search(network_obj_host[0][1], host_op,
re.IGNORECASE):
log.info(banner("New renamed object name is shown
properly"))
else:
self.failed("Old object name not removed properly")

with substep.start("Validating the changes in show nat commands"):


for cmd in ['show running-config nat',
'show nat detail']:
cmd_op = primary_ssh.conn.execute(cmd, timeout=120)
if re.search(obj_rename, cmd_op, re.IGNORECASE):
log.info(banner(f"New renamed object name is shown
properly in '{cmd}' command"))
else:
self.failed("Old object name not removed properly")
except Exception as err:
self.failed(err)

@aetest.cleanup
def cleanup(self):
primary_ssh = cfg.get('primary_ssh')
try:
log.info("Disconnecting the SSH handle")
primary_ssh.conn.disconnect()
except Exception as err:
self.failed(err)

class TC_DeploymentFailureInBreakfixCLI():
"""
TC 20: To check OOB and health alert when deployment fails from FMC due to
CLI-EDIT Inprogress in FTD
"""

# @aetest.setup
def setup(self):
set_testcase_feature([Features77.feature4.value])
set_tims_testcase("Txw16474602r,Txw16474626r,Txw16474604r")

@aetest.test
def deployment_failure_breakfix_cli(self, testbed, api_service_fmc1, datayaml):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
parentDevice = cfg.get('parentDevice')
primaryDevice = cfg.get('primaryDevice')
primary_ip = cfg.get('primaryDevice').name
primaryconf = ConfigProvider(testbed, primaryDevice.name)
fmc = ConfigProvider(testbed, TestBedConstants.fmc1.value)
primary_ssh = primaryconf.get_ssh_connection()
fmc_ssh = fmc.get_ssh_connection()
cfg.update({'primary_ssh': primary_ssh,'fmc_ssh':fmc_ssh})

with steps.start("Entering into the breakfix mode CLI"):


breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)

with steps.start("Initiate one pending deployemnt in FMC"):

data_interface_name =
testbed.devices['sensor1'].custom.data_interface_name
data_interface = testbed.devices['sensor1'].custom.data_interface

phyIntf = api_service_fmc1.find_one(PhysicalInterface,
condition=lambda intfname:
intfname.name == data_interface,

container_id=deviceObjDict[primary_ip].id)
if phyIntf:
phyIntf.description = data_interface_name
api_service_fmc1.update(copy.deepcopy(phyIntf),
container_id=deviceObjDict[primary_ip].id)

try:
log.info(banner("Deploying the changes in FMC"))
breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=parentDevice)
except Exception as err:
log.info(banner("Deployment getting failed."))
log.info(err)
time.sleep(3)

log.info(banner("Getting the last deployment transaction id in FMC"))


fmc_ssh.conn.go_to('sudo_state')
get_transaction_id_cmd = "cat -n
/opt/CSCOpx/MDC/log/operation/usmsharedsvcs.log | grep transactionId | tail -1"
transaction_log =
fmc_ssh.conn.execute(get_transaction_id_cmd,timeout=120)
transid_match = re.search(r'"transactionId":(\d+)', transaction_log)
if transid_match:
transaction_id = transid_match.group(1)
log.info(banner(f"Transaction id : {transaction_id}"))
else:
log.error("Transaction ID not found.")
self.failed("Transaction ID not found.")

log.info(banner(f"Getting the transcript log from transaction id


{transaction_id} in deployment history in FMC"))

get_transcript_log_cmd = f"cat
/var/opt/CSCOpx/MDC/temp/{transaction_id}*transcript.txt"
transcript_log =
fmc_ssh.conn.execute(get_transcript_log_cmd,timeout=120)
if transcript_log:
if re.search('CLI-edit is in
progress',transcript_log,re.IGNORECASE):
log.info(banner("Deployment blocking with correct behaviour
i.e, breakix cli edit is inprogress...So passing the testcase"))
log.info("Exiting from the breakfix CLI and do the pending
deployment")

primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute("Y", prompt='#')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')
time.sleep(2)
log.info("Exited from the breakfix CLI")

log.info("Redeploy the device")


log.info(banner("Deploying the changes in FMC"))
breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=parentDevice)
log.info(banner("Deployment completed"))
time.sleep(3)
self.passed("Deployment blocking with correct behaviour i.e,
breakix cli edit is inprogress...So passing the testcase")
else:
log.error("Deployment failing with incorrect behaviour..Plzz
check the transcipt for more detail")
self.failed("Deployment failing with incorrect behaviour..Plzz
check the transcipt for more detail")
else:
log.error("Transcript log not found")
self.failed("Transcript log not found")

@aetest.cleanup
def cleanup(self):
primary_ssh = cfg.get('primary_ssh')
fmc_ssh = cfg.get('fmc_ssh')
try:
log.info("Disconnecting the SSH handle")
primary_ssh.conn.disconnect()
fmc_ssh.conn.disconnect()
except Exception as err:
self.failed(err)

class TC_ChangeNATRulePosition():

"""
TC :21 To change the position of nat rules , static and dynamic - FMC and FTD
TC: 22 To check the no form of NAT rule
TC: 23 To modify NAT rules configured , deployed from FMC and check for OOB
changes.
TC :24 To create a NAT , modify it twice and check for latest OOB changes
"""

# @aetest.setup
def setup(self):
set_testcase_feature([Features77.feature4.value])
set_tims_testcase("Txw16474602r,Txw16474626r,Txw16474604r")

@aetest.test
def change_nat_rule_position(self, testbed, api_service_fmc1, datayaml,fmc1):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
brkfx_nat_lib = BreakfixNatUtils()
parentDevice = cfg.get('parentDevice')
primaryDevice = cfg.get('primaryDevice')
primary_ip = cfg.get('primaryDevice').name
primaryconf = ConfigProvider(testbed, primaryDevice.name)
primary_ssh = primaryconf.get_ssh_connection()
cfg.update({'primary_ssh': primary_ssh})
rule_to_change = 'nat (any,any) source static obj_rename obj_rename'

with steps.start("Getting the already presented NAT rule positions in


device"):
try:
nat_position_dict =
brkfx_nat_lib.nat_rule_position(primary_ssh=primary_ssh)
before_position = nat_position_dict[rule_to_change]
log.info(banner(f"Position of the nat rule '{rule_to_change}'
before change is '{before_position}' "))

except Exception as err:


self.failed(err)

with steps.start(f"Changing the position of the rule '{rule_to_change}' in


FTD"):
try:
breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)
if rule_to_change in nat_position_dict.keys():
log.info("Deleting the rule in ftd")
primary_ssh.conn.execute(f"no {rule_to_change}",prompt='>|
#',timeout=120)
log.info(f"Changing the position of the nat rule
'{rule_to_change}' to 1")
updated_rule = rule_to_change.replace('nat (any,any)', 'nat
(any,any) 1')
primary_ssh.conn.execute(f"{updated_rule}",prompt='>|
#',timeout=120)

primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute("Y", prompt='#')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')

else:
self.failed("Nat rule is not present")
except Exception as err:
self.failed(err)

with steps.start("Validating the OOB file present in FTD"):


try:
oob_file_result =
breakfix_lib.OOB_file_validation(ftd_ssh=primary_ssh)
if oob_file_result != True:
log.error("OOB file not Generated Properly")
self.failed("OOB file not Generated Properly")
except Exception as err:
self.failed(err)

with steps.start("Validating the position of the nat rule after change"):


try:
nat_position_after_dict =
brkfx_nat_lib.nat_rule_position(primary_ssh=primary_ssh)
after_position = nat_position_after_dict[rule_to_change]
if before_position != after_position and after_position==1:
log.info(banner(f"Position of the nat rule '{rule_to_change}'
after change is '{after_position}'...So expected behaviour"))
else:
self.failed("Position is not changed properly")
except Exception as err:
self.failed(err)

with steps.start("Detect Out of Band changes"):


try:
outof_change = store.get("file:{}".format(datayaml),
root_object='outofband.change6')
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is Detected"))
except Exception as err:
self.failed(err)

with steps.start("Acknowledging the Out of Band of changes in FMC"):


try:
outof_change.oobaction = 'ACKNOWLEDGE_OUT_OF_BAND_CHANGES'
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is acknowledged"))
except Exception as err:
self.failed(err)

with steps.start("Configuring the same breakfix changes in FMC") as


substep:
try:
breakfix_nat_policy = api_service_fmc1.find_one(FtdNatPolicy,
lambda obj: obj.name == 'Breakfix_Nat')
log.info("Creating a network object host 'obj_13'")
obj_13 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_13')
api_service_fmc1.create(obj_13)

with substep.start(f"Deleting the nat rule '{rule_to_change}' in


FMC "):
nat_rule_created_above = cfg.get('tc_21_data')
moved_nat_rule = api_service_fmc1.find_one(ManualNatRule,
condition=lambda manaulrule:
(manaulrule.natType == "STATIC"),

container_id=nat_rule_created_above.id)

api_service_fmc1.delete(moved_nat_rule,
container_id=breakfix_nat_policy.id)
log.info("Nat Rule Deleted successfully")

with substep.start(f"Creating a NAT rule above the rule 1"):


data = create_manual_nat_with_query_params(fmc1=fmc1,
nat_policy=breakfix_nat_policy,

object_name_in_data_yaml=
"manual_nat_rules.tc21_rule",

targetIndex_value="1")

assert data
log.info("Nat Rule Created successfully")

log.info(banner("Deploying the changes in FMC"))


breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=parentDevice)
log.info(banner("Deployment completed"))
time.sleep(3)

except Exception as err:


self.failed(err)

with steps.start("Validating the position of the nat rule after change"):


try:
rule = "nat (any,any) source static obj_13 obj_13"
nat_position_dict =
brkfx_nat_lib.nat_rule_position(primary_ssh=primary_ssh)
position = nat_position_dict[rule]
if position == 1:
log.info(banner(f"Position of the nat rule '{rule_to_change}'
after change is '{position}'...So expected behaviour"))
else:
self.failed("Position is not changed properly")
except Exception as err:
self.failed(err)

@aetest.cleanup
def cleanup(self):
primary_ssh = cfg.get('primary_ssh')
try:
log.info("Disconnecting the SSH handle")
primary_ssh.conn.disconnect()
except Exception as err:
self.failed(err)

class TC_MappedInterfaceStaticNatCombinations():
"""
TC :25 [static_manual_Nat_src_] To create a NAT rule with
~ real , mapped interfaces.
~ real, mapped source address as object, any, interface options.
~ port translations need to be used using service objects.
Tc :26 [static_manual_Nat_src_dst] To create a NAT rule with
~ real , mapped interfaces.
~ real, mapped destination addresses as object and any respectively.
"""

# @aetest.setup
def setup(self):
set_testcase_feature([Features77.feature4.value])
set_tims_testcase("Txw16474602r,Txw16474626r,Txw16474604r")

@aetest.test
def mapped_interface_static_nat(self, testbed, api_service_fmc1, datayaml,
seczone):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
brkfx_nat_lib = BreakfixNatUtils()
parentDevice = cfg.get('parentDevice')
primaryDevice = cfg.get('primaryDevice')
primary_ip = cfg.get('primaryDevice').name
primaryconf = ConfigProvider(testbed, primaryDevice.name)
primary_ssh = primaryconf.get_ssh_connection()
cfg.update({'primary_ssh': primary_ssh})
nat_detail_dict = cfg.get('nat_detail_dict')
show_commands = cfg.get('show_commands')

network_obj = [['obj_14', '14.14.14.1'],


['obj_15', '15.15.15.1'],

['obj_range_11', '11.11.12.2', '11.11.12.40'],


['obj_range_12', '12.12.12.2', '12.12.12.40'],

['obj_subnet_6', '6.6.2.0', '255.255.255.0'],

['obj_serv_1', '9091']

cli_regex_dict = {f'nat ({seczone[0]},{seczone[1]}) source static


{network_obj[0][0]} {network_obj[2][0]} service any {network_obj[-1][0]}':
rf"source\s+static\s+{network_obj[0][0]}\s+
{network_obj[2][0]}\s+service\s+any\s+{network_obj[-1][0]}",
f'nat ({seczone[0]},{seczone[1]}) source static
{network_obj[3][0]} {network_obj[1][0]} destination static {network_obj[4][0]}
any':
rf"source\s+static\s+{network_obj[3][0]}\s+
{network_obj[1][0]}\s+destination\s+static\s+{network_obj[4][0]}\s+any"
}

breakfix_cli_args = [cli for cli in cli_regex_dict.keys()]

with steps.start("Executing the breakfix CLI change"):


try:
breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)

for host in network_obj[0:2]:


log.info(f"Creating the host network objects - {host[0]}")
primary_ssh.conn.execute(f'object network {host[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'host {host[1]}', prompt='>|#',
timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info("Network objects host created successfully")

for obj_range in network_obj[2:4]:


log.info(f"Creating the range network objects -
{obj_range[0]}")
primary_ssh.conn.execute(f'object network {obj_range[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'range {obj_range[1]}
{obj_range[2]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info("Network objects range created successfully")

log.info("Creating all the network subnet objects")


primary_ssh.conn.execute(f'object network {network_obj[4][0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'subnet {network_obj[4][1]}
{network_obj[4][2]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info(f"Network subnet object {network_obj[4][0]} created
successfully")

log.info("Creating all the network tcp service objects")


primary_ssh.conn.execute(f'object service {network_obj[5][0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'service tcp source eq {network_obj[5]
[1]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info(f"Network tcp service object {network_obj[5][0]} created
successfully")

for cli in breakfix_cli_args:


log.info(banner(f"Executing the nat cli - {cli}"))
primary_ssh.conn.execute(f'{cli}', prompt='>|#', timeout=120)
time.sleep(2)

primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute("Y", prompt='#')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')

except Exception as err:


self.failed(err)

with steps.start("Validating the OOB file present in FTD"):


try:
oob_file_result =
breakfix_lib.OOB_file_validation(ftd_ssh=primary_ssh)
if oob_file_result != True:
log.error("OOB file not Generated Properly")
self.failed("OOB file not Generated Properly")
except Exception as err:
self.failed(err)

with steps.start("Validating the show commands in FTD") as substep:


try:
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,
show_commands=show_commands,
key_name='before_nat',

nat_detail=nat_detail_dict['before_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

with substep.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
xlate_op = primary_ssh.conn.execute('show xlate detail')

except Exception as err:


self.failed(err)

with steps.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
primary_ssh.conn.execute('show xlate detail')

with steps.start("Detect Out of Band changes"):


try:
outof_change = store.get("file:{}".format(datayaml),
root_object='outofband.change7')
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is Detected"))
except Exception as err:
self.failed(err)

with steps.start("Acknowledging the Out of Band of changes in FMC"):


try:
outof_change.oobaction = 'ACKNOWLEDGE_OUT_OF_BAND_CHANGES'
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is acknowledged"))
except Exception as err:
self.failed(err)

with steps.start("Configuring the same breakfix changes in FMC") as


substep:
try:
breakfix_nat_policy = api_service_fmc1.find_one(FtdNatPolicy,
lambda obj: obj.name == 'Breakfix_Nat')

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[0]}' "):
log.info("Creating a network object 'obj_14' ")
nw_obj_14 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_14')
api_service_fmc1.create(nw_obj_14)

log.info("Creating a network range object 'obj_range_11' ")


nw_range_11 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_range_11')
api_service_fmc1.create(nw_range_11)

log.info("Creating a network service object 'obj_serv_1' ")


nw_serv_1 = store.get('file:{}'.format(datayaml),
root_object='protocol_port_object.protocol_port_src1_tcp')
api_service_fmc1.create(nw_serv_1)

sourceInterface = api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[0])
destinationInterface =
api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[1])
originalSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_14')
translatedSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_range_11')
translatedSourcePort =
api_service_fmc1.find_one(ProtocolPortObject,
lambda
protocol_port_object: protocol_port_object.name == 'obj_serv_1')

mapped_interface_nat_rule_1 = ManualNatRule()
mapped_interface_nat_rule_1.enabled = True
mapped_interface_nat_rule_1.natType = 'STATIC'
mapped_interface_nat_rule_1.sourceInterface = sourceInterface
mapped_interface_nat_rule_1.destinationInterface =
destinationInterface
mapped_interface_nat_rule_1.originalSource = originalSource
mapped_interface_nat_rule_1.translatedSource = translatedSource
mapped_interface_nat_rule_1.translatedSourcePort =
translatedSourcePort

api_service_fmc1.create(copy.deepcopy(mapped_interface_nat_rule_1),
container_id=breakfix_nat_policy.id)

assert mapped_interface_nat_rule_1 is not None

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[1]}' "):
log.info("Creating a network range object 'obj_range_12' ")
nw_range_12 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_range_12')
api_service_fmc1.create(nw_range_12)

log.info("Creating a network range object 'obj_15' ")


nw_obj_15 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_15')
api_service_fmc1.create(nw_obj_15)

log.info("Creating a network subnet object 'obj_subnet_6'")


nw_subnet_16 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_subnet_6')
api_service_fmc1.create(nw_subnet_16)

sourceInterface = api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[0])
destinationInterface =
api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[1])
originalSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_range_12')
translatedSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_15')

originalDestination = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_subnet_6')
translatedDestination =
api_service_fmc1.find_one(NetworkObject,
lambda
network: network.name == 'any-ipv4')

mapped_interface_nat_rule_2 = ManualNatRule()
mapped_interface_nat_rule_2.enabled = True
mapped_interface_nat_rule_2.natType = 'STATIC'
mapped_interface_nat_rule_2.sourceInterface = sourceInterface
mapped_interface_nat_rule_2.destinationInterface =
destinationInterface
mapped_interface_nat_rule_2.originalSource = originalSource
mapped_interface_nat_rule_2.translatedSource = translatedSource
mapped_interface_nat_rule_2.originalDestination =
originalDestination
mapped_interface_nat_rule_2.translatedDestination =
translatedDestination

api_service_fmc1.create(copy.deepcopy(mapped_interface_nat_rule_2),
container_id=breakfix_nat_policy.id)

assert mapped_interface_nat_rule_2 is not None

log.info(banner("Deploying the changes in FMC"))


breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=parentDevice)
log.info(banner("Deployment completed"))
time.sleep(3)

except Exception as err:


self.failed(err)

# with steps.start("Validating the show commands in FTD") as substep:


# try:
# result =
brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,
#
cli_regex_dict=cli_regex_dict,
#
breakfix_cli_args=breakfix_cli_args,
# steps=substep,
#
show_commands=show_commands,
#
key_name='before_nat',
#
nat_detail=nat_detail_dict['before_nat'])
# if result:
# log.info("All values properly configured in show command..")
# else:
# log.error("Values not properly showing in show commands..")
# self.failed("Values not properly showing in show commands..")
#
# with substep.start("Validate xlate id in FTD"):
# primary_ssh.conn.go_to('fireos_state')
# xlate_op = primary_ssh.conn.execute('show xlate detail')
#
# except Exception as err:
# self.failed(err)
#
# with steps.start("Validate xlate id in FTD"):
# primary_ssh.conn.go_to('fireos_state')
# primary_ssh.conn.execute('show xlate detail')

@aetest.cleanup
def cleanup(self):
primary_ssh = cfg.get('primary_ssh')
try:
log.info("Disconnecting the SSH handle")
primary_ssh.conn.disconnect()
except Exception as err:
self.failed(err)

class TC_MappedInterfaceDnsNatCombinations():
"""
TC :27 [static_manual_nat] To use the created xlate to rewrite DNS record
by creating a new rule.
Tc :28 [static_dynamic_manual_nat] To create manual NAT rule with the
mapped network obj/ obj-name for pat-pool along with dns to rewrite the DNS record.
/
Please cover dynamic manual nat nat (eth12_subintf_one,eth12_subintf_two)
source dynamic any object_one_nat_any dns
Also check if dns is not supported in pat-pool

"""

# @aetest.setup
def setup(self):
set_testcase_feature([Features77.feature4.value])
set_tims_testcase("Txw16474602r,Txw16474626r,Txw16474604r")

@aetest.test
def mapped_interface_dns_nat(self,testbed, api_service_fmc1, datayaml,
seczone):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
brkfx_nat_lib = BreakfixNatUtils()
parentDevice = cfg.get('parentDevice')
primaryDevice = cfg.get('primaryDevice')
primary_ip = cfg.get('primaryDevice').name
primaryconf = ConfigProvider(testbed, primaryDevice.name)
primary_ssh = primaryconf.get_ssh_connection()
cfg.update({'primary_ssh': primary_ssh})
nat_detail_dict = cfg.get('nat_detail_dict')
show_commands = cfg.get('show_commands')

network_obj = [['obj_16', '16.16.16.1'],

['obj_range_13', '13.13.12.2', '13.13.12.40'],


['obj_range_14', '14.14.12.2', '14.14.12.40'],

['obj_subnet_7', '7.7.3.0', '255.255.255.0'],


['obj_subnet_8', '8.8.3.0', '255.255.255.0'],

['obj_grp_5','obj_16', 'obj_range_13']

cli_regex_dict = {
f'nat ({seczone[0]},{seczone[1]}) source static {network_obj[-1][0]}
{network_obj[3][0]} dns':
rf"source\s+static\s+{network_obj[-1][0]}\s+{network_obj[3][0]}\
s+dns"
rf"| nat\s+\(\s*{seczone[0]}\s*,\s*{seczone[1]}\s*\)\s+source\
s+static\s+{network_obj[-1][0]}\s+{network_obj[3][0]}\s+dns",

f'nat ({seczone[0]},{seczone[1]}) source static any {network_obj[4][0]}


dns':
rf"| \(\s*{seczone[0]}\s*\)\s+to\s+\(\s*{seczone[1]}\s*\)\s+source\
s+static\s+any\s+{network_obj[4][0]}\s+dns"
rf"| nat\s+\(\s*{seczone[0]}\s*\)\s+to\s+\(\s*{seczone[1]}\s*\)\
s+source\s+static\s+any\s+{network_obj[4][0]}\s+dns",

f'nat ({seczone[0]},{seczone[1]}) source dynamic any {network_obj[2]


[0]} dns':
rf"nat\s+\({seczone[0]},{seczone[1]}\)\s+source\s+dynamic\s+any\s+
{network_obj[2][0]}\s+dns"
rf"| source\s+dynamic\s+any\s+{network_obj[2][0]}\s+dns"
}

breakfix_cli_args = [cli for cli in cli_regex_dict.keys()]

with steps.start("Executing the breakfix CLI change"):


try:
breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)

for host in network_obj[0:1]:


log.info(f"Creating the host network objects - {host[0]}")
primary_ssh.conn.execute(f'object network {host[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'host {host[1]}', prompt='>|#',
timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info("Network objects host created successfully")

for obj_range in network_obj[1:3]:


log.info(f"Creating the range network objects -
{obj_range[0]}")
primary_ssh.conn.execute(f'object network {obj_range[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'range {obj_range[1]}
{obj_range[2]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info("Network objects range created successfully")

for obj_subnet in network_obj[3:5]:


log.info(f"Creating the subnet network objects -
{obj_subnet[0]}")
primary_ssh.conn.execute(f'object network {obj_subnet[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'subnet {obj_subnet[1]}
{obj_subnet[2]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info("Network objects subnet created successfully")

log.info("Creating all the network group")


primary_ssh.conn.execute(f'object-group network {network_obj[5]
[0]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'network-object object {network_obj[5]
[1]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'network-object object {network_obj[5]
[2]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info(f"Network object group {network_obj[5][0]} created
successfully")

for cli in breakfix_cli_args:


log.info(banner(f"Executing the nat cli - {cli}"))
primary_ssh.conn.execute(f'{cli}', prompt='>|#', timeout=120)
time.sleep(2)

primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute("Y", prompt='#')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')

except Exception as err:


self.failed(err)

with steps.start("Validating the OOB file present in FTD"):


try:
oob_file_result =
breakfix_lib.OOB_file_validation(ftd_ssh=primary_ssh)
if oob_file_result != True:
log.error("OOB file not Generated Properly")
self.failed("OOB file not Generated Properly")
except Exception as err:
self.failed(err)

with steps.start("Validating the show commands in FTD") as substep:


try:
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,
breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name='before_nat',

nat_detail=nat_detail_dict['before_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

with substep.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
xlate_op = primary_ssh.conn.execute('show xlate detail')

except Exception as err:


self.failed(err)

with steps.start("Detect Out of Band changes"):


try:
outof_change = store.get("file:{}".format(datayaml),
root_object='outofband.change8')
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is Detected"))
except Exception as err:
self.failed(err)

with steps.start("Acknowledging the Out of Band of changes in FMC"):


try:
outof_change.oobaction = 'ACKNOWLEDGE_OUT_OF_BAND_CHANGES'
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is acknowledged"))
except Exception as err:
self.failed(err)

with steps.start("Configuring the same breakfix changes in FMC") as


substep:
try:
breakfix_nat_policy = api_service_fmc1.find_one(FtdNatPolicy,
lambda obj: obj.name == 'Breakfix_Nat')

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[0]}' "):
log.info("Creating a network object 'obj_grp_5' ")
nw_grp_5 = store.get('file:{}'.format(datayaml),
root_object='NetworkGroup.obj_grp_5')
api_service_fmc1.create(nw_grp_5)

log.info("Creating a network range object 'obj_subnet_7' ")


obj_subnet_7 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_subnet_7')
api_service_fmc1.create(obj_subnet_7)

sourceInterface = api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[0])
destinationInterface =
api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[1])
originalSource = api_service_fmc1.find_one(NetworkGroup,
lambda network:
network.name == 'obj_grp_5')
translatedSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_subnet_7')

mapped_interface_dns_rule_1 = ManualNatRule()
mapped_interface_dns_rule_1.enabled = True
mapped_interface_dns_rule_1.natType = 'STATIC'
mapped_interface_dns_rule_1.dns = True
mapped_interface_dns_rule_1.sourceInterface = sourceInterface
mapped_interface_dns_rule_1.destinationInterface =
destinationInterface
mapped_interface_dns_rule_1.originalSource = originalSource
mapped_interface_dns_rule_1.translatedSource = translatedSource

api_service_fmc1.create(copy.deepcopy(mapped_interface_dns_rule_1),
container_id=breakfix_nat_policy.id)

assert mapped_interface_dns_rule_1 is not None

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[1]}' "):

log.info("Creating a network range object 'obj_subnet_8' ")


obj_subnet_8 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_subnet_8')
api_service_fmc1.create(obj_subnet_8)

sourceInterface = api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[0])
destinationInterface =
api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[1])
originalSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'any-ipv4')
translatedSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_subnet_8')

mapped_interface_dns_rule_2 = ManualNatRule()
mapped_interface_dns_rule_2.enabled = True
mapped_interface_dns_rule_2.natType = 'STATIC'
mapped_interface_dns_rule_2.dns = True
mapped_interface_dns_rule_2.sourceInterface = sourceInterface
mapped_interface_dns_rule_2.destinationInterface =
destinationInterface
mapped_interface_dns_rule_2.originalSource = originalSource
mapped_interface_dns_rule_2.translatedSource = translatedSource

api_service_fmc1.create(copy.deepcopy(mapped_interface_dns_rule_2),
container_id=breakfix_nat_policy.id)

assert mapped_interface_dns_rule_2 is not None

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[2]}' "):

log.info("Creating a network range object 'obj_range_14' ")


obj_range_14 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_range_14')
api_service_fmc1.create(obj_range_14)

sourceInterface = api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[0])
destinationInterface =
api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[1])
originalSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'any-ipv4')
translatedSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_range_14')

mapped_interface_dns_rule_3 = ManualNatRule()
mapped_interface_dns_rule_3.enabled = True
mapped_interface_dns_rule_3.natType = 'DYNAMIC'
mapped_interface_dns_rule_3.dns = True
mapped_interface_dns_rule_3.unidirectional = True
mapped_interface_dns_rule_3.sourceInterface = sourceInterface
mapped_interface_dns_rule_3.destinationInterface =
destinationInterface
mapped_interface_dns_rule_3.originalSource = originalSource
mapped_interface_dns_rule_3.translatedSource = translatedSource

api_service_fmc1.create(copy.deepcopy(mapped_interface_dns_rule_3),container_id=bre
akfix_nat_policy.id)

assert mapped_interface_dns_rule_3 is not None

log.info(banner("Deploying the changes in FMC"))


breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=parentDevice)
log.info(banner("Deployment completed"))
time.sleep(3)

except Exception as err:


self.failed(err)

with steps.start("Validating the show commands in FTD") as substep:


try:
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,
cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name='before_nat',

nat_detail=nat_detail_dict['before_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

with substep.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
xlate_op = primary_ssh.conn.execute('show xlate detail')

except Exception as err:


self.failed(err)

with steps.start("Validate the dns support not in dynamic pat pool"):


breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)

dns_op = primary_ssh.conn.execute('nat source dynamic any pat-pool


any ?',timeout=120, prompt='>|#|:')
data = breakfix_lib.cli_extract(data=dns_op)
if 'dns' not in data:
log.info(banner(f"DNS is not supported in dynamic PAT Pool"))
else:
self.failed("DNS is showing in PAT POOL")

primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')

@aetest.cleanup
def cleanup(self):
primary_ssh = cfg.get('primary_ssh')
try:
log.info("Disconnecting the SSH handle")
primary_ssh.conn.disconnect()
except Exception as err:
self.failed(err)

class TC_MappedInterfaceDnsAutoNat():
"""
TC :29 [dynamic_auto_nat] To create auto NAT rule with the mapped IP
address along with dns to rewrite the DNS record.
"""

# @aetest.setup
def setup(self):
set_testcase_feature([Features77.feature4.value])
set_tims_testcase("Txw16474602r,Txw16474626r,Txw16474604r")

@aetest.test
def mapped_interface_dns_auto_nat(self, testbed, api_service_fmc1, datayaml,
seczone):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
brkfx_nat_lib = BreakfixNatUtils()
parentDevice = cfg.get('parentDevice')
primaryDevice = cfg.get('primaryDevice')
primary_ip = cfg.get('primaryDevice').name
primaryconf = ConfigProvider(testbed, primaryDevice.name)
primary_ssh = primaryconf.get_ssh_connection()
cfg.update({'primary_ssh': primary_ssh})
nat_detail_dict = cfg.get('nat_detail_dict')
show_commands = cfg.get('show_commands')

network_obj = [['obj_17', '17.17.17.1'],


['obj_range_15', '15.15.15.2', '15.15.15.40'],
]

cli_regex_dict = {
f'nat ({seczone[0]},{seczone[1]}) dynamic {network_obj[1][0]} dns':
rf"nat\s+\({seczone[0]},{seczone[1]}\)\s+dynamic\s+{network_obj[1]
[0]}\s+dns"
rf"| object\s+network\s+{network_obj[0][0]}\s*nat\s*\({seczone[0]},
{seczone[1]}\)\s*dynamic\s*{network_obj[1][0]}\s+dns"
rf"| \({seczone[0]}\)\s+to\s+\({seczone[1]}\)\s+source\s+dynamic\s+
{network_obj[0][0]}\s+{network_obj[1][0]}\s+dns"
}
auto_nat_objs =[network_obj[0]]
breakfix_cli_args = [cli for cli in cli_regex_dict.keys()]

with steps.start("Executing the breakfix CLI change"):


try:
breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)

log.info(f"Creating the host network objects - {network_obj[0]


[0]}")
primary_ssh.conn.execute(f'object network {network_obj[0][0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'host {network_obj[0][1]}', prompt='>|#',
timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)

log.info(f"Creating the range network objects - {network_obj[1]


[0]}")
primary_ssh.conn.execute(f'object network {network_obj[1][0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'range {network_obj[1][1]}
{network_obj[1][2]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)

for objs, cli in zip(auto_nat_objs, breakfix_cli_args):


log.info(banner(f"Executing the auto-nat cli - {cli}"))
primary_ssh.conn.execute(f' object network {objs[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'{cli}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute("Y", prompt='#')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')

except Exception as err:


self.failed(err)

with steps.start("Validating the OOB file present in FTD"):


try:
oob_file_result =
breakfix_lib.OOB_file_validation(ftd_ssh=primary_ssh)
if oob_file_result != True:
log.error("OOB file not Generated Properly")
self.failed("OOB file not Generated Properly")
except Exception as err:
self.failed(err)

with steps.start("Validating the show commands in FTD") as substep:


try:
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name='auto_nat',

nat_detail=nat_detail_dict['auto_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

with substep.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
xlate_op = primary_ssh.conn.execute('show xlate detail')

except Exception as err:


self.failed(err)

with steps.start("Detect Out of Band changes"):


try:
outof_change = store.get("file:{}".format(datayaml),
root_object='outofband.change9')
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is Detected"))
except Exception as err:
self.failed(err)

with steps.start("Acknowledging the Out of Band of changes in FMC"):


try:
outof_change.oobaction = 'ACKNOWLEDGE_OUT_OF_BAND_CHANGES'
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is acknowledged"))
except Exception as err:
self.failed(err)

with steps.start("Configuring the same breakfix changes in FMC") as


substep:
try:
breakfix_nat_policy = api_service_fmc1.find_one(FtdNatPolicy,
lambda obj: obj.name == 'Breakfix_Nat')

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[0]}' "):
log.info("Creating a network object 'obj_8' ")
obj_17 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_17')
api_service_fmc1.create(obj_17)
log.info("Creating a network range object 'obj_9' ")
obj_range_15 = store.get('file:{}'.format(datayaml),
root_object='networks.obj_range_15')
api_service_fmc1.create(obj_range_15)

sourceInterface = api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[0])
destinationInterface =
api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[1])
originalNetwork = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_17')
translatedNetwork = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'obj_range_15')

mapped_int_auto_nat_rule = AutoNatRule()
mapped_int_auto_nat_rule.natType = 'DYNAMIC'
mapped_int_auto_nat_rule.dns = True
mapped_int_auto_nat_rule.sourceInterface = sourceInterface
mapped_int_auto_nat_rule.destinationInterface =
destinationInterface
mapped_int_auto_nat_rule.originalNetwork = originalNetwork
mapped_int_auto_nat_rule.translatedNetwork = translatedNetwork

api_service_fmc1.create(copy.deepcopy(mapped_int_auto_nat_rule),
container_id=breakfix_nat_policy.id)

log.info(banner("Deploying the changes in FMC"))


breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=parentDevice)
log.info(banner("Deployment completed"))
time.sleep(3)

except Exception as err:


self.failed(err)
with steps.start("Validating the show commands in FTD") as substep:
try:
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name='auto_nat',

nat_detail=nat_detail_dict['auto_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

with substep.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
xlate_op = primary_ssh.conn.execute('show xlate detail')

except Exception as err:


self.failed(err)

@aetest.cleanup
def cleanup(self):
primary_ssh = cfg.get('primary_ssh')
try:
log.info("Disconnecting the SSH handle")
primary_ssh.conn.disconnect()
except Exception as err:
self.failed(err)

class TC_NetworkGroupNatCombination():
"""
TC :30 [static_PAT_manual_NAT_src_only] To configure a static PAT rule with
~ real, mapped interfaces.
~ real and mapped source addressess as a single host in the form of
objects.
~ group of IPs to mapped group of Ips
"""

# @aetest.setup
def setup(self):
set_testcase_feature([Features77.feature4.value])
set_tims_testcase("Txw16474602r,Txw16474626r,Txw16474604r")

@aetest.test
def network_group_nat_rule(self, testbed, api_service_fmc1, datayaml, seczone):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
brkfx_nat_lib = BreakfixNatUtils()
parentDevice = cfg.get('parentDevice')
primaryDevice = cfg.get('primaryDevice')
primary_ip = cfg.get('primaryDevice').name
primaryconf = ConfigProvider(testbed, primaryDevice.name)
primary_ssh = primaryconf.get_ssh_connection()
cfg.update({'primary_ssh': primary_ssh})
nat_detail_dict = cfg.get('nat_detail_dict')
show_commands = cfg.get('show_commands')

network_obj = [['obj_range_16', '16.16.16.2', '16.16.16.40'],


['obj_range_17', '17.17.17.2', '17.17.17.40'],

['obj_subnet_9', '9.9.3.0','255.255.255.0'],
['obj_subnet_10', '10.10.3.0','255.255.255.0'],

['obj_grp_6','obj_subnet_9', 'obj_range_16'],
['obj_grp_7', 'obj_subnet_10', 'obj_range_17'],

cli_regex_dict = {
f'nat ({seczone[0]},{seczone[1]}) source static {network_obj[4][0]}
{network_obj[5][0]}':
rf"nat\s*\(\s*{seczone[0]}\s*,\s*{seczone[1]}\s*\)\s*source\
s+static\s+{network_obj[4][0]}\s+{network_obj[5][0]}"
rf"| \(\s*{seczone[0]}\s*\)\s+to\s+\(\s*{seczone[1]}\s*\)\s+source\
s+static\s+{network_obj[4][0]}\s+{network_obj[5][0]}"
rf"| source\s+static\s+{network_obj[4][0]}\s+{network_obj[5][0]}"

breakfix_cli_args = [cli for cli in cli_regex_dict.keys()]

with steps.start("Executing the breakfix CLI change"):


try:
breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)

for obj_range in network_obj[0:2]:


log.info(f"Creating the range network objects -
{obj_range[0]}")
primary_ssh.conn.execute(f'object network {obj_range[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'range {obj_range[1]}
{obj_range[2]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info("Network objects range created successfully")

for obj_subnet in network_obj[2:4]:


log.info(f"Creating the subnet network objects -
{obj_subnet[0]}")
primary_ssh.conn.execute(f'object network {obj_subnet[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'subnet {obj_subnet[1]}
{obj_subnet[2]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info("Network objects subnet created successfully")

for obj_grp in network_obj[4:6]:


primary_ssh.conn.execute(f'object-group network {obj_grp[0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'network-object object {obj_grp[1]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'network-object object {obj_grp[2]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info(f"Network object group {obj_grp[0]} created
successfully")

for cli in breakfix_cli_args:


log.info(banner(f"Executing the nat cli - {cli}"))
primary_ssh.conn.execute(f'{cli}', prompt='>|#', timeout=120)
time.sleep(2)

primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute("Y", prompt='#')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')

except Exception as err:


self.failed(err)

with steps.start("Validating the OOB file present in FTD"):


try:
oob_file_result =
breakfix_lib.OOB_file_validation(ftd_ssh=primary_ssh)
if oob_file_result != True:
log.error("OOB file not Generated Properly")
self.failed("OOB file not Generated Properly")
except Exception as err:
self.failed(err)

with steps.start("Validating the show commands in FTD") as substep:


try:
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name='before_nat',

nat_detail=nat_detail_dict['before_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

with substep.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
xlate_op = primary_ssh.conn.execute('show xlate detail')

except Exception as err:


self.failed(err)
with steps.start("Detect Out of Band changes"):
try:
outof_change = store.get("file:{}".format(datayaml),
root_object='outofband.change10')
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is Detected"))
except Exception as err:
self.failed(err)

with steps.start("Acknowledging the Out of Band of changes in FMC"):


try:
outof_change.oobaction = 'ACKNOWLEDGE_OUT_OF_BAND_CHANGES'
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is acknowledged"))
except Exception as err:
self.failed(err)

with steps.start("Configuring the same breakfix changes in FMC") as


substep:
try:
breakfix_nat_policy = api_service_fmc1.find_one(FtdNatPolicy,
lambda obj: obj.name == 'Breakfix_Nat')

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[0]}' "):
log.info("Creating a network object group 'obj_grp_6'")
obj_grp_6 = store.get('file:{}'.format(datayaml),
root_object='NetworkGroup.obj_grp_6')
api_service_fmc1.create(obj_grp_6)

log.info("Creating a network object group 'obj_grp_7'")


obj_grp_7 = store.get('file:{}'.format(datayaml),
root_object='NetworkGroup.obj_grp_7')
api_service_fmc1.create(obj_grp_7)

sourceInterface = api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[0])
destinationInterface =
api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[1])
originalSource = api_service_fmc1.find_one(NetworkGroup,
lambda network:
network.name == 'obj_grp_6')
translatedSource = api_service_fmc1.find_one(NetworkGroup,
lambda network:
network.name == 'obj_grp_7')
nat_rule_grp = ManualNatRule()
nat_rule_grp.enabled = 'True'
nat_rule_grp.natType = 'STATIC'
nat_rule_grp.sourceInterface = sourceInterface
nat_rule_grp.destinationInterface = destinationInterface
nat_rule_grp.originalSource = originalSource
nat_rule_grp.translatedSource = translatedSource
api_service_fmc1.create(copy.deepcopy(nat_rule_grp),
container_id=breakfix_nat_policy.id)

log.info(banner("Deploying the changes in FMC"))


breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=parentDevice)
log.info(banner("Deployment completed"))
time.sleep(3)
except Exception as err:
self.failed(err)

with steps.start("Validating the show commands in FTD") as substep:


try:
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name='before_nat',

nat_detail=nat_detail_dict['before_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

with substep.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
xlate_op = primary_ssh.conn.execute('show xlate detail')

except Exception as err:


self.failed(err)

@aetest.cleanup
def cleanup(self):
primary_ssh = cfg.get('primary_ssh')
try:
log.info("Disconnecting the SSH handle")
primary_ssh.conn.disconnect()
except Exception as err:
self.failed(err)

class TC_NegativeTestcases():
"""
TC :31 To map a non-existant object to the NAT rule
TC :32 To map an empty obj to an object-group
"""

# @aetest.setup
def setup(self):
set_testcase_feature([Features77.feature4.value])
set_tims_testcase("Txw16474602r,Txw16474626r,Txw16474604r")

@aetest.test
def map_non_existant_object(self, testbed, api_service_fmc1,datayaml):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
parentDevice = cfg.get('parentDevice')
primaryDevice = cfg.get('primaryDevice')
primary_ip = cfg.get('primaryDevice').name
primaryconf = ConfigProvider(testbed, primaryDevice.name)
primary_ssh = primaryconf.get_ssh_connection()
cfg.update({'primary_ssh': primary_ssh})

with steps.start("Mapping a non existant object to a nat rule"):


breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)

err_obj_op = primary_ssh.conn.execute('nat source static any


obj_nonexist',prompt='>|#|:',timeout=120)
expected_err = "ERROR: obj_nonexist doesn't match an existing object or
object-group"
if re.search(expected_err,err_obj_op,re.IGNORECASE):
log.info(banner(expected_err))
else:
log.error("Not a expected behaviour")
self.failed()

with steps.start("Mapping an empty object to a nat rule"):


log.info("Creating an empty object")
primary_ssh.conn.execute('object network empty_obj',prompt='>|
#|:',timeout=120)
primary_ssh.conn.execute('exit',prompt='>|#|:',timeout=120)
empty_error_op = primary_ssh.conn.execute('nat source static any
empty_obj',prompt='>|#|:',timeout=120)
if re.search(r"ERROR:\s+empty\s+object/object-group\(s\)\s+detected\.",
empty_error_op,re.IGNORECASE):
log.info(banner(expected_err))
else:
log.error("Not a expected behaviour")
self.failed()

primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute("Y", prompt='#')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')

with steps.start("Detect Out of Band changes"):


try:
outof_change = store.get("file:{}".format(datayaml),
root_object='outofband.change11')
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is Detected"))
except Exception as err:
self.failed(err)

with steps.start("Acknowledging the Out of Band of changes in FMC"):


try:
outof_change.oobaction = 'ACKNOWLEDGE_OUT_OF_BAND_CHANGES'
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is acknowledged"))
except Exception as err:
self.failed(err)

@aetest.cleanup
def cleanup(self):
primary_ssh = cfg.get('primary_ssh')
try:
log.info("Disconnecting the SSH handle")
primary_ssh.conn.disconnect()
except Exception as err:
self.failed(err)

class TC_RoundRobinNatRule():
"""
TC :33 To configure NAT using round robin
"""

# @aetest.setup
def setup(self):
set_testcase_feature([Features77.feature4.value])
set_tims_testcase("Txw16474602r,Txw16474626r,Txw16474604r")

@aetest.test
def round_robin_rule(self, testbed, api_service_fmc1, datayaml,seczone):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
brkfx_nat_lib = BreakfixNatUtils()
parentDevice = cfg.get('parentDevice')
primaryDevice = cfg.get('primaryDevice')
primary_ip = cfg.get('primaryDevice').name
primaryconf = ConfigProvider(testbed, primaryDevice.name)
primary_ssh = primaryconf.get_ssh_connection()
cfg.update({'primary_ssh': primary_ssh})
nat_detail_dict = cfg.get('nat_detail_dict')
show_commands = cfg.get('show_commands')

network_obj = [['obj_range_18', '18.18.18.2', '18.18.18.40'],


['obj_18','18.18.18.18'],
['obj_grp_8', 'obj_18', 'obj_range_18']
]

cli_regex_dict = {f'nat ({seczone[0]},{seczone[1]}) source dynamic any pat-


pool {network_obj[-1][0]} round-robin':
rf"nat\s+\({seczone[0]},{seczone[1]}\)\s+"rf"source\
s+dynamic\s+any\s+pat-pool\s+{network_obj[-1][0]}\s+round-robin"
rf"| source\s+dynamic\s+any\s+pat-pool\s+
{network_obj[-1][0]}\s+round-robin"
rf"| \({seczone[0]}\)\s+to\s+\({seczone[1]}\)\
s+source\s+dynamic\s+any\s+pat-pool\s+{network_obj[-1][0]}\s+round-robin"}

breakfix_cli_args = [cli for cli in cli_regex_dict.keys()]

with steps.start("Executing the breakfix CLI change"):


try:
breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)

log.info(f"Creating the range network objects - {network_obj[0]


[0]}")
primary_ssh.conn.execute(f'object network {network_obj[0][0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'range {network_obj[0][1]}
{network_obj[0][2]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info("Network objects range created successfully")

log.info(f"Creating the host network objects - {network_obj[1]


[0]}")
primary_ssh.conn.execute(f'object network {network_obj[1][0]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'object host {network_obj[1][1]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info("Network objects host created successfully")

primary_ssh.conn.execute(f'object-group network {network_obj[-1]


[0]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'network-object object {network_obj[-1]
[1]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'network-object object {network_obj[-1]
[2]}', prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'exit', prompt='>|#', timeout=120)
time.sleep(2)
log.info(f"Network object group {network_obj[-1][0]} created
successfully")

for cli in breakfix_cli_args:


log.info(banner(f"Executing the nat cli - {cli}"))
primary_ssh.conn.execute(f'{cli}', prompt='>|#', timeout=120)
time.sleep(2)

primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute("Y", prompt='#')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')

except Exception as err:


self.failed(err)

with steps.start("Validating the OOB file present in FTD"):


try:
oob_file_result =
breakfix_lib.OOB_file_validation(ftd_ssh=primary_ssh)
if oob_file_result != True:
log.error("OOB file not Generated Properly")
self.failed("OOB file not Generated Properly")
except Exception as err:
self.failed(err)

with steps.start("Validating the show commands in FTD") as substep:


try:
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name='before_nat',

nat_detail=nat_detail_dict['before_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

with substep.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
xlate_op = primary_ssh.conn.execute('show xlate detail')

except Exception as err:


self.failed(err)

with steps.start("Detect Out of Band changes"):


try:
outof_change = store.get("file:{}".format(datayaml),
root_object='outofband.change12')
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is Detected"))
except Exception as err:
self.failed(err)

with steps.start("Acknowledging the Out of Band of changes in FMC"):


try:
outof_change.oobaction = 'ACKNOWLEDGE_OUT_OF_BAND_CHANGES'
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is acknowledged"))
except Exception as err:
self.failed(err)

with steps.start("Configuring the same breakfix changes in FMC") as


substep:
try:
breakfix_nat_policy = api_service_fmc1.find_one(FtdNatPolicy,
lambda obj: obj.name == 'Breakfix_Nat')

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[0]}' "):
log.info("Creating a network object 'obj_grp_8' ")
obj_grp_8 = store.get('file:{}'.format(datayaml),
root_object='NetworkGroup.obj_grp_8')
api_service_fmc1.create(obj_grp_8)

sourceInterface = api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[0])
destinationInterface =
api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[1])
originalSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'any-ipv4')

round_robin_rule = ManualNatRule()
patOptions = FtdPatFragment(patPoolAddress=obj_grp_8,
roundRobin=True)
round_robin_rule.enabled = True
round_robin_rule.natType = 'DYNAMIC'
round_robin_rule.sourceInterface = sourceInterface
round_robin_rule.destinationInterface = destinationInterface
round_robin_rule.originalSource = originalSource
round_robin_rule.patOptions = patOptions
round_robin_rule.unidirectional = True

api_service_fmc1.create(copy.deepcopy(round_robin_rule),container_id=breakfix_nat_p
olicy.id)

assert round_robin_rule is not None

log.info(banner("Deploying the changes in FMC"))


breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=parentDevice)
log.info(banner("Deployment completed"))
time.sleep(3)

except Exception as err:


self.failed(err)

with steps.start("Validating the show commands in FTD") as substep:


try:
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name='before_nat',

nat_detail=nat_detail_dict['before_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

with substep.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
xlate_op = primary_ssh.conn.execute('show xlate detail')

except Exception as err:


self.failed(err)
@aetest.cleanup
def cleanup(self):
primary_ssh = cfg.get('primary_ssh')
try:
log.info("Disconnecting the SSH handle")
primary_ssh.conn.disconnect()
except Exception as err:
self.failed(err)

class TC_UnidirectionalNatRule():
"""
TC :34 To create a NAT rule with unidirectional
"""

# @aetest.setup
def setup(self):
set_testcase_feature([Features77.feature4.value])
set_tims_testcase("Txw16474602r,Txw16474626r,Txw16474604r")

@aetest.test
def unidirectional_nat_rule(self, testbed, api_service_fmc1, datayaml,
seczone):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
brkfx_nat_lib = BreakfixNatUtils()
parentDevice = cfg.get('parentDevice')
primaryDevice = cfg.get('primaryDevice')
primary_ip = cfg.get('primaryDevice').name
primaryconf = ConfigProvider(testbed, primaryDevice.name)
primary_ssh = primaryconf.get_ssh_connection()
cfg.update({'primary_ssh': primary_ssh})
nat_detail_dict = cfg.get('nat_detail_dict')
show_commands = cfg.get('show_commands')

cli_regex_dict = {
f'nat ({seczone[0]},{seczone[1]}) source static any any
unidirectional':
rf"nat\s+\(({seczone[0]},{seczone[1]})\)\s+source\s+static\s+any\
s+any\s+unidirectional"
rf"| source\s+static\s+any\s+any\s+\s+unidirectional"
rf"| \({seczone[0]}\)\s+to\s+\({seczone[1]}\)\s+source\s+static\
s+any\s+any\s+unidirectional"}

breakfix_cli_args = [cli for cli in cli_regex_dict.keys()]

with steps.start("Executing the breakfix CLI change"):


try:
breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)

for cli in breakfix_cli_args:


log.info(banner(f"Executing the nat cli - {cli}"))
primary_ssh.conn.execute(f'{cli}', prompt='>|#', timeout=120)
time.sleep(2)
primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute("Y", prompt='#')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')

except Exception as err:


self.failed(err)

with steps.start("Validating the OOB file present in FTD"):


try:
oob_file_result =
breakfix_lib.OOB_file_validation(ftd_ssh=primary_ssh)
if oob_file_result != True:
log.error("OOB file not Generated Properly")
self.failed("OOB file not Generated Properly")
except Exception as err:
self.failed(err)

with steps.start("Validating the show commands in FTD") as substep:


try:
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name='before_nat',

nat_detail=nat_detail_dict['before_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

with substep.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
xlate_op = primary_ssh.conn.execute('show xlate detail')

except Exception as err:


self.failed(err)

with steps.start("Detect Out of Band changes"):


try:
outof_change = store.get("file:{}".format(datayaml),
root_object='outofband.change13')
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is Detected"))
except Exception as err:
self.failed(err)

with steps.start("Acknowledging the Out of Band of changes in FMC"):


try:
outof_change.oobaction = 'ACKNOWLEDGE_OUT_OF_BAND_CHANGES'
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is acknowledged"))
except Exception as err:
self.failed(err)

with steps.start("Configuring the same breakfix changes in FMC") as


substep:
try:
breakfix_nat_policy = api_service_fmc1.find_one(FtdNatPolicy,
lambda obj: obj.name == 'Breakfix_Nat')

with substep.start(f"Configuring the NAT rule in FMC for


'{breakfix_cli_args[0]}' "):

sourceInterface = api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[0])
destinationInterface =
api_service_fmc1.find_one(SecurityZoneObject,
lambda zone:
zone.name == seczone[1])
originalSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == 'any-ipv4')
translatedSource = api_service_fmc1.find_one(NetworkObject,
lambda
network: network.name == 'any-ipv4')

unidirectional_rule = ManualNatRule()
unidirectional_rule.enabled = True
unidirectional_rule.natType = 'STATIC'
unidirectional_rule.sourceInterface = sourceInterface
unidirectional_rule.destinationInterface = destinationInterface
unidirectional_rule.originalSource = originalSource
unidirectional_rule.translatedSource =translatedSource
unidirectional_rule.unidirectional = True

api_service_fmc1.create(copy.deepcopy(unidirectional_rule),
container_id=breakfix_nat_policy.id)

assert unidirectional_rule is not None

log.info(banner("Deploying the changes in FMC"))


breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=parentDevice)
log.info(banner("Deployment completed"))
time.sleep(3)

except Exception as err:


self.failed(err)

with steps.start("Validating the show commands in FTD") as substep:


try:
result = brkfx_nat_lib.show_nat_validations(ftd_handle=primary_ssh,

cli_regex_dict=cli_regex_dict,

breakfix_cli_args=breakfix_cli_args,
steps=substep,

show_commands=show_commands,
key_name='before_nat',

nat_detail=nat_detail_dict['before_nat'])
if result:
log.info("All values properly configured in show command..")
else:
log.error("Values not properly showing in show commands..")
self.failed("Values not properly showing in show commands..")

with substep.start("Validate xlate id in FTD"):


primary_ssh.conn.go_to('fireos_state')
xlate_op = primary_ssh.conn.execute('show xlate detail')

except Exception as err:


self.failed(err)

@aetest.cleanup
def cleanup(self):
primary_ssh = cfg.get('primary_ssh')
try:
log.info("Disconnecting the SSH handle")
primary_ssh.conn.disconnect()
except Exception as err:
self.failed(err)

class TC_WriteMemValidation():
"""
TC :35 To check the running, startup config after performing wr mem and exit
from breakfix mode
"""

#@aetest.setup
def setup(self):
set_testcase_feature([Features77.feature4.value])
set_tims_testcase("Txw16474602r,Txw16474626r,Txw16474604r")

@aetest.test
def write_mem_validation(self, testbed, api_service_fmc1, datayaml):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
brkfx_nat_lib = BreakfixNatUtils()
parentDevice = cfg.get('parentDevice')
primaryDevice = cfg.get('primaryDevice')
primary_ip = cfg.get('primaryDevice').name
primaryconf = ConfigProvider(testbed, primaryDevice.name)
primary_ssh = primaryconf.get_ssh_connection()
cfg.update({'primary_ssh': primary_ssh})
nat_detail_dict = cfg.get('nat_detail_dict')
show_commands = cfg.get('show_commands')
network_obj = ['obj_11','obj_subnet_10']

nat_cli = f'nat source static {network_obj[0]} {network_obj[1]}'

with steps.start("Creating one NAT rule in Breakfix mode and give 'N'
option for write mem"):
breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)

log.info(banner(f"Executing the nat cli - {nat_cli}"))


primary_ssh.conn.execute(f'{nat_cli}', prompt='>|#', timeout=120)
time.sleep(2)

log.info("Giving 'N' in exit")


primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute("N", prompt='>|#|:')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')

with steps.start("Validating the OOB file present in FTD"):


try:
oob_file_result =
breakfix_lib.OOB_file_validation(ftd_ssh=primary_ssh)
if oob_file_result != True:
log.error("OOB file not Generated Properly")
self.failed("OOB file not Generated Properly")
except Exception as err:
self.failed(err)

with steps.start("Verifying the confiigs output in startup and running-


config in FTD"):
try:
primary_ssh.conn.go_to('fireos_state')
log.info(banner("Output in running-config command"))
running_config_op = primary_ssh.conn.execute('show running-config
nat',timeout=120)
log.info(banner("Output in startup-config command"))
startup_config_op = primary_ssh.conn.execute('show startup-config |
grep nat',timeout=120)

pattern = rf"source\s+static\s+{network_obj[0]}\s+{network_obj[1]}"

if re.search(pattern,running_config_op,re.IGNORECASE) and \
not re.search(pattern,startup_config_op,re.IGNORECASE):
log.info(banner(f"After giving write mem 'N' '{nat_cli}''
output showing in running-config and not shwoing in startup-config in FTD"))
else:
self.failed("Not expected behaviour")

except Exception as err:


self.failed(err)

with steps.start("Detect Out of Band changes"):


try:
outof_change = store.get("file:{}".format(datayaml),
root_object='outofband.change14')
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is Detected"))
except Exception as err:
self.failed(err)

with steps.start("Acknowledging the Out of Band of changes in FMC"):


try:
outof_change.oobaction = 'ACKNOWLEDGE_OUT_OF_BAND_CHANGES'
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is acknowledged"))
except Exception as err:
self.failed(err)

with steps.start("Configuring the same breakfix changes in FMC") as


substep:
try:
breakfix_nat_policy = api_service_fmc1.find_one(FtdNatPolicy,
lambda obj: obj.name == 'Breakfix_Nat')

with substep.start(f"Configuring the NAT rule in FMC for


'{nat_cli}' "):
originalSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == network_obj[0])

translatedSource = api_service_fmc1.find_one(NetworkObject,
lambda network:
network.name == network_obj[1])
nat_rule = ManualNatRule()
nat_rule.enabled = True
nat_rule.natType = 'STATIC'
nat_rule.originalSource = originalSource
nat_rule.translatedSource = translatedSource
nat_rule.unidirectional = True

api_service_fmc1.create(copy.deepcopy(nat_rule),
container_id=breakfix_nat_policy.id)
assert nat_rule is not None

log.info(banner("Deploying the changes in FMC"))


breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=parentDevice)
log.info(banner("Deployment completed"))
time.sleep(3)

except Exception as err:


self.failed(err)

@aetest.cleanup
def cleanup(self):
primary_ssh = cfg.get('primary_ssh')
try:
log.info("Disconnecting the SSH handle")
primary_ssh.conn.disconnect()
except Exception as err:
self.failed(err)

class TC_InterfaceNameModifyValidation():
"""
TC :36 To modify the security zone names(FMC) / nameif (device ) used by NAT
and ACL
"""

# @aetest.setup
def setup(self):
set_testcase_feature([Features77.feature4.value])
set_tims_testcase("Txw16474602r,Txw16474626r,Txw16474604r")
@aetest.test
def interface_change(self, testbed, api_service_fmc1, datayaml,seczone):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
brkfx_nat_lib = BreakfixNatUtils()
parentDevice = cfg.get('parentDevice')
primaryDevice = cfg.get('primaryDevice')
primary_ip = cfg.get('primaryDevice').name
primaryconf = ConfigProvider(testbed, primaryDevice.name)
primary_ssh = primaryconf.get_ssh_connection()
cfg.update({'primary_ssh': primary_ssh})
nat_detail_dict = cfg.get('nat_detail_dict')
show_commands = cfg.get('show_commands')
breakfix_cli_args = ['outside_modified']

with steps.start("Validating the interface name present in show running


config CLI before changing"):
try:
primary_ssh.conn.go_to('fireos_state')
primary_ssh.conn.execute('show running-config nat',timeout=120)

before_op = primary_ssh.conn.execute('show running-config


interface',timeout=120)

if re.search(seczone[0],before_op,re.IGNORECASE):
log.info(banner(f"GigabitEthernet0/0 interface name is
{seczone[0]}"))
except Exception as err:
self.failed(err)

with steps.start(f"Modifying the {seczone[0]} name in breakfix mode and


validate it should reflect in NAT rules") as substep:
try:
with substep.start("Modifying the inteface name via breakfix
mode"):
phyIntf = api_service_fmc1.find_one(PhysicalInterface,
condition=lambda intfname:
intfname.ifname == seczone[0],

container_id=primaryDevice.id)
data_interface1 = phyIntf.name
breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)

primary_ssh.conn.execute(f'int {data_interface1}', prompt='>|


#')
primary_ssh.conn.execute(f'nameif {breakfix_cli_args[0]}',
prompt='>|#')

primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute("Y", prompt='#')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')

with substep.start("Validating the OOB file present in FTD"):


oob_file_result =
breakfix_lib.OOB_file_validation(ftd_ssh=primary_ssh)
if oob_file_result != True:
log.error("OOB file not Generated Properly")
self.failed("OOB file not Generated Properly")

with substep.start("Validating the change in FTD nat commands"):


primary_ssh.conn.go_to('fireos_state')
after_op = primary_ssh.conn.execute('show running-config nat',
timeout=120)

if re.search(breakfix_cli_args[0], after_op, re.IGNORECASE):


log.info(banner(f"GigabitEthernet0/0 interface name
'{seczone[0]}' is changed to '{breakfix_cli_args[0]}' "))
else:
self.failed("Interface name is not changes in NAT outputs")

with substep.start("Detect Out of Band changes"):

outof_change = store.get("file:{}".format(datayaml),
root_object='outofband.change15')
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is Detected"))

with substep.start("Acknowledging the Out of Band of changes in


FMC"):

outof_change.oobaction = 'ACKNOWLEDGE_OUT_OF_BAND_CHANGES'
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is acknowledged"))

with substep.start("Configuring the changes back to the devices"):


phyIntf = api_service_fmc1.find_one(PhysicalInterface,
condition=lambda intfname:
intfname.ifname == seczone[0],

container_id=primaryDevice.id)
phyIntf.ifname = seczone[0]
api_service_fmc1.update(copy.deepcopy(phyIntf),
container_id=primaryDevice.id)

log.info(banner("Deploying the changes in FMC"))


breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=parentDevice)
log.info(banner("Deployment completed"))
time.sleep(3)

except Exception as err:


self.failed(err)

@aetest.cleanup
def cleanup(self):
primary_ssh = cfg.get('primary_ssh')
try:
log.info("Disconnecting the SSH handle")
primary_ssh.conn.disconnect()
except Exception as err:
self.failed(err)
class TC_ExistingObjectChange(aetest.Testcase):
"""
TC :37 To modify the existing object / object groups being mapped to the NAT
rule.
"""

# @aetest.setup
def setup(self):
set_testcase_feature([Features77.feature4.value])
set_tims_testcase("Txw16474602r,Txw16474626r,Txw16474604r")

@aetest.test
def exisiting_object_change(self, testbed, api_service_fmc1,datayaml):
steps = Steps()
deviceList = api_service_fmc1.find_all(Device)
deviceObjDict = {}
for device in range(len(deviceList)):
deviceObjDict[deviceList[device].name] = deviceList[device]
breakfix_lib = BreakfixUtils()
brkfx_nat_lib = BreakfixNatUtils()
parentDevice = cfg.get('parentDevice')
primaryDevice = cfg.get('primaryDevice')
primary_ip = cfg.get('primaryDevice').name
primaryconf = ConfigProvider(testbed, primaryDevice.name)
primary_ssh = primaryconf.get_ssh_connection()
cfg.update({'primary_ssh': primary_ssh})
nat_detail_dict = cfg.get('nat_detail_dict')
show_commands = cfg.get('show_commands')
breakfix_cli_args = ['obj_8','8.8.13.1']

with steps.start("Getting the already present object 'obj_8' detail in


FTD") as substep:
primary_ssh.conn.go_to('fireos_state')
primary_ssh.conn.execute('show object id obj_8')

with substep.start("Changing the ip in 'obj_8 in breakfix mode"):


breakfix_lib.breakfix_mode(ftd_ssh=primary_ssh)

primary_ssh.conn.execute(f'object network {breakfix_cli_args[0]}',


prompt='>|#', timeout=120)
primary_ssh.conn.execute(f'object host {breakfix_cli_args[1]}',
prompt='>|#', timeout=120)
primary_ssh.conn.execute('exit', prompt='>|#')

primary_ssh.conn.execute('end', prompt='>|#|:')
primary_ssh.conn.execute("Y", prompt='#')
primary_ssh.conn.execute('exit', prompt='>|#')
primary_ssh.conn.execute('exit', prompt='>|#')

with substep.start("Validating the OOB file present in FTD"):


oob_file_result =
breakfix_lib.OOB_file_validation(ftd_ssh=primary_ssh)
if oob_file_result != True:
log.error("OOB file not Generated Properly")
self.failed("OOB file not Generated Properly")

with substep.start("Validating the changes in FTD "):


primary_ssh.conn.go_to('fireos_state')
obj_op = primary_ssh.conn.execute('show object id obj_8')
if re.search(breakfix_cli_args[1], obj_op, re.IGNORECASE):
log.info(banner("Ip change is properly reflecting in the object
host obj_8"))
else:
log.error("Ip change is not reflecting properly in 'obj_8'
object host")
self.failed("Ip change is not reflecting properly in 'obj_8'
object host")

with substep.start("Validating the changes in NAT rule"):


primary_ssh.conn.go_to('fireos_state')
nat_op = primary_ssh.conn.execute('show nat detail')
if re.search(breakfix_cli_args[1], nat_op, re.IGNORECASE):
log.info(banner("Ip change is properly reflecting for the
object host 'obj_8' in show nat detail "))
else:
log.error("Ip change is not properly reflecting for the object
host 'obj_8' in show nat detail ")
self.failed("Ip change is not properly reflecting for the
object host 'obj_8' in show nat detail ")

with substep.start("Detect Out of Band changes"):

outof_change = store.get("file:{}".format(datayaml),
root_object='outofband.change16')
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is Detected"))

with substep.start("Acknowledging the Out of Band of changes in FMC"):


outof_change.oobaction = 'ACKNOWLEDGE_OUT_OF_BAND_CHANGES'
api_service_fmc1.create(outof_change,
container_id=deviceObjDict[primary_ip].id)
log.info(banner("OOB is acknowledged"))

with substep.start("Configuring the same changes back in the FMC"):


obj_8 = api_service_fmc1.find_one(NetworkObject, lambda network:
network.name == breakfix_cli_args[0])
obj_8.value = breakfix_cli_args[1]
api_service_fmc1.update(obj_8)

log.info(banner("Deploying the changes in FMC"))


breakfix_lib.deploy_on_ftd(api_service_fmc1, ftd=parentDevice)
log.info(banner("Deployment completed"))
time.sleep(3)

@aetest.cleanup
def cleanup(self):
primary_ssh = cfg.get('primary_ssh')
try:
log.info("Disconnecting the SSH handle")
primary_ssh.conn.disconnect()
except Exception as err:
self.failed(err)

class CommonCleanup(aetest.CommonCleanup):
#@aetest.subsection
def common_cleanup(self, api_service_fmc1):
steps = Steps()
try:
with steps.start("Delete all Network object"):
api_service_fmc1.delete_all(NetworkObject)

except Exception as err:


self.failed(err)

if __name__ == '__main__':
aetest.main()

You might also like