summaryrefslogtreecommitdiffstats
path: root/tests/json_echo/run-test.py
blob: dd7797fb6f0416a5a6a060a2b89ba7ddd53d860f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#!/usr/bin/python

from __future__ import print_function
import sys
import os
import json

TESTS_PATH = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(TESTS_PATH, '../../py/'))

from nftables import Nftables

# Change working directory to repository root
os.chdir(TESTS_PATH + "/../..")

if not os.path.exists('src/.libs/libnftables.so'):
    print("The nftables library does not exist. "
          "You need to build the project.")
    sys.exit(1)

nftables = Nftables(sofile = 'src/.libs/libnftables.so')
nftables.set_echo_output(True)

# various commands to work with

flush_ruleset = { "flush": { "ruleset": None } }

list_ruleset = { "list": { "ruleset": None } }

add_table = { "add": {
    "table": {
        "family": "inet",
        "name": "t",
    }
}}

add_chain = { "add": {
    "chain": {
        "family": "inet",
        "table": "t",
        "name": "c"
    }
}}

add_set = { "add": {
    "set": {
        "family": "inet",
        "table": "t",
        "name": "s",
        "type": "inet_service"
    }
}}

add_rule = { "add": {
    "rule": {
        "family": "inet",
        "table": "t",
        "chain": "c",
        "expr": [ { "accept": None } ]
    }
}}

add_counter = { "add": {
    "counter": {
        "family": "inet",
        "table": "t",
        "name": "c"
    }
}}

add_quota = { "add": {
    "quota": {
        "family": "inet",
        "table": "t",
        "name": "q",
        "bytes": 65536
    }
}}

# helper functions

def exit_err(msg):
    print("Error: %s" %msg)
    sys.exit(1)

def exit_dump(e, obj):
    print("FAIL: {}".format(e))
    print("Output was:")
    json.dumps(out, sort_keys = True, indent = 4, separators = (',', ': '))
    sys.exit(1)

def do_flush():
    rc, out, err = nftables.json_cmd({ "nftables": [flush_ruleset] })
    if not rc is 0:
        exit_err("flush ruleset failed: {}".format(err))

def do_command(cmd):
    if not type(cmd) is list:
        cmd = [cmd]
    rc, out, err = nftables.json_cmd({ "nftables": cmd })
    if not rc is 0:
        exit_err("command failed: {}".format(err))
    return out

def do_list_ruleset():
    echo = nftables.get_echo_output()
    nftables.set_echo_output(False)
    out = do_command(list_ruleset)
    nftables.set_echo_output(echo)
    return out

def get_handle(output, search):
    try:
        for item in output["nftables"]:
            if "add" in item:
                data = item["add"]
            elif "insert" in item:
                data = item["insert"]
            else:
                data = item

            k = search.keys()[0]

            if not k in data:
                continue
            found = True
            for key in list(search[k].keys()):
                if key == "handle":
                    continue
                if not key in data[k] or search[k][key] != data[k][key]:
                    found = False
                    break
            if not found:
                continue

            return data[k]["handle"]
    except Exception as e:
        exit_dump(e, output)

# single commands first

do_flush()

print("Adding table t")
out = do_command(add_table)
handle = get_handle(out, add_table["add"])

out = do_list_ruleset()
handle_cmp = get_handle(out, add_table["add"])

if handle != handle_cmp:
    exit_err("handle mismatch!")

add_table["add"]["table"]["handle"] = handle

print("Adding chain c")
out = do_command(add_chain)
handle = get_handle(out, add_chain["add"])

out = do_list_ruleset()
handle_cmp = get_handle(out, add_chain["add"])

if handle != handle_cmp:
    exit_err("handle mismatch!")

add_chain["add"]["chain"]["handle"] = handle

print("Adding set s")
out = do_command(add_set)
handle = get_handle(out, add_set["add"])

out = do_list_ruleset()
handle_cmp = get_handle(out, add_set["add"])

if handle != handle_cmp:
    exit_err("handle mismatch!")

add_set["add"]["set"]["handle"] = handle

print("Adding rule")
out = do_command(add_rule)
handle = get_handle(out, add_rule["add"])

out = do_list_ruleset()
handle_cmp = get_handle(out, add_rule["add"])

if handle != handle_cmp:
    exit_err("handle mismatch!")

add_rule["add"]["rule"]["handle"] = handle

print("Adding counter")
out = do_command(add_counter)
handle = get_handle(out, add_counter["add"])

out = do_list_ruleset()
handle_cmp = get_handle(out, add_counter["add"])

if handle != handle_cmp:
    exit_err("handle mismatch!")

add_counter["add"]["counter"]["handle"] = handle

print("Adding quota")
out = do_command(add_quota)
handle = get_handle(out, add_quota["add"])

out = do_list_ruleset()
handle_cmp = get_handle(out, add_quota["add"])

if handle != handle_cmp:
    exit_err("handle mismatch!")

add_quota["add"]["quota"]["handle"] = handle

# adjust names and add items again
# Note: Handles are per-table, hence add renamed objects to first table
#       to make sure assigned handle differs from first run.

add_table["add"]["table"]["name"] = "t2"
add_chain["add"]["chain"]["name"] = "c2"
add_set["add"]["set"]["name"] = "s2"
add_counter["add"]["counter"]["name"] = "c2"
add_quota["add"]["quota"]["name"] = "q2"

print("Adding table t2")
out = do_command(add_table)
handle = get_handle(out, add_table["add"])
if handle == add_table["add"]["table"]["handle"]:
   exit_err("handle not changed in re-added table!")

print("Adding chain c2")
out = do_command(add_chain)
handle = get_handle(out, add_chain["add"])
if handle == add_chain["add"]["chain"]["handle"]:
   exit_err("handle not changed in re-added chain!")

print("Adding set s2")
out = do_command(add_set)
handle = get_handle(out, add_set["add"])
if handle == add_set["add"]["set"]["handle"]:
   exit_err("handle not changed in re-added set!")

print("Adding rule again")
out = do_command(add_rule)
handle = get_handle(out, add_rule["add"])
if handle == add_rule["add"]["rule"]["handle"]:
   exit_err("handle not changed in re-added rule!")

print("Adding counter c2")
out = do_command(add_counter)
handle = get_handle(out, add_counter["add"])
if handle == add_counter["add"]["counter"]["handle"]:
   exit_err("handle not changed in re-added counter!")

print("Adding quota q2")
out = do_command(add_quota)
handle = get_handle(out, add_quota["add"])
if handle == add_quota["add"]["quota"]["handle"]:
   exit_err("handle not changed in re-added quota!")

# now multiple commands

# reset name changes again
add_table["add"]["table"]["name"] = "t"
add_chain["add"]["chain"]["name"] = "c"
add_set["add"]["set"]["name"] = "s"
add_counter["add"]["counter"]["name"] = "c"
add_quota["add"]["quota"]["name"] = "q"

do_flush()

print("doing multi add")
# XXX: Add table separately, otherwise this triggers cache bug
out = do_command(add_table)
thandle = get_handle(out, add_table["add"])
add_multi = [ add_chain, add_set, add_rule ]
out = do_command(add_multi)

chandle = get_handle(out, add_chain["add"])
shandle = get_handle(out, add_set["add"])
rhandle = get_handle(out, add_rule["add"])

out = do_list_ruleset()

if thandle != get_handle(out, add_table["add"]):
    exit_err("table handle mismatch!")

if chandle != get_handle(out, add_chain["add"]):
    exit_err("chain handle mismatch!")

if shandle != get_handle(out, add_set["add"]):
    exit_err("set handle mismatch!")

if rhandle != get_handle(out, add_rule["add"]):
    exit_err("rule handle mismatch!")