Skip to content

Commit

Permalink
Fix Compiler.
Browse files Browse the repository at this point in the history
  • Loading branch information
wert310 committed Nov 23, 2020
1 parent be4f623 commit d90b030
Show file tree
Hide file tree
Showing 5 changed files with 262 additions and 13 deletions.
25 changes: 20 additions & 5 deletions frontend/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
<b-icon pack="fa" :icon="active ? 'angle-up' : 'angle-down'"></b-icon>
</button>

<b-dropdown-item v-for="target in frontends" v-bind:key="target" aria-role="listitem" @click="compilerCompile(target)">{{ target }}</b-dropdown-item>
<b-dropdown-item v-for="target in targets" v-bind:key="target" aria-role="listitem" @click="compilerCompile(target)">{{ target }}</b-dropdown-item>
</b-dropdown>


Expand Down Expand Up @@ -81,7 +81,7 @@
<h1 v-if="isWorking && query_progress > 0" class="is-size-6 has-text-centered has-text-weight-bold is-family-monospace">Synthesizing policy...</h1>
<b-progress class="mt-3 ml-3 mr-3 mb-5" :value="query_progress" show-value format="percent" v-if="isWorking && query_progress > 0"></b-progress>

<div v-for="mode in Object.keys(fwspolicy)" v-bind:key="mode">
<div v-for="mode in Object.keys(fwspolicy).filter(n => n != 'locals')" v-bind:key="mode">
<h1 class="is-size-5 has-text-weight-bold is-family-monospace">{{ mode.toUpperCase() }}</h1>

<table class="fws-table singleline" v-if="mode == 'aliases'">
Expand Down Expand Up @@ -379,16 +379,18 @@ export default {
if (this.getCurrentMode() != 'compiler') return
this.fwspolicy = {}
var query_code_backup = this.query_code
this.query_code = `table_style json\naliases(${policy})\nsynthesis(${policy})\n`
this.query_code = `table_style json\nlocals(${policy})\naliases(${policy})\nsynthesis(${policy})\n`
this.queryRun().then(() => {
const sregex = /FORWARD\n\n(\{.*\})\n?(\{.*\}?)\n\nINPUT\n\n(\{.*\})(\n\{.*\})?\n\nOUTPUT\n\n(\{.*\})(\n\{.*\})?\n\nLOOPBACK\n\n(\{.*\})(\n\{.*\})?/
const aregex = /([a-zA-Z0-9_-]+): ([0-9./]+)/g
const lregex = /local ([0-9./]+)/g
console.log(this.query_output)
const match = this.query_output.match(sregex)
if (!match)
this.showError(this.query_output.replaceAll("<", "&lt;"))
else {
this.fwspolicy = {
'locals': [...this.query_output.matchAll(lregex)].map(x => x[1]),
'aliases': [...this.query_output.matchAll(aregex)].map(x => [x[1], x[2]]),
'forward': Array.prototype.concat([JSON.parse(match[1])], (match[2] ? [JSON.parse(match[2])] : [])),
'input': Array.prototype.concat([JSON.parse(match[3])], (match[4] ? [JSON.parse(match[4])] : [])),
Expand Down Expand Up @@ -440,8 +442,15 @@ export default {
}).then(b => b.json())
.then(res => {
console.log(res)
this.isWorking = false
// TODO
const blob = new Blob([res.value], {type: 'text/plain'})
const e = document.createEvent('MouseEvents'),
a = document.createElement('a');
a.download = `${target}_policy_${new Date().toJSON()}.rules`;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/plain', a.download, a.href].join(':');
e.initEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
this.isWorking = false;
}).catch(this.showError)
},
Expand Down Expand Up @@ -485,6 +494,11 @@ export default {
console.log(res)
this.frontends = res
}).catch(this.showError)
fetch(`${FWS_URI}/compiler/targets`).then(b => b.json())
.then(res => {
console.log(res)
this.targets = res
}).catch(this.showError)
},
},
Expand Down Expand Up @@ -513,6 +527,7 @@ export default {
loaded_policies: [],
isWorking: true,
frontends: [],
targets: [],
fws_instance: null,
query_code: "",
query_output: "",
Expand Down
1 change: 1 addition & 0 deletions fwsynthesizer/compile/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from compile_ipfw import *
from compile_pf import *

TARGETS = ['iptables', 'ipfw', 'pf']

def fw_compile(semantics, target):
"""
Expand Down
31 changes: 27 additions & 4 deletions fwsynthesizer/synthesis/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,19 @@ def any_protocol(self):
def any_mark(self):
return self.mark[0][0] == Any_tag[0][0] and self.mark[0][1] == Any_tag[0][1]

def to_mrule_packet(self):
return [ # srcIp, srcPort, dstIp, dstPort, srcMac, dstMac, protocol, state, mark
[ [struct.unpack(">I", ip.packed)[0] for ip in ips] for ips in self.srcIp ],
self.srcPort,
[ [struct.unpack(">I", ip.packed)[0] for ip in ips] for ips in self.dstIp ],
self.dstPort,
[ [mac._mac for mac in macs] for macs in self.srcMac ],
[ [mac._mac for mac in macs] for macs in self.dstMac ],
self.protocol,
self.state,
self.mark
]


class Rule(object):
"FWS Rule Object"
Expand Down Expand Up @@ -178,17 +191,24 @@ def __init__(self, packet_in, packet_out):
def __repr__(self):
return "#<Rule {} {} {}>".format(self.type, self.packet_in, self.packet_out)

def to_mrule(self):
return [self.packet_in.to_mrule_packet(), self.packet_out.to_mrule_packet()]


class SynthesisOutput:
"Firewall synthesis output"

def __init__(self, fw, rules):
def __init__(self, fw, rules, mrules_precomputed=False):
self.firewall = fw
self.__rules = rules
self.mrules_precomputed = mrules_precomputed

def get_rules(self):
"Get the rules as lists of Rule objects"
rules = [ Synthesis.mrule_list(r) for r in self.__rules ]
if self.mrules_precomputed:
rules = self.__rules
else:
rules = [ Synthesis.mrule_list(r) for r in self.__rules ]
return [ Rule(Packet(*pin), Packet(*pout)) for pin,pout in rules ]

def print_table(self, table_style=TableStyle.UNICODE, local_src=LocalFlag.BOTH,
Expand All @@ -209,12 +229,15 @@ def print_table(self, table_style=TableStyle.UNICODE, local_src=LocalFlag.BOTH,
hide_nats = nat == NatFlag.FILTER
hide_filters = nat == NatFlag.NAT
table_printer.print_table(
rules, table_style, [ipaddr.IPv4Address(a) for a in self.firewall.locals],
rules, table_style, [ipaddr.IPv4Address(a) for a in self.firewall.locals] if self.firewall else [],
hide_src, hide_dst, hide_nats, hide_filters,
projection, aliases=aliases)

def get_rules_no_duplicates(self):
rules = [Synthesis.mrule_list(r) for r in self.__rules]
if self.mrules_precomputed:
rules = self.__rules
else:
rules = [Synthesis.mrule_list(r) for r in self.__rules]

for rule in rules:
for pkt in rule:
Expand Down
11 changes: 10 additions & 1 deletion fwsynthesizer/synthesis/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,14 @@ def eval(self, fws):
print "{}: {}".format(a, aliases[a])
print

class Locals(FWSCmd, namedtuple('Locals', ['p'])):
def eval(self, fws):
policy = fws.get_variable(self.p)
locals_ = policy.firewall.locals
for ip in locals_:
print "local {}".format(ip)
print

class Porting(FWSCmd, namedtuple('Porting', ['p', 'target', 'file'])):
def eval(self, fws):
policy = fws.get_variable(self.p)
Expand Down Expand Up @@ -369,6 +377,7 @@ def eval(self, fws):
echo = (sym('echo') >> litstr).parsecmap(Echo)
ifcl = sym('ifcl') >> parens(identifier).parsecmap(lambda p: Ifcl(p))
aliases = sym('aliases') >> parens(identifier).parsecmap(lambda p: Aliases(p))
locals_ = sym('locals') >> parens(identifier).parsecmap(lambda p: Locals(p))
setting = (sym('help').parsecmap(lambda _: Echo(help_message)) ^
sym('show_time').parsecmap(lambda _: ShowTime()) ^
sym('verbose_mode').parsecmap(lambda _: VerboseMode()) ^
Expand Down Expand Up @@ -423,7 +432,7 @@ def load_policy():

@generate
def fws_command():
cmd = yield ( echo ^ setting ^ aliases ^ porting ^ comparison ^ synthesis ^
cmd = yield ( echo ^ setting ^ aliases ^ locals_ ^ porting ^ comparison ^ synthesis ^
related ^ ifcl ^ load_policy ^ comment.parsecmap(lambda _: Nop()) ^
identifier.parsecmap(lambda n: ShowIdentifier(n)) )
preturn ( cmd )
Expand Down
Loading

0 comments on commit d90b030

Please sign in to comment.