fuzzer.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. import argparse
  2. import json
  3. import logging
  4. import posixpath
  5. import random
  6. import re
  7. import requests
  8. import string
  9. import sys
  10. import urllib.parse
  11. #######################################################################################################################
  12. # Utilities
  13. def some(s):
  14. return random.choice(sorted(s))
  15. def not_some(s):
  16. test_set = random.choice([string.ascii_uppercase + string.ascii_lowercase,
  17. string.digits,
  18. string.digits + ".E-",
  19. '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJK'
  20. 'LMNOPQRSTUVWXYZ!"#$%\'()*+,-./:;<=>?@[\\]^_`{|}~ '])
  21. test_len = random.choice([1, 2, 3, 37, 61, 121])
  22. while True:
  23. x = ''.join([random.choice(test_set) for _ in range(test_len)])
  24. if x not in s:
  25. return x
  26. def build_url(host_maybe_scheme, base_path):
  27. try:
  28. if '//' not in host_maybe_scheme:
  29. host_maybe_scheme = '//' + host_maybe_scheme
  30. url_tuple = urllib.parse.urlparse(host_maybe_scheme)
  31. if base_path[0] == '/':
  32. base_path = base_path[1:]
  33. return url_tuple.netloc, posixpath.join(url_tuple.path, base_path)
  34. except Exception as e:
  35. L.error(f"Critical failure decoding arguments -> {e}")
  36. sys.exit(-1)
  37. #######################################################################################################################
  38. # Data-model and processing
  39. class Param(object):
  40. def __init__(self, name, location, kind):
  41. self.location = location
  42. self.kind = kind
  43. self.name = name
  44. self.values = set()
  45. def dump(self):
  46. print(f"{self.name} in {self.location} is {self.kind} : {{{self.values}}}")
  47. def does_response_fit_schema(schema_path, schema, resp):
  48. '''The schema_path argument tells us where we are (globally) in the schema. The schema argument is the
  49. sub-tree within the schema json that we are validating against. The resp is the json subtree from the
  50. target host's response.
  51. The basic idea is this: swagger defines a model of valid json trees. In this sense it is a formal
  52. language and we can validate a given server response by checking if the language accepts a particular
  53. server response. This is basically a parser, but instead of strings we are operating on languages
  54. of trees.
  55. This could probably be extended to arbitrary swagger definitions - but the amount of work increases
  56. rapidly as we attempt to cover the full semantics of languages of trees defined in swagger. Instead
  57. we have some special cases that describe the parts of the semantics that we've used to describe the
  58. netdata API.
  59. If we hit an error (in the schema) that prevents further checks then we return early, otherwise we
  60. try to collect as many errors as possible.
  61. '''
  62. success = True
  63. if "type" not in schema:
  64. L.error(f"Cannot progress past {schema_path} -> no type specified in dictionary")
  65. print(json.dumps(schema, indent=2))
  66. return False
  67. if schema["type"] == "object":
  68. if isinstance(resp, dict) and "properties" in schema and isinstance(schema["properties"], dict):
  69. L.debug(f"Validate properties against dictionary at {schema_path}")
  70. for k, v in schema["properties"].items():
  71. L.debug(f"Validate {k} received with {v}")
  72. if v.get("required", False) and k not in resp:
  73. L.error(f"Missing {k} in response at {schema_path}")
  74. print(json.dumps(resp, indent=2))
  75. return False
  76. if k in resp:
  77. if not does_response_fit_schema(posixpath.join(schema_path, k), v, resp[k]):
  78. success = False
  79. elif isinstance(resp, dict) and "additionalProperties" in schema \
  80. and isinstance(schema["additionalProperties"], dict):
  81. kv_schema = schema["additionalProperties"]
  82. L.debug(f"Validate additionalProperties against every value in dictionary at {schema_path}")
  83. if "type" in kv_schema and kv_schema["type"] == "object":
  84. for k, v in resp.items():
  85. if not does_response_fit_schema(posixpath.join(schema_path, k), kv_schema, v):
  86. success = False
  87. else:
  88. L.error("Don't understand what the additionalProperties means (it has no type?)")
  89. return False
  90. else:
  91. L.error(f"Can't understand schema at {schema_path}")
  92. print(json.dumps(schema, indent=2))
  93. return False
  94. elif schema["type"] == "string":
  95. if isinstance(resp, str):
  96. L.debug(f"{repr(resp)} matches {repr(schema)} at {schema_path}")
  97. return True
  98. L.error(f"{repr(resp)} does not match schema {repr(schema)} at {schema_path}")
  99. return False
  100. elif schema["type"] == "boolean":
  101. if isinstance(resp, bool):
  102. L.debug(f"{repr(resp)} matches {repr(schema)} at {schema_path}")
  103. return True
  104. L.error(f"{repr(resp)} does not match schema {repr(schema)} at {schema_path}")
  105. return False
  106. elif schema["type"] == "number":
  107. if 'nullable' in schema and resp is None:
  108. L.debug(f"{repr(resp)} matches {repr(schema)} at {schema_path} (because nullable)")
  109. return True
  110. if isinstance(resp, int) or isinstance(resp, float):
  111. L.debug(f"{repr(resp)} matches {repr(schema)} at {schema_path}")
  112. return True
  113. L.error(f"{repr(resp)} does not match schema {repr(schema)} at {schema_path}")
  114. return False
  115. elif schema["type"] == "integer":
  116. if 'nullable' in schema and resp is None:
  117. L.debug(f"{repr(resp)} matches {repr(schema)} at {schema_path} (because nullable)")
  118. return True
  119. if isinstance(resp, int):
  120. L.debug(f"{repr(resp)} matches {repr(schema)} at {schema_path}")
  121. return True
  122. L.error(f"{repr(resp)} does not match schema {repr(schema)} at {schema_path}")
  123. return False
  124. elif schema["type"] == "array":
  125. if "items" not in schema:
  126. L.error(f"Schema for array at {schema_path} does not specify items!")
  127. return False
  128. item_schema = schema["items"]
  129. if not isinstance(resp, list):
  130. L.error(f"Server did not return a list for {schema_path} (typed as array in schema)")
  131. return False
  132. for i, item in enumerate(resp):
  133. if not does_response_fit_schema(posixpath.join(schema_path, str(i)), item_schema, item):
  134. success = False
  135. else:
  136. L.error(f"Invalid swagger type {schema['type']} for {type(resp)} at {schema_path}")
  137. print(json.dumps(schema, indent=2))
  138. return False
  139. return success
  140. class GetPath(object):
  141. def __init__(self, url, spec):
  142. self.url = url
  143. self.req_params = {}
  144. self.opt_params = {}
  145. self.success = None
  146. self.failures = {}
  147. if 'parameters' in spec.keys():
  148. for p in spec['parameters']:
  149. name = p['name']
  150. req = p.get('required', False)
  151. target = self.req_params if req else self.opt_params
  152. target[name] = Param(name, p['in'], p['type'])
  153. if 'default' in p:
  154. defs = p['default']
  155. if isinstance(defs, list):
  156. for d in defs:
  157. target[name].values.add(d)
  158. else:
  159. target[name].values.add(defs)
  160. if 'enum' in p:
  161. for v in p['enum']:
  162. target[name].values.add(v)
  163. if req and len(target[name].values) == 0:
  164. print(f"FAIL: No default values in swagger for required parameter {name} in {self.url}")
  165. for code, schema in spec['responses'].items():
  166. if code[0] == "2" and 'schema' in schema:
  167. self.success = schema['schema']
  168. elif code[0] == "2":
  169. L.error(f"2xx response with no schema in {self.url}")
  170. else:
  171. self.failures[code] = schema
  172. def generate_success(self, host):
  173. url_args = "&".join([f"{p.name}={some(p.values)}" for p in self.req_params.values()])
  174. base_url = urllib.parse.urljoin(host, self.url)
  175. test_url = f"{base_url}?{url_args}"
  176. if url_filter.match(test_url):
  177. try:
  178. resp = requests.get(url=test_url, verify=(not args.tls_no_verify))
  179. self.validate(test_url, resp, True)
  180. except Exception as e:
  181. L.error(f"Network failure in test {e}")
  182. else:
  183. L.debug(f"url_filter skips {test_url}")
  184. def generate_failure(self, host):
  185. all_params = list(self.req_params.values()) + list(self.opt_params.values())
  186. bad_param = ''.join([random.choice(string.ascii_lowercase) for _ in range(5)])
  187. while bad_param in all_params:
  188. bad_param = ''.join([random.choice(string.ascii_lowercase) for _ in range(5)])
  189. all_params.append(Param(bad_param, "query", "string"))
  190. url_args = "&".join([f"{p.name}={not_some(p.values)}" for p in all_params])
  191. base_url = urllib.parse.urljoin(host, self.url)
  192. test_url = f"{base_url}?{url_args}"
  193. if url_filter.match(test_url):
  194. try:
  195. resp = requests.get(url=test_url, verify=(not args.tls_no_verify))
  196. self.validate(test_url, resp, False)
  197. except Exception as e:
  198. L.error(f"Network failure in test {e}")
  199. def validate(self, test_url, resp, expect_success):
  200. try:
  201. resp_json = json.loads(resp.text)
  202. except json.decoder.JSONDecodeError as e:
  203. L.error(f"Non-json response from {test_url}")
  204. return
  205. success_code = resp.status_code >= 200 and resp.status_code < 300
  206. if success_code and expect_success:
  207. if self.success is not None:
  208. if does_response_fit_schema(posixpath.join(self.url, str(resp.status_code)), self.success, resp_json):
  209. L.info(f"tested {test_url}")
  210. else:
  211. L.error(f"tested {test_url}")
  212. else:
  213. L.error(f"Missing schema {test_url}")
  214. elif not success_code and not expect_success:
  215. schema = self.failures.get(str(resp.status_code), None)
  216. if schema is not None:
  217. if does_response_fit_schema(posixpath.join(self.url, str(resp.status_code)), schema, resp_json):
  218. L.info(f"tested {test_url}")
  219. else:
  220. L.error(f"tested {test_url}")
  221. else:
  222. L.error("Missing schema for {resp.status_code} from {test_url}")
  223. else:
  224. L.error(f"Received incorrect status code {resp.status_code} against {test_url}")
  225. def get_the_spec(url):
  226. if url[:7] == "file://":
  227. with open(url[7:]) as f:
  228. return f.read()
  229. return requests.get(url=url).text
  230. # Swagger paths look absolute but they are relative to the base.
  231. def not_absolute(path):
  232. return path[1:] if path[0] == '/' else path
  233. def find_ref(spec, path):
  234. if len(path) > 0 and path[0] == '#':
  235. return find_ref(spec, path[1:])
  236. if len(path) == 1:
  237. return spec[path[0]]
  238. return find_ref(spec[path[0]], path[1:])
  239. def resolve_refs(spec, spec_root=None):
  240. '''Find all "$ref" keys in the swagger spec and inline their target schemas.
  241. As with all inliners this will break if a definition recursively links to itself, but this should not
  242. happen in swagger as embedding a structure inside itself would produce a record of infinite size.'''
  243. if spec_root is None:
  244. spec_root = spec
  245. newspec = {}
  246. for k, v in spec.items():
  247. if k == "$ref":
  248. path = v.split('/')
  249. target = find_ref(spec_root, path)
  250. # Unfold one level of the tree and erase the $ref if possible.
  251. if isinstance(target, dict):
  252. for kk, vv in resolve_refs(target, spec_root).items():
  253. newspec[kk] = vv
  254. else:
  255. newspec[k] = target
  256. elif isinstance(v, dict):
  257. newspec[k] = resolve_refs(v, spec_root)
  258. else:
  259. newspec[k] = v
  260. # This is an artifact of inline the $refs when they are inside a properties key as their children should be
  261. # pushed up into the parent dictionary. They must be merged (union) rather than replace as we use this to
  262. # implement polymorphism in the data-model.
  263. if 'properties' in newspec and isinstance(newspec['properties'], dict) and \
  264. 'properties' in newspec['properties']:
  265. sub = newspec['properties']['properties']
  266. del newspec['properties']['properties']
  267. if 'type' in newspec['properties']:
  268. del newspec['properties']['type']
  269. for k, v in sub.items():
  270. newspec['properties'][k] = v
  271. return newspec
  272. #######################################################################################################################
  273. # Initialization
  274. random.seed(7) # Default is reproducible sequences
  275. parser = argparse.ArgumentParser()
  276. parser.add_argument('--url', type=str,
  277. default='https://raw.githubusercontent.com/netdata/netdata/master/src/web/api/netdata-swagger.json',
  278. help='The URL of the API definition in swagger. The default will pull the latest version '
  279. 'from the main branch.')
  280. parser.add_argument('--host', type=str,
  281. help='The URL of the target host to fuzz. The default will read the host from the swagger '
  282. 'definition.')
  283. parser.add_argument('--reseed', action='store_true',
  284. help="Pick a random seed for the PRNG. The default uses a constant seed for reproducibility.")
  285. parser.add_argument('--passes', action='store_true',
  286. help="Log information about tests that pass")
  287. parser.add_argument('--detail', action='store_true',
  288. help="Log information about the response/schema comparisons during each test")
  289. parser.add_argument('--filter', type=str,
  290. default=".*",
  291. help="Supply a regex used to filter the testing URLs generated")
  292. parser.add_argument('--tls-no-verify', action='store_true',
  293. help="Disable TLS certification verification to allow connection to hosts that use"
  294. "self-signed certificates")
  295. parser.add_argument('--dump-inlined', action='store_true',
  296. help='Dump the inlined swagger spec instead of fuzzing. For "reasons".')
  297. args = parser.parse_args()
  298. if args.reseed:
  299. random.seed()
  300. spec = json.loads(get_the_spec(args.url))
  301. inlined_spec = resolve_refs(spec)
  302. if args.dump_inlined:
  303. print(json.dumps(inlined_spec, indent=2))
  304. sys.exit(-1)
  305. logging.addLevelName(40, "FAIL")
  306. logging.addLevelName(20, "PASS")
  307. logging.addLevelName(10, "DETAIL")
  308. L = logging.getLogger()
  309. handler = logging.StreamHandler(sys.stdout)
  310. if not args.passes and not args.detail:
  311. L.setLevel(logging.ERROR)
  312. elif args.passes and not args.detail:
  313. L.setLevel(logging.INFO)
  314. elif args.detail:
  315. L.setLevel(logging.DEBUG)
  316. handler.setFormatter(logging.Formatter(fmt="%(levelname)s %(message)s"))
  317. L.addHandler(handler)
  318. url_filter = re.compile(args.filter)
  319. if spec['swagger'] != '2.0':
  320. L.error(f"Unexpected swagger version")
  321. sys.exit(-1)
  322. L.info(f"Fuzzing {spec['info']['title']} / {spec['info']['version']}")
  323. host, base_url = build_url(args.host or spec['host'], inlined_spec['basePath'])
  324. L.info(f"Target host is {base_url}")
  325. paths = []
  326. for name, p in inlined_spec['paths'].items():
  327. if 'get' in p:
  328. name = not_absolute(name)
  329. paths.append(GetPath(posixpath.join(base_url, name), p['get']))
  330. elif 'put' in p:
  331. L.error(f"Generation of PUT methods (for {name} is unimplemented")
  332. for s in inlined_spec['schemes']:
  333. for p in paths:
  334. resp = p.generate_success(s + "://" + host)
  335. resp = p.generate_failure(s+"://"+host)