diff --git a/.travis.yml b/.travis.yml index 0a3a9120..18c02c6c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,31 +6,30 @@ services: cache: pip python: - - "3.4" - - "3.5" - - "3.5-dev" - "3.6" - "3.6-dev" + - "3.7-dev" install: - - pip install -U nose codecov pytest - - pip install -U -r REQUIREMENTS - - pip install . + - sudo apt-get install libzbar0 libzbar-dev libpoppler-cpp-dev + - pip install pipenv + - pipenv install --dev script: - - coverage run -m --parallel-mode --source=misp_modules misp_modules.__init__ -l 127.0.0.1 & + - pipenv run coverage run -m --parallel-mode --source=misp_modules misp_modules.__init__ -l 127.0.0.1 & - pid=$! - sleep 5 - - nosetests --with-coverage --cover-package=misp_modules - - kill -s INT $pid + - pipenv run nosetests --with-coverage --cover-package=misp_modules + - kill -s KILL $pid - pushd ~/ - - coverage run -m --parallel-mode --source=misp_modules misp_modules.__init__ -s -l 127.0.0.1 & + - pipenv run coverage run -m --parallel-mode --source=misp_modules misp_modules.__init__ -s -l 127.0.0.1 & - pid=$! - popd - sleep 5 - - nosetests --with-coverage --cover-package=misp_modules - - kill -s INT $pid + - pipenv run nosetests --with-coverage --cover-package=misp_modules + - kill -s KILL $pid + - pipenv run flake8 --ignore=E501,W503 misp_modules after_success: - - coverage combine .coverage* - - codecov + - pipenv run coverage combine .coverage* + - pipenv run codecov diff --git a/Pipfile b/Pipfile new file mode 100644 index 00000000..36f059ea --- /dev/null +++ b/Pipfile @@ -0,0 +1,60 @@ +[[source]] +name = "pypi" +url = "https://pypi.org/simple" +verify_ssl = true + +[dev-packages] +nose = "*" +codecov = "*" +pytest = "*" +flake8 = "*" + +[packages] +dnspython = "*" +requests = "*" +urlarchiver = "*" +passivetotal = "*" +pypdns = "*" +pypssl = "*" +pyeupi = "*" +uwhois = {editable = true,git = "https://github.com/Rafiot/uwhoisd.git",ref = "testing",subdirectory = "client"} +pymisp = {editable = true,git = "https://github.com/MISP/PyMISP.git"} +pyonyphe = {editable = true,git = "https://github.com/sebdraven/pyonyphe"} +pydnstrails = {editable = true,git = "https://github.com/sebdraven/pydnstrails"} +pytesseract = "*" +pygeoip = "*" +beautifulsoup4 = "*" +oauth2 = "*" +yara-python = "==3.8.1" +sigmatools = "*" +stix2-patterns = "*" +maclookup = "*" +vulners = "*" +blockchain = "*" +reportlab = "*" +pyintel471 = {editable = true,git = "https://github.com/MISP/PyIntel471.git"} +shodan = "*" +Pillow = "*" +Wand = "*" +SPARQLWrapper = "*" +domaintools_api = "*" +misp-modules = {editable = true,path = "."} +pybgpranking = {editable = true,git = "https://github.com/D4-project/BGP-Ranking.git/",subdirectory = "client"} +pyipasnhistory = {editable = true,git = "https://github.com/D4-project/IPASN-History.git/",subdirectory = "client"} +backscatter = "*" +pyzbar = "*" +opencv-python = "*" +np = "*" +ODTReader = {editable = true,git = "https://github.com/cartertemm/ODTReader.git/"} +python-pptx = "*" +python-docx = "*" +ezodf = "*" +pandas = "*" +pandas_ods_reader = "*" +pdftotext = "*" +lxml = "*" +xlrd = "*" +idna-ssl = {markers="python_version < '3.7'"} + +[requires] +python_version = "3" diff --git a/Pipfile.lock b/Pipfile.lock new file mode 100644 index 00000000..fa07b4cb --- /dev/null +++ b/Pipfile.lock @@ -0,0 +1,986 @@ +{ + "_meta": { + "hash": { + "sha256": "9aac0a9c45df16b9502c13f9468095cf5ffdb8bc407fe2b55faee3ff53d8eba3" + }, + "pipfile-spec": 6, + "requires": { + "python_version": "3" + }, + "sources": [ + { + "name": "pypi", + "url": "https://pypi.org/simple", + "verify_ssl": true + } + ] + }, + "default": { + "aiohttp": { + "hashes": [ + "sha256:0419705a36b43c0ac6f15469f9c2a08cad5c939d78bd12a5c23ea167c8253b2b", + "sha256:1812fc4bc6ac1bde007daa05d2d0f61199324e0cc893b11523e646595047ca08", + "sha256:2214b5c0153f45256d5d52d1e0cafe53f9905ed035a142191727a5fb620c03dd", + "sha256:275909137f0c92c61ba6bb1af856a522d5546f1de8ea01e4e726321c697754ac", + "sha256:3983611922b561868428ea1e7269e757803713f55b53502423decc509fef1650", + "sha256:51afec6ffa50a9da4cdef188971a802beb1ca8e8edb40fa429e5e529db3475fa", + "sha256:589f2ec8a101a0f340453ee6945bdfea8e1cd84c8d88e5be08716c34c0799d95", + "sha256:789820ddc65e1f5e71516adaca2e9022498fa5a837c79ba9c692a9f8f916c330", + "sha256:7a968a0bdaaf9abacc260911775611c9a602214a23aeb846f2eb2eeaa350c4dc", + "sha256:7aeefbed253f59ea39e70c5848de42ed85cb941165357fc7e87ab5d8f1f9592b", + "sha256:7b2eb55c66512405103485bd7d285a839d53e7fdc261ab20e5bcc51d7aaff5de", + "sha256:87bc95d3d333bb689c8d755b4a9d7095a2356108002149523dfc8e607d5d32a4", + "sha256:9d80e40db208e29168d3723d1440ecbb06054d349c5ece6a2c5a611490830dd7", + "sha256:a1b442195c2a77d33e4dbee67c9877ccbdd3a1f686f91eb479a9577ed8cc326b", + "sha256:ab3d769413b322d6092f169f316f7b21cd261a7589f7e31db779d5731b0480d8", + "sha256:b066d3dec5d0f5aee6e34e5765095dc3d6d78ef9839640141a2b20816a0642bd", + "sha256:b24e7845ae8de3e388ef4bcfcf7f96b05f52c8e633b33cf8003a6b1d726fc7c2", + "sha256:c59a953c3f8524a7c86eaeaef5bf702555be12f5668f6384149fe4bb75c52698", + "sha256:cf2cc6c2c10d242790412bea7ccf73726a9a44b4c4b073d2699ef3b48971fd95", + "sha256:e0c9c8d4150ae904f308ff27b35446990d2b1dfc944702a21925937e937394c6", + "sha256:f1839db4c2b08a9c8f9788112644f8a8557e8e0ecc77b07091afabb941dc55d0", + "sha256:f3df52362be39908f9c028a65490fae0475e4898b43a03d8aa29d1e765b45e07" + ], + "version": "==3.4.4" + }, + "antlr4-python3-runtime": { + "hashes": [ + "sha256:168cdcec8fb9152e84a87ca6fd261b3d54c8f6358f42ab3b813b14a7193bb50b" + ], + "markers": "python_version >= '3'", + "version": "==4.7.2" + }, + "async-timeout": { + "hashes": [ + "sha256:0c3c816a028d47f659d6ff5c745cb2acf1f966da1fe5c19c77a70282b25f4c5f", + "sha256:4291ca197d287d274d0b6cb5d6f8f8f82d434ed288f962539ff18cc9012f9ea3" + ], + "version": "==3.0.1" + }, + "attrs": { + "hashes": [ + "sha256:69c0dbf2ed392de1cb5ec704444b08a5ef81680a61cb899dc08127123af36a79", + "sha256:f0b870f674851ecbfbbbd364d6b5cbdff9dcedbc7f3f5e18a6891057f21fe399" + ], + "version": "==19.1.0" + }, + "backscatter": { + "hashes": [ + "sha256:7a0d1aa3661635de81e2a09b15d53e35cbe399a111cc58a70925f80e6874abd3", + "sha256:afb0efcf5d2551dac953ec4c38fb710b274b8e811775650e02c1ef42cafb14c8" + ], + "index": "pypi", + "version": "==0.2.4" + }, + "beautifulsoup4": { + "hashes": [ + "sha256:034740f6cb549b4e932ae1ab975581e6103ac8f942200a0e9759065984391858", + "sha256:945065979fb8529dd2f37dbb58f00b661bdbcbebf954f93b32fdf5263ef35348", + "sha256:ba6d5c59906a85ac23dadfe5c88deaf3e179ef565f4898671253e50a78680718" + ], + "index": "pypi", + "version": "==4.7.1" + }, + "blockchain": { + "hashes": [ + "sha256:dbaa3eebb6f81b4245005739da802c571b09f98d97eb66520afd95d9ccafebe2" + ], + "index": "pypi", + "version": "==1.4.4" + }, + "certifi": { + "hashes": [ + "sha256:59b7658e26ca9c7339e00f8f4636cdfe59d34fa37b9b04f6f9e9926b3cece1a5", + "sha256:b26104d6835d1f5e49452a26eb2ff87fe7090b89dfcaee5ea2212697e1e1d7ae" + ], + "version": "==2019.3.9" + }, + "chardet": { + "hashes": [ + "sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae", + "sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691" + ], + "version": "==3.0.4" + }, + "click": { + "hashes": [ + "sha256:2335065e6395b9e67ca716de5f7526736bfa6ceead690adf616d925bdc622b13", + "sha256:5b94b49521f6456670fdb30cd82a4eca9412788a93fa6dd6df72c94d5a8ff2d7" + ], + "version": "==7.0" + }, + "click-plugins": { + "hashes": [ + "sha256:46ab999744a9d831159c3411bb0c79346d94a444df9a3a3742e9ed63645f264b", + "sha256:5d262006d3222f5057fd81e1623d4443e41dcda5dc815c06b442aa3c02889fc8" + ], + "version": "==1.1.1" + }, + "colorama": { + "hashes": [ + "sha256:05eed71e2e327246ad6b38c540c4a3117230b19679b875190486ddd2d721422d", + "sha256:f8ac84de7840f5b9c4e3347b3c1eaa50f7e49c2b07596221daec5edaabbd7c48" + ], + "version": "==0.4.1" + }, + "dnspython": { + "hashes": [ + "sha256:36c5e8e38d4369a08b6780b7f27d790a292b2b08eea01607865bf0936c558e01", + "sha256:f69c21288a962f4da86e56c4905b49d11aba7938d3d740e80d9e366ee4f1632d" + ], + "index": "pypi", + "version": "==1.16.0" + }, + "domaintools-api": { + "hashes": [ + "sha256:f567f407b8997e947df5badf7c2bea64fdfd33c54ade24eab36ef575fb71ccb7" + ], + "index": "pypi", + "version": "==0.3.3" + }, + "enum-compat": { + "hashes": [ + "sha256:939ceff18186a5762ae4db9fa7bfe017edbd03b66526b798dd8245394c8a4192" + ], + "version": "==0.0.2" + }, + "ez-setup": { + "hashes": [ + "sha256:303c5b17d552d1e3fb0505d80549f8579f557e13d8dc90e5ecef3c07d7f58642" + ], + "version": "==0.9" + }, + "ezodf": { + "hashes": [ + "sha256:000da534f689c6d55297a08f9e2ed7eada9810d194d31d164388162fb391122d" + ], + "index": "pypi", + "version": "==0.3.2" + }, + "future": { + "hashes": [ + "sha256:67045236dcfd6816dc439556d009594abf643e5eb48992e36beac09c2ca659b8" + ], + "version": "==0.17.1" + }, + "httplib2": { + "hashes": [ + "sha256:23914b5487dfe8ef09db6656d6d63afb0cf3054ad9ebc50868ddc8e166b5f8e8", + "sha256:a18121c7c72a56689efbf1aef990139ad940fee1e64c6f2458831736cd593600" + ], + "version": "==0.12.3" + }, + "idna": { + "hashes": [ + "sha256:c357b3f628cf53ae2c4c05627ecc484553142ca23264e593d327bcde5e9c3407", + "sha256:ea8b7f6188e6fa117537c3df7da9fc686d485087abf6ac197f9c46432f7e4a3c" + ], + "version": "==2.8" + }, + "idna-ssl": { + "hashes": [ + "sha256:a933e3bb13da54383f9e8f35dc4f9cb9eb9b3b78c6b36f311254d6d0d92c6c7c" + ], + "index": "pypi", + "markers": "python_version < '3.7'", + "version": "==1.1.0" + }, + "isodate": { + "hashes": [ + "sha256:2e364a3d5759479cdb2d37cce6b9376ea504db2ff90252a2e5b7cc89cc9ff2d8", + "sha256:aa4d33c06640f5352aca96e4b81afd8ab3b47337cc12089822d6f322ac772c81" + ], + "version": "==0.6.0" + }, + "jsonschema": { + "hashes": [ + "sha256:0c0a81564f181de3212efa2d17de1910f8732fa1b71c42266d983cd74304e20d", + "sha256:a5f6559964a3851f59040d3b961de5e68e70971afb88ba519d27e6a039efff1a" + ], + "version": "==3.0.1" + }, + "lxml": { + "hashes": [ + "sha256:03984196d00670b2ab14ae0ea83d5cc0cfa4f5a42558afa9ab5fa745995328f5", + "sha256:0815b0c9f897468de6a386dc15917a0becf48cc92425613aa8bbfc7f0f82951f", + "sha256:175f3825f075cf02d15099eb52658457cf0ff103dcf11512b5d2583e1d40f58b", + "sha256:30e14c62d88d1e01a26936ecd1c6e784d4afc9aa002bba4321c5897937112616", + "sha256:3210da6f36cf4b835ff1be853962b22cc354d506f493b67a4303c88bbb40d57b", + "sha256:40f60819fbd5bad6e191ba1329bfafa09ab7f3f174b3d034d413ef5266963294", + "sha256:43b26a865a61549919f8a42e094dfdb62847113cf776d84bd6b60e4e3fc20ea3", + "sha256:4a03dd682f8e35a10234904e0b9508d705ff98cf962c5851ed052e9340df3d90", + "sha256:62f382cddf3d2e52cf266e161aa522d54fd624b8cc567bc18f573d9d50d40e8e", + "sha256:7b98f0325be8450da70aa4a796c4f06852949fe031878b4aa1d6c417a412f314", + "sha256:846a0739e595871041385d86d12af4b6999f921359b38affb99cdd6b54219a8f", + "sha256:a3080470559938a09a5d0ec558c005282e99ac77bf8211fb7b9a5c66390acd8d", + "sha256:ad841b78a476623955da270ab8d207c3c694aa5eba71f4792f65926dc46c6ee8", + "sha256:afdd75d9735e44c639ffd6258ce04a2de3b208f148072c02478162d0944d9da3", + "sha256:b4fbf9b552faff54742bcd0791ab1da5863363fb19047e68f6592be1ac2dab33", + "sha256:b90c4e32d6ec089d3fa3518436bdf5ce4d902a0787dbd9bb09f37afe8b994317", + "sha256:b91cfe4438c741aeff662d413fd2808ac901cc6229c838236840d11de4586d63", + "sha256:bdb0593a42070b0a5f138b79b872289ee73c8e25b3f0bea6564e795b55b6bcdd", + "sha256:c4e4bca2bb68ce22320297dfa1a7bf070a5b20bcbaec4ee023f83d2f6e76496f", + "sha256:cec4ab14af9eae8501be3266ff50c3c2aecc017ba1e86c160209bb4f0423df6a", + "sha256:e83b4b2bf029f5104bc1227dbb7bf5ace6fd8fabaebffcd4f8106fafc69fc45f", + "sha256:e995b3734a46d41ae60b6097f7c51ba9958648c6d1e0935b7e0ee446ee4abe22", + "sha256:f679d93dec7f7210575c85379a31322df4c46496f184ef650d3aba1484b38a2d", + "sha256:fd213bb5166e46974f113c8228daaef1732abc47cb561ce9c4c8eaed4bd3b09b", + "sha256:fdcb57b906dbc1f80666e6290e794ab8fb959a2e17aa5aee1758a85d1da4533f", + "sha256:ff424b01d090ffe1947ec7432b07f536912e0300458f9a7f48ea217dd8362b86" + ], + "index": "pypi", + "version": "==4.3.3" + }, + "maclookup": { + "hashes": [ + "sha256:33bf8eaebe3b1e4ab4ae9277dd93c78024e0ebf6b3c42f76c37695bc26ce287a", + "sha256:795e792cd3e03c9bdad77e52904d43ff71d3ac03b360443f99d4bae08a6bffef" + ], + "index": "pypi", + "version": "==1.0.3" + }, + "misp-modules": { + "editable": true, + "path": "." + }, + "multidict": { + "hashes": [ + "sha256:024b8129695a952ebd93373e45b5d341dbb87c17ce49637b34000093f243dd4f", + "sha256:041e9442b11409be5e4fc8b6a97e4bcead758ab1e11768d1e69160bdde18acc3", + "sha256:045b4dd0e5f6121e6f314d81759abd2c257db4634260abcfe0d3f7083c4908ef", + "sha256:047c0a04e382ef8bd74b0de01407e8d8632d7d1b4db6f2561106af812a68741b", + "sha256:068167c2d7bbeebd359665ac4fff756be5ffac9cda02375b5c5a7c4777038e73", + "sha256:148ff60e0fffa2f5fad2eb25aae7bef23d8f3b8bdaf947a65cdbe84a978092bc", + "sha256:1d1c77013a259971a72ddaa83b9f42c80a93ff12df6a4723be99d858fa30bee3", + "sha256:1d48bc124a6b7a55006d97917f695effa9725d05abe8ee78fd60d6588b8344cd", + "sha256:31dfa2fc323097f8ad7acd41aa38d7c614dd1960ac6681745b6da124093dc351", + "sha256:34f82db7f80c49f38b032c5abb605c458bac997a6c3142e0d6c130be6fb2b941", + "sha256:3d5dd8e5998fb4ace04789d1d008e2bb532de501218519d70bb672c4c5a2fc5d", + "sha256:4a6ae52bd3ee41ee0f3acf4c60ceb3f44e0e3bc52ab7da1c2b2aa6703363a3d1", + "sha256:4b02a3b2a2f01d0490dd39321c74273fed0568568ea0e7ea23e02bd1fb10a10b", + "sha256:4b843f8e1dd6a3195679d9838eb4670222e8b8d01bc36c9894d6c3538316fa0a", + "sha256:5de53a28f40ef3c4fd57aeab6b590c2c663de87a5af76136ced519923d3efbb3", + "sha256:61b2b33ede821b94fa99ce0b09c9ece049c7067a33b279f343adfe35108a4ea7", + "sha256:6a3a9b0f45fd75dc05d8e93dc21b18fc1670135ec9544d1ad4acbcf6b86781d0", + "sha256:76ad8e4c69dadbb31bad17c16baee61c0d1a4a73bed2590b741b2e1a46d3edd0", + "sha256:7ba19b777dc00194d1b473180d4ca89a054dd18de27d0ee2e42a103ec9b7d014", + "sha256:7c1b7eab7a49aa96f3db1f716f0113a8a2e93c7375dd3d5d21c4941f1405c9c5", + "sha256:7fc0eee3046041387cbace9314926aa48b681202f8897f8bff3809967a049036", + "sha256:8ccd1c5fff1aa1427100ce188557fc31f1e0a383ad8ec42c559aabd4ff08802d", + "sha256:8e08dd76de80539d613654915a2f5196dbccc67448df291e69a88712ea21e24a", + "sha256:c18498c50c59263841862ea0501da9f2b3659c00db54abfbf823a80787fde8ce", + "sha256:c49db89d602c24928e68c0d510f4fcf8989d77defd01c973d6cbe27e684833b1", + "sha256:ce20044d0317649ddbb4e54dab3c1bcc7483c78c27d3f58ab3d0c7e6bc60d26a", + "sha256:d1071414dd06ca2eafa90c85a079169bfeb0e5f57fd0b45d44c092546fcd6fd9", + "sha256:d3be11ac43ab1a3e979dac80843b42226d5d3cccd3986f2e03152720a4297cd7", + "sha256:db603a1c235d110c860d5f39988ebc8218ee028f07a7cbc056ba6424372ca31b" + ], + "version": "==4.5.2" + }, + "np": { + "hashes": [ + "sha256:781265283f3823663ad8fb48741aae62abcf4c78bc19f908f8aa7c1d3eb132f8" + ], + "index": "pypi", + "version": "==1.0.2" + }, + "numpy": { + "hashes": [ + "sha256:0e2eed77804b2a6a88741f8fcac02c5499bba3953ec9c71e8b217fad4912c56c", + "sha256:1c666f04553ef70fda54adf097dbae7080645435fc273e2397f26bbf1d127bbb", + "sha256:1f46532afa7b2903bfb1b79becca2954c0a04389d19e03dc73f06b039048ac40", + "sha256:315fa1b1dfc16ae0f03f8fd1c55f23fd15368710f641d570236f3d78af55e340", + "sha256:3d5fcea4f5ed40c3280791d54da3ad2ecf896f4c87c877b113576b8280c59441", + "sha256:48241759b99d60aba63b0e590332c600fc4b46ad597c9b0a53f350b871ef0634", + "sha256:4b4f2924b36d857cf302aec369caac61e43500c17eeef0d7baacad1084c0ee84", + "sha256:54fe3b7ed9e7eb928bbc4318f954d133851865f062fa4bbb02ef8940bc67b5d2", + "sha256:5a8f021c70e6206c317974c93eaaf9bc2b56295b6b1cacccf88846e44a1f33fc", + "sha256:754a6be26d938e6ca91942804eb209307b73f806a1721176278a6038869a1686", + "sha256:771147e654e8b95eea1293174a94f34e2e77d5729ad44aefb62fbf8a79747a15", + "sha256:78a6f89da87eeb48014ec652a65c4ffde370c036d780a995edaeb121d3625621", + "sha256:7fde5c2a3a682a9e101e61d97696687ebdba47637611378b4127fe7e47fdf2bf", + "sha256:80d99399c97f646e873dd8ce87c38cfdbb668956bbc39bc1e6cac4b515bba2a0", + "sha256:88a72c1e45a0ae24d1f249a529d9f71fe82e6fa6a3fd61414b829396ec585900", + "sha256:a4f4460877a16ac73302a9c077ca545498d9fe64e6a81398d8e1a67e4695e3df", + "sha256:a61255a765b3ac73ee4b110b28fccfbf758c985677f526c2b4b39c48cc4b509d", + "sha256:ab4896a8c910b9a04c0142871d8800c76c8a2e5ff44763513e1dd9d9631ce897", + "sha256:abbd6b1c2ef6199f4b7ca9f818eb6b31f17b73a6110aadc4e4298c3f00fab24e", + "sha256:b16d88da290334e33ea992c56492326ea3b06233a00a1855414360b77ca72f26", + "sha256:b78a1defedb0e8f6ae1eb55fa6ac74ab42acc4569c3a2eacc2a407ee5d42ebcb", + "sha256:cfef82c43b8b29ca436560d51b2251d5117818a8d1fb74a8384a83c096745dad", + "sha256:d160e57731fcdec2beda807ebcabf39823c47e9409485b5a3a1db3a8c6ce763e" + ], + "version": "==1.16.3" + }, + "oauth2": { + "hashes": [ + "sha256:15b5c42301f46dd63113f1214b0d81a8b16254f65a86d3c32a1b52297f3266e6", + "sha256:c006a85e7c60107c7cc6da1b184b5c719f6dd7202098196dfa6e55df669b59bf" + ], + "index": "pypi", + "version": "==1.9.0.post1" + }, + "odtreader": { + "editable": true, + "git": "https://github.com/cartertemm/ODTReader.git/", + "ref": "49d6938693f6faa3ff09998f86dba551ae3a996b" + }, + "opencv-python": { + "hashes": [ + "sha256:1703a296a96d3d46615e5053f224867977accb4240bcaa0fcabcb0768bf5ac13", + "sha256:1777ce7535ee7a1995cae168a107a1320e9df13648b930e72a1a2c2eccd64cda", + "sha256:1e5520482fb18fbd64d079e7f17ac0018f195fd75f6360a53bb82d7903106b50", + "sha256:25522dcf2529614750a71112a6659759080b4bdc2323f19d47f4d895960fd796", + "sha256:2af5f2842ad44c65ae2647377e0ff198719e1a1cfc9c6a19bc0c525c035d4bd8", + "sha256:31ec48d7eca13fc25c287dea7cecab453976e372cad8f50d55c054a247efda21", + "sha256:47cf48ff5dbd554e9f58cc9e98cf0b5de3f6a971172612bffa06bc5fb79ce872", + "sha256:494f98366bb5d6c2ac7e50e6617139f353704fd97a6d12ec9d392e72817d5cb0", + "sha256:4a9845870739e640e3350a8d98d511c92c087fe3d66090e83be7bf94e0ac64f7", + "sha256:4ac29cc0847d948a6636899014e84e165c30cc8779d6218394d44363462a01ce", + "sha256:5857ace03b7854221abf8072462d306c2c2ce4e366190b21d90ee8ee8aaf5bb4", + "sha256:5b4a23d99d5a2874767034466f5a8fd37b9f93ac14955a01b1a208983c76b9ad", + "sha256:734d87a5021c037064beb62133e135e66c7128e401a63b8b842b809ae2093749", + "sha256:78005c1c5d15ef4e32e0f485557bd15b5b6d87f49c19db7fe3e9246a61ebe7e4", + "sha256:81ae2283225c5c52fc3d72debd4241c30ccff2bb922578bf7867f9851cce3acb", + "sha256:88dbf900f297fdae0f62b899d6a784d8868ec2135854c5f8a9abbad00a6f0c5b", + "sha256:8c98ea7b8d327a31cd6028782a06147d0e0329ae8e829e881fb5d02f7ed8aec9", + "sha256:937d4686fef6967921145290f5b50c01c00c5b5d3542a6519e8a85cd88448723", + "sha256:a057958c0e362b3c4f03b9af1cbdb6d5af035fd22ecd7fd794eba8fdeb049eb8", + "sha256:c41eab31fa2c641226c6187caa391a688d064c99f078d604574f1912296b771f", + "sha256:cf4f7e62d1f80d1fa85a1693a3500def5cde54b2b75212b3609e552e4c25acfb", + "sha256:d90d60143e18334330c149f293071c9f2f3c79c896f33dc4ec65099e58baaaa7", + "sha256:db3106b7ca86999a7bd1f2fcc93e49314e5e6e451356774e421a69428df5020b", + "sha256:dbaf264db56f4771dfac6624f438bc4dc670aa94f61a6138848fcab7e9e77380", + "sha256:e65206c4cf651dc9cf0829962fae8bec986767c9f123d6a1ad17f9356bf7257e", + "sha256:eac94ddc78c58e891cff7180274317dad2938a4ddfc6ced1c04846c7f50e77e9", + "sha256:f2e828711f044a965509c862b3a59b3181e9c56c145a950cb53d43fec54e66d2" + ], + "index": "pypi", + "version": "==4.1.0.25" + }, + "pandas": { + "hashes": [ + "sha256:071e42b89b57baa17031af8c6b6bbd2e9a5c68c595bc6bf9adabd7a9ed125d3b", + "sha256:17450e25ae69e2e6b303817bdf26b2cd57f69595d8550a77c308be0cd0fd58fa", + "sha256:17916d818592c9ec891cbef2e90f98cc85e0f1e89ed0924c9b5220dc3209c846", + "sha256:2538f099ab0e9f9c9d09bbcd94b47fd889bad06dc7ae96b1ed583f1dc1a7a822", + "sha256:366f30710172cb45a6b4f43b66c220653b1ea50303fbbd94e50571637ffb9167", + "sha256:42e5ad741a0d09232efbc7fc648226ed93306551772fc8aecc6dce9f0e676794", + "sha256:4e718e7f395ba5bfe8b6f6aaf2ff1c65a09bb77a36af6394621434e7cc813204", + "sha256:4f919f409c433577a501e023943e582c57355d50a724c589e78bc1d551a535a2", + "sha256:4fe0d7e6438212e839fc5010c78b822664f1a824c0d263fd858f44131d9166e2", + "sha256:5149a6db3e74f23dc3f5a216c2c9ae2e12920aa2d4a5b77e44e5b804a5f93248", + "sha256:627594338d6dd995cfc0bacd8e654cd9e1252d2a7c959449228df6740d737eb8", + "sha256:83c702615052f2a0a7fb1dd289726e29ec87a27272d775cb77affe749cca28f8", + "sha256:8c872f7fdf3018b7891e1e3e86c55b190e6c5cee70cab771e8f246c855001296", + "sha256:90f116086063934afd51e61a802a943826d2aac572b2f7d55caaac51c13db5b5", + "sha256:a3352bacac12e1fc646213b998bce586f965c9d431773d9e91db27c7c48a1f7d", + "sha256:bcdd06007cca02d51350f96debe51331dec429ac8f93930a43eb8fb5639e3eb5", + "sha256:c1bd07ebc15285535f61ddd8c0c75d0d6293e80e1ee6d9a8d73f3f36954342d0", + "sha256:c9a4b7c55115eb278c19aa14b34fcf5920c8fe7797a09b7b053ddd6195ea89b3", + "sha256:cc8fc0c7a8d5951dc738f1c1447f71c43734244453616f32b8aa0ef6013a5dfb", + "sha256:d7b460bc316064540ce0c41c1438c416a40746fd8a4fb2999668bf18f3c4acf1" + ], + "index": "pypi", + "version": "==0.24.2" + }, + "pandas-ods-reader": { + "hashes": [ + "sha256:0f7d510639c8957a06aa1227b9f84d1be47a437dfd306464ce803b91cf5eeec4", + "sha256:d85ef58fc3aeac1616028d22954b6ef2e8983ab9bae015e1e90ce3979d138553" + ], + "index": "pypi", + "version": "==0.0.6" + }, + "passivetotal": { + "hashes": [ + "sha256:d745a6519ec04e3a354682978ebf07778bf7602beac30307cbad075ff1a4418d" + ], + "index": "pypi", + "version": "==1.0.30" + }, + "pdftotext": { + "hashes": [ + "sha256:e3ad11efe0aa22cbfc46aa1296b2ea5a52ad208b778288311f2801adef178ccb" + ], + "index": "pypi", + "version": "==2.1.1" + }, + "pillow": { + "hashes": [ + "sha256:15c056bfa284c30a7f265a41ac4cbbc93bdbfc0dfe0613b9cb8a8581b51a9e55", + "sha256:1a4e06ba4f74494ea0c58c24de2bb752818e9d504474ec95b0aa94f6b0a7e479", + "sha256:1c3c707c76be43c9e99cb7e3d5f1bee1c8e5be8b8a2a5eeee665efbf8ddde91a", + "sha256:1fd0b290203e3b0882d9605d807b03c0f47e3440f97824586c173eca0aadd99d", + "sha256:24114e4a6e1870c5a24b1da8f60d0ba77a0b4027907860188ea82bd3508c80eb", + "sha256:258d886a49b6b058cd7abb0ab4b2b85ce78669a857398e83e8b8e28b317b5abb", + "sha256:33c79b6dd6bc7f65079ab9ca5bebffb5f5d1141c689c9c6a7855776d1b09b7e8", + "sha256:367385fc797b2c31564c427430c7a8630db1a00bd040555dfc1d5c52e39fcd72", + "sha256:3c1884ff078fb8bf5f63d7d86921838b82ed4a7d0c027add773c2f38b3168754", + "sha256:44e5240e8f4f8861d748f2a58b3f04daadab5e22bfec896bf5434745f788f33f", + "sha256:46aa988e15f3ea72dddd81afe3839437b755fffddb5e173886f11460be909dce", + "sha256:74d90d499c9c736d52dd6d9b7221af5665b9c04f1767e35f5dd8694324bd4601", + "sha256:809c0a2ce9032cbcd7b5313f71af4bdc5c8c771cb86eb7559afd954cab82ebb5", + "sha256:85d1ef2cdafd5507c4221d201aaf62fc9276f8b0f71bd3933363e62a33abc734", + "sha256:8c3889c7681af77ecfa4431cd42a2885d093ecb811e81fbe5e203abc07e0995b", + "sha256:9218d81b9fca98d2c47d35d688a0cea0c42fd473159dfd5612dcb0483c63e40b", + "sha256:9aa4f3827992288edd37c9df345783a69ef58bd20cc02e64b36e44bcd157bbf1", + "sha256:9d80f44137a70b6f84c750d11019a3419f409c944526a95219bea0ac31f4dd91", + "sha256:b7ebd36128a2fe93991293f997e44be9286503c7530ace6a55b938b20be288d8", + "sha256:c4c78e2c71c257c136cdd43869fd3d5e34fc2162dc22e4a5406b0ebe86958239", + "sha256:c6a842537f887be1fe115d8abb5daa9bc8cc124e455ff995830cc785624a97af", + "sha256:cf0a2e040fdf5a6d95f4c286c6ef1df6b36c218b528c8a9158ec2452a804b9b8", + "sha256:cfd28aad6fc61f7a5d4ee556a997dc6e5555d9381d1390c00ecaf984d57e4232", + "sha256:dca5660e25932771460d4688ccbb515677caaf8595f3f3240ec16c117deff89a", + "sha256:de7aedc85918c2f887886442e50f52c1b93545606317956d65f342bd81cb4fc3", + "sha256:e6c0bbf8e277b74196e3140c35f9a1ae3eafd818f7f2d3a15819c49135d6c062" + ], + "index": "pypi", + "version": "==6.0.0" + }, + "psutil": { + "hashes": [ + "sha256:206eb909aa8878101d0eca07f4b31889c748f34ed6820a12eb3168c7aa17478e", + "sha256:649f7ffc02114dced8fbd08afcd021af75f5f5b2311bc0e69e53e8f100fe296f", + "sha256:6ebf2b9c996bb8c7198b385bade468ac8068ad8b78c54a58ff288cd5f61992c7", + "sha256:753c5988edc07da00dafd6d3d279d41f98c62cd4d3a548c4d05741a023b0c2e7", + "sha256:76fb0956d6d50e68e3f22e7cc983acf4e243dc0fcc32fd693d398cb21c928802", + "sha256:828e1c3ca6756c54ac00f1427fdac8b12e21b8a068c3bb9b631a1734cada25ed", + "sha256:a4c62319ec6bf2b3570487dd72d471307ae5495ce3802c1be81b8a22e438b4bc", + "sha256:acba1df9da3983ec3c9c963adaaf530fcb4be0cd400a8294f1ecc2db56499ddd", + "sha256:ef342cb7d9b60e6100364f50c57fa3a77d02ff8665d5b956746ac01901247ac4" + ], + "version": "==5.6.2" + }, + "pybgpranking": { + "editable": true, + "git": "https://github.com/D4-project/BGP-Ranking.git/", + "ref": "4e0741056bcc0077de1120b8724a31330b26033e", + "subdirectory": "client" + }, + "pydnstrails": { + "editable": true, + "git": "https://github.com/sebdraven/pydnstrails", + "ref": "48c1f740025c51289f43a24863d1845ff12fd21a" + }, + "pyeupi": { + "hashes": [ + "sha256:35b0e6b430f23ecd303f7cc7a8fe5147cf2509a5b2254eaf9695392c0af02901" + ], + "index": "pypi", + "version": "==1.0" + }, + "pygeoip": { + "hashes": [ + "sha256:1938b9dac7b00d77f94d040b9465ea52c938f3fcdcd318b5537994f3c16aef96", + "sha256:f22c4e00ddf1213e0fae36dc60b46ee7c25a6339941ec1a975539014c1f9a96d" + ], + "index": "pypi", + "version": "==0.3.2" + }, + "pyintel471": { + "editable": true, + "git": "https://github.com/MISP/PyIntel471.git", + "ref": "0df8d51f1c1425de66714b3a5a45edb69b8cc2fc" + }, + "pyipasnhistory": { + "editable": true, + "git": "https://github.com/D4-project/IPASN-History.git/", + "ref": "c0c2bbf8d70811982dad065ea463a7e01593a38d", + "subdirectory": "client" + }, + "pymisp": { + "editable": true, + "git": "https://github.com/MISP/PyMISP.git", + "ref": "582dda0ce2a8ca8e1dd2cf3842e0491caca51c62" + }, + "pyonyphe": { + "editable": true, + "git": "https://github.com/sebdraven/pyonyphe", + "ref": "cbb0168d5cb28a9f71f7ab3773164a7039ccdb12" + }, + "pyparsing": { + "hashes": [ + "sha256:1873c03321fc118f4e9746baf201ff990ceb915f433f23b395f5580d1840cb2a", + "sha256:9b6323ef4ab914af344ba97510e966d64ba91055d6b9afa6b30799340e89cc03" + ], + "version": "==2.4.0" + }, + "pypdns": { + "hashes": [ + "sha256:0356360156dd26d2cf27a415a10ff2bd1ff1d2eb3b2dd51b35553d60b87fd328" + ], + "index": "pypi", + "version": "==1.3" + }, + "pypssl": { + "hashes": [ + "sha256:4dbe772aefdf4ab18934d83cde79e2fc5d5ba9d2b4153dc419a63faab3432643" + ], + "index": "pypi", + "version": "==2.1" + }, + "pyrsistent": { + "hashes": [ + "sha256:5403d37f4d55ff4572b5b5676890589f367a9569529c6f728c11046c4ea4272b" + ], + "version": "==0.15.1" + }, + "pytesseract": { + "hashes": [ + "sha256:11c20321595b6e2e904b594633edf1a717212b13bac7512986a2d807b8849770" + ], + "index": "pypi", + "version": "==0.2.6" + }, + "python-dateutil": { + "hashes": [ + "sha256:7e6584c74aeed623791615e26efd690f29817a27c73085b78e4bad02493df2fb", + "sha256:c89805f6f4d64db21ed966fda138f8a5ed7a4fdbc1a8ee329ce1b74e3c74da9e" + ], + "version": "==2.8.0" + }, + "python-docx": { + "hashes": [ + "sha256:bc76ecac6b2d00ce6442a69d03a6f35c71cd72293cd8405a7472dfe317920024" + ], + "index": "pypi", + "version": "==0.8.10" + }, + "python-pptx": { + "hashes": [ + "sha256:1f2d5d1d923d91f50a1f0ed794935e7d670993fdcb6c12c81cc83977c1f23e14" + ], + "index": "pypi", + "version": "==0.6.17" + }, + "pytz": { + "hashes": [ + "sha256:303879e36b721603cc54604edcac9d20401bdbe31e1e4fdee5b9f98d5d31dfda", + "sha256:d747dd3d23d77ef44c6a3526e274af6efeb0a6f1afd5a69ba4d5be4098c8e141" + ], + "version": "==2019.1" + }, + "pyyaml": { + "hashes": [ + "sha256:1adecc22f88d38052fb787d959f003811ca858b799590a5eaa70e63dca50308c", + "sha256:436bc774ecf7c103814098159fbb84c2715d25980175292c648f2da143909f95", + "sha256:460a5a4248763f6f37ea225d19d5c205677d8d525f6a83357ca622ed541830c2", + "sha256:5a22a9c84653debfbf198d02fe592c176ea548cccce47553f35f466e15cf2fd4", + "sha256:7a5d3f26b89d688db27822343dfa25c599627bc92093e788956372285c6298ad", + "sha256:9372b04a02080752d9e6f990179a4ab840227c6e2ce15b95e1278456664cf2ba", + "sha256:a5dcbebee834eaddf3fa7366316b880ff4062e4bcc9787b78c7fbb4a26ff2dd1", + "sha256:aee5bab92a176e7cd034e57f46e9df9a9862a71f8f37cad167c6fc74c65f5b4e", + "sha256:c51f642898c0bacd335fc119da60baae0824f2cde95b0330b56c0553439f0673", + "sha256:c68ea4d3ba1705da1e0d85da6684ac657912679a649e8868bd850d2c299cce13", + "sha256:e23d0cc5299223dcc37885dae624f382297717e459ea24053709675a976a3e19" + ], + "version": "==5.1" + }, + "pyzbar": { + "hashes": [ + "sha256:0e204b904e093e5e75aa85e0203bb0e02888105732a509b51f31cff400f34265", + "sha256:496249b546be70ec98c0ff0ad9151e73daaffff129266df86150a15dcd8dac4c", + "sha256:7d6c01d2c0a352fa994aa91b5540d1caeaeaac466656eb41468ca5df33be9f2e" + ], + "index": "pypi", + "version": "==0.1.8" + }, + "rdflib": { + "hashes": [ + "sha256:58d5994610105a457cff7fdfe3d683d87786c5028a45ae032982498a7e913d6f", + "sha256:da1df14552555c5c7715d8ce71c08f404c988c58a1ecd38552d0da4fc261280d" + ], + "version": "==4.2.2" + }, + "redis": { + "hashes": [ + "sha256:6946b5dca72e86103edc8033019cc3814c031232d339d5f4533b02ea85685175", + "sha256:8ca418d2ddca1b1a850afa1680a7d2fd1f3322739271de4b704e0d4668449273" + ], + "version": "==3.2.1" + }, + "reportlab": { + "hashes": [ + "sha256:13714baa9753bfca94df67716cccb3eedcaaa30cf7bc40b282d338a718e0b610", + "sha256:16c1bb717a1a0e2ed065aa31eb5968dc03b34b728926216ef282cefeebf50c1b", + "sha256:2d9d66770880e8d112b6b925458593d34b84947c355847578cd974df0a3e3b8b", + "sha256:3334a30e477e1dfa0276eb41ed5bfd2a684c9917e55c6acb30d91abac46555f6", + "sha256:33796ea88d20c05958903c11ff34d896e462381f4a0f550854aabe6dd07cc189", + "sha256:5184f53c0babeedb4ebe297eb97794822cb122456ca03411c68256730c998d48", + "sha256:53589c5db35041920cd7a92a171506ff4eb5542ab8415af272fe4558927399a8", + "sha256:58ba0a9ca51d666d55ec7ecd83ab14763b79e7e5e0775b7717694e94c2fbbf18", + "sha256:6998652beba357da9687eba13b46ceccd0a7a2153d656cf8a03b7494c915e077", + "sha256:6c3b07c8a94ee9609c31a51e4131891c8330ffd379db23ab582fd225a06a4e59", + "sha256:7b248d2d9d4ab6d4cad91eb2b153b2c4c7b3fced89cb5a5b5bfbc7d09593871a", + "sha256:81d991c9994a576ea053b281b8c9afc28b12261197d478e72055d381f60fa26f", + "sha256:8a9a8be6841b88b13aa9c0f7d193c6d24b04b10c2e7cbf6657b1807bac5b1e9f", + "sha256:8de3107436e68014890adcec446207fd98d60c26e7feae6f550eea9eab3a622d", + "sha256:90f85afb68f7cd4fd8681af3123d23488274e4d1c3fea8d3831ef7257d9733c8", + "sha256:94857052c951ffa56de95cfce483fdf3de19587db4b1bc4f6a4043fb1c4af772", + "sha256:a47603d9b975e8870ed30ade22db3478b030dd7a6041c8272c3719d9bbeaef34", + "sha256:a5671b152d3f85963d8450e956ddecfb5d30af62dd1f73207fab9aa32a0240d2", + "sha256:a745cd1a4368fac093deff3b65614f052eced6afa9ed7fe223da2a52813f2e23", + "sha256:af454e8e844e3eeace5aead02701748b2a908f3e8cbc386cc5ddc185cef8c57f", + "sha256:c3c6c1234eed451111e969c776688e866554cb362250b88f782ab80ea62f9114", + "sha256:cc1cf8ba1b2f1669f5d873a7cfdb9e07a920243d74a66a78f8afa2cf78587864", + "sha256:cce3c9b0e115ea5553615a647b6644e5724bdc776e778593ffa5f383d907afb2", + "sha256:d137feacef83627d10adb869aa6998f29eb7af4cff3101c9fc94a1d73943b6cc", + "sha256:d7213814d050ca3b0bf7e018f94ed947e90477cd36aff298ff5932b849a0f36a", + "sha256:e381d08675807d2bb465717f69818040173351650af82730d721ecad429279a6", + "sha256:e39c6efdd64027be56ce991f7ffb86c7cee47da8c844c3544bbd68ef842831a0", + "sha256:f8526cfbbad599d22de6eb59b5a43610ba9b28f74ac2406125fe803f31a262a6" + ], + "index": "pypi", + "version": "==3.5.20" + }, + "requests": { + "hashes": [ + "sha256:502a824f31acdacb3a35b6690b5fbf0bc41d63a24a45c4004352b0242707598e", + "sha256:7bf2a778576d825600030a110f3c0e3e8edc51dfaafe1c146e39a2027784957b" + ], + "index": "pypi", + "version": "==2.21.0" + }, + "requests-cache": { + "hashes": [ + "sha256:6822f788c5ee248995c4bfbd725de2002ad710182ba26a666e85b64981866060", + "sha256:73a7211870f7d67af5fd81cad2f67cfe1cd3eb4ee6a85155e07613968cc72dfc" + ], + "version": "==0.5.0" + }, + "shodan": { + "hashes": [ + "sha256:c30baebce853ad67677bf002dde96a1ca1a9729bdd300fbb3c5e5d889547a639" + ], + "index": "pypi", + "version": "==1.12.1" + }, + "sigmatools": { + "hashes": [ + "sha256:ae980b6d6fd466294911efa493934d24e3c5df406da4a190b9fff0943a81cc5f" + ], + "index": "pypi", + "version": "==0.10" + }, + "six": { + "hashes": [ + "sha256:3350809f0555b11f552448330d0b52d5f24c91a322ea4a15ef22629740f3761c", + "sha256:d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73" + ], + "version": "==1.12.0" + }, + "soupsieve": { + "hashes": [ + "sha256:6898e82ecb03772a0d82bd0d0a10c0d6dcc342f77e0701d0ec4a8271be465ece", + "sha256:b20eff5e564529711544066d7dc0f7661df41232ae263619dede5059799cdfca" + ], + "version": "==1.9.1" + }, + "sparqlwrapper": { + "hashes": [ + "sha256:14ec551f0d60b4a496ffcc31f15337e844c085b8ead8cbe9a7178748a6de3794", + "sha256:21928e7a97f565e772cdeeb0abad428960f4307e3a13dbdd8f6d3da8a6a506c9", + "sha256:abc3e7eadcad32fa69a85c003853e2f6f73bda6cc999853838f401a5a1ea1109" + ], + "index": "pypi", + "version": "==1.8.4" + }, + "stix2-patterns": { + "hashes": [ + "sha256:137cbe28d29af774d526a49d60b3a40af7c19fe1e5f252e741bb25f253d5616f" + ], + "index": "pypi", + "version": "==1.1.0" + }, + "tabulate": { + "hashes": [ + "sha256:8af07a39377cee1103a5c8b3330a421c2d99b9141e9cc5ddd2e3263fea416943" + ], + "version": "==0.8.3" + }, + "tornado": { + "hashes": [ + "sha256:1174dcb84d08887b55defb2cda1986faeeea715fff189ef3dc44cce99f5fca6b", + "sha256:2613fab506bd2aedb3722c8c64c17f8f74f4070afed6eea17f20b2115e445aec", + "sha256:44b82bc1146a24e5b9853d04c142576b4e8fa7a92f2e30bc364a85d1f75c4de2", + "sha256:457fcbee4df737d2defc181b9073758d73f54a6cfc1f280533ff48831b39f4a8", + "sha256:49603e1a6e24104961497ad0c07c799aec1caac7400a6762b687e74c8206677d", + "sha256:8c2f40b99a8153893793559919a355d7b74649a11e59f411b0b0a1793e160bc0", + "sha256:e1d897889c3b5a829426b7d52828fb37b28bc181cd598624e65c8be40ee3f7fa" + ], + "version": "==6.0.2" + }, + "url-normalize": { + "hashes": [ + "sha256:3468d64cb22a9092a2c086e46c781f741dc9a1689b24e9b48ab5e8244ffa6c02", + "sha256:51e0f14050c79e732d175c33d12167f5e642cc23e0cb23275236af843faf884f" + ], + "version": "==1.4.1" + }, + "urlarchiver": { + "hashes": [ + "sha256:652e0890dab58bf62a759656671dcfb9a40eb4a77aac8a8d93154f00360238b5" + ], + "index": "pypi", + "version": "==0.2" + }, + "urllib3": { + "hashes": [ + "sha256:4c291ca23bbb55c76518905869ef34bdd5f0e46af7afe6861e8375643ffee1a0", + "sha256:9a247273df709c4fedb38c711e44292304f73f39ab01beda9f6b9fc375669ac3" + ], + "version": "==1.24.2" + }, + "uwhois": { + "editable": true, + "git": "https://github.com/Rafiot/uwhoisd.git", + "ref": "411572840eba4c72dc321c549b36a54ed5cea9de", + "subdirectory": "client" + }, + "vulners": { + "hashes": [ + "sha256:146ef130f215b50cdff790b06b4886c7edb325c075e9fce4bf1d3ab8d64a10d0", + "sha256:53406a86126159eaee9575fa667c99459bfdf9dd8c06bd0ce73fbe536b305e30", + "sha256:a258ccdbaee586207bc80d3590f0315ff151cfe16ea54f2e1629a6018fd9f2a3" + ], + "index": "pypi", + "version": "==1.5.0" + }, + "wand": { + "hashes": [ + "sha256:63ab24dee0264a44f5f045d4ecc0d392bc1cc195e5a2f80ce537b2c205c3033b", + "sha256:a2c318993791fab4fcfd460045415176f81d42f8c6fd8a88fb8d74d2f0f34b97", + "sha256:f68f32f2e4eca663a361d36148f06372de560442dcf8c785a53a64ee282572c9" + ], + "index": "pypi", + "version": "==0.5.3" + }, + "xlrd": { + "hashes": [ + "sha256:546eb36cee8db40c3eaa46c351e67ffee6eeb5fa2650b71bc4c758a29a1b29b2", + "sha256:e551fb498759fa3a5384a94ccd4c3c02eb7c00ea424426e212ac0c57be9dfbde" + ], + "index": "pypi", + "version": "==1.2.0" + }, + "xlsxwriter": { + "hashes": [ + "sha256:2a40b427dac0f640031e5b33abe97e761de6e0f12d4d346e7b2e2b67cf6ee927", + "sha256:431edc9ba1132eec1996939aa83fffe41885d3042ab09d47c3086f41a156c430" + ], + "version": "==1.1.7" + }, + "yara-python": { + "hashes": [ + "sha256:03e5c5e333c8572e7994b0b11964d515d61a393f23c5e272f8d0e4229f368c58", + "sha256:0423e08bd618752a028ac0405ff8e0103f3a8fd607dde7618a64a4c010c3757b", + "sha256:0a0dd632dcdb347d1a9a8b1f6a83b3a77d5e63f691357ea4021fb1cf1d7ff0a4", + "sha256:728b99627a8072a877eaaa4dafb4eff39d1b14ff4fd70d39f18899ce81e29625", + "sha256:7cb0d5724eccfa52e1bcd352a56cb4dc422aa51f5f6d0945d4f830783927513b", + "sha256:8c76531e89806c0309586dd4863a972d12f1d5d63261c6d4b9331a99859fd1d8", + "sha256:9472676583e212bc4e17c2236634e02273d53c872b350f0571b48e06183de233", + "sha256:9735b680a7d95c1d3f255c351bb067edc62cdb3c0999f7064278cb2c85245405", + "sha256:997f104590167220a9af5564c042ec4d6534261e7b8a5b49655d8dffecc6b8a2", + "sha256:a48e071d02a3699363e628ac899b5b7237803bcb4b512c92ebcb4fb9b1488497", + "sha256:b67c0d75a6519ca357b4b85ede9768c96a81fff20fbc169bd805ff009ddee561" + ], + "index": "pypi", + "version": "==3.8.1" + }, + "yarl": { + "hashes": [ + "sha256:024ecdc12bc02b321bc66b41327f930d1c2c543fa9a561b39861da9388ba7aa9", + "sha256:2f3010703295fbe1aec51023740871e64bb9664c789cba5a6bdf404e93f7568f", + "sha256:3890ab952d508523ef4881457c4099056546593fa05e93da84c7250516e632eb", + "sha256:3e2724eb9af5dc41648e5bb304fcf4891adc33258c6e14e2a7414ea32541e320", + "sha256:5badb97dd0abf26623a9982cd448ff12cb39b8e4c94032ccdedf22ce01a64842", + "sha256:73f447d11b530d860ca1e6b582f947688286ad16ca42256413083d13f260b7a0", + "sha256:7ab825726f2940c16d92aaec7d204cfc34ac26c0040da727cf8ba87255a33829", + "sha256:b25de84a8c20540531526dfbb0e2d2b648c13fd5dd126728c496d7c3fea33310", + "sha256:c6e341f5a6562af74ba55205dbd56d248daf1b5748ec48a0200ba227bb9e33f4", + "sha256:c9bb7c249c4432cd47e75af3864bc02d26c9594f49c82e2a28624417f0ae63b8", + "sha256:e060906c0c585565c718d1c3841747b61c5439af2211e185f6739a9412dfbde1" + ], + "version": "==1.3.0" + } + }, + "develop": { + "atomicwrites": { + "hashes": [ + "sha256:03472c30eb2c5d1ba9227e4c2ca66ab8287fbfbbda3888aa93dc2e28fc6811b4", + "sha256:75a9445bac02d8d058d5e1fe689654ba5a6556a1dfd8ce6ec55a0ed79866cfa6" + ], + "version": "==1.3.0" + }, + "attrs": { + "hashes": [ + "sha256:69c0dbf2ed392de1cb5ec704444b08a5ef81680a61cb899dc08127123af36a79", + "sha256:f0b870f674851ecbfbbbd364d6b5cbdff9dcedbc7f3f5e18a6891057f21fe399" + ], + "version": "==19.1.0" + }, + "certifi": { + "hashes": [ + "sha256:59b7658e26ca9c7339e00f8f4636cdfe59d34fa37b9b04f6f9e9926b3cece1a5", + "sha256:b26104d6835d1f5e49452a26eb2ff87fe7090b89dfcaee5ea2212697e1e1d7ae" + ], + "version": "==2019.3.9" + }, + "chardet": { + "hashes": [ + "sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae", + "sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691" + ], + "version": "==3.0.4" + }, + "codecov": { + "hashes": [ + "sha256:8ed8b7c6791010d359baed66f84f061bba5bd41174bf324c31311e8737602788", + "sha256:ae00d68e18d8a20e9c3288ba3875ae03db3a8e892115bf9b83ef20507732bed4" + ], + "index": "pypi", + "version": "==2.0.15" + }, + "coverage": { + "hashes": [ + "sha256:3684fabf6b87a369017756b551cef29e505cb155ddb892a7a29277b978da88b9", + "sha256:39e088da9b284f1bd17c750ac672103779f7954ce6125fd4382134ac8d152d74", + "sha256:3c205bc11cc4fcc57b761c2da73b9b72a59f8d5ca89979afb0c1c6f9e53c7390", + "sha256:465ce53a8c0f3a7950dfb836438442f833cf6663d407f37d8c52fe7b6e56d7e8", + "sha256:48020e343fc40f72a442c8a1334284620f81295256a6b6ca6d8aa1350c763bbe", + "sha256:5296fc86ab612ec12394565c500b412a43b328b3907c0d14358950d06fd83baf", + "sha256:5f61bed2f7d9b6a9ab935150a6b23d7f84b8055524e7be7715b6513f3328138e", + "sha256:68a43a9f9f83693ce0414d17e019daee7ab3f7113a70c79a3dd4c2f704e4d741", + "sha256:6b8033d47fe22506856fe450470ccb1d8ba1ffb8463494a15cfc96392a288c09", + "sha256:7ad7536066b28863e5835e8cfeaa794b7fe352d99a8cded9f43d1161be8e9fbd", + "sha256:7bacb89ccf4bedb30b277e96e4cc68cd1369ca6841bde7b005191b54d3dd1034", + "sha256:839dc7c36501254e14331bcb98b27002aa415e4af7ea039d9009409b9d2d5420", + "sha256:8f9a95b66969cdea53ec992ecea5406c5bd99c9221f539bca1e8406b200ae98c", + "sha256:932c03d2d565f75961ba1d3cec41ddde00e162c5b46d03f7423edcb807734eab", + "sha256:988529edadc49039d205e0aa6ce049c5ccda4acb2d6c3c5c550c17e8c02c05ba", + "sha256:998d7e73548fe395eeb294495a04d38942edb66d1fa61eb70418871bc621227e", + "sha256:9de60893fb447d1e797f6bf08fdf0dbcda0c1e34c1b06c92bd3a363c0ea8c609", + "sha256:9e80d45d0c7fcee54e22771db7f1b0b126fb4a6c0a2e5afa72f66827207ff2f2", + "sha256:a545a3dfe5082dc8e8c3eb7f8a2cf4f2870902ff1860bd99b6198cfd1f9d1f49", + "sha256:a5d8f29e5ec661143621a8f4de51adfb300d7a476224156a39a392254f70687b", + "sha256:aca06bfba4759bbdb09bf52ebb15ae20268ee1f6747417837926fae990ebc41d", + "sha256:bb23b7a6fd666e551a3094ab896a57809e010059540ad20acbeec03a154224ce", + "sha256:bfd1d0ae7e292105f29d7deaa9d8f2916ed8553ab9d5f39ec65bcf5deadff3f9", + "sha256:c62ca0a38958f541a73cf86acdab020c2091631c137bd359c4f5bddde7b75fd4", + "sha256:c709d8bda72cf4cd348ccec2a4881f2c5848fd72903c185f363d361b2737f773", + "sha256:c968a6aa7e0b56ecbd28531ddf439c2ec103610d3e2bf3b75b813304f8cb7723", + "sha256:df785d8cb80539d0b55fd47183264b7002077859028dfe3070cf6359bf8b2d9c", + "sha256:f406628ca51e0ae90ae76ea8398677a921b36f0bd71aab2099dfed08abd0322f", + "sha256:f46087bbd95ebae244a0eda01a618aff11ec7a069b15a3ef8f6b520db523dcf1", + "sha256:f8019c5279eb32360ca03e9fac40a12667715546eed5c5eb59eb381f2f501260", + "sha256:fc5f4d209733750afd2714e9109816a29500718b32dd9a5db01c0cb3a019b96a" + ], + "version": "==4.5.3" + }, + "entrypoints": { + "hashes": [ + "sha256:589f874b313739ad35be6e0cd7efde2a4e9b6fea91edcc34e58ecbb8dbe56d19", + "sha256:c70dd71abe5a8c85e55e12c19bd91ccfeec11a6e99044204511f9ed547d48451" + ], + "version": "==0.3" + }, + "flake8": { + "hashes": [ + "sha256:859996073f341f2670741b51ec1e67a01da142831aa1fdc6242dbf88dffbe661", + "sha256:a796a115208f5c03b18f332f7c11729812c8c3ded6c46319c59b53efd3819da8" + ], + "index": "pypi", + "version": "==3.7.7" + }, + "idna": { + "hashes": [ + "sha256:c357b3f628cf53ae2c4c05627ecc484553142ca23264e593d327bcde5e9c3407", + "sha256:ea8b7f6188e6fa117537c3df7da9fc686d485087abf6ac197f9c46432f7e4a3c" + ], + "version": "==2.8" + }, + "mccabe": { + "hashes": [ + "sha256:ab8a6258860da4b6677da4bd2fe5dc2c659cff31b3ee4f7f5d64e79735b80d42", + "sha256:dd8d182285a0fe56bace7f45b5e7d1a6ebcbf524e8f3bd87eb0f125271b8831f" + ], + "version": "==0.6.1" + }, + "more-itertools": { + "hashes": [ + "sha256:2112d2ca570bb7c3e53ea1a35cd5df42bb0fd10c45f0fb97178679c3c03d64c7", + "sha256:c3e4748ba1aad8dba30a4886b0b1a2004f9a863837b8654e7059eebf727afa5a" + ], + "markers": "python_version > '2.7'", + "version": "==7.0.0" + }, + "nose": { + "hashes": [ + "sha256:9ff7c6cc443f8c51994b34a667bbcf45afd6d945be7477b52e97516fd17c53ac", + "sha256:dadcddc0aefbf99eea214e0f1232b94f2fa9bd98fa8353711dacb112bfcbbb2a", + "sha256:f1bffef9cbc82628f6e7d7b40d7e255aefaa1adb6a1b1d26c69a8b79e6208a98" + ], + "index": "pypi", + "version": "==1.3.7" + }, + "pluggy": { + "hashes": [ + "sha256:19ecf9ce9db2fce065a7a0586e07cfb4ac8614fe96edf628a264b1c70116cf8f", + "sha256:84d306a647cc805219916e62aab89caa97a33a1dd8c342e87a37f91073cd4746" + ], + "version": "==0.9.0" + }, + "py": { + "hashes": [ + "sha256:64f65755aee5b381cea27766a3a147c3f15b9b6b9ac88676de66ba2ae36793fa", + "sha256:dc639b046a6e2cff5bbe40194ad65936d6ba360b52b3c3fe1d08a82dd50b5e53" + ], + "version": "==1.8.0" + }, + "pycodestyle": { + "hashes": [ + "sha256:95a2219d12372f05704562a14ec30bc76b05a5b297b21a5dfe3f6fac3491ae56", + "sha256:e40a936c9a450ad81df37f549d676d127b1b66000a6c500caa2b085bc0ca976c" + ], + "version": "==2.5.0" + }, + "pyflakes": { + "hashes": [ + "sha256:17dbeb2e3f4d772725c777fabc446d5634d1038f234e77343108ce445ea69ce0", + "sha256:d976835886f8c5b31d47970ed689944a0262b5f3afa00a5a7b4dc81e5449f8a2" + ], + "version": "==2.1.1" + }, + "pytest": { + "hashes": [ + "sha256:3773f4c235918987d51daf1db66d51c99fac654c81d6f2f709a046ab446d5e5d", + "sha256:b7802283b70ca24d7119b32915efa7c409982f59913c1a6c0640aacf118b95f5" + ], + "index": "pypi", + "version": "==4.4.1" + }, + "requests": { + "hashes": [ + "sha256:502a824f31acdacb3a35b6690b5fbf0bc41d63a24a45c4004352b0242707598e", + "sha256:7bf2a778576d825600030a110f3c0e3e8edc51dfaafe1c146e39a2027784957b" + ], + "index": "pypi", + "version": "==2.21.0" + }, + "six": { + "hashes": [ + "sha256:3350809f0555b11f552448330d0b52d5f24c91a322ea4a15ef22629740f3761c", + "sha256:d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73" + ], + "version": "==1.12.0" + }, + "urllib3": { + "hashes": [ + "sha256:4c291ca23bbb55c76518905869ef34bdd5f0e46af7afe6861e8375643ffee1a0", + "sha256:9a247273df709c4fedb38c711e44292304f73f39ab01beda9f6b9fc375669ac3" + ], + "version": "==1.24.2" + } + } +} diff --git a/README.md b/README.md index 67ba189a..6ec5bc63 100644 --- a/README.md +++ b/README.md @@ -17,37 +17,72 @@ For more information: [Extending MISP with Python modules](https://www.circl.lu/ ### Expansion modules -* [ASN History](misp_modules/modules/expansion/asn_history.py) - a hover and expansion module to expand an AS number with the ASN description and its history. +* [Backscatter.io](misp_modules/modules/expansion/backscatter_io) - a hover and expansion module to expand an IP address with mass-scanning observations. +* [BGP Ranking](misp_modules/modules/expansion/bgpranking.py) - a hover and expansion module to expand an AS number with the ASN description, its history, and position in BGP Ranking. +* [BTC scam check](misp_modules/modules/expansion/btc_scam_check.py) - An expansion hover module to instantly check if a BTC address has been abused. +* [BTC transactions](misp_modules/modules/expansion/btc_steroids.py) - An expansion hover module to get a blockchain balance and the transactions from a BTC address in MISP. * [CIRCL Passive DNS](misp_modules/modules/expansion/circl_passivedns.py) - a hover and expansion module to expand hostname and IP addresses with passive DNS information. * [CIRCL Passive SSL](misp_modules/modules/expansion/circl_passivessl.py) - a hover and expansion module to expand IP addresses with the X.509 certificate seen. * [countrycode](misp_modules/modules/expansion/countrycode.py) - a hover module to tell you what country a URL belongs to. * [CrowdStrike Falcon](misp_modules/modules/expansion/crowdstrike_falcon.py) - an expansion module to expand using CrowdStrike Falcon Intel Indicator API. * [CVE](misp_modules/modules/expansion/cve.py) - a hover module to give more information about a vulnerability (CVE). +* [Cuckoo submit](misp_modules/modules/expansion/cuckoo_submit.py) - A hover module to submit malware sample, url, attachment, domain to Cuckoo Sandbox. +* [DBL Spamhaus](misp_modules/modules/expansion/dbl_spamhaus.py) - a hover module to check Spamhaus DBL for a domain name. * [DNS](misp_modules/modules/expansion/dns.py) - a simple module to resolve MISP attributes like hostname and domain to expand IP addresses attributes. +* [docx-enrich](misp_modules/modules/expansion/docx-enrich.py) - an enrichment module to get text out of Word document into MISP (using free-text parser). * [DomainTools](misp_modules/modules/expansion/domaintools.py) - a hover and expansion module to get information from [DomainTools](http://www.domaintools.com/) whois. * [EUPI](misp_modules/modules/expansion/eupi.py) - a hover and expansion module to get information about an URL from the [Phishing Initiative project](https://phishing-initiative.eu/?lang=en). * [Farsight DNSDB Passive DNS](misp_modules/modules/expansion/farsight_passivedns.py) - a hover and expansion module to expand hostname and IP addresses with passive DNS information. * [GeoIP](misp_modules/modules/expansion/geoip_country.py) - a hover and expansion module to get GeoIP information from geolite/maxmind. +* [Greynoise](misp_modules/modules/expansion/greynoise.py) - a hover to get information from greynoise. +* [hashdd](misp_modules/modules/expansion/hashdd.py) - a hover module to check file hashes against [hashdd.com](http://www.hashdd.com) including NSLR dataset. +* [hibp](misp_modules/modules/expansion/hibp.py) - a hover module to lookup against Have I Been Pwned? +* [intel471](misp_modules/modules/expansion/intel471.py) - an expansion module to get info from [Intel471](https://intel471.com). * [IPASN](misp_modules/modules/expansion/ipasn.py) - a hover and expansion to get the BGP ASN of an IP address. -* [iprep](misp-modules/modules/expansion/iprep.py) - an expansion module to get IP reputation from packetmail.net. +* [iprep](misp_modules/modules/expansion/iprep.py) - an expansion module to get IP reputation from packetmail.net. +* [macaddress.io](misp_modules/modules/expansion/macaddress_io.py) - a hover module to retrieve vendor details and other information regarding a given MAC address or an OUI from [MAC address Vendor Lookup](https://macaddress.io). See [integration tutorial here](https://macaddress.io/integrations/MISP-module). +* [macvendors](misp_modules/modules/expansion/macvendors.py) - a hover module to retrieve mac vendor information. +* [ocr-enrich](misp_modules/modules/expansion/ocr-enrich.py) - an enrichment module to get OCRized data from images into MISP. +* [ods-enrich](misp_modules/modules/expansion/ods-enrich.py) - an enrichment module to get text out of OpenOffice spreadsheet document into MISP (using free-text parser). +* [odt-enrich](misp_modules/modules/expansion/odt-enrich.py) - an enrichment module to get text out of OpenOffice document into MISP (using free-text parser). +* [onyphe](misp_modules/modules/expansion/onyphe.py) - a modules to process queries on Onyphe. +* [onyphe_full](misp_modules/modules/expansion/onyphe_full.py) - a modules to process full queries on Onyphe. * [OTX](misp_modules/modules/expansion/otx.py) - an expansion module for [OTX](https://otx.alienvault.com/). * [passivetotal](misp_modules/modules/expansion/passivetotal.py) - a [passivetotal](https://www.passivetotal.org/) module that queries a number of different PassiveTotal datasets. +* [pdf-enrich](misp_modules/modules/expansion/pdf-enrich.py) - an enrichment module to extract text from PDF into MISP (using free-text parser). +* [pptx-enrich](misp_modules/modules/expansion/pptx-enrich.py) - an enrichment module to get text out of PowerPoint document into MISP (using free-text parser). +* [qrcode](misp_modules/modules/expansion/qrcode.py) - a module decode QR code, barcode and similar codes from an image and enrich with the decoded values. * [rbl](misp_modules/modules/expansion/rbl.py) - a module to get RBL (Real-Time Blackhost List) values from an attribute. +* [reversedns](misp_modules/modules/expansion/reversedns.py) - Simple Reverse DNS expansion service to resolve reverse DNS from MISP attributes. +* [securitytrails](misp_modules/modules/expansion/securitytrails.py) - an expansion module for [securitytrails](https://securitytrails.com/). * [shodan](misp_modules/modules/expansion/shodan.py) - a minimal [shodan](https://www.shodan.io/) expansion module. +* [Sigma queries](misp_modules/modules/expansion/sigma_queries.py) - Experimental expansion module querying a sigma rule to convert it into all the available SIEM signatures. +* [Sigma syntax validator](misp_modules/modules/expansion/sigma_syntax_validator.py) - Sigma syntax validator. * [sourcecache](misp_modules/modules/expansion/sourcecache.py) - a module to cache a specific link from a MISP instance. +* [STIX2 pattern syntax validator](misp_modules/modules/expansion/stix2_pattern_syntax_validator.py) - a module to check a STIX2 pattern syntax. * [ThreatCrowd](misp_modules/modules/expansion/threatcrowd.py) - an expansion module for [ThreatCrowd](https://www.threatcrowd.org/). * [threatminer](misp_modules/modules/expansion/threatminer.py) - an expansion module to expand from [ThreatMiner](https://www.threatminer.org/). +* [urlscan](misp_modules/modules/expansion/urlscan.py) - an expansion module to query [urlscan.io](https://urlscan.io). * [virustotal](misp_modules/modules/expansion/virustotal.py) - an expansion module to pull known resolutions and malware samples related with an IP/Domain from virusTotal (this modules require a VirusTotal private API key) +* [VMray](misp_modules/modules/expansion/vmray_submit.py) - a module to submit a sample to VMray. +* [VulnDB](misp_modules/modules/expansion/vulndb.py) - a module to query [VulnDB](https://www.riskbasedsecurity.com/). +* [Vulners](misp_modules/modules/expansion/vulners.py) - an expansion module to expand information about CVEs using Vulners API. +* [whois](misp_modules/modules/expansion) - a module to query a local instance of [uwhois](https://github.com/rafiot/uwhoisd). * [wikidata](misp_modules/modules/expansion/wiki.py) - a [wikidata](https://www.wikidata.org) expansion module. * [xforce](misp_modules/modules/expansion/xforceexchange.py) - an IBM X-Force Exchange expansion module. +* [xlsx-enrich](misp_modules/modules/expansion/xlsx-enrich.py) - an enrichment module to get text out of an Excel document into MISP (using free-text parser). +* [YARA query](misp_modules/modules/expansion/yara_query.py) - a module to create YARA rules from single hash attributes. * [YARA syntax validator](misp_modules/modules/expansion/yara_syntax_validator.py) - YARA syntax validator. ### Export modules * [CEF](misp_modules/modules/export_mod/cef_export.py) module to export Common Event Format (CEF). -* [GoAML export](misp_modules/modules/export_mod/goamlexport.py) module to export in GoAML format. +* [Cisco FireSight Manager ACL rule](misp_modules/modules/export_mod/cisco_firesight_manager_ACL_rule_export.py) module to export as rule for the Cisco FireSight manager ACL. +* [GoAML export](misp_modules/modules/export_mod/goamlexport.py) module to export in [GoAML format](http://goaml.unodc.org/goaml/en/index.html). * [Lite Export](misp_modules/modules/export_mod/liteexport.py) module to export a lite event. -* [Simple PDF export](misp_modules/modules/export_mod/pdfexport.py) module to export in PDF (required: asciidoctor-pdf). +* [PDF export](misp_modules/modules/export_mod/pdfexport.py) module to export an event in PDF. +* [Nexthink query format](misp_modules/modules/export_mod/nexthinkexport.py) module to export in Nexthink query format. +* [osquery](misp_modules/modules/export_mod/osqueryexport.py) module to export in [osquery](https://osquery.io/) query format. * [ThreatConnect](misp_modules/modules/export_mod/threat_connect_export.py) module to export in ThreatConnect CSV format. * [ThreatStream](misp_modules/modules/export_mod/threatStream_misp_export.py) module to export in ThreatStream format. @@ -56,23 +91,67 @@ For more information: [Extending MISP with Python modules](https://www.circl.lu/ * [CSV import](misp_modules/modules/import_mod/csvimport.py) Customizable CSV import module. * [Cuckoo JSON](misp_modules/modules/import_mod/cuckooimport.py) Cuckoo JSON import. * [Email Import](misp_modules/modules/import_mod/email_import.py) Email import module for MISP to import basic metadata. +* [GoAML import](misp_modules/modules/import_mod/) Module to import [GoAML](http://goaml.unodc.org/goaml/en/index.html) XML format. * [OCR](misp_modules/modules/import_mod/ocr.py) Optical Character Recognition (OCR) module for MISP to import attributes from images, scan or faxes. * [OpenIOC](misp_modules/modules/import_mod/openiocimport.py) OpenIOC import based on PyMISP library. -* [stiximport](misp_modules/modules/import_mod/stiximport.py) - An import module to process STIX xml/json. * [ThreatAnalyzer](misp_modules/modules/import_mod/threatanalyzer_import.py) - An import module to process ThreatAnalyzer archive.zip/analysis.json sandbox exports. * [VMRay](misp_modules/modules/import_mod/vmray_import.py) - An import module to process VMRay export. -## How to install and start MISP modules? +## How to install and start MISP modules in a Python virtualenv? (recommended) ~~~~bash -sudo apt-get install python3-dev python3-pip libpq5 libjpeg-dev +sudo apt-get install python3-dev python3-pip libpq5 libjpeg-dev tesseract-ocr libpoppler-cpp-dev imagemagick virtualenv libopencv-dev zbar-tools libzbar0 libzbar-dev libfuzzy-dev -y +sudo -u www-data virtualenv -p python3 /var/www/MISP/venv cd /usr/local/src/ sudo git clone https://github.com/MISP/misp-modules.git cd misp-modules -sudo pip3 install -I -r REQUIREMENTS -sudo pip3 install -I . -sudo vi /etc/rc.local, add this line: `sudo -u www-data misp-modules -s &` -misp-modules #to start the modules +sudo -u www-data /var/www/MISP/venv/bin/pip install -I -r REQUIREMENTS +sudo -u www-data /var/www/MISP/venv/bin/pip install . +# Start misp-modules as a service +sudo cp etc/systemd/system/misp-modules.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable --now misp-modules +/var/www/MISP/venv/bin/misp-modules -l 127.0.0.1 -s & #to start the modules +~~~~ + +## How to install and start MISP modules on RHEL-based distributions ? +As of this writing, the official RHEL repositories only contain Ruby 2.0.0 and Ruby 2.1 or higher is required. As such, this guide installs Ruby 2.2 from the [SCL](https://access.redhat.com/documentation/en-us/red_hat_software_collections/3/html/3.2_release_notes/chap-installation#sect-Installation-Subscribe) repository. + +~~~~bash +sudo yum install rh-ruby22 +sudo yum install openjpeg-devel +sudo yum install rubygem-rouge rubygem-asciidoctor zbar-devel opencv-devel +cd /var/www/MISP +git clone https://github.com/MISP/misp-modules.git +cd misp-modules +sudo -u apache /usr/bin/scl enable rh-python36 "virtualenv -p python3 /var/www/MISP/venv" +sudo -u apache /var/www/MISP/venv/bin/pip install -U -I -r REQUIREMENTS +sudo -u apache /var/www/MISP/venv/bin/pip install -U . +~~~~ + +Create the service file /etc/systemd/system/misp-modules.service : +~~~~ +echo "[Unit] +Description=MISP's modules +After=misp-workers.service + +[Service] +Type=simple +User=apache +Group=apache +ExecStart=/usr/bin/scl enable rh-python36 rh-ruby22 '/opt/rh/rh-python36/root/bin/misp-modules –l 127.0.0.1 –s' +Restart=always +RestartSec=10 + +[Install] +WantedBy=multi-user.target" | sudo tee /etc/systemd/system/misp-modules.service +~~~~ + +The `After=misp-workers.service` must be changed or removed if you have not created a misp-workers service. +Then, enable the misp-modules service and start it: +~~~~bash +systemctl daemon-reload +systemctl enable --now misp-modules ~~~~ ## How to add your own MISP modules? @@ -85,6 +164,8 @@ Create your module in [misp_modules/modules/expansion/](misp_modules/modules/exp Don't forget to return an error key and value if an error is raised to propagate it to the MISP user-interface. +Your module's script name should also be added in the `__all__` list of `/__init__.py` in order for it to be loaded. + ~~~python ... # Checking for required value @@ -176,6 +257,19 @@ def handler(q=False): codecs.encode(src, "rot-13")} ~~~ +#### export module + +For an export module, the `request["data"]` object corresponds to a list of events (dictionaries) to handle. + +Iterating over events attributes is performed using their `Attribute` key. + +~~~python +... +for event in request["data"]: + for attribute in event["Attribute"]: + # do stuff w/ attribute['type'], attribute['value'], ... +... + ### Returning Binary Data If you want to return a file or other data you need to add a data attribute. @@ -372,7 +466,7 @@ Recommended Plugin.Import_ocr_enabled true Enable or disable the ocr In this same menu set any other plugin settings that are required for testing. ## Install misp-module on an offline instance. -First, you need to grab all necessery packages for example like this : +First, you need to grab all necessary packages for example like this : Use pip wheel to create an archive ~~~ @@ -380,7 +474,7 @@ mkdir misp-modules-offline pip3 wheel -r REQUIREMENTS shodan --wheel-dir=./misp-modules-offline tar -cjvf misp-module-bundeled.tar.bz2 ./misp-modules-offline/* ~~~ -On offline machine : +On offline machine : ~~~ mkdir misp-modules-bundle tar xvf misp-module-bundeled.tar.bz2 -C misp-modules-bundle @@ -401,7 +495,7 @@ Download a pre-built virtual image from the [MISP training materials](https://ww - Create a Host-Only adapter in VirtualBox - Set your Misp OVA to that Host-Only adapter - Start the virtual machine -- Get the IP address of the virutal machine +- Get the IP address of the virtual machine - SSH into the machine (Login info on training page) - Go into the misp-modules directory @@ -419,16 +513,18 @@ sudo git checkout MyModBranch Remove the contents of the build directory and re-install misp-modules. -~~~python +~~~bash sudo rm -fr build/* -sudo pip3 install --upgrade . +sudo -u www-data /var/www/MISP/venv/bin/pip install --upgrade . ~~~ SSH in with a different terminal and run `misp-modules` with debugging enabled. -~~~python -sudo killall misp-modules -misp-modules -d +~~~bash +# In case misp-modules is not a service do: +# sudo killall misp-modules +sudo systemctl disable --now misp-modules +sudo -u www-data /var/www/MISP/venv/bin/misp-modules -d ~~~ @@ -439,3 +535,14 @@ cd tests/ curl -s http://127.0.0.1:6666/query -H "Content-Type: application/json" --data @MY_TEST_FILE.json -X POST cd ../ ~~~ + +## Documentation + +In order to provide documentation about some modules that require specific input / output / configuration, the [doc](doc) directory contains detailed information about the general purpose, requirements, features, input and ouput of each of these modules: + +- ***description** - quick description of the general purpose of the module, as the one given by the moduleinfo +- **requirements** - special libraries needed to make the module work +- **features** - description of the way to use the module, with the required MISP features to make the module give the intended result +- **references** - link(s) giving additional information about the format concerned in the module +- **input** - description of the format of data used in input +- **output** - description of the format given as the result of the module execution diff --git a/REQUIREMENTS b/REQUIREMENTS index 9e383d40..9447c473 100644 --- a/REQUIREMENTS +++ b/REQUIREMENTS @@ -1,24 +1,81 @@ -stix -cybox -tornado -dnspython -requests -urlarchiver -passivetotal -PyPDNS -pypssl -redis -pyeupi -ipasn-redis -asnhistory -git+https://github.com/Rafiot/uwhoisd.git@testing#egg=uwhois&subdirectory=client -git+https://github.com/MISP/MISP-STIX-Converter.git#egg=misp_stix_converter -git+https://github.com/MISP/PyMISP.git#egg=pymisp -pillow -pytesseract -SPARQLWrapper -domaintools_api -pygeoip -bs4 -oauth2 -yara +-i https://pypi.org/simple +-e . +-e git+https://github.com/D4-project/BGP-Ranking.git/@4e0741056bcc0077de1120b8724a31330b26033e#egg=pybgpranking&subdirectory=client +-e git+https://github.com/D4-project/IPASN-History.git/@c0c2bbf8d70811982dad065ea463a7e01593a38d#egg=pyipasnhistory&subdirectory=client +-e git+https://github.com/MISP/PyIntel471.git@0df8d51f1c1425de66714b3a5a45edb69b8cc2fc#egg=pyintel471 +-e git+https://github.com/MISP/PyMISP.git@582dda0ce2a8ca8e1dd2cf3842e0491caca51c62#egg=pymisp +-e git+https://github.com/Rafiot/uwhoisd.git@411572840eba4c72dc321c549b36a54ed5cea9de#egg=uwhois&subdirectory=client +-e git+https://github.com/cartertemm/ODTReader.git/@49d6938693f6faa3ff09998f86dba551ae3a996b#egg=odtreader +-e git+https://github.com/sebdraven/pydnstrails@48c1f740025c51289f43a24863d1845ff12fd21a#egg=pydnstrails +-e git+https://github.com/sebdraven/pyonyphe@cbb0168d5cb28a9f71f7ab3773164a7039ccdb12#egg=pyonyphe +aiohttp==3.4.4 +antlr4-python3-runtime==4.7.2 ; python_version >= '3' +async-timeout==3.0.1 +attrs==19.1.0 +backscatter==0.2.4 +beautifulsoup4==4.7.1 +blockchain==1.4.4 +certifi==2019.3.9 +chardet==3.0.4 +click-plugins==1.1.1 +click==7.0 +colorama==0.4.1 +dnspython==1.16.0 +domaintools-api==0.3.3 +enum-compat==0.0.2 +ez-setup==0.9 +ezodf==0.3.2 +future==0.17.1 +httplib2==0.12.3 +idna-ssl==1.1.0 ; python_version < '3.7' +idna==2.8 +isodate==0.6.0 +jsonschema==3.0.1 +lxml==4.3.3 +maclookup==1.0.3 +multidict==4.5.2 +np==1.0.2 +numpy==1.16.3 +oauth2==1.9.0.post1 +opencv-python==4.1.0.25 +pandas-ods-reader==0.0.6 +pandas==0.24.2 +passivetotal==1.0.30 +pdftotext==2.1.1 +pillow==6.0.0 +psutil==5.6.2 +pyeupi==1.0 +pygeoip==0.3.2 +pyparsing==2.4.0 +pypdns==1.3 +pypssl==2.1 +pyrsistent==0.15.1 +pytesseract==0.2.6 +python-dateutil==2.8.0 +python-docx==0.8.10 +python-pptx==0.6.17 +pytz==2019.1 +pyyaml==5.1 +pyzbar==0.1.8 +rdflib==4.2.2 +redis==3.2.1 +reportlab==3.5.20 +requests-cache==0.5.0 +requests==2.21.0 +shodan==1.12.1 +sigmatools==0.10 +six==1.12.0 +soupsieve==1.9.1 +sparqlwrapper==1.8.4 +stix2-patterns==1.1.0 +tabulate==0.8.3 +tornado==6.0.2 +url-normalize==1.4.1 +urlarchiver==0.2 +urllib3==1.24.2 +vulners==1.5.0 +wand==0.5.3 +xlrd==1.2.0 +xlsxwriter==1.1.7 +yara-python==3.8.1 +yarl==1.3.0 diff --git a/doc/README.md b/doc/README.md new file mode 100644 index 00000000..02506abf --- /dev/null +++ b/doc/README.md @@ -0,0 +1,1306 @@ +# MISP modules documentation + +## Expansion Modules + +#### [backscatter_io](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/backscatter_io.py) + + + +Query backscatter.io (https://backscatter.io/). +- **features**: +>The module takes a source or destination IP address as input and displays the information known by backscatter.io. +> +> +- **input**: +>IP addresses. +- **output**: +>Text containing a history of the IP addresses especially on scanning based on backscatter.io information . +- **references**: +>https://pypi.org/project/backscatter/ +- **requirements**: +>backscatter python library + +----- + +#### [bgpranking](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/bgpranking.py) + +Query BGP Ranking (https://bgpranking-ng.circl.lu/). +- **features**: +>The module takes an AS number attribute as input and displays its description and history, and position in BGP Ranking. +> +> +- **input**: +>Autonomous system number. +- **output**: +>Text containing a description of the ASN, its history, and the position in BGP Ranking. +- **references**: +>https://github.com/D4-project/BGP-Ranking/ +- **requirements**: +>pybgpranking python library + +----- + +#### [btc_scam_check](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/btc_scam_check.py) + + + +An expansion hover module to query a special dns blacklist to check if a bitcoin address has been abused. +- **features**: +>The module queries a dns blacklist directly with the bitcoin address and get a response if the address has been abused. +- **input**: +>btc address attribute. +- **output**: +>Text to indicate if the BTC address has been abused. +- **references**: +>https://btcblack.it/ +- **requirements**: +>dnspython3: dns python library + +----- + +#### [btc_steroids](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/btc_steroids.py) + + + +An expansion hover module to get a blockchain balance from a BTC address in MISP. +- **input**: +>btc address attribute. +- **output**: +>Text to describe the blockchain balance and the transactions related to the btc address in input. + +----- + +#### [circl_passivedns](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/circl_passivedns.py) + + + +Module to access CIRCL Passive DNS. +- **features**: +>This module takes a hostname, domain or ip-address (ip-src or ip-dst) attribute as input, and queries the CIRCL Passive DNS REST API to get and display information about this input. +> +>To make it work a username and a password are thus required to authenticate to the CIRCL Passive DNS API. +- **input**: +>Hostname, domain, or ip-address attribute. +- **ouput**: +>Text describing passive DNS information related to the input attribute. +- **references**: +>https://www.circl.lu/services/passive-dns/, https://datatracker.ietf.org/doc/draft-dulaunoy-dnsop-passive-dns-cof/ +- **requirements**: +>pypdns: Passive DNS python library, A CIRCL passive DNS account with username & password + +----- + +#### [circl_passivessl](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/circl_passivessl.py) + + + +Modules to access CIRCL Passive SSL. +- **features**: +>This module takes an ip-address (ip-src or ip-dst) attribute as input, and queries the CIRCL Passive SSL REST API to get and display information about this input. +> +>To make it work a username and a password are thus required to authenticate to the CIRCL Passive SSL API. +- **input**: +>Ip-address attribute. +- **output**: +>Text describing passive SSL information related to the input attribute. +- **references**: +>https://www.circl.lu/services/passive-ssl/ +- **requirements**: +>pypssl: Passive SSL python library, A CIRCL passive SSL account with username & password + +----- + +#### [countrycode](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/countrycode.py) + +Module to expand country codes. +- **features**: +>The module takes a domain or a hostname as input, and returns the country it belongs to. +> +>For non country domains, a list of the most common possible extensions is used. +- **input**: +>Hostname or domain attribute. +- **output**: +>Text with the country code the input belongs to. + +----- + +#### [crowdstrike_falcon](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/crowdstrike_falcon.py) + + + +Module to query Crowdstrike Falcon. +- **features**: +>This module takes a MISP attribute as input to query a CrowdStrike Falcon API. The API returns then the result of the query with some types we map into compatible types we add as MISP attributes. +> +>Please note that composite attributes composed by at least one of the input types mentionned below (domains, IPs, hostnames) are also supported. +- **input**: +>A MISP attribute included in the following list: +>- domain +>- email-attachment +>- email-dst +>- email-reply-to +>- email-src +>- email-subject +>- filename +>- hostname +>- ip-src +>- ip-dst +>- md5 +>- mutex +>- regkey +>- sha1 +>- sha256 +>- uri +>- url +>- user-agent +>- whois-registrant-email +>- x509-fingerprint-md5 +- **output**: +>MISP attributes mapped after the CrowdStrike API has been queried, included in the following list: +>- hostname +>- email-src +>- email-subject +>- filename +>- md5 +>- sha1 +>- sha256 +>- ip-dst +>- ip-dst +>- mutex +>- regkey +>- url +>- user-agent +>- x509-fingerprint-md5 +- **references**: +>https://www.crowdstrike.com/products/crowdstrike-falcon-faq/ +- **requirements**: +>A CrowdStrike API access (API id & key) + +----- + +#### [cuckoo_submit](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/cuckoo_submit.py) + + + +An expansion module to submit files and URLs to Cuckoo Sandbox. +- **features**: +>The module takes a malware-sample, attachment, url or domain and submits it to Cuckoo Sandbox. +> The returned task id can be used to retrieve results when the analysis completed. +- **input**: +>A malware-sample or attachment for files. A url or domain for URLs. +- **output**: +>A text field containing 'Cuckoo task id: ' +- **references**: +>https://cuckoosandbox.org/, https://cuckoo.sh/docs/ +- **requirements**: +>Access to a Cuckoo Sandbox API and an API key if the API requires it. (api_url and api_key) + +----- + +#### [cve](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/cve.py) + + + +An expansion hover module to expand information about CVE id. +- **features**: +>The module takes a vulnerability attribute as input and queries the CIRCL CVE search API to get information about the vulnerability as it is described in the list of CVEs. +- **input**: +>Vulnerability attribute. +- **output**: +>Text giving information about the CVE related to the Vulnerability. +- **references**: +>https://cve.circl.lu/, https://cve.mitre.org/ + +----- + +#### [dbl_spamhaus](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/dbl_spamhaus.py) + + + +Module to check Spamhaus DBL for a domain name. +- **features**: +>This modules takes a domain or a hostname in input and queries the Domain Block List provided by Spamhaus to determine what kind of domain it is. +> +>DBL then returns a response code corresponding to a certain classification of the domain we display. If the queried domain is not in the list, it is also mentionned. +> +>Please note that composite MISP attributes containing domain or hostname are supported as well. +- **input**: +>Domain or hostname attribute. +- **output**: +>Information about the nature of the input. +- **references**: +>https://www.spamhaus.org/faq/section/Spamhaus%20DBL +- **requirements**: +>dnspython3: DNS python3 library + +----- + +#### [dns](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/dns.py) + +A simple DNS expansion service to resolve IP address from domain MISP attributes. +- **features**: +>The module takes a domain of hostname attribute as input, and tries to resolve it. If no error is encountered, the IP address that resolves the domain is returned, otherwise the origin of the error is displayed. +> +>The address of the DNS resolver to use is also configurable, but if no configuration is set, we use the Google public DNS address (8.8.8.8). +> +>Please note that composite MISP attributes containing domain or hostname are supported as well. +- **input**: +>Domain or hostname attribute. +- **output**: +>IP address resolving the input. +- **requirements**: +>dnspython3: DNS python3 library + +----- + +#### [domaintools](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/domaintools.py) + + + +DomainTools MISP expansion module. +- **features**: +>This module takes a MISP attribute as input to query the Domaintools API. The API returns then the result of the query with some types we map into compatible types we add as MISP attributes. +> +>Please note that composite attributes composed by at least one of the input types mentionned below (domains, IPs, hostnames) are also supported. +- **input**: +>A MISP attribute included in the following list: +>- domain +>- hostname +>- email-src +>- email-dst +>- target-email +>- whois-registrant-email +>- whois-registrant-name +>- whois-registrant-phone +>- ip-src +>- ip-dst +- **output**: +>MISP attributes mapped after the Domaintools API has been queried, included in the following list: +>- whois-registrant-email +>- whois-registrant-phone +>- whois-registrant-name +>- whois-registrar +>- whois-creation-date +>- text +>- domain +- **references**: +>https://www.domaintools.com/ +- **requirements**: +>Domaintools python library, A Domaintools API access (username & apikey) + +----- + +#### [eupi](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/eupi.py) + + + +A module to query the Phishing Initiative service (https://phishing-initiative.lu). +- **features**: +>This module takes a domain, hostname or url MISP attribute as input to query the Phishing Initiative API. The API returns then the result of the query with some information about the value queried. +> +>Please note that composite attributes containing domain or hostname are also supported. +- **input**: +>A domain, hostname or url MISP attribute. +- **output**: +>Text containing information about the input, resulting from the query on Phishing Initiative. +- **references**: +>https://phishing-initiative.eu/?lang=en +- **requirements**: +>pyeupi: eupi python library, An access to the Phishing Initiative API (apikey & url) + +----- + +#### [farsight_passivedns](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/farsight_passivedns.py) + + + +Module to access Farsight DNSDB Passive DNS. +- **features**: +>This module takes a domain, hostname or IP address MISP attribute as input to query the Farsight Passive DNS API. The API returns then the result of the query with some information about the value queried. +- **input**: +>A domain, hostname or IP address MISP attribute. +- **output**: +>Text containing information about the input, resulting from the query on the Farsight Passive DNS API. +- **references**: +>https://www.farsightsecurity.com/ +- **requirements**: +>An access to the Farsight Passive DNS API (apikey) + +----- + +#### [geoip_country](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/geoip_country.py) + + + +Module to query a local copy of Maxmind's Geolite database. +- **features**: +>This module takes an IP address MISP attribute as input and queries a local copy of the Maxmind's Geolite database to get information about the location of this IP address. +> +>Please note that composite attributes domain|ip are also supported. +- **input**: +>An IP address MISP Attribute. +- **output**: +>Text containing information about the location of the IP address. +- **references**: +>https://www.maxmind.com/en/home +- **requirements**: +>A local copy of Maxmind's Geolite database + +----- + +#### [hashdd](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/hashdd.py) + +A hover module to check hashes against hashdd.com including NSLR dataset. +- **features**: +>This module takes a hash attribute as input to check its known level, using the hashdd API. This information is then displayed. +- **input**: +>A hash MISP attribute (md5). +- **output**: +>Text describing the known level of the hash in the hashdd databases. +- **references**: +>https://hashdd.com/ + +----- + +#### [intelmq_eventdb](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/intelmq_eventdb.py) + + + +Module to access intelmqs eventdb. +- **features**: +>/!\ EXPERIMENTAL MODULE, some features may not work /!\ +> +>This module takes a domain, hostname, IP address or Autonomous system MISP attribute as input to query the IntelMQ database. The result of the query gives then additional information about the input. +- **input**: +>A hostname, domain, IP address or AS attribute. +- **output**: +>Text giving information about the input using IntelMQ database. +- **references**: +>https://github.com/certtools/intelmq, https://intelmq.readthedocs.io/en/latest/Developers-Guide/ +- **requirements**: +>psycopg2: Python library to support PostgreSQL, An access to the IntelMQ database (username, password, hostname and database reference) + +----- + +#### [ipasn](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/ipasn.py) + +Module to query an IP ASN history service (https://github.com/D4-project/IPASN-History). +- **features**: +>This module takes an IP address attribute as input and queries the CIRCL IPASN service to get additional information about the input. +- **input**: +>An IP address MISP attribute. +- **output**: +>Text describing additional information about the input after a query on the IPASN-history database. +- **references**: +>https://github.com/D4-project/IPASN-History +- **requirements**: +>pyipasnhistory: Python library to access IPASN-history instance + +----- + +#### [iprep](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/iprep.py) + +Module to query IPRep data for IP addresses. +- **features**: +>This module takes an IP address attribute as input and queries the database from packetmail.net to get some information about the reputation of the IP. +- **input**: +>An IP address MISP attribute. +- **output**: +>Text describing additional information about the input after a query on the IPRep API. +- **references**: +>https://github.com/mahesh557/packetmail +- **requirements**: +>An access to the packetmail API (apikey) + +----- + +#### [macaddress_io](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/macaddress_io.py) + + + +MISP hover module for macaddress.io +- **features**: +>This module takes a MAC address attribute as input and queries macaddress.io for additional information. +> +>This information contains data about: +>- MAC address details +>- Vendor details +>- Block details +- **input**: +>MAC address MISP attribute. +- **output**: +>Text containing information on the MAC address fetched from a query on macaddress.io. +- **references**: +>https://macaddress.io/, https://github.com/CodeLineFi/maclookup-python +- **requirements**: +>maclookup: macaddress.io python library, An access to the macaddress.io API (apikey) + +----- + +#### [onyphe](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/onyphe.py) + + + +Module to process a query on Onyphe. +- **features**: +>This module takes a domain, hostname, or IP address attribute as input in order to query the Onyphe API. Data fetched from the query is then parsed and MISP attributes are extracted. +- **input**: +>A domain, hostname or IP address MISP attribute. +- **output**: +>MISP attributes fetched from the Onyphe query. +- **references**: +>https://www.onyphe.io/, https://github.com/sebdraven/pyonyphe +- **requirements**: +>onyphe python library, An access to the Onyphe API (apikey) + +----- + +#### [onyphe_full](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/onyphe_full.py) + + + +Module to process a full query on Onyphe. +- **features**: +>This module takes a domain, hostname, or IP address attribute as input in order to query the Onyphe API. Data fetched from the query is then parsed and MISP attributes are extracted. +> +>The parsing is here more advanced than the one on onyphe module, and is returning more attributes, since more fields of the query result are watched and parsed. +- **input**: +>A domain, hostname or IP address MISP attribute. +- **output**: +>MISP attributes fetched from the Onyphe query. +- **references**: +>https://www.onyphe.io/, https://github.com/sebdraven/pyonyphe +- **requirements**: +>onyphe python library, An access to the Onyphe API (apikey) + +----- + +#### [otx](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/otx.py) + + + +Module to get information from AlienVault OTX. +- **features**: +>This module takes a MISP attribute as input to query the OTX Alienvault API. The API returns then the result of the query with some types we map into compatible types we add as MISP attributes. +- **input**: +>A MISP attribute included in the following list: +>- hostname +>- domain +>- ip-src +>- ip-dst +>- md5 +>- sha1 +>- sha256 +>- sha512 +- **output**: +>MISP attributes mapped from the result of the query on OTX, included in the following list: +>- domain +>- ip-src +>- ip-dst +>- text +>- md5 +>- sha1 +>- sha256 +>- sha512 +>- email +- **references**: +>https://www.alienvault.com/open-threat-exchange +- **requirements**: +>An access to the OTX API (apikey) + +----- + +#### [passivetotal](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/passivetotal.py) + + + + +- **features**: +>The PassiveTotal MISP expansion module brings the datasets derived from Internet scanning directly into your MISP instance. This module supports passive DNS, historic SSL, WHOIS, and host attributes. In order to use the module, you must have a valid PassiveTotal account username and API key. Registration is free and can be done by visiting https://www.passivetotal.org/register +- **input**: +>A MISP attribute included in the following list: +>- hostname +>- domain +>- ip-src +>- ip-dst +>- x509-fingerprint-sha1 +>- email-src +>- email-dst +>- target-email +>- whois-registrant-email +>- whois-registrant-phone +>- text +>- whois-registrant-name +>- whois-registrar +>- whois-creation-date +- **output**: +>MISP attributes mapped from the result of the query on PassiveTotal, included in the following list: +>- hostname +>- domain +>- ip-src +>- ip-dst +>- x509-fingerprint-sha1 +>- email-src +>- email-dst +>- target-email +>- whois-registrant-email +>- whois-registrant-phone +>- text +>- whois-registrant-name +>- whois-registrar +>- whois-creation-date +>- md5 +>- sha1 +>- sha256 +>- link +- **references**: +>https://www.passivetotal.org/register +- **requirements**: +>Passivetotal python library, An access to the PassiveTotal API (apikey) + +----- + +#### [rbl](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/rbl.py) + +Module to check an IPv4 address against known RBLs. +- **features**: +>This module takes an IP address attribute as input and queries multiple know Real-time Blackhost Lists to check if they have already seen this IP address. +> +>We display then all the information we get from those different sources. +- **input**: +>IP address attribute. +- **output**: +>Text with additional data from Real-time Blackhost Lists about the IP address. +- **references**: +>[RBLs list](https://github.com/MISP/misp-modules/blob/8817de476572a10a9c9d03258ec81ca70f3d926d/misp_modules/modules/expansion/rbl.py#L20) +- **requirements**: +>dnspython3: DNS python3 library + +----- + +#### [reversedns](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/reversedns.py) + +Simple Reverse DNS expansion service to resolve reverse DNS from MISP attributes. +- **features**: +>The module takes an IP address as input and tries to find the hostname this IP address is resolved into. +> +>The address of the DNS resolver to use is also configurable, but if no configuration is set, we use the Google public DNS address (8.8.8.8). +> +>Please note that composite MISP attributes containing IP addresses are supported as well. +- **input**: +>An IP address attribute. +- **output**: +>Hostname attribute the input is resolved into. +- **requirements**: +>DNS python library + +----- + +#### [securitytrails](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/securitytrails.py) + + + +An expansion modules for SecurityTrails. +- **features**: +>The module takes a domain, hostname or IP address attribute as input and queries the SecurityTrails API with it. +> +>Multiple parsing operations are then processed on the result of the query to extract a much information as possible. +> +>From this data extracted are then mapped MISP attributes. +- **input**: +>A domain, hostname or IP address attribute. +- **output**: +>MISP attributes resulting from the query on SecurityTrails API, included in the following list: +>- hostname +>- domain +>- ip-src +>- ip-dst +>- dns-soa-email +>- whois-registrant-email +>- whois-registrant-phone +>- whois-registrant-name +>- whois-registrar +>- whois-creation-date +>- domain +- **references**: +>https://securitytrails.com/ +- **requirements**: +>dnstrails python library, An access to the SecurityTrails API (apikey) + +----- + +#### [shodan](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/shodan.py) + + + +Module to query on Shodan. +- **features**: +>The module takes an IP address as input and queries the Shodan API to get some additional data about it. +- **input**: +>An IP address MISP attribute. +- **output**: +>Text with additional data about the input, resulting from the query on Shodan. +- **references**: +>https://www.shodan.io/ +- **requirements**: +>shodan python library, An access to the Shodan API (apikey) + +----- + +#### [sigma_queries](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/sigma_queries.py) + + + +An expansion hover module to display the result of sigma queries. +- **features**: +>This module takes a Sigma rule attribute as input and tries all the different queries available to convert it into different formats recognized by SIEMs. +- **input**: +>A Sigma attribute. +- **output**: +>Text displaying results of queries on the Sigma attribute. +- **references**: +>https://github.com/Neo23x0/sigma/wiki +- **requirements**: +>Sigma python library + +----- + +#### [sigma_syntax_validator](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/sigma_syntax_validator.py) + + + +An expansion hover module to perform a syntax check on sigma rules. +- **features**: +>This module takes a Sigma rule attribute as input and performs a syntax check on it. +> +>It displays then that the rule is valid if it is the case, and the error related to the rule otherwise. +- **input**: +>A Sigma attribute. +- **output**: +>Text describing the validity of the Sigma rule. +- **references**: +>https://github.com/Neo23x0/sigma/wiki +- **requirements**: +>Sigma python library, Yaml python library + +----- + +#### [sourcecache](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/sourcecache.py) + +Module to cache web pages of analysis reports, OSINT sources. The module returns a link of the cached page. +- **features**: +>This module takes a link or url attribute as input and caches the related web page. It returns then a link of the cached page. +- **input**: +>A link or url attribute. +- **output**: +>A malware-sample attribute describing the cached page. +- **references**: +>https://github.com/adulau/url_archiver +- **requirements**: +>urlarchiver: python library to fetch and archive URL on the file-system + +----- + +#### [stix2_pattern_syntax_validator](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/stix2_pattern_syntax_validator.py) + + + +An expansion hover module to perform a syntax check on stix2 patterns. +- **features**: +>This module takes a STIX2 pattern attribute as input and performs a syntax check on it. +> +>It displays then that the rule is valid if it is the case, and the error related to the rule otherwise. +- **input**: +>A STIX2 pattern attribute. +- **output**: +>Text describing the validity of the STIX2 pattern. +- **references**: +>[STIX2.0 patterning specifications](http://docs.oasis-open.org/cti/stix/v2.0/cs01/part5-stix-patterning/stix-v2.0-cs01-part5-stix-patterning.html) +- **requirements**: +>stix2patterns python library + +----- + +#### [threatcrowd](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/threatcrowd.py) + + + +Module to get information from ThreatCrowd. +- **features**: +>This module takes a MISP attribute as input and queries ThreatCrowd with it. +> +>The result of this query is then parsed and some data is mapped into MISP attributes in order to enrich the input attribute. +- **input**: +>A MISP attribute included in the following list: +>- hostname +>- domain +>- ip-src +>- ip-dst +>- md5 +>- sha1 +>- sha256 +>- sha512 +>- whois-registrant-email +- **output**: +>MISP attributes mapped from the result of the query on ThreatCrowd, included in the following list: +>- domain +>- ip-src +>- ip-dst +>- text +>- md5 +>- sha1 +>- sha256 +>- sha512 +>- hostname +>- whois-registrant-email +- **references**: +>https://www.threatcrowd.org/ + +----- + +#### [threatminer](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/threatminer.py) + + + +Module to get information from ThreatMiner. +- **features**: +>This module takes a MISP attribute as input and queries ThreatMiner with it. +> +>The result of this query is then parsed and some data is mapped into MISP attributes in order to enrich the input attribute. +- **input**: +>A MISP attribute included in the following list: +>- hostname +>- domain +>- ip-src +>- ip-dst +>- md5 +>- sha1 +>- sha256 +>- sha512 +- **output**: +>MISP attributes mapped from the result of the query on ThreatMiner, included in the following list: +>- domain +>- ip-src +>- ip-dst +>- text +>- md5 +>- sha1 +>- sha256 +>- sha512 +>- ssdeep +>- authentihash +>- filename +>- whois-registrant-email +>- url +>- link +- **references**: +>https://www.threatminer.org/ + +----- + +#### [urlscan](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/urlscan.py) + + + +An expansion module to query urlscan.io. +- **features**: +>This module takes a MISP attribute as input and queries urlscan.io with it. +> +>The result of this query is then parsed and some data is mapped into MISP attributes in order to enrich the input attribute. +- **input**: +>A domain, hostname or url attribute. +- **output**: +>MISP attributes mapped from the result of the query on urlscan.io. +- **references**: +>https://urlscan.io/ +- **requirements**: +>An access to the urlscan.io API + +----- + +#### [virustotal](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/virustotal.py) + + + +Module to get information from virustotal. +- **features**: +>This module takes a MISP attribute as input and queries the VirusTotal API with it, in order to get additional data on the input attribute. +> +>Multiple recursive requests on the API can then be processed on some attributes found in the first request. A limit can be set to restrict the number of values to query again, and at the same time the number of request submitted to the API. +> +>This limit is important because the default user VirusTotal apikey only allows to process a certain nunmber of queries per minute. As a consequence it is recommended to have a larger number of requests or a private apikey. +> +>Data is then mapped into MISP attributes. +- **input**: +>A domain, hash (md5, sha1, sha256 or sha512), hostname or IP address attribute. +- **output**: +>MISP attributes mapped from the rersult of the query on VirusTotal API. +- **references**: +>https://www.virustotal.com/ +- **requirements**: +>An access to the VirusTotal API (apikey) + +----- + +#### [vmray_submit](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/vmray_submit.py) + + + +Module to submit a sample to VMRay. +- **features**: +>This module takes an attachment or malware-sample attribute as input to query the VMRay API. +> +>The sample contained within the attribute in then enriched with data from VMRay mapped into MISP attributes. +- **input**: +>An attachment or malware-sample attribute. +- **output**: +>MISP attributes mapped from the result of the query on VMRay API, included in the following list: +>- text +>- sha1 +>- sha256 +>- md5 +>- link +- **references**: +>https://www.vmray.com/ +- **requirements**: +>An access to the VMRay API (apikey & url) + +----- + +#### [vulndb](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/vulndb.py) + + + +Module to query VulnDB (RiskBasedSecurity.com). +- **features**: +>This module takes a vulnerability attribute as input and queries VulnDB in order to get some additional data about it. +> +>The API gives the result of the query which can be displayed in the screen, and/or mapped into MISP attributes to add in the event. +- **input**: +>A vulnerability attribute. +- **output**: +>Additional data enriching the CVE input, fetched from VulnDB. +- **references**: +>https://vulndb.cyberriskanalytics.com/ +- **requirements**: +>An access to the VulnDB API (apikey, apisecret) + +----- + +#### [vulners](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/vulners.py) + + + +An expansion hover module to expand information about CVE id using Vulners API. +- **features**: +>This module takes a vulnerability attribute as input and queries the Vulners API in order to get some additional data about it. +> +>The API then returns details about the vulnerability. +- **input**: +>A vulnerability attribute. +- **output**: +>Text giving additional information about the CVE in input. +- **references**: +>https://vulners.com/ +- **requirements**: +>Vulners python library, An access to the Vulners API + +----- + +#### [whois](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/whois.py) + +Module to query a local instance of uwhois (https://github.com/rafiot/uwhoisd). +- **features**: +>This module takes a domain or IP address attribute as input and queries a 'Univseral Whois proxy server' to get the correct details of the Whois query on the input value (check the references for more details about this whois server). +- **input**: +>A domain or IP address attribute. +- **output**: +>Text describing the result of a whois request for the input value. +- **references**: +>https://github.com/rafiot/uwhoisd +- **requirements**: +>uwhois: A whois python library + +----- + +#### [wiki](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/wiki.py) + + + +An expansion hover module to extract information from Wikidata to have additional information about particular term for analysis. +- **features**: +>This module takes a text attribute as input and queries the Wikidata API. If the text attribute is clear enough to define a specific term, the API returns a wikidata link in response. +- **input**: +>Text attribute. +- **output**: +>Text attribute. +- **references**: +>https://www.wikidata.org +- **requirements**: +>SPARQLWrapper python library + +----- + +#### [xforceexchange](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/xforceexchange.py) + + + +An expansion module for IBM X-Force Exchange. +- **features**: +>This module takes a MISP attribute as input to query the X-Force API. The API returns then additional information known in their threats data, that is mapped into MISP attributes. +- **input**: +>A MISP attribute included in the following list: +>- ip-src +>- ip-dst +>- vulnerability +>- md5 +>- sha1 +>- sha256 +- **output**: +>MISP attributes mapped from the result of the query on X-Force Exchange. +- **references**: +>https://exchange.xforce.ibmcloud.com/ +- **requirements**: +>An access to the X-Force API (apikey) + +----- + +#### [yara_query](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/yara_query.py) + + + +An expansion & hover module to translate any hash attribute into a yara rule. +- **features**: +>The module takes a hash attribute (md5, sha1, sha256, imphash) as input, and is returning a YARA rule from it. This YARA rule is also validated using the same method as in 'yara_syntax_validator' module. +>Both hover and expansion functionalities are supported with this module, where the hover part is displaying the resulting YARA rule and the expansion part allows you to add the rule as a new attribute, as usual with expansion modules. +- **input**: +>MISP Hash attribute (md5, sha1, sha256, imphash, or any of the composite attribute with filename and one of the previous hash type). +- **output**: +>YARA rule. +- **references**: +>https://virustotal.github.io/yara/, https://github.com/virustotal/yara-python +- **requirements**: +>yara-python python library + +----- + +#### [yara_syntax_validator](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/expansion/yara_syntax_validator.py) + + + +An expansion hover module to perform a syntax check on if yara rules are valid or not. +- **features**: +>This modules simply takes a YARA rule as input, and checks its syntax. It returns then a confirmation if the syntax is valid, otherwise the syntax error is displayed. +- **input**: +>YARA rule attribute. +- **output**: +>Text to inform users if their rule is valid. +- **references**: +>http://virustotal.github.io/yara/ +- **requirements**: +>yara_python python library + +----- + +## Export Modules + +#### [cef_export](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/export_mod/cef_export.py) + +Module to export a MISP event in CEF format. +- **features**: +>The module takes a MISP event in input, to look every attribute. Each attribute matching with some predefined types is then exported in Common Event Format. +>Thus, there is no particular feature concerning MISP Events since any event can be exported. However, 4 configuration parameters recognized by CEF format are required and should be provided by users before exporting data: the device vendor, product and version, as well as the default severity of data. +- **input**: +>MISP Event attributes +- **output**: +>Common Event Format file +- **references**: +>https://community.softwaregrp.com/t5/ArcSight-Connectors/ArcSight-Common-Event-Format-CEF-Guide/ta-p/1589306?attachment-id=65537 + +----- + +#### [goamlexport](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/export_mod/goamlexport.py) + + + +This module is used to export MISP events containing transaction objects into GoAML format. +- **features**: +>The module works as long as there is at least one transaction object in the Event. +> +>Then in order to have a valid GoAML document, please follow these guidelines: +>- For each transaction object, use either a bank-account, person, or legal-entity object to describe the origin of the transaction, and again one of them to describe the target of the transaction. +>- Create an object reference for both origin and target objects of the transaction. +>- A bank-account object needs a signatory, which is a person object, put as object reference of the bank-account. +>- A person can have an address, which is a geolocation object, put as object reference of the person. +> +>Supported relation types for object references that are recommended for each object are the folowing: +>- transaction: +> - 'from', 'from_my_client': Origin of the transaction - at least one of them is required. +> - 'to', 'to_my_client': Target of the transaction - at least one of them is required. +> - 'address': Location of the transaction - optional. +>- bank-account: +> - 'signatory': Signatory of a bank-account - the reference from bank-account to a signatory is required, but the relation-type is optional at the moment since this reference will always describe a signatory. +> - 'entity': Entity owning the bank account - optional. +>- person: +> - 'address': Address of a person - optional. +- **input**: +>MISP objects (transaction, bank-account, person, legal-entity, geolocation), with references, describing financial transactions and their origin and target. +- **output**: +>GoAML format file, describing financial transactions, with their origin and target (bank accounts, persons or entities). +- **references**: +>http://goaml.unodc.org/ +- **requirements**: +>PyMISP, MISP objects + +----- + +#### [liteexport](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/export_mod/liteexport.py) + +Lite export of a MISP event. +- **features**: +>This module is simply producing a json MISP event format file, but exporting only Attributes from the Event. Thus, MISP Events exported with this module should have attributes that are not internal references, otherwise the resulting event would be empty. +- **input**: +>MISP Event attributes +- **output**: +>Lite MISP Event + +----- + +#### [nexthinkexport](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/export_mod/nexthinkexport.py) + + + +Nexthink NXQL query export module +- **features**: +>This module export an event as Nexthink NXQL queries that can then be used in your own python3 tool or from wget/powershell +- **input**: +>MISP Event attributes +- **output**: +>Nexthink NXQL queries +- **references**: +>https://doc.nexthink.com/Documentation/Nexthink/latest/APIAndIntegrations/IntroducingtheWebAPIV2 + +----- + +#### [osqueryexport](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/export_mod/osqueryexport.py) + + + +OSQuery export of a MISP event. +- **features**: +>This module export an event as osquery queries that can be used in packs or in fleet management solution like Kolide. +- **input**: +>MISP Event attributes +- **output**: +>osquery SQL queries + +----- + +#### [pdfexport](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/export_mod/pdfexport.py) + +Simple export of a MISP event to PDF. +- **features**: +>The module takes care of the PDF file building, and work with any MISP Event. Except the requirement of reportlab, used to create the file, there is no special feature concerning the Event. Some parameters can be given through the config dict. 'MISP_base_url_for_dynamic_link' is your MISP URL, to attach an hyperlink to your event on your MISP instance from the PDF. Keep it clear to avoid hyperlinks in the generated pdf. +> 'MISP_name_for_metadata' is your CERT or MISP instance name. Used as text in the PDF' metadata +> 'Activate_textual_description' is a boolean (True or void) to activate the textual description/header abstract of an event +> 'Activate_galaxy_description' is a boolean (True or void) to activate the description of event related galaxies. +> 'Activate_related_events' is a boolean (True or void) to activate the description of related event. Be aware this might leak information on confidential events linked to the current event ! +> 'Activate_internationalization_fonts' is a boolean (True or void) to activate Noto fonts instead of default fonts (Helvetica). This allows the support of CJK alphabet. Be sure to have followed the procedure to download Noto fonts (~70Mo) in the right place (/tools/pdf_fonts/Noto_TTF), to allow PyMisp to find and use them during PDF generation. +> 'Custom_fonts_path' is a text (path or void) to the TTF file of your choice, to create the PDF with it. Be aware the PDF won't support bold/italic/special style anymore with this option +- **input**: +>MISP Event +- **output**: +>MISP Event in a PDF file. +- **references**: +>https://acrobat.adobe.com/us/en/acrobat/about-adobe-pdf.html +- **requirements**: +>PyMISP, reportlab + +----- + +#### [testexport](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/export_mod/testexport.py) + +Skeleton export module. + +----- + +#### [threatStream_misp_export](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/export_mod/threatStream_misp_export.py) + + + +Module to export a structured CSV file for uploading to threatStream. +- **features**: +>The module takes a MISP event in input, to look every attribute. Each attribute matching with some predefined types is then exported in a CSV format recognized by ThreatStream. +- **input**: +>MISP Event attributes +- **output**: +>ThreatStream CSV format file +- **references**: +>https://www.anomali.com/platform/threatstream, https://github.com/threatstream +- **requirements**: +>csv + +----- + +#### [threat_connect_export](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/export_mod/threat_connect_export.py) + + + +Module to export a structured CSV file for uploading to ThreatConnect. +- **features**: +>The module takes a MISP event in input, to look every attribute. Each attribute matching with some predefined types is then exported in a CSV format recognized by ThreatConnect. +>Users should then provide, as module configuration, the source of data they export, because it is required by the output format. +- **input**: +>MISP Event attributes +- **output**: +>ThreatConnect CSV format file +- **references**: +>https://www.threatconnect.com +- **requirements**: +>csv + +----- + +## Import Modules + +#### [csvimport](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/import_mod/csvimport.py) + +Module to import MISP attributes from a csv file. +- **features**: +>In order to parse data from a csv file, a header is required to let the module know which column is matching with known attribute fields / MISP types. +>This header is part of the configuration of the module and should be filled out in MISP plugin settings, each field separated by COMMAS. Fields that do not match with any type known in MISP can be ignored in import, using a space or simply nothing between two separators (example: 'ip-src, , comment, '). +>There is also one type that is confused and can be either a MISP attribute type or an attribute field: 'comment'. In this case, using 'attrComment' specifies that the attribute field 'comment' should be considered, otherwise it will be considered as the MISP attribute type. +> +>For each MISP attribute type, an attribute is created. +>Attribute fields that are imported are the following: value, type, category, to-ids, distribution, comment, tag. +- **input**: +>CSV format file. +- **output**: +>MISP Event attributes +- **references**: +>https://tools.ietf.org/html/rfc4180, https://tools.ietf.org/html/rfc7111 +- **requirements**: +>PyMISP + +----- + +#### [cuckooimport](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/import_mod/cuckooimport.py) + + + +Module to import Cuckoo JSON. +- **features**: +>The module simply imports MISP Attributes from a Cuckoo JSON format file. There is thus no special feature to make it work. +- **input**: +>Cuckoo JSON file +- **output**: +>MISP Event attributes +- **references**: +>https://cuckoosandbox.org/, https://github.com/cuckoosandbox/cuckoo + +----- + +#### [email_import](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/import_mod/email_import.py) + +Module to import emails in MISP. +- **features**: +>This module can be used to import e-mail text as well as attachments and urls. +>3 configuration parameters are then used to unzip attachments, guess zip attachment passwords, and extract urls: set each one of them to True or False to process or not the respective corresponding actions. +- **input**: +>E-mail file +- **output**: +>MISP Event attributes + +----- + +#### [goamlimport](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/import_mod/goamlimport.py) + + + +Module to import MISP objects about financial transactions from GoAML files. +- **features**: +>Unlike the GoAML export module, there is here no special feature to import data from GoAML external files, since the module will import MISP Objects with their References on its own, as it is required for the export module to rebuild a valid GoAML document. +- **input**: +>GoAML format file, describing financial transactions, with their origin and target (bank accounts, persons or entities). +- **output**: +>MISP objects (transaction, bank-account, person, legal-entity, geolocation), with references, describing financial transactions and their origin and target. +- **references**: +>http://goaml.unodc.org/ +- **requirements**: +>PyMISP + +----- + +#### [mispjson](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/import_mod/mispjson.py) + +Module to import MISP JSON format for merging MISP events. +- **features**: +>The module simply imports MISP Attributes from an other MISP Event in order to merge events together. There is thus no special feature to make it work. +- **input**: +>MISP Event +- **output**: +>MISP Event attributes + +----- + +#### [ocr](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/import_mod/ocr.py) + +Optical Character Recognition (OCR) module for MISP. +- **features**: +>The module tries to recognize some text from an image and import the result as a freetext attribute, there is then no special feature asked to users to make it work. +- **input**: +>Image +- **output**: +>freetext MISP attribute + +----- + +#### [openiocimport](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/import_mod/openiocimport.py) + +Module to import OpenIOC packages. +- **features**: +>The module imports MISP Attributes from OpenIOC packages, there is then no special feature for users to make it work. +- **input**: +>OpenIOC packages +- **output**: +>MISP Event attributes +- **references**: +>https://www.fireeye.com/blog/threat-research/2013/10/openioc-basics.html +- **requirements**: +>PyMISP + +----- + +#### [threatanalyzer_import](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/import_mod/threatanalyzer_import.py) + +Module to import ThreatAnalyzer archive.zip / analysis.json files. +- **features**: +>The module imports MISP Attributes from a ThreatAnalyzer format file. This file can be either ZIP, or JSON format. +>There is by the way no special feature for users to make the module work. +- **input**: +>ThreatAnalyzer format file +- **output**: +>MISP Event attributes +- **references**: +>https://www.threattrack.com/malware-analysis.aspx + +----- + +#### [vmray_import](https://github.com/MISP/misp-modules/tree/master/misp_modules/modules/import_mod/vmray_import.py) + + + +Module to import VMRay (VTI) results. +- **features**: +>The module imports MISP Attributes from VMRay format, using the VMRay api. +>Users should then provide as the module configuration the API Key as well as the server url in order to fetch their data to import. +- **input**: +>VMRay format +- **output**: +>MISP Event attributes +- **references**: +>https://www.vmray.com/ +- **requirements**: +>vmray_rest_api + +----- diff --git a/doc/expansion/backscatter_io.json b/doc/expansion/backscatter_io.json new file mode 100644 index 00000000..a8475c54 --- /dev/null +++ b/doc/expansion/backscatter_io.json @@ -0,0 +1,9 @@ +{ + "description": "Query backscatter.io (https://backscatter.io/).", + "requirements": ["backscatter python library"], + "features": "The module takes a source or destination IP address as input and displays the information known by backscatter.io.\n\n", + "logo": "logos/backscatter_io.png", + "references": ["https://pypi.org/project/backscatter/"], + "input": "IP addresses.", + "output": "Text containing a history of the IP addresses especially on scanning based on backscatter.io information ." +} diff --git a/doc/expansion/bgpranking.json b/doc/expansion/bgpranking.json new file mode 100644 index 00000000..a98b780f --- /dev/null +++ b/doc/expansion/bgpranking.json @@ -0,0 +1,8 @@ +{ + "description": "Query BGP Ranking (https://bgpranking-ng.circl.lu/).", + "requirements": ["pybgpranking python library"], + "features": "The module takes an AS number attribute as input and displays its description and history, and position in BGP Ranking.\n\n", + "references": ["https://github.com/D4-project/BGP-Ranking/"], + "input": "Autonomous system number.", + "output": "Text containing a description of the ASN, its history, and the position in BGP Ranking." +} diff --git a/doc/expansion/btc_scam_check.json b/doc/expansion/btc_scam_check.json new file mode 100644 index 00000000..44fce035 --- /dev/null +++ b/doc/expansion/btc_scam_check.json @@ -0,0 +1,9 @@ +{ + "description": "An expansion hover module to query a special dns blacklist to check if a bitcoin address has been abused.", + "requirements": ["dnspython3: dns python library"], + "features": "The module queries a dns blacklist directly with the bitcoin address and get a response if the address has been abused.", + "logo": "logos/bitcoin.png", + "input": "btc address attribute.", + "output" : "Text to indicate if the BTC address has been abused.", + "references": ["https://btcblack.it/"] +} diff --git a/doc/expansion/btc_steroids.json b/doc/expansion/btc_steroids.json new file mode 100644 index 00000000..fd264d8b --- /dev/null +++ b/doc/expansion/btc_steroids.json @@ -0,0 +1,6 @@ +{ + "description": "An expansion hover module to get a blockchain balance from a BTC address in MISP.", + "logo": "logos/bitcoin.png", + "input": "btc address attribute.", + "output": "Text to describe the blockchain balance and the transactions related to the btc address in input." +} diff --git a/doc/expansion/circl_passivedns.json b/doc/expansion/circl_passivedns.json new file mode 100644 index 00000000..fda50eb7 --- /dev/null +++ b/doc/expansion/circl_passivedns.json @@ -0,0 +1,9 @@ +{ + "description": "Module to access CIRCL Passive DNS.", + "logo": "logos/passivedns.png", + "requirements": ["pypdns: Passive DNS python library", "A CIRCL passive DNS account with username & password"], + "input": "Hostname, domain, or ip-address attribute.", + "ouput": "Text describing passive DNS information related to the input attribute.", + "features": "This module takes a hostname, domain or ip-address (ip-src or ip-dst) attribute as input, and queries the CIRCL Passive DNS REST API to get and display information about this input.\n\nTo make it work a username and a password are thus required to authenticate to the CIRCL Passive DNS API.", + "references": ["https://www.circl.lu/services/passive-dns/", "https://datatracker.ietf.org/doc/draft-dulaunoy-dnsop-passive-dns-cof/"] +} diff --git a/doc/expansion/circl_passivessl.json b/doc/expansion/circl_passivessl.json new file mode 100644 index 00000000..ec449ee7 --- /dev/null +++ b/doc/expansion/circl_passivessl.json @@ -0,0 +1,9 @@ +{ + "description": "Modules to access CIRCL Passive SSL.", + "logo": "logos/passivessl.png", + "requirements": ["pypssl: Passive SSL python library", "A CIRCL passive SSL account with username & password"], + "input": "Ip-address attribute.", + "output": "Text describing passive SSL information related to the input attribute.", + "features": "This module takes an ip-address (ip-src or ip-dst) attribute as input, and queries the CIRCL Passive SSL REST API to get and display information about this input.\n\nTo make it work a username and a password are thus required to authenticate to the CIRCL Passive SSL API.", + "references": ["https://www.circl.lu/services/passive-ssl/"] +} diff --git a/doc/expansion/countrycode.json b/doc/expansion/countrycode.json new file mode 100644 index 00000000..c6214e50 --- /dev/null +++ b/doc/expansion/countrycode.json @@ -0,0 +1,6 @@ +{ + "description": "Module to expand country codes.", + "input": "Hostname or domain attribute.", + "output": "Text with the country code the input belongs to.", + "features": "The module takes a domain or a hostname as input, and returns the country it belongs to.\n\nFor non country domains, a list of the most common possible extensions is used." +} diff --git a/doc/expansion/crowdstrike_falcon.json b/doc/expansion/crowdstrike_falcon.json new file mode 100644 index 00000000..07e9dbde --- /dev/null +++ b/doc/expansion/crowdstrike_falcon.json @@ -0,0 +1,9 @@ +{ + "description": "Module to query Crowdstrike Falcon.", + "logo": "logos/crowdstrike.png", + "requirements": ["A CrowdStrike API access (API id & key)"], + "input": "A MISP attribute included in the following list:\n- domain\n- email-attachment\n- email-dst\n- email-reply-to\n- email-src\n- email-subject\n- filename\n- hostname\n- ip-src\n- ip-dst\n- md5\n- mutex\n- regkey\n- sha1\n- sha256\n- uri\n- url\n- user-agent\n- whois-registrant-email\n- x509-fingerprint-md5", + "output": "MISP attributes mapped after the CrowdStrike API has been queried, included in the following list:\n- hostname\n- email-src\n- email-subject\n- filename\n- md5\n- sha1\n- sha256\n- ip-dst\n- ip-dst\n- mutex\n- regkey\n- url\n- user-agent\n- x509-fingerprint-md5", + "references": ["https://www.crowdstrike.com/products/crowdstrike-falcon-faq/"], + "features": "This module takes a MISP attribute as input to query a CrowdStrike Falcon API. The API returns then the result of the query with some types we map into compatible types we add as MISP attributes.\n\nPlease note that composite attributes composed by at least one of the input types mentionned below (domains, IPs, hostnames) are also supported." +} diff --git a/doc/expansion/cuckoo_submit.json b/doc/expansion/cuckoo_submit.json new file mode 100644 index 00000000..7fe80674 --- /dev/null +++ b/doc/expansion/cuckoo_submit.json @@ -0,0 +1,9 @@ +{ + "description": "An expansion module to submit files and URLs to Cuckoo Sandbox.", + "logo": "logos/cuckoo.png", + "requirements": ["Access to a Cuckoo Sandbox API and an API key if the API requires it. (api_url and api_key)"], + "input": "A malware-sample or attachment for files. A url or domain for URLs.", + "output": "A text field containing 'Cuckoo task id: '", + "references": ["https://cuckoosandbox.org/", "https://cuckoo.sh/docs/"], + "features": "The module takes a malware-sample, attachment, url or domain and submits it to Cuckoo Sandbox.\n The returned task id can be used to retrieve results when the analysis completed." +} diff --git a/doc/expansion/cve.json b/doc/expansion/cve.json new file mode 100644 index 00000000..04f131fc --- /dev/null +++ b/doc/expansion/cve.json @@ -0,0 +1,8 @@ +{ + "description": "An expansion hover module to expand information about CVE id.", + "logo": "logos/cve.png", + "input": "Vulnerability attribute.", + "output": "Text giving information about the CVE related to the Vulnerability.", + "references": ["https://cve.circl.lu/", "https://cve.mitre.org/"], + "features": "The module takes a vulnerability attribute as input and queries the CIRCL CVE search API to get information about the vulnerability as it is described in the list of CVEs." +} diff --git a/doc/expansion/dbl_spamhaus.json b/doc/expansion/dbl_spamhaus.json new file mode 100644 index 00000000..ea73dcb3 --- /dev/null +++ b/doc/expansion/dbl_spamhaus.json @@ -0,0 +1,9 @@ +{ + "description": "Module to check Spamhaus DBL for a domain name.", + "logo": "logos/spamhaus.jpg", + "requirements": ["dnspython3: DNS python3 library"], + "input": "Domain or hostname attribute.", + "output": "Information about the nature of the input.", + "references": ["https://www.spamhaus.org/faq/section/Spamhaus%20DBL"], + "features": "This modules takes a domain or a hostname in input and queries the Domain Block List provided by Spamhaus to determine what kind of domain it is.\n\nDBL then returns a response code corresponding to a certain classification of the domain we display. If the queried domain is not in the list, it is also mentionned.\n\nPlease note that composite MISP attributes containing domain or hostname are supported as well." +} diff --git a/doc/expansion/dns.json b/doc/expansion/dns.json new file mode 100644 index 00000000..dc43b64d --- /dev/null +++ b/doc/expansion/dns.json @@ -0,0 +1,7 @@ +{ + "description": "A simple DNS expansion service to resolve IP address from domain MISP attributes.", + "requirements": ["dnspython3: DNS python3 library"], + "input": "Domain or hostname attribute.", + "output": "IP address resolving the input.", + "features": "The module takes a domain of hostname attribute as input, and tries to resolve it. If no error is encountered, the IP address that resolves the domain is returned, otherwise the origin of the error is displayed.\n\nThe address of the DNS resolver to use is also configurable, but if no configuration is set, we use the Google public DNS address (8.8.8.8).\n\nPlease note that composite MISP attributes containing domain or hostname are supported as well." +} diff --git a/doc/expansion/domaintools.json b/doc/expansion/domaintools.json new file mode 100644 index 00000000..849028cd --- /dev/null +++ b/doc/expansion/domaintools.json @@ -0,0 +1,9 @@ +{ + "description": "DomainTools MISP expansion module.", + "logo": "logos/domaintools.png", + "requirements": ["Domaintools python library", "A Domaintools API access (username & apikey)"], + "input": "A MISP attribute included in the following list:\n- domain\n- hostname\n- email-src\n- email-dst\n- target-email\n- whois-registrant-email\n- whois-registrant-name\n- whois-registrant-phone\n- ip-src\n- ip-dst", + "output": "MISP attributes mapped after the Domaintools API has been queried, included in the following list:\n- whois-registrant-email\n- whois-registrant-phone\n- whois-registrant-name\n- whois-registrar\n- whois-creation-date\n- text\n- domain", + "references": ["https://www.domaintools.com/"], + "features": "This module takes a MISP attribute as input to query the Domaintools API. The API returns then the result of the query with some types we map into compatible types we add as MISP attributes.\n\nPlease note that composite attributes composed by at least one of the input types mentionned below (domains, IPs, hostnames) are also supported." +} diff --git a/doc/expansion/eupi.json b/doc/expansion/eupi.json new file mode 100644 index 00000000..02a16fb0 --- /dev/null +++ b/doc/expansion/eupi.json @@ -0,0 +1,9 @@ +{ + "description": "A module to query the Phishing Initiative service (https://phishing-initiative.lu).", + "logo": "logos/eupi.png", + "requirements": ["pyeupi: eupi python library", "An access to the Phishing Initiative API (apikey & url)"], + "input": "A domain, hostname or url MISP attribute.", + "output": "Text containing information about the input, resulting from the query on Phishing Initiative.", + "references": ["https://phishing-initiative.eu/?lang=en"], + "features": "This module takes a domain, hostname or url MISP attribute as input to query the Phishing Initiative API. The API returns then the result of the query with some information about the value queried.\n\nPlease note that composite attributes containing domain or hostname are also supported." +} diff --git a/doc/expansion/farsight_passivedns.json b/doc/expansion/farsight_passivedns.json new file mode 100644 index 00000000..2c1bf05a --- /dev/null +++ b/doc/expansion/farsight_passivedns.json @@ -0,0 +1,9 @@ +{ + "description": "Module to access Farsight DNSDB Passive DNS.", + "logo": "logos/farsight.png", + "requirements": ["An access to the Farsight Passive DNS API (apikey)"], + "input": "A domain, hostname or IP address MISP attribute.", + "output": "Text containing information about the input, resulting from the query on the Farsight Passive DNS API.", + "references": ["https://www.farsightsecurity.com/"], + "features": "This module takes a domain, hostname or IP address MISP attribute as input to query the Farsight Passive DNS API. The API returns then the result of the query with some information about the value queried." +} diff --git a/doc/expansion/geoip_country.json b/doc/expansion/geoip_country.json new file mode 100644 index 00000000..9db49a27 --- /dev/null +++ b/doc/expansion/geoip_country.json @@ -0,0 +1,9 @@ +{ + "description": "Module to query a local copy of Maxmind's Geolite database.", + "logo": "logos/maxmind.png", + "requirements": ["A local copy of Maxmind's Geolite database"], + "input": "An IP address MISP Attribute.", + "output": "Text containing information about the location of the IP address.", + "references": ["https://www.maxmind.com/en/home"], + "features": "This module takes an IP address MISP attribute as input and queries a local copy of the Maxmind's Geolite database to get information about the location of this IP address.\n\nPlease note that composite attributes domain|ip are also supported." +} diff --git a/doc/expansion/hashdd.json b/doc/expansion/hashdd.json new file mode 100644 index 00000000..d963820c --- /dev/null +++ b/doc/expansion/hashdd.json @@ -0,0 +1,7 @@ +{ + "description": "A hover module to check hashes against hashdd.com including NSLR dataset.", + "input": "A hash MISP attribute (md5).", + "output": "Text describing the known level of the hash in the hashdd databases.", + "references": ["https://hashdd.com/"], + "features": "This module takes a hash attribute as input to check its known level, using the hashdd API. This information is then displayed." +} diff --git a/doc/expansion/intelmq_eventdb.json b/doc/expansion/intelmq_eventdb.json new file mode 100644 index 00000000..bc48414e --- /dev/null +++ b/doc/expansion/intelmq_eventdb.json @@ -0,0 +1,9 @@ +{ + "description": "Module to access intelmqs eventdb.", + "logo": "logos/intelmq.png", + "requirements": ["psycopg2: Python library to support PostgreSQL", "An access to the IntelMQ database (username, password, hostname and database reference)"], + "input": "A hostname, domain, IP address or AS attribute.", + "output": "Text giving information about the input using IntelMQ database.", + "references": ["https://github.com/certtools/intelmq", "https://intelmq.readthedocs.io/en/latest/Developers-Guide/"], + "features": "/!\\ EXPERIMENTAL MODULE, some features may not work /!\\\n\nThis module takes a domain, hostname, IP address or Autonomous system MISP attribute as input to query the IntelMQ database. The result of the query gives then additional information about the input." +} diff --git a/doc/expansion/ipasn.json b/doc/expansion/ipasn.json new file mode 100644 index 00000000..68b10d1e --- /dev/null +++ b/doc/expansion/ipasn.json @@ -0,0 +1,8 @@ +{ + "description": "Module to query an IP ASN history service (https://github.com/D4-project/IPASN-History).", + "requirements": ["pyipasnhistory: Python library to access IPASN-history instance"], + "input": "An IP address MISP attribute.", + "output": "Text describing additional information about the input after a query on the IPASN-history database.", + "references": ["https://github.com/D4-project/IPASN-History"], + "features": "This module takes an IP address attribute as input and queries the CIRCL IPASN service to get additional information about the input." +} diff --git a/doc/expansion/iprep.json b/doc/expansion/iprep.json new file mode 100644 index 00000000..95250e0d --- /dev/null +++ b/doc/expansion/iprep.json @@ -0,0 +1,8 @@ +{ + "description": "Module to query IPRep data for IP addresses.", + "requirements": ["An access to the packetmail API (apikey)"], + "input": "An IP address MISP attribute.", + "output": "Text describing additional information about the input after a query on the IPRep API.", + "references": ["https://github.com/mahesh557/packetmail"], + "features": "This module takes an IP address attribute as input and queries the database from packetmail.net to get some information about the reputation of the IP." +} diff --git a/doc/expansion/macaddress_io.json b/doc/expansion/macaddress_io.json new file mode 100644 index 00000000..6bd26586 --- /dev/null +++ b/doc/expansion/macaddress_io.json @@ -0,0 +1,9 @@ +{ + "description": "MISP hover module for macaddress.io", + "logo": "logos/macaddress_io.png", + "requirements": ["maclookup: macaddress.io python library", "An access to the macaddress.io API (apikey)"], + "input": "MAC address MISP attribute.", + "output": "Text containing information on the MAC address fetched from a query on macaddress.io.", + "references": ["https://macaddress.io/", "https://github.com/CodeLineFi/maclookup-python"], + "features": "This module takes a MAC address attribute as input and queries macaddress.io for additional information.\n\nThis information contains data about:\n- MAC address details\n- Vendor details\n- Block details" +} diff --git a/doc/expansion/onyphe.json b/doc/expansion/onyphe.json new file mode 100644 index 00000000..04ebdd36 --- /dev/null +++ b/doc/expansion/onyphe.json @@ -0,0 +1,9 @@ +{ + "description": "Module to process a query on Onyphe.", + "logo": "logos/onyphe.jpg", + "requirements": ["onyphe python library", "An access to the Onyphe API (apikey)"], + "input": "A domain, hostname or IP address MISP attribute.", + "output": "MISP attributes fetched from the Onyphe query.", + "references": ["https://www.onyphe.io/", "https://github.com/sebdraven/pyonyphe"], + "features": "This module takes a domain, hostname, or IP address attribute as input in order to query the Onyphe API. Data fetched from the query is then parsed and MISP attributes are extracted." +} diff --git a/doc/expansion/onyphe_full.json b/doc/expansion/onyphe_full.json new file mode 100644 index 00000000..4b722faf --- /dev/null +++ b/doc/expansion/onyphe_full.json @@ -0,0 +1,9 @@ +{ + "description": "Module to process a full query on Onyphe.", + "logo": "logos/onyphe.jpg", + "requirements": ["onyphe python library", "An access to the Onyphe API (apikey)"], + "input": "A domain, hostname or IP address MISP attribute.", + "output": "MISP attributes fetched from the Onyphe query.", + "references": ["https://www.onyphe.io/", "https://github.com/sebdraven/pyonyphe"], + "features": "This module takes a domain, hostname, or IP address attribute as input in order to query the Onyphe API. Data fetched from the query is then parsed and MISP attributes are extracted.\n\nThe parsing is here more advanced than the one on onyphe module, and is returning more attributes, since more fields of the query result are watched and parsed." +} diff --git a/doc/expansion/otx.json b/doc/expansion/otx.json new file mode 100644 index 00000000..c6032ccc --- /dev/null +++ b/doc/expansion/otx.json @@ -0,0 +1,9 @@ +{ + "description": "Module to get information from AlienVault OTX.", + "logo": "logos/otx.png", + "requirements": ["An access to the OTX API (apikey)"], + "input": "A MISP attribute included in the following list:\n- hostname\n- domain\n- ip-src\n- ip-dst\n- md5\n- sha1\n- sha256\n- sha512", + "output": "MISP attributes mapped from the result of the query on OTX, included in the following list:\n- domain\n- ip-src\n- ip-dst\n- text\n- md5\n- sha1\n- sha256\n- sha512\n- email", + "references": ["https://www.alienvault.com/open-threat-exchange"], + "features": "This module takes a MISP attribute as input to query the OTX Alienvault API. The API returns then the result of the query with some types we map into compatible types we add as MISP attributes." +} diff --git a/doc/expansion/passivetotal.json b/doc/expansion/passivetotal.json new file mode 100644 index 00000000..ef8b044a --- /dev/null +++ b/doc/expansion/passivetotal.json @@ -0,0 +1,9 @@ +{ + "description": "", + "logo": "logos/passivetotal.png", + "requirements": ["Passivetotal python library", "An access to the PassiveTotal API (apikey)"], + "input": "A MISP attribute included in the following list:\n- hostname\n- domain\n- ip-src\n- ip-dst\n- x509-fingerprint-sha1\n- email-src\n- email-dst\n- target-email\n- whois-registrant-email\n- whois-registrant-phone\n- text\n- whois-registrant-name\n- whois-registrar\n- whois-creation-date", + "output": "MISP attributes mapped from the result of the query on PassiveTotal, included in the following list:\n- hostname\n- domain\n- ip-src\n- ip-dst\n- x509-fingerprint-sha1\n- email-src\n- email-dst\n- target-email\n- whois-registrant-email\n- whois-registrant-phone\n- text\n- whois-registrant-name\n- whois-registrar\n- whois-creation-date\n- md5\n- sha1\n- sha256\n- link", + "references": ["https://www.passivetotal.org/register"], + "features": "The PassiveTotal MISP expansion module brings the datasets derived from Internet scanning directly into your MISP instance. This module supports passive DNS, historic SSL, WHOIS, and host attributes. In order to use the module, you must have a valid PassiveTotal account username and API key. Registration is free and can be done by visiting https://www.passivetotal.org/register" +} diff --git a/doc/expansion/rbl.json b/doc/expansion/rbl.json new file mode 100644 index 00000000..9700eca9 --- /dev/null +++ b/doc/expansion/rbl.json @@ -0,0 +1,8 @@ +{ + "description": "Module to check an IPv4 address against known RBLs.", + "requirements": ["dnspython3: DNS python3 library"], + "input": "IP address attribute.", + "output": "Text with additional data from Real-time Blackhost Lists about the IP address.", + "references": ["[RBLs list](https://github.com/MISP/misp-modules/blob/8817de476572a10a9c9d03258ec81ca70f3d926d/misp_modules/modules/expansion/rbl.py#L20)"], + "features": "This module takes an IP address attribute as input and queries multiple know Real-time Blackhost Lists to check if they have already seen this IP address.\n\nWe display then all the information we get from those different sources." +} diff --git a/doc/expansion/reversedns.json b/doc/expansion/reversedns.json new file mode 100644 index 00000000..69344628 --- /dev/null +++ b/doc/expansion/reversedns.json @@ -0,0 +1,7 @@ +{ + "description": "Simple Reverse DNS expansion service to resolve reverse DNS from MISP attributes.", + "requirements": ["DNS python library"], + "input": "An IP address attribute.", + "output": "Hostname attribute the input is resolved into.", + "features": "The module takes an IP address as input and tries to find the hostname this IP address is resolved into.\n\nThe address of the DNS resolver to use is also configurable, but if no configuration is set, we use the Google public DNS address (8.8.8.8).\n\nPlease note that composite MISP attributes containing IP addresses are supported as well." +} diff --git a/doc/expansion/securitytrails.json b/doc/expansion/securitytrails.json new file mode 100644 index 00000000..8541e4e0 --- /dev/null +++ b/doc/expansion/securitytrails.json @@ -0,0 +1,9 @@ +{ + "description": "An expansion modules for SecurityTrails.", + "logo": "logos/securitytrails.png", + "requirements": ["dnstrails python library", "An access to the SecurityTrails API (apikey)"], + "input": "A domain, hostname or IP address attribute.", + "output": "MISP attributes resulting from the query on SecurityTrails API, included in the following list:\n- hostname\n- domain\n- ip-src\n- ip-dst\n- dns-soa-email\n- whois-registrant-email\n- whois-registrant-phone\n- whois-registrant-name\n- whois-registrar\n- whois-creation-date\n- domain", + "references": ["https://securitytrails.com/"], + "features": "The module takes a domain, hostname or IP address attribute as input and queries the SecurityTrails API with it.\n\nMultiple parsing operations are then processed on the result of the query to extract a much information as possible.\n\nFrom this data extracted are then mapped MISP attributes." +} diff --git a/doc/expansion/shodan.json b/doc/expansion/shodan.json new file mode 100644 index 00000000..57241f06 --- /dev/null +++ b/doc/expansion/shodan.json @@ -0,0 +1,9 @@ +{ + "description": "Module to query on Shodan.", + "logo": "logos/shodan.png", + "requirements": ["shodan python library", "An access to the Shodan API (apikey)"], + "input": "An IP address MISP attribute.", + "output": "Text with additional data about the input, resulting from the query on Shodan.", + "references": ["https://www.shodan.io/"], + "features": "The module takes an IP address as input and queries the Shodan API to get some additional data about it." +} diff --git a/doc/expansion/sigma_queries.json b/doc/expansion/sigma_queries.json new file mode 100644 index 00000000..f127ba4c --- /dev/null +++ b/doc/expansion/sigma_queries.json @@ -0,0 +1,9 @@ +{ + "description": "An expansion hover module to display the result of sigma queries.", + "logo": "logos/sigma.png", + "requirements": ["Sigma python library"], + "input": "A Sigma attribute.", + "output": "Text displaying results of queries on the Sigma attribute.", + "references": ["https://github.com/Neo23x0/sigma/wiki"], + "features": "This module takes a Sigma rule attribute as input and tries all the different queries available to convert it into different formats recognized by SIEMs." +} diff --git a/doc/expansion/sigma_syntax_validator.json b/doc/expansion/sigma_syntax_validator.json new file mode 100644 index 00000000..8e17ae01 --- /dev/null +++ b/doc/expansion/sigma_syntax_validator.json @@ -0,0 +1,9 @@ +{ + "description": "An expansion hover module to perform a syntax check on sigma rules.", + "logo": "logos/sigma.png", + "requirements": ["Sigma python library", "Yaml python library"], + "input": "A Sigma attribute.", + "output": "Text describing the validity of the Sigma rule.", + "references": ["https://github.com/Neo23x0/sigma/wiki"], + "features": "This module takes a Sigma rule attribute as input and performs a syntax check on it.\n\nIt displays then that the rule is valid if it is the case, and the error related to the rule otherwise." +} diff --git a/doc/expansion/sourcecache.json b/doc/expansion/sourcecache.json new file mode 100644 index 00000000..ab4669c4 --- /dev/null +++ b/doc/expansion/sourcecache.json @@ -0,0 +1,8 @@ +{ + "description": "Module to cache web pages of analysis reports, OSINT sources. The module returns a link of the cached page.", + "requirements": ["urlarchiver: python library to fetch and archive URL on the file-system"], + "input": "A link or url attribute.", + "output": "A malware-sample attribute describing the cached page.", + "references": ["https://github.com/adulau/url_archiver"], + "features": "This module takes a link or url attribute as input and caches the related web page. It returns then a link of the cached page." +} diff --git a/doc/expansion/stix2_pattern_syntax_validator.json b/doc/expansion/stix2_pattern_syntax_validator.json new file mode 100644 index 00000000..2ea43b53 --- /dev/null +++ b/doc/expansion/stix2_pattern_syntax_validator.json @@ -0,0 +1,9 @@ +{ + "description": "An expansion hover module to perform a syntax check on stix2 patterns.", + "logo": "logos/stix.png", + "requirements": ["stix2patterns python library"], + "input": "A STIX2 pattern attribute.", + "output": "Text describing the validity of the STIX2 pattern.", + "references": ["[STIX2.0 patterning specifications](http://docs.oasis-open.org/cti/stix/v2.0/cs01/part5-stix-patterning/stix-v2.0-cs01-part5-stix-patterning.html)"], + "features": "This module takes a STIX2 pattern attribute as input and performs a syntax check on it.\n\nIt displays then that the rule is valid if it is the case, and the error related to the rule otherwise." +} diff --git a/doc/expansion/threatcrowd.json b/doc/expansion/threatcrowd.json new file mode 100644 index 00000000..99725b8e --- /dev/null +++ b/doc/expansion/threatcrowd.json @@ -0,0 +1,8 @@ +{ + "description": "Module to get information from ThreatCrowd.", + "logo": "logos/threatcrowd.png", + "input": "A MISP attribute included in the following list:\n- hostname\n- domain\n- ip-src\n- ip-dst\n- md5\n- sha1\n- sha256\n- sha512\n- whois-registrant-email", + "output": "MISP attributes mapped from the result of the query on ThreatCrowd, included in the following list:\n- domain\n- ip-src\n- ip-dst\n- text\n- md5\n- sha1\n- sha256\n- sha512\n- hostname\n- whois-registrant-email", + "references": ["https://www.threatcrowd.org/"], + "features": "This module takes a MISP attribute as input and queries ThreatCrowd with it.\n\nThe result of this query is then parsed and some data is mapped into MISP attributes in order to enrich the input attribute." +} diff --git a/doc/expansion/threatminer.json b/doc/expansion/threatminer.json new file mode 100644 index 00000000..d2f26bd4 --- /dev/null +++ b/doc/expansion/threatminer.json @@ -0,0 +1,8 @@ +{ + "description": "Module to get information from ThreatMiner.", + "logo": "logos/threatminer.png", + "input": "A MISP attribute included in the following list:\n- hostname\n- domain\n- ip-src\n- ip-dst\n- md5\n- sha1\n- sha256\n- sha512", + "output": "MISP attributes mapped from the result of the query on ThreatMiner, included in the following list:\n- domain\n- ip-src\n- ip-dst\n- text\n- md5\n- sha1\n- sha256\n- sha512\n- ssdeep\n- authentihash\n- filename\n- whois-registrant-email\n- url\n- link", + "references": ["https://www.threatminer.org/"], + "features": "This module takes a MISP attribute as input and queries ThreatMiner with it.\n\nThe result of this query is then parsed and some data is mapped into MISP attributes in order to enrich the input attribute." +} diff --git a/doc/expansion/urlscan.json b/doc/expansion/urlscan.json new file mode 100644 index 00000000..d8477619 --- /dev/null +++ b/doc/expansion/urlscan.json @@ -0,0 +1,9 @@ +{ + "description": "An expansion module to query urlscan.io.", + "logo": "logos/urlscan.jpg", + "requirements": ["An access to the urlscan.io API"], + "input": "A domain, hostname or url attribute.", + "output": "MISP attributes mapped from the result of the query on urlscan.io.", + "references": ["https://urlscan.io/"], + "features": "This module takes a MISP attribute as input and queries urlscan.io with it.\n\nThe result of this query is then parsed and some data is mapped into MISP attributes in order to enrich the input attribute." +} diff --git a/doc/expansion/virustotal.json b/doc/expansion/virustotal.json new file mode 100644 index 00000000..90080037 --- /dev/null +++ b/doc/expansion/virustotal.json @@ -0,0 +1,9 @@ +{ + "description": "Module to get information from virustotal.", + "logo": "logos/virustotal.png", + "requirements": ["An access to the VirusTotal API (apikey)"], + "input": "A domain, hash (md5, sha1, sha256 or sha512), hostname or IP address attribute.", + "output": "MISP attributes mapped from the rersult of the query on VirusTotal API.", + "references": ["https://www.virustotal.com/"], + "features": "This module takes a MISP attribute as input and queries the VirusTotal API with it, in order to get additional data on the input attribute.\n\nMultiple recursive requests on the API can then be processed on some attributes found in the first request. A limit can be set to restrict the number of values to query again, and at the same time the number of request submitted to the API.\n\nThis limit is important because the default user VirusTotal apikey only allows to process a certain nunmber of queries per minute. As a consequence it is recommended to have a larger number of requests or a private apikey.\n\nData is then mapped into MISP attributes." +} diff --git a/doc/expansion/vmray_submit.json b/doc/expansion/vmray_submit.json new file mode 100644 index 00000000..ea6cf3ff --- /dev/null +++ b/doc/expansion/vmray_submit.json @@ -0,0 +1,9 @@ +{ + "description": "Module to submit a sample to VMRay.", + "logo": "logos/vmray.png", + "requirements": ["An access to the VMRay API (apikey & url)"], + "input": "An attachment or malware-sample attribute.", + "output": "MISP attributes mapped from the result of the query on VMRay API, included in the following list:\n- text\n- sha1\n- sha256\n- md5\n- link", + "references": ["https://www.vmray.com/"], + "features": "This module takes an attachment or malware-sample attribute as input to query the VMRay API.\n\nThe sample contained within the attribute in then enriched with data from VMRay mapped into MISP attributes." +} diff --git a/doc/expansion/vulndb.json b/doc/expansion/vulndb.json new file mode 100644 index 00000000..330a3eb6 --- /dev/null +++ b/doc/expansion/vulndb.json @@ -0,0 +1,9 @@ +{ + "description": "Module to query VulnDB (RiskBasedSecurity.com).", + "logo": "logos/vulndb.png", + "requirements": ["An access to the VulnDB API (apikey, apisecret)"], + "input": "A vulnerability attribute.", + "output": "Additional data enriching the CVE input, fetched from VulnDB.", + "references": ["https://vulndb.cyberriskanalytics.com/"], + "features": "This module takes a vulnerability attribute as input and queries VulnDB in order to get some additional data about it.\n\nThe API gives the result of the query which can be displayed in the screen, and/or mapped into MISP attributes to add in the event." +} diff --git a/doc/expansion/vulners.json b/doc/expansion/vulners.json new file mode 100644 index 00000000..f3f30267 --- /dev/null +++ b/doc/expansion/vulners.json @@ -0,0 +1,9 @@ +{ + "description": "An expansion hover module to expand information about CVE id using Vulners API.", + "logo": "logos/vulners.png", + "requirements": ["Vulners python library", "An access to the Vulners API"], + "input": "A vulnerability attribute.", + "output": "Text giving additional information about the CVE in input.", + "references": ["https://vulners.com/"], + "features": "This module takes a vulnerability attribute as input and queries the Vulners API in order to get some additional data about it.\n\nThe API then returns details about the vulnerability." +} diff --git a/doc/expansion/whois.json b/doc/expansion/whois.json new file mode 100644 index 00000000..938bad5f --- /dev/null +++ b/doc/expansion/whois.json @@ -0,0 +1,8 @@ +{ + "description": "Module to query a local instance of uwhois (https://github.com/rafiot/uwhoisd).", + "requirements": ["uwhois: A whois python library"], + "input": "A domain or IP address attribute.", + "output": "Text describing the result of a whois request for the input value.", + "references": ["https://github.com/rafiot/uwhoisd"], + "features": "This module takes a domain or IP address attribute as input and queries a 'Univseral Whois proxy server' to get the correct details of the Whois query on the input value (check the references for more details about this whois server)." +} diff --git a/doc/expansion/wiki.json b/doc/expansion/wiki.json new file mode 100644 index 00000000..d6de62b3 --- /dev/null +++ b/doc/expansion/wiki.json @@ -0,0 +1,9 @@ +{ + "description": "An expansion hover module to extract information from Wikidata to have additional information about particular term for analysis.", + "logo": "logos/wikidata.png", + "requirements": ["SPARQLWrapper python library"], + "input": "Text attribute.", + "output": "Text attribute.", + "references": ["https://www.wikidata.org"], + "features": "This module takes a text attribute as input and queries the Wikidata API. If the text attribute is clear enough to define a specific term, the API returns a wikidata link in response." +} diff --git a/doc/expansion/xforceexchange.json b/doc/expansion/xforceexchange.json new file mode 100644 index 00000000..bbe3c866 --- /dev/null +++ b/doc/expansion/xforceexchange.json @@ -0,0 +1,9 @@ +{ + "description": "An expansion module for IBM X-Force Exchange.", + "logo": "logos/xforce.png", + "requirements": ["An access to the X-Force API (apikey)"], + "input": "A MISP attribute included in the following list:\n- ip-src\n- ip-dst\n- vulnerability\n- md5\n- sha1\n- sha256", + "output": "MISP attributes mapped from the result of the query on X-Force Exchange.", + "references": ["https://exchange.xforce.ibmcloud.com/"], + "features": "This module takes a MISP attribute as input to query the X-Force API. The API returns then additional information known in their threats data, that is mapped into MISP attributes." +} diff --git a/doc/expansion/yara_query.json b/doc/expansion/yara_query.json new file mode 100644 index 00000000..408353d3 --- /dev/null +++ b/doc/expansion/yara_query.json @@ -0,0 +1,9 @@ +{ + "description": "An expansion & hover module to translate any hash attribute into a yara rule.", + "logo": "logos/yara.png", + "requirements": ["yara-python python library"], + "features": "The module takes a hash attribute (md5, sha1, sha256, imphash) as input, and is returning a YARA rule from it. This YARA rule is also validated using the same method as in 'yara_syntax_validator' module.\nBoth hover and expansion functionalities are supported with this module, where the hover part is displaying the resulting YARA rule and the expansion part allows you to add the rule as a new attribute, as usual with expansion modules.", + "input": "MISP Hash attribute (md5, sha1, sha256, imphash, or any of the composite attribute with filename and one of the previous hash type).", + "output": "YARA rule.", + "references": ["https://virustotal.github.io/yara/", "https://github.com/virustotal/yara-python"] +} diff --git a/doc/expansion/yara_syntax_validator.json b/doc/expansion/yara_syntax_validator.json new file mode 100644 index 00000000..93a96eec --- /dev/null +++ b/doc/expansion/yara_syntax_validator.json @@ -0,0 +1,9 @@ +{ + "description": "An expansion hover module to perform a syntax check on if yara rules are valid or not.", + "logo": "logos/yara.png", + "requirements": ["yara_python python library"], + "input": "YARA rule attribute.", + "output": "Text to inform users if their rule is valid.", + "references": ["http://virustotal.github.io/yara/"], + "features": "This modules simply takes a YARA rule as input, and checks its syntax. It returns then a confirmation if the syntax is valid, otherwise the syntax error is displayed." +} diff --git a/doc/export_mod/cef_export.json b/doc/export_mod/cef_export.json new file mode 100644 index 00000000..84bba8ea --- /dev/null +++ b/doc/export_mod/cef_export.json @@ -0,0 +1,8 @@ +{ + "description": "Module to export a MISP event in CEF format.", + "requirements": [], + "features": "The module takes a MISP event in input, to look every attribute. Each attribute matching with some predefined types is then exported in Common Event Format.\nThus, there is no particular feature concerning MISP Events since any event can be exported. However, 4 configuration parameters recognized by CEF format are required and should be provided by users before exporting data: the device vendor, product and version, as well as the default severity of data.", + "references": ["https://community.softwaregrp.com/t5/ArcSight-Connectors/ArcSight-Common-Event-Format-CEF-Guide/ta-p/1589306?attachment-id=65537"], + "input": "MISP Event attributes", + "output": "Common Event Format file" +} diff --git a/doc/export_mod/goamlexport.json b/doc/export_mod/goamlexport.json new file mode 100644 index 00000000..57a15879 --- /dev/null +++ b/doc/export_mod/goamlexport.json @@ -0,0 +1,9 @@ +{ + "description": "This module is used to export MISP events containing transaction objects into GoAML format.", + "logo": "logos/goAML.jpg", + "requirements": ["PyMISP","MISP objects"], + "features": "The module works as long as there is at least one transaction object in the Event.\n\nThen in order to have a valid GoAML document, please follow these guidelines:\n- For each transaction object, use either a bank-account, person, or legal-entity object to describe the origin of the transaction, and again one of them to describe the target of the transaction.\n- Create an object reference for both origin and target objects of the transaction.\n- A bank-account object needs a signatory, which is a person object, put as object reference of the bank-account.\n- A person can have an address, which is a geolocation object, put as object reference of the person.\n\nSupported relation types for object references that are recommended for each object are the folowing:\n- transaction:\n\t- 'from', 'from_my_client': Origin of the transaction - at least one of them is required.\n\t- 'to', 'to_my_client': Target of the transaction - at least one of them is required.\n\t- 'address': Location of the transaction - optional.\n- bank-account:\n\t- 'signatory': Signatory of a bank-account - the reference from bank-account to a signatory is required, but the relation-type is optional at the moment since this reference will always describe a signatory.\n\t- 'entity': Entity owning the bank account - optional.\n- person:\n\t- 'address': Address of a person - optional.", + "references": ["http://goaml.unodc.org/"], + "input": "MISP objects (transaction, bank-account, person, legal-entity, geolocation), with references, describing financial transactions and their origin and target.", + "output": "GoAML format file, describing financial transactions, with their origin and target (bank accounts, persons or entities)." +} diff --git a/doc/export_mod/liteexport.json b/doc/export_mod/liteexport.json new file mode 100644 index 00000000..110577cb --- /dev/null +++ b/doc/export_mod/liteexport.json @@ -0,0 +1,8 @@ +{ + "description": "Lite export of a MISP event.", + "requirements": [], + "features": "This module is simply producing a json MISP event format file, but exporting only Attributes from the Event. Thus, MISP Events exported with this module should have attributes that are not internal references, otherwise the resulting event would be empty.", + "references": [], + "input": "MISP Event attributes", + "output": "Lite MISP Event" +} diff --git a/doc/export_mod/nexthinkexport.json b/doc/export_mod/nexthinkexport.json new file mode 100644 index 00000000..182448c7 --- /dev/null +++ b/doc/export_mod/nexthinkexport.json @@ -0,0 +1,9 @@ +{ + "description": "Nexthink NXQL query export module", + "requirements": [], + "features": "This module export an event as Nexthink NXQL queries that can then be used in your own python3 tool or from wget/powershell", + "references": ["https://doc.nexthink.com/Documentation/Nexthink/latest/APIAndIntegrations/IntroducingtheWebAPIV2"], + "input": "MISP Event attributes", + "output": "Nexthink NXQL queries", + "logo": "logos/nexthink.svg" +} diff --git a/doc/export_mod/osqueryexport.json b/doc/export_mod/osqueryexport.json new file mode 100644 index 00000000..6543cb1d --- /dev/null +++ b/doc/export_mod/osqueryexport.json @@ -0,0 +1,9 @@ +{ + "description": "OSQuery export of a MISP event.", + "requirements": [], + "features": "This module export an event as osquery queries that can be used in packs or in fleet management solution like Kolide.", + "references": [], + "input": "MISP Event attributes", + "output": "osquery SQL queries", + "logo": "logos/osquery.png" +} diff --git a/doc/export_mod/pdfexport.json b/doc/export_mod/pdfexport.json new file mode 100644 index 00000000..f1654dc8 --- /dev/null +++ b/doc/export_mod/pdfexport.json @@ -0,0 +1,8 @@ +{ + "description": "Simple export of a MISP event to PDF.", + "requirements": ["PyMISP", "reportlab"], + "features": "The module takes care of the PDF file building, and work with any MISP Event. Except the requirement of reportlab, used to create the file, there is no special feature concerning the Event. Some parameters can be given through the config dict. 'MISP_base_url_for_dynamic_link' is your MISP URL, to attach an hyperlink to your event on your MISP instance from the PDF. Keep it clear to avoid hyperlinks in the generated pdf.\n 'MISP_name_for_metadata' is your CERT or MISP instance name. Used as text in the PDF' metadata\n 'Activate_textual_description' is a boolean (True or void) to activate the textual description/header abstract of an event\n 'Activate_galaxy_description' is a boolean (True or void) to activate the description of event related galaxies.\n 'Activate_related_events' is a boolean (True or void) to activate the description of related event. Be aware this might leak information on confidential events linked to the current event !\n 'Activate_internationalization_fonts' is a boolean (True or void) to activate Noto fonts instead of default fonts (Helvetica). This allows the support of CJK alphabet. Be sure to have followed the procedure to download Noto fonts (~70Mo) in the right place (/tools/pdf_fonts/Noto_TTF), to allow PyMisp to find and use them during PDF generation.\n 'Custom_fonts_path' is a text (path or void) to the TTF file of your choice, to create the PDF with it. Be aware the PDF won't support bold/italic/special style anymore with this option ", + "references": ["https://acrobat.adobe.com/us/en/acrobat/about-adobe-pdf.html"], + "input": "MISP Event", + "output": "MISP Event in a PDF file." +} diff --git a/doc/export_mod/testexport.json b/doc/export_mod/testexport.json new file mode 100644 index 00000000..213ea924 --- /dev/null +++ b/doc/export_mod/testexport.json @@ -0,0 +1,3 @@ +{ + "description": "Skeleton export module." +} diff --git a/doc/export_mod/threatStream_misp_export.json b/doc/export_mod/threatStream_misp_export.json new file mode 100644 index 00000000..3fdc50a7 --- /dev/null +++ b/doc/export_mod/threatStream_misp_export.json @@ -0,0 +1,9 @@ +{ + "description": "Module to export a structured CSV file for uploading to threatStream.", + "logo": "logos/threatstream.png", + "requirements": ["csv"], + "features": "The module takes a MISP event in input, to look every attribute. Each attribute matching with some predefined types is then exported in a CSV format recognized by ThreatStream.", + "references": ["https://www.anomali.com/platform/threatstream", "https://github.com/threatstream"], + "input": "MISP Event attributes", + "output": "ThreatStream CSV format file" +} diff --git a/doc/export_mod/threat_connect_export.json b/doc/export_mod/threat_connect_export.json new file mode 100644 index 00000000..8d195721 --- /dev/null +++ b/doc/export_mod/threat_connect_export.json @@ -0,0 +1,9 @@ +{ + "description": "Module to export a structured CSV file for uploading to ThreatConnect.", + "logo": "logos/threatconnect.png", + "requirements": ["csv"], + "features": "The module takes a MISP event in input, to look every attribute. Each attribute matching with some predefined types is then exported in a CSV format recognized by ThreatConnect.\nUsers should then provide, as module configuration, the source of data they export, because it is required by the output format.", + "references": ["https://www.threatconnect.com"], + "input": "MISP Event attributes", + "output": "ThreatConnect CSV format file" +} diff --git a/doc/generate_documentation.py b/doc/generate_documentation.py new file mode 100644 index 00000000..caef84e3 --- /dev/null +++ b/doc/generate_documentation.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +import os +import json + +module_types = ['expansion', 'export_mod', 'import_mod'] +titles = ['Expansion Modules', 'Export Modules', 'Import Modules'] +markdown = ["# MISP modules documentation\n"] +githublink = 'https://github.com/MISP/misp-modules/tree/master/misp_modules/modules' + + +def generate_doc(root_path): + for _path, title in zip(module_types, titles): + markdown.append('\n## {}\n'.format(title)) + current_path = os.path.join(root_path, _path) + files = sorted(os.listdir(current_path)) + githubpath = '{}/{}'.format(githublink, _path) + for _file in files: + modulename = _file.split('.json')[0] + githubref = '{}/{}.py'.format(githubpath, modulename) + markdown.append('\n#### [{}]({})\n'.format(modulename, githubref)) + filename = os.path.join(current_path, _file) + with open(filename, 'rt') as f: + definition = json.loads(f.read()) + if 'logo' in definition: + markdown.append('\n\n'.format(definition.pop('logo'))) + if 'description' in definition: + markdown.append('\n{}\n'.format(definition.pop('description'))) + for field, value in sorted(definition.items()): + if value: + value = ', '.join(value) if isinstance(value, list) else '{}'.format(value.replace('\n', '\n>')) + markdown.append('- **{}**:\n>{}\n'.format(field, value)) + markdown.append('\n-----\n') + with open('README.md', 'w') as w: + w.write(''.join(markdown)) + + +if __name__ == '__main__': + root_path = os.path.dirname(os.path.realpath(__file__)) + generate_doc(root_path) diff --git a/doc/import_mod/csvimport.json b/doc/import_mod/csvimport.json new file mode 100644 index 00000000..6dc6182a --- /dev/null +++ b/doc/import_mod/csvimport.json @@ -0,0 +1,8 @@ +{ + "description": "Module to import MISP attributes from a csv file.", + "requirements": ["PyMISP"], + "features": "In order to parse data from a csv file, a header is required to let the module know which column is matching with known attribute fields / MISP types.\nThis header is part of the configuration of the module and should be filled out in MISP plugin settings, each field separated by COMMAS. Fields that do not match with any type known in MISP can be ignored in import, using a space or simply nothing between two separators (example: 'ip-src, , comment, ').\nThere is also one type that is confused and can be either a MISP attribute type or an attribute field: 'comment'. In this case, using 'attrComment' specifies that the attribute field 'comment' should be considered, otherwise it will be considered as the MISP attribute type.\n\nFor each MISP attribute type, an attribute is created.\nAttribute fields that are imported are the following: value, type, category, to-ids, distribution, comment, tag.", + "references": ["https://tools.ietf.org/html/rfc4180", "https://tools.ietf.org/html/rfc7111"], + "input": "CSV format file.", + "output": "MISP Event attributes" +} diff --git a/doc/import_mod/cuckooimport.json b/doc/import_mod/cuckooimport.json new file mode 100644 index 00000000..8091d074 --- /dev/null +++ b/doc/import_mod/cuckooimport.json @@ -0,0 +1,9 @@ +{ + "description": "Module to import Cuckoo JSON.", + "logo": "logos/cuckoo.png", + "requirements": [], + "features": "The module simply imports MISP Attributes from a Cuckoo JSON format file. There is thus no special feature to make it work.", + "references": ["https://cuckoosandbox.org/", "https://github.com/cuckoosandbox/cuckoo"], + "input": "Cuckoo JSON file", + "output": "MISP Event attributes" +} diff --git a/doc/import_mod/email_import.json b/doc/import_mod/email_import.json new file mode 100644 index 00000000..1f53852b --- /dev/null +++ b/doc/import_mod/email_import.json @@ -0,0 +1,8 @@ +{ + "description": "Module to import emails in MISP.", + "requirements": [], + "features": "This module can be used to import e-mail text as well as attachments and urls.\n3 configuration parameters are then used to unzip attachments, guess zip attachment passwords, and extract urls: set each one of them to True or False to process or not the respective corresponding actions.", + "references": [], + "input": "E-mail file", + "output": "MISP Event attributes" +} diff --git a/doc/import_mod/goamlimport.json b/doc/import_mod/goamlimport.json new file mode 100644 index 00000000..f2a1ec24 --- /dev/null +++ b/doc/import_mod/goamlimport.json @@ -0,0 +1,9 @@ +{ + "description": "Module to import MISP objects about financial transactions from GoAML files.", + "logo": "logos/goAML.jpg", + "requirements": ["PyMISP"], + "features": "Unlike the GoAML export module, there is here no special feature to import data from GoAML external files, since the module will import MISP Objects with their References on its own, as it is required for the export module to rebuild a valid GoAML document.", + "references": "http://goaml.unodc.org/", + "input": "GoAML format file, describing financial transactions, with their origin and target (bank accounts, persons or entities).", + "output": "MISP objects (transaction, bank-account, person, legal-entity, geolocation), with references, describing financial transactions and their origin and target." +} diff --git a/doc/import_mod/mispjson.json b/doc/import_mod/mispjson.json new file mode 100644 index 00000000..dd114051 --- /dev/null +++ b/doc/import_mod/mispjson.json @@ -0,0 +1,8 @@ +{ + "description": "Module to import MISP JSON format for merging MISP events.", + "requirements": [], + "features": "The module simply imports MISP Attributes from an other MISP Event in order to merge events together. There is thus no special feature to make it work.", + "references": [], + "input": "MISP Event", + "output": "MISP Event attributes" +} diff --git a/doc/import_mod/ocr.json b/doc/import_mod/ocr.json new file mode 100644 index 00000000..14bbf0b5 --- /dev/null +++ b/doc/import_mod/ocr.json @@ -0,0 +1,8 @@ +{ + "description": "Optical Character Recognition (OCR) module for MISP.", + "requirements": [], + "features": "The module tries to recognize some text from an image and import the result as a freetext attribute, there is then no special feature asked to users to make it work.", + "references": [], + "input": "Image", + "output": "freetext MISP attribute" +} diff --git a/doc/import_mod/openiocimport.json b/doc/import_mod/openiocimport.json new file mode 100644 index 00000000..e1733929 --- /dev/null +++ b/doc/import_mod/openiocimport.json @@ -0,0 +1,8 @@ +{ + "description": "Module to import OpenIOC packages.", + "requirements": ["PyMISP"], + "features": "The module imports MISP Attributes from OpenIOC packages, there is then no special feature for users to make it work.", + "references": ["https://www.fireeye.com/blog/threat-research/2013/10/openioc-basics.html"], + "input": "OpenIOC packages", + "output": "MISP Event attributes" +} diff --git a/doc/import_mod/threatanalyzer_import.json b/doc/import_mod/threatanalyzer_import.json new file mode 100644 index 00000000..40e4436e --- /dev/null +++ b/doc/import_mod/threatanalyzer_import.json @@ -0,0 +1,8 @@ +{ + "description": "Module to import ThreatAnalyzer archive.zip / analysis.json files.", + "requirements": [], + "features": "The module imports MISP Attributes from a ThreatAnalyzer format file. This file can be either ZIP, or JSON format.\nThere is by the way no special feature for users to make the module work.", + "references": ["https://www.threattrack.com/malware-analysis.aspx"], + "input": "ThreatAnalyzer format file", + "output": "MISP Event attributes" +} diff --git a/doc/import_mod/vmray_import.json b/doc/import_mod/vmray_import.json new file mode 100644 index 00000000..b7c0dada --- /dev/null +++ b/doc/import_mod/vmray_import.json @@ -0,0 +1,9 @@ +{ + "description": "Module to import VMRay (VTI) results.", + "logo": "logos/vmray.png", + "requirements": ["vmray_rest_api"], + "features": "The module imports MISP Attributes from VMRay format, using the VMRay api.\nUsers should then provide as the module configuration the API Key as well as the server url in order to fetch their data to import.", + "references": ["https://www.vmray.com/"], + "input": "VMRay format", + "output": "MISP Event attributes" +} diff --git a/doc/logos/backscatter_io.png b/doc/logos/backscatter_io.png new file mode 100644 index 00000000..09731128 Binary files /dev/null and b/doc/logos/backscatter_io.png differ diff --git a/doc/logos/bitcoin.png b/doc/logos/bitcoin.png new file mode 100644 index 00000000..e80ad6d1 Binary files /dev/null and b/doc/logos/bitcoin.png differ diff --git a/doc/logos/crowdstrike.png b/doc/logos/crowdstrike.png new file mode 100644 index 00000000..359cb01a Binary files /dev/null and b/doc/logos/crowdstrike.png differ diff --git a/doc/logos/cuckoo.png b/doc/logos/cuckoo.png new file mode 100644 index 00000000..57cf35a5 Binary files /dev/null and b/doc/logos/cuckoo.png differ diff --git a/doc/logos/cve.png b/doc/logos/cve.png new file mode 100644 index 00000000..315ccd81 Binary files /dev/null and b/doc/logos/cve.png differ diff --git a/doc/logos/domaintools.png b/doc/logos/domaintools.png new file mode 100644 index 00000000..69965e1b Binary files /dev/null and b/doc/logos/domaintools.png differ diff --git a/doc/logos/eupi.png b/doc/logos/eupi.png new file mode 100644 index 00000000..18006572 Binary files /dev/null and b/doc/logos/eupi.png differ diff --git a/doc/logos/farsight.png b/doc/logos/farsight.png new file mode 100644 index 00000000..31a73c10 Binary files /dev/null and b/doc/logos/farsight.png differ diff --git a/doc/logos/goAML.jpg b/doc/logos/goAML.jpg new file mode 100644 index 00000000..4e938eed Binary files /dev/null and b/doc/logos/goAML.jpg differ diff --git a/doc/logos/intelmq.png b/doc/logos/intelmq.png new file mode 100644 index 00000000..fad627cc Binary files /dev/null and b/doc/logos/intelmq.png differ diff --git a/doc/logos/macaddress_io.png b/doc/logos/macaddress_io.png new file mode 100644 index 00000000..e77f4552 Binary files /dev/null and b/doc/logos/macaddress_io.png differ diff --git a/doc/logos/maxmind.png b/doc/logos/maxmind.png new file mode 100644 index 00000000..8f8a6c6e Binary files /dev/null and b/doc/logos/maxmind.png differ diff --git a/doc/logos/nexthink.svg b/doc/logos/nexthink.svg new file mode 100644 index 00000000..f18ba8fe --- /dev/null +++ b/doc/logos/nexthink.svg @@ -0,0 +1,22 @@ + + + + nexthink + Created with Sketch. + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/doc/logos/onyphe.jpg b/doc/logos/onyphe.jpg new file mode 100644 index 00000000..cd16f760 Binary files /dev/null and b/doc/logos/onyphe.jpg differ diff --git a/doc/logos/osquery.png b/doc/logos/osquery.png new file mode 100644 index 00000000..2e4320ee Binary files /dev/null and b/doc/logos/osquery.png differ diff --git a/doc/logos/otx.png b/doc/logos/otx.png new file mode 100644 index 00000000..eae32c15 Binary files /dev/null and b/doc/logos/otx.png differ diff --git a/doc/logos/passivedns.png b/doc/logos/passivedns.png new file mode 100644 index 00000000..4959a847 Binary files /dev/null and b/doc/logos/passivedns.png differ diff --git a/doc/logos/passivessl.png b/doc/logos/passivessl.png new file mode 100644 index 00000000..e92c87d0 Binary files /dev/null and b/doc/logos/passivessl.png differ diff --git a/doc/logos/passivetotal.png b/doc/logos/passivetotal.png new file mode 100644 index 00000000..87cef695 Binary files /dev/null and b/doc/logos/passivetotal.png differ diff --git a/doc/logos/securitytrails.png b/doc/logos/securitytrails.png new file mode 100644 index 00000000..072dac54 Binary files /dev/null and b/doc/logos/securitytrails.png differ diff --git a/doc/logos/shodan.png b/doc/logos/shodan.png new file mode 100644 index 00000000..7de068e9 Binary files /dev/null and b/doc/logos/shodan.png differ diff --git a/doc/logos/sigma.png b/doc/logos/sigma.png new file mode 100644 index 00000000..0bd0db14 Binary files /dev/null and b/doc/logos/sigma.png differ diff --git a/doc/logos/spamhaus.jpg b/doc/logos/spamhaus.jpg new file mode 100644 index 00000000..4c868e46 Binary files /dev/null and b/doc/logos/spamhaus.jpg differ diff --git a/doc/logos/stix.png b/doc/logos/stix.png new file mode 100644 index 00000000..e8b82414 Binary files /dev/null and b/doc/logos/stix.png differ diff --git a/doc/logos/threatconnect.png b/doc/logos/threatconnect.png new file mode 100644 index 00000000..4c8a5b15 Binary files /dev/null and b/doc/logos/threatconnect.png differ diff --git a/doc/logos/threatcrowd.png b/doc/logos/threatcrowd.png new file mode 100644 index 00000000..94eacfc5 Binary files /dev/null and b/doc/logos/threatcrowd.png differ diff --git a/doc/logos/threatminer.png b/doc/logos/threatminer.png new file mode 100644 index 00000000..d7ac96e2 Binary files /dev/null and b/doc/logos/threatminer.png differ diff --git a/doc/logos/threatstream.png b/doc/logos/threatstream.png new file mode 100644 index 00000000..eb3837ef Binary files /dev/null and b/doc/logos/threatstream.png differ diff --git a/doc/logos/urlscan.jpg b/doc/logos/urlscan.jpg new file mode 100644 index 00000000..52e24e24 Binary files /dev/null and b/doc/logos/urlscan.jpg differ diff --git a/doc/logos/virustotal.png b/doc/logos/virustotal.png new file mode 100644 index 00000000..935c5ccf Binary files /dev/null and b/doc/logos/virustotal.png differ diff --git a/doc/logos/vmray.png b/doc/logos/vmray.png new file mode 100644 index 00000000..e2e9fa17 Binary files /dev/null and b/doc/logos/vmray.png differ diff --git a/doc/logos/vulndb.png b/doc/logos/vulndb.png new file mode 100644 index 00000000..bfaf40f8 Binary files /dev/null and b/doc/logos/vulndb.png differ diff --git a/doc/logos/vulners.png b/doc/logos/vulners.png new file mode 100644 index 00000000..ef9bab4c Binary files /dev/null and b/doc/logos/vulners.png differ diff --git a/doc/logos/wikidata.png b/doc/logos/wikidata.png new file mode 100644 index 00000000..0ffb4b15 Binary files /dev/null and b/doc/logos/wikidata.png differ diff --git a/doc/logos/xforce.png b/doc/logos/xforce.png new file mode 100644 index 00000000..96db659b Binary files /dev/null and b/doc/logos/xforce.png differ diff --git a/doc/logos/yara.png b/doc/logos/yara.png new file mode 100644 index 00000000..c74c314a Binary files /dev/null and b/doc/logos/yara.png differ diff --git a/etc/systemd/system/misp-modules.service b/etc/systemd/system/misp-modules.service new file mode 100644 index 00000000..99cd1027 --- /dev/null +++ b/etc/systemd/system/misp-modules.service @@ -0,0 +1,14 @@ +[Unit] +Description=System-wide instance of the MISP Modules +After=network.target + +[Service] +User=www-data +Group=www-data +WorkingDirectory=/usr/local/src/misp-modules +Environment="PATH=/var/www/MISP/venv/bin" +ExecStart=/var/www/MISP/venv/bin/misp-modules -l 127.0.0.1 -s + +[Install] +WantedBy=multi-user.target + diff --git a/misp_modules/__init__.py b/misp_modules/__init__.py index 1c1713b9..440ad3fe 100644 --- a/misp_modules/__init__.py +++ b/misp_modules/__init__.py @@ -29,6 +29,7 @@ import fnmatch import argparse import re import datetime +import psutil import tornado.web import tornado.process @@ -37,14 +38,14 @@ from tornado.concurrent import run_on_executor from concurrent.futures import ThreadPoolExecutor try: - from .modules import * + from .modules import * # noqa HAS_PACKAGE_MODULES = True except Exception as e: print(e) HAS_PACKAGE_MODULES = False try: - from .helpers import * + from .helpers import * # noqa HAS_PACKAGE_HELPERS = True except Exception as e: print(e) @@ -54,7 +55,7 @@ log = logging.getLogger('misp-modules') def handle_signal(sig, frame): - IOLoop.instance().add_callback(IOLoop.instance().stop) + IOLoop.instance().add_callback_from_signal(IOLoop.instance().stop) def init_logger(level=False): @@ -147,7 +148,7 @@ def load_package_modules(): mhandlers = {} modules = [] for path, module in sys.modules.items(): - r = re.findall("misp_modules[.]modules[.](\w+)[.]([^_]\w+)", path) + r = re.findall(r"misp_modules[.]modules[.](\w+)[.]([^_]\w+)", path) if r and len(r[0]) == 2: moduletype, modulename = r[0] mhandlers[modulename] = module @@ -158,6 +159,9 @@ def load_package_modules(): class ListModules(tornado.web.RequestHandler): + global loaded_modules + global mhandlers + def get(self): ret = [] for module in loaded_modules: @@ -193,7 +197,7 @@ class QueryModule(tornado.web.RequestHandler): if dict_payload.get('timeout'): timeout = datetime.timedelta(seconds=int(dict_payload.get('timeout'))) else: - timeout = datetime.timedelta(seconds=30) + timeout = datetime.timedelta(seconds=300) response = yield tornado.gen.with_timeout(timeout, self.run_request(jsonpayload)) self.write(response) except tornado.gen.TimeoutError: @@ -206,48 +210,89 @@ class QueryModule(tornado.web.RequestHandler): self.finish() +def _launch_from_current_dir(): + log.info('Launch MISP modules server from current directory.') + os.chdir(os.path.dirname(__file__)) + modulesdir = 'modules' + helpersdir = 'helpers' + load_helpers(helpersdir=helpersdir) + return load_modules(modulesdir) + + def main(): global mhandlers global loaded_modules signal.signal(signal.SIGINT, handle_signal) signal.signal(signal.SIGTERM, handle_signal) - argParser = argparse.ArgumentParser(description='misp-modules server') + argParser = argparse.ArgumentParser(description='misp-modules server', formatter_class=argparse.RawTextHelpFormatter) argParser.add_argument('-t', default=False, action='store_true', help='Test mode') argParser.add_argument('-s', default=False, action='store_true', help='Run a system install (package installed via pip)') argParser.add_argument('-d', default=False, action='store_true', help='Enable debugging') argParser.add_argument('-p', default=6666, help='misp-modules TCP port (default 6666)') argParser.add_argument('-l', default='localhost', help='misp-modules listen address (default localhost)') argParser.add_argument('-m', default=[], action='append', help='Register a custom module') + argParser.add_argument('--devel', default=False, action='store_true', help='''Start in development mode, enable debug, start only the module(s) listed in -m.\nExample: -m misp_modules.modules.expansion.bgpranking''') args = argParser.parse_args() port = args.p listen = args.l - log = init_logger(level=args.d) - if args.s: - log.info('Launch MISP modules server from package.') - load_package_helpers() - mhandlers, loaded_modules = load_package_modules() + if args.devel: + log = init_logger(level=True) + log.info('Launch MISP modules server in developement mode. Enable debug, load a list of modules is -m is used.') + if args.m: + mhandlers = {} + modules = [] + for module in args.m: + splitted = module.split(".") + modulename = splitted[-1] + moduletype = splitted[2] + mhandlers[modulename] = importlib.import_module(module) + mhandlers['type:' + modulename] = moduletype + modules.append(modulename) + log.info('MISP modules {0} imported'.format(modulename)) + else: + mhandlers, loaded_modules = _launch_from_current_dir() else: - log.info('Launch MISP modules server from current directory.') - os.chdir(os.path.dirname(__file__)) - modulesdir = 'modules' - helpersdir = 'helpers' - load_helpers(helpersdir=helpersdir) - mhandlers, loaded_modules = load_modules(modulesdir) + log = init_logger(level=args.d) + if args.s: + log.info('Launch MISP modules server from package.') + load_package_helpers() + mhandlers, loaded_modules = load_package_modules() + else: + mhandlers, loaded_modules = _launch_from_current_dir() + + for module in args.m: + mispmod = importlib.import_module(module) + mispmod.register(mhandlers, loaded_modules) - for module in args.m: - mispmod = importlib.import_module(module) - mispmod.register(mhandlers, loaded_modules) - service = [(r'/modules', ListModules), (r'/query', QueryModule)] application = tornado.web.Application(service) - application.listen(port, address=listen) + try: + application.listen(port, address=listen) + except Exception as e: + if e.errno == 98: + pids = psutil.pids() + for pid in pids: + p = psutil.Process(pid) + if p.name() == "misp-modules": + print("\n\n\n") + print(e) + print("\nmisp-modules is still running as PID: {}\n".format(pid)) + print("Please kill accordingly:") + print("sudo kill {}".format(pid)) + sys.exit(-1) + print(e) + print("misp-modules might still be running.") + log.info('MISP modules server started on {0} port {1}'.format(listen, port)) if args.t: log.info('MISP modules started in test-mode, quitting immediately.') sys.exit() - IOLoop.instance().start() - IOLoop.instance().stop() + try: + IOLoop.instance().start() + finally: + IOLoop.instance().stop() + return 0 diff --git a/misp_modules/helpers/cache.py b/misp_modules/helpers/cache.py index 7d70159b..f833b8e1 100644 --- a/misp_modules/helpers/cache.py +++ b/misp_modules/helpers/cache.py @@ -19,32 +19,34 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . +import os + import redis import hashlib -port = 6379 -hostname = '127.0.0.1' -db = 5 +port = int(os.getenv("REDIS_PORT")) if os.getenv("REDIS_PORT") else 6379 +hostname = os.getenv("REDIS_BACKEND") or '127.0.0.1' +db = int(os.getenv("REDIS_DATABASE")) if os.getenv("REDIS_DATABASE") else 0 def selftest(enable=True): if not enable: return False - r = redis.StrictRedis(host=hostname, port=port, db=db) + r = redis.Redis(host=hostname, port=port, db=db) try: r.ping() - except: + except Exception: return 'Redis not running or not installed. Helper will be disabled.' def get(modulename=None, query=None, value=None, debug=False): if (modulename is None or query is None): return False - r = redis.StrictRedis(host=hostname, port=port, db=db) + r = redis.Redis(host=hostname, port=port, db=db, decode_responses=True) h = hashlib.sha1() h.update(query.encode('UTF-8')) hv = h.hexdigest() - key = "m:" + modulename + ":" + hv + key = "m:{}:{}".format(modulename, hv) if not r.exists(key): if debug: @@ -58,10 +60,11 @@ def get(modulename=None, query=None, value=None, debug=False): def flush(): - r = redis.StrictRedis(host=hostname, port=port, db=db) + r = redis.StrictRedis(host=hostname, port=port, db=db, decode_responses=True) returncode = r.flushdb() return returncode + if __name__ == "__main__": import sys if selftest() is not None: @@ -69,7 +72,7 @@ if __name__ == "__main__": else: print("Selftest ok") v = get(modulename="testmodule", query="abcdef", value="barfoo", debug=True) - if v == b'barfoo': + if v == 'barfoo': print("Cache ok") v = get(modulename="testmodule", query="abcdef") print(v) diff --git a/misp_modules/modules/__init__.py b/misp_modules/modules/__init__.py index 65ce6b20..47ddcbf4 100644 --- a/misp_modules/modules/__init__.py +++ b/misp_modules/modules/__init__.py @@ -1,3 +1,3 @@ -from .expansion import * -from .import_mod import * -from .export_mod import * +from .expansion import * # noqa +from .import_mod import * # noqa +from .export_mod import * # noqa diff --git a/misp_modules/modules/expansion/__init__.py b/misp_modules/modules/expansion/__init__.py index e40e844b..70aca683 100644 --- a/misp_modules/modules/expansion/__init__.py +++ b/misp_modules/modules/expansion/__init__.py @@ -1,6 +1,13 @@ -from . import _vmray +from . import _vmray # noqa -__all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl', - 'countrycode', 'cve', 'dns', 'domaintools', 'eupi', 'farsight_passivedns', 'ipasn', 'passivetotal', 'sourcecache', - 'virustotal', 'whois', 'shodan', 'reversedns', 'geoip_country', 'wiki', 'iprep', 'threatminer', 'otx', - 'threatcrowd', 'vulndb', 'crowdstrike_falcon','yara_syntax_validator'] +__all__ = ['cuckoo_submit', 'vmray_submit', 'bgpranking', 'circl_passivedns', 'circl_passivessl', + 'countrycode', 'cve', 'dns', 'btc_steroids', 'domaintools', 'eupi', + 'farsight_passivedns', 'ipasn', 'passivetotal', 'sourcecache', 'virustotal', + 'whois', 'shodan', 'reversedns', 'geoip_country', 'wiki', 'iprep', + 'threatminer', 'otx', 'threatcrowd', 'vulndb', 'crowdstrike_falcon', + 'yara_syntax_validator', 'hashdd', 'onyphe', 'onyphe_full', 'rbl', + 'xforceexchange', 'sigma_syntax_validator', 'stix2_pattern_syntax_validator', + 'sigma_queries', 'dbl_spamhaus', 'vulners', 'yara_query', 'macaddress_io', + 'intel471', 'backscatter_io', 'btc_scam_check', 'hibp', 'greynoise', 'macvendors', + 'qrcode', 'ocr-enrich', 'pdf-enrich', 'docx-enrich', 'xlsx-enrich', 'pptx-enrich', + 'ods-enrich', 'odt-enrich'] diff --git a/misp_modules/modules/expansion/_dnsdb_query/dnsdb_query.py b/misp_modules/modules/expansion/_dnsdb_query/dnsdb_query.py index 0ab58e84..af3f2044 100755 --- a/misp_modules/modules/expansion/_dnsdb_query/dnsdb_query.py +++ b/misp_modules/modules/expansion/_dnsdb_query/dnsdb_query.py @@ -47,9 +47,11 @@ options = None locale.setlocale(locale.LC_ALL, '') + class QueryError(Exception): pass + class DnsdbClient(object): def __init__(self, server, apikey, limit=None, http_proxy=None, https_proxy=None): self.server = server @@ -81,7 +83,6 @@ class DnsdbClient(object): return self._query(path, before, after) def _query(self, path, before=None, after=None): - res = [] url = '%s/lookup/%s' % (self.server, path) params = {} @@ -120,12 +121,15 @@ class DnsdbClient(object): except (HTTPError, URLError) as e: raise QueryError(str(e), sys.exc_traceback) + def quote(path): return urllib_quote(path, safe='') + def sec_to_text(ts): return time.strftime('%Y-%m-%d %H:%M:%S -0000', time.gmtime(ts)) + def rrset_to_text(m): s = StringIO() @@ -155,9 +159,11 @@ def rrset_to_text(m): finally: s.close() + def rdata_to_text(m): return '%s IN %s %s' % (m['rrname'], m['rrtype'], m['rdata']) + def parse_config(cfg_files): config = {} @@ -172,6 +178,7 @@ def parse_config(cfg_files): return config + def time_parse(s): try: epoch = int(s) @@ -193,14 +200,15 @@ def time_parse(s): m = re.match(r'^(?=\d)(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?$', s, re.I) if m: - return -1*(int(m.group(1) or 0)*604800 + - int(m.group(2) or 0)*86400+ - int(m.group(3) or 0)*3600+ - int(m.group(4) or 0)*60+ - int(m.group(5) or 0)) + return -1 * (int(m.group(1) or 0) * 604800 + + int(m.group(2) or 0) * 86400 + + int(m.group(3) or 0) * 3600 + + int(m.group(4) or 0) * 60 + + int(m.group(5) or 0)) raise ValueError('Invalid time: "%s"' % s) + def epipe_wrapper(func): def f(*args, **kwargs): try: @@ -211,31 +219,23 @@ def epipe_wrapper(func): raise return f + @epipe_wrapper def main(): global cfg global options parser = optparse.OptionParser(epilog='Time formats are: "%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%d" (UNIX timestamp), "-%d" (Relative time in seconds), BIND format (e.g. 1w1h, (w)eek, (d)ay, (h)our, (m)inute, (s)econd)') - parser.add_option('-c', '--config', dest='config', - help='config file', action='append') - parser.add_option('-r', '--rrset', dest='rrset', type='string', - help='rrset [/[/BAILIWICK]]') - parser.add_option('-n', '--rdataname', dest='rdata_name', type='string', - help='rdata name [/]') - parser.add_option('-i', '--rdataip', dest='rdata_ip', type='string', - help='rdata ip ') - parser.add_option('-t', '--rrtype', dest='rrtype', type='string', - help='rrset or rdata rrtype') - parser.add_option('-b', '--bailiwick', dest='bailiwick', type='string', - help='rrset bailiwick') + parser.add_option('-c', '--config', dest='config', help='config file', action='append') + parser.add_option('-r', '--rrset', dest='rrset', type='string', help='rrset [/[/BAILIWICK]]') + parser.add_option('-n', '--rdataname', dest='rdata_name', type='string', help='rdata name [/]') + parser.add_option('-i', '--rdataip', dest='rdata_ip', type='string', help='rdata ip ') + parser.add_option('-t', '--rrtype', dest='rrtype', type='string', help='rrset or rdata rrtype') + parser.add_option('-b', '--bailiwick', dest='bailiwick', type='string', help='rrset bailiwick') parser.add_option('-s', '--sort', dest='sort', type='string', help='sort key') - parser.add_option('-R', '--reverse', dest='reverse', action='store_true', default=False, - help='reverse sort') - parser.add_option('-j', '--json', dest='json', action='store_true', default=False, - help='output in JSON format') - parser.add_option('-l', '--limit', dest='limit', type='int', default=0, - help='limit number of results') + parser.add_option('-R', '--reverse', dest='reverse', action='store_true', default=False, help='reverse sort') + parser.add_option('-j', '--json', dest='json', action='store_true', default=False, help='output in JSON format') + parser.add_option('-l', '--limit', dest='limit', type='int', default=0, help='limit number of results') parser.add_option('', '--before', dest='before', type='string', help='only output results seen before this time') parser.add_option('', '--after', dest='after', type='string', help='only output results seen after this time') @@ -263,20 +263,20 @@ def main(): print(str(e), file=sys.stderr) sys.exit(1) - if not 'DNSDB_SERVER' in cfg: + if 'DNSDB_SERVER' not in cfg: cfg['DNSDB_SERVER'] = DEFAULT_DNSDB_SERVER - if not 'HTTP_PROXY' in cfg: + if 'HTTP_PROXY' not in cfg: cfg['HTTP_PROXY'] = DEFAULT_HTTP_PROXY - if not 'HTTPS_PROXY' in cfg: + if 'HTTPS_PROXY' not in cfg: cfg['HTTPS_PROXY'] = DEFAULT_HTTPS_PROXY - if not 'APIKEY' in cfg: + if 'APIKEY' not in cfg: sys.stderr.write('dnsdb_query: APIKEY not defined in config file\n') sys.exit(1) client = DnsdbClient(cfg['DNSDB_SERVER'], cfg['APIKEY'], - limit=options.limit, - http_proxy=cfg['HTTP_PROXY'], - https_proxy=cfg['HTTPS_PROXY']) + limit=options.limit, + http_proxy=cfg['HTTP_PROXY'], + https_proxy=cfg['HTTPS_PROXY']) if options.rrset: if options.rrtype or options.bailiwick: qargs = (options.rrset, options.rrtype, options.bailiwick) @@ -307,7 +307,7 @@ def main(): if options.sort: results = list(results) if len(results) > 0: - if not options.sort in results[0]: + if options.sort not in results[0]: sort_keys = results[0].keys() sort_keys.sort() sys.stderr.write('dnsdb_query: invalid sort key "%s". valid sort keys are %s\n' % (options.sort, ', '.join(sort_keys))) @@ -319,5 +319,6 @@ def main(): print(e.message, file=sys.stderr) sys.exit(1) + if __name__ == '__main__': main() diff --git a/misp_modules/modules/expansion/backscatter_io.py b/misp_modules/modules/expansion/backscatter_io.py new file mode 100644 index 00000000..07969176 --- /dev/null +++ b/misp_modules/modules/expansion/backscatter_io.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- +"""Backscatter.io Module.""" +import json +try: + from backscatter import Backscatter +except ImportError: + print("Backscatter.io library not installed.") + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['ip-src', 'ip-dst'], 'output': ['freetext']} +moduleinfo = {'version': '1', 'author': 'brandon@backscatter.io', + 'description': 'Backscatter.io module to bring mass-scanning observations into MISP.', + 'module-type': ['expansion', 'hover']} +moduleconfig = ['api_key'] +query_playbook = [ + {'inputs': ['ip-src', 'ip-dst'], + 'services': ['observations', 'enrichment'], + 'name': 'generic'} +] + + +def check_query(request): + """Check the incoming request for a valid configuration.""" + output = {'success': False} + config = request.get('config', None) + if not config: + misperrors['error'] = "Configuration is missing from the request." + return output + for item in moduleconfig: + if config.get(item, None): + continue + misperrors['error'] = "Backscatter.io authentication is missing." + return output + if not request.get('ip-src') and request.get('ip-dst'): + misperrors['error'] = "Unsupported attributes type." + return output + profile = {'success': True, 'config': config, 'playbook': 'generic'} + if 'ip-src' in request: + profile.update({'value': request.get('ip-src')}) + else: + profile.update({'value': request.get('ip-dst')}) + return profile + + +def handler(q=False): + """Handle gathering data.""" + if not q: + return q + request = json.loads(q) + checks = check_query(request) + if not checks['success']: + return misperrors + + try: + bs = Backscatter(checks['config']['api_key']) + response = bs.get_observations(query=checks['value'], query_type='ip') + if not response['success']: + misperrors['error'] = '%s: %s' % (response['error'], response['message']) + return misperrors + output = {'results': [{'types': mispattributes['output'], 'values': [str(response)]}]} + except Exception as e: + misperrors['error'] = str(e) + return misperrors + + return output + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/asn_history.py b/misp_modules/modules/expansion/bgpranking.py similarity index 50% rename from misp_modules/modules/expansion/asn_history.py rename to misp_modules/modules/expansion/bgpranking.py index 9775f6d3..b01088d7 100755 --- a/misp_modules/modules/expansion/asn_history.py +++ b/misp_modules/modules/expansion/bgpranking.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- import json -from asnhistory import ASNHistory +from datetime import date, timedelta +from pybgpranking import BGPRanking misperrors = {'error': 'Error'} mispattributes = {'input': ['AS'], 'output': ['freetext']} @@ -9,8 +10,6 @@ moduleinfo = {'version': '0.1', 'author': 'Raphaël Vinot', 'description': 'Query an ASN Description history service (https://github.com/CIRCL/ASN-Description-History.git)', 'module-type': ['expansion', 'hover']} -moduleconfig = ['host', 'port', 'db'] - def handler(q=False): if q is False: @@ -22,19 +21,11 @@ def handler(q=False): misperrors['error'] = "Unsupported attributes type" return misperrors - if not request.get('config') and not (request['config'].get('host') and - request['config'].get('port') and - request['config'].get('db')): - misperrors['error'] = 'ASN description history configuration is missing' - return misperrors - - asnhistory = ASNHistory(host=request['config'].get('host'), - port=request['config'].get('port'), db=request['config'].get('db')) - - values = ['{} {}'.format(date.isoformat(), description) for date, description in asnhistory.get_all_descriptions(toquery)] + bgpranking = BGPRanking() + values = bgpranking.query(toquery, date=(date.today() - timedelta(1)).isoformat()) if not values: - misperrors['error'] = 'Unable to find descriptions for this ASN' + misperrors['error'] = 'Unable to find the ASN in BGP Ranking' return misperrors return {'results': [{'types': mispattributes['output'], 'values': values}]} @@ -44,5 +35,4 @@ def introspection(): def version(): - moduleinfo['config'] = moduleconfig return moduleinfo diff --git a/misp_modules/modules/expansion/btc_scam_check.py b/misp_modules/modules/expansion/btc_scam_check.py new file mode 100644 index 00000000..f5519265 --- /dev/null +++ b/misp_modules/modules/expansion/btc_scam_check.py @@ -0,0 +1,44 @@ +import json +import sys + +try: + from dns.resolver import Resolver, NXDOMAIN + from dns.name import LabelTooLong + resolver = Resolver() + resolver.timeout = 1 + resolver.lifetime = 1 +except ImportError: + sys.exit("dnspython3 in missing. use 'pip install dnspython3' to install it.") + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['btc'], 'output': ['text']} +moduleinfo = {'version': '0.1', 'author': 'Christian Studer', + 'description': 'Checks if a BTC address has been abused.', + 'module-type': ['hover']} +moduleconfig = [] + +url = 'bl.btcblack.it' + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + btc = request['btc'] + query = f"{btc}.{url}" + try: + result = ' - '.join([str(r) for r in resolver.query(query, 'TXT')])[1:-1] + except NXDOMAIN: + result = f"{btc} is not known as a scam address." + except LabelTooLong: + result = f"{btc} is probably not a valid BTC address." + return {'results': [{'types': mispattributes['output'], 'values': result}]} + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/btc_steroids.py b/misp_modules/modules/expansion/btc_steroids.py new file mode 100755 index 00000000..04b71383 --- /dev/null +++ b/misp_modules/modules/expansion/btc_steroids.py @@ -0,0 +1,229 @@ +import json +import requests +import time + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['btc'], 'output': ['text']} +moduleinfo = {'version': '0.1', 'author': 'Sascha Rommelfangen', + 'description': 'BTC expansion service to \ + get quick information from MISP attributes', + 'module-type': ['hover']} + +moduleconfig = [] + +blockchain_firstseen = 'https://blockchain.info/q/addressfirstseen/' +blockchain_balance = 'https://blockchain.info/q/addressbalance/' +blockchain_totalreceived = 'https://blockchain.info/q/getreceivedbyaddress/' +blockchain_all = 'https://blockchain.info/rawaddr/{}?filter=5{}' +converter = 'https://min-api.cryptocompare.com/data/pricehistorical?fsym=BTC&tsyms=USD,EUR&ts={}' +converter_rls = 'https://min-api.cryptocompare.com/stats/rate/limit' +result_text = "" +g_rate_limit = 300 +start_time = 0 +conversion_rates = {} + + +def get_consumption(output=False): + try: + req = requests.get(converter_rls) + jreq = req.json() + minute = str(jreq['Data']['calls_left']['minute']) + hour = str(jreq['Data']['calls_left']['hour']) + except Exception: + minute = str(-1) + hour = str(-1) + # Debug out for the console + print("Calls left this minute / hour: " + minute + " / " + hour) + return minute, hour + + +def convert(btc, timestamp): + global g_rate_limit + global start_time + global now + global conversion_rates + date = time.strftime('%Y-%m-%d', time.localtime(timestamp)) + # Lookup conversion rates in the cache: + if date in conversion_rates: + (usd, eur) = conversion_rates[date] + else: + # If not cached, we have to get the converion rates + # We have to be careful with rate limiting on the server side + if g_rate_limit == 300: + minute, hour = get_consumption() + g_rate_limit -= 1 + now = time.time() + # delta = now - start_time + # print(g_rate_limit) + if g_rate_limit <= 10: + minute, hour = get_consumption(output=True) + if int(minute) <= 10: + # print(minute) + # get_consumption(output=True) + time.sleep(3) + else: + mprint(minute) + start_time = time.time() + g_rate_limit = int(minute) + try: + req = requests.get(converter.format(timestamp)) + jreq = req.json() + usd = jreq['BTC']['USD'] + eur = jreq['BTC']['EUR'] + # Since we have the rates, store them in the cache + conversion_rates[date] = (usd, eur) + except Exception as ex: + mprint(ex) + get_consumption(output=True) + # Actually convert and return the values + u = usd * btc + e = eur * btc + return u, e + + +def mprint(input): + # Prepare the final print + global result_text + result_text = result_text + "\n" + str(input) + + +def handler(q=False): + global result_text + global conversion_rates + result_text = "" + # start_time = time.time() + # now = time.time() + if q is False: + return False + request = json.loads(q) + click = False + # This means the magnifying glass has been clicked + if request.get('persistent') == 1: + click = True + # Otherwise the attribute was only hovered over + if request.get('btc'): + btc = request['btc'] + else: + return False + mprint("\nAddress:\t" + btc) + try: + req = requests.get(blockchain_all.format(btc, "&limit=50")) + jreq = req.json() + except Exception: + # print(e) + print(req.text) + result_text = "Not a valid BTC address" + r = { + 'results': [ + { + 'types': ['text'], + 'values':[ + str(result_text) + ] + } + ] + } + return r + + n_tx = jreq['n_tx'] + balance = float(jreq['final_balance'] / 100000000) + rcvd = float(jreq['total_received'] / 100000000) + sent = float(jreq['total_sent'] / 100000000) + output = 'Balance:\t{0:.10f} BTC (+{1:.10f} BTC / -{2:.10f} BTC)' + mprint(output.format(balance, rcvd, sent)) + if click is False: + mprint("Transactions:\t" + str(n_tx) + "\t (previewing up to 5 most recent)") + else: + mprint("Transactions:\t" + str(n_tx)) + if n_tx > 0: + mprint("======================================================================================") + i = 0 + while i < n_tx: + if click is False: + try: + req = requests.get(blockchain_all.format(btc, "&limit=5&offset={}".format(i))) + except Exception as e: + # Lazy retry - cries for a function + print(e) + time.sleep(3) + req = requests.get(blockchain_all.format(btc, "&limit=5&offset={}".format(i))) + if n_tx > 5: + n_tx = 5 + else: + try: + req = requests.get(blockchain_all.format(btc, "&limit=50&offset={}".format(i))) + except Exception as e: + # Lazy retry - cries for a function + print(e) + time.sleep(3) + req = requests.get(blockchain_all.format(btc, "&limit=50&offset={}".format(i))) + jreq = req.json() + if jreq['txs']: + for transactions in jreq['txs']: + sum = 0 + sum_counter = 0 + for tx in transactions['inputs']: + script_old = tx['script'] + try: + addr_in = tx['prev_out']['addr'] + except KeyError: + addr_in = None + try: + prev_out = tx['prev_out']['value'] + except KeyError: + prev_out = None + if prev_out != 0 and addr_in == btc: + datetime = time.strftime("%d %b %Y %H:%M:%S %Z", time.localtime(int(transactions['time']))) + value = float(tx['prev_out']['value'] / 100000000) + u, e = convert(value, transactions['time']) + mprint("#" + str(n_tx - i) + "\t" + str(datetime) + "\t-{0:10.8f} BTC {1:10.2f} USD\t{2:10.2f} EUR".format(value, u, e).rstrip('0')) + if script_old != tx['script']: + i += 1 + else: + sum_counter += 1 + sum += value + if sum_counter > 1: + u, e = convert(sum, transactions['time']) + mprint("\t\t\t\t\t----------------------------------------------") + mprint("#" + str(n_tx - i) + "\t\t\t\t Sum:\t-{0:10.8f} BTC {1:10.2f} USD\t{2:10.2f} EUR\n".format(sum, u, e).rstrip('0')) + for tx in transactions['out']: + try: + addr_out = tx['addr'] + except KeyError: + addr_out = None + try: + prev_out = tx['prev_out']['value'] + except KeyError: + prev_out = None + if prev_out != 0 and addr_out == btc: + datetime = time.strftime("%d %b %Y %H:%M:%S %Z", time.localtime(int(transactions['time']))) + value = float(tx['value'] / 100000000) + u, e = convert(value, transactions['time']) + mprint("#" + str(n_tx - i) + "\t" + str(datetime) + "\t {0:10.8f} BTC {1:10.2f} USD\t{2:10.2f} EUR".format(value, u, e).rstrip('0')) + # i += 1 + i += 1 + + r = { + 'results': [ + { + 'types': ['text'], + 'values':[ + str(result_text) + ] + } + ] + } + # Debug output on the console + print(result_text) + # Unset the result for the next request + result_text = "" + return r + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/circl_passivedns.py b/misp_modules/modules/expansion/circl_passivedns.py index 3da5bacf..263b92ab 100755 --- a/misp_modules/modules/expansion/circl_passivedns.py +++ b/misp_modules/modules/expansion/circl_passivedns.py @@ -32,7 +32,7 @@ def handler(q=False): res = x.query(toquery) out = '' for v in res: - out = out + "{} ".format(v['rdata']) + out = out + "{} ".format(v['rdata']) r = {'results': [{'types': mispattributes['output'], 'values': out}]} return r diff --git a/misp_modules/modules/expansion/countrycode.py b/misp_modules/modules/expansion/countrycode.py index af58fc66..64c09509 100755 --- a/misp_modules/modules/expansion/countrycode.py +++ b/misp_modules/modules/expansion/countrycode.py @@ -12,40 +12,43 @@ moduleinfo = {'version': '1', 'author': 'Hannah Ward', # config fields that your code expects from the site admin moduleconfig = [] -common_tlds = {"com":"Commercial (Worldwide)", - "org":"Organisation (Worldwide)", - "net":"Network (Worldwide)", - "int":"International (Worldwide)", - "edu":"Education (Usually USA)", - "gov":"Government (USA)" - } +common_tlds = {"com": "Commercial (Worldwide)", + "org": "Organisation (Worldwide)", + "net": "Network (Worldwide)", + "int": "International (Worldwide)", + "edu": "Education (Usually USA)", + "gov": "Government (USA)" + } + +codes = False -codes = requests.get("http://www.geognos.com/api/en/countries/info/all.json").json() def handler(q=False): global codes + if not codes: + codes = requests.get("http://www.geognos.com/api/en/countries/info/all.json").json() if q is False: return False request = json.loads(q) - domain = request["domain"] + domain = request["domain"] if "domain" in request else request["hostname"] # Get the extension ext = domain.split(".")[-1] - # Check if if's a common, non country one + # Check if it's a common, non country one if ext in common_tlds.keys(): - val = common_tlds[ext] + val = common_tlds[ext] else: - # Retrieve a json full of country info - if not codes["StatusMsg"] == "OK": - val = "Unknown" - else: - # Find our code based on TLD - codes = codes["Results"] - for code in codes.keys(): - if codes[code]["CountryCodes"]["tld"] == ext: - val = codes[code]["Name"] - r = {'results': [{'types':['text'], 'values':[val]}]} + # Retrieve a json full of country info + if not codes["StatusMsg"] == "OK": + val = "Unknown" + else: + # Find our code based on TLD + codes = codes["Results"] + for code in codes.keys(): + if codes[code]["CountryCodes"]["tld"] == ext: + val = codes[code]["Name"] + r = {'results': [{'types': ['text'], 'values':[val]}]} return r @@ -56,4 +59,3 @@ def introspection(): def version(): moduleinfo['config'] = moduleconfig return moduleinfo - diff --git a/misp_modules/modules/expansion/cuckoo_submit.py b/misp_modules/modules/expansion/cuckoo_submit.py new file mode 100644 index 00000000..c1ded90c --- /dev/null +++ b/misp_modules/modules/expansion/cuckoo_submit.py @@ -0,0 +1,153 @@ +import base64 +import io +import json +import logging +import requests +import sys +import urllib.parse +import zipfile + +from requests.exceptions import RequestException + +log = logging.getLogger("cuckoo_submit") +log.setLevel(logging.DEBUG) +sh = logging.StreamHandler(sys.stdout) +sh.setLevel(logging.DEBUG) +fmt = logging.Formatter( + "%(asctime)s - %(name)s - %(levelname)s - %(message)s" +) +sh.setFormatter(fmt) +log.addHandler(sh) + +moduleinfo = { + "version": "0.1", "author": "Evert Kors", + "description": "Submit files and URLs to Cuckoo Sandbox", + "module-type": ["expansion", "hover"] +} +misperrors = {"error": "Error"} +moduleconfig = ["api_url", "api_key"] +mispattributes = { + "input": ["attachment", "malware-sample", "url", "domain"], + "output": ["text"] +} + + +class APIKeyError(RequestException): + """Raised if the Cuckoo API returns a 401. This means no or an invalid + bearer token was supplied.""" + pass + + +class CuckooAPI(object): + + def __init__(self, api_url, api_key=""): + self.api_key = api_key + if not api_url.startswith("http"): + api_url = "https://{}".format(api_url) + + self.api_url = api_url + + def _post_api(self, endpoint, files=None, data={}): + data.update({ + "owner": "MISP" + }) + + try: + response = requests.post( + urllib.parse.urljoin(self.api_url, endpoint), + files=files, data=data, + headers={"Authorization": "Bearer {}".format(self.api_key)} + ) + except RequestException as e: + log.error("Failed to submit sample to Cuckoo Sandbox. %s", e) + return None + + if response.status_code == 401: + raise APIKeyError("Invalid or no Cuckoo Sandbox API key provided") + + if response.status_code != 200: + log.error("Invalid Cuckoo API response") + return None + + return response.json() + + def create_task(self, filename, fp): + response = self._post_api( + "/tasks/create/file", files={"file": (filename, fp)} + ) + if not response: + return False + + return response["task_id"] + + def create_url(self, url): + response = self._post_api( + "/tasks/create/url", data={"url": url} + ) + if not response: + return False + + return response["task_id"] + + +def handler(q=False): + if q is False: + return False + + request = json.loads(q) + + # See if the API URL was provided. The API key is optional, as it can + # be disabled in the Cuckoo API settings. + api_url = request["config"].get("api_url") + api_key = request["config"].get("api_key", "") + if not api_url: + misperrors["error"] = "No Cuckoo API URL provided" + return misperrors + + url = request.get("url") or request.get("domain") + data = request.get("data") + filename = None + if data: + data = base64.b64decode(data) + + if "malware-sample" in request: + filename = request.get("malware-sample").split("|", 1)[0] + with zipfile.ZipFile(io.BytesIO(data)) as zipf: + data = zipf.read(zipf.namelist()[0], pwd=b"infected") + + elif "attachment" in request: + filename = request.get("attachment") + + cuckoo_api = CuckooAPI(api_url=api_url, api_key=api_key) + task_id = None + try: + if url: + log.debug("Submitting URL to Cuckoo Sandbox %s", api_url) + task_id = cuckoo_api.create_url(url) + elif data and filename: + log.debug("Submitting file to Cuckoo Sandbox %s", api_url) + task_id = cuckoo_api.create_task( + filename=filename, fp=io.BytesIO(data) + ) + except APIKeyError as e: + misperrors["error"] = "Failed to submit to Cuckoo: {}".format(e) + return misperrors + + if not task_id: + misperrors["error"] = "File or URL submission failed" + return misperrors + + return { + "results": [ + {"types": "text", "values": "Cuckoo task id: {}".format(task_id)} + ] + } + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo["config"] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/dbl_spamhaus.py b/misp_modules/modules/expansion/dbl_spamhaus.py new file mode 100644 index 00000000..529815ba --- /dev/null +++ b/misp_modules/modules/expansion/dbl_spamhaus.py @@ -0,0 +1,63 @@ +import json +import sys + +try: + import dns.resolver + resolver = dns.resolver.Resolver() + resolver.timeout = 0.2 + resolver.lifetime = 0.2 +except ImportError: + print("dnspython3 is missing, use 'pip install dnspython3' to install it.") + sys.exit(0) + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['domain', 'domain|ip', 'hostname', 'hostname|port'], 'output': ['text']} +moduleinfo = {'version': '0.1', 'author': 'Christian Studer', + 'description': 'Checks Spamhaus DBL for a domain name.', + 'module-type': ['expansion', 'hover']} +moduleconfig = [] + +dbl = 'dbl.spamhaus.org' +dbl_mapping = {'127.0.1.2': 'spam domain', + '127.0.1.4': 'phish domain', + '127.0.1.5': 'malware domain', + '127.0.1.6': 'botnet C&C domain', + '127.0.1.102': 'abused legit spam', + '127.0.1.103': 'abused spammed redirector domain', + '127.0.1.104': 'abused legit phish', + '127.0.1.105': 'abused legit malware', + '127.0.1.106': 'abused legit botnet C&C', + '127.0.1.255': 'IP queries prohibited!'} + + +def fetch_requested_value(request): + for attribute_type in mispattributes['input']: + if request.get(attribute_type): + return request[attribute_type].split('|')[0] + return None + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + requested_value = fetch_requested_value(request) + if requested_value is None: + misperrors['error'] = "Unsupported attributes type" + return misperrors + query = "{}.{}".format(requested_value, dbl) + try: + query_result = resolver.query(query, 'A')[0] + result = "{} - {}".format(requested_value, dbl_mapping[str(query_result)]) + except Exception as e: + result = str(e) + return {'results': [{'types': mispattributes.get('output'), 'values': result}]} + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/dns.py b/misp_modules/modules/expansion/dns.py index 41da8b21..c5af9d6a 100755 --- a/misp_modules/modules/expansion/dns.py +++ b/misp_modules/modules/expansion/dns.py @@ -43,7 +43,7 @@ def handler(q=False): except dns.exception.Timeout: misperrors['error'] = "Timeout" return misperrors - except: + except Exception: misperrors['error'] = "DNS resolving error" return misperrors diff --git a/misp_modules/modules/expansion/docx-enrich.py b/misp_modules/modules/expansion/docx-enrich.py new file mode 100644 index 00000000..d5da3f86 --- /dev/null +++ b/misp_modules/modules/expansion/docx-enrich.py @@ -0,0 +1,61 @@ +import json +import binascii +import np +import docx +import io + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['attachment'], + 'output': ['freetext', 'text']} +moduleinfo = {'version': '0.1', 'author': 'Sascha Rommelfangen', + 'description': '.docx to freetext-import IOC extractor', + 'module-type': ['expansion']} + +moduleconfig = [] + + +def handler(q=False): + if q is False: + return False + q = json.loads(q) + filename = q['attachment'] + try: + docx_array = np.frombuffer(binascii.a2b_base64(q['data']), np.uint8) + except Exception as e: + print(e) + err = "Couldn't fetch attachment (JSON 'data' is empty). Are you using the 'Query enrichment' action?" + misperrors['error'] = err + print(err) + return misperrors + + doc_content = "" + doc_file = io.BytesIO(docx_array) + try: + doc = docx.Document(doc_file) + for para in doc.paragraphs: + print(para.text) + doc_content = doc_content + "\n" + para.text + tables = doc.tables + for table in tables: + for row in table.rows: + for cell in row.cells: + for para in cell.paragraphs: + print(para.text) + doc_content = doc_content + "\n" + para.text + print(doc_content) + return {'results': [{'types': ['freetext'], 'values': doc_content, 'comment': ".docx-to-text from file " + filename}, + {'types': ['text'], 'values': doc_content, 'comment': ".docx-to-text from file " + filename}]} + except Exception as e: + print(e) + err = "Couldn't analyze file as .docx. Error was: " + str(e) + misperrors['error'] = err + return misperrors + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/farsight_passivedns.py b/misp_modules/modules/expansion/farsight_passivedns.py index 2518771f..7c1aa27b 100755 --- a/misp_modules/modules/expansion/farsight_passivedns.py +++ b/misp_modules/modules/expansion/farsight_passivedns.py @@ -51,7 +51,7 @@ def lookup_name(client, name): for i in item.get('rdata'): # grab email field and replace first dot by @ to convert to an email address yield(i.split(' ')[1].rstrip('.').replace('.', '@', 1)) - except QueryError as e: + except QueryError: pass try: @@ -59,7 +59,7 @@ def lookup_name(client, name): for item in res: if item.get('rrtype') in ['A', 'AAAA', 'CNAME']: yield(item.get('rrname').rstrip('.')) - except QueryError as e: + except QueryError: pass @@ -68,7 +68,7 @@ def lookup_ip(client, ip): res = client.query_rdata_ip(ip) for item in res: yield(item['rrname'].rstrip('.')) - except QueryError as e: + except QueryError: pass diff --git a/misp_modules/modules/expansion/geoip_country.py b/misp_modules/modules/expansion/geoip_country.py index 31c1b6a3..1709d912 100644 --- a/misp_modules/modules/expansion/geoip_country.py +++ b/misp_modules/modules/expansion/geoip_country.py @@ -27,7 +27,7 @@ try: config.read(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'geoip_country.cfg')) gi = pygeoip.GeoIP(config.get('GEOIP', 'database')) enabled = True -except: +except Exception: enabled = False @@ -49,7 +49,7 @@ def handler(q=False): try: answer = gi.country_code_by_addr(toquery) - except: + except Exception: misperrors['error'] = "GeoIP resolving error" return misperrors diff --git a/misp_modules/modules/expansion/greynoise.py b/misp_modules/modules/expansion/greynoise.py new file mode 100644 index 00000000..d26736d9 --- /dev/null +++ b/misp_modules/modules/expansion/greynoise.py @@ -0,0 +1,43 @@ +import requests +import json + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['ip-dst', 'ip-src'], 'output': ['text']} +moduleinfo = {'version': '0.1', 'author': 'Aurélien Schwab ', 'description': 'Module to access GreyNoise.io API.', 'module-type': ['hover']} +moduleconfig = ['user-agent'] # TODO take this into account in the code + +greynoise_api_url = 'http://api.greynoise.io:8888/v1/query/ip' +default_user_agent = 'MISP-Module' + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + for input_type in mispattributes['input']: + if input_type in request: + ip = request[input_type] + break + else: + misperrors['error'] = "Unsupported attributes type" + return misperrors + data = {'ip': ip} + r = requests.post(greynoise_api_url, data=data, headers={'user-agent': default_user_agent}) # Real request + if r.status_code == 200: # OK (record found) + response = json.loads(r.text) + if response: + return {'results': [{'types': mispattributes['output'], 'values': response}]} + elif r.status_code == 404: # Not found (not an error) + return {'results': [{'types': mispattributes['output'], 'values': 'No data'}]} + else: # Real error + misperrors['error'] = 'GreyNoise API not accessible (HTTP ' + str(r.status_code) + ')' + return misperrors['error'] + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/hashdd.py b/misp_modules/modules/expansion/hashdd.py new file mode 100755 index 00000000..907447f7 --- /dev/null +++ b/misp_modules/modules/expansion/hashdd.py @@ -0,0 +1,45 @@ +import json +import requests + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['md5', 'sha1', 'sha256'], 'output': ['text']} +moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion module to check hashes against hashdd.com including NSLR dataset.', 'module-type': ['hover']} +moduleconfig = [] +hashddapi_url = 'https://api.hashdd.com/' + + +def handler(q=False): + if q is False: + return False + v = None + request = json.loads(q) + for input_type in mispattributes['input']: + if request.get(input_type): + v = request[input_type].upper() + break + if v is None: + misperrors['error'] = 'Hash value is missing.' + return misperrors + r = requests.post(hashddapi_url, data={'hash': v}) + if r.status_code == 200: + state = json.loads(r.text) + if state: + if state.get(v): + summary = state[v]['known_level'] + else: + summary = 'Unknown hash' + else: + misperrors['error'] = '{} API not accessible'.format(hashddapi_url) + return misperrors['error'] + + r = {'results': [{'types': mispattributes['output'], 'values': summary}]} + return r + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/hibp.py b/misp_modules/modules/expansion/hibp.py new file mode 100644 index 00000000..8db3fa74 --- /dev/null +++ b/misp_modules/modules/expansion/hibp.py @@ -0,0 +1,43 @@ +import requests +import json + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['email-dst', 'email-src'], 'output': ['text']} # All mails as input +moduleinfo = {'version': '0.1', 'author': 'Aurélien Schwab', 'description': 'Module to access haveibeenpwned.com API.', 'module-type': ['hover']} +moduleconfig = ['user-agent'] # TODO take this into account in the code + +haveibeenpwned_api_url = 'https://api.haveibeenpwned.com/api/v2/breachedaccount/' +default_user_agent = 'MISP-Module' # User agent (must be set, requiered by API)) + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + for input_type in mispattributes['input']: + if input_type in request: + email = request[input_type] + break + else: + misperrors['error'] = "Unsupported attributes type" + return misperrors + + r = requests.get(haveibeenpwned_api_url + email, headers={'user-agent': default_user_agent}) # Real request + if r.status_code == 200: # OK (record found) + breaches = json.loads(r.text) + if breaches: + return {'results': [{'types': mispattributes['output'], 'values': breaches}]} + elif r.status_code == 404: # Not found (not an error) + return {'results': [{'types': mispattributes['output'], 'values': 'OK (Not Found)'}]} + else: # Real error + misperrors['error'] = 'haveibeenpwned.com API not accessible (HTTP ' + str(r.status_code) + ')' + return misperrors['error'] + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/intel471.py b/misp_modules/modules/expansion/intel471.py new file mode 100755 index 00000000..bf95b2e3 --- /dev/null +++ b/misp_modules/modules/expansion/intel471.py @@ -0,0 +1,61 @@ +import json +from pyintel471 import PyIntel471 + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['hostname', 'domain', 'url', 'ip-src', 'ip-dst', 'email-src', + 'email-dst', 'target-email', 'whois-registrant-email', + 'whois-registrant-name', 'md5', 'sha1', 'sha256'], 'output': ['freetext']} +moduleinfo = {'version': '0.1', 'author': 'Raphaël Vinot', 'description': 'Module to access Intel 471', + 'module-type': ['hover', 'expansion']} +moduleconfig = ['email', 'authkey'] + + +def cleanup(response): + '''The entries have uids that will be recognised as hashes when they shouldn't''' + j = response.json() + if j['iocTotalCount'] == 0: + return 'Nothing has been found.' + for ioc in j['iocs']: + ioc.pop('uid') + if ioc['links']['actorTotalCount'] > 0: + for actor in ioc['links']['actors']: + actor.pop('uid') + if ioc['links']['reportTotalCount'] > 0: + for report in ioc['links']['reports']: + report.pop('uid') + return json.dumps(j, indent=2) + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + for input_type in mispattributes['input']: + if input_type in request: + to_query = request[input_type] + break + else: + misperrors['error'] = "Unsupported attributes type" + return misperrors + + if (request.get('config')): + if (request['config'].get('email') is None) or (request['config'].get('authkey') is None): + misperrors['error'] = 'Intel 471 authentication is missing' + return misperrors + + intel471 = PyIntel471(email=request['config'].get('email'), authkey=request['config'].get('authkey')) + ioc_filters = intel471.iocs_filters(ioc=to_query) + res = intel471.iocs(filters=ioc_filters) + to_return = cleanup(res) + + r = {'results': [{'types': mispattributes['output'], 'values': to_return}]} + return r + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/ipasn.py b/misp_modules/modules/expansion/ipasn.py index 22c9a704..8489aa06 100755 --- a/misp_modules/modules/expansion/ipasn.py +++ b/misp_modules/modules/expansion/ipasn.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- import json -from ipasn_redis import IPASN +from pyipasnhistory import IPASNHistory misperrors = {'error': 'Error'} mispattributes = {'input': ['ip-src', 'ip-dst'], 'output': ['freetext']} @@ -9,8 +9,6 @@ moduleinfo = {'version': '0.1', 'author': 'Raphaël Vinot', 'description': 'Query an IP ASN history service (https://github.com/CIRCL/IP-ASN-history.git)', 'module-type': ['expansion', 'hover']} -moduleconfig = ['host', 'port', 'db'] - def handler(q=False): if q is False: @@ -24,18 +22,8 @@ def handler(q=False): misperrors['error'] = "Unsupported attributes type" return misperrors - if not request.get('config') and not (request['config'].get('host') and - request['config'].get('port') and - request['config'].get('db')): - misperrors['error'] = 'IP ASN history configuration is missing' - return misperrors - - ipasn = IPASN(host=request['config'].get('host'), - port=request['config'].get('port'), db=request['config'].get('db')) - - values = [] - for first_seen, last_seen, asn, block in ipasn.aggregate_history(toquery): - values.append('{} {} {} {}'.format(first_seen.decode(), last_seen.decode(), asn.decode(), block)) + ipasn = IPASNHistory() + values = ipasn.query(toquery) if not values: misperrors['error'] = 'Unable to find the history of this IP' @@ -48,5 +36,4 @@ def introspection(): def version(): - moduleinfo['config'] = moduleconfig return moduleinfo diff --git a/misp_modules/modules/expansion/iprep.py b/misp_modules/modules/expansion/iprep.py index 60730523..558dbdd7 100755 --- a/misp_modules/modules/expansion/iprep.py +++ b/misp_modules/modules/expansion/iprep.py @@ -45,7 +45,7 @@ def parse_iprep(ip, api): url = 'https://www.packetmail.net/iprep.php/%s' % ip try: data = requests.get(url, params={'apikey': api}).json() - except: + except Exception: return ['Error pulling data'], rep # print '%s' % data for name, val in data.items(): @@ -71,11 +71,11 @@ def parse_iprep(ip, api): misp_val = context full_text += '\n%s' % context misp_comment = 'IPRep Source %s: %s' % (name, val['last_seen']) - rep.append({'types': mispattributes['output'], 'categories':['External analysis'], 'values': misp_val, 'comment': misp_comment}) - except: + rep.append({'types': mispattributes['output'], 'categories': ['External analysis'], 'values': misp_val, 'comment': misp_comment}) + except Exception: err.append('Error parsing source: %s' % name) - rep.append({'types': ['freetext'], 'values': full_text , 'comment': 'Free text import of IPRep'}) + rep.append({'types': ['freetext'], 'values': full_text, 'comment': 'Free text import of IPRep'}) return err, rep diff --git a/misp_modules/modules/expansion/macaddress_io.py b/misp_modules/modules/expansion/macaddress_io.py new file mode 100644 index 00000000..e72fa1e1 --- /dev/null +++ b/misp_modules/modules/expansion/macaddress_io.py @@ -0,0 +1,124 @@ +import json + +from maclookup import ApiClient, exceptions + +misperrors = { + 'error': 'Error' +} + +mispattributes = { + 'input': ['mac-address'], +} + +moduleinfo = { + 'version': '1.0', + 'author': 'CodeLine OY - macaddress.io', + 'description': 'MISP hover module for macaddress.io', + 'module-type': ['hover'] +} + +moduleconfig = ['api_key'] + + +def handler(q=False): + if q is False: + return False + + request = json.loads(q) + + if request.get('mac-address'): + mac_address = request['mac-address'] + else: + return False + + if request['config'].get('api_key'): + api_key = request['config'].get('api_key') + + else: + misperrors['error'] = 'Authorization required' + return misperrors + + api_client = ApiClient(api_key) + + try: + response = api_client.get(mac_address) + + except exceptions.EmptyResponseException: + misperrors['error'] = 'Empty response' + return misperrors + + except exceptions.UnparsableResponseException: + misperrors['error'] = 'Unparsable response' + return misperrors + + except exceptions.ServerErrorException: + misperrors['error'] = 'Internal server error' + return misperrors + + except exceptions.UnknownOutputFormatException: + misperrors['error'] = 'Unknown output' + return misperrors + + except exceptions.AuthorizationRequiredException: + misperrors['error'] = 'Authorization required' + return misperrors + + except exceptions.AccessDeniedException: + misperrors['error'] = 'Access denied' + return misperrors + + except exceptions.InvalidMacOrOuiException: + misperrors['error'] = 'Invalid MAC or OUI' + return misperrors + + except exceptions.NotEnoughCreditsException: + misperrors['error'] = 'Not enough credits' + return misperrors + + except Exception: + misperrors['error'] = 'Unknown error' + return misperrors + + date_created = \ + response.block_details.date_created.strftime('%d %B %Y') if response.block_details.date_created else None + + date_updated = \ + response.block_details.date_updated.strftime('%d %B %Y') if response.block_details.date_updated else None + + results = { + 'results': + [{'types': ['text'], 'values': + { + # Mac address details + 'Valid MAC address': "True" if response.mac_address_details.is_valid else "False", + 'Transmission type': response.mac_address_details.transmission_type, + 'Administration type': response.mac_address_details.administration_type, + + # Vendor details + 'OUI': response.vendor_details.oui, + 'Vendor details are hidden': "True" if response.vendor_details.is_private else "False", + 'Company name': response.vendor_details.company_name, + 'Company\'s address': response.vendor_details.company_address, + 'County code': response.vendor_details.country_code, + + # Block details + 'Block found': "True" if response.block_details.block_found else "False", + 'The left border of the range': response.block_details.border_left, + 'The right border of the range': response.block_details.border_right, + 'The total number of MAC addresses in this range': response.block_details.block_size, + 'Assignment block size': response.block_details.assignment_block_size, + 'Date when the range was allocated': date_created, + 'Date when the range was last updated': date_updated + }}] + } + + return results + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/macvendors.py b/misp_modules/modules/expansion/macvendors.py new file mode 100644 index 00000000..55d0ef39 --- /dev/null +++ b/misp_modules/modules/expansion/macvendors.py @@ -0,0 +1,42 @@ +import requests +import json + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['mac-address'], 'output': ['text']} +moduleinfo = {'version': '0.1', 'author': 'Aurélien Schwab', 'description': 'Module to access Macvendors API.', 'module-type': ['hover']} +moduleconfig = ['user-agent'] # TODO take this into account in the code + +macvendors_api_url = 'https://api.macvendors.com/' +default_user_agent = 'MISP-Module' + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + for input_type in mispattributes['input']: + if input_type in request: + mac = request[input_type] + break + else: + misperrors['error'] = "Unsupported attributes type" + return misperrors + r = requests.get(macvendors_api_url + mac, headers={'user-agent': default_user_agent}) # Real request + if r.status_code == 200: # OK (record found) + response = r.text + if response: + return {'results': [{'types': mispattributes['output'], 'values': response}]} + elif r.status_code == 404: # Not found (not an error) + return {'results': [{'types': mispattributes['output'], 'values': 'Not found'}]} + else: # Real error + misperrors['error'] = 'MacVendors API not accessible (HTTP ' + str(r.status_code) + ')' + return misperrors['error'] + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/modules/expansion/module.py.skeleton b/misp_modules/modules/expansion/module.py.skeleton similarity index 100% rename from modules/expansion/module.py.skeleton rename to misp_modules/modules/expansion/module.py.skeleton diff --git a/misp_modules/modules/expansion/ocr-enrich.py b/misp_modules/modules/expansion/ocr-enrich.py new file mode 100644 index 00000000..cd6baca8 --- /dev/null +++ b/misp_modules/modules/expansion/ocr-enrich.py @@ -0,0 +1,50 @@ +import json +import binascii +import cv2 +import np +import pytesseract + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['attachment'], + 'output': ['freetext', 'text']} +moduleinfo = {'version': '0.1', 'author': 'Sascha Rommelfangen', + 'description': 'OCR decoder', + 'module-type': ['expansion']} + +moduleconfig = [] + + +def handler(q=False): + if q is False: + return False + q = json.loads(q) + filename = q['attachment'] + try: + img_array = np.frombuffer(binascii.a2b_base64(q['data']), np.uint8) + except Exception as e: + print(e) + err = "Couldn't fetch attachment (JSON 'data' is empty). Are you using the 'Query enrichment' action?" + misperrors['error'] = err + print(err) + return misperrors + + image = img_array + image = cv2.imdecode(img_array, cv2.IMREAD_COLOR) + try: + decoded = pytesseract.image_to_string(image) + return {'results': [{'types': ['freetext'], 'values': decoded, 'comment': "OCR from file " + filename}, + {'types': ['text'], 'values': decoded, 'comment': "ORC from file " + filename}]} + except Exception as e: + print(e) + err = "Couldn't analyze file type. Only images are supported right now." + misperrors['error'] = err + return misperrors + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/ods-enrich.py b/misp_modules/modules/expansion/ods-enrich.py new file mode 100644 index 00000000..b247c445 --- /dev/null +++ b/misp_modules/modules/expansion/ods-enrich.py @@ -0,0 +1,56 @@ +import json +import binascii +import np +import ezodf +import pandas_ods_reader +import io + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['attachment'], + 'output': ['freetext', 'text']} +moduleinfo = {'version': '0.1', 'author': 'Sascha Rommelfangen', + 'description': '.ods to freetext-import IOC extractor', + 'module-type': ['expansion']} + +moduleconfig = [] + + +def handler(q=False): + if q is False: + return False + q = json.loads(q) + filename = q['attachment'] + try: + ods_array = np.frombuffer(binascii.a2b_base64(q['data']), np.uint8) + except Exception as e: + print(e) + err = "Couldn't fetch attachment (JSON 'data' is empty). Are you using the 'Query enrichment' action?" + misperrors['error'] = err + print(err) + return misperrors + + ods_content = "" + ods_file = io.BytesIO(ods_array) + doc = ezodf.opendoc(ods_file) + num_sheets = len(doc.sheets) + try: + for i in range(0, num_sheets): + ods = pandas_ods_reader.read_ods(ods_file, i, headers=False) + ods_content = ods_content + "\n" + ods.to_string(max_rows=None) + print(ods_content) + return {'results': [{'types': ['freetext'], 'values': ods_content, 'comment': ".ods-to-text from file " + filename}, + {'types': ['text'], 'values': ods_content, 'comment': ".ods-to-text from file " + filename}]} + except Exception as e: + print(e) + err = "Couldn't analyze file as .ods. Error was: " + str(e) + misperrors['error'] = err + return misperrors + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/odt-enrich.py b/misp_modules/modules/expansion/odt-enrich.py new file mode 100644 index 00000000..c4513ae8 --- /dev/null +++ b/misp_modules/modules/expansion/odt-enrich.py @@ -0,0 +1,51 @@ +import json +import binascii +import np +from ODTReader.odtreader import odtToText +import io + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['attachment'], + 'output': ['freetext', 'text']} +moduleinfo = {'version': '0.1', 'author': 'Sascha Rommelfangen', + 'description': '.odt to freetext-import IOC extractor', + 'module-type': ['expansion']} + +moduleconfig = [] + + +def handler(q=False): + if q is False: + return False + q = json.loads(q) + filename = q['attachment'] + try: + odt_array = np.frombuffer(binascii.a2b_base64(q['data']), np.uint8) + except Exception as e: + print(e) + err = "Couldn't fetch attachment (JSON 'data' is empty). Are you using the 'Query enrichment' action?" + misperrors['error'] = err + print(err) + return misperrors + + odt_content = "" + odt_file = io.BytesIO(odt_array) + try: + odt_content = odtToText(odt_file) + print(odt_content) + return {'results': [{'types': ['freetext'], 'values': odt_content, 'comment': ".odt-to-text from file " + filename}, + {'types': ['text'], 'values': odt_content, 'comment': ".odt-to-text from file " + filename}]} + except Exception as e: + print(e) + err = "Couldn't analyze file as .odt. Error was: " + str(e) + misperrors['error'] = err + return misperrors + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/onyphe.py b/misp_modules/modules/expansion/onyphe.py new file mode 100644 index 00000000..aceaf057 --- /dev/null +++ b/misp_modules/modules/expansion/onyphe.py @@ -0,0 +1,108 @@ +# -*- coding: utf-8 -*- + +import json +try: + from onyphe import Onyphe +except ImportError: + print("pyonyphe module not installed.") + +misperrors = {'error': 'Error'} + +mispattributes = {'input': ['ip-src', 'ip-dst', 'hostname', 'domain'], + 'output': ['hostname', 'domain', 'ip-src', 'ip-dst', 'url']} +# possible module-types: 'expansion', 'hover' or both +moduleinfo = {'version': '1', 'author': 'Sebastien Larinier @sebdraven', + 'description': 'Query on Onyphe', + 'module-type': ['expansion', 'hover']} + +# config fields that your code expects from the site admin +moduleconfig = ['apikey'] + + +def handler(q=False): + if q: + + request = json.loads(q) + + if not request.get('config') and not (request['config'].get('apikey')): + misperrors['error'] = 'Onyphe authentication is missing' + return misperrors + + api = Onyphe(request['config'].get('apikey')) + + if not api: + misperrors['error'] = 'Onyphe Error instance api' + + ip = '' + if request.get('ip-src'): + ip = request['ip-src'] + elif request.get('ip-dst'): + ip = request['ip-dst'] + else: + misperrors['error'] = "Unsupported attributes type" + return misperrors + + return handle_expansion(api, ip, misperrors) + else: + return False + + +def handle_expansion(api, ip, misperrors): + result = api.ip(ip) + + if result['status'] == 'nok': + misperrors['error'] = result['message'] + return misperrors + + # categories = list(set([item['@category'] for item in result['results']])) + + result_filtered = {"results": []} + urls_pasties = [] + asn_list = [] + os_list = [] + domains_resolver = [] + domains_forward = [] + + for r in result['results']: + if r['@category'] == 'pastries': + if r['source'] == 'pastebin': + urls_pasties.append('https://pastebin.com/raw/%s' % r['key']) + elif r['@category'] == 'synscan': + asn_list.append(r['asn']) + os_target = r['os'] + if os_target != 'Unknown': + os_list.append(r['os']) + elif r['@category'] == 'resolver' and r['type'] == 'reverse': + domains_resolver.append(r['reverse']) + elif r['@category'] == 'resolver' and r['type'] == 'forward': + domains_forward.append(r['forward']) + + result_filtered['results'].append({'types': ['url'], 'values': urls_pasties, + 'categories': ['External analysis']}) + + result_filtered['results'].append({'types': ['AS'], 'values': list(set(asn_list)), + 'categories': ['Network activity']}) + + result_filtered['results'].append({'types': ['target-machine'], + 'values': list(set(os_list)), + 'categories': ['Targeting data']}) + + result_filtered['results'].append({'types': ['domain'], + 'values': list(set(domains_resolver)), + 'categories': ['Network activity'], + 'comment': 'resolver to %s' % ip}) + + result_filtered['results'].append({'types': ['domain'], + 'values': list(set(domains_forward)), + 'categories': ['Network activity'], + 'comment': 'forward to %s' % ip}) + return result_filtered + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/onyphe_full.py b/misp_modules/modules/expansion/onyphe_full.py new file mode 100644 index 00000000..aadb7448 --- /dev/null +++ b/misp_modules/modules/expansion/onyphe_full.py @@ -0,0 +1,377 @@ +# -*- coding: utf-8 -*- + +import json +try: + from onyphe import Onyphe +except ImportError: + print("pyonyphe module not installed.") + +misperrors = {'error': 'Error'} + +mispattributes = {'input': ['ip-src', 'ip-dst', 'hostname', 'domain'], + 'output': ['hostname', 'domain', 'ip-src', 'ip-dst', 'url']} + +# possible module-types: 'expansion', 'hover' or both +moduleinfo = {'version': '1', 'author': 'Sebastien Larinier @sebdraven', + 'description': 'Query on Onyphe', + 'module-type': ['expansion', 'hover']} + +# config fields that your code expects from the site admin +moduleconfig = ['apikey'] + + +def handler(q=False): + if q: + + request = json.loads(q) + + if not request.get('config') and not (request['config'].get('apikey')): + misperrors['error'] = 'Onyphe authentication is missing' + return misperrors + + api = Onyphe(request['config'].get('apikey')) + + if not api: + misperrors['error'] = 'Onyphe Error instance api' + + ip = '' + if request.get('ip-src'): + ip = request['ip-src'] + return handle_ip(api, ip, misperrors) + elif request.get('ip-dst'): + ip = request['ip-dst'] + return handle_ip(api, ip, misperrors) + elif request.get('domain'): + domain = request['domain'] + return handle_domain(api, domain, misperrors) + elif request.get('hostname'): + hostname = request['hostname'] + return handle_domain(api, hostname, misperrors) + else: + misperrors['error'] = "Unsupported attributes type" + return misperrors + else: + return False + + +def handle_domain(api, domain, misperrors): + result_filtered = {"results": []} + + r, status_ok = expand_pastries(api, misperrors, domain=domain) + + if status_ok: + result_filtered['results'].extend(r) + else: + misperrors['error'] = 'Error pastries result' + return misperrors + + r, status_ok = expand_datascan(api, misperrors, domain=domain) + + if status_ok: + result_filtered['results'].extend(r) + else: + misperrors['error'] = 'Error datascan result ' + return misperrors + + r, status_ok = expand_threatlist(api, misperrors, domain=domain) + + if status_ok: + result_filtered['results'].extend(r) + else: + misperrors['error'] = 'Error threat list' + return misperrors + + return result_filtered + + +def handle_ip(api, ip, misperrors): + result_filtered = {"results": []} + + r, status_ok = expand_syscan(api, ip, misperrors) + + if status_ok: + result_filtered['results'].extend(r) + else: + misperrors['error'] = "Error syscan result" + + r, status_ok = expand_pastries(api, misperrors, ip=ip) + + if status_ok: + result_filtered['results'].extend(r) + else: + misperrors['error'] = 'Error pastries result' + return misperrors + + r, status_ok = expand_datascan(api, misperrors, ip=ip) + + if status_ok: + result_filtered['results'].extend(r) + else: + misperrors['error'] = 'Error datascan result ' + return misperrors + + r, status_ok = expand_forward(api, ip, misperrors) + + if status_ok: + result_filtered['results'].extend(r) + else: + misperrors['error'] = 'Error forward result' + return misperrors + + r, status_ok = expand_reverse(api, ip, misperrors) + + if status_ok: + result_filtered['results'].extend(r) + else: + misperrors['error'] = 'Error reverse result' + return misperrors + + r, status_ok = expand_threatlist(api, misperrors, ip=ip) + + if status_ok: + result_filtered['results'].extend(r) + else: + misperrors['error'] = 'Error threat list' + return misperrors + + return result_filtered + + +def expand_syscan(api, ip, misperror): + status_ok = False + r = [] + asn_list = [] + os_list = [] + geoloc = [] + orgs = [] + results = api.synscan(ip) + + if results['status'] == 'ok': + status_ok = True + for elem in results['results']: + asn_list.append(elem['asn']) + os_target = elem['os'] + geoloc.append(elem['location']) + orgs.append(elem['organization']) + if os_target != 'Unknown' and os_target != 'Undefined': + os_list.append(elem['os']) + + r.append({'types': ['target-machine'], + 'values': list(set(os_list)), + 'categories': ['Targeting data'], + 'comment': 'OS found on %s with synscan of Onyphe' % ip}) + + r.append({'types': ['target-location'], + 'values': list(set(geoloc)), + 'categories': ['Targeting data'], + 'comment': 'Geolocalisation of %s found with synscan of Onyphe' + % ip + }) + + r.append({'types': ['target-org'], + 'values': list(set(orgs)), + 'categories': ['Targeting data'], + 'comment': 'Organisations of %s found with synscan of Onyphe' + % ip + }) + + r.append({'types': ['AS'], + 'values': list(set(asn_list)), + 'categories': ['Network activity'], + 'comment': 'As number of %s found with synscan of Onyphe' % ip + }) + + return r, status_ok + + +def expand_datascan(api, misperror, **kwargs): + status_ok = False + r = [] + # ip = '' + query = '' + asn_list = [] + geoloc = [] + orgs = [] + ports = [] + + if 'ip' in kwargs: + query = kwargs.get('ip') + results = api.datascan(query) + else: + query = kwargs.get('domain') + results = api.search_datascan('domain:%s' % query) + + if results['status'] == 'ok': + status_ok = True + for elem in results['results']: + asn_list.append(elem['asn']) + geoloc.append(elem['location']) + orgs.append(elem['organization']) + ports.append(elem['port']) + + r.append({'types': ['port'], + 'values': list(set(ports)), + 'categories': ['Other'], + 'comment': 'Ports of %s found with datascan of Onyphe' + % query + }) + + r.append({'types': ['target-location'], + 'values': list(set(geoloc)), + 'categories': ['Targeting data'], + 'comment': 'Geolocalisation of %s found with synscan of Onyphe' + % query + }) + + r.append({'types': ['target-org'], + 'values': list(set(orgs)), + 'categories': ['Targeting data'], + 'comment': 'Organisations of %s found with synscan of Onyphe' + % query + }) + + r.append({'types': ['AS'], + 'values': list(set(asn_list)), + 'categories': ['Network activity'], + 'comment': 'As number of %s found with synscan of Onyphe' % query + }) + return r, status_ok + + +def expand_reverse(api, ip, misperror): + status_ok = False + r = None + status_ok = False + r = [] + results = api.reverse(ip) + + domains_reverse = [] + + domains = [] + if results['status'] == 'ok': + status_ok = True + + for elem in results['results']: + domains_reverse.append(elem['reverse']) + domains.append(elem['domain']) + + r.append({'types': ['domain'], + 'values': list(set(domains)), + 'categories': ['Network activity'], + 'comment': 'Domains of %s from forward service of Onyphe' % ip}) + + r.append({'types': ['domain'], + 'values': list(set(domains_reverse)), + 'categories': ['Network activity'], + 'comment': 'Reverse Domains of %s from forward service of Onyphe' % ip}) + return r, status_ok + + +def expand_forward(api, ip, misperror): + status_ok = False + r = [] + results = api.forward(ip) + + domains_forward = [] + + domains = [] + if results['status'] == 'ok': + status_ok = True + + for elem in results['results']: + domains_forward.append(elem['forward']) + domains.append(elem['domain']) + + r.append({'types': ['domain'], + 'values': list(set(domains)), + 'categories': ['Network activity'], + 'comment': 'Domains of %s from forward service of Onyphe' % ip}) + + r.append({'types': ['domain'], + 'values': list(set(domains_forward)), + 'categories': ['Network activity'], + 'comment': 'Forward Domains of %s from forward service of Onyphe' % ip}) + return r, status_ok + + +def expand_pastries(api, misperror, **kwargs): + status_ok = False + r = [] + + query = None + result = None + urls_pasties = [] + domains = [] + ips = [] + if 'ip' in kwargs: + query = kwargs.get('ip') + result = api.pastries(query) + if 'domain' in kwargs: + query = kwargs.get('domain') + result = api.search_pastries('domain:%s' % query) + + if result['status'] == 'ok': + status_ok = True + for item in result['results']: + if item['@category'] == 'pastries': + if item['source'] == 'pastebin': + urls_pasties.append('https://pastebin.com/raw/%s' % item['key']) + + if 'domain' in item: + domains.extend(item['domain']) + if 'ip' in item: + ips.extend(item['ip']) + if 'hostname' in item: + domains.extend(item['hostname']) + + r.append({'types': ['url'], + 'values': urls_pasties, + 'categories': ['External analysis'], + 'comment': 'URLs of pasties where %s has found' % query}) + r.append({'types': ['domain'], 'values': list(set(domains)), + 'categories': ['Network activity'], + 'comment': 'Domains found in pasties of Onyphe'}) + + r.append({'types': ['ip-dst'], 'values': list(set(ips)), + 'categories': ['Network activity'], + 'comment': 'IPs found in pasties of Onyphe'}) + + return r, status_ok + + +def expand_threatlist(api, misperror, **kwargs): + status_ok = False + r = [] + + query = None + + threat_list = [] + + if 'ip' in kwargs: + query = kwargs.get('ip') + results = api.threatlist(query) + else: + query = kwargs.get('domain') + results = api.search_threatlist('domain:%s' % query) + + if results['status'] == 'ok': + status_ok = True + threat_list = ['seen %s on %s ' % (item['seen_date'], item['threatlist']) + for item in results['results']] + + r.append({'types': ['comment'], + 'categories': ['Other'], + 'values': threat_list, + 'comment': '%s is present in threatlist' % query + }) + + return r, status_ok + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/otx.py b/misp_modules/modules/expansion/otx.py index 214e7f05..e5861807 100755 --- a/misp_modules/modules/expansion/otx.py +++ b/misp_modules/modules/expansion/otx.py @@ -15,9 +15,10 @@ moduleinfo = {'version': '1', 'author': 'chrisdoman', # We're not actually using the API key yet moduleconfig = ["apikey"] + # Avoid adding windows update to enrichment etc. def isBlacklisted(value): - blacklist = ['0.0.0.0', '8.8.8.8', '255.255.255.255', '192.168.56.' , 'time.windows.com'] + blacklist = ['0.0.0.0', '8.8.8.8', '255.255.255.255', '192.168.56.', 'time.windows.com'] for b in blacklist: if value in b: @@ -25,28 +26,31 @@ def isBlacklisted(value): return True + def valid_ip(ip): m = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip) return bool(m) and all(map(lambda n: 0 <= int(n) <= 255, m.groups())) + def findAll(data, keys): a = [] if isinstance(data, dict): - for key in data.keys(): + for key, value in data.items(): if key == keys: - a.append(data[key]) + a.append(value) else: - if isinstance(data[key], (dict, list)): - a += findAll(data[key], keys) + if isinstance(value, (dict, list)): + a.extend(findAll(value, keys)) if isinstance(data, list): for i in data: - a += findAll(i, keys) - + a.extend(findAll(i, keys)) return a + def valid_email(email): return bool(re.search(r"[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?", email)) + def handler(q=False): if q is False: return False @@ -82,10 +86,10 @@ def handler(q=False): return r -def getHash(hash, key): +def getHash(_hash, key): ret = [] - req = json.loads(requests.get("https://otx.alienvault.com/otxapi/indicator/file/analysis/" + hash).text) + req = json.loads(requests.get("https://otx.alienvault.com/otxapi/indicator/file/analysis/" + _hash).text) for ip in findAll(req, "dst"): if not isBlacklisted(ip) and valid_ip(ip): @@ -100,19 +104,17 @@ def getHash(hash, key): def getIP(ip, key): ret = [] - req = json.loads( requests.get("https://otx.alienvault.com/otxapi/indicator/ip/malware/" + ip + "?limit=1000").text ) + req = json.loads(requests.get("https://otx.alienvault.com/otxapi/indicator/ip/malware/" + ip + "?limit=1000").text) - for hash in findAll(req, "hash"): - ret.append({"types": ["sha256"], "values": [hash]}) + for _hash in findAll(req, "hash"): + ret.append({"types": ["sha256"], "values": [_hash]}) - - req = json.loads( requests.get("https://otx.alienvault.com/otxapi/indicator/ip/passive_dns/" + ip).text ) + req = json.loads(requests.get("https://otx.alienvault.com/otxapi/indicator/ip/passive_dns/" + ip).text) for hostname in findAll(req, "hostname"): if not isBlacklisted(hostname): ret.append({"types": ["hostname"], "values": [hostname]}) - return ret @@ -120,23 +122,23 @@ def getDomain(domain, key): ret = [] - req = json.loads( requests.get("https://otx.alienvault.com/otxapi/indicator/domain/malware/" + domain + "?limit=1000").text ) + req = json.loads(requests.get("https://otx.alienvault.com/otxapi/indicator/domain/malware/" + domain + "?limit=1000").text) - for hash in findAll(req, "hash"): - ret.append({"types": ["sha256"], "values": [hash]}) + for _hash in findAll(req, "hash"): + ret.append({"types": ["sha256"], "values": [_hash]}) req = json.loads(requests.get("https://otx.alienvault.com/otxapi/indicator/domain/whois/" + domain).text) - for domain in findAll(req, "domain"): - ret.append({"types": ["hostname"], "values": [domain]}) + for _domain in findAll(req, "domain"): + ret.append({"types": ["hostname"], "values": [_domain]}) for email in findAll(req, "value"): if valid_email(email): - ret.append({"types": ["email"], "values": [domain]}) + ret.append({"types": ["email"], "values": [email]}) - for domain in findAll(req, "hostname"): - if "." in domain and not isBlacklisted(domain): - ret.append({"types": ["hostname"], "values": [domain]}) + for _domain in findAll(req, "hostname"): + if "." in _domain and not isBlacklisted(_domain): + ret.append({"types": ["hostname"], "values": [_domain]}) req = json.loads(requests.get("https://otx.alienvault.com/otxapi/indicator/hostname/passive_dns/" + domain).text) for ip in findAll(req, "address"): @@ -145,6 +147,7 @@ def getDomain(domain, key): return ret + def introspection(): return mispattributes diff --git a/misp_modules/modules/expansion/passivetotal.py b/misp_modules/modules/expansion/passivetotal.py index 5325d191..6bf2f93b 100755 --- a/misp_modules/modules/expansion/passivetotal.py +++ b/misp_modules/modules/expansion/passivetotal.py @@ -331,7 +331,7 @@ def handler(q=False): output['results'] += results else: log.error("Unsupported query pattern issued.") - except: + except Exception: return misperrors return output diff --git a/misp_modules/modules/expansion/pdf-enrich.py b/misp_modules/modules/expansion/pdf-enrich.py new file mode 100644 index 00000000..ef85fde2 --- /dev/null +++ b/misp_modules/modules/expansion/pdf-enrich.py @@ -0,0 +1,48 @@ +import json +import binascii +import np +import pdftotext +import io + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['attachment'], + 'output': ['freetext', 'text']} +moduleinfo = {'version': '0.1', 'author': 'Sascha Rommelfangen', + 'description': 'PDF to freetext-import IOC extractor', + 'module-type': ['expansion']} + +moduleconfig = [] + + +def handler(q=False): + if q is False: + return False + q = json.loads(q) + filename = q['attachment'] + try: + pdf_array = np.frombuffer(binascii.a2b_base64(q['data']), np.uint8) + except Exception as e: + print(e) + err = "Couldn't fetch attachment (JSON 'data' is empty). Are you using the 'Query enrichment' action?" + misperrors['error'] = err + print(err) + return misperrors + + pdf_file = io.BytesIO(pdf_array) + try: + pdf_content = "\n\n".join(pdftotext.PDF(pdf_file)) + return {'results': [{'types': ['freetext'], 'values': pdf_content, 'comment': "PDF-to-text from file " + filename}]} + except Exception as e: + print(e) + err = "Couldn't analyze file as PDF. Error was: " + str(e) + misperrors['error'] = err + return misperrors + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/pptx-enrich.py b/misp_modules/modules/expansion/pptx-enrich.py new file mode 100644 index 00000000..816e4391 --- /dev/null +++ b/misp_modules/modules/expansion/pptx-enrich.py @@ -0,0 +1,55 @@ +import json +import binascii +import np +from pptx import Presentation +import io + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['attachment'], + 'output': ['freetext', 'text']} +moduleinfo = {'version': '0.1', 'author': 'Sascha Rommelfangen', + 'description': '.pptx to freetext-import IOC extractor', + 'module-type': ['expansion']} + +moduleconfig = [] + + +def handler(q=False): + if q is False: + return False + q = json.loads(q) + filename = q['attachment'] + try: + pptx_array = np.frombuffer(binascii.a2b_base64(q['data']), np.uint8) + except Exception as e: + print(e) + err = "Couldn't fetch attachment (JSON 'data' is empty). Are you using the 'Query enrichment' action?" + misperrors['error'] = err + print(err) + return misperrors + + ppt_content = "" + ppt_file = io.BytesIO(pptx_array) + try: + ppt = Presentation(ppt_file) + for slide in ppt.slides: + for shape in slide.shapes: + if hasattr(shape, "text"): + print(shape.text) + ppt_content = ppt_content + "\n" + shape.text + return {'results': [{'types': ['freetext'], 'values': ppt_content, 'comment': ".pptx-to-text from file " + filename}, + {'types': ['text'], 'values': ppt_content, 'comment': ".pptx-to-text from file " + filename}]} + except Exception as e: + print(e) + err = "Couldn't analyze file as .pptx. Error was: " + str(e) + misperrors['error'] = err + return misperrors + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/qrcode.py b/misp_modules/modules/expansion/qrcode.py new file mode 100644 index 00000000..9a628270 --- /dev/null +++ b/misp_modules/modules/expansion/qrcode.py @@ -0,0 +1,89 @@ +import json +from pyzbar import pyzbar +import cv2 +import re +import binascii +import np + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['attachment'], + 'output': ['url', 'btc']} +moduleinfo = {'version': '0.1', 'author': 'Sascha Rommelfangen', + 'description': 'QR code decoder', + 'module-type': ['expansion', 'hover']} + +debug = True +debug_prefix = "[DEBUG] QR Code module: " +# format example: bitcoin:1GXZ6v7FZzYBEnoRaG77SJxhu7QkvQmFuh?amount=0.15424 +# format example: http://example.com +cryptocurrencies = ['bitcoin'] +schemas = ['http://', 'https://', 'ftp://'] +moduleconfig = [] + + +def handler(q=False): + if q is False: + return False + q = json.loads(q) + filename = q['attachment'] + try: + img_array = np.fromstring(binascii.a2b_base64(q['data']), np.uint8) + except Exception as e: + err = "Couldn't fetch attachment (JSON 'data' is empty). Are you using the 'Query enrichment' action?" + misperrors['error'] = err + print(err) + print(e) + return misperrors + image = cv2.imdecode(img_array, cv2.IMREAD_COLOR) + if q: + barcodes = pyzbar.decode(image) + for item in barcodes: + try: + result = item.data.decode() + except Exception as e: + print(e) + return + if debug: + print(debug_prefix + result) + for item in cryptocurrencies: + if item in result: + try: + currency, address, extra = re.split(r'\:|\?', result) + except Exception as e: + print(e) + if currency in cryptocurrencies: + try: + amount = re.split('=', extra)[1] + if debug: + print(debug_prefix + address) + print(debug_prefix + amount) + return {'results': [{'types': ['btc'], 'values': address, 'comment': "BTC: " + amount + " from file " + filename}]} + except Exception as e: + print(e) + else: + print(address) + for item in schemas: + if item in result: + try: + url = result + if debug: + print(debug_prefix + url) + return {'results': [{'types': ['url'], 'values': url, 'comment': "from QR code of file " + filename}]} + except Exception as e: + print(e) + else: + try: + return {'results': [{'types': ['text'], 'values': result, 'comment': "from QR code of file " + filename}]} + except Exception as e: + print(e) + misperrors['error'] = "Couldn't decode QR code in attachment." + return misperrors + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/rbl.py b/misp_modules/modules/expansion/rbl.py index da8c5fb1..b9b89bbc 100644 --- a/misp_modules/modules/expansion/rbl.py +++ b/misp_modules/modules/expansion/rbl.py @@ -1,12 +1,12 @@ import json -import datetime +import sys try: import dns.resolver resolver = dns.resolver.Resolver() resolver.timeout = 0.2 resolver.lifetime = 0.2 -except: +except ImportError: print("dnspython3 is missing, use 'pip install dnspython3' to install it.") sys.exit(0) @@ -18,64 +18,65 @@ moduleinfo = {'version': '0.1', 'author': 'Christian Studer', moduleconfig = [] rbls = { - 'spam.spamrats.com': 'http://www.spamrats.com', - 'spamguard.leadmon.net': 'http://www.leadmon.net/SpamGuard/', - 'rbl-plus.mail-abuse.org': 'http://www.mail-abuse.com/lookup.html', - 'web.dnsbl.sorbs.net': 'http://www.sorbs.net', - 'ix.dnsbl.manitu.net': 'http://www.dnsbl.manitu.net', - 'virus.rbl.jp': 'http://www.rbl.jp', - 'dul.dnsbl.sorbs.net': 'http://www.sorbs.net', - 'bogons.cymru.com': 'http://www.team-cymru.org/Services/Bogons/', - 'psbl.surriel.com': 'http://psbl.surriel.com', - 'misc.dnsbl.sorbs.net': 'http://www.sorbs.net', - 'httpbl.abuse.ch': 'http://dnsbl.abuse.ch', - 'combined.njabl.org': 'http://combined.njabl.org', - 'smtp.dnsbl.sorbs.net': 'http://www.sorbs.net', - 'korea.services.net': 'http://korea.services.net', - 'drone.abuse.ch': 'http://dnsbl.abuse.ch', - 'rbl.efnetrbl.org': 'http://rbl.efnetrbl.org', - 'cbl.anti-spam.org.cn': 'http://www.anti-spam.org.cn/?Locale=en_US', - 'b.barracudacentral.org': 'http://www.barracudacentral.org/rbl/removal-request', - 'bl.spamcannibal.org': 'http://www.spamcannibal.org', - 'xbl.spamhaus.org': 'http://www.spamhaus.org/xbl/', - 'zen.spamhaus.org': 'http://www.spamhaus.org/zen/', - 'rbl.suresupport.com': 'http://suresupport.com/postmaster', - 'db.wpbl.info': 'http://www.wpbl.info', - 'sbl.spamhaus.org': 'http://www.spamhaus.org/sbl/', - 'http.dnsbl.sorbs.net': 'http://www.sorbs.net', - 'csi.cloudmark.com': 'http://www.cloudmark.com/en/products/cloudmark-sender-intelligence/index', - 'rbl.interserver.net': 'http://rbl.interserver.net', - 'ubl.unsubscore.com': 'http://www.lashback.com/blacklist/', - 'dnsbl.sorbs.net': 'http://www.sorbs.net', - 'virbl.bit.nl': 'http://virbl.bit.nl', - 'pbl.spamhaus.org': 'http://www.spamhaus.org/pbl/', - 'socks.dnsbl.sorbs.net': 'http://www.sorbs.net', - 'short.rbl.jp': 'http://www.rbl.jp', - 'dnsbl.dronebl.org': 'http://www.dronebl.org', - 'blackholes.mail-abuse.org': 'http://www.mail-abuse.com/lookup.html', - 'truncate.gbudb.net': 'http://www.gbudb.com/truncate/index.jsp', - 'dyna.spamrats.com': 'http://www.spamrats.com', - 'spamrbl.imp.ch': 'http://antispam.imp.ch', - 'spam.dnsbl.sorbs.net': 'http://www.sorbs.net', - 'wormrbl.imp.ch': 'http://antispam.imp.ch', - 'query.senderbase.org': 'http://www.senderbase.org/about', - 'opm.tornevall.org': 'http://dnsbl.tornevall.org', - 'netblock.pedantic.org': 'http://pedantic.org', - 'access.redhawk.org': 'http://www.redhawk.org/index.php?option=com_wrapper&Itemid=33', - 'cdl.anti-spam.org.cn': 'http://www.anti-spam.org.cn/?Locale=en_US', - 'multi.surbl.org': 'http://www.surbl.org', - 'noptr.spamrats.com': 'http://www.spamrats.com', - 'dnsbl.inps.de': 'http://dnsbl.inps.de/index.cgi?lang=en', - 'bl.spamcop.net': 'http://bl.spamcop.net', - 'cbl.abuseat.org': 'http://cbl.abuseat.org', - 'dsn.rfc-ignorant.org': 'http://www.rfc-ignorant.org/policy-dsn.php', - 'zombie.dnsbl.sorbs.net': 'http://www.sorbs.net', - 'dnsbl.njabl.org': 'http://dnsbl.njabl.org', - 'relays.mail-abuse.org': 'http://www.mail-abuse.com/lookup.html', - 'rbl.spamlab.com': 'http://tools.appriver.com/index.aspx?tool=rbl', - 'all.bl.blocklist.de': 'http://www.blocklist.de/en/rbldns.html' + 'spam.spamrats.com': 'http://www.spamrats.com', + 'spamguard.leadmon.net': 'http://www.leadmon.net/SpamGuard/', + 'rbl-plus.mail-abuse.org': 'http://www.mail-abuse.com/lookup.html', + 'web.dnsbl.sorbs.net': 'http://www.sorbs.net', + 'ix.dnsbl.manitu.net': 'http://www.dnsbl.manitu.net', + 'virus.rbl.jp': 'http://www.rbl.jp', + 'dul.dnsbl.sorbs.net': 'http://www.sorbs.net', + 'bogons.cymru.com': 'http://www.team-cymru.org/Services/Bogons/', + 'psbl.surriel.com': 'http://psbl.surriel.com', + 'misc.dnsbl.sorbs.net': 'http://www.sorbs.net', + 'httpbl.abuse.ch': 'http://dnsbl.abuse.ch', + 'combined.njabl.org': 'http://combined.njabl.org', + 'smtp.dnsbl.sorbs.net': 'http://www.sorbs.net', + 'korea.services.net': 'http://korea.services.net', + 'drone.abuse.ch': 'http://dnsbl.abuse.ch', + 'rbl.efnetrbl.org': 'http://rbl.efnetrbl.org', + 'cbl.anti-spam.org.cn': 'http://www.anti-spam.org.cn/?Locale=en_US', + 'b.barracudacentral.org': 'http://www.barracudacentral.org/rbl/removal-request', + 'bl.spamcannibal.org': 'http://www.spamcannibal.org', + 'xbl.spamhaus.org': 'http://www.spamhaus.org/xbl/', + 'zen.spamhaus.org': 'http://www.spamhaus.org/zen/', + 'rbl.suresupport.com': 'http://suresupport.com/postmaster', + 'db.wpbl.info': 'http://www.wpbl.info', + 'sbl.spamhaus.org': 'http://www.spamhaus.org/sbl/', + 'http.dnsbl.sorbs.net': 'http://www.sorbs.net', + 'csi.cloudmark.com': 'http://www.cloudmark.com/en/products/cloudmark-sender-intelligence/index', + 'rbl.interserver.net': 'http://rbl.interserver.net', + 'ubl.unsubscore.com': 'http://www.lashback.com/blacklist/', + 'dnsbl.sorbs.net': 'http://www.sorbs.net', + 'virbl.bit.nl': 'http://virbl.bit.nl', + 'pbl.spamhaus.org': 'http://www.spamhaus.org/pbl/', + 'socks.dnsbl.sorbs.net': 'http://www.sorbs.net', + 'short.rbl.jp': 'http://www.rbl.jp', + 'dnsbl.dronebl.org': 'http://www.dronebl.org', + 'blackholes.mail-abuse.org': 'http://www.mail-abuse.com/lookup.html', + 'truncate.gbudb.net': 'http://www.gbudb.com/truncate/index.jsp', + 'dyna.spamrats.com': 'http://www.spamrats.com', + 'spamrbl.imp.ch': 'http://antispam.imp.ch', + 'spam.dnsbl.sorbs.net': 'http://www.sorbs.net', + 'wormrbl.imp.ch': 'http://antispam.imp.ch', + 'query.senderbase.org': 'http://www.senderbase.org/about', + 'opm.tornevall.org': 'http://dnsbl.tornevall.org', + 'netblock.pedantic.org': 'http://pedantic.org', + 'access.redhawk.org': 'http://www.redhawk.org/index.php?option=com_wrapper&Itemid=33', + 'cdl.anti-spam.org.cn': 'http://www.anti-spam.org.cn/?Locale=en_US', + 'multi.surbl.org': 'http://www.surbl.org', + 'noptr.spamrats.com': 'http://www.spamrats.com', + 'dnsbl.inps.de': 'http://dnsbl.inps.de/index.cgi?lang=en', + 'bl.spamcop.net': 'http://bl.spamcop.net', + 'cbl.abuseat.org': 'http://cbl.abuseat.org', + 'dsn.rfc-ignorant.org': 'http://www.rfc-ignorant.org/policy-dsn.php', + 'zombie.dnsbl.sorbs.net': 'http://www.sorbs.net', + 'dnsbl.njabl.org': 'http://dnsbl.njabl.org', + 'relays.mail-abuse.org': 'http://www.mail-abuse.com/lookup.html', + 'rbl.spamlab.com': 'http://tools.appriver.com/index.aspx?tool=rbl', + 'all.bl.blocklist.de': 'http://www.blocklist.de/en/rbldns.html' } + def handler(q=False): if q is False: return False @@ -89,24 +90,23 @@ def handler(q=False): return misperrors listed = [] info = [] + ipRev = '.'.join(ip.split('.')[::-1]) for rbl in rbls: - ipRev = '.'.join(ip.split('.')[::-1]) query = '{}.{}'.format(ipRev, rbl) try: - txt = resolver.query(query,'TXT') + txt = resolver.query(query, 'TXT') listed.append(query) - info.append(str(txt[0])) - except: + info.append([str(t) for t in txt]) + except Exception: continue - result = {} - for l, i in zip(listed, info): - result[l] = i - r = {'results': [{'types': mispattributes.get('output'), 'values': json.dumps(result)}]} - return r + result = "\n".join(["{}: {}".format(l, " - ".join(i)) for l, i in zip(listed, info)]) + return {'results': [{'types': mispattributes.get('output'), 'values': result}]} + def introspection(): return mispattributes + def version(): moduleinfo['config'] = moduleconfig return moduleinfo diff --git a/misp_modules/modules/expansion/reversedns.py b/misp_modules/modules/expansion/reversedns.py index 46fe94a6..3b945a74 100644 --- a/misp_modules/modules/expansion/reversedns.py +++ b/misp_modules/modules/expansion/reversedns.py @@ -1,5 +1,5 @@ import json -import dns.reversename, dns.resolver +from dns import reversename, resolver, exception misperrors = {'error': 'Error'} mispattributes = {'input': ['ip-src', 'ip-dst', 'domain|ip'], 'output': ['hostname']} @@ -12,6 +12,7 @@ moduleinfo = {'version': '0.1', 'author': 'Andreas Muehlemann', # config fields that your code expects from the site admin moduleconfig = ['nameserver'] + def handler(q=False): if q is False: return False @@ -26,9 +27,9 @@ def handler(q=False): return False # reverse lookup for ip - revname = dns.reversename.from_address(toquery) + revname = reversename.from_address(toquery) - r = dns.resolver.Resolver() + r = resolver.Resolver() r.timeout = 2 r.lifetime = 2 @@ -42,13 +43,13 @@ def handler(q=False): try: answer = r.query(revname, 'PTR') - except dns.resolver.NXDOMAIN: + except resolver.NXDOMAIN: misperrors['error'] = "NXDOMAIN" return misperrors - except dns.exception.Timeout: + except exception.Timeout: misperrors['error'] = "Timeout" return misperrors - except: + except Exception: misperrors['error'] = "DNS resolving error" return misperrors @@ -56,9 +57,11 @@ def handler(q=False): 'values':[str(answer[0])]}]} return r + def introspection(): return mispattributes + def version(): moduleinfo['config'] = moduleconfig return moduleinfo diff --git a/misp_modules/modules/expansion/securitytrails.py b/misp_modules/modules/expansion/securitytrails.py new file mode 100644 index 00000000..21ff089b --- /dev/null +++ b/misp_modules/modules/expansion/securitytrails.py @@ -0,0 +1,559 @@ +import json +import logging +import sys +import time + +from dnstrails import APIError +from dnstrails import DnsTrails + +log = logging.getLogger('dnstrails') +log.setLevel(logging.DEBUG) +ch = logging.StreamHandler(sys.stdout) +ch.setLevel(logging.DEBUG) +formatter = logging.Formatter( + '%(asctime)s - %(name)s - %(levelname)s - %(message)s') +ch.setFormatter(formatter) +log.addHandler(ch) + +misperrors = {'error': 'Error'} +mispattributes = { + 'input': ['hostname', 'domain', 'ip-src', 'ip-dst'], + 'output': ['hostname', 'domain', 'ip-src', 'ip-dst', 'dns-soa-email', + 'whois-registrant-email', 'whois-registrant-phone', + 'whois-registrant-name', + 'whois-registrar', 'whois-creation-date', 'domain'] +} + +moduleinfo = {'version': '1', 'author': 'Sebastien Larinier @sebdraven', + 'description': 'Query on securitytrails.com', + 'module-type': ['expansion', 'hover']} + +# config fields that your code expects from the site admin +moduleconfig = ['apikey'] + + +def handler(q=False): + if q: + + request = json.loads(q) + + if not request.get('config') and not (request['config'].get('apikey')): + misperrors['error'] = 'DNS authentication is missing' + return misperrors + + api = DnsTrails(request['config'].get('apikey')) + + if not api: + misperrors['error'] = 'Onyphe Error instance api' + if request.get('ip-src'): + ip = request['ip-src'] + return handle_ip(api, ip, misperrors) + elif request.get('ip-dst'): + ip = request['ip-dst'] + return handle_ip(api, ip, misperrors) + elif request.get('domain'): + domain = request['domain'] + return handle_domain(api, domain, misperrors) + elif request.get('hostname'): + hostname = request['hostname'] + return handle_domain(api, hostname, misperrors) + else: + misperrors['error'] = "Unsupported attributes types" + return misperrors + else: + return False + + +def handle_domain(api, domain, misperrors): + result_filtered = {"results": []} + + r, status_ok = expand_domain_info(api, misperrors, domain) + + if status_ok: + if r: + result_filtered['results'].extend(r) + else: + misperrors['error'] = misperrors['error'] + ' Error DNS result' + return misperrors + + time.sleep(1) + r, status_ok = expand_subdomains(api, domain) + + if status_ok: + if r: + result_filtered['results'].extend(r) + else: + misperrors['error'] = misperrors['error'] + ' Error subdomains result' + return misperrors + + time.sleep(1) + r, status_ok = expand_whois(api, domain) + + if status_ok: + if r: + result_filtered['results'].extend(r) + else: + misperrors['error'] = misperrors['error'] + ' Error whois result' + return misperrors + + time.sleep(1) + r, status_ok = expand_history_ipv4_ipv6(api, domain) + + if status_ok: + if r: + result_filtered['results'].extend(r) + else: + misperrors['error'] = misperrors['error'] + ' Error history ipv4' + return misperrors + + time.sleep(1) + + r, status_ok = expand_history_dns(api, domain) + + if status_ok: + if r: + result_filtered['results'].extend(r) + else: + misperrors['error'] = misperrors['error'] + ' Error in expand History DNS' + return misperrors + + r, status_ok = expand_history_whois(api, domain) + + if status_ok: + if r: + result_filtered['results'].extend(r) + else: + misperrors['error'] = misperrors['error'] + ' Error in expand History Whois' + return misperrors + + return result_filtered + + +def handle_ip(api, ip, misperrors): + result_filtered = {"results": []} + + r, status_ok = expand_searching_domain(api, ip) + + if status_ok: + if r: + result_filtered['results'].extend(r) + else: + misperrors['error'] += ' Error in expand searching domain' + return misperrors + + return result_filtered + + +def expand_domain_info(api, misperror, domain): + r = [] + status_ok = False + ns_servers = [] + list_ipv4 = [] + list_ipv6 = [] + servers_mx = [] + soa_hostnames = [] + + results = api.domain(domain) + + if results: + status_ok = True + if 'current_dns' in results: + if 'values' in results['current_dns']['ns']: + ns_servers = [ns_entry['nameserver'] for ns_entry in + results['current_dns']['ns']['values'] + if 'nameserver' in ns_entry] + if 'values' in results['current_dns']['a']: + list_ipv4 = [a_entry['ip'] for a_entry in + results['current_dns']['a']['values'] if + 'ip' in a_entry] + + if 'values' in results['current_dns']['aaaa']: + list_ipv6 = [ipv6_entry['ipv6'] for ipv6_entry in + results['current_dns']['aaaa']['values'] if + 'ipv6' in ipv6_entry] + + if 'values' in results['current_dns']['mx']: + servers_mx = [mx_entry['hostname'] for mx_entry in + results['current_dns']['mx']['values'] if + 'hostname' in mx_entry] + if 'values' in results['current_dns']['soa']: + soa_hostnames = [soa_entry['email'] for soa_entry in + results['current_dns']['soa']['values'] if + 'email' in soa_entry] + + if ns_servers: + r.append({'types': ['domain'], + 'values': ns_servers, + 'categories': ['Network activity'], + 'comment': 'List of name servers of %s first seen %s ' % + (domain, + results['current_dns']['ns']['first_seen']) + }) + + if list_ipv4: + r.append({'types': ['domain|ip'], + 'values': ['%s|%s' % (domain, ipv4) for ipv4 in + list_ipv4], + 'categories': ['Network activity'], + + 'comment': ' List ipv4 of %s first seen %s' % + (domain, + results['current_dns']['a']['first_seen']) + + }) + if list_ipv6: + r.append({'types': ['domain|ip'], + 'values': ['%s|%s' % (domain, ipv6) for ipv6 in + list_ipv6], + 'categories': ['Network activity'], + 'comment': ' List ipv6 of %s first seen %s' % + (domain, + results['current_dns']['aaaa']['first_seen']) + + }) + + if servers_mx: + r.append({'types': ['domain'], + 'values': servers_mx, + 'categories': ['Network activity'], + 'comment': ' List mx of %s first seen %s' % + (domain, + results['current_dns']['mx']['first_seen']) + + }) + if soa_hostnames: + r.append({'types': ['domain'], + 'values': soa_hostnames, + 'categories': ['Network activity'], + 'comment': ' List soa of %s first seen %s' % + (domain, + results['current_dns']['soa']['first_seen']) + }) + + return r, status_ok + + +def expand_subdomains(api, domain): + r = [] + status_ok = False + + try: + results = api.subdomains(domain) + + if results: + status_ok = True + if 'subdomains' in results: + r.append({ + 'types': ['domain'], + 'values': ['%s.%s' % (sub, domain) + for sub in results['subdomains']], + 'categories': ['Network activity'], + 'comment': 'subdomains of %s' % domain + } + + ) + except APIError as e: + misperrors['error'] = e.value + return [], False + + return r, status_ok + + +def expand_whois(api, domain): + r = [] + status_ok = False + + try: + results = api.whois(domain) + + if results: + status_ok = True + item_registrant = __select_registrant_item(results) + if item_registrant: + + if 'email' in item_registrant[0]: + r.append( + { + 'types': ['whois-registrant-email'], + 'values': [item_registrant[0]['email']], + 'categories': ['Attribution'], + 'comment': 'Whois information of %s by securitytrails' + % domain + } + ) + + if 'telephone' in item_registrant[0]: + r.append( + { + 'types': ['whois-registrant-phone'], + 'values': [item_registrant[0]['telephone']], + 'categories': ['Attribution'], + 'comment': 'Whois information of %s by securitytrails' + % domain + } + ) + + if 'name' in item_registrant[0]: + r.append( + { + 'types': ['whois-registrant-name'], + 'values': [item_registrant[0]['name']], + 'categories': ['Attribution'], + 'comment': 'Whois information of %s by securitytrails' + % domain + } + ) + + if 'registrarName' in item_registrant[0]: + r.append( + { + 'types': ['whois-registrar'], + 'values': [item_registrant[0]['registrarName']], + 'categories': ['Attribution'], + 'comment': 'Whois information of %s by securitytrails' + % domain + } + ) + + if 'createdDate' in item_registrant[0]: + r.append( + { + 'types': ['whois-creation-date'], + 'values': [item_registrant[0]['createdDate']], + 'categories': ['Attribution'], + 'comment': 'Whois information of %s by securitytrails' + % domain + } + ) + + except APIError as e: + misperrors['error'] = e.value + return [], False + + return r, status_ok + + +def expand_history_ipv4_ipv6(api, domain): + r = [] + status_ok = False + + try: + results = api.history_dns_ipv4(domain) + + if results: + status_ok = True + r.extend(__history_ip(results, domain)) + + time.sleep(1) + results = api.history_dns_aaaa(domain) + + if results: + status_ok = True + r.extend(__history_ip(results, domain, type_ip='ipv6')) + + except APIError as e: + misperrors['error'] = e.value + return [], False + + return r, status_ok + + +def expand_history_dns(api, domain): + r = [] + status_ok = False + + try: + + results = api.history_dns_ns(domain) + if results: + r.extend(__history_dns(results, domain, 'nameserver', 'ns')) + + time.sleep(1) + + results = api.history_dns_soa(domain) + + if results: + r.extend(__history_dns(results, domain, 'email', 'soa')) + + time.sleep(1) + + results = api.history_dns_mx(domain) + + if results: + status_ok = True + r.extend(__history_dns(results, domain, 'host', 'mx')) + + except APIError as e: + misperrors['error'] = e.value + return [], False + + status_ok = True + + return r, status_ok + + +def expand_history_whois(api, domain): + r = [] + status_ok = False + try: + results = api.history_whois(domain) + + if results: + + if 'items' in results['result']: + for item in results['result']['items']: + item_registrant = __select_registrant_item(item) + + r.append( + { + 'types': ['domain'], + 'values': item['nameServers'], + 'categories': ['Network activity'], + 'comment': 'Whois history Name Servers of %s ' + 'Status: %s ' % ( + domain, ' '.join(item['status'])) + + } + ) + if item_registrant: + + if 'email' in item_registrant[0]: + r.append( + { + 'types': ['whois-registrant-email'], + 'values': [item_registrant[0]['email']], + 'categories': ['Attribution'], + 'comment': 'Whois history registrant email of %s' + 'Status: %s' % ( + domain, + ' '.join(item['status'])) + } + ) + + if 'telephone' in item_registrant[0]: + r.append( + { + 'types': ['whois-registrant-phone'], + 'values': [item_registrant[0]['telephone']], + 'categories': ['Attribution'], + 'comment': 'Whois history registrant phone of %s' + 'Status: %s' % ( + domain, + ' '.join(item['status'])) + } + ) + + except APIError as e: + misperrors['error'] = e.value + return [], False + status_ok = True + + return r, status_ok + + +def __history_ip(results, domain, type_ip='ip'): + r = [] + if 'records' in results: + for record in results['records']: + if 'values' in record: + for item in record['values']: + r.append( + {'types': ['domain|ip'], + 'values': ['%s|%s' % (domain, item[type_ip])], + 'categories': ['Network activity'], + 'comment': 'History IP on securitytrails %s ' + 'last seen: %s first seen: %s' % + (domain, record['last_seen'], + record['first_seen']) + } + ) + + return r + + +def __history_dns(results, domain, type_serv, service): + r = [] + + if 'records' in results: + for record in results['records']: + if 'values' in record: + values = record['values'] + if type(values) is list: + + for item in record['values']: + r.append( + {'types': ['domain|ip'], + 'values': [item[type_serv]], + 'categories': ['Network activity'], + 'comment': 'history %s of %s last seen: %s first seen: %s' % + (service, domain, record['last_seen'], + record['first_seen']) + } + ) + else: + r.append( + {'types': ['domain|ip'], + 'values': [values[type_serv]], + 'categories': ['Network activity'], + 'comment': 'history %s of %s last seen: %s first seen: %s' % + (service, domain, record['last_seen'], + record['first_seen']) + } + ) + return r + + +def expand_searching_domain(api, ip): + r = [] + status_ok = False + + try: + results = api.searching_domains(ipv4=ip) + + if results: + if 'records' in results: + res = [(r['host_provider'], r['hostname'], r['whois']) + for r in results['records']] + + for host_provider, hostname, whois in res: + comment = 'domain for %s by %s' % (ip, host_provider[0]) + if whois['registrar']: + comment = comment + ' registrar %s' % whois['registrar'] + + r.append( + { + 'types': ['domain'], + 'category': ['Network activity'], + 'values': [hostname], + 'comment': comment + + } + ) + status_ok = True + except APIError as e: + misperrors['error'] = e.value + return [], False + + return r, status_ok + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo + + +def __select_registrant_item(entry): + res = None + if 'contacts' in entry: + res = list(filter(lambda x: x['type'] == 'registrant', + entry['contacts'])) + + if 'contact' in entry: + res = list(filter(lambda x: x['type'] == 'registrant', + entry['contact'])) + + return res diff --git a/misp_modules/modules/expansion/sigma_queries.py b/misp_modules/modules/expansion/sigma_queries.py new file mode 100644 index 00000000..7799f2a4 --- /dev/null +++ b/misp_modules/modules/expansion/sigma_queries.py @@ -0,0 +1,56 @@ +import sys +import io +import json +try: + from sigma.parser.collection import SigmaCollectionParser + from sigma.configuration import SigmaConfiguration + from sigma.backends.base import BackendOptions + from sigma.backends.discovery import getBackend +except ImportError: + print("sigma or yaml is missing, use 'pip3 install sigmatools' to install it.") + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['sigma'], 'output': ['text']} +moduleinfo = {'version': '0.1', 'author': 'Christian Studer', 'module-type': ['expansion', 'hover'], + 'description': 'An expansion hover module to display the result of sigma queries.'} +moduleconfig = [] +sigma_targets = ('es-dsl', 'es-qs', 'graylog', 'kibana', 'xpack-watcher', 'logpoint', 'splunk', 'grep', 'wdatp', 'splunkxml', 'arcsight', 'qualys') + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + if not request.get('sigma'): + misperrors['error'] = 'Sigma rule missing' + return misperrors + config = SigmaConfiguration() + backend_options = BackendOptions(None) + f = io.TextIOWrapper(io.BytesIO(request.get('sigma').encode()), encoding='utf-8') + parser = SigmaCollectionParser(f, config, None) + targets = [] + old_stdout = sys.stdout + result = io.StringIO() + sys.stdout = result + for t in sigma_targets: + backend = getBackend(t)(config, backend_options, None) + try: + parser.generate(backend) + backend.finalize() + print("#NEXT") + targets.append(t) + except Exception: + continue + sys.stdout = old_stdout + results = result.getvalue()[:-5].split('#NEXT') + d_result = {t: r.strip() for t, r in zip(targets, results)} + return {'results': [{'types': mispattributes['output'], 'values': d_result}]} + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/sigma_syntax_validator.py b/misp_modules/modules/expansion/sigma_syntax_validator.py new file mode 100644 index 00000000..658b4d3f --- /dev/null +++ b/misp_modules/modules/expansion/sigma_syntax_validator.py @@ -0,0 +1,38 @@ +import json +try: + import yaml + from sigma.parser.rule import SigmaParser + from sigma.configuration import SigmaConfiguration +except ImportError: + print("sigma or yaml is missing, use 'pip3 install sigmatools' to install it.") + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['sigma'], 'output': ['text']} +moduleinfo = {'version': '0.1', 'author': 'Christian Studer', 'module-type': ['expansion', 'hover'], + 'description': 'An expansion hover module to perform a syntax check on sigma rules'} +moduleconfig = [] + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + if not request.get('sigma'): + misperrors['error'] = 'Sigma rule missing' + return misperrors + config = SigmaConfiguration() + try: + parser = SigmaParser(yaml.safe_load(request.get('sigma')), config) + result = ("Syntax valid: {}".format(parser.values)) + except Exception as e: + result = ("Syntax error: {}".format(str(e))) + return {'results': [{'types': mispattributes['output'], 'values': result}]} + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/stix2_pattern_syntax_validator.py b/misp_modules/modules/expansion/stix2_pattern_syntax_validator.py new file mode 100644 index 00000000..b87ab839 --- /dev/null +++ b/misp_modules/modules/expansion/stix2_pattern_syntax_validator.py @@ -0,0 +1,45 @@ +import json +try: + from stix2patterns.validator import run_validator +except ImportError: + print("stix2 patterns python library is missing, use 'pip3 install stix2-patterns' to install it.") + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['stix2-pattern'], 'output': ['text']} +moduleinfo = {'version': '0.1', 'author': 'Christian Studer', 'module-type': ['expansion', 'hover'], + 'description': 'An expansion hover module to perform a syntax check on stix2 patterns.'} +moduleconfig = [] + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + if not request.get('stix2-pattern'): + misperrors['error'] = 'STIX2 pattern missing' + return misperrors + pattern = request.get('stix2-pattern') + syntax_errors = [] + for p in pattern[2:-2].split(' AND '): + syntax_validator = run_validator("[{}]".format(p)) + if syntax_validator: + for error in syntax_validator: + syntax_errors.append(error) + if syntax_errors: + s = 's' if len(syntax_errors) > 1 else '' + s_errors = "" + for error in syntax_errors: + s_errors += "{}\n".format(error[6:]) + result = "Syntax error{}: \n{}".format(s, s_errors[:-1]) + else: + result = "Syntax valid" + return {'results': [{'types': mispattributes['output'], 'values': result}]} + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/threatcrowd.py b/misp_modules/modules/expansion/threatcrowd.py index 9187ca5b..268832fc 100644 --- a/misp_modules/modules/expansion/threatcrowd.py +++ b/misp_modules/modules/expansion/threatcrowd.py @@ -17,7 +17,7 @@ moduleconfig = [] # Avoid adding windows update to enrichment etc. def isBlacklisted(value): - blacklist = ['8.8.8.8', '255.255.255.255', '192.168.56.' , 'time.windows.com'] + blacklist = ['8.8.8.8', '255.255.255.255', '192.168.56.', 'time.windows.com'] for b in blacklist: if value in b: @@ -25,28 +25,31 @@ def isBlacklisted(value): return False + def valid_ip(ip): m = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip) return bool(m) and all(map(lambda n: 0 <= int(n) <= 255, m.groups())) + def valid_domain(hostname): if len(hostname) > 255: return False if hostname[-1] == ".": - hostname = hostname[:-1] # strip exactly one dot from the right, if present - allowed = re.compile("(?!-)[A-Z\d-]{1,63}(? stats > malicious') + threat_list = set() + + if 'matches' in result['meta']['processors']['gsb']['data']: + for item in result['meta']['processors']['gsb']['data']['matches']: + if item['threatType']: + threat_list.add(item['threatType']) + + threat_list = ', '.join(threat_list) + log.debug('threat_list values are: \'' + threat_list + '\'') + + if threat_list: + misp_val = '{} threat(s) detected'.format(threat_list) + r.append({'types': 'text', + 'categories': ['External analysis'], + 'values': misp_val, + 'comment': misp_comment}) + + if result.get('lists'): + if result['lists'].get('urls'): + for url in result['lists']['urls']: + url = url.lower() + if 'office' in url: + misp_val = "Possible Office-themed phishing" + elif 'o365' in url or '0365' in url: + misp_val = "Possible O365-themed phishing" + elif 'microsoft' in url: + misp_val = "Possible Microsoft-themed phishing" + elif 'paypal' in url: + misp_val = "Possible PayPal-themed phishing" + elif 'onedrive' in url: + misp_val = "Possible OneDrive-themed phishing" + elif 'docusign' in url: + misp_val = "Possible DocuSign-themed phishing" + r.append({'types': 'text', + 'categories': ['External analysis'], + 'values': misp_val, + 'comment': misp_comment}) + + if result.get('task'): + if result['task'].get('reportURL'): + misp_val = result['task']['reportURL'] + r.append({'types': 'link', + 'categories': ['External analysis'], + 'values': misp_val, + 'comment': misp_comment}) + + if result['task'].get('screenshotURL'): + image_url = result['task']['screenshotURL'] + r.append({'types': 'link', + 'categories': ['External analysis'], + 'values': image_url, + 'comment': misp_comment}) + # ## TO DO ### + # ## Add ability to add an in-line screenshot of the target website into an attribute + # screenshot = requests.get(image_url).content + # r.append({'types': ['attachment'], + # 'categories': ['External analysis'], + # 'values': image_url, + # 'image': str(base64.b64encode(screenshot), 'utf-8'), + # 'comment': 'Screenshot of website'}) + + return r + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo + + +class urlscanAPI(): + def __init__(self, apikey=None, uuid=None): + self.key = apikey + self.uuid = uuid + + def request(self, query): + log.debug('From request function with the parameter: ' + query) + payload = {'url': query} + headers = {'API-Key': self.key, + 'Content-Type': "application/json", + 'Cache-Control': "no-cache"} + + # Troubleshooting problems with initial search request + log.debug('PAYLOAD: ' + json.dumps(payload)) + log.debug('HEADERS: ' + json.dumps(headers)) + + search_url_string = "https://urlscan.io/api/v1/scan/" + response = requests.request("POST", + search_url_string, + data=json.dumps(payload), + headers=headers) + + # HTTP 400 - Bad Request + if response.status_code == 400: + raise Exception('HTTP Error 400 - Bad Request') + + # HTTP 404 - Not found + if response.status_code == 404: + raise Exception('HTTP Error 404 - These are not the droids you\'re looking for') + + # Any other status code + if response.status_code != 200: + raise Exception('HTTP Error ' + str(response.status_code)) + + if response.text: + response = json.loads(response.content.decode("utf-8")) + time.sleep(3) + self.uuid = response['uuid'] + + # Strings for to check for errors on the results page + # Null response string for any unavailable resources + null_response_string = '"status": 404' + # Redirect string accounting for 301/302/303/307/308 status codes + redirect_string = '"status": 30' + # Normal response string with 200 status code + normal_response_string = '"status": 200' + + results_url_string = "https://urlscan.io/api/v1/result/" + self.uuid + log.debug('Results URL: ' + results_url_string) + + # Need to wait for results to process and check if they are valid + tries = 10 + while tries >= 0: + results = requests.request("GET", results_url_string) + log.debug('Made a GET request') + results = results.content.decode("utf-8") + # checking if there is a 404 status code and no available resources + if null_response_string in results and \ + redirect_string not in results and \ + normal_response_string not in results: + log.debug('Results not processed. Please check again later.') + time.sleep(3) + tries -= 1 + else: + return json.loads(results) + + raise Exception('Results contained a 404 status error and could not be processed.') + + def search_url(self, query): + log.debug('From search_url with parameter: ' + query) + return self.request(query) diff --git a/misp_modules/modules/expansion/virustotal.py b/misp_modules/modules/expansion/virustotal.py old mode 100755 new mode 100644 index 3997ee6c..65623fba --- a/misp_modules/modules/expansion/virustotal.py +++ b/misp_modules/modules/expansion/virustotal.py @@ -2,195 +2,166 @@ import json import requests from requests import HTTPError import base64 +from collections import defaultdict misperrors = {'error': 'Error'} mispattributes = {'input': ['hostname', 'domain', "ip-src", "ip-dst", "md5", "sha1", "sha256", "sha512"], 'output': ['domain', "ip-src", "ip-dst", "text", "md5", "sha1", "sha256", "sha512", "ssdeep", - "authentihash", "filename"] - } + "authentihash", "filename"]} # possible module-types: 'expansion', 'hover' or both -moduleinfo = {'version': '2', 'author': 'Hannah Ward', +moduleinfo = {'version': '3', 'author': 'Hannah Ward', 'description': 'Get information from virustotal', 'module-type': ['expansion']} # config fields that your code expects from the site admin moduleconfig = ["apikey", "event_limit"] -limit = 5 # Default -comment = '%s: Enriched via VT' +comment = '{}: Enriched via VirusTotal' +hash_types = ["md5", "sha1", "sha256", "sha512"] + + +class VirusTotalRequest(object): + def __init__(self, config): + self.apikey = config['apikey'] + self.limit = int(config.get('event_limit', 5)) + self.base_url = "https://www.virustotal.com/vtapi/v2/{}/report" + self.results = defaultdict(set) + self.to_return = [] + self.input_types_mapping = {'ip-src': self.get_ip, 'ip-dst': self.get_ip, + 'domain': self.get_domain, 'hostname': self.get_domain, + 'md5': self.get_hash, 'sha1': self.get_hash, + 'sha256': self.get_hash, 'sha512': self.get_hash} + self.output_types_mapping = {'submission_names': 'filename', 'ssdeep': 'ssdeep', + 'authentihash': 'authentihash', 'ITW_urls': 'url'} + + def parse_request(self, q): + req_values = set() + for attribute_type, attribute_value in q.items(): + req_values.add(attribute_value) + try: + error = self.input_types_mapping[attribute_type](attribute_value) + except KeyError: + continue + if error is not None: + return error + for key, values in self.results.items(): + values = values.difference(req_values) + if values: + if isinstance(key, tuple): + types, comment = key + self.to_return.append({'types': list(types), 'values': list(values), 'comment': comment}) + else: + self.to_return.append({'types': key, 'values': list(values)}) + return self.to_return + + def get_domain(self, domain, do_not_recurse=False): + req = requests.get(self.base_url.format('domain'), params={'domain': domain, 'apikey': self.apikey}) + try: + req.raise_for_status() + req = req.json() + except HTTPError as e: + return str(e) + if req["response_code"] == 0: + # Nothing found + return [] + if "resolutions" in req: + for res in req["resolutions"][:self.limit]: + ip_address = res["ip_address"] + self.results[(("ip-dst", "ip-src"), comment.format(domain))].add(ip_address) + # Pivot from here to find all domain info + if not do_not_recurse: + error = self.get_ip(ip_address, True) + if error is not None: + return error + self.get_more_info(req) + + def get_hash(self, _hash): + req = requests.get(self.base_url.format('file'), params={'resource': _hash, 'apikey': self.apikey, 'allinfo': 1}) + try: + req.raise_for_status() + req = req.json() + except HTTPError as e: + return str(e) + if req["response_code"] == 0: + # Nothing found + return [] + self.get_more_info(req) + + def get_ip(self, ip, do_not_recurse=False): + req = requests.get(self.base_url.format('ip-address'), params={'ip': ip, 'apikey': self.apikey}) + try: + req.raise_for_status() + req = req.json() + except HTTPError as e: + return str(e) + if req["response_code"] == 0: + # Nothing found + return [] + if "resolutions" in req: + for res in req["resolutions"][:self.limit]: + hostname = res["hostname"] + self.results[(("domain",), comment.format(ip))].add(hostname) + # Pivot from here to find all domain info + if not do_not_recurse: + error = self.get_domain(hostname, True) + if error is not None: + return error + self.get_more_info(req) + + def find_all(self, data): + hashes = [] + if isinstance(data, dict): + for key, value in data.items(): + if key in hash_types: + self.results[key].add(value) + hashes.append(value) + else: + if isinstance(value, (dict, list)): + hashes.extend(self.find_all(value)) + elif isinstance(data, list): + for d in data: + hashes.extend(self.find_all(d)) + return hashes + + def get_more_info(self, req): + # Get all hashes first + hashes = self.find_all(req) + for h in hashes[:self.limit]: + # Search VT for some juicy info + try: + data = requests.get(self.base_url.format('file'), params={'resource': h, 'apikey': self.apikey, 'allinfo': 1}).json() + except Exception: + continue + # Go through euch key and check if it exists + for VT_type, MISP_type in self.output_types_mapping.items(): + if VT_type in data: + try: + self.results[((MISP_type,), comment.format(h))].add(data[VT_type]) + except TypeError: + self.results[((MISP_type,), comment.format(h))].update(data[VT_type]) + # Get the malware sample + sample = requests.get(self.base_url[:-6].format('file/download'), params={'hash': h, 'apikey': self.apikey}) + malsample = sample.content + # It is possible for VT to not give us any submission names + if "submission_names" in data: + self.to_return.append({"types": ["malware-sample"], "categories": ["Payload delivery"], + "values": data["submimssion_names"], "data": str(base64.b64encore(malsample), 'utf-8')}) def handler(q=False): - global limit if q is False: return False - q = json.loads(q) - - key = q["config"]["apikey"] - limit = int(q["config"].get("event_limit", 5)) - - r = {"results": []} - - if "ip-src" in q: - r["results"] += getIP(q["ip-src"], key) - if "ip-dst" in q: - r["results"] += getIP(q["ip-dst"], key) - if "domain" in q: - r["results"] += getDomain(q["domain"], key) - if 'hostname' in q: - r["results"] += getDomain(q['hostname'], key) - if 'md5' in q: - r["results"] += getHash(q['md5'], key) - if 'sha1' in q: - r["results"] += getHash(q['sha1'], key) - if 'sha256' in q: - r["results"] += getHash(q['sha256'], key) - if 'sha512' in q: - r["results"] += getHash(q['sha512'], key) - - uniq = [] - for res in r["results"]: - if res not in uniq: - uniq.append(res) - r["results"] = uniq - return r - - -def getHash(hash, key, do_not_recurse=False): - req = requests.get("https://www.virustotal.com/vtapi/v2/file/report", - params={"allinfo": 1, "apikey": key, 'resource': hash}) - try: - req.raise_for_status() - req = req.json() - except HTTPError as e: - misperrors['error'] = str(e) + if not q.get('config') or not q['config'].get('apikey'): + misperrors['error'] = "A VirusTotal api key is required for this module." return misperrors - - if req["response_code"] == 0: - # Nothing found - return [] - - return getMoreInfo(req, key) - - -def getIP(ip, key, do_not_recurse=False): - global limit - toReturn = [] - req = requests.get("https://www.virustotal.com/vtapi/v2/ip-address/report", - params={"ip": ip, "apikey": key}) - try: - req.raise_for_status() - req = req.json() - except HTTPError as e: - misperrors['error'] = str(e) + del q['module'] + query = VirusTotalRequest(q.pop('config')) + r = query.parse_request(q) + if isinstance(r, str): + misperrors['error'] = r return misperrors - - if req["response_code"] == 0: - # Nothing found - return [] - - if "resolutions" in req: - for res in req["resolutions"][:limit]: - toReturn.append({"types": ["domain"], "values": [res["hostname"]], "comment": comment % ip}) - # Pivot from here to find all domain info - if not do_not_recurse: - toReturn += getDomain(res["hostname"], key, True) - - toReturn += getMoreInfo(req, key) - return toReturn - - -def getDomain(domain, key, do_not_recurse=False): - global limit - toReturn = [] - req = requests.get("https://www.virustotal.com/vtapi/v2/domain/report", - params={"domain": domain, "apikey": key}) - try: - req.raise_for_status() - req = req.json() - except HTTPError as e: - misperrors['error'] = str(e) - return misperrors - - if req["response_code"] == 0: - # Nothing found - return [] - - if "resolutions" in req: - for res in req["resolutions"][:limit]: - toReturn.append({"types": ["ip-dst", "ip-src"], "values": [res["ip_address"]], "comment": comment % domain}) - # Pivot from here to find all info on IPs - if not do_not_recurse: - toReturn += getIP(res["ip_address"], key, True) - if "subdomains" in req: - for subd in req["subdomains"]: - toReturn.append({"types": ["domain"], "values": [subd], "comment": comment % domain}) - toReturn += getMoreInfo(req, key) - return toReturn - - -def findAll(data, keys): - a = [] - if isinstance(data, dict): - for key in data.keys(): - if key in keys: - a.append(data[key]) - else: - if isinstance(data[key], (dict, list)): - a += findAll(data[key], keys) - if isinstance(data, list): - for i in data: - a += findAll(i, keys) - - return a - - -def getMoreInfo(req, key): - global limit - r = [] - # Get all hashes first - hashes = [] - hashes = findAll(req, ["md5", "sha1", "sha256", "sha512"]) - r.append({"types": ["freetext"], "values": hashes}) - for hsh in hashes[:limit]: - # Search VT for some juicy info - try: - data = requests.get("http://www.virustotal.com/vtapi/v2/file/report", - params={"allinfo": 1, "apikey": key, "resource": hsh} - ).json() - except: - continue - - # Go through each key and check if it exists - if "submission_names" in data: - r.append({'types': ["filename"], "values": data["submission_names"], "comment": comment % hsh}) - - if "ssdeep" in data: - r.append({'types': ["ssdeep"], "values": [data["ssdeep"]], "comment": comment % hsh}) - - if "authentihash" in data: - r.append({"types": ["authentihash"], "values": [data["authentihash"]], "comment": comment % hsh}) - - if "ITW_urls" in data: - r.append({"types": ["url"], "values": data["ITW_urls"], "comment": comment % hsh}) - - # Get the malware sample - sample = requests.get("https://www.virustotal.com/vtapi/v2/file/download", - params={"hash": hsh, "apikey": key}) - - malsample = sample.content - - # It is possible for VT to not give us any submission names - if "submission_names" in data: - r.append({"types": ["malware-sample"], - "categories": ["Payload delivery"], - "values": data["submission_names"], - "data": str(base64.b64encode(malsample), 'utf-8') - } - ) - - return r + return {'results': r} def introspection(): diff --git a/misp_modules/modules/expansion/vmray_submit.py b/misp_modules/modules/expansion/vmray_submit.py index 15b163b8..062c21f0 100644 --- a/misp_modules/modules/expansion/vmray_submit.py +++ b/misp_modules/modules/expansion/vmray_submit.py @@ -40,12 +40,12 @@ def handler(q=False): data = request.get("data") if 'malware-sample' in request: # malicious samples are encrypted with zip (password infected) and then base64 encoded - sample_filename = request.get("malware-sample").split("|",1)[0] + sample_filename = request.get("malware-sample").split("|", 1)[0] data = base64.b64decode(data) fl = io.BytesIO(data) zf = zipfile.ZipFile(fl) sample_hashname = zf.namelist()[0] - data = zf.read(sample_hashname,b"infected") + data = zf.read(sample_hashname, b"infected") zf.close() elif 'attachment' in request: # All attachments get base64 encoded @@ -55,7 +55,7 @@ def handler(q=False): else: misperrors['error'] = "No malware sample or attachment supplied" return misperrors - except: + except Exception: misperrors['error'] = "Unable to process submited sample data" return misperrors @@ -102,7 +102,7 @@ def handler(q=False): return misperrors else: return vmrayProcess(vmraydata) - except: + except Exception: misperrors['error'] = "Problem when calling API." return misperrors else: @@ -148,7 +148,7 @@ def vmrayProcess(vmraydata): else: misperrors['error'] = "No valid results returned." return misperrors - except: + except Exception: misperrors['error'] = "No valid submission data returned." return misperrors else: diff --git a/misp_modules/modules/expansion/vulndb.py b/misp_modules/modules/expansion/vulndb.py index 64761996..db6c4619 100644 --- a/misp_modules/modules/expansion/vulndb.py +++ b/misp_modules/modules/expansion/vulndb.py @@ -24,8 +24,8 @@ log.addHandler(ch) misperrors = {'error': 'Error'} mispattributes = { - 'input': ['vulnerability'], - 'output': ['text', 'link', 'cpe']} + 'input': ['vulnerability'], + 'output': ['text', 'link', 'cpe']} moduleinfo = {'version': '0.1', 'author': 'Koen Van Impe', 'description': 'Query VulnDB - RiskBasedSecurity.com', 'module-type': ['expansion', 'hover']} @@ -61,7 +61,7 @@ def handler(q=False): add_dates = True add_ext_references = True - if request["config"].get("discard_dates") is not None and request["config"].get("discard_dates").lower() == "true": + if request["config"].get("discard_dates") is not None and request["config"].get("discard_dates").lower() == "true": add_dates = False if request["config"].get("discard_external_references") is not None and request["config"].get("discard_external_references").lower() == "true": add_ext_references = False @@ -80,7 +80,7 @@ def handler(q=False): find_by_cve_url = "%s/api/v1/vulnerabilities/%s/find_by_cve_id%s" % (VULNDB_URL, vulnerability, cpu_vulndb) log.debug(find_by_cve_url) - + try: consumer = oauth.Consumer(key=apikey, secret=apisecret) @@ -116,7 +116,7 @@ def handler(q=False): if t_description: values_text.append(t_description) if manual_notes: - values_text.append("Notes: " + manual_notes) + values_text.append("Notes: " + manual_notes) if keywords: values_text.append("Keywords: " + keywords) if solution: @@ -130,22 +130,22 @@ def handler(q=False): values_text.append("Solution date: " + solution_date) disclosure_date = results.get('disclosure_date', '') or '' if disclosure_date: - values_text.append("Disclosure date: " + disclosure_date) + values_text.append("Disclosure date: " + disclosure_date) discovery_date = results.get('discovery_date', '') or '' if discovery_date: - values_text.append("Discovery date: " + discovery_date) + values_text.append("Discovery date: " + discovery_date) exploit_publish_date = results.get('exploit_publish_date', '') or '' if exploit_publish_date: - values_text.append("Exploit published date: " + exploit_publish_date) + values_text.append("Exploit published date: " + exploit_publish_date) vendor_informed_date = results.get('vendor_informed_date', '') or '' if vendor_informed_date: - values_text.append("Vendor informed date: " + vendor_informed_date) + values_text.append("Vendor informed date: " + vendor_informed_date) vendor_ack_date = results.get('vendor_ack_date', '') or '' if vendor_ack_date: - values_text.append("Vendor acknowledgement date: " + vendor_ack_date) + values_text.append("Vendor acknowledgement date: " + vendor_ack_date) third_party_solution_date = results.get('third_party_solution_date', '') or '' if third_party_solution_date: - values_text.append("Third party solution date: " + third_party_solution_date) + values_text.append("Third party solution date: " + third_party_solution_date) # External references if add_ext_references: @@ -159,7 +159,7 @@ def handler(q=False): elif reference_type == "News Article": values_links.append(reference["value"]) elif reference_type == "Generic Informational URL": - values_links.append(reference["value"]) + values_links.append(reference["value"]) elif reference_type == "Vendor Specific Advisory URL": values_links.append(reference["value"]) elif reference_type == "Vendor URL": @@ -183,7 +183,7 @@ def handler(q=False): values_links.append(reference_link) elif reference_type == "Exploit Database": reference_link = "https://www.exploit-db.com/exploits/%s" % reference["value"] - values_links.append(reference_link) + values_links.append(reference_link) elif reference_type == "Generic Informational URL": values_links.append(reference["value"]) elif reference_type == "Generic Informational URL": @@ -260,17 +260,17 @@ def handler(q=False): values_text.append(vulnerability_classification) # Finished processing the VulnDB reply; set the result for MISP - output['results'] += [{'types': 'text', 'values': values_text }] - output['results'] += [{'types': 'link', 'values': values_links }] + output['results'] += [{'types': 'text', 'values': values_text}] + output['results'] += [{'types': 'link', 'values': values_links}] if add_cpe: - output['results'] += [{'types': 'cpe', 'values': values_cpe }] + output['results'] += [{'types': 'cpe', 'values': values_cpe}] return output else: misperrors["error"] = "No information retrieved from VulnDB." return misperrors - except: + except Exception: misperrors["error"] = "Error while fetching information from VulnDB, wrong API keys?" - return misperrors + return misperrors def introspection(): diff --git a/misp_modules/modules/expansion/vulners.py b/misp_modules/modules/expansion/vulners.py new file mode 100644 index 00000000..557fdb61 --- /dev/null +++ b/misp_modules/modules/expansion/vulners.py @@ -0,0 +1,64 @@ +import json +import vulners + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['vulnerability'], 'output': ['text']} +moduleinfo = {'version': '0.1', 'author': 'Igor Ivanov', 'description': 'An expansion hover module to expand information about CVE id using Vulners API.', 'module-type': ['hover']} + +# Get API key from https://vulners.com/userinfo +moduleconfig = ["apikey"] + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + if not request.get('vulnerability'): + misperrors['error'] = 'Vulnerability id missing' + return misperrors + + ai_summary = '' + exploit_summary = '' + vuln_summary = '' + + key = request['config'].get('apikey') + vulners_api = vulners.Vulners(api_key=key) + vulnerability = request.get('vulnerability') + vulners_document = vulners_api.document(vulnerability) + + # Get AI scoring from the document if it's already calculated + # There is no need to call AI Scoring method + if 'score' in vulners_document.get('enchantments', {}): + vulners_ai_score = vulners_document['enchantments']['score']['value'] + else: + vulners_ai_score = None + + vulners_exploits = vulners_api.searchExploit(vulnerability) + + if vulners_document: + vuln_summary += vulners_document.get('description') + else: + vuln_summary += 'Non existing CVE' + + if vulners_ai_score: + ai_summary += 'Vulners AI Score is ' + str(vulners_ai_score[0]) + " " + + if vulners_exploits: + exploit_summary += " || " + str(len(vulners_exploits[0])) + " Public exploits available:\n " + for exploit in vulners_exploits[0]: + exploit_summary += exploit['title'] + " " + exploit['href'] + "\n " + exploit_summary += "|| Vulnerability Description: " + vuln_summary + + summary = ai_summary + exploit_summary + vuln_summary + + r = {'results': [{'types': mispattributes['output'], 'values': summary}]} + return r + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/wiki.py b/misp_modules/modules/expansion/wiki.py index 85279b11..f5d7933e 100755 --- a/misp_modules/modules/expansion/wiki.py +++ b/misp_modules/modules/expansion/wiki.py @@ -1,5 +1,4 @@ import json -import requests from SPARQLWrapper import SPARQLWrapper, JSON misperrors = {'error': 'Error'} @@ -17,17 +16,17 @@ def handler(q=False): if not request.get('text'): misperrors['error'] = 'Query text missing' return misperrors - + sparql = SPARQLWrapper(wiki_api_url) query_string = \ - "SELECT ?item \n" \ - "WHERE { \n" \ - "?item rdfs:label\"" + request.get('text') + "\" @en \n" \ - "}\n"; + "SELECT ?item \n" \ + "WHERE { \n" \ + "?item rdfs:label\"" + request.get('text') + "\" @en \n" \ + "}\n" sparql.setQuery(query_string) sparql.setReturnFormat(JSON) results = sparql.query().convert() - + summary = '' try: result = results["results"]["bindings"][0] @@ -47,4 +46,3 @@ def introspection(): def version(): moduleinfo['config'] = moduleconfig return moduleinfo - diff --git a/misp_modules/modules/expansion/xforceexchange.py b/misp_modules/modules/expansion/xforceexchange.py index 459c69ad..6bb71268 100644 --- a/misp_modules/modules/expansion/xforceexchange.py +++ b/misp_modules/modules/expansion/xforceexchange.py @@ -1,101 +1,104 @@ -import requests -import json -import sys - -BASEurl = "https://api.xforce.ibmcloud.com/" - -extensions = {"ip1": "ipr/%s", - "ip2": "ipr/malware/%s", - "url": "url/%s", - "hash": "malware/%s", - "vuln": "/vulnerabilities/search/%s", - "dns": "resolve/%s"} - -sys.path.append('./') - -misperrors = {'error': 'Error'} -mispattributes = {'input': ['ip-src','ip-dst' 'vulnerability', 'md5', 'sha1', 'sha256'], - 'output': ['ip-src', 'ip-dst', 'text', 'domain']} - -# possible module-types: 'expansion', 'hover' or both -moduleinfo = {'version': '1', 'author': 'Joerg Stephan (@johest)', - 'description': 'IBM X-Force Exchange expansion module', - 'module-type': ['expansion', 'hover']} - -# config fields that your code expects from the site admin -moduleconfig = ["apikey", "event_limit"] -limit = 5000 #Default - - - -def MyHeader(key=False): - global limit - if key is False: - return None - - return {"Authorization": "Basic %s " % key, - "Accept": "application/json", - 'User-Agent': 'Mozilla 5.0'} - -def handler(q=False): - global limit - if q is False: - return False - - q = json.loads(q) - - key = q["config"]["apikey"] - limit = int(q["config"].get("event_limit", 5)) - - r = {"results": []} - - if "ip-src" in q: - r["results"] += apicall("dns", q["ip-src"], key) - if "ip-dst" in q: - r["results"] += apicall("dns", q["ip-dst"], key) - if "md5" in q: - r["results"] += apicall("hash", q["md5"], key) - if "sha1" in q: - r["results"] += apicall("hash", q["sha1"], key) - if "sha256" in q: - r["results"] += apicall("hash", q["sha256"], key) - if 'vulnerability' in q: - r["results"] += apicall("vuln", q["vulnerability"], key) - if "domain" in q: - r["results"] += apicall("dns", q["domain"], key) - - uniq = [] - for res in r["results"]: - if res not in uniq: - uniq.append(res) - r["results"] = uniq - return r - -def apicall(indicator_type, indicator, key=False): - try: - myURL = BASEurl + (extensions[str(indicator_type)])%indicator - jsondata = requests.get(myURL, headers=MyHeader(key)).json() - except: - jsondata = None - redata = [] - #print(jsondata) - if not jsondata is None: - if indicator_type is "hash": - if "malware" in jsondata: - lopointer = jsondata["malware"] - redata.append({"type": "text", "values": lopointer["risk"]}) - if indicator_type is "dns": - if "records" in str(jsondata): - lopointer = jsondata["Passive"]["records"] - for dataset in lopointer: - redata.append({"type":"domain", "values": dataset["value"]}) - - return redata - -def introspection(): - return mispattributes - - -def version(): - moduleinfo['config'] = moduleconfig - return moduleinfo +import requests +import json +import sys + +BASEurl = "https://api.xforce.ibmcloud.com/" + +extensions = {"ip1": "ipr/%s", + "ip2": "ipr/malware/%s", + "url": "url/%s", + "hash": "malware/%s", + "vuln": "/vulnerabilities/search/%s", + "dns": "resolve/%s"} + +sys.path.append('./') + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['ip-src', 'ip-dst', 'vulnerability', 'md5', 'sha1', 'sha256'], + 'output': ['ip-src', 'ip-dst', 'text', 'domain']} + +# possible module-types: 'expansion', 'hover' or both +moduleinfo = {'version': '1', 'author': 'Joerg Stephan (@johest)', + 'description': 'IBM X-Force Exchange expansion module', + 'module-type': ['expansion', 'hover']} + +# config fields that your code expects from the site admin +moduleconfig = ["apikey", "event_limit"] +limit = 5000 # Default + + +def MyHeader(key=False): + global limit + if key is False: + return None + + return {"Authorization": "Basic %s " % key, + "Accept": "application/json", + 'User-Agent': 'Mozilla 5.0'} + + +def handler(q=False): + global limit + if q is False: + return False + + q = json.loads(q) + + key = q["config"]["apikey"] + limit = int(q["config"].get("event_limit", 5)) + + r = {"results": []} + + if "ip-src" in q: + r["results"] += apicall("dns", q["ip-src"], key) + if "ip-dst" in q: + r["results"] += apicall("dns", q["ip-dst"], key) + if "md5" in q: + r["results"] += apicall("hash", q["md5"], key) + if "sha1" in q: + r["results"] += apicall("hash", q["sha1"], key) + if "sha256" in q: + r["results"] += apicall("hash", q["sha256"], key) + if 'vulnerability' in q: + r["results"] += apicall("vuln", q["vulnerability"], key) + if "domain" in q: + r["results"] += apicall("dns", q["domain"], key) + + uniq = [] + for res in r["results"]: + if res not in uniq: + uniq.append(res) + r["results"] = uniq + return r + + +def apicall(indicator_type, indicator, key=False): + try: + myURL = BASEurl + (extensions[str(indicator_type)]) % indicator + jsondata = requests.get(myURL, headers=MyHeader(key)).json() + except Exception: + jsondata = None + redata = [] + # print(jsondata) + if jsondata is not None: + if indicator_type == "hash": + if "malware" in jsondata: + lopointer = jsondata["malware"] + redata.append({"type": "text", "values": lopointer["risk"]}) + if indicator_type == "dns": + if "records" in str(jsondata): + lopointer = jsondata["Passive"]["records"] + for dataset in lopointer: + redata.append( + {"type": "domain", "values": dataset["value"]}) + + return redata + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/xlsx-enrich.py b/misp_modules/modules/expansion/xlsx-enrich.py new file mode 100644 index 00000000..6e0ee739 --- /dev/null +++ b/misp_modules/modules/expansion/xlsx-enrich.py @@ -0,0 +1,53 @@ +import json +import binascii +import np +import pandas +import io + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['attachment'], + 'output': ['freetext', 'text']} +moduleinfo = {'version': '0.1', 'author': 'Sascha Rommelfangen', + 'description': '.xlsx to freetext-import IOC extractor', + 'module-type': ['expansion']} + +moduleconfig = [] + + +def handler(q=False): + if q is False: + return False + q = json.loads(q) + filename = q['attachment'] + try: + xlsx_array = np.frombuffer(binascii.a2b_base64(q['data']), np.uint8) + except Exception as e: + print(e) + err = "Couldn't fetch attachment (JSON 'data' is empty). Are you using the 'Query enrichment' action?" + misperrors['error'] = err + print(err) + return misperrors + + xls_content = "" + xls_file = io.BytesIO(xlsx_array) + pandas.set_option('display.max_colwidth', -1) + try: + xls = pandas.read_excel(xls_file) + xls_content = xls.to_string(max_rows=None) + print(xls_content) + return {'results': [{'types': ['freetext'], 'values': xls_content, 'comment': ".xlsx-to-text from file " + filename}, + {'types': ['text'], 'values': xls_content, 'comment': ".xlsx-to-text from file " + filename}]} + except Exception as e: + print(e) + err = "Couldn't analyze file as .xlsx. Error was: " + str(e) + misperrors['error'] = err + return misperrors + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/yara_query.py b/misp_modules/modules/expansion/yara_query.py new file mode 100644 index 00000000..3a75acc8 --- /dev/null +++ b/misp_modules/modules/expansion/yara_query.py @@ -0,0 +1,54 @@ +import json +import re +try: + import yara +except (OSError, ImportError): + print("yara is missing, use 'pip3 install -I -r REQUIREMENTS' from the root of this repository to install it.") + +misperrors = {'error': 'Error'} +moduleinfo = {'version': '1', 'author': 'Christian STUDER', + 'description': 'Yara export for hashes.', + 'module-type': ['expansion', 'hover'], + 'require_standard_format': True} +moduleconfig = [] +mispattributes = {'input': ['md5', 'sha1', 'sha256', 'filename|md5', 'filename|sha1', 'filename|sha256', 'imphash'], 'output': ['yara']} + + +def get_hash_condition(hashtype, hashvalue): + hashvalue = hashvalue.lower() + required_module, params = ('pe', '()') if hashtype == 'imphash' else ('hash', '(0, filesize)') + return '{}.{}{} == "{}"'.format(required_module, hashtype, params, hashvalue), required_module + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + del request['module'] + if 'event_id' in request: + del request['event_id'] + uuid = request.pop('attribute_uuid') if 'attribute_uuid' in request else None + attribute_type, value = list(request.items())[0] + if 'filename' in attribute_type: + _, attribute_type = attribute_type.split('|') + _, value = value.split('|') + condition, required_module = get_hash_condition(attribute_type, value) + import_section = 'import "{}"'.format(required_module) + rule_start = '%s\r\nrule %s_%s {' % (import_section, attribute_type.upper(), re.sub(r'\W+', '_', uuid)) if uuid else '%s\r\nrule %s {' % (import_section, attribute_type.upper()) + condition = '\tcondition:\r\n\t\t{}'.format(condition) + rule = '\r\n'.join([rule_start, condition, '}']) + try: + yara.compile(source=rule) + except Exception as e: + misperrors['error'] = 'Syntax error: {}'.format(e) + return misperrors + return {'results': [{'types': mispattributes['output'], 'values': rule}]} + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/expansion/yara_syntax_validator.py b/misp_modules/modules/expansion/yara_syntax_validator.py index 4953c413..cad533fc 100644 --- a/misp_modules/modules/expansion/yara_syntax_validator.py +++ b/misp_modules/modules/expansion/yara_syntax_validator.py @@ -1,9 +1,8 @@ import json -import requests try: import yara -except: - print("yara is missing, use 'pip3 install yara' to install it.") +except (OSError, ImportError): + print("yara is missing, use 'pip3 install -I -r REQUIREMENTS' from the root of this repository to install it.") misperrors = {'error': 'Error'} mispattributes = {'input': ['yara'], 'output': ['text']} @@ -20,7 +19,7 @@ def handler(q=False): return misperrors try: - rules = yara.compile(source=request.get('yara')) + yara.compile(source=request.get('yara')) summary = ("Syntax valid") except Exception as e: summary = ("Syntax error: " + str(e)) diff --git a/misp_modules/modules/export_mod/__init__.py b/misp_modules/modules/export_mod/__init__.py index 0034f5dc..1affbd21 100644 --- a/misp_modules/modules/export_mod/__init__.py +++ b/misp_modules/modules/export_mod/__init__.py @@ -1 +1,2 @@ -__all__ = ['testexport','cef_export','liteexport','goamlexport','threat_connect_export','pdfexport','threatStream_misp_export'] +__all__ = ['cef_export', 'liteexport', 'goamlexport', 'threat_connect_export', 'pdfexport', + 'threatStream_misp_export', 'osqueryexport', 'nexthinkexport'] diff --git a/misp_modules/modules/export_mod/cef_export.py b/misp_modules/modules/export_mod/cef_export.py index 3f2ff614..0aa82f03 100755 --- a/misp_modules/modules/export_mod/cef_export.py +++ b/misp_modules/modules/export_mod/cef_export.py @@ -12,30 +12,32 @@ moduleinfo = {'version': '1', 'author': 'Hannah Ward', # config fields that your code expects from the site admin moduleconfig = ["Default_Severity", "Device_Vendor", "Device_Product", "Device_Version"] -cefmapping = {"ip-src":"src", "ip-dst":"dst", "hostname":"dhost", "domain":"dhost", - "md5":"fileHash", "sha1":"fileHash", "sha256":"fileHash", - "url":"request"} +cefmapping = {"ip-src": "src", "ip-dst": "dst", "hostname": "dhost", "domain": "dhost", + "md5": "fileHash", "sha1": "fileHash", "sha256": "fileHash", + "url": "request"} -mispattributes = {'input':list(cefmapping.keys())} +mispattributes = {'input': list(cefmapping.keys())} outputFileExtension = "cef" responseType = "application/txt" + def handler(q=False): if q is False: return False request = json.loads(q) if "config" in request: - config = request["config"] + config = request["config"] else: - config = {"Default_Severity":1, "Device_Vendor":"MISP", "Device_Product":"MISP", "Device_Version":1} + config = {"Default_Severity": 1, "Device_Vendor": "MISP", + "Device_Product": "MISP", "Device_Version": 1} data = request["data"] response = "" for ev in data: - event = ev["Attribute"] - for attr in event: - if attr["type"] in cefmapping: - response += "{} host CEF:0|{}|{}|{}|{}|{}|{}|{}={}\n".format( + event = ev["Attribute"] + for attr in event: + if attr["type"] in cefmapping: + response += "{} host CEF:0|{}|{}|{}|{}|{}|{}|{}={}\n".format( datetime.datetime.fromtimestamp(int(attr["timestamp"])).strftime("%b %d %H:%M:%S"), config["Device_Vendor"], config["Device_Product"], @@ -45,37 +47,37 @@ def handler(q=False): config["Default_Severity"], cefmapping[attr["type"]], attr["value"], - ) - - r = {"response":[], "data":str(base64.b64encode(bytes(response, 'utf-8')), 'utf-8')} + ) + + r = {"response": [], "data": str(base64.b64encode(bytes(response, 'utf-8')), 'utf-8')} return r def introspection(): - modulesetup = {} - try: + modulesetup = {} + try: responseType modulesetup['responseType'] = responseType - except NameError: - pass - try: - userConfig - modulesetup['userConfig'] = userConfig - except NameError: - pass - try: - outputFileExtension - modulesetup['outputFileExtension'] = outputFileExtension - except NameError: - pass - try: - inputSource - modulesetup['inputSource'] = inputSource - except NameError: - pass - return modulesetup + except NameError: + pass + try: + userConfig + modulesetup['userConfig'] = userConfig + except NameError: + pass + try: + outputFileExtension + modulesetup['outputFileExtension'] = outputFileExtension + except NameError: + pass + try: + inputSource + modulesetup['inputSource'] = inputSource + except NameError: + pass + return modulesetup + def version(): moduleinfo['config'] = moduleconfig return moduleinfo - diff --git a/misp_modules/modules/export_mod/cisco_firesight_manager_ACL_rule_export.py b/misp_modules/modules/export_mod/cisco_firesight_manager_ACL_rule_export.py new file mode 100644 index 00000000..ab79692d --- /dev/null +++ b/misp_modules/modules/export_mod/cisco_firesight_manager_ACL_rule_export.py @@ -0,0 +1,140 @@ +###################################################### +# # +# Author: Stanislav Klevtsov, Ukraine; Feb 2019. # +# # +# # +# Script was tested on the following configuration: # +# MISP v2.4.90 # +# Cisco Firesight Manager Console v6.2.3 (bld 84) # +# # +###################################################### + +import json +import base64 +from urllib.parse import quote + +misperrors = {'error': 'Error'} + +moduleinfo = {'version': '1', 'author': 'Stanislav Klevtsov', + 'description': 'Export malicious network activity attributes of the MISP event to Cisco firesight manager block rules', + 'module-type': ['export']} + + +moduleconfig = ['fmc_ip_addr', 'fmc_login', 'fmc_pass', 'domain_id', 'acpolicy_id'] + +fsmapping = {"ip-dst": "dst", "url": "request"} + +mispattributes = {'input': list(fsmapping.keys())} + +# options: event, attribute, event-collection, attribute-collection +inputSource = ['event'] + +outputFileExtension = 'sh' +responseType = 'application/txt' + +# .sh file templates +SH_FILE_HEADER = """#!/bin/sh\n\n""" + +BLOCK_JSON_TMPL = """ +BLOCK_RULE='{{ "action": "BLOCK", "enabled": true, "type": "AccessRule", "name": "{rule_name}", "destinationNetworks": {{ "literals": [ {dst_networks} ] }}, "urls": {{ "literals": [ {urls} ] }}, "newComments": [ "{event_info_comment}" ] }}'\n +""" + +BLOCK_DST_JSON_TMPL = """{{ "type": "Host", "value": "{ipdst}" }} """ +BLOCK_URL_JSON_TMPL = """{{ "type": "Url", "url": "{url}" }} """ + +CURL_ADD_RULE_TMPL = """ +curl -X POST -v -k -H 'Content-Type: application/json' -H \"Authorization: Basic $LOGINPASS_BASE64\" -H \"X-auth-access-token: $ACC_TOKEN\" -i \"https://$FIRESIGHT_IP_ADDR/api/fmc_config/v1/domain/$DOMAIN_ID/policy/accesspolicies/$ACPOLICY_ID/accessrules\" --data \"$BLOCK_RULE\" """ + + +def handler(q=False): + if q is False: + return False + + r = {'results': []} + request = json.loads(q) + + if "config" in request: + config = request["config"] + + # check if config is empty + if not config['fmc_ip_addr']: + config['fmc_ip_addr'] = "0.0.0.0" + if not config['fmc_login']: + config['fmc_login'] = "login" + if not config['fmc_pass']: + config['fmc_pass'] = "password" + if not config['domain_id']: + config['domain_id'] = "SET_FIRESIGHT_DOMAIN_ID" + if not config['acpolicy_id']: + config['acpolicy_id'] = "SET_FIRESIGHT_ACPOLICY_ID" + + data = request["data"] + output = "" + ipdst = [] + urls = [] + + # populate the ACL rule with attributes + for ev in data: + + event = ev["Attribute"] + event_id = ev["Event"]["id"] + event_info = ev["Event"]["info"] + + for index, attr in enumerate(event): + if attr["to_ids"] is True: + if attr["type"] in fsmapping: + if attr["type"] == "ip-dst": + ipdst.append(BLOCK_DST_JSON_TMPL.format(ipdst=attr["value"])) + else: + urls.append(BLOCK_URL_JSON_TMPL.format(url=quote(attr["value"], safe='@/:;?&=-_.,+!*'))) + + # building the .sh file + output += SH_FILE_HEADER + output += "FIRESIGHT_IP_ADDR='{}'\n".format(config['fmc_ip_addr']) + + output += "LOGINPASS_BASE64=`echo -n '{}:{}' | base64`\n".format(config['fmc_login'], config['fmc_pass']) + output += "DOMAIN_ID='{}'\n".format(config['domain_id']) + output += "ACPOLICY_ID='{}'\n\n".format(config['acpolicy_id']) + + output += "ACC_TOKEN=`curl -X POST -v -k -sD - -o /dev/null -H \"Authorization: Basic $LOGINPASS_BASE64\" -i \"https://$FIRESIGHT_IP_ADDR/api/fmc_platform/v1/auth/generatetoken\" | grep -i x-auth-acc | sed 's/.*:\\ //g' | tr -d '[:space:]' | tr -d '\\n'`\n" + + output += BLOCK_JSON_TMPL.format(rule_name="misp_event_{}".format(event_id), + dst_networks=', '.join(ipdst), + urls=', '.join(urls), + event_info_comment=event_info) + "\n" + + output += CURL_ADD_RULE_TMPL + # END building the .sh file + + r = {"data": base64.b64encode(output.encode('utf-8')).decode('utf-8')} + return r + + +def introspection(): + modulesetup = {} + try: + responseType + modulesetup['responseType'] = responseType + except NameError: + pass + try: + userConfig + modulesetup['userConfig'] = userConfig + except NameError: + pass + try: + outputFileExtension + modulesetup['outputFileExtension'] = outputFileExtension + except NameError: + pass + try: + inputSource + modulesetup['inputSource'] = inputSource + except NameError: + pass + return modulesetup + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/export_mod/goamlexport.py b/misp_modules/modules/export_mod/goamlexport.py index c2776404..b9ce086f 100644 --- a/misp_modules/modules/export_mod/goamlexport.py +++ b/misp_modules/modules/export_mod/goamlexport.py @@ -1,4 +1,5 @@ -import json, datetime, base64 +import json +import base64 from pymisp import MISPEvent from collections import defaultdict, Counter @@ -26,7 +27,7 @@ goAMLmapping = {'bank-account': {'bank-account': 't_account', 'institution-name' 'person': {'person': 't_person', 'text': 'comments', 'first-name': 'first_name', 'middle-name': 'middle_name', 'last-name': 'last_name', 'title': 'title', 'mothers-name': 'mothers_name', 'alias': 'alias', 'date-of-birth': 'birthdate', - 'place-of-birth': 'birth_place', 'gender': 'gender','nationality': 'nationality1', + 'place-of-birth': 'birth_place', 'gender': 'gender', 'nationality': 'nationality1', 'passport-number': 'passport_number', 'passport-country': 'passport_country', 'social-security-number': 'ssn', 'identity-card-number': 'id_number'}, 'geolocation': {'geolocation': 'location', 'city': 'city', 'region': 'state', @@ -47,6 +48,7 @@ referencesMapping = {'bank-account': {'aml_type': '{}_account', 'bracket': 't_{} 'legal-entity': {'transaction': {'aml_type': '{}_entity', 'bracket': 't_{}'}, 'bank-account': {'aml_type': 't_entity'}}, 'geolocation': {'aml_type': 'address', 'bracket': 'addresses'}} + class GoAmlGeneration(object): def __init__(self, config): self.config = config @@ -67,7 +69,7 @@ class GoAmlGeneration(object): try: report_code.append(obj.get_attributes_by_relation('report-code')[0].value.split(' ')[0]) currency_code.append(obj.get_attributes_by_relation('currency-code')[0].value) - except: + except IndexError: print('report_code or currency_code error') self.uuids, self.report_codes, self.currency_codes = uuids, report_code, currency_code @@ -87,9 +89,12 @@ class GoAmlGeneration(object): person_to_parse = [person_uuid for person_uuid in self.uuids.get('person') if person_uuid not in self.parsed_uuids.get('person')] if len(person_to_parse) == 1: self.itterate('person', 'reporting_person', person_to_parse[0], 'header') - location_to_parse = [location_uuid for location_uuid in self.uuids.get('geolocation') if location_uuid not in self.parsed_uuids.get('geolocation')] - if len(location_to_parse) == 1: - self.itterate('geolocation', 'location', location_to_parse[0], 'header') + try: + location_to_parse = [location_uuid for location_uuid in self.uuids.get('geolocation') if location_uuid not in self.parsed_uuids.get('geolocation')] + if len(location_to_parse) == 1: + self.itterate('geolocation', 'location', location_to_parse[0], 'header') + except TypeError: + pass self.xml['data'] += "" def itterate(self, object_type, aml_type, uuid, xml_part): @@ -182,6 +187,7 @@ class GoAmlGeneration(object): self.itterate(next_object_type, next_aml_type, uuid, xml_part) self.xml[xml_part] += "".format(bracket) + def handler(q=False): if q is False: return False @@ -208,6 +214,7 @@ def handler(q=False): exp_doc = "{}{}".format(export_doc.xml.get('header'), export_doc.xml.get('data')) return {'response': [], 'data': str(base64.b64encode(bytes(exp_doc, 'utf-8')), 'utf-8')} + def introspection(): modulesetup = {} try: @@ -232,6 +239,7 @@ def introspection(): pass return modulesetup + def version(): moduleinfo['config'] = moduleconfig return moduleinfo diff --git a/misp_modules/modules/export_mod/liteexport.py b/misp_modules/modules/export_mod/liteexport.py index 5d47489e..870f52a2 100755 --- a/misp_modules/modules/export_mod/liteexport.py +++ b/misp_modules/modules/export_mod/liteexport.py @@ -3,10 +3,10 @@ import base64 misperrors = {'error': 'Error'} -moduleinfo = {'version': '1', - 'author': 'TM', - 'description': 'export lite', - 'module-type': ['export']} +moduleinfo = {'version': '1', + 'author': 'TM', + 'description': 'export lite', + 'module-type': ['export']} moduleconfig = ["indent_json_export"] @@ -14,76 +14,75 @@ mispattributes = {} outputFileExtension = "json" responseType = "application/json" + def handler(q=False): - if q is False: - return False + if q is False: + return False - request = json.loads(q) + request = json.loads(q) - config = {} - if "config" in request: - config = request["config"] - else: - config = {"indent_json_export" : None} + config = {} + if "config" in request: + config = request["config"] + else: + config = {"indent_json_export": None} - if config['indent_json_export'] is not None: - try: - config['indent_json_export'] = int(config['indent_json_export']) - except: - config['indent_json_export'] = None + if config['indent_json_export'] is not None: + try: + config['indent_json_export'] = int(config['indent_json_export']) + except Exception: + config['indent_json_export'] = None - if 'data' not in request: - return False + if 'data' not in request: + return False - #~ Misp json structur - liteEvent = {'Event':{}} + # ~ Misp json structur + liteEvent = {'Event': {}} - for evt in request['data']: - rawEvent = evt['Event'] - liteEvent['Event']['info'] = rawEvent['info'] - liteEvent['Event']['Attribute'] = [] - - attrs = evt['Attribute'] - for attr in attrs: - if 'Internal reference' not in attr['category']: - liteAttr = {} - liteAttr['category'] = attr['category'] - liteAttr['type'] = attr['type'] - liteAttr['value'] = attr['value'] - liteEvent['Event']['Attribute'].append(liteAttr) + for evt in request['data']: + rawEvent = evt['Event'] + liteEvent['Event']['info'] = rawEvent['info'] + liteEvent['Event']['Attribute'] = [] + + attrs = evt['Attribute'] + for attr in attrs: + if 'Internal reference' not in attr['category']: + liteAttr = {} + liteAttr['category'] = attr['category'] + liteAttr['type'] = attr['type'] + liteAttr['value'] = attr['value'] + liteEvent['Event']['Attribute'].append(liteAttr) + + return {'response': [], + 'data': str(base64.b64encode(bytes( + json.dumps(liteEvent, indent=config['indent_json_export']), 'utf-8')), 'utf-8')} - return {'response' : [], - 'data' : str(base64.b64encode( - bytes( - json.dumps(liteEvent, indent=config['indent_json_export']), - 'utf-8')), - 'utf-8') - } def introspection(): - modulesetup = {} - try: - responseType - modulesetup['responseType'] = responseType - except NameError: - pass - try: - userConfig - modulesetup['userConfig'] = userConfig - except NameError: - pass - try: - outputFileExtension - modulesetup['outputFileExtension'] = outputFileExtension - except NameError: - pass - try: - inputSource - modulesetup['inputSource'] = inputSource - except NameError: - pass - return modulesetup + modulesetup = {} + try: + responseType + modulesetup['responseType'] = responseType + except NameError: + pass + try: + userConfig + modulesetup['userConfig'] = userConfig + except NameError: + pass + try: + outputFileExtension + modulesetup['outputFileExtension'] = outputFileExtension + except NameError: + pass + try: + inputSource + modulesetup['inputSource'] = inputSource + except NameError: + pass + return modulesetup + def version(): - moduleinfo['config'] = moduleconfig - return moduleinfo + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/export_mod/nexthinkexport.py b/misp_modules/modules/export_mod/nexthinkexport.py new file mode 100755 index 00000000..c87b3fbc --- /dev/null +++ b/misp_modules/modules/export_mod/nexthinkexport.py @@ -0,0 +1,121 @@ +""" +Export module for coverting MISP events into Nexthink NXQL queries. +Source: https://github.com/HacknowledgeCH/misp-modules/blob/master/misp_modules/modules/export_mod/nexthinkexport.py +Config['Period'] : allows to define period over witch to look for IOC from now (15m, 1d, 2w, 30d, ...), see Nexthink data model documentation +""" + +import base64 +import json + +misperrors = {"error": "Error"} + +types_to_use = ['sha1', 'sha256', 'md5', 'domain'] + +userConfig = { + +} + +moduleconfig = ["Period"] +inputSource = ['event'] + +outputFileExtension = 'nxql' +responseType = 'application/txt' + +moduleinfo = {'version': '1.0', 'author': 'Julien Bachmann, Hacknowledge', + 'description': 'Nexthink NXQL query export module', + 'module-type': ['export']} + + +def handle_sha1(value, period): + query = '''select ((binary (executable_name version)) (user (name)) (device (name last_ip_address)) (execution (binary_path start_time))) +(from (binary user device execution) +(where binary (eq sha1 (sha1 %s))) +(between now-%s now)) +(limit 1000) + ''' % (value, period) + return query.replace('\n', ' ') + + +def handle_sha256(value, period): + query = '''select ((binary (executable_name version)) (user (name)) (device (name last_ip_address)) (execution (binary_path start_time))) +(from (binary user device execution) +(where binary (eq sha256 (sha256 %s))) +(between now-%s now)) +(limit 1000) + ''' % (value, period) + return query.replace('\n', ' ') + + +def handle_md5(value, period): + query = '''select ((binary (executable_name version)) (user (name)) (device (name last_ip_address)) (execution (binary_path start_time))) +(from (binary user device execution) +(where binary (eq hash (md5 %s))) +(between now-%s now)) +(limit 1000) + ''' % (value, period) + return query.replace('\n', ' ') + + +def handle_domain(value, period): + query = '''select ((device name) (device (name last_ip_address)) (user name)(user department) (binary executable_name)(binary application_name)(binary description)(binary application_category)(binary (executable_name version)) (binary #"Suspicious binary")(binary first_seen)(binary last_seen)(binary threat_level)(binary hash) (binary paths) +(destination name)(domain name) (domain domain_category)(domain hosting_country)(domain protocol)(domain threat_level) (port port_number)(web_request incoming_traffic)(web_request outgoing_traffic)) +(from (web_request device user binary executable destination domain port) +(where domain (eq name(string %s))) +(between now-%s now)) +(limit 1000) + ''' % (value, period) + return query.replace('\n', ' ') + + +handlers = { + 'sha1': handle_sha1, + 'sha256': handle_sha256, + 'md5': handle_md5, + 'domain': handle_domain +} + + +def handler(q=False): + if q is False: + return False + r = {'results': []} + request = json.loads(q) + config = request.get("config", {"Period": ""}) + output = '' + + for event in request["data"]: + for attribute in event["Attribute"]: + if attribute['type'] in types_to_use: + output = output + handlers[attribute['type']](attribute['value'], config['Period']) + '\n' + r = {"response": [], "data": str(base64.b64encode(bytes(output, 'utf-8')), 'utf-8')} + return r + + +def introspection(): + modulesetup = {} + try: + responseType + modulesetup['responseType'] = responseType + except NameError: + pass + try: + userConfig + modulesetup['userConfig'] = userConfig + except NameError: + pass + try: + outputFileExtension + modulesetup['outputFileExtension'] = outputFileExtension + except NameError: + pass + try: + inputSource + modulesetup['inputSource'] = inputSource + except NameError: + pass + return modulesetup + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/export_mod/osqueryexport.py b/misp_modules/modules/export_mod/osqueryexport.py new file mode 100755 index 00000000..6368875c --- /dev/null +++ b/misp_modules/modules/export_mod/osqueryexport.py @@ -0,0 +1,115 @@ +""" +Export module for coverting MISP events into OSQuery queries. +Source: https://github.com/0xmilkmix/misp-modules/blob/master/misp_modules/modules/export_mod/osqueryexport.py +""" + +import base64 +import json +import re + +misperrors = {"error": "Error"} + +types_to_use = ['regkey', 'regkey|value', 'mutex', 'windows-service-displayname', 'windows-scheduled-task', 'yara'] + +userConfig = { + +} + +moduleconfig = [] +inputSource = ['event'] + +outputFileExtension = 'conf' +responseType = 'application/txt' + + +moduleinfo = {'version': '1.0', 'author': 'Julien Bachmann, Hacknowledge', + 'description': 'OSQuery query export module', + 'module-type': ['export']} + + +def handle_regkey(value): + rep = {'HKCU': 'HKEY_USERS\\%', 'HKLM': 'HKEY_LOCAL_MACHINE'} + rep = dict((re.escape(k), v) for k, v in rep.items()) + pattern = re.compile("|".join(rep.keys())) + value = pattern.sub(lambda m: rep[re.escape(m.group(0))], value) + return 'SELECT * FROM registry WHERE path LIKE \'%s\';' % value + + +def handle_regkeyvalue(value): + key, value = value.split('|') + rep = {'HKCU': 'HKEY_USERS\\%', 'HKLM': 'HKEY_LOCAL_MACHINE'} + rep = dict((re.escape(k), v) for k, v in rep.items()) + pattern = re.compile("|".join(rep.keys())) + key = pattern.sub(lambda m: rep[re.escape(m.group(0))], key) + return 'SELECT * FROM registry WHERE path LIKE \'%s\' AND data LIKE \'%s\';' % (key, value) + + +def handle_mutex(value): + return 'SELECT * FROM winbaseobj WHERE object_name LIKE \'%s\';' % value + + +def handle_service(value): + return 'SELECT * FROM services WHERE display_name LIKE \'%s\' OR name like \'%s\';' % (value, value) + + +def handle_yara(value): + return 'not implemented yet, not sure it\'s easily feasible w/o dropping the sig on the hosts first' + + +def handle_scheduledtask(value): + return 'SELECT * FROM scheduled_tasks WHERE name LIKE \'%s\';' % value + + +handlers = { + 'regkey': handle_regkey, + 'regkey|value': handle_regkeyvalue, + 'mutex': handle_mutex, + 'windows-service-displayname': handle_service, + 'windows-scheduled-task': handle_scheduledtask, + 'yara': handle_yara +} + + +def handler(q=False): + if q is False: + return False + r = {'results': []} + request = json.loads(q) + output = '' + + for event in request["data"]: + for attribute in event["Attribute"]: + if attribute['type'] in types_to_use: + output = output + handlers[attribute['type']](attribute['value']) + '\n' + r = {"response": [], "data": str(base64.b64encode(bytes(output, 'utf-8')), 'utf-8')} + return r + + +def introspection(): + modulesetup = {} + try: + responseType + modulesetup['responseType'] = responseType + except NameError: + pass + try: + userConfig + modulesetup['userConfig'] = userConfig + except NameError: + pass + try: + outputFileExtension + modulesetup['outputFileExtension'] = outputFileExtension + except NameError: + pass + try: + inputSource + modulesetup['inputSource'] = inputSource + except NameError: + pass + return modulesetup + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/export_mod/pdfexport.py b/misp_modules/modules/export_mod/pdfexport.py index 2aeaec7f..44b3bc9e 100755 --- a/misp_modules/modules/export_mod/pdfexport.py +++ b/misp_modules/modules/export_mod/pdfexport.py @@ -1,67 +1,29 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -from datetime import date import json -import shlex -import subprocess -import base64 from pymisp import MISPEvent - +from pymisp.tools import reportlab_generator misperrors = {'error': 'Error'} -moduleinfo = {'version': '1', - 'author': 'Raphaël Vinot', +moduleinfo = {'version': '2', + 'author': 'Vincent Falconieri (prev. Raphaël Vinot)', 'description': 'Simple export to PDF', 'module-type': ['export'], 'require_standard_format': True} -moduleconfig = [] - +# config fields that your code expects from the site admin +moduleconfig = ["MISP_base_url_for_dynamic_link", "MISP_name_for_metadata", "Activate_textual_description", "Activate_galaxy_description", "Activate_related_events", "Activate_internationalization_fonts", "Custom_fonts_path"] mispattributes = {} + outputFileExtension = "pdf" responseType = "application/pdf" types_to_attach = ['ip-dst', 'url', 'domain'] objects_to_attach = ['domain-ip'] -headers = """ -:toc: right -:toclevels: 1 -:toc-title: Daily Report -:icons: font -:sectanchors: -:sectlinks: -= Daily report by {org_name} -{date} - -:icons: font - -""" - -event_level_tags = """ -IMPORTANT: This event is classified TLP:{value}. - -{expanded} - -""" - -attributes = """ -=== Indicator(s) of compromise - -{list_attributes} - -""" - -title = """ -== ({internal_id}) {title} - -{summary} - -""" - class ReportGenerator(): def __init__(self): @@ -79,60 +41,6 @@ class ReportGenerator(): self.misp_event = MISPEvent() self.misp_event.load(event) - def attributes(self): - if not self.misp_event.attributes: - return '' - list_attributes = [] - for attribute in self.misp_event.attributes: - if attribute.type in types_to_attach: - list_attributes.append("* {}".format(attribute.value)) - for obj in self.misp_event.Object: - if obj.name in objects_to_attach: - for attribute in obj.Attribute: - if attribute.type in types_to_attach: - list_attributes.append("* {}".format(attribute.value)) - return attributes.format(list_attributes="\n".join(list_attributes)) - - def _get_tag_info(self, machinetag): - return self.taxonomies.revert_machinetag(machinetag) - - def report_headers(self): - content = {'org_name': 'name', - 'date': date.today().isoformat()} - self.report += headers.format(**content) - - def event_level_tags(self): - if not self.misp_event.Tag: - return '' - for tag in self.misp_event.Tag: - # Only look for TLP for now - if tag['name'].startswith('tlp'): - tax, predicate = self._get_tag_info(tag['name']) - return self.event_level_tags.format(value=predicate.predicate.upper(), expanded=predicate.expanded) - - def title(self): - internal_id = '' - summary = '' - # Get internal refs for report - if not hasattr(self.misp_event, 'Object'): - return '' - for obj in self.misp_event.Object: - if obj.name != 'report': - continue - for a in obj.Attribute: - if a.object_relation == 'case-number': - internal_id = a.value - if a.object_relation == 'summary': - summary = a.value - - return title.format(internal_id=internal_id, title=self.misp_event.info, - summary=summary) - - def asciidoc(self, lang='en'): - self.report += self.title() - self.report += self.event_level_tags() - self.report += self.attributes() - def handler(q=False): if q is False: @@ -143,45 +51,48 @@ def handler(q=False): if 'data' not in request: return False - for evt in request['data']: - report = ReportGenerator() - report.report_headers() - report.from_event(evt) - report.asciidoc() + config = {} - command_line = 'asciidoctor-pdf -' - args = shlex.split(command_line) - with subprocess.Popen(args, stdout=subprocess.PIPE, stdin=subprocess.PIPE) as process: - cmd_out, cmd_err = process.communicate(input=report.report.encode('utf-8')) - return {'response': [], 'data': str(base64.b64encode(cmd_out), 'utf-8')} + # Construct config object for reportlab_generator + for config_item in moduleconfig: + if (request.get('config')) and (request['config'].get(config_item) is not None): + config[config_item] = request['config'].get(config_item) + + for evt in request['data']: + misp_event = MISPEvent() + misp_event.load(evt) + + pdf = reportlab_generator.get_base64_from_value(reportlab_generator.convert_event_in_pdf_buffer(misp_event, config)) + + return {'response': [], 'data': str(pdf, 'utf-8')} def introspection(): - modulesetup = {} - try: - responseType - modulesetup['responseType'] = responseType - except NameError: - pass + modulesetup = {} + try: + responseType + modulesetup['responseType'] = responseType + except NameError: + pass - try: - userConfig - modulesetup['userConfig'] = userConfig - except NameError: - pass - try: - outputFileExtension - modulesetup['outputFileExtension'] = outputFileExtension - except NameError: - pass - try: - inputSource - modulesetup['inputSource'] = inputSource - except NameError: - pass - return modulesetup + try: + userConfig + modulesetup['userConfig'] = userConfig + except NameError: + pass + try: + outputFileExtension + modulesetup['outputFileExtension'] = outputFileExtension + except NameError: + pass + try: + inputSource + modulesetup['inputSource'] = inputSource + except NameError: + pass + return modulesetup def version(): - moduleinfo['config'] = moduleconfig - return moduleinfo + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/misp_modules/modules/export_mod/testexport.py b/misp_modules/modules/export_mod/testexport.py index ed93228c..1fc7ff7d 100755 --- a/misp_modules/modules/export_mod/testexport.py +++ b/misp_modules/modules/export_mod/testexport.py @@ -1,13 +1,12 @@ import json import base64 -import csv misperrors = {'error': 'Error'} userConfig = { -}; +} moduleconfig = [] @@ -28,9 +27,9 @@ def handler(q=False): if q is False: return False r = {'results': []} - result = json.loads(q) - output = ''; # Insert your magic here! - r = {"data":base64.b64encode(output.encode('utf-8')).decode('utf-8')} + result = json.loads(q) # noqa + output = '' # Insert your magic here! + r = {"data": base64.b64encode(output.encode('utf-8')).decode('utf-8')} return r diff --git a/misp_modules/modules/export_mod/threatStream_misp_export.py b/misp_modules/modules/export_mod/threatStream_misp_export.py index 3fd88c84..a9f7f06e 100755 --- a/misp_modules/modules/export_mod/threatStream_misp_export.py +++ b/misp_modules/modules/export_mod/threatStream_misp_export.py @@ -49,9 +49,7 @@ def handler(q=False): if q is False or not q: return False - request = json.loads(q) - response = io.StringIO() writer = csv.DictWriter(response, fieldnames=["value", "itype", "tags"]) diff --git a/misp_modules/modules/import_mod/__init__.py b/misp_modules/modules/import_mod/__init__.py index 886eaf77..c3eea054 100644 --- a/misp_modules/modules/import_mod/__init__.py +++ b/misp_modules/modules/import_mod/__init__.py @@ -1,4 +1,3 @@ -from . import _vmray +from . import _vmray # noqa -__all__ = ['vmray_import', 'testimport', 'ocr', 'stiximport', 'cuckooimport', 'goamlimport', - 'email_import', 'mispjson', 'openiocimport', 'threatanalyzer_import', 'csvimport'] +__all__ = ['vmray_import', 'ocr', 'cuckooimport', 'goamlimport', 'email_import', 'mispjson', 'openiocimport', 'threatanalyzer_import', 'csvimport'] diff --git a/misp_modules/modules/import_mod/csvimport.py b/misp_modules/modules/import_mod/csvimport.py index 543d67b9..0e42d947 100644 --- a/misp_modules/modules/import_mod/csvimport.py +++ b/misp_modules/modules/import_mod/csvimport.py @@ -1,47 +1,63 @@ # -*- coding: utf-8 -*- -import json, os, base64 +import json +import os +import base64 import pymisp misperrors = {'error': 'Error'} -mispattributes = {'inputSource': ['file'], 'output': ['MISP attributes']} moduleinfo = {'version': '0.1', 'author': 'Christian Studer', 'description': 'Import Attributes from a csv file.', 'module-type': ['import']} -moduleconfig = ['header'] +moduleconfig = [] +inputSource = ['file'] +userConfig = {'header': { + 'type': 'String', + 'message': 'Define the header of the csv file, with types (included in MISP attribute types or attribute fields) separated by commas.\nFor fields that do not match these types, please use space or simply nothing between commas.\nFor instance: ip-src,domain, ,timestamp'}, + 'has_header': { + 'type': 'Boolean', + 'message': 'Tick this box ONLY if there is a header line, NOT COMMENTED, in the file (which will be skipped atm).' +}} duplicatedFields = {'mispType': {'mispComment': 'comment'}, 'attrField': {'attrComment': 'comment'}} +attributesFields = ['type', 'value', 'category', 'to_ids', 'comment', 'distribution'] +delimiters = [',', ';', '|', '/', '\t', ' '] + class CsvParser(): - def __init__(self, header): + def __init__(self, header, has_header): self.header = header + self.fields_number = len(header) + self.has_header = has_header self.attributes = [] def parse_data(self, data): return_data = [] - for line in data: - l = line.split('#')[0].strip() if '#' in line else line.strip() - if l: - return_data.append(l) - self.data = return_data - # find which delimiter is used - self.delimiter, self.length = self.findDelimiter() - - def findDelimiter(self): - n = len(self.header) - if n > 1: - tmpData = [] - for da in self.data: - tmp = [] - for d in (';', '|', '/', ',', '\t', ' ',): - if da.count(d) == (n-1): - tmp.append(d) - if len(tmp) == 1 and tmp == tmpData: - return tmpData[0], n - else: - tmpData = tmp + if self.fields_number == 1: + for line in data: + line = line.split('#')[0].strip() + if line: + return_data.append(line) + self.delimiter = None else: - return None, 1 + self.delimiter_count = dict([(d, 0) for d in delimiters]) + for line in data: + line = line.split('#')[0].strip() + if line: + self.parse_delimiter(line) + return_data.append(line) + # find which delimiter is used + self.delimiter = self.find_delimiter() + self.data = return_data[1:] if self.has_header else return_data + + def parse_delimiter(self, line): + for d in delimiters: + if line.count(d) >= (self.fields_number - 1): + self.delimiter_count[d] += 1 + + def find_delimiter(self): + _, delimiter = max((n, v) for v, n in self.delimiter_count.items()) + return delimiter def buildAttributes(self): # if there is only 1 field of data @@ -59,7 +75,7 @@ class CsvParser(): datamisp = [] datasplit = data.split(self.delimiter) # in case there is an empty line or an error - if len(datasplit) != self.length: + if len(datasplit) != self.fields_number: continue # pop from the line data that matches with a misp type, using the list of indexes for l in list2pop: @@ -93,12 +109,16 @@ class CsvParser(): elif h in duplicatedFields['attrField']: # fields that should be considered as attribute fields head.append(duplicatedFields['attrField'].get(h)) - # otherwise, it is an attribute field - else: + # or, it could be an attribute field + elif h in attributesFields: head.append(h) + # otherwise, it is not defined + else: + head.append('') # return list of indexes of the misp types, list of the misp types, remaining fields that will be attribute fields return list2pop, misp, list(reversed(head)) + def handler(q=False): if q is False: return False @@ -111,17 +131,32 @@ def handler(q=False): if not request.get('config') and not request['config'].get('header'): misperrors['error'] = "Configuration error" return misperrors - config = request['config'].get('header').split(',') - config = [c.strip() for c in config] - csv_parser = CsvParser(config) + header = request['config'].get('header').split(',') + header = [c.strip() for c in header] + has_header = request['config'].get('has_header') + has_header = True if has_header == '1' else False + csv_parser = CsvParser(header, has_header) csv_parser.parse_data(data.split('\n')) # build the attributes csv_parser.buildAttributes() r = {'results': csv_parser.attributes} return r + def introspection(): - return mispattributes + modulesetup = {} + try: + userConfig + modulesetup['userConfig'] = userConfig + except NameError: + pass + try: + inputSource + modulesetup['inputSource'] = inputSource + except NameError: + pass + return modulesetup + def version(): moduleinfo['config'] = moduleconfig diff --git a/misp_modules/modules/import_mod/cuckooimport.py b/misp_modules/modules/import_mod/cuckooimport.py index 193477f1..fc0c30e8 100755 --- a/misp_modules/modules/import_mod/cuckooimport.py +++ b/misp_modules/modules/import_mod/cuckooimport.py @@ -1,7 +1,5 @@ import json -import logging -import sys -import base64 +import base64 misperrors = {'error': 'Error'} userConfig = {} @@ -13,160 +11,163 @@ moduleinfo = {'version': '0.1', 'author': 'Victor van der Stoep', moduleconfig = [] + def handler(q=False): # Just in case we have no data if q is False: return False - + # The return value r = {'results': []} # Load up that JSON - q = json.loads(q) + q = json.loads(q) data = base64.b64decode(q.get("data")).decode('utf-8') - + # If something really weird happened if not data: return json.dumps({"success": 0}) - + data = json.loads(data) - - # Get characteristics of file + + # Get characteristics of file targetFile = data['target']['file'] - + # Process the inital binary - processBinary(r, targetFile, initial = True) - + processBinary(r, targetFile, initial=True) + # Get binary information for dropped files if(data.get('dropped')): for droppedFile in data['dropped']: - processBinary(r, droppedFile, dropped = True) - + processBinary(r, droppedFile, dropped=True) + # Add malscore to results - r["results"].append({ - "values": "Malscore: {} ".format(data['malscore']), + r["results"].append({ + "values": "Malscore: {} ".format(data['malscore']), "types": "comment", - "categories": "Payload delivery", + "categories": "Payload delivery", "comment": "Cuckoo analysis: MalScore" }) - + # Add virustotal data, if exists if(data.get('virustotal')): processVT(r, data['virustotal']) - + # Add network information, should be improved processNetwork(r, data['network']) - + # Add behavioral information processSummary(r, data['behavior']['summary']) - - # Return + + # Return return r + def processSummary(r, summary): - r["results"].append({ - "values": summary['mutexes'], + r["results"].append({ + "values": summary['mutexes'], "types": "mutex", - "categories": "Artifacts dropped", + "categories": "Artifacts dropped", "comment": "Cuckoo analysis: Observed mutexes" }) - + + def processVT(r, virustotal): category = "Antivirus detection" - comment = "VirusTotal analysis" - + comment = "VirusTotal analysis" + if(virustotal.get('permalink')): - r["results"].append({ - "values": virustotal['permalink'], + r["results"].append({ + "values": virustotal['permalink'], "types": "link", - "categories": category, + "categories": category, "comments": comment + " - Permalink" }) - + if(virustotal.get('total')): - r["results"].append({ + r["results"].append({ "values": "VirusTotal detection rate {}/{}".format( virustotal['positives'], virustotal['total'] - ), + ), "types": "comment", - "categories": category, - "comment": comment - }) - else: - r["results"].append({ - "values": "Sample not detected on VirusTotal", - "types": "comment", - "categories": category, + "categories": category, "comment": comment }) - + else: + r["results"].append({ + "values": "Sample not detected on VirusTotal", + "types": "comment", + "categories": category, + "comment": comment + }) + def processNetwork(r, network): category = "Network activity" - + for host in network['hosts']: - r["results"].append({ - "values": host['ip'], + r["results"].append({ + "values": host['ip'], "types": "ip-dst", - "categories": category, + "categories": category, "comment": "Cuckoo analysis: Observed network traffic" }) - -def processBinary(r, target, initial = False, dropped = False): - if(initial): + +def processBinary(r, target, initial=False, dropped=False): + if(initial): comment = "Cuckoo analysis: Initial file" category = "Payload delivery" elif(dropped): category = "Artifacts dropped" comment = "Cuckoo analysis: Dropped file" - - r["results"].append({ - "values": target['name'], + + r["results"].append({ + "values": target['name'], "types": "filename", - "categories": category, + "categories": category, "comment": comment }) - - r["results"].append({ - "values": target['md5'], + + r["results"].append({ + "values": target['md5'], "types": "md5", - "categories": category, + "categories": category, "comment": comment }) - - r["results"].append({ - "values": target['sha1'], + + r["results"].append({ + "values": target['sha1'], "types": "sha1", - "categories": category, + "categories": category, "comment": comment }) - - r["results"].append({ - "values": target['sha256'], + + r["results"].append({ + "values": target['sha256'], "types": "sha256", - "categories": category, + "categories": category, "comment": comment }) - - r["results"].append({ - "values": target['sha512'], + + r["results"].append({ + "values": target['sha512'], "types": "sha512", - "categories": category, + "categories": category, "comment": comment }) - + # todo : add file size? - + if(target.get('guest_paths')): - r["results"].append({ + r["results"].append({ "values": target['guest_paths'], "types": "filename", - "categories": "Payload installation", + "categories": "Payload installation", "comment": comment + " - Path" }) - + def introspection(): modulesetup = {} @@ -187,10 +188,11 @@ def version(): moduleinfo['config'] = moduleconfig return moduleinfo + if __name__ == '__main__': x = open('test.json', 'r') q = [] q['data'] = x.read() q = base64.base64encode(q) - + handler(q) diff --git a/misp_modules/modules/import_mod/email_import.py b/misp_modules/modules/import_mod/email_import.py index fa7d5dc2..956f5203 100644 --- a/misp_modules/modules/import_mod/email_import.py +++ b/misp_modules/modules/import_mod/email_import.py @@ -115,7 +115,7 @@ def handler(q=False): email_targets = set() for rec in received: try: - email_check = re.search("for\s(.*@.*);", rec).group(1) + email_check = re.search(r"for\s(.*@.*);", rec).group(1) email_check = email_check.strip(' <>') email_targets.add(parseaddr(email_check)[1]) except (AttributeError): @@ -166,7 +166,7 @@ def handler(q=False): for ext in zipped_files: if filename.endswith(ext) is True: zipped_filetype = True - if zipped_filetype == False: + if not zipped_filetype: try: attachment_files += get_zipped_contents(filename, attachment_data) except RuntimeError: # File is encrypted with a password @@ -294,7 +294,7 @@ def get_zip_passwords(message): # Grab any strings that are marked off by special chars marking_chars = [["\'", "\'"], ['"', '"'], ['[', ']'], ['(', ')']] for char_set in marking_chars: - regex = re.compile("""\{0}([^\{1}]*)\{1}""".format(char_set[0], char_set[1])) + regex = re.compile(r"""\{0}([^\{1}]*)\{1}""".format(char_set[0], char_set[1])) marked_off = re.findall(regex, raw_text) possible_passwords += marked_off @@ -397,6 +397,7 @@ def version(): moduleinfo['config'] = moduleconfig return moduleinfo + if __name__ == '__main__': with open('tests/test_no_attach.eml', 'r') as email_file: handler(q=email_file.read()) diff --git a/misp_modules/modules/import_mod/goamlimport.py b/misp_modules/modules/import_mod/goamlimport.py index ecb0a2d8..7116b444 100644 --- a/misp_modules/modules/import_mod/goamlimport.py +++ b/misp_modules/modules/import_mod/goamlimport.py @@ -1,6 +1,7 @@ -import json, datetime, time, base64 +import json +import time +import base64 import xml.etree.ElementTree as ET -from collections import defaultdict from pymisp import MISPEvent, MISPObject misperrors = {'error': 'Error'} @@ -11,12 +12,12 @@ moduleconfig = [] mispattributes = {'inputSource': ['file'], 'output': ['MISP objects']} t_from_objects = {'nodes': ['from_person', 'from_account', 'from_entity'], - 'leaves': ['from_funds_code', 'from_country']} + 'leaves': ['from_funds_code', 'from_country']} t_to_objects = {'nodes': ['to_person', 'to_account', 'to_entity'], - 'leaves': ['to_funds_code', 'to_country']} + 'leaves': ['to_funds_code', 'to_country']} t_person_objects = {'nodes': ['addresses'], - 'leaves': ['first_name', 'middle_name', 'last_name', 'gender', 'title', 'mothers_name', 'birthdate', - 'passport_number', 'passport_country', 'id_number', 'birth_place', 'alias', 'nationality1']} + 'leaves': ['first_name', 'middle_name', 'last_name', 'gender', 'title', 'mothers_name', 'birthdate', + 'passport_number', 'passport_country', 'id_number', 'birth_place', 'alias', 'nationality1']} t_account_objects = {'nodes': ['signatory'], 'leaves': ['institution_name', 'institution_code', 'swift', 'branch', 'non_banking_insitution', 'account', 'currency_code', 'account_name', 'iban', 'client_number', 'opened', 'closed', @@ -51,7 +52,7 @@ t_account_mapping = {'misp_name': 'bank-account', 'institution_name': 'instituti t_person_mapping = {'misp_name': 'person', 'comments': 'text', 'first_name': 'first-name', 'middle_name': 'middle-name', 'last_name': 'last-name', 'title': 'title', 'mothers_name': 'mothers-name', 'alias': 'alias', - 'birthdate': 'date-of-birth', 'birth_place': 'place-of-birth', 'gender': 'gender','nationality1': 'nationality', + 'birthdate': 'date-of-birth', 'birth_place': 'place-of-birth', 'gender': 'gender', 'nationality1': 'nationality', 'passport_number': 'passport-number', 'passport_country': 'passport-country', 'ssn': 'social-security-number', 'id_number': 'identity-card-number'} @@ -73,6 +74,7 @@ goAMLmapping = {'from_account': t_account_mapping, 'to_account': t_account_mappi nodes_to_ignore = ['addresses', 'signatory'] relationship_to_keep = ['signatory', 't_from', 't_from_my_client', 't_to', 't_to_my_client', 'address'] + class GoAmlParser(): def __init__(self): self.misp_event = MISPEvent() @@ -145,6 +147,7 @@ class GoAmlParser(): to_country_attribute = {'object_relation': 'to-country', 'value': to_country} misp_object.add_attribute(**to_country_attribute) + def handler(q=False): if q is False: return False @@ -157,16 +160,18 @@ def handler(q=False): aml_parser = GoAmlParser() try: aml_parser.read_xml(data) - except: + except Exception: misperrors['error'] = "Impossible to read XML data" return misperrors aml_parser.parse_xml() r = {'results': [obj.to_json() for obj in aml_parser.misp_event.objects]} return r + def introspection(): return mispattributes + def version(): moduleinfo['config'] = moduleconfig return moduleinfo diff --git a/misp_modules/modules/import_mod/mispjson.py b/misp_modules/modules/import_mod/mispjson.py index f9d52ec7..a9c22267 100755 --- a/misp_modules/modules/import_mod/mispjson.py +++ b/misp_modules/modules/import_mod/mispjson.py @@ -2,7 +2,7 @@ import json import base64 misperrors = {'error': 'Error'} -userConfig = { }; +userConfig = {} inputSource = ['file'] @@ -19,23 +19,24 @@ def handler(q=False): r = {'results': []} request = json.loads(q) try: - mfile = base64.b64decode(request["data"]).decode('utf-8') - misp = json.loads(mfile) - event = misp['response'][0]['Event'] - for a in event["Attribute"]: - tmp = {} - tmp["values"] = a["value"] - tmp["categories"] = a["category"] - tmp["types"] = a["type"] - tmp["to_ids"] = a["to_ids"] - tmp["comment"] = a["comment"] - if a.get("data"): - tmp["data"] = a["data"] - r['results'].append(tmp) - except: - pass + mfile = base64.b64decode(request["data"]).decode('utf-8') + misp = json.loads(mfile) + event = misp['response'][0]['Event'] + for a in event["Attribute"]: + tmp = {} + tmp["values"] = a["value"] + tmp["categories"] = a["category"] + tmp["types"] = a["type"] + tmp["to_ids"] = a["to_ids"] + tmp["comment"] = a["comment"] + if a.get("data"): + tmp["data"] = a["data"] + r['results'].append(tmp) + except Exception: + pass return r + def introspection(): modulesetup = {} try: @@ -55,6 +56,7 @@ def version(): moduleinfo['config'] = moduleconfig return moduleinfo + if __name__ == '__main__': x = open('test.json', 'r') r = handler(q=x.read()) diff --git a/misp_modules/modules/import_mod/ocr.py b/misp_modules/modules/import_mod/ocr.py index aafe6538..fef0fd12 100755 --- a/misp_modules/modules/import_mod/ocr.py +++ b/misp_modules/modules/import_mod/ocr.py @@ -1,16 +1,24 @@ +import sys import json import base64 - -from PIL import Image - -from pytesseract import image_to_string from io import BytesIO + +import logging + +log = logging.getLogger('ocr') +log.setLevel(logging.DEBUG) +ch = logging.StreamHandler(sys.stdout) +ch.setLevel(logging.DEBUG) +formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') +ch.setFormatter(formatter) +log.addHandler(ch) + misperrors = {'error': 'Error'} -userConfig = { }; +userConfig = {} inputSource = ['file'] -moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', +moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', 'description': 'Optical Character Recognition (OCR) module for MISP', 'module-type': ['import']} @@ -18,14 +26,60 @@ moduleconfig = [] def handler(q=False): + # try to import modules and return errors if module not found + try: + from PIL import Image + except ImportError: + misperrors['error'] = "Please pip(3) install pillow" + return misperrors + + try: + # Official ImageMagick module + from wand.image import Image as WImage + except ImportError: + misperrors['error'] = "Please pip(3) install wand" + return misperrors + + try: + from pytesseract import image_to_string + except ImportError: + misperrors['error'] = "Please pip(3) install pytesseract" + return misperrors + if q is False: return False r = {'results': []} request = json.loads(q) - image = base64.b64decode(request["data"]) + document = base64.b64decode(request["data"]) + document = WImage(blob=document) + if document.format == 'PDF': + with document as pdf: + # Get number of pages + pages = len(pdf.sequence) + log.debug("PDF with {} page(s) detected".format(pages)) + # Create new image object where the height will be the number of pages. With huge PDFs this will overflow, break, consume silly memory etc… + img = WImage(width=pdf.width, height=pdf.height * pages) + # Cycle through pages and stitch it together to one big file + for p in range(pages): + log.debug("Stitching page {}".format(p + 1)) + image = img.composite(pdf.sequence[p], top=pdf.height * p, left=0) + # Create a png blob + image = img.make_blob('png') + log.debug("Final image size is {}x{}".format(pdf.width, pdf.height * (p + 1))) + else: + image = document + image_file = BytesIO(image) image_file.seek(0) - ocrized = image_to_string(Image.open(image_file)) + + try: + im = Image.open(image_file) + except IOError: + misperrors['error'] = "Corrupt or not an image file." + return misperrors + + ocrized = image_to_string(im) + freetext = {} freetext['values'] = ocrized freetext['types'] = ['freetext'] @@ -52,6 +106,7 @@ def version(): moduleinfo['config'] = moduleconfig return moduleinfo + if __name__ == '__main__': x = open('test.json', 'r') handler(q=x.read()) diff --git a/misp_modules/modules/import_mod/openiocimport.py b/misp_modules/modules/import_mod/openiocimport.py index c237bdcc..074a4649 100755 --- a/misp_modules/modules/import_mod/openiocimport.py +++ b/misp_modules/modules/import_mod/openiocimport.py @@ -63,7 +63,7 @@ def handler(q=False): "comment": getattr(attrib, 'comment', '')} # add tag if q.get('config') and q['config'].get('default tag') is not None: - toAppend["tags"] = q['config']['default tag'].split(",") + toAppend["tags"] = q['config']['default tag'].split(",") r["results"].append(toAppend) return r diff --git a/misp_modules/modules/import_mod/testimport.py b/misp_modules/modules/import_mod/testimport.py index 02369c5d..891b3a68 100755 --- a/misp_modules/modules/import_mod/testimport.py +++ b/misp_modules/modules/import_mod/testimport.py @@ -1,28 +1,27 @@ import json import base64 -import csv misperrors = {'error': 'Error'} userConfig = { - 'number1': { - 'type': 'Integer', - 'regex': '/^[0-4]$/i', - 'errorMessage': 'Expected a number in range [0-4]', - 'message': 'Column number used for value' - }, - 'some_string': { - 'type': 'String', - 'message': 'A text field' - }, - 'boolean_field': { - 'type': 'Boolean', - 'message': 'Boolean field test' - }, - 'comment': { - 'type': 'Integer', - 'message': 'Column number used for comment' - } - }; + 'number1': { + 'type': 'Integer', + 'regex': '/^[0-4]$/i', + 'errorMessage': 'Expected a number in range [0-4]', + 'message': 'Column number used for value' + }, + 'some_string': { + 'type': 'String', + 'message': 'A text field' + }, + 'boolean_field': { + 'type': 'Boolean', + 'message': 'Boolean field test' + }, + 'comment': { + 'type': 'Integer', + 'message': 'Column number used for comment' + } +} inputSource = ['file', 'paste'] @@ -39,8 +38,8 @@ def handler(q=False): r = {'results': []} request = json.loads(q) request["data"] = base64.b64decode(request["data"]) - fields = ["value", "category", "type", "comment"] - r = {"results":[{"values":["192.168.56.1"], "types":["ip-src"], "categories":["Network activity"]}]} + # fields = ["value", "category", "type", "comment"] + r = {"results": [{"values": ["192.168.56.1"], "types":["ip-src"], "categories": ["Network activity"]}]} return r diff --git a/misp_modules/modules/import_mod/threatanalyzer_import.py b/misp_modules/modules/import_mod/threatanalyzer_import.py index fded5081..ff0a5b14 100755 --- a/misp_modules/modules/import_mod/threatanalyzer_import.py +++ b/misp_modules/modules/import_mod/threatanalyzer_import.py @@ -15,7 +15,7 @@ misperrors = {'error': 'Error'} userConfig = {} inputSource = ['file'] -moduleinfo = {'version': '0.6', 'author': 'Christophe Vandeplas', +moduleinfo = {'version': '0.10', 'author': 'Christophe Vandeplas', 'description': 'Import for ThreatAnalyzer archive.zip/analysis.json files', 'module-type': ['import']} @@ -45,16 +45,21 @@ def handler(q=False): if re.match(r"Analysis/proc_\d+/modified_files/mapping\.log", zip_file_name): with zf.open(zip_file_name, mode='r', pwd=None) as fp: file_data = fp.read() - for line in file_data.decode().split('\n'): - if line: + for line in file_data.decode("utf-8", 'ignore').split('\n'): + if not line: + continue + if line.count('|') == 3: l_fname, l_size, l_md5, l_created = line.split('|') - l_fname = cleanup_filepath(l_fname) - if l_fname: - if l_size == 0: - pass # FIXME create an attribute for the filename/path - else: - # file is a non empty sample, upload the sample later - modified_files_mapping[l_md5] = l_fname + if line.count('|') == 4: + l_fname, l_size, l_md5, l_sha256, l_created = line.split('|') + l_fname = cleanup_filepath(l_fname) + if l_fname: + if l_size == 0: + results.append({'values': l_fname, 'type': 'filename', 'to_ids': True, + 'categories': ['Artifacts dropped', 'Payload delivery'], 'comment': ''}) + else: + # file is a non empty sample, upload the sample later + modified_files_mapping[l_md5] = l_fname # now really process the data for zip_file_name in zf.namelist(): # Get all files in the zip file @@ -62,12 +67,12 @@ def handler(q=False): if re.match(r"Analysis/proc_\d+/modified_files/.+\.", zip_file_name) and "mapping.log" not in zip_file_name: sample_md5 = zip_file_name.split('/')[-1].split('.')[0] if sample_md5 in modified_files_mapping: - sample_filename = modified_files_mapping[sample_md5] - # print("{} maps to {}".format(sample_md5, sample_filename)) + current_sample_filename = modified_files_mapping[sample_md5] + # print("{} maps to {}".format(sample_md5, current_sample_filename)) with zf.open(zip_file_name, mode='r', pwd=None) as fp: file_data = fp.read() results.append({ - 'values': sample_filename, + 'values': current_sample_filename, 'data': base64.b64encode(file_data).decode(), 'type': 'malware-sample', 'categories': ['Artifacts dropped', 'Payload delivery'], 'to_ids': True, 'comment': ''}) @@ -76,8 +81,18 @@ def handler(q=False): file_data = fp.read() analysis_json = json.loads(file_data.decode('utf-8')) results += process_analysis_json(analysis_json) - # if 'sample' in zip_file_name: - # sample['data'] = base64.b64encode(file_data).decode() + try: + sample_filename = analysis_json.get('analysis').get('@filename') + if sample_filename: + with zf.open('sample', mode='r', pwd=None) as fp: + file_data = fp.read() + results.append({ + 'values': sample_filename, + 'data': base64.b64encode(file_data).decode(), + 'type': 'malware-sample', 'categories': ['Payload delivery', 'Artifacts dropped'], 'to_ids': True, 'comment': ''}) + except Exception: + # no 'sample' in archive, might be an url analysis, just ignore + pass else: try: @@ -99,7 +114,22 @@ def process_analysis_json(analysis_json): for process in analysis_json['analysis']['processes']['process']: # print_json(process) if 'connection_section' in process and 'connection' in process['connection_section']: + # compensate for absurd behavior of the data format: if one entry = immediately the dict, if multiple entries = list containing dicts + # this will always create a list, even with only one item + if isinstance(process['connection_section']['connection'], dict): + process['connection_section']['connection'] = [process['connection_section']['connection']] + + # iterate over each entry for connection_section_connection in process['connection_section']['connection']: + # compensate for absurd behavior of the data format: if one entry = immediately the dict, if multiple entries = list containing dicts + # this will always create a list, even with only one item + for subsection in ['http_command', 'http_header']: + if isinstance(connection_section_connection[subsection], dict): + connection_section_connection[subsection] = [connection_section_connection[subsection]] + + if 'name_to_ip' in connection_section_connection: # TA 6.1 data format + connection_section_connection['@remote_ip'] = connection_section_connection['name_to_ip']['@result_addresses'] + connection_section_connection['@remote_hostname'] = connection_section_connection['name_to_ip']['@request_name'] connection_section_connection['@remote_ip'] = cleanup_ip(connection_section_connection['@remote_ip']) connection_section_connection['@remote_hostname'] = cleanup_hostname(connection_section_connection['@remote_hostname']) @@ -110,7 +140,7 @@ def process_analysis_json(analysis_json): # connection_section_connection['@remote_hostname'], # connection_section_connection['@remote_ip']) # ) - yield({'values': val, 'type': 'domain|ip', 'categories': 'Network activity', 'to_ids': True, 'comment': ''}) + yield({'values': val, 'type': 'domain|ip', 'categories': ['Network activity'], 'to_ids': True, 'comment': ''}) elif connection_section_connection['@remote_ip']: # print("connection_section_connection ip-dst: {} IDS:yes".format( # connection_section_connection['@remote_ip']) @@ -124,31 +154,31 @@ def process_analysis_json(analysis_json): if 'http_command' in connection_section_connection: for http_command in connection_section_connection['http_command']: # print('connection_section_connection HTTP COMMAND: {}\t{}'.format( - # http_command['@method'], # comment - # http_command['@url']) # url + # connection_section_connection['http_command']['@method'], # comment + # connection_section_connection['http_command']['@url']) # url # ) val = cleanup_url(http_command['@url']) if val: - yield({'values': val, 'type': 'url', 'categories': 'Network activity', 'to_ids': True, 'comment': http_command['@method']}) + yield({'values': val, 'type': 'url', 'categories': ['Network activity'], 'to_ids': True, 'comment': http_command['@method']}) if 'http_header' in connection_section_connection: for http_header in connection_section_connection['http_header']: if 'User-Agent:' in http_header['@header']: val = http_header['@header'][len('User-Agent: '):] - yield({'values': val, 'type': 'user-agent', 'categories': 'Network activity', 'to_ids': False, 'comment': ''}) + yield({'values': val, 'type': 'user-agent', 'categories': ['Network activity'], 'to_ids': False, 'comment': ''}) elif 'Host:' in http_header['@header']: val = http_header['@header'][len('Host: '):] if ':' in val: try: val_port = int(val.split(':')[1]) - except ValueError as e: + except ValueError: val_port = False val_hostname = cleanup_hostname(val.split(':')[0]) val_ip = cleanup_ip(val.split(':')[0]) if val_hostname and val_port: val_combined = '{}|{}'.format(val_hostname, val_port) # print({'values': val_combined, 'type': 'hostname|port', 'to_ids': True, 'comment': ''}) - yield({'values': val_combined, 'type': 'hostname|port', 'to_ids': True, 'comment': ''}) + yield({'values': val_combined, 'type': 'hostname|port', 'categories': ['Network activity'], 'to_ids': True, 'comment': ''}) elif val_ip and val_port: val_combined = '{}|{}'.format(val_ip, val_port) # print({'values': val_combined, 'type': 'ip-dst|port', 'to_ids': True, 'comment': ''}) @@ -193,7 +223,7 @@ def process_analysis_json(analysis_json): # networkoperation_section_dns_request_by_name['@request_name'], # networkoperation_section_dns_request_by_name['@result_addresses']) # ) - yield({'values': val, 'type': 'domain|ip', 'categories': 'Network activity', 'to_ids': True, 'comment': ''}) + yield({'values': val, 'type': 'domain|ip', 'categories': ['Network activity'], 'to_ids': True, 'comment': ''}) elif networkoperation_section_dns_request_by_name['@request_name']: # print("networkoperation_section_dns_request_by_name hostname: {} IDS:yes".format( # networkoperation_section_dns_request_by_name['@request_name']) @@ -217,14 +247,14 @@ def process_analysis_json(analysis_json): # networkpacket_section_connect_to_computer['@remote_port']) # ) val_combined = "{}|{}".format(networkpacket_section_connect_to_computer['@remote_hostname'], networkpacket_section_connect_to_computer['@remote_ip']) - yield({'values': val_combined, 'type': 'hostname|ip', 'to_ids': True, 'comment': ''}) + yield({'values': val_combined, 'type': 'domain|ip', 'to_ids': True, 'comment': ''}) elif networkpacket_section_connect_to_computer['@remote_hostname']: # print("networkpacket_section_connect_to_computer hostname: {} IDS:yes COMMENT:port {}".format( # networkpacket_section_connect_to_computer['@remote_hostname'], # networkpacket_section_connect_to_computer['@remote_port']) # ) val_combined = "{}|{}".format(networkpacket_section_connect_to_computer['@remote_hostname'], networkpacket_section_connect_to_computer['@remote_port']) - yield({'values': val_combined, 'type': 'hostname|port', 'to_ids': True, 'comment': ''}) + yield({'values': val_combined, 'type': 'hostname|port', 'categories': ['Network activity'], 'to_ids': True, 'comment': ''}) elif networkpacket_section_connect_to_computer['@remote_ip']: # print("networkpacket_section_connect_to_computer ip-dst: {} IDS:yes COMMENT:port {}".format( # networkpacket_section_connect_to_computer['@remote_ip'], @@ -295,7 +325,7 @@ def process_analysis_json(analysis_json): for stored_created_file in process['stored_files']['stored_created_file']: stored_created_file['@filename'] = cleanup_filepath(stored_created_file['@filename']) if stored_created_file['@filename']: - if stored_created_file['@filesize'] is not '0': + if stored_created_file['@filesize'] != '0': val = '{}|{}'.format(stored_created_file['@filename'], stored_created_file['@md5']) # print("stored_created_file filename|md5: {}|{} IDS:yes".format( # stored_created_file['@filename'], # filename @@ -316,7 +346,7 @@ def process_analysis_json(analysis_json): for stored_modified_file in process['stored_files']['stored_modified_file']: stored_modified_file['@filename'] = cleanup_filepath(stored_modified_file['@filename']) if stored_modified_file['@filename']: - if stored_modified_file['@filesize'] is not '0': + if stored_modified_file['@filesize'] != '0': val = '{}|{}'.format(stored_modified_file['@filename'], stored_modified_file['@md5']) # print("stored_modified_file MODIFY FILE: {}\t{}".format( # stored_modified_file['@filename'], # filename @@ -411,28 +441,30 @@ def cleanup_url(item): def cleanup_filepath(item): noise_substrings = { - 'C:\\Windows\\Prefetch\\', - '\\AppData\\Roaming\\Microsoft\\Windows\\Recent\\', - '\\AppData\\Roaming\\Microsoft\\Office\\Recent\\', - 'C:\\ProgramData\\Microsoft\\OfficeSoftwareProtectionPlatform\\Cache\\cache.dat', - '\\AppData\\Local\\Microsoft\\Windows\\Temporary Internet Files\\Content.', - '\\AppData\\Local\\Microsoft\\Internet Explorer\\Recovery\\High\\', + '\\AppData\\Local\\GDIPFONTCACHEV1.DAT', '\\AppData\\Local\\Microsoft\\Internet Explorer\\DOMStore\\', - '\\AppData\\LocalLow\\Microsoft\\Internet Explorer\\Services\\search_', - '\\AppData\\Local\\Microsoft\\Windows\\History\\History.', - '\\AppData\\Roaming\\Microsoft\\Windows\\Cookies\\', - '\\AppData\\LocalLow\\Microsoft\\CryptnetUrlCache\\', + '\\AppData\\Local\\Microsoft\\Internet Explorer\\Recovery\\High\\', '\\AppData\\Local\\Microsoft\\Windows\\Caches\\', - '\\AppData\\Local\\Microsoft\\Windows\WebCache\\', '\\AppData\\Local\\Microsoft\\Windows\\Explorer\\thumbcache', + '\\AppData\\Local\\Microsoft\\Windows\\History\\History.', + '\\AppData\\Local\\Microsoft\\Windows\\Temporary Internet Files\\Content.', + '\\AppData\\Local\\Microsoft\\Windows\\WebCache\\', + '\\AppData\\Local\\Temp\\.*tmp$', + '\\AppData\\LocalLow\\Microsoft\\CryptnetUrlCache\\', + '\\AppData\\LocalLow\\Microsoft\\Internet Explorer\\Services\\search_', + '\\AppData\\Roaming\\Microsoft\\Office\\Recent\\', + '\\AppData\\Roaming\\Microsoft\\Windows\\Cookies\\', + '\\AppData\\Roaming\\Microsoft\\Windows\\Recent\\', + 'C:\\ProgramData\\Microsoft\\OfficeSoftwareProtectionPlatform\\Cache\\cache.dat', + 'C:\\Windows\\Prefetch\\', '\\AppData\\Roaming\\Adobe\\Acrobat\\9.0\\SharedDataEvents-journal', '\\AppData\\Roaming\\Adobe\\Acrobat\\9.0\\UserCache.bin', '\\AppData\\Roaming\\Macromedia\\Flash Player\\macromedia.com\\support\\flashplayer\\sys\\settings.sol', - '\\AppData\\Roaming\Adobe\\Flash Player\\NativeCache\\', + '\\AppData\\Roaming\\Adobe\\Flash Player\\NativeCache\\', 'C:\\Windows\\AppCompat\\Programs\\', - 'C:\~' # caused by temp file created by MS Office when opening malicious doc/xls/... + 'C:\\~' # caused by temp file created by MS Office when opening malicious doc/xls/... } if list_in_string(noise_substrings, item): return None @@ -441,24 +473,27 @@ def cleanup_filepath(item): def cleanup_regkey(item): noise_substrings = { - r'\\Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\', - r'\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\', + r'\\CurrentVersion\\Explorer\\FileExts\\[a-z\.]+\\OpenWith', r'\\CurrentVersion\\Explorer\\RecentDocs\\', r'\\CurrentVersion\\Explorer\\UserAssist\\', - r'\\CurrentVersion\\Explorer\\FileExts\\[a-z\.]+\\OpenWith', - r'\\Software\\Microsoft\\Internet Explorer\\Main\\WindowsSearch', - r'\\Software\\Microsoft\\Office\\[0-9\.]+\\', - r'\\SOFTWARE\\Microsoft\\OfficeSoftwareProtectionPlatform\\', - r'\\Software\\Microsoft\\Office\\Common\\Smart Tag\\', - r'\\Usage\\SpellingAndGrammarFiles', - r'^HKLM\\Software\\Microsoft\\Tracing\\', + r'\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\Bag', r'\\Software\\Classes\\CLSID\\', r'\\Software\\Classes\\Local Settings\\MuiCache\\', - r'\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\Bag', - r'\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU\\' + r'\\Software\\Microsoft\\Internet Explorer\\Main\\WindowsSearch', + r'\\Software\\Microsoft\\Office\\[0-9\.]+\\', + r'\\Software\\Microsoft\\Office\\Common\\Smart Tag\\', + r'\\Software\\Microsoft\\OfficeSoftwareProtectionPlatform\\', + r'\\Software\\Microsoft\\Shared Tools\\Panose\\', + r'\\Software\\Microsoft\\Tracing\\', + r'\\Software\\Microsoft\\Tracing\\powershell_RASAPI32\\', + r'\\Software\\Microsoft\\Tracing\\powershell_RASMANCS\\', + r'\\Software\\Microsoft\\Windows\\CurrentVersion\\Action Center\\', + r'\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU\\', + r'\\Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\', + r'\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\', + r'\\System\\CurrentControlSet\\Services\\RdyBoost\\', + r'\\Usage\\SpellingAndGrammarFiles' } - item = item.replace('\\REGISTRY\\MACHINE\\', 'HKLM\\') - item = item.replace('\\REGISTRY\\USER\\', 'HKCU\\') if list_in_string(noise_substrings, item, regex=True): return None return item diff --git a/misp_modules/modules/import_mod/vmray_import.py b/misp_modules/modules/import_mod/vmray_import.py index 88caa8f7..819ea66a 100644 --- a/misp_modules/modules/import_mod/vmray_import.py +++ b/misp_modules/modules/import_mod/vmray_import.py @@ -105,8 +105,8 @@ def handler(q=False): url1 = "https://cloud.vmray.com/user/analysis/view?from_sample_id=%u" % sample_id url2 = "&id=%u" % analysis_id url3 = "&sub=%2Freport%2Foverview.html" - a_id["results"].append({ "values": url1 + url2 + url3, "types": "link" }) - vmray_results = {'results': vmray_results["results"] + a_id["results"] } + a_id["results"].append({"values": url1 + url2 + url3, "types": "link"}) + vmray_results = {'results': vmray_results["results"] + a_id["results"]} # Clean up (remove doubles) if vti_patterns_found: vmray_results = vmrayCleanup(vmray_results) @@ -117,7 +117,7 @@ def handler(q=False): else: misperrors['error'] = "Unable to fetch sample id %u" % (sample_id) return misperrors - except: + except Exception: misperrors['error'] = "Unable to access VMRay API" return misperrors else: @@ -267,7 +267,7 @@ def vmrayGeneric(el, attr="", attrpos=1): if content: if attr: # Some elements are put between \"\" ; replace them to single - content = content.replace("\"\"","\"") + content = content.replace("\"\"", "\"") content_split = content.split("\"") # Attributes are between open " and close "; so use > if len(content_split) > attrpos: diff --git a/setup.py b/setup.py index 3bdc1801..55ed8b7a 100644 --- a/setup.py +++ b/setup.py @@ -12,6 +12,7 @@ setup( description='MISP modules are autonomous modules that can be used for expansion and other services in MISP', packages=find_packages(), entry_points={'console_scripts': ['misp-modules = misp_modules:main']}, + scripts=['tools/update_misp_modules.sh'], test_suite="tests", classifiers=[ 'License :: OSI Approved :: GNU Affero General Public License v3', @@ -23,20 +24,7 @@ setup( ], install_requires=[ 'tornado', - 'dnspython3', - 'requests', - 'urlarchiver', - 'passivetotal', - 'PyPDNS', - 'pypssl', - 'redis', - 'pyeupi', - 'ipasn-redis', - 'asnhistory', - 'stix', - 'cybox', - 'pillow', - 'pytesseract', - 'shodan', + 'psutil', + 'redis>=3' ], ) diff --git a/tests/bodyhashdd.json b/tests/bodyhashdd.json new file mode 100644 index 00000000..3bdfa821 --- /dev/null +++ b/tests/bodyhashdd.json @@ -0,0 +1 @@ +{"module": "hashdd", "md5": "838DE99E82C5B9753BAC96D82C1A8DCC"} diff --git a/tests/query-cve.sh b/tests/query-cve.sh old mode 100755 new mode 100644 diff --git a/tests/query-hashdd.sh b/tests/query-hashdd.sh new file mode 100755 index 00000000..4d736632 --- /dev/null +++ b/tests/query-hashdd.sh @@ -0,0 +1 @@ +curl -s http://127.0.0.1:6666/query -H "Content-Type: application/json" --data @bodyhashdd.json -X POST diff --git a/tests/stix.xml b/tests/stix.xml deleted file mode 100644 index a4a60d8c..00000000 --- a/tests/stix.xml +++ /dev/null @@ -1,331 +0,0 @@ - - - - CNC Server 1 - - - 82.146.166.56 - - - - - CNC Server 2 - - - 209.239.79.47 - - - - - CNC Server 3 - - - 41.213.121.180 - - - - - Watering Hole Wordpress - - - eu-society.com - - - - - Watering Hole Wordpress - - - aromatravel.org - - - - - Watering Hole Wordpress - - - bss.servebbs.com - - - - - - - Watering Hole Detected - URL Watchlist - - - - C2 List - - - C2 List - - - C2 List - - - - - - CnC Beaconing Detected - C2 - - - - - - - - - - - - - - - Malware CnC Channels - - Advantage - - - - Hosting - - - - - - - - - - - - - Fingerprinting and whitelisting during watering-hole operations - - Theft - Credential Theft - - - - Domain Registration - - - C2 List - - - C2 List - - - C2 List - - - - - - - - - - Spear-phishing in tandem with 0-day exploits - - Unauthorized Access - - - - - - - Infiltration of organisations via third party supplier/partner - - Unauthorized Access - - - - - - - Custom recon tool to compromise and identify credentials of the network - - Theft - Credential Theft - - - - - - - Multiple means of C2 communications given the diversity of the attacker toolset - - Advantage - - - - - - - rootkit communicates during the same time as network activity, encoded with an XOR key - - Advantage - - - - - - - Kernel-centric rootkit waits for network trigger before launching - - Advantage - - - - - - - Kernel centric exfiltration over TCP/UDP/DNS/ICMP/HTTP - - Theft - - - - - - - Exfiltration over HTTP/HTTPS - - Theft - - - - - - - Use of previously undocumented functions in their Kernel centric attacks - - Advantage - - - - - - - - - - - - - - - - - Privilage Escalation Vulnerability - - CVE-2013-5065 - - - - - - The Epic Turla Campaign - The Epic Turla Campaign - - Advantage - Political - - - - - - - - - - SNAKE Campaign - The SNAKE Campaign - - Advantage - Political - - - - - - - - - - - - SNAKE - -The group behind the SNAKE campaign are a top tier nation-state threat. Their capabilities extend from subtle watering-hole attacks to sophisticated server rootkits – virtually undetectable by conventional security products. -This threat actor group has been operating continuously for over a decade, infiltrating governments and strategic private sector networks in that time. The most notorious of their early campaigns led to a breach of classified US military systems, an extensive clean-up called ‘Operation Buckshot Yankee’, and led to the creation of the US Cyber Command. -Whilst the sophisticated rootkit is used for persistent access to networks, the group also leverage more straight-forward capabilities for gaining an initial toe-hold on targets. This includes the use of watering-hole attacks and basic remote access tools. - - -The group behind the SNAKE campaign are a top tier nation-state threat. Their capabilities extend from subtle watering-hole attacks to sophisticated server rootkits – virtually undetectable by conventional security products. - - - - - - SNAKE - - - Turla - - - WRAITH - - - - - - Russia - - - Moscow - - - - - snake@gmail.com - twitter.com/snake - - - Russian - - - - - Political - - - Expert - - - Advantage - Political - - - Theft - Intellectual Property - - - - diff --git a/tests/test.py b/tests/test.py index 5a56f5ac..d32bd00a 100644 --- a/tests/test.py +++ b/tests/test.py @@ -57,21 +57,6 @@ class TestModules(unittest.TestCase): assert("mrxcls.sys" in values) assert("mdmcpq3.PNF" in values) - def test_stix(self): - with open("tests/stix.xml", "rb") as f: - content = base64.b64encode(f.read()) - data = json.dumps({"module": "stiximport", - "data": content.decode('utf-8'), - }) - response = requests.post(self.url + "query", data=data).json() - - print("STIX :: {}".format(response)) - values = [x["values"][0] for x in response["results"]] - - assert("209.239.79.47" in values) - assert("41.213.121.180" in values) - assert("eu-society.com" in values) - def test_email_headers(self): query = {"module": "email_import"} query["config"] = {"unzip_attachments": None, diff --git a/tests/test_expansions.py b/tests/test_expansions.py new file mode 100644 index 00000000..d581a316 --- /dev/null +++ b/tests/test_expansions.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +import unittest +import requests +from urllib.parse import urljoin + + +class TestExpansions(unittest.TestCase): + + def setUp(self): + self.maxDiff = None + self.headers = {'Content-Type': 'application/json'} + self.url = "http://127.0.0.1:6666/" + + def misp_modules_post(self, query): + return requests.post(urljoin(self.url, "query"), json=query) + + def get_values(self, response): + return response.json()['results'][0]['values'] + + def test_cve(self): + query = {"module": "cve", "vulnerability": "CVE-2010-3333"} + response = self.misp_modules_post(query) + self.assertTrue(self.get_values(response).startswith("Stack-based buffer overflow in Microsoft Office XP SP3, Office 2003 SP3")) + + def test_dns(self): + query = {"module": "dns", "hostname": "www.circl.lu", "config": {"nameserver": "8.8.8.8"}} + response = self.misp_modules_post(query) + self.assertEqual(self.get_values(response), ['149.13.33.14']) + + def test_macvendors(self): + query = {"module": "macvendors", "mac-address": "FC-A1-3E-2A-1C-33"} + response = self.misp_modules_post(query) + self.assertEqual(self.get_values(response), 'Samsung Electronics Co.,Ltd') + + def test_haveibeenpwned(self): + query = {"module": "hibp", "email-src": "info@circl.lu"} + response = self.misp_modules_post(query) + self.assertEqual(self.get_values(response), 'OK (Not Found)') + + def test_greynoise(self): + query = {"module": "greynoise", "ip-dst": "1.1.1.1"} + response = self.misp_modules_post(query) + self.assertEqual(self.get_values(response)['status'], 'ok') + + def test_ipasn(self): + query = {"module": "ipasn", "ip-dst": "1.1.1.1"} + response = self.misp_modules_post(query) + key = list(self.get_values(response)['response'].keys())[0] + entry = self.get_values(response)['response'][key]['asn'] + self.assertEqual(entry, '13335') + + def test_bgpranking(self): + query = {"module": "bgpranking", "AS": "13335"} + response = self.misp_modules_post(query) + self.assertEqual(self.get_values(response)['response']['asn_description'], 'CLOUDFLARENET - Cloudflare, Inc., US') diff --git a/tests/yara_hash_module_test.yara b/tests/yara_hash_module_test.yara new file mode 100644 index 00000000..4674eef4 --- /dev/null +++ b/tests/yara_hash_module_test.yara @@ -0,0 +1,7 @@ +import "hash" +rule oui { + condition: + hash.md5(0, filesize) == "8764605c6f388c89096b534d33565802" and + hash.sha1(0, filesize) == "46aba99aa7158e4609aaa72b50990842fd22ae86" and + hash.sha256(0, filesize) == "ec5aedf5ecc6bdadd4120932170d1b10f6cfa175cfda22951dfd882928ab279b" +} diff --git a/tests/yara_pe_module_test.yara b/tests/yara_pe_module_test.yara new file mode 100644 index 00000000..4998b84e --- /dev/null +++ b/tests/yara_pe_module_test.yara @@ -0,0 +1,5 @@ +import "pe" +rule my_pe { + condition: + pe.imphash() == "eecc824da5b175f530705611127a6b41" +} diff --git a/tests/yara_test.py b/tests/yara_test.py new file mode 100644 index 00000000..ea88f032 --- /dev/null +++ b/tests/yara_test.py @@ -0,0 +1,22 @@ +import sys +try: + import yara +except (OSError, ImportError): + sys.exit("yara is missing, use 'pip3 install -I -r REQUIREMENTS' from the root of this repository to install it.") + +# Usage: python3 yara_test.py [yara files] +# with any yara file(s) in order to test if yara library is correctly installed. +# (it is also validating yara syntax) +# +# If no argument is given, this script takes the 2 yara test rules in the same directory +# in order to test if both yara modules we need work properly. + +files = sys.argv[1:] if len(sys.argv) > 1 else ['yara_hash_module_test.yara', 'yara_pe_module_test.yara'] + +for file_ in files: + try: + yara.compile(file_) + status = "Valid syntax" + except Exception as e: + status = e + print("{}: {}".format(file_, status)) diff --git a/tools/update_misp_modules.sh b/tools/update_misp_modules.sh new file mode 100755 index 00000000..372d1466 --- /dev/null +++ b/tools/update_misp_modules.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash + +set -e +set -x + +# Updates the MISP Modules while respecting the current permissions +# It aims to support the two following installation methods: +# * Everything is runinng on the same machine following the MISP installation guide. +# * The modules are installed using pipenv on a different machine from the one where MISP is running. + +if [ -d "/var/www/MISP" ] && [ -d "/usr/local/src/misp-modules" ] +then + echo "MISP is installed on the same machine, following the recommanded install script. Using MISP virtualenv." + PATH_TO_MISP="/var/www/MISP" + PATH_TO_MISP_MODULES="/usr/local/src/misp-modules" + + pushd ${PATH_TO_MISP_MODULES} + USER=`stat -c "%U" .` + sudo -H -u ${USER} git pull + sudo -H -u ${USER} ${PATH_TO_MISP}/venv/bin/pip install -U -r REQUIREMENTS + sudo -H -u ${USER} ${PATH_TO_MISP}/venv/bin/pip install -U -e . + + service misp-modules restart + + popd +else + if ! [ -x "$(command -v pipenv)" ]; then + echo 'Error: pipenv not available, unable to automatically update.' >&2 + exit 1 + fi + + echo "Standalone mode, use pipenv from the current directory." + git pull + pipenv install +fi + +