• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
k
 

k

on

  • 1,094 views

 

Statistics

Views

Total Views
1,094
Views on SlideShare
1,094
Embed Views
0

Actions

Likes
0
Downloads
6
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    k k Document Transcript

    • Detected Java Issues
    • Contents Articles Detected Java Issues 1 Conventions used in reported Java issue messages 8 Checkers:ANDROID.NPE 9 Checkers:ANDROID.RLK.MEDIAPLAYER 10 Checkers:ANDROID.RLK.MEDIARECORDER 11 Checkers:ANDROID.RLK.SQLCON 13 Checkers:ANDROID.RLK.SQLOBJ 15 Checkers:ANDROID.UF.BITMAP 17 Checkers:ANDROID.UF.CAMERA 18 Checkers:ANDROID.UF.MEDIAPLAYER 20 Checkers:ANDROID.UF.MEDIARECORDER 21 Checkers:CMP.CLASS 22 Checkers:CMP.OBJ 23 Checkers:CMP.STR 24 Checkers:CMPF.FLOAT 25 Checkers:COV.CMP 26 Checkers:ECC.EMPTY 27 Checkers:EHC.EQ 28 Checkers:EHC.HASH 29 Checkers:ESCMP.EMPTYSTR 30 Checkers:EXC.BROADTHROWS 31 Checkers:FIN.EMPTY 32 Checkers:FIN.NOSUPER 33 Checkers:FSC.PRT 34 Checkers:FSC.PUB 35 Checkers:FSC.PRV 36 Checkers:JD.BITCMP 37 Checkers:JD.BITMASK 38 Checkers:JD.BITR 39 Checkers:JD.CALL.WRONGSTATIC 40 Checkers:JD.CAST.COL 41 Checkers:JD.CAST.KEY 42 Checkers:JD.CAST.SUSP 43 Checkers:JD.CAST.UPCAST 44
    • Checkers:JD.CATCH 45 Checkers:JD.CONCUR 46 Checkers:JD.EQ.ARR 47 Checkers:JD.EQ.UTA 48 Checkers:JD.EQ.UTC 49 Checkers:JD.FINRET 50 Checkers:JD.IFBAD 51 Checkers:JD.IFEMPTY 52 Checkers:JD.INF.AREC 53 Checkers:JD.INST.TRUE 54 Checkers:JD.LIST.ADD 55 Checkers:JD.LOCK 56 Checkers:JD.LOCK.NOTIFY 58 Checkers:JD.LOCK.SLEEP 59 Checkers:JD.LOCK.WAIT 60 Checkers:JD.NEXT 61 Checkers:JD.OVER 63 Checkers:JD.RC.EXPR.CHECK 64 Checkers:JD.RC.EXPR.DEAD 65 Checkers:JD.ST.POS 67 Checkers:JD.SYNC.DCL 68 Checkers:JD.SYNC.IN 70 Checkers:JD.THREAD.RUN 71 Checkers:JD.UMC.FINALIZE 72 Checkers:JD.UMC.RUNFIN 73 Checkers:JD.UMC.WAIT 74 Checkers:JD.UN.MET 75 Checkers:JD.UN.PMET 76 Checkers:JD.UNCAUGHT 77 Checkers:JD.UNMOD 78 Checkers:JD.VNU 80 Checkers:JD.VNU.NULL 82 Checkers:MNA.CAP 83 Checkers:MNA.CNS 84 Checkers:MNA.SUS 85 Checkers:NPE.COND 86 Checkers:NPE.CONST 87 Checkers:NPE.RET 88
    • Checkers:NPE.RET.UTIL 90 Checkers:NPE.STAT 91 Checkers:REDUN.DEF 92 Checkers:REDUN.EQ 93 Checkers:REDUN.EQNULL 94 Checkers:REDUN.FINAL 95 Checkers:REDUN.NULL 96 Checkers:REDUN.OP 97 Checkers:RI.IGNOREDCALL 98 Checkers:RI.IGNOREDNEW 99 Checkers:RLK.AWT 100 Checkers:RLK.FIELD 102 Checkers:RLK.HIBERNATE 104 Checkers:RLK.IMAGEIO 106 Checkers:RLK.IN 107 Checkers:RLK.JNDI 109 Checkers:RLK.MAIL 111 Checkers:RLK.MICRO 112 Checkers:RLK.NIO 114 Checkers:RLK.OUT 116 Checkers:RLK.SOCK 118 Checkers:RLK.SQLCON 120 Checkers:RLK.SQLOBJ 122 Checkers:RLK.SWT 123 Checkers:RLK.ZIP 124 Checkers:RNU.THIS 125 Checkers:RR.IGNORED 126 Checkers:RTC.CALL 127 Checkers:STRCON.LOOP 129 Checkers:SV.CLEXT.CLLOADER 130 Checkers:SV.CLEXT.POLICY 131 Checkers:SV.CLLOADER 132 Checkers:SV.CLONE.SUP 133 Checkers:SV.DATA.BOUND 135 Checkers:SV.DATA.DB 136 Checkers:SV.DOS.ARRINDEX 138 Checkers:SV.DOS.ARRSIZE 140 Checkers:SV.DOS.TMPFILEDEL 142
    • Checkers:SV.DOS.TMPFILEEXIT 143 Checkers:SV.EMAIL 144 Checkers:SV.EXEC 146 Checkers:SV.EXEC.DIR 147 Checkers:SV.EXEC.ENV 148 Checkers:SV.EXPOSE.FIELD 149 Checkers:SV.EXPOSE.FIN 150 Checkers:SV.EXPOSE.IFIELD 152 Checkers:SV.EXPOSE.MUTABLEFIELD 153 Checkers:SV.EXPOSE.RET 154 Checkers:SV.EXPOSE.STORE 155 Checkers:SV.HTTP SPLIT 156 Checkers:SV.IL.DEV 158 Checkers:SV.INT OVF 160 Checkers:SV.IL.FILE 162 Checkers:SV.LDAP 163 Checkers:SV.LOG FORGING 164 Checkers:SV.PASSWD.HC.EMPTY 165 Checkers:SV.PASSWD.PLAIN 166 Checkers:SV.PATH.INJ 167 Checkers:SV.PASSWD.HC 168 Checkers:SV.PATH 169 Checkers:SV.RANDOM 171 Checkers:SV.SERIAL.INON 172 Checkers:SV.SERIAL.NON 173 Checkers:SV.SERIAL.NOREAD 174 Checkers:SV.SERIAL.NOWRITE 175 Checkers:SV.SHARED.VAR 176 Checkers:SV.SERIAL.SIG 177 Checkers:SV.SOCKETS 178 Checkers:SV.STRBUF.CLEAN 180 Checkers:SV.SQL.DBSOURCE 182 Checkers:SV.SQL 183 Checkers:SV.STRUTS.NOTRESET 185 Checkers:SV.STRUTS.NOTVALID 187 Checkers:SV.STRUTS.PRIVATE 189 Checkers:SV.STRUTS.RESETMET 190 Checkers:SV.STRUTS.STATIC 191
    • Checkers:SV.STRUTS.VALIDMET 193 Checkers:SV.TAINT 195 Checkers:SV.TAINT NATIVE 196 Checkers:SV.TMPFILE 197 Checkers:SV.UMC.EXIT 198 Checkers:SV.UMC.JDBC 200 Checkers:SV.UMC.THREADS 202 Checkers:SV.UMD.MAIN 204 Checkers:SV.USE.POLICY 206 Checkers:SV.XPATH 207 Checkers:SV.XSS.DB 208 Checkers:SV.XSS.REF 210 Checkers:SYNCH.NESTED 212 Checkers:SYNCH.NESTEDS 213 Checkers:UC.BOOLB 214 Checkers:UC.BOOLS 215 Checkers:UC.STRS 216 Checkers:UC.STRV 217 Checkers:UF.IMAGEIO 218 Checkers:UF.IN 221 Checkers:UF.JNDI 224 Checkers:UF.MAIL 227 Checkers:UF.MICRO 229 Checkers:UF.NIO 231 Checkers:UF.OUT 233 Checkers:UF.SOCK 234 Checkers:UF.SQLCON 235 Checkers:UF.SQLOBJ 237 Checkers:UF.ZIP 239 Checkers:UMC.EXIT 241 Checkers:UMC.GC 242 Checkers:UMC.SYSERR 243 Checkers:UMC.SYSOUT 244 Checkers:UMC.TOSTRING 245 Article Licenses License 246
    • Detected Java Issues 1 Detected Java Issues Note: To download all of these pages from the Wiki as a PDF, go to the book page [1]. See also: • → Conventions used in reported Java issue messages • CWE IDs mapped to Klocwork Java issue types Issue code Description CWE Mapping → ANDROID.NPE Dereference of a null value in an Android application → ANDROID.RLK.MEDIAPLAYER Media player not released on exit → Media recorder not released on exit ANDROID.RLK.MEDIARECORDER → ANDROID.RLK.SQLCON Sql connection not closed on exit → ANDROID.RLK.SQLOBJ Sql object not closed on exit → ANDROID.UF.BITMAP Usage of recycled bitmap → ANDROID.UF.CAMERA Usage of released camera → ANDROID.UF.MEDIAPLAYER Usage of released media player → ANDROID.UF.MEDIARECORDER Usage of released media recorder → CMP.CLASS Comparing by classname [2] 486 → CMP.OBJ Comparing objects with == [3] 595 → CMP.STR Comparing strings with ==" → CMPF.FLOAT Equality checks on floating point types → COV.CMP Method compareTo() should have signature 'public int compareTo(Object)' → ECC.EMPTY Empty catch clause [4] 391 → EHC.EQ Class defines hashCode() but does not define equals() [5] 581 → EHC.HASH Class defines equals() but does not define hashCode() [5] 581 → ESCMP.EMPTYSTR Inefficient empty string comparison → EXC.BROADTHROWS Method has an overly broad throws declaration [6] 396 → FIN.EMPTY Empty finalize() method [7] 568 → FIN.NOSUPER Implementation of finalize() without call to super.finalize() [7] 568 → FSC.PRT Class and its superclass have protected fields with same name → FSC.PRV Class and its superclass have private fields with same name → FSC.PUB Class and its superclass have public fields with same name → JD.BITCMP Using non short-circuit logic in expression → JD.BITMASK Possible error in bit operations → JD.BITR Redundant expression → JD.CALL.WRONGSTATIC Call to static method via instance reference → JD.CAST.COL Possible ClassCastException for collection
    • Detected Java Issues 2 → JD.CAST.KEY Suspicious key type used to retrieve element from collection → JD.CAST.SUSP Possible ClassCastException for different types → JD.CAST.UPCAST Possible ClassCastException for subtypes → JD.CATCH Catching runtime exception → JD.CONCUR Possible ConcurrentModificationException → JD.EQ.ARR Calling 'equals' on array → JD.EQ.UTA Calling 'equals' on incompatible types (array and non-array) → JD.EQ.UTC Calling equals on incompatible types → JD.FINRET Return inside finally → JD.IFBAD Redundant 'if' statement → JD.IFEMPTY Redundant 'if' statement. Unfinished code → JD.INF.AREC Apparent infinite recursion → JD.INST.TRUE Redundant 'instanceof' conditio → JD.LIST.ADD Container added to itself → JD.LOCK Lock without unlock → JD.LOCK.NOTIFY Method 'notify' called with locks held → JD.LOCK.SLEEP Method 'sleep' called with locks held → JD.LOCK.WAIT Method 'wait' called with locks held → JD.NEXT Possible 'NoSuchElementException' → JD.OVER Mismatched override → JD.RC.EXPR.CHECK Test expression is always true → JD.RC.EXPR.DEAD Redundant check causing dead code → JD.ST.POS Incorrect check for method 'indexOf' → JD.SYNC.DCL Double-checked locking → JD.SYNC.IN Inconsistent synchronization → JD.THREAD.RUN Explicit call to a 'Thread.run' method → JD.UMC.FINALIZE Explicit call to method 'Object.finalize' → JD.UMC.RUNFIN runFinalizersOnExit() is called → JD.UMC.WAIT Wait called on incorrect object → JD.UN.MET Unused non-private method → JD.UN.PMET Unused private method → JD.UNCAUGHT Uncaught exception → JD.UNMOD Modification of unmodifiable collection → JD.VNU Variable was never read after being assigned → JD.VNU.NULL Variable was never read after null being assigned → MNA.CAP Method name should start with non-capital letter → MNA.CNS Method name is same as constructor name but is not a constructor → MNA.SUS Suspicious method name → NPE.COND Null pointer dereference where null comes from condition
    • Detected Java Issues 3 → NPE.CONST Null pointer dereference where null comes from constant → NPE.RET Dereference of a null value which is returned from a method → NPE.RET.UTIL Dereference of a null value which is returned from a map or a collection → NPE.STAT Null pointer dereference of a return value (statistical) → REDUN.DEF Assignment of expression to itself → REDUN.EQ Suspicious equals() called with same expression on both sides [8] 571 → REDUN.EQNULL Suspicious equals() called with expression and null (never true) [9] 570 → REDUN.FINAL Redundant 'final' modifier → REDUN.NULL Usage of variable instead of null constant → REDUN.OP Suspicious operation with same expression on both sides → RI.IGNOREDCALL The value returned by a method called on immutable object is ignored [4] 391 → RI.IGNOREDNEW Newly created object is ignored [4] 391 → RLK.AWT AWT object not disposed on exit → RLK.FIELD Possible leak of system resource stored in a field [10] 404 → RLK.HIBERNATE Hibernate object is not closed on exit → RLK.IMAGEIO ImageIO stream is not closed on exit → RLK.IN Input stream is not closed on exit [10] 404 → RLK.JNDI JNDI context is not closed on exi → RLK.MAIL Java mail object is not closed on exit → RLK.MICRO Java Microedition connection is not closed on exit → RLK.NIO NIO object is not closed on exit → RLK.OUT Output stream is not closed on exit [10] 404 → RLK.SOCK Socket is not closed on exit → RLK.SQLCON Sql connection is not closed on exit [10] 404 → RLK.SQLOBJ Sql object is not closed on exit → RLK.SWT SWT object is not disposed on exit [10] 404 → RLK.ZIP Zip file is not closed on exit → RNU.THIS Comparison of this and null but this cannot be null [11] 476 → RR.IGNORED The returned value is ignored [4] 391 → RTC.CALL Type cast is redundant → STRCON.LOOP Using append for string in a loop → SV.CLEXT.CLLOADER Class extends 'java.lang.ClassLoader' → SV.CLEXT.POLICY Class extends 'java.security.Policy' → SV.CLLOADER Direct use of Classloader → SV.CLONE.SUP Class implements 'clone' method but does not implement Cloneable [12] 580 → SV.DATA.BOUND Untrusted Data leaks into trusted storag [13] 501
    • Detected Java Issues 4 → SV.DATA.DB Data injection [14] 79 , 89 [15] → SV.DOS.ARRINDEX Tainted index used for array access [16] 129 → SV.DOS.ARRSIZE Tainted size used for array allocation [17] 130 → SV.DOS.TMPFILEDEL Leaving temporary file for lifetime of JVM [18] 459 → SV.DOS.TMPFILEEXIT Leaving temporary file [18] 459 → SV.EMAIL Unchecked e-mail [19] 472 → SV.EXEC Process Injection [20] 77 → SV.EXEC.DIR Process Injection. Working Directory [20] 77 → SV.EXEC.ENV Process Injection. Environment Variables [21] 454 → SV.EXPOSE.FIELD Static field may be changed by malicious code [22] 493 → SV.EXPOSE.FIN Method finalize() should have protected access modifier, not public [23] 583 → SV.EXPOSE.IFIELD Instance field should be made final → SV.EXPOSE.MUTABLEFIELD Static mutable field can be accessed by malicious code → SV.EXPOSE.RET Internal representation may be exposed [24] 374 → SV.EXPOSE.STORE Method stores reference to mutable object [24] 374 → SV.HTTP_SPLIT HTTP Response Splitting [25] 113 → SV.IL.DEV Design information leakage [26] 497 → SV.IL.FILE File Name Leaking [27] 548 → SV.INT_OVF Tainted data may lead to Integer Overflow [28] 190 → SV.LDAP Unvalidated user input is used as LDAP filter → SV.LOG_FORGING Log Forging [29] 117 → SV.PASSWD.HC Hardcoded Password [30] 259 → SV.PASSWD.HC.EMPTY Empty Password [31] 25 → SV.PASSWD.PLAIN Plain-text Password [32] 555 → SV.PATH Path and file name injection [33] 73 → SV.PATH.INJ File injection [33] 73 → SV.RANDOM Use of insecure Random number generator [34] 330 → SV.SERIAL.INON Interface extends 'Serializable' → SV.SERIAL.NON Class implements 'Serializable' → SV.SERIAL.NOREAD Method readObject() should be defined for a serializable class → SV.SERIAL.NOWRITE Method writeObject() should be defined for a serializable class → SV.SERIAL.SIG Methods readObject() and writeObject() in serializable classes should have correct signature
    • Detected Java Issues 5 → SV.SHARED.VAR Unsynchronized access to static variable from servlet [35] 567 → SV.SOCKETS Bad practices: use of socket [36] 246 → SV.SQL Sql Injection [15] 89 → SV.SQL.DBSOURCE Unchecked information from the database is used in SQL statements [15] 89 → SV.STRBUF.CLEAN String buffer not cleaned → SV.STRUTS.NOTRESET Struts Forms: inconsistent reset [37] 226 → SV.STRUTS.NOTVALID Struts Forms: inconsistent validate [38] 105 → SV.STRUTS.PRIVATE Struts Forms: non-private fields → SV.STRUTS.RESETMET Struts Forms: reset method [37] 226 → SV.STRUTS.STATIC Struts Forms: static fields [39] 500 → SV.STRUTS.VALIDMET Struts Forms: validate method [40] 103 → SV.TAINT Tainted data [41] 20 → SV.TAINT_NATIVE Tainted data goes to native code [41] 20 → SV.TMPFILE Temporary file path tampering [33] 73 → SV.UMC.EXIT The System.exit() and Runtime.exit() method calls should not be used in servlets code [42] 382 → SV.UMC.JDBC Application should avoid calling DriverManager.getConnection() directly [43] 245 → SV.UMC.THREADS Bad practices: use of thread management [44] 383 → SV.UMD.MAIN Leftover debug code - main method [45] 489 → SV.USE.POLICY Direct use methods of Policy → SV.XPATH Unvalidated user input is used as an XPath expression → SV.XSS.DB Cross Site Scripting (Stored XSS) [14] 79 , 80 [46] → SV.XSS.REF Cross Site Scripting (Reflected XSS) [14] 79 , 80 [46] → SYNCH.NESTED Synchronized method calls another synchronized method with the same lock held → SYNCH.NESTEDS Synchronized static method calls another synchronized static method with the same lock held → UC.BOOLB Unnecessary creation of new Boolean object from a boolean expression → UC.BOOLS Unnecessary creation of new Boolean object from a string expression → UC.STRS Unnecessary creation of new String object from a string expression → UC.STRV Unnecessary creation of empty String object → UF.IMAGEIO Usage of closed ImageIO stream → UF.IN Usage of closed input stream → UF.JNDI Usage of closed JNDI context → UF.MAIL Usage of closed Java mail object → UF.MICRO Usage of closed Java Microedition connection
    • Detected Java Issues 6 → UF.NIO Usage of closed NIO object → UF.OUT Usage of closed output stream → UF.SOCK Usage of closed socket → UF.SQLCON Usage of closed SQL connection → UF.SQLOBJ Usage of closed SQL object → UF.ZIP Usage of closed zip file → UMC.EXIT The System.exit() and Runtime.exit() method calls should not be used in servlets code [42] 382 → UMC.GC The System.gc() method call is unwanted → UMC.SYSERR Debug print using System.err method calls is unwanted [47] 576 → UMC.SYSOUT Debug print using System.out method calls is unwanted [47] 576 → UMC.TOSTRING Unnecessary toString() method called for a String argument References [1] http:/ / www. klocwork. com/ products/ documentation/ Insight-9. 1/ Insight-9. 1:Books/ Detected_Java_Issues [2] http:/ / cwe. mitre. org/ data/ definitions/ 486. html [3] http:/ / cwe. mitre. org/ data/ definitions/ 595. html [4] http:/ / cwe. mitre. org/ data/ definitions/ 391. html [5] http:/ / cwe. mitre. org/ data/ definitions/ 581. html [6] http:/ / cwe. mitre. org/ data/ definitions/ 396. html [7] http:/ / cwe. mitre. org/ data/ definitions/ 568. html [8] http:/ / cwe. mitre. org/ data/ definitions/ 571. html [9] http:/ / cwe. mitre. org/ data/ definitions/ 570. html [10] http:/ / cwe. mitre. org/ data/ definitions/ 404. html [11] http:/ / cwe. mitre. org/ data/ definitions/ 476. html [12] http:/ / cwe. mitre. org/ data/ definitions/ 580. html [13] http:/ / cwe. mitre. org/ data/ definitions/ 501. html [14] http:/ / cwe. mitre. org/ data/ definitions/ 79. html [15] http:/ / cwe. mitre. org/ data/ definitions/ 89. html [16] http:/ / cwe. mitre. org/ data/ definitions/ 129. html [17] http:/ / cwe. mitre. org/ data/ definitions/ 130. html [18] http:/ / cwe. mitre. org/ data/ definitions/ 459. html [19] http:/ / cwe. mitre. org/ data/ definitions/ 472. html [20] http:/ / cwe. mitre. org/ data/ definitions/ 77. html [21] http:/ / cwe. mitre. org/ data/ definitions/ 454. html [22] http:/ / cwe. mitre. org/ data/ definitions/ 493. html [23] http:/ / cwe. mitre. org/ data/ definitions/ 583. html [24] http:/ / cwe. mitre. org/ data/ definitions/ 374. html [25] http:/ / cwe. mitre. org/ data/ definitions/ 113. html [26] http:/ / cwe. mitre. org/ data/ definitions/ 497. html [27] http:/ / cwe. mitre. org/ data/ definitions/ 548. html [28] http:/ / cwe. mitre. org/ data/ definitions/ 190. html [29] http:/ / cwe. mitre. org/ data/ definitions/ 117. html [30] http:/ / cwe. mitre. org/ data/ definitions/ 259. html [31] http:/ / cwe. mitre. org/ data/ definitions/ 258. html [32] http:/ / cwe. mitre. org/ data/ definitions/ 555. html [33] http:/ / cwe. mitre. org/ data/ definitions/ 73. html [34] http:/ / cwe. mitre. org/ data/ definitions/ 330. html [35] http:/ / cwe. mitre. org/ data/ definitions/ 567. html [36] http:/ / cwe. mitre. org/ data/ definitions/ 246. html [37] http:/ / cwe. mitre. org/ data/ definitions/ 226. html [38] http:/ / cwe. mitre. org/ data/ definitions/ 105. html
    • Detected Java Issues 7 [39] http:/ / cwe. mitre. org/ data/ definitions/ 500. html [40] http:/ / cwe. mitre. org/ data/ definitions/ 103. html [41] http:/ / cwe. mitre. org/ data/ definitions/ 20. html [42] http:/ / cwe. mitre. org/ data/ definitions/ 382. html [43] http:/ / cwe. mitre. org/ data/ definitions/ 245. html [44] http:/ / cwe. mitre. org/ data/ definitions/ 383. html [45] http:/ / cwe. mitre. org/ data/ definitions/ 489. html [46] http:/ / cwe. mitre. org/ data/ definitions/ 80. html [47] http:/ / cwe. mitre. org/ data/ definitions/ 576. html
    • Conventions used in reported Java issue messages 8 Conventions used in reported Java issue messages In the message or "output" of a detected Java issue: • the string "someMethodName().$RET" means the value that was returned by someMethodName(). • the string "someMethodName().$N", where N can be 1, 2, 3 (and so on), means the first, second, third (and so on) parameter of the someMethodName() call. See also: • → Detected Java Issues • Fixing issues before they enter the code stream • Investigating issues in your integration build
    • Checkers:ANDROID.NPE 9 Checkers:ANDROID.NPE A NullPointerException is thrown in case of an attempt to dereference a null value. The dereference may be a function call, a read or write of a field, or an array access. An ANDROID.NPE error is reported for Android [1] -specific null pointer dereference situations. Example 1 17 protected void onCreate(Bundle bundle) { 18 super.onCreate(bundle); 19 setContentView(R.layout.note_layout); 20 final ImageView image = (ImageView) findViewById(R.id.image); 21 22 final String title = bundle.getString(TITLE); 23 setTitle(title); 24 } ANDROID.NPE is reported for line 22 since 'bundle' might be null in the 'onCreate()' method due to the contract. See also • → NPE.CONST • → NPE.RET • → NPE.RET.UTIL • → NPE.STAT Language: English References [1] http:/ / code. google. com/ android
    • Checkers:ANDROID.RLK.MEDIAPLAYER 10 Checkers:ANDROID.RLK.MEDIAPLAYER RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. An ANDROID.RLK.MEDIAPLAYER warning indicates that a MediaPlayer that was opened is not explicitly closed. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 19 public boolean onKeyDown(final int keyCode, final KeyEvent event) { 20 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 21 final MediaPlayer player = MediaPlayer.create(this, ringtoneUri); 22 player.start(); 23 24 } 25 return super.onKeyDown(keyCode, event); 26 } ANDROID.RLK.CAMERA is reported for the snippet on line 25: 'player' is not released on exit. Language: English
    • Checkers:ANDROID.RLK.MEDIARECORDER 11 Checkers:ANDROID.RLK. MEDIARECORDER RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. An ANDROID.RLK.MEDIARECORDER warning indicates that a MediaRecorder that was opened is not explicitly released. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 20 public boolean onKeyDown(final int keyCode, final KeyEvent event) { 21 if (keyCode == KeyEvent.KEYCODE_ENTER) { 22 MediaRecorder recorder = new MediaRecorder(); 23 recorder.setAudioSource(MediaRecorder.AudioSource.MIC); 24 recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 25 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 26 recorder.setOutputFile(PATH_NAME); 27 recorder.prepare(); 28 recorder.start(); // Recording is now started 29 recorder.stop(); 30 recorder.reset(); // You can reuse the object by going back to setAudioSource() step 31 recorder.release(); 32 return true; 33 } 34 return super.onKeyDown(keyCode, event); 35 } ANDROID.RLK.MEDIARECORDER is reported for the snippet on line 22: 'recorder' will not be released on exit if 'setAudioSource(...)' throws java.lang.IllegalStateException (line 23).
    • Checkers:ANDROID.RLK.MEDIARECORDER 12 Example 2 20 public boolean onKeyDown(final int keyCode, final KeyEvent event) { 21 if (keyCode == KeyEvent.KEYCODE_ENTER) { 22 MediaRecorder recorder = new MediaRecorder(); 23 try { 24 recorder.setAudioSource(MediaRecorder.AudioSource.MIC); 25 recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 26 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 27 recorder.setOutputFile(PATH_NAME); 28 recorder.prepare(); 29 recorder.start(); // Recording is now started 30 recorder.stop(); 31 recorder.reset(); // You can reuse the object by going back to setAudioSource() step 32 } finally { 33 recorder.release(); 34 } 35 return true; 36 } 37 return super.onKeyDown(keyCode, event); 38 } The snippet from the previous section is fixed; ANDROID.RLK.MEDIARECORDER is not reported here. Language: English
    • Checkers:ANDROID.RLK.SQLCON 13 Checkers:ANDROID.RLK.SQLCON RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. ANDROID.RLK.SQLCON indicates that an Sql connection is not closed on exit. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 30 protected void onCreate(Bundle bundle) { 31 super.onCreate(bundle); 32 final SQLiteDatabase database = openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null); 33 final Cursor query = database.query(DATABASE_TABLE, 34 new String[]{KEY_FILE, KEY_DATE, KEY_COMMENT}, 35 null, 36 null, 37 null, 38 null, 39 KEY_DATE + " asc"); 40 startManagingCursor(query); 41 42 ListAdapter adapter = new SimpleCursorAdapter(this, 43 android.R.layout.simple_list_item_1, 44 query, 45 new String[]{Contacts.People.NAME}, 46 new int[]{android.R.id.text1}); 47 setListAdapter(adapter); 48 } ANDROID.RLK.SQLCON is reported for the snippet on line 32: connection 'database' is not closed on exit.
    • Checkers:ANDROID.RLK.SQLCON 14 See also • → ANDROID.RLK.SQLOBJ Language: English
    • Checkers:ANDROID.RLK.SQLOBJ 15 Checkers:ANDROID.RLK.SQLOBJ RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. An ANDROID.RLK.SQLOBJ warning indicates that an SQLite API object (other than an SQL connection) is not closed on exit. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 41 protected void onCreate(Bundle bundle) { 42 super.onCreate(bundle); 43 database = openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null); 44 45 if (bundle != null) { 46 final String[] queryClauseArray = bundle.getStringArray(KEY_QUERY); 47 if (queryClauseArray != null) { 48 for (final String queryClause : queryClauseArray) { 49 final Cursor query = database.query(DATABASE_TABLE, 50 new String[]{KEY_FILE, KEY_DATE, KEY_COMMENT}, 51 null, 52 null, 53 null, 54 null, 55 queryClause); 56 files.add(query.getString(0)); 57 dates.add(query.getString(1)); 58 comments.add(query.getString(2)); 59 60 } 61 } 62 }
    • Checkers:ANDROID.RLK.SQLOBJ 16 63 } ANDROID.RLK.SQLOBJ is reported for the snippet on line 49: database cursor 'query' is not closed on exit. See also • → ANDROID.RLK.SQLCON Language: English
    • Checkers:ANDROID.UF.BITMAP 17 Checkers:ANDROID.UF.BITMAP UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The ANDROID.UF.BITMAP warning indicates an attempt to get pixel(s) from a Bitmap or set pixel(s) into a Bitmap after it was recycled. Example 1 19 public void addWatermark(final byte[] data) { 20 final Bitmap bmp = loadBitmap(data); 21 if (bmp != null) { 22 final int width = bmp.getWidth(); 23 for (int i = 0; i < width; i++) { 24 bmp.setPixel(i, i, Color.argb(255, 0, 0, 0)); 25 } 26 } 27 } 28 29 private Bitmap loadBitmap(byte[] data) { 30 final Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length); 31 if (bmp == null) { 32 Log.d(TAG, "Was not able to decode an image"); 33 } 34 35 final int width = bmp.getWidth(); 36 final int height = bmp.getHeight(); 37 if (width <= 3 || height <= 3 ) { 38 bmp.recycle(); 39 } 40 return bmp; 41 } ANDROID.UF.BITMAP is reported for the snippet on line 24 since method 'loadBitmap()' recycles the bitmap if one of its dimensions is less than '3' (line 38). Language: English
    • Checkers:ANDROID.UF.CAMERA 18 Checkers:ANDROID.UF.CAMERA UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The ANDROID.UF.CAMERA warning indicates an attempt to use Camera after it was released. Example 1 21 private Camera camera; 22 23 private void initCamera() { 24 camera = Camera.open(); 25 } 26 27 public boolean onKeyDown(final int keyCode, final KeyEvent event) { 28 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 29 if (camera != null) { 30 final CameraPictureCallbackImpl callback = new CameraPictureCallbackImpl(); 31 camera.takePicture(null, null, callback); 32 } 33 return true; 34 } 35 return super.onKeyDown(keyCode, event); 36 } 37 38 private class CameraPictureCallbackImpl implements Camera.PictureCallback { 39 private Bitmap bitmap; 40 41 public void onPictureTaken(final byte[] bytes, final Camera camera) { 42 camera.stopPreview(); 43 camera.release(); 44 bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); 45 if (bitmap == null) { 46 camera.startPreview(); 47 } 48 } 49 50 public Bitmap getBitmap() { 51 return bitmap; 52 } 53 } ANDROID.UF.CAMERA is reported for the snippet on line 46 since callback method 'onPictureTaken(...)' starts the camera preview even if the camera was released on line 43.
    • Checkers:ANDROID.UF.CAMERA 19 Language: English
    • Checkers:ANDROID.UF.MEDIAPLAYER 20 Checkers:ANDROID.UF.MEDIAPLAYER UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The ANDROID.UF.MEDIAPLAYER warning indicates an attempt to use MediaPlayer after it was released. Example 1 26 public boolean onKeyDown(final int keyCode, final KeyEvent event) { 27 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 28 MediaPlayer mp = new MediaPlayer(); 29 try { 30 mp.setDataSource(PATH_TO_FILE); 31 mp.prepare(); 32 } catch (IOException e) { 33 mp.release(); 34 } 35 mp.start(); 36 mp.release(); 37 return true; 38 } 39 return super.onKeyDown(keyCode, event); 40 } ANDROID.UF.MEDIAPLAYER is reported for the snippet on line 35 since there is an attempt to use the 'mp' that is released in case of IOException on line 33. Language: English
    • Checkers:ANDROID.UF.MEDIARECORDER 21 Checkers:ANDROID.UF.MEDIARECORDER UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The ANDROID.UF.MEDIARECORDER warning indicates an attempt to use MediaRecorder after it was released. Example 1 15 public boolean onKeyDown(final int keyCode, final KeyEvent event) { 16 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 17 MediaRecorder mRecorder = new MediaRecorder(); 18 19 mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); 20 mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 21 mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 22 23 final File file = new File("test.raw"); 24 if (file.exists()) { 25 mRecorder.release(); 26 } else { 27 mRecorder.setOutputFile(file.getPath()); 28 } 29 30 mRecorder.start(); 31 mRecorder.release(); 32 return true; 33 } 34 return super.onKeyDown(keyCode, event); 35 } ANDROID.UF.MEDIARECORDER is reported for the snippet on line 30 since there is an attempt to use the 'mRecorder' that is released if the output file exists (line 25). Language: English
    • Checkers:CMP.CLASS 22 Checkers:CMP.CLASS This error appears when the program attempts to compare two objects' classnames to see whether they are the same. It can also appear if an object has a certain class using other means than a currently loaded class or via the classloader itself. Vulnerability and risk When comparing classes by name, you allow for mix-and-match attacks, where an attacker constructs new code that links some of your code together with malicious classes or links two classes together that were not meant to be together. Mitigation and prevention Do not use an object's equals method to find classnames. Instead, retrieve the first object's class with getClass method, then retrieve the second object's class by means of the current classloader. Example 1 10 public void privateMethod(Object object1, Object object2) { 11 if (object1.getClass().getName().equals("anotherClass")) {// wrong 12 // do work based on the assumption we're dealing with 13 // the right object 14 } 15 if (object1.getClass() == object2.getClass()) { // correct 16 // do work based on the fact that the objects are the 17 // of the same class 18 } 19 } CMP.CLASS is reported for line 11: Comparing by classname. Security Guidelines • CWE-486: Comparison of Classes by Name [2] Language: English
    • Checkers:CMP.OBJ 23 Checkers:CMP.OBJ This warning appears if object references are compared rather than the objects themselves. An error is reported only if the compared objects have different types, and none of them has the explicit Object type. Vulnerability and risk This problem can cause unexpected application behavior. Comparing objects using == usually produces deceptive results, since the == operator compares object references rather than their values. To use == on a string, the programmer has to make sure that these objects are unique in the program, that is, that they don't have the equals method defined, or they have a static factory that produces unique objects. Mitigation and prevention Use the equals() method to compare objects instead of the == operator. If using ==, it is important for performance reasons that your objects are created by a static factory, not by a constructor. Example 1 9 /** 10 * Check that person is John 25 miner 11 */ 12 Proffesional john = new Proffesional("John", 25, "miner"); 13 public boolean checkJohn(Person p) { 14 return p == john; 15 } CMP.OBJ is reported for line 14: Comparing objects 'p' and 'john' with == Security Guidelines • CWE-595: Comparison of Object References Instead of Object Contents [3] Language: English
    • Checkers:CMP.STR 24 Checkers:CMP.STR This warning appears if string references are compared rather than strings themselves for String type. Vulnerability and risk This problem can cause unexpected application behavior. Comparing objects using == usually produces deceptive results, since the == operator compares object references rather than values. To use == on a string, the programmer has to make sure that these are constant strings, statically created in the same class or "interned" prior to comparison using the intern() method. Mitigation and prevention Use the equals() method to compare objects instead of the == operator. Example 1 10 /** 11 * Return symbolic name of operation 12 */ 13 public String nameOperation(String key) { 14 if (key == "++") return "PLUS"; 15 if (key == "--") return "MINUS"; 16 return "UNKNOWN"; 17 } CMP.STR is reported for line 14: Comparing strings 'key' and '++' with ==CMP.STR is reported for line 15: Comparing strings 'key' and '--' with == Language: English
    • Checkers:CMPF.FLOAT 25 Checkers:CMPF.FLOAT Error printed when two float or double value compared using equals operator (==). Vulnerability and risk Avoid equality checks on floating point types because of possible inaccuracy of floating point calculations. The example below can lead to an infinite loop because x1 + 700 times ((x2 - x1) / 700) does not equal to x2, due to inaccuracy. Mitigation and prevention Use check great or equals, less or equals or abs different less than something, for example (Math.abs(x1-x2) < MIN_DIFF). Example 1 9 /** 10 * Calculates define integral 11 */ 12 public static double integral(MyFunction f, double x1, 13 double x2) { 14 double x = x1; 15 double result = 0; 16 double step = (x2 - x1) / 700; 17 while (x != x2) { // should use (x <= x2) 18 result = result + f.valueFor(x) * step; 19 x = x + step; 20 } 21 return result; 22 } CMPF.FLOAT is reported for line 17: Equality checks on floating point types should be avoided Language: English
    • Checkers:COV.CMP 26 Checkers:COV.CMP Error exists when method compareTo declared with signature different than int compareTo(Object). Vulnerability and risk Intent was probably to implement interface method of Comparable interface, but since this method has different signature it is not same method and will not be called when comparator is used. Mitigation and prevention Declare that class implements Comparable, declare int compareTo(Object) method. Example 1 14 String name; 15 int compareTo(MyClass a) { 16 return name.compareTo(a.name); 17 } COV.CMP is reported for line 15: Method compareTo(..) should have signature 'public int compareTo(Object)' Language: English
    • Checkers:ECC.EMPTY 27 Checkers:ECC.EMPTY An Empty Catch Clause (ECC.EMPTY) warning appears if nothing is written in a catch block. If you catch an exception, it would be better to process it rather than to ignore it. Example 1 12 public void openFile(String name) { 13 try { 14 FileInputStream is = new FileInputStream(name); 15 // read file ... 16 } catch (FileNotFoundException e) { 17 // TODO Auto-generated catch block 18 } 19 } ECC.EMPTY is reported for line 16: Empty catch clause Security Guidelines • CWE-391: Unchecked Error Condition [4] Language: English
    • Checkers:EHC.EQ 28 Checkers:EHC.EQ The EHC Class should implement both equals(Object) and hashCode() methods. EHC warnings appear if an equals() method was specified without a hashCode() method, or vice versa. This warning appears if a hashCode() is specified without an equals(). This may cause a problem with some collections that expect equal objects to have equal hashcodes. Example 1 8 public class EHC_EQ_Sample_1 { 9 private int seed; 10 public EHC_EQ_Sample_1(int seed) { 11 this.seed = seed; 12 } 13 public int hashCode() { 14 return seed; 15 } 16 // no equals(Object o) method defined 17 } EHC.EQ is reported for class declaration on line 8: Class defines hashCode() but does not define equals(). Security Guidelines • CWE-581: Object Model Violation: Just One of Equals and Hashcode Defined [5] See also • → EHC.HASH Language: English
    • Checkers:EHC.HASH 29 Checkers:EHC.HASH The EHC Class should implement both equals(Object) and hashCode() methods. EHC warnings appear if an equals() method was specified without a hashCode() method, or vice versa. This may cause a problem with some collections that expect equal objects to have equal hashcodes. Example 1 8 public class EHC_HASH_Sample_1 { 9 private int seed; 10 public EHC_HASH_Sample_1(int seed) { 11 this.seed = seed; 12 } 13 public boolean equals(Object o) { 14 return (o instanceof EHC_HASH_Sample_1) 15 && ((EHC_HASH_Sample_1) o).seed == seed; 16 } 17 // no hashCode method defined 18 } EHC.HASH is reported for class declaration on line 8: Class defines equals() but does not define hashCode(). Security Guidelines • CWE-581: Object Model Violation: Just One of Equals and Hashcode Defined [5] See also • → EHC.EQ Language: English
    • Checkers:ESCMP.EMPTYSTR 30 Checkers:ESCMP.EMPTYSTR ESCMP Compare string with an empty string using equals(). It is not necessary to call equals() to compare a string with an empty string. s.length() works twice as fast. The following expressions: s.equals("") or "".equals(s) can be easily replaced with (s.length() == 0) and (s != null && s.length() == 0) Performance measurements (done using Java 2 Runtime Environment, Standard Edition, build 1.4.1_02-b06) showed that code with "equals" executed in 147 units of time while the same code with "length" executed in 71 units of time. Example 1 9 public boolean emptyCheck1(String s) { 10 if (s.equals("")) return true; 11 return false; 12 } 13 public boolean emptyCheck2(String s) { 14 if ("".equals(s)) return true; 15 return false; 16 } 17 // fixed code 18 public boolean emptyCheck3(String s) { 19 if (s.length() == 0) return true; 20 return false; 21 } ESCMP.EMPTYSTR is reported for line 10: Comparing strings 's' and "" using equals(), instead of length() == 0ESCMP.EMPTYSTR is reported for line 14: Comparing strings "" and 's' using equals(), instead of length() == 0 Language: English
    • Checkers:EXC.BROADTHROWS 31 Checkers:EXC.BROADTHROWS A method should throw exceptions appropriate to the abstraction level. When a method throws exceptions that are too general, like Exception and Throwable, it is difficult for callers to handle errors correctly and do appropriate error recovery. Vulnerability and risk When method throws exceptions that are too general, callers have to investigate what kind of problem happened so that they can handle it appropriately. Also, when a method code is changed and a new kind of exception is introduced, it's harder to force all callers to handle it properly. Mitigation and prevention A method should throw exceptions appropriate to the abstraction level. When necessary, low-level exceptions can be wrapped with higher-level exceptions. Example 1 15 public void processFile(String fileName) throws Exception { 16 InputStream is = new FileInputStream(fileName); 17 // do something 18 } 19 public int calculateSum(Collection data) throws Throwable { 20 int sum = 0; 21 for (Iterator it = data.iterator(); it.hasNext();) { 22 String element = (String) it.next(); 23 int i = Integer.parseInt(element); 24 sum += i; 25 } 26 return sum; 27 } EXC.BROADTHROWS is reported for method 'processFile' declaration on line 15: The 'processFile' method throws a generic exception 'java.lang.Exception'. EXC.BROADTHROWS is reported for method 'calculateSum' declaration on line 19: The 'calculateSum' method throws a generic exception 'java.lang.Throwable'. Security Guidelines • CWE-396: Declaration of Catch for Generic Exception [6] Language: English
    • Checkers:FIN.EMPTY 32 Checkers:FIN.EMPTY Empty finalize() method. FIN.* code problems have a questionable implementation of the finalize method(). In this case, there is an empty finalize() method. Example 1 11 public void test3() { 12 new FIN_EMPTY_Sample_1() { 13 protected void finalize() throws Throwable { 14 15 } 16 }; 17 } 18 // fixed code 19 public void test1() { 20 new FIN_EMPTY_Sample_1() { 21 }; 22 } FIN.EMPTY is reported for line 13: Empty finalize() method should be removed. Security Guidelines • CWE-568: finalize() Method Without super.finalize() [7] Language: English
    • Checkers:FIN.NOSUPER 33 Checkers:FIN.NOSUPER Implementation of the finalize() method should call super.finalize(). FIN.* code problems report on questionable implementations of the finalize method(). In this case there is a finalize() method implementation that does not call super.finalize(). Vulnerability and risk If a superclass implementor overrides a superclass finalizer but forgets to invoke the superclass finalizer manually, the superclass finalizer will never be invoked. This means resource cleanup for the superclass will never be performed, leading to resource leaks. Example 1 8 public class FIN_NOSUPER_Sample_1 { 9 /* 10 * no super.finalize() was called 11 */ 12 public void finalize() { 13 System.err.println("finalized"); 14 } 15 } FIN.NOSUPER is reported for 'finalize' method declaration on line 12: Implementation of the finalize() method should call super.finalize(). Security Guidelines • CWE-568: finalize() Method Without super.finalize() [7] Language: English
    • Checkers:FSC.PRT 34 Checkers:FSC.PRT This warning is reported for protected fields. It appears if some field in a subclass shadows (has the same name, type and modifier) as some field in the superclass. This can cause confusion. Example 1 9 public class SuperClass { 10 protected int index; 11 // ... 12 } 13 public class SubClass extends SuperClass { 14 protected int index; 15 // ... 16 } FSC.PRT is reported for field declaration on line 14: Class 'com.klocwork.jdefects.checkers.ast.samples.FSC_PRT_Sample_1$SubClass' hides field 'index' of superclass 'com.klocwork.jdefects.checkers.ast.samples.FSC_PRT_Sample_1$SuperClass' by declaring a protected or package-private field with the same name 4 Language: English
    • Checkers:FSC.PUB 35 Checkers:FSC.PUB This warning is reported for public fields. It appears if some field in a subclass shadows (has the same name, type and modifier) as some field in the superclass. This can cause confusion. Example 1 9 public class SuperClass { 10 protected int index; 11 // ... 12 } 13 public class SubClass extends SuperClass { 14 public int index; 15 // ... 16 } FSC.PUB is reported for field declaration on line 14: Class 'com.klocwork.jdefects.checkers.ast.samples.FSC_PUB_Sample_1$SubClass' hides field 'index' of superclass 'com.klocwork.jdefects.checkers.ast.samples.FSC_PUB_Sample_1$SuperClass' by declaring a public field with the same name Language: English
    • Checkers:FSC.PRV 36 Checkers:FSC.PRV This warning is reported for private fields. It appears if some field in a subclass shadows (has the same name, type and modifier) as some field in the superclass. This can cause confusion. Example 1 9 public class SuperClass { 10 protected int index; 11 // ... 12 } 13 public class SubClass extends SuperClass { 14 private int index; 15 // ... 16 } FSC.PRV is reported for field declaration on line 14: Class 'com.klocwork.jdefects.checkers.ast.samples.FSC_PRV_Sample_1$SubClass' hides field 'index' of superclass 'com.klocwork.jdefects.checkers.ast.samples.FSC_PRV_Sample_1$SuperClass' by declaring a private field with the same name Language: English
    • Checkers:JD.BITCMP 37 Checkers:JD.BITCMP JD.BITCMP happens when an if check contains binary such as & or | instead of short-circuit, such as && or ||. It is better to use short-circuit operation for performance. Also, if you use binary, both sides of the expression are evaluated, and this can cause other unexpected problems, such as a null pointer exception being thrown. as in the example below. Vulnerability and risk A JD.BITCMP defect can cause a performance impact or unexpected behavior, such as a RuntimeException being thrown. Mitigation and prevention Replace bit operation with short-circuit operation. Example 1 10 static void check(int arr[]) { 11 if (arr!=null & arr.length!=0) { 12 foo(); 13 } 14 return; 15 } JD.BITCMP is reported for line 11: Questionable use of bit operation '&' in expression. Did you mean '&&'? See also • → JD.BITMASK • → JD.BITR Language: English
    • Checkers:JD.BITMASK 38 Checkers:JD.BITMASK JD.BITMASK happens when int or a long variable is used with bit operation & or | and is then compared to a constant, while the result of the evaluation is known in advance. For example ((a & 0x0f) == 0xf0) is always false because bitmasks are incompatible. Vulnerability and risk It is unlikely that the code was intentional, so the error can cause unexpected behavior. Mitigation and prevention Fix the bit operator (if it was the cause), or fix the bitmask. Example 1 10 final static int FLAG = 0x01; 11 static boolean checkMask(int a) { 12 // mistyped, should be & 13 if ((a | FLAG) == 0) return true; 14 return false; 15 } JD.BITMASK is reported for line 13: Incompatible bitmasks 'a | FLAG' and '0' cause the expression to always be 'false'. See also • → JD.BITCMP • → JD.BITR Language: English
    • Checkers:JD.BITR 39 Checkers:JD.BITR JD.BITR happens when an if check contains only constants on both sides. It can be the result of a programming error followed by compiler optimization which replaces expressions with constants. As a sub-case, this checker will trigger accidental assignments in conditions such as those in the example below. Note: Whether or not this error occurs depends on how the Java compiler optimizes the code. For some compilers, JD.BITR never occurs and either JD.RC.EXPR.DEAD or JD.RC.EXPR.CHECK occurs instead. Vulnerability and risk A statically evaluatable expression in an 'if' statement is most likely an error in logic. Mitigation and prevention Fix the 'if' statement. Example 1 10 static void check(boolean hasFields) { 11 if (hasFields = true) { 12 foo(); 13 } 14 return; 15 } JD.BITR is reported for lline 11: Expression 'hasFields = true' is always 'true'. Is there a typo? See also • → JD.BITCMP • → JD.BITMASK • → JD.RC.EXPR.CHECK • → JD.RC.EXPR.DEAD Language: English
    • Checkers:JD.CALL.WRONGSTATIC 40 Checkers:JD.CALL.WRONGSTATIC JD.CALL.WRONGSTATIC appears when a static method is called by means of instance reference. Vulnerability and risk Calling of a static method by means of an instance reference is a bad coding practice, and it can cause incorrect behavior. For example, if static method interrupted() is called by means of an instance reference, then the returned state would be the state of the current Thread, not the state of the given instance. If you wants to get the state of the instance, use a non-static call isInterrupted(). Mitigation and prevention Do not call static methods by means of instance references. Example 1 9 void run(final Thread thread) throws Throwable{ 10 thread.interrupted(); 11 } JD.CALL.WRONGSTATIC is reported for line 10: Call to static method 'java.lang.Thread.interrupted' via instance reference. Language: English
    • Checkers:JD.CAST.COL 41 Checkers:JD.CAST.COL JD.CAST.COL is found when an object is retrieved from a collection (map or list) and is cast immediately as type A, although it was put into the collection as type B, where types A and B are unrelated. That is, Klocwork cannot find that A is a subtype of B or B is a subtype of A. The JD.CAST.COL checker checks only class fields. Vulnerability and risk This usually causes a ClassCastException, because objects in the collection have different types. Mitigation and prevention Choose which type you actually want to use--A or B--and, either put objects of type A, or get objects of type B. The other option is to allow both of these types to use an instanceof check before casting the object. Example 1 10 public class JD_CAST_COL_Sample_1 { 11 HashMap test; 12 void foo(){ 13 test.put("a","b"); 14 JD_CAST_COL_Sample_1 res =(JD_CAST_COL_Sample_1)test.get("a"); 15 } 16 } JD.CAST.COL is reported for line 14: Suspicious cast to 'com.klocwork.jdefects.checkers.ast.samples.JD_CAST_COL_Sample_1' of collection element. Object was put into the collection as 'java.lang.String'.-> 13: test.put(a, b)-> 14: (JD_CAST_COL_Sample_1)test.get(a) See also • → JD.CAST.UPCAST • → JD.CATCH Language: English
    • Checkers:JD.CAST.KEY 42 Checkers:JD.CAST.KEY JD.CAST.KEY is reported when the type of key used to retrieve a collection element differs from the type of key used to put the object into the collection. Vulnerability and risk The expected element will not be found in the collection, since no elements were put into the collection with a key of this type. Mitigation and prevention Check if the collection is expected to contain keys of different types. Check if the key used to retrieve an element from the collection is of the correct type. Example 1 11 public class JD_CAST_KEY_Sample_1 { 12 13 HashMap len=new HashMap(); 14 15 void fill(File dir){ 16 File[] list = dir.listFiles(); 17 for (int i = 0; i < list.length; i++) { 18 File file = list[i]; 19 len.put(file, new Long(file.length())); 20 } 21 } 22 23 int getLength(String file){ 24 Long l = (Long) len.get(file); 25 if (l!=null) return l.intValue(); 26 return 0; 27 } 28 } JD.CAST.KEY is reported for call to 'len.get(file)' on line 24: Suspicious key of type 'java.lang.String' used to retrieve a collection element. Object was put into the collection with key of type 'java.io.File'. See also • → JD.CAST.COL Language: English
    • Checkers:JD.CAST.SUSP 43 Checkers:JD.CAST.SUSP JD.CAST.SUSP is triggered when an object is checked with an instance of operator for type A and than cast to type B, where types A and B are unrelated. (That is Klocwork cannot find that A is a subtype of B or B is a subtype of A.) Vulnerability and risk This is usually an error, because cast is not safe; the object can actually be another type than B. In some cases, this error can produce false positives when the path from instanceof to cast is incompatible. Mitigation and prevention Choose which type you actually want to use--A or B--and either change the typecast to A, or check the instanceof to B. Example 1 10 void setValue(Object a, Object value) { 11 if (a instanceof String) { 12 StringBuffer b = (StringBuffer) a; 13 b.append("="); 14 b.append(value); 15 } 16 } JD.CAST.SUSP is reported for cast on line 12: Suspicious cast of 'a' from 'String' to 'StringBuffer', where types are unrelated.-> 11: a instanceof String-> 12: (StringBuffer)a See also • → JD.CAST.UPCAST Language: English
    • Checkers:JD.CAST.UPCAST 44 Checkers:JD.CAST.UPCAST JD.CAST.UPCAST is triggered when an object is checked with an instance of operator for type A and than cast to type B, where B is a subtype of type A. Vulnerability and risk This is usually an error, because the cast is not safe, the object can actually be another subtype of A. In some cases, this error can produce false positives when the path from the instanceof to the cast is incompatible. Example 1 14 void setValue(Object a, Object value) { 15 if (a instanceof Map) { 16 HashMap b = (HashMap) a; 17 b.put(value, ""); 18 } else if (a instanceof List) { 19 List b = (List) a; 20 b.add(value); 21 } 22 } JD.CAST.UPCAST: Suspicious cast of 'a' to 'HashMap', where 'HashMap' is a subtype of 'Map'. This object can hold other subtypes of 'Map' which can cause a ClassCastException.-> 15: a instanceof Map-> 16: (HashMap)a See also • → JD.CAST.SUSP Language: English
    • Checkers:JD.CATCH 45 Checkers:JD.CATCH Klocwork reports a JD.CATCH issue when it finds a catch block with an unwanted exception such as java.lang.NullPointerException. A list of possible exceptions is in the Parameters section. Vulnerability and risk Exceptions, as their names implies, should be used only for exceptional conditions; they should never be used for ordinary control flow. Using exceptions for control flow dramatically reduces performance, maintainability, and readability of the code. Mitigation and prevention Change the code to code that does a preventive check (full null, array index, and so on). Example 1 9 String test1(String my) { 10 try { 11 return my.substring(1,4); 12 } catch (NullPointerException e) { 13 return ""; 14 } 15 } JD.CATCH is reported on line 12: Catching 'java.lang.NullPointerException' explicitly is usually a bad practice. Use preventive checks on data instead. Language: English
    • Checkers:JD.CONCUR 46 Checkers:JD.CONCUR JD.CONCUR is found when an iterator is created for collection A, then something is removed from the collection, but the loop is not stopped. For more information see ConcurrentModificationException [1] Vulnerability and risk On the following invocation of the "next" method, the code will throw a ConcurrentModificationException. Mitigation and prevention An object under iteration cannot be modified. Elements for removal have to be stored in another collection and removed later, or the collection can be cloned and the iterator used on the cloned version. Example 1 12 void fixList(Collection col) { 13 for (Iterator iter = col.iterator(); iter.hasNext();) { 14 String el = (String) iter.next(); 15 if (el.startsWith("/")) { 16 col.remove(el); 17 } 18 } 19 } JD.CONCUR is reported for line 14: Possible 'ConcurrentModificationException' can be thrown by method 'iter.next()' while iterating over 'col'. You cannot remove a collection element while iterating over the same collection. Language: English References [1] http:/ / java. sun. com/ j2se/ 1. 5. 0/ docs/ api/ java/ util/ ConcurrentModificationException. html
    • Checkers:JD.EQ.ARR 47 Checkers:JD.EQ.ARR JD.EQ.ARR is reported when two arrays are compared through an equals() method. Vulnerability and risk Method equals() called on array operates the same as a '==' operator, comparing references, not the array itself. It is most likely an error; a deep array comparison is required. Mitigation and prevention Either change this method invocation to an invocation of a deep array comparison Arrays.equals(arr1,arr2) or use a direct reference comparison arr1==arr2 (but only if the objects are exactly the same.) Example 1 9 static class MyClass { 10 String names[]; 11 public boolean equals(Object o) { 12 if (!(o instanceof MyClass)) 13 return false; 14 MyClass m = (MyClass)o; 15 return this.names.equals(m.names); 16 } 17 } JD.EQ.ARR is reported for 'equals' call on line 15: Comparison of arrays using the 'equals' method. For arrays, 'equals' compares the identities of the two arrays - not the values of the array contents. See also • → JD.EQ.UTA • → JD.EQ.UTC Language: English
    • Checkers:JD.EQ.UTA 48 Checkers:JD.EQ.UTA JD.EQ.UTA is found when there is a comparison of array and non-array types through the equals method. Vulnerability and risk This call always returns false, meaning that the program contains an error which can cause incorrect behavior. Mitigation and prevention Fix arguments of equals methods. Most likely, the comparison should be with an array element. Example 1 9 public boolean checkNames(String[] ids) { 10 if (ids.equals("")) return false; 11 // ... 12 return true; 13 } JD.EQ.UTA is reported for line 10: Comparing an array with a non-array type always returns false. See also • → JD.EQ.UTC • → JD.EQ.ARR Language: English
    • Checkers:JD.EQ.UTC 49 Checkers:JD.EQ.UTC JD.EQ.UTC is found when objects of incompatible types are compared through the equals method. Object types are considered to be incompatible if they don't have any class or interface in common. Vulnerability and risk Most likely an error. For example, a comparison of String and File objects, was probably meant to be file.getPath().equals(""). Mitigation and prevention Fix the equals argument to make it type compatible. It probably needs additional function calls to retrieve an object of the correct type for comparison. Example 1 11 public boolean checkFile(File file) { 12 if (file==null || file.equals("")) return false; 13 // ... 14 return true; 15 } JD.EQ.UTC is reported for 'equals' call on line 12: Calling equals on incompatible types 'java.io.File' and 'java.lang.String'. See also • → JD.EQ.UTA • → JD.EQ.ARR Language: English
    • Checkers:JD.FINRET 50 Checkers:JD.FINRET JD.FINRET is found when a return statement occurs in a finally block. Vulnerability and risk A return statement inside a finally block will cause any exception that might be thrown in the try block to be discarded and any value that was originally intended to be returned by the method to be replaced with the value returned in the finally block. Mitigation and prevention A finally block should contain only finalization code. Any logic about return values and re-throwing expectations should not be in a finally block. Example 1 9 int foo2(String name) { 10 try { 11 return Integer.parseInt(name); 12 } catch (NumberFormatException e) { 13 throw e; 14 } finally { 15 return -1; 16 } 17 } JD.FINRET is reported on line 15: A 'return' in a finally block can cause exceptions to be ignored. Language: English
    • Checkers:JD.IFBAD 51 Checkers:JD.IFBAD JD.IFBAD happens when an 'if' statement has only an empty 'then' branch. Possible misplaced ";". Vulnerability and risk Usually JD.IFBAD represents a logical error in the code. When there is a misplaced semicolon, the following statement is assumed to be executed only on condition but, in fact, is always executed. In less severe cases, it is just left-over code and should be removed for efficiency. Mitigation and prevention Change the code so that the 'if' contains a non-empty branch or remove the 'if' altogether. Example 1 9 private void foo(boolean debug) { 10 // ... 11 if (debug); { // print something 12 System.err.println("Enter foo"); 13 } 14 } JD.IFBAD is reported for line 11: Redundant 'if' statement. The cause is probably a misplaced semicolon. See also • → JD.IFEMPTY Language: English
    • Checkers:JD.IFEMPTY 52 Checkers:JD.IFEMPTY JD.IFEMPTY happens when an if statement has only an empty then branch. Possible unfinished code. Vulnerability and risk A programmer might have left this check, intending to return and add something to the code but forgetting. An if that does nothing impacts performance, especially if method calls are involved. Mitigation and prevention Change the code so that the if contains a non-empty branch or remove the if altogether. Example 1 9 private void foo(Object a) { 10 // ... 11 if (a==null) { 12 // do something 13 } 14 } JD.IFEMPTY is reported for line 11: Redundant 'if' statement. This may be unfinished code. See also • → JD.IFBAD Language: English
    • Checkers:JD.INF.AREC 53 Checkers:JD.INF.AREC JD.INF.AREC occurs when the method calls itself without any prior checks. Vulnerability and risk If this method is called, it will call itself again and again, and then the program stack will overflow and the JVM will throw a StackOverflowError. Obviously this is not what the programmer intended. Mitigation and prevention JD.INF.AREC has three possible causes. • There is a misspelled instance object. For example, instead of "super.equals(o)", the programmer typed "this.equals(o)" Fix the spelling of the instance object. • The argument of the method is not cast for a specific type. For example, it should be this.equals((MyType)o). Cast the argument to a specific type. • A condition for terminating the recursion is missing. Add a condition that will stop recursion. Example 1 10 /** 11 * Implementation required by the interface. 12 * @param o - object to compare 13 * @return true, if equal. 14 */ 15 public boolean equals(Object o) { 16 return this.equals(o); 17 } JD.INF.AREC is reported for call on line 16: Apparent infinite recursion by calling 'equals(java.lang.Object)' from itself Language: English
    • Checkers:JD.INST.TRUE 54 Checkers:JD.INST.TRUE JD.INST.TRUE is reported when the result of an instance of for type check is known in advance. Vulnerability and risk There is no error in this construction, but the check does not make sense, and can be replaced by a check for non-null. Maybe there was a typo in a type name or in the name of an instanceof argument. Mitigation and prevention Remove this check or replace it with a check for non-null or change the code to use an appropriate type of object. Example 1 9 private void test3(String b) { 10 if (b instanceof String) { 11 foo(); 12 } 13 } JD.INST.TRUE is reported for 'instanceof' expression on line 10: Condition 'b instanceof String' is redundant and can be replaced with '!=null'. Language: English
    • Checkers:JD.LIST.ADD 55 Checkers:JD.LIST.ADD JD.LIST.ADD occurs when an operation is performed on a container, for example, addAll, removeAll, retainAll or containsAll, but the argument is a container itself. This is definitely a typo. Vulnerability and risk This is not an error in itself, but since it makes no sense, there is an error in the logic. For example, instead of writing con1.addAll(con2), the programmer wrote con1.addAll(con1). The severity of this error depends on where and how the code is used. Mitigation and prevention Fix the name of the method argument or, perhaps, replace removeAll with list.clean(). Example 1 11 private Collection foo(Collection list12_3, 12 Collection list12_4) { 13 if (list12_3.size() < list12_4.size()) { 14 list12_3.addAll(list12_4); 15 return list12_3; 16 } else { 17 list12_4.addAll(list12_4); 18 return list12_4; 19 } 20 21 } JD.LIST.ADD is reported for 'addAll' call on line 17 : Container 'list12_4' calls 'addAll' with itself as an argument. This code does nothing, or there is simpler way to do it. Probably a typo. Language: English
    • Checkers:JD.LOCK 56 Checkers:JD.LOCK JD.LOCK occurs when a lock was acquired with a java.util.concurrent.locks.Lock.lock() method call, but it was never actually released; that is, the java.util.concurrent.locks.Lock.unlock() method was not called on some path. Vulnerability and risk This situation can cause deadlock. Mitigation and prevention Here is a pattern for implementing locking by means of a Lock object: l.lock(); try { ... } finally { l.unlock(); } Example 1 12 void action() { 13 Lock l = new ReentrantLock(); 14 l.lock(); 15 try { 16 dosomething(); 17 } catch (Exception e) { 18 l.unlock(); 19 } 20 } 21 22 private void dosomething() throws Exception { 23 // ... 24 } JD.LOCK is reported for the line 13: Lock 'l' acquired but not released. Example 2 11 void action() { 12 Lock l = new ReentrantLock(); 13 l.lock(); 14 try { 15 dosomething(); 16 } catch (Exception e) { 17 // ...
    • Checkers:JD.LOCK 57 18 } finally { 19 l.unlock(); 20 } 21 } 22 23 private void dosomething() throws Exception { 24 // ... 25 } The problem from the previous snippet is fixed: the lock would be released whether an exception was thrown or not. JD.LOCK is not reported here. Language: English
    • Checkers:JD.LOCK.NOTIFY 58 Checkers:JD.LOCK.NOTIFY JD.LOCK.NOTIFY occurs when the code calls notify() or notifyAll() while two locks are held. Vulnerability and risk The code calls notify() or notifyAll() while two locks are held. If this notification is intended to wake up a wait() that is holding the same locks, it may deadlock, since the wait will only give up one lock and the notify will be unable to get both locks, and thus the notify will not succeed. If there is also a warning about a two-lock wait, the probability of a problem is quite high. Mitigation and prevention Preferably call a notify() method without locks held. Example 1 9 synchronized void finish(Object o) { 10 synchronized(o) { 11 o.notify(); 12 } 13 } JD.LOCK.NOTIFY is reported for line 11: Calling 'java.lang.Object.notify()' with two or more locks held '[this, o]' could cause a deadlock. See also • → JD.LOCK.SLEEP • → JD.LOCK.WAIT Language: English
    • Checkers:JD.LOCK.SLEEP 59 Checkers:JD.LOCK.SLEEP JD.LOCK.SLEEP occurs when a method calls Thread.sleep() while a lock is held. Vulnerability and risk This may result in very poor performance and scalability, or in a deadlock, since other threads may be waiting to acquire the lock. It is a much better idea to call wait() on the lock, which releases the lock and allows other threads to run. Mitigation and prevention Call a sleep() method without holding locks. Example 1 13 String name; 14 synchronized void finish(Object o) throws InterruptedException { 15 while (!name.equals("root")) { 16 Thread.sleep(1000); 17 } 18 } JD.LOCK.SLEEP is reported for line 16: Calling 'java.lang.Thread.sleep(long)' with locks '[this]' held could cause a deadlock. See also • → JD.LOCK.NOTIFY • → JD.LOCK.WAIT Language: English
    • Checkers:JD.LOCK.WAIT 60 Checkers:JD.LOCK.WAIT JD.LOCK.WAIT occurs when an Object.wait() method is called while the method is holding two or more locks. This checker checks only local locks. Vulnerability and risk Waiting on a monitor while two locks are held may cause deadlock. Performing a wait releases the lock only on the object being waited on, not on any other locks. Not necessarily a problem. Mitigation and prevention Preferably, use a call wait() method without a lock held, or with a lock on the same object for which the wait is called. Example 1 9 String name; 10 synchronized void waitForCondition(Object lock) { 11 try { 12 synchronized(lock) { 13 name = "aa"; 14 lock.wait(); 15 } 16 } catch (InterruptedException e) { 17 return; 18 } 19 } JD.LOCK.WAIT is reported for line 14: Calling 'java.lang.Object.wait()' with two or more locks held '[lock, this]' could cause a deadlock. See also • → JD.LOCK.NOTIFY • → JD.LOCK.SLEEP Language: English
    • Checkers:JD.NEXT 61 Checkers:JD.NEXT JD.NEXT occurs when an Iterator.next() is called without a preceding hasNext(). Vulnerability and risk A 'next()' method can throw a NoSuchElement exception if there are not enough elements in the collection. Mitigation and prevention If an exception is expected, mark your method as throwing a java.util.NoSuchElementException. Otherwise, it is better to add an explicit check for iter.hasNext instead of collection.size(), to avoid a time-to-check time-to-use race condition. Even if you think that this method is not mult-ithreaded, it will improve the readability and maintainability of the code. Example 1 11 public boolean intersects(Set setA, Set setB) { 12 for (final Iterator iteratorA = setA.iterator(); iteratorA.hasNext();) { 13 final Object a = iteratorA.next(); 14 for (final Iterator iteratorB = setB.iterator(); iteratorB.hasNext();) { 15 Object b = iteratorA.next(); 16 if (a.equals(b)) { 17 return true; 18 } 19 } 20 } 21 return false; 22 } JD.NEXT is reported for the snippet on line 15: method 'next()' is called for 'iteratorA' without a preceding 'hasNext()' check. You may have intended to call the 'next()' method for 'iteratorB' instead of 'iteratorA'. Example 2 11 public boolean intersects(Set setA, Set setB) { 12 for (final Iterator iteratorA = setA.iterator(); iteratorA.hasNext();) { 13 final Object a = iteratorA.next(); 14 for (final Iterator iteratorB = setB.iterator(); iteratorB.hasNext();) { 15 Object b = iteratorB.next(); 16 if (a.equals(b)) { 17 return true; 18 } 19 } 20 }
    • Checkers:JD.NEXT 62 21 return false; 22 } The snippet from the previous section is fixed; all calls to 'next' are preceded with appropriate 'hasNext' checks. JD.NEXT is not reported here. Language: English
    • Checkers:JD.OVER 63 Checkers:JD.OVER JD.OVER occurs when a subclass has a method defined and its superclass has a method with the same name defined but with a different signature, and both the class and the superclass do not have other methods with the same name. Vulnerability and risk In some cases it might be an attempt to override a method in a superclass, but the parameter lists do not match, so the superclass method is not overridden. It could have happened when the method signature changed in the superclass but not in the subclasses. It is not an error if the designer intended the behavior. Mitigation and prevention If it is an error, fix the method signature in the subclass(es). Example 1 8 public class JD_OVER_Sample_1 { 9 class MyClass { 10 void init(int i) { 11 12 } 13 } 14 15 class MyOtherClass extends MyClass { 16 void init() { 17 18 } 19 } 20 } JD.OVER is reported for method declaration on line 16: Possible incorrect override for method 'init()'. Maybe 'init(int)' from class 'com.klocwork.jdefects.checkers.ast.samples.JD_OVER_Sample_1$MyClass' is what was intended to be overridden. Language: English
    • Checkers:JD.RC.EXPR.CHECK 64 Checkers:JD.RC.EXPR.CHECK JD.RC.EXPR.CHECK is triggered when a local variable is checked even though that check will always result in a 'true' value, so the block of code will always execute under this condition. Vulnerability and risk Logic flaw. Checks should only be done for properties that are not known in compile time. Mitigation and prevention Make sure that you are checking the right variables for the right values. Example 1 13 void handleEvent(AWTEvent event) { 14 if (event instanceof MouseEvent) { 15 if (event != null) { 16 handleMouseEvent((MouseEvent) event); 17 } 18 } 19 } JD.RC.EXPR.CHECK is reported for the check on line 15, since the check on line 14 guarantees that 'event' is not null; Example 2 13 void handleEvent(AWTEvent event) { 14 if (event != null) { 15 if (event instanceof MouseEvent) { 16 handleMouseEvent((MouseEvent) event); 17 } 18 } 19 } JD.RC.EXPR.CHECK is not reported for the snippet: the null check on line 14 does not guarantee that the 'event' is an instance of the MouseEvent class. See also • → JD.RC.EXPR.DEAD Language: English
    • Checkers:JD.RC.EXPR.DEAD 65 Checkers:JD.RC.EXPR.DEAD JD.RC.EXPR.DEAD is triggered when a local variable is checked even though that check will always result in a 'false' value, so the block of code will never execute under this condition. Vulnerability and risk Logic flaw. Checks should only be done for properties that are not known at compile time. Mitigation and prevention Make sure that you are checking the right variables for the right values. Example 1 13 void configure(final String path) throws IOException { 14 BufferedReader in = new BufferedReader(new FileReader(path)); 15 if (in == null) { 16 log("Was not able to access the file"); 17 return; 18 } 19 20 String line; 21 while ((line = in.readLine()) != null) { 22 parseConfiguration(line); 23 } 24 } JD.RC.EXPR.DEAD is reported for the check on line 15: 'in' is not null due to the assignment on line 14. Example 2 14 void configure(final String path) throws IOException { 15 BufferedReader in = null; 16 17 try { 18 in = new BufferedReader(new FileReader(path)); 19 } catch (FileNotFoundException e) { 20 e.printStackTrace(); 21 } 22 23 if (in == null) { 24 log("Was not able to access the file"); 25 return; 26 } 27 28 String line; 29 while ((line = in.readLine()) != null) { 30 parseConfiguration(line);
    • Checkers:JD.RC.EXPR.DEAD 66 31 } 32 } JD.RC.EXPR.DEAD is not reported for the snippet: 'in' can be null on line 23 if FileNotFoundException is thrown by the FileReader constructor on line 18 . See also • → JD.RC.EXPR.CHECK Language: English
    • Checkers:JD.ST.POS 67 Checkers:JD.ST.POS JD.ST.POS is found when the result of a String.indexOf(..) method is checked for greater than 0. Vulnerability and risk The method String.indexOf(..) returns the position of the found symbol, starting with 0, so a check for greater than 0 is most likely incorrect, because it misses any cases where a symbol is first in the string. Mitigation and prevention Replace a check for >0 with a check for ==-1, or >=0. Example 1 9 public boolean checkFile(String file) { 10 if (file.indexOf("/")>0) { 11 return true; 12 } 13 return false; 14 } JD.ST.POS is reported for call on line 10: Result of method 'indexOf' should be checked for >=0 or <0 instead of >0. Language: English
    • Checkers:JD.SYNC.DCL 68 Checkers:JD.SYNC.DCL JD.SYNC.DCL occurs when double-checked locking is found (as in first the example below). Vulnerability and risk Double-checked locking is widely cited and used as an efficient method for implementing lazy initialization in a multithreaded environment. Unfortunately, it will not work reliably in a platform independent way when implemented in J2SE 1.4 (and earlier versions). Although the double-checked locking idiom cannot be used for references to objects, it can work for 32-bit primitive values (e.g., int's or float's). Note, that it does not work for long's or double's, since unsynchronized reads/writes of 64-bit primitives are not guaranteed to be atomic. The double-checked locking pattern will not work when under certain circumstances the code, generated by compiler, will contain assignment of an incompletely initialized object to a field before statements, that finalize the object initialization. Thus other threads will see a non-null reference to an object with default field values. Even if the compiler does not reorder those statements, on a multiprocessor system the processor or the memory system may reorder those statements, as perceived by a thread running on another processor. Mitigation and prevention As of J2SE 5.0, this problem has been fixed. The 'volatile' keyword now ensures that multiple threads handle the singleton instance correctly. If the singleton that is created is static, the solution will be to define the singleton as a static field in a separate class. The semantics of Java guarantee that the field will not be initialized until the field is referenced, and that any thread which accesses the field will see all of the writes resulting from initializing that field. Otherwise, one can use synchronization without a double check, but should keep in mind that synchronizing a method may decrease performance significantly (see second example below). For more information see The "Double-Checked Locking is Broken" Declaration [1]and Wikipedia article: Double-checked locking [2] Example 1 9 class MyClass { 10 MyClass son; 11 void doubleCheckedLocking() { 12 if (son==null) { 13 synchronized (this) { 14 if (son==null) { 15 son = new MyClass(); 16 } 17 } 18 } 19 } 20 } JD.SYNC.DCL is reported for line 14: Double-checked locking for 'son' -- idiom that does not achieve its goal.
    • Checkers:JD.SYNC.DCL 69 Example 2 14 class MyClass { 15 private MyClass son = null; 16 public synchronized void doubleCheckedLocking() { 17 if (son == null) 18 son = new MyClass(); 19 } 20 } Method is synchronized, no need for double checks. Language: English References [1] http:/ / www. cs. umd. edu/ ~pugh/ java/ memoryModel/ DoubleCheckedLocking. html [2] http:/ / en. wikipedia. org/ wiki/ Double-checked_locking
    • Checkers:JD.SYNC.IN 70 Checkers:JD.SYNC.IN JD.SYNC.IN is found when a class is using its own field inconsistently. "Inconsistently" means that the number of protected usages is greater than 66% of the number of all usages. The error is reported when the count of field usages is greater than three. These numbers are checker parameters that you can change. Vulnerability and risk Inconsistent synchronization can cause race conditions. Mitigation and prevention Fields should either be synchronized with the same lock all the time, or not synchronized at all. Partial synchronization is a root-cause of race condition problems. Example 1 9 class MyClass { 10 private String name; 11 public MyClass() { 12 name = ""; 13 } 14 synchronized public String getName() { 15 return name; 16 } 17 synchronized public void setName(String name) { 18 this.name = name; 19 } 20 public void foo(String x) { 21 name = x; 22 } 23 } JD.SYNC.IN is reported for field declaration on line 10: Field 'name' synchronized inconsistently. Language: English
    • Checkers:JD.THREAD.RUN 71 Checkers:JD.THREAD.RUN JD.THREAD.RUN occurs when a Thread.run() method is called explicitly. Vulnerability and risk In most cases, this is a mistake. The method is called implicitly by the thread itself. After a Thread.start() method has been invoked, calling Thread.run() will not start a thread. Mitigation and prevention Should you change it to Thread.start()? Example 1 9 static void start() { 10 new Thread(){ 11 public void run(){ 12 // do something 13 } 14 }.run(); 15 } JD.THREAD.RUN is reported for line 14: There is a call to the 'Thread.run()' method. This method is not meant to be called explicitly. Should probably be replaced with 'Thread.start()'? Language: English
    • Checkers:JD.UMC.FINALIZE 72 Checkers:JD.UMC.FINALIZE JD.UMC.FINALIZE shows that a method contains an explicit invocation of the finalize() method of an object. Vulnerability and risk Object finalizer methods are supposed to be executed once, and only by the JVM, so calling one explicitly is bad practice. Depending on the particular JVM and its method of implementation, the improper behavior may be because the object finalizer method was called twice. Mitigation and prevention It is better practice to avoid finalizers at all, and to create an explicit termination method with a different name. If absolutely necessary, a finalizer can call an object finalizer method as a "safety net". Example 1 11 OutputStream st; 12 protected void finalize() throws Throwable { 13 if (st!=null) st.close(); 14 super.finalize(); 15 } 16 17 void run() throws Throwable{ 18 // ... 19 finalize(); 20 } JD.UMC.FINALIZE is reported for call on line 19: There is a call to a 'finalize()' method. This method is not intended to be called explicitly. Language: English
    • Checkers:JD.UMC.RUNFIN 73 Checkers:JD.UMC.RUNFIN JD.UMC.RUNFIN reports a call to method runFinalizersOnExit() that may cause erratic behavior or deadlocks. Vulnerability and risk There is a call to method runFinalizersOnExit() which may cause erratic behavior or deadlocks. Mitigation and prevention Avoid the call to runFinalizersOnExit(). Example 1 9 void run() throws Throwable{ 10 System.runFinalizersOnExit(true); 11 } JD.UMC.RUNFIN is reported for line 10: There is a call to method 'runFinalizersOnExit'. This method is inherently unsafe. Language: English
    • Checkers:JD.UMC.WAIT 74 Checkers:JD.UMC.WAIT JD.UMC.WAIT occurs when a method calls wait() on a java.util.concurrent.locks.Condition object. Vulnerability and risk This code will not achieve the intended results. Mitigation and prevention Waiting for a Condition should be done with one of the await() methods defined by the Condition interface. Example 1 11 void waitForCondition(Condition cond) { 12 try { 13 cond.wait(); 14 } catch (InterruptedException e) { 15 return; 16 } 17 } 18 // corrected code 19 void waitForCondition2(Condition cond) { 20 try { 21 cond.await(); 22 } catch (InterruptedException e) { 23 return; 24 } 25 } JD.UMC.WAIT is reported for call on line 13: There is a call to method 'cond.wait()'. Should use method 'cond.await()' instead. Language: English
    • Checkers:JD.UN.MET 75 Checkers:JD.UN.MET JD.UN.MET occurs if no call for method is found in the analyzed code. (This checker is triggered only by non-private methods that were not overloaded, or did not overload something). Vulnerability and risk Unused methods can be used as back doors. They also increase code footprint in memory. Additionally, they increase the size of source code which decreases maintainability. Mitigation and prevention Remove unused methods. Be careful when removing methods. Make sure the method was not designed for extensibility or is not a library method that may be used by code that is not part of the code you are analyzing with Klocwork. Example 1 9 static class MyClass { 10 void foo(){ 11 System.err.println("Hello, World!"); 12 } 13 } JD.UN.MET is reported for method declaration on line 10: Method 'foo()' is never called in the analyzed context. See also • → JD.UN.PMET Language: English
    • Checkers:JD.UN.PMET 76 Checkers:JD.UN.PMET JD.UN.PMET occurs if no call for method is found in the analyzed context. This checker is triggered only by private methods. Vulnerability and risk Unused methods can be used as back doors. They also increase code footprint in memory. Additionally, they increase the size of source code which decreases maintainability. Mitigation and prevention Remove unused private methods. Example 1 9 static class MyClass { 10 private void foo(){ 11 System.err.println("Hello, World!"); 12 } 13 } JD.UN.PMET is reported for method declaration on line 10: Private method 'foo' is unused. See also • → JD.UN.MET Language: English
    • Checkers:JD.UNCAUGHT 77 Checkers:JD.UNCAUGHT JD.UNCAUGHT is a powerful customizable checker that checks for methods listed in parameters, that do not catch all exceptions thrown inside their bodies transitively. A list of the checked exceptions is also a parameter. JD.UNCAUGHT reports a list of exceptions that, theoretically, can be thrown by a method body, which probably requires a safety net - top most catch block that catches all exceptions. By default, the list of methods includes servlet entry points: doGet and doPost, Thread.run() and main() method. Vulnerability and risk Unprocessed exceptions not caught by servlet entry methods can lead to system information leaks (like stacktrace) and to XSS errors. However, the framework supports special methods that have to be defined to process exceptions. If a special method is implemented, however; this error should be ignored. For the Thread.run() method, uncaught exceptions can cause unexpected thread termination and possible deadlocks. For the main() method, uncaught exceptions can cause the JVM to halt. Mitigation and prevention Wrap the method body in a try block that catches all exceptions, and create a meaningful procedure that deals with exceptions. For servlets, report the stack trace to the server log, but not to the user! Example 1 16 protected void doPost(HttpServletRequest req, // 17 HttpServletResponse arg1) // 18 throws ServletException, IOException { 19 String ip = req.getRemoteAddr(); 20 InetAddress addr = InetAddress.getByName(ip); 21 // ... 22 arg1.getOutputStream().println("Host name is " + 23 addr.getHostName()); 24 foo(); 25 } 26 27 static class Ex1 extends RuntimeException { } 28 29 private static void foo() throws Ex1 { 30 throw new Ex1(); 31 } JD.UNCAUGHT is reported for method 'doPost' declaration on line 16: Method 'doPost' does not catch exceptions 'com.klocwork.jdefects.checkers.ast.samples.JD_UNCAUGHT_Sample_1$Ex1'. Language: English
    • Checkers:JD.UNMOD 78 Checkers:JD.UNMOD This error is reported when an attempt to modify an unmodifiable collection is detected. Such attempts cause runtime exceptions. Example 1 12 public static void main(String[] args) { 13 argsCol = createCollection(args); 14 for (final Iterator<String> iterator = argsCol.iterator(); iterator.hasNext();) { 15 final String arg = iterator.next(); 16 if ("version".equals(arg)) { 17 printVersion(); 18 iterator.remove(); 19 } 20 } 21 run(); 22 } 23 24 public static Collection<String> createCollection(final String[] array) { 25 return Arrays.asList(array); 26 } JD.UNMOD is reported for the snippet on line 18: attempt to modify the unmodifiable collection 'argsCol' via its iterator. Example 2 12 public static void main(String[] args) { 13 argsCol = createCollection(args); 14 for (final Iterator<String> iterator = argsCol.iterator(); iterator.hasNext();) { 15 final String arg = iterator.next(); 16 if ("version".equals(arg)) { 17 printVersion(); 18 iterator.remove(); 19 } 20 } 21 run(); 22 } 23 24 public static Collection<String> createCollection(final String[] array) { 25 final List<String> list = new ArrayList<String>(); 26 for (final String str : array) {
    • Checkers:JD.UNMOD 79 27 list.add(str); 28 } 29 return list; 30 } The problem from the previous snippet is fixed: the code is still modifying 'argsCol' via its iterator, however the 'argsCol' is not unmodifiable here; see the modified 'createCollection' method. JD.UNMOD is not reported here. Language: English
    • Checkers:JD.VNU 80 Checkers:JD.VNU JD.VNU shows that the value assigned to a variable was never read after assignment. Vulnerability and risk In most cases, it is just less than optimal code, but sometimes, it can signify a major logical error when a value is set up, but never actually used. Mitigation and prevention Optimize the code and remove the unused assignments. Example 1 13 boolean checkArray(int arr[]) { 14 for (int i = 0; i < arr.length; i++) { 15 int item = arr[i]; 16 String hexString = Integer.toHexString(item); 17 if (i % 2 == 0) { 18 return true; 19 } 20 } 21 return false; 22 } JD.VNU is reported for line 16: a hexString is created for each 'item' in the array, though it is never used afterwards. Example 2 13 private long getTimeLen(long arr[]) { 14 long time1 = 0; 15 long time2 = 0; 16 long len = 0; 17 for (int i = 0; i < arr.length; i += 2) { 18 time1 = arr[i]; 19 time1 = arr[i + 1]; 20 if (time1 < time2) { 21 long d = time1 - time2; 22 if (d > len) { 23 len = d; 24 } 25 } 26 } 27 return len; 28 } JD.VNU is reported for two assignments in the snippet: • assignment on line 14: this operation pointless and unoptimal since 'time1' is overwritten on line 18.
    • Checkers:JD.VNU 81 • assignment on line 18: the developer intended to initialize 'time2' variable but used 'time1' instead. See also • → JD.VNU.NULL Language: English
    • Checkers:JD.VNU.NULL 82 Checkers:JD.VNU.NULL JD.VNU.NULL shows that the null value assigned to a variable was never read after assignment. Vulnerability and risk In most cases, it is just a redundant initialization code, but sometimes, it can signify a major logical error. Mitigation and prevention Optimize the code and remove the unused assignments. Example 1 16 Reader prepareReader(Reader r) { 17 BufferedReader bufferedReader = null; 18 19 try { 20 bufferedReader = new BufferedReader(r); 21 register(bufferedReader); 22 } catch (Exception e) { 23 e.printStackTrace(); 24 } 25 26 return bufferedReader; 27 } 28 29 private void register(BufferedReader bufferedReader) { 30 // ... 31 } JD.VNU.NULL is reported for line 17: BufferedReader constructor does not throw exceptions, so the 'bufferedReader' variable is always reassigned on line 20. See also • → JD.VNU Language: English
    • Checkers:MNA.CAP 83 Checkers:MNA.CAP An MNA error appears if someone gave a method a suspicious name. For example, if you write a method with the signature: public int hashcode() you could mean: public int hashCode() An MNA.CAP warning is reported for methods whose names start with a capital letter (the default convention for method names is not followed). Example 1 8 public class MNA_CAP_Sample_1 { 9 // method name starts with capital letter 10 public String Foo() { 11 return ""; 12 } 13 } MNA.CAP is reported for method declaration on line 10: Method name should start with non-capital letter 'Foo'. See also • → MNA.CNS • → MNA.SUS Language: English
    • Checkers:MNA.CNS 84 Checkers:MNA.CNS An MNA error appears if someone gave a method a suspicious name. For example, if you write a method with the signature: public int hashcode() you could mean: public int hashCode() An MNA.CNS warning is reported for methods whose names are the same as constructor names, but these methods are not constructors because they return values. Example 1 8 public class MNA_CNS_Sample_1 { 9 String name; 10 // constructor 11 public MNA_CNS_Sample_1() { 12 } 13 // this method has a constructor name, but not a constructor 14 public void MNA_CNS_Sample_1(String name) { 15 this.name = name; 16 } 17 } MNA.CNS is reported for method declaration on line 14: Suspicious method name 'MNA_CNS_Sample_1', same as constructor name but it is not a constructor because it has return type See also • → MNA.CAP • → MNA.SUS Language: English
    • Checkers:MNA.SUS 85 Checkers:MNA.SUS An MNA error appears if someone gave a method a suspicious name. For example, if you write a method with the signature: public int hashcode() you could mean: public int hashCode() An MNA.SUS warning is reported for methods whose names might contain a typing error. Example 1 8 public class MNA_SUS_Sample_1 { 9 // method name might contain a typing error 10 public String tostring() { 11 return "Some string"; 12 } 13 } MNA.SUS is reported for method declaration on line 10: Suspicious method name 'tostring', did you mean 'toString'? See also • → MNA.CAP • → MNA.CNS Language: English
    • Checkers:NPE.COND 86 Checkers:NPE.COND A NullPointerException is thrown in case of an attempt to dereference a null value. The dereference may be a function call, a read or write of a field, or an array access. An NPE.COND error is reported for a local variable being dereferenced if it was checked for null earlier, and the check confirmed that its value might be null. Example 1 15 static void printPoint(Point p) { 16 if (p == null) { 17 System.err.println("p is null"); 18 } 19 if (p.x < 0 || p.y < 0) { 20 System.out.println("Invalid point"); 21 return; 22 } 23 System.out.println(p); 24 } NPE.COND is reported for line 19 since 'p' is dereferenced there, and 'p' could be null due to the check on line 16. See also • → NPE.CONST • → NPE.RET • → NPE.RET.UTIL • → NPE.STAT Language: English
    • Checkers:NPE.CONST 87 Checkers:NPE.CONST A NullPointerException is thrown in case of an attempt to dereference a null value. The dereference may be a function call, a read or write of a field, or an array access. NPE.CONST is reported for an attempt to dereference a variable that was initialized with a null constant. Example 1 15 static String searchForMaxString(final String text) { 16 if (text == null) return null; 17 int max = 0; 18 StringTokenizer tok = new StringTokenizer(text, ":"); 19 String found = null; 20 while (tok.hasMoreTokens()) { 21 String x = tok.nextToken(); 22 if (x.length() >= max) { 23 max = x.length(); 24 found = x; 25 } 26 } 27 int len = found.length(); 28 System.err.println(len + " -> " + found); 29 return found; 30 } NPE.CONST is reported for line 27 since the null value was assigned to variable 'found' on line 19. See also • → NPE.COND • → NPE.RET • → NPE.RET.UTIL • → NPE.STAT Language: English
    • Checkers:NPE.RET 88 Checkers:NPE.RET A NullPointerException is thrown in case of an attempt to dereference a null value. The dereference may be a function call, a read or write of a field, or an array access. NPE.RET is reported for the result of a method call being dereferenced when there is a path on which the value coming from a method call returns null. Example 1 15 Reader getReader(String configurationPath) throws IOException { 16 File file = new File(configurationPath); 17 if (file.exists()) { 18 return new BufferedReader(new FileReader(file)); 19 } 20 return null; 21 } 22 23 24 Reader getDefaultReader() throws IOException { 25 return getReader("conf"); 26 } 27 28 public void init() throws IOException { 29 load(getDefaultReader()); 30 } 31 32 private String load(Reader reader) throws IOException { 33 StringBuffer sb = new StringBuffer(); 34 35 char[] buffer = new char[1024]; 36 int length; 37 while ((length = reader.read(buffer)) > 0) { 38 sb.append(buffer, 0, length); 39 } 40 return sb.toString(); 41 } NPE.RET is reported for line 30, since the value returned by 'getDefaultReader()' call can be null and it is passed into the 'load(Reader reader)' method as a parameter, where it would be dereferenced.
    • Checkers:NPE.RET 89 See also • → NPE.CONST • → NPE.COND • → NPE.RET.UTIL • → NPE.STAT Language: English
    • Checkers:NPE.RET.UTIL 90 Checkers:NPE.RET.UTIL A NullPointerException is thrown in case of an attempt to dereference a null value. The dereference may be a function call, a read or write of a field, or an array access. NPE.RET.UTIL is reported for the result of a method call from a class from the 'java.util' package being dereferenced, in case where this method was described in the knowledge base as the one which can return a null value. Example 1 17 private Map<String, String> paths = new HashMap<String, String>(); 18 19 public void addPath(String name, String path) { 20 paths.put(name, path); 21 } 22 23 private String getNormalizedPath(String name) throws IOException { 24 return paths.get(name).toLowerCase(); 25 } NPE.RET.UTIL is reported for line 24, since the value returned by 'paths.get(name)' call can be null. See also • → NPE.CONST • → NPE.COND • → NPE.RET • → NPE.STAT Language: English
    • Checkers:NPE.STAT 91 Checkers:NPE.STAT A NullPointerException is thrown in case of an attempt to dereference a null value. The dereference may be a function call, a read or write of a field, or an array access. NPE.STAT is reported for the result of a method call being dereferenced when the source code of the method is unavailable, but statistics indicate that it can return null. Statistics are gathered for the null checks applied to the values returned by methods. Example 1 22 public void printAbsoluteParentPath() { 23 final File parent = f.getParentFile(); 24 if (parent != null) { 25 String absolutePath = parent.getAbsolutePath(); 26 System.out.println("absolute path " + absolutePath); 27 } 28 } 29 30 public void printCanonicalParentPath() throws IOException { 31 final File parent = f.getParentFile(); 32 if (parent != null) { 33 String canonicalPath = parent.getCanonicalPath(); 34 System.out.println("canonical path: " + canonicalPath); 35 } 36 } 37 38 public void printParentPath() throws IOException { 39 String path = f.getParentFile().getPath(); 40 System.out.println("path " + path); 41 } NPE.STAT is reported for line 39, since the value returned by 'getParentFile()' is usually checked for null before dereferencing, so there is a possibility of an NPE here. See also • → NPE.CONST • → NPE.COND • → NPE.RET • → NPE.RET.UTIL Language: English
    • Checkers:REDUN.DEF 92 Checkers:REDUN.DEF A redundant operation is one that does not have any effect, such as: • an assignment of a variable to itself • use of an expression that will be evaluated to a constant such as a/a • use of an expression that can be reduced to one operand such as a & a. Even if this is not an error on its own, it may indicate a larger error in the code. A REDUND.DEF error indicates there is a redundant operation, in this case assignment of a variable to itself. Example 1 9 public void test() { 10 String s = "String"; 11 s = s; 12 } REDUN.DEF is reported for line 11: Assignment of 's' to itself Language: English
    • Checkers:REDUN.EQ 93 Checkers:REDUN.EQ A redundant operation is one that does not have any effect, such as • an assignment of a variable to itself • use of an expression that will be evaluated to a constant such as a/a • use of an expression that can be reduced to one operand such as a & a Even if this is not an error on its own, it may indicate a larger error in the code. A REDUN.EQ warning is reported for a suspicious call to equals() with the same object on both sides. Normally, equals() returns true to the same objects. Example 1 9 public int test() { 10 String s = "String"; 11 if (s.equals(s)) { 12 return 1; 13 } 14 return 0; 15 } REDUN.EQ is reported for line 11: Suspicious equals() called with 's' on both sides. Security Guidelines • CWE-571: Expression is Always True [8] Language: English
    • Checkers:REDUN.EQNULL 94 Checkers:REDUN.EQNULL A redundant operation is one that does not have any effect, such as • an assignment of a variable to itself • use of an expression that will be evaluated to a constant such as a/a • use of an expression that can be reduced to one operand such as a & a Even if this is not an error on its own, it may indicate a larger error in the code. A REDUN.EQNULL warning is reported for a suspicious call to equals() with null passed as a parameter. Normally, equals(null) returns false (object is never equal to null). Example 1 9 public int test() { 10 String s = "String"; 11 if (s.equals(null)) { 12 return 1; 13 } 14 return 0; 15 } REDUN.EQNULL is reported for line 11: Suspicious equals() called with 's' and null (never true). Security Guidelines • CWE-570: Expression is Always False [9] Language: English
    • Checkers:REDUN.FINAL 95 Checkers:REDUN.FINAL This issue is reported when a 'private' method is declared 'final'. Since private methods cannot be meaningfully overridden, declaring them final is redundant. Example 1 9 private final void foo() { 10 11 } REDUN.FINAL is reported for method declaration on line 9: Redundant 'final' modifier Language: English
    • Checkers:REDUN.NULL 96 Checkers:REDUN.NULL REDUN.NULL is reported when a variable that always has null value is used in an expression . Vulnerability and risk A programmer may forget to initialize the variable with its actual value or variable is redundant. Mitigation and prevention Use a null constant or initialize the variable properly. Example 1 10 String search(Collection<String> strings, String prefix) { 11 String res = null; 12 for (final String string : strings) { 13 if (string.startsWith(prefix)) { 14 return string; 15 } 16 } 17 return res; 18 } REDUN.NULL is reported for the snippet on line 17: variable 'res' is always null here. Language: English
    • Checkers:REDUN.OP 97 Checkers:REDUN.OP A redundant operation is one that does not have any effect, such as • an assignment of a variable to itself • use of an expression that will be evaluated to a constant such as a/a • use of an expression that can be reduced to one operand such as a & a. Even if this is not an error on its own, it may indicate a larger error in the code. A REDUN.OP error indicates there is a redundant operation such as a/a, a&a, a | a, a <a. Example 1 9 public int test() { 10 int var = 1; 11 if (var < var) { 12 return 1; 13 } 14 return 0; 15 } REDUN.OP is reported for line 11: Suspicious operation with 'var' on both sides Language: English
    • Checkers:RI.IGNOREDCALL 98 Checkers:RI.IGNOREDCALL An RI.IGNOREDCALL error appears if there is a call to a method for an immutable class. The method has side effects, and its result is not assigned to a variable (it is just ignored). This can happen because programming assumes a different API when a function modifies the value of its class. The methods that Klocwork looks for are: • any method of String class that returns String • method toString() from StringBuffer class • any method of InetAddress, BigInteger, BigDecimal classes • method digest(byte[]) from MessageDigest class • constructor of Thread class Vulnerability and risk Misunderstanding of method behavior will cause flaws in application logic. Mitigation and prevention Store the value return by the method, for example a=a.trim(). Example 1 13 public void write(String indent, Writer writer) { 14 String description = getDescription(); 15 if (description != null) 16 description.trim(); 17 // ... 18 // write it 19 } RI.IGNOREDCALL is reported for line 16: The value returned by 'java.lang.String.trim()' is ignored. Security Guidelines • CWE-391: Unchecked Error Condition [4] Language: English
    • Checkers:RI.IGNOREDNEW 99 Checkers:RI.IGNOREDNEW An RI.IGNOREDNEW warning appears when there is a call to a constructor method and the result of this method call is ignored. In some cases, it may cause an error (for example, Thread class, because user should start the thread after initialization). Vulnerability and risk Misunderstanding of method behavior will cause flaws in application logic. Mitigation and prevention Store the value return by the method, for example a=a.trim(). Example 1 9 public void runMyProcessing() { 10 Runnable myRunnable = new Runnable() { 11 public void run() { 12 // do actual processing... 13 } 14 }; 15 new Thread(myRunnable); // ignored! 16 } RI.IGNOREDNEW is reported for line 15: Newly created object of type 'java.lang.Thread' is ignored. Security Guidelines • CWE-391: Unchecked Error Condition [4] Language: English
    • Checkers:RLK.AWT 100 Checkers:RLK.AWT RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. Failing to properly dispose a resource can lead to such problems as: • too many files being open • an application not being able to access a temporary file when it is needed An RLK.AWT warning indicates that an AWT object is not disposed on exit. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 12 public void deleteAll(File[] files) { 13 for (final File file : files) { 14 ConfirmDialog confirmDialog = new ConfirmDialog(file); 15 confirmDialog.setVisible(true); 16 if (confirmDialog.isConfimed()) { 17 file.delete(); 18 } 19 } 20 } RLK.AWT is reported for the snippet on line 14: dialog 'confirmDialog' is not disposed after creation. Example 2 12 public void deleteAll(File[] files) { 13 for (final File file : files) { 14 ConfirmDialog confirmDialog = new ConfirmDialog(file); 15 try { 16 confirmDialog.setVisible(true); 17 if (confirmDialog.isConfimed()) { 18 file.delete(); 19 } 20 } finally { 21 confirmDialog.dispose(); 22 } 23 }
    • Checkers:RLK.AWT 101 The snippet from the previous section is fixed; RLK.AWT is not reported here. Language: English
    • Checkers:RLK.FIELD 102 Checkers:RLK.FIELD An RLK error indicates that a system resource was allocated and stored in a field, and there are no calls to methods that free this resource. The difference between RLK.FIELD and other RLK errors is that RLK.FIELD reports resources that are created and stored in a field (it is acceptable not to close the allocated resources immediately), and there are no methods where these resources are closed. Other RLK errors are reported for local variables (not fields). If a resource is not stored in a field, it should be closed after it is used. RLK.FIELD is reported only for private fields. Checkers with the prefix RLK.* are resource leak checkers. All knowledge base checkers use the same parameter types: sources and sinks. Sources are methods that allocate resources, for example new FileInputStream(). Sink methods dispose resources, for example "close". RLK.* errors may be reported for different resources: streams, SQL connections and SWT resources. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 13 class Logger { 14 private final PrintStream stream; 15 public Logger(String fileName) 16 throws FileNotFoundException { 17 if (fileName == null) stream = System.err; 18 else stream = new PrintStream(new FileOutputStream( 19 fileName)); 20 } 21 public void warning(String str) { 22 System.out.print("Warning: " + str + ".n"); 23 } 24 } RLK.FIELD is reported for field declaration on line 14: Possible leak of system resource 'java.io.PrintStream' stored in field 'stream'. Resource is not closed in any of the class methods.
    • Checkers:RLK.FIELD 103 Security Guidelines • CWE-404: Improper Resource Shutdown or Release [10] See also • → RLK.IN • → RLK.OUT Language: English
    • Checkers:RLK.HIBERNATE 104 Checkers:RLK.HIBERNATE RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. Failing to properly dispose a resource can lead to such problems as: • too many files being open • an application not being able to access a temporary file when it is needed An RLK.HIBERNATE warning indicates that a Hibernate object is not closed on exit. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 16 private SessionFactoryImplementor factory; 17 18 public void makePersistent(final Object[] keys) { 19 Session session = factory.openSession(); 20 session.beginTransaction(); 21 22 for (final Object key : keys) { 23 session.persist(key); 24 } 25 session.close(); 26 } RLK.HIBERNATE is reported for the snippet on line 19: 'session' is not disposed after creation. Example 2 16 private SessionFactoryImplementor factory; 17 18 public void makePersistent(final Object[] keys) { 19 Session session = factory.openSession(); 20 try { 21 session.beginTransaction(); 22 23 for (final Object key : keys) { 24 session.persist(key); 25 }
    • Checkers:RLK.HIBERNATE 105 26 } finally { 27 session.close(); 28 } 29 } The snippet from the previous section is fixed; RLK.HIBERNATE is not reported here. Language: English
    • Checkers:RLK.IMAGEIO 106 Checkers:RLK.IMAGEIO RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. Failing to properly dispose a resource can lead to such problems as: • too many files being open • an application not being able to access a temporary file when it is needed An RLK.IMAGEIO warning indicates that an ImageIO stream is not closed on exit. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 16 public int getBitOffset(final Object input) throws IOException { 17 ImageInputStream inputStream = ImageIO.createImageInputStream(input); 18 int bitOffset = inputStream.getBitOffset(); 19 return bitOffset; 20 } RLK.IMAGEIO is reported for the snippet on line 17: image input stream 'inputStream' is not disposed after creation. Example 2 16 public int getBitOffset(final Object input) throws IOException { 17 ImageInputStream inputStream = ImageIO.createImageInputStream(input); 18 try { 19 int bitOffset = inputStream.getBitOffset(); 20 return bitOffset; 21 } finally { 22 inputStream.close(); 23 } 24 } The snippet from the previous section is fixed; RLK.IMAGEIO is not reported here. Language: English
    • Checkers:RLK.IN 107 Checkers:RLK.IN RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. Failing to properly dispose a resource can lead to such problems as: • too many files being open • an application not being able to access a temporary file when it is needed RLK.IN indicates that an input stream that was opened is not explicitly closed. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 12 static final String propertyFile = "my_config.ini"; 13 14 static String getProperyFromConfigFile(String name) 15 throws IOException { 16 Properties prop = new Properties(); 17 FileInputStream st = new FileInputStream(propertyFile); 18 prop.load(st); 19 return prop.getProperty(name); 20 } RLK.IN is reported for the snippet on line 17: input stream 'st' is not closed after creation. Example 2 12 static final String propertyFile = "my_config.ini"; 13 14 static String getProperyFromConfigFile(String name) 15 throws IOException { 16 Properties prop = new Properties(); 17 FileInputStream st = new FileInputStream(propertyFile); 18 try { 19 prop.load(st); 20 } finally { 21 st.close(); 22 } 23 return prop.getProperty(name);
    • Checkers:RLK.IN 108 24 } The snippet from the previous section is fixed; RLK.IN is not reported here. Security Guidelines • CWE-404: Improper Resource Shutdown or Release [10] Language: English
    • Checkers:RLK.JNDI 109 Checkers:RLK.JNDI RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. Failing to properly dispose a resource can lead to such problems as: • too many files being open • an application not being able to access a temporary file when it is needed An RLK.JNDI warning indicates that a JNDI context is not closed on exit. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 25 public NamingEnumeration<SearchResult> search(final String providerURL, 26 final String name, 27 final String filter, 28 final SearchControls cons) { 29 try { 30 Hashtable environment = new Hashtable(); 31 environment.put(INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY); 32 environment.put(Context.PROVIDER_URL, providerURL); 33 environment.put(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION); 34 InitialLdapContext context = new InitialLdapContext(environment, null); 35 36 NamingEnumeration<SearchResult> result = context.search(name, filter, cons); // Resource allocated 37 return result; 38 } catch (NamingException e) { 39 System.err.println("LDAP search failed: " + e.getMessage()); 40 } 41 return null;
    • Checkers:RLK.JNDI 110 42 } RLK.JNDI is reported for the snippet on line 34: JNDI context 'context' is not closed on exit. Example 2 25 public NamingEnumeration<SearchResult> search(final String providerURL, 26 final String name, 27 final String filter, 28 final SearchControls cons) { 29 try { 30 Hashtable environment = new Hashtable(); 31 environment.put(INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY); 32 environment.put(Context.PROVIDER_URL, providerURL); 33 environment.put(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION); 34 35 InitialLdapContext context = new InitialLdapContext(environment, null); // Resource allocated 36 37 try { 38 NamingEnumeration<SearchResult> result = context.search(name, filter, cons); 39 return result; 40 } finally { 41 context.close(); // Resource released 42 } 43 } catch (NamingException e) { 44 System.err.println("LDAP search failed: " + e.getMessage()); 45 } 46 47 return null; 48 } The snippet from the previous section is fixed; RLK.JNDI is not reported here. Language: English
    • Checkers:RLK.MAIL 111 Checkers:RLK.MAIL RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. Failing to properly dispose a resource can lead to such problems as: • too many files being open • an application not being able to access a temporary file when it is needed An RLK.MAIL warning indicates that a Java mail object is not closed on exit. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 20 public void printQuotas(Session s, URLName name) { 21 try { 22 IMAPStore store = new IMAPStore(s, name); // Store created 23 final Quota[] quotas = store.getQuota("key"); 24 for (int i = 0; i < quotas.length; i++) { 25 final Quota quota = quotas[i]; 26 System.out.println("quota: " + quota); 27 } 28 } catch (MessagingException e) { 29 System.err.println("Was not able to get quota: " + e.getMessage()); 30 } 31 } RLK.MAIL is reported for the snippet on line 22: IMAPStore 'store' is not closed on exit. Language: English
    • Checkers:RLK.MICRO 112 Checkers:RLK.MICRO RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. Failing to properly dispose a resource can lead to such problems as: • too many files being open • an application not being able to access a temporary file when it is needed An RLK.MICRO warning indicates that a JavaME connection is not closed on exit. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 20 public byte[] getData(final String url) throws IOException { 21 ContentConnection connection = (ContentConnection) Connector.open(url); // Resource allocated 22 InputStream iStrm = connection.openInputStream(); 23 int length = (int) connection.getLength(); 24 if (length > 0) { 25 byte data[] = new byte[length]; 26 iStrm.read(data); 27 return data; 28 } 29 return EMPTY; 30 } RLK.MICRO is reported for the snippet on line 21: 'connection' is not closed on exit. Example 2 20 public byte[] getData(final String url) throws IOException { 21 ContentConnection connection = (ContentConnection) Connector.open(url); // Resource allocated 22 try { 23 InputStream iStrm = connection.openInputStream(); 24 int length = (int) connection.getLength(); 25 if (length > 0) { 26 byte data[] = new byte[length]; 27 iStrm.read(data);
    • Checkers:RLK.MICRO 113 28 return data; 29 } 30 return EMPTY; 31 } finally { 32 connection.close(); // Resource released 33 } 34 } The snippet from the previous section is fixed; RLK.MICRO is not reported here. Language: English
    • Checkers:RLK.NIO 114 Checkers:RLK.NIO RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. Failing to properly dispose a resource can lead to such problems as: • too many files being open • an application not being able to access a temporary file when it is needed An RLK.NIO warning indicates that a NIO object is not closed on exit. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 21 public void channelData(final FileInputStream stream, final byte[] data) { 22 try { 23 DatagramChannel ch = DatagramChannel.open(); // Resource allocated 24 ch.configureBlocking(true); 25 ByteBuffer packet = ByteBuffer.wrap(data); 26 ch.send(packet, dest); 27 ch.close(); 28 } catch (IOException e) { 29 System.err.println(e.getMessage()); 30 } 31 } RLK.NIO is reported for the snippet on line 23: DatagramChannel 'ch' is never disposed after it has been created. Example 2 21 public void channelData(final FileInputStream stream, final byte[] data) { 22 DatagramChannel ch = null; 23 try { 24 ch = DatagramChannel.open(); // Resource allocated 25 try { 26 ch.configureBlocking(true); 27 ByteBuffer packet = ByteBuffer.wrap(data);
    • Checkers:RLK.NIO 115 28 ch.send(packet, dest); 29 } finally { 30 ch.close(); // Resource released 31 } 32 } catch (IOException e) { 33 System.err.println(e.getMessage()); 34 } 35 } The snippet from the previous section is fixed; RLK.NIO is not reported here. Language: English
    • Checkers:RLK.OUT 116 Checkers:RLK.OUT RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. Failing to properly dispose a resource can lead to such problems as: • too many files being open • an application not being able to access a temporary file when it is needed RLK.OUT indicates that an output stream that was opened is not explicitly closed. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 11 public void printLines(String fName, Collection<String> lines) { 12 try { 13 File file = new File(fName); 14 PrintWriter pstr = new PrintWriter( 15 new BufferedOutputStream( 16 new FileOutputStream(file))); 17 for (final String line : lines) { 18 pstr.println(line); 19 } 20 } catch (IOException e) { 21 e.printStackTrace(); 22 } 23 } RLK.OUT is reported for the snippet on line 16: Output stream 'pstr' is not closed on exit. Example 2 11 public void printLines(String fName, Collection<String> lines) { 12 try { 13 File file = new File(fName); 14 PrintWriter pstr = new PrintWriter( 15 new BufferedOutputStream( 16 new FileOutputStream(file)));
    • Checkers:RLK.OUT 117 17 try { 18 for (final String line : lines) { 19 pstr.println(line); 20 } 21 } finally { 22 pstr.close(); 23 } 24 } catch (IOException e) { 25 e.printStackTrace(); 26 } 27 } The snippet from the previous section is fixed; RLK.OUT is not reported here. Security Guidelines • CWE-404: Improper Resource Shutdown or Release [10] Language: English
    • Checkers:RLK.SOCK 118 Checkers:RLK.SOCK RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. Failing to properly dispose a resource can lead to such problems as: • too many files being open • an application not being able to access a temporary file when it is needed An RLK.SOCK warning indicates that a Socket is not closed on exit. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 23 public void accept() throws IOException { 24 ServerSocket serverSocket = null; 25 try { 26 serverSocket = new ServerSocket(1034); 27 Socket socket = serverSocket.accept(); // socket created 28 final OutputStream outputStream = socket.getOutputStream(); 29 sendStatus(outputStream); 30 outputStream.close(); 31 } finally { 32 serverSocket.close(); 33 } 34 } RLK.SOCK is reported for the snippet on line 27: 'socket' created by 'serverSocket.accept()' call is not closed after creation. Example 2 23 public void accept() throws IOException { 24 ServerSocket serverSocket = null; 25 try { 26 serverSocket = new ServerSocket(1034); 27 Socket socket = serverSocket.accept(); // socket created
    • Checkers:RLK.SOCK 119 28 try { 29 final OutputStream outputStream = socket.getOutputStream(); 30 sendStatus(outputStream); 31 outputStream.close(); 32 } finally { 33 socket.close(); // socket closed 34 } 35 } finally { 36 serverSocket.close(); 37 } 38 } The snippet from the previous section is fixed; RLK.SOCK is not reported here. Language: English
    • Checkers:RLK.SQLCON 120 Checkers:RLK.SQLCON RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. Failing to properly dispose a resource can lead to such problems as: • too many files being open • an application not being able to access a temporary file when it is needed RLK.SQLCON indicates that an Sql connection is not closed on exit. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 13 public List<Integer> getActiveIDs() throws SQLException { 14 Connection con = DriverManager.getConnection("http://"); 15 Statement statement = con.createStatement(); 16 ResultSet rs = statement.executeQuery("SELECT * FROM table"); 17 18 final List<Integer> result = new ArrayList<Integer>(); 19 while (rs.next()) { 20 if (rs.getBoolean("active")) { 21 result.add(rs.getInt("id")); 22 } 23 } 24 return result; 25 } RLK.SQLCON is reported for the snippet on line 14: connection 'con' is not closed on exit.
    • Checkers:RLK.SQLCON 121 Security Guidelines • CWE-404: Improper Resource Shutdown or Release [10] See also • → RLK.SQLOBJ Language: English
    • Checkers:RLK.SQLOBJ 122 Checkers:RLK.SQLOBJ RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. Failing to properly dispose a resource can lead to such problems as: • too many files being open • an application not being able to access a temporary file when it is needed An RLK.SQLOBJ warning indicates that a Java SQL API object (other than an SQL connection) is not closed on exit. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 17 public void cleanUp(Connection con, int... ids) throws SQLException { 18 PreparedStatement statement = con.prepareStatement("delete from entity where id=?"); // Resource allocated 19 for (int id : ids) { 20 statement.setInt(1, id); 21 statement.executeUpdate(); 22 } 23 } RLK.SQLOBJ is reported for the snippet on line 18: Sql object 'statement' is not closed on exit. See also • → RLK.SQLCON Language: English
    • Checkers:RLK.SWT 123 Checkers:RLK.SWT RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. Failing to properly dispose a resource can lead to such problems as: • too many files being open • an application not being able to access a temporary file when it is needed An RLK.SWT warning indicates that an SWT object is not disposed on exit. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 15 public void printImage(String filename, GC gc, int x, int y) { 16 ImageData imageData = new ImageData(filename); 17 Image image = new Image(display, imageData); 18 gc.drawImage(image, x, y); 19 } RLK.SWT is reported for the snippet on line 17: 'image' is not disposed on exit. Security Guidelines • CWE-404: Improper Resource Shutdown or Release [10] Language: English
    • Checkers:RLK.ZIP 124 Checkers:RLK.ZIP RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. Failing to properly dispose a resource can lead to such problems as: • too many files being open • an application not being able to access a temporary file when it is needed An RLK.ZIP warning indicates that a ZipFile object is not disposed on exit. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 18 public static Collection<String> findDeprecated(final Properties properties) throws IOException { 19 final List<String> list = new ArrayList<String>(); 20 final ZipFile doczipFile = new ZipFile(properties.getProperty("doczip")); 21 22 final Enumeration<? extends ZipEntry> entries = doczipFile.entries(); 23 while (entries.hasMoreElements()) { 24 final ZipEntry entry = entries.nextElement(); 25 final String name = entry.getName(); 26 if (name.matches(".*_DEPRECATED_.*")) { 27 list.add(name); 28 } 29 } 30 31 return list; 32 } RLK.ZIP is reported for the snippet on line 20: Zip file 'doczipFile' is not closed on exit. Language: English
    • Checkers:RNU.THIS 125 Checkers:RNU.THIS An RNU.THIS error indicates comparing 'this' with null, but this cannot be null. Mitigation and prevention Remove redundant check. Example 1 12 public void doSomethingStrange() { 13 if (this == null) { 14 System.err.println("this == null!"); 15 } 16 } RNU.THIS will be reported at line 13. See also • → JD.RC.EXPR.CHECK • → JD.RC.EXPR.DEAD Security Guidelines • CWE-476: NULL Pointer Dereference [11] Language: English
    • Checkers:RR.IGNORED 126 Checkers:RR.IGNORED The "RR Value returned by read() or skip() is never checked" error appears when a code entity ignores the result of a read() or skip() method. In this case, another entity may need to read an array of bytes of some length. The array may not be available for reading. RR.IGNORED indicates that a value returned by read() or skip() is never checked. Example 1 14 void copyFile(String src, String dest) { 15 try { 16 File srcFile = new File(src); 17 File destFile = new File(dest); 18 FileInputStream fis = 19 new FileInputStream(srcFile); 20 FileOutputStream fos = 21 new FileOutputStream(destFile); 22 byte bytes[] = new byte[1024]; 23 fis.read(bytes); 24 fos.write(bytes, 0, bytes.length); 25 fis.close(); 26 fos.close(); 27 } catch (IOException e) { 28 e.printStackTrace(); 29 } 30 } RR.IGNORED is reported for 'read' call on line 23: The value returned by 'java.io.FileInputStream.read'() method is ignored. Security Guidelines • CWE-391: Unchecked Error Condition [4] Language: English
    • Checkers:RTC.CALL 127 Checkers:RTC.CALL The Redundant Type Cast (RTC) warning appears when one adds cast to some class while invoking a method which is defined in a more general class. An example is below: public class Apple { public String someAppleToString(Object o) { return ((Apple) o).toString(); } } In this example, a type-cast to Apple is redundant, because Apple class does not redefine toString() method and Object's method is actually used. The RTC.CALL warning appears when one adds cast to some class while invoking a method which is defined in a more general class. Example 1 9 public class Instruction { 10 } 11 public class JmpInstruction extends Instruction { 12 private final Number address; 13 protected JmpInstruction(Number address) { 14 this.address = address; 15 } 16 public Number getAddress() { 17 return address; 18 } 19 } 20 public class ShortJmpInstruction extends JmpInstruction { 21 public ShortJmpInstruction(Byte address) { 22 super(address); 23 } 24 } 25 // ... 26 public void visitInstruction(JmpInstruction i) { 27 if (i instanceof ShortJmpInstruction) { 28 // cast is not necessary here 29 Number address = 30 ((ShortJmpInstruction) i).getAddress(); 31 print(address); 32 } 33 // then visit other instrucrions.. 34 } RTC.CALL is reported for line 30: Type cast from 'com.klocwork.jdefects.checkers.ast.samples.RTC_CALL_Sample_1$JmpInstruction' to 'com.klocwork.jdefects.checkers.ast.samples.RTC_CALL_Sample_1$ShortJmpInstruction' is redundant because method 'getAddress' is defined in
    • Checkers:RTC.CALL 128 'com.klocwork.jdefects.checkers.ast.samples.RTC_CALL_Sample_1$JmpInstruction' Language: English
    • Checkers:STRCON.LOOP 129 Checkers:STRCON.LOOP Using string concatenation in a loop wastes time and memory. Use StringBuffer instead. Example 1 9 public String test1(int n, String x) { 10 String res = ""; 11 for (int i = 0; i < n; i++) { 12 res+=x; 13 } 14 return res; 15 } 16 // fixed code 17 public String test2(int n, String x) { 18 StringBuffer res = new StringBuffer(); 19 for (int i = 0; i < n; i++) { 20 res.append(x); 21 } 22 return res.toString(); 23 } STRCON.LOOP is reported for line 12: Using append for string 'res' in a loop Language: English
    • Checkers:SV.CLEXT.CLLOADER 130 Checkers:SV.CLEXT.CLLOADER SV.CLEXT.CLLOADER occurs when a class extends java.lang.ClassLoader. The error is not applicable to interfaces. Vulnerability and risk Allowing implementations of Classloader could lead to a security and/or permissions breach. Mitigation and prevention Do not extend ClassLoader. If you must extend ClassLoader, it is better to use SecureClassLoader. Example 1 8 public class SV_CLEXT_CLLOADER_Sample_1 extends ClassLoader { 9 } SV.CLEXT.CLLOADER is reported for class declaration on line 8: Class 'com.klocwork.jdefects.checkers.ast.samples.SV_CLEXT_CLLOADER_Sample_1' extends 'java.lang.ClassLoader'. Language: English
    • Checkers:SV.CLEXT.POLICY 131 Checkers:SV.CLEXT.POLICY Code inspection rule. SV.CLEXT.POLICY occurs when a class extends java.security.Policy. Vulnerability and risk Allowing implementations of 'java.security.Policy' could lead to a security and/or permissions breach. Mitigation and prevention Avoid extending java.security.Policy. Example 1 13 class MyPolicy extends Policy { 14 // example end 15 public PermissionCollection getPermissions(CodeSource codesource) { 16 return null; 17 } 18 public void refresh() { 19 } 20 } SV.CLEXT.POLICY is reported for class declaration on line 13: Class 'com.klocwork.jdefects.checkers.ast.samples.SV_CLEXT_POLICY_Sample_1$MyPolicy' extends 'java.security.Policy'. Language: English
    • Checkers:SV.CLLOADER 132 Checkers:SV.CLLOADER This error appears when the program attempts to load classes by means of the classloader. Vulnerability and risk Loading classed directly using a custom classloader can allow malicious code into the system. Mitigation and prevention Use a known secure classloader. Example 1 10 public void loadMyClass(String maliciousClass) { 11 ClassLoader cLoader = ClassLoader 12 .getSystemClassLoader(); 13 try { 14 cLoader.loadClass(maliciousClass); 15 } catch (ClassNotFoundException e) { 16 // TODO Auto-generated catch block 17 e.printStackTrace(); 18 } 19 } SV.CLLOADER is reported for call on line 14: Classloader is used directly 'loadClass' Language: English
    • Checkers:SV.CLONE.SUP 133 Checkers:SV.CLONE.SUP This error appears when class defines clone method which calls super.clone() but it does not implement Cloneable interface. Vulnerability and risk If object does not implement Cloneable Object.clone() method would throw an Exception, which is probably not the intended behavior in this case. Mitigation and prevention If the intention was to throw an exception, define the following clone method: public final Object clone() throws CloneNotSupportedException { throw CloneNotSupportedException(); } If intention was to define a proper clone method, the class must implement a Cloneable interface. Example 1 8 public class SV_CLONE_SUP_Sample_1 { 9 private String password; 10 protected SV_CLONE_SUP_Sample_1(String x) { 11 password = x; 12 } 13 protected String getPassword() { 14 return password; 15 } 16 protected final Object clone() 17 throws CloneNotSupportedException { 18 return super.clone(); 19 } 20 } SV.CLONE.SUP is reported for class declaration on line 18: Class 'com.klocwork.jdefects.checkers.ast.samples.SV_CLONE_SUP_Sample_1' implements 'clone' method but does not implement Cloneable, which makes Object clone implementation throw an exception
    • Checkers:SV.CLONE.SUP 134 Security Guidelines • CWE-580: clone() Method Without super.clone() [12] Language: English
    • Checkers:SV.DATA.BOUND 135 Checkers:SV.DATA.BOUND This error occurs when unvalidated user data is stored in semi-trusted storage such as session attributes. Vulnerability and risk A source such as getParameter() is always considered to be tainted, and users must do server validation for it. Server validation involves reading data read from other structures, such as session attributes or the database, considered to be safe. By storing unchecked user data in such structures, you risk allowing other vulnerabilities to occur. Mitigation and prevention Validate user data before you enter it into a trusted source, such as a database or session attributes. Example 1 15 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 16 String name = req.getParameter("userName"); 17 HttpSession sess = req.getSession(); 18 sess.setAttribute("user", name); 19 } SV.DATA.BOUND is reported for line 18: unvalidated user input stored in 'name' on line 16 is stored in the HTTP session on line 18. Security Guidelines • CWE-501:Trust Boundary Violation [13] Language: English
    • Checkers:SV.DATA.DB 136 Checkers:SV.DATA.DB This error detects the insertion of unvalidated user data into SQL database queries. This data is stored in the database directly from user input and could contain malicious content. If the data is later used in other SQL statements, then an SQL injection vulnerability also exists. If the data is later used as output to the web interface, a cross-site scripting vulnerability also exists. Vulnerability and risk A data injection vulnerability opens up an application to the storage of malicious content. The vulnerability exists when user input is stored directly, unchecked, into the application's database. This data could contain malicious HTML content, SQL statements, manipulated paths, etc., that could later be used in the application. For example, a data injection can lead to a cross-site scripting vulnerability if this data is reflected back to the web interface. Mitigation and prevention The prevention of data injection flaws can be achieved by validating any and all input from outside the application (user input, file input, system parameters, etc.). Validation should include length and content. All data stored in the database should include a lexical check for a particular type, such as user name. Typically only alphanumeric characters are needed (i.e., A-Za-z, 0-9). Any other accepted characters should be escaped. This validation should be done at each source of data, such as when each parameter is read from the HTTP request. Additionally, it may be advisable to check all strings used in SQL statements before their use. Example 1 12 public void setUserLastName(ServletRequest req, Connection con) throws SQLException { 13 // Source of data from HTTP request in servlet 14 String lastName = req.getParameter("lastName"); 15 int userId = Integer.parseInt(req.getParameter("userId")); 16 17 String query = "UPDATE userData INTO lastName=? WHERE userid = ?"; 18 PreparedStatement statement = con.prepareStatement(query); 19 statement.setString(1, lastName); 20 statement.setInt(2, userId); 21 statement.executeUpdate(); 22 } SV.DATA.DB is reported for line 21: 'lastName' contains a value coming from an HTTP request and thus can be tainted (line 14). On line 19 tainted 'lastName' is used to create an SQL statement 'statement', which is executed on line 21.
    • Checkers:SV.DATA.DB 137 Security Guidelines • CWE-89: Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection') [15] • CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting') [14] Language: English
    • Checkers:SV.DOS.ARRINDEX 138 Checkers:SV.DOS.ARRINDEX This error occurs when unvalidated user input is used as the index of an array or by methods that will use it as the index of an array. Vulnerability and risk When unvalidated user input is used as the index of an array or by methods that will use it as the index of an array, an attack can cause the methods to throw an ArrayOutOfBounds exception. This can then be used to cause Denial of Service or to manipulate the stated object to create an alternate control flow, which could be used to the advantage of the attacker. For example, if an error is printed, it might leak some information to the attacker. If an error occurred during authentication, it could create open-on-fail conditions, allowing the attacker to get an unauthorized session. Mitigation and prevention To prevent denial of service attacks from user input, validate any and all input from outside the application (user input, file input, system parameters, and so on). Validation should include bounds validation using information from an appropriate, accessible container. Example 1 16 protected synchronized void doPost(HttpServletRequest req, HttpServletResponse resp) 17 throws ServletException, IOException { 18 String indexString = req.getParameter("index"); 19 final int index; 20 try { 21 index = Integer.parseInt(indexString); 22 } catch (NumberFormatException e) { 23 resp.sendError(505, "Internal Error"); 24 return; 25 } 26 27 String key = data[index]; 28 resp.getOutputStream().println("Success! " + key); 29 } SV.DOS.ARRINDEX is reported for line 27: 'indexString' contains a value coming from an HTTP request and thus can be tainted (line 18). On line 21 tainted 'indexString' is parsed and stored in 'index' which is used to access an array element on line 27. A potential attacker can specify a large number, leading to an ArrayOutOfBounds exception, which can damage the state of the application and lead to a denial of service (DOS) attack.
    • Checkers:SV.DOS.ARRINDEX 139 Security Guidelines • CWE-129: Improper Validation of Array Index [16] Language: English
    • Checkers:SV.DOS.ARRSIZE 140 Checkers:SV.DOS.ARRSIZE This error is detected when unvalidated user input is used as an array size or in methods that will use it as an array size. Vulnerability and risk The use of data from outside the application must be validated before use by the application. If this data is used to allocate arrays of objects in the application, the content of the data must be closely checked. Attackers can exploit this vulnerability to force the application to allocate very large numbers of objects, leading to high resource usage on the application server and the potential for a denial of service condition. Mitigation and prevention The prevention of denial of service attacks from user input can be achieved by validating any and all input from outside the application (user input, file input, system parameters, etc.). Validation should include length and content. Ideally, sizes for objects should not come from untrusted user sources such as parameters. This validation should be done at each source of data, such as when each parameter is read from the HTTP request. Data used for allocation should also be checked for reasonable values, assuming that user input could contain very small or vary large values. Example 1 14 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, 15 IOException { 16 String size = req.getParameter("size"); 17 final int value; 18 try { 19 value = Integer.parseInt(size); 20 } catch (NumberFormatException e) { 21 resp.sendError(505, "Internal Error"); 22 return; 23 } 24 String arr[] = new String[value]; 25 for (int i = 0; i < arr.length; i++) { 26 arr[i] = req.getParameter("field" + i); 27 } 28 // ... 29 } SV.DOS.ARRSIZE is reported for line 24: 'size' contains a string coming from an HTTP request and thus can be tainted (line 16). On line 19 tainted 'size' string is parsed and the result is stored in 'value', which is used on line 24 for array allocation. This leads to a potential denial of service (DOS) attack: an attacker can specify a large number, leading to high resource usage on the server.
    • Checkers:SV.DOS.ARRSIZE 141 Security Guidelines • CWE-130: Improper Handling of Length Parameter Inconsistency [17] Language: English
    • Checkers:SV.DOS.TMPFILEDEL 142 Checkers:SV.DOS.TMPFILEDEL This error occurs when a temporary file is scheduled to be deleted on exit but is not explicitly deleted. This error mostly presents a problem in a server or servlet context. Vulnerability and risk Temporary files should be deleted as soon as possible. If a file contains sensitive information, the longer it exists, the better chance an attacker has to gain access to its contents. Also, because directories typically have limits on the number of files allowed, it is possible to overflow the number of temporary files, leading to a denial of service problem. Mitigation and prevention Temporary files should be deleted immediately after use. Example 1 17 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 18 String name = req.getParameter("userName"); 19 File file = File.createTempFile("file", ".dat"); 20 file.deleteOnExit(); 21 fillWithUserData(name); 22 char[] data = readData(file); 23 resp.getWriter().print(data); 24 } SV.DOS.TMPFILEDEL is reported for line 19: File 'file' scheduled for 'delete on exit', meaning that it will remain for the lifetime of the jvm (which can be very long in the case of a server or servlet). Server-side applications should remove files explicitly. Security Guidelines • CWE-459: Incomplete Cleanup [18] Language: English
    • Checkers:SV.DOS.TMPFILEEXIT 143 Checkers:SV.DOS.TMPFILEEXIT This error appears when a temporary file is created and not scheduled to be deleted on exit or after use. Vulnerability and risk If a temporary file contains sensitive information, an attacker could get access to this information after the application exits. Moreover, a web application could cause resource exhaustion, because the application could run out of temporary file names, or the directory might not be able to hold all the files. Mitigation and prevention Temporary files should be deleted immediately after use. At the very least, mark all temporary files deleteOnExit. Example 1 17 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 18 String name = req.getParameter("userName"); 19 File file = File.createTempFile("file", ".dat"); 20 fillWithUserData(name); 21 char[] data = readData(file); 22 resp.getWriter().print(data); 23 } SV.DOS.TMPFILEEXIT is reported for line 19: File 'file' is a temporary file, but it is not deleted on exit. Security Guidelines • CWE-459: Incomplete Cleanup [18] Language: English
    • Checkers:SV.EMAIL 144 Checkers:SV.EMAIL This error is detected when unchecked user input is used for email addresses or other parts of emails. Vulnerability and risk Email addresses are a very common input field for web applications. In some cases these email addresses are used by the application to send email to users or to display email addresses on the web site. Email addresses, like all other user input, are vulnerable to attack via malicious content. For example, an application may send email to a user by invoking the sendmail command directly, using the e-mail string stored for the user. This string, if used unchecked, can contain arbitrary commands that would be run along with sendmail on the application host (thus causing a command injection vulnerability). Also, malicious users can use your web server to send "spam" emails or emails with unwanted content. Mitigation and prevention Prevent e-mail injection attacks from user input by validating any and all input from outside the application (user input, file input, system parameters, etc.). Validation should include length and content. Typically only alphanumeric characters are needed (i.e., A-Za-z, 0-9), but for e-mail addresses '@' and possibly underscores would be acceptable. Any other accepted characters should be escaped. Perform validation at each source of data, such as when each parameter is read from the HTTP request. Example 1 22 protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { 23 try { 24 // Get system properties 25 Properties props = System.getProperties(); 26 // Setup mail server 27 props.put("mail.smtp.host", "my.company.com"); 28 // Get session 29 Session session = Session.getDefaultInstance(props, null); 30 // Define message 31 MimeMessage message = new MimeMessage(session); 32 message.setFrom(new InternetAddress("admin@my.company.com")); 33 final String email = req.getParameter("email"); 34 Address addr = new InternetAddress(email); 35 message.setRecipient(Message.RecipientType.TO, addr); 36 message.setSubject(subject); 37 message.setText(text); 38 // Send message 39 Transport.send(message); 40 } catch (AddressException e) { 41 throw new ServletException(e); 42 } catch (MessagingException e) {
    • Checkers:SV.EMAIL 145 43 throw new ServletException(e); 44 } 45 } SV.EMAIL is reported for line 35: unvalidated user input is stored in 'email' (line 33), which is used to create address object 'addr' (line 34) that is then used as a recipient's address on line 35. Security Guidelines • CWE-472: External Control of Assumed-Immutable Web Parameter [19] Language: English
    • Checkers:SV.EXEC 146 Checkers:SV.EXEC This error is detected when user input is used, unchecked, for all or part of an operating system command executed by the application. Vulnerability and risk In general, process creation or execution of external commands within an application is a security concern. There is a serious vulnerability if user input is used in any part of the command string used for execution. Attackers can inject additional commands and have them executed on the application server, leading to a process or command injection condition. The ability to run arbitrary commands can lead to denial of service, data corruption, data security violations and other risks. Mitigation and prevention Prevent process or command injection attacks from user input by validating any and all input from outside the application (user input, file input, system parameters, etc.). Validation should include length and content. Ideally you should avoid using user data in process creation commands. Any other accepted characters should be escaped. Perform validation at each source of data, such as when each parameter is read from the HTTP request, or user interface such as an application or the console. Example 1 11 public void checkHost(ServletRequest req) throws IOException { 12 // Source of data from HTTP request in servlet 13 String hostName = req.getParameter("userHostName"); 14 String command = "nslookup " + hostName; 15 Process proc = Runtime.getRuntime().exec(command); 16 // ... 17 } SV.EXEC is reported for line 15: 'hostName' contains data coming from an HTTP request parameter and might be tainted (line 13). This value is concatenated with a constant string and stored in 'command' on line 14. The 'command' is executed as a shell command on line 15, thus the host system is vulnerable to dangerous commands executed by attackers. Security Guidelines • CWE-77: Improper Sanitization of Special Elements used in a Command ('Command Injection') [20] Language: English
    • Checkers:SV.EXEC.DIR 147 Checkers:SV.EXEC.DIR This error is detected when user input is used, unchecked, for all or part of a working directory used to select a command executed by the application. Vulnerability and risk In general, process creation or execution of external commands within an application is a security concern. This particular vulnerability occurs when all or part of the working directory used for the command or process is derived from unvalidated user input. An attacker can manipulate the working directory and cause undesired behavior, possibly running commands planted by the attacker rather than the intended command. Mitigation and prevention Prevent process or command injection attacks from user input by validating any and all input from outside the application (user input, file input, system parameters, etc.). Validation should include length and content. Typically only alphanumeric characters are needed (i.e., A-Za-z, 0-9). Any other accepted characters should be escaped. Perform validation at each source of data, such as when each parameter is read from the HTTP request, or user interface such as an application or the console. Example 1 15 public void dataQuery(ServletRequest req) throws IOException { 16 String var = req.getParameter("user_name"); 17 File userRoot = new File(webRoot, var); 18 Process proc = Runtime.getRuntime().exec("processRequest", null, userRoot); 19 // parse results of command 20 // ... 21 } SV.EXEC.DIR is reported for line 18: 'var' contains data coming from an HTTP request parameter and might be tainted (line 13). This value is used to create an object of type 'java.io.File' on line 17, which is later used as the working directory for the process being executed on line 18. Security Guidelines • CWE-77: Improper Sanitization of Special Elements used in a Command ('Command Injection') [20] Language: English
    • Checkers:SV.EXEC.ENV 148 Checkers:SV.EXEC.ENV This error is detected when user input is used, unchecked, for all or part of an environment variable used by the application. Vulnerability and risk In general, process creation or execution of external commands within an application is a security concern. There is a serious vulnerability if user input is used in any part of the command string used for execution. Attackers can change environment variables, leading to denial of service, data corruption, data security violations and other risks. Mitigation and prevention Prevent process or command injection attacks from user input by validating any and all input from outside the application (user input, file input, system parameters, etc.). Validation should include length and content. Typically only alphanumeric characters are needed (i.e., A-Za-z, 0-9). Any other accepted characters should be escaped. Perform validation at each source of data, such as when each parameter is read from the HTTP request, or user interface such as an application or the console. Example 1 11 public void dataQuery(ServletRequest req) throws IOException { 12 String var = "USER_HOME=" + req.getParameter("user_name"); 13 String[] env = new String[]{var}; 14 Process proc = Runtime.getRuntime().exec("processRequest", env); 15 // parse results of command 16 // ... 17 } SV.EXEC.ENV is reported for line 14: 'var' contains data coming from an HTTP request parameter and might be tainted (line 12). This value is stored in string array 'env' on line 13 which is used as a parameter for process execution on line 14. An attacker may change environment variables to modify application behavior. Security Guidelines • CWE-454: External Initialization of Trusted Variables [21] Language: English
    • Checkers:SV.EXPOSE.FIELD 149 Checkers:SV.EXPOSE.FIELD This error is detected when a static field in a class is not defined as final. Vulnerability and risk Because applets can persist after the Web browser leaves the page that contains them, it becomes important to protect applets from each other. Otherwise, an attacker's applet could deliberately sabotage a third party's applet. In many environments, it would be unacceptable for an applet to even learn of the existence of another applet. In Netscape Navigator 3.0, AppletContext.getApplets() is careful to return handles only to applets on the same Web page as the caller. However, an applet could easily get a handle to the top-level ThreadGroup and then enumerate every thread running in the system, including threads belonging to other arbitrary applets. The Java runtime encodes the applet's class name in its thread name, so a rogue applet can now learn the names of all applets running in the system. In addition, an applet could call the stop() or setPriority() methods on threads in other applets. The SecurityManager checked only that applets could not alter the state of system threads; there were no restraints on applets altering other applet threads. Netscape Navigator 4.0 prevents an attacker from seeing threads belonging to applets on other Web pages, in the same way it protects applets. Internet Explorer allows an applet to see those threads, but calls to stop() or setPriority() have no effect. An insidious form of this attack involves a malicious applet that lies dormant except when a particular victim applet is resident. When the victim applet is running, the malicious applet randomly mixes degradation of service attacks with attacks on the victim applet's threads. The result is that the user sees the victim applet as slow and buggy. The attacker applet can use security vulnerabilities to modify the internal state of the victim applet, so it is important to keep the visibility of methods and fields as low as possible, avoid static fields, and use 'final' as much as possible. Mitigation and prevention Make non-final public or protected static fields final. Example 1 9 public static boolean debug; SV.EXPOSE.FIELD is reported for line 9: Non-final public or protected static field 'debug' could be changed by malicious code or by accident from another package. Security Guidelines • CWE-493: Critical Public Variable Without Final Modifier [22] Language: English
    • Checkers:SV.EXPOSE.FIN 150 Checkers:SV.EXPOSE.FIN This error is detected when a class has a public finalize() method. Vulnerability and risk Because applets can persist after the Web browser leaves the page that contains them, it becomes important to protect applets from each other. Otherwise, an attacker's applet could deliberately sabotage a third party's applet. In many environments, it would be unacceptable for an applet to even learn of the existence of another applet. In Netscape Navigator 3.0, AppletContext.getApplets() is careful to return handles only to applets on the same Web page as the caller. However, an applet could easily get a handle to the top-level ThreadGroup and then enumerate every thread running in the system, including threads belonging to other arbitrary applets. The Java runtime encodes the applet's class name in its thread name, so a rogue applet can now learn the names of all applets running in the system. In addition, an applet could call the stop() or setPriority() methods on threads in other applets. The SecurityManager checked only that applets could not alter the state of system threads; there were no restraints on applets altering other applet threads. Netscape Navigator 4.0 prevents an attacker from seeing threads belonging to applets on other Web pages, in the same way it protects applets. Internet Explorer allows an applet to see those threads, but calls to stop() or setPriority() have no effect. An insidious form of this attack involves a malicious applet that lies dormant except when a particular victim applet is resident. When the victim applet is running, the malicious applet randomly mixes degradation of service attacks with attacks on the victim applet's threads. The result is that the user sees the victim applet as slow and buggy. Attacker applet can use security vulnerabilities to modify internal state of victim applet, so it is important to keep visibility of methods and field as low as possible, avoid static fields and use final as much as possible. Mitigation and prevention This vulnerability can be mitigated by making all finalize() methods protected. Example 1 10 public void finalize() throws Throwable { 11 try { 12 close(); // close open files 13 } finally { 14 super.finalize(); 15 } 16 } SV.EXPOSE.FIN is reported for line 10: Method finalize() should have protected access modifier, not public.
    • Checkers:SV.EXPOSE.FIN 151 Security Guidelines • CWE-583: finalize() Method Declared Public [23] Language: English
    • Checkers:SV.EXPOSE.IFIELD 152 Checkers:SV.EXPOSE.IFIELD This warning is reported for non-final public or protected non-static fields. Vulnerability and risk These fields might be changed by malicious code from another package. Mitigation and prevention To fix the problem, make the fields final (if possible) or private/package protected. Example 1 8 public class SV_EXPOSE_IFIELD_Sample_1 { 9 public boolean debug; 10 // ... 11 } SV.EXPOSE.IFIELD is reported for field declaration on line 9: Non-final public instance field 'debug' could be changed by malicious code or by accident. See also • → SV.EXPOSE.FIELD Language: English
    • Checkers:SV.EXPOSE.MUTABLEFIELD 153 Checkers:SV.EXPOSE.MUTABLEFIELD This error is detected when a class contains a public, static, final field that references a mutable object. Vulnerability and risk See → SV.EXPOSE.FIN. Mitigation and prevention This vulnerability can be mitigated by removing references to mutable objects from the public interface of each class, using immutable object instead or avoid using static fields. Example 1 10 final public static String adminUsers[] = new String[]{"root","toor"}; 11 12 // ... 13 void maliciousUserCode() { 14 adminUsers[1]="myself"; 15 } SV.EXPOSE.MUTABLEFIELD is reported for line 10: Public or protected static final field 'adminUsers' references a mutable object of type 'java.lang.String[]'. This object could be changed by malicious code or by accident from another package Language: English
    • Checkers:SV.EXPOSE.RET 154 Checkers:SV.EXPOSE.RET This error is detected when a method returns a reference to a mutable object. Vulnerability and risk See SV.EXPOSE.FIN. Mitigation and prevention This vulnerability can be mitigated by preventing public methods from returning references to mutable objects. Example 1 17 private ArrayList adminUsers; 18 public Collection getAdminUsers() { 19 return adminUsers; 20 } 21 // ... 22 void maliciousUserCode() { 23 getAdminUsers().add("myself"); 24 } SV.EXPOSE.RET is reported for 'return' statement on line 19: Method returns reference to mutable object 'adminUsers'. Internal state of object can be modified by malicious user. Security Guidelines • CWE-374: Mutable Objects Passed by Reference [24] Language: English
    • Checkers:SV.EXPOSE.STORE 155 Checkers:SV.EXPOSE.STORE This error is detected when a public method stores a reference to a mutable object. Vulnerability and risk Malicious applet can modify internal state of object by modifying result that returned. Mitigation and prevention This vulnerability can be prevented by not storing references to mutable objects in public methods, using immutable object instead or avoid using static fields. Example 1 18 private Collection users; 19 public void setUsers(Collection users) throws AuthorizationException { 20 for (Iterator iter = users.iterator(); iter.hasNext();) { 21 String user = (String) iter.next(); 22 if (!authorized(user)) throw new AuthorizationException(); 23 24 } 25 this.users = users; 26 } 27 // ... 28 void maliciousUserCode() throws AuthorizationException { 29 Collection myUsers = new ArrayList(); 30 myUsers.add("goodUser"); 31 setUsers(myUsers); 32 myUsers.add("anotherUser"); 33 } SV.EXPOSE.STORE is reported for line 26: Method stores reference to mutable object 'users'. Internal state of object can be modified by malicious user. Security Guidelines • CWE-374: Mutable Objects Passed by Reference [24] Language: English
    • Checkers:SV.HTTP SPLIT 156 Checkers:SV.HTTP SPLIT This error is reported when a value from an HTTP client or database appears, without validation, in a method that writes to an HTTP header. The SV.XSS.* checkers cover similar attacks. Vulnerability and risk "HTTP Response Splitting" is a technique for attacking applications. It enables various new attacks such as web cache poisoning, cross-user defacement, hijacking pages with sensitive user information and cross-site scripting (XSS). This attack technique, and the attacks that are derived from it, can happen in most web environments and result from an application not rejecting illegal user input such as malicious or unexpected characters. The essence of HTTP Response Splitting is the attacker's ability to send a single HTTP request that forces the web server to form an output stream, which is then interpreted by the target as two HTTP responses instead of the normal single response. The first response may be partially controlled by the attacker, but this is less important. What is more important is that the attacker completely controls the form of the second response (header). Once this is possible, the attacker can complete the attack by sending two requests through the target. The first one invokes two responses from the web server, and the second request would typically be to some innocent resource on the web server. However, the second request would be matched, by the target, to the second HTTP response, which is fully controlled by the attacker. The attacker therefore tricks the target into believing that a particular resource on the web server (designated by the second request) is the server's HTTP response (server content), while it is in fact data forged by the attacker through the web server -- this is the second response. Mitigation and prevention Validate all input data, even when coming from a semi-trusted source such as a database. Especially check for a Carriage Return followed by a Line Feed (CRLF) combination. Example 1 15 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 16 String url = req.getParameter("HIDDEN_URL"); 17 if (url.length() == 0) { 18 generatePage(req, resp); 19 } else { 20 resp.sendRedirect(url); 21 } 22 } 23 24 private void generatePage(HttpServletRequest req, HttpServletResponse resp) throws IOException { 25 PrintWriter wr = resp.getWriter(); 26 wr.print("Hello, World!"); 27 } SV.HTTP_SPLIT is reported for line 20: 'url' contains data coming from an HTTP request parameter and might be tainted (line 16). This value is used to send an HTTP redirect on line 20.
    • Checkers:SV.HTTP SPLIT 157 Security Guidelines • CWE-113: Failure to Sanitize CRLF Sequences in HTTP Headers ('HTTP Response Splitting') [25] Language: English
    • Checkers:SV.IL.DEV 158 Checkers:SV.IL.DEV This error is detected when an application reveals design information to the web interface of the application. Vulnerability and risk Revealing details about an application's implementation is a security issue because it provides attackers with information they can use to further their attacks. Details such as class, file or path names reveal information to the attacker that can be used to attempt other attacks. For example, revealing path information in a message to the web interface may reveal the location of the web server's directory hierarchy. An attacker could use this information in a path injection attack. In general, the amount of information revealed to the web interface should be minimized, and design details in particular should not be revealed. Mitigation and prevention Design information leakage can be prevented by removing information from messages sent to the web interface for the application. General users of the application are likely not going to need such information, and attackers can gain information that can be used for further attacks. A common case of disclosure of design information occurs in Java exception-handling. Exception information is useful during programming, but dangerous after release. Be very careful of displaying or sending exception information, and make sure users never see such information. All stack traces and debug information should be stored in server logs in places where attackers cannot read it. Example 1 15 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 16 String name = req.getParameter("userName"); 17 File file = new File(System.getProperty("web.root"), name + ".dat"); 18 try { 19 FileOutputStream str = new FileOutputStream(file); 20 // ... 21 str.close(); 22 } catch (IOException e) { 23 throw new ServletException("Cannot open file " + file + ":" + e.getMessage()); 24 } 25 } SV.IL.DEV is reported for line 23: 'name' is initialized with a value of an HTTP request parameter and might be tainted (line 16). This value is used to create 'file' on line 17. If an exception is thrown on line 19, 'file' would be wrapped into ServletException, thus revelaing the value of an http request parameter to the web interface. Design information leakage can reveal important clues to attackers.
    • Checkers:SV.IL.DEV 159 Security Guidelines • CWE-497: Exposure of System Data to an Unauthorized Control Sphere [26] Language: English
    • Checkers:SV.INT OVF 160 Checkers:SV.INT OVF This error appears when tainted data can be traced to arithmetical operations. Vulnerability and risk Integer overflow may fail some important security checks, which can lead to privilege escalation, or can lead to dos attacks. For example, a loop counter can lead to infinitive or very long loops, or to excessive memory allocation, if large numbers of objects are requested. All operations can lead to problems, not just addition and multiplication. Mitigation and prevention Make sure any int values you process are in the correct range and, if they are expecting size values, always check that the values are not negative and check again the allowable top limit. Example 1 19 protected void doPost(HttpServletRequest req, 20 HttpServletResponse resp) throws ServletException, 21 IOException { 22 String amount = req.getParameter("creditAmount"); 23 int value = Integer.parseInt(amount); 24 int prevCreditBalance = getCreditBalance(req 25 .getParameter("user")); 26 // maximum credit is 5000 27 if (prevCreditBalance + value > 5000) { 28 // transaction 29 dosomething(); 30 } 31 // ... 32 } Klocwork produces the following report: com/klocwork/examples/Example_117.java:27:Severe(2): SV.INT_OVF: Tainted data value from getParameter().$RET used in arithmetic operation '+' can cause integer overflow or unexpected result -> getParameter().$RET at com/klocwork/examples/Example_117.java:22 -> amount at com/klocwork/examples/Example_117.java:22 23 -> parseInt().$RET at com/klocwork/examples/Example_117.java:23 -> value at com/klocwork/examples/Example_117.java:23 27
    • Checkers:SV.INT OVF 161 Security Guidelines • CWE-190: Integer Overflow or Wraparound [28] Language: English
    • Checkers:SV.IL.FILE 162 Checkers:SV.IL.FILE This error appears when a file name is printed back to the user, either as an internal file name or temporary file name. Vulnerability and risk A file name printed back to the user can be used by an attacker to predict other file names, for example to predict the next name of a temporary file. This information can then be used for unauthorized access, such as viewing other users' secret data. It also releases the directory structure, which allows an attacker to create a path manipulation attack if the code has a path injection vulnerability. Also called "path disclosure" vulnerability. Mitigation and prevention Never print the full or temporary file name back to a user. For debug purposes use the server log, not the user's screen. Example 1 12 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 13 // use user Name as the unique prefix 14 String debug = req.getParameter("debug"); 15 File file = File.createTempFile("tempfile", ".tmp"); 16 if (debug.equals("true")) { 17 resp.getOutputStream().print("Using " + file.toString()); 18 } 19 // ... 20 file.delete(); 21 } SV.IL.FILE is reported for line 17: leaking name of temporary file 'file' created on line 15. This is sensitive information that can be used by an attacker to predict the location of other files to achieve unauthorized access. Security Guidelines • CWE-548: Information Leak Through Directory Listing [27] Language: English
    • Checkers:SV.LDAP 163 Checkers:SV.LDAP This error is detected when unchecked user input is used for the filter part of a LDAP query. Mitigation and prevention The prevention of LDAP injection attacks can be achieved by validating any and all input from outside the application (user input, file input, system parameters, etc.). The best way to filter user data is with a blacklist regular expression that includes only the type of characters that are allowed. Make the LDAP query filters as specific as possible. If you need to allow the use of any special symbols, make sure to escape them. Example 1 24 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 25 try { 26 String filter = req.getParameter("filter"); 27 NamingEnumeration<SearchResult> namingEnumeration = context.search(name, filter, null); 28 29 while (namingEnumeration.hasMore()) { 30 SearchResult searchResult = namingEnumeration.next(); 31 Attribute attribute = searchResult.getAttributes().get(""); 32 if (ATTRIBUTE_TYPE.equals(attribute.getID())) { 33 resp.getOutputStream().println(attribute.get() + ";"); 34 } 35 36 } 37 } catch (NamingException e) { 38 throw new ServletException("LDAP failure", e); 39 } 40 } SV.LDAP is reported for line 27: unvalidated user input is stored in 'filter' on line 26 which is used as a LDAP filter. This filter could contain arbitrary content and makes the server vulnerable to an LDAP injection attack. Language: English
    • Checkers:SV.LOG FORGING 164 Checkers:SV.LOG FORGING This error occurs when an unvalidated user enters information in the system log file. Vulnerability and risk Logging is an important part of security measures taken by an organization. Log entries allow you to create automatic alert tools, gain statistics, or trace an attacker when there is a security breakdown. Log forging allows an attacker to manipulate log records by adding false entries. This may confuse automatic scanning utilities and allow attacks to happen unnoticed or allow attackers to misdirect the reviewer after an attack has happened. Mitigation and prevention Strings should be escaped for all characters that have special meaning for a particular log, for example CR for text log, or angle brackets for an XML log, and should be filtered for all non-text characters. Example 1 14 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 15 String amount = req.getParameter("amount"); 16 try { 17 int iAmount = Integer.parseInt(amount); 18 processAmount(iAmount); 19 } catch (NumberFormatException e) { 20 req.getSession().getServletContext().log("Incorrect int value specified for the 'amount' " + amount); 21 } 22 } SV.LOG.FORGING is reported for line 20: Unvalidated user input is stored in 'amount' variable on line 15, and on line 20 it is concatenated with a constant string and written to log. This sequence makes log forging possible. Security Guidelines • CWE-117: Improper Output Sanitization for Logs [29] Language: English
    • Checkers:SV.PASSWD.HC.EMPTY 165 Checkers:SV.PASSWD.HC.EMPTY This error occurs when an empty string reaches a method that accepts passwords or a method which performs encryption. Vulnerability and risk An empty password is an easy way to attack the system. Mitigation and prevention Do not use empty passwords, especially hardcoded ones. Example 1 13 public static void main(String[] args) throws SQLException { 14 Properties info = new Properties(); 15 info.setProperty("user", "root"); 16 info.setProperty("password", ""); 17 DriverManager.getConnection("jdbc:mysql://localhost:3307", info); 18 } SV.PASSWD.HC.EMPTY is reported for line 16: empty string is used as a password: leaving an empty password in an application is a major security risk. Security Guidelines • CWE-258: Empty Password in Configuration File [31] Language: English
    • Checkers:SV.PASSWD.PLAIN 166 Checkers:SV.PASSWD.PLAIN This error occurs when a string can be traced from file storage or the network to the method that uses it as a password. Vulnerability and risk If the storage or network is not protected by external encryption, anyone who can access it will be able to see the password's meaning. Mitigation and prevention Passwords should be entered dynamically. If that is not possible, they should be stored as irreversible digest, such as md5. If methods require a password in plain text, store an encrypted password in the configuration file. Example 1 13 public static void main(String[] args) throws Exception { 14 Properties info = new Properties(); 15 final FileInputStream st = new FileInputStream("config.ini"); 16 info.load(st); 17 st.close(); 18 DriverManager.getConnection("jdbc:mysql://localhost:3307", info); 19 } SV.PASSWD.PLAIN is reported for line 18: password used at the call to 'getConnection' was obtained from 'info'. This password is stored or transmitted in plain-text, unless external encryption is applied (such as SSL). Security Guidelines • CWE-555: J2EE Misconfiguration: Plaintext Password in Configuration File [32] Language: English
    • Checkers:SV.PATH.INJ 167 Checkers:SV.PATH.INJ This error occurs when unvalidated user data is used as part of a file name which is created or written. Vulnerability and risk In conjunction with data injection, this situation can allow injection of data into arbitrary files, for example, /etc/passwd. On its own, file injection can be used to create files and directories with which the attacker's chosen names can be used in future attacks. For example, the attacker could force an application to create a file with sensitive information on a world-readable location. Mitigation and prevention Validate all user data for allowable lexical values and size. For example, if usernames have to be part of the directory structure, check them for size and content on alphanumeric characters. Example 1 16 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 17 String name = req.getParameter("userName"); 18 File userDir = new File("userFiles", name); 19 File profile = new File(userDir, "profile"); 20 FileOutputStream stream = new FileOutputStream(profile); 21 try { 22 createFileWithSensitiveInformation(stream); 23 } finally { 24 stream.close(); 25 } 26 } SV.PATH.INJ is reported for line 20: 'name' contains data coming from an HTTP request parameter and might be tainted (line 17). This value is used to create file 'profile' on line 19 which is used on line 20 to create a FileOutputStream. This can be used to inject information into an arbitrary file in the server file system. Security Guidelines • CWE-73: External Control of File Name or Path [33] Language: English
    • Checkers:SV.PASSWD.HC 168 Checkers:SV.PASSWD.HC This error occurs when a hardcoded string, or part of a hardcoded string, reaches a method that accepts passwords or a method which performs encryption. Vulnerability and risk Source code is bad storage for secrets. First, it allows other developers to read them. String passwords can be easily extracted from Java bytecode, allowing people who have bytecode to read them. Also, it is not possible to change them without upgrading software. Hard-coded strings used as part of a digest can provide attackers with a clue to how a key is made, so attackers can try to predict it (for example, a session key). Mitigation and prevention Passwords should be entered dynamically and should store irreversible digest, such as md5. If methods require a password in plain text, store the encrypted password in the configuration file. Example 1 13 public static void main(String[] args) throws Exception { 14 Properties info = new Properties(); 15 info.setProperty("user", "root"); 16 info.setProperty("password", "^6nR$%_"); 17 Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3307", info); 18 try { 19 //... 20 } finally { 21 connection.close(); 22 } 23 } SV.PASSWD.HC is reported for line 16: string '"^6nR$%_"' used as password or its part: source code is bad storage for secrets; using this string, an attacker can determine an alternate authentication channel or guess how your session keys are formed. Security Guidelines • CWE-259: Hard-Coded Password [30] Language: English
    • Checkers:SV.PATH 169 Checkers:SV.PATH This error detects the situation in which unvalidated or tainted data is used directly in a file or path name for methods that work with system or read/write files. Attackers can use file separator characters and relative path names to read files which they should not access. Vulnerability and risk In general, file access and creation on the host system within an application is a security concern. There is a security vulnerability if unchecked user input is used in any part of the file or path string used for execution. Attackers can manipulate files and paths to write data or to access data on the host system. A typical attack could involve manipulating a file name to access the /etc/passwd file from the host system. In general, path injections can compromise the security of the file system on the host server. Mitigation and prevention The prevention of path injection attacks from user input can be achieved by validating any and all input from outside the application (user input, file input, system parameters, etc.). Validation should include length and content. Typically only alphanumeric characters are needed (i.e., A-Za-z, 0-9). Any other accepted characters should be escaped. This validation should be done at each source of data such as when each parameter is read from the HTTP request. Example 1 17 public void processUserProfile(ServletRequest req) throws IOException { 18 // Source of data from HTTP request in servlet 19 String userName = req.getParameter("userName"); 20 String profile = profileDir + File.separator + userName; 21 BufferedReader reader = new BufferedReader(new FileReader(profile)); 22 try { 23 //... 24 } finally { 25 reader.close(); 26 } 27 } SV.PATH is reported for line 21: 'userName' contains data coming from an HTTP request parameter and might be tainted (line 19). This value is concatenated with a constant string and stored in 'profile' on line 20. On line 21 'profile' is used to access a file in the local filesystem. File and path names can be manipulated to reveal important information or be used to change application behavior.
    • Checkers:SV.PATH 170 Security Guidelines • CWE-73: External Control of File Name or Path [33] Language: English
    • Checkers:SV.RANDOM 171 Checkers:SV.RANDOM This error appears when using initializing an object of type 'java.util.Random'. Vulnerability and risk Using 'java.util.Random' can produce very predictable results. If two instances of Random are created with the same seed and sequence of method calls, they will generate the exact same results. Mitigation and prevention Use 'java.security.SecureRandom' instead. This class provides a cryptographically strong random number generator. SecureRandom still uses PRNG, which means they are using a deterministic algorithm to produce a pseudo-random number from a true random seed. SecureRandom produces non-deterministic output. Example 1 12 public String generateRandomSessionId() { 13 Random random = new Random(); 14 random.setSeed(System.currentTimeMillis()); 15 return ("sessionId=" + random.nextInt(2000000000)); 16 } 17 public String generateRandomNumberUsingMath() { 18 double randomNum = Math.random(); 19 return (String.valueOf(randomNum)); 20 } SV.RANDOM is reported for lines 13 and 18: Use of insecure Random number generator 'Random'. Security Guidelines • CWE-330: Use of Insufficiently Random Values [34] Language: English
    • Checkers:SV.SERIAL.INON 172 Checkers:SV.SERIAL.INON SV.SERIAL.INON occurs when an interface extends a Serializable interface. Vulnerability and risk When an object is serialized, it is outside the control of the Java Runtime Environment, and therefore, outside control of the security provided by Java. Risk determined by company policy. Mitigation and prevention Avoid implementing Serializable unless necessary. If you do implement Serializable, use transient for fields that contain handles to system resources or information relative to an address space. Example 1 10 public interface SV_SERIAL_INON_Sample_1 extends Serializable { 11 } SV.SERIAL.INON is reported for interface declaration on line 10: Interface 'SV_SERIAL_INON_Sample_1' extends 'java.io.Serializable'. Language: English
    • Checkers:SV.SERIAL.NON 173 Checkers:SV.SERIAL.NON SV.SERIAL.NON occurs when a class implements a Serializable interface. Vulnerability and risk When an object is serialized, it is outside the control of the Java Runtime Environment, and therefore, outside control of the security provided by Java. Risk determined by company policy. Mitigation and prevention Avoid implementing Serializable unless necessary. If you do implement Serializable, use transient for fields that contain handles to system resources or information relative to an address space. Example 1 10 public class SV_SERIAL_NON_Sample_1 implements Serializable { 11 } SV.SERIAL.NON is reported for class declaration on line 10: Class 'SV_SERIAL_NON_Sample_1' implements 'java.io.Serializable'. Language: English
    • Checkers:SV.SERIAL.NOREAD 174 Checkers:SV.SERIAL.NOREAD SV.SERIAL.NOREAD is reported for a class when this class directly or indirectly implements 'java.io.Serializable' interface but does not define method 'private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException'. Vulnerability and risk If a class does not implement a 'readObject' method with the correct signature, the default serialization provided by 'defaultReadObject' will be used. Thus this class is not protected from deserialization, and an attacker can create a sequence of bytes that deserializes to an instance of your class. Mitigation and prevention Implement method 'private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException'. Example 1 5 public class SV_SERIAL_Sample_1 implements Serializable { 6 7 public static void main(String[] args) 8 { 9 System.out.println("Hello World!"); 10 } 11 } SV.SERIAL.NOREAD is reported for class 'SV_SERIAL_Sample_1' declaration on line 5. See also • → SV.SERIAL.NOWRITE • → SV.SERIAL.SIG • → SV.SERIAL.NON • → SV.SERIAL.INON Language: English
    • Checkers:SV.SERIAL.NOWRITE 175 Checkers:SV.SERIAL.NOWRITE SV.SERIAL.NOWRITE is reported for a class when this class directly or indirectly implements 'java.io.Serializable' interface but does not define method 'private void writeObject(java.io.ObjectOutputStream out) throws IOException'. Vulnerability and risk If a class does not implement the 'writeObject' method with the correct signature, the default serialization provided by 'defaultWriteObject' will be used. An attacker can serialize your objects into a byte array that can be read. This will allow the attacker to inspect the full internal state of your object. Mitigation and prevention Implement method 'private void writeObject(java.io.ObjectOutputStream out) throws IOException'. Example 1 5 public class SV_SERIAL_Sample_1 implements Serializable { 6 7 public static void main(String[] args) 8 { 9 System.out.println("Hello World!"); 10 } 11 } SV.SERIAL.NOWRITE is reported for class 'SV_SERIAL_Sample_1' declaration on line 5. See also • → SV.SERIAL.NOREAD • → SV.SERIAL.SIG • → SV.SERIAL.NON • → SV.SERIAL.INON Language: English
    • Checkers:SV.SHARED.VAR 176 Checkers:SV.SHARED.VAR This error appears if a value is ACCESSED from a static field without synchronization in some method, and this method is transitively called from the doPost or doGet method of the servlet. This is a thread safety problem because one instance of the servlet class is shared by several threads. Vulnerability and risk The vulnerability exists because a servlet is multi-threaded, and shared static variables are not protected from concurrent access. This is a typical programming mistake in J2EE applications, since the multi-threading is handled by the framework. The use of shared variables can be exploited by attackers to gain information or to cause denial of service conditions. If this shared data contains sensitive information, it may be manipulated or displayed in another user session. If this data is used to control the application, its value can be manipulated to cause the application to crash or perform poorly. Mitigation and prevention A shared variable vulnerability can be prevented by removing the use of static variables used between servlets or to provide protection when shared access is absolutely needed. In this case, access should be synchronized. Example 1 17 public static class Counter extends HttpServlet { 18 static int count = 0; 19 protected void doGet(HttpServletRequest in, 20 HttpServletResponse out) throws ServletException, 21 IOException { 22 out.setContentType("text/plain"); 23 PrintWriter p = out.getWriter(); 24 count++; 25 p.println(count + " hits so far!"); 26 } 27 } SV.SHARED.VAR is reported for lines 24 and 25: Unsynchronized access to static variable 'count' accessible from servlet code. Security Guidelines • CWE-567: Unsynchronized Access to Shared Data [35] Language: English
    • Checkers:SV.SERIAL.SIG 177 Checkers:SV.SERIAL.SIG SV.SERIAL.SIG is reported for a class when this class directly or indirectly implements 'java.io.Serializable' interface but the declared method 'readObject' or 'writeObject' has an incorrect signature. Vulnerability and risk If a class does not implement 'readObject' and 'writeObject' methods with the correct signature, the default serialization will be used. Mitigation and prevention Methods 'readObject' and 'writeObject' should have the following signatures respectively: 'private void writeObject(java.io.ObjectOutputStream out) throws IOException' and 'private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException'. Example 1 13 public class SV_SERIAL_SIG_Sample_1 implements Serializable { 14 final void readObject(ObjectInputStream in) { 15 } 16 17 void writeObject(ObjectOutputStream in) throws IOException { 18 } 19 } SV.SERIAL.SIG is reported for class 'SV_SERIAL_SIG_Sample_1' declaration on line 17: method 'writeObject() does not have 'private' modifier. SV.SERIAL.SIG is reported for class 'SV_SERIAL_SIG_Sample_1' declaration on line 14: method 'readObject() does not have 'private' modifier. SV.SERIAL.SIG is reported for class 'SV_SERIAL_SIG_Sample_1' declaration on line 14: method 'readObject() does not declare throwing 'java.io.IOException' and 'java.lang.ClassNotFoundException'. See also • → SV.SERIAL.NOREAD • → SV.SERIAL.NOWRITE • → SV.SERIAL.NON • → SV.SERIAL.INON Language: English
    • Checkers:SV.SOCKETS 178 Checkers:SV.SOCKETS This warning is reported when an application is using sockets. Vulnerability and risk Socket usage should be avoided in many cases. For example, the EJB standard contains the following guidelines: An enterprise bean must not attempt to listen on a socket, accept connections on a socket, or use socket for multicast. Other applications (applets, servlets, and so on) might have serious security problems if sockets are used. Mitigation and prevention Use framework method calls instead of using sockets directly. Example 1 17 public class SV_SOCKETS_Sample_1 extends Applet { 18 static final int PORT = 7776; 19 public void init() { 20 super.init(); 21 try { 22 final ServerSocket serv = new ServerSocket(PORT); 23 Runnable rr = new Runnable() { 24 public void run() { 25 try { 26 while (true) { 27 Socket sock = serv.accept(); 28 BufferedReader r = new BufferedReader( 29 new InputStreamReader(sock 30 .getInputStream())); 31 PrintWriter w = new PrintWriter(sock 32 .getOutputStream(), false); // no autoFlush 33 w.write("Hello"); 34 w.flush(); 35 r.close(); 36 w.close(); 37 sock.close(); 38 } 39 } catch (IOException e) { 40 e.printStackTrace(); 41 } 42 } 43 }; 44 new Thread(rr).start(); 45 } catch (IOException e1) { 46 e1.printStackTrace(); 47 }
    • Checkers:SV.SOCKETS 179 48 } 49 //... 50 public void paint(Graphics g) { 51 } 52 } SV.SOCKETS is reported for line 22: Using sockets directly should be avoided in many cases (e.g. in Applets, EJBs). This might cause security problems Security Guidelines • CWE-246: J2EE Bad Practices: Direct Use of Sockets [36] Language: English
    • Checkers:SV.STRBUF.CLEAN 180 Checkers:SV.STRBUF.CLEAN STRBUF.CLEAN occurs when potentially secure data is not cleared from a StringBuffer. Vulnerability and risk Relying on the garbage collector to clear data is not safe. An attacker can access data that has not been released. Mitigation and prevention Do not use mutable objects to store sensitive data. If you must use mutable objects for sensitive data, NULL the object immediately after use. Example 1 16 private void processingData(String user) throws SQLException { 17 String credential = getCredential(user); 18 // ... 19 } 20 21 private String getCredential(String user) throws SQLException { 22 Statement statement = con.createStatement(); 23 try { 24 StringBuffer buffer = new StringBuffer(); 25 ResultSet resultSet = statement.executeQuery("SELECT * FROM credentials WHERE name='" + user + '''); 26 while (resultSet.next()) { 27 String key = resultSet.getString("key"); 28 buffer.append(key); 29 } 30 31 final String result = buffer.toString(); 32 return result; 33 } finally { 34 statement.close(); 35 } 36 } SV.STRBUF.CLEAN is reported for line 24: String buffer 'buffer' not cleaned before garbage collection. Example 2 16 private void processingData(String user) throws SQLException { 17 String credential = getCredential(user); 18 // ... 19 20 } 21 22 private String getCredential(String user) throws SQLException {
    • Checkers:SV.STRBUF.CLEAN 181 23 Statement statement = con.createStatement(); 24 StringBuffer buffer = new StringBuffer(); 25 try { 26 ResultSet resultSet = statement.executeQuery("SELECT * FROM credentials WHERE name='" + user + '''); 27 while (resultSet.next()) { 28 String key = resultSet.getString("key"); 29 buffer.append(key); 30 } 31 32 final String result = buffer.toString(); 33 return result; 34 } finally { 35 buffer.delete(0, buffer.length()); 36 statement.close(); 37 } 38 } The snippet from the previous section is fixed; SV.STRBUF.CLEAN is not reported here. Language: English
    • Checkers:SV.SQL.DBSOURCE 182 Checkers:SV.SQL.DBSOURCE This error detects the situation where the results of a database query are used unchecked to create another database query, which can lead to an SQL Injection attack. Vulnerability and risk SQL injections put data in the database at risk. Since unvalidated user input is used in the SQL statement, an attacker can inject any SQL statement they wish to execute. This includes deleting, updating or creating data. It may also be possible to retrieve sensitive data from the database with this type of vulnerability. This vulnerability might be exploited in conjunction with the → SV.DATA.DB vulnerability. Mitigation and prevention For more information, see Knowledge base parameters. Example 1 11 public ResultSet getAllPeopleWithSameLastName(ServletRequest req, Connection con, int userId) throws SQLException { 12 Statement statement = con.createStatement(); 13 ResultSet results = statement.executeQuery("SELECT lastName FROM user_data WHERE userid=" + userId); 14 String lastName = results.getString("lastName"); 15 String query = "SELECT * FROM user_data WHERE lastName = '" + lastName + "'"; 16 return statement.executeQuery(query); 17 } SV.SQL.DBSOURCE is reported for line 16: 'lastName' contains data coming from the database (line 14) which is concatenated with a constant string and stored in 'query' on line 15. On line 16 'query' is executed as an SQL statement. This means that information from a database is used unchecked in an SQL statement executed on the same or another database. This can be exploited to inject arbitrary SQL statements if database data injection (→ SV.DATA.DB) is possible. Security Guidelines • CWE-89: Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection') [15] See also • → SV.DATA.DB Language: English
    • Checkers:SV.SQL 183 Checkers:SV.SQL This error detects the situation when unvalidated or tainted data is used directly in an SQL query string. Specifically, this error traces user input from various sources, such as HTTP requests via J2EE servlets, to the use of this data in SQL statements. If this data is used, unchecked, directly in the SQL statement used in the java.sql.Statement.execute() method, then attackers can enter arbitrary SQL statements into this string. This allows arbitrary SQL commands to be run directly from the user interface. Vulnerability and risk SQL injections put data in the database at risk. Since unvalidated user input is being used in the SQL statement, an attacker can inject any SQL statement they wish to execute. This includes deleting, updating or creating data. It may also be possible to retrieve sensitive data from the database with this type of vulnerability. If the command is used for authentication, it will lead to unauthorized access. Mitigation and prevention Prevent SQL injection flaws by validating any and all input from outside the application (user input, file input, system parameters, etc.). Validation should include length and content. Typically only alphanumeric characters are needed (i.e., A-Za-z, 0-9). Any other accepted characters should be escaped. This validation should be done at each source of data, such as when each parameter is read from the HTTP request. Additionally it may be advisable to check all strings that are used in SQL statements before their use. Moreover, the use of SQL statements as in the sample is also dangerous, as it allows for injection flaws and other potentially dangerous SQL execution. Use SQL prepared statements for creating, updating and deleting records. Example 1 15 public ResultSet getUserData(ServletRequest req, Connection con) throws SQLException { 16 // Source of data from HTTP request in servlet 17 String accountNumber = req.getParameter("accountNumber"); 18 // Use of string in SQL statement 19 String query = "SELECT * FROM user_data WHERE userid = '" + accountNumber + "'"; 20 Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); 21 ResultSet results = statement.executeQuery(query); 22 return results; 23 } SV.SQL is reported for line 21: 'accountNumber' contains data coming from an HTTP request parameter and might be tainted (line 17). This value is concatenated with a constant string to form the 'query' on line 19. The 'query' is executed as an SQL statement on line 21. This can be exploited to inject arbitrary SQL statements.
    • Checkers:SV.SQL 184 Security Guidelines • CWE-89: Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection') [15] Language: English
    • Checkers:SV.STRUTS.NOTRESET 185 Checkers:SV.STRUTS.NOTRESET This error appears when a class extends org.apache.struts.action.ActionForm and has a reset method, but it does not reset some fields. Vulnerability and risk IReset method is called before filling out a form with request parameters. If some fields are not reset, they can have old values which can be used by an attacker. Since a client request can be easily manipulated by an attacker, do not depend on the presence of certain fields in a request. Mitigation and prevention Reset all fields that a client can populate. If a field cannot be populated by the client that usually means the Form tries to implement some business logic or is used as an output form, which normally should not be part of the ActionForm and should be implemented by a different class. Example 1 13 public class SV_STRUTS_NOTRESET_Sample_1 extends ActionForm { 14 private String name; 15 private String[] cars = new String[10]; 16 public String getName() { 17 return name; 18 } 19 public void setName(String name) { 20 this.name = name; 21 } 22 public String getCar(int i) { 23 return cars[i]; 24 } 25 public void setCar(int i, String car) { 26 this.cars[i] = car; 27 } 28 public void reset(ActionMapping map, 29 HttpServletRequest req) { 30 cars = new String[10]; 31 } 32 } SV.STRUTS.NOTRESET is reported for field declaration on line 14: Struts: Form field 'SV_STRUTS_NOTRESET_Sample_1' 'name' is not reset by 'reset' method
    • Checkers:SV.STRUTS.NOTRESET 186 Security Guidelines • CWE-226: Sensitive Information Uncleared Before Release [37] Language: English
    • Checkers:SV.STRUTS.NOTVALID 187 Checkers:SV.STRUTS.NOTVALID This error occurs when a class extends org.apache.struts.action.ActionForm and has a validate method, but does not validate some fields. Vulnerability and risk Unvalidated fields is a number-one security issue for web applications. Unvalidated fields can lead to many security vulnerabilities, such as SQL Injections, Cross-Site scripting, and so on. Mitigation and prevention Define the validate method and validate ALL form fields. Integer fields can be checked by size, negativity and being non-zero, for example. String fields need more complicated checks based on the type of information. Example 1 18 public class SV_STRUTS_NOTVALID_Sample_1 extends ActionForm { 19 private String name; 20 private String birthdayString; 21 protected Date birthday; 22 public ActionErrors validate(ActionMapping map, 23 HttpServletRequest req) { 24 ActionErrors errors = new ActionErrors(); 25 SimpleDateFormat dateConvertor = new SimpleDateFormat( 26 req.getParameter("date.format")); 27 try { 28 birthday = dateConvertor.parse(birthdayString); 29 } catch (ParseException e) { 30 errors.add(ActionErrors.GLOBAL_MESSAGE, 31 new ActionMessage("Bad date")); 32 } 33 return super.validate(map, req); 34 } 35 public String getName() { 36 return name; 37 } 38 public void setName(String name) { 39 this.name = name; 40 } 41 public String getBirthday() { 42 return birthdayString; 43 } 44 public void setBirthday(String birthday) { 45 this.birthdayString = birthday; 46 } 47 }
    • Checkers:SV.STRUTS.NOTVALID 188 SV.STRUTS.NOTVALID for field declaration on line 19: Struts: Form field 'SV_STRUTS_NOTVALID_Sample_1' 'name' is not validated by 'validate' method. Security Guidelines • CWE-105: Struts: Form Field Without Validator [38] Language: English
    • Checkers:SV.STRUTS.PRIVATE 189 Checkers:SV.STRUTS.PRIVATE This error appears when a Class extends an org.apache.struts.action.ActionForm and has a class field that is not private. Vulnerability and risk ActionForm class should contain only private fields which are accessed by setter and getter. Creating non-private fields violated this contract and has introduced the possibility of avoiding validation and creating an invalid state for the Form object. Mitigation and prevention Make all fields private. Use getter to get the value of the field. Setter should be used only by the framework; setting an action form field from other actions is bad practice and should be avoided. Example 1 10 public class SV_STRUTS_PRIVATE_Sample_1 extends ActionForm { 11 private String name; 12 protected String birthdayString; 13 public String getName() { 14 return name; 15 } 16 public void setName(String name) { 17 this.name = name; 18 } 19 public String getBirthday() { 20 return birthdayString; 21 } 22 public void setBirthday(String birthday) { 23 this.birthdayString = birthday; 24 } 25 } SV.STRUTS.PRIVATE is reported for field declaration on line 12: Struts: Form field 'birthdayString' should be private Language: English
    • Checkers:SV.STRUTS.RESETMET 190 Checkers:SV.STRUTS.RESETMET This error is detected when a class extends org.apache.struts.action.ActionForm and does not implement the method 'reset'. Vulnerability and risk The reset method is called before filling out a form with request parameters. If some fields are not reset, they can retain old values which can be user by an attacker. Since a client request can be early manipulated by an attacker, do not depend on the presence of certain fields in a request. Mitigation and prevention Reset all fields that a client can populate. If a field cannot be populated by the client, that usually mean the form tries to implement some business logic or is used as an output form, which normally should not be part of the ActionForm and should be implemented by a different class. Example 1 10 public class SV_STRUTS_RESETMET_Sample_1 extends ActionForm { 11 private String name; 12 private String[] cars = new String[10]; 13 public String getName() { 14 return name; 15 } 16 public void setName(String name) { 17 this.name = name; 18 } 19 public String getCar(int i) { 20 return cars[i]; 21 } 22 public void setCar(int i, String car) { 23 this.cars[i] = car; 24 } 25 } SV.STRUTS.RESETMET is reported for form declaration on line 10: Struts: Form 'SV_STRUTS_RESETMET_Sample_1' does not have method 'reset' defined Security Guidelines • CWE-226: Sensitive Information Uncleared Before Release [37] Language: English
    • Checkers:SV.STRUTS.STATIC 191 Checkers:SV.STRUTS.STATIC This error is reported when a class extends org.apache.struts.action.ActionForm and defines a static field which is not final. Vulnerability and risk Non-final static fields can create race-conditions, because can be changed by different instances of the form at the same time, or between time of check and time of use (TOCTOU). Mitigation and prevention Avoid using non-final static fields. Make fields final or non-static. If you make a field final, make sure the object it contains is immutable. If the value of this field depends on a request, it should not be static, because it will be possible to create some exposure by creating a malicious form. If it does not depend on a request, it should be made final. Example 1 18 public class SV_STRUTS_STATIC_Sample_1 extends ActionForm { 19 20 private String birthdayString; 21 protected Date birthday; 22 private static SimpleDateFormat dateConvertor; 23 public ActionErrors validate(ActionMapping map, 24 HttpServletRequest req) { 25 ActionErrors errors = new ActionErrors(); 26 if (dateConvertor == null) { 27 dateConvertor = new SimpleDateFormat(req 28 .getParameter("date.format")); 29 } 30 try { 31 birthday = dateConvertor.parse(birthdayString); 32 } catch (ParseException e) { 33 errors.add(ActionErrors.GLOBAL_MESSAGE, 34 new ActionMessage("Bad date")); 35 } 36 return super.validate(map, req); 37 } 38 public String getBirthday() { 39 return birthdayString; 40 } 41 public void setBirthday(String birthday) { 42 this.birthdayString = birthday; 43 } 44 }
    • Checkers:SV.STRUTS.STATIC 192 SV.STRUTS.STATIC is reported for field declaration on line 22: Struts: Static form field variables 'dateConvertor' should be final Security Guidelines • CWE-500: Public Static Field Not Marked Final [39] Language: English
    • Checkers:SV.STRUTS.VALIDMET 193 Checkers:SV.STRUTS.VALIDMET This error is reported when a class extends org.apache.struts.action.ActionForm and does not implement the method 'validate'. Note that this error is not reported if the class extends ValidatorForm because in this case, the method validate is generated automatically based on the XML specification. Vulnerability and risk The validate method is the standard mechanism for a struts framework to validate fields. Unvalidated fields is a top security problem for web applications. Mitigation and prevention Define the validate method and validate ALL form fields. Integer fields can be checked by size, negativity and non-zero value, for example. String fields need more complicated checks based on the type of information. Unvalidated fields can lead to many security vulnerabilities such as SQL injections, Cross-site scripting, and so on. Example 1 10 public class SV_STRUTS_VALIDMET_Sample_1 extends ActionForm { 11 private String name; 12 private String birthdayString; 13 14 public String getName() { 15 return name; 16 } 17 public void setName(String name) { 18 this.name = name; 19 } 20 public String getBirthday() { 21 return birthdayString; 22 } 23 public void setBirthday(String birthday) { 24 this.birthdayString = birthday; 25 } 26 } SV.STRUTS.VALIDMET is reported for class declaration on line 10: Struts: Form 'SV_STRUTS_VALIDMET_Sample_1' does not have method 'validate' defined
    • Checkers:SV.STRUTS.VALIDMET 194 Security Guidelines • CWE-103: Struts: Incomplete validate() Method Definition [40] Language: English
    • Checkers:SV.TAINT 195 Checkers:SV.TAINT This error is detected when data from user input is traced to use in a potentially dangerous location. This error analyzes the flow of data from the input via HTTP requests from the web interface to its final destination in the application. This is useful for finding vulnerabilities that other unvalidated/tainted data error types may miss. Vulnerability and risk The use of unvalidated user input is, in general, a security vulnerability. Even if the current iteration of the application does not use it in a dangerous manner, future iterations may, and usually the data is assumed to be untainted. All user input should be checked for length and content at the point where it enters the application, so that subsequent use of this data is not vulnerable to attacks. Mitigation and prevention Mitigation of unvalidated user input, tainted data and other related vulnerabilities from user input can be achieved by validating any and all input from outside the application (user input, file input, system parameters, etc.). Validation should include length and content. Typically only alphanumeric characters are needed (i.e., A-Za-z, 0-9). Any other accepted characters should be escaped. This validation should be done at each source of data, such as when each parameter is read from the HTTP request. Example 1 14 protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { 15 String act = req.getParameter("action"); 16 String value = req.getParameter("actionValue"); 17 System.setProperty(act, value); 18 } SV.TAINT is reported for line 17: Potential tainted data vulnerability. Unchecked user data store in 'act' is entering a security-sensitive method. Security Guidelines • CWE-20: Improper Input Validation [41] Language: English
    • Checkers:SV.TAINT NATIVE 196 Checkers:SV.TAINT NATIVE This error occurs when unchecked user input is passed to native method calls. Vulnerability and risk Native code is usually C/C++ code. This language carries inherent security risks. If a user input enters native code, it can create much more dangerous problems than any error in Java code, such as buffer overflows and denial of service by a JVM crash. Mitigation and prevention All user data should be sanitized before passing it to native methods. User data should especially be checked for size and for dangerous symbols such as '0'. Example 1 14 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 15 String name = req.getParameter("userName"); 16 processNatively(name); 17 } 18 19 private native void processNatively(String name); SV.TAINT_NATIVE is reported for line 16: tainted data from 'name' goes to a native code call which can have BufferOverflows and other critical errors. Security Guidelines • CWE-20: Improper Input Validation [41] Language: English
    • Checkers:SV.TMPFILE 197 Checkers:SV.TMPFILE This error appears when unvalidated user input enters an API for temporary file creation as a prefix, suffix or temporary directory path. Vulnerability and risk This situation can lead to Path Manipulation or Denial of Service. With Path Manipulation, a user can manipulate a path to a temporary file to make it available in non-protected directories, for example in web root. A user can make this method throw an IllegalArgumentException (for example, if a prefix is too short). This situation could also result in an IOException, which can cause denial of service to the application, if it is not properly processed. Mitigation and prevention Never use user data for names of temporary files. Example 1 15 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 16 String name = req.getParameter("USERNAME"); 17 File file = File.createTempFile(name, ".tmp"); 18 dumpSensitiveInfoAndRunSomeApp(file); 19 file.delete(); 20 } 21 22 private void dumpSensitiveInfoAndRunSomeApp(File file) { 23 // ... 24 } SV.TMPFILE is reported for line 17: 'name' contains data coming from an HTTP request parameter and might be tainted (line 16). This value is used to create the temporary file on line 17. This can be used to create temporary files in different locations, allowing access escalation or denial of service. Security Guidelines • CWE-73: External Control of File Name or Path [33] Language: English
    • Checkers:SV.UMC.EXIT 198 Checkers:SV.UMC.EXIT A web application should not make calls to System.exit() or Runtime.exit(). Even if it is "dead" code, or has no permission to shut down the Java Virtual Machine, the code is probably leftover debug code, or code left from a non-J2EE application. Vulnerability and risk System.exit() and Runtime.exit() can shut down the Java Virtual Machine. This might lead to a Denial of Service attack. Mitigation and prevention Calls to System.exit() and Runtime.exit() should be removed. An appropriate error handling should be implemented. Example 1 16 public void doPost(HttpServletRequest request, 17 HttpServletResponse response) throws IOException, 18 ServletException { 19 doProcessRequest(request, response); 20 } 21 public void doGet(HttpServletRequest request, 22 HttpServletResponse response) throws IOException, 23 ServletException { 24 doProcessRequest(request, response); 25 } 26 // called from servlet 27 private void doProcessRequest(HttpServletRequest request, 28 HttpServletResponse response) throws IOException, 29 ServletException { 30 if ("shutdown".equals(request.getParameter("action"))) { 31 System.exit(1); 32 } 33 doCreatePage(request, response); 34 // ... 35 } SV.UMC.EXIT is reported for call on line 31: 'java.lang.System.exit()' method call should not be used in servlets code
    • Checkers:SV.UMC.EXIT 199 Security Guidelines • CWE-382: J2EE Bad Practices: Use of System.exit() [42] Language: English
    • Checkers:SV.UMC.JDBC 200 Checkers:SV.UMC.JDBC The DataSource interface, new in the JDBC 2.0 API, provides a better way to connect to a data source. Calling DriverManager.getConnection(...) should be avoided. Vulnerability and risk Acquiring and releasing database connections by means of the database manager, using JDBC 1.0, will impact the performance of the application. That impact is due to the overhead in creating and destroying those objects by the database resource manager process. Mitigation and prevention The use of a DataSource object is the preferred means of connecting to a data source. Example 1 18 protected void doPost(HttpServletRequest req, 19 HttpServletResponse resp) throws ServletException { 20 String name = req.getParameter("userName"); 21 String pswd = req.getParameter("passwd"); 22 Connection conn = doGetConnection(name, pswd); 23 // ... 24 } 25 private Connection doGetConnection(String name, 26 String pswd) { 27 Connection conn = null; 28 try { 29 return DriverManager.getConnection("localhost:3300", 30 name, pswd); 31 } catch (SQLException e) { 32 // ... 33 } 34 return conn; 35 } SV.UMC.JDBC is reported for call on line 29: Application should avoid calling DriverManager.getConnection() directly.
    • Checkers:SV.UMC.JDBC 201 Security Guidelines • CWE-245: J2EE Bad Practices: Direct Management of Connections [43] Language: English
    • Checkers:SV.UMC.THREADS 202 Checkers:SV.UMC.THREADS This warning is reported when an application is using threads. Vulnerability and risk Thread management should be avoided in many cases. For example, the EJB standard contains the following guidelines: The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread, or to change a thread's priority or name. The enterprise bean must not attempt to manage thread groups. Thread management in servlets is also very questionable and might lead to problems. On the other hand, threads are used in applets and other GUI applications. In this context, a warning serves not to report an error, but rather as a reminder to programmers to pay more attention to this code. Mitigation and prevention For EBJ use framework approaches for parallel execution, instead of using threads. Example 1 23 public class SV_UMC_THREADS_Sample_1 extends HttpServlet { 24 public void doPost(HttpServletRequest request, 25 HttpServletResponse response) throws IOException, 26 ServletException { 27 doProcessRequest(request, response); 28 } 29 public void doGet(HttpServletRequest request, 30 HttpServletResponse response) throws IOException, 31 ServletException { 32 doProcessRequest(request, response); 33 } 34 private void doProcessRequest(HttpServletRequest request, 35 HttpServletResponse response) throws IOException, 36 ServletException { 37 final StringBuffer buffer = new StringBuffer(); 38 Runnable r = new Runnable() { 39 public void run() { 40 buffer.append("Processing...n"); 41 // do something 42 buffer.append("Finished.n"); 43 } 44 };
    • Checkers:SV.UMC.THREADS 203 45 Thread t = new Thread(r); 46 t.start(); 47 // do something else, then get results from background thread 48 try { 49 t.join(); 50 } catch (InterruptedException e) { 51 } 52 String log = buffer.toString(); 53 // create page... 54 } 55 } SV.UMC.THREADS is reported for calling 'Thread' constructor on line 36: Method 'Thread' is used. Thread management is deprecated in many cases (e.g. in EJBs). Also, it is always highly error prone SV.UMC.THREADS is reported for call on line 37: Method 'start' is used. Thread management is deprecated in many cases (e.g. in EJBs). Also, it is always highly error prone SV.UMC.THREADS is reported for call on line 40: Method 'join' is used. Thread management is deprecated in many cases (e.g. in EJBs). Also, it is always highly error prone Security Guidelines • CWE-383: J2EE Bad Practices: Direct Use of Threads [44] Language: English
    • Checkers:SV.UMD.MAIN 204 Checkers:SV.UMD.MAIN This error occurs when a main method is detected in web applications, J2EE applications, and applets. Vulnerability and risk Leaving main() methods behind in a web application allows easy back-door access to the application. Security designs in web applications tend not to consider main method access and therefore are a risk. Mitigation and prevention Remove all main methods in production code. Example 1 15 public class SV_UMD_MAIN_Sample_1 extends HttpServlet { 16 public void doGet(HttpServletRequest req, 17 HttpServletResponse res) throws ServletException, 18 IOException { 19 res.setContentType("text/html"); 20 PrintWriter out = res.getWriter(); 21 String name = req.getParameter("name"); 22 out.println("<HTML>"); 23 out.println("<HEAD><TITLE>Hello, " + name 24 + "</TITLE></HEAD>"); 25 out.println("<BODY>"); 26 out.println("Hello, " + name); 27 out.println("</BODY></HTML>"); 28 } 29 public String getServletInfo() { 30 return "A servlet that knows " 31 + "the name of the person to whom it's" 32 + "saying hello"; 33 } 34 private void work() { 35 // test some code within our application 36 } 37 // leaving this around is unwanted once in production 38 public static void main(String[] args) { 39 SV_UMD_MAIN_Sample_1 ex = new SV_UMD_MAIN_Sample_1(); 40 // test that our code is working 41 ex.work(); 42 } 43 } SV.UMD.MAIN is reported for line 38: The main() method definition provides entry point to the application, remove all unused main methods.
    • Checkers:SV.UMD.MAIN 205 Security Guidelines • CWE-489: Leftover Debug Code [45] Language: English
    • Checkers:SV.USE.POLICY 206 Checkers:SV.USE.POLICY Code inspection rule. SV.USE.POLICY occurs when code uses getPolicy or setPolicy from java.security.Policy. Vulnerability and risk Usually 'security.Policy' should not be changed within the application. Cases where it is accessed and changed require an inspection. Mitigation and prevention Determined by company policy. Example 1 11 void setPolicy(Policy newPolicy) { 12 Policy.setPolicy(newPolicy); 13 } SV.USE.POLICY is reported for call on line 12: Method 'setPolicy' from 'java.security.Policy' is used directly. Language: English
    • Checkers:SV.XPATH 207 Checkers:SV.XPATH This error is detected when unchecked user input is used as an XPath expression. Mitigation and prevention The prevention of XPath injection attacks can be achieved by validating any and all input from outside the application (user input, file input, system parameters, etc.). The best way to filter user data is with a blacklist regular expression that includes only the type of characters that are allowed; all other characters should be escaped. Example 1 24 protected void doGet(HttpServletRequest httpServletRequest, 25 HttpServletResponse httpServletResponse) throws ServletException, IOException { 26 super.doGet(httpServletRequest, httpServletResponse); 27 String userName = httpServletRequest.getParameter("user.name"); 28 String userDescr = httpServletRequest.getParameter("user.descr"); 29 CompiledExpression compiledExpression = JXPathContext.compile("string(//user[name/text()='" + userName + "']/account/text())"); 30 compiledExpression.setValue(context, userDescr); 31 httpServletResponse.getOutputStream().println("User info updated"); 32 } SV.XPATH is reported for the snippet twice: • user data is stored in 'userName' on line 27 and later is used for the construction of an XPath expression on line 29 • user data is stored in 'userDescr' on line 28 and later is passed to 'setValue(...)' on line 30 Language: English
    • Checkers:SV.XSS.DB 208 Checkers:SV.XSS.DB This error is reported when cross-site scripting from the application database is detected. Cross-site scripting vulnerabilities occur when unchecked user input is reflected back to the web interface. Vulnerability and risk An XSS or cross-site scripting vulnerability results from using unchecked user input in information used in the web interface. This data can contain arbitrary content such as HTML and SCRIPT tags. If this information is displayed for other users of the system, these scripts can be used to manipulate the user's session, direct them to other web sites, perform "phishing" attacks or run other malicious script content. This vulnerability is common on message boards of web applications where users can post information back to other users. This content must be closely screened to prevent the injection of HTML or SCRIPT tags into the output seen by other users. Mitigation and prevention Cross-site scripting vulnerabilities, in general, can be prevented by validating any and all input from outside the application (user input, file input, system parameters, etc.). Validation should include length and content. Typically only alphanumeric characters are needed (i.e., A-Za-z, 0-9). Any other accepted characters should be escaped. In particular for XSS vulnerabilities, no tags should be allowed in the user input. This validation should be done at each source of data, such as when each parameter is read from the HTTP request. Validation should be done at the server side; client-side validation is not enough to protect against XSS, since users can send raw HTTP packets without the need of a client browser. Example 1 15 protected void printComment(Connection conn, ServletOutputStream out, String user) throws SQLException, IOException { 16 PreparedStatement pr = conn.prepareStatement("SELECT * FROM comms WHERE user = ?"); 17 pr.setString(0, user); 18 String comment = pr.executeQuery().getString("comment"); 19 out.println("Comments: " + comment); 20 } SV.XSS.DB is reported for line 19: 'comment' contains data coming from the database (line 18). On line 19 it is used to render a web page. This means that information previously stored in the database is used unchecked to render a web page; this information may contain arbitrary HTML and JavaScript content. To exploit this vulnerability, a database injection vulnerability must also exist.
    • Checkers:SV.XSS.DB 209 Security Guidelines • CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting') [14] • CWE-80: Improper Sanitization of Script-Related HTML Tags in a Web Page (Basic XSS) [46] See also • → SV.DATA.DB • → SV.XSS.REF Language: English
    • Checkers:SV.XSS.REF 210 Checkers:SV.XSS.REF This error indicates cross-site scripting from the application database. Cross-site scripting vulnerabilities occur when unchecked user input is reflected back to the web interface. Vulnerability and risk An XSS or cross-site scripting vulnerability results from using unchecked user input in information used in the web interface. This data can contain arbitrary content such as HTML and SCRIPT tags. If this information is displayed for other users of the system, these scripts can be used to manipulate the user's session, direct them to other web sites, perform "phishing" attacks or run other malicious script content. This vulnerability is common on message boards of web applications where users can post information back to other users. This content must be closely screened to prevent the injection of HTML or SCRIPT tags into the output seen by other users. Mitigation and prevention Cross-site scripting vulnerabilities, in general, can be prevented by validating any and all input from outside the application (user input, file input, system parameters, etc.). Validation should include length and content. Typically only alphanumeric characters are needed (i.e., A-Za-z, 0-9). Any other accepted characters should be escaped. In particular for XSS vulnerabilities, no tags should be allowed in the user input. This validation should be done at each source of data, such as when each parameter is read from the HTTP request. Validation should be done at the server side; client-side validation is not enough to protect against XSS, since users can send raw HTTP packets without the need of a client browser. Example 1 15 protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { 16 String action = req.getParameter("action"); 17 if ("chart".equals(action)) { 18 renderChart(res.getOutputStream()); 19 } else if ("table".equals(action)) { 20 renderTable(res.getOutputStream()); 21 } else { 22 throw new ServletException("Cannot find action " + action); 23 } 24 } 25 26 private void renderTable(ServletOutputStream outputStream) { 27 //... 28 } 29 30 private void renderChart(ServletOutputStream outputStream) { 31 //... 32 }
    • Checkers:SV.XSS.REF 211 SV.XSS.REF is reported for line 22: 'action' contains data coming from an HTTP request parameter and might be tainted (line 16). This value is used as a message for the ServletException thrown on line 22. This message will be rendered in the browser. This is a reflected cross-site scripting (Reflected XSS) vulnerability: unvalidated user input is used for web application output, which may contain arbitrary HTML and JavaScript. Security Guidelines • CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting') [14] • CWE-80: Improper Sanitization of Script-Related HTML Tags in a Web Page (Basic XSS) [46] See also • → SV.XSS.DB Language: English
    • Checkers:SYNCH.NESTED 212 Checkers:SYNCH.NESTED When a synchronized method calls other synchronized methods on same object, it does not create synchronization problems but it does have a detrimental effect on performance. This error is reported for non-static methods. Example 1 12 public class MyClass { 13 public synchronized List getElements() { 14 return internalGetElements(); 15 } 16 synchronized List internalGetElements() { 17 List list = new ArrayList(); 18 // calculate and return list of elements 19 return list; 20 } 21 // ... 22 } SYNCH.NESTED is reported for line 14: Synchronized method calls another synchronized method 'internalGetElements' with the same lock held Language: English
    • Checkers:SYNCH.NESTEDS 213 Checkers:SYNCH.NESTEDS When a synchronized method calls other synchronized methods on same object, it does not create synchronization problems but it does have a detrimental effect on performance. This error is reported for static method calls. Example 1 12 public static class MyClass { 13 static public synchronized List getElements() { 14 return internalGetElements(); 15 } 16 static synchronized List internalGetElements() { 17 List list = new ArrayList(); 18 // calculate and return list of elements 19 return list; 20 } 21 // ... 22 } SYNCH.NESTEDS is reported for line 14: Synchronized static method calls another synchronized static method 'internalGetElements' with the same lock held Language: English
    • Checkers:UC.BOOLB 214 Checkers:UC.BOOLB It is unnecessary to create new objects like String or Boolean by calling some of their constructors. Using factory methods, static instances or just expression values helps avoid unnecessary object creation. An UC.BOOLB warning appears if there is a call of new Boolean(boolean expression) constructor instead of using Boolean.valueOf(boolean expression) or singletons Boolean.TRUE, Boolean.FALSE. Vulnerability and risk This method creates extra objects which take up more memory and reduce performance, without any other functional effect. Example 1 11 ArrayList bool1(boolean arr[]) { 12 ArrayList res = new ArrayList(); 13 for (int i = 0; i < arr.length; i++) { 14 boolean b = arr[i]; 15 res.add(new Boolean(b)); 16 } 17 return res; 18 } UC.BOOLB is reported for line 15: Unnecessary object creation, new Boolean(boolean expression) method can be replaced with Boolean.valueOf(boolean expression), or with singletons Boolean.TRUE and Boolean.FALSE Language: English
    • Checkers:UC.BOOLS 215 Checkers:UC.BOOLS This warning appears if there is a call of new Boolean(string expression) constructor instead of using Boolean.valueOf(string expression). Vulnerability and risk This method creates extra objects which take up more memory and reduce performance, without any other functional effect. Example 1 11 ArrayList bool1(String arr[]) { 12 ArrayList res = new ArrayList(); 13 for (int i = 0; i < arr.length; i++) { 14 String b = arr[i]; 15 res.add(new Boolean(b)); 16 } 17 return res; 18 } UC.BOOLS is reported for line 15: Unnecessary object creation, new Boolean(string expression) method can be replaced with Boolean.valueOf(string expression) Language: English
    • Checkers:UC.STRS 216 Checkers:UC.STRS It is unnecessary to create new objects like String or Boolean by calling some of their constructors. Using factory methods, static instances or just expression values helps avoid unnecessary object creation. A UC.STRS warning appears if there is a call of new String(string expression) constructor instead of using string expression. Vulnerability and risk This method creates extra objects which take up more memory and reduce performance, without any other functional effect. Example 1 17 public String toString() { 18 return new String(name + ":" + age); 19 } 20 // fixed code 21 public String toString2() { 22 return name + ":" + age; 23 } UC.STRS is reported for line 18: Unnecessary object creation, new String(string expression) method can be replaced with string expression Language: English
    • Checkers:UC.STRV 217 Checkers:UC.STRV It is unnecessary to create new objects like String or Boolean by calling some of their constructors. Using factory methods, static instances or just expression values helps avoid unnecessary object creation. An UC.STRV warning appears if there is a call of new String() constructor instead of using empty string. Vulnerability and risk This method creates extra objects which take up more memory and reduce performance, without any other functional effect. Example 1 12 ArrayList str1(int n) { 13 ArrayList res = new ArrayList(); 14 for (int i = 0; i < n; i++) { 15 16 res.add(new String()); 17 } 18 return res; 19 } 20 // correct one 21 ArrayList str2(int n) { 22 ArrayList res = new ArrayList(); 23 for (int i = 0; i < n; i++) { 24 25 res.add(""); 26 } 27 return res; 28 } UC.STRV is reported for line 16: Unnecessary object creation, new String() method can be replaced with empty string Language: English
    • Checkers:UF.IMAGEIO 218 Checkers:UF.IMAGEIO UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The UF.IMAGEIO warning indicates an attempt to use an ImageIO stream after it was closed. Example 1 17 public boolean canDecodeInput(ImageInputStream stream) { 18 byte[] b = new byte[8]; 19 try { 20 final long l = stream.length(); 21 if (l > 655335) { 22 return false; 23 } 24 stream.mark(); 25 stream.readFully(b); 26 stream.reset(); 27 } catch (IOException e) { 28 return false; 29 } finally { 30 try { 31 stream.close(); 32 } catch (IOException e) { 33 // do nothing 34 } 35 } 36 37 // Cast unsigned character constants prior to comparison 38 return (b[0] == (byte) 'm' && b[1] == (byte) 'y' && 39 b[2] == (byte) 'f' && b[3] == (byte) 'o' && 40 b[4] == (byte) 'r' && b[5] == (byte) 'm' && 41 b[6] == (byte) 'a' && b[7] == (byte) 't'); 42 } 43 44 public void decode(Object data) throws IOException { 45 final ImageInputStream stream = ImageIO.createImageInputStream(data); 46 if (canDecodeInput(stream)) { 47 try { 48 final int[] colors = new int[(int) stream.length()]; 49 for (int i = 0; i < colors.length; i++) { 50 colors[i] = stream.readInt(); 51 } 52 } catch (IOException e) {
    • Checkers:UF.IMAGEIO 219 53 e.printStackTrace(); 54 } 55 } 56 57 } UF.IMAGEIO is reported for the snippet on line 48: image input stream 'stream' is used after it was closed on line 31. Example 2 17 public boolean canDecodeInput(ImageInputStream stream) { 18 byte[] b = new byte[8]; 19 try { 20 final long l = stream.length(); 21 if (l > 655335) { 22 return false; 23 } 24 stream.mark(); 25 stream.readFully(b); 26 stream.reset(); 27 } catch (IOException e) { 28 return false; 29 } 30 31 // Cast unsigned character constants prior to comparison 32 return (b[0] == (byte) 'm' && b[1] == (byte) 'y' && 33 b[2] == (byte) 'f' && b[3] == (byte) 'o' && 34 b[4] == (byte) 'r' && b[5] == (byte) 'm' && 35 b[6] == (byte) 'a' && b[7] == (byte) 't'); 36 } 37 38 public void decode(Object data) throws IOException { 39 final ImageInputStream stream = ImageIO.createImageInputStream(data); 40 try { 41 if (canDecodeInput(stream)) { 42 try { 43 final int[] colors = new int[(int) stream.length()]; 44 for (int i = 0; i < colors.length; i++) { 45 colors[i] = stream.readInt(); 46 } 47 } catch (IOException e) { 48 e.printStackTrace();
    • Checkers:UF.IMAGEIO 220 49 } 50 } 51 } finally { 52 stream.close(); 53 } 54 } The snippet from the previous section is fixed. Method 'canDecodeInput' no longer closes the stream. Now it is closed by the 'decode' method, which is the method that opened the stream. In general, it is good coding practice to release a resource with the same method that originally allocated the resource. Language: English
    • Checkers:UF.IN 221 Checkers:UF.IN UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The UF.IN warning indicates an attempt to use an input stream after it was closed. Example 1 18 public boolean checkMeta(InputStream stream) { 19 byte[] b = new byte[8]; 20 try { 21 final long l = stream.available(); 22 if (l < 8) { 23 return false; 24 } 25 stream.read(b); 26 } catch (IOException e) { 27 return false; 28 } finally { 29 try { 30 stream.close(); 31 } catch (IOException e) { 32 // do nothing 33 } 34 } 35 36 // Cast unsigned character constants prior to comparison 37 return (b[0] == (byte) 'm' && b[1] == (byte) 'y' && 38 b[2] == (byte) 'f' && b[3] == (byte) 'o' && 39 b[4] == (byte) 'r' && b[5] == (byte) 'm' && 40 b[6] == (byte) 'a' && b[7] == (byte) 't'); 41 } 42 43 public void printOut(final URL url, final PrintStream ps) throws IOException { 44 final InputStream stream = url.openStream(); 45 if (checkMeta(stream)) { 46 try { 47 ps.println("content:"); 48 byte[] b = new byte[1024]; 49 int i; 50 while ((i = stream.read(b)) > 0) { 51 ps.print(new String(b, 0, i)); 52 } 53 ps.println();
    • Checkers:UF.IN 222 54 } catch (IOException e) { 55 e.printStackTrace(); 56 } 57 } 58 } UF.IN is reported for the snippet on line 50: input stream 'stream' is used after it was closed on line 30. Example 2 18 public boolean checkMeta(InputStream stream) { 19 byte[] b = new byte[8]; 20 try { 21 final long l = stream.available(); 22 if (l < 8) { 23 return false; 24 } 25 stream.read(b); 26 } catch (IOException e) { 27 return false; 28 } 29 30 // Cast unsigned character constants prior to comparison 31 return (b[0] == (byte) 'm' && b[1] == (byte) 'y' && 32 b[2] == (byte) 'f' && b[3] == (byte) 'o' && 33 b[4] == (byte) 'r' && b[5] == (byte) 'm' && 34 b[6] == (byte) 'a' && b[7] == (byte) 't'); 35 } 36 37 public void printOut(final URL url, final PrintStream ps) throws IOException { 38 final InputStream stream = url.openStream(); 39 try { 40 if (checkMeta(stream)) { 41 try { 42 ps.println("content:"); 43 byte[] b = new byte[1024]; 44 int i; 45 while ((i = stream.read(b)) > 0) { 46 ps.print(new String(b, 0, i)); 47 } 48 ps.println(); 49 } catch (IOException e) { 50 e.printStackTrace(); 51 }
    • Checkers:UF.IN 223 52 } 53 } finally { 54 try { 55 stream.close(); 56 } catch (IOException e) { 57 // do nothing 58 } 59 } 60 } The snippet from the previous section is fixed. Method 'checkMeta' no longer closes the stream. Now it is closed by the 'printOut' method, which is the method that opened the stream. In general, it is good coding practice to release resources with the same methods in which they were originally allocated. Language: English
    • Checkers:UF.JNDI 224 Checkers:UF.JNDI UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The UF.JNDI warning indicates an attempt to use a JNDI context after it was closed. Example 1 25 public void scan(Name name, String... filters) { 26 try { 27 DirContext ctx = initContext(); 28 try { 29 for (final String filter : filters) { 30 search(name, filter, ctx); 31 } 32 } finally { 33 ctx.close(); 34 } 35 } catch (NamingException e) { 36 e.printStackTrace(); 37 } 38 } 39 40 private DirContext initContext() throws NamingException { 41 Hashtable env = new Hashtable(11); 42 env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); 43 env.put(Context.PROVIDER_URL, "ldap:///o=JndiSample,dc=example,dc=com"); 44 45 DirContext ctx = new InitialDirContext(env); 46 return ctx; 47 } 48 49 private void search(Name name, String filter, DirContext ctx) throws NamingException { 50 try { 51 final SearchControls searchControls = new SearchControls(); 52 searchControls.setReturningAttributes(necessaryItemAttributes); 53 searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); 54 final NamingEnumeration<SearchResult> resultNamingEnumeration = ctx.search(name, filter, searchControls); 55 } catch (NamingException e) { 56 ctx.close(); 57 }
    • Checkers:UF.JNDI 225 58 } UF.JNDI is reported for the snippet on line 30: JNDI context 'ctx' is accessed in the for-cycle in method 'scan' (see line 54). This is a problem because 'ctx' could be previously closed on one of the iterations as the result of an exception happening in method 'search' on line 56. Example 2 25 public void scan(Name name, String... filters) { 26 try { 27 DirContext ctx = initContext(); 28 try { 29 for (final String filter : filters) { 30 search(name, filter, ctx); 31 } 32 } finally { 33 ctx.close(); 34 } 35 } catch (NamingException e) { 36 e.printStackTrace(); 37 } 38 } 39 40 private DirContext initContext() throws NamingException { 41 Hashtable env = new Hashtable(11); 42 env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); 43 env.put(Context.PROVIDER_URL, "ldap:///o=JndiSample,dc=example,dc=com"); 44 45 DirContext ctx = new InitialDirContext(env); 46 return ctx; 47 } 48 49 private void search(Name name, String filter, DirContext ctx) throws NamingException { 50 final SearchControls searchControls = new SearchControls(); 51 searchControls.setReturningAttributes(necessaryItemAttributes); 52 searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); 53 final NamingEnumeration<SearchResult> resultNamingEnumeration = ctx.search(name, filter, searchControls); 54 } The snippet from the previous section is fixed. Method 'search' no longer closes the stream. Now it is closed by the 'scan' method, which is the method that opened the stream. In general, it is good coding practice to release resources with the same methods in which they were originally allocated. Language: English
    • Checkers:UF.JNDI 226
    • Checkers:UF.MAIL 227 Checkers:UF.MAIL UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The UF.MAIL warning indicates an attempt to use Java Mail API object after it was closed. Example 1 13 public Collection<Message> getMessages(final Session session, 14 final String... folderNames) throws MessagingException { 15 final Collection<Message> result = new ArrayList<Message>(); 16 Store store = session.getStore("pop3"); 17 store.connect(); 18 19 for (String folderName : folderNames) { 20 Folder folder = getFolder(store, folderName); 21 if (folder != null) { 22 Message messages[] = folder.getMessages(); 23 for (int i = 0, n = messages.length; i < n; i++) { 24 result.add(messages[i]); 25 } 26 } 27 } 28 29 return result; 30 } 31 32 private Folder getFolder(Store store, final String folderName) throws MessagingException { 33 if (folderName == null) { 34 return null; 35 } 36 37 try { 38 Folder folder = store.getFolder(folderName); 39 folder.open(Folder.READ_ONLY); 40 return folder; 41 } catch (MessagingException e) { 42 store.close(); 43 } 44 return null; 45 } UF.MAIL is reported for the snippet on line 20: Java Mail API object 'store' is closed by method 'getFolder()' in case if MessagingException is thrown on line 38. This is a problem because on the next iteration of the cycle the method 'getFolder()' would be called once more and it will attempt to access the closed store.
    • Checkers:UF.MAIL 228 Example 2 13 public Collection<Message> getMessages(final Session session, 14 final String... folderNames) throws MessagingException { 15 final Collection<Message> result = new ArrayList<Message>(); 16 Store store = session.getStore("pop3"); 17 store.connect(); 18 19 for (String folderName : folderNames) { 20 Folder folder = getFolder(store, folderName); 21 if (folder != null) { 22 Message messages[] = folder.getMessages(); 23 for (int i = 0, n = messages.length; i < n; i++) { 24 result.add(messages[i]); 25 } 26 } 27 } 28 29 return result; 30 } 31 32 private Folder getFolder(Store store, final String folderName) throws MessagingException { 33 if (folderName == null) { 34 return null; 35 } 36 37 try { 38 Folder folder = store.getFolder(folderName); 39 folder.open(Folder.READ_ONLY); 40 return folder; 41 } catch (MessagingException e) { 42 store.close(); 43 throw e; 44 } 45 } The snippet from the previous section is fixed. Method 'getFolder()' re-throws the MessagingExcpetion now. Language: English
    • Checkers:UF.MICRO 229 Checkers:UF.MICRO UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The UF.MICRO warning indicates an attempt to use Java MicroEdition object after it was closed. Example 1 20 class DBTestMidlet extends MIDlet { 21 22 private Display display; 23 private int nextRecordId; 24 25 public DBTestMidlet() { 26 display = Display.getDisplay(this); 27 28 RecordStore store = null; 29 try { 30 store = RecordStore.openRecordStore("TestStore", true); 31 nextRecordId = store.getNextRecordID(); 32 } catch (RecordStoreException e) { 33 handleException(e); 34 if (store != null) { 35 try { 36 store.closeRecordStore(); 37 } catch (RecordStoreException e1) { 38 // ignore 39 } 40 } 41 } 42 43 try { 44 final String name = store.getName(); 45 display.setCurrent(new TextBox("", "Connected to database: " + name, 6000, TextField.ANY)); 46 } catch (Exception e) { 47 handleException(e); 48 } 49 } 50 51 private void handleException(Exception e) { 52 display.setCurrent(new TextBox("Error", e.toString(), 60000, TextField.ANY)); 53 } 54 55 public void startApp() { 56 }
    • Checkers:UF.MICRO 230 57 58 public void pauseApp() { 59 } 60 61 public void destroyApp(boolean unconditional) { 62 } 63 } UF.MICRO is reported for the snippet on line 44: There is attempt to get the name of the Java MicroEdition record store which is closed on line 36 in case if RecordStoreException is thrown on line 31. Language: English
    • Checkers:UF.NIO 231 Checkers:UF.NIO UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The UF.NIO warning indicates an attempt to use a java.nio.* object after it was closed. Example 1 15 public boolean checkMeta(ReadableByteChannel channel) { 16 final ByteBuffer b = ByteBuffer.allocate(8); 17 try { 18 final int i = channel.read(b); 19 if (i < 8) { 20 return false; 21 } 22 } catch (IOException e) { 23 return false; 24 } finally { 25 try { 26 channel.close(); 27 } catch (IOException e) { 28 // do nothing 29 } 30 } 31 32 // Cast unsigned character constants prior to comparison 33 return (b.get(0) == (byte) 'm' && b.get(1) == (byte) 'y' && 34 b.get(2) == (byte) 'f' && b.get(3) == (byte) 'o' && 35 b.get(4) == (byte) 'r' && b.get(5) == (byte) 'm' && 36 b.get(6) == (byte) 'a' && b.get(7) == (byte) 't'); 37 } 38 39 public void printOut(final String path) throws IOException { 40 final ReadableByteChannel ch = new FileInputStream(path).getChannel(); 41 if (checkMeta(ch)) { 42 try { 43 final ByteBuffer b = ByteBuffer.allocate(1024); 44 int i; 45 while ((i = ch.read(b)) > 0) { 46 print(b); 47 } 48 } catch (IOException e) { 49 e.printStackTrace();
    • Checkers:UF.NIO 232 50 } 51 } 52 } 53 54 public void print(final ByteBuffer b) { 55 while (b.hasRemaining()) { 56 System.out.print(b); 57 } 58 b.clear(); 59 } UF.NIO is reported for the snippet on line 45: There is an attempt to read from the channel which is closed on line 26 Language: English
    • Checkers:UF.OUT 233 Checkers:UF.OUT UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The UF.OUT warning indicates an attempt to use an output stream after it was closed. Example 1 15 public boolean writeMeta(OutputStream stream) { 16 try { 17 stream.write("mystate".getBytes()); 18 } catch (IOException e) { 19 return false; 20 } finally { 21 try { 22 stream.close(); 23 } catch (IOException e) { 24 // do nothing 25 } 26 } 27 return true; 28 } 29 30 public void saveState(final String path, final byte[] data) throws IOException { 31 final FileOutputStream stream = new FileOutputStream(path); 32 if (writeMeta(stream)) { 33 stream.write(data); 34 } 35 } UF.OUT is reported for the snippet on line 33: the output stream 'stream' is used after it was closed on line 22. Language: English
    • Checkers:UF.SOCK 234 Checkers:UF.SOCK UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The UF.SOCK warning indicates an attempt to use a socket after it was closed. Example 1 16 private Socket s; 17 18 private void message(final Socket s, final String message) { 19 try { 20 s.getOutputStream().write(message.getBytes()); 21 } catch (IOException e) { 22 try { 23 s.close(); 24 } catch (IOException e1) { 25 //ignore 26 } 27 } 28 } 29 30 public void handshake() { 31 message(s, "hello"); 32 } 33 34 public void requestData(final String key) throws IOException { 35 handshake(); 36 message(s, "get_data[" + key + ']'); 37 } UF.SOCK is reported for the snippet on line 36: if an IOExcpetion is thrown on line 20, then 'socket' will be closed on line 23. However, the method 'message' called on line 36 will attempt to write into the socket whether it was closed or not. Language: English
    • Checkers:UF.SQLCON 235 Checkers:UF.SQLCON UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The UF.SQLCON warning indicates an attempt to use a JDBC connection after it was closed. Example 1 26 public List<String> order() { 27 final List<String> strings = new ArrayList<String>(); 28 populate(strings, 1, 3, 5, 7, 9); 29 populate(strings, 0, 2, 4, 6, 8); 30 return strings; 31 } 32 33 public void populate(List<String> data, int... keys) { 34 try { 35 PreparedStatement ps = conn.prepareStatement("SELECT * FROM Table where key=?"); 36 try { 37 for (int key : keys) { 38 ps.setInt(1, key); 39 final ResultSet resultSet = ps.executeQuery(); 40 try { 41 populate(data, resultSet); 42 } finally { 43 resultSet.close(); 44 } 45 } 46 } catch (SQLException e) { 47 conn.close(); 48 } finally { 49 ps.close(); 50 } 51 } catch (SQLException e) { 52 // do nothing 53 } 54 } 55 56 public void populate(List<String> data, ResultSet rs) throws SQLException { 57 while (rs.next()) { 58 String s = rs.getString(1); 59 data.add(s); 60 } 61 }
    • Checkers:UF.SQLCON 236 UF.SQLCON is reported for the snippet on line 29 since the method 'populate' called on line 28 is closing the JDBC connection 'conn' in case of any SQLException thrown. That means that the next call to 'populate' on line 29 might attempt to use the closed connection. Language: English
    • Checkers:UF.SQLOBJ 237 Checkers:UF.SQLOBJ UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The UF.SQLOBJ warning indicates an attempt to use a JDBC object (such as a statement, prepared statement or result set) after it was closed. Example 1 28 public List<String> order() { 29 final List<String> strings = new ArrayList<String>(); 30 populate(strings, 1, 3, 5, 7, 9); 31 return strings; 32 } 33 34 public void populate(List<String> data, int... keys) { 35 try { 36 try { 37 ps = conn.prepareStatement("SELECT * FROM Table where key=?"); 38 for (int key : keys) { 39 populate(data, key); 40 } 41 } finally { 42 ps.close(); 43 } 44 } catch (SQLException e) { 45 // do nothing 46 } 47 } 48 49 public void populate(List<String> data, int key) { 50 try { 51 ps.setInt(1, key); 52 final ResultSet rs = ps.executeQuery(); 53 try { 54 while (rs.next()) { 55 String s = rs.getString(1); 56 data.add(s); 57 } 58 } finally { 59 rs.close(); 60 } 61 } catch (SQLException e) { 62 try { 63 ps.close(); 64 } catch (SQLException e1) {
    • Checkers:UF.SQLOBJ 238 65 // do nothing 66 } 67 } 68 } UF.SQLOBJ is reported for the snippet on line 39: the method 'populate(List<String> data, int... keys)' is called on line 39 on every iteration of the cycle. This method is closing the prepared statement 'ps' in case of any SQLException thrown (see line 63). This might cause an attempt to use the closed prepared statemnt on the next iteration of the cycle. Language: English
    • Checkers:UF.ZIP 239 Checkers:UF.ZIP UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The UF.ZIP warning indicates an attempt to use a ZipFile after it was closed. Example 1 18 public static final void copy(InputStream in, OutputStream out) throws IOException { 19 byte[] buffer = new byte[1024]; 20 int len; 21 22 while ((len = in.read(buffer)) >= 0) { 23 out.write(buffer, 0, len); 24 } 25 26 in.close(); 27 out.close(); 28 } 29 30 public final void unzip(final ZipFile zipFile) { 31 Enumeration entries; 32 entries = zipFile.entries(); 33 34 try { 35 while (entries.hasMoreElements()) { 36 ZipEntry entry = (ZipEntry) entries.nextElement(); 37 38 if (entry.isDirectory()) { 39 final File dir = new File(entry.getName()); 40 dir.mkdir(); 41 } else { 42 try { 43 copy(zipFile.getInputStream(entry), new FileOutputStream(entry.getName())); 44 } catch (IOException e) { 45 zipFile.close(); 46 } 47 } 48 } 49 50 zipFile.close(); 51 } catch (IOException e) { 52 // do nothing 53 } 54 }
    • Checkers:UF.ZIP 240 UF.ZIP is reported for the snippet on line 43: 'zipFile' is closed on line 45 in case of an IOException, but there will be an attempt to access ‘zipFile’ on the next iteration of the cycle. Language: English
    • Checkers:UMC.EXIT 241 Checkers:UMC.EXIT The "UMC Unwanted method calls" group of errors relates to methods such as System.exit() and System.gc() that might be unwanted. Debug print, such as System.out.println() and System.err.println(), might be unwanted as well. A UMC.EXIT warning appears if there is a call to the System.exit method. Vulnerability and risk Use of this method should be limited to one occurrence. The exiting of the JVM is an unwanted side effect: it is better to throw an exception or error, and let the caller deal with it. Example 1 10 String square(String x) { 11 try { 12 int y = Integer.parseInt(x.toLowerCase()); 13 return y * y + ""; 14 } catch (NumberFormatException e) { 15 e.printStackTrace(); 16 System.exit(1); 17 return ""; 18 } 19 } UMC.EXIT is reported for line 16: The System.exit() method call is unwanted Security Guidelines • CWE-382: J2EE Bad Practices: Use of System.exit() [42] Language: English
    • Checkers:UMC.GC 242 Checkers:UMC.GC The "UMC Unwanted method calls" group of errors relates to some methods, such as System.exit() and System.gc() that might be unwanted. Debug print, such as System.out.println() and System.err.println(), might be unwanted as well. A UMC.GC warning appears if there is a call to the System.gc() method. Vulnerability and risk This method should only be used in performance-related testing procedure; otherwise the impact might be opposite of that expected. Example 1 10 String multiply(String x, int n) { 11 if (n <= 0) return ""; 12 StringBuffer buf = new StringBuffer(); 13 while (n-- > 0) { 14 buf.append(x); 15 } 16 return buf.toString(); 17 } 18 String multiplyGc(String x, int n) { 19 System.gc(); // see perfromance resutlts if run this test 20 return multiply(x, n); 21 } UMC.GC is reported for line 19: The System.gc() method call is unwanted Language: English
    • Checkers:UMC.SYSERR 243 Checkers:UMC.SYSERR The "UMC Unwanted method calls" group of errors relates to methods such as System.exit() and System.gc() that might be unwanted. Debug print, such as System.out.println() and System.err.println(), might be unwanted as well. A UMC.SYSERR warning appears if there is a call to a print method of the System.err stream. Vulnerability and risk In a mature application, this call should be limited to one logging module and functional console output; otherwise it causes misused diagnostics, which should be fixed. Mitigation and prevention Replace calls that print to syserr with calls to the Logger module. Replace calls that print to stdout either with calls to the Logger or with calls to specific methods, for example printRawToUser(). Example 1 9 public int internalCalculateSum(int x, int y) { 10 if (x < 0 || y < 0) { 11 System.err.println("XXX: got strange arguments!"); 12 } 13 return x + y; 14 } UMC.SYSERR is reported for line 11: Debug print using System.err method calls is unwanted. Security Guidelines • CWE-576: EJB Bad Practices: Use of Java I/O [47] Language: English
    • Checkers:UMC.SYSOUT 244 Checkers:UMC.SYSOUT The "UMC Unwanted method calls" group of errors relates to methods such as System.exit() and System.gc() that might be unwanted. Debug print, such as System.out.println() and System.err.println(), might be unwanted as well. A UMC.SYSOUT warning appears if there is a call to a print method of the System.out stream. Vulnerability and risk In a mature application, this call should be limited to one logging module and functional console output; otherwise it causes misused diagnostics, which should be fixed. Mitigation and prevention Replace calls that print to syserr with calls to the Logger module. Replace calls that print to stdout either with calls to the Logger or with calls to specific methods, for example printRawToUser(). Example 1 9 public int internalCalculateSum(int x, int y) { 10 if (x < 0 || y < 0) { 11 System.out.println("XXX: got strange arguments!"); 12 } 13 return x + y; 14 } UMC.SYSOUT is reported for line 11: Debug print using System.out method calls is unwanted. Security Guidelines • CWE-576: EJB Bad Practices: Use of Java I/O [47] Language: English
    • Checkers:UMC.TOSTRING 245 Checkers:UMC.TOSTRING A UMC.TOSTRING warning appears if there is a call to the toString() method on a string argument. Removing such call can help optimize the code in certain cases. Vulnerability and risk This method creates extra objects which take up more memory and reduce performance, without any other functional effect. Example 1 12 ArrayList bool1(String arr[]) { 13 ArrayList res = new ArrayList(); 14 for (int i = 0; i < arr.length; i++) { 15 String b = arr[i]; 16 res.add(b); 17 } 18 return res; 19 } 20 // correct one 21 ArrayList bool2(String arr[]) { 22 ArrayList res = new ArrayList(); 23 for (int i = 0; i < arr.length; i++) { 24 String b = arr[i]; 25 res.add(b.toString()); 26 } 27 return res; 28 } UMC.TOSTRING is reported for line 25: Unnecessary toString() method is called for String argument. Use argument instead Language: English
    • License 246 License Copyright © 1998-2009 Klocwork Inc. All rights reserved This document, as well as the software described in it, is furnished under license and may only be used or copied in accordance with the terms of such license. The information contained herein is the property of Klocwork Inc. and is confidential between Klocwork Inc. and the client and remains the exclusive property of Klocwork Inc. No part of this documentation may be copied, translated, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise without the prior written permission of Klocwork Inc. If you find any problems in the documentation, please report them to us in writing. Klocwork Inc. does not warrant that this document is error-free. Klocwork Inc. and Klocwork are registered trademarks and Klocwork Insight, Klocwork Solo, Klocwork Insight Architect, Klocwork Insight Review, Klocwork Source Cross-Reference, Klocwork Management Console, Klocwork Developer for Java in Eclipse, Klocwork for C/C++, Klocwork for Java, Klocwork Extensibility Interface, Klocwork Stack Overflow Analyzer, and Klocwork Truepath are trademarks of Klocwork Inc. Copyright notices for third-party software are contained in the file 3rdparty_copyright_notices.txt, located in the Klocwork installation directory. Adobe®, Adobe Acrobat, Acrobat Exchange, Acrobat Reader, and PostScript are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries. Rational ClearCase is a registered trademark of IBM Corporation. Linux is a registered trademark of Linus Torvalds. FLEXlm is a registered trademark of Macrovision Corporation. Microsoft®, Microsoft Word, Microsoft Excel, Microsoft Office, Internet Explorer, Windows®, Windows NT®, Windows® 2000, Windows® 2000 Server, Windows® Server 2003, Windows® XP, MS-DOS™, Microsoft Visual Studio®, Microsoft .NET, and Microsoft Visual C++ are trademarks of Microsoft Corporation. Pentium® is a registered trademark of Intel Corporation. Red Hat is a trademark of Red Hat, Inc., in the United States and other countries. Sun, Sun Microsystems, the Sun Logo, Solaris, Forte, Java, JRE and all Java-related trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. in the United States and other countries. Products bearing SPARC trademarks are based upon an architecture developed by Sun Microsystems, Inc. MySQL is a registered trademark of MySQL AB in the USA and other countries. InstallShield is a service mark and is either a registered trademark or trademark of InstallShield Software Corporation in the United States and/or other countries. IntelliJ IDEA is either a trademark or a registered trademark of JetBrains, Inc. Java Service Wrapper is a trademark of Tanuki Software. WinCVS, Krusader and SourceForge are trademarks of OSTG Open Source Technology Group, All Rights Reserved. Freemind is a trademark of Freemind Solutions, Inc. Apache TomCat is a trademark of the Apache Software Foundation. Green Hills is a registered trademark of Green Hills Software, Inc. Metrowerks is a registered trademark and StarCore and AltiVec are trademarks of Freescale Semiconductor, Inc. Wind River is a registered trademark of Wind River Systems, Inc. yEd is a trademark of yWorks GmbH. JBuilder is a registered trademark of Borland Software Corporation. BEA WebLogic is a registered trademark of BEA Systems, Inc. Carbide.c++ is a registered trademark of Nokia Corporation. AIX is a registered trademark of IBM Corporation. Electric Cloud is a trademark of Electric Cloud, Inc. Apple Safari is a registered trademark of Apple, Inc., registered in the U.S. and other countries. Klocwork Inc. Toll-free telephone (North America): 1-866-556-2967 E-mail: sales@klocwork.com or support@klocwork.com Web site: http:/ / www. klocwork. com In the U.S.: 8 New England Executive Park, Suite 180 Burlington, Massachusetts 01803 USA In Canada: 30 Edgewater Street, Suite 114 Ottawa, Ontario Canada K2L 1V8