Created
April 25, 2022 02:23
-
-
Save readybuilderone/25f0db6be6088c0964d0bf367e89943b to your computer and use it in GitHub Desktop.
Python Scripts to update AWS Network Firewall rule group in batch, python3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from urllib import response | |
import boto3 | |
TargetRuleGroupName='aurora-firewall-sample-stateful-rule-group' | |
ExpectedIPList=['54.222.61.40','54.222.61.41','54.222.61.42','54.222.61.43','54.222.61.45','54.222.61.40'] | |
def getUpdateToken(filewallClient, targetRuleGroupName): | |
rulegroupResponse = filewallClient.describe_rule_group( | |
RuleGroupName=targetRuleGroupName, Type='STATEFUL') | |
updateToken = rulegroupResponse['UpdateToken'] | |
# print(updateToken) | |
return updateToken | |
def main(): | |
uniqueExpectedIPList=list(set(ExpectedIPList)) | |
totalUniqueExpectedIPNumber=len(uniqueExpectedIPList) | |
print('Total unique IP Number: ',totalUniqueExpectedIPNumber) | |
confirm = input("Enter y to continue, n to stop: ") | |
if(confirm != 'y'): | |
return | |
filewallClient = boto3.client('network-firewall') | |
updateToken = getUpdateToken(filewallClient, TargetRuleGroupName) | |
initRuleGroup = { | |
'RulesSource': { | |
'StatefulRules': [ | |
{ | |
'Action': 'DROP', | |
'Header': { | |
'Protocol': 'IP', | |
'Source': 'Any', | |
'SourcePort': 'Any', | |
'Direction': 'FORWARD', | |
'Destination': 'Any', | |
'DestinationPort': 'Any' | |
}, | |
'RuleOptions': [ | |
{ | |
'Keyword': 'sid', | |
'Settings': [ | |
'1' | |
] | |
} | |
] | |
} | |
] | |
}, | |
'StatefulRuleOptions': { | |
'RuleOrder': 'DEFAULT_ACTION_ORDER' | |
} | |
} | |
for i in range(totalUniqueExpectedIPNumber): | |
sourceIP=uniqueExpectedIPList[i].strip()+'/32' | |
sidSequence= str(i+2) | |
item = { | |
'Action': 'PASS', | |
'Header': { | |
'Protocol': 'IP', | |
'Source': sourceIP, | |
'SourcePort': 'Any', | |
'Direction': 'FORWARD', | |
'Destination': 'Any', | |
'DestinationPort': 'Any' | |
}, | |
'RuleOptions': [ | |
{ | |
'Keyword': 'sid', | |
'Settings': [ | |
sidSequence | |
] | |
} | |
] | |
} | |
initRuleGroup['RulesSource']['StatefulRules'].append(item) | |
# print(initRuleGroup) | |
updateResponse = filewallClient.update_rule_group( | |
UpdateToken=updateToken, | |
RuleGroupName='aurora-firewall-sample-stateful-rule-group', | |
RuleGroup=initRuleGroup, | |
Type='STATEFUL' | |
) | |
if(updateResponse['ResponseMetadata']['HTTPStatusCode']==200): | |
print('Firewall rule group updated successfully.') | |
# print('updateResponse: ', updateResponse) | |
if __name__=="__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment