diff --git a/README.rst b/README.rst deleted file mode 120000 index 42061c0..0000000 --- a/README.rst +++ /dev/null @@ -1 +0,0 @@ -README.md \ No newline at end of file diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..fbc9400 --- /dev/null +++ b/README.rst @@ -0,0 +1,225 @@ +# MISP modules + +[![Build Status](https://travis-ci.org/MISP/misp-modules.svg?branch=master)](https://travis-ci.org/MISP/misp-modules) +[![Coverage Status](https://coveralls.io/repos/github/MISP/misp-modules/badge.svg?branch=master)](https://coveralls.io/github/MISP/misp-modules?branch=master) +[![codecov](https://codecov.io/gh/MISP/misp-modules/branch/master/graph/badge.svg)](https://codecov.io/gh/MISP/misp-modules) + +MISP modules are autonomous modules that can be used for expansion and other services in [MISP](https://github.com/MISP/MISP). + +The modules are written in Python 3 following a simple API interface. The objective is to ease the extensions of MISP functionalities +without modifying core components. The API is available via a simple REST API which is independent from MISP installation or configuration. + +MISP modules support is included in MISP starting from version 2.4.28. + +For more information: [Extending MISP with Python modules](https://www.circl.lu/assets/files/misp-training/3.1-MISP-modules.pdf) slides from MISP training. + +## Existing MISP modules + +### 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. +* [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. +* [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. +* [CVE](misp_modules/modules/expansion/cve.py) - a hover module to give more information about a vulnerability (CVE). +* [DNS](misp_modules/modules/expansion/dns.py) - a simple module to resolve MISP attributes like hostname and domain to expand IP addresses attributes. +* [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). +* [IPASN](misp_modules/modules/expansion/ipasn.py) - a hover and expansion to get the BGP ASN of an IP address. +* [passivetotal](misp_modules/modules/expansion/passivetotal.py) - a [passivetotal](https://www.passivetotal.org/) module that queries a number of different PassiveTotal datasets. +* [sourcecache](misp_modules/modules/expansion/sourcecache.py) - a module to cache a specific link from a MISP instance. +* [countrycode](misp_modules/modules/expansion/countrycode.py) - a hover module to tell you what country a URL belongs to. +* [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) + +### Export modules + +* [CEF](misp_modules/modules/export_mod/cef_export.py) module to export Common Event Format (CEF). + +### Import modules + +* [OCR](misp_modules/modules/import_mod/ocr.py) Optical Character Recognition (OCR) module for MISP to import attributes from images, scan or faxes. +* [stiximport](misp_modules/modules/import_mod/stiximport.py) - An import module to process STIX xml/json + +## How to install and start MISP modules? + +~~~~bash +sudo apt-get install python3-dev python3-pip libpq5 +cd /usr/local/src/ +sudo git clone https://github.com/MISP/misp-modules.git +cd misp-modules +sudo pip3 install --upgrade -r REQUIREMENTS +sudo pip3 install --upgrade . +sudo vi /etc/rc.local, add this line: `sudo -u www-data misp-modules -s &` +~~~~ + +## How to add your own MISP modules? + +Create your module in [misp_modules/modules/expansion/](misp_modules/modules/expansion/). The module should have at minimum three functions: + +* **introspection** function that returns a dict of the supported attributes (input and output) by your expansion module. +* **handler** function which accepts a JSON document to expand the values and return a dictionary of the expanded values. +* **version** function that returns a dict with the version and the associated meta-data including potential configurations required of the module. + +Don't forget to return an error key and value if an error is raised to propagate it to the MISP user-interface. + +If your module requires additional configuration (to be exposed via the MISP user-interface), a config array is added to the meta-data output containing all the potential configuration values: + +~~~ +"meta": { + "description": "PassiveTotal expansion service to expand values with multiple Passive DNS sources", + "config": [ + "username", + "password" + ], + "module-type": [ + "expansion", + "hover" + ], + +... +~~~ + +### Module type + +A MISP module can be of two types: + +- **expansion** - service related to an attribute that can be used to extend and update an existing event. +- **hover** - service related to an attribute to provide additional information to the users without updating the event. + +module-type is an array where the list of supported types can be added. + +## Testing your modules? + +MISP uses the **modules** function to discover the available MISP modules and their supported MISP attributes: + +~~~ +% curl -s http://127.0.0.1:6666/modules | jq . +[ + { + "name": "passivetotal", + "type": "expansion", + "mispattributes": { + "input": [ + "hostname", + "domain", + "ip-src", + "ip-dst" + ], + "output": [ + "ip-src", + "ip-dst", + "hostname", + "domain" + ] + }, + "meta": { + "description": "PassiveTotal expansion service to expand values with multiple Passive DNS sources", + "config": [ + "username", + "password" + ], + "author": "Alexandre Dulaunoy", + "version": "0.1" + } + }, + { + "name": "sourcecache", + "type": "expansion", + "mispattributes": { + "input": [ + "link" + ], + "output": [ + "link" + ] + }, + "meta": { + "description": "Module to cache web pages of analysis reports, OSINT sources. The module returns a link of the cached page.", + "author": "Alexandre Dulaunoy", + "version": "0.1" + } + }, + { + "name": "dns", + "type": "expansion", + "mispattributes": { + "input": [ + "hostname", + "domain" + ], + "output": [ + "ip-src", + "ip-dst" + ] + }, + "meta": { + "description": "Simple DNS expansion service to resolve IP address from MISP attributes", + "author": "Alexandre Dulaunoy", + "version": "0.1" + } + } +] + +~~~ + +The MISP module service returns the available modules in a JSON array containing each module name along with their supported input attributes. + +Based on this information, a query can be built in a JSON format and saved as body.json: + +~~~json +{ + "hostname": "www.foo.be", + "module": "dns" +} +~~~ + +Then you can POST this JSON format query towards the MISP object server: + +~~~ +curl -s http://127.0.0.1:6666/query -H "Content-Type: application/json" --data @body.json -X POST +~~~ + +The module should output the following JSON: + +~~~json +{ + "results": [ + { + "types": [ + "ip-src", + "ip-dst" + ], + "values": [ + "188.65.217.78" + ] + } + ] +} +~~~ + +It is also possible to restrict the category options of the resolved attributes by passing a list of categories along (optional): + +~~~json +{ + "results": [ + { + "types": [ + "ip-src", + "ip-dst" + ], + "values": [ + "188.65.217.78" + ], + "categories": [ + "Network activity", + "Payload delivery" + ] + } + ] +} +~~~ + +For both the type and the category lists, the first item in the list will be the default setting on the interface. + +## How to contribute your own module? + +Fork the project, add your module, test it and make a pull-request. Modules can be also private as you can add a module in your own MISP installation. + diff --git a/var/LICENSE b/var/LICENSE new file mode 100644 index 0000000..dbbe355 --- /dev/null +++ b/var/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/var/README.md b/var/README.md new file mode 100644 index 0000000..fbc9400 --- /dev/null +++ b/var/README.md @@ -0,0 +1,225 @@ +# MISP modules + +[![Build Status](https://travis-ci.org/MISP/misp-modules.svg?branch=master)](https://travis-ci.org/MISP/misp-modules) +[![Coverage Status](https://coveralls.io/repos/github/MISP/misp-modules/badge.svg?branch=master)](https://coveralls.io/github/MISP/misp-modules?branch=master) +[![codecov](https://codecov.io/gh/MISP/misp-modules/branch/master/graph/badge.svg)](https://codecov.io/gh/MISP/misp-modules) + +MISP modules are autonomous modules that can be used for expansion and other services in [MISP](https://github.com/MISP/MISP). + +The modules are written in Python 3 following a simple API interface. The objective is to ease the extensions of MISP functionalities +without modifying core components. The API is available via a simple REST API which is independent from MISP installation or configuration. + +MISP modules support is included in MISP starting from version 2.4.28. + +For more information: [Extending MISP with Python modules](https://www.circl.lu/assets/files/misp-training/3.1-MISP-modules.pdf) slides from MISP training. + +## Existing MISP modules + +### 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. +* [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. +* [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. +* [CVE](misp_modules/modules/expansion/cve.py) - a hover module to give more information about a vulnerability (CVE). +* [DNS](misp_modules/modules/expansion/dns.py) - a simple module to resolve MISP attributes like hostname and domain to expand IP addresses attributes. +* [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). +* [IPASN](misp_modules/modules/expansion/ipasn.py) - a hover and expansion to get the BGP ASN of an IP address. +* [passivetotal](misp_modules/modules/expansion/passivetotal.py) - a [passivetotal](https://www.passivetotal.org/) module that queries a number of different PassiveTotal datasets. +* [sourcecache](misp_modules/modules/expansion/sourcecache.py) - a module to cache a specific link from a MISP instance. +* [countrycode](misp_modules/modules/expansion/countrycode.py) - a hover module to tell you what country a URL belongs to. +* [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) + +### Export modules + +* [CEF](misp_modules/modules/export_mod/cef_export.py) module to export Common Event Format (CEF). + +### Import modules + +* [OCR](misp_modules/modules/import_mod/ocr.py) Optical Character Recognition (OCR) module for MISP to import attributes from images, scan or faxes. +* [stiximport](misp_modules/modules/import_mod/stiximport.py) - An import module to process STIX xml/json + +## How to install and start MISP modules? + +~~~~bash +sudo apt-get install python3-dev python3-pip libpq5 +cd /usr/local/src/ +sudo git clone https://github.com/MISP/misp-modules.git +cd misp-modules +sudo pip3 install --upgrade -r REQUIREMENTS +sudo pip3 install --upgrade . +sudo vi /etc/rc.local, add this line: `sudo -u www-data misp-modules -s &` +~~~~ + +## How to add your own MISP modules? + +Create your module in [misp_modules/modules/expansion/](misp_modules/modules/expansion/). The module should have at minimum three functions: + +* **introspection** function that returns a dict of the supported attributes (input and output) by your expansion module. +* **handler** function which accepts a JSON document to expand the values and return a dictionary of the expanded values. +* **version** function that returns a dict with the version and the associated meta-data including potential configurations required of the module. + +Don't forget to return an error key and value if an error is raised to propagate it to the MISP user-interface. + +If your module requires additional configuration (to be exposed via the MISP user-interface), a config array is added to the meta-data output containing all the potential configuration values: + +~~~ +"meta": { + "description": "PassiveTotal expansion service to expand values with multiple Passive DNS sources", + "config": [ + "username", + "password" + ], + "module-type": [ + "expansion", + "hover" + ], + +... +~~~ + +### Module type + +A MISP module can be of two types: + +- **expansion** - service related to an attribute that can be used to extend and update an existing event. +- **hover** - service related to an attribute to provide additional information to the users without updating the event. + +module-type is an array where the list of supported types can be added. + +## Testing your modules? + +MISP uses the **modules** function to discover the available MISP modules and their supported MISP attributes: + +~~~ +% curl -s http://127.0.0.1:6666/modules | jq . +[ + { + "name": "passivetotal", + "type": "expansion", + "mispattributes": { + "input": [ + "hostname", + "domain", + "ip-src", + "ip-dst" + ], + "output": [ + "ip-src", + "ip-dst", + "hostname", + "domain" + ] + }, + "meta": { + "description": "PassiveTotal expansion service to expand values with multiple Passive DNS sources", + "config": [ + "username", + "password" + ], + "author": "Alexandre Dulaunoy", + "version": "0.1" + } + }, + { + "name": "sourcecache", + "type": "expansion", + "mispattributes": { + "input": [ + "link" + ], + "output": [ + "link" + ] + }, + "meta": { + "description": "Module to cache web pages of analysis reports, OSINT sources. The module returns a link of the cached page.", + "author": "Alexandre Dulaunoy", + "version": "0.1" + } + }, + { + "name": "dns", + "type": "expansion", + "mispattributes": { + "input": [ + "hostname", + "domain" + ], + "output": [ + "ip-src", + "ip-dst" + ] + }, + "meta": { + "description": "Simple DNS expansion service to resolve IP address from MISP attributes", + "author": "Alexandre Dulaunoy", + "version": "0.1" + } + } +] + +~~~ + +The MISP module service returns the available modules in a JSON array containing each module name along with their supported input attributes. + +Based on this information, a query can be built in a JSON format and saved as body.json: + +~~~json +{ + "hostname": "www.foo.be", + "module": "dns" +} +~~~ + +Then you can POST this JSON format query towards the MISP object server: + +~~~ +curl -s http://127.0.0.1:6666/query -H "Content-Type: application/json" --data @body.json -X POST +~~~ + +The module should output the following JSON: + +~~~json +{ + "results": [ + { + "types": [ + "ip-src", + "ip-dst" + ], + "values": [ + "188.65.217.78" + ] + } + ] +} +~~~ + +It is also possible to restrict the category options of the resolved attributes by passing a list of categories along (optional): + +~~~json +{ + "results": [ + { + "types": [ + "ip-src", + "ip-dst" + ], + "values": [ + "188.65.217.78" + ], + "categories": [ + "Network activity", + "Payload delivery" + ] + } + ] +} +~~~ + +For both the type and the category lists, the first item in the list will be the default setting on the interface. + +## How to contribute your own module? + +Fork the project, add your module, test it and make a pull-request. Modules can be also private as you can add a module in your own MISP installation. + diff --git a/var/README.rst b/var/README.rst new file mode 100644 index 0000000..fbc9400 --- /dev/null +++ b/var/README.rst @@ -0,0 +1,225 @@ +# MISP modules + +[![Build Status](https://travis-ci.org/MISP/misp-modules.svg?branch=master)](https://travis-ci.org/MISP/misp-modules) +[![Coverage Status](https://coveralls.io/repos/github/MISP/misp-modules/badge.svg?branch=master)](https://coveralls.io/github/MISP/misp-modules?branch=master) +[![codecov](https://codecov.io/gh/MISP/misp-modules/branch/master/graph/badge.svg)](https://codecov.io/gh/MISP/misp-modules) + +MISP modules are autonomous modules that can be used for expansion and other services in [MISP](https://github.com/MISP/MISP). + +The modules are written in Python 3 following a simple API interface. The objective is to ease the extensions of MISP functionalities +without modifying core components. The API is available via a simple REST API which is independent from MISP installation or configuration. + +MISP modules support is included in MISP starting from version 2.4.28. + +For more information: [Extending MISP with Python modules](https://www.circl.lu/assets/files/misp-training/3.1-MISP-modules.pdf) slides from MISP training. + +## Existing MISP modules + +### 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. +* [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. +* [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. +* [CVE](misp_modules/modules/expansion/cve.py) - a hover module to give more information about a vulnerability (CVE). +* [DNS](misp_modules/modules/expansion/dns.py) - a simple module to resolve MISP attributes like hostname and domain to expand IP addresses attributes. +* [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). +* [IPASN](misp_modules/modules/expansion/ipasn.py) - a hover and expansion to get the BGP ASN of an IP address. +* [passivetotal](misp_modules/modules/expansion/passivetotal.py) - a [passivetotal](https://www.passivetotal.org/) module that queries a number of different PassiveTotal datasets. +* [sourcecache](misp_modules/modules/expansion/sourcecache.py) - a module to cache a specific link from a MISP instance. +* [countrycode](misp_modules/modules/expansion/countrycode.py) - a hover module to tell you what country a URL belongs to. +* [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) + +### Export modules + +* [CEF](misp_modules/modules/export_mod/cef_export.py) module to export Common Event Format (CEF). + +### Import modules + +* [OCR](misp_modules/modules/import_mod/ocr.py) Optical Character Recognition (OCR) module for MISP to import attributes from images, scan or faxes. +* [stiximport](misp_modules/modules/import_mod/stiximport.py) - An import module to process STIX xml/json + +## How to install and start MISP modules? + +~~~~bash +sudo apt-get install python3-dev python3-pip libpq5 +cd /usr/local/src/ +sudo git clone https://github.com/MISP/misp-modules.git +cd misp-modules +sudo pip3 install --upgrade -r REQUIREMENTS +sudo pip3 install --upgrade . +sudo vi /etc/rc.local, add this line: `sudo -u www-data misp-modules -s &` +~~~~ + +## How to add your own MISP modules? + +Create your module in [misp_modules/modules/expansion/](misp_modules/modules/expansion/). The module should have at minimum three functions: + +* **introspection** function that returns a dict of the supported attributes (input and output) by your expansion module. +* **handler** function which accepts a JSON document to expand the values and return a dictionary of the expanded values. +* **version** function that returns a dict with the version and the associated meta-data including potential configurations required of the module. + +Don't forget to return an error key and value if an error is raised to propagate it to the MISP user-interface. + +If your module requires additional configuration (to be exposed via the MISP user-interface), a config array is added to the meta-data output containing all the potential configuration values: + +~~~ +"meta": { + "description": "PassiveTotal expansion service to expand values with multiple Passive DNS sources", + "config": [ + "username", + "password" + ], + "module-type": [ + "expansion", + "hover" + ], + +... +~~~ + +### Module type + +A MISP module can be of two types: + +- **expansion** - service related to an attribute that can be used to extend and update an existing event. +- **hover** - service related to an attribute to provide additional information to the users without updating the event. + +module-type is an array where the list of supported types can be added. + +## Testing your modules? + +MISP uses the **modules** function to discover the available MISP modules and their supported MISP attributes: + +~~~ +% curl -s http://127.0.0.1:6666/modules | jq . +[ + { + "name": "passivetotal", + "type": "expansion", + "mispattributes": { + "input": [ + "hostname", + "domain", + "ip-src", + "ip-dst" + ], + "output": [ + "ip-src", + "ip-dst", + "hostname", + "domain" + ] + }, + "meta": { + "description": "PassiveTotal expansion service to expand values with multiple Passive DNS sources", + "config": [ + "username", + "password" + ], + "author": "Alexandre Dulaunoy", + "version": "0.1" + } + }, + { + "name": "sourcecache", + "type": "expansion", + "mispattributes": { + "input": [ + "link" + ], + "output": [ + "link" + ] + }, + "meta": { + "description": "Module to cache web pages of analysis reports, OSINT sources. The module returns a link of the cached page.", + "author": "Alexandre Dulaunoy", + "version": "0.1" + } + }, + { + "name": "dns", + "type": "expansion", + "mispattributes": { + "input": [ + "hostname", + "domain" + ], + "output": [ + "ip-src", + "ip-dst" + ] + }, + "meta": { + "description": "Simple DNS expansion service to resolve IP address from MISP attributes", + "author": "Alexandre Dulaunoy", + "version": "0.1" + } + } +] + +~~~ + +The MISP module service returns the available modules in a JSON array containing each module name along with their supported input attributes. + +Based on this information, a query can be built in a JSON format and saved as body.json: + +~~~json +{ + "hostname": "www.foo.be", + "module": "dns" +} +~~~ + +Then you can POST this JSON format query towards the MISP object server: + +~~~ +curl -s http://127.0.0.1:6666/query -H "Content-Type: application/json" --data @body.json -X POST +~~~ + +The module should output the following JSON: + +~~~json +{ + "results": [ + { + "types": [ + "ip-src", + "ip-dst" + ], + "values": [ + "188.65.217.78" + ] + } + ] +} +~~~ + +It is also possible to restrict the category options of the resolved attributes by passing a list of categories along (optional): + +~~~json +{ + "results": [ + { + "types": [ + "ip-src", + "ip-dst" + ], + "values": [ + "188.65.217.78" + ], + "categories": [ + "Network activity", + "Payload delivery" + ] + } + ] +} +~~~ + +For both the type and the category lists, the first item in the list will be the default setting on the interface. + +## How to contribute your own module? + +Fork the project, add your module, test it and make a pull-request. Modules can be also private as you can add a module in your own MISP installation. + diff --git a/var/REQUIREMENTS b/var/REQUIREMENTS new file mode 100644 index 0000000..92a84d7 --- /dev/null +++ b/var/REQUIREMENTS @@ -0,0 +1,17 @@ +stix +cybox +tornado +dnspython3 +requests +urlarchiver +passivetotal +PyPDNS +pypssl +redis +pyeupi +ipasn-redis +asnhistory +git+https://github.com/Rafiot/uwhoisd.git@testing#egg=uwhois&subdirectory=client +pillow +pytesseract +SPARQLWrapper diff --git a/var/misp_modules/__init__.py b/var/misp_modules/__init__.py new file mode 100644 index 0000000..1edfc86 --- /dev/null +++ b/var/misp_modules/__init__.py @@ -0,0 +1,249 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# +# Core MISP expansion modules loader and web service +# +# Copyright (C) 2016 Alexandre Dulaunoy +# Copyright (C) 2016 CIRCL - Computer Incident Response Center Luxembourg +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . + +import os +import signal +import sys +import importlib +import json +import logging +import fnmatch +import argparse +import re +import datetime + +import tornado.web +import tornado.process +from tornado.ioloop import IOLoop +from tornado.concurrent import run_on_executor +from concurrent.futures import ThreadPoolExecutor + +try: + from .modules import * + HAS_PACKAGE_MODULES = True +except Exception as e: + print(e) + HAS_PACKAGE_MODULES = False + +try: + from .helpers import * + HAS_PACKAGE_HELPERS = True +except Exception as e: + print(e) + HAS_PACKAGE_HELPERS = False + +log = logging.getLogger('misp-modules') + + +def handle_signal(sig, frame): + IOLoop.instance().add_callback(IOLoop.instance().stop) + + +def init_logger(level=False): + formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') + handler = logging.StreamHandler(stream=sys.stdout) + handler.setFormatter(formatter) + handler.setLevel(logging.INFO) + if level: + handler.setLevel(logging.DEBUG) + log.addHandler(handler) + log.setLevel(logging.INFO) + if level: + log.setLevel(logging.DEBUG) + return log + + +def load_helpers(helpersdir): + sys.path.append(helpersdir) + hhandlers = {} + helpers = [] + for root, dirnames, filenames in os.walk(helpersdir): + if os.path.basename(root) == '__pycache__': + continue + if re.match(r'^\.', os.path.basename(root)): + continue + for filename in fnmatch.filter(filenames, '*.py'): + if filename == '__init__.py': + continue + helpername = filename.split(".")[0] + hhandlers[helpername] = importlib.import_module(helpername) + selftest = hhandlers[helpername].selftest() + if selftest is None: + helpers.append(helpername) + log.info('Helpers loaded {} '.format(filename)) + else: + log.info('Helpers failed {} due to {}'.format(filename, selftest)) + + +def load_package_helpers(): + if not HAS_PACKAGE_HELPERS: + log.info('Unable to load MISP helpers from package.') + sys.exit() + mhandlers = {} + helpers = [] + for path, helper in sys.modules.items(): + if not path.startswith('misp_modules.helpers.'): + continue + helpername = path.replace('misp_modules.helpers.', '') + mhandlers[helpername] = helper + selftest = mhandlers[helpername].selftest() + if selftest is None: + helpers.append(helpername) + log.info('Helper loaded {}'.format(helpername)) + else: + log.info('Helpers failed {} due to {}'.format(helpername, selftest)) + return mhandlers, helpers + + +def load_modules(mod_dir): + sys.path.append(mod_dir) + mhandlers = {} + modules = [] + for root, dirnames, filenames in os.walk(mod_dir): + if os.path.basename(root) == '__pycache__': + continue + if os.path.basename(root).startswith("."): + continue + for filename in fnmatch.filter(filenames, '*.py'): + if root.split('/')[-1].startswith('_'): + continue + if filename == '__init__.py': + continue + modulename = filename.split(".")[0] + moduletype = os.path.split(mod_dir)[1] + try: + mhandlers[modulename] = importlib.import_module(os.path.basename(root) + '.' + modulename) + except Exception as e: + log.warning('MISP modules {0} failed due to {1}'.format(modulename, e)) + continue + modules.append(modulename) + log.info('MISP modules {0} imported'.format(modulename)) + mhandlers['type:' + modulename] = moduletype + return mhandlers, modules + + +def load_package_modules(): + if not HAS_PACKAGE_MODULES: + log.info('Unable to load MISP modules from package.') + sys.exit() + mhandlers = {} + modules = [] + for path, module in sys.modules.items(): + r = re.findall("misp_modules[.]modules[.](\w+)[.]([^_]\w+)", path) + if r and len(r[0]) == 2: + moduletype, modulename = r[0] + mhandlers[modulename] = module + modules.append(modulename) + log.info('MISP modules {0} imported'.format(modulename)) + mhandlers['type:' + modulename] = moduletype + return mhandlers, modules + + +class ListModules(tornado.web.RequestHandler): + def get(self): + ret = [] + for module in loaded_modules: + x = {} + x['name'] = module + x['type'] = mhandlers['type:' + module] + x['mispattributes'] = mhandlers[module].introspection() + x['meta'] = mhandlers[module].version() + ret.append(x) + log.debug('MISP ListModules request') + self.write(json.dumps(ret)) + + +class QueryModule(tornado.web.RequestHandler): + + # Default value in Python 3.5 + # https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor + nb_threads = tornado.process.cpu_count() * 5 + executor = ThreadPoolExecutor(nb_threads) + + @run_on_executor + def run_request(self, jsonpayload): + x = json.loads(jsonpayload) + log.debug('MISP QueryModule request {0}'.format(jsonpayload)) + response = mhandlers[x['module']].handler(q=jsonpayload) + return json.dumps(response) + + @tornado.gen.coroutine + def post(self): + try: + jsonpayload = self.request.body.decode('utf-8') + dict_payload = json.loads(jsonpayload) + if dict_payload.get('timeout'): + timeout = datetime.timedelta(seconds=int(dict_payload.get('timeout'))) + else: + timeout = datetime.timedelta(seconds=30) + response = yield tornado.gen.with_timeout(timeout, self.run_request(jsonpayload)) + self.write(response) + except tornado.gen.TimeoutError: + log.warning('Timeout on {} '.format(dict_payload['module'])) + self.write(json.dumps({'error': 'Timeout.'})) + except Exception: + self.write(json.dumps({'error': 'Something went wrong, look in the server logs for details'})) + log.exception('Something went wrong:') + finally: + self.finish() + + +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.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)') + 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() + 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) + service = [(r'/modules', ListModules), (r'/query', QueryModule)] + + application = tornado.web.Application(service) + application.listen(port, address=listen) + 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() + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/var/misp_modules/helpers/__init__.py b/var/misp_modules/helpers/__init__.py new file mode 100644 index 0000000..cd16c88 --- /dev/null +++ b/var/misp_modules/helpers/__init__.py @@ -0,0 +1 @@ +__all__ = ['cache'] diff --git a/var/misp_modules/helpers/cache.py b/var/misp_modules/helpers/cache.py new file mode 100644 index 0000000..7d70159 --- /dev/null +++ b/var/misp_modules/helpers/cache.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# +# MISP modules helper - cache +# +# Copyright (C) 2016 Alexandre Dulaunoy +# Copyright (C) 2016 CIRCL - Computer Incident Response Center Luxembourg +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . + +import redis +import hashlib + +port = 6379 +hostname = '127.0.0.1' +db = 5 + + +def selftest(enable=True): + if not enable: + return False + r = redis.StrictRedis(host=hostname, port=port, db=db) + try: + r.ping() + except: + 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) + h = hashlib.sha1() + h.update(query.encode('UTF-8')) + hv = h.hexdigest() + key = "m:" + modulename + ":" + hv + + if not r.exists(key): + if debug: + print("Key {} added in cache".format(key)) + r.setex(key, 86400, value) + else: + if debug: + print("Cache hit with Key {}".format(key)) + + return r.get(key) + + +def flush(): + r = redis.StrictRedis(host=hostname, port=port, db=db) + returncode = r.flushdb() + return returncode + +if __name__ == "__main__": + import sys + if selftest() is not None: + sys.exit() + else: + print("Selftest ok") + v = get(modulename="testmodule", query="abcdef", value="barfoo", debug=True) + if v == b'barfoo': + print("Cache ok") + v = get(modulename="testmodule", query="abcdef") + print(v) + v = get(modulename="testmodule") + if (not v): + print("Failed ok") + if flush(): + print("Cache flushed ok") diff --git a/var/misp_modules/modules/__init__.py b/var/misp_modules/modules/__init__.py new file mode 100644 index 0000000..65ce6b2 --- /dev/null +++ b/var/misp_modules/modules/__init__.py @@ -0,0 +1,3 @@ +from .expansion import * +from .import_mod import * +from .export_mod import * diff --git a/var/misp_modules/modules/expansion/__init__.py b/var/misp_modules/modules/expansion/__init__.py new file mode 100644 index 0000000..62a6ecd --- /dev/null +++ b/var/misp_modules/modules/expansion/__init__.py @@ -0,0 +1,4 @@ +from . import _vmray + +__all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl', 'countrycode', 'cve', 'dns', + 'eupi', 'ipasn', 'passivetotal', 'sourcecache', 'virustotal', 'whois', 'shodan', 'reversedns', 'wiki'] diff --git a/var/misp_modules/modules/expansion/_vmray/__init__.py b/var/misp_modules/modules/expansion/_vmray/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/var/misp_modules/modules/expansion/_vmray/vmray_rest_api.py b/var/misp_modules/modules/expansion/_vmray/vmray_rest_api.py new file mode 100644 index 0000000..4d5245b --- /dev/null +++ b/var/misp_modules/modules/expansion/_vmray/vmray_rest_api.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +"""Python client library for VMRay REST API""" + +import base64 +import datetime +import os.path +import requests +import urllib.parse + +# disable nasty certification warning +# pylint: disable=no-member +try: + requests.packages.urllib3.disable_warnings() +except AttributeError: + try: + import urllib3 + try: + urllib3.disable_warnings() + except AttributeError: + pass + except ImportError: + pass + +# pylint: disable= + + +class VMRayRESTAPIError(Exception): + """Exception class that is used when API returns an error""" + + def __init__(self, *args, **kwargs): + self.status_code = kwargs.pop("status_code", None) + Exception.__init__(self, *args, **kwargs) + + +def handle_rest_api_result(result): + """Handle result of API request (check for errors)""" + + if (result.status_code < 200) or (result.status_code > 299): + try: + json_result = result.json() + except ValueError: + raise VMRayRESTAPIError("API returned error %u: %s" % (result.status_code, result.text), status_code=result.status_code) + + raise VMRayRESTAPIError(json_result.get("error_msg", "Unknown error"), status_code=result.status_code) + + +class VMRayRESTAPI(object): + """VMRay REST API class""" + + def __init__(self, server, api_key, verify_cert=True): + # split server URL into components + url_desc = urllib.parse.urlsplit(server) + + # assume HTTPS if no scheme is specified + if url_desc.scheme == "": + server = "https://" + server + + # save variables + self.server = server + self.api_key = api_key + self.verify_cert = verify_cert + + def call(self, http_method, api_path, params=None, raw_data=False): + """Call VMRay REST API""" + + # get function of requests package + requests_func = getattr(requests, http_method.lower()) + + # parse parameters + req_params = {} + file_params = {} + + if params is not None: + for key, value in params.items(): + if isinstance(value, (datetime.date, + datetime.datetime, + float, + int)): + req_params[key] = str(value) + elif isinstance(value, str): + req_params[key] = str(value) + elif isinstance(value, dict): + filename = value["filename"] + sample = value["data"] + file_params[key] = (filename, sample, "application/octet-stream") + elif hasattr(value, "read"): + filename = os.path.split(value.name)[1] + # For the following block refer to DEV-1820 + try: + filename.decode("ASCII") + except (UnicodeDecodeError, UnicodeEncodeError): + b64_key = key + "name_b64enc" + byte_value = filename.encode("utf-8") + b64_value = base64.b64encode(byte_value) + + filename = "@param=%s" % b64_key + req_params[b64_key] = b64_value + file_params[key] = (filename, value, "application/octet-stream") + else: + raise VMRayRESTAPIError("Parameter \"%s\" has unknown type \"%s\"" % (key, type(value))) + + # construct request + if file_params: + files = file_params + else: + files = None + + # we need to adjust some stuff for POST requests + if http_method.lower() == "post": + req_data = req_params + req_params = None + else: + req_data = None + + # do request + result = requests_func(self.server + api_path, data=req_data, params=req_params, headers={"Authorization": "api_key " + self.api_key}, files=files, verify=self.verify_cert, stream=raw_data) + handle_rest_api_result(result) + + if raw_data: + return result.raw + + # parse result + try: + json_result = result.json() + except ValueError: + raise ValueError("API returned invalid JSON: %s" % (result.text)) + + # if there are no cached elements then return the data + if "continuation_id" not in json_result: + return json_result.get("data", None) + + data = json_result["data"] + + # get cached results + while "continuation_id" in json_result: + # send request to server + result = requests.get("%s/rest/continuation/%u" % (self.server, json_result["continuation_id"]), headers={"Authorization": "api_key " + self.api_key}, verify=self.verify_cert) + handle_rest_api_result(result) + + # parse result + try: + json_result = result.json() + except ValueError: + raise ValueError("API returned invalid JSON: %s" % (result.text)) + + data.extend(json_result["data"]) + + return data diff --git a/var/misp_modules/modules/expansion/asn_history.py b/var/misp_modules/modules/expansion/asn_history.py new file mode 100755 index 0000000..9775f6d --- /dev/null +++ b/var/misp_modules/modules/expansion/asn_history.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- + +import json +from asnhistory import ASNHistory + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['AS'], 'output': ['freetext']} +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: + return False + request = json.loads(q) + if request.get('AS'): + toquery = request['AS'] + else: + 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)] + + if not values: + misperrors['error'] = 'Unable to find descriptions for this ASN' + return misperrors + return {'results': [{'types': mispattributes['output'], 'values': values}]} + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/var/misp_modules/modules/expansion/circl_passivedns.py b/var/misp_modules/modules/expansion/circl_passivedns.py new file mode 100755 index 0000000..3da5bac --- /dev/null +++ b/var/misp_modules/modules/expansion/circl_passivedns.py @@ -0,0 +1,47 @@ +import json +import pypdns + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['hostname', 'domain', 'ip-src', 'ip-dst'], 'output': ['freetext']} +moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', 'description': 'Module to access CIRCL Passive DNS', 'module-type': ['expansion', 'hover']} +moduleconfig = ['username', 'password'] + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + if request.get('hostname'): + toquery = request['hostname'] + elif request.get('domain'): + toquery = request['domain'] + elif request.get('ip-src'): + toquery = request['ip-src'] + elif request.get('ip-dst'): + toquery = request['ip-dst'] + else: + misperrors['error'] = "Unsupported attributes type" + return misperrors + + if (request.get('config')): + if (request['config'].get('username') is None) or (request['config'].get('password') is None): + misperrors['error'] = 'CIRCL Passive DNS authentication is missing' + return misperrors + + x = pypdns.PyPDNS(basic_auth=(request['config']['username'], request['config']['password'])) + res = x.query(toquery) + out = '' + for v in res: + out = out + "{} ".format(v['rdata']) + + r = {'results': [{'types': mispattributes['output'], 'values': out}]} + return r + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/var/misp_modules/modules/expansion/circl_passivessl.py b/var/misp_modules/modules/expansion/circl_passivessl.py new file mode 100755 index 0000000..c6d5a3f --- /dev/null +++ b/var/misp_modules/modules/expansion/circl_passivessl.py @@ -0,0 +1,41 @@ +import json +import pypssl + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['ip-src', 'ip-dst'], 'output': ['freetext']} +moduleinfo = {'version': '0.1', 'author': 'Raphaël Vinot', 'description': 'Module to access CIRCL Passive SSL', 'module-type': ['expansion', 'hover']} +moduleconfig = ['username', 'password'] + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + if request.get('ip-src'): + toquery = request['ip-src'] + elif request.get('ip-dst'): + toquery = request['ip-dst'] + else: + misperrors['error'] = "Unsupported attributes type" + return misperrors + + if request.get('config'): + if (request['config'].get('username') is None) or (request['config'].get('password') is None): + misperrors['error'] = 'CIRCL Passive SSL authentication is missing' + return misperrors + + x = pypssl.PyPSSL(basic_auth=(request['config']['username'], request['config']['password'])) + res = x.query(toquery) + out = res.get(toquery) + + r = {'results': [{'types': mispattributes['output'], 'values': out}]} + return r + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/var/misp_modules/modules/expansion/countrycode.py b/var/misp_modules/modules/expansion/countrycode.py new file mode 100755 index 0000000..af58fc6 --- /dev/null +++ b/var/misp_modules/modules/expansion/countrycode.py @@ -0,0 +1,59 @@ +import json +import requests + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['hostname', 'domain']} + +# possible module-types: 'expansion', 'hover' or both +moduleinfo = {'version': '1', 'author': 'Hannah Ward', + 'description': 'Expand Country Codes', + 'module-type': ['hover']} + +# 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)" + } + +codes = requests.get("http://www.geognos.com/api/en/countries/info/all.json").json() + +def handler(q=False): + global codes + if q is False: + return False + request = json.loads(q) + domain = request["domain"] + + # Get the extension + ext = domain.split(".")[-1] + + # Check if if's a common, non country one + if ext in common_tlds.keys(): + 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]}]} + return r + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo + diff --git a/var/misp_modules/modules/expansion/cve.py b/var/misp_modules/modules/expansion/cve.py new file mode 100755 index 0000000..e370116 --- /dev/null +++ b/var/misp_modules/modules/expansion/cve.py @@ -0,0 +1,38 @@ +import json +import requests + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['vulnerability'], 'output': ['text']} +moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion hover module to expand information about CVE id.', 'module-type': ['hover']} +moduleconfig = [] +cveapi_url = 'https://cve.circl.lu/api/cve/' + + +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 + + r = requests.get(cveapi_url + request.get('vulnerability')) + if r.status_code == 200: + vulnerability = json.loads(r.text) + if vulnerability.get('summary'): + summary = vulnerability['summary'] + else: + misperrors['error'] = 'cve.circl.lu API not accessible' + 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/var/misp_modules/modules/expansion/dns.py b/var/misp_modules/modules/expansion/dns.py new file mode 100755 index 0000000..41da8b2 --- /dev/null +++ b/var/misp_modules/modules/expansion/dns.py @@ -0,0 +1,61 @@ +import json +import dns.resolver + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['hostname', 'domain', 'domain|ip'], 'output': ['ip-src', + 'ip-dst']} +moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', + 'description': 'Simple DNS expansion service to resolve IP address from MISP attributes', + 'module-type': ['expansion', 'hover']} + +moduleconfig = ['nameserver'] + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + if request.get('hostname'): + toquery = request['hostname'] + elif request.get('domain'): + toquery = request['domain'] + elif request.get('domain|ip'): + toquery = request['domain|ip'].split('|')[0] + else: + return False + r = dns.resolver.Resolver() + r.timeout = 2 + r.lifetime = 2 + + if request.get('config'): + if request['config'].get('nameserver'): + nameservers = [] + nameservers.append(request['config'].get('nameserver')) + r.nameservers = nameservers + else: + r.nameservers = ['8.8.8.8'] + + try: + answer = r.query(toquery, 'A') + except dns.resolver.NXDOMAIN: + misperrors['error'] = "NXDOMAIN" + return misperrors + except dns.exception.Timeout: + misperrors['error'] = "Timeout" + return misperrors + except: + misperrors['error'] = "DNS resolving error" + return misperrors + + r = {'results': [{'types': mispattributes['output'], + 'values':[str(answer[0])]}]} + return r + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/var/misp_modules/modules/expansion/eupi.py b/var/misp_modules/modules/expansion/eupi.py new file mode 100755 index 0000000..e230bcf --- /dev/null +++ b/var/misp_modules/modules/expansion/eupi.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- + +import json +from pyeupi import PyEUPI + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['hostname', 'domain', 'url'], 'output': ['freetext']} +moduleinfo = {'version': '0.1', 'author': 'Raphaël Vinot', + 'description': 'Query the Phishing Initiative service (https://phishing-initiative.lu)', + 'module-type': ['expansion', 'hover']} + +moduleconfig = ['apikey', 'url'] + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + if request.get('hostname'): + toquery = request['hostname'] + elif request.get('domain'): + toquery = request['domain'] + elif request.get('url'): + toquery = request['url'] + else: + misperrors['error'] = "Unsupported attributes type" + return misperrors + + if not request.get('config') and not (request['config'].get('apikey') and request['config'].get('url')): + misperrors['error'] = 'EUPI authentication is missing' + return misperrors + + pyeupi = PyEUPI(request['config']['apikey'], request['config']['url']) + + if 'event_id' in request: + return handle_expansion(pyeupi, toquery) + else: + return handle_hover(pyeupi, toquery) + + +def handle_expansion(pyeupi, url): + results = pyeupi.search_url(url=url) + + if results.get('results'): + to_return = '' + for r in results['results']: + if r['tag_label'] != 'phishing': + continue + to_return += ' {} {} {} '.format(r['url'], r['domain'], r['ip_address']) + if to_return: + return {'results': [{'types': mispattributes['output'], 'values': to_return}]} + else: + misperrors['error'] = 'Unknown in the EUPI service' + return misperrors + else: + return {'results': [{'types': mispattributes['output'], 'values': ''}]} + + +def handle_hover(pyeupi, url): + try: + result = pyeupi.lookup(url=url)['results'][0] + except (KeyError, IndexError): + misperrors['error'] = 'Error in EUPI lookup' + return misperrors + + return {'results': [{'types': mispattributes['output'], + 'values': result['tag_label'].title()}]} + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/var/misp_modules/modules/expansion/intelmq_eventdb.py.experimental b/var/misp_modules/modules/expansion/intelmq_eventdb.py.experimental new file mode 100755 index 0000000..0e40608 --- /dev/null +++ b/var/misp_modules/modules/expansion/intelmq_eventdb.py.experimental @@ -0,0 +1,67 @@ +import json +import psycopg2 + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['hostname', 'domain', 'ip-src', 'ip-dst', 'AS'], 'output': ['freetext']} +moduleinfo = {'version': '0.1', 'author': 'L. Aaron Kaplan ', 'description': 'Module to access intelmqs eventdb', 'module-type': ['expansion', 'hover']} +moduleconfig = ['username', 'password', 'hostname', 'database'] + + +def connect(user, password, host, dbname): + try: + conn = psycopg2.connect(database=dbname, user=user, host=host, password=password) + except Exception as e: + print("I am unable to connect to the database: %s" %e) + return conn + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + #if request.get('hostname'): + # toquery = request['hostname'] + #elif request.get('domain'): + # toquery = request['domain'] + if request.get('ip-src'): + toquery = request['ip-src'] + #elif request.get('ip-dst'): + # toquery = request['ip-dst'] + #elif request.get('AS'): + # toquery = request['AS'] + else: + misperrors['error'] = "Unsupported attributes type" + return misperrors + + if (request.get('config')): + if (request['config'].get('username') is None) or (request['config'].get('password') is None): + misperrors['error'] = 'intelmq eventdb authentication is missing' + return misperrors + + conn = connect(request['config']['username'], request['config']['password'], request['config']['hostname'], request['config']['database']) + cur = conn.cursor() + SQL1 = 'SELECT COUNT(*) from events where "source.ip" = \'%s\'' %(toquery) + try: + cur.execute(SQL1) + except Exception as e: + misperrors['error'] = 'can not query database' + print(e) + return misperrors + + results = cur.fetchone() + + out = '' + out = out + "{} ".format(results[0]) + " results found in the DB" + + r = {'results': [{'types': mispattributes['output'], 'values': out}]} + conn.close() + return r + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/var/misp_modules/modules/expansion/ipasn.py b/var/misp_modules/modules/expansion/ipasn.py new file mode 100755 index 0000000..22c9a70 --- /dev/null +++ b/var/misp_modules/modules/expansion/ipasn.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- + +import json +from ipasn_redis import IPASN + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['ip-src', 'ip-dst'], 'output': ['freetext']} +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: + return False + request = json.loads(q) + if request.get('ip-src'): + toquery = request['ip-src'] + elif request.get('ip-dst'): + toquery = request['ip-dst'] + else: + 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)) + + if not values: + misperrors['error'] = 'Unable to find the history of this IP' + return misperrors + return {'results': [{'types': mispattributes['output'], 'values': values}]} + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/var/misp_modules/modules/expansion/passivetotal.py b/var/misp_modules/modules/expansion/passivetotal.py new file mode 100755 index 0000000..5325d19 --- /dev/null +++ b/var/misp_modules/modules/expansion/passivetotal.py @@ -0,0 +1,346 @@ +import json +import logging +import sys + +from passivetotal.common.utilities import is_ip + + +log = logging.getLogger('passivetotal') +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', + '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': ['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'] +} +moduleinfo = { + 'version': '1.0', + 'author': 'Brandon Dixon', + 'description': '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', + 'module-type': ['expansion', 'hover'] +} +moduleconfig = ['username', 'api_key'] +query_playbook = [ + {'inputs': ['ip-src', 'ip-dst', 'hostname', 'domain'], + 'services': ['whois', 'ssl', 'dns', 'enrichment'], + 'name': 'generic'}, + {'inputs': ['whois-registrant-email', 'whois-registrant-phone', + 'whois-registrant-name', 'email-src', 'email-dst', + 'target-email'], + 'services': ['whois'], + 'name': 'reverse-whois'}, + {'inputs': ['x509-fingerprint-sha1'], + 'services': ['ssl'], + 'name': 'ssl-history'}, +] + + +def query_finder(request): + """Find the query value in the client request.""" + for item in mispattributes['input']: + if not request.get(item, None): + continue + + playbook = None + for x in query_playbook: + if item not in x['inputs']: + continue + playbook = x + break + + return {'type': item, 'value': request.get(item), 'playbook': playbook} + + +def build_profile(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'] = "PassiveTotal authentication is missing." + return output + + profile = {'success': True, 'config': config} + profile.update(query_finder(request)) + + return profile + + +def _generate_request_instance(conf, request_type): + """Automatically generate a request instance to use. + + In the end, this saves us from having to load each request class in a + explicit way. Loading via a string is helpful to reduce the code per + call. + + :param request_type: Type of client to load + :return: Loaded PassiveTotal client + """ + pt_username = conf.get('username') + pt_api_key = conf.get('api_key') + + class_lookup = {'dns': 'DnsRequest', 'whois': 'WhoisRequest', + 'ssl': 'SslRequest', 'enrichment': 'EnrichmentRequest', + 'attributes': 'AttributeRequest'} + class_name = class_lookup[request_type] + mod = __import__('passivetotal.libs.%s' % request_type, + fromlist=[class_name]) + loaded = getattr(mod, class_name) + headers = {'PT-INTEGRATION': 'MISP'} + authenticated = loaded(pt_username, pt_api_key, headers=headers) + return authenticated + + +def _has_error(results): + """Check to see if there's an error in place and log it.""" + if 'error' in results: + msg = "%s - %s" % (results['error']['message'], + results['error']['developer_message']) + misperrors['error'] = msg + return True + + return False + + +def process_ssl_details(instance, query): + """Process details for a specific certificate.""" + log.debug("SSL Details: starting") + values = list() + _ = instance.get_ssl_certificate_details(query=query) + err = _has_error(_) + if err: + raise Exception("We hit an error, time to bail!") + + for key, value in _.items(): + if not value: + continue + values.append(value) + txt = [{'types': ['ssl-cert-attributes'], 'values': list(set(values))}] + log.debug("SSL Details: ending") + + return txt + + +def process_ssl_history(instance, query): + """Process the history for an SSL certificate.""" + log.debug("SSL History: starting") + + type_map = { + 'ip': ['ip-src', 'ip-dst'], + 'domain': ['domain', 'hostname'], + 'sha1': ['x509-fingerprint-sha1'] + } + + hits = {'ip': list(), 'sha1': list(), 'domain': list()} + _ = instance.get_ssl_certificate_history(query=query) + err = _has_error(_) + if err: + raise Exception("We hit an error, time to bail!") + + for item in _.get('results', []): + hits['ip'] += item.get('ipAddresses', []) + hits['sha1'].append(item['sha1']) + hits['domain'] += item.get('domains', []) + + tmp = list() + for key, value in hits.items(): + txt = {'types': type_map[key], 'values': list(set(value))} + tmp.append(txt) + + log.debug("SSL Details: ending") + + return tmp + + +def process_whois_details(instance, query): + """Process the detail from the WHOIS record.""" + log.debug("WHOIS Details: starting") + tmp = list() + _ = instance.get_whois_details(query=query, compact_record=True) + err = _has_error(_) + if err: + raise Exception("We hit an error, time to bail!") + + if _.get('contactEmail', None): + tmp.append({'types': ['whois-registrant-email'], 'values': [_.get('contactEmail')]}) + phones = _['compact']['telephone']['raw'] + tmp.append({'types': ['whois-registrant-phone'], 'values': phones}) + names = _['compact']['name']['raw'] + tmp.append({'types': ['whois-registrant-name'], 'values': names}) + if _.get('registrar', None): + tmp.append({'types': ['whois-registrar'], 'values': [_.get('registrar')]}) + if _.get('registered', None): + tmp.append({'types': ['whois-creation-date'], 'values': [_.get('registered')]}) + log.debug("WHOIS Details: ending") + + return tmp + + +def process_whois_search(instance, query, qtype): + """Process a WHOIS search for a specific field value.""" + log.debug("WHOIS Search: starting") + if qtype in ['whois-registrant-email', 'email-src', 'email-dst', 'target-email']: + field_type = 'email' + if qtype in ['whois-registrant-phone']: + field_type = 'phone' + if qtype in ['whois-registrant-name']: + field_type = 'name' + + domains = list() + _ = instance.search_whois_by_field(field=field_type, query=query) + err = _has_error(_) + if err: + raise Exception("We hit an error, time to bail!") + + for item in _.get('results', []): + domain = item.get('domain', None) + if not domain: + continue + domains.append(domain) + + tmp = [{'types': ['hostname', 'domain'], 'values': list(set(domains))}] + log.debug("WHOIS Search: ending") + + return tmp + + +def process_passive_dns(instance, query): + """Process passive DNS data.""" + log.debug("Passive DNS: starting") + tmp = list() + _ = instance.get_unique_resolutions(query=query) + err = _has_error(_) + if err: + raise Exception("We hit an error, time to bail!") + + if is_ip(query): + tmp = [{'types': ['domain', 'hostname'], 'values': _.get('results', [])}] + else: + tmp = [{'types': ['ip-src', 'ip-dst'], 'values': _.get('results', [])}] + log.debug("Passive DNS: ending") + + return tmp + + +def process_osint(instance, query): + """Process OSINT links.""" + log.debug("OSINT: starting") + urls = list() + _ = instance.get_osint(query=query) + err = _has_error(_) + if err: + raise Exception("We hit an error, time to bail!") + + for item in _.get('results', []): + urls.append(item['sourceUrl']) + + tmp = [{'types': ['link'], 'values': urls}] + log.debug("OSINT: ending") + + return tmp + + +def process_malware(instance, query): + """Process malware samples.""" + log.debug("Malware: starting") + content = {'hashes': list(), 'urls': list()} + _ = instance.get_malware(query=query) + err = _has_error(_) + if err: + raise Exception("We hit an error, time to bail!") + + for item in _.get('results', []): + content['hashes'].append(item['sample']) + content['urls'].append(item['sourceUrl']) + + tmp = [{'types': ['link'], 'values': content['urls']}] + hashes = {'md5': list(), 'sha1': list(), 'sha256': list()} + for h in content['hashes']: + if len(h) == 32: + hashes['md5'].append(h) + elif len(h) == 41: + hashes['sha1'].append(h) + elif len(h) == 64: + hashes['sha256'].append(h) + tmp += [{'types': ['md5'], 'values': hashes['md5']}] + tmp += [{'types': ['sha1'], 'values': hashes['sha1']}] + tmp += [{'types': ['sha256'], 'values': hashes['sha256']}] + log.debug("Malware: ending") + + return tmp + + +def handler(q=False): + if not q: + return q + + request = json.loads(q) + profile = build_profile(request) + if not profile['success']: + log.error(misperrors['error']) + return misperrors + + output = {'results': list()} + + instances = dict() + for service in profile['playbook']['services']: + instances[service] = _generate_request_instance( + profile['config'], service) + + play_type = profile['playbook']['name'] + query = profile['value'] + qtype = profile['type'] + try: + if play_type == 'generic': + results = process_passive_dns(instances['dns'], query) + output['results'] += results + results = process_whois_details(instances['whois'], query) + output['results'] += results + results = process_ssl_history(instances['ssl'], query) + output['results'] += results + results = process_osint(instances['enrichment'], query) + output['results'] += results + results = process_malware(instances['enrichment'], query) + output['results'] += results + elif play_type == 'reverse-whois': + results = process_whois_search(instances['whois'], query, qtype) + output['results'] += results + elif play_type == 'ssl-history': + results = process_ssl_details(instances['ssl'], query) + output['results'] += results + results = process_ssl_history(instances['ssl'], query) + output['results'] += results + else: + log.error("Unsupported query pattern issued.") + except: + return misperrors + + return output + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/var/misp_modules/modules/expansion/reversedns.py b/var/misp_modules/modules/expansion/reversedns.py new file mode 100644 index 0000000..46fe94a --- /dev/null +++ b/var/misp_modules/modules/expansion/reversedns.py @@ -0,0 +1,64 @@ +import json +import dns.reversename, dns.resolver + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['ip-src', 'ip-dst', 'domain|ip'], 'output': ['hostname']} + +# possible module-types: 'expansion', 'hover' or both +moduleinfo = {'version': '0.1', 'author': 'Andreas Muehlemann', + 'description': 'Simple Reverse DNS expansion service to resolve reverse DNS from MISP attributes', + 'module-type': ['expansion', 'hover']} + +# config fields that your code expects from the site admin +moduleconfig = ['nameserver'] + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + if request.get('ip-dst'): + toquery = request['ip-dst'] + elif request.get('ip-src'): + toquery = request['ip-src'] + elif request.get('domain|ip'): + toquery = request['domain|ip'].split('|')[1] + else: + return False + + # reverse lookup for ip + revname = dns.reversename.from_address(toquery) + + r = dns.resolver.Resolver() + r.timeout = 2 + r.lifetime = 2 + + if request.get('config'): + if request['config'].get('nameserver'): + nameservers = [] + nameservers.append(request['config'].get('nameserver')) + r.nameservers = nameservers + else: + r.nameservers = ['8.8.8.8'] + + try: + answer = r.query(revname, 'PTR') + except dns.resolver.NXDOMAIN: + misperrors['error'] = "NXDOMAIN" + return misperrors + except dns.exception.Timeout: + misperrors['error'] = "Timeout" + return misperrors + except: + misperrors['error'] = "DNS resolving error" + return misperrors + + r = {'results': [{'types': mispattributes['output'], + 'values':[str(answer[0])]}]} + return r + +def introspection(): + return mispattributes + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/var/misp_modules/modules/expansion/shodan.py b/var/misp_modules/modules/expansion/shodan.py new file mode 100755 index 0000000..fbdf5cd --- /dev/null +++ b/var/misp_modules/modules/expansion/shodan.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- + +import json +try: + import shodan +except ImportError: + print("shodan module not installed.") + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['ip-src', 'ip-dst'], 'output': ['freetext']} +moduleinfo = {'version': '0.1', 'author': 'Raphaël Vinot', + 'description': 'Query on Shodan', + 'module-type': ['expansion']} + +moduleconfig = ['apikey'] + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + if request.get('ip-src'): + toquery = request['ip-src'] + elif request.get('ip-dst'): + toquery = request['ip-dst'] + else: + misperrors['error'] = "Unsupported attributes type" + return misperrors + + if not request.get('config') and not (request['config'].get('apikey')): + misperrors['error'] = 'shodan authentication is missing' + return misperrors + api = shodan.Shodan(request['config'].get('apikey')) + + return handle_expansion(api, toquery) + + +def handle_expansion(api, domain): + return {'results': [{'types': mispattributes['output'], 'values': json.dumps(api.host(domain))}]} + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/var/misp_modules/modules/expansion/sourcecache.py b/var/misp_modules/modules/expansion/sourcecache.py new file mode 100755 index 0000000..b09068b --- /dev/null +++ b/var/misp_modules/modules/expansion/sourcecache.py @@ -0,0 +1,45 @@ +import json +from url_archiver import url_archiver + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['link', 'url'], 'output': ['attachment', 'malware-sample']} +moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', 'description': 'Module to cache web pages of analysis reports, OSINT sources. The module returns a link of the cached page.', 'module-type': ['expansion']} +moduleconfig = ['archivepath'] + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + if (request.get('config')): + archive_path = request['config']['archivepath'] + else: + archive_path = '/tmp/' + if request.get('link'): + tocache = request['link'] + data = __archiveLink(archive_path, tocache) + mispattributes['output'] = ['attachment'] + elif request.get('url'): + tocache = request['url'] + data = __archiveLink(archive_path, tocache) + mispattributes['output'] = ['malware-sample'] + else: + misperrors['error'] = "Link is missing" + return misperrors + enc_data = data.decode('ascii') + r = {'results': [{'types': mispattributes['output'], 'values': tocache, 'data': enc_data}]} + return r + + +def __archiveLink(archive_path, tocache): + archiver = url_archiver.Archive(archive_path=archive_path) + return archiver.fetch(url=tocache, armor=True) + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/var/misp_modules/modules/expansion/virustotal.py b/var/misp_modules/modules/expansion/virustotal.py new file mode 100755 index 0000000..4048942 --- /dev/null +++ b/var/misp_modules/modules/expansion/virustotal.py @@ -0,0 +1,154 @@ +import json +import requests +import hashlib +import re +import base64 +import os + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['hostname', 'domain', "ip-src", "ip-dst"], + 'output':['domain', "ip-src", "ip-dst", "text"] + } + +# possible module-types: 'expansion', 'hover' or both +moduleinfo = {'version': '1', '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 + +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) + + uniq = [] + for res in r["results"]: + if res not in uniq: + uniq.append(res) + r["results"] = uniq + return r + +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} + ).json() + 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"]]}) + #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} + ).json() + 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"]]}) + #Pivot from here to find all info on IPs + if not do_not_recurse: + toReturn += getIP(res["ip_address"], key, True) + 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 isset(d, key): + if key in d: + if d[key] not in [None, '', ' ']: + return True + return False + +def getMoreInfo(req, key): + global limit + r = [] + #Get all hashes first + hashes = [] + hashes = findAll(req, ["md5", "sha1", "sha256", "sha512"]) + r.append({"types":["md5", "sha1", "sha256", "sha512"], "values":hashes}) + for hsh in hashes[:limit]: + #Search VT for some juicy info + data = requests.get("http://www.virustotal.com/vtapi/v2/file/report", + params={"allinfo":1, "apikey":key, "resource":hsh} + ).json() + if isset(data, "submission_names"): + r.append({'types':["filename"], "values":data["submission_names"]}) + + if isset(data, "ssdeep"): + r.append({'types':["ssdeep"], "values":[data["ssdeep"]]}) + + if isset(data, "authentihash"): + r.append({"types":["authentihash"], "values":[data["authentihash"]]}) + + if isset(data, "ITW_urls"): + r.append({"types":["url"], "values":data["ITW_urls"]}) + + #Get the malware sample + sample = requests.get("https://www.virustotal.com/vtapi/v2/file/download", + params = {"hash":hsh, "apikey":key}) + + malsample = sample.content + r.append({"types":["malware-sample"], + "categories":["Payload delivery"], + "values":data["submission_names"], + "data": str(base64.b64encode(malsample), 'utf-8') + } + ) + return r + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo + diff --git a/var/misp_modules/modules/expansion/vmray_submit.py b/var/misp_modules/modules/expansion/vmray_submit.py new file mode 100644 index 0000000..407853c --- /dev/null +++ b/var/misp_modules/modules/expansion/vmray_submit.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 + +''' +Submit sample to VMRay. + +Submit a sample to VMRay + +TODO: + # Deal with malicious samples (ZIP file, 'infected') + # Deal with archive submissions + +''' + +import json +import base64 + +import io + +from ._vmray.vmray_rest_api import VMRayRESTAPI + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['attachment'], 'output': ['text', 'sha1', 'sha256', 'md5', 'link']} +moduleinfo = {'version': '0.1', 'author': 'Koen Van Impe', + 'description': 'Submit a sample to VMRay', + 'module-type': ['expansion']} +moduleconfig = ['apikey', 'url', 'shareable', 'do_not_reanalyze', 'do_not_include_vmrayjobids'] + + +include_vmrayjobids = False + + +def handler(q=False): + global include_vmrayjobids + + if q is False: + return False + request = json.loads(q) + + try: + data = request.get("data") + attachment = request.get("attachment") + data = base64.b64decode(data) + except: + misperrors['error'] = "Unable to process submited sample data" + return misperrors + + if (request["config"].get("apikey") is None) or (request["config"].get("url") is None): + misperrors["error"] = "Missing API key or server URL (hint: try cloud.vmray.com)" + return misperrors + + api = VMRayRESTAPI(request["config"].get("url"), request["config"].get("apikey"), False) + + shareable = request["config"].get("shareable") + do_not_reanalyze = request["config"].get("do_not_reanalyze") + do_not_include_vmrayjobids = request["config"].get("do_not_include_vmrayjobids") + + # Do we want the sample to be shared? + if shareable == "True": + shareable = True + else: + shareable = False + + # Always reanalyze the sample? + if do_not_reanalyze == "True": + do_not_reanalyze = True + else: + do_not_reanalyze = False + reanalyze = not do_not_reanalyze + + # Include the references to VMRay job IDs + if do_not_include_vmrayjobids == "True": + do_not_include_vmrayjobids = True + else: + do_not_include_vmrayjobids = False + include_vmrayjobids = not do_not_include_vmrayjobids + + if data and attachment: + args = {} + args["shareable"] = shareable + args["sample_file"] = {'data': io.BytesIO(data), 'filename': attachment} + args["reanalyze"] = reanalyze + + try: + vmraydata = vmraySubmit(api, args) + if vmraydata["errors"]: + misperrors['error'] = "VMRay: %s" % vmraydata["errors"][0]["error_msg"] + return misperrors + else: + return vmrayProcess(vmraydata) + except: + misperrors['error'] = "Problem when calling API." + return misperrors + else: + misperrors['error'] = "No sample data or filename." + return misperrors + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo + + +def vmrayProcess(vmraydata): + ''' Process the JSON file returned by vmray''' + if vmraydata: + try: + submissions = vmraydata["submissions"][0] + jobs = vmraydata["jobs"] + + # Result received? + if submissions and jobs: + r = {'results': []} + r["results"].append({"types": "md5", "values": submissions["submission_sample_md5"]}) + r["results"].append({"types": "sha1", "values": submissions["submission_sample_sha1"]}) + r["results"].append({"types": "sha256", "values": submissions["submission_sample_sha256"]}) + r["results"].append({"types": "text", "values": "VMRay Sample ID: %s" % submissions["submission_sample_id"]}) + r["results"].append({"types": "text", "values": "VMRay Submission ID: %s" % submissions["submission_id"]}) + r["results"].append({"types": "text", "values": "VMRay Submission Sample IP: %s" % submissions["submission_ip_ip"]}) + r["results"].append({"types": "link", "values": submissions["submission_webif_url"]}) + + # Include data from different jobs + if include_vmrayjobids: + for job in jobs: + job_id = job["job_id"] + job_vm_name = job["job_vm_name"] + job_configuration_name = job["job_configuration_name"] + r["results"].append({"types": "text", "values": "VMRay Job ID %s (%s - %s)" % (job_id, job_vm_name, job_configuration_name)}) + return r + else: + misperrors['error'] = "No valid results returned." + return misperrors + except: + misperrors['error'] = "No valid submission data returned." + return misperrors + else: + misperrors['error'] = "Unable to parse results." + return misperrors + + +def vmraySubmit(api, args): + ''' Submit the sample to VMRay''' + vmraydata = api.call("POST", "/rest/sample/submit", args) + return vmraydata diff --git a/var/misp_modules/modules/expansion/whois.py b/var/misp_modules/modules/expansion/whois.py new file mode 100755 index 0000000..4aec40c --- /dev/null +++ b/var/misp_modules/modules/expansion/whois.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- + +import json +try: + from uwhois import Uwhois +except ImportError: + print("uwhois module not installed.") + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['domain', 'ip-src', 'ip-dst'], 'output': ['freetext']} +moduleinfo = {'version': '0.1', 'author': 'Raphaël Vinot', + 'description': 'Query a local instance of uwhois (https://github.com/rafiot/uwhoisd)', + 'module-type': ['expansion']} + +moduleconfig = ['server', 'port'] + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + if request.get('domain'): + toquery = request['domain'] + elif request.get('ip-src'): + toquery = request['ip-src'] + elif request.get('ip-dst'): + toquery = request['ip-dst'] + else: + misperrors['error'] = "Unsupported attributes type" + return misperrors + + if not request.get('config') and not (request['config'].get('apikey') and request['config'].et('url')): + misperrors['error'] = 'EUPI authentication is missing' + return misperrors + + uwhois = Uwhois(request['config']['server'], int(request['config']['port'])) + + if 'event_id' in request: + return handle_expansion(uwhois, toquery) + + +def handle_expansion(w, domain): + return {'results': [{'types': mispattributes['output'], 'values': w.query(domain)}]} + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/var/misp_modules/modules/expansion/wiki.py b/var/misp_modules/modules/expansion/wiki.py new file mode 100755 index 0000000..85279b1 --- /dev/null +++ b/var/misp_modules/modules/expansion/wiki.py @@ -0,0 +1,50 @@ +import json +import requests +from SPARQLWrapper import SPARQLWrapper, JSON + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['text'], 'output': ['text']} +moduleinfo = {'version': '0.2', 'author': 'Roman Graf', 'description': 'An expansion hover module to extract information from Wikidata to have additional information about particular term for analysis.', 'module-type': ['hover']} +moduleconfig = [] +# sample query text 'Microsoft' should provide Wikidata link https://www.wikidata.org/wiki/Q2283 in response +wiki_api_url = 'https://query.wikidata.org/bigdata/namespace/wdq/sparql' + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + 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"; + sparql.setQuery(query_string) + sparql.setReturnFormat(JSON) + results = sparql.query().convert() + + summary = '' + try: + result = results["results"]["bindings"][0] + summary = result["item"]["value"] + except Exception as e: + misperrors['error'] = 'wikidata API not accessible' + e + 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/var/misp_modules/modules/export_mod/__init__.py b/var/misp_modules/modules/export_mod/__init__.py new file mode 100644 index 0000000..69f1c00 --- /dev/null +++ b/var/misp_modules/modules/export_mod/__init__.py @@ -0,0 +1 @@ +__all__ = ['testexport','cef_export'] diff --git a/var/misp_modules/modules/export_mod/cef_export.py b/var/misp_modules/modules/export_mod/cef_export.py new file mode 100755 index 0000000..3f2ff61 --- /dev/null +++ b/var/misp_modules/modules/export_mod/cef_export.py @@ -0,0 +1,81 @@ +import json +import base64 +import datetime + +misperrors = {'error': 'Error'} + +# possible module-types: 'expansion', 'hover' or both +moduleinfo = {'version': '1', 'author': 'Hannah Ward', + 'description': 'Export a module in CEF format', + 'module-type': ['export']} + +# 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"} + +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"] + else: + 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( + datetime.datetime.fromtimestamp(int(attr["timestamp"])).strftime("%b %d %H:%M:%S"), + config["Device_Vendor"], + config["Device_Product"], + config["Device_Version"], + attr["category"], + attr["category"], + config["Default_Severity"], + cefmapping[attr["type"]], + attr["value"], + ) + + r = {"response":[], "data":str(base64.b64encode(bytes(response, '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/var/misp_modules/modules/export_mod/testexport.py b/var/misp_modules/modules/export_mod/testexport.py new file mode 100755 index 0000000..ed93228 --- /dev/null +++ b/var/misp_modules/modules/export_mod/testexport.py @@ -0,0 +1,64 @@ +import json +import base64 +import csv + +misperrors = {'error': 'Error'} + + +userConfig = { + +}; + +moduleconfig = [] + +# fixed for now, options in the future: +# event, attribute, event-collection, attribute-collection +inputSource = ['event'] + +outputFileExtension = 'txt' +responseType = 'application/txt' + + +moduleinfo = {'version': '0.1', 'author': 'Andras Iklody', + 'description': 'Skeleton export module', + 'module-type': ['export']} + + +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')} + 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/var/misp_modules/modules/import_mod/__init__.py b/var/misp_modules/modules/import_mod/__init__.py new file mode 100644 index 0000000..70b674a --- /dev/null +++ b/var/misp_modules/modules/import_mod/__init__.py @@ -0,0 +1,3 @@ +from . import _vmray + +__all__ = ['vmray_import', 'testimport', 'ocr', 'stiximport'] diff --git a/var/misp_modules/modules/import_mod/_vmray/__init__.py b/var/misp_modules/modules/import_mod/_vmray/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/var/misp_modules/modules/import_mod/_vmray/vmray_rest_api.py b/var/misp_modules/modules/import_mod/_vmray/vmray_rest_api.py new file mode 100644 index 0000000..d37c6f2 --- /dev/null +++ b/var/misp_modules/modules/import_mod/_vmray/vmray_rest_api.py @@ -0,0 +1,148 @@ +#!/usr/bin/python3 +"""Python client library for VMRay REST API""" + +import base64 +import datetime +import os.path +import requests +import urllib.parse + +# disable nasty certification warning +# pylint: disable=no-member +try: + requests.packages.urllib3.disable_warnings() +except AttributeError: + try: + import urllib3 + try: + urllib3.disable_warnings() + except AttributeError: + pass + except ImportError: + pass + +# pylint: disable= + + +class VMRayRESTAPIError(Exception): + """Exception class that is used when API returns an error""" + + def __init__(self, *args, **kwargs): + self.status_code = kwargs.pop("status_code", None) + Exception.__init__(self, *args, **kwargs) + + +def handle_rest_api_result(result): + """Handle result of API request (check for errors)""" + + if (result.status_code < 200) or (result.status_code > 299): + try: + json_result = result.json() + except ValueError: + raise VMRayRESTAPIError("API returned error %u: %s" % (result.status_code, result.text), status_code=result.status_code) + + raise VMRayRESTAPIError(json_result.get("error_msg", "Unknown error"), status_code=result.status_code) + + +class VMRayRESTAPI(object): + """VMRay REST API class""" + + def __init__(self, server, api_key, verify_cert=True): + # split server URL into components + url_desc = urllib.parse.urlsplit(server) + + # assume HTTPS if no scheme is specified + if url_desc.scheme == "": + server = "https://" + server + + # save variables + self.server = server + self.api_key = api_key + self.verify_cert = verify_cert + + def call(self, http_method, api_path, params=None, raw_data=False): + """Call VMRay REST API""" + + # get function of requests package + requests_func = getattr(requests, http_method.lower()) + + # parse parameters + req_params = {} + file_params = {} + + if params is not None: + for key, value in params.items(): + if isinstance(value, (datetime.date, + datetime.datetime, + float, + int)): + req_params[key] = str(value) + elif isinstance(value, str): + req_params[key] = str(value) + elif isinstance(value, dict): + filename = value["filename"] + sample = value["data"] + file_params[key] = (filename, sample, "application/octet-stream") + elif hasattr(value, "read"): + filename = os.path.split(value.name)[1] + # For the following block refer to DEV-1820 + try: + filename.decode("ASCII") + except (UnicodeDecodeError, UnicodeEncodeError): + b64_key = key + "name_b64enc" + byte_value = filename.encode("utf-8") + b64_value = base64.b64encode(byte_value) + + filename = "@param=%s" % b64_key + req_params[b64_key] = b64_value + file_params[key] = (filename, value, "application/octet-stream") + else: + raise VMRayRESTAPIError("Parameter \"%s\" has unknown type \"%s\"" % (key, type(value))) + + # construct request + if file_params: + files = file_params + else: + files = None + + # we need to adjust some stuff for POST requests + if http_method.lower() == "post": + req_data = req_params + req_params = None + else: + req_data = None + + # do request + result = requests_func(self.server + api_path, data=req_data, params=req_params, headers={"Authorization": "api_key " + self.api_key}, files=files, verify=self.verify_cert, stream=raw_data) + handle_rest_api_result(result) + + if raw_data: + return result.raw + + # parse result + try: + json_result = result.json() + except ValueError: + raise ValueError("API returned invalid JSON: %s" % (result.text)) + + # if there are no cached elements then return the data + if "continuation_id" not in json_result: + return json_result.get("data", None) + + data = json_result["data"] + + # get cached results + while "continuation_id" in json_result: + # send request to server + result = requests.get("%s/rest/continuation/%u" % (self.server, json_result["continuation_id"]), headers={"Authorization": "api_key " + self.api_key}, verify=self.verify_cert) + handle_rest_api_result(result) + + # parse result + try: + json_result = result.json() + except ValueError: + raise ValueError("API returned invalid JSON: %s" % (result.text)) + + data.extend(json_result["data"]) + + return data diff --git a/var/misp_modules/modules/import_mod/ocr.py b/var/misp_modules/modules/import_mod/ocr.py new file mode 100755 index 0000000..aafe653 --- /dev/null +++ b/var/misp_modules/modules/import_mod/ocr.py @@ -0,0 +1,57 @@ +import json +import base64 + +from PIL import Image + +from pytesseract import image_to_string +from io import BytesIO +misperrors = {'error': 'Error'} +userConfig = { }; + +inputSource = ['file'] + +moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', + 'description': 'Optical Character Recognition (OCR) module for MISP', + 'module-type': ['import']} + +moduleconfig = [] + + +def handler(q=False): + if q is False: + return False + r = {'results': []} + request = json.loads(q) + image = base64.b64decode(request["data"]) + image_file = BytesIO(image) + image_file.seek(0) + ocrized = image_to_string(Image.open(image_file)) + freetext = {} + freetext['values'] = ocrized + freetext['types'] = ['freetext'] + r['results'].append(freetext) + return r + + +def introspection(): + modulesetup = {} + try: + userConfig + modulesetup['userConfig'] = userConfig + except NameError: + pass + try: + inputSource + modulesetup['inputSource'] = inputSource + except NameError: + pass + return modulesetup + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo + +if __name__ == '__main__': + x = open('test.json', 'r') + handler(q=x.read()) diff --git a/var/misp_modules/modules/import_mod/stiximport.py b/var/misp_modules/modules/import_mod/stiximport.py new file mode 100755 index 0000000..16a2f22 --- /dev/null +++ b/var/misp_modules/modules/import_mod/stiximport.py @@ -0,0 +1,259 @@ +import json +from stix.core import STIXPackage +import re +import base64 +import hashlib +import tempfile + +misperrors = {'error': 'Error'} +userConfig = {} +inputSource = ['file'] + +moduleinfo = {'version': '0.1', 'author': 'Hannah Ward', + 'description': 'Import some stix stuff', + 'module-type': ['import']} + +moduleconfig = ["max_size"] + + +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) + + # It's b64 encoded, so decode that stuff + package = base64.b64decode(q.get("data")).decode('utf-8') + + # If something really weird happened + if not package: + return json.dumps({"success": 0}) + + # Get the maxsize from the config + # Default to 10MB + # (I believe the max_size arg is given in bytes) + # Check if we were given a configuration + memsize = q.get("config", None) + + # If we were, find out if there's a memsize field + if memsize: + memsize = memsize.get("max_size", 10 * 1024) + else: + memsize = 10 * 1024 + + # Load up the package into STIX + package = loadPackage(package, memsize) + + # Build all the observables + if package.observables: + for obs in package.observables: + r["results"].append(buildObservable(obs)) + + # And now the threat actors + if package.threat_actors: + for ta in package.threat_actors: + r["results"].append(buildActor(ta)) + + # Aaaand the indicators + if package.indicators: + for ind in package.indicators: + r["results"] += buildIndicator(ind) + + # Are you seeing a pattern? + if package.exploit_targets: + for et in package.exploit_targets: + r["results"].append(buildExploitTarget(et)) + + # LOADING STUFF + if package.campaigns: + for cpn in package.campaigns: + r["results"].append(buildCampaign(cpn)) + + # Clean up results + # Don't send on anything that didn't have a value + r["results"] = [x for x in r["results"] if isinstance(x, dict) and len(x["values"]) != 0] + return r + +# Quick and dirty regex for IP addresses +ipre = re.compile("([0-9]{1,3}.){3}[0-9]{1,3}") + + +def buildCampaign(cpn): + """ + Extract a campaign name + """ + return {"values": [cpn.title], "types": ["campaign-name"]} + + +def buildExploitTarget(et): + """ + Extract CVEs from exploit targets + """ + + r = {"values": [], "types": ["vulnerability"]} + + if et.vulnerabilities: + for v in et.vulnerabilities: + if v.cve_id: + r["values"].append(v.cve_id) + return r + + + +def identifyHash(hsh): + """ + What's that hash!? + """ + + possible_hashes = [] + + hashes = [x for x in hashlib.algorithms_guaranteed] + + for h in hashes: + if len(str(hsh)) == len(hashlib.new(h).hexdigest()): + possible_hashes.append(h) + possible_hashes.append("filename|{}".format(h)) + return possible_hashes + + +def buildIndicator(ind): + """ + Extract hashes + and other fun things + like that + """ + r = [] + # Try to get hashes. I hate stix + if ind.observables: + for i in ind.observables: + if i.observable_composition: + for j in i.observable_composition.observables: + r.append(buildObservable(j)) + r.append(buildObservable(i)) + return r + + +def buildActor(ta): + """ + Extract the name + and comment of a + threat actor + """ + + r = {"values": [ta.title], "types": ["threat-actor"]} + + return r + + +def buildObservable(o): + """ + Take a STIX observable + and extract the value + and category + """ + # Life is easier with json + if not isinstance(o, dict): + o = json.loads(o.to_json()) + # Make a new record to store values in + r = {"values": []} + + # Get the object properties. This contains all the + # fun stuff like values + if "observable_composition" in o: + # May as well be useless + return r + + if not o.get('object'): + return r + + props = o["object"]["properties"] + + # If it has an address_value field, it's gonna be an address + # Kinda obvious really + if "address_value" in props: + + # We've got ourselves a nice little address + value = props["address_value"] + + if isinstance(value, dict): + # Sometimes it's embedded in a dictionary + value = value["value"] + + # Is it an IP? + if ipre.match(str(value)): + # Yes! + r["values"].append(value) + r["types"] = ["ip-src", "ip-dst"] + else: + # Probably a domain yo + r["values"].append(value) + r["types"] = ["domain", "hostname"] + + if "hashes" in props: + for hsh in props["hashes"]: + r["values"].append(hsh["simple_hash_value"]["value"]) + r["types"] = identifyHash(hsh["simple_hash_value"]["value"]) + + elif "xsi:type" in props: + # Cybox. Ew. + try: + type_ = props["xsi:type"] + val = props["value"] + + if type_ == "LinkObjectType": + r["types"] = ["link"] + r["values"].append(val) + else: + print("Ignoring {}".format(type_)) + except: + pass + return r + + +def loadPackage(data, memsize=1024): + # Write the stix package to a tmp file + + temp = tempfile.SpooledTemporaryFile(max_size=int(memsize), mode="w+") + + temp.write(data) + + # Back to the beginning so we can read it again + temp.seek(0) + try: + # Try loading it into every format we know of + try: + package = STIXPackage().from_xml(temp) + except: + # We have to seek back again + temp.seek(0) + package = STIXPackage().from_json(temp) + except Exception: + print("Failed to load package") + raise ValueError("COULD NOT LOAD STIX PACKAGE!") + temp.close() + return package + + +def introspection(): + modulesetup = {} + try: + userConfig + modulesetup['userConfig'] = userConfig + except NameError: + pass + try: + inputSource + modulesetup['inputSource'] = inputSource + except NameError: + pass + return modulesetup + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/var/misp_modules/modules/import_mod/testimport.py b/var/misp_modules/modules/import_mod/testimport.py new file mode 100755 index 0000000..02369c5 --- /dev/null +++ b/var/misp_modules/modules/import_mod/testimport.py @@ -0,0 +1,64 @@ +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' + } + }; + +inputSource = ['file', 'paste'] + +moduleinfo = {'version': '0.2', 'author': 'Andras Iklody', + 'description': 'Simple CSV import tool with mapable columns', + 'module-type': ['import']} + +moduleconfig = [] + + +def handler(q=False): + if q is False: + return 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"]}]} + return r + + +def introspection(): + modulesetup = {} + try: + userConfig + modulesetup['userConfig'] = userConfig + except NameError: + pass + try: + inputSource + modulesetup['inputSource'] = inputSource + except NameError: + pass + return modulesetup + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo diff --git a/var/misp_modules/modules/import_mod/vmray_import.py b/var/misp_modules/modules/import_mod/vmray_import.py new file mode 100644 index 0000000..dceeb1f --- /dev/null +++ b/var/misp_modules/modules/import_mod/vmray_import.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 + +''' +Import VMRay results. + +This version supports import from different analyze jobs, starting from one sample +(the supplied sample_id). + +Requires "vmray_rest_api" + +TODO: + # Import one job (analyze_id) + # Import STIX package (XML version) + +''' + +import json +import re + +from ._vmray.vmray_rest_api import VMRayRESTAPI + +misperrors = {'error': 'Error'} +inputSource = [] +moduleinfo = {'version': '0.1', 'author': 'Koen Van Impe', + 'description': 'Import VMRay (VTI) results', + 'module-type': ['import']} +userConfig = {'include_textdescr': {'type': 'Boolean', + 'message': 'Include textual description' + }, + 'include_analysisid': {'type': 'Boolean', + 'message': 'Include VMRay analysis_id text' + }, + 'only_network_info': {'type': 'Boolean', + 'message': 'Only include network (src-ip, hostname, domain, ...) information' + }, + 'sample_id': {'type': 'Integer', + 'errorMessage': 'Expected a sample ID', + 'message': 'The VMRay sample_id' + } + } + +moduleconfig = ['apikey', 'url'] + +include_textdescr = False +include_analysisid = False +only_network_info = False + + +def handler(q=False): + global include_textdescr + global include_analysisid + global only_network_info + + if q is False: + return False + request = json.loads(q) + + include_textdescr = request["config"].get("include_textdescr") + include_analysisid = request["config"].get("include_analysisid") + only_network_info = request["config"].get("only_network_info") + if include_textdescr == "1": + include_textdescr = True + else: + include_textdescr = False + if include_analysisid == "1": + include_analysisid = True + else: + include_analysisid = False + if only_network_info == "1": + only_network_info = True + else: + only_network_info = False + + sample_id = int(request["config"].get("sample_id")) + + if (request["config"].get("apikey") is None) or (request["config"].get("url") is None): + misperrors["error"] = "Missing API key or server URL (hint: try cloud.vmray.com)" + return misperrors + + if sample_id > 0: + try: + api = VMRayRESTAPI(request["config"].get("url"), request["config"].get("apikey"), False) + vmray_results = {'results': []} + # Get all information on the sample, returns a set of finished analyze jobs + data = vmrayGetInfoAnalysis(api, sample_id) + if data["data"]: + for analysis in data["data"]: + analysis_id = analysis["analysis_id"] + + if analysis_id > 0: + # Get the details for an analyze job + analysis_data = vmrayDownloadAnalysis(api, analysis_id) + + if analysis_data: + p = vmrayVtiPatterns(analysis_data["vti_patterns"]) + if p: + if include_analysisid: + url1 = "https://cloud.vmray.com/user/analysis/view?from_sample_id=%u" % sample_id + url2 = "&id=%u" % analysis_id + url3 = "&sub=%2Freport%2Foverview.html" + p["results"].append({"values": url1 + url2 + url3, "types": "link"}) + vmray_results = {'results': vmray_results["results"] + p["results"]} + + # Clean up (remove doubles) + vmray_results = vmrayCleanup(vmray_results) + return vmray_results + else: + misperrors['error'] = "Unable to fetch sample id %u" % (sample_id) + return misperrors + except: + misperrors['error'] = "Unable to access VMRay API" + return misperrors + else: + misperrors['error'] = "Not a valid sample id" + return misperrors + + +def introspection(): + modulesetup = {} + try: + userConfig + modulesetup['userConfig'] = userConfig + except NameError: + pass + try: + inputSource + modulesetup['inputSource'] = inputSource + except NameError: + pass + return modulesetup + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo + + +def vmrayGetInfoAnalysis(api, sample_id): + ''' Get information from a sample, returns a set of analyzed reports''' + + if sample_id: + data = api.call("GET", "/rest/analysis/sample/%u" % (sample_id), raw_data=True) + return json.loads(data.read().decode()) + else: + return False + + +def vmrayDownloadAnalysis(api, analysis_id): + ''' Get the details from an analysis''' + if analysis_id: + data = api.call("GET", "/rest/analysis/%u/archive/additional/vti_result.json" % (analysis_id), raw_data=True) + return json.loads(data.read().decode()) + else: + return False + + +def vmrayVtiPatterns(vti_patterns): + ''' Match the VTI patterns to MISP data''' + + if vti_patterns: + r = {'results': []} + y = {'results': []} + + for pattern in vti_patterns: + content = False + if pattern["category"] == "_network" and pattern["operation"] == "_download_data": + content = vmrayGeneric(pattern, "url", 1) + elif pattern["category"] == "_network" and pattern["operation"] == "_connect": + content = vmrayConnect(pattern) + + elif only_network_info is False and pattern["category"] == "_process" and pattern["operation"] == "_alloc_wx_page": + content = vmrayGeneric(pattern) + elif only_network_info is False and pattern["category"] == "_process" and pattern["operation"] == "_install_ipc_endpoint": + content = vmrayGeneric(pattern, "mutex", 1) + + elif only_network_info is False and pattern["category"] == "_anti_analysis" and pattern["operation"] == "_delay_execution": + content = vmrayGeneric(pattern) + elif only_network_info is False and pattern["category"] == "_anti_analysis" and pattern["operation"] == "_dynamic_api_usage": + content = vmrayGeneric(pattern) + + elif only_network_info is False and pattern["category"] == "_static" and pattern["operation"] == "_drop_pe_file": + content = vmrayGeneric(pattern, "filename", 1) + elif only_network_info is False and pattern["category"] == "_static" and pattern["operation"] == "_execute_dropped_pe_file": + content = vmrayGeneric(pattern, "filename", 1) + + elif only_network_info is False and pattern["category"] == "_injection" and pattern["operation"] == "_modify_memory": + content = vmrayGeneric(pattern) + elif only_network_info is False and pattern["category"] == "_injection" and pattern["operation"] == "_modify_control_flow": + content = vmrayGeneric(pattern) + elif only_network_info is False and pattern["category"] == "_file_system" and pattern["operation"] == "_create_many_files": + content = vmrayGeneric(pattern) + + elif only_network_info is False and pattern["category"] == "_persistence" and pattern["operation"] == "_install_startup_script": + content = vmrayGeneric(pattern, "regkey", 1) + elif only_network_info is False and pattern["category"] == "_os" and pattern["operation"] == "_enable_process_privileges": + content = vmrayGeneric(pattern) + + if content: + r["results"].append(content["attributes"]) + r["results"].append(content["text"]) + + # Remove empty results + r["results"] = [x for x in r["results"] if isinstance(x, dict) and len(x["values"]) != 0] + for el in r["results"]: + if el not in y["results"]: + y["results"].append(el) + return y + else: + return False + + +def vmrayCleanup(x): + ''' Remove doubles''' + y = {'results': []} + + for el in x["results"]: + if el not in y["results"]: + y["results"].append(el) + return y + + +def vmraySanitizeInput(s): + ''' Sanitize some input so it gets properly imported in MISP''' + if s: + s = s.replace('"', '') + s = re.sub('\\\\', r'\\', s) + return s + else: + return False + + +def vmrayGeneric(el, attr="", attrpos=1): + ''' Convert a 'generic' VTI pattern to MISP data''' + + r = {"values": []} + f = {"values": []} + + if el: + content = el["technique_desc"] + if content: + if attr: + content_split = content.split("\"") + content_split[attrpos] = vmraySanitizeInput(content_split[attrpos]) + r["values"].append(content_split[attrpos]) + r["types"] = [attr] + + # Adding the value also as text to get the extra description, + # but this is pretty useless for "url" + if include_textdescr and attr != "url": + f["values"].append(vmraySanitizeInput(content)) + f["types"] = ["text"] + + return {"text": f, "attributes": r} + else: + return False + else: + return False + + +def vmrayConnect(el): + ''' Extension of vmrayGeneric , parse network connect data''' + ipre = re.compile("([0-9]{1,3}.){3}[0-9]{1,3}") + + r = {"values": []} + f = {"values": []} + + if el: + content = el["technique_desc"] + if content: + target = content.split("\"") + # port = (target[1].split(":"))[1] ## FIXME: not used + host = (target[1].split(":"))[0] + if ipre.match(str(host)): + r["values"].append(host) + r["types"] = ["ip-dst"] + else: + r["values"].append(host) + r["types"] = ["domain", "hostname"] + + f["values"].append(vmraySanitizeInput(target[1])) + f["types"] = ["text"] + + if include_textdescr: + f["values"].append(vmraySanitizeInput(content)) + f["types"] = ["text"] + + return {"text": f, "attributes": r} + else: + return False + else: + return False diff --git a/var/modules/expansion/module.py.skeleton b/var/modules/expansion/module.py.skeleton new file mode 100755 index 0000000..8937502 --- /dev/null +++ b/var/modules/expansion/module.py.skeleton @@ -0,0 +1,44 @@ +import json + +misperrors = {'error': 'Error'} +mispattributes = {'input': ['hostname', 'domain'], 'output': ['ip-src', + 'ip-dst']} + +# possible module-types: 'expansion', 'hover' or both +moduleinfo = {'version': '1', 'author': 'YOUR_NAME_HERE', + 'description': 'MODULE_DESCRIPTION', + 'module-type': ['expansion', 'hover']} + +# config fields that your code expects from the site admin +moduleconfig = [] + + +def handler(q=False): + if q is False: + return False + request = json.loads(q) + # You code that converts the data passed along in request + # input will be the query values + # output should be a list of dictionaries with types and values + # The types will be the types that the user can choose between + # for a given value + # An example would be a network indicator enrichment that returns + # a list of IP addresses and domain names. + # IP addresses would allow for attributes type ip-src and ip-dst, + # either of which the user can choose + # So the resulting list would look like this: + # r = {'results': [{'types': ['ip-src', 'ip-dst'], 'values': ips}, + # {'types': ['domain'], 'values': domains}]} + r = {'results': [{'types': types1, 'values': values1}, + {'types': types2, 'values': values2}]} + return r + + +def introspection(): + return mispattributes + + +def version(): + moduleinfo['config'] = moduleconfig + return moduleinfo + diff --git a/var/setup.py b/var/setup.py new file mode 100644 index 0000000..8ad517e --- /dev/null +++ b/var/setup.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from setuptools import setup, find_packages + +setup( + name='misp-modules', + version='1.0', + author='Alexandre Dulaunoy', + author_email='alexandre.dulaunoy@circl.lu', + maintainer='Alexandre Dulaunoy', + url='https://github.com/MISP/misp-modules', + 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']}, + test_suite="tests", + classifiers=[ + 'License :: OSI Approved :: GNU Affero General Public License v3', + 'Development Status :: 5 - Production/Stable', + 'Environment :: Console', + 'Intended Audience :: Science/Research', + 'Programming Language :: Python :: 3', + 'Topic :: Security', + ], + install_requires=[ + 'tornado', + 'dnspython3', + 'requests', + 'urlarchiver', + 'passivetotal', + 'PyPDNS', + 'pypssl', + 'redis', + 'pyeupi', + 'ipasn-redis', + 'asnhistory', + 'stix', + 'cybox', + 'pillow', + 'pytesseract', + 'shodan', + ] +) diff --git a/var/tests/__init__.py b/var/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/var/tests/body.json b/var/tests/body.json new file mode 100644 index 0000000..a0bf718 --- /dev/null +++ b/var/tests/body.json @@ -0,0 +1 @@ +{"module": "dns", "hostname": "www.circl.lu", "config" : {"nameserver":"8.8.8.8"}} diff --git a/var/tests/body_timeout.json b/var/tests/body_timeout.json new file mode 100644 index 0000000..f524c67 --- /dev/null +++ b/var/tests/body_timeout.json @@ -0,0 +1 @@ +{"module": "dns", "hostname": "www.circl.lu", "timeout": 1, "config" : {"nameserver":"8.8.8.8"}} diff --git a/var/tests/bodycircl_passivedns.json.sample b/var/tests/bodycircl_passivedns.json.sample new file mode 100644 index 0000000..ddd302f --- /dev/null +++ b/var/tests/bodycircl_passivedns.json.sample @@ -0,0 +1 @@ +{"module": "circl_passivedns", "ip-src": "149.13.33.14", "config": {"username": "auser", "password": "somepass"} } diff --git a/var/tests/bodycircl_passivessl.json.sample b/var/tests/bodycircl_passivessl.json.sample new file mode 100644 index 0000000..03294b8 --- /dev/null +++ b/var/tests/bodycircl_passivessl.json.sample @@ -0,0 +1 @@ +{"module": "circl_passivessl", "ip-src": "149.13.33.14", "config": {"username": "auser", "password": "somepass"} } diff --git a/var/tests/bodycve.json b/var/tests/bodycve.json new file mode 100644 index 0000000..c4bd37a --- /dev/null +++ b/var/tests/bodycve.json @@ -0,0 +1 @@ +{"module": "cve", "vulnerability": "CVE-2010-3333"} diff --git a/var/tests/bodypassivetotal.json.sample b/var/tests/bodypassivetotal.json.sample new file mode 100644 index 0000000..332c59f --- /dev/null +++ b/var/tests/bodypassivetotal.json.sample @@ -0,0 +1 @@ +{"module": "passivetotal", "ip-src": "149.13.33.14", "config": {"username": "abc@foo.be", "api_key": "deadbeef"} } diff --git a/var/tests/bodysourcecache.json b/var/tests/bodysourcecache.json new file mode 100644 index 0000000..327394a --- /dev/null +++ b/var/tests/bodysourcecache.json @@ -0,0 +1 @@ +{"module": "sourcecache", "link": "http://cve.circl.lu/" } diff --git a/var/tests/bodyvirustotal.json.sample b/var/tests/bodyvirustotal.json.sample new file mode 100644 index 0000000..43cad6b --- /dev/null +++ b/var/tests/bodyvirustotal.json.sample @@ -0,0 +1 @@ +{"module": "virustotal", "ip-dst": "5.104.106.190", "config": {"api_key": "deadbeef"} } diff --git a/var/tests/query-circl_passivedns.sh b/var/tests/query-circl_passivedns.sh new file mode 100755 index 0000000..1d15aba --- /dev/null +++ b/var/tests/query-circl_passivedns.sh @@ -0,0 +1 @@ +curl -s http://127.0.0.1:6666/query -H "Content-Type: application/json" --data @bodycircl_passivedns.json -X POST diff --git a/var/tests/query-circl_passivessl.sh b/var/tests/query-circl_passivessl.sh new file mode 100755 index 0000000..9e06571 --- /dev/null +++ b/var/tests/query-circl_passivessl.sh @@ -0,0 +1 @@ +curl -s http://127.0.0.1:6666/query -H "Content-Type: application/json" --data @bodycircl_passivessl.json -X POST diff --git a/var/tests/query-cve.sh b/var/tests/query-cve.sh new file mode 100755 index 0000000..215de4f --- /dev/null +++ b/var/tests/query-cve.sh @@ -0,0 +1 @@ +curl -s http://127.0.0.1:6666/query -H "Content-Type: application/json" --data @bodycve.json -X POST diff --git a/var/tests/query-dns.sh b/var/tests/query-dns.sh new file mode 100755 index 0000000..d03dc4d --- /dev/null +++ b/var/tests/query-dns.sh @@ -0,0 +1 @@ +curl -s http://127.0.0.1:6666/query -H "Content-Type: application/json" --data @body.json -X POST diff --git a/var/tests/query-sourcecache.sh b/var/tests/query-sourcecache.sh new file mode 100755 index 0000000..db6f365 --- /dev/null +++ b/var/tests/query-sourcecache.sh @@ -0,0 +1 @@ +curl -s http://127.0.0.1:6666/query -H "Content-Type: application/json" --data @bodysourcecache.json -X POST diff --git a/var/tests/search-modules.sh b/var/tests/search-modules.sh new file mode 100755 index 0000000..5b7e09f --- /dev/null +++ b/var/tests/search-modules.sh @@ -0,0 +1 @@ +curl -s http://127.0.0.1:6666/modules diff --git a/var/tests/stix.xml b/var/tests/stix.xml new file mode 100644 index 0000000..a4a60d8 --- /dev/null +++ b/var/tests/stix.xml @@ -0,0 +1,331 @@ + + + + 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/var/tests/test.py b/var/tests/test.py new file mode 100644 index 0000000..d506595 --- /dev/null +++ b/var/tests/test.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +import unittest +import requests +import base64 +import json +import os + + +class TestModules(unittest.TestCase): + + def setUp(self): + self.maxDiff = None + self.headers = {'Content-Type': 'application/json'} + self.url = "http://127.0.0.1:6666/" + + def test_introspection(self): + response = requests.get(self.url + "modules") + print(response.json()) + + def test_cve(self): + with open('tests/bodycve.json', 'r') as f: + response = requests.post(self.url + "query", data=f.read()) + print(response.json()) + + def test_dns(self): + with open('tests/body.json', 'r') as f: + response = requests.post(self.url + "query", data=f.read()) + print(response.json()) + with open('tests/body_timeout.json', 'r') as f: + response = requests.post(self.url + "query", data=f.read()) + print(response.json()) + + 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'), + "config": {"max_size": "15000"}, + }) + response = requests.post(self.url + "query", data=data) + print('STIX', response.json()) + + def test_virustotal(self): + # This can't actually be tested without disclosing a private + # API key. This will attempt to run with a .gitignored keyfile + # and pass if it can't find one + + if not os.path.exists("tests/bodyvirustotal.json"): + return + + with open("tests/bodyvirustotal.json", "r") as f: + response = requests.post(self.url + "query", data=f.read()).json() + assert(response) + +if __name__ == '__main__': + unittest.main()