fixcwes.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import csv
  2. import re
  3. import json
  4. def find_roots(cwes_parents, root_list):
  5. roots = dict()
  6. for cwe in cwes_parents:
  7. ancestor_list = cwes_parents[cwe]
  8. roots[cwe] = recursive_ancestor(cwes_parents, ancestor_list, root_list)
  9. return(roots)
  10. def recursive_ancestor(cwes_parents,ancestor_list, root_list):
  11. new_ancestor_list=[]
  12. for ancestor in ancestor_list:
  13. try:
  14. print(ancestor)
  15. new_ancestor_list += cwes_parents[ancestor]
  16. except KeyError:
  17. print('We have a problem with the following ancestor:')
  18. print(ancestor)
  19. print('#'*80)
  20. flag = True
  21. for i in new_ancestor_list:
  22. if i not in root_list:
  23. flag = False
  24. break
  25. if flag:
  26. return(new_ancestor_list)
  27. else:
  28. # Yes it is tail-recursive
  29. return(recursive_ancestor(cwes_parents,new_ancestor_list, root_list))
  30. def ret_roots(cwe):
  31. roots = dict()
  32. with open("cwe_roots.json",'r') as fp:
  33. roots = json.load(fp)
  34. try:
  35. return(roots[cwe.split('-')[1]])
  36. except KeyError:
  37. return([0])
  38. except IndexError:
  39. return([0])
  40. except AttributeError:
  41. return([0])
  42. def main():
  43. cwes_parents = dict()
  44. cwes_roots = dict()
  45. with open("1000.csv","r") as csvfile:
  46. spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
  47. for row in spamreader:
  48. s = row[6]
  49. if row[0]=='732':
  50. print(s)
  51. m = re.findall(r'::NATURE:ChildOf:CWE ID:([0-9]*):VIEW ID:1000',s)
  52. try:
  53. #print(row[0],', ', row[6])
  54. #print(m.group(1))
  55. cwes_parents[row[0]] = m
  56. print(m)
  57. except AttributeError:
  58. print(s)
  59. root_list = ['682', '118', '330', '435', '664', '691', '693', '697', '703', '707', '710' ]
  60. for cwe in root_list:
  61. cwes_parents[cwe] = [cwe]
  62. cwe_roots = find_roots(cwes_parents, root_list)
  63. print(cwe_roots)
  64. with open("cwe_roots.json","w") as fp:
  65. json.dump(cwe_roots,fp)
  66. if __name__ == "__main__":
  67. main()