├── .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 | 
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 |
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 |