diff options
author | Phil Sutter <phil@nwl.cc> | 2019-05-27 13:36:41 +0200 |
---|---|---|
committer | Pablo Neira Ayuso <pablo@netfilter.org> | 2019-05-31 18:17:36 +0200 |
commit | ef2ff133007855707f978f75ac638af3d5c06fbe (patch) | |
tree | 9e270cf8cf1e82499ce1b782eb1307bcb8570637 /py/nftables.py | |
parent | 6d0c815e281c4edc539c535491d6425cf0f8edeb (diff) |
py: Implement JSON validation in nftables module
Using jsonschema it is possible to validate any JSON input to make sure
it formally conforms with libnftables JSON API requirements.
Implement a simple validator class for use within a new Nftables class
method 'json_validate' and ship a minimal schema definition along with
the package.
Signed-off-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
Diffstat (limited to 'py/nftables.py')
-rw-r--r-- | py/nftables.py | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/py/nftables.py b/py/nftables.py index 33cd2dfd..81e57567 100644 --- a/py/nftables.py +++ b/py/nftables.py @@ -17,9 +17,23 @@ import json from ctypes import * import sys +import os NFTABLES_VERSION = "0.1" +class SchemaValidator: + """Libnftables JSON validator using jsonschema""" + + def __init__(self): + schema_path = os.path.join(os.path.dirname(__file__), "schema.json") + with open(schema_path, 'r') as schema_file: + self.schema = json.load(schema_file) + import jsonschema + self.jsonschema = jsonschema + + def validate(self, json): + self.jsonschema.validate(instance=json, schema=self.schema) + class Nftables: """A class representing libnftables interface""" @@ -46,6 +60,8 @@ class Nftables: "numeric_symbol": (1 << 9), } + validator = None + def __init__(self, sofile="libnftables.so"): """Instantiate a new Nftables class object. @@ -382,3 +398,16 @@ class Nftables: if len(output): output = json.loads(output) return (rc, output, error) + + def json_validate(self, json_root): + """Validate JSON object against libnftables schema. + + Accepts a hash object as input. + + Returns True if JSON is valid, raises an exception otherwise. + """ + if not self.validator: + self.validator = SchemaValidator() + + self.validator.validate(json_root) + return True |