├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── PowershellTrigger1.docm ├── PowershellTrigger2.docm ├── README.md ├── img ├── ProcessBouncer.gif ├── pb-inaction.png ├── pb-started.png ├── pb-starting.png ├── pblogo.jpg ├── pblogo.png ├── pblogo_small.png └── statendpoint_db.png └── processbouncer.ps1 /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team via @HolgerJunker. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | SHARING IS CARING!!! 2 | Everybody is welcome to contibute to the development of ProcessBouncer. Please use the features on GitHub or get into contact via @HolgerJunker. 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | EUROPEAN UNION PUBLIC LICENCE v. 1.2 2 | EUPL © the European Union 2007, 2016 3 | 4 | This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined 5 | below) which is provided under the terms of this Licence. Any use of the Work, 6 | other than as authorised under this Licence is prohibited (to the extent such 7 | use is covered by a right of the copyright holder of the Work). 8 | 9 | The Work is provided under the terms of this Licence when the Licensor (as 10 | defined below) has placed the following notice immediately following the 11 | copyright notice for the Work: 12 | 13 | Licensed under the EUPL 14 | 15 | or has expressed by any other means his willingness to license under the EUPL. 16 | 17 | 1. Definitions 18 | 19 | In this Licence, the following terms have the following meaning: 20 | 21 | - ‘The Licence’: this Licence. 22 | 23 | - ‘The Original Work’: the work or software distributed or communicated by the 24 | Licensor under this Licence, available as Source Code and also as Executable 25 | Code as the case may be. 26 | 27 | - ‘Derivative Works’: the works or software that could be created by the 28 | Licensee, based upon the Original Work or modifications thereof. This Licence 29 | does not define the extent of modification or dependence on the Original Work 30 | required in order to classify a work as a Derivative Work; this extent is 31 | determined by copyright law applicable in the country mentioned in Article 15. 32 | 33 | - ‘The Work’: the Original Work or its Derivative Works. 34 | 35 | - ‘The Source Code’: the human-readable form of the Work which is the most 36 | convenient for people to study and modify. 37 | 38 | - ‘The Executable Code’: any code which has generally been compiled and which is 39 | meant to be interpreted by a computer as a program. 40 | 41 | - ‘The Licensor’: the natural or legal person that distributes or communicates 42 | the Work under the Licence. 43 | 44 | - ‘Contributor(s)’: any natural or legal person who modifies the Work under the 45 | Licence, or otherwise contributes to the creation of a Derivative Work. 46 | 47 | - ‘The Licensee’ or ‘You’: any natural or legal person who makes any usage of 48 | the Work under the terms of the Licence. 49 | 50 | - ‘Distribution’ or ‘Communication’: any act of selling, giving, lending, 51 | renting, distributing, communicating, transmitting, or otherwise making 52 | available, online or offline, copies of the Work or providing access to its 53 | essential functionalities at the disposal of any other natural or legal 54 | person. 55 | 56 | 2. Scope of the rights granted by the Licence 57 | 58 | The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, 59 | sublicensable licence to do the following, for the duration of copyright vested 60 | in the Original Work: 61 | 62 | - use the Work in any circumstance and for all usage, 63 | - reproduce the Work, 64 | - modify the Work, and make Derivative Works based upon the Work, 65 | - communicate to the public, including the right to make available or display 66 | the Work or copies thereof to the public and perform publicly, as the case may 67 | be, the Work, 68 | - distribute the Work or copies thereof, 69 | - lend and rent the Work or copies thereof, 70 | - sublicense rights in the Work or copies thereof. 71 | 72 | Those rights can be exercised on any media, supports and formats, whether now 73 | known or later invented, as far as the applicable law permits so. 74 | 75 | In the countries where moral rights apply, the Licensor waives his right to 76 | exercise his moral right to the extent allowed by law in order to make effective 77 | the licence of the economic rights here above listed. 78 | 79 | The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to 80 | any patents held by the Licensor, to the extent necessary to make use of the 81 | rights granted on the Work under this Licence. 82 | 83 | 3. Communication of the Source Code 84 | 85 | The Licensor may provide the Work either in its Source Code form, or as 86 | Executable Code. If the Work is provided as Executable Code, the Licensor 87 | provides in addition a machine-readable copy of the Source Code of the Work 88 | along with each copy of the Work that the Licensor distributes or indicates, in 89 | a notice following the copyright notice attached to the Work, a repository where 90 | the Source Code is easily and freely accessible for as long as the Licensor 91 | continues to distribute or communicate the Work. 92 | 93 | 4. Limitations on copyright 94 | 95 | Nothing in this Licence is intended to deprive the Licensee of the benefits from 96 | any exception or limitation to the exclusive rights of the rights owners in the 97 | Work, of the exhaustion of those rights or of other applicable limitations 98 | thereto. 99 | 100 | 5. Obligations of the Licensee 101 | 102 | The grant of the rights mentioned above is subject to some restrictions and 103 | obligations imposed on the Licensee. Those obligations are the following: 104 | 105 | Attribution right: The Licensee shall keep intact all copyright, patent or 106 | trademarks notices and all notices that refer to the Licence and to the 107 | disclaimer of warranties. The Licensee must include a copy of such notices and a 108 | copy of the Licence with every copy of the Work he/she distributes or 109 | communicates. The Licensee must cause any Derivative Work to carry prominent 110 | notices stating that the Work has been modified and the date of modification. 111 | 112 | Copyleft clause: If the Licensee distributes or communicates copies of the 113 | Original Works or Derivative Works, this Distribution or Communication will be 114 | done under the terms of this Licence or of a later version of this Licence 115 | unless the Original Work is expressly distributed only under this version of the 116 | Licence — for example by communicating ‘EUPL v. 1.2 only’. The Licensee 117 | (becoming Licensor) cannot offer or impose any additional terms or conditions on 118 | the Work or Derivative Work that alter or restrict the terms of the Licence. 119 | 120 | Compatibility clause: If the Licensee Distributes or Communicates Derivative 121 | Works or copies thereof based upon both the Work and another work licensed under 122 | a Compatible Licence, this Distribution or Communication can be done under the 123 | terms of this Compatible Licence. For the sake of this clause, ‘Compatible 124 | Licence’ refers to the licences listed in the appendix attached to this Licence. 125 | Should the Licensee's obligations under the Compatible Licence conflict with 126 | his/her obligations under this Licence, the obligations of the Compatible 127 | Licence shall prevail. 128 | 129 | Provision of Source Code: When distributing or communicating copies of the Work, 130 | the Licensee will provide a machine-readable copy of the Source Code or indicate 131 | a repository where this Source will be easily and freely available for as long 132 | as the Licensee continues to distribute or communicate the Work. 133 | 134 | Legal Protection: This Licence does not grant permission to use the trade names, 135 | trademarks, service marks, or names of the Licensor, except as required for 136 | reasonable and customary use in describing the origin of the Work and 137 | reproducing the content of the copyright notice. 138 | 139 | 6. Chain of Authorship 140 | 141 | The original Licensor warrants that the copyright in the Original Work granted 142 | hereunder is owned by him/her or licensed to him/her and that he/she has the 143 | power and authority to grant the Licence. 144 | 145 | Each Contributor warrants that the copyright in the modifications he/she brings 146 | to the Work are owned by him/her or licensed to him/her and that he/she has the 147 | power and authority to grant the Licence. 148 | 149 | Each time You accept the Licence, the original Licensor and subsequent 150 | Contributors grant You a licence to their contributions to the Work, under the 151 | terms of this Licence. 152 | 153 | 7. Disclaimer of Warranty 154 | 155 | The Work is a work in progress, which is continuously improved by numerous 156 | Contributors. It is not a finished work and may therefore contain defects or 157 | ‘bugs’ inherent to this type of development. 158 | 159 | For the above reason, the Work is provided under the Licence on an ‘as is’ basis 160 | and without warranties of any kind concerning the Work, including without 161 | limitation merchantability, fitness for a particular purpose, absence of defects 162 | or errors, accuracy, non-infringement of intellectual property rights other than 163 | copyright as stated in Article 6 of this Licence. 164 | 165 | This disclaimer of warranty is an essential part of the Licence and a condition 166 | for the grant of any rights to the Work. 167 | 168 | 8. Disclaimer of Liability 169 | 170 | Except in the cases of wilful misconduct or damages directly caused to natural 171 | persons, the Licensor will in no event be liable for any direct or indirect, 172 | material or moral, damages of any kind, arising out of the Licence or of the use 173 | of the Work, including without limitation, damages for loss of goodwill, work 174 | stoppage, computer failure or malfunction, loss of data or any commercial 175 | damage, even if the Licensor has been advised of the possibility of such damage. 176 | However, the Licensor will be liable under statutory product liability laws as 177 | far such laws apply to the Work. 178 | 179 | 9. Additional agreements 180 | 181 | While distributing the Work, You may choose to conclude an additional agreement, 182 | defining obligations or services consistent with this Licence. However, if 183 | accepting obligations, You may act only on your own behalf and on your sole 184 | responsibility, not on behalf of the original Licensor or any other Contributor, 185 | and only if You agree to indemnify, defend, and hold each Contributor harmless 186 | for any liability incurred by, or claims asserted against such Contributor by 187 | the fact You have accepted any warranty or additional liability. 188 | 189 | 10. Acceptance of the Licence 190 | 191 | The provisions of this Licence can be accepted by clicking on an icon ‘I agree’ 192 | placed under the bottom of a window displaying the text of this Licence or by 193 | affirming consent in any other similar way, in accordance with the rules of 194 | applicable law. Clicking on that icon indicates your clear and irrevocable 195 | acceptance of this Licence and all of its terms and conditions. 196 | 197 | Similarly, you irrevocably accept this Licence and all of its terms and 198 | conditions by exercising any rights granted to You by Article 2 of this Licence, 199 | such as the use of the Work, the creation by You of a Derivative Work or the 200 | Distribution or Communication by You of the Work or copies thereof. 201 | 202 | 11. Information to the public 203 | 204 | In case of any Distribution or Communication of the Work by means of electronic 205 | communication by You (for example, by offering to download the Work from a 206 | remote location) the distribution channel or media (for example, a website) must 207 | at least provide to the public the information requested by the applicable law 208 | regarding the Licensor, the Licence and the way it may be accessible, concluded, 209 | stored and reproduced by the Licensee. 210 | 211 | 12. Termination of the Licence 212 | 213 | The Licence and the rights granted hereunder will terminate automatically upon 214 | any breach by the Licensee of the terms of the Licence. 215 | 216 | Such a termination will not terminate the licences of any person who has 217 | received the Work from the Licensee under the Licence, provided such persons 218 | remain in full compliance with the Licence. 219 | 220 | 13. Miscellaneous 221 | 222 | Without prejudice of Article 9 above, the Licence represents the complete 223 | agreement between the Parties as to the Work. 224 | 225 | If any provision of the Licence is invalid or unenforceable under applicable 226 | law, this will not affect the validity or enforceability of the Licence as a 227 | whole. Such provision will be construed or reformed so as necessary to make it 228 | valid and enforceable. 229 | 230 | The European Commission may publish other linguistic versions or new versions of 231 | this Licence or updated versions of the Appendix, so far this is required and 232 | reasonable, without reducing the scope of the rights granted by the Licence. New 233 | versions of the Licence will be published with a unique version number. 234 | 235 | All linguistic versions of this Licence, approved by the European Commission, 236 | have identical value. Parties can take advantage of the linguistic version of 237 | their choice. 238 | 239 | 14. Jurisdiction 240 | 241 | Without prejudice to specific agreement between parties, 242 | 243 | - any litigation resulting from the interpretation of this License, arising 244 | between the European Union institutions, bodies, offices or agencies, as a 245 | Licensor, and any Licensee, will be subject to the jurisdiction of the Court 246 | of Justice of the European Union, as laid down in article 272 of the Treaty on 247 | the Functioning of the European Union, 248 | 249 | - any litigation arising between other parties and resulting from the 250 | interpretation of this License, will be subject to the exclusive jurisdiction 251 | of the competent court where the Licensor resides or conducts its primary 252 | business. 253 | 254 | 15. Applicable Law 255 | 256 | Without prejudice to specific agreement between parties, 257 | 258 | - this Licence shall be governed by the law of the European Union Member State 259 | where the Licensor has his seat, resides or has his registered office, 260 | 261 | - this licence shall be governed by Belgian law if the Licensor has no seat, 262 | residence or registered office inside a European Union Member State. 263 | 264 | Appendix 265 | 266 | ‘Compatible Licences’ according to Article 5 EUPL are: 267 | 268 | - GNU General Public License (GPL) v. 2, v. 3 269 | - GNU Affero General Public License (AGPL) v. 3 270 | - Open Software License (OSL) v. 2.1, v. 3.0 271 | - Eclipse Public License (EPL) v. 1.0 272 | - CeCILL v. 2.0, v. 2.1 273 | - Mozilla Public Licence (MPL) v. 2 274 | - GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3 275 | - Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for 276 | works other than software 277 | - European Union Public Licence (EUPL) v. 1.1, v. 1.2 278 | - Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong 279 | Reciprocity (LiLiQ-R+). 280 | 281 | The European Commission may update this Appendix to later versions of the above 282 | licences without producing a new version of the EUPL, as long as they provide 283 | the rights granted in Article 2 of this Licence and protect the covered Source 284 | Code from exclusive appropriation. 285 | 286 | All other changes or additions to this Appendix require the production of a new 287 | EUPL version. 288 | -------------------------------------------------------------------------------- /PowershellTrigger1.docm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hjunker/ProcessBouncer/ccbb9e3eef72b7d87012a89d7f0971329f6660a1/PowershellTrigger1.docm -------------------------------------------------------------------------------- /PowershellTrigger2.docm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hjunker/ProcessBouncer/ccbb9e3eef72b7d87012a89d7f0971329f6660a1/PowershellTrigger2.docm -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ProcessBouncer 2 | ProcessBouncer is a simple but effective tool for blocking malware with a process-based approach. With a little fine-tuning this allows to effectively block most of current ransomware that is out there. 3 | 4 | ## Running ProcessBouncer 5 | 6 | ProcessBouncer is basically a powershell script. Simply run processbouncer.ps1 to get started. 7 | 8 | 9 | 10 | The powershell window you see will fill up with information on newly spawned processes over time. 11 | 12 | 13 | 14 | An alert pops up when a new process is created that ProcessBouncer categorizes as suspicious. 15 | 16 | 17 | 18 | The user can then see some further information and (if he is allowed to by the admin's configuration/customization) make a decision on running / suspending / terminating the process. 19 | 20 | For testing purposes, some .docm files are included in this repository. You can use these to fine-tune ProcessBouncer (especially $new_process_check_interval in the settings section) to make it fit your needs. 21 | 22 | Simply running ProcessBouncer without customization might leave some risks and make you prone to false positives. Check the section marked "1. settings (CONFIG section)" of processbouncer.ps1 for adjusting ProcessBouncer to your individual needs. The configuration in this section is pretty self-explanatory. 23 | 24 | ## important: liability statement 25 | 26 | The default configuration of ProcessBouncer has been created using best efforts for minimizing any negative impact on windows systems secured with this tool. Anyhow it can not be guaranteed that ProcessBouncer has not negative impact on (legitimate) processes on your system(s). This can happen when e.g. the configuration is changed or ProcessBouncer suspends a screen saver or driver components. Such scenarios regarding false positives should be tested on a non-productive system before deployment and the configuration of ProcessBouncer should be optimized for your specific needs. The authors and publishers of ProcessBouncer can not be held liable or responsible for any impact of the tool to your systems. 27 | 28 | ### ExecutionPolicy and Run as... 29 | Depending on your Windows version and various settings it might be necessary to run ProcessBouncer with Administrator's priviledges. If you run into the situation that you are not allowed running (unsigned) powershell scripts. Try running powershell as Administrator and type: 30 | Set-ExecutionPolicy Unrestricted 31 | ...and confirm the dialogue. 32 | Please refer to https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/set-executionpolicy?view=powershell-6 for further information. 33 | 34 | ### Enable Writing to Windows EventLog 35 | In order to enable ProcessBouncer to write to the windows EventLog, execute the following command as administrator: 36 | 37 | New-EventLog -LogName ProcessBouncer -Source "ProcessBouncer" 38 | 39 | You may choose an individual LogName, but remember to change $logname in the powershell script. 40 | 41 | ### Sign your ProcessBouncer script 42 | No matter whether you run ProcessBouncer as Administrator or a regular user, you should 43 | allow your windows system(s) to execute only signed powershell scripts. 44 | 45 | Please refer to this site for further advice: https://www.scriptinglibrary.com/languages/powershell/how-to-sign-a-powershell-script/ 46 | 47 | ### co-existence with other security software 48 | ProcessBouncer is mainly tested in combination with Windows Defender. 49 | 50 | Problems have been reported to me when using Symantec or TrendMicro. One solution to this can be to whitelist the ProcessBouncer Powershell script in your anti-virus software. 51 | 52 | ## Technical details 53 | While this script is running (no admin permissions shall be required) this should protect the user from typical ransomware infections. This is accomplished by using _Windows Management Instrumentation (WMI)_ to get notified (asynchronously get events) on newly started processes and check some of their characteristics for things that are probably of malicious nature. There are various options to choose and to extend for making the script work best. Please check and tune the included white- and blacklists carefully. Once a process is rated as suspicious it is suspended / terminated. A GUI popup is shown to the user to inform him that it might be the time to take his hands of his keyboard and call the IT department. If you configure Process Bouncer to only suspend the suspicious process, you can e.g. set up a remote-session and check the process that is still running... and hey... you are on the front line of cyber defense... and you are winning! 54 | 55 | ### Limitations 56 | 57 | Because Process Bouncer relies on WMI to get information about newly spawned processes, it will not be able to suspend extremely _short-lived processes_ (processes which only execute for a split second, e.g. Windows' _whoami.exe_). PsC is not involved in the process creation logic, it relies on 58 | WMI events which are only generated once the process has already been launched. There are methods to get synchronously involved in the process creation logic (e.g. by using the _PsSetCreateProcessNotifyRoutine kernel API_), but this is out of scope for this Powershell tool :-). 59 | 60 | ### Customization 61 | Well, if you have gone through the steps of initial configuration / customization (the config section mentioned earlier - you remember?!) you should have a basic idea for further enhancements and customizations that especially meet the requirements and specifics of your infrastructure. You might want to exclude further paths from being able to execute processes. There might be individual applications that require some whitelisting. There is way more to work on here. Please feel welcome to get back to me with feedback and suggestions for further improvements. Twitter @HolgerJunker is a good way to catch me. 62 | 63 | Share your ideas! Here are some of mine... 64 | - One optional feature I have been thinking about is to use functions of MS Defender. 65 | - why not keep track of file access as an additional way of finding suspicious parameters (this looks more on ransomware already installed instead of the initial infection vector). 66 | - ProcessBouncer might soon include an option to make some improvement to windows settings (registry keys, AttackSurfaceReductionRules, ...) when ProcessBouncer is started. 67 | - Self-defence of ProcessBouncer might also make sense. 68 | 69 | ### implement your own statistics endpoint 70 | In order to collect statistics data for findings of ProcessBouncer you can make use of the mechanism already implemented. I save this data in a simple good old relational DB. 71 | 72 | 73 | 74 | ## License and Credits 75 | ProcessBouncer is licensed under EUPL (https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12). Please feel free to use and improve it. 76 | 77 | _author:_ Holger Junker ([@HolgerJunker](https://twitter.com/HolgerJunker)) 78 | 79 | logo: © Can Stock Photo / Tribalium 80 | 81 | technical credits: the initial implementation was re-done based on the great script Process Spawn Control (PsC, [website](https://github.com/felixweyne/ProcessSpawnControl)) from Felix Weyne in 2018. 82 | 83 | Please also take a look at [ProcessBouncerService](https://github.com/Rotrixx/ProcessBouncerService) - an implementation of the same approach but as a windows service instead of a powershell script created by [@r0trixx](https://twitter.com/r0trixx) during his internship at BSI. 84 | 85 | musical credits: the work based on Felix's code was mainly done while listening to the great music of Mono Inc (e.g. Children of the Dark or Voices of Doom). 86 | -------------------------------------------------------------------------------- /img/ProcessBouncer.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hjunker/ProcessBouncer/ccbb9e3eef72b7d87012a89d7f0971329f6660a1/img/ProcessBouncer.gif -------------------------------------------------------------------------------- /img/pb-inaction.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hjunker/ProcessBouncer/ccbb9e3eef72b7d87012a89d7f0971329f6660a1/img/pb-inaction.png -------------------------------------------------------------------------------- /img/pb-started.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hjunker/ProcessBouncer/ccbb9e3eef72b7d87012a89d7f0971329f6660a1/img/pb-started.png -------------------------------------------------------------------------------- /img/pb-starting.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hjunker/ProcessBouncer/ccbb9e3eef72b7d87012a89d7f0971329f6660a1/img/pb-starting.png -------------------------------------------------------------------------------- /img/pblogo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hjunker/ProcessBouncer/ccbb9e3eef72b7d87012a89d7f0971329f6660a1/img/pblogo.jpg -------------------------------------------------------------------------------- /img/pblogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hjunker/ProcessBouncer/ccbb9e3eef72b7d87012a89d7f0971329f6660a1/img/pblogo.png -------------------------------------------------------------------------------- /img/pblogo_small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hjunker/ProcessBouncer/ccbb9e3eef72b7d87012a89d7f0971329f6660a1/img/pblogo_small.png -------------------------------------------------------------------------------- /img/statendpoint_db.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hjunker/ProcessBouncer/ccbb9e3eef72b7d87012a89d7f0971329f6660a1/img/statendpoint_db.png -------------------------------------------------------------------------------- /processbouncer.ps1: -------------------------------------------------------------------------------- 1 | ######################################## 2 | # 3 | # ProcessBouncer - preventing ransomware with a simple script 4 | # 5 | # WARNING: Running this script shall prevent you from most of the current ransomware 6 | # samples that are out there. This script is not a replacement for anti virus software, 7 | # endpoint detection, etc. - it is only an additional security measure 8 | # Everyone is advised to be careful and watch his or her clicks. 9 | 10 | ######################################## 11 | 12 | 13 | # 14 | # 1. settings (CONFIG section) 15 | # 16 | #region settings 17 | # these variables let you enable/disable each kind of check 18 | $checkBadHashes = $False; 19 | $checkPowershellPayload = $False; 20 | $checkIgnoredProcesses = $True; 21 | $checkWhitelistedExecutablePaths = $True; 22 | $checkSuspiciousProcesses = $True; 23 | $checkSuspiciousParents = $True; 24 | $checkExecutablePaths = $True; 25 | $checkDoubleExtensions = $True; 26 | $checkCommandLineLength = $False; 27 | 28 | # gui settings 29 | $showPopup = $True 30 | $popupWidth=650; 31 | $popupScreenBorderDistance=20; 32 | 33 | # logfile 34 | $time = (Get-Date -Format "yyyy-MM-dd_HH-mm-ss"); 35 | $out_file = ".\ProcessBouncer-" + $time + ".log"; 36 | 37 | # To enable / disable reporting suspicious findings to the given endpoint can be done by setting $reportfindings to $True / $False. deactivate feedback you can comment the following line. But keep in mind that only by giving this kind of feedback there can be further improvements to ProcessBouncer. 38 | $reportfindings = $False; 39 | 40 | # if you want to enable Process Bouncer to write to Windows EventLog set this to $True - but check the README file's section 'Enable Writing to Windows EventLog' for setting this up 41 | $writeEventLog = $False; 42 | # The acceptable values for the parameter $eventLogEntryType are: Error, Warning, Information, SuccessAudit, and FailureAudit 43 | $eventLogEntryType = "Warning"; 44 | 45 | # URL of the endpoint where suspicious finding is reported to (if $reportfindings == $True) 46 | $endpointUrl = "http://www.seculancer.de/test.php" 47 | 48 | # These processes are considered suspicious mostly but there are further checks. Handle with care. 49 | # if you really need to run stuff like powershell or cmd, do not include them here. It might be better for you to catch them with suspicious parents - e.g. a svchost.exe called from powershell might be worth blocking. 50 | $suspiciousProcesses=@("powershell.exe", "powershell","cmd.exe", "cmd"); 51 | 52 | # These LotL tools (meaning: living off the land tools already present on the victim's system that come handy for an attacker - not the great band lord of the lost) 53 | $lotlTools=@("at", "at.exe", "bitsadmin", "bitsadmin.exe", "certutil", "certutil.exe", "cmd", "cmd.exe", "cmstp", "cmstp.exe", "control", "control.exe", "copy", "copy.exe", "csc", "csc.exe", "cscript", "cscript.exe", "curl", "curl.exe", "eqnedt32", "eqnedt32.exe", "hh", "hh.exe", "installutil", "installutil.exe", "javaw", "javaw.exe", "msbuild", "msbuild.exe", "mshta", "mshta.exe", "msiexec", "msiexec.exe", "msxsl", "msxsl.exe", "net", "net.exe", "netsh", "netsh.exe", "powershell", "powershell.exe", "psexec", "psexec.exe", "reg", "reg.exe", "regasm", "regasm.exe", "regedit", "regedit.exe", "regsvcs", "regsvcs.exe", "regsvr32", "regsvr32.exe", "remcos", "remcos.exe", "rundll32", "rundll32.exe", "runonce", "runonce.exe", "sc", "sc.exe", "schtasks", "schtasks.exe", "streams", "streams.exe", "tasklist", "tasklist.exe", "whoami", "whoami.exe", "winexesvc", "winexesvc.exe", "wmic", "wmic.exe", "wscript", "wscript"); 54 | 55 | # add # at the beginning of the following line to NOT check for LotL tools in suspiciousProcesses 56 | $suspiciousProcesses = [array]$suspiciousProcesses + $lotlTools; 57 | 58 | # These processes are considered suspicious when they become parents by creating a child process. Handle with care. 59 | $suspiciousParents=@("WINWORD","WINWORD.EXE","EXCEL","EXCEL.EXE","powershell.exe","powershell","cmd","cmd.exe"); 60 | 61 | # these processes are whitelisted - meaning the just pass through Process Bouncer. Handle with greatest care. Malicious processes might lie about their name. 62 | $ignoredProcesses=@("chrome.exe","dllhost.exe","SearchProtocolHost.exe","SearchFilterHost.exe","taskhost.exe", "conhost.exe", "SearchProtocolHost", "SearchProtocolHost.exe", "backgroundTaskHost.exe", "RuntimeBroker.exe"); #these processes will never be suspended 63 | 64 | # these executable paths are considered suspicious. Handle with care 65 | $suspiciousExecutablePaths=@("C:\\Users", [System.IO.Path]::GetTempPath(), $env:USERPROFILE); 66 | 67 | # these whitelisted entries can skip detection e.g. for LotL tools! Handle with extreme care! Do not include things like C:\\Windows or C:\\WINDOWS\\system32 here! 68 | #$whitelistedExecutablePaths = @("---"); 69 | $whitelistedExecutablePaths = @("C:\\hp", "C:\Programme", "C:\\Progra~1", "C:\\ProgramData", "C:\\Program Files (x86)\\Google\\Chrome\\Application", "C:\\Program Files\\Realtek\\Audio", "C:\\Program Files (x86)\\Microsoft\\Edge Dev\\Application", "C:\\Windows", "C:\\WINDOWS\\system32", "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Accessories"); 70 | 71 | # Suspicious double extension of file 72 | $ext1 = @("jpg", "jpeg", "pdf", "doc", "docx", "docm", "dot", "xls"); 73 | $ext2 = @("exe", "com", "ps1", "dll", "bat", "pif"); 74 | ForEach ($e1 in $ext1) 75 | { 76 | ForEach ($e2 in $ext2) 77 | { 78 | [array]$DoubleExtensions += $e1 + "." + $e2; 79 | } 80 | } 81 | 82 | # length which seems suspicious for some calls, might be e.g. from powershell payload 83 | $suspiciousCmdLen = 20 84 | 85 | # Test the default for TimeSpan is (0,0,0,0,750). Shorter time spans can result in increased system load. Longer time spans can result in blind spots with regards to very short-lived processes (which might apply to malicious powershell calls). Handle with a lot of care. 86 | $new_process_check_interval = New-Object System.TimeSpan(0,0,0,0,600); #public TimeSpan (int days, int hours, int minutes, int seconds, int milliseconds); 87 | 88 | # bad hashes list / file(s) - this will soon be taken from a local file 89 | $badHashes = @("3803A81C05CAE8BAF87BD18DAB7DC590B8A2AC98789C3ADABCCED7BA26A36BFE", "13CE56C12DCCB52FEB4B01622D6440CC1934BA6F37F48A8FFA469DB3AE71BDDF", "13CE56C12DCCB52FEB4B01622D6440CC1934BA6F37F48A8FFA469DB3AE71BDDF"); 90 | #endregion settings 91 | 92 | # 93 | # 2. setup - write some things to files from registry, ... 94 | # 95 | #region setup 96 | Add-Content -Path $out_file -Value ($time + ' - ProcessBouncer starting...') 97 | 98 | # The following log data is written locally. It might be helpful for debugging yourself or if you need support from me. 99 | $(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion' CurrentMajorVersionNumber).CurrentMajorVersionNumber 100 | 101 | Add-Content -Path $out_file -Value ("Windows Major Version: " + $(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion' CurrentMajorVersionNumber).CurrentMajorVersionNumber); 102 | Add-Content -Path $out_file -Value ("Windows Minor Version: " + $(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion' CurrentMinorVersionNumber).CurrentMinorVersionNumber); 103 | #Add-Content -Path $out_file -Value ("HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Word\Security: " + $(Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Word\Security' VBAWarnings).VBAWarnings); 104 | #Add-Content -Path $out_file -Value ("HKEY_CURRENT_USER\software\policies\microsoft\office\16.0\excel\security: " + $(Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\software\policies\microsoft\office\16.0\excel\security' VBAWarnings).VBAWarnings); 105 | #Add-Content -Path $out_file -Value ("HKEY_CURRENT_USER\software\policies\microsoft\office\16.0\excel\security: " + $(Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\software\policies\microsoft\office\16.0\excel\security' VBAWarnings).VBAWarnings); 106 | #Add-Content -Path $out_file -Value ("HKEY_CURRENT_USER\software\policies\microsoft\office\16.0\powerpoint\security: " + $(Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\software\policies\microsoft\office\16.0\powerpoint\security' VBAWarnings).VBAWarnings); 107 | #Add-Content -Path $out_file -Value ("HKEY_CURRENT_USER\software\policies\microsoft\office\16.0\word\security: " + $(Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\software\policies\microsoft\office\16.0\word\security' VBAWarnings).VBAWarnings); 108 | #Add-Content -Path $out_file -Value ("HKEY_CURRENT_USER\software\policies\microsoft\office\16.0\powerpoint\security: " + $(Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\software\policies\microsoft\office\16.0\powerpoint\security' VBAWarnings).VBAWarnings); 109 | #Add-Content -Path $out_file -Value ("HKEY_CURRENT_USER\software\policies\microsoft\office\16.0\word\security: " + $(Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\software\policies\microsoft\office\16.0\word\security' VBAWarnings).VBAWarnings); 110 | Add-Content -Path $out_file -Value ("HKEY_CURRENT_USER\Environment: " + $(Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\Environment' Path).Path); 111 | Add-Content -Path $out_file -Value ("HKEY_CURRENT_USER\Environment: " + $(Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\Environment' TEMP).TEMP); 112 | Add-Content -Path $out_file -Value ("HKEY_CURRENT_USER\Environment: " + $(Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\Environment' TMP).TMP); 113 | 114 | #cmd /c assoc 115 | 116 | # TODO: Create undo-file when making changes! 117 | #cmd /c ftype htafile 118 | #cmd /c ftype WSHFile 119 | #cmd /c ftype batfile 120 | #cmd /c ftype htafile="%SystemRoot%\system32\NOTEPAD.EXE" "%1" 121 | #cmd /c ftype WSHFile="%SystemRoot%\system32\NOTEPAD.EXE" "%1" 122 | #cmd /c ftype batfile="%SystemRoot%\system32\NOTEPAD.EXE" "%1" 123 | 124 | #:: Block Office applications from creating child processes 125 | #powershell.exe Add-MpPreference -AttackSurfaceReductionRules_Ids D4F940AB-401B-4EFC-AADC-AD5F3C50688A -AttackSurfaceReductionRules_Actions Enabled 126 | #:: Block Office applications from injecting code into other processes 127 | #powershell.exe Add-MpPreference -AttackSurfaceReductionRules_Ids 75668C1F-73B5-4CF0-BB93-3ECF5CB7CC84 -AttackSurfaceReductionRules_Actions enable 128 | #:: Block Win32 API calls from Office macro 129 | #powershell.exe Add-MpPreference -AttackSurfaceReductionRules_Ids 92E97FA1-2EDF-4476-BDD6-9DD0B4DDDC7B -AttackSurfaceReductionRules_Actions enable 130 | #:: Block Office applications from creating executable content 131 | #powershell.exe Add-MpPreference -AttackSurfaceReductionRules_Ids '3B576869-A4EC-4529-8536-B80A7769E899' -AttackSurfaceReductionRules_Actions enable 132 | #:: Block execution of potentially obfuscated scripts 133 | #powershell.exe Add-MpPreference -AttackSurfaceReductionRules_Ids 5BEB7EFE-FD9A-4556-801D-275E5FFC04CC -AttackSurfaceReductionRules_Actions Enabled 134 | #:: Block executable content from email client and webmail 135 | #powershell.exe Add-MpPreference -AttackSurfaceReductionRules_Ids BE9BA2D9-53EA-4CDC-84E5-9B1EEEE46550 -AttackSurfaceReductionRules_Actions Enabled 136 | #:: Block JavaScript or VBScript from launching downloaded executable content 137 | #powershell.exe Add-MpPreference -AttackSurfaceReductionRules_Ids D3E037E1-3EB8-44C8-A917-57927947596D -AttackSurfaceReductionRules_Actions Enabled 138 | 139 | Add-Content -Path $out_file -Value "---PROCESSES---"; 140 | Add-Content -Path $out_file -Value (Get-Process); 141 | Add-Content -Path $out_file -Value "---SERVICES---"; 142 | Add-Content -Path $out_file -Value (Get-Service); 143 | Add-Content -Path $out_file -Value "---HOTFIXES---"; 144 | Add-Content -Path $out_file -Value (Get-HotFix); 145 | Add-Content -Path $out_file -Value "---AUTORUN---"; 146 | Add-Content -Path $out_file -Value (Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\run); 147 | Add-Content -Path $out_file -Value "---NETFIREWALLRULES---"; 148 | Add-Content -Path $out_file -Value (Get-NetFirewallRule -all); 149 | #endregion setup 150 | 151 | # 152 | # 3. Functionality to suspend and resume processes 153 | # Source of this function: Poshcode, Joel Bennett 154 | # 155 | #region processhandling 156 | Add-Type -Name Threader -Namespace "" -Member @" 157 | [Flags] 158 | public enum ProcessAccess : uint 159 | { 160 | Terminate = 0x00000001, 161 | CreateThread = 0x00000002, 162 | VMOperation = 0x00000008, 163 | VMRead = 0x00000010, 164 | VMWrite = 0x00000020, 165 | DupHandle = 0x00000040, 166 | SetInformation = 0x00000200, 167 | QueryInformation = 0x00000400, 168 | SuspendResume = 0x00000800, 169 | Synchronize = 0x00100000, 170 | All = 0x001F0FFF 171 | } 172 | 173 | [DllImport("ntdll.dll", EntryPoint = "NtSuspendProcess", SetLastError = true)] 174 | public static extern uint SuspendProcess(IntPtr processHandle); 175 | 176 | [DllImport("ntdll.dll", EntryPoint = "NtResumeProcess", SetLastError = true)] 177 | public static extern uint ResumeProcess(IntPtr processHandle); 178 | 179 | [DllImport("kernel32.dll")] 180 | public static extern IntPtr OpenProcess(ProcessAccess dwDesiredAccess, bool bInheritHandle, uint dwProcessId); 181 | 182 | [DllImport("kernel32.dll", SetLastError=true)] 183 | public static extern bool CloseHandle(IntPtr hObject); 184 | "@ 185 | 186 | function Suspend-Process($processID) { 187 | if(($pProc = [Threader]::OpenProcess("SuspendResume", $false, $processID)) -ne [IntPtr]::Zero){ 188 | Write-Host "Trying to suspend process: $processID" 189 | 190 | $result = [Threader]::SuspendProcess($pProc) 191 | if($result -ne 0) { 192 | Write-Error "Failed to suspend. SuspendProcess returned: $result" 193 | return $False 194 | } 195 | [Threader]::CloseHandle($pProc) | out-null; 196 | } else { 197 | Write-Error "Unable to open process. Not elevated? Process doesn't exist anymore?" 198 | return $False 199 | } 200 | return $True 201 | } 202 | 203 | function Resume-Process($processID) { 204 | if(($pProc = [Threader]::OpenProcess("SuspendResume", $false, $processID)) -ne [IntPtr]::Zero){ 205 | Write-Host "Trying to resume process: $processID" 206 | Write-Host "" 207 | $result = [Threader]::ResumeProcess($pProc) 208 | if($result -ne 0) { 209 | Write-Error "Failed to resume. ResumeProcess returned: $result" 210 | } 211 | [Threader]::CloseHandle($pProc) | out-null 212 | } else { 213 | Write-Error "Unable to open process. Process doesn't exist anymore?" 214 | } 215 | } 216 | 217 | # TODO: Terminate suspicious processes instead of just keeping them suspended 218 | function Stop-Process($processID) { 219 | if(($pProc = [Threader]::OpenProcess("SuspendResume", $false, $processID)) -ne [IntPtr]::Zero){ 220 | Write-Host "Trying to terminate process: $processID" 221 | Write-Host "" 222 | $result = [Threader]::TerminateProcess($pProc) 223 | if($result -ne 0) { 224 | Write-Error "Failed to terminate. TerminateProcess returned: $result" 225 | } 226 | [Threader]::CloseHandle($pProc) | out-null 227 | } else { 228 | Write-Error "Unable to open process. Process doesn't exist anymore?" 229 | } 230 | } 231 | #endregion processhandling 232 | 233 | # 234 | # 4. Functionality to create user interface popup dialog 235 | # 236 | #region gui 237 | #function GenerateForm($processName,$processID,$parentProcessName) { 238 | [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null; 239 | [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null; 240 | 241 | $screen = [System.Windows.Forms.Screen]::PrimaryScreen; 242 | $bounds = $screen.Bounds; 243 | 244 | $mainForm = New-Object System.Windows.Forms.Form; 245 | $mainForm.TopMost = $True 246 | $labelProcessRun = New-Object System.Windows.Forms.Label; 247 | $labelRunningProcess = New-Object System.Windows.Forms.Label; 248 | $labelProcessID = New-Object System.Windows.Forms.Label; 249 | $labelParentProcessID = New-Object System.Windows.Forms.Label; 250 | $closeFormButton = New-Object System.Windows.Forms.Button; 251 | $resumeButton = New-Object System.Windows.Forms.Button; 252 | $suspendButton = New-Object System.Windows.Forms.Button; 253 | 254 | #button event handlers; 255 | $handler_closeFormButton_Click={ 256 | $this.findform().close(); 257 | } 258 | 259 | $handler_resumeButton_Click={ 260 | if ($listBox.SelectedItem -ne $null){ 261 | #[int]$processToResume=[convert]::ToInt32($this.Tag); 262 | $selectedId = $listBox.SelectedItem.substring($listBox.SelectedItem.IndexOf('(')+1,$listBox.SelectedItem.IndexOf(')')-$listBox.SelectedItem.IndexOf('(')-1); 263 | #[int]$processToResume=[convert]::ToInt32($listBox.SelectedItem); 264 | [int]$processToResume=[convert]::ToInt32($selectedId); 265 | $outstr = "Process " + $listBox.SelectedItem + " resumed by user."; 266 | Add-Content -Path $out_file -Value $outstr; 267 | if ($writeEventLog -eq $True){ 268 | Write-EventLog -LogName ProcessBouncer -Source "ProcessBouncer" -EntryType $eventLogEntryType -Message $outstr -EventId 1; 269 | } 270 | $listBox.Items.Remove($listBox.SelectedItem); 271 | Resume-Process -processID $processToResume 272 | #$this.findform().close(); 273 | } 274 | } 275 | $handler_suspendButton_Click={ 276 | if ($listBox.SelectedItem -ne $null){ 277 | $outstr = "Process " + $listBox.SelectedItem + " kept suspended by user."; 278 | Add-Content -Path $out_file -Value $outstr; 279 | if ($writeEventLog -eq $True){ 280 | Write-EventLog -LogName ProcessBouncer -Source "ProcessBouncer" -EntryType $eventLogEntryType -Message $outstr -EventId 1; 281 | } 282 | $listBox.Items.Remove($listBox.SelectedItem); 283 | #$this.findform().close(); 284 | } 285 | } 286 | 287 | #resume/suspend form 288 | $popupHeight=$popupWidth*0.4; 289 | $mainForm.Size = new-object System.Drawing.Size $popupWidth,$popupHeight; 290 | $mainForm.ControlBox = $False; 291 | $mainForm.Name = "mainForm"; 292 | $mainForm.FormBorderStyle = 'None'; 293 | $mainForm.BackColor = '#2c3e5b'; 294 | $mainForm.Text = "ProcessBouncer Warning: New process"; 295 | $mainForm.Left = $bounds.Right-$popupWidth-$popupScreenBorderDistance; 296 | $mainForm.Top = $bounds.Top+$popupScreenBorderDistance ; 297 | $mainForm.StartPosition = 'Manual'; 298 | 299 | #label description new process 300 | $labelProcessRun.Text = "ProcessBouncer wants to deny access:" 301 | $labelProcessRun.AutoSize = $True 302 | $labelProcessRun.Font = New-Object System.Drawing.Font("Lucida Console",9,[System.Drawing.FontStyle]::Regular); 303 | $labelProcessRun.ForeColor = 'white'; 304 | $labelProcessRun_drawingPoint = New-Object System.Drawing.Point; 305 | $labelProcessRun_drawingPoint.X = ($popupWidth*0.05); 306 | $labelProcessRun_drawingPoint.Y = ($popupHeight*0.06); 307 | $labelProcessRun.Location = $labelProcessRun_drawingPoint; 308 | 309 | #label running process 310 | $labelRunningProcess.Text = "Process: $processName" 311 | $labelRunningProcess.AutoSize = $True 312 | $labelRunningProcess.Font = New-Object System.Drawing.Font("Lucida Console",9,[System.Drawing.FontStyle]::Regular); 313 | $labelRunningProcess.ForeColor = 'white'; 314 | $labelRunningProcess_drawingPoint = New-Object System.Drawing.Point; 315 | $labelRunningProcess_drawingPoint.X = ($popupWidth*0.05); 316 | $labelRunningProcess_drawingPoint.Y = ($popupHeight*0.25); 317 | $labelRunningProcess.Location = $labelRunningProcess_drawingPoint; 318 | 319 | #label process id 320 | $labelProcessID.Text = "Process ID: $processID" 321 | $labelProcessID.AutoSize = $True 322 | $labelProcessID.Font = New-Object System.Drawing.Font("Lucida Console",9,[System.Drawing.FontStyle]::Regular); 323 | $labelProcessID.ForeColor = 'white'; 324 | $labelProcessID_drawingPoint = New-Object System.Drawing.Point; 325 | $labelProcessID_drawingPoint.X = ($popupWidth*0.05); 326 | $labelProcessID_drawingPoint.Y = ($popupHeight*0.4); 327 | $labelProcessID.Location = $labelProcessID_drawingPoint; 328 | 329 | #label parent process name 330 | $labelParentProcessID.Text = "Parent Process: $parentProcessName" 331 | $labelParentProcessID.AutoSize = $True 332 | $labelParentProcessID.Font = New-Object System.Drawing.Font("Lucida Console",9,[System.Drawing.FontStyle]::Regular); 333 | $labelParentProcessID.ForeColor = 'white'; 334 | $labelParentProcessID_drawingPoint = New-Object System.Drawing.Point; 335 | $labelParentProcessID_drawingPoint.X = ($popupWidth*0.05); 336 | $labelParentProcessID_drawingPoint.Y = ($popupHeight*0.55); 337 | $labelParentProcessID.Location = $labelParentProcessID_drawingPoint; 338 | 339 | #CloseForm Button 340 | $closeFormButton.TabIndex = 2; 341 | $closeFormButton_drawingSize = New-Object System.Drawing.Size; 342 | $closeFormButton_drawingSize.Width = 0.05*$popupWidth; 343 | $closeFormButton_drawingSize.Height = 0.05*$popupWidth; 344 | $closeFormButton.Size = $closeFormButton_drawingSize; 345 | $closeFormButton.FlatStyle = [System.Windows.Forms.FlatStyle]::Flat; 346 | $closeFormButton.FlatAppearance.BorderSize = 0; 347 | $closeFormButton.ForeColor = 'White'; 348 | $closeFormButton.Text = "X"; 349 | 350 | $closeFormButton_drawingPoint = New-Object System.Drawing.Point; 351 | $closeFormButton_drawingPoint.X = ($popupWidth*0.93); 352 | $closeFormButton_drawingPoint.Y = ($popupHeight*0.05); 353 | $closeFormButton.Location = $closeFormButton_drawingPoint; 354 | 355 | #resume process button 356 | $resumeButton.TabIndex = 0; 357 | $resumeButton_drawingSize = New-Object System.Drawing.Size; 358 | $resumeButton_drawingSize.Width = 0.40*$popupWidth; 359 | $resumeButton_drawingSize.Height = 0.20*$resumeButton_drawingSize.Width; 360 | $resumeButton.Size = $resumeButton_drawingSize; 361 | $resumeButton.FlatStyle = [System.Windows.Forms.FlatStyle]::Flat; 362 | $resumeButton.FlatAppearance.BorderColor = 'White'; 363 | $resumeButton.ForeColor = 'White'; 364 | $resumeButton.BackColor = '#169355'; 365 | $resumeButton.Font = New-Object System.Drawing.Font("Lucida Console",9,[System.Drawing.FontStyle]::Regular); 366 | $resumeButton.Text = "Allow run"; 367 | $resumeButton.Tag = $processID; 368 | 369 | $resumeButton_drawingPoint = New-Object System.Drawing.Point; 370 | $resumeButton_drawingPoint.X = ($popupWidth*0.05); 371 | $resumeButton_drawingPoint.Y = ($popupHeight*0.75); 372 | $resumeButton.Location = $resumeButton_drawingPoint; 373 | 374 | #suspend process button 375 | $suspendButton.TabIndex = 1; 376 | $suspendButton_drawingSize = New-Object System.Drawing.Size; 377 | $suspendButton_drawingSize.Width = $resumeButton_drawingSize.Width; 378 | $suspendButton_drawingSize.Height = $resumeButton_drawingSize.Height; 379 | $suspendButton.Size = $suspendButton_drawingSize; 380 | $suspendButton.FlatStyle = [System.Windows.Forms.FlatStyle]::Flat; 381 | $suspendButton.FlatAppearance.BorderColor = 'White'; 382 | $suspendButton.ForeColor = 'White'; 383 | $suspendButton.BackColor = '#921650'; 384 | $suspendButton.Font = New-Object System.Drawing.Font("Lucida Console",9,[System.Drawing.FontStyle]::Regular); 385 | $suspendButton.Text = "Keep suspended"; 386 | 387 | $suspendButton_drawingPoint = New-Object System.Drawing.Point; 388 | $suspendButton_drawingPoint.X = $popupWidth-($popupWidth*0.05) - $resumeButton_drawingSize.Width; 389 | $suspendButton_drawingPoint.Y = $resumeButton_drawingPoint.Y; 390 | $suspendButton.Location = $suspendButton_drawingPoint; 391 | 392 | $listBox = New-Object System.Windows.Forms.ListBox 393 | $listBox.Location = New-Object System.Drawing.Point(10,40) 394 | $listBox.Size = New-Object System.Drawing.Size(600,40) 395 | $listBox.Height = 80 396 | 397 | #add event handlers to buttons 398 | $closeFormButton.add_Click($handler_closeFormButton_Click); 399 | $resumeButton.add_Click($handler_resumeButton_Click); 400 | $suspendButton.add_Click($handler_suspendButton_Click); 401 | 402 | #add controls to form 403 | $mainForm.Controls.Add($closeFormButton); 404 | $mainForm.Controls.Add($resumeButton); 405 | $mainForm.Controls.Add($suspendButton); 406 | $mainForm.Controls.Add($labelProcessRun); 407 | #$mainForm.Controls.Add($labelProcessID); 408 | #$mainForm.Controls.Add($labelParentProcessID); 409 | #$mainForm.Controls.Add($labelRunningProcess); 410 | $mainForm.Controls.Add($listBox) 411 | 412 | #If we call $mainForm.ShowDialog() to launch the form, the console and form will share the same thread. 413 | #This means that the form will launch, and no further code of the powershell script will be processed run until the form closes. 414 | #We need to work around this by launching the form in a new runspace. 415 | #Source of tis code snippet: LogicVomit, Reddit. https://www.reddit.com/r/PowerShell/comments/41lebp/how_to_close_a_runspace_from_a_powershell_gui/ 416 | $Runspace = [Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($Host); 417 | $Runspace.ApartmentState = 'STA'; 418 | $Runspace.ThreadOptions = 'ReuseThread'; 419 | $Runspace.Open(); 420 | 421 | $Runspace.SessionStateProxy.SetVariable('mainForm', $mainForm); 422 | 423 | #Create new thread 424 | $PowerShellRunspace = [System.Management.Automation.PowerShell]::Create(); 425 | $PowerShellRunspace.Runspace = $Runspace; 426 | $PowerShellRunspace.AddScript({ 427 | $mainForm.ShowDialog(); 428 | }) | out-null; 429 | 430 | # open and run the runspace asynchronously 431 | $AsyncResult = $PowerShellRunspace.BeginInvoke(); 432 | #} 433 | #endregion gui 434 | 435 | # 436 | # 5. Functionality to monitor newly created processes & interact with the suspend/resume functionality. 437 | # This makes use of Windows Management Instrumentation to get information about newly created processes. 438 | # 439 | #region checks 440 | 441 | #There is a bug in WqlEventQuery which occurs when the supplied time interval is too small and if your system locale is non-English (e.g. Belgian). 442 | #(relevant StackOverflow page: https://stackoverflow.com/questions/5953434/wmi-query-in-c-sharp-does-not-work-on-non-english-machine) 443 | #Should you get the error "Exception calling WaitForNextEvent ... Unparsable query", uncomment the below code which changes the culture for the PS session. 444 | $culture = [System.Globalization.CultureInfo]::GetCultureInfo('en-US'); 445 | [System.Threading.Thread]::CurrentThread.CurrentUICulture = $culture; 446 | [System.Threading.Thread]::CurrentThread.CurrentCulture = $culture; 447 | 448 | Write-Host "Monitoring newly spawned processes via WMI..."; 449 | Write-host ""; 450 | 451 | #https://docs.microsoft.com/en-us/dotnet/api/system.management.wqleventquery.withininterval 452 | $scope = New-Object System.Management.ManagementScope("\\.\root\cimV2"); 453 | $query = New-Object System.Management.WQLEventQuery("__InstanceCreationEvent",$new_process_check_interval,"TargetInstance ISA 'Win32_Process'" ); 454 | $watcher = New-Object System.Management.ManagementEventWatcher($scope,$query); 455 | 456 | $processSpawnCounter=1; 457 | do 458 | { 459 | $newlyArrivedEvent = $watcher.WaitForNextEvent(); #Synchronous call! If Control+C is pressed to stop the PowerShell script, PS will only react once the call has returned an event. 460 | $e = $newlyArrivedEvent.TargetInstance; 461 | Write-Host "($processSpawnCounter) New process spawned:"; 462 | 463 | $processName=[string]$e.Name; 464 | Write-host "PID:`t`t" $e.ProcessId; 465 | Write-host "Name:`t`t" $processName; 466 | Write-host "PPID:`t`t" $e.ParentProcessID; 467 | Write-host "ExecutablePath:`t`t" $e.ExecutablePath; 468 | $filehash = "n/a"; 469 | if ($Null -ne $e.ExecutablePath) 470 | { 471 | $filehash = (Get-FileHash $e.ExecutablePath -Algorithm SHA256).Hash; 472 | #$filehash = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; 473 | } 474 | Write-host "File Hash:`t`t" $filehash; 475 | #$itemproperties = Get-ItemProperty $e.ExecutablePath | Format-List; 476 | $itemproperties = Get-ChildItem $e.ExecutablePath; 477 | Write-host "filesize:`t`t" $itemproperties.Length; 478 | 479 | #Write-host "file properties:`t`t" $itemproperties; 480 | Write-host "CommandLine:`t`t" $e.CommandLine; 481 | 482 | $parent_process=''; 483 | try {$proc=(Get-Process -id $e.ParentProcessID -ea stop); $parent_process=$proc.ProcessName;} catch {$parent_process='unknown';} 484 | Write-host "Parent name:`t" $parent_process; 485 | Write-host "CommandLine:`t" $e.CommandLine; 486 | 487 | $time = (Get-Date -UFormat "%A %B/%d/%Y %T"); 488 | $outstr = $time + "|" + $e.ProcessId + "|" + $processName + "|" + $parent_process + "|" + $e.ExecutablePath + "|" + $filehash + "|" + $e.CommandLine; 489 | Add-Content -Path $out_file -Value $outstr; 490 | if ($writeEventLog -eq $True){ 491 | Write-EventLog -LogName ProcessBouncer -Source "ProcessBouncer" -EntryType $eventLogEntryType -Message $outstr -EventId 1; 492 | } 493 | 494 | $tobeignoredProcess = $False; 495 | $tobeignoredPath = $False; 496 | $tobechecked = $False; 497 | 498 | if ($True -eq $checkPowershellPayload) 499 | { 500 | if (($e.processName -eq "powershell.exe") -or ($e.processName -eq "powershell")) 501 | { 502 | # TODO: extract powershell payload from command line - i.e. throw away command and options 503 | #$tmp = Write-host $e.CommandLine; 504 | #Write-host "deobfuscated powershell script:`t`t" $tmp; 505 | } 506 | } 507 | 508 | if ($True -eq $checkBadHashes) 509 | { 510 | ForEach ($el in $badHashes) 511 | { 512 | if ($filehash -eq $el) 513 | { 514 | $tobechecked = $True; 515 | Write-Host "-- badHashes match"; 516 | } 517 | } 518 | } 519 | 520 | # the following conditional statements can be tuned, extended, etc. to meet your specific requirements, minimize false positives, whitelist legitimate scripts and tools, ... 521 | #if (-not ($ignoredProcesses -match $processName)) 522 | if ($True -eq $checkIgnoredProcesses) 523 | { 524 | if ($ignoredProcesses -match $processName) 525 | { 526 | $tobeignoredProcess = $True; 527 | Write-Host "-- ignoredProcesses match"; 528 | } 529 | } 530 | 531 | if ($True -eq $checkWhitelistedExecutablePaths) 532 | { 533 | if ($null -ne ($whitelistedExecutablePaths | Where-Object { $e.ExecutablePath -match $_ })) 534 | { 535 | $tobeignoredPath = $True; 536 | Write-Host "-- whitelistedExecutablePaths match"; 537 | } 538 | } 539 | 540 | if ($True -eq $checkSuspiciousProcesses) 541 | { 542 | if ($null -ne ($suspiciousProcesses | Where-Object { $processName -match $_ })) 543 | { 544 | $tobechecked = $True; 545 | Write-Host "-- suspiciousProcesses match"; 546 | } 547 | } 548 | 549 | if ($True -eq $checkSuspiciousParents) 550 | { 551 | if ($suspiciousParents -match $parent_process) 552 | { 553 | $tobechecked = $True; 554 | Write-Host "-- suspiciousParents match"; 555 | } 556 | } 557 | 558 | if ($True -eq $checkExecutablePaths) 559 | { 560 | if ($null -ne ($suspiciousExecutablePaths | Where-Object { $e.ExecutablePath -match $_ })) 561 | { 562 | $tobechecked = $True; 563 | Write-Host "-- suspiciousExecutablePaths match"; 564 | } 565 | } 566 | 567 | if ($True -eq $checkDoubleExtensions) 568 | { 569 | if ($null -ne ($DoubleExtensions | Where-Object { $e.ExecutablePath -match $_ })) 570 | { 571 | $tobechecked = $True; 572 | Write-Host "-- doubleExtensions match"; 573 | } 574 | } 575 | 576 | if ($True -eq $checkCommandLineLength) 577 | { 578 | if ($e.CommandLine.length -gt $suspiciousCmdLen) 579 | { 580 | $tobechecked = $True; 581 | Write-Host "-- suspiciousCmdLen match"; 582 | } 583 | } 584 | 585 | if (($tobeignoredProcess -match $True) -or 586 | (($tobeignoredPath -match $True) -and ($tobechecked -match $False)) -or 587 | ($tobechecked -match $False) 588 | ) 589 | { 590 | Write-Host "Process ignored as per configuration."; 591 | }else{ 592 | if(Suspend-Process -processID $e.ProcessId){ 593 | 594 | $cmdlen = $e.CommandLine.Length; 595 | if ($cmdlen -gt 530) { 596 | $cmdlen = 530; 597 | } 598 | $cmdline = $e.CommandLine.Substring(0,$cmdlen); 599 | 600 | $outstr = "Suspicious process " + $processName + " spawned by " + $parent_process + " from path " + $e.ExecutablePath + " with parameters " + $cmdline + " and file hash " + $filehash; 601 | Add-Content -Path $out_file -Value $outstr; 602 | 603 | if($reportfindings -match $True){ 604 | $url = $endpointUrl + "?procname=" + $processName + "&processParentName=" + $parent_process + "&executablePath=" + $e.ExecutablePath + "&CommandLine=" + $cmdline + "&fileHash=" + $filehash 605 | $response = Invoke-WebRequest -URI $url; 606 | } 607 | if ($writeEventLog -eq $True){ 608 | Write-EventLog -LogName ProcessBouncer -Source "ProcessBouncer" -EntryType $eventLogEntryType -Message $outstr -EventId 1; 609 | } 610 | if ($showPopup -eq $True){ 611 | $listItemText = $processName + " initiated by " + $parent_process + " (" + $e.ProcessId + ")"; 612 | [void] $listBox.Items.Add($listItemText) 613 | } 614 | }else{ 615 | Write-Host "error during handling of suspicious process." 616 | } 617 | } 618 | 619 | Write-host ""; 620 | $processSpawnCounter += 1; 621 | } while ($True) 622 | #endregion checks --------------------------------------------------------------------------------