├── LICENSE
├── README.txt
├── Securing Development with PMD - Teaching an Old Dog New Tricks - 20120402.pdf
├── lib
└── pmd-gds-1.0.jar
├── rulesets
└── GDS
│ ├── OWASP
│ ├── A1 - Injection.xml
│ ├── A10 - Unvalidated Redirects and Forwards.xml
│ ├── A2 - Cross-Site Scripting.xml
│ ├── A7 - Insecure Cryptographic Storage.xml
│ └── A8 - Failure to Restrict URL Access.xml
│ └── SecureCodingRuleset.xml
├── samples
├── gds
│ ├── WebContent
│ │ ├── WEB-INF
│ │ │ ├── classes
│ │ │ │ ├── org
│ │ │ │ │ └── apache
│ │ │ │ │ │ └── jsp
│ │ │ │ │ │ └── test
│ │ │ │ │ │ ├── XSS
│ │ │ │ │ │ ├── XSS1_jsp.class
│ │ │ │ │ │ ├── XSS1_jsp.class.smap
│ │ │ │ │ │ ├── XSS1_jsp.java
│ │ │ │ │ │ ├── XSS2_jsp.class
│ │ │ │ │ │ ├── XSS2_jsp.class.smap
│ │ │ │ │ │ └── XSS2_jsp.java
│ │ │ │ │ │ └── include
│ │ │ │ │ │ ├── XSS2Include_jsp.class
│ │ │ │ │ │ ├── XSS2Include_jsp.class.smap
│ │ │ │ │ │ └── XSS2Include_jsp.java
│ │ │ │ └── test
│ │ │ │ │ └── com
│ │ │ │ │ └── gdssecurity
│ │ │ │ │ └── pmd
│ │ │ │ │ └── webapp
│ │ │ │ │ └── servlet
│ │ │ │ │ ├── TestRedirectServlet.class
│ │ │ │ │ ├── TestSqliServlet.class
│ │ │ │ │ ├── TestXSSServlet.class
│ │ │ │ │ └── authz
│ │ │ │ │ └── TestRoleAuthZServlet.class
│ │ │ └── generated_web.xml
│ │ └── test
│ │ │ ├── XSS
│ │ │ ├── XSS1.jsp
│ │ │ └── XSS2.jsp
│ │ │ └── include
│ │ │ └── XSS2Include.jsp
│ └── src
│ │ └── test
│ │ └── com
│ │ └── gdssecurity
│ │ └── pmd
│ │ └── webapp
│ │ └── servlet
│ │ ├── TestRedirectServlet.java
│ │ ├── TestSqliServlet.java
│ │ ├── TestXSSServlet.java
│ │ └── authz
│ │ └── TestRoleAuthZServlet.java
├── juliet-2010-12
│ ├── LICENSE
│ ├── antbuild
│ │ ├── testcases
│ │ │ ├── CWE327_Use_Broken_Crypto
│ │ │ │ └── CWE327_Use_Broken_Crypto__basic_01.class
│ │ │ └── CWE328_Reversible_One_Way_Hash
│ │ │ │ └── CWE328_Reversible_One_Way_Hash__basic_01.class
│ │ └── testcasesupport
│ │ │ ├── AbstractTestCase.class
│ │ │ ├── AbstractTestCaseClassIssueBad.class
│ │ │ ├── AbstractTestCaseClassIssueGood.class
│ │ │ ├── AbstractTestCaseServlet.class
│ │ │ ├── IO.class
│ │ │ ├── Main.class
│ │ │ └── ServletMain.class
│ └── src
│ │ └── testcases
│ │ ├── CWE327_Use_Broken_Crypto
│ │ └── CWE327_Use_Broken_Crypto__basic_01.java
│ │ └── CWE328_Reversible_One_Way_Hash
│ │ └── CWE328_Reversible_One_Way_Hash__basic_01.java
└── run_pmd.bat
└── src
└── com
└── gdssecurity
└── pmd
├── SecurityRuleViolation.java
├── Utils.java
├── rules
├── BaseSecurityRule.java
├── SqlStringConcatentation.java
└── dfa
│ └── DfaSecurityRule.java
└── smap
├── SmapFileReader.java
├── SmapReader.java
└── SmapResolver.java
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------
/README.txt:
--------------------------------------------------------------------------------
1 | GDS PMD Secure Coding Ruleset - Custom ruleset for the open source static analysis tool PMD (http://pmd.sourceforge.net/). The ruleset contains rules intended to identify security violations that map to the 2010 OWASP Top 10 (https://www.owasp.org/index.php/Top_10_2010-Main) application security risks.
2 |
3 | Author: Joe Hemler - Gotham Digital Science (labs@gdssecurity.com)
4 |
5 | Below are instructions for running PMD 4.2.X with the GDS Secure Coding Ruleset.
6 |
7 |
8 | Basic Usage Steps
9 | -----------------
10 |
11 | Before reading the steps below, please first read the official PMD documentation for running PMD from the command-line or as a ANT task. The following steps supplement the typical instructions for running PMD and should be followed irrespective of whether PMD will be run from the command-line or as a ANT task.
12 |
13 | 1. Place pmd-gds-1.0.jar on the PMD CLASSPATH
14 |
15 | 2. For the application source code to be scanned, place libraries and classes normally needed to build it on the PMD CLASSPATH. This provides additional type information to PMD, which makes for more accurate results.
16 |
17 | 3. Configure PMD to use the GDS Secure Coding Ruleset. Assuming pmd-gds-1.0.jar is on the CLASSPATH, this ruleset will be accessible via "rulesets/GDS/SecureCodingRuleset.xml".
18 |
19 | 4. Run PMD against application source code and audit the results to determine if a security violation reported by PMD is actually a security vulnerability.
20 |
21 | Next Steps
22 | ----------
23 |
24 | - Refer to the section in this README "Preparing JSP Files for Scanning" if the application source code includes JSP files.
25 |
26 | - Refer to the section in this README "Running PMDTask with the GDS Secure Coding Ruleset" for assistance with running the PMD ANT task with the GDS Secure Coding Ruleset.
27 |
28 | - Refer to the file rulesets/GDS/SecureCodingRuleset.xml for information about the types of issues the rules will find and how they work.
29 |
30 | - Read and then run the the batch file samples\run_pmd.bat to give the rules a quick test run.
31 |
32 | - Contribute to the project!
33 |
34 |
35 | Preparing JSP Files for Scanning
36 | --------------------------------
37 | Official PMD documentation states that PMD only supports JSP files that are XHTML-compliant (i.e. JSP Documents / XML syntax). Refer to http://pmd.sourceforge.net/jspsupport.html for additional information on this limitation.
38 |
39 | A workaround to this limitation is leveraging JSP pre-compilation using JSP compiler (Jasper) features. Jasper converts JSP files into Java files (.java) and also creates a mapping (i.e. a .smap file) for each .java and .jsp file set. The GDS Secure Coding Ruleset was designed to leverage this functionality. PMD configured with the ruleset can be run against the Java files and when a violation is identified, the .smap file is used to map the violation in the .java file to the .jsp file. The JSP developer can then focus remediation efforts on the JSP file.
40 |
41 | Example 1 below is a snippet from apache.org of the recommended jasper2 ANT configuration for pre-compiling JSP files. Example 2 is updated with additional configuration to generate the .java and .smap files need by the GDS Secure Coding Ruleset.
42 |
43 | Example 1 - from "http://tomcat.apache.org/tomcat-6.0-doc/jasper-howto.html#Web_Application_Compilation"
44 |
45 |
50 |
51 | Example 2 - the smapSuppressed, smapDumped, and compile options should be configured as shown below in order to scan JSP files with the GDS Secure Coding Ruleset.
52 |
53 |
61 |
62 | After the pre-compilation is completed, the outputDir will contain a .java, .class, and .smap file for each JSP file in uriroot. The outputDir should be included as a source code directory to be scanned by PMD with the GDS Secure Coding Ruleset. Additionally, outputDir should be added to the PMD CLASSPATH.
63 |
64 |
65 | Running PMDTask with the GDS Secure Coding Ruleset
66 | -------------------------------------------------
67 | This section assumes you have already read and followed the directions in the official PMD documentation for "Ant task usage" (http://pmd.sourceforge.net/ant-task.html) as well as the section in this README called "Preparing JSP Files for Scanning". The following is provided to further assist with configuring PMDTask to scan application source code with the GDS Secure Coding Ruleset.
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 | ..snip..
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 | Miscellaneous Notes
109 | ------------------
110 | - Unfortunately, the official PMD Eclipse plugin only supports XPath rules out of box. Therefore, GDS Secure Coding Ruleset is not officially supported in Eclipse at this time.
111 |
112 | GDS PMD Secure Coding Ruleset is released under the Reciprocal Public License 1.5 (RPL1.5) http://www.opensource.org/licenses/rpl1.5
113 | Copyright (c) 2012 Gotham Digital Science, LLC -- All Rights Reserved
--------------------------------------------------------------------------------
/Securing Development with PMD - Teaching an Old Dog New Tricks - 20120402.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/Securing Development with PMD - Teaching an Old Dog New Tricks - 20120402.pdf
--------------------------------------------------------------------------------
/lib/pmd-gds-1.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/lib/pmd-gds-1.0.jar
--------------------------------------------------------------------------------
/rulesets/GDS/OWASP/A1 - Injection.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 | This file is part of the GDS PMD Secure Coding Ruleset.
10 |
11 | This ruleset contains rules that are intended to detect Injection flaws (SQLi, XMLi, LDAPi, etc).
12 |
13 |
14 |
15 |
16 | This rule utilizes the PMD data flow analysis (DFA) layer to help trace input from source to sink. PMD is unable to track data flow from source to sink across files. Therefore, the scope of analysis is limited to a single file and even within that a single method (i.e. PMD DFA is intraprocedural).
17 |
18 | Specifically, it is configured with sinks that might suggest a potential SQL Injection vulnerability. Additional sinks should be added for increased coverage.
19 |
20 |
21 | 1
22 |
23 |
24 |
25 | java.sql.Statement.executeQuery|
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 | This rule identifies expressions that appear to be SQL statements concatenated with objects of type java.lang.String or potentially other dangerous types that could potentially expose the application to SQL Injection. When evaluating the violation, the concatenated expression(s) must be manually reviewed for user-controllable input. If the type is likely to contain/return tainted data (such as javax.servlet.http.HttpServletRequest) these can be configured via the insecureTypes property.
34 |
35 | Concatenation is identified by inspecting the AST for AdditiveExpression nodes. The pattern used to identify SQL statements is configured with the standardsqlregex and customsqlregex properties. The customsqlregex property allows for detection of custom SQL statements, such as application stored procedures and functions.
36 |
37 | This rule was implemented to help identify potential SQL Injection because PMD is unable to track data flow from source to sink across files.
38 |
39 |
40 | 3
41 |
42 |
43 |
44 | select.+from.+(where)?|insert.+into|update.+set|delete.+(from|where)
45 |
46 |
47 |
48 |
49 |
50 | javax.servlet.http.HttpServletRequest|
51 |
52 |
53 |
54 | java.lang.Long|java.lang.Integer|java.lang.Short|java.lang.Byte|java.lang.Double|java.lang.Float|java.math.BigInteger|java.math.BigDecimal
55 |
56 |
57 |
58 |
59 |
60 |
61 |
--------------------------------------------------------------------------------
/rulesets/GDS/OWASP/A10 - Unvalidated Redirects and Forwards.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 | This file is part of the GDS PMD Secure Coding Ruleset.
10 |
11 | This ruleset contains rules that are intended to detect Unvalidated Redirects and Forwards.
12 |
13 |
14 |
15 |
16 | This rule utilizes the PMD data flow analysis (DFA) layer to help trace input from source to sink. PMD is unable to track data flow from source to sink across files. Therefore, the scope of analysis is limited to a single file and even within that a single method (i.e. PMD DFA is intraprocedural).
17 |
18 | Specifically, it is configured with sinks that might suggest a potential URL Redirection vulnerability. Additional sinks should be added for increased coverage.
19 |
20 |
21 | 1
22 |
23 |
24 |
25 | javax.servlet.http.HttpServletResponse.sendRedirect
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/rulesets/GDS/OWASP/A2 - Cross-Site Scripting.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 | This file is part of the GDS PMD Secure Coding Ruleset.
10 |
11 | This ruleset contains rules that are intended to detect Cross-Site Scripting.
12 |
13 |
14 |
15 |
16 | This rule utilizes the PMD data flow analysis (DFA) layer to help trace input from source to sink. PMD is unable to track data flow from source to sink across files. Therefore, the scope of analysis is limited to a single file and even within that a single method (i.e. PMD DFA is intraprocedural).
17 |
18 | Specifically, it is configured with sinks that might suggest a potential Cross-Site Scripting vulnerability. Additional sinks should be added for increased coverage.
19 |
20 |
21 | 1
22 |
23 |
24 |
25 | javax.servlet.jsp.JspWriter.print|java.io.PrintWriter.print
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/rulesets/GDS/OWASP/A7 - Insecure Cryptographic Storage.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 | This file is part of the GDS PMD Secure Coding Ruleset.
10 |
11 | This ruleset contains rules that are intended to detect Insecure Cryptographic Storage weaknesses.
12 |
13 |
14 |
15 |
16 | This rule is intended to identify instances of weak cryptographic algorithms. Violations should be manually reviewed and in most cases the algorithm should be replaced with a stronger alternative. Additional algorithms should be added for increased coverage.
17 |
18 |
19 |
20 |
21 |
22 |
26 |
27 |
28 |
29 | 3
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/rulesets/GDS/OWASP/A8 - Failure to Restrict URL Access.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 | This file is part of the GDS PMD Secure Coding Ruleset.
10 |
11 | This ruleset contains rules that are intended to detect authorization weaknesses.
12 |
13 |
14 |
15 |
16 | This rule is intended to be a proof-of-concept example of how to identify missing or inadequate authorization functions in a class of a specific type. Specifically, it looks for the the method isUserInRole within classes that extended HttpServlet. For this rule to be useful, it should be customized with authorization functions and types specific to the application being scanned.
17 |
18 |
19 |
20 |
21 |
24 |
25 |
26 |
27 | 3
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/rulesets/GDS/SecureCodingRuleset.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 | This file is part of the GDS PMD Secure Coding Ruleset.
10 |
11 | This file should be used to enable/disable specific rulesets under rulesets/GDS/OWASP.
12 |
13 | Each referenced ruleset listed below is intended to match up with the OWASP TOP 10.
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 | javax.servlet.http.HttpServletRequest.getParameter|javax.servlet.http.HttpServletRequest.getHeader
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/samples/gds/WebContent/WEB-INF/classes/org/apache/jsp/test/XSS/XSS1_jsp.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/samples/gds/WebContent/WEB-INF/classes/org/apache/jsp/test/XSS/XSS1_jsp.class
--------------------------------------------------------------------------------
/samples/gds/WebContent/WEB-INF/classes/org/apache/jsp/test/XSS/XSS1_jsp.class.smap:
--------------------------------------------------------------------------------
1 | SMAP
2 | XSS1_jsp.java
3 | JSP
4 | *S JSP
5 | *F
6 | + 0 XSS1.jsp
7 | test/XSS/XSS1.jsp
8 | *L
9 | 1,10:53,0
10 | 10:54
11 | 11,3:55,0
12 | *E
13 |
--------------------------------------------------------------------------------
/samples/gds/WebContent/WEB-INF/classes/org/apache/jsp/test/XSS/XSS1_jsp.java:
--------------------------------------------------------------------------------
1 | package org.apache.jsp.test.XSS;
2 |
3 | import javax.servlet.*;
4 | import javax.servlet.http.*;
5 | import javax.servlet.jsp.*;
6 |
7 | public final class XSS1_jsp extends org.apache.jasper.runtime.HttpJspBase
8 | implements org.apache.jasper.runtime.JspSourceDependent {
9 |
10 | private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
11 |
12 | private static java.util.List _jspx_dependants;
13 |
14 | private javax.el.ExpressionFactory _el_expressionfactory;
15 | private org.apache.AnnotationProcessor _jsp_annotationprocessor;
16 |
17 | public Object getDependants() {
18 | return _jspx_dependants;
19 | }
20 |
21 | public void _jspInit() {
22 | _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
23 | _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
24 | }
25 |
26 | public void _jspDestroy() {
27 | }
28 |
29 | public void _jspService(HttpServletRequest request, HttpServletResponse response)
30 | throws java.io.IOException, ServletException {
31 |
32 | PageContext pageContext = null;
33 | HttpSession session = null;
34 | ServletContext application = null;
35 | ServletConfig config = null;
36 | JspWriter out = null;
37 | Object page = this;
38 | JspWriter _jspx_out = null;
39 | PageContext _jspx_page_context = null;
40 |
41 |
42 | try {
43 | response.setContentType("text/html; charset=ISO-8859-1");
44 | pageContext = _jspxFactory.getPageContext(this, request, response,
45 | null, true, 8192, true);
46 | _jspx_page_context = pageContext;
47 | application = pageContext.getServletContext();
48 | config = pageContext.getServletConfig();
49 | session = pageContext.getSession();
50 | out = pageContext.getOut();
51 | _jspx_out = out;
52 |
53 | out.write("\r\n\r\n\r\n
\r\n\r\nInsert title here\r\n\r\n\r\n\r\n");
54 | out.print( request.getParameter("a1"));
55 | out.write("\r\n\r\n\r\n");
56 | } catch (Throwable t) {
57 | if (!(t instanceof SkipPageException)){
58 | out = _jspx_out;
59 | if (out != null && out.getBufferSize() != 0)
60 | try { out.clearBuffer(); } catch (java.io.IOException e) {}
61 | if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
62 | }
63 | } finally {
64 | _jspxFactory.releasePageContext(_jspx_page_context);
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/samples/gds/WebContent/WEB-INF/classes/org/apache/jsp/test/XSS/XSS2_jsp.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/samples/gds/WebContent/WEB-INF/classes/org/apache/jsp/test/XSS/XSS2_jsp.class
--------------------------------------------------------------------------------
/samples/gds/WebContent/WEB-INF/classes/org/apache/jsp/test/XSS/XSS2_jsp.class.smap:
--------------------------------------------------------------------------------
1 | SMAP
2 | XSS2_jsp.java
3 | JSP
4 | *S JSP
5 | *F
6 | + 0 XSS2.jsp
7 | test/XSS/XSS2.jsp
8 | + 1 XSS2Include.jsp
9 | test/XSS/../include/XSS2Include.jsp
10 | *L
11 | 2,10:58,0
12 | 1#1,3:59,0
13 | 3:60
14 | 11#0,3:61,0
15 | 13:62
16 | 14,3:63,0
17 | *E
18 |
--------------------------------------------------------------------------------
/samples/gds/WebContent/WEB-INF/classes/org/apache/jsp/test/XSS/XSS2_jsp.java:
--------------------------------------------------------------------------------
1 | package org.apache.jsp.test.XSS;
2 |
3 | import javax.servlet.*;
4 | import javax.servlet.http.*;
5 | import javax.servlet.jsp.*;
6 |
7 | public final class XSS2_jsp extends org.apache.jasper.runtime.HttpJspBase
8 | implements org.apache.jasper.runtime.JspSourceDependent {
9 |
10 | private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
11 |
12 | private static java.util.List _jspx_dependants;
13 |
14 | static {
15 | _jspx_dependants = new java.util.ArrayList(1);
16 | _jspx_dependants.add("/test/XSS/../include/XSS2Include.jsp");
17 | }
18 |
19 | private javax.el.ExpressionFactory _el_expressionfactory;
20 | private org.apache.AnnotationProcessor _jsp_annotationprocessor;
21 |
22 | public Object getDependants() {
23 | return _jspx_dependants;
24 | }
25 |
26 | public void _jspInit() {
27 | _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
28 | _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
29 | }
30 |
31 | public void _jspDestroy() {
32 | }
33 |
34 | public void _jspService(HttpServletRequest request, HttpServletResponse response)
35 | throws java.io.IOException, ServletException {
36 |
37 | PageContext pageContext = null;
38 | HttpSession session = null;
39 | ServletContext application = null;
40 | ServletConfig config = null;
41 | JspWriter out = null;
42 | Object page = this;
43 | JspWriter _jspx_out = null;
44 | PageContext _jspx_page_context = null;
45 |
46 |
47 | try {
48 | response.setContentType("text/html; charset=ISO-8859-1");
49 | pageContext = _jspxFactory.getPageContext(this, request, response,
50 | null, true, 8192, true);
51 | _jspx_page_context = pageContext;
52 | application = pageContext.getServletContext();
53 | config = pageContext.getServletConfig();
54 | session = pageContext.getSession();
55 | out = pageContext.getOut();
56 | _jspx_out = out;
57 |
58 | out.write("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n");
59 | out.write("\r\n\r\n");
60 | String inputStr = request.getParameter("a1");
61 | out.write("\r\n\r\n");
62 | out.print(inputStr );
63 | out.write("\r\n\r\n\r\n");
64 | } catch (Throwable t) {
65 | if (!(t instanceof SkipPageException)){
66 | out = _jspx_out;
67 | if (out != null && out.getBufferSize() != 0)
68 | try { out.clearBuffer(); } catch (java.io.IOException e) {}
69 | if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
70 | }
71 | } finally {
72 | _jspxFactory.releasePageContext(_jspx_page_context);
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/samples/gds/WebContent/WEB-INF/classes/org/apache/jsp/test/include/XSS2Include_jsp.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/samples/gds/WebContent/WEB-INF/classes/org/apache/jsp/test/include/XSS2Include_jsp.class
--------------------------------------------------------------------------------
/samples/gds/WebContent/WEB-INF/classes/org/apache/jsp/test/include/XSS2Include_jsp.class.smap:
--------------------------------------------------------------------------------
1 | SMAP
2 | XSS2Include_jsp.java
3 | JSP
4 | *S JSP
5 | *F
6 | + 0 XSS2Include.jsp
7 | test/include/XSS2Include.jsp
8 | *L
9 | 1,3:53,0
10 | 3:54
11 | *E
12 |
--------------------------------------------------------------------------------
/samples/gds/WebContent/WEB-INF/classes/org/apache/jsp/test/include/XSS2Include_jsp.java:
--------------------------------------------------------------------------------
1 | package org.apache.jsp.test.include;
2 |
3 | import javax.servlet.*;
4 | import javax.servlet.http.*;
5 | import javax.servlet.jsp.*;
6 |
7 | public final class XSS2Include_jsp extends org.apache.jasper.runtime.HttpJspBase
8 | implements org.apache.jasper.runtime.JspSourceDependent {
9 |
10 | private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
11 |
12 | private static java.util.List _jspx_dependants;
13 |
14 | private javax.el.ExpressionFactory _el_expressionfactory;
15 | private org.apache.AnnotationProcessor _jsp_annotationprocessor;
16 |
17 | public Object getDependants() {
18 | return _jspx_dependants;
19 | }
20 |
21 | public void _jspInit() {
22 | _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
23 | _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
24 | }
25 |
26 | public void _jspDestroy() {
27 | }
28 |
29 | public void _jspService(HttpServletRequest request, HttpServletResponse response)
30 | throws java.io.IOException, ServletException {
31 |
32 | PageContext pageContext = null;
33 | HttpSession session = null;
34 | ServletContext application = null;
35 | ServletConfig config = null;
36 | JspWriter out = null;
37 | Object page = this;
38 | JspWriter _jspx_out = null;
39 | PageContext _jspx_page_context = null;
40 |
41 |
42 | try {
43 | response.setContentType("text/html; charset=ISO-8859-1");
44 | pageContext = _jspxFactory.getPageContext(this, request, response,
45 | null, true, 8192, true);
46 | _jspx_page_context = pageContext;
47 | application = pageContext.getServletContext();
48 | config = pageContext.getServletConfig();
49 | session = pageContext.getSession();
50 | out = pageContext.getOut();
51 | _jspx_out = out;
52 |
53 | out.write("\r\n\r\n");
54 | String inputStr = request.getParameter("a1");
55 | } catch (Throwable t) {
56 | if (!(t instanceof SkipPageException)){
57 | out = _jspx_out;
58 | if (out != null && out.getBufferSize() != 0)
59 | try { out.clearBuffer(); } catch (java.io.IOException e) {}
60 | if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
61 | }
62 | } finally {
63 | _jspxFactory.releasePageContext(_jspx_page_context);
64 | }
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/samples/gds/WebContent/WEB-INF/classes/test/com/gdssecurity/pmd/webapp/servlet/TestRedirectServlet.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/samples/gds/WebContent/WEB-INF/classes/test/com/gdssecurity/pmd/webapp/servlet/TestRedirectServlet.class
--------------------------------------------------------------------------------
/samples/gds/WebContent/WEB-INF/classes/test/com/gdssecurity/pmd/webapp/servlet/TestSqliServlet.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/samples/gds/WebContent/WEB-INF/classes/test/com/gdssecurity/pmd/webapp/servlet/TestSqliServlet.class
--------------------------------------------------------------------------------
/samples/gds/WebContent/WEB-INF/classes/test/com/gdssecurity/pmd/webapp/servlet/TestXSSServlet.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/samples/gds/WebContent/WEB-INF/classes/test/com/gdssecurity/pmd/webapp/servlet/TestXSSServlet.class
--------------------------------------------------------------------------------
/samples/gds/WebContent/WEB-INF/classes/test/com/gdssecurity/pmd/webapp/servlet/authz/TestRoleAuthZServlet.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/samples/gds/WebContent/WEB-INF/classes/test/com/gdssecurity/pmd/webapp/servlet/authz/TestRoleAuthZServlet.class
--------------------------------------------------------------------------------
/samples/gds/WebContent/WEB-INF/generated_web.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 | org.apache.jsp.test.XSS.XSS1_jsp
10 | org.apache.jsp.test.XSS.XSS1_jsp
11 |
12 |
13 |
14 | org.apache.jsp.test.XSS.XSS2_jsp
15 | org.apache.jsp.test.XSS.XSS2_jsp
16 |
17 |
18 |
19 | org.apache.jsp.test.include.XSS2Include_jsp
20 | org.apache.jsp.test.include.XSS2Include_jsp
21 |
22 |
23 |
24 | org.apache.jsp.test.XSS.XSS1_jsp
25 | /test/XSS/XSS1.jsp
26 |
27 |
28 |
29 | org.apache.jsp.test.XSS.XSS2_jsp
30 | /test/XSS/XSS2.jsp
31 |
32 |
33 |
34 | org.apache.jsp.test.include.XSS2Include_jsp
35 | /test/include/XSS2Include.jsp
36 |
37 |
38 |
43 |
--------------------------------------------------------------------------------
/samples/gds/WebContent/test/XSS/XSS1.jsp:
--------------------------------------------------------------------------------
1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
2 |
3 |
4 |
5 |
6 | Insert title here
7 |
8 |
9 |
10 | <%= request.getParameter("a1")%>
11 |
12 |
13 |
--------------------------------------------------------------------------------
/samples/gds/WebContent/test/XSS/XSS2.jsp:
--------------------------------------------------------------------------------
1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
2 | pageEncoding="ISO-8859-1"%>
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 | <%@ include file="../include/XSS2Include.jsp"%>
12 |
13 | <%=inputStr %>
14 |
15 |
16 |
--------------------------------------------------------------------------------
/samples/gds/WebContent/test/include/XSS2Include.jsp:
--------------------------------------------------------------------------------
1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
2 |
3 | <% String inputStr = request.getParameter("a1");%>
--------------------------------------------------------------------------------
/samples/gds/src/test/com/gdssecurity/pmd/webapp/servlet/TestRedirectServlet.java:
--------------------------------------------------------------------------------
1 | package test.com.gdssecurity.pmd.webapp.servlet;
2 |
3 | import java.io.IOException;
4 |
5 | import javax.servlet.ServletException;
6 | import javax.servlet.http.HttpServlet;
7 | import javax.servlet.http.HttpServletRequest;
8 | import javax.servlet.http.HttpServletResponse;
9 |
10 | public class TestRedirectServlet extends HttpServlet {
11 |
12 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
13 | {
14 | String url = request.getParameter("url");
15 | response.sendRedirect(url);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/samples/gds/src/test/com/gdssecurity/pmd/webapp/servlet/TestSqliServlet.java:
--------------------------------------------------------------------------------
1 | package test.com.gdssecurity.pmd.webapp.servlet;
2 |
3 | import java.io.*;
4 | import java.sql.*;
5 | import javax.servlet.*;
6 | import javax.servlet.http.*;
7 |
8 | public class TestSqliServlet extends HttpServlet {
9 |
10 | public void doGet(HttpServletRequest request, HttpServletResponse response)
11 | throws ServletException, IOException {
12 | Connection con = null;
13 | Statement stmt = null;
14 | ResultSet rs = null;
15 |
16 | response.setContentType("text/html");
17 | PrintWriter out = response.getWriter( );
18 |
19 | String id = request.getParameter("id");
20 |
21 | try {
22 |
23 | Class.forName("oracle.jdbc.driver.OracleDriver");
24 |
25 | con = DriverManager.getConnection(
26 | "jdbc:oracle:thin:@dbhost:1521:ORCL", "user", "passwd");
27 |
28 | String strSql = "SELECT * FROM USERS WHERE ID = '" + id + "'";
29 |
30 | stmt = con.createStatement( );
31 |
32 | rs = stmt.executeQuery(strSql);
33 |
34 | out.println("SqlInjectionExample");
35 | out.println("");
36 | while(rs.next( )) {
37 | out.println(rs.getString("firstname") + " " + rs.getString("lastname"));
38 | }
39 | out.println("");
40 | }
41 | catch(ClassNotFoundException e) {
42 | out.println("Couldn't load database driver: " + e.getMessage( ));
43 | }
44 | catch(SQLException e) {
45 | out.println("SQLException caught: " + e.getMessage( ));
46 | }
47 | finally {
48 |
49 | try {
50 | if (con != null) con.close( );
51 | }
52 | catch (SQLException ignored) { }
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/samples/gds/src/test/com/gdssecurity/pmd/webapp/servlet/TestXSSServlet.java:
--------------------------------------------------------------------------------
1 | package test.com.gdssecurity.pmd.webapp.servlet;
2 |
3 | import java.io.IOException;
4 | import java.io.PrintWriter;
5 |
6 | import javax.servlet.ServletException;
7 | import javax.servlet.http.HttpServlet;
8 | import javax.servlet.http.HttpServletRequest;
9 | import javax.servlet.http.HttpServletResponse;
10 | import javax.servlet.http.HttpSession;
11 |
12 | public class TestXSSServlet extends HttpServlet {
13 |
14 | /**
15 | * Variable declaration (v1) and initialization with tainted source of input
16 | * Second variable declared (w1) and assigned tainted variable (v1)
17 | * Tainted variable w1 passed to XSS sink
18 | * This pattern creates XSS vulnerability
19 | *
20 | */
21 |
22 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
23 |
24 | PrintWriter pw = response.getWriter();
25 |
26 | String v1 = request.getParameter("p1");
27 |
28 | String w1 = v1;
29 |
30 | pw.print(w1);
31 |
32 | }
33 |
34 |
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/samples/gds/src/test/com/gdssecurity/pmd/webapp/servlet/authz/TestRoleAuthZServlet.java:
--------------------------------------------------------------------------------
1 | package test.com.gdssecurity.pmd.webapp.servlet.authz;
2 |
3 | import java.io.IOException;
4 |
5 | import javax.servlet.ServletException;
6 | import javax.servlet.http.*;
7 |
8 | public class TestRoleAuthZServlet extends HttpServlet {
9 |
10 | /**
11 | *
12 | */
13 | private static final long serialVersionUID = 1L;
14 |
15 | public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
16 |
17 | if (req.isUserInRole("admin")) { // role-based authorization check
18 | // Do admin stuff
19 | } else {
20 | // Access denied
21 | }
22 |
23 | }
24 |
25 | public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
26 |
27 | req.isUserInRole("admin"); // inadequate role-based authorization check
28 | // Do admin stuff
29 |
30 | }
31 |
32 | public void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
33 |
34 | // missing role-based authorization check
35 | // Do admin stuff
36 |
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/samples/juliet-2010-12/LICENSE:
--------------------------------------------------------------------------------
1 | This software is not subject to copyright protection and is in the public domain. NIST assumes no responsibility whatsoever for its use by other parties, and makes no guaranties, expressed or implied, about its quality, reliability, or any other characteristic.
2 |
--------------------------------------------------------------------------------
/samples/juliet-2010-12/antbuild/testcases/CWE327_Use_Broken_Crypto/CWE327_Use_Broken_Crypto__basic_01.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/samples/juliet-2010-12/antbuild/testcases/CWE327_Use_Broken_Crypto/CWE327_Use_Broken_Crypto__basic_01.class
--------------------------------------------------------------------------------
/samples/juliet-2010-12/antbuild/testcases/CWE328_Reversible_One_Way_Hash/CWE328_Reversible_One_Way_Hash__basic_01.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/samples/juliet-2010-12/antbuild/testcases/CWE328_Reversible_One_Way_Hash/CWE328_Reversible_One_Way_Hash__basic_01.class
--------------------------------------------------------------------------------
/samples/juliet-2010-12/antbuild/testcasesupport/AbstractTestCase.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/samples/juliet-2010-12/antbuild/testcasesupport/AbstractTestCase.class
--------------------------------------------------------------------------------
/samples/juliet-2010-12/antbuild/testcasesupport/AbstractTestCaseClassIssueBad.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/samples/juliet-2010-12/antbuild/testcasesupport/AbstractTestCaseClassIssueBad.class
--------------------------------------------------------------------------------
/samples/juliet-2010-12/antbuild/testcasesupport/AbstractTestCaseClassIssueGood.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/samples/juliet-2010-12/antbuild/testcasesupport/AbstractTestCaseClassIssueGood.class
--------------------------------------------------------------------------------
/samples/juliet-2010-12/antbuild/testcasesupport/AbstractTestCaseServlet.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/samples/juliet-2010-12/antbuild/testcasesupport/AbstractTestCaseServlet.class
--------------------------------------------------------------------------------
/samples/juliet-2010-12/antbuild/testcasesupport/IO.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/samples/juliet-2010-12/antbuild/testcasesupport/IO.class
--------------------------------------------------------------------------------
/samples/juliet-2010-12/antbuild/testcasesupport/Main.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/samples/juliet-2010-12/antbuild/testcasesupport/Main.class
--------------------------------------------------------------------------------
/samples/juliet-2010-12/antbuild/testcasesupport/ServletMain.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDSSecurity/GDS-PMD-Security-Rules/326611b48c15c1ba791cd1f68527c39b101dd5f6/samples/juliet-2010-12/antbuild/testcasesupport/ServletMain.class
--------------------------------------------------------------------------------
/samples/juliet-2010-12/src/testcases/CWE327_Use_Broken_Crypto/CWE327_Use_Broken_Crypto__basic_01.java:
--------------------------------------------------------------------------------
1 | /* TEMPLATE GENERATED TESTCASE FILE
2 | Filename: CWE327_Use_Broken_Crypto__basic_01.java
3 | Label Definition File: CWE327_Use_Broken_Crypto__basic.label.xml
4 | Template File: point-flaw-01.tmpl.java
5 | */
6 | /*
7 | * @description
8 | * CWE: 327 Use of Broken or Risky Cryptographic Algorithm
9 | * Sinks:
10 | * GoodSink: use AES
11 | * BadSink : use DES
12 | * Flow Variant: 01 Baseline
13 | *
14 | * */
15 |
16 | package testcases.CWE327_Use_Broken_Crypto;
17 |
18 | import testcasesupport.*;
19 |
20 | import javax.servlet.http.*;
21 | import java.io.*;
22 | import javax.crypto.Cipher;
23 | import javax.crypto.KeyGenerator;
24 | import javax.crypto.SecretKey;
25 |
26 | public class CWE327_Use_Broken_Crypto__basic_01 extends AbstractTestCase
27 | {
28 |
29 | public void bad() throws Throwable
30 | {
31 |
32 | java.util.logging.Logger log_bsnk = java.util.logging.Logger.getLogger("local-logger");
33 |
34 | IO.writeLine("Enter string for encryption: ");
35 |
36 | BufferedReader bufread2 = null;
37 | InputStreamReader inread2 = null;
38 | try
39 | {
40 | inread2 = new InputStreamReader(System.in);
41 | bufread2 = new BufferedReader(inread2);
42 | String str = bufread2.readLine();
43 |
44 | /* FLAW: Insecure cryptographic algorithm (DES) */
45 | Cipher des = Cipher.getInstance("DES");
46 | SecretKey key = KeyGenerator.getInstance("DES").generateKey();
47 | des.init(Cipher.ENCRYPT_MODE, key);
48 |
49 | byte[] enc_str = des.doFinal(str.getBytes());
50 |
51 | IO.writeLine(IO.toHex(enc_str));
52 | }
53 | catch(IOException e)
54 | {
55 | log_bsnk.warning("Error reading from console");
56 | }
57 | finally
58 | {
59 | try
60 | {
61 | if( bufread2 != null )
62 | {
63 | bufread2.close();
64 | }
65 | }
66 | catch( IOException e )
67 | {
68 | log_bsnk.warning("Error closing bufread2");
69 | }
70 | finally
71 | {
72 | try
73 | {
74 | if( inread2 != null )
75 | {
76 | inread2.close();
77 | }
78 | }
79 | catch( IOException e )
80 | {
81 | log_bsnk.warning("Error closing inread2");
82 | }
83 | }
84 | }
85 |
86 | }
87 |
88 | public void good() throws Throwable
89 | {
90 | good1();
91 | }
92 |
93 | private void good1() throws Throwable
94 | {
95 |
96 | java.util.logging.Logger log_gsnk = java.util.logging.Logger.getLogger("local-logger");
97 |
98 | IO.writeLine("Enter string for encryption: ");
99 |
100 | BufferedReader bufread2 = null;
101 | InputStreamReader inread2 = null;
102 | try
103 | {
104 | inread2 = new InputStreamReader(System.in);
105 | bufread2 = new BufferedReader(inread2);
106 | String str = bufread2.readLine();
107 |
108 | /* FIX: Secure cryptographic algorithm (AES) */
109 | Cipher aes = Cipher.getInstance("AES");
110 | KeyGenerator kg = KeyGenerator.getInstance("AES");
111 | kg.init(128);
112 | SecretKey key = kg.generateKey();
113 | aes.init(Cipher.ENCRYPT_MODE, key);
114 |
115 | byte[] enc_str = aes.doFinal(str.getBytes());
116 |
117 | IO.writeLine(IO.toHex(enc_str));
118 | }
119 | catch(IOException e)
120 | {
121 | log_gsnk.warning("Error reading from console");
122 | }
123 | finally
124 | {
125 | try
126 | {
127 | if( bufread2 != null )
128 | {
129 | bufread2.close();
130 | }
131 | }
132 | catch( IOException e )
133 | {
134 | log_gsnk.warning("Error closing bufread2");
135 | }
136 | finally
137 | {
138 | try
139 | {
140 | if( inread2 != null )
141 | {
142 | inread2.close();
143 | }
144 | }
145 | catch( IOException e )
146 | {
147 | log_gsnk.warning("Error closing inread2");
148 | }
149 | }
150 | }
151 |
152 | }
153 |
154 | /* Below is the main(). It is only used when building this testcase on
155 | its own for testing or for building a binary to use in testing binary
156 | analysis tools. It is not used when compiling all the testcases as one
157 | application, which is how source code analysis tools are tested. */
158 | public static void main(String[] args) throws ClassNotFoundException,
159 | InstantiationException, IllegalAccessException
160 | {
161 | mainFromParent(args);
162 | }
163 | }
164 |
165 |
--------------------------------------------------------------------------------
/samples/juliet-2010-12/src/testcases/CWE328_Reversible_One_Way_Hash/CWE328_Reversible_One_Way_Hash__basic_01.java:
--------------------------------------------------------------------------------
1 | /* TEMPLATE GENERATED TESTCASE FILE
2 | Filename: CWE328_Reversible_One_Way_Hash__basic_01.java
3 | Label Definition File: CWE328_Reversible_One_Way_Hash__basic.label.xml
4 | Template File: point-flaw-01.tmpl.java
5 | */
6 | /*
7 | * @description
8 | * CWE: 328 Bad case uses insecure cryptographic hashing algorithm (MD5). Good case uses secure cryptographic hashing algorithm (SHA-512).
9 | * Sinks:
10 | * GoodSink: sha512
11 | * BadSink : md5
12 | * Flow Variant: 01 Baseline
13 | *
14 | * */
15 |
16 | package testcases.CWE328_Reversible_One_Way_Hash;
17 |
18 | import testcasesupport.*;
19 |
20 | import java.security.GeneralSecurityException;
21 | import java.security.MessageDigest;
22 |
23 | public class CWE328_Reversible_One_Way_Hash__basic_01 extends AbstractTestCase
24 | {
25 |
26 | public void bad() throws Throwable
27 | {
28 |
29 | String input = "Test Input";
30 |
31 | /* FLAW: Insecure cryptographic hashing algorithm (MD5) */
32 | MessageDigest hash = MessageDigest.getInstance("MD5");
33 | byte[] hashv = hash.digest(input.getBytes()); /* INCIDENTAL FLAW: Hard-coded input to hash algorithm */
34 |
35 | IO.writeLine(IO.toHex(hashv));
36 |
37 | }
38 |
39 | public void good() throws Throwable
40 | {
41 | good1();
42 | }
43 |
44 | private void good1() throws Throwable
45 | {
46 |
47 | String input = "Test Input";
48 |
49 | /* FIX: Secure cryptographic hashing algorithm (SHA-512) */
50 | MessageDigest hash = MessageDigest.getInstance("SHA-512");
51 | byte[] hashv = hash.digest(input.getBytes()); /* INCIDENTAL FLAW: Hard-coded input to hash algorithm */
52 |
53 | IO.writeLine(IO.toHex(hashv));
54 |
55 | }
56 |
57 | /* Below is the main(). It is only used when building this testcase on
58 | its own for testing or for building a binary to use in testing binary
59 | analysis tools. It is not used when compiling all the testcases as one
60 | application, which is how source code analysis tools are tested. */
61 | public static void main(String[] args) throws ClassNotFoundException,
62 | InstantiationException, IllegalAccessException
63 | {
64 | mainFromParent(args);
65 | }
66 | }
67 |
68 |
--------------------------------------------------------------------------------
/samples/run_pmd.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 |
3 | set PMD_HOME=H:\Demo\PMD\pmd-bin-4.2.5\pmd-4.2.5
4 | set CATALINA_HOME=C:\tomcat\apache-tomcat-6.0.29
5 | set CLASSPATH=%CLASSPATH%;..\lib\pmd-gds-1.0.jar;%CATALINA_HOME%\lib\*;gds\WebContent\WEB-INF\classes;juliet-2010-12\antbuild
6 |
7 | set JSP_SRC_PATH=gds\WebContent\WEB-INF\classes
8 | set JAVA_SRC_PATH=gds\src
9 | set JULIET_SRC_PATH=juliet-2010-12\src
10 |
11 | %PMD_HOME%\bin\pmd.bat -targetjdk 1.6 -reportfile report.html %JSP_SRC_PATH%,%JAVA_SRC_PATH%,%JULIET_SRC_PATH% html "rulesets/GDS/SecureCodingRuleset.xml"
12 |
13 |
14 | rem # File Line Problem
15 | rem 1 \samples\gds\WebContent\test/XSS/XSS1.jsp 10 Cross-Site Scripting (Reflected)
16 | rem 2 \samples\gds\WebContent\test/XSS/XSS2.jsp 13 Cross-Site Scripting (Reflected)
17 | rem 3 \samples\gds\src\test\com\gdssecurity\pmd\webapp\servlet\TestRedirectServlet.java 15 Unvalidated Redirect
18 | rem 4 \samples\gds\src\test\com\gdssecurity\pmd\webapp\servlet\TestSqliServlet.java 28 id of type java.lang.String concatenated to SQL string creating a possible SQL Injection vulnerability. Additional information: Check whether id contains tainted data.
19 | rem 5 \samples\gds\src\test\com\gdssecurity\pmd\webapp\servlet\TestSqliServlet.java 32 Sql Injection
20 | rem 6 \samples\gds\src\test\com\gdssecurity\pmd\webapp\servlet\TestXSSServlet.java 30 Cross-Site Scripting (Reflected)
21 | rem 7 \samples\gds\src\test\com\gdssecurity\pmd\webapp\servlet\authz\TestRoleAuthZServlet.java 25 Missing Or Incorrect Authorization
22 | rem 8 \samples\gds\src\test\com\gdssecurity\pmd\webapp\servlet\authz\TestRoleAuthZServlet.java 32 Missing Or Incorrect Authorization
23 | rem 9 \samples\juliet-2010-12\src\testcases\CWE327_Use_Broken_Crypto\CWE327_Use_Broken_Crypto__basic_01.java 45 Insecure Cryptographic Algorithm
24 | rem 10 \samples\juliet-2010-12\src\testcases\CWE328_Reversible_One_Way_Hash\CWE328_Reversible_One_Way_Hash__basic_01.java 32 Insecure Cryptographic Algorithm
25 |
26 |
--------------------------------------------------------------------------------
/src/com/gdssecurity/pmd/SecurityRuleViolation.java:
--------------------------------------------------------------------------------
1 | /*
2 | * This code is licensed under the Reciprocal Public License 1.5 (RPL1.5)http://www.opensource.org/licenses/rpl1.5
3 | *
4 | * Copyright (c) 2012 Gotham Digital Science, LLC -- All Rights Reserved
5 | *
6 | */
7 |
8 |
9 | package com.gdssecurity.pmd;
10 |
11 |
12 | import java.io.File;
13 | import java.util.ArrayList;
14 | import java.util.Comparator;
15 | import java.util.List;
16 |
17 | import com.gdssecurity.pmd.smap.SmapFileReader;
18 | import com.gdssecurity.pmd.smap.SmapResolver;
19 |
20 | import net.sourceforge.pmd.IRuleViolation;
21 | import net.sourceforge.pmd.Rule;
22 | import net.sourceforge.pmd.RuleContext;
23 | import net.sourceforge.pmd.RuleViolation;
24 | import net.sourceforge.pmd.ast.ASTClassOrInterfaceBodyDeclaration;
25 | import net.sourceforge.pmd.ast.ASTClassOrInterfaceDeclaration;
26 | import net.sourceforge.pmd.ast.ASTCompilationUnit;
27 | import net.sourceforge.pmd.ast.ASTFieldDeclaration;
28 | import net.sourceforge.pmd.ast.ASTFormalParameter;
29 | import net.sourceforge.pmd.ast.ASTLocalVariableDeclaration;
30 | import net.sourceforge.pmd.ast.ASTMethodDeclaration;
31 | import net.sourceforge.pmd.ast.ASTTypeDeclaration;
32 | import net.sourceforge.pmd.ast.ASTVariableDeclaratorId;
33 | import net.sourceforge.pmd.ast.CanSuppressWarnings;
34 | import net.sourceforge.pmd.ast.SimpleNode;
35 |
36 |
37 | public class SecurityRuleViolation implements Comparator, IRuleViolation {
38 |
39 | private Rule rule;
40 | private String description;
41 | private String fileName;
42 |
43 | private String className;
44 | private String methodName;
45 | private String variableName;
46 | private String type;
47 | private String packageName;
48 | private int beginLine;
49 | private int endLine;
50 |
51 | private int beginColumn;
52 | private int endColumn;
53 | private boolean isSuppressed;
54 |
55 | private String javaFileName;
56 | private int javaBeginLine;
57 | private int javaEndLine;
58 |
59 | public int compare(IRuleViolation r1, IRuleViolation r2) {
60 | if (!r1.getFilename().equals(r2.getFilename())) {
61 | return r1.getFilename().compareTo(r2.getFilename());
62 | }
63 |
64 | if (r1.getBeginLine() != r2.getBeginLine()) {
65 | return r1.getBeginLine() - r2.getBeginLine();
66 | }
67 |
68 | if (r1.getDescription() != null && r2.getDescription() != null
69 | && !r1.getDescription().equals(r2.getDescription())) {
70 | return r1.getDescription().compareTo(r2.getDescription());
71 | }
72 |
73 | if (r1.getBeginLine() == r2.getBeginLine()) {
74 | return 1;
75 | }
76 |
77 | return r1.getBeginLine() - r2.getBeginLine();
78 | }
79 |
80 | public SecurityRuleViolation(Rule rule, RuleContext ctx, SimpleNode node, String specificMsg, String variable, String type) {
81 |
82 | this.rule = rule;
83 | this.javaFileName = ctx.getSourceCodeFilename();
84 | this.variableName = variable;
85 | this.type = type;
86 |
87 | if (node != null) {
88 | if (node.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class)
89 | == null) {
90 |
91 | className = "";
92 | } else {
93 |
94 | className = node.getScope().getEnclosingClassScope().getClassName()
95 | == null
96 | ? ""
97 | : node.getScope().getEnclosingClassScope().getClassName();
98 | }
99 |
100 | String qualifiedName = null;
101 | List parents = node.getParentsOfType(
102 | ASTClassOrInterfaceDeclaration.class);
103 |
104 | for (ASTClassOrInterfaceDeclaration parent : parents) {
105 | if (qualifiedName == null) {
106 | qualifiedName = parent.getScope().getEnclosingClassScope().getClassName();
107 | } else {
108 | qualifiedName = parent.getScope().getEnclosingClassScope().getClassName()
109 | + "$" + qualifiedName;
110 | }
111 | }
112 |
113 | if (!"net.sourceforge.pmd.symboltable.SourceFileScope".equals(
114 | node.getScope().getClass().getName())) {
115 | className = node.getScope().getEnclosingClassScope().getClassName()
116 | == null
117 | ? ""
118 | : qualifiedName;
119 | }
120 |
121 | methodName = node.getFirstParentOfType(ASTMethodDeclaration.class)
122 | == null
123 | ? ""
124 | : node.getScope().getEnclosingMethodScope().getName();
125 |
126 | packageName = node.getScope().getEnclosingSourceFileScope().getPackageName()
127 | == null
128 | ? ""
129 | : node.getScope().getEnclosingSourceFileScope().getPackageName();
130 |
131 | javaBeginLine = node.getBeginLine();
132 | javaEndLine = node.getEndLine();
133 |
134 | if (this.javaFileName.indexOf("WEB-INF") > 0) {
135 | int webRootDirPos = this.javaFileName.indexOf("WEB-INF");
136 | String webRootDirName = this.javaFileName.substring(0,
137 | webRootDirPos);
138 |
139 | int dot = this.javaFileName.lastIndexOf(".");
140 | String smapFileName = this.javaFileName.substring(0, dot)
141 | + ".class.smap";
142 | SmapFileReader r = new SmapFileReader(new File(smapFileName));
143 | SmapResolver resolver = new SmapResolver(r);
144 |
145 | fileName = webRootDirName
146 | + resolver.getJspFileName(javaBeginLine, 0);
147 | beginLine = resolver.unmangle(javaBeginLine, 0);
148 | endLine = resolver.unmangle(javaEndLine, 0);
149 | } else {
150 | fileName = javaFileName;
151 | beginLine = javaBeginLine;
152 | endLine = javaEndLine;
153 | }
154 |
155 | if (specificMsg == "") {
156 | this.description = "No message for rule violation. Code snippet: "
157 | + Utils.getCodeSnippet(fileName, beginLine, endLine);
158 | } else {
159 | this.description = specificMsg;
160 | }
161 |
162 | List parentTypes = new ArrayList(
163 | node.getParentsOfType(ASTTypeDeclaration.class));
164 |
165 | if (node instanceof ASTTypeDeclaration) {
166 | parentTypes.add(node);
167 | }
168 | parentTypes.addAll(
169 | node.getParentsOfType(
170 | ASTClassOrInterfaceBodyDeclaration.class));
171 | if (node instanceof ASTClassOrInterfaceBodyDeclaration) {
172 | parentTypes.add(node);
173 | }
174 | parentTypes.addAll(node.getParentsOfType(ASTFormalParameter.class));
175 | if (node instanceof ASTFormalParameter) {
176 | parentTypes.add(node);
177 | }
178 | parentTypes.addAll(
179 | node.getParentsOfType(ASTLocalVariableDeclaration.class));
180 | if (node instanceof ASTLocalVariableDeclaration) {
181 | parentTypes.add(node);
182 | }
183 | if (node instanceof ASTCompilationUnit) {
184 | for (int i = 0; i < node.jjtGetNumChildren(); i++) {
185 | SimpleNode n = (SimpleNode) node.jjtGetChild(i);
186 |
187 | if (n instanceof ASTTypeDeclaration) {
188 | parentTypes.add(n);
189 | }
190 | }
191 | }
192 | for (SimpleNode parentType : parentTypes) {
193 | CanSuppressWarnings t = (CanSuppressWarnings) parentType;
194 |
195 | if (t.hasSuppressWarningsAnnotationFor(getRule())) {
196 | isSuppressed = true;
197 | }
198 | }
199 | } else {
200 | className = "";
201 | methodName = "";
202 | packageName = "";
203 | fileName = "";
204 | }
205 | }
206 |
207 | public Rule getRule() {
208 | return rule;
209 | }
210 |
211 | public boolean isSuppressed() {
212 | return this.isSuppressed;
213 | }
214 |
215 | public int getBeginColumn() {
216 | return beginColumn;
217 | }
218 |
219 | public int getEndColumn() {
220 | return endColumn;
221 | }
222 |
223 | public String getDescription() {
224 | return description;
225 | }
226 |
227 | public String getFilename() {
228 | return fileName;
229 | }
230 |
231 | public String getClassName() {
232 | return className;
233 | }
234 |
235 | public String getMethodName() {
236 | return methodName;
237 | }
238 |
239 | public String getPackageName() {
240 | return packageName;
241 | }
242 |
243 | public int getBeginLine() {
244 | return beginLine;
245 | }
246 |
247 | public int getEndLine() {
248 | return endLine;
249 | }
250 |
251 | public String getVariableName() {
252 | return variableName;
253 | }
254 |
255 | @Override
256 | public String toString() {
257 | return getFilename() + ":" + getRule() + ":" + getDescription() + ":"
258 | + beginLine;
259 | }
260 |
261 | public int getJavaBeginLine() {
262 | return javaBeginLine;
263 | }
264 |
265 | public int getJavaEndLine() {
266 | return javaEndLine;
267 | }
268 |
269 | public String getJavaFileName() {
270 | return javaFileName;
271 | }
272 |
273 | public String getType() {
274 | return type;
275 | }
276 | }
277 |
--------------------------------------------------------------------------------
/src/com/gdssecurity/pmd/Utils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * This code is licensed under the Reciprocal Public License 1.5 (RPL1.5)http://www.opensource.org/licenses/rpl1.5
3 | *
4 | * Copyright (c) 2012 Gotham Digital Science, LLC -- All Rights Reserved
5 | *
6 | */
7 |
8 |
9 | package com.gdssecurity.pmd;
10 |
11 |
12 | import java.io.BufferedReader;
13 | import java.io.File;
14 | import java.io.FileNotFoundException;
15 | import java.io.FileReader;
16 | import java.io.IOException;
17 | import java.util.HashSet;
18 | import java.util.logging.Level;
19 | import java.util.logging.Logger;
20 |
21 | import net.sourceforge.pmd.RuleContext;
22 | import net.sourceforge.pmd.ast.ASTClassOrInterfaceType;
23 | import net.sourceforge.pmd.ast.ASTExpression;
24 | import net.sourceforge.pmd.ast.ASTName;
25 | import net.sourceforge.pmd.ast.ASTPrimaryExpression;
26 | import net.sourceforge.pmd.ast.SimpleNode;
27 |
28 |
29 | public class Utils {
30 |
31 | private static final Logger LOG = Logger.getLogger(
32 | "com.gdssecurity.pmd.rules");
33 |
34 | public static String getCodeSnippet(String fileName, int start, int end) {
35 | StringBuffer sb = new StringBuffer();
36 | BufferedReader br = null;
37 |
38 | try {
39 | br = new BufferedReader(new FileReader(new File(fileName)));
40 | int lintCtr = 1;
41 |
42 | for (String s = null; (s = br.readLine()) != null;) {
43 | if (lintCtr >= start && lintCtr <= end) {
44 | sb.append(s);
45 | }
46 | lintCtr++;
47 | }
48 | } catch (FileNotFoundException fnfe) {
49 | LOG.warning(
50 | "Unable to find the file " + fileName
51 | + ". Ensure PMD short file names option is disabled.");
52 | } catch (IOException ioe) {
53 | LOG.warning(
54 | "Unexpected error while retrieving code snippet from "
55 | + fileName + " " + ioe.getStackTrace().toString());
56 | }
57 |
58 | return sb.toString();
59 | }
60 |
61 | public static String getType(SimpleNode node, RuleContext rc, String method) {
62 | String methodMsg = "Utils::getType - {0}";
63 |
64 | String cannonicalName = "";
65 | Class type = null;
66 |
67 | try {
68 | if (node instanceof ASTExpression) {
69 |
70 | type = node.getFirstChildOfType(ASTPrimaryExpression.class).getFirstChildOfType(ASTName.class).getType();
71 | } else if (node instanceof ASTPrimaryExpression) {
72 | if (node.containsChildOfType(ASTClassOrInterfaceType.class)) {
73 |
74 | type = node.getFirstChildOfType(ASTClassOrInterfaceType.class).getType();
75 | } else {
76 |
77 | type = node.getFirstChildOfType(ASTName.class).getType();
78 | }
79 | } else if (node instanceof ASTName) {
80 | type = ((ASTName) node).getType();
81 | }
82 |
83 | cannonicalName = type.getCanonicalName();
84 | } catch (Exception ex1) {
85 |
86 | LOG.log(Level.INFO, methodMsg,
87 | "Unable to get type for " + method + " at "
88 | + rc.getSourceCodeFilename() + " (" + node.getBeginLine()
89 | + ")");
90 | cannonicalName = "UNKNOWN_TYPE";
91 | }
92 |
93 | return cannonicalName;
94 | }
95 |
96 | public static HashSet arrayAsHashSet(String[] array) {
97 | HashSet hashSet = new HashSet(array.length);
98 | int nbItem = 0;
99 |
100 | while (nbItem < array.length) {
101 | String str = array[nbItem++];
102 |
103 | hashSet.add(str);
104 | }
105 | return hashSet;
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/src/com/gdssecurity/pmd/rules/BaseSecurityRule.java:
--------------------------------------------------------------------------------
1 | /*
2 | * This code is licensed under the Reciprocal Public License 1.5 (RPL1.5)http://www.opensource.org/licenses/rpl1.5
3 | *
4 | * Copyright (c) 2012 Gotham Digital Science, LLC -- All Rights Reserved
5 | *
6 | */
7 |
8 |
9 | package com.gdssecurity.pmd.rules;
10 |
11 |
12 | import java.io.IOException;
13 | import java.util.HashSet;
14 | import java.util.Iterator;
15 | import java.util.List;
16 | import java.util.logging.FileHandler;
17 | import java.util.logging.Level;
18 | import java.util.logging.Logger;
19 | import java.util.logging.SimpleFormatter;
20 |
21 | import com.gdssecurity.pmd.SecurityRuleViolation;
22 | import com.gdssecurity.pmd.Utils;
23 |
24 | import net.sourceforge.pmd.IRuleViolation;
25 | import net.sourceforge.pmd.AbstractJavaRule;
26 | import net.sourceforge.pmd.PropertyDescriptor;
27 | import net.sourceforge.pmd.Report;
28 | import net.sourceforge.pmd.Rule;
29 | import net.sourceforge.pmd.RuleContext;
30 | import net.sourceforge.pmd.ast.SimpleNode;
31 | import net.sourceforge.pmd.properties.StringProperty;
32 |
33 |
34 | public class BaseSecurityRule extends AbstractJavaRule {
35 | private static final Logger LOG = Logger.getLogger(
36 | "com.gdssecurity.pmd.rules");
37 | private static FileHandler fileHandler;
38 |
39 | private static HashSet sources = new HashSet();
40 | private static PropertyDescriptor sourceDescriptor = new StringProperty(
41 | "sources", "",
42 | new String[] {
43 | "javax.servlet.http.HttpServletRequest.getParameter" }, 1.0f, '|');
44 |
45 | protected HashSet getDefaultSources() {
46 | return sources;
47 | }
48 |
49 | public void start(RuleContext ctx) {
50 | String methodMsg = "AbstractSecurityRule::start";
51 |
52 | LOG.fine(methodMsg);
53 | if (sources.size() < 1) {
54 | sources = Utils.arrayAsHashSet(getStringProperties(sourceDescriptor));
55 | }
56 | }
57 |
58 | public void apply(List list, RuleContext rulecontext) {
59 | String methodMsg = "AbstractSecurityRule::apply";
60 |
61 | LOG.fine(methodMsg);
62 | super.apply(list, rulecontext);
63 | }
64 |
65 | public static Logger getLogger() {
66 |
67 | if (LOG.getLevel() == null) {
68 | LOG.setLevel(Level.OFF);
69 | }
70 |
71 | if (!LOG.getLevel().equals(Level.OFF)) {
72 | try {
73 | if (fileHandler == null) {
74 | LOG.setUseParentHandlers(false);
75 | fileHandler = new FileHandler("PMD.GDS.log");
76 | fileHandler.setFormatter(new SimpleFormatter());
77 | LOG.addHandler(fileHandler);
78 | }
79 | } catch (SecurityException e) {
80 |
81 | e.printStackTrace();
82 | } catch (IOException e) {
83 |
84 | e.printStackTrace();
85 | }
86 | }
87 |
88 | return LOG;
89 | }
90 |
91 | protected final void addSecurityViolation(Rule rule, RuleContext ctx, SimpleNode simpleNode, String message, String variableName, String type) {
92 | Report rpt = ctx.getReport();
93 |
94 | boolean isNewSecurityViolation = true;
95 |
96 | if (rpt.getViolationTree().size() > 0) {
97 | for (Iterator i = rpt.iterator(); i.hasNext();) {
98 | IRuleViolation ruleViolation = i.next();
99 |
100 | if (ruleViolation instanceof SecurityRuleViolation) {
101 | SecurityRuleViolation secRuleViolation = (SecurityRuleViolation) ruleViolation;
102 |
103 | if (rule.getName() == secRuleViolation.getRule().getName()
104 | && ctx.getSourceCodeFilename()
105 | == secRuleViolation.getJavaFileName()
106 | && simpleNode.getBeginLine()
107 | == secRuleViolation.getJavaBeginLine()
108 | && simpleNode.getEndLine()
109 | == secRuleViolation.getJavaEndLine()) {
110 | isNewSecurityViolation = false;
111 | }
112 | }
113 | }
114 | }
115 |
116 | if (isNewSecurityViolation == true) {
117 | LOG.log(Level.FINE,
118 | "*** Adding security violation to report for rule "
119 | + rule.getName() + " in " + ctx.getSourceCodeFilename()
120 | + " Begin line: " + simpleNode.getBeginLine()
121 | + " End line: " + simpleNode.getEndLine()
122 | + " Violation message: " + message);
123 | rpt.addRuleViolation(
124 | new SecurityRuleViolation(rule, ctx, simpleNode, message,
125 | variableName, type));
126 |
127 | } else {
128 | LOG.log(Level.FINE,
129 | "*** Duplicate security violation in report for rule "
130 | + rule.getName() + " in " + ctx.getSourceCodeFilename()
131 | + " Begin line: " + simpleNode.getBeginLine()
132 | + " End line: " + simpleNode.getEndLine()
133 | + " Violation will not be added to report");
134 | }
135 | }
136 |
137 | }
138 |
--------------------------------------------------------------------------------
/src/com/gdssecurity/pmd/rules/SqlStringConcatentation.java:
--------------------------------------------------------------------------------
1 | /*
2 | * This code is licensed under the Reciprocal Public License 1.5 (RPL1.5)http://www.opensource.org/licenses/rpl1.5
3 | *
4 | * Copyright (c) 2012 Gotham Digital Science, LLC -- All Rights Reserved
5 | *
6 | */
7 |
8 |
9 | package com.gdssecurity.pmd.rules;
10 |
11 |
12 | import java.text.MessageFormat;
13 | import java.util.*;
14 | import java.util.logging.Logger;
15 | import java.util.regex.Pattern;
16 |
17 | import com.gdssecurity.pmd.Utils;
18 |
19 | import net.sourceforge.pmd.PropertyDescriptor;
20 | import net.sourceforge.pmd.RuleContext;
21 | import net.sourceforge.pmd.ast.ASTAdditiveExpression;
22 | import net.sourceforge.pmd.ast.ASTName;
23 | import net.sourceforge.pmd.properties.StringProperty;
24 | import net.sourceforge.pmd.rules.regex.RegexHelper;
25 | import net.sourceforge.pmd.symboltable.NameOccurrence;
26 |
27 |
28 | public class SqlStringConcatentation extends BaseSecurityRule {
29 |
30 | private static final Logger LOG = getLogger();
31 | private static final PropertyDescriptor standardSqlRegexDescriptor = new StringProperty(
32 | "standardsqlregex",
33 | "regular expression for detecting standard SQL statements",
34 | "undefined", 1.0F);
35 | private static final PropertyDescriptor customSqlRegexDescriptor = new StringProperty(
36 | "customsqlregex",
37 | "regular expression for detecting custom SQL, such as stored procedures and functions",
38 | "undefined", 1.0F);
39 | private static final PropertyDescriptor insecureTypesDescriptor = new StringProperty(
40 | "insecureTypes",
41 | "types that could create a potential SQLi exposure when concatenated to a SQL statement",
42 | new String[] { "\"java.lang.String\"" }, 1.0f, '|');
43 |
44 | // Ignoring Numeric types by default
45 | private static final PropertyDescriptor safeTypesDescriptor = new StringProperty(
46 | "safeTypes",
47 | "types that may be considered safe to ignore.",
48 | new String[] { "\"java.lang.Integer\"" }, 1.0f, '|');
49 |
50 | private static Pattern standardSqlRegex = null;
51 | private static Pattern customSqlRegex = null;
52 | private static HashSet insecureTypes = null;
53 | private static HashSet safeTypes = null;
54 |
55 | protected void init() {
56 | if (standardSqlRegex == null) {
57 | standardSqlRegex = Pattern.compile(
58 | getStringProperty(standardSqlRegexDescriptor), Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
59 | }
60 |
61 | if (customSqlRegex == null) {
62 | customSqlRegex = Pattern.compile(
63 | getStringProperty(customSqlRegexDescriptor), Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
64 | }
65 |
66 | if (insecureTypes == null) {
67 | insecureTypes = Utils.arrayAsHashSet(
68 | getStringProperties(insecureTypesDescriptor));
69 | }
70 |
71 | if (safeTypes == null) {
72 | safeTypes = Utils.arrayAsHashSet(
73 | getStringProperties(safeTypesDescriptor));
74 | }
75 | }
76 |
77 | public void apply(List list, RuleContext rulecontext) {
78 | LOG.finest("Analyzing file " + rulecontext.getSourceCodeFilename());
79 | init();
80 | super.apply(list, rulecontext);
81 | }
82 |
83 | public Object visit(ASTAdditiveExpression astAdditiveExpression, Object obj) {
84 | RuleContext rc = (RuleContext) obj;
85 | int beginLine = astAdditiveExpression.getBeginLine();
86 | int endLine = astAdditiveExpression.getEndLine();
87 | String codeSnippet = Utils.getCodeSnippet(rc.getSourceCodeFilename(),
88 | beginLine, endLine);
89 | boolean match = false;
90 |
91 | if (codeSnippet != null && standardSqlRegex != null
92 | && RegexHelper.isMatch(standardSqlRegex, codeSnippet)) {
93 | match = true;
94 | LOG.finest(
95 | "SQL regex match on line(s) " + beginLine + "-" + endLine
96 | + " with pattern " + standardSqlRegex.toString());
97 | } else if (codeSnippet != null && customSqlRegex != null
98 | && RegexHelper.isMatch(customSqlRegex, codeSnippet)) {
99 | match = true;
100 | LOG.finest(
101 | "SQL regex match on line(s) " + beginLine + "-" + endLine
102 | + " with pattern " + customSqlRegex.toString());
103 | }
104 |
105 | if (match) {
106 | List concatentatedVars = (ArrayList) astAdditiveExpression.findChildrenOfType(
107 | ASTName.class);
108 |
109 | if (concatentatedVars != null) {
110 | Iterator iterator = concatentatedVars.iterator();
111 |
112 | while (iterator.hasNext()) {
113 | ASTName astName = iterator.next();
114 | String varName = astName.getImage();
115 | String varType = Utils.getType(astName, rc, varName);
116 |
117 | if (varType.indexOf("java.lang.String") != -1) {
118 | NameOccurrence n = new NameOccurrence(astName,
119 | astName.getImage());
120 |
121 | if (astAdditiveExpression.getScope().getEnclosingMethodScope().contains(
122 | n)) {
123 | addSecurityViolation(this, rc, astAdditiveExpression,
124 | MessageFormat.format(getMessage(),
125 | new Object[] {
126 | varName, "java.lang.String",
127 | varName + " appears to be a method argument"}),
128 | "",
129 | "");
130 | } else {
131 | addSecurityViolation(this, rc, astAdditiveExpression,
132 | MessageFormat.format(getMessage(),
133 | new Object[] {
134 | varName, "java.lang.String",
135 | "Check whether " + varName
136 | + " contains tainted data"}),
137 | "",
138 | "");
139 | }
140 | } else if (insecureTypes.contains(varType)) {
141 | addSecurityViolation(this, rc, astAdditiveExpression,
142 | MessageFormat.format(getMessage(),
143 | new Object[] {
144 | varName, varType,
145 | varType + " is tainted data"}),
146 | "",
147 | "");
148 | } else if (safeTypes.contains(varType)) {
149 | LOG.finest("Ignoring " + varType + " as this was configured as one of the safe types.");
150 | } else {
151 | addSecurityViolation(this, rc, astAdditiveExpression,
152 | MessageFormat.format(getMessage(),
153 | new Object[] {
154 | varName, varType,
155 | "Check whether " + varType
156 | + " contains tainted data"}),
157 | "",
158 | "");
159 | }
160 | }
161 | } else {
162 | LOG.finest("Concatenation of SQL strings detected. This does not appear to introduce a potential SQL Injection vulnerability; however, consider a parameterized command and moving the SQL into a stored procedure");
163 | }
164 | }
165 |
166 | return super.visit(astAdditiveExpression, obj);
167 | }
168 |
169 | }
170 |
--------------------------------------------------------------------------------
/src/com/gdssecurity/pmd/rules/dfa/DfaSecurityRule.java:
--------------------------------------------------------------------------------
1 | /*
2 | * This code is licensed under the Reciprocal Public License 1.5 (RPL1.5)http://www.opensource.org/licenses/rpl1.5
3 | *
4 | * Copyright (c) 2012 Gotham Digital Science, LLC -- All Rights Reserved
5 | *
6 | */
7 |
8 |
9 | package com.gdssecurity.pmd.rules.dfa;
10 |
11 |
12 | import java.util.ArrayList;
13 | import java.util.HashSet;
14 | import java.util.Iterator;
15 | import java.util.LinkedList;
16 | import java.util.List;
17 | import java.util.logging.Level;
18 | import java.util.logging.Logger;
19 |
20 | import net.sourceforge.pmd.PropertyDescriptor;
21 | import net.sourceforge.pmd.RuleContext;
22 | import net.sourceforge.pmd.ast.ASTAdditiveExpression;
23 | import net.sourceforge.pmd.ast.ASTArgumentList;
24 | import net.sourceforge.pmd.ast.ASTArguments;
25 | import net.sourceforge.pmd.ast.ASTAssignmentOperator;
26 | import net.sourceforge.pmd.ast.ASTClassOrInterfaceDeclaration;
27 | import net.sourceforge.pmd.ast.ASTClassOrInterfaceType;
28 | import net.sourceforge.pmd.ast.ASTConditionalExpression;
29 | import net.sourceforge.pmd.ast.ASTExpression;
30 | import net.sourceforge.pmd.ast.ASTMethodDeclaration;
31 | import net.sourceforge.pmd.ast.ASTName;
32 | import net.sourceforge.pmd.ast.ASTPrimaryExpression;
33 | import net.sourceforge.pmd.ast.ASTReturnStatement;
34 | import net.sourceforge.pmd.ast.ASTStatementExpression;
35 | import net.sourceforge.pmd.ast.ASTThrowStatement;
36 | import net.sourceforge.pmd.ast.ASTVariableDeclarator;
37 | import net.sourceforge.pmd.ast.SimpleNode;
38 | import net.sourceforge.pmd.dfa.IDataFlowNode;
39 | import net.sourceforge.pmd.dfa.pathfinder.CurrentPath;
40 | import net.sourceforge.pmd.dfa.pathfinder.DAAPathFinder;
41 | import net.sourceforge.pmd.dfa.pathfinder.Executable;
42 | import net.sourceforge.pmd.dfa.variableaccess.VariableAccess;
43 | import net.sourceforge.pmd.properties.StringProperty;
44 |
45 | import org.jaxen.JaxenException;
46 |
47 | import com.gdssecurity.pmd.Utils;
48 | import com.gdssecurity.pmd.rules.BaseSecurityRule;
49 |
50 |
51 | public class DfaSecurityRule extends BaseSecurityRule
52 | implements Executable {
53 | private static final Logger LOG = getLogger();
54 |
55 | private LinkedList currentPathTaintedVariables;
56 |
57 | private static HashSet sources = new HashSet();
58 |
59 | private PropertyDescriptor sourceDescriptor = new StringProperty("sources",
60 | "",
61 | new String[] {
62 | "javax.servlet.http.HttpServletRequest.getParameter" }, 1.0f, '|');
63 |
64 | private HashSet sinks;
65 |
66 | private PropertyDescriptor sinkDescriptor = new StringProperty("sinks", "",
67 | new String[] { "" }, 1.0f, '|');
68 |
69 | private RuleContext rc;
70 | private int methodDataFlowCount;
71 | private String methodName = "";
72 | private int methodNumOfDataFlows;
73 |
74 | private List additionalDataFlowNodes = new ArrayList();
75 |
76 | private static final int MAX_DATAFLOWS = 10;
77 |
78 | public void start(RuleContext ctx) {
79 | String methodMsg = "DfaSecurityRule::start";
80 |
81 | LOG.fine(methodMsg);
82 | if (sources.size() < 1) {
83 | sources = getDefaultSources();
84 | }
85 | }
86 |
87 | public void apply(List list, RuleContext rulecontext) {
88 | String methodMsg = "DfaSecurityRule::apply";
89 |
90 | LOG.fine(methodMsg);
91 |
92 | if (sources.size() < 1) {
93 | sources = Utils.arrayAsHashSet(
94 | getStringProperties(this.sourceDescriptor));
95 | LOG.warning(
96 | "Unable to get sources from BaseSecurityRule. Defaulting to sources hard-coded in "
97 | + this.getClass().getName()
98 | + " or in the rule XML for " + this.getName() + ": "
99 | + sources.toString());
100 | }
101 | sinks = Utils.arrayAsHashSet(getStringProperties(sinkDescriptor));
102 | super.apply(list, rulecontext);
103 | }
104 |
105 | private boolean isSource(String type, String variable) {
106 | String methodMsg = "DfaSecurityRule::isTaintedSource - {0}";
107 |
108 | LOG.log(Level.FINE, methodMsg, type + "." + variable);
109 |
110 | return sources.contains(type + "." + variable) ? true : false;
111 |
112 | }
113 |
114 | private boolean isTaintedVariable(String variable) {
115 | String methodMsg = "DfaSecurityRule::isTaintedVariable - {0}";
116 |
117 | LOG.log(Level.FINE, methodMsg, variable);
118 |
119 | return currentPathTaintedVariables.contains(variable) ? true : false;
120 | }
121 |
122 | public Object visit(ASTMethodDeclaration astMethodDeclaration, Object data) {
123 | String methodMsg = "DfaSecurityRule::visit(ASTMethodDeclaration) - {0}";
124 |
125 | String visitedClass = astMethodDeclaration.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class).getImage();
126 | String visitedMethod = astMethodDeclaration.getMethodName();
127 |
128 | LOG.log(Level.FINE, methodMsg,
129 | "ENTRY " + visitedClass + "." + visitedMethod);
130 |
131 | rc = (RuleContext) data;
132 |
133 | try {
134 |
135 | List returnStatements = astMethodDeclaration.findChildNodesWithXPath(
136 | "./Block/BlockStatement/" + "/TryStatement/CatchStatement/"
137 | + "/ReturnStatement");
138 |
139 | if (returnStatements != null && returnStatements.size() > 0) {
140 | for (int i = 0; i
141 | < astMethodDeclaration.getDataFlowNode().getFlow().size(); i++) {
142 |
143 | for (int j = 0; j < returnStatements.size(); j++) {
144 | if (((IDataFlowNode) astMethodDeclaration.getDataFlowNode().getFlow().get(i)).equals(
145 | returnStatements.get(j).getDataFlowNode())) {
146 | additionalDataFlowNodes.add(
147 | astMethodDeclaration.getDataFlowNode().getFlow().get(
148 | i + 1));
149 | } else {
150 | LOG.log(Level.FINE, methodMsg,
151 | "Unexpected condition when checking for ReturnStatement nodes");
152 | }
153 | }
154 | }
155 | }
156 |
157 | List throwStatements = astMethodDeclaration.findChildNodesWithXPath(
158 | "./Block/BlockStatement/" + "/TryStatement/CatchStatement/"
159 | + "/ThrowStatement");
160 |
161 | if (throwStatements != null && throwStatements.size() > 0) {
162 | for (int i = 0; i
163 | < astMethodDeclaration.getDataFlowNode().getFlow().size(); i++) {
164 |
165 | for (int j = 0; j < throwStatements.size(); j++) {
166 | if (((IDataFlowNode) astMethodDeclaration.getDataFlowNode().getFlow().get(i)).equals(
167 | throwStatements.get(j).getDataFlowNode())) {
168 | additionalDataFlowNodes.add(
169 | astMethodDeclaration.getDataFlowNode().getFlow().get(
170 | i + 1));
171 | } else {
172 | LOG.log(Level.FINE, methodMsg,
173 | "Unexpected condition when checking for ThrowStatement nodes");
174 | }
175 | }
176 | }
177 | }
178 | } catch (JaxenException e) {
179 | LOG.log(Level.WARNING, methodMsg,
180 | "Unexpected error when running Xpath query against AST - "
181 | + e.getMessage());
182 | }
183 |
184 | IDataFlowNode rootDataFlowNode = (IDataFlowNode) astMethodDeclaration.getDataFlowNode().getFlow().get(
185 | 0);
186 |
187 | methodName = visitedMethod;
188 | methodDataFlowCount = 0;
189 | methodNumOfDataFlows = rootDataFlowNode.getFlow().size();
190 |
191 | DAAPathFinder daaPathFinder = new DAAPathFinder(rootDataFlowNode, this,
192 | MAX_DATAFLOWS);
193 |
194 | daaPathFinder.run();
195 |
196 | LOG.log(Level.FINE, methodMsg,
197 | "Super.visit() " + visitedClass + "." + visitedMethod);
198 |
199 | super.visit(astMethodDeclaration, data);
200 |
201 | LOG.log(Level.FINE, methodMsg,
202 | "EXIT " + visitedClass + "." + visitedMethod);
203 |
204 | return data;
205 | }
206 |
207 | public void execute(CurrentPath currentPath) {
208 | String methodMsg = "DfaSecurityRule::execute - {0}";
209 |
210 | methodDataFlowCount++;
211 |
212 | LOG.log(Level.FINE, methodMsg, "ENTRY");
213 | LOG.log(Level.FINE, methodMsg,
214 | "Dataflow count for current method: " + methodDataFlowCount);
215 | LOG.log(Level.FINE, methodMsg,
216 | "Path length for current dataflow: " + currentPath.getLength());
217 |
218 | if (methodDataFlowCount < MAX_DATAFLOWS) {
219 | for (Iterator iterator = currentPath.iterator(); iterator.hasNext();) {
220 | IDataFlowNode iDataFlowNode = iterator.next();
221 |
222 | if (iDataFlowNode.getSimpleNode() instanceof ASTMethodDeclaration) {
223 | currentPathTaintedVariables = new LinkedList();
224 | } else if (iDataFlowNode.getSimpleNode() instanceof ASTVariableDeclarator
225 | || iDataFlowNode.getSimpleNode() instanceof ASTStatementExpression) {
226 | handleDataFlowNode(iDataFlowNode);
227 | } else {
228 | LOG.log(Level.FINE, methodMsg,
229 | "Unhandled Node: " + iDataFlowNode.toString());
230 | }
231 |
232 | }
233 |
234 | if (additionalDataFlowNodes.size() > 0) {
235 | IDataFlowNode additionalRootNode = additionalDataFlowNodes.get(0);
236 |
237 | additionalDataFlowNodes.remove(0);
238 | DAAPathFinder daaPathFinder = new DAAPathFinder(
239 | additionalRootNode, this, MAX_DATAFLOWS);
240 |
241 | methodDataFlowCount = 0;
242 |
243 | daaPathFinder.run();
244 | }
245 |
246 | } else {
247 | LOG.log(Level.INFO, methodMsg,
248 | "Maximum number of allowable dataflows " + MAX_DATAFLOWS
249 | + " exceeded for " + methodName + " in "
250 | + rc.getSourceCodeFilename()
251 | + ". Total possible dataflows for method: "
252 | + methodNumOfDataFlows);
253 | }
254 |
255 | LOG.log(Level.FINE, methodMsg, "EXIT");
256 |
257 | }
258 |
259 | private void handleDataFlowNode(IDataFlowNode iDataFlowNode) {
260 |
261 | String methodMsg = "DfaSecurityRule::handleDataFlowNode - {0}";
262 |
263 | LOG.log(Level.FINE, methodMsg, "ENTRY");
264 | LOG.log(Level.FINE, methodMsg, iDataFlowNode.toString());
265 | LOG.log(Level.FINE, methodMsg,
266 | " # of variable access: "
267 | + iDataFlowNode.getVariableAccess().size());
268 |
269 | boolean def = false;
270 | boolean ref = false;
271 | String variableName = "";
272 |
273 | for (int i = 0; i < iDataFlowNode.getVariableAccess().size(); i++) {
274 | if (((VariableAccess) iDataFlowNode.getVariableAccess().get(i)).isDefinition()) {
275 | def = true;
276 | variableName = ((VariableAccess) iDataFlowNode.getVariableAccess().get(i)).getVariableName();
277 | }
278 | if (((VariableAccess) iDataFlowNode.getVariableAccess().get(i)).isReference()) {
279 | ref = true;
280 | }
281 | }
282 |
283 | if (def) {
284 | handleVariableDefinition(iDataFlowNode, variableName);
285 | }
286 |
287 | if (ref && !def) {
288 | handleVariableReference(iDataFlowNode, variableName);
289 | }
290 |
291 | if (!def && !ref) {
292 | LOG.log(Level.FINE, methodMsg, "Unexpected Access Type");
293 | }
294 |
295 | LOG.log(Level.FINE, methodMsg, iDataFlowNode.toString());
296 | LOG.log(Level.FINE, methodMsg, "EXIT");
297 | }
298 |
299 | private void handleVariableReference(IDataFlowNode iDataFlowNode,
300 | String variableName) {
301 |
302 | String methodMsg = "DfaSecurityRule::handleVariableReference - {0}";
303 |
304 | LOG.log(Level.FINE, methodMsg, "ENTRY");
305 | SimpleNode simpleNode = iDataFlowNode.getSimpleNode();
306 |
307 | LOG.log(Level.FINEST, methodMsg, simpleNode.toString());
308 |
309 | if (isMethodCall(simpleNode)) {
310 |
311 | String type = "";
312 | String method = "";
313 |
314 | if (simpleNode.getFirstChildOfType(ASTAssignmentOperator.class)
315 | == null) {
316 | method = getMethod(
317 | simpleNode.getFirstChildOfType(
318 | ASTPrimaryExpression.class));
319 | type = Utils.getType(
320 | simpleNode.getFirstChildOfType(
321 | ASTPrimaryExpression.class),
322 | rc,
323 | method);
324 | } else {
325 |
326 | method = getMethod(
327 | simpleNode.getFirstChildOfType(ASTExpression.class));
328 | type = Utils.getType(
329 | simpleNode.getFirstChildOfType(ASTExpression.class), rc,
330 | method);
331 | }
332 |
333 | LOG.log(Level.FINE, methodMsg,
334 | "type " + type + " invoking method " + method);
335 |
336 | if (isSink(type, method)) {
337 | LOG.finest(
338 | "Checking method " + method + " for tainted arguments");
339 | analyzeMethodArgs(simpleNode);
340 | }
341 |
342 | } else {
343 | LOG.log(Level.FINE, methodMsg,
344 | "Do we need to do any further processing here?");
345 |
346 | }
347 |
348 | LOG.log(Level.FINE, methodMsg, "EXIT");
349 |
350 | }
351 |
352 | private void analyzeMethodArgs(SimpleNode simpleNode) {
353 |
354 | ASTArgumentList argListNode = simpleNode.getFirstChildOfType(
355 | ASTArgumentList.class);
356 | List listOfArgs = new ArrayList();
357 |
358 | listOfArgs.addAll(argListNode.findChildrenOfType(ASTName.class));
359 |
360 | for (Iterator iterator = listOfArgs.iterator(); iterator.hasNext();) {
361 |
362 | ASTName name = iterator.next();
363 |
364 | String argumentName = name.getImage();
365 | String argumentType = "";
366 |
367 | if (argumentName.indexOf('.') != -1) {
368 | argumentName = argumentName.substring(
369 | argumentName.indexOf('.') + 1);
370 | }
371 |
372 | argumentType = Utils.getType(name, rc, argumentName);
373 |
374 | if (isSource(argumentType, argumentName)
375 | || isTaintedVariable(argumentName)) {
376 | addSecurityViolation(this, rc, simpleNode, getMessage(),
377 | argumentName, argumentType);
378 | }
379 | }
380 |
381 | }
382 |
383 | private boolean isSink(String objectType, String objectMethod) {
384 |
385 | String methodMsg = "DfaSecurityRule::isSink - {0}";
386 |
387 | LOG.log(Level.FINE, methodMsg, objectType + "." + objectMethod);
388 |
389 | return sinks.contains(objectType + "." + objectMethod) ? true : false;
390 | }
391 |
392 | private boolean isMethodCall(SimpleNode node) {
393 |
394 | String methodMsg = "DfaSecurityRule::isMethodCall";
395 |
396 | LOG.log(Level.FINE, methodMsg);
397 |
398 | ASTArguments arguments = node.getFirstChildOfType(ASTArguments.class);
399 |
400 | return (arguments != null) ? true : false;
401 | }
402 |
403 | private void handleVariableDefinition(IDataFlowNode iDataFlowNode,
404 | String variable) {
405 |
406 | String methodMsg = "DfaSecurityRule::handleVariableDefinition - {0}";
407 |
408 | LOG.log(Level.FINE, methodMsg, "ENTRY");
409 | SimpleNode simpleNode = iDataFlowNode.getSimpleNode();
410 |
411 | LOG.log(Level.FINEST, methodMsg, simpleNode.toString());
412 |
413 | if (simpleNode.containsChildOfType(ASTConditionalExpression.class)) {
414 | handleConditionalExpression(simpleNode, variable);
415 | } else if (simpleNode.containsChildOfType(ASTExpression.class)) {
416 |
417 | List primaryExpressions = simpleNode.getFirstChildOfType(ASTExpression.class).findChildrenOfType(
418 | ASTPrimaryExpression.class);
419 |
420 | for (int i = 0; i < primaryExpressions.size(); i++) {
421 | if (primaryExpressions.get(i).getFirstChildOfType(ASTName.class)
422 | != null) {
423 | analyzeNode(primaryExpressions.get(i), variable);
424 | }
425 | }
426 | } else {
427 | LOG.log(Level.FINE, methodMsg,
428 | "Unhandled node: " + simpleNode.toString());
429 | }
430 |
431 | LOG.log(Level.FINE, methodMsg, "EXIT");
432 |
433 | }
434 |
435 | private void handleConditionalExpression(SimpleNode node, String variable) {
436 |
437 | SimpleNode ifResult = (ASTExpression) node.getFirstChildOfType(ASTConditionalExpression.class).jjtGetChild(
438 | 1);
439 |
440 | analyzeNode(ifResult, variable);
441 | SimpleNode elseResult = (SimpleNode) node.getFirstChildOfType(ASTConditionalExpression.class).jjtGetChild(
442 | 2);
443 |
444 | if (elseResult instanceof ASTAdditiveExpression) {
445 | List primaryExpressions = elseResult.findChildrenOfType(
446 | ASTPrimaryExpression.class);
447 |
448 | for (Iterator iterator = primaryExpressions.iterator(); iterator.hasNext();) {
449 | analyzeNode(iterator.next(), variable);
450 | }
451 | } else if (elseResult instanceof ASTPrimaryExpression) {
452 | analyzeNode(elseResult, variable);
453 | }
454 |
455 | }
456 |
457 | private void analyzeNode(SimpleNode node, String variable) {
458 |
459 | String methodMsg = "DfaSecurityRule::checkNodeForTaint - {0}";
460 |
461 | LOG.log(Level.FINE, methodMsg, "ENTRY");
462 |
463 | if (isMethodCall(node)) {
464 | String method = getMethod(node);
465 | String type = Utils.getType(node, rc, method);
466 |
467 | LOG.log(Level.FINE, methodMsg,
468 | "Variable " + variable + " initialized with Type: " + type
469 | + " Method: " + method);
470 |
471 | if (isSource(type, method)) {
472 |
473 | LOG.log(Level.FINE, methodMsg,
474 | "Adding " + variable + " to list of taint");
475 | currentPathTaintedVariables.add(variable);
476 | } else if (isSink(type, method)) {
477 | analyzeMethodArgs(node);
478 | } else if (isPassThrough(type, method)) {}
479 | } else {
480 | LOG.log(Level.FINE, methodMsg,
481 | "Initialized with variable or literal");
482 |
483 | List astNames = node.findChildrenOfType(ASTName.class);
484 |
485 | if (astNames.size() > 0) {
486 | analyzeVariable(variable, astNames);
487 | }
488 | }
489 |
490 | LOG.log(Level.FINE, methodMsg, "EXIT");
491 | }
492 |
493 | private String getMethod(SimpleNode node) {
494 |
495 | String method = "";
496 |
497 | if (node.containsChildOfType(ASTClassOrInterfaceType.class)) {
498 | method = node.getFirstChildOfType(ASTClassOrInterfaceType.class).getImage();
499 | } else {
500 | method = node.getFirstChildOfType(ASTName.class).getImage();
501 | }
502 |
503 | if (method.indexOf('.') != -1) {
504 | method = method.substring(method.indexOf('.') + 1);
505 | }
506 |
507 | return method;
508 | }
509 |
510 | private boolean isPassThrough(String type, String method) {
511 |
512 | String methodMsg = "DfaSecurityRule::isPassthroughMethod - {0}";
513 |
514 | LOG.log(Level.FINE, methodMsg, "Not Implemented");
515 |
516 | return false;
517 | }
518 |
519 | private void analyzeVariable(String variableName,
520 | List listOfAstNames) {
521 | String methodMsg = "DfaSecurityRule::checkVariableForTaint - {0}";
522 |
523 | LOG.log(Level.FINE, methodMsg, "ENTRY");
524 |
525 | if (listOfAstNames.size() > 0) {
526 | for (int i = 0; i < listOfAstNames.size(); i++) {
527 | ASTName name = listOfAstNames.get(i);
528 | String var = name.getImage();
529 | String type = Utils.getType(name, rc, var);
530 |
531 | if (var.indexOf('.') != -1) {
532 | var = var.substring(var.indexOf('.') + 1);
533 | }
534 |
535 | LOG.log(Level.FINE, methodMsg,
536 | "Variable " + variableName + " initialized with " + var
537 | + " of type " + type);
538 |
539 | if (isSource(type, var) || isTaintedVariable(var)) {
540 | LOG.log(Level.FINE, methodMsg,
541 | "Adding " + variableName + " to list of taint");
542 | currentPathTaintedVariables.add(variableName);
543 | }
544 | }
545 |
546 | }
547 |
548 | LOG.log(Level.FINE, methodMsg, "EXIT");
549 | }
550 |
551 | }
552 |
--------------------------------------------------------------------------------
/src/com/gdssecurity/pmd/smap/SmapFileReader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * This code is licensed under the Reciprocal Public License 1.5 (RPL1.5)http://www.opensource.org/licenses/rpl1.5
3 | *
4 | * Copyright (c) 2012 Gotham Digital Science, LLC -- All Rights Reserved
5 | *
6 | */
7 |
8 |
9 | package com.gdssecurity.pmd.smap;
10 |
11 |
12 | import java.io.*;
13 |
14 |
15 | public class SmapFileReader implements SmapReader {
16 |
17 | private File file;
18 |
19 | public SmapFileReader(java.io.File file) {
20 | this.file = file;
21 | }
22 |
23 | public String toString() {
24 | if (file != null) {
25 | return file.toString();
26 | }
27 | return null;
28 | }
29 |
30 | public String readSmap() {
31 | if (file != null) {
32 | try {
33 | FileReader fr = new FileReader(file);
34 | LineNumberReader lnr = new LineNumberReader(fr);
35 | String line = "";
36 | String out = "";
37 |
38 | while ((line = lnr.readLine()) != null) {
39 | out = out.concat(line);
40 | out = out.concat("\n");
41 | }
42 | return out;
43 | } catch (FileNotFoundException fne) {
44 | return null;
45 | } catch (IOException ioe) {
46 | return null;
47 | }
48 | }
49 | return null;
50 | }
51 |
52 | }
53 |
54 |
--------------------------------------------------------------------------------
/src/com/gdssecurity/pmd/smap/SmapReader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * This code is licensed under the Reciprocal Public License 1.5 (RPL1.5)http://www.opensource.org/licenses/rpl1.5
3 | *
4 | * Copyright (c) 2012 Gotham Digital Science, LLC -- All Rights Reserved
5 | *
6 | */
7 |
8 |
9 | package com.gdssecurity.pmd.smap;
10 |
11 |
12 | public interface SmapReader {
13 |
14 | public String readSmap();
15 | }
16 |
--------------------------------------------------------------------------------
/src/com/gdssecurity/pmd/smap/SmapResolver.java:
--------------------------------------------------------------------------------
1 | /*
2 | * This code is licensed under the Reciprocal Public License 1.5 (RPL1.5)http://www.opensource.org/licenses/rpl1.5
3 | *
4 | * Copyright (c) 2012 Gotham Digital Science, LLC -- All Rights Reserved
5 | *
6 | */
7 |
8 |
9 | package com.gdssecurity.pmd.smap;
10 |
11 |
12 | import java.util.*;
13 | import java.io.IOException;
14 |
15 |
16 | public class SmapResolver {
17 |
18 | private static final String SMAP_HEADER = "SMAP";
19 |
20 | private static final String DEFAULT_STRATUM = "JSP";
21 |
22 | private static final String STRATUM_SECTION = "*S JSP";
23 |
24 | private static final String LINE_SECTION = "*L";
25 |
26 | private static final String FILE_SECTION = "*F";
27 |
28 | private static final String END_SECTION = "*E";
29 |
30 | private static final String FID_DELIM = "#";
31 |
32 | private SmapReader reader = null;
33 |
34 | private boolean resolved = false;
35 |
36 | private String defaultStratum = null;
37 |
38 | private String outputFileName = null;
39 |
40 | private Hashtable fsection = new Hashtable(3);
41 |
42 | private boolean fsection_sourceNameSourcePath = false;
43 |
44 | private Map jsp2java = new TreeMap();
45 |
46 | private Map java2jsp = new TreeMap();
47 |
48 | public SmapResolver(SmapReader reader) {
49 | this.resolved = resolve(reader.readSmap());
50 | this.reader = reader;
51 | }
52 |
53 | public String toString() {
54 | return reader.toString();
55 | }
56 |
57 | private boolean resolve(String smap) {
58 |
59 | boolean fileSection = false;
60 | boolean lineSection = false;
61 | boolean jspStratumSection = false;
62 |
63 | if (smap == null) {
64 | return false;
65 | }
66 |
67 | StringTokenizer st = new StringTokenizer(smap, "\n", false);
68 |
69 | int counter = 1;
70 | int sectionCounter = 0;
71 |
72 | String fileIndex = null;
73 |
74 | boolean cont = true;
75 |
76 | while (st.hasMoreTokens()) {
77 | String token = st.nextToken();
78 |
79 | if (counter == 1) {
80 | if (!SMAP_HEADER.equals(token)) {
81 | return false;
82 | }
83 | } else if (counter == 2) {
84 | outputFileName = token;
85 | } else if (counter == 3) {
86 | defaultStratum = token;
87 | } else if (STRATUM_SECTION.equals(token)) {
88 | jspStratumSection = true;
89 | } else if (FILE_SECTION.equals(token) && (jspStratumSection)) {
90 | fileSection = true;
91 | sectionCounter = 0;
92 | } else if (LINE_SECTION.equals(token) && (jspStratumSection)) {
93 | fileSection = false;
94 | lineSection = true;
95 | sectionCounter = 0;
96 | fileIndex = "0";
97 | } else if (END_SECTION.equals(token) && (jspStratumSection)) {
98 | cont = false;
99 | lineSection = false;
100 | fileSection = false;
101 | sectionCounter = 0;
102 | }
103 |
104 | if (fileSection) {
105 |
106 | if (sectionCounter != 0) {
107 | storeFile(token);
108 | }
109 | sectionCounter++;
110 | }
111 |
112 | if (lineSection) {
113 | if (sectionCounter != 0) {
114 | int hashPresent = token.indexOf(FID_DELIM);
115 |
116 | if (hashPresent > -1) {
117 | fileIndex = token.substring(hashPresent + 1,
118 | token.indexOf(':'));
119 | if (fileIndex.indexOf(",") != -1) {
120 | fileIndex = fileIndex.substring(0,
121 | fileIndex.indexOf(","));
122 | }
123 | }
124 |
125 | storeLine(token, fileIndex);
126 | }
127 | sectionCounter++;
128 | }
129 | counter++;
130 | }
131 |
132 | this.resolved = sanityCheck();
133 | return this.resolved;
134 | }
135 |
136 | private void storeFile(String token) {
137 |
138 | String sourceName = "";
139 | String sourcePath = "";
140 | String id = "";
141 | boolean sourceNameSourcePath = false;
142 |
143 | if (token.indexOf("+") != -1) {
144 | int firstSpaceIndex = token.indexOf(" ");
145 | int secondSpaceIndex = token.lastIndexOf(" ");
146 |
147 | id = token.substring(firstSpaceIndex + 1, secondSpaceIndex);
148 | sourceName = token.substring(secondSpaceIndex + 1);
149 | sourceNameSourcePath = true;
150 | } else if (fsection_sourceNameSourcePath) {
151 | sourcePath = token;
152 | if (token.lastIndexOf("/") != -1) {
153 | sourceName = sourcePath.substring(token.lastIndexOf("/") + 1,
154 | sourcePath.length());
155 | id = getIndexByFileName(sourceName);
156 | } else {
157 | sourceName = sourcePath;
158 | id = getIndexByFileName(sourceName);
159 | }
160 |
161 | }
162 |
163 | fsection.put(id,
164 | (fsection_sourceNameSourcePath) ? sourcePath : sourceName);
165 |
166 | fsection_sourceNameSourcePath = (sourceNameSourcePath) ? true : false;
167 | }
168 |
169 | private void storeLine(String token, String fileIndex) {
170 | int delimIndex = token.indexOf(":");
171 |
172 | String jspLine = token.substring(0, delimIndex);
173 | String javaLine = token.substring(delimIndex + 1);
174 |
175 | int hashPresent = jspLine.indexOf(FID_DELIM);
176 | int commaPresent = jspLine.indexOf(',');
177 |
178 | int jspIndex = 0;
179 | int repeatCount = 0;
180 |
181 | if (commaPresent != -1) {
182 | repeatCount = Integer.parseInt(jspLine.substring(commaPresent + 1));
183 | if (hashPresent == -1) {
184 | jspIndex = Integer.parseInt(jspLine.substring(0, commaPresent));
185 | } else {
186 | jspIndex = Integer.parseInt(jspLine.substring(0, hashPresent));
187 | }
188 | } else {
189 | if (hashPresent == -1) {
190 | jspIndex = Integer.parseInt(jspLine);
191 | } else {
192 | jspIndex = Integer.parseInt(jspLine.substring(0, hashPresent));
193 | }
194 | repeatCount = 1;
195 | }
196 |
197 | commaPresent = javaLine.indexOf(',');
198 |
199 | int outputIncrement;
200 | int javaIndex;
201 |
202 | if (commaPresent != -1) {
203 | outputIncrement = Integer.parseInt(
204 | javaLine.substring(commaPresent + 1));
205 | javaIndex = Integer.parseInt(javaLine.substring(0, commaPresent));
206 | } else {
207 | outputIncrement = 1;
208 | javaIndex = Integer.parseInt(javaLine);
209 | }
210 |
211 | for (int i = 0; i < repeatCount; i++) {
212 | int jspL = jspIndex + i;
213 | int javaL = javaIndex + (i * outputIncrement);
214 |
215 | jspLine = Integer.toString(jspL).concat(FID_DELIM).concat(fileIndex);
216 | javaLine = Integer.toString(javaL);
217 | if (!jsp2java.containsKey(jspLine)) {
218 | jsp2java.put(jspLine, javaLine);
219 | }
220 |
221 | jspLine = Integer.toString(jspL).concat("#").concat(fileIndex);
222 |
223 | javaLine = Integer.toString(javaL);
224 |
225 | if (!java2jsp.containsKey(javaLine)) {
226 | java2jsp.put(javaLine, jspLine);
227 | }
228 | }
229 | }
230 |
231 | private boolean sanityCheck() {
232 | if (!DEFAULT_STRATUM.equals(defaultStratum)) {
233 | return false;
234 | }
235 | if (!(outputFileName.endsWith(".java"))) {
236 | return false;
237 | }
238 | if (fsection.isEmpty()) {
239 | return false;
240 | }
241 | if (jsp2java.isEmpty()) {
242 | return false;
243 | }
244 | if (java2jsp.isEmpty()) {
245 | return false;
246 | }
247 | return true;
248 | }
249 |
250 | private String getFileNameByIndex(String index) {
251 | return (String) fsection.get(index);
252 | }
253 |
254 | private String getIndexByFileName(String fname) {
255 | Set s = fsection.entrySet();
256 | Iterator i = s.iterator();
257 |
258 | while (i.hasNext()) {
259 | Map.Entry mentry = (Map.Entry) i.next();
260 | String value = (String) mentry.getValue();
261 |
262 | if (value.equalsIgnoreCase(fname)) {
263 | return mentry.getKey().toString();
264 | }
265 | }
266 | return null;
267 | }
268 |
269 | public String getSourcePath(String fname) {
270 | Set s = fsection.entrySet();
271 | Iterator i = s.iterator();
272 |
273 | while (i.hasNext()) {
274 | Map.Entry mentry = (Map.Entry) i.next();
275 | String value = (String) mentry.getValue();
276 | int delim = value.lastIndexOf(":");
277 | String sourceName = value.substring(0, delim);
278 | String sourcePath = value.substring(delim + 1);
279 |
280 | if (sourceName.equalsIgnoreCase(fname)) {
281 | return sourcePath;
282 | }
283 | }
284 | return null;
285 | }
286 |
287 | public boolean isResolved() {
288 | return this.resolved;
289 | }
290 |
291 | public Map getFileNames() {
292 | Hashtable h = new Hashtable(fsection.size());
293 | Collection c = fsection.values();
294 | Iterator i = c.iterator();
295 | int counter = 0;
296 |
297 | while (i.hasNext()) {
298 | h.put(new Integer(counter++), i.next());
299 | }
300 | return h;
301 | }
302 |
303 | public String getPrimaryJspFileName() {
304 | TreeMap tm = new TreeMap(fsection);
305 | Object o = tm.firstKey();
306 | String s = (String) fsection.get(o);
307 |
308 | return s;
309 | }
310 |
311 | public boolean hasIncludedFiles() {
312 | return (fsection.size() > 1);
313 | }
314 |
315 | public String getJavaLineType(int line, int col) {
316 |
317 | return null;
318 | }
319 |
320 | public boolean isEmpty() {
321 | return jsp2java.isEmpty();
322 | }
323 |
324 | public String getJspFileName(int line, int col) {
325 | String key = Integer.toString(line);
326 | String value = (String) java2jsp.get(key);
327 |
328 | if (value == null) {
329 | return null;
330 | }
331 | String index = value.substring(value.indexOf(FID_DELIM) + 1);
332 |
333 | return getFileNameByIndex(index);
334 | }
335 |
336 | public int mangle(String jspFileName, int line, int col) {
337 | String fileIndex = getIndexByFileName(jspFileName);
338 |
339 | if (fileIndex == null) {
340 | return -1;
341 | }
342 | String key = "".concat(Integer.toString(line)).concat("#").concat(
343 | fileIndex);
344 | String value = (String) jsp2java.get(key);
345 |
346 | if (value == null) {
347 | return -1;
348 | }
349 | return Integer.parseInt(value);
350 | }
351 |
352 | public int unmangle(int line, int col) {
353 | String key = Integer.toString(line);
354 | String value = (String) java2jsp.get(key);
355 |
356 | if (value == null) {
357 | return -1;
358 | }
359 | int jspline = Integer.parseInt(value.substring(0, value.indexOf("#")));
360 |
361 | return jspline;
362 | }
363 |
364 | }
365 |
--------------------------------------------------------------------------------