Sie sind auf Seite 1von 1019

CWE Version 1.8.

Edited by:
Steven M. Christey, Conor O. Harris,
Janis E. Kenderdine, and Brendan Miles

Project Lead:
Robert A. Martin
CWE Version 1.8.1
2010-04-05

CWE is a Software Assurance strategic initiative sponsored by the National


Cyber Security Division of the U.S. Department of Homeland Security

Copyright 2010, The MITRE Corporation

CWE and the CWE logo are trademarks of The MITRE Corporation
Contact cwe@mitre.org for more information
CWE Version 1.8.1
Table of Contents

Table of Contents
Symbols Used in CWE ................................................................................................................... xvii
Individual CWE Definitions
CWE-1: Location................................................................................................................................................. 1
CWE-2: Environment.......................................................................................................................................... 1
CWE-3: Technology-specific Environment Issues.............................................................................................. 1
CWE-4: J2EE Environment Issues..................................................................................................................... 2
CWE-5: J2EE Misconfiguration: Data Transmission Without Encryption............................................................ 2
CWE-6: J2EE Misconfiguration: Insufficient Session-ID Length......................................................................... 3
CWE-7: J2EE Misconfiguration: Missing Custom Error Page............................................................................ 4
CWE-8: J2EE Misconfiguration: Entity Bean Declared Remote......................................................................... 5
CWE-9: J2EE Misconfiguration: Weak Access Permissions for EJB Methods................................................... 6
CWE-10: ASP.NET Environment Issues............................................................................................................ 7
CWE-11: ASP.NET Misconfiguration: Creating Debug Binary........................................................................... 7
CWE-12: ASP.NET Misconfiguration: Missing Custom Error Page.................................................................... 8
CWE-13: ASP.NET Misconfiguration: Password in Configuration File............................................................... 9
CWE-14: Compiler Removal of Code to Clear Buffers..................................................................................... 10
CWE-15: External Control of System or Configuration Setting........................................................................ 12
CWE-16: Configuration..................................................................................................................................... 13
CWE-17: Code.................................................................................................................................................. 14
CWE-18: Source Code..................................................................................................................................... 14
CWE-19: Data Handling.................................................................................................................................... 14
CWE-20: Improper Input Validation.................................................................................................................. 15
CWE-21: Pathname Traversal and Equivalence Errors................................................................................... 23

Table of Contents
CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')................................ 24
CWE-23: Relative Path Traversal..................................................................................................................... 31
CWE-24: Path Traversal: '../filedir'.................................................................................................................... 34
CWE-25: Path Traversal: '/../filedir'................................................................................................................... 35
CWE-26: Path Traversal: '/dir/../filename'......................................................................................................... 35
CWE-27: Path Traversal: 'dir/../../filename'....................................................................................................... 36
CWE-28: Path Traversal: '..\filedir'.................................................................................................................... 37
CWE-29: Path Traversal: '\..\filename'.............................................................................................................. 39
CWE-30: Path Traversal: '\dir\..\filename'......................................................................................................... 40
CWE-31: Path Traversal: 'dir\..\..\filename'....................................................................................................... 41
CWE-32: Path Traversal: '...' (Triple Dot)......................................................................................................... 42
CWE-33: Path Traversal: '....' (Multiple Dot)..................................................................................................... 43
CWE-34: Path Traversal: '....//'......................................................................................................................... 44
CWE-35: Path Traversal: '.../...//'...................................................................................................................... 45
CWE-36: Absolute Path Traversal.................................................................................................................... 47
CWE-37: Path Traversal: '/absolute/pathname/here'........................................................................................ 47
CWE-38: Path Traversal: '\absolute\pathname\here'........................................................................................ 48
CWE-39: Path Traversal: 'C:dirname'............................................................................................................... 49
CWE-40: Path Traversal: '\\UNC\share\name\' (Windows UNC Share)............................................................ 50
CWE-41: Improper Resolution of Path Equivalence......................................................................................... 51
CWE-42: Path Equivalence: 'filename.' (Trailing Dot)....................................................................................... 53
CWE-43: Path Equivalence: 'filename....' (Multiple Trailing Dot)...................................................................... 53
CWE-44: Path Equivalence: 'file.name' (Internal Dot)...................................................................................... 54
CWE-45: Path Equivalence: 'file...name' (Multiple Internal Dot)....................................................................... 54
CWE-46: Path Equivalence: 'filename ' (Trailing Space).................................................................................. 55
CWE-47: Path Equivalence: ' filename (Leading Space)................................................................................. 56
CWE-48: Path Equivalence: 'file name' (Internal Whitespace)......................................................................... 56
CWE-49: Path Equivalence: 'filename/' (Trailing Slash)................................................................................... 57
CWE-50: Path Equivalence: '//multiple/leading/slash'....................................................................................... 57
CWE-51: Path Equivalence: '/multiple//internal/slash'....................................................................................... 58
CWE-52: Path Equivalence: '/multiple/trailing/slash//'....................................................................................... 59
CWE-53: Path Equivalence: '\multiple\\internal\backslash'............................................................................... 59
CWE-54: Path Equivalence: 'filedir\' (Trailing Backslash)................................................................................. 60
CWE-55: Path Equivalence: '/./' (Single Dot Directory).................................................................................... 60
CWE-56: Path Equivalence: 'filedir*' (Wildcard)................................................................................................ 61
iii
CWE Version 1.8.1
Table of Contents

CWE-57: Path Equivalence: 'fakedir/../realdir/filename'.................................................................................... 61


CWE-58: Path Equivalence: Windows 8.3 Filename........................................................................................ 62
CWE-59: Improper Link Resolution Before File Access ('Link Following')........................................................ 63
CWE-60: UNIX Path Link Problems................................................................................................................. 64
CWE-61: UNIX Symbolic Link (Symlink) Following.......................................................................................... 65
CWE-62: UNIX Hard Link................................................................................................................................. 66
CWE-63: Windows Path Link Problems........................................................................................................... 67
CWE-64: Windows Shortcut Following (.LNK).................................................................................................. 68
CWE-65: Windows Hard Link........................................................................................................................... 69
CWE-66: Improper Handling of File Names that Identify Virtual Resources.................................................... 69
CWE-67: Improper Handling of Windows Device Names................................................................................ 70
CWE-68: Windows Virtual File Problems......................................................................................................... 71
CWE-69: Failure to Handle Windows ::DATA Alternate Data Stream.............................................................. 72
CWE-70: Mac Virtual File Problems................................................................................................................. 73
CWE-71: Apple '.DS_Store'.............................................................................................................................. 73
CWE-72: Improper Handling of Apple HFS+ Alternate Data Stream Path....................................................... 74
CWE-73: External Control of File Name or Path.............................................................................................. 75
CWE-74: Failure to Sanitize Data into a Different Plane ('Injection')................................................................ 79
CWE-75: Failure to Sanitize Special Elements into a Different Plane (Special Element Injection)................... 81
CWE-76: Failure to Resolve Equivalent Special Elements into a Different Plane............................................ 82
CWE-77: Improper Sanitization of Special Elements used in a Command ('Command Injection')................... 82
CWE-78: Improper Sanitization of Special Elements used in an OS Command ('OS Command Injection')...... 86
CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting')....................................................... 92
CWE-80: Improper Sanitization of Script-Related HTML Tags in a Web Page (Basic XSS)............................ 99
CWE-81: Improper Sanitization of Script in an Error Message Web Page..................................................... 101
CWE-82: Improper Sanitization of Script in Attributes of IMG Tags in a Web Page....................................... 102
CWE-83: Improper Neutralization of Script in Attributes in a Web Page........................................................ 103
Table of Contents

CWE-84: Failure to Resolve Encoded URI Schemes in a Web Page............................................................ 104


CWE-85: Doubled Character XSS Manipulations........................................................................................... 105
CWE-86: Improper Neutralization of Invalid Characters in Identifiers in Web Pages..................................... 106
CWE-87: Failure to Sanitize Alternate XSS Syntax....................................................................................... 107
CWE-88: Argument Injection or Modification.................................................................................................. 108
CWE-89: Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection')................. 111
CWE-90: Failure to Sanitize Data into LDAP Queries ('LDAP Injection')....................................................... 119
CWE-91: XML Injection (aka Blind XPath Injection)....................................................................................... 119
CWE-92: DEPRECATED: Improper Sanitization of Custom Special Characters........................................... 120
CWE-93: Failure to Sanitize CRLF Sequences ('CRLF Injection')................................................................. 121
CWE-94: Failure to Control Generation of Code ('Code Injection')................................................................ 122
CWE-95: Improper Sanitization of Directives in Dynamically Evaluated Code ('Eval Injection')..................... 125
CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')................. 127
CWE-97: Failure to Sanitize Server-Side Includes (SSI) Within a Web Page................................................ 128
CWE-98: Improper Control of Filename for Include/Require Statement in PHP Program ('PHP File
Inclusion')........................................................................................................................................................ 129
CWE-99: Improper Control of Resource Identifiers ('Resource Injection')...................................................... 134
CWE-100: Technology-Specific Input Validation Problems............................................................................ 135
CWE-101: Struts Validation Problems............................................................................................................ 136
CWE-102: Struts: Duplicate Validation Forms................................................................................................ 136
CWE-103: Struts: Incomplete validate() Method Definition............................................................................. 137
CWE-104: Struts: Form Bean Does Not Extend Validation Class.................................................................. 138
CWE-105: Struts: Form Field Without Validator............................................................................................. 139
CWE-106: Struts: Plug-in Framework not in Use........................................................................................... 140
CWE-107: Struts: Unused Validation Form.................................................................................................... 141
CWE-108: Struts: Unvalidated Action Form................................................................................................... 141
CWE-109: Struts: Validator Turned Off.......................................................................................................... 142
CWE-110: Struts: Validator Without Form Field............................................................................................. 143
CWE-111: Direct Use of Unsafe JNI.............................................................................................................. 145
CWE-112: Missing XML Validation................................................................................................................. 146
CWE-113: Failure to Sanitize CRLF Sequences in HTTP Headers ('HTTP Response Splitting')................... 147
CWE-114: Process Control............................................................................................................................. 150
CWE-115: Misinterpretation of Input............................................................................................................... 152
CWE-116: Improper Encoding or Escaping of Output.................................................................................... 153

iv
CWE Version 1.8.1
Table of Contents

CWE-117: Improper Output Sanitization for Logs.......................................................................................... 158


CWE-118: Improper Access of Indexable Resource ('Range Error').............................................................. 160
CWE-119: Failure to Constrain Operations within the Bounds of a Memory Buffer....................................... 160
CWE-120: Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')........................................ 166
CWE-121: Stack-based Buffer Overflow......................................................................................................... 171
CWE-122: Heap-based Buffer Overflow......................................................................................................... 173
CWE-123: Write-what-where Condition.......................................................................................................... 174
CWE-124: Buffer Underwrite ('Buffer Underflow')........................................................................................... 175
CWE-125: Out-of-bounds Read...................................................................................................................... 177
CWE-126: Buffer Over-read............................................................................................................................ 178
CWE-127: Buffer Under-read.......................................................................................................................... 179
CWE-128: Wrap-around Error........................................................................................................................ 179
CWE-129: Improper Validation of Array Index............................................................................................... 181
CWE-130: Improper Handling of Length Parameter Inconsistency ............................................................... 186
CWE-131: Incorrect Calculation of Buffer Size............................................................................................... 187
CWE-132: DEPRECATED (Duplicate): Miscalculated Null Termination......................................................... 192
CWE-133: String Errors.................................................................................................................................. 192
CWE-134: Uncontrolled Format String........................................................................................................... 192
CWE-135: Incorrect Calculation of Multi-Byte String Length.......................................................................... 196
CWE-136: Type Errors.................................................................................................................................... 197
CWE-137: Representation Errors................................................................................................................... 197
CWE-138: Improper Neutralization of Special Elements................................................................................ 197
CWE-139: DEPRECATED: General Special Element Problems.................................................................... 199
CWE-140: Failure to Sanitize Delimiters........................................................................................................ 200
CWE-141: Improper Neutralization of Parameter/Argument Delimiters.......................................................... 200
CWE-142: Improper Neutralization of Value Delimiters.................................................................................. 201
CWE-143: Improper Neutralization of Record Delimiters............................................................................... 202

Table of Contents
CWE-144: Improper Neutralization of Line Delimiters.................................................................................... 203
CWE-145: Improper Neutralization of Section Delimiters............................................................................... 204
CWE-146: Improper Neutralization of Expression/Command Delimiters........................................................ 205
CWE-147: Improper Neutralization of Input Terminators................................................................................ 206
CWE-148: Failure to Sanitize Input Leaders.................................................................................................. 206
CWE-149: Failure to Sanitize Quoting Syntax................................................................................................ 207
CWE-150: Improper Neutralization of Escape, Meta, or Control Sequences................................................. 208
CWE-151: Improper Neutralization of Comment Delimiters........................................................................... 209
CWE-152: Improper Neutralization of Macro Symbols................................................................................... 210
CWE-153: Improper Neutralization of Substitution Characters....................................................................... 211
CWE-154: Improper Neutralization of Variable Name Delimiters................................................................... 212
CWE-155: Improper Neutralization of Wildcards or Matching Symbols.......................................................... 213
CWE-156: Improper Neutralization of Whitespace......................................................................................... 213
CWE-157: Failure to Sanitize Paired Delimiters............................................................................................. 214
CWE-158: Improper Neutralization of Null Byte or NUL Character................................................................ 215
CWE-159: Failure to Sanitize Special Element.............................................................................................. 217
CWE-160: Improper Neutralization of Leading Special Elements.................................................................. 218
CWE-161: Improper Neutralization of Multiple Leading Special Elements..................................................... 219
CWE-162: Improper Neutralization of Trailing Special Elements................................................................... 220
CWE-163: Improper Neutralization of Multiple Trailing Special Elements...................................................... 220
CWE-164: Improper Neutralization of Internal Special Elements................................................................... 221
CWE-165: Improper Neutralization of Multiple Internal Special Elements...................................................... 222
CWE-166: Improper Handling of Missing Special Element............................................................................ 223
CWE-167: Improper Handling of Additional Special Element......................................................................... 224
CWE-168: Failure to Resolve Inconsistent Special Elements........................................................................ 225
CWE-169: Technology-Specific Special Elements......................................................................................... 225
CWE-170: Improper Null Termination............................................................................................................. 226
CWE-171: Cleansing, Canonicalization, and Comparison Errors................................................................... 229
CWE-172: Encoding Error.............................................................................................................................. 231
CWE-173: Failure to Handle Alternate Encoding........................................................................................... 232
CWE-174: Double Decoding of the Same Data............................................................................................. 233
CWE-175: Failure to Handle Mixed Encoding................................................................................................ 233
CWE-176: Failure to Handle Unicode Encoding............................................................................................ 234
CWE-177: Failure to Handle URL Encoding (Hex Encoding)......................................................................... 235

v
CWE Version 1.8.1
Table of Contents

CWE-178: Failure to Resolve Case Sensitivity.............................................................................................. 236


CWE-179: Incorrect Behavior Order: Early Validation.................................................................................... 238
CWE-180: Incorrect Behavior Order: Validate Before Canonicalize............................................................... 239
CWE-181: Incorrect Behavior Order: Validate Before Filter........................................................................... 240
CWE-182: Collapse of Data Into Unsafe Value.............................................................................................. 241
CWE-183: Permissive Whitelist...................................................................................................................... 242
CWE-184: Incomplete Blacklist....................................................................................................................... 243
CWE-185: Incorrect Regular Expression........................................................................................................ 245
CWE-186: Overly Restrictive Regular Expression.......................................................................................... 246
CWE-187: Partial Comparison........................................................................................................................ 247
CWE-188: Reliance on Data/Memory Layout................................................................................................. 249
CWE-189: Numeric Errors.............................................................................................................................. 250
CWE-190: Integer Overflow or Wraparound................................................................................................... 250
CWE-191: Integer Underflow (Wrap or Wraparound)..................................................................................... 254
CWE-192: Integer Coercion Error................................................................................................................... 255
CWE-193: Off-by-one Error............................................................................................................................ 257
CWE-194: Unexpected Sign Extension.......................................................................................................... 260
CWE-195: Signed to Unsigned Conversion Error.......................................................................................... 262
CWE-196: Unsigned to Signed Conversion Error.......................................................................................... 264
CWE-197: Numeric Truncation Error.............................................................................................................. 266
CWE-198: Use of Incorrect Byte Ordering..................................................................................................... 267
CWE-199: Information Management Errors.................................................................................................... 268
CWE-200: Information Exposure.................................................................................................................... 268
CWE-201: Information Leak Through Sent Data............................................................................................ 270
CWE-202: Privacy Leak through Data Queries.............................................................................................. 271
CWE-203: Information Exposure Through Discrepancy................................................................................. 271
CWE-204: Response Discrepancy Information Leak...................................................................................... 272
Table of Contents

CWE-205: Information Exposure Through Behavioral Discrepancy............................................................... 274


CWE-206: Internal Behavioral Inconsistency Information Leak...................................................................... 274
CWE-207: Information Exposure Through an External Behavioral Inconsistency.......................................... 275
CWE-208: Timing Discrepancy Information Leak........................................................................................... 276
CWE-209: Information Exposure Through an Error Message........................................................................ 276
CWE-210: Product-Generated Error Message Information Leak.................................................................... 280
CWE-211: Product-External Error Message Information Leak....................................................................... 281
CWE-212: Improper Cross-boundary Removal of Sensitive Data.................................................................. 282
CWE-213: Intended Information Leak............................................................................................................ 284
CWE-214: Process Environment Information Leak........................................................................................ 285
CWE-215: Information Leak Through Debug Information.............................................................................. 286
CWE-216: Containment Errors (Container Errors)......................................................................................... 287
CWE-217: DEPRECATED: Failure to Protect Stored Data from Modification................................................ 287
CWE-218: DEPRECATED (Duplicate): Failure to provide confidentiality for stored data............................... 288
CWE-219: Sensitive Data Under Web Root................................................................................................... 288
CWE-220: Sensitive Data Under FTP Root................................................................................................... 288
CWE-221: Information Loss or Omission....................................................................................................... 289
CWE-222: Truncation of Security-relevant Information.................................................................................. 290
CWE-223: Omission of Security-relevant Information.................................................................................... 290
CWE-224: Obscured Security-relevant Information by Alternate Name......................................................... 291
CWE-225: DEPRECATED (Duplicate): General Information Management Problems.................................... 291
CWE-226: Sensitive Information Uncleared Before Release.......................................................................... 291
CWE-227: Failure to Fulfill API Contract ('API Abuse').................................................................................. 293
CWE-228: Improper Handling of Syntactically Invalid Structure..................................................................... 294
CWE-229: Improper Handling of Values........................................................................................................ 295
CWE-230: Improper Handling of Missing Values........................................................................................... 296
CWE-231: Improper Handling of Extra Values............................................................................................... 296
CWE-232: Improper Handling of Undefined Values....................................................................................... 297
CWE-233: Parameter Problems..................................................................................................................... 297
CWE-234: Failure to Handle Missing Parameter............................................................................................ 298
CWE-235: Improper Handling of Extra Parameters........................................................................................ 299
CWE-236: Improper Handling of Undefined Parameters................................................................................ 300
CWE-237: Improper Handling of Structural Elements.................................................................................... 300
CWE-238: Improper Handling of Incomplete Structural Elements.................................................................. 300

vi
CWE Version 1.8.1
Table of Contents

CWE-239: Failure to Handle Incomplete Element.......................................................................................... 301


CWE-240: Improper Handling of Inconsistent Structural Elements................................................................ 302
CWE-241: Improper Handling of Unexpected Data Type............................................................................... 302
CWE-242: Use of Inherently Dangerous Function......................................................................................... 303
CWE-243: Failure to Change Working Directory in chroot Jail...................................................................... 304
CWE-244: Failure to Clear Heap Memory Before Release ('Heap Inspection').............................................. 305
CWE-245: J2EE Bad Practices: Direct Management of Connections............................................................ 306
CWE-246: J2EE Bad Practices: Direct Use of Sockets................................................................................. 308
CWE-247: Reliance on DNS Lookups in a Security Decision........................................................................ 309
CWE-248: Uncaught Exception...................................................................................................................... 310
CWE-249: DEPRECATED: Often Misused: Path Manipulation...................................................................... 311
CWE-250: Execution with Unnecessary Privileges......................................................................................... 311
CWE-251: Often Misused: String Management.............................................................................................. 314
CWE-252: Unchecked Return Value.............................................................................................................. 314
CWE-253: Incorrect Check of Function Return Value.................................................................................... 318
CWE-254: Security Features.......................................................................................................................... 319
CWE-255: Credentials Management.............................................................................................................. 320
CWE-256: Plaintext Storage of a Password................................................................................................... 321
CWE-257: Storing Passwords in a Recoverable Format................................................................................ 322
CWE-258: Empty Password in Configuration File.......................................................................................... 323
CWE-259: Use of Hard-coded Password....................................................................................................... 324
CWE-260: Password in Configuration File..................................................................................................... 327
CWE-261: Weak Cryptography for Passwords............................................................................................... 328
CWE-262: Not Using Password Aging........................................................................................................... 329
CWE-263: Password Aging with Long Expiration........................................................................................... 330
CWE-264: Permissions, Privileges, and Access Controls.............................................................................. 331
CWE-265: Privilege / Sandbox Issues............................................................................................................ 332

Table of Contents
CWE-266: Incorrect Privilege Assignment...................................................................................................... 333
CWE-267: Privilege Defined With Unsafe Actions......................................................................................... 334
CWE-268: Privilege Chaining......................................................................................................................... 335
CWE-269: Improper Privilege Management................................................................................................... 336
CWE-270: Privilege Context Switching Error.................................................................................................. 337
CWE-271: Privilege Dropping / Lowering Errors............................................................................................ 338
CWE-272: Least Privilege Violation................................................................................................................ 339
CWE-273: Improper Check for Dropped Privileges........................................................................................ 341
CWE-274: Improper Handling of Insufficient Privileges.................................................................................. 342
CWE-275: Permission Issues......................................................................................................................... 343
CWE-276: Incorrect Default Permissions....................................................................................................... 344
CWE-277: Insecure Inherited Permissions..................................................................................................... 345
CWE-278: Insecure Preserved Inherited Permissions.................................................................................... 346
CWE-279: Incorrect Execution-Assigned Permissions................................................................................... 346
CWE-280: Improper Handling of Insufficient Permissions or Privileges ........................................................ 347
CWE-281: Improper Preservation of Permissions.......................................................................................... 348
CWE-282: Improper Ownership Management................................................................................................ 349
CWE-283: Unverified Ownership.................................................................................................................... 350
CWE-284: Access Control (Authorization) Issues.......................................................................................... 350
CWE-285: Improper Access Control (Authorization)...................................................................................... 352
CWE-286: Incorrect User Management.......................................................................................................... 355
CWE-287: Improper Authentication................................................................................................................ 356
CWE-288: Authentication Bypass Using an Alternate Path or Channel......................................................... 360
CWE-289: Authentication Bypass by Alternate Name.................................................................................... 360
CWE-290: Authentication Bypass by Spoofing............................................................................................... 361
CWE-291: Trusting Self-reported IP Address................................................................................................. 362
CWE-292: Trusting Self-reported DNS Name................................................................................................ 364
CWE-293: Using Referer Field for Authentication.......................................................................................... 365
CWE-294: Authentication Bypass by Capture-replay..................................................................................... 367
CWE-295: Certificate Issues........................................................................................................................... 368
CWE-296: Improper Following of Chain of Trust for Certificate Validation..................................................... 368
CWE-297: Improper Validation of Host-specific Certificate Data.................................................................... 370
CWE-298: Improper Validation of Certificate Expiration................................................................................. 371
CWE-299: Improper Check for Certificate Revocation................................................................................... 371

vii
CWE Version 1.8.1
Table of Contents

CWE-300: Channel Accessible by Non-Endpoint ('Man-in-the-Middle').......................................................... 372


CWE-301: Reflection Attack in an Authentication Protocol............................................................................ 374
CWE-302: Authentication Bypass by Assumed-Immutable Data.................................................................... 375
CWE-303: Incorrect Implementation of Authentication Algorithm................................................................... 376
CWE-304: Missing Critical Step in Authentication.......................................................................................... 377
CWE-305: Authentication Bypass by Primary Weakness............................................................................... 378
CWE-306: Missing Authentication for Critical Function.................................................................................. 378
CWE-307: Improper Restriction of Excessive Authentication Attempts.......................................................... 381
CWE-308: Use of Single-factor Authentication............................................................................................... 383
CWE-309: Use of Password System for Primary Authentication.................................................................... 384
CWE-310: Cryptographic Issues..................................................................................................................... 385
CWE-311: Missing Encryption of Sensitive Data............................................................................................ 386
CWE-312: Cleartext Storage of Sensitive Information.................................................................................... 390
CWE-313: Plaintext Storage in a File or on Disk........................................................................................... 391
CWE-314: Plaintext Storage in the Registry.................................................................................................. 391
CWE-315: Plaintext Storage in a Cookie....................................................................................................... 392
CWE-316: Plaintext Storage in Memory......................................................................................................... 392
CWE-317: Plaintext Storage in GUI............................................................................................................... 393
CWE-318: Plaintext Storage in Executable.................................................................................................... 394
CWE-319: Cleartext Transmission of Sensitive Information........................................................................... 394
CWE-320: Key Management Errors............................................................................................................... 396
CWE-321: Use of Hard-coded Cryptographic Key......................................................................................... 397
CWE-322: Key Exchange without Entity Authentication................................................................................. 398
CWE-323: Reusing a Nonce, Key Pair in Encryption..................................................................................... 399
CWE-324: Use of a Key Past its Expiration Date.......................................................................................... 401
CWE-325: Missing Required Cryptographic Step........................................................................................... 401
CWE-326: Inadequate Encryption Strength.................................................................................................... 402
Table of Contents

CWE-327: Use of a Broken or Risky Cryptographic Algorithm...................................................................... 404


CWE-328: Reversible One-Way Hash............................................................................................................ 406
CWE-329: Not Using a Random IV with CBC Mode...................................................................................... 407
CWE-330: Use of Insufficiently Random Values............................................................................................ 408
CWE-331: Insufficient Entropy........................................................................................................................ 412
CWE-332: Insufficient Entropy in PRNG........................................................................................................ 412
CWE-333: Improper Handling of Insufficient Entropy in TRNG...................................................................... 414
CWE-334: Small Space of Random Values................................................................................................... 414
CWE-335: PRNG Seed Error......................................................................................................................... 415
CWE-336: Same Seed in PRNG.................................................................................................................... 416
CWE-337: Predictable Seed in PRNG........................................................................................................... 416
CWE-338: Use of Cryptographically Weak PRNG......................................................................................... 417
CWE-339: Small Seed Space in PRNG......................................................................................................... 418
CWE-340: Predictability Problems.................................................................................................................. 419
CWE-341: Predictable from Observable State............................................................................................... 419
CWE-342: Predictable Exact Value from Previous Values............................................................................. 420
CWE-343: Predictable Value Range from Previous Values........................................................................... 420
CWE-344: Use of Invariant Value in Dynamically Changing Context............................................................. 421
CWE-345: Insufficient Verification of Data Authenticity.................................................................................. 422
CWE-346: Origin Validation Error................................................................................................................... 423
CWE-347: Improper Verification of Cryptographic Signature......................................................................... 424
CWE-348: Use of Less Trusted Source......................................................................................................... 425
CWE-349: Acceptance of Extraneous Untrusted Data With Trusted Data..................................................... 425
CWE-350: Improperly Trusted Reverse DNS................................................................................................. 426
CWE-351: Insufficient Type Distinction........................................................................................................... 427
CWE-352: Cross-Site Request Forgery (CSRF)............................................................................................ 427
CWE-353: Failure to Add Integrity Check Value............................................................................................ 431
CWE-354: Improper Validation of Integrity Check Value................................................................................ 433
CWE-355: User Interface Security Issues...................................................................................................... 434
CWE-356: Product UI does not Warn User of Unsafe Actions...................................................................... 434
CWE-357: Insufficient UI Warning of Dangerous Operations......................................................................... 435
CWE-358: Improperly Implemented Security Check for Standard.................................................................. 436
CWE-359: Privacy Violation............................................................................................................................ 436
CWE-360: Trust of System Event Data.......................................................................................................... 438

viii
CWE Version 1.8.1
Table of Contents

CWE-361: Time and State.............................................................................................................................. 439


CWE-362: Race Condition.............................................................................................................................. 440
CWE-363: Race Condition Enabling Link Following....................................................................................... 444
CWE-364: Signal Handler Race Condition..................................................................................................... 444
CWE-365: Race Condition in Switch.............................................................................................................. 446
CWE-366: Race Condition within a Thread.................................................................................................... 447
CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition............................................................... 449
CWE-368: Context Switching Race Condition................................................................................................ 451
CWE-369: Divide By Zero.............................................................................................................................. 452
CWE-370: Missing Check for Certificate Revocation after Initial Check......................................................... 454
CWE-371: State Issues................................................................................................................................... 455
CWE-372: Incomplete Internal State Distinction............................................................................................. 456
CWE-373: State Synchronization Error.......................................................................................................... 457
CWE-374: Mutable Objects Passed by Reference......................................................................................... 458
CWE-375: Passing Mutable Objects to an Untrusted Method........................................................................ 459
CWE-376: Temporary File Issues................................................................................................................... 460
CWE-377: Insecure Temporary File............................................................................................................... 460
CWE-378: Creation of Temporary File With Insecure Permissions................................................................ 462
CWE-379: Creation of Temporary File in Directory with Incorrect Permissions.............................................. 463
CWE-380: Technology-Specific Time and State Issues................................................................................. 465
CWE-381: J2EE Time and State Issues........................................................................................................ 465
CWE-382: J2EE Bad Practices: Use of System.exit().................................................................................... 465
CWE-383: J2EE Bad Practices: Direct Use of Threads................................................................................. 466
CWE-384: Session Fixation............................................................................................................................ 467
CWE-385: Covert Timing Channel................................................................................................................. 469
CWE-386: Symbolic Name not Mapping to Correct Object............................................................................ 470
CWE-387: Signal Errors.................................................................................................................................. 471

Table of Contents
CWE-388: Error Handling............................................................................................................................... 472
CWE-389: Error Conditions, Return Values, Status Codes............................................................................ 473
CWE-390: Detection of Error Condition Without Action................................................................................. 474
CWE-391: Unchecked Error Condition........................................................................................................... 478
CWE-392: Failure to Report Error in Status Code......................................................................................... 479
CWE-393: Return of Wrong Status Code....................................................................................................... 480
CWE-394: Unexpected Status Code or Return Value.................................................................................... 481
CWE-395: Use of NullPointerException Catch to Detect NULL Pointer Dereference..................................... 482
CWE-396: Declaration of Catch for Generic Exception.................................................................................. 482
CWE-397: Declaration of Throws for Generic Exception............................................................................... 483
CWE-398: Indicator of Poor Code Quality...................................................................................................... 484
CWE-399: Resource Management Errors...................................................................................................... 486
CWE-400: Uncontrolled Resource Consumption ('Resource Exhaustion')..................................................... 486
CWE-401: Failure to Release Memory Before Removing Last Reference ('Memory Leak')........................... 490
CWE-402: Transmission of Private Resources into a New Sphere ('Resource Leak')................................... 492
CWE-403: UNIX File Descriptor Leak............................................................................................................ 493
CWE-404: Improper Resource Shutdown or Release.................................................................................... 493
CWE-405: Asymmetric Resource Consumption (Amplification)..................................................................... 497
CWE-406: Insufficient Control of Network Message Volume (Network Amplification).................................... 498
CWE-407: Algorithmic Complexity.................................................................................................................. 499
CWE-408: Incorrect Behavior Order: Early Amplification............................................................................... 500
CWE-409: Improper Handling of Highly Compressed Data (Data Amplification)............................................ 501
CWE-410: Insufficient Resource Pool............................................................................................................ 501
CWE-411: Resource Locking Problems......................................................................................................... 503
CWE-412: Unrestricted Externally Accessible Lock....................................................................................... 503
CWE-413: Insufficient Resource Locking....................................................................................................... 504
CWE-414: Missing Lock Check...................................................................................................................... 505
CWE-415: Double Free................................................................................................................................... 505
CWE-416: Use After Free............................................................................................................................... 508
CWE-417: Channel and Path Errors.............................................................................................................. 510
CWE-418: Channel Errors.............................................................................................................................. 510
CWE-419: Unprotected Primary Channel....................................................................................................... 511
CWE-420: Unprotected Alternate Channel..................................................................................................... 511
CWE-421: Race Condition During Access to Alternate Channel.................................................................... 512

ix
CWE Version 1.8.1
Table of Contents

CWE-422: Unprotected Windows Messaging Channel ('Shatter').................................................................. 513


CWE-423: DEPRECATED (Duplicate): Proxied Trusted Channel.................................................................. 514
CWE-424: Failure to Protect Alternate Path................................................................................................... 514
CWE-425: Direct Request ('Forced Browsing')............................................................................................... 515
CWE-426: Untrusted Search Path.................................................................................................................. 516
CWE-427: Uncontrolled Search Path Element............................................................................................... 519
CWE-428: Unquoted Search Path or Element............................................................................................... 520
CWE-429: Handler Errors............................................................................................................................... 522
CWE-430: Deployment of Wrong Handler...................................................................................................... 522
CWE-431: Missing Handler............................................................................................................................. 523
CWE-432: Dangerous Handler not Disabled During Sensitive Operations..................................................... 524
CWE-433: Unparsed Raw Web Content Delivery.......................................................................................... 524
CWE-434: Unrestricted Upload of File with Dangerous Type........................................................................ 525
CWE-435: Interaction Error............................................................................................................................. 529
CWE-436: Interpretation Conflict.................................................................................................................... 530
CWE-437: Incomplete Model of Endpoint Features....................................................................................... 532
CWE-438: Behavioral Problems..................................................................................................................... 532
CWE-439: Behavioral Change in New Version or Environment..................................................................... 533
CWE-440: Expected Behavior Violation......................................................................................................... 533
CWE-441: Unintended Proxy/Intermediary..................................................................................................... 534
CWE-442: Web Problems............................................................................................................................... 535
CWE-443: DEPRECATED (Duplicate): HTTP response splitting................................................................... 535
CWE-444: Inconsistent Interpretation of HTTP Requests ('HTTP Request Smuggling')................................ 535
CWE-445: User Interface Errors..................................................................................................................... 537
CWE-446: UI Discrepancy for Security Feature............................................................................................. 537
CWE-447: Unimplemented or Unsupported Feature in UI............................................................................. 538
CWE-448: Obsolete Feature in UI.................................................................................................................. 538
Table of Contents

CWE-449: The UI Performs the Wrong Action............................................................................................... 539


CWE-450: Multiple Interpretations of UI Input................................................................................................ 539
CWE-451: UI Misrepresentation of Critical Information.................................................................................. 540
CWE-452: Initialization and Cleanup Errors................................................................................................... 542
CWE-453: Insecure Default Variable Initialization.......................................................................................... 542
CWE-454: External Initialization of Trusted Variables or Data Stores............................................................ 543
CWE-455: Non-exit on Failed Initialization..................................................................................................... 544
CWE-456: Missing Initialization...................................................................................................................... 544
CWE-457: Use of Uninitialized Variable......................................................................................................... 546
CWE-458: DEPRECATED: Incorrect Initialization.......................................................................................... 549
CWE-459: Incomplete Cleanup...................................................................................................................... 549
CWE-460: Improper Cleanup on Thrown Exception....................................................................................... 550
CWE-461: Data Structure Issues.................................................................................................................... 551
CWE-462: Duplicate Key in Associative List (Alist)........................................................................................ 552
CWE-463: Deletion of Data Structure Sentinel............................................................................................... 552
CWE-464: Addition of Data Structure Sentinel............................................................................................... 554
CWE-465: Pointer Issues................................................................................................................................ 555
CWE-466: Return of Pointer Value Outside of Expected Range.................................................................... 555
CWE-467: Use of sizeof() on a Pointer Type................................................................................................. 556
CWE-468: Incorrect Pointer Scaling............................................................................................................... 558
CWE-469: Use of Pointer Subtraction to Determine Size.............................................................................. 559
CWE-470: Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')...................... 560
CWE-471: Modification of Assumed-Immutable Data (MAID)........................................................................ 562
CWE-472: External Control of Assumed-Immutable Web Parameter............................................................. 563
CWE-473: PHP External Variable Modification.............................................................................................. 565
CWE-474: Use of Function with Inconsistent Implementations...................................................................... 566
CWE-475: Undefined Behavior for Input to API............................................................................................. 567
CWE-476: NULL Pointer Dereference............................................................................................................ 568
CWE-477: Use of Obsolete Functions............................................................................................................ 570
CWE-478: Missing Default Case in Switch Statement................................................................................... 572
CWE-479: Unsafe Function Call from a Signal Handler................................................................................. 573
CWE-480: Use of Incorrect Operator............................................................................................................. 575
CWE-481: Assigning instead of Comparing................................................................................................... 576
CWE-482: Comparing instead of Assigning................................................................................................... 578

x
CWE Version 1.8.1
Table of Contents

CWE-483: Incorrect Block Delimitation........................................................................................................... 579


CWE-484: Omitted Break Statement in Switch.............................................................................................. 580
CWE-485: Insufficient Encapsulation.............................................................................................................. 581
CWE-486: Comparison of Classes by Name................................................................................................. 583
CWE-487: Reliance on Package-level Scope................................................................................................ 584
CWE-488: Data Leak Between Sessions....................................................................................................... 584
CWE-489: Leftover Debug Code.................................................................................................................... 586
CWE-490: Mobile Code Issues....................................................................................................................... 587
CWE-491: Public cloneable() Method Without Final ('Object Hijack')............................................................. 587
CWE-492: Use of Inner Class Containing Sensitive Data.............................................................................. 588
CWE-493: Critical Public Variable Without Final Modifier.............................................................................. 594
CWE-494: Download of Code Without Integrity Check.................................................................................. 595
CWE-495: Private Array-Typed Field Returned From A Public Method......................................................... 598
CWE-496: Public Data Assigned to Private Array-Typed Field...................................................................... 598
CWE-497: Exposure of System Data to an Unauthorized Control Sphere..................................................... 599
CWE-498: Information Leak through Class Cloning....................................................................................... 601
CWE-499: Serializable Class Containing Sensitive Data............................................................................... 602
CWE-500: Public Static Field Not Marked Final............................................................................................. 603
CWE-501: Trust Boundary Violation............................................................................................................... 604
CWE-502: Deserialization of Untrusted Data................................................................................................. 605
CWE-503: Byte/Object Code.......................................................................................................................... 606
CWE-504: Motivation/Intent............................................................................................................................ 606
CWE-505: Intentionally Introduced Weakness............................................................................................... 607
CWE-506: Embedded Malicious Code........................................................................................................... 607
CWE-507: Trojan Horse.................................................................................................................................. 608
CWE-508: Non-Replicating Malicious Code................................................................................................... 609
CWE-509: Replicating Malicious Code (Virus or Worm)................................................................................ 609

Table of Contents
CWE-510: Trapdoor........................................................................................................................................ 610
CWE-511: Logic/Time Bomb.......................................................................................................................... 610
CWE-512: Spyware......................................................................................................................................... 611
CWE-513: Intentionally Introduced Nonmalicious Weakness......................................................................... 611
CWE-514: Covert Channel............................................................................................................................. 612
CWE-515: Covert Storage Channel................................................................................................................ 612
CWE-516: DEPRECATED (Duplicate): Covert Timing Channel..................................................................... 613
CWE-517: Other Intentional, Nonmalicious Weakness.................................................................................. 613
CWE-518: Inadvertently Introduced Weakness.............................................................................................. 614
CWE-519: .NET Environment Issues.............................................................................................................. 614
CWE-520: .NET Misconfiguration: Use of Impersonation............................................................................... 614
CWE-521: Weak Password Requirements..................................................................................................... 615
CWE-522: Insufficiently Protected Credentials............................................................................................... 616
CWE-523: Unprotected Transport of Credentials........................................................................................... 617
CWE-524: Information Leak Through Caching............................................................................................... 618
CWE-525: Information Leak Through Browser Caching................................................................................. 618
CWE-526: Information Leak Through Environmental Variables..................................................................... 619
CWE-527: Exposure of CVS Repository to an Unauthorized Control Sphere................................................ 619
CWE-528: Exposure of Core Dump File to an Unauthorized Control Sphere................................................ 620
CWE-529: Exposure of Access Control List Files to an Unauthorized Control Sphere.................................. 620
CWE-530: Exposure of Backup File to an Unauthorized Control Sphere....................................................... 621
CWE-531: Information Leak Through Test Code........................................................................................... 621
CWE-532: Information Leak Through Log Files............................................................................................. 622
CWE-533: Information Leak Through Server Log Files.................................................................................. 623
CWE-534: Information Leak Through Debug Log Files.................................................................................. 624
CWE-535: Information Leak Through Shell Error Message........................................................................... 624
CWE-536: Information Leak Through Servlet Runtime Error Message.......................................................... 624
CWE-537: Information Leak Through Java Runtime Error Message.............................................................. 625
CWE-538: File and Directory Information Exposure....................................................................................... 626
CWE-539: Information Leak Through Persistent Cookies.............................................................................. 627
CWE-540: Information Leak Through Source Code....................................................................................... 628
CWE-541: Information Leak Through Include Source Code.......................................................................... 629
CWE-542: Information Leak Through Cleanup Log Files............................................................................... 629
CWE-543: Use of Singleton Pattern in a Non-thread-safe Manner................................................................ 629

xi
CWE Version 1.8.1
Table of Contents

CWE-544: Failure to Use a Standardized Error Handling Mechanism........................................................... 630


CWE-545: Use of Dynamic Class Loading..................................................................................................... 631
CWE-546: Suspicious Comment.................................................................................................................... 632
CWE-547: Use of Hard-coded, Security-relevant Constants.......................................................................... 632
CWE-548: Information Leak Through Directory Listing.................................................................................. 633
CWE-549: Missing Password Field Masking.................................................................................................. 634
CWE-550: Information Leak Through Server Error Message......................................................................... 634
CWE-551: Incorrect Behavior Order: Authorization Before Parsing and Canonicalization............................. 635
CWE-552: Files or Directories Accessible to External Parties....................................................................... 635
CWE-553: Command Shell in Externally Accessible Directory...................................................................... 636
CWE-554: ASP.NET Misconfiguration: Not Using Input Validation Framework.............................................. 637
CWE-555: J2EE Misconfiguration: Plaintext Password in Configuration File................................................. 637
CWE-556: ASP.NET Misconfiguration: Use of Identity Impersonation........................................................... 638
CWE-557: Concurrency Issues....................................................................................................................... 638
CWE-558: Use of getlogin() in Multithreaded Application.............................................................................. 639
CWE-559: Often Misused: Arguments and Parameters................................................................................. 639
CWE-560: Use of umask() with chmod-style Argument................................................................................. 640
CWE-561: Dead Code.................................................................................................................................... 640
CWE-562: Return of Stack Variable Address................................................................................................. 642
CWE-563: Unused Variable............................................................................................................................ 643
CWE-564: SQL Injection: Hibernate............................................................................................................... 643
CWE-565: Reliance on Cookies without Validation and Integrity Checking................................................... 644
CWE-566: Access Control Bypass Through User-Controlled SQL Primary Key............................................ 645
CWE-567: Unsynchronized Access to Shared Data....................................................................................... 646
CWE-568: finalize() Method Without super.finalize()...................................................................................... 647
CWE-569: Expression Issues......................................................................................................................... 648
CWE-570: Expression is Always False.......................................................................................................... 648
Table of Contents

CWE-571: Expression is Always True............................................................................................................ 650


CWE-572: Call to Thread run() instead of start()........................................................................................... 651
CWE-573: Failure to Follow Specification...................................................................................................... 652
CWE-574: EJB Bad Practices: Use of Synchronization Primitives................................................................. 653
CWE-575: EJB Bad Practices: Use of AWT Swing........................................................................................ 654
CWE-576: EJB Bad Practices: Use of Java I/O............................................................................................. 656
CWE-577: EJB Bad Practices: Use of Sockets.............................................................................................. 657
CWE-578: EJB Bad Practices: Use of Class Loader..................................................................................... 658
CWE-579: J2EE Bad Practices: Non-serializable Object Stored in Session.................................................. 660
CWE-580: clone() Method Without super.clone()........................................................................................... 660
CWE-581: Object Model Violation: Just One of Equals and Hashcode Defined............................................ 661
CWE-582: Array Declared Public, Final, and Static....................................................................................... 662
CWE-583: finalize() Method Declared Public................................................................................................. 663
CWE-584: Return Inside Finally Block........................................................................................................... 663
CWE-585: Empty Synchronized Block........................................................................................................... 664
CWE-586: Explicit Call to Finalize()................................................................................................................ 665
CWE-587: Assignment of a Fixed Address to a Pointer................................................................................ 665
CWE-588: Attempt to Access Child of a Non-structure Pointer...................................................................... 666
CWE-589: Call to Non-ubiquitous API............................................................................................................ 667
CWE-590: Free of Memory not on the Heap................................................................................................. 668
CWE-591: Sensitive Data Storage in Improperly Locked Memory................................................................. 669
CWE-592: Authentication Bypass Issues....................................................................................................... 670
CWE-593: Authentication Bypass: OpenSSL CTX Object Modified after SSL Objects are Created............... 671
CWE-594: J2EE Framework: Saving Unserializable Objects to Disk............................................................. 672
CWE-595: Comparison of Object References Instead of Object Contents..................................................... 673
CWE-596: Incorrect Semantic Object Comparison......................................................................................... 674
CWE-597: Use of Wrong Operator in String Comparison.............................................................................. 675
CWE-598: Information Leak Through Query Strings in GET Request........................................................... 675
CWE-599: Trust of OpenSSL Certificate Without Validation.......................................................................... 676
CWE-600: Failure to Catch All Exceptions in Servlet .................................................................................... 676
CWE-601: URL Redirection to Untrusted Site ('Open Redirect').................................................................... 677
CWE-602: Client-Side Enforcement of Server-Side Security......................................................................... 680
CWE-603: Use of Client-Side Authentication................................................................................................. 683
CWE-604: Deprecated Entries........................................................................................................................ 684

xii
CWE Version 1.8.1
Table of Contents

CWE-605: Multiple Binds to the Same Port................................................................................................... 684


CWE-606: Unchecked Input for Loop Condition............................................................................................. 685
CWE-607: Public Static Final Field References Mutable Object.................................................................... 686
CWE-608: Struts: Non-private Field in ActionForm Class.............................................................................. 686
CWE-609: Double-Checked Locking.............................................................................................................. 687
CWE-610: Externally Controlled Reference to a Resource in Another Sphere.............................................. 688
CWE-611: Information Leak Through XML External Entity File Disclosure.................................................... 689
CWE-612: Information Leak Through Indexing of Private Data..................................................................... 690
CWE-613: Insufficient Session Expiration...................................................................................................... 690
CWE-614: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute.................................................... 691
CWE-615: Information Leak Through Comments........................................................................................... 692
CWE-616: Incomplete Identification of Uploaded File Variables (PHP).......................................................... 693
CWE-617: Reachable Assertion..................................................................................................................... 694
CWE-618: Exposed Unsafe ActiveX Method.................................................................................................. 695
CWE-619: Dangling Database Cursor ('Cursor Injection').............................................................................. 696
CWE-620: Unverified Password Change........................................................................................................ 696
CWE-621: Variable Extraction Error............................................................................................................... 697
CWE-622: Unvalidated Function Hook Arguments......................................................................................... 698
CWE-623: Unsafe ActiveX Control Marked Safe For Scripting...................................................................... 699
CWE-624: Executable Regular Expression Error........................................................................................... 700
CWE-625: Permissive Regular Expression.................................................................................................... 700
CWE-626: Null Byte Interaction Error (Poison Null Byte)............................................................................... 701
CWE-627: Dynamic Variable Evaluation........................................................................................................ 702
CWE-628: Function Call with Incorrectly Specified Arguments...................................................................... 703
CWE-629: Weaknesses in OWASP Top Ten (2007)..................................................................................... 704
CWE-630: Weaknesses Examined by SAMATE............................................................................................ 705
CWE-631: Resource-specific Weaknesses.................................................................................................... 706

Table of Contents
CWE-632: Weaknesses that Affect Files or Directories................................................................................. 706
CWE-633: Weaknesses that Affect Memory.................................................................................................. 707
CWE-634: Weaknesses that Affect System Processes.................................................................................. 708
CWE-635: Weaknesses Used by NVD........................................................................................................... 708
CWE-636: Not Failing Securely ('Failing Open')............................................................................................. 710
CWE-637: Failure to Use Economy of Mechanism........................................................................................ 711
CWE-638: Failure to Use Complete Mediation............................................................................................... 713
CWE-639: Access Control Bypass Through User-Controlled Key.................................................................. 714
CWE-640: Weak Password Recovery Mechanism for Forgotten Password................................................... 715
CWE-641: Insufficient Filtering of File and Other Resource Names for Executable Content.......................... 717
CWE-642: External Control of Critical State Data.......................................................................................... 718
CWE-643: Improper Neutralization of Data within XPath Expressions ('XPath injection')............................... 721
CWE-644: Improper Neutralization of HTTP Headers for Scripting Syntax.................................................... 723
CWE-645: Overly Restrictive Account Lockout Mechanism........................................................................... 724
CWE-646: Reliance on File Name or Extension of Externally-Supplied File.................................................. 725
CWE-647: Use of Non-Canonical URL Paths for Authorization Decisions..................................................... 726
CWE-648: Incorrect Use of Privileged APIs................................................................................................... 727
CWE-649: Reliance on Obfuscation or Encryption of Security-Relevant Inputs without Integrity Checking.... 728
CWE-650: Trusting HTTP Permission Methods on the Server Side.............................................................. 730
CWE-651: Information Leak through WSDL File............................................................................................ 731
CWE-652: Improper Neutralization of Data within XQuery Expressions ('XQuery Injection').......................... 732
CWE-653: Insufficient Compartmentalization.................................................................................................. 733
CWE-654: Reliance on a Single Factor in a Security Decision...................................................................... 734
CWE-655: Insufficient Psychological Acceptability......................................................................................... 736
CWE-656: Reliance on Security through Obscurity........................................................................................ 737
CWE-657: Violation of Secure Design Principles........................................................................................... 738
CWE-658: Weaknesses in Software Written in C.......................................................................................... 739
CWE-659: Weaknesses in Software Written in C++...................................................................................... 741
CWE-660: Weaknesses in Software Written in Java...................................................................................... 743
CWE-661: Weaknesses in Software Written in PHP...................................................................................... 745
CWE-662: Insufficient Synchronization........................................................................................................... 745
CWE-663: Use of a Non-reentrant Function in an Unsynchronized Context.................................................. 746
CWE-664: Improper Control of a Resource Through its Lifetime................................................................... 747
CWE-665: Improper Initialization.................................................................................................................... 748

xiii
CWE Version 1.8.1
Table of Contents

CWE-666: Operation on Resource in Wrong Phase of Lifetime..................................................................... 751


CWE-667: Insufficient Locking........................................................................................................................ 752
CWE-668: Exposure of Resource to Wrong Sphere...................................................................................... 753
CWE-669: Incorrect Resource Transfer Between Spheres............................................................................ 754
CWE-670: Always-Incorrect Control Flow Implementation............................................................................. 755
CWE-671: Lack of Administrator Control over Security.................................................................................. 755
CWE-672: Operation on a Resource after Expiration or Release.................................................................. 756
CWE-673: External Influence of Sphere Definition......................................................................................... 757
CWE-674: Uncontrolled Recursion................................................................................................................. 758
CWE-675: Duplicate Operations on Resource............................................................................................... 759
CWE-676: Use of Potentially Dangerous Function......................................................................................... 760
CWE-677: Weakness Base Elements............................................................................................................ 761
CWE-678: Composites.................................................................................................................................... 767
CWE-679: Chain Elements............................................................................................................................. 768
CWE-680: Integer Overflow to Buffer Overflow.............................................................................................. 770
CWE-681: Incorrect Conversion between Numeric Types............................................................................. 770
CWE-682: Incorrect Calculation...................................................................................................................... 771
CWE-683: Function Call With Incorrect Order of Arguments......................................................................... 775
CWE-684: Failure to Provide Specified Functionality..................................................................................... 775
CWE-685: Function Call With Incorrect Number of Arguments...................................................................... 776
CWE-686: Function Call With Incorrect Argument Type................................................................................ 777
CWE-687: Function Call With Incorrectly Specified Argument Value............................................................. 777
CWE-688: Function Call With Incorrect Variable or Reference as Argument................................................. 778
CWE-689: Permission Race Condition During Resource Copy...................................................................... 779
CWE-690: Unchecked Return Value to NULL Pointer Dereference............................................................... 780
CWE-691: Insufficient Control Flow Management.......................................................................................... 782
CWE-692: Incomplete Blacklist to Cross-Site Scripting.................................................................................. 783
Table of Contents

CWE-693: Protection Mechanism Failure....................................................................................................... 783


CWE-694: Use of Multiple Resources with Duplicate Identifier...................................................................... 785
CWE-695: Use of Low-Level Functionality..................................................................................................... 786
CWE-696: Incorrect Behavior Order............................................................................................................... 786
CWE-697: Insufficient Comparison................................................................................................................. 787
CWE-698: Redirect Without Exit..................................................................................................................... 788
CWE-699: Development Concepts................................................................................................................. 788
CWE-700: Seven Pernicious Kingdoms......................................................................................................... 789
CWE-701: Weaknesses Introduced During Design........................................................................................ 790
CWE-702: Weaknesses Introduced During Implementation........................................................................... 797
CWE-703: Failure to Handle Exceptional Conditions..................................................................................... 809
CWE-704: Incorrect Type Conversion or Cast............................................................................................... 810
CWE-705: Incorrect Control Flow Scoping..................................................................................................... 811
CWE-706: Use of Incorrectly-Resolved Name or Reference.......................................................................... 811
CWE-707: Improper Enforcement of Message or Data Structure.................................................................. 812
CWE-708: Incorrect Ownership Assignment.................................................................................................. 813
CWE-709: Named Chains............................................................................................................................... 814
CWE-710: Coding Standards Violation........................................................................................................... 814
CWE-711: Weaknesses in OWASP Top Ten (2004)..................................................................................... 814
CWE-712: OWASP Top Ten 2007 Category A1 - Cross Site Scripting (XSS)............................................... 816
CWE-713: OWASP Top Ten 2007 Category A2 - Injection Flaws................................................................. 816
CWE-714: OWASP Top Ten 2007 Category A3 - Malicious File Execution................................................... 817
CWE-715: OWASP Top Ten 2007 Category A4 - Insecure Direct Object Reference.................................... 817
CWE-716: OWASP Top Ten 2007 Category A5 - Cross Site Request Forgery (CSRF)................................ 817
CWE-717: OWASP Top Ten 2007 Category A6 - Information Leakage and Improper Error Handling........... 818
CWE-718: OWASP Top Ten 2007 Category A7 - Broken Authentication and Session Management............ 818
CWE-719: OWASP Top Ten 2007 Category A8 - Insecure Cryptographic Storage....................................... 819
CWE-720: OWASP Top Ten 2007 Category A9 - Insecure Communications................................................ 819
CWE-721: OWASP Top Ten 2007 Category A10 - Failure to Restrict URL Access...................................... 819
CWE-722: OWASP Top Ten 2004 Category A1 - Unvalidated Input............................................................. 820
CWE-723: OWASP Top Ten 2004 Category A2 - Broken Access Control..................................................... 821
CWE-724: OWASP Top Ten 2004 Category A3 - Broken Authentication and Session Management............ 821
CWE-725: OWASP Top Ten 2004 Category A4 - Cross-Site Scripting (XSS) Flaws..................................... 822
CWE-726: OWASP Top Ten 2004 Category A5 - Buffer Overflows.............................................................. 822

xiv
CWE Version 1.8.1
Table of Contents

CWE-727: OWASP Top Ten 2004 Category A6 - Injection Flaws................................................................. 823


CWE-728: OWASP Top Ten 2004 Category A7 - Improper Error Handling................................................... 823
CWE-729: OWASP Top Ten 2004 Category A8 - Insecure Storage.............................................................. 824
CWE-730: OWASP Top Ten 2004 Category A9 - Denial of Service.............................................................. 824
CWE-731: OWASP Top Ten 2004 Category A10 - Insecure Configuration Management.............................. 825
CWE-732: Incorrect Permission Assignment for Critical Resource................................................................ 825
CWE-733: Compiler Optimization Removal or Modification of Security-critical Code..................................... 830
CWE-734: Weaknesses Addressed by the CERT C Secure Coding Standard.............................................. 831
CWE-735: CERT C Secure Coding Section 01 - Preprocessor (PRE).......................................................... 832
CWE-736: CERT C Secure Coding Section 02 - Declarations and Initialization (DCL).................................. 833
CWE-737: CERT C Secure Coding Section 03 - Expressions (EXP)............................................................ 833
CWE-738: CERT C Secure Coding Section 04 - Integers (INT).................................................................... 833
CWE-739: CERT C Secure Coding Section 05 - Floating Point (FLP)........................................................... 834
CWE-740: CERT C Secure Coding Section 06 - Arrays (ARR)..................................................................... 834
CWE-741: CERT C Secure Coding Section 07 - Characters and Strings (STR)............................................ 835
CWE-742: CERT C Secure Coding Section 08 - Memory Management (MEM)............................................ 835
CWE-743: CERT C Secure Coding Section 09 - Input Output (FIO)............................................................. 836
CWE-744: CERT C Secure Coding Section 10 - Environment (ENV)............................................................ 837
CWE-745: CERT C Secure Coding Section 11 - Signals (SIG)..................................................................... 837
CWE-746: CERT C Secure Coding Section 12 - Error Handling (ERR)........................................................ 838
CWE-747: CERT C Secure Coding Section 49 - Miscellaneous (MSC)......................................................... 838
CWE-748: CERT C Secure Coding Section 50 - POSIX (POS).................................................................... 839
CWE-749: Exposed Dangerous Method or Function...................................................................................... 839
CWE-750: Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors................... 841
CWE-751: 2009 Top 25 - Insecure Interaction Between Components........................................................... 842
CWE-752: 2009 Top 25 - Risky Resource Management............................................................................... 842
CWE-753: 2009 Top 25 - Porous Defenses................................................................................................... 843

Table of Contents
CWE-754: Improper Check for Unusual or Exceptional Conditions............................................................... 843
CWE-755: Improper Handling of Exceptional Conditions............................................................................... 849
CWE-756: Missing Custom Error Page.......................................................................................................... 849
CWE-757: Selection of Less-Secure Algorithm During Negotiation ('Algorithm Downgrade')......................... 850
CWE-758: Reliance on Undefined, Unspecified, or Implementation-Defined Behavior.................................. 851
CWE-759: Use of a One-Way Hash without a Salt........................................................................................ 851
CWE-760: Use of a One-Way Hash with a Predictable Salt.......................................................................... 852
CWE-761: Free of Pointer not at Start of Buffer............................................................................................ 852
CWE-762: Mismatched Memory Management Routines................................................................................ 855
CWE-763: Release of Invalid Pointer or Reference....................................................................................... 856
CWE-764: Multiple Locks of a Critical Resource............................................................................................ 857
CWE-765: Multiple Unlocks of a Critical Resource........................................................................................ 858
CWE-766: Critical Variable Declared Public................................................................................................... 859
CWE-767: Access to Critical Private Variable via Public Method................................................................... 861
CWE-768: Incorrect Short Circuit Evaluation.................................................................................................. 862
CWE-769: File Descriptor Exhaustion............................................................................................................ 863
CWE-770: Allocation of Resources Without Limits or Throttling..................................................................... 864
CWE-771: Missing Reference to Active Allocated Resource......................................................................... 869
CWE-772: Missing Release of Resource after Effective Lifetime................................................................... 870
CWE-773: Missing Reference to Active File Descriptor or Handle................................................................. 872
CWE-774: Allocation of File Descriptors or Handles Without Limits or Throttling........................................... 873
CWE-775: Missing Release of File Descriptor or Handle after Effective Lifetime........................................... 873
CWE-776: Unrestricted Recursive Entity References in DTDs ('XML Bomb')................................................ 874
CWE-777: Regular Expression without Anchors............................................................................................ 876
CWE-778: Insufficient Logging....................................................................................................................... 877
CWE-779: Logging of Excessive Data........................................................................................................... 878
CWE-780: Use of RSA Algorithm without OAEP........................................................................................... 879
CWE-781: Improper Address Validation in IOCTL with METHOD_NEITHER I/O Control Code..................... 881
CWE-782: Exposed IOCTL with Insufficient Access Control.......................................................................... 882
CWE-783: Operator Precedence Logic Error................................................................................................. 883
CWE-784: Reliance on Cookies without Validation and Integrity Checking in a Security Decision................. 884
CWE-785: Use of Path Manipulation Function without Maximum-sized Buffer.............................................. 887
CWE-786: Access of Memory Location Before Start of Buffer....................................................................... 888
CWE-787: Out-of-bounds Write...................................................................................................................... 888

xv
CWE Version 1.8.1
Table of Contents

CWE-788: Access of Memory Location After End of Buffer........................................................................... 889


CWE-789: Uncontrolled Memory Allocation.................................................................................................... 889
CWE-790: Improper Filtering of Special Elements......................................................................................... 891
CWE-791: Incomplete Filtering of Special Elements...................................................................................... 892
CWE-792: Incomplete Filtering of One or More Instances of Special Elements............................................. 893
CWE-793: Only Filtering One Instance of a Special Element........................................................................ 893
CWE-794: Incomplete Filtering of Multiple Instances of Special Elements.................................................... 894
CWE-795: Only Filtering Special Elements at a Specified Location............................................................... 895
CWE-796: Only Filtering Special Elements Relative to a Marker................................................................... 896
CWE-797: Only Filtering Special Elements at an Absolute Position.............................................................. 896
CWE-798: Use of Hard-coded Credentials..................................................................................................... 897
CWE-799: Improper Control of Interaction Frequency................................................................................... 900
CWE-800: Weaknesses in the 2010 CWE/SANS Top 25 Most Dangerous Programming Errors................... 902
CWE-801: 2010 Top 25 - Insecure Interaction Between Components........................................................... 903
CWE-802: 2010 Top 25 - Risky Resource Management............................................................................... 903
CWE-803: 2010 Top 25 - Porous Defenses................................................................................................... 904
CWE-804: Guessable CAPTCHA................................................................................................................... 904
CWE-805: Buffer Access with Incorrect Length Value................................................................................... 905
CWE-806: Buffer Access Using Size of Source Buffer.................................................................................. 908
CWE-807: Reliance on Untrusted Inputs in a Security Decision.................................................................... 909
CWE-808: 2010 Top 25 - Weaknesses On the Cusp.................................................................................... 912
CWE-1000: Research Concepts..................................................................................................................... 913
CWE-2000: Comprehensive CWE Dictionary................................................................................................. 914
Appendix A: Graph Views
CWE-629: Weaknesses in OWASP Top Ten (2007)..................................................................................... 931
CWE-631: Resource-specific Weaknesses.................................................................................................... 932
Table of Contents

CWE-678: Composites.................................................................................................................................... 934


CWE-699: Development Concepts................................................................................................................. 935
CWE-700: Seven Pernicious Kingdoms......................................................................................................... 957
CWE-709: Named Chains............................................................................................................................... 959
CWE-711: Weaknesses in OWASP Top Ten (2004)..................................................................................... 960
CWE-734: Weaknesses Addressed by the CERT C Secure Coding Standard.............................................. 963
CWE-750: Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors................... 966
CWE-800: Weaknesses in the 2010 CWE/SANS Top 25 Most Dangerous Programming Errors................... 967
CWE-1000: Research Concepts..................................................................................................................... 969
Glossary ................................................................................................................................................... 990
Index ........................................................................................................................................................... 994

xvi
CWE Version 1.8.1
Symbols Used in CWE

Symbol Meaning

View
Category
Weakness - Class
Weakness - Base
Weakness - Variant
Compound Element - Composite
Compound Element - Named Chain

Symbols Used in CWE

xvii
CWE Version 1.8.1
CWE-1: Location

CWE-1: Location
Category ID: 1 (Category) Status: Incomplete
Description
Summary
Weaknesses in this category are organized based on which phase they are introduced during the
software development and deployment process.
Relationships
Nature Type ID Name Page
ParentOf 2 Environment 699 1
ParentOf 16 Configuration 699 13
ParentOf 17 Code 699 14
MemberOf 699 Development Concepts 699 788

CWE-2: Environment
Category ID: 2 (Category) Status: Draft
Description
Summary
Weaknesses in this category are typically introduced during unexpected environmental
conditions.
Relationships
Nature Type ID Name Page
ChildOf 1 Location 699 1

CWE-1: Location
ParentOf 3 Technology-specific Environment Issues 699 1
ParentOf 5 J2EE Misconfiguration: Data Transmission Without Encryption 700 2
ParentOf 6 J2EE Misconfiguration: Insufficient Session-ID Length 700 3
ParentOf 7 J2EE Misconfiguration: Missing Custom Error Page 700 4
ParentOf 8 J2EE Misconfiguration: Entity Bean Declared Remote 700 5
ParentOf 9 J2EE Misconfiguration: Weak Access Permissions for EJB 700 6
Methods
ParentOf 11 ASP.NET Misconfiguration: Creating Debug Binary 700 7
ParentOf 12 ASP.NET Misconfiguration: Missing Custom Error Page 700 8
ParentOf 13 ASP.NET Misconfiguration: Password in Configuration File 700 9
ParentOf 14 Compiler Removal of Code to Clear Buffers 699 10
700
ParentOf 15 External Control of System or Configuration Setting 699 12
ParentOf 435 Interaction Error 699 529
ParentOf 552 Files or Directories Accessible to External Parties 699 635
ParentOf 650 Trusting HTTP Permission Methods on the Server Side 699 730
MemberOf 700 Seven Pernicious Kingdoms 700 789

CWE-3: Technology-specific Environment Issues


Category ID: 3 (Category) Status: Draft
Description
Summary
Weaknesses in this category are typically introduced during unexpected environmental conditions
in particular technologies.
Relationships
Nature Type ID Name Page
ChildOf 2 Environment 699 1
ParentOf 4 J2EE Environment Issues 699 2

1
CWE Version 1.8.1
CWE-4: J2EE Environment Issues

Nature Type ID Name Page


ParentOf 519 .NET Environment Issues 699 614

CWE-4: J2EE Environment Issues


Category ID: 4 (Category) Status: Incomplete
Description
Summary
J2EE framework related environment issues with security implications.
Relationships
Nature Type ID Name Page
ChildOf 3 Technology-specific Environment Issues 699 1
ChildOf 731 OWASP Top Ten 2004 Category A10 - Insecure Configuration 711 825
Management
ParentOf 5 J2EE Misconfiguration: Data Transmission Without Encryption 699 2
ParentOf 6 J2EE Misconfiguration: Insufficient Session-ID Length 699 3
ParentOf 7 J2EE Misconfiguration: Missing Custom Error Page 699 4
ParentOf 8 J2EE Misconfiguration: Entity Bean Declared Remote 699 5
ParentOf 9 J2EE Misconfiguration: Weak Access Permissions for EJB 699 6
Methods
CWE-4: J2EE Environment Issues

ParentOf 555 J2EE Misconfiguration: Plaintext Password in Configuration 699 637


File
Taxonomy Mappings
Mapped Taxonomy Name Node ID Fit Mapped Node Name
OWASP Top Ten 2004 A10 CWE More Specific Insecure Configuration Management

CWE-5: J2EE Misconfiguration: Data Transmission


Without Encryption
Weakness ID: 5 (Weakness Variant) Status: Draft
Description
Summary
Information sent over a network can be compromised while in transit. An attacker may be able to
read/modify the contents if the data are sent in plaintext or are weakly encrypted.
Time of Introduction
• Implementation
• Operation
Applicable Platforms
Languages
• Java
Potential Mitigations
The application configuration should ensure that SSL or an encryption mechanism of equivalent
strength and vetted reputation is used for all access-controlled pages.
Other Notes
If an application uses SSL to guarantee confidential communication with client browsers, the
application configuration should make it impossible to view any access controlled page without
SSL. There are three common ways for SSL to be bypassed: - (1) A user manually enters URL and
types "HTTP" rather than "HTTPS". - (2) Attackers intentionally send a user to an insecure URL. -
(3) A programmer erroneously creates a relative link to a page in the application, failing to switch
from HTTP to HTTPS. (This is particularly easy to do when the link moves between public and
secured areas on a web site.)
Relationships

2
CWE Version 1.8.1
CWE-6: J2EE Misconfiguration: Insufficient Session-ID Length

Nature Type ID Name Page


ChildOf 2 Environment 700 1
ChildOf 4 J2EE Environment Issues 699 2
ChildOf 319 Cleartext Transmission of Sensitive Information 1000 394

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
7 Pernicious Kingdoms J2EE Misconfiguration: Insecure Transport

CWE-6: J2EE Misconfiguration: Insufficient Session-ID


Length
Weakness ID: 6 (Weakness Variant) Status: Incomplete

CWE-6: J2EE Misconfiguration: Insufficient Session-ID Length


Description
Summary
The J2EE application is configured to use an insufficient session ID length.
Extended Description
If an attacker can guess or steal a session ID, then he/she may be able to take over the user's
session (called session hijacking). The number of possible session IDs increases with increased
session ID length, making it more difficult to guess or steal a session ID.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• Java
Common Consequences
Integrity
If an attacker can guess an authenticated user's session identifier, they can take over the user's
session.
Enabling Factors for Exploitation
If attackers use a botnet with hundreds or thousands of drone computers, it is reasonable to
assume that they could attempt tens of thousands of guesses per second. If the web site in
question is large and popular, a high volume of guessing might go unnoticed for some time.
Potential Mitigations
Session identifiers should be at least 128 bits long to prevent brute-force session guessing. A
shorter session identifier leaves the application open to brute-force session guessing attacks.
Implementation
A lower bound on the number of valid session identifiers that are available to be guessed is the
number of users that are active on a site at any given moment. However, any users that abandon
their sessions without logging out will increase this number. (This is one of many good reasons to
have a short inactive session timeout.) With a 64 bit session identifier, assume 32 bits of entropy.
For a large web site, assume that the attacker can try 1,000 guesses per second and that there
are 10,000 valid session identifiers at any given moment. Given these assumptions, the expected
time for an attacker to successfully guess a valid session identifier is less than 4 minutes. Now
assume a 128 bit session identifier that provides 64 bits of entropy. With a very large web site, an
attacker might try 10,000 guesses per second with 100,000 valid session identifiers available to
be guessed. Given these assumptions, the expected time for an attacker to successfully guess a
valid session identifier is greater than 292 years.
Background Details
Session ID's can be used to identify communicating parties in a web environment.
The expected number of seconds required to guess a valid session identifier is given by the
equation: (2^B+1)/(2*A*S) Where: - B is the number of bits of entropy in the session identifier. -

3
CWE Version 1.8.1
CWE-7: J2EE Misconfiguration: Missing Custom Error Page

A is the number of guesses an attacker can try each second. - S is the number of valid session
identifiers that are valid and available to be guessed at any given time. The number of bits of
entropy in the session identifier is always less than the total number of bits in the session identifier.
For example, if session identifiers were provided in ascending order, there would be close to zero
bits of entropy in the session identifier no matter the identifier's length. Assuming that the session
identifiers are being generated using a good source of random numbers, we will estimate the
number of bits of entropy in a session identifier to be half the total number of bits in the session
identifier. For realistic identifier lengths this is possible, though perhaps optimistic.
Relationships
Nature Type ID Name Page
ChildOf 2 Environment 700 1
ChildOf 4 J2EE Environment Issues 699 2
ChildOf 334 Small Space of Random Values 1000 414
CWE-7: J2EE Misconfiguration: Missing Custom Error Page

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
7 Pernicious Kingdoms J2EE Misconfiguration: Insufficient Session-ID Length
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
21 Exploitation of Session Variables, Resource IDs and other Trusted Credentials
59 Session Credential Falsification through Prediction
References
< http://www.securiteam.com/securityreviews/5TP0F0UEVQ.html >.

CWE-7: J2EE Misconfiguration: Missing Custom Error


Page
Weakness ID: 7 (Weakness Variant) Status: Incomplete
Description
Summary
The default error page of a web application should not display sensitive information about the
software system.
Extended Description
A Web application must define a default error page for 4xx errors (e.g. 404), 5xx (e.g. 500) errors
and catch java.lang.Throwable exceptions to prevent attackers from mining information from the
application container's built-in error response.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• Java
Demonstrative Examples
In the snippet below, an unchecked runtime exception thrown from within the try block may cause
the container to display its default error page (which may contain a full stack trace, among other
things).
Java Example: Bad Code

Public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


try {
...
} catch (ApplicationSpecificException ase) {
logger.error("Caught: " + ase.toString());
}
}

4
CWE Version 1.8.1
CWE-8: J2EE Misconfiguration: Entity Bean Declared Remote

Potential Mitigations
Handle exceptions appropriately in source code.
Always define appropriate error pages.
Do not attempt to process an error or attempt to mask it.
Verify return values are correct and do not supply sensitive information about the system.
Other Notes
When an attacker explores a web site looking for vulnerabilities, the amount of information that
the site provides is crucial to the eventual success or failure of any attempted attacks. If the
application shows the attacker a stack trace, it relinquishes information that makes the attacker's
job significantly easier. For example, a stack trace might show the attacker a malformed SQL
query string, the type of database being used, and the version of the application container.
This information enables the attacker to target known vulnerabilities in these components.
The application configuration should specify a default error page in order to guarantee that the

CWE-8: J2EE Misconfiguration: Entity Bean Declared Remote


application will never leak error messages to an attacker. Handling standard HTTP error codes is
useful and user-friendly in addition to being a good security practice, and a good configuration will
also define a last-chance error handler that catches any exception that could possibly be thrown by
the application.
Relationships
Nature Type ID Name Page
ChildOf 2 Environment 700 1
ChildOf 4 J2EE Environment Issues 699 2
ChildOf 728 OWASP Top Ten 2004 Category A7 - Improper Error 711 823
Handling
ChildOf 756 Missing Custom Error Page 699 849
1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
7 Pernicious Kingdoms J2EE Misconfiguration: Missing Error Handling
References
M. Howard, D. LeBlanc and J. Viega. "19 Deadly Sins of Software Security". McGraw-Hill/Osborne.
2005.

CWE-8: J2EE Misconfiguration: Entity Bean Declared


Remote
Weakness ID: 8 (Weakness Variant) Status: Incomplete
Description
Summary
When an application exposes a remote interface for an entity bean, it might also expose methods
that get or set the bean's data. These methods could be leveraged to read sensitive information,
or to change data in ways that violate the application's expectations, potentially leading to other
vulnerabilities.
Time of Introduction
• Architecture and Design
• Implementation
Demonstrative Examples
XML Example: Bad Code

<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>EmployeeRecord</ejb-name>
<home>com.wombat.empl.EmployeeRecordHome</home>
<remote>com.wombat.empl.EmployeeRecord</remote>
...

5
CWE Version 1.8.1
CWE-9: J2EE Misconfiguration: Weak Access Permissions for EJB Methods

</entity>
...
</enterprise-beans>
</ejb-jar>

Potential Mitigations
Declare Java beans "local" when possible. When a bean must be remotely accessible, make
sure that sensitive information is not exposed, and ensure that your application logic performs
appropriate validation of any data that might be modified by an attacker.
Other Notes
Entity beans that expose a remote interface become part of an application's attack surface. For
CWE-9: J2EE Misconfiguration: Weak Access Permissions for EJB Methods

performance reasons, an application should rarely use remote entity beans, so there is a good
chance that a remote entity bean declaration is an error.
Relationships
Nature Type ID Name Page
ChildOf 2 Environment 700 1
ChildOf 4 J2EE Environment Issues 699 2
ChildOf 668 Exposure of Resource to Wrong Sphere 1000 753

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
7 Pernicious Kingdoms J2EE Misconfiguration: Unsafe Bean Declaration

CWE-9: J2EE Misconfiguration: Weak Access Permissions


for EJB Methods
Weakness ID: 9 (Weakness Variant) Status: Draft
Description
Summary
If elevated access rights are assigned to EJB methods, then an attacker can take advantage of
the permissions to exploit the software system.
Time of Introduction
• Architecture and Design
• Implementation
Demonstrative Examples
The following deployment descriptor grants ANYONE permission to invoke the Employee EJB's
method named getSalary().
XML Example: Bad Code

<ejb-jar>
...
<assembly-descriptor>
<method-permission>
<role-name>ANYONE</role-name>
<method>
<ejb-name>Employee</ejb-name>
<method-name>getSalary</method-name>
</method-permission>
</assembly-descriptor>
...
</ejb-jar>

Potential Mitigations
Follow the principle of least privilege when assigning access rights to EJB methods. Permission to
invoke EJB methods should not be granted to the ANYONE role.
Other Notes
If the EJB deployment descriptor contains one or more method permissions that grant access to
the special ANYONE role, it indicates that access control for the application has not been fully

6
CWE Version 1.8.1
CWE-10: ASP.NET Environment Issues

thought through or that the application is structured in such a way that reasonable access control
restrictions are impossible.
Relationships
Nature Type ID Name Page
ChildOf 2 Environment 700 1
ChildOf 4 J2EE Environment Issues 699 2
ChildOf 266 Incorrect Privilege Assignment 1000 333
ChildOf 723 OWASP Top Ten 2004 Category A2 - Broken Access Control 711 821

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
7 Pernicious Kingdoms J2EE Misconfiguration: Weak Access Permissions

CWE-10: ASP.NET Environment Issues


Category ID: 10 (Category) Status: Incomplete
Description
Summary
ASP.NET framework/language related environment issues with security implications.

CWE-10: ASP.NET Environment Issues


Relationships
Nature Type ID Name Page
ChildOf 519 .NET Environment Issues 699 614
ChildOf 731 OWASP Top Ten 2004 Category A10 - Insecure Configuration 711 825
Management
ParentOf 11 ASP.NET Misconfiguration: Creating Debug Binary 699 7
ParentOf 12 ASP.NET Misconfiguration: Missing Custom Error Page 699 8
ParentOf 13 ASP.NET Misconfiguration: Password in Configuration File 699 9
ParentOf 554 ASP.NET Misconfiguration: Not Using Input Validation 699 637
Framework
ParentOf 556 ASP.NET Misconfiguration: Use of Identity Impersonation 699 638

Taxonomy Mappings
Mapped Taxonomy Name Node ID Fit Mapped Node Name
OWASP Top Ten 2004 A10 CWE More Specific Insecure Configuration Management

CWE-11: ASP.NET Misconfiguration: Creating Debug


Binary
Weakness ID: 11 (Weakness Variant) Status: Draft
Description
Summary
Debugging messages help attackers learn about the system and plan a form of attack.
Extended Description
ASP .NET applications can be configured to produce debug binaries. These binaries give detailed
debugging messages and should not be used in production environments. Debug binaries are
meant to be used in a development or testing environment and can pose a security risk if they are
deployed to production.
Time of Introduction
• Implementation
• Operation
Applicable Platforms
Languages
• .NET
Common Consequences

7
CWE Version 1.8.1
CWE-12: ASP.NET Misconfiguration: Missing Custom Error Page

Confidentiality
Attackers can leverage the additional information they gain from debugging output to mount
attacks targeted on the framework, database, or other resources used by the application.
Demonstrative Examples
The file web.config contains the debug mode setting. Setting debug to "true" will let the browser
display debugging information.
XML Example: Bad Code

<?xml version="1.0" encoding="utf-8" ?>


<configuration>
<system.web>
<compilation
defaultLanguage="c#"
debug="true"
CWE-12: ASP.NET Misconfiguration: Missing Custom Error Page

/>
...
</system.web>
</configuration>

Change the debug mode to false when the application is deployed into production.
Potential Mitigations
Avoid releasing debug binaries into the production environment. Change the debug mode to false
when the application is deployed into production (See demonstrative example).
Background Details
The debug attribute of the <compilation> tag defines whether compiled binaries should include
debugging information. The use of debug binaries causes an application to provide as much
information about itself as possible to the user.
Relationships
Nature Type ID Name Page
ChildOf 2 Environment 700 1
ChildOf 10 ASP.NET Environment Issues 699 7
ChildOf 215 Information Leak Through Debug Information 1000 286

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
7 Pernicious Kingdoms ASP.NET Misconfiguration: Creating Debug Binary

CWE-12: ASP.NET Misconfiguration: Missing Custom Error


Page
Weakness ID: 12 (Weakness Variant) Status: Draft
Description
Summary
An ASP .NET application must enable custom error pages in order to prevent attackers from
mining information from the framework's built-in responses.
Time of Introduction
• Implementation
• Operation
Applicable Platforms
Languages
• .NET
Common Consequences
Confidentiality
Default error pages gives detailed information about the error that occurred, and should not be
used in production environments.
Attackers can leverage the additional information provided by a default error page to mount
attacks targeted on the framework, database, or other resources used by the application.
8
CWE Version 1.8.1
CWE-13: ASP.NET Misconfiguration: Password in Configuration File

Demonstrative Examples
Example 1:
Custom error message mode is turned off. An ASP.NET error message with detailed stack trace
and platform versions will be returned.
ASP.NET Example: Bad Code

<customErrors ... mode="Off" />

Example 2:
Custom error message mode for remote user only. No defaultRedirect error page is specified.
The local user on the web server will see a detailed stack trace. For remote users, an ASP.NET
error message with the server customError configuration setting and the platform version will be
returned.

CWE-13: ASP.NET Misconfiguration: Password in Configuration File


ASP.NET Example: Good Code

<customErrors mode="RemoteOnly" />

Potential Mitigations
Handle exceptions appropriately in source code. The best practice is to use a custom error
message. Make sure that the mode attribute is set to "RemoteOnly" in the web.config file as shown
in the following example.
Good Code

<customErrors mode="RemoteOnly" />

The mode attribute of the <customErrors> tag in the Web.config file defines whether custom or
default error pages are used. It should be configured to use a custom page as follows:
Good Code

<customErrors mode="On" defaultRedirect="YourErrorPage.htm" />

Do not attempt to process an error or attempt to mask it.


Verify return values are correct and do not supply sensitive information about the system.
ASP .NET applications should be configured to use custom error pages instead of the framework
default page.
Background Details
The mode attribute of the <customErrors> tag defines whether custom or default error pages are
used.
Relationships
Nature Type ID Name Page
ChildOf 2 Environment 700 1
ChildOf 10 ASP.NET Environment Issues 699 7
ChildOf 756 Missing Custom Error Page 1000 849

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
7 Pernicious Kingdoms ASP.NET Misconfiguration: Missing Custom Error Handling
References
M. Howard, D. LeBlanc and J. Viega. "19 Deadly Sins of Software Security". McGraw-Hill/Osborne.
2005.
OWASP, Fortify Software. "ASP.NET Misconfiguration: Missing Custom Error Handling". < http://
www.owasp.org/index.php/ASP.NET_Misconfiguration:_Missing_Custom_Error_Handling >.

CWE-13: ASP.NET Misconfiguration: Password in


Configuration File
Weakness ID: 13 (Weakness Variant) Status: Draft
Description

9
CWE Version 1.8.1
CWE-14: Compiler Removal of Code to Clear Buffers

Summary
Storing a plaintext password in a configuration file allows anyone who can read the file access to
the password-protected resource making them an easy target for attackers.
Time of Introduction
• Architecture and Design
• Implementation
Demonstrative Examples
The following connectionString has clear text credentials.
XML Example: Bad Code

<connectionStrings>
<add name="ud_DEV" connectionString="connectDB=uDB; uid=db2admin; pwd=password; dbalias=uDB;"
providerName="System.Data.Odbc" />
</connectionStrings>

Potential Mitigations
Good password management guidelines require that a password never be stored in plaintext.
CWE-14: Compiler Removal of Code to Clear Buffers

Implementation
credentials stored in configuration files should be encrypted.
Implementation
Use standard APIs and industry accepted algorithms to encrypt the credentials stored in
configuration files.
Relationships
Nature Type ID Name Page
ChildOf 2 Environment 700 1
ChildOf 10 ASP.NET Environment Issues 699 7
ChildOf 260 Password in Configuration File 1000 327

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
7 Pernicious Kingdoms ASP.NET Misconfiguration: Password in Configuration File
References
Microsoft Corporation. "How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI". <
http://msdn.microsoft.com/en-us/library/ms998280.aspx >.
Microsoft Corporation. "How To: Encrypt Configuration Sections in ASP.NET 2.0 Using RSA". <
http://msdn.microsoft.com/en-us/library/ms998283.aspx >.
Microsoft Corporation. ".NET Framework Developer's Guide - Securing Connection Strings". <
http://msdn.microsoft.com/en-us/library/89211k9b(VS.80).aspx >.

CWE-14: Compiler Removal of Code to Clear Buffers


Weakness ID: 14 (Weakness Base) Status: Draft
Description
Summary
Sensitive memory is cleared according to the source code, but compiler optimizations leave the
memory untouched when it is not read from again, aka "dead store removal."
Extended Description
This compiler optimization error occurs when:
1. Secret data are stored in memory.
2. The secret data are scrubbed from memory by overwriting its contents.
3. The source code is compiled using an optimizing compiler, which identifies and removes
the function that overwrites the contents as a dead store because the memory is not used
subsequently.
Time of Introduction
• Implementation
• Build and Compilation
10
CWE Version 1.8.1
CWE-14: Compiler Removal of Code to Clear Buffers

Applicable Platforms
Languages
• C
• C++
Detection Methods
Black Box
This specific weakness is impossible to detect using black box methods. While an analyst could
examine memory to see that it has not been scrubbed, an analysis of the executable would not be
successful. This is because the compiler has already removed the relevant code. Only the source
code shows whether the programmer intended to clear the memory or not, so this weakness is
indistinguishable from others.
White Box
This weakness is only detectable using white box methods (see black box detection factor).
Careful analysis is required to determine if the code is likely to be removed by the compiler.
Demonstrative Examples

CWE-14: Compiler Removal of Code to Clear Buffers


The following code reads a password from the user, uses the password to connect to a back-end
mainframe and then attempts to scrub the password from memory using memset().
C Example: Bad Code

void GetData(char *MFAddr) {


char pwd[64];
if (GetPasswordFromUser(pwd, sizeof(pwd))) {
if (ConnectToMainframe(MFAddr, pwd)) {
// Interaction with mainframe
}
}
memset(pwd, 0, sizeof(pwd));
}

The code in the example will behave correctly if it is executed verbatim, but if the code is compiled
using an optimizing compiler, such as Microsoft Visual C++ .NET or GCC 3.x, then the call to
memset() will be removed as a dead store because the buffer pwd is not used after its value
is overwritten [18]. Because the buffer pwd contains a sensitive value, the application may be
vulnerable to attack if the data are left memory resident. If attackers are able to access the
correct region of memory, they may use the recovered password to gain control of the system.
It is common practice to overwrite sensitive data manipulated in memory, such as passwords or
cryptographic keys, in order to prevent attackers from learning system secrets. However, with the
advent of optimizing compilers, programs do not always behave as their source code alone would
suggest. In the example, the compiler interprets the call to memset() as dead code because the
memory being written to is not subsequently used, despite the fact that there is clearly a security
motivation for the operation to occur. The problem here is that many compilers, and in fact many
programming languages, do not take this and other security concerns into consideration in their
efforts to improve efficiency. Attackers typically exploit this type of vulnerability by using a core
dump or runtime mechanism to access the memory used by a particular application and recover
the secret information. Once an attacker has access to the secret information, it is relatively
straightforward to further exploit the system and possibly compromise other resources with which
the application interacts.
Potential Mitigations
Implementation
Store the sensitive data in a "volatile" memory location if available.
Build and Compilation
If possible, configure your compiler so that it does not remove dead stores.
Architecture and Design
Where possible, encrypt sensitive data that are used by a software system.
Relationships

11
CWE Version 1.8.1
CWE-15: External Control of System or Configuration Setting

Nature Type ID Name Page


ChildOf 2 Environment 699 1
700
ChildOf 503 Byte/Object Code 699 606
ChildOf 633 Weaknesses that Affect Memory 631 707
ChildOf 729 OWASP Top Ten 2004 Category A8 - Insecure Storage 711 824
ChildOf 733 Compiler Optimization Removal or Modification of Security- 1000 830
critical Code
ChildOf 747 CERT C Secure Coding Section 49 - Miscellaneous (MSC) 734 838

Affected Resources
• Memory
Taxonomy Mappings
Mapped Taxonomy Name Node ID Fit Mapped Node Name
CWE-15: External Control of System or Configuration Setting

7 Pernicious Kingdoms Insecure Compiler Optimization


PLOVER Sensitive memory uncleared by compiler
optimization
OWASP Top Ten 2004 A8 CWE More Specific Insecure Storage
CERT C Secure Coding MSC06-C Be aware of compiler optimization when
dealing with sensitive data
References
[REF-11] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 9, "A Compiler Optimization
Caveat" Page 322. 2nd Edition. Microsoft. 2002.
Michael Howard. "When scrubbing secrets in memory doesn't work". BugTraq. 2002-11-05. <
http://cert.uni-stuttgart.de/archive/bugtraq/2002/11/msg00046.html >.
< http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncode/html/
secure10102002.asp >.
Joseph Wagner. "GNU GCC: Optimizer Removes Code Necessary for Security". Bugtraq.
2002-11-16. < http://www.derkeiler.com/Mailing-Lists/securityfocus/bugtraq/2002-11/0257.html >.

CWE-15: External Control of System or Configuration


Setting
Weakness ID: 15 (Weakness Base) Status: Incomplete
Description
Summary
One or more system settings or configuration elements can be externally controlled by a user.
Extended Description
Allowing external control of system settings can disrupt service or cause an application to behave
in unexpected, and potentially malicious ways.
Time of Introduction
• Implementation
Modes of Introduction
Setting manipulation vulnerabilities occur when an attacker can control values that govern the
behavior of the system, manage specific resources, or in some way affect the functionality of the
application.
Demonstrative Examples
Example 1:
The following C code accepts a number as one of its command line parameters and sets it as the
host ID of the current machine.
C Example: Bad Code

...
sethostid(argv[1]);
...

12
CWE Version 1.8.1
CWE-16: Configuration

Although a process must be privileged to successfully invoke sethostid(), unprivileged users may
be able to invoke the program. The code in this example allows user input to directly control the
value of a system setting. If an attacker provides a malicious value for host ID, the attacker can
misidentify the affected machine on the network or cause other unintended behavior.
Example 2:
The following Java code snippet reads a string from an HttpServletRequest and sets it as the
active catalog for a database Connection.
Java Example: Bad Code

...
conn.setCatalog(request.getParameter("catalog"));
...

In this example, an attacker could cause an error by providing a nonexistent catalog name or
connect to an unauthorized portion of the database.
Potential Mitigations
Compartmentalize your system and determine where the trust boundaries exist. Any input/control
outside the trust boundary should be treated as potentially hostile.
Because setting manipulation covers a diverse set of functions, any attempt at illustrating it will
inevitably be incomplete. Rather than searching for a tight-knit relationship between the functions
addressed in the setting manipulation category, take a step back and consider the sorts of system
values that an attacker should not be allowed to control.
In general, do not allow user-provided or otherwise untrusted data to control sensitive values. The

CWE-16: Configuration
leverage that an attacker gains by controlling these values is not always immediately obvious, but
do not underestimate the creativity of your attacker.
Relationships
Nature Type ID Name Page
ChildOf 2 Environment 699 1
ChildOf 20 Improper Input Validation 700 15
ChildOf 610 Externally Controlled Reference to a Resource in Another 1000 688
Sphere
ChildOf 642 External Control of Critical State Data 1000 718

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
7 Pernicious Kingdoms Setting Manipulation
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
13 Subverting Environment Variable Values
69 Target Programs with Elevated Privileges
76 Manipulating Input to File System Calls
77 Manipulating User-Controlled Variables
146 XML Schema Poisoning

CWE-16: Configuration
Category ID: 16 (Category) Status: Draft
Description
Summary
Weaknesses in this category are typically introduced during the configuration of the software.
Relationships
Nature Type ID Name Page
ChildOf 1 Location 699 1
MemberOf 635 Weaknesses Used by NVD 635 708

Taxonomy Mappings

13
CWE Version 1.8.1
CWE-17: Code

Mapped Taxonomy Name Node ID Mapped Node Name


WASC 14 Server Misconfiguration
WASC 15 Application Misconfiguration

CWE-17: Code
Category ID: 17 (Category) Status: Draft
Description
Summary
Weaknesses in this category are typically introduced during code development, including
specification, design, and implementation.
Relationships
Nature Type ID Name Page
ChildOf 1 Location 699 1
ParentOf 18 Source Code 699 14
ParentOf 503 Byte/Object Code 699 606
ParentOf 657 Violation of Secure Design Principles 699 738

CWE-18: Source Code


Category ID: 18 (Category) Status: Draft
Description
Summary
Weaknesses in this category are typically found within source code.
Relationships
CWE-17: Code

Nature Type ID Name Page


ChildOf 17 Code 699 14
ParentOf 19 Data Handling 699 14
ParentOf 227 Failure to Fulfill API Contract ('API Abuse') 699 293
ParentOf 254 Security Features 699 319
ParentOf 361 Time and State 699 439
ParentOf 388 Error Handling 699 472
ParentOf 398 Indicator of Poor Code Quality 699 484
ParentOf 417 Channel and Path Errors 699 510
ParentOf 429 Handler Errors 699 522
ParentOf 438 Behavioral Problems 699 532
ParentOf 442 Web Problems 699 535
ParentOf 445 User Interface Errors 699 537
ParentOf 452 Initialization and Cleanup Errors 699 542
ParentOf 465 Pointer Issues 699 555
ParentOf 485 Insufficient Encapsulation 699 581

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
Landwehr Source Code

CWE-19: Data Handling


Category ID: 19 (Category) Status: Draft
Description
Summary
Weaknesses in this category are typically found in functionality that processes data.
Relationships

14
CWE Version 1.8.1
CWE-20: Improper Input Validation

Nature Type ID Name Page


ChildOf 18 Source Code 699 14
ParentOf 20 Improper Input Validation 699 15
ParentOf 116 Improper Encoding or Escaping of Output 699 153
ParentOf 118 Improper Access of Indexable Resource ('Range Error') 699 160
ParentOf 133 String Errors 699 192
ParentOf 136 Type Errors 699 197
ParentOf 137 Representation Errors 699 197
ParentOf 189 Numeric Errors 699 250
ParentOf 199 Information Management Errors 699 268
ParentOf 228 Improper Handling of Syntactically Invalid Structure 699 294
ParentOf 461 Data Structure Issues 699 551
ParentOf 471 Modification of Assumed-Immutable Data (MAID) 699 562

Related Attack Patterns


CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
99 XML Parser Attack
100 Overflow Buffers

CWE-20: Improper Input Validation

CWE-20: Improper Input Validation


Weakness ID: 20 (Weakness Class) Status: Usable
Description
Summary
The product does not validate or incorrectly validates input that can affect the control flow or data
flow of a program.
Extended Description
When software fails to validate input properly, an attacker is able to craft the input in a form
that is not expected by the rest of the application. This will lead to parts of the system receiving
unintended input, which may result in altered control flow, arbitrary control of a resource, or
arbitrary code execution.
Terminology Notes
The "input validation" term is extremely common, but it is used in many different ways. In some
cases its usage can obscure the real underlying weakness or otherwise hide chaining and
composite relationships.
Some people use "input validation" as a general term that covers many different techniques for
ensuring that input is appropriate, such as cleansing/filtering, canonicalization, and escaping.
Others use the term in a more narrow context to simply mean "checking if an input conforms to
expectations without changing it."
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• Language-independent
Platform Notes
Modes of Introduction
If a programmer believes that an attacker cannot modify certain inputs, then the programmer
might not perform any input validation at all. For example, in web applications, many programmers
believe that cookies and hidden form fields can not be modified from a web browser (CWE-472),
although they can be altered using a proxy or a custom program. In a client-server architecture,
the programmer might assume that client-side security checks cannot be bypassed, even when a
custom client could be written that skips those checks (CWE-602).
Common Consequences
15
CWE Version 1.8.1
CWE-20: Improper Input Validation

Availability
An attacker could provide unexpected values and cause a program crash or excessive
consumption of resources, such as memory and CPU.
Confidentiality
An attacker could read confidential data if they are able to control resource references.
Integrity
An attacker could use malicious input to modify data or possibly alter control flow in unexpected
ways, including arbitrary command execution.
Likelihood of Exploit
High
Detection Methods
Automated Static Analysis
Some instances of improper input validation can be detected using automated static analysis.
A static analysis tool might allow the user to specify which application-specific methods or
functions perform input validation; the tool might also have built-in knowledge of validation
frameworks such as Struts. The tool may then suppress or de-prioritize any associated warnings.
This allows the analyst to focus on areas of the software in which input validation does not appear
to be present.
Except in the cases described in the previous paragraph, automated static analysis might not be
CWE-20: Improper Input Validation

able to recognize when proper input validation is being performed, leading to false positives - i.e.,
warnings that do not have any security consequences or require any code changes.
Manual Static Analysis
When custom input validation is required, such as when enforcing business rules, manual
analysis is necessary to ensure that the validation is properly implemented.
Fuzzing
Fuzzing techniques can be useful for detecting input validation errors. When unexpected inputs
are provided to the software, the software should not crash or otherwise become unstable, and
it should generate application-controlled error messages. If exceptions or interpreter-generated
error messages occur, this indicates that the input was not detected and handled within the
application logic itself.
Demonstrative Examples
Example 1:
This example demonstrates a shopping interaction in which the user is free to specify the quantity
of items to be purchased and a total is calculated.
Java Example: Bad Code

...
public static final double price = 20.00;
int quantity = currentUser.getAttribute("quantity");
double total = price * quantity;
chargeUser(total);
...

The user has no control over the price variable, however the code does not prevent a negative
value from being specified for quantity. If an attacker were to provide a negative value, then the
user would have their account credited instead of debited.
Example 2:
This example asks the user for a height and width of an m X n game board with a maximum
dimension of 100 squares.
C Example: Bad Code

...
#define MAX_DIM 100
...
/* board dimensions */
int m,n, error;
board_square_t *board;

16
CWE Version 1.8.1
CWE-20: Improper Input Validation

printf("Please specify the board height: \n");


error = scanf("%d", &m);
if ( EOF == error ){
die("No integer passed: Die evil hacker!\n");
}
printf("Please specify the board width: \n");
error = scanf("%d", &n);
if ( EOF == error ){
die("No integer passed: Die evil hacker!\n");
}
if ( m > MAX_DIM || n > MAX_DIM ) {
die("Value too large: Die evil hacker!\n");
}
board = (board_square_t*) malloc( m * n * sizeof(board_square_t));
...

While this code checks to make sure the user cannot specify large, positive integers and consume
too much memory, it fails to check for negative values supplied by the user. As a result, an attacker
can perform a resource consumption (CWE-400) attack against this program by specifying two,
large negative values that will not overflow, resulting in a very large memory allocation (CWE-789)
and possibly a system crash. Alternatively, an attacker can provide very large negative values
which will cause an integer overflow (CWE-190) and unexpected behavior will follow depending on
how the values are treated in the remainder of the program.

CWE-20: Improper Input Validation


Example 3:
The following example shows a PHP application in which the programmer attempts to display a
user's birthday and homepage.
PHP Example: Bad Code

$birthday = $_GET['birthday'];
$homepage = $_GET['homepage'];
echo "Birthday: $birthday<br>Homepage: <a href=$homepage>click here</a>"

The programmer intended for $birthday to be in a date format and $homepage to be a valid URL.
However, since the values are derived from an HTTP request, if an attacker can trick a victim into
clicking a crafted URL with <script> tags providing the values for birthday and / or homepage, then
the script will run on the client's browser when the web server echoes the content. Notice that even
if the programmer were to defend the $birthday variable by restricting input to integers and dashes,
it would still be possible for an attacker to provide a string of the form:
Attack

2009-01-09--

If this data were used in a SQL statement, it would treat the remainder of the statement as a
comment. The comment could disable other security-related logic in the statement. In this case,
encoding combined with input validation would be a more useful protection mechanism.
Furthermore, an XSS (CWE-79) attack or SQL injection (CWE-89) are just a few of the potential
consequences in a failed protection mechanism of this nature. Depending on the context of the
code, CRLF Injection (CWE-93), Argument Injection (CWE-88), or Command Injection (CWE-77)
may also be possible.
Example 4:
This function attempts to extract a pair of numbers from a user-supplied string.
C Example: Bad Code

void parse_data(char *untrusted_input){


int m, n, error;
error = sscanf(untrusted_input, "%d:%d", &m, &n);
if ( EOF == error ){
die("Did not specify integer value. Die evil hacker!\n");
}
/* proceed assuming n and m are initialized correctly */
}

17
CWE Version 1.8.1
CWE-20: Improper Input Validation

This code attempts to extract two integer values out of a formatted, user-supplied input. However,
if an attacker were to provide an input of the form:
Attack

123:

then only the m variable will be initialized. Subsequent use of n may result in the use of an
uninitialized variable (CWE-457).
Example 5:
The following example takes a user-supplied value to allocate an array of objects and then
operates on the array.
Java Example: Bad Code

private void buildList ( int untrustedListSize ){


if ( 0 > untrustedListSize ){
die("Negative value supplied for list size, die evil hacker!");
}
Widget[] list = new Widget [ untrustedListSize ];
list[0] = new Widget();
}

This example attempts to build a list from a user-specified value, and even checks to ensure a non-
negative value is supplied. If, however, a 0 value is provided, the code will build an array of size 0
CWE-20: Improper Input Validation

and then try to store a new Widget in the first location, causing an exception to be thrown.
Observed Examples
Reference Description
CVE-2006-3790 size field that is inconsistent with packet size leads to buffer over-read
CVE-2006-5462 use of extra data in a signature allows certificate signature forging
CVE-2006-5525 incomplete blacklist allows SQL injection
CVE-2006-6658 request with missing parameters leads to information leak
CVE-2006-6870 infinite loop from DNS packet with a label that points to itself
CVE-2007-2442 zero-length input causes free of uninitialized pointer
CVE-2007-3409 infinite loop from DNS packet with a label that points to itself
CVE-2007-5893 HTTP request with missing protocol version number leads to crash
CVE-2008-0600 kernel does not validate an incoming pointer before dereferencing it
CVE-2008-1284 NUL byte in theme name cause directory traversal impact to be worse
CVE-2008-1303 missing parameter leads to crash
CVE-2008-1440 lack of validation of length field leads to infinite loop
CVE-2008-1625 lack of validation of input to an IOCTL allows code execution
CVE-2008-1737 anti-virus product allows DoS via zero-length field
CVE-2008-1738 anti-virus product has insufficient input validation of hooked SSDT functions, allowing code
execution
CVE-2008-2223 SQL injection through an ID that was supposed to be numeric.
CVE-2008-2252 kernel does not validate parameters sent in from userland, allowing code execution
CVE-2008-2309 product uses a blacklist to identify potentially dangerous content, allowing attacker to
bypass a warning
CVE-2008-2374 lack of validation of string length fields allows memory consumption or buffer over-read
CVE-2008-3174 driver in security product allows code execution due to insufficient validation
CVE-2008-3177 zero-length attachment causes crash
CVE-2008-3464 driver does not validate input from userland to the kernel
CVE-2008-3477 lack of input validation in spreadsheet program leads to buffer overflows, integer overflows,
array index errors, and memory corruption.
CVE-2008-3494 security bypass via an extra header
CVE-2008-3571 empty packet triggers reboot
CVE-2008-3660 crash via multiple "." characters in file extension
CVE-2008-3680 packet with invalid version number leads to NULL pointer dereference
CVE-2008-3812 router crashes with a malformed packet
CVE-2008-3843 insufficient validation enables XSS
CVE-2008-4114 system crash with offset value that is inconsistent with packet size
CVE-2008-5285 infinite loop from a long SMTP request

18
CWE Version 1.8.1
CWE-20: Improper Input Validation

Reference Description
CVE-2008-5305 Eval injection in Perl program using an ID that should only contain hyphens and numbers.
CVE-2008-5563 crash via a malformed frame structure
Potential Mitigations
Architecture and Design
Input Validation
Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. If you use
Struts, be mindful of weaknesses covered by the CWE-101 category.
Architecture and Design
Implementation
Identify and Reduce Attack Surface
Understand all the potential areas where untrusted inputs can enter your software: parameters
or arguments, cookies, anything read from the network, environment variables, reverse DNS
lookups, query results, request headers, URL components, e-mail, files, databases, and any
external systems that provide data to the application. Remember that such inputs may be
obtained indirectly through API calls.
Implementation
Input Validation

CWE-20: Improper Input Validation


Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a
whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not
strictly conform to specifications, or transform it into something that does. Do not rely exclusively
on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). However, blacklists
can be useful for detecting potential attacks or determining which inputs are so malformed that
they should be rejected outright.
When performing input validation, consider all potentially relevant properties, including length,
type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency
across related fields, and conformance to business rules. As an example of business rule logic,
"boat" may be syntactically valid because it only contains alphanumeric characters, but it is not
valid if you are expecting colors such as "red" or "blue."
Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are
duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side
checks by modifying values after the checks have been performed, or by changing the client to
remove the client-side checks entirely. Then, these modified values would be submitted to the
server.
Even though client-side checks provide minimal benefits with respect to server-side security,
they are still useful. First, they can support intrusion detection. If the server receives input that
should have been rejected by the client, then it may be an indication of an attack. Second, client-
side error-checking can provide helpful feedback to the user about the expectations for valid
input. Third, there may be a reduction in server-side processing time for accidental input errors,
although this is typically a small savings.
Architecture and Design
Do not rely exclusively on blacklist validation to detect malicious input or to encode output
(CWE-184). There are too many ways to encode the same character, so you're likely to miss
some variants.
Implementation
When your application combines data from multiple sources, perform the validation after the
sources have been combined. The individual data elements may pass the validation step but
violate the intended restrictions after they have been combined.

19
CWE Version 1.8.1
CWE-20: Improper Input Validation

Implementation
Be especially careful to validate your input when you invoke code that crosses language
boundaries, such as from an interpreted language to native code. This could create an
unexpected interaction between the language boundaries. Ensure that you are not violating any
of the expectations of the language with which you are interfacing. For example, even though
Java may not be susceptible to buffer overflows, providing a large argument in a call to native
code might trigger an overflow.
Implementation
Directly convert your input type into the expected data type, such as using a conversion function
that translates a string into a number. After converting to the expected data type, ensure that the
input's values fall within the expected range of allowable values and that multi-field consistencies
are maintained.
Implementation
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated (CWE-180, CWE-181). Make sure that your application does not
inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass
whitelist schemes by introducing dangerous inputs after they have been checked. Use libraries
such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This
CWE-20: Improper Input Validation

will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are
allowed to contain properly-encoded dangerous content.
Implementation
When exchanging data between components, ensure that both components are using the same
character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the
encoding you are using whenever the protocol allows you to do so.
Testing
Use automated static analysis tools that target this type of weakness. Many modern techniques
use data flow analysis to minimize the number of false positives. This is not a perfect solution,
since 100% accuracy and coverage are not feasible.
Testing
Use dynamic tools and techniques that interact with the software using large test suites with
many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The
software's operation may slow down, but it should not become unstable, crash, or generate
incorrect results.
Relationships
Nature Type ID Name Page
ChildOf 19 Data Handling 699 14
CanPrecede 22 Improper Limitation of a Pathname to a Restricted Directory 1000 24
('Path Traversal')
CanPrecede 41 Improper Resolution of Path Equivalence 1000 51
CanPrecede 74 Failure to Sanitize Data into a Different Plane ('Injection') 1000 79
ChildOf 693 Protection Mechanism Failure 1000 783
ChildOf 722 OWASP Top Ten 2004 Category A1 - Unvalidated Input 711 820
ChildOf 738 CERT C Secure Coding Section 04 - Integers (INT) 734 833
ChildOf 742 CERT C Secure Coding Section 08 - Memory Management 734 835
(MEM)
ChildOf 746 CERT C Secure Coding Section 12 - Error Handling (ERR) 734 838
ChildOf 747 CERT C Secure Coding Section 49 - Miscellaneous (MSC) 734 838
ChildOf 751 2009 Top 25 - Insecure Interaction Between Components 750 842
ParentOf 15 External Control of System or Configuration Setting 700 12
ParentOf 21 Pathname Traversal and Equivalence Errors 699 23
ParentOf 73 External Control of File Name or Path 699 75
700

20
CWE Version 1.8.1
CWE-20: Improper Input Validation

Nature Type ID Name Page


ParentOf 77 Improper Sanitization of Special Elements used in a 700 82
Command ('Command Injection')
ParentOf 79 Failure to Preserve Web Page Structure ('Cross-site 700 92
Scripting')
ParentOf 89 Improper Sanitization of Special Elements used in an SQL 700 111
Command ('SQL Injection')
ParentOf 99 Improper Control of Resource Identifiers ('Resource Injection') 700 134
ParentOf 100 Technology-Specific Input Validation Problems 699 135
ParentOf 102 Struts: Duplicate Validation Forms 700 136
ParentOf 103 Struts: Incomplete validate() Method Definition 700 137
ParentOf 104 Struts: Form Bean Does Not Extend Validation Class 700 138
ParentOf 105 Struts: Form Field Without Validator 700 139
1000
ParentOf 106 Struts: Plug-in Framework not in Use 700 140
ParentOf 107 Struts: Unused Validation Form 700 141
ParentOf 108 Struts: Unvalidated Action Form 700 141
1000
ParentOf 109 Struts: Validator Turned Off 700 142
ParentOf 110 Struts: Validator Without Form Field 700 143

CWE-20: Improper Input Validation


ParentOf 111 Direct Use of Unsafe JNI 699 145
700
ParentOf 112 Missing XML Validation 699 146
700
1000
ParentOf 113 Failure to Sanitize CRLF Sequences in HTTP Headers 700 147
('HTTP Response Splitting')
ParentOf 114 Process Control 699 150
700
1000
ParentOf 117 Improper Output Sanitization for Logs 700 158
ParentOf 119 Failure to Constrain Operations within the Bounds of a 699 160
Memory Buffer 700
ParentOf 120 Buffer Copy without Checking Size of Input ('Classic Buffer 700 166
Overflow')
ParentOf 129 Improper Validation of Array Index 699 181
1000
ParentOf 134 Uncontrolled Format String 700 192
ParentOf 170 Improper Null Termination 700 226
ParentOf 190 Integer Overflow or Wraparound 700 250
ParentOf 466 Return of Pointer Value Outside of Expected Range 700 555
ParentOf 470 Use of Externally-Controlled Input to Select Classes or Code 699 560
('Unsafe Reflection') 700
ParentOf 554 ASP.NET Misconfiguration: Not Using Input Validation 699 637
Framework 1000
ParentOf 601 URL Redirection to Untrusted Site ('Open Redirect') 699 677
ParentOf 606 Unchecked Input for Loop Condition 699 685
1000
ParentOf 621 Variable Extraction Error 699 697
ParentOf 622 Unvalidated Function Hook Arguments 699 698
ParentOf 626 Null Byte Interaction Error (Poison Null Byte) 699 701
1000
MemberOf 635 Weaknesses Used by NVD 635 708
ParentOf 680 Integer Overflow to Buffer Overflow 1000 770
ParentOf 690 Unchecked Return Value to NULL Pointer Dereference 1000 780
ParentOf 692 Incomplete Blacklist to Cross-Site Scripting 1000 783
MemberOf 700 Seven Pernicious Kingdoms 700 789
21
CWE Version 1.8.1
CWE-20: Improper Input Validation

Nature Type ID Name Page


ParentOf 781 Improper Address Validation in IOCTL with 699 881
METHOD_NEITHER I/O Control Code 1000
ParentOf 785 Use of Path Manipulation Function without Maximum-sized 699 887
Buffer 700
ParentOf 789 Uncontrolled Memory Allocation 1000 889

Relationship Notes
CWE-116 and CWE-20 have a close association because, depending on the nature of the
structured message, proper input validation can indirectly prevent special characters from
changing the meaning of a structured message. For example, by validating that a numeric ID field
should only contain the 0-9 characters, the programmer effectively prevents injection attacks.
However, input validation is not always sufficient, especially when less stringent data types must
be supported, such as free-form text. Consider a SQL injection scenario in which a last name
is inserted into a query. The name "O'Reilly" would likely pass the validation step since it is a
common last name in the English language. However, it cannot be directly inserted into the
database because it contains the "'" apostrophe character, which would need to be escaped or
otherwise handled. In this case, stripping the apostrophe might reduce the risk of SQL injection,
but it would produce incorrect behavior because the wrong name would be recorded.
Research Gaps
CWE-20: Improper Input Validation

There is not much research into the classification of input validation techniques and their
application. Many publicly-disclosed vulnerabilities simply characterize a problem as "input
validation" without providing more specific details that might contribute to a deeper understanding
of validation techniques and the weaknesses they can prevent or reduce. Validation is over-
emphasized in contrast to other sanitization techniques such as cleansing and enforcement by
conversion. See the vulnerability theory paper.
Taxonomy Mappings
Mapped Taxonomy Name Node ID Fit Mapped Node Name
7 Pernicious Kingdoms Input validation and representation
OWASP Top Ten 2004 A1 CWE More Specific Unvalidated Input
CERT C Secure Coding ERR07-C Prefer functions that support error checking
over equivalent functions that don't
CERT C Secure Coding INT06-C Use strtol() or a related function to convert
a string token to an integer
CERT C Secure Coding MEM10-C Define and use a pointer validation function
CERT C Secure Coding MSC08-C Library functions should validate their
parameters
WASC 20 Improper Input Handling
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
3 Using Leading 'Ghost' Character Sequences to Bypass Input Filters
7 Blind SQL Injection
8 Buffer Overflow in an API Call
9 Buffer Overflow in Local Command-Line Utilities
10 Buffer Overflow via Environment Variables
13 Subverting Environment Variable Values
14 Client-side Injection-induced Buffer Overflow
18 Embedding Scripts in Nonscript Elements
22 Exploiting Trust in Client (aka Make the Client Invisible)
24 Filter Failure through Buffer Overflow
28 Fuzzing
31 Accessing/Intercepting/Modifying HTTP Cookies
32 Embedding Scripts in HTTP Query Strings
42 MIME Conversion
43 Exploiting Multiple Input Interpretation Layers
45 Buffer Overflow via Symbolic Links
46 Overflow Variables and Tags
22
CWE Version 1.8.1
CWE-21: Pathname Traversal and Equivalence Errors

CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)


47 Buffer Overflow via Parameter Expansion
52 Embedding NULL Bytes
53 Postfix, Null Terminate, and Backslash
63 Simple Script Injection
64 Using Slashes and URL Encoding Combined to Bypass Validation Logic
66 SQL Injection
67 String Format Overflow in syslog()
71 Using Unicode Encoding to Bypass Validation Logic
72 URL Encoding
73 User-Controlled Filename
78 Using Escaped Slashes in Alternate Encoding
79 Using Slashes in Alternate Encoding
80 Using UTF-8 Encoding to Bypass Validation Logic
81 Web Logs Tampering
83 XPath Injection

CWE-21: Pathname Traversal and Equivalence Errors


85 Client Network Footprinting (using AJAX/XSS)
86 Embedding Script (XSS ) in HTTP Headers
88 OS Command Injection
91 XSS in IMG Tags
99 XML Parser Attack
101 Server Side Include (SSI) Injection
104 Cross Zone Scripting
106 Cross Site Scripting through Log Files
108 Command Line Execution through SQL Injection
109 Object Relational Mapping Injection
110 SQL Injection through SOAP Parameter Tampering
171 Variable Manipulation
References
Jim Manico. "Input Validation with ESAPI - Very Important". 2008-08-15. < http://
manicode.blogspot.com/2008/08/input-validation-with-esapi.html >.
"OWASP Enterprise Security API (ESAPI) Project". < http://www.owasp.org/index.php/ESAPI >.
Joel Scambray, Mike Shema and Caleb Sima. "Hacking Exposed Web Applications, Second
Edition". Input Validation Attacks. McGraw-Hill. 2006-06-05.
Jeremiah Grossman. "Input validation or output filtering, which is better?". 2007-01-30. < http://
jeremiahgrossman.blogspot.com/2007/01/input-validation-or-output-filtering.html >.
Kevin Beaver. "The importance of input validation". 2006-09-06. < http://
searchsoftwarequality.techtarget.com/tip/0,289483,sid92_gci1214373,00.html >.
[REF-11] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 10, "All Input Is Evil!" Page
341. 2nd Edition. Microsoft. 2002.
Maintenance Notes
Input validation - whether missing or incorrect - is such an essential and widespread part of secure
development that it is implicit in many different weaknesses. Traditionally, problems such as
buffer overflows and XSS have been classified as input validation problems by many security
professionals. However, input validation is not necessarily the only protection mechanism available
for avoiding such problems, and in some cases it is not even sufficient. The CWE team has begun
capturing these subtleties in chains within the Research Concepts view (CWE-1000), but more
work is needed.

CWE-21: Pathname Traversal and Equivalence Errors


Category ID: 21 (Category) Status: Incomplete
Description
Summary
Weaknesses in this category can be used to access files outside of a restricted directory (path
traversal) or to perform operations on files that would otherwise be restricted (path equivalence).

23
CWE Version 1.8.1
CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

Extended Description
Files, directories, and folders are so central to information technology that many different
weaknesses and variants have been discovered. The manipulations generally involve special
characters or sequences in pathnames, or the use of alternate references or channels.
Applicable Platforms
Languages
• All
Potential Mitigations
Assume all input is malicious. Use an appropriate combination of black lists and white lists to
ensure only valid and expected input is processed by the system.
Relationships
Nature Type ID Name Page
ChildOf 20 Improper Input Validation 699 15
ParentOf 22 Improper Limitation of a Pathname to a Restricted Directory 699 24
('Path Traversal')
ParentOf 41 Improper Resolution of Path Equivalence 699 51
ParentOf 59 Improper Link Resolution Before File Access ('Link Following') 699 63
CWE-22: Improper Limitation of a Pathname
to a Restricted Directory ('Path Traversal')

ParentOf 66 Improper Handling of File Names that Identify Virtual 699 69


Resources
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Pathname Traversal and Equivalence Errors
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
64 Using Slashes and URL Encoding Combined to Bypass Validation Logic
72 URL Encoding
78 Using Escaped Slashes in Alternate Encoding
79 Using Slashes in Alternate Encoding
80 Using UTF-8 Encoding to Bypass Validation Logic

CWE-22: Improper Limitation of a Pathname to a Restricted


Directory ('Path Traversal')
Weakness ID: 22 (Weakness Class) Status: Draft
Description
Summary
The software uses external input to construct a pathname that is intended to identify a file or
directory that is located underneath a restricted parent directory, but the software does not
properly sanitize special elements that can resolve to a location that is outside of the restricted
directory.
Extended Description
Many file operations are intended to take place within a restricted directory. By using special
elements such as ".." and "/" separators, attackers can escape outside of the restricted location
to access files or directories that are elsewhere on the system. One of the most common special
elements is the "../" sequence, which in most modern operating systems is interpreted as the
parent directory of the current location. This is referred to as relative path traversal. Path traversal
also covers the use of absolute pathnames such as "/usr/local/bin", which may also be useful in
accessing unexpected files. This is referred to as absolute path traversal.
In many programming languages, the injection of a null byte (the 0 or NUL) may allow an attacker
to truncate a generated filename to widen the scope of attack. For example, the software may add
".txt" to any pathname, thus limiting the attacker to text files, but a null injection may effectively
remove this restriction.
Alternate Terms

24
CWE Version 1.8.1
CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

Directory traversal
Path traversal
"Path traversal" is preferred over "directory traversal," but both terms are attack-focused.
Terminology Notes
Like other weaknesses, terminology is often based on the types of manipulations used, instead of
the underlying weaknesses. Some people use "directory traversal" only to refer to the injection of
".." and equivalent sequences whose specific meaning is to traverse directories.
Other variants like "absolute pathname" and "drive letter" have the *effect* of directory traversal,
but some people may not call it such, since it doesn't involve ".." or equivalent.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• Language-independent
Common Consequences
Integrity

CWE-22: Improper Limitation of a Pathname


to a Restricted Directory ('Path Traversal')
Execute unauthorized code or commands
The attacker may be able to create or overwrite critical files that are used to execute code, such
as programs or libraries.
Integrity
Read / write files or directories
The attacker may be able to overwrite or create critical files, such as programs, libraries, or
important data. If the targeted file is used for a security mechanism, then the attacker may be able
to bypass that mechanism. For example, appending a new account at the end of a password file
may allow an attacker to bypass authentication.
Confidentiality
Read / write files or directories
The attacker may be able read the contents of unexpected files and expose sensitive data. If
the targeted file is used for a security mechanism, then the attacker may be able to bypass that
mechanism. For example, by reading a password file, the attacker could conduct brute force
password guessing attacks in order to break into an account on the system.
Availability
The attacker may be able to overwrite, delete, or corrupt unexpected critical files such as
programs, libraries, or important data. This may prevent the software from working at all and in
the case of a protection mechanisms such as authentication, it has the potential to lockout every
user of the software.
Likelihood of Exploit
High to Very High
Detection Methods
Automated Static Analysis
High
Automated techniques can find areas where path traversal weaknesses exist. However, tuning
or customization may be required to filter path-traversal problems that are only exploitable by
the software's administrator - or other privileged users - and thus potentially valid behavior or, at
worst, a bug instead of a vulnerability.
Manual Static Analysis
High
Manual white box techniques may be able to provide sufficient code coverage and reduction of
false positives if all file access operations can be assessed within limited time constraints.
Demonstrative Examples
Example 1:

25
CWE Version 1.8.1
CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

The following code could be for a social networking application in which each user's profile
information is stored in a separate file. All files are stored in a single directory.
Perl Example: Bad Code

my $dataPath = "/users/cwe/profiles";
my $username = param("user");
my $profilePath = $dataPath . "/" . $username;
open(my $fh, "<$profilePath") || ExitError("profile read error: $profilePath");
print "<ul>\n";
while (<$fh>) {
print "<li>$_</li>\n";
}
print "</ul>\n";

While the programmer intends to access files such as "/users/cwe/profiles/alice" or "/users/cwe/


profiles/bob", there is no verification of the incoming user parameter. An attacker could provide a
string such as:
Attack

../../../etc/passwd

The program would generate a profile pathname like this:


CWE-22: Improper Limitation of a Pathname
to a Restricted Directory ('Path Traversal')

Result

/users/cwe/profiles/../../../etc/passwd

When the file is opened, the operating system resolves the "../" during path canonicalization and
actually accesses this file:
Result

/etc/passwd

As a result, the attacker could read the entire text of the password file.
Notice how this code also contains an error message information leak (CWE-209) if the user
parameter does not produce a file that exists: the full pathname is provided. Because of the lack
of output encoding of the file that is retrieved, there might also be a cross-site scripting problem
(CWE-79) if profile contains any HTML, but other code would need to be examined.
Example 2:
In the example below, the path to a dictionary file is read from a system property and used to
initialize a File object.
Java Example: Bad Code

String filename = System.getProperty("com.domain.application.dictionaryFile");


File dictionaryFile = new File(filename);

However, the path is not sanitized before creating the File object. This allows anyone who can
control the system property to determine what file is used. Ideally, the path should be resolved
relative to some kind of application or user home directory.
Example 3:
The following code takes untrusted input and uses a regular expression to filter "../" from the input.
It then appends this result to the /home/user/ directory and attempts to read the file in the final
resulting path.
Perl Example: Bad Code

my $Username = GetUntrustedInput();
$Username =~ s/\.\.\///;
my $filename = "/home/user/" . $Username;
ReadAndSendFile($filename);

Since the regular expression does not have the /g global match modifier, it only removes the first
instance of "../" it comes across. So an input value such as:
Attack

../../../etc/passwd

26
CWE Version 1.8.1
CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

will have the first "../" stripped, resulting in:


Result

../../etc/passwd

This value is then concatenated with the /home/user/ directory:


Result

/home/user/../../etc/passwd

which causes the /etc/passwd file to be retrieved once the operating system has resolved the ../
sequences in the pathname. This leads to relative path traversal (CWE-23).
Example 4:
The following code attempts to validate a given input path by checking it against a white list and
once validated delete the given file. In this specific case, the path is considered valid if it starts with
the string "/safe_dir/".
Java Example: Bad Code

String path = getInputPath();


if (path.startsWith("/safe_dir/"))

CWE-22: Improper Limitation of a Pathname


{

to a Restricted Directory ('Path Traversal')


File f = new File(path);
f.delete()
}

An attacker could provide an input such as this:


/safe_dir/../important.dat
The software assumes that the path is valid because it starts with the "/safe_path/" sequence, but
the "../" sequence will cause the program to delete the important.dat file in the parent directory
Example 5:
The following code demonstrates the unrestricted upload of a file with a Java servlet and a path
traversal vulnerability. The HTML code is the same as in the previous example with the action
attribute of the form sending the upload file request to the Java servlet instead of the PHP code.
HTML Example: Good Code

<form action="FileUploadServlet" method="post" enctype="multipart/form-data">


Choose a file to upload:
<input type="file" name="filename"/>
<br/>
<input type="submit" name="submit" value="Submit"/>
</form>

When submitted the Java servlet's doPost method will receive the request, extract the name of the
file from the Http request header, read the file contents from the request and output the file to the
local upload directory.
Java Example: Bad Code

public class FileUploadServlet extends HttpServlet {


...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String contentType = request.getContentType();
// the starting position of the boundary header
int ind = contentType.indexOf("boundary=");
String boundary = contentType.substring(ind+9);
String pLine = new String();
String uploadLocation = new String(UPLOAD_DIRECTORY_STRING); //Constant value
// verify that content type is multipart form data
if (contentType != null && contentType.indexOf("multipart/form-data") != -1) {
// extract the filename from the Http header
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
...
pLine = br.readLine();

27
CWE Version 1.8.1
CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

String filename = pLine.substring(pLine.lastIndexOf("\\"), pLine.lastIndexOf("\""));


...
// output the file to the local upload directory
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(uploadLocation+filename, true));
for (String line; (line=br.readLine())!=null; ) {
if (line.indexOf(boundary) == -1) {
bw.write(line);
bw.newLine();
bw.flush();
}
} //end of for loop
bw.close();
} catch (IOException ex) {...}
// output successful upload response HTML page
}
// output unsuccessful upload response HTML page
else
{...}
}
...
}
CWE-22: Improper Limitation of a Pathname
to a Restricted Directory ('Path Traversal')

This code does not check the filename that is provided in the header, so an attacker can use
"../" sequences to write to files outside of the intended directory. Depending on the executing
environment, the attacker may be able to specify arbitrary files to write to, leading to a wide variety
of consequences, from code execution, XSS (CWE-79), or system crash.
Also, this code does not perform a check on the type of the file being uploaded. This could allow
an attacker to upload any executable file or other file with malicious code (CWE-434).
Observed Examples
Reference Description
CVE-2008-5748 Chain: external control of values for user's desired language and theme enables path
traversal.
CVE-2009-0244 OBEX FTP service for a Bluetooth device allows listing of directories, and creation or
reading of files using ".." sequences..
CVE-2009-4013 Software package maintenance program allows overwriting arbitrary files using "../"
sequences.
CVE-2009-4053 FTP server allows creation of arbitrary directories using ".." in the MKD command.
CVE-2009-4194 FTP server allows deletion of arbitrary files using ".." in the DELE command.
CVE-2009-4449 Bulletin board allows attackers to determine the existence of files using the avatar.
CVE-2009-4581 PHP program allows arbitrary code execution using ".." in filenames that are fed to the
include() function.
CVE-2010-0012 Overwrite of files using a .. in a Torrent file.
CVE-2010-0013 Chat program allows overwriting files using a custom smiley request.
CVE-2010-0467 Newsletter module allows reading arbitrary files using "../" sequences.
Potential Mitigations

28
CWE Version 1.8.1
CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

Implementation
Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a
whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not
strictly conform to specifications, or transform it into something that does. Do not rely exclusively
on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). However, blacklists
can be useful for detecting potential attacks or determining which inputs are so malformed that
they should be rejected outright.
When performing input validation, consider all potentially relevant properties, including length,
type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency
across related fields, and conformance to business rules. As an example of business rule logic,
"boat" may be syntactically valid because it only contains alphanumeric characters, but it is not
valid if you are expecting colors such as "red" or "blue."
For filenames, use stringent whitelists that limit the character set to be used. If feasible, only
allow a single "." character in the filename to avoid weaknesses such as CWE-23, and exclude
directory separators such as "/" to avoid CWE-36. Use a whitelist of allowable file extensions,
which will help to avoid CWE-434.

CWE-22: Improper Limitation of a Pathname


Warning: if you attempt to cleanse your data, then do so that the end result is not in the form

to a Restricted Directory ('Path Traversal')


that can be dangerous. A sanitizing mechanism can remove characters such as '.' and ';' which
may be required for some exploits. An attacker can try to fool the sanitizing mechanism into
"cleaning" data into a dangerous form. Suppose the attacker injects a '.' inside a filename (e.g.
"sensi.tiveFile") and the sanitizing mechanism removes the character resulting in the valid
filename, "sensitiveFile". If the input data are now assumed to be safe, then the file may be
compromised. See CWE-182 (Collapse of Data Into Unsafe Value).
Implementation
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated (CWE-180). Make sure that your application does not decode the same
input twice. Such errors could be used to bypass whitelist schemes by introducing dangerous
inputs after they have been checked.
Use a built-in path canonicalization function (such as realpath() in C) that produces the canonical
version of the pathname, which effectively removes ".." sequences and symbolic links (CWE-23,
CWE-59). This includes:
realpath() in C
getCanonicalPath() in Java
GetFullPath() in ASP.NET
realpath() or abs_path() in Perl
realpath() in PHP
Implementation
Environment Hardening
Run your code using the least privileges possible. If possible, create isolated accounts with limited
privileges that are only used for a single task. That way, a successful attack will not immediately
give the attacker access to the rest of the software or its environment. For example, database
applications rarely need to run as the database administrator, especially in day-to-day operations.
Architecture and Design
When the set of filenames is limited or known, create a mapping from a set of fixed input
values (such as numeric IDs) to the actual filenames, and reject all other inputs. For example,
ID 1 could map to "inbox.txt" and ID 2 could map to "profile.txt". Features such as the ESAPI
AccessReferenceMap provide this capability.

29
CWE Version 1.8.1
CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

Architecture and Design


Operation
Environment Hardening
Run your code in a "jail" or similar sandbox environment that enforces strict boundaries between
the process and the operating system. This may effectively restrict all access to files within a
particular directory.
OS-level examples include the Unix chroot jail, AppArmor, and SELinux. In general,
managed code may provide some protection. For example, java.io.FilePermission in the Java
SecurityManager allows you to specify restrictions on file operations.
This may not be a feasible solution, and it only limits the impact to the operating system; the rest
of your application may still be subject to compromise.
Be careful to avoid CWE-243 and other weaknesses related to jails.
Other Notes
Incomplete diagnosis or reporting of vulnerabilities can make it difficult to know which variant is
affected. For example, a researcher might say that "..\" is vulnerable, but not test "../" which may
also be vulnerable.
Any combination of the items below can provide its own variant, e.g. "//../" is not listed
CWE-22: Improper Limitation of a Pathname

(CVE-2004-0325).
to a Restricted Directory ('Path Traversal')

Weakness Ordinalities
Primary (where the weakness exists independent of other weaknesses)
Resultant (where the weakness is typically related to the presence of some other weaknesses)
Relationships
Nature Type ID Name Page
ChildOf 21 Pathname Traversal and Equivalence Errors 699 23
ChildOf 632 Weaknesses that Affect Files or Directories 631 706
ChildOf 668 Exposure of Resource to Wrong Sphere 1000 753
ChildOf 706 Use of Incorrectly-Resolved Name or Reference 1000 811
ChildOf 715 OWASP Top Ten 2007 Category A4 - Insecure Direct Object 629 817
Reference
ChildOf 723 OWASP Top Ten 2004 Category A2 - Broken Access Control 711 821
ChildOf 743 CERT C Secure Coding Section 09 - Input Output (FIO) 734 836
ChildOf 802 2010 Top 25 - Risky Resource Management 800 903
CanFollow 20 Improper Input Validation 1000 15
ParentOf 23 Relative Path Traversal 699 31
1000
ParentOf 36 Absolute Path Traversal 699 47
1000
CanFollow 73 External Control of File Name or Path 1000 75
CanFollow 172 Encoding Error 1000 231
MemberOf 635 Weaknesses Used by NVD 635 708

Relationship Notes
Pathname equivalence can be regarded as a type of canonicalization error.
Some pathname equivalence issues are not directly related to directory traversal, rather are used
to bypass security-relevant checks for whether a file/directory can be accessed by the attacker
(e.g. a trailing "/" on a filename could bypass access rules that don't expect a trailing /, causing a
server to provide the file when it normally would not).
Research Gaps
Many variants of path traversal attacks are probably under-studied with respect to root cause.
CWE-790 and CWE-182 begin to cover part of this gap.
Affected Resources
• File/Directory
Relevant Properties
• Equivalence
30
CWE Version 1.8.1
CWE-23: Relative Path Traversal

Functional Areas
• File processing
Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Node ID Fit Mapped Node Name
PLOVER Path Traversal
OWASP Top Ten 2007 A4 CWE More Specific Insecure Direct Object Reference
OWASP Top Ten 2004 A2 CWE More Specific Broken Access Control
CERT C Secure Coding FIO02-C Canonicalize path names originating from
untrusted sources
WASC 33 Path Traversal
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
23 File System Function Injection, Content Based
64 Using Slashes and URL Encoding Combined to Bypass Validation Logic
76 Manipulating Input to File System Calls
78 Using Escaped Slashes in Alternate Encoding
79 Using Slashes in Alternate Encoding
139 Relative Path Traversal

CWE-23: Relative Path Traversal


References
[REF-11] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 11, "Directory Traversal and
Using Parent Paths (..)" Page 370. 2nd Edition. Microsoft. 2002.
[REF-17] OWASP. "OWASP Enterprise Security API (ESAPI) Project". < http://www.owasp.org/
index.php/ESAPI >.
OWASP. "Testing for Path Traversal (OWASP-AZ-001)". < http://www.owasp.org/index.php/
Testing_for_Path_Traversal_(OWASP-AZ-001) >.

CWE-23: Relative Path Traversal


Weakness ID: 23 (Weakness Base) Status: Draft
Description
Summary
The software uses external input to construct a pathname that should be within a restricted
directory, but it does not properly sanitize sequences such as ".." that can resolve to a location
that is outside of that directory.
Extended Description
This allows attackers to traverse the file system to access files or directories that are outside of
the restricted directory.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Demonstrative Examples
Example 1:
The following URLs are vulnerable to this attack:
Bad Code

http://example.com.br/get-files.jsp?file=report.pdf
http://example.com.br/get-page.php?home=aaa.html
http://example.com.br/some-page.asp?page=index.html

A simple way to execute this attack is like this:


Attack

http://example.com.br/get-files?file=../../../../somedir/somefile

31
CWE Version 1.8.1
CWE-23: Relative Path Traversal

http://example.com.br/../../../../etc/shadow
http://example.com.br/get-files?file=../../../../etc/passwd

Example 2:
The following code demonstrates the unrestricted upload of a file with a Java servlet and a path
traversal vulnerability. The HTML code is the same as in the previous example with the action
attribute of the form sending the upload file request to the Java servlet instead of the PHP code.
HTML Example: Good Code

<form action="FileUploadServlet" method="post" enctype="multipart/form-data">


Choose a file to upload:
<input type="file" name="filename"/>
<br/>
<input type="submit" name="submit" value="Submit"/>
</form>

When submitted the Java servlet's doPost method will receive the request, extract the name of the
file from the Http request header, read the file contents from the request and output the file to the
local upload directory.
Java Example: Bad Code

public class FileUploadServlet extends HttpServlet {


...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
CWE-23: Relative Path Traversal

IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String contentType = request.getContentType();
// the starting position of the boundary header
int ind = contentType.indexOf("boundary=");
String boundary = contentType.substring(ind+9);
String pLine = new String();
String uploadLocation = new String(UPLOAD_DIRECTORY_STRING); //Constant value
// verify that content type is multipart form data
if (contentType != null && contentType.indexOf("multipart/form-data") != -1) {
// extract the filename from the Http header
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
...
pLine = br.readLine();
String filename = pLine.substring(pLine.lastIndexOf("\\"), pLine.lastIndexOf("\""));
...
// output the file to the local upload directory
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(uploadLocation+filename, true));
for (String line; (line=br.readLine())!=null; ) {
if (line.indexOf(boundary) == -1) {
bw.write(line);
bw.newLine();
bw.flush();
}
} //end of for loop
bw.close();
} catch (IOException ex) {...}
// output successful upload response HTML page
}
// output unsuccessful upload response HTML page
else
{...}
}
...
}

As with the previous example this code does not perform a check on the type of the file being
uploaded. This could allow an attacker to upload any executable file or other file with malicious
code.
Additionally, the creation of the BufferedWriter object is subject to relative path traversal (CWE-22,
CWE-23). Depending on the executing environment, the attacker may be able to specify arbitrary
32
CWE Version 1.8.1
CWE-23: Relative Path Traversal

files to write to, leading to a wide variety of consequences, from code execution, XSS (CWE-79), or
system crash.
Potential Mitigations
Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file
system. Use an appropriate combination of black lists and white lists to ensure only valid and
expected input is processed by the system. Warning: if you attempt to cleanse your data, then do
so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove
characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool
the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects
a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character
resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then
the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).
Architecture and Design
Assume all input is malicious. Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8).
Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.

CWE-23: Relative Path Traversal


Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Relationships
Nature Type ID Name Page
ChildOf 22 Improper Limitation of a Pathname to a Restricted Directory 699 24
('Path Traversal') 1000
ParentOf 24 Path Traversal: '../filedir' 699 34
1000
ParentOf 25 Path Traversal: '/../filedir' 699 35
1000
ParentOf 26 Path Traversal: '/dir/../filename' 699 35
1000
ParentOf 27 Path Traversal: 'dir/../../filename' 699 36
1000
ParentOf 28 Path Traversal: '..\filedir' 699 37
1000
ParentOf 29 Path Traversal: '\..\filename' 699 39
1000
ParentOf 30 Path Traversal: '\dir\..\filename' 699 40
1000
ParentOf 31 Path Traversal: 'dir\..\..\filename' 699 41
1000
ParentOf 32 Path Traversal: '...' (Triple Dot) 699 42
1000
ParentOf 33 Path Traversal: '....' (Multiple Dot) 699 43
1000
ParentOf 34 Path Traversal: '....//' 699 44
1000
ParentOf 35 Path Traversal: '.../...//' 699 45
1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Relative Path Traversal

33
CWE Version 1.8.1
CWE-24: Path Traversal: '../filedir'

Related Attack Patterns


CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
23 File System Function Injection, Content Based
76 Manipulating Input to File System Calls
References
OWASP. "OWASP Attack listing". < http://www.owasp.org/index.php/Relative_Path_Traversal >.

CWE-24: Path Traversal: '../filedir'


Weakness ID: 24 (Weakness Variant) Status: Incomplete
Description
Summary
The software uses external input to construct a pathname that should be within a restricted
directory, but it does not properly sanitize "../" sequences that can resolve to a location that is
outside of that directory.
Extended Description
This allows attackers to traverse the file system to access files or directories that are outside of
the restricted directory.
The "../" manipulation is the canonical manipulation for operating systems that use "/" as directory
separators, such as UNIX- and Linux-based systems. In some cases, it is useful for bypassing
CWE-24: Path Traversal: '../filedir'

protection schemes in environments for which "/" is supported but not the primary separator, such
as Windows, which uses "\" but can also accept "/".
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• All
Potential Mitigations
Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file
system. Use an appropriate combination of black lists and white lists to ensure only valid and
expected input is processed by the system. Warning: if you attempt to cleanse your data, then do
so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove
characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool
the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects
a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character
resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then
the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).
Architecture and Design
Assume all input is malicious. Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8).
Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Relationships
Nature Type ID Name Page
ChildOf 23 Relative Path Traversal 699 31
1000
34
CWE Version 1.8.1
CWE-25: Path Traversal: '/../filedir'

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER '../filedir

CWE-25: Path Traversal: '/../filedir'


Weakness ID: 25 (Weakness Variant) Status: Incomplete
Description
Summary
The software uses external input to construct a pathname that should be within a restricted
directory, but it does not properly sanitize "/../" sequences that can resolve to a location that is
outside of that directory.
Extended Description
This allows attackers to traverse the file system to access files or directories that are outside of
the restricted directory.
Sometimes a program checks for "../" at the beginning of the input, so a "/../" can bypass that
check.
Time of Introduction
• Implementation
Applicable Platforms

CWE-25: Path Traversal: '/../filedir'


Languages
• All
Potential Mitigations
Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file
system. Use an appropriate combination of black lists and white lists to ensure only valid and
expected input is processed by the system. Warning: if you attempt to cleanse your data, then do
so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove
characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool
the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects
a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character
resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then
the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).
Architecture and Design
Assume all input is malicious. Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8).
Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Relationships
Nature Type ID Name Page
ChildOf 23 Relative Path Traversal 699 31
1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER '/../filedir

CWE-26: Path Traversal: '/dir/../filename'


35
CWE Version 1.8.1
CWE-27: Path Traversal: 'dir/../../filename'

Weakness ID: 26 (Weakness Variant) Status: Draft


Description
Summary
The software uses external input to construct a pathname that should be within a restricted
directory, but it does not properly sanitize "/dir/../filename" sequences that can resolve to a
location that is outside of that directory.
Extended Description
This allows attackers to traverse the file system to access files or directories that are outside of
the restricted directory.
The '/dir/../filename' manipulation is useful for bypassing some path traversal protection schemes.
Sometimes a program only checks for "../" at the beginning of the input, so a "/../" can bypass that
check.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
CWE-27: Path Traversal: 'dir/../../filename'

Technology Classes
• Web-Server (Often)
Potential Mitigations
Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file
system. Use an appropriate combination of black lists and white lists to ensure only valid and
expected input is processed by the system. Warning: if you attempt to cleanse your data, then do
so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove
characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool
the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects
a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character
resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then
the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).
Architecture and Design
Assume all input is malicious. Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8).
Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Relationships
Nature Type ID Name Page
ChildOf 23 Relative Path Traversal 699 31
1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER '/directory/../filename

CWE-27: Path Traversal: 'dir/../../filename'


Weakness ID: 27 (Weakness Variant) Status: Draft
Description

36
CWE Version 1.8.1
CWE-28: Path Traversal: '..\filedir'

Summary
The software uses external input to construct a pathname that should be within a restricted
directory, but it does not properly sanitize multiple internal "../" sequences that can resolve to a
location that is outside of that directory.
Extended Description
This allows attackers to traverse the file system to access files or directories that are outside of
the restricted directory.
The 'directory/../../filename' manipulation is useful for bypassing some path traversal protection
schemes. Sometimes a program only removes one "../" sequence, so multiple "../" can bypass
that check. Alternately, this manipulation could be used to bypass a check for "../" at the
beginning of the pathname, moving up more than one directory level.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-2002-0298

CWE-28: Path Traversal: '..\filedir'


Potential Mitigations
Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file
system. Use an appropriate combination of black lists and white lists to ensure only valid and
expected input is processed by the system. Warning: if you attempt to cleanse your data, then do
so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove
characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool
the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects
a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character
resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then
the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).
Architecture and Design
Assume all input is malicious. Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8).
Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Relationships
Nature Type ID Name Page
ChildOf 23 Relative Path Traversal 699 31
1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER 'directory/../../filename

CWE-28: Path Traversal: '..\filedir'


Weakness ID: 28 (Weakness Variant) Status: Incomplete
Description
37
CWE Version 1.8.1
CWE-28: Path Traversal: '..\filedir'

Summary
The software uses external input to construct a pathname that should be within a restricted
directory, but it does not properly sanitize "..\" sequences that can resolve to a location that is
outside of that directory.
Extended Description
This allows attackers to traverse the file system to access files or directories that are outside of
the restricted directory.
The '..\' manipulation is the canonical manipulation for operating systems that use "\" as directory
separators, such as Windows. However, it is also useful for bypassing path traversal protection
schemes that only assume that the "/" separator is valid.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Operating Systems
• Windows
Observed Examples
Reference Description
CWE-28: Path Traversal: '..\filedir'

CVE-2002-0661 "\" not in blacklist for web server, allowing path traversal attacks when the server is run in
Windows and other OSes.
CVE-2002-0946 Arbitrary files may be read files via ..\ (dot dot) sequences in an HTTP request.
CVE-2002-1042
CVE-2002-1178
CVE-2002-1209
Potential Mitigations
Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file
system. Use an appropriate combination of black lists and white lists to ensure only valid and
expected input is processed by the system. Warning: if you attempt to cleanse your data, then do
so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove
characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool
the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects
a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character
resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then
the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).
Architecture and Design
Assume all input is malicious. Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8).
Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Relationships
Nature Type ID Name Page
ChildOf 23 Relative Path Traversal 699 31
1000
Taxonomy Mappings

38
CWE Version 1.8.1
CWE-29: Path Traversal: '\..\filename'

Mapped Taxonomy Name Mapped Node Name


PLOVER '..\filename' ('dot dot backslash')

CWE-29: Path Traversal: '\..\filename'


Weakness ID: 29 (Weakness Variant) Status: Incomplete
Description
Summary
The software uses external input to construct a pathname that should be within a restricted
directory, but it does not properly sanitize '\..\filename'" (leading backslash dot dot) sequences
that can resolve to a location that is outside of that directory.
Extended Description
This allows attackers to traverse the file system to access files or directories that are outside of
the restricted directory.
This is similar to CWE-25, except using "\" instead of "/". Sometimes a program checks for "..\"
at the beginning of the input, so a "\..\" can bypass that check. It is also useful for bypassing path
traversal protection schemes that only assume that the "/" separator is valid.
Time of Introduction
• Implementation

CWE-29: Path Traversal: '\..\filename'


Applicable Platforms
Languages
• All
Operating Systems
• Windows
Observed Examples
Reference Description
CVE-2002-1987 Protection mechanism checks for "/.." but doesn't account for Windows-specific "\.."
allowing read of arbitrary files.
CVE-2005-2142
Potential Mitigations
Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file
system. Use an appropriate combination of black lists and white lists to ensure only valid and
expected input is processed by the system. Warning: if you attempt to cleanse your data, then do
so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove
characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool
the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects
a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character
resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then
the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).
Architecture and Design
Assume all input is malicious. Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8).
Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Relationships

39
CWE Version 1.8.1
CWE-30: Path Traversal: '\dir\..\filename'

Nature Type ID Name Page


ChildOf 23 Relative Path Traversal 699 31
1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER '\..\filename' ('leading dot dot backslash')

CWE-30: Path Traversal: '\dir\..\filename'


Weakness ID: 30 (Weakness Variant) Status: Draft
Description
Summary
The software uses external input to construct a pathname that should be within a restricted
directory, but it does not properly sanitize '\dir\..\filename' (leading backslash dot dot) sequences
that can resolve to a location that is outside of that directory.
Extended Description
This allows attackers to traverse the file system to access files or directories that are outside of
the restricted directory.
CWE-30: Path Traversal: '\dir\..\filename'

This is similar to CWE-26, except using "\" instead of "/". The '\dir\..\filename' manipulation is
useful for bypassing some path traversal protection schemes. Sometimes a program only checks
for "..\" at the beginning of the input, so a "\..\" can bypass that check.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Operating Systems
• Windows
Observed Examples
Reference Description
CVE-2002-1987 Protection mechanism checks for "/.." but doesn't account for Windows-specific "\.."
allowing read of arbitrary files.
Potential Mitigations
Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file
system. Use an appropriate combination of black lists and white lists to ensure only valid and
expected input is processed by the system. Warning: if you attempt to cleanse your data, then do
so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove
characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool
the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects
a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character
resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then
the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).
Architecture and Design
Assume all input is malicious. Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8).
Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.

40
CWE Version 1.8.1
CWE-31: Path Traversal: 'dir\..\..\filename'

Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Relationships
Nature Type ID Name Page
ChildOf 23 Relative Path Traversal 699 31
1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER 7 - '\directory\..\filename

CWE-31: Path Traversal: 'dir\..\..\filename'


Weakness ID: 31 (Weakness Variant) Status: Draft
Description
Summary
The software uses external input to construct a pathname that should be within a restricted

CWE-31: Path Traversal: 'dir\..\..\filename'


directory, but it does not properly sanitize 'dir\..\..\filename' (multiple internal backslash dot dot)
sequences that can resolve to a location that is outside of that directory.
Extended Description
This allows attackers to traverse the file system to access files or directories that are outside of
the restricted directory.
The 'dir\..\..\filename' manipulation is useful for bypassing some path traversal protection
schemes. Sometimes a program only removes one "..\" sequence, so multiple "..\" can bypass
that check. Alternately, this manipulation could be used to bypass a check for "..\" at the
beginning of the pathname, moving up more than one directory level.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Operating Systems
• Windows
Observed Examples
Reference Description
CVE-2002-0160
Potential Mitigations
Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file
system. Use an appropriate combination of black lists and white lists to ensure only valid and
expected input is processed by the system. Warning: if you attempt to cleanse your data, then do
so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove
characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool
the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects
a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character
resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then
the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).
Architecture and Design
Assume all input is malicious. Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8).

41
CWE Version 1.8.1
CWE-32: Path Traversal: '...' (Triple Dot)

Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Relationships
Nature Type ID Name Page
ChildOf 23 Relative Path Traversal 699 31
1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER 8 - 'directory\..\..\filename

CWE-32: Path Traversal: '...' (Triple Dot)


Weakness ID: 32 (Weakness Variant) Status: Incomplete
Description
CWE-32: Path Traversal: '...' (Triple Dot)

Summary
The software uses external input to construct a pathname that should be within a restricted
directory, but it does not properly sanitize '...' (triple dot) sequences that can resolve to a location
that is outside of that directory.
Extended Description
This allows attackers to traverse the file system to access files or directories that are outside of
the restricted directory.
The '...' manipulation is useful for bypassing some path traversal protection schemes. On some
Windows systems, it is equivalent to "..\.." and might bypass checks that assume only two dots
are valid. Insufficient filtering, such as removal of "./" sequences, can ultimately produce valid ".."
sequences due to a collapse into unsafe value (CWE-182).
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-2001-0467 "\..." in web server
CVE-2001-0480 read of arbitrary files and directories using GET or CD with "..." in Windows-based FTP
server.
CVE-2001-0615 "..." or "...." in chat server
CVE-2001-0963 "..." in cd command in FTP server
CVE-2001-1131 "..." in cd command in FTP server
CVE-2001-1193 "..." in cd command in FTP server
CVE-2002-0288 read files using "." and Unicode-encoded "/" or "\" characters in the URL.
CVE-2003-0313 Directory listing of web server using "..."
CVE-2005-1658 Triple dot
Potential Mitigations

42
CWE Version 1.8.1
CWE-33: Path Traversal: '....' (Multiple Dot)

Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file
system. Use an appropriate combination of black lists and white lists to ensure only valid and
expected input is processed by the system. Warning: if you attempt to cleanse your data, then do
so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove
characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool
the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects
a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character
resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then
the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).
Architecture and Design
Assume all input is malicious. Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8).
Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.

CWE-33: Path Traversal: '....' (Multiple Dot)


Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Relationships
Nature Type ID Name Page
ChildOf 23 Relative Path Traversal 699 31
1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER '...' (triple dot)
Maintenance Notes
This manipulation-focused entry is currently hiding two distinct weaknesses, so it might need to be
split. The manipulation is effective in two different contexts: (1) it is equivalent to "..\.." on Windows,
or (2) it can take advantage of insufficient filtering, e.g. if the programmer does a single-pass
removal of "./" in a string (collapse of data into unsafe value)

CWE-33: Path Traversal: '....' (Multiple Dot)


Weakness ID: 33 (Weakness Variant) Status: Incomplete
Description
Summary
The software uses external input to construct a pathname that should be within a restricted
directory, but it does not properly sanitize '....' (multiple dot) sequences that can resolve to a
location that is outside of that directory.
Extended Description
This allows attackers to traverse the file system to access files or directories that are outside of
the restricted directory.
The '....' manipulation is useful for bypassing some path traversal protection schemes. On some
Windows systems, it is equivalent to "..\..\.." and might bypass checks that assume only two dots
are valid. Insufficient filtering, such as removal of "./" sequences, can ultimately produce valid ".."
sequences due to a collapse into unsafe value (CWE-182).
Time of Introduction
• Implementation
Applicable Platforms
Languages

43
CWE Version 1.8.1
CWE-34: Path Traversal: '....//'

• All
Observed Examples
Reference Description
CVE-1999-1082 read files via "......" in web server (doubled triple dot?)
CVE-2000-0240 read files via "/........../" in URL
CVE-2000-0773 read files via "...." in web server
CVE-2001-0491 multiple attacks using "..", "...", and "...." in different commands
CVE-2001-0615 "..." or "...." in chat server
CVE-2004-2121 read files via "......" in web server (doubled triple dot?)
Potential Mitigations
Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file
system. Use an appropriate combination of black lists and white lists to ensure only valid and
expected input is processed by the system. Warning: if you attempt to cleanse your data, then do
so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove
characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool
the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects
a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character
resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then
the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).
Architecture and Design
Assume all input is malicious. Use a standard input validation mechanism to validate all input for
CWE-34: Path Traversal: '....//'

length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8).
Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Relationships
Nature Type ID Name Page
ChildOf 23 Relative Path Traversal 699 31
1000
CanFollow 182 Collapse of Data Into Unsafe Value 1000 241

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER '....' (multiple dot)
Maintenance Notes
Like the triple-dot CWE-32, this manipulation probably hides multiple weaknesses that should be
made more explicit.

CWE-34: Path Traversal: '....//'


Weakness ID: 34 (Weakness Variant) Status: Incomplete
Description
Summary
The software uses external input to construct a pathname that should be within a restricted
directory, but it does not properly sanitize '....//' (doubled dot dot slash) sequences that can
resolve to a location that is outside of that directory.
Extended Description

44
CWE Version 1.8.1
CWE-35: Path Traversal: '.../...//'

This allows attackers to traverse the file system to access files or directories that are outside of
the restricted directory.
The '....//' manipulation is useful for bypassing some path traversal protection schemes. If "../"
is filtered in a sequential fashion, as done by some regular expression engines, then "....//" can
collapse into the "../" unsafe value (CWE-182). It could also be useful when ".." is removed, if the
operating system treats "//" and "/" as equivalent.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Description
Merak Mail Server with Icewarp, Sep. 10, 2004
Potential Mitigations
Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file
system. Use an appropriate combination of black lists and white lists to ensure only valid and
expected input is processed by the system. Warning: if you attempt to cleanse your data, then do
so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove
characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool

CWE-35: Path Traversal: '.../...//'


the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects
a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character
resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then
the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).
Architecture and Design
Assume all input is malicious. Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8).
Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Relationships
Nature Type ID Name Page
ChildOf 23 Relative Path Traversal 699 31
1000
ChildOf 182 Collapse of Data Into Unsafe Value 1000 241
CanFollow 182 Collapse of Data Into Unsafe Value 1000 241

Relationship Notes
This could occur due to a cleansing error that removes a single "../" from "....//"
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER '....//' (doubled dot dot slash)

CWE-35: Path Traversal: '.../...//'


Weakness ID: 35 (Weakness Variant) Status: Incomplete
Description
Summary
45
CWE Version 1.8.1
CWE-35: Path Traversal: '.../...//'

The software uses external input to construct a pathname that should be within a restricted
directory, but it does not properly sanitize '.../...//' (doubled triple dot slash) sequences that can
resolve to a location that is outside of that directory.
Extended Description
This allows attackers to traverse the file system to access files or directories that are outside of
the restricted directory.
The '.../...//' manipulation is useful for bypassing some path traversal protection schemes. If "../"
is filtered in a sequential fashion, as done by some regular expression engines, then ".../...//" can
collapse into the "../" unsafe value (CWE-182). Removing the first "../" yields "....//"; the second
removal yields "../". Depending on the algorithm, the software could be susceptible to CWE-34 but
not CWE-35, or vice versa.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-2005-0202 ".../....///" bypasses regexp's that remove "./" and "../"
CVE-2005-2169 chain: ".../...//" bypasses protection mechanism using regexp's that remove "../" resulting in
CWE-35: Path Traversal: '.../...//'

collapse into an unsafe value "../" (CWE-182) and resultant path traversal.
Potential Mitigations
Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file
system. Use an appropriate combination of black lists and white lists to ensure only valid and
expected input is processed by the system. Warning: if you attempt to cleanse your data, then do
so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove
characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool
the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects
a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character
resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then
the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).
Architecture and Design
Assume all input is malicious. Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8).
Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Relationships
Nature Type ID Name Page
ChildOf 23 Relative Path Traversal 699 31
1000
ChildOf 182 Collapse of Data Into Unsafe Value 1000 241
CanFollow 182 Collapse of Data Into Unsafe Value 1000 241

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER '.../...//'

46
CWE Version 1.8.1
CWE-36: Absolute Path Traversal

CWE-36: Absolute Path Traversal


Weakness ID: 36 (Weakness Base) Status: Draft
Description
Summary
The software uses external input to construct a pathname that should be within a restricted
directory, but it does not properly sanitize absolute path sequences such as "/abs/path" that can
resolve to a location that is outside of that directory.
Extended Description
This allows attackers to traverse the file system to access files or directories that are outside of
the restricted directory.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• All
Demonstrative Examples
In the example below, the path to a dictionary file is read from a system property and used to
initialize a File object.

CWE-36: Absolute Path Traversal


Java Example: Bad Code

String filename = System.getProperty("com.domain.application.dictionaryFile");


File dictionaryFile = new File(filename);

However, the path is not sanitized before creating the File object. This allows anyone who can
control the system property to determine what file is used. Ideally, the path should be resolved
relative to some kind of application or user home directory.
Potential Mitigations
see "Path Traversal" (CWE-22)
Relationships
Nature Type ID Name Page
ChildOf 22 Improper Limitation of a Pathname to a Restricted Directory 699 24
('Path Traversal') 1000
ParentOf 37 Path Traversal: '/absolute/pathname/here' 699 47
1000
ParentOf 38 Path Traversal: '\absolute\pathname\here' 699 48
1000
ParentOf 39 Path Traversal: 'C:dirname' 699 49
1000
ParentOf 40 Path Traversal: '\\UNC\share\name\' (Windows UNC Share) 699 50
1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Absolute Path Traversal

CWE-37: Path Traversal: '/absolute/pathname/here'


Weakness ID: 37 (Weakness Variant) Status: Draft
Description
Summary
A software system that accepts input in the form of a slash absolute path ('/absolute/pathname/
here') without appropriate validation can allow an attacker to traverse the file system to
unintended locations or access arbitrary files.
Time of Introduction
• Implementation
47
CWE Version 1.8.1
CWE-38: Path Traversal: '\absolute\pathname\here'

Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-2000-0614 Arbitrary files may be overwritten via compressed attachments that specify absolute path
names for the decompressed output.
CVE-2001-1269 ZIP file extractor allows full path
CVE-2002-1345 Multiple FTP clients write arbitrary files via absolute paths in server responses
CVE-2002-1818 Path traversal using absolute pathname
CVE-2002-1913 Path traversal using absolute pathname
CVE-2005-2147 Path traversal using absolute pathname
Potential Mitigations
Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file
system. Use an appropriate combination of black lists and white lists to ensure only valid and
expected input is processed by the system. Warning: if you attempt to cleanse your data, then do
CWE-38: Path Traversal: '\absolute\pathname\here'

so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove
characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool
the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects
a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character
resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then
the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).
Architecture and Design
Assume all input is malicious. Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8).
Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Relationships
Nature Type ID Name Page
ChildOf 36 Absolute Path Traversal 699 47
1000
ChildOf 160 Improper Neutralization of Leading Special Elements 1000 218
ChildOf 743 CERT C Secure Coding Section 09 - Input Output (FIO) 734 836

Taxonomy Mappings
Mapped Taxonomy Name Node ID Mapped Node Name
PLOVER /absolute/pathname/here
CERT C Secure Coding FIO05-C Identify files using multiple file attributes

CWE-38: Path Traversal: '\absolute\pathname\here'


Weakness ID: 38 (Weakness Variant) Status: Draft
Description
Summary
A software system that accepts input in the form of a backslash absolute path ('\absolute
\pathname\here') without appropriate validation can allow an attacker to traverse the file system to
unintended locations or access arbitrary files.
Time of Introduction
48
CWE Version 1.8.1
CWE-39: Path Traversal: 'C:dirname'

• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-1999-1263
CVE-2002-1525
CVE-2003-0753
Potential Mitigations
Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file
system. Use an appropriate combination of black lists and white lists to ensure only valid and
expected input is processed by the system. Warning: if you attempt to cleanse your data, then do
so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove
characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool
the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects
a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character
resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then
the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).

CWE-39: Path Traversal: 'C:dirname'


Architecture and Design
Assume all input is malicious. Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8).
Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Relationships
Nature Type ID Name Page
ChildOf 36 Absolute Path Traversal 699 47
1000
ChildOf 743 CERT C Secure Coding Section 09 - Input Output (FIO) 734 836

Taxonomy Mappings
Mapped Taxonomy Name Node ID Mapped Node Name
PLOVER \absolute\pathname\here ('backslash absolute path')
CERT C Secure Coding FIO05-C Identify files using multiple file attributes

CWE-39: Path Traversal: 'C:dirname'


Weakness ID: 39 (Weakness Variant) Status: Draft
Description
Summary
An attacker can inject a drive letter or Windows volume letter ('C:dirname') into a software system
to potentially redirect access to an unintended location or arbitrary file.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All

49
CWE Version 1.8.1
CWE-40: Path Traversal: '\\UNC\share\name\' (Windows UNC Share)

Observed Examples
Reference Description
CVE-2001-0038
CVE-2001-0255
CVE-2001-0687
CVE-2001-0933
CVE-2002-0466
CVE-2002-1483
CVE-2004-2488 FTP server read/access arbitrary files using "C:\" filenames
Potential Mitigations
Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file
system. Use an appropriate combination of black lists and white lists to ensure only valid and
CWE-40: Path Traversal: '\\UNC\share\name\' (Windows UNC Share)

expected input is processed by the system. Warning: if you attempt to cleanse your data, then do
so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove
characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool
the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects
a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character
resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then
the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).
Architecture and Design
Assume all input is malicious. Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8).
Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Relationships
Nature Type ID Name Page
ChildOf 36 Absolute Path Traversal 699 47
1000
ChildOf 743 CERT C Secure Coding Section 09 - Input Output (FIO) 734 836

Taxonomy Mappings
Mapped Taxonomy Name Node ID Mapped Node Name
PLOVER 'C:dirname' or C: (Windows volume or 'drive letter')
CERT C Secure Coding FIO05-C Identify files using multiple file attributes

CWE-40: Path Traversal: '\\UNC\share\name\' (Windows


UNC Share)
Weakness ID: 40 (Weakness Variant) Status: Draft
Description
Summary
An attacker can inject a Windows UNC share ('\\UNC\share\name') into a software system to
potentially redirect access to an unintended location or arbitrary file.
Time of Introduction
• Implementation
Applicable Platforms
Languages

50
CWE Version 1.8.1
CWE-41: Improper Resolution of Path Equivalence

• All
Observed Examples
Reference Description
CVE-2001-0687
Potential Mitigations
Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file
system. Use an appropriate combination of black lists and white lists to ensure only valid and
expected input is processed by the system. Warning: if you attempt to cleanse your data, then do
so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove
characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool
the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects
a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character
resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then
the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).
Architecture and Design

CWE-41: Improper Resolution of Path Equivalence


Assume all input is malicious. Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8).
Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Relationships
Nature Type ID Name Page
ChildOf 36 Absolute Path Traversal 699 47
1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER '\\UNC\share\name\' (Windows UNC share)

CWE-41: Improper Resolution of Path Equivalence


Weakness ID: 41 (Weakness Base) Status: Incomplete
Description
Summary
The system or application is vulnerable to file system contents disclosure through path
equivalence. Path equivalence involves the use of special characters in file and directory names.
The associated manipulations are intended to generate multiple names for the same object.
Extended Description
Path equivalence is usually employed in order to circumvent access controls expressed using
an incomplete set of file name or file path representations. This is different from path traversal,
wherein the manipulations are performed to generate a name for a different object.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Potential Mitigations

51
CWE Version 1.8.1
CWE-41: Improper Resolution of Path Equivalence

Architecture and Design


Assume all input is malicious. Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the data to be displayed or stored. Use
an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not
appropriate should not be processed into HTTP headers.
Use and specify a strong output encoding (such as ISO 8859-1 or UTF 8).
Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There
are too many variants to encode a character; you're likely to miss some variants.
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated. Make sure that your application does not decode the same input twice.
Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they
have been checked.
Other Notes
Some of these manipulations could be effective in path traversal issues, too.
Relationships
CWE-41: Improper Resolution of Path Equivalence

Nature Type ID Name Page


ChildOf 21 Pathname Traversal and Equivalence Errors 699 23
ChildOf 632 Weaknesses that Affect Files or Directories 631 706
ChildOf 706 Use of Incorrectly-Resolved Name or Reference 1000 811
ChildOf 723 OWASP Top Ten 2004 Category A2 - Broken Access Control 711 821
ChildOf 743 CERT C Secure Coding Section 09 - Input Output (FIO) 734 836
CanFollow 20 Improper Input Validation 1000 15
ParentOf 42 Path Equivalence: 'filename.' (Trailing Dot) 699 53
1000
ParentOf 44 Path Equivalence: 'file.name' (Internal Dot) 699 54
1000
ParentOf 46 Path Equivalence: 'filename ' (Trailing Space) 699 55
1000
ParentOf 47 Path Equivalence: ' filename (Leading Space) 699 56
1000
ParentOf 48 Path Equivalence: 'file name' (Internal Whitespace) 699 56
1000
ParentOf 49 Path Equivalence: 'filename/' (Trailing Slash) 699 57
1000
ParentOf 50 Path Equivalence: '//multiple/leading/slash' 699 57
1000
ParentOf 51 Path Equivalence: '/multiple//internal/slash' 699 58
1000
ParentOf 52 Path Equivalence: '/multiple/trailing/slash//' 699 59
1000
ParentOf 53 Path Equivalence: '\multiple\\internal\backslash' 699 59
1000
ParentOf 54 Path Equivalence: 'filedir\' (Trailing Backslash) 699 60
1000
ParentOf 55 Path Equivalence: '/./' (Single Dot Directory) 699 60
1000
ParentOf 56 Path Equivalence: 'filedir*' (Wildcard) 699 61
1000
ParentOf 57 Path Equivalence: 'fakedir/../realdir/filename' 699 61
1000
ParentOf 58 Path Equivalence: Windows 8.3 Filename 699 62
1000
CanFollow 73 External Control of File Name or Path 1000 75
CanFollow 172 Encoding Error 1000 231

Affected Resources

52
CWE Version 1.8.1
CWE-42: Path Equivalence: 'filename.' (Trailing Dot)

• File/Directory
Taxonomy Mappings
Mapped Taxonomy Name Node ID Mapped Node Name
PLOVER Path Equivalence
CERT C Secure Coding FIO02-C Canonicalize path names originating from untrusted sources
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
3 Using Leading 'Ghost' Character Sequences to Bypass Input Filters
4 Using Alternative IP Address Encodings

CWE-42: Path Equivalence: 'filename.' (Trailing Dot)


Weakness ID: 42 (Weakness Variant) Status: Incomplete
Description
Summary
A software system that accepts path input in the form of trailing dot ('filedir.') without appropriate

CWE-42: Path Equivalence: 'filename.' (Trailing Dot)


validation can lead to ambiguous path resolution and allow an attacker to traverse the file system
to unintended locations or access arbitrary files.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-2000-1114 Source code disclosure using trailing dot
CVE-2000-1133 Bypass directory access restrictions using trailing dot in URL
CVE-2001-1386 Bypass check for ".lnk" extension using ".lnk."
CVE-2002-1986, Source code disclosure using trailing dot
CVE-2004-0061 Bypass directory access restrictions using trailing dot in URL
CVE-2004-2213 Source code disclosure using trailing dot
CVE-2005-3293 Source code disclosure using trailing dot
Potential Mitigations
see the vulnerability category "Path Equivalence"
Relationships
Nature Type ID Name Page
ChildOf 41 Improper Resolution of Path Equivalence 699 51
1000
ChildOf 162 Improper Neutralization of Trailing Special Elements 1000 220
ParentOf 43 Path Equivalence: 'filename....' (Multiple Trailing Dot) 699 53
1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Trailing Dot - 'filedir.'

CWE-43: Path Equivalence: 'filename....' (Multiple Trailing


Dot)
Weakness ID: 43 (Weakness Variant) Status: Incomplete
Description
Summary
A software system that accepts path input in the form of multiple trailing dot ('filedir....') without
appropriate validation can lead to ambiguous path resolution and allow an attacker to traverse the
file system to unintended locations or access arbitrary files.

53
CWE Version 1.8.1
CWE-44: Path Equivalence: 'file.name' (Internal Dot)

Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
BUGTRAQ:20040205
Apache + Resin Reveals JSP Source Code ...
CVE-2004-0281 Multiple trailing dot allows directory listing
Potential Mitigations
see the vulnerability category "Pathname Traversal and Equivalence Errors"
Relationships
Nature Type ID Name Page
ChildOf 42 Path Equivalence: 'filename.' (Trailing Dot) 699 53
1000
CWE-44: Path Equivalence: 'file.name' (Internal Dot)

ChildOf 163 Improper Neutralization of Multiple Trailing Special Elements 1000 220

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Multiple Trailing Dot - 'filedir....'

CWE-44: Path Equivalence: 'file.name' (Internal Dot)


Weakness ID: 44 (Weakness Variant) Status: Incomplete
Description
Summary
A software system that accepts path input in the form of internal dot ('file.ordir') without
appropriate validation can lead to ambiguous path resolution and allow an attacker to traverse the
file system to unintended locations or access arbitrary files.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Potential Mitigations
see the vulnerability category "Path Equivalence"
Other Notes
This variant does not have any easily findable, publicly reported vulnerabilities, but it can be an
effective manipulation in weaknesses such as validate-before-cleanse, which might remove a dot
from a string to produce an unexpected string.
Relationships
Nature Type ID Name Page
ChildOf 41 Improper Resolution of Path Equivalence 699 51
1000
ParentOf 45 Path Equivalence: 'file...name' (Multiple Internal Dot) 699 54
1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Internal Dot - 'file.ordir'

CWE-45: Path Equivalence: 'file...name' (Multiple Internal


Dot)
Weakness ID: 45 (Weakness Variant) Status: Incomplete

54
CWE Version 1.8.1
CWE-46: Path Equivalence: 'filename ' (Trailing Space)

Description
Summary
A software system that accepts path input in the form of multiple internal dot ('file...dir') without
appropriate validation can lead to ambiguous path resolution and allow an attacker to traverse the
file system to unintended locations or access arbitrary files.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Potential Mitigations
see the vulnerability category "Path Equivalence"
Other Notes
This variant does not have any easily findable, publicly reported vulnerabilities, but it can be an

CWE-46: Path Equivalence: 'filename ' (Trailing Space)


effective manipulation in weaknesses such as validate-before-cleanse, which might use a regular
expression that removes ".." sequences from a string to produce an unexpected string.
Relationships
Nature Type ID Name Page
ChildOf 44 Path Equivalence: 'file.name' (Internal Dot) 699 54
1000
ChildOf 165 Improper Neutralization of Multiple Internal Special Elements 1000 222

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Multiple Internal Dot - 'file...dir'

CWE-46: Path Equivalence: 'filename ' (Trailing Space)


Weakness ID: 46 (Weakness Variant) Status: Incomplete
Description
Summary
A software system that accepts path input in the form of trailing space ('filedir ') without
appropriate validation can lead to ambiguous path resolution and allow an attacker to traverse the
file system to unintended locations or access arbitrary files.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-2001-0054 Multi-Factor Vulnerability (MVF). directory traversal and other issues in FTP server using
Web encodings such as "%20"; certain manipulations have unusual side effects.
CVE-2001-0693 Source disclosure via trailing encoded space "%20"
CVE-2001-0778 Source disclosure via trailing encoded space "%20"
CVE-2001-1248 Source disclosure via trailing encoded space "%20"
CVE-2002-1451 Trailing space ("+" in query string) leads to source code disclosure.
CVE-2002-1603 Source disclosure via trailing encoded space "%20"
CVE-2004-0280 Source disclosure via trailing encoded space "%20"
CVE-2004-2213 Source disclosure via trailing encoded space "%20"
CVE-2005-0622 Source disclosure via trailing encoded space "%20"
CVE-2005-1656 Source disclosure via trailing encoded space "%20"
Potential Mitigations
see the vulnerability category "Path Equivalence"
Relationships
55
CWE Version 1.8.1
CWE-47: Path Equivalence: ' filename (Leading Space)

Nature Type ID Name Page


ChildOf 41 Improper Resolution of Path Equivalence 699 51
1000
ChildOf 162 Improper Neutralization of Trailing Special Elements 1000 220
CanPrecede 289 Authentication Bypass by Alternate Name 1000 360

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Trailing Space - 'filedir '

CWE-47: Path Equivalence: ' filename (Leading Space)


Weakness ID: 47 (Weakness Variant) Status: Incomplete
Description
Summary
A software system that accepts path input in the form of leading space (' filedir') without
CWE-47: Path Equivalence: ' filename (Leading Space)

appropriate validation can lead to ambiguous path resolution and allow an attacker to traverse the
file system to unintended locations or access arbitrary files.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Potential Mitigations
see the vulnerability category "Path Equivalence"
Relationships
Nature Type ID Name Page
ChildOf 41 Improper Resolution of Path Equivalence 699 51
1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Leading Space - ' filedir'

CWE-48: Path Equivalence: 'file name' (Internal


Whitespace)
Weakness ID: 48 (Weakness Variant) Status: Incomplete
Description
Summary
A software system that accepts path input in the form of internal space ('file(SPACE)name')
without appropriate validation can lead to ambiguous path resolution and allow an attacker to
traverse the file system to unintended locations or access arbitrary files.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-2000-0293 Filenames with spaces allow arbitrary file deletion when the product does not properly
quote them; some overlap with path traversal.
CVE-2001-1567 "+" characters in query string converted to spaces before sensitive file/extension (internal
space), leading to bypass of access restrictions to the file.
Potential Mitigations

56
CWE Version 1.8.1
CWE-49: Path Equivalence: 'filename/' (Trailing Slash)

see the vulnerability category "Path Equivalence"


Other Notes
This is not necessarily an equivalence issue, but it can also be used to spoof icons or conduct
information hiding via information truncation (see user interface errors).
This weakness is likely to overlap quoting problems, e.g. the "Program Files" untrusted search path
variants. It also could be an equivalence issue if filtering removes all extraneous spaces.
Relationships
Nature Type ID Name Page
ChildOf 41 Improper Resolution of Path Equivalence 699 51
1000
Taxonomy Mappings
Mapped Taxonomy Name Node ID Fit Mapped Node Name
PLOVER file(SPACE)name (internal space)
OWASP Top Ten 2004 A9 CWE More Specific Denial of Service

CWE-49: Path Equivalence: 'filename/' (Trailing Slash)


CWE-49: Path Equivalence: 'filename/' (Trailing Slash)
Weakness ID: 49 (Weakness Variant) Status: Incomplete
Description
Summary
A software system that accepts path input in the form of trailing slash ('filedir/') without appropriate
validation can lead to ambiguous path resolution and allow an attacker to traverse the file system
to unintended locations or access arbitrary files.
Time of Introduction
• Implementation
• Operation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
BID:3518
CVE-2001-0446
CVE-2001-0892
CVE-2001-0893 Read sensitive files with trailing "/"
CVE-2002-0253 Overlaps infoleak
CVE-2004-0334 Bypass Basic Authentication for files using trailing "/"
CVE-2004-1101 Failure to handle filename request with trailing "/" causes multiple consequences, including
server crash and a Visual Basic error message that enables XSS and information leak.
CVE-2004-1814
Potential Mitigations
see the vulnerability category "Path Equivalence"
Relationships
Nature Type ID Name Page
ChildOf 41 Improper Resolution of Path Equivalence 699 51
1000
ChildOf 162 Improper Neutralization of Trailing Special Elements 1000 220

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER filedir/ (trailing slash, trailing /)

CWE-50: Path Equivalence: '//multiple/leading/slash'


Weakness ID: 50 (Weakness Variant) Status: Incomplete

57
CWE Version 1.8.1
CWE-51: Path Equivalence: '/multiple//internal/slash'

Description
Summary
A software system that accepts path input in the form of multiple leading slash ('//multiple/leading/
slash') without appropriate validation can lead to ambiguous path resolution and allow an attacker
to traverse the file system to unintended locations or access arbitrary files.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-1999-1456
CVE-2000-1050 Access directory using multiple leading slash.
CVE-2001-1072 Bypass access restrictions via multiple leading slash, which causes a regular expression to
CWE-51: Path Equivalence: '/multiple//internal/slash'

fail.
CVE-2002-0275
CVE-2002-1238
CVE-2002-1483
CVE-2004-0235 Archive extracts to arbitrary files using multiple leading slash in filenames in the archive.
CVE-2004-0578
CVE-2004-1032
CVE-2004-1878
CVE-2005-1365
Potential Mitigations
see the vulnerability category "Path Equivalence"
Relationships
Nature Type ID Name Page
ChildOf 41 Improper Resolution of Path Equivalence 699 51
1000
ChildOf 161 Improper Neutralization of Multiple Leading Special Elements 1000 219

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER //multiple/leading/slash ('multiple leading slash')

CWE-51: Path Equivalence: '/multiple//internal/slash'


Weakness ID: 51 (Weakness Variant) Status: Incomplete
Description
Summary
A software system that accepts path input in the form of multiple internal slash ('/multiple//
internal/slash/') without appropriate validation can lead to ambiguous path resolution and allow an
attacker to traverse the file system to unintended locations or access arbitrary files.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-2002-1483 Read files with full pathname using multiple internal slash.
Potential Mitigations
see the vulnerability category "Path Equivalence"
Relationships
58
CWE Version 1.8.1
CWE-52: Path Equivalence: '/multiple/trailing/slash//'

Nature Type ID Name Page


ChildOf 41 Improper Resolution of Path Equivalence 699 51
1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER /multiple//internal/slash ('multiple internal slash')

CWE-52: Path Equivalence: '/multiple/trailing/slash//'


Weakness ID: 52 (Weakness Variant) Status: Incomplete
Description
Summary
A software system that accepts path input in the form of multiple trailing slash ('/multiple/trailing/
slash//') without appropriate validation can lead to ambiguous path resolution and allow an
attacker to traverse the file system to unintended locations or access arbitrary files.
Time of Introduction

CWE-52: Path Equivalence: '/multiple/trailing/slash//'


• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-2002-1078 Directory listings in web server using multiple trailing slash
Potential Mitigations
see the vulnerability category "Path Equivalence"
Relationships
Nature Type ID Name Page
ChildOf 41 Improper Resolution of Path Equivalence 699 51
1000
ChildOf 163 Improper Neutralization of Multiple Trailing Special Elements 1000 220
CanPrecede 289 Authentication Bypass by Alternate Name 1000 360

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER /multiple/trailing/slash// ('multiple trailing slash')

CWE-53: Path Equivalence: '\multiple\\internal\backslash'


Weakness ID: 53 (Weakness Variant) Status: Incomplete
Description
Summary
A software system that accepts path input in the form of multiple internal backslash ('\multiple
\trailing\\slash') without appropriate validation can lead to ambiguous path resolution and allow an
attacker to traverse the file system to unintended locations or access arbitrary files.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Potential Mitigations
see the vulnerability category "Path Equivalence"
Relationships
Nature Type ID Name Page
ChildOf 41 Improper Resolution of Path Equivalence 699 51

59
CWE Version 1.8.1
CWE-54: Path Equivalence: 'filedir\' (Trailing Backslash)

Nature Type ID Name Page


1000
ChildOf 165 Improper Neutralization of Multiple Internal Special Elements 1000 222

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER \multiple\\internal\backslash

CWE-54: Path Equivalence: 'filedir\' (Trailing Backslash)


Weakness ID: 54 (Weakness Variant) Status: Incomplete
Description
Summary
A software system that accepts path input in the form of trailing backslash ('filedir\') without
appropriate validation can lead to ambiguous path resolution and allow an attacker to traverse the
file system to unintended locations or access arbitrary files.
CWE-54: Path Equivalence: 'filedir\' (Trailing Backslash)

Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-2004-0847
Potential Mitigations
see the vulnerability category "Path Equivalence"
Relationships
Nature Type ID Name Page
ChildOf 41 Improper Resolution of Path Equivalence 699 51
1000
ChildOf 162 Improper Neutralization of Trailing Special Elements 1000 220

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER filedir\ (trailing backslash)

CWE-55: Path Equivalence: '/./' (Single Dot Directory)


Weakness ID: 55 (Weakness Variant) Status: Incomplete
Description
Summary
A software system that accepts path input in the form of single dot directory exploit ('/./') without
appropriate validation can lead to ambiguous path resolution and allow an attacker to traverse the
file system to unintended locations or access arbitrary files.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
BID:6042
CVE-1999-1083 Possibly (could be a cleansing error)
CVE-2000-0004
CVE-2002-0112
CVE-2002-0304

60
CWE Version 1.8.1
CWE-56: Path Equivalence: 'filedir*' (Wildcard)

Reference Description
CVE-2004-0815 "/./////etc" cleansed to ".///etc" then "/etc"
Potential Mitigations
see the vulnerability category "Path Equivalence"
Relationships
Nature Type ID Name Page
ChildOf 41 Improper Resolution of Path Equivalence 699 51
1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER /./ (single dot directory)

CWE-56: Path Equivalence: 'filedir*' (Wildcard)


Weakness ID: 56 (Weakness Variant) Status: Incomplete
Description
Summary

CWE-56: Path Equivalence: 'filedir*' (Wildcard)


A software system that accepts path input in the form of asterisk wildcard ('filedir*') without
appropriate validation can lead to ambiguous path resolution and allow an attacker to traverse the
file system to unintended locations or access arbitrary files.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-2002-0433 List files in web server using "*.ext"
CVE-2004-0696 List directories using desired path and "*"
Potential Mitigations
see the vulnerability category "Path Equivalence"
Relationships
Nature Type ID Name Page
ChildOf 41 Improper Resolution of Path Equivalence 699 51
1000
ChildOf 155 Improper Neutralization of Wildcards or Matching Symbols 1000 213

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER filedir* (asterisk / wildcard)

CWE-57: Path Equivalence: 'fakedir/../realdir/filename'


Weakness ID: 57 (Weakness Variant) Status: Incomplete
Description
Summary
The software contains protection mechanisms to restrict access to 'realdir/filename', but it
constructs pathnames using external input in the form of 'fakedir/../realdir/filename' that are not
handled by those mechanisms. This allows attackers to perform unauthorized actions against the
targeted file.
Time of Introduction
• Implementation
Applicable Platforms
Languages

61
CWE Version 1.8.1
CWE-58: Path Equivalence: Windows 8.3 Filename

• All
Observed Examples
Reference Description
CVE-2000-0191 application check access for restricted URL before canonicalization
CVE-2001-1152
CVE-2005-1366 CGI source disclosure using "dirname/../cgi-bin"
Potential Mitigations
see the vulnerability category "Path Equivalence"
Relationships
Nature Type ID Name Page
ChildOf 41 Improper Resolution of Path Equivalence 699 51
1000
Theoretical Notes
This is a manipulation that uses an injection for one consequence (containment violation using
relative path) to achieve a different consequence (equivalence by alternate name).
CWE-58: Path Equivalence: Windows 8.3 Filename

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER dirname/fakechild/../realchild/filename

CWE-58: Path Equivalence: Windows 8.3 Filename


Weakness ID: 58 (Weakness Variant) Status: Incomplete
Description
Summary
The software contains a protection mechanism that restricts access to a long filename on a
Windows operating system, but the software does not properly restrict access to the equivalent
short "8.3" filename.
Extended Description
On later Windows operating systems, a file can have a "long name" and a short name that
is compatible with older Windows file systems, with up to 8 characters in the filename and 3
characters for the extension. These "8.3" filenames, therefore, act as an alternate name for files
with long names, so they are useful pathname equivalence manipulations.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Operating Systems
• Windows
Observed Examples
Reference Description
CVE-1999-0012 Multiple web servers allow restriction bypass using 8.3 names instead of long names
CVE-2001-0795 Source code disclosure using 8.3 file name.
CVE-2005-0471 Multi-Factor Vulnerability. Product generates temporary filenames using long filenames,
which become predictable in 8.3 format.
Potential Mitigations
Disable Windows from supporting 8.3 filenames by editing the Windows registry. Preventing 8.3
filenames will not remove previously generated 8.3 filenames.
Relationships
Nature Type ID Name Page
ChildOf 41 Improper Resolution of Path Equivalence 699 51
1000
Research Gaps

62
CWE Version 1.8.1
CWE-59: Improper Link Resolution Before File Access ('Link Following')

Probably under-studied
Functional Areas
• File processing
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Windows 8.3 Filename
References
M. Howard and D. LeBlanc. "Writing Secure Code". 2nd Edition. Microsoft. 2003.

CWE-59: Improper Link Resolution Before File Access

CWE-59: Improper Link Resolution Before File Access ('Link Following')


('Link Following')
Weakness ID: 59 (Weakness Base) Status: Draft
Description
Summary
The software attempts to access a file based on the filename, but it does not properly prevent that
filename from identifying a link or shortcut that resolves to an unintended resource.
Alternate Terms
insecure temporary file
Some people use the phrase "insecure temporary file" when referring to a link following
weakness, but other weaknesses can produce insecure temporary files without any symlink
involvement at all.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Operating Systems
• Windows (Sometimes)
• UNIX (Often)
Likelihood of Exploit
Low to Medium
Potential Mitigations
Architecture and Design
Implementation
Follow the principle of least privilege when assigning access rights to files. Denying access to
a file can prevent an attacker from replacing that file with a link to a sensitive file. Ensure good
compartmentalization in the system to provide protected areas that can be trusted.
Background Details
Soft links are a UNIX term that is synonymous with simple shortcuts on windows based platforms.
Other Notes
Windows simple shortcuts, sometimes referred to as soft links, can be exploited remotely since an
".LNK" file can be uploaded like a normal file.
Weakness Ordinalities
Resultant (where the weakness is typically related to the presence of some other weaknesses)
Relationships
Nature Type ID Name Page
ChildOf 21 Pathname Traversal and Equivalence Errors 699 23
ChildOf 632 Weaknesses that Affect Files or Directories 631 706
ChildOf 706 Use of Incorrectly-Resolved Name or Reference 1000 811
ChildOf 743 CERT C Secure Coding Section 09 - Input Output (FIO) 734 836
ChildOf 748 CERT C Secure Coding Section 50 - POSIX (POS) 734 839
ChildOf 808 2010 Top 25 - Weaknesses On the Cusp 800 912
63
CWE Version 1.8.1
CWE-60: UNIX Path Link Problems

Nature Type ID Name Page


ParentOf 60 UNIX Path Link Problems 699 64
ParentOf 61 UNIX Symbolic Link (Symlink) Following 1000 65
ParentOf 62 UNIX Hard Link 1000 66
ParentOf 63 Windows Path Link Problems 699 67
ParentOf 64 Windows Shortcut Following (.LNK) 1000 68
ParentOf 65 Windows Hard Link 1000 69
CanFollow 73 External Control of File Name or Path 1000 75
CanFollow 363 Race Condition Enabling Link Following 1000 444
MemberOf 635 Weaknesses Used by NVD 635 708

Relationship Notes
Link following vulnerabilities are Multi-factor Vulnerabilities (MFV). They are the combination of
multiple elements: file or directory permissions, filename predictability, race conditions, and in
some cases, a design limitation in which there is no mechanism for performing atomic file creation
operations.
Some potential factors are race conditions, permissions, and predictability.
Research Gaps
UNIX hard links, and Windows hard/soft links are under-studied and under-reported.
CWE-60: UNIX Path Link Problems

Affected Resources
• File/Directory
Functional Areas
• File processing, temporary files
Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Node ID Mapped Node Name
PLOVER Link Following
CERT C Secure Coding FIO02-C Canonicalize path names originating from untrusted sources
CERT C Secure Coding POS01-C Check for the existence of links when dealing with files
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
17 Accessing, Modifying or Executing Executable Files
35 Leverage Executable Code in Nonexecutable Files
76 Manipulating Input to File System Calls
132 Symlink Attacks

CWE-60: UNIX Path Link Problems


Category ID: 60 (Category) Status: Draft
Description
Summary
Weaknesses in this category are related to improper handling of links within Unix-based operating
systems.
Applicable Platforms
Languages
• All
Relationships
Nature Type ID Name Page
ChildOf 59 Improper Link Resolution Before File Access ('Link Following') 699 63
ChildOf 632 Weaknesses that Affect Files or Directories 631 706
ParentOf 61 UNIX Symbolic Link (Symlink) Following 631 65
699
ParentOf 62 UNIX Hard Link 631 66

64
CWE Version 1.8.1
CWE-61: UNIX Symbolic Link (Symlink) Following

Nature Type ID Name Page


699
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER UNIX Path Link problems

CWE-61: UNIX Symbolic Link (Symlink) Following


Compound Element ID: 61 (Compound Element Variant: Composite) Status: Incomplete
Description
Summary
The software, when opening a file or directory, does not sufficiently account for when the file is a
symbolic link that resolves to a target outside of the intended control sphere. This could allow an
attacker to cause the software to operate on unauthorized files.
Extended Description
A software system that allows UNIX symbolic links (symlink) as part of paths whether in internal

CWE-61: UNIX Symbolic Link (Symlink) Following


code or through user input can allow an attacker to spoof the symbolic link and traverse the file
system to unintended locations or access arbitrary files. The symbolic link can permit an attacker
to read/write/corrupt a file that they originally did not have permissions to access.
Alternate Terms
Symlink following
symlink vulnerability
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Likelihood of Exploit
High to Very High
Observed Examples
Reference Description
CVE-1999-1386
CVE-2000-0972 Setuid product allows file reading by replacing a file being edited with a symlink to the
targeted file, leaking the result in error messages when parsing fails.
CVE-2000-1178
CVE-2003-0517
CVE-2004-0217
CVE-2004-0689 Possible interesting example
CVE-2005-0824 Signal causes a dump that follows symlinks.
CVE-2005-1879 Second-order symlink vulnerabilities
CVE-2005-1880 Second-order symlink vulnerabilities
CVE-2005-1916 Symlink in Python program
Potential Mitigations
Symbolic link attacks often occur when a program creates a tmp directory that stores files/
links. Access to the directory should be restricted to the program as to prevent attackers from
manipulating the files.
Follow the principle of least privilege when assigning access rights to files. Denying access to
a file can prevent an attacker from replacing that file with a link to a sensitive file. Ensure good
compartmentalization in the system to provide protected areas that can be trusted.
Other Notes
Fault: filename predictability, insecure directory permissions, non-atomic operations, race
condition.
These are typically reported for temporary files or privileged programs.
Weakness Ordinalities
65
CWE Version 1.8.1
CWE-62: UNIX Hard Link

Resultant (where the weakness is typically related to the presence of some other weaknesses)
Relationships
Nature Type ID Name Page
ChildOf 59 Improper Link Resolution Before File Access ('Link Following') 1000 63
ChildOf 60 UNIX Path Link Problems 631 64
699
Requires 216 Containment Errors (Container Errors) 1000 287
Requires 275 Permission Issues 1000 343
Requires 340 Predictability Problems 1000 419
Requires 362 Race Condition 1000 440
Requires 386 Symbolic Name not Mapping to Correct Object 1000 470

Research Gaps
Symlink vulnerabilities are regularly found in C and shell programs, but all programming languages
can have this problem. Even shell programs are probably under-reported.
"Second-order symlink vulnerabilities" may exist in programs that invoke other programs that follow
symlinks. They are rarely reported but are likely to be fairly common when process invocation is
used. Reference: [Christey2005]
Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
CWE-62: UNIX Hard Link

PLOVER UNIX symbolic link following


Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
27 Leveraging Race Conditions via Symbolic Links
References
Steve Christey. "Second-Order Symlink Vulnerabilities". Bugtraq. 2005-06-07. < http://
www.securityfocus.com/archive/1/401682 >.
Shaun Colley. "Crafting Symlinks for Fun and Profit". Infosec Writers Text Library. 2004-04-12. <
http://www.infosecwriters.com/texts.php?op=display&id=159 >.

CWE-62: UNIX Hard Link


Weakness ID: 62 (Weakness Variant) Status: Incomplete
Description
Summary
The software, when opening a file or directory, does not sufficiently account for when the name
is associated with a hard link to a target that is outside of the intended control sphere. This could
allow an attacker to cause the software to operate on unauthorized files.
Extended Description
Failure for a system to check for hard links can result in vulnerability to different types of attacks.
For example, an attacker can escalate their privileges if a file used by a privileged program is
replaced with a hard link to a sensitive file (e.g. /etc/passwd). When the process opens the file,
the attacker can assume the privileges of that process.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Operating Systems
• UNIX
Observed Examples

66
CWE Version 1.8.1
CWE-63: Windows Path Link Problems

Reference Description
BUGTRAQ:20030203
OpenBSD chpass/chfn/chsh file content leak
ASA-0001
CVE-1999-0783
CVE-2001-1494 Hard link attack, file overwrite; interesting because program checks against soft links
CVE-2002-0793
CVE-2003-0578
CVE-2004-1603
CVE-2004-1901
CVE-2005-1111 Hard link race condition
Potential Mitigations
Follow the principle of least privilege when assigning access rights to files. Denying access to
a file can prevent an attacker from replacing that file with a link to a sensitive file. Ensure good
compartmentalization in the system to provide protected areas that can be trusted.
Weakness Ordinalities
Resultant (where the weakness is typically related to the presence of some other weaknesses)
Relationships
Nature Type ID Name Page
ChildOf 59 Improper Link Resolution Before File Access ('Link Following') 1000 63

CWE-63: Windows Path Link Problems


ChildOf 60 UNIX Path Link Problems 631 64
699
ChildOf 743 CERT C Secure Coding Section 09 - Input Output (FIO) 734 836
PeerOf 71 Apple '.DS_Store' 1000 73

Research Gaps
Under-studied. It is likely that programs that check for symbolic links could be vulnerable to hard
links.
Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Node ID Mapped Node Name
PLOVER UNIX hard link
CERT C Secure Coding FIO05-C Identify files using multiple file attributes

CWE-63: Windows Path Link Problems


Category ID: 63 (Category) Status: Draft
Description
Summary
Weaknesses in this category are related to improper handling of links within Windows-based
operating systems.
Applicable Platforms
Languages
• All
Operating Systems
• Windows
Relationships
Nature Type ID Name Page
ChildOf 59 Improper Link Resolution Before File Access ('Link Following') 699 63
ChildOf 632 Weaknesses that Affect Files or Directories 631 706
ParentOf 64 Windows Shortcut Following (.LNK) 631 68
699
ParentOf 65 Windows Hard Link 631 69
699

67
CWE Version 1.8.1
CWE-64: Windows Shortcut Following (.LNK)

CWE-64: Windows Shortcut Following (.LNK)


Weakness ID: 64 (Weakness Variant) Status: Incomplete
Description
Summary
The software, when opening a file or directory, does not sufficiently handle when the file is a
Windows shortcut (.LNK) whose target is outside of the intended control sphere. This could allow
an attacker to cause the software to operate on unauthorized files.
Extended Description
The shortcut (file with the .lnk extension) can permit an attacker to read/write a file that they
originally did not have permissions to access.
Alternate Terms
Windows symbolic link following
symlink
Time of Introduction
• Operation
Applicable Platforms
CWE-64: Windows Shortcut Following (.LNK)

Languages
• All
Operating Systems
• Windows
Likelihood of Exploit
Medium to High
Observed Examples
Reference Description
CVE-2000-0342
CVE-2001-1042
CVE-2001-1043
CVE-2001-1386 ".LNK." - .LNK with trailing dot
CVE-2003-1233 Rootkits can bypass file access restrictions to Windows kernel directories using
NtCreateSymbolicLinkObject function to create symbolic link
CVE-2005-0587
Potential Mitigations
Follow the principle of least privilege when assigning access rights to files. Denying access to
a file can prevent an attacker from replacing that file with a link to a sensitive file. Ensure good
compartmentalization in the system to provide protected areas that can be trusted.
Weakness Ordinalities
Resultant (where the weakness is typically related to the presence of some other weaknesses)
Relationships
Nature Type ID Name Page
ChildOf 59 Improper Link Resolution Before File Access ('Link Following') 1000 63
ChildOf 63 Windows Path Link Problems 631 67
699
ChildOf 743 CERT C Secure Coding Section 09 - Input Output (FIO) 734 836

Research Gaps
Under-studied. Windows .LNK files are more "portable" than Unix symlinks and have been used in
remote exploits. Some Windows API's will access LNK's as if they are regular files, so one would
expect that they would be reported more frequently.
Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Node ID Mapped Node Name
PLOVER Windows Shortcut Following (.LNK)

68
CWE Version 1.8.1
CWE-65: Windows Hard Link

Mapped Taxonomy Name Node ID Mapped Node Name


CERT C Secure Coding FIO05-C Identify files using multiple file attributes

CWE-65: Windows Hard Link


Weakness ID: 65 (Weakness Variant) Status: Incomplete
Description
Summary
The software, when opening a file or directory, does not sufficiently handle when the name is
associated with a hard link to a target that is outside of the intended control sphere. This could
allow an attacker to cause the software to operate on unauthorized files.
Extended Description
Failure for a system to check for hard links can result in vulnerability to different types of attacks.
For example, an attacker can escalate their privileges if a file used by a privileged program is
replaced with a hard link to a sensitive file (e.g. AUTOEXEC.BAT). When the process opens
the file, the attacker can assume the privileges of that process, or prevent the program from
accurately processing data.
Time of Introduction
• Implementation
• Operation
Applicable Platforms

CWE-65: Windows Hard Link


Languages
• All
Operating Systems
• Windows
Observed Examples
Reference Description
CVE-2002-0725
CVE-2003-0844
Potential Mitigations
Follow the principle of least privilege when assigning access rights to files. Denying access to
a file can prevent an attacker from replacing that file with a link to a sensitive file. Ensure good
compartmentalization in the system to provide protected areas that can be trusted.
Relationships
Nature Type ID Name Page
ChildOf 59 Improper Link Resolution Before File Access ('Link Following') 1000 63
ChildOf 63 Windows Path Link Problems 631 67
699
ChildOf 743 CERT C Secure Coding Section 09 - Input Output (FIO) 734 836

Research Gaps
Under-studied
Taxonomy Mappings
Mapped Taxonomy Name Node ID Mapped Node Name
PLOVER Windows hard link
CERT C Secure Coding FIO05-C Identify files using multiple file attributes

CWE-66: Improper Handling of File Names that Identify


Virtual Resources
Weakness ID: 66 (Weakness Base) Status: Draft
Description
Summary

69
CWE Version 1.8.1
CWE-67: Improper Handling of Windows Device Names

The product does not handle or incorrectly handles a file name that identifies a "virtual" resource
that is not directly specified within the directory that is associated with the file name, causing the
product to perform file-based operations on a resource that is not a file.
Extended Description
Virtual file names are represented like normal file names, but they are effectively aliases for other
resources that do not behave like normal files. Depending on their functionality, they could be
alternate entities. They are not necessarily listed in directories.
Time of Introduction
• Architecture and Design
• Implementation
• Operation
Applicable Platforms
Languages
• All
CWE-67: Improper Handling of Windows Device Names

Relationships
Nature Type ID Name Page
ChildOf 21 Pathname Traversal and Equivalence Errors 699 23
ChildOf 706 Use of Incorrectly-Resolved Name or Reference 1000 811
ParentOf 67 Improper Handling of Windows Device Names 699 70
1000
ParentOf 68 Windows Virtual File Problems 699 71
ParentOf 69 Failure to Handle Windows ::DATA Alternate Data Stream 699 72
1000
ParentOf 70 Mac Virtual File Problems 699 73
ParentOf 71 Apple '.DS_Store' 1000 73
ParentOf 72 Improper Handling of Apple HFS+ Alternate Data Stream Path 699 74
1000
Affected Resources
• File/Directory
Functional Areas
• File processing
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Virtual Files

CWE-67: Improper Handling of Windows Device Names


Weakness ID: 67 (Weakness Variant) Status: Incomplete
Description
Summary
The software constructs pathnames from user input, but it does not handle or incorrectly handles
a pathname containing a Windows device name such as AUX or CON. This typically leads to
denial of service or an information leak when the application attempts to process the pathname as
a regular file.
Extended Description
Failing to properly handle virtual filenames (e.g. AUX, CON, PRN, COM1, LPT1) can result in
different types of vulnerabilities. In some cases an attacker can request a device via injection of
a virtual filename in a URL, which may cause an error that leads to a denial of service or an error
page that reveals sensitive information. A software system that allows device names to bypass
filtering runs the risk of an attacker injecting malicious code in a file with the name of a device.
Time of Introduction
• Architecture and Design
• Implementation
• Operation
70
CWE Version 1.8.1
CWE-68: Windows Virtual File Problems

Applicable Platforms
Languages
• All
Operating Systems
• Windows
Likelihood of Exploit
High to Very High
Observed Examples
Reference Description
CVE-2000-0168
CVE-2001-0492
CVE-2001-0493
CVE-2001-0558
CVE-2002-0106
CVE-2002-0200
CVE-2002-1052
CVE-2004-0552
CVE-2005-2195

CWE-68: Windows Virtual File Problems


Potential Mitigations
Be familiar with the device names in the operating system where your system is deployed. Check
input for these device names.
Background Details
Historically, there was a bug in the Windows operating system that caused a blue screen of death.
Even after that issue was fixed DOS device names continue to be a factor.
Weakness Ordinalities
Resultant (where the weakness is typically related to the presence of some other weaknesses)
Relationships
Nature Type ID Name Page
ChildOf 66 Improper Handling of File Names that Identify Virtual 699 69
Resources 1000
ChildOf 68 Windows Virtual File Problems 631 71
ChildOf 632 Weaknesses that Affect Files or Directories 631 706
ChildOf 743 CERT C Secure Coding Section 09 - Input Output (FIO) 734 836

Affected Resources
• File/Directory
Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Node ID Mapped Node Name
PLOVER Windows MS-DOS device names
CERT C Secure Coding FIO32-C Do not perform operations on devices that are only appropriate for
files
References
M. Howard and D. LeBlanc. "Writing Secure Code". 2nd Edition. Microsoft. 2003.

CWE-68: Windows Virtual File Problems


Category ID: 68 (Category) Status: Draft
Description
Summary
Weaknesses in this category are related to improper handling of virtual files within Windows-
based operating systems.
Applicable Platforms
Languages
71
CWE Version 1.8.1
CWE-69: Failure to Handle Windows ::DATA Alternate Data Stream

• All
Relationships
Nature Type ID Name Page
ChildOf 66 Improper Handling of File Names that Identify Virtual 699 69
Resources
ChildOf 632 Weaknesses that Affect Files or Directories 631 706
ParentOf 67 Improper Handling of Windows Device Names 631 70
ParentOf 69 Failure to Handle Windows ::DATA Alternate Data Stream 631 72
699
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Windows Virtual File problems
CWE-69: Failure to Handle Windows ::DATA Alternate Data Stream

CWE-69: Failure to Handle Windows ::DATA Alternate Data


Stream
Weakness ID: 69 (Weakness Variant) Status: Incomplete
Description
Summary
The software does not properly prevent access to, or detect usage of, alternate data streams
(ADS).
Extended Description
An attacker can use an ADS to hide information about a file (e.g. size, the name of the process)
from a system or file browser tools such as Windows Explorer and 'dir' at the command line utility.
Alternately, the attacker might be able to bypass intended access restrictions for the associated
data fork.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• All
Operating Systems
• Windows
Observed Examples
Reference Description
CVE-1999-0278
CVE-2000-0927
Potential Mitigations
Software tools are capable of finding ADSs on your system.
Ensure that the source code correctly parses the filename to read or write to the correct stream.
Background Details
Alternate data streams (ADS) were first implemented in the Windows NT operating system
to provide compatibility between NTFS and the Macintosh Hierarchical File System (HFS). In
HFS, data and resource forks are used to store information about a file. The data fork provides
information about the contents of the file while the resource fork stores metadata such as file type.
Relationships
Nature Type ID Name Page
ChildOf 66 Improper Handling of File Names that Identify Virtual 699 69
Resources 1000
ChildOf 68 Windows Virtual File Problems 631 71
699
ChildOf 634 Weaknesses that Affect System Processes 631 708

72
CWE Version 1.8.1
CWE-70: Mac Virtual File Problems

Theoretical Notes
This and similar problems exist because the same resource can have multiple identifiers that
dictate which behavior can be performed on the resource.
Affected Resources
• System Process
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Windows ::DATA alternate data stream
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
11 Cause Web Server Misclassification
168 Windows ::DATA Alternate Data Stream
References
Don Parker. "Windows NTFS Alternate Data Streams". 2005-02-16. < http://
www.securityfocus.com/infocus/1822 >.
M. Howard and D. LeBlanc. "Writing Secure Code". 2nd Edition. Microsoft. 2003.

CWE-70: Mac Virtual File Problems


Category ID: 70 (Category) Status: Draft

CWE-70: Mac Virtual File Problems


Description
Summary
Weaknesses in this category are related to improper handling of virtual files within Mac-based
operating systems.
Applicable Platforms
Languages
• All
Relationships
Nature Type ID Name Page
ChildOf 66 Improper Handling of File Names that Identify Virtual 699 69
Resources
ChildOf 632 Weaknesses that Affect Files or Directories 631 706
ParentOf 71 Apple '.DS_Store' 631 73
699
ParentOf 72 Improper Handling of Apple HFS+ Alternate Data Stream Path 631 74
699
Affected Resources
• File/Directory
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Mac Virtual File problems

CWE-71: Apple '.DS_Store'


Weakness ID: 71 (Weakness Variant) Status: Incomplete
Description
Summary
Software operating in a MAC OS environment, where .DS_Store is in effect, must carefully
manage hard links, otherwise an attacker may be able to leverage a hard link from .DS_Store to
overwrite arbitrary files and gain privileges.
Time of Introduction
• Architecture and Design
• Implementation
• Operation

73
CWE Version 1.8.1
CWE-72: Improper Handling of Apple HFS+ Alternate Data Stream Path

Applicable Platforms
Languages
• All
Observed Examples
Reference Description
BUGTRAQ:20010910
More security problems in Apache on Mac OS X
CVE-2005-0342 The Finder in Mac OS X and earlier allows local users to overwrite arbitrary files and gain
privileges by creating a hard link from the .DS_Store file to an arbitrary file.
Relationships
Nature Type ID Name Page
PeerOf 62 UNIX Hard Link 1000 66
CWE-72: Improper Handling of Apple HFS+ Alternate Data Stream Path

ChildOf 66 Improper Handling of File Names that Identify Virtual 1000 69


Resources
ChildOf 70 Mac Virtual File Problems 631 73
699
Research Gaps
Under-studied
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER DS - Apple '.DS_Store
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
18 Embedding Scripts in Nonscript Elements
19 Embedding Scripts within Scripts
32 Embedding Scripts in HTTP Query Strings
63 Simple Script Injection
86 Embedding Script (XSS ) in HTTP Headers
91 XSS in IMG Tags
Maintenance Notes
This entry, which originated from PLOVER, probably stems from a common manipulation that
is used to exploit symlink and hard link following weaknesses, like /etc/passwd is often used for
UNIX-based exploits. As such, it is probably too low-level for inclusion in CWE.

CWE-72: Improper Handling of Apple HFS+ Alternate Data


Stream Path
Weakness ID: 72 (Weakness Variant) Status: Incomplete
Description
Summary
The software does not properly handle special paths that may identify the data or resource fork of
a file on the HFS+ file system.
Extended Description
If the software chooses actions to take based on the file name, then if an attacker provides
the data or resource fork, the software may take unexpected actions. Further, if the software
intends to restrict access to a file, then an attacker might still be able to bypass intended access
restrictions by requesting the data or resource fork for that file.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• All
Operating Systems

74
CWE Version 1.8.1
CWE-73: External Control of File Name or Path

• Mac OS
Demonstrative Examples
A web server that interprets FILE.cgi as processing instructions could disclose the source code
for FILE.cgi by requesting FILE.cgi/..namedfork/data. This might occur because the web server
invokes the default handler which may return the contents of the file.
Observed Examples
Reference Description
CVE-2004-1084
Background Details
The Apple HFS+ file system permits files to have multiple data input streams, accessible through
special paths. The Mac OS X operating system provides a way to access the different data input
streams through special paths and as an extended attribute:
- Resource fork: file/..namedfork/rsrc, file/rsrc (deprecated), xattr:com.apple.ResourceFork
- Data fork: file/..namedfork/data (only versions prior to Mac OS X v10.5)
Additionally, on filesystems that lack native support for multiple streams, the resource fork and file
metadata may be stored in a file with "._" prepended to the name.

CWE-73: External Control of File Name or Path


Forks can also be accessed through non-portable APIs.
Forks inherit the file system access controls of the file they belong to.
Programs need to control access to these paths, if the processing of a file system object is
dependent on the structure of its path.
Relationships
Nature Type ID Name Page
ChildOf 66 Improper Handling of File Names that Identify Virtual 699 69
Resources 1000
ChildOf 70 Mac Virtual File Problems 631 73
699
Research Gaps
Under-studied
Theoretical Notes
This and similar problems exist because the same resource can have multiple identifiers that
dictate which behavior can be performed on the resource.
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Apple HFS+ alternate data stream
References
Apple Inc.. < http://docs.info.apple.com/article.html?artnum=300422 >.

CWE-73: External Control of File Name or Path


Weakness ID: 73 (Weakness Class) Status: Draft
Description
Summary
The software allows user input to control or influence paths or file names that are used in
filesystem operations.
Extended Description
This could allow an attacker to access or modify system files or other files that are critical to the
application.
Path manipulation errors occur when the following two conditions are met:
1. An attacker can specify a path used in an operation on the filesystem.
2. By specifying the resource, the attacker gains a capability that would not otherwise be
permitted.
For example, the program may give the attacker the ability to overwrite the specified file or run
with a configuration controlled by the attacker.
75
CWE Version 1.8.1
CWE-73: External Control of File Name or Path

Time of Introduction
• Architecture and Design
• Implementation
• Operation
Applicable Platforms
Languages
• All
Operating Systems
• UNIX (Often)
• Windows (Often)
• Mac OS (Often)
Common Consequences
Confidentiality
The application can operate on unexpected files. Confidentiality is violated when the targeted
filename is not directly readable by the attacker.
Integrity
CWE-73: External Control of File Name or Path

The application can operate on unexpected files. This may violate integrity if the filename is
written to, or if the filename is for a program or other form of executable code.
Availability
The application can operate on unexpected files. Availability can be violated if the attacker
specifies an unexpected file that the application modifies. Availability can also be affected if the
attacker specifies a filename for a large file, or points to a special device or a file that does not
have the format that the application expects.
Likelihood of Exploit
High to Very High
Detection Methods
Automated Static Analysis
The external control or influence of filenames can often be detected using automated static
analysis that models data flow within the software.
Automated static analysis might not be able to recognize when proper input validation is being
performed, leading to false positives - i.e., warnings that do not have any security consequences
or require any code changes.
Demonstrative Examples
Example 1:
The following code uses input from an HTTP request to create a file name. The programmer has
not considered the possibility that an attacker could provide a file name such as "../../tomcat/conf/
server.xml", which causes the application to delete one of its own configuration files (CWE-22).
Java Example: Bad Code

String rName = request.getParameter("reportName");


File rFile = new File("/usr/local/apfr/reports/" + rName);
...
rFile.delete();

Example 2:
The following code uses input from a configuration file to determine which file to open and
echo back to the user. If the program runs with privileges and malicious users can change the
configuration file, they can use the program to read any file on the system that ends with the
extension .txt.
Java Example: Bad Code

fis = new FileInputStream(cfg.getProperty("sub")+".txt");


amt = fis.read(arr);
out.println(arr);

Observed Examples

76
CWE Version 1.8.1
CWE-73: External Control of File Name or Path

Reference Description
CVE-2008-5748 Chain: external control of values for user's desired language and theme enables path
traversal.
CVE-2008-5764 Chain: external control of user's target language enables remote file inclusion.
Potential Mitigations
Architecture and Design
When the set of filenames is limited or known, create a mapping from a set of fixed input
values (such as numeric IDs) to the actual filenames, and reject all other inputs. For example,
ID 1 could map to "inbox.txt" and ID 2 could map to "profile.txt". Features such as the ESAPI
AccessReferenceMap provide this capability.
Architecture and Design
Operation
Run your code in a "jail" or similar sandbox environment that enforces strict boundaries between
the process and the operating system. This may effectively restrict all access to files within a
particular directory.
Examples include the Unix chroot jail and AppArmor. In general, managed code may provide
some protection.

CWE-73: External Control of File Name or Path


This may not be a feasible solution, and it only limits the impact to the operating system; the rest
of your application may still be subject to compromise.
Be careful to avoid CWE-243 and other weaknesses related to jails.
Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are
duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side
checks by modifying values after the checks have been performed, or by changing the client to
remove the client-side checks entirely. Then, these modified values would be submitted to the
server.
Implementation
Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a
whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not
strictly conform to specifications, or transform it into something that does. Do not rely exclusively
on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). However, blacklists
can be useful for detecting potential attacks or determining which inputs are so malformed that
they should be rejected outright.
When performing input validation, consider all potentially relevant properties, including length,
type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency
across related fields, and conformance to business rules. As an example of business rule logic,
"boat" may be syntactically valid because it only contains alphanumeric characters, but it is not
valid if you are expecting colors such as "red" or "blue."
For filenames, use stringent whitelists that limit the character set to be used. If feasible, only
allow a single "." character in the filename to avoid weaknesses such as CWE-23, and exclude
directory separators such as "/" to avoid CWE-36. Use a whitelist of allowable file extensions,
which will help to avoid CWE-434.
Implementation
Use a built-in path canonicalization function (such as realpath() in C) that produces the canonical
version of the pathname, which effectively removes ".." sequences and symbolic links (CWE-23,
CWE-59).
Installation
Operation
Use OS-level permissions and run as a low-privileged user to limit the scope of any successful
attack.

77
CWE Version 1.8.1
CWE-73: External Control of File Name or Path

Operation
Implementation
If you are using PHP, configure your application so that it does not use register_globals. During
implementation, develop your application so that it does not rely on this feature, but be wary
of implementing a register_globals emulation that is subject to weaknesses such as CWE-95,
CWE-621, and similar issues.
Testing
Use automated static analysis tools that target this type of weakness. Many modern techniques
use data flow analysis to minimize the number of false positives. This is not a perfect solution,
since 100% accuracy and coverage are not feasible.
Testing
Use dynamic tools and techniques that interact with the software using large test suites with
many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The
software's operation may slow down, but it should not become unstable, crash, or generate
incorrect results.
Testing
CWE-73: External Control of File Name or Path

Use tools and techniques that require manual (human) analysis, such as penetration testing,
threat modeling, and interactive tools that allow the tester to record and modify an active session.
These may be more effective than strictly automated techniques. This is especially the case with
weaknesses that are related to design and business rules.
Weakness Ordinalities
Primary (where the weakness exists independent of other weaknesses)
Relationships
Nature Type ID Name Page
ChildOf 20 Improper Input Validation 699 15
700
CanPrecede 22 Improper Limitation of a Pathname to a Restricted Directory 1000 24
('Path Traversal')
CanPrecede 41 Improper Resolution of Path Equivalence 1000 51
CanPrecede 59 Improper Link Resolution Before File Access ('Link Following') 1000 63
CanPrecede 98 Improper Control of Filename for Include/Require Statement 1000 129
in PHP Program ('PHP File Inclusion')
CanPrecede 434 Unrestricted Upload of File with Dangerous Type 1000 525
ChildOf 610 Externally Controlled Reference to a Resource in Another 1000 688
Sphere
ChildOf 642 External Control of Critical State Data 1000 718
ChildOf 723 OWASP Top Ten 2004 Category A2 - Broken Access Control 711 821
ChildOf 752 2009 Top 25 - Risky Resource Management 750 842
CanAlsoBe 99 Improper Control of Resource Identifiers ('Resource Injection') 1000 134

Relationship Notes
The external control of filenames can be the primary link in chains with other file-related
weaknesses, as seen in the CanPrecede relationships. This is because software systems use
files for many different purposes: to execute programs, load code libraries, to store application
data, to store configuration settings, record temporary data, act as signals or semaphores to other
processes, etc.
However, those weaknesses do not always require external control. For example, link-following
weaknesses (CWE-59) often involve pathnames that are not controllable by the attacker at all.
The external control can be resultant from other issues. For example, in PHP applications, the
register_globals setting can allow an attacker to modify variables that the programmer thought
were immutable, enabling file inclusion (CWE-98) and path traversal (CWE-22). Operating with
excessive privileges (CWE-250) might allow an attacker to specify an input filename that is not
directly readable by the attacker, but is accessible to the privileged program. A buffer overflow

78
CWE Version 1.8.1
CWE-74: Failure to Sanitize Data into a Different Plane ('Injection')

(CWE-119) might give an attacker control over nearby memory locations that are related to
pathnames, but were not directly modifiable by the attacker.
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
7 Pernicious Kingdoms Path Manipulation
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
13 Subverting Environment Variable Values
64 Using Slashes and URL Encoding Combined to Bypass Validation Logic
72 URL Encoding
76 Manipulating Input to File System Calls
78 Using Escaped Slashes in Alternate Encoding

CWE-74: Failure to Sanitize Data into a Different Plane ('Injection')


79 Using Slashes in Alternate Encoding
80 Using UTF-8 Encoding to Bypass Validation Logic
References
"OWASP Enterprise Security API (ESAPI) Project". < http://www.owasp.org/index.php/ESAPI >.

CWE-74: Failure to Sanitize Data into a Different Plane


('Injection')
Weakness ID: 74 (Weakness Class) Status: Incomplete
Description
Summary
The software fails to adequately filter user-controlled input data for syntax that has control-plane
implications.
Extended Description
Software has certain assumptions about what constitutes data and control respectively. It is the
lack of verification of these assumptions for user-controlled input that leads to injection problems.
Injection problems encompass a wide variety of issues -- all mitigated in very different ways
and usually attempted in order to alter the control flow of the process. For this reason, the most
effective way to discuss these weaknesses is to note the distinct features which classify them as
injection weaknesses. The most important issue to note is that all injection problems share one
thing in common -- i.e., they allow for the injection of control plane data into the user-controlled
data plane. This means that the execution of the process may be altered by sending code in
through legitimate data channels, using no other mechanism. While buffer overflows, and many
other flaws, involve the use of some further issue to gain execution, injection problems need only
for the data to be parsed. The most classic instantiations of this category of weakness are SQL
injection and format string vulnerabilities.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• All
Common Consequences
Confidentiality
Many injection attacks involve the disclosure of important information -- in terms of both data
sensitivity and usefulness in further exploitation
Authentication
In some cases injectable code controls authentication; this may lead to remote vulnerability
Access Control
Injection attacks are characterized by the ability to significantly change the flow of a given
process, and in some cases, to the execution of arbitrary code.

79
CWE Version 1.8.1
CWE-74: Failure to Sanitize Data into a Different Plane ('Injection')

Integrity
Data injection attacks lead to loss of data integrity in nearly all cases as the control-plane data
injected is always incidental to data recall or writing.
Accountability
Often the actions performed by injected control code are unlogged.
Likelihood of Exploit
Very High
Potential Mitigations
Requirements specification: Programming languages and supporting technologies might be
chosen which are not subject to these issues.
Implementation
Utilize an appropriate mix of white-list and black-list parsing to filter control-plane syntax from all
CWE-74: Failure to Sanitize Data into a Different Plane ('Injection')

input.
Weakness Ordinalities
Primary (where the weakness exists independent of other weaknesses)
Relationships
Nature Type ID Name Page
ChildOf 20 Improper Input Validation 699 15
ChildOf 707 Improper Enforcement of Message or Data Structure 1000 812
ChildOf 727 OWASP Top Ten 2004 Category A6 - Injection Flaws 711 823
CanFollow 20 Improper Input Validation 1000 15
ParentOf 75 Failure to Sanitize Special Elements into a Different Plane 699 81
(Special Element Injection) 1000
ParentOf 77 Improper Sanitization of Special Elements used in a 699 82
Command ('Command Injection') 1000
ParentOf 79 Failure to Preserve Web Page Structure ('Cross-site 699 92
Scripting') 1000
ParentOf 91 XML Injection (aka Blind XPath Injection) 699 119
1000
ParentOf 93 Failure to Sanitize CRLF Sequences ('CRLF Injection') 699 121
1000
ParentOf 94 Failure to Control Generation of Code ('Code Injection') 699 122
1000
ParentOf 99 Improper Control of Resource Identifiers ('Resource Injection') 699 134
1000
CanFollow 116 Improper Encoding or Escaping of Output 1000 153
ParentOf 134 Uncontrolled Format String 699 192
1000
ParentOf 138 Improper Neutralization of Special Elements 699 197

Relationship Notes
In the development view (CWE-699), this is classified as an Input Validation problem (CWE-20)
because many people do not distinguish between the consequence/attack (injection) and the
protection mechanism that prevents the attack from succeeding. In the research view (CWE-1000),
however, input validation is only one potential protection mechanism (output encoding is another),
and there is a chaining relationship between improper input validation and the failure to enforce the
structure of messsages to other components. Other issues not directly related to input validation,
such as race conditions, could similarly impact message structure.
Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Node ID Fit Mapped Node Name
CLASP Injection problem ('data' used as something
else)
OWASP Top Ten 2004 A6 CWE More Specific Injection Flaws

80
CWE Version 1.8.1
CWE-75: Failure to Sanitize Special Elements into a Different Plane (Special Element Injection)

Related Attack Patterns


CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
3 Using Leading 'Ghost' Character Sequences to Bypass Input Filters
7 Blind SQL Injection
8 Buffer Overflow in an API Call
9 Buffer Overflow in Local Command-Line Utilities
10 Buffer Overflow via Environment Variables
13 Subverting Environment Variable Values
14 Client-side Injection-induced Buffer Overflow
24 Filter Failure through Buffer Overflow
28 Fuzzing
34 HTTP Response Splitting
40 Manipulating Writeable Terminal Devices
42 MIME Conversion
43 Exploiting Multiple Input Interpretation Layers
45 Buffer Overflow via Symbolic Links
46 Overflow Variables and Tags
47 Buffer Overflow via Parameter Expansion

into a Different Plane (Special Element Injection)


CWE-75: Failure to Sanitize Special Elements
51 Poison Web Service Registry
52 Embedding NULL Bytes
53 Postfix, Null Terminate, and Backslash
64 Using Slashes and URL Encoding Combined to Bypass Validation Logic
66 SQL Injection
67 String Format Overflow in syslog()
71 Using Unicode Encoding to Bypass Validation Logic
72 URL Encoding
76 Manipulating Input to File System Calls
78 Using Escaped Slashes in Alternate Encoding
79 Using Slashes in Alternate Encoding
80 Using UTF-8 Encoding to Bypass Validation Logic
83 XPath Injection
84 XQuery Injection
91 XSS in IMG Tags
101 Server Side Include (SSI) Injection
106 Cross Site Scripting through Log Files
108 Command Line Execution through SQL Injection
273 HTTP Response Smuggling

CWE-75: Failure to Sanitize Special Elements into a


Different Plane (Special Element Injection)
Weakness ID: 75 (Weakness Class) Status: Draft
Description
Summary
The software fails to adequately filter user-controlled input for special elements with control
implications.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• All
Potential Mitigations
Requirements specification: Programming languages and supporting technologies might be
chosen which are not subject to these issues.

81
CWE Version 1.8.1
CWE-76: Failure to Resolve Equivalent Special Elements into a Different Plane

Implementation
Utilize an appropriate mix of white-list and black-list parsing to filter special element syntax from
all input.
Relationships
Nature Type ID Name Page
ChildOf 74 Failure to Sanitize Data into a Different Plane ('Injection') 699 79
1000
ParentOf 76 Failure to Resolve Equivalent Special Elements into a 699 82
Different Plane 1000
CWE-76: Failure to Resolve Equivalent Special Elements into a Different Plane

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Special Element Injection

CWE-76: Failure to Resolve Equivalent Special Elements


into a Different Plane
Weakness ID: 76 (Weakness Base) Status: Draft
Description
Summary
The software fails to adequately filter non-typical special elements that are equivalent to control-
relevant special elements that are already being filtered. This can also include encoded special
characters.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• All
Likelihood of Exploit
High to Very High
Potential Mitigations
Requirements specification: Programming languages and supporting technologies might be
chosen which are not subject to these issues.
Implementation
Utilize an appropriate mix of white-list and black-list parsing to filter equivalent special element
syntax from all input.
Weakness Ordinalities
Primary (where the weakness exists independent of other weaknesses)
Relationships
Nature Type ID Name Page
ChildOf 75 Failure to Sanitize Special Elements into a Different Plane 699 81
(Special Element Injection) 1000
Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Equivalent Special Element Injection

CWE-77: Improper Sanitization of Special Elements used in


a Command ('Command Injection')
Weakness ID: 77 (Weakness Class) Status: Draft
Description
82
CWE Version 1.8.1
CWE-77: Improper Sanitization of Special Elements used in a Command ('Command Injection')

Summary
The software constructs all or part of a command using externally-influenced input from an
upstream component, but it does not sanitize or incorrectly sanitizes special elements that could
modify the intended command when it is sent to a downstream component.
Extended Description
Command injection vulnerabilities typically occur when:
1. Data enters the application from an untrusted source.
2. The data is part of a string that is executed as a command by the application.
3. By executing the command, the application gives an attacker a privilege or capability that the
attacker would not otherwise have.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages

CWE-77: Improper Sanitization of Special Elements


• All
Common Consequences

used in a Command ('Command Injection')


Access Control
Command injection allows for the execution of arbitrary commands and code by the attacker.
Integrity
If a malicious user injects a character (such as a semi-colon) that delimits the end of one
command and the beginning of another, it may be possible to then insert an entirely new and
unrelated command that was not intended to be executed.
Likelihood of Exploit
Very High
Demonstrative Examples
Example 1:
The following simple program accepts a filename as a command line argument and displays the
contents of the file back to the user. The program is installed setuid root because it is intended for
use as a learning tool to allow system administrators in-training to inspect privileged system files
without giving them the ability to modify them or damage the system.
C Example:
int main(char* argc, char** argv) {
char cmd[CMD_MAX] = "/usr/bin/cat ";
strcat(cmd, argv[1]);
system(cmd);
}

Because the program runs with root privileges, the call to system() also executes with root
privileges. If a user specifies a standard filename, the call works as expected. However, if an
attacker passes a string of the form ";rm -rf /", then the call to system() fails to execute cat due to a
lack of arguments and then plows on to recursively delete the contents of the root partition.
Example 2:
The following code is from an administrative web application designed to allow users to kick
off a backup of an Oracle database using a batch-file wrapper around the rman utility and then
run a cleanup.bat script to delete some temporary files. The script rmanDB.bat accepts a single
command line parameter, which specifies what type of backup to perform. Because access to the
database is restricted, the application runs the backup as a privileged user.
Java Example: Bad Code

...
String btype = request.getParameter("backuptype");
String cmd = new String("cmd.exe /K \"
c:\\util\\rmanDB.bat "
+btype+

83
CWE Version 1.8.1
CWE-77: Improper Sanitization of Special Elements used in a Command ('Command Injection')

"&&c:\\utl\\cleanup.bat\"")
System.Runtime.getRuntime().exec(cmd);
...

The problem here is that the program does not do any validation on the backuptype parameter
read from the user. Typically the Runtime.exec() function will not execute multiple commands,
but in this case the program first runs the cmd.exe shell in order to run multiple commands with a
single call to Runtime.exec(). Once the shell is invoked, it will happily execute multiple commands
separated by two ampersands. If an attacker passes a string of the form "& del c:\\dbms\\*.*", then
the application will execute this command along with the others specified by the program. Because
of the nature of the application, it runs with the privileges necessary to interact with the database,
which means whatever command the attacker injects will run with those privileges as well.
Example 3:
The following code from a system utility uses the system property APPHOME to determine the
directory in which it is installed and then executes an initialization script based on a relative path
from the specified directory.
Java Example:
CWE-77: Improper Sanitization of Special Elements

Bad Code

...
used in a Command ('Command Injection')

String home = System.getProperty("APPHOME");


String cmd = home + INITCMD;
java.lang.Runtime.getRuntime().exec(cmd);
...

The code above allows an attacker to execute arbitrary commands with the elevated privilege of
the application by modifying the system property APPHOME to point to a different path containing
a malicious version of INITCMD. Because the program does not validate the value read from the
environment, if an attacker can control the value of the system property APPHOME, then they can
fool the application into running malicious code and take control of the system.
Example 4:
The following code is from a web application that allows users access to an interface through
which they can update their password on the system. Part of the process for updating passwords
in certain network environments is to run a make command in the /var/yp directory, the code for
which is shown below.
Java Example: Bad Code

...
System.Runtime.getRuntime().exec("make");
...

The problem here is that the program does not specify an absolute path for make and fails to clean
its environment prior to executing the call to Runtime.exec(). If an attacker can modify the $PATH
variable to point to a malicious binary called make and cause the program to be executed in their
environment, then the malicious binary will be loaded instead of the one intended. Because of
the nature of the application, it runs with the privileges necessary to perform system operations,
which means the attacker's make will now be run with these privileges, possibly giving the attacker
complete control of the system.
Example 5:
The following code is a wrapper around the UNIX command cat which prints the contents of a file
to standard out. It is also injectable:
C Example: Bad Code

#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv) {
char cat[] = "cat ";
char *command;
size_t commandLength;
commandLength = strlen(cat) + strlen(argv[1]) + 1;
command = (char *) malloc(commandLength);
strncpy(command, cat, commandLength);

84
CWE Version 1.8.1
CWE-77: Improper Sanitization of Special Elements used in a Command ('Command Injection')

strncat(command, argv[1], (commandLength - strlen(cat)) );


system(command);
return (0);
}

Used normally, the output is simply the contents of the file requested:
$ ./catWrapper Story.txt
When last we left our heroes...

However, if we add a semicolon and another command to the end of this line, the command is
executed by catWrapper with no complaint:
Attack

$ ./catWrapper Story.txt; ls
When last we left our heroes...
Story.txt
SensitiveFile.txt
PrivateData.db
a.out*

CWE-77: Improper Sanitization of Special Elements


If catWrapper had been set to have a higher privilege level than the standard user, arbitrary
commands could be executed with that higher privilege.

used in a Command ('Command Injection')


Potential Mitigations
Architecture and Design
If at all possible, use library calls rather than external processes to recreate the desired
functionality
Implementation
If possible, ensure that all external commands called from the program are statically created.
Implementation
Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a
whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not
strictly conform to specifications, or transform it into something that does. Do not rely exclusively
on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). However, blacklists
can be useful for detecting potential attacks or determining which inputs are so malformed that
they should be rejected outright.
When performing input validation, consider all potentially relevant properties, including length,
type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency
across related fields, and conformance to business rules. As an example of business rule logic,
"boat" may be syntactically valid because it only contains alphanumeric characters, but it is not
valid if you are expecting colors such as "red" or "blue."
Run time: Run time policy enforcement may be used in a white-list fashion to prevent use of any
non-sanctioned commands.
Assign permissions to the software system that prevents the user from accessing/opening
privileged files.
Other Notes
Command injection is a common problem with wrapper programs.
Weakness Ordinalities
Primary (where the weakness exists independent of other weaknesses)
Relationships
Nature Type ID Name Page
ChildOf 20 Improper Input Validation 700 15
ChildOf 74 Failure to Sanitize Data into a Different Plane ('Injection') 699 79
1000
ChildOf 713 OWASP Top Ten 2007 Category A2 - Injection Flaws 629 816
ChildOf 722 OWASP Top Ten 2004 Category A1 - Unvalidated Input 711 820
ChildOf 727 OWASP Top Ten 2004 Category A6 - Injection Flaws 711 823

85
CWE Version 1.8.1
CWE-78: Improper Sanitization of Special Elements used in an OS Command ('OS Command
Injection')

Nature Type ID Name Page


ParentOf 78 Improper Sanitization of Special Elements used in an OS 699 86
Command ('OS Command Injection') 1000
ParentOf 88 Argument Injection or Modification 699 108
1000
ParentOf 89 Improper Sanitization of Special Elements used in an SQL 699 111
Command ('SQL Injection') 1000
ParentOf 90 Failure to Sanitize Data into LDAP Queries ('LDAP Injection') 699 119
1000
ParentOf 624 Executable Regular Expression Error 699 700
1000
Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Node ID Fit Mapped Node Name
7 Pernicious Kingdoms Command Injection
CWE-78: Improper Sanitization of Special Elements
used in an OS Command ('OS Command Injection')

CLASP Command injection


OWASP Top Ten 2007 A2 CWE More Specific Injection Flaws
OWASP Top Ten 2004 A1 CWE More Specific Unvalidated Input
OWASP Top Ten 2004 A6 CWE More Specific Injection Flaws
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
6 Argument Injection
11 Cause Web Server Misclassification
15 Command Delimiters
23 File System Function Injection, Content Based
43 Exploiting Multiple Input Interpretation Layers
75 Manipulating Writeable Configuration Files
76 Manipulating Input to File System Calls
References
G. Hoglund and G. McGraw. "Exploiting Software: How to Break Code". Addison-Wesley. February
2004.

CWE-78: Improper Sanitization of Special Elements used in


an OS Command ('OS Command Injection')
Weakness ID: 78 (Weakness Base) Status: Draft
Description
Summary
The software constructs all or part of an OS command using externally-influenced input from an
upstream component, but it does not sanitize or incorrectly sanitizes special elements that could
modify the intended OS command when it is sent to a downstream component.
Extended Description
This could allow attackers to execute unexpected, dangerous commands directly on the operating
system. This weakness can lead to a vulnerability in environments in which the attacker does
not have direct access to the operating system, such as in web applications. Alternately, if
the weakness occurs in a privileged program, it could allow the attacker to specify commands
that normally would not be accessible, or to call alternate commands with privileges that the
attacker does not have. The problem is exacerbated if the compromised process fails to follow
the principle of least privilege, because the attacker-controlled commands may run with special
system privileges that increases the amount of damage.
There are at least two subtypes of OS command injection:
1) The application intends to execute a single, fixed program that is under its own control.
It intends to use externally-supplied inputs as arguments to that program. For example, the
program might use system("nslookup [HOSTNAME]") to run nslookup and allow the user to
86
CWE Version 1.8.1
CWE-78: Improper Sanitization of Special Elements used in an OS Command ('OS Command
Injection')

supply a HOSTNAME, which is used as an argument. Attackers cannot prevent nslookup from
executing. However, if the program does not remove command separators from the HOSTNAME
argument, attackers could place the separators into the arguments, which allows them to
execute their own program after nslookup has finished executing.
2) The application accepts an input that it uses to fully select which program to run, as well as
which commands to use. The application simply redirects this entire command to the operating
system. For example, the program might use "exec([COMMAND])" to execute the [COMMAND]
that was supplied by the user. If the COMMAND is under attacker control, then the attacker can
execute arbitrary commands or programs. If the command is being executed using functions
like exec() and CreateProcess(), the attacker might not be able to combine multiple commands
together in the same line.
From a weakness standpoint, these variants represent distinct programmer errors. In the first
variant, the programmer clearly intends that input from untrusted parties will be part of the
arguments in the command to be executed. In the second variant, the programmer does not
intend for the command to be accessible to any untrusted party, but the programmer probably has
not accounted for alternate ways in which malicious attackers can provide input.

CWE-78: Improper Sanitization of Special Elements


used in an OS Command ('OS Command Injection')
Alternate Terms
Shell injection
Shell metacharacters
Terminology Notes
The "OS command injection" phrase carries different meanings to different people. For some,
it refers to any type of attack that can allow the attacker to execute OS commands of his or her
choosing. This usage could include untrusted search path weaknesses (CWE-426) that cause
the application to find and execute an attacker-controlled program. For others, it only refers
to the first variant, in which the attacker injects command separators into arguments for an
application-controlled program that is being invoked. Further complicating the issue is the case
when argument injection (CWE-88) allows alternate command-line switches or options to be
inserted into the command line, such as an "-exec" switch whose purpose may be to execute the
subsequent argument as a command (this -exec switch exists in the UNIX "find" command, for
example). In this latter case, however, CWE-88 could be regarded as the primary weakness in a
chain with CWE-78.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• All
Common Consequences
Confidentiality
Integrity
Availability
Non-Repudiation
Attackers could execute unauthorized commands, which could then be used to disable the
software, or read and modify data for which the attacker does not have permissions to access
directly. Since the targeted application is directly executing the commands instead of the attacker,
any malicious activities may appear to come from the application or the application's owner.
Likelihood of Exploit
High
Detection Methods

87
CWE Version 1.8.1
CWE-78: Improper Sanitization of Special Elements used in an OS Command ('OS Command
Injection')

Automated Static Analysis


This weakness can often be detected using automated static analysis tools. Many modern tools
use data flow analysis or constraint-based techniques to minimize the number of false positives.
Automated static analysis might not be able to recognize when proper input validation is being
performed, leading to false positives - i.e., warnings that do not have any security consequences
or require any code changes.
Automated static analysis might not be able to detect the usage of custom API functions or third-
party libraries that indirectly invoke OS commands, leading to false negatives - especially if the
API/library code is not available for analysis.
Manual Static Analysis
High
Since this weakness does not typically appear frequently within a single software package,
manual white box techniques may be able to provide sufficient code coverage and reduction
of false positives if all potentially-vulnerable operations can be assessed within limited time
constraints.
CWE-78: Improper Sanitization of Special Elements
used in an OS Command ('OS Command Injection')

Demonstrative Examples
Example 1:
This example is a web application that intends to perform a DNS lookup of a user-supplied domain
name. It is subject to the first variant of OS command injection.
Perl Example: Bad Code

use CGI qw(:standard);


$name = param('name');
$nslookup = "/path/to/nslookup";
print header;
if (open($fh, "$nslookup $name|")) {
while (<$fh>) {
print escapeHTML($_);
print "<br>\n";
}
close($fh);
}

Suppose an attacker provides a domain name like this:


Attack

cwe.mitre.org%20%3B%20/bin/ls%20-l

The "%3B" sequence decodes to the ";" character, and the %20 decodes to a space. The open()
statement would then process a string like this:
/path/to/nslookup cwe.mitre.org ; /bin/ls -l

As a result, the attacker executes the "/bin/ls -l" command and gets a list of all the files in the
program's working directory. The input could be replaced with much more dangerous commands,
such as installing a malicious program on the server.
Example 2:
The example below reads the name of a shell script to execute from the system properties. It is
subject to the second variant of OS command injection.
Java Example: Bad Code

String script = System.getProperty("SCRIPTNAME");


if (script != null)
System.exec(script);

If an attacker has control over this property, then he or she could modify the property to point to a
dangerous program.
Observed Examples
Reference Description
CVE-1999-0067 Canonical example. CGI program does not sanitize "|" metacharacter when invoking a
phonebook program.

88
CWE Version 1.8.1
CWE-78: Improper Sanitization of Special Elements used in an OS Command ('OS Command
Injection')

Reference Description
CVE-2001-1246 Language interpreter's mail function accepts another argument that is concatenated
to a string used in a dangerous popen() call. Since there is no sanitization against this
argument, both OS Command Injection (CWE-78) and Argument Injection (CWE-88) are
possible.
CVE-2002-0061 Web server allows command execution using "|" (pipe) character.
CVE-2002-1898 Shell metacharacters in a telnet:// link are not properly handled when the launching
application processes the link.
CVE-2003-0041 FTP client does not filter "|" from filenames returned by the server, allowing for OS
command injection.
CVE-2007-3572 Chain: incomplete blacklist for OS command injection
CVE-2008-2575 Shell metacharacters in a filename in a ZIP archive
CVE-2008-4304 OS command injection through environment variable.
CVE-2008-4796 OS command injection through https:// URLs
Potential Mitigations
Architecture and Design

CWE-78: Improper Sanitization of Special Elements


If at all possible, use library calls rather than external processes to recreate the desired

used in an OS Command ('OS Command Injection')


functionality.
Architecture and Design
Operation
Sandbox or Jail
Run your code in a "jail" or similar sandbox environment that enforces strict boundaries between
the process and the operating system. This may effectively restrict which commands can be
executed by your software.
Examples include the Unix chroot jail and AppArmor. In general, managed code may provide
some protection.
This may not be a feasible solution, and it only limits the impact to the operating system; the rest
of your application may still be subject to compromise.
Be careful to avoid CWE-243 and other weaknesses related to jails.
Architecture and Design
For any data that will be used to generate a command to be executed, keep as much of that data
out of external control as possible. For example, in web applications, this may require storing the
command locally in the session's state instead of sending it out to the client in a hidden form field.
Architecture and Design
Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides
constructs that make this weakness easier to avoid.
For example, consider using the ESAPI Encoding control or a similar tool, library, or framework.
These will help the programmer encode outputs in a manner less prone to error.
Implementation
Properly quote arguments and escape any special characters within those arguments. If
some special characters are still needed, wrap the arguments in quotes, and escape all other
characters that do not pass a strict whitelist. Be careful of argument injection (CWE-88).
Implementation
If the program to be executed allows arguments to be specified within an input file or from
standard input, then consider using that mode to pass arguments instead of the command line.

89
CWE Version 1.8.1
CWE-78: Improper Sanitization of Special Elements used in an OS Command ('OS Command
Injection')

Implementation
If available, use structured mechanisms that automatically enforce the separation between
data and code. These mechanisms may be able to provide the relevant quoting, encoding, and
validation automatically, instead of relying on the developer to provide this capability at every
point where output is generated.
Some languages offer multiple functions that can be used to invoke commands. Where possible,
identify any function that invokes a command shell using a single string, and replace it with a
function that requires individual arguments. These functions typically perform appropriate quoting
and filtering of arguments. For example, in C, the system() function accepts a string that contains
the entire command to be executed, whereas execl(), execve(), and others require an array of
strings, one for each argument. In Windows, CreateProcess() only accepts one command at a
time. In Perl, if system() is provided with an array of arguments, then it will quote each of the
arguments.
Implementation
Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a
CWE-78: Improper Sanitization of Special Elements
used in an OS Command ('OS Command Injection')

whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not
strictly conform to specifications, or transform it into something that does. Do not rely exclusively
on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). However, blacklists
can be useful for detecting potential attacks or determining which inputs are so malformed that
they should be rejected outright.
When performing input validation, consider all potentially relevant properties, including length,
type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency
across related fields, and conformance to business rules. As an example of business rule logic,
"boat" may be syntactically valid because it only contains alphanumeric characters, but it is not
valid if you are expecting colors such as "red" or "blue."
When constructing OS command strings, use stringent whitelists that limit the character set based
on the expected value of the parameter in the request. This will indirectly limit the scope of an
attack, but this technique is less important than proper output encoding and escaping.
Note that proper output encoding, escaping, and quoting is the most effective solution for
preventing OS command injection, although input validation may provide some defense-in-depth.
This is because it effectively limits what will appear in output. Input validation will not always
prevent OS command injection, especially if you are required to support free-form text fields
that could contain arbitrary characters. For example, when invoking a mail program, you might
need to allow the subject field to contain otherwise-dangerous inputs like ";" and ">" characters,
which would need to be escaped or otherwise handled. In this case, stripping the character
might reduce the risk of OS command injection, but it would produce incorrect behavior because
the subject field would not be recorded as the user intended. This might seem to be a minor
inconvenience, but it could be more important when the program relies on well-structured subject
lines in order to pass messages to other components.
Even if you make a mistake in your validation (such as forgetting one out of 100 input fields),
appropriate encoding is still likely to protect you from injection-based attacks. As long as it is not
done in isolation, input validation is still a useful technique, since it may significantly reduce your
attack surface, allow you to detect some attacks, and provide other security benefits that proper
encoding does not address.
Testing
Implementation
Use automated static analysis tools that target this type of weakness. Many modern techniques
use data flow analysis to minimize the number of false positives. This is not a perfect solution,
since 100% accuracy and coverage are not feasible.

90
CWE Version 1.8.1
CWE-78: Improper Sanitization of Special Elements used in an OS Command ('OS Command
Injection')

Testing
Use dynamic tools and techniques that interact with the software using large test suites with
many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The
software's operation may slow down, but it should not become unstable, crash, or generate
incorrect results.
Operation
Run the code in an environment that performs automatic taint propagation and prevents any
command execution that uses tainted variables, such as Perl's "-T" switch. This will force you to
perform validation steps that remove the taint, although you must be careful to correctly validate
your inputs so that you do not accidentally mark dangerous inputs as untainted (see CWE-183
and CWE-184).
Operation
Use runtime policy enforcement to create a whitelist of allowable commands, then prevent use of
any command that does not appear in the whitelist. Technologies such as AppArmor are available
to do this.

CWE-78: Improper Sanitization of Special Elements


used in an OS Command ('OS Command Injection')
System Configuration
Assign permissions to the software system that prevent the user from accessing/opening
privileged files. Run the application with the lowest privileges possible (CWE-250).
Relationships
Nature Type ID Name Page
ChildOf 77 Improper Sanitization of Special Elements used in a 699 82
Command ('Command Injection') 1000
CanAlsoBe 88 Argument Injection or Modification 1000 108
ChildOf 634 Weaknesses that Affect System Processes 631 708
ChildOf 714 OWASP Top Ten 2007 Category A3 - Malicious File 629 817
Execution
ChildOf 727 OWASP Top Ten 2004 Category A6 - Injection Flaws 711 823
ChildOf 741 CERT C Secure Coding Section 07 - Characters and Strings 734 835
(STR)
ChildOf 744 CERT C Secure Coding Section 10 - Environment (ENV) 734 837
ChildOf 751 2009 Top 25 - Insecure Interaction Between Components 750 842
ChildOf 801 2010 Top 25 - Insecure Interaction Between Components 800 903
CanFollow 184 Incomplete Blacklist 1000 243
MemberOf 630 Weaknesses Examined by SAMATE 630 705
MemberOf 635 Weaknesses Used by NVD 635 708

Research Gaps
More investigation is needed into the distinction between the OS command injection variants,
including the role with argument injection (CWE-88). Equivalent distinctions may exist in other
injection-related problems such as SQL injection.
Affected Resources
• System Process
Functional Areas
• Program invocation
Taxonomy Mappings
Mapped Taxonomy Name Node ID Fit Mapped Node Name
PLOVER OS Command Injection
OWASP Top Ten 2007 A3 CWE More Specific Malicious File Execution
OWASP Top Ten 2004 A6 CWE More Specific Injection Flaws
CERT C Secure Coding ENV03-C Sanitize the environment when invoking
external programs
CERT C Secure Coding ENV04-C Do not call system() if you do not need a
command processor
CERT C Secure Coding STR02-C Sanitize data passed to complex
subsystems

91
CWE Version 1.8.1
CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting')

Mapped Taxonomy Name Node ID Fit Mapped Node Name


WASC 31 OS Commanding
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
6 Argument Injection
15 Command Delimiters
43 Exploiting Multiple Input Interpretation Layers
88 OS Command Injection
108 Command Line Execution through SQL Injection
White Box Definitions
A weakness where the code path has:
CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting')

1. start statement that accepts input


2. end statement that executes an operating system command where
a. the input is used as a part of the operating system command and
b. the operating system command is undesirable
Where "undesirable" is defined through the following scenarios:
1. not validated
2. incorrectly validated
References
G. Hoglund and G. McGraw. "Exploiting Software: How to Break Code". Addison-Wesley. 2004-02.
Pascal Meunier. "Meta-Character Vulnerabilities". 2008-02-20. < http://www.cs.purdue.edu/homes/
cs390s/slides/week09.pdf >.
Robert Auger. "OS Commanding". 2009-06. < http://projects.webappsec.org/OS-Commanding >.
Lincoln Stein and John Stewart. "The World Wide Web Security FAQ". chapter: "CGI Scripts".
2002-02-04. < http://www.w3.org/Security/Faq/wwwsf4.html >.
Jordan Dimov, Cigital. "Security Issues in Perl Scripts". < http://www.cgisecurity.com/lib/sips.html
>.
[REF-17] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software Security".
"Sin 10: Command Injection." Page 171. McGraw-Hill. 2010.

CWE-79: Failure to Preserve Web Page Structure ('Cross-


site Scripting')
Weakness ID: 79 (Weakness Base) Status: Usable
Description
Summary
The software does not sufficiently validate, filter, escape, and/or encode user-controllable input
before it is placed in output that is used as a web page that is served to other users.
Extended Description
Cross-site scripting (XSS) vulnerabilities occur when:
1. Untrusted data enters a web application, typically from a web request.
2. The web application dynamically generates a web page that contains this untrusted data.
3. During page generation, the application does not prevent the data from containing content
that is executable by a web browser, such as JavaScript, HTML tags, HTML attributes, mouse
events, Flash, ActiveX, etc.
4. A victim visits the generated web page through a web browser, which contains malicious
script that was injected using the untrusted data.
5. Since the script comes from a web page that was sent by the web server, the victim's web
browser executes the malicious script in the context of the web server's domain.
6. This effectively violates the intention of the web browser's same-origin policy, which states
that scripts in one domain should not be able to access resources or run code in a different
domain.
There are three main kinds of XSS:
92
CWE Version 1.8.1
CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting')

The server reads data directly from the HTTP request and reflects it back in the HTTP response.
Reflected XSS exploits occur when an attacker causes a victim to supply dangerous content
to a vulnerable web application, which is then reflected back to the victim and executed by the
web browser. The most common mechanism for delivering malicious content is to include it as
a parameter in a URL that is posted publicly or e-mailed directly to the victim. URLs constructed
in this manner constitute the core of many phishing schemes, whereby an attacker convinces a
victim to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content
back to the victim, the content is executed by the victim's browser.
The application stores dangerous data in a database, message forum, visitor log, or other
trusted data store. At a later time, the dangerous data is subsequently read back into the
application and included in dynamic content. From an attacker's perspective, the optimal place

CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting')


to inject malicious content is in an area that is displayed to either many users or particularly
interesting users. Interesting users typically have elevated privileges in the application or interact
with sensitive data that is valuable to the attacker. If one of these users executes malicious
content, the attacker may be able to perform privileged operations on behalf of the user or gain
access to sensitive data belonging to the user. For example, the attacker might inject XSS into a
log message, which might not be handled properly when an administrator views the logs.
In DOM-based XSS, the client performs the injection of XSS into the page; in the other types,
the server performs the injection. DOM-based XSS generally involves server-controlled, trusted
script that is sent to the client, such as Javascript that performs sanity checks on a form before
the user submits it. If the server-supplied script processes user-supplied data and then injects it
back into the web page (such as with dynamic HTML), then DOM-based XSS is possible.
Once the malicious script is injected, the attacker can perform a variety of malicious activities. The
attacker could transfer private information, such as cookies that may include session information,
from the victim's machine to the attacker. The attacker could send malicious requests to a web
site on behalf of the victim, which could be especially dangerous to the site if the victim has
administrator privileges to manage that site. Phishing attacks could be used to emulate trusted
web sites and trick the victim into entering a password, allowing the attacker to compromise the
victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser
itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking."
In many cases, the attack can be launched without the victim even being aware of it. Even with
careful users, attackers frequently use a variety of methods to encode the malicious portion of the
attack, such as URL encoding or Unicode, so the request looks less suspicious.
Alternate Terms
XSS
CSS
"CSS" was once used as the acronym for this problem, but this could cause confusion with
"Cascading Style Sheets," so usage of this acronym has declined significantly.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• Language-independent
Architectural Paradigms
• Web-based (Often)
Technology Classes
• Web-Server (Often)
Platform Notes
Common Consequences

93
CWE Version 1.8.1
CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting')

Confidentiality
The most common attack performed with cross-site scripting involves the disclosure of
information stored in user cookies. Typically, a malicious user will craft a client-side script, which
-- when parsed by a web browser -- performs some activity (such as sending all site cookies to a
given E-mail address). This script will be loaded and run by each user visiting the web site. Since
the site requesting to run the script has access to the cookies in question, the malicious script
does also.
Access Control
In some circumstances it may be possible to run arbitrary code on a victim's computer when
cross-site scripting is combined with other flaws.
Confidentiality
CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting')

Integrity
Availability
The consequence of an XSS attack is the same regardless of whether it is stored or reflected.
The difference is in how the payload arrives at the server.
XSS can cause a variety of problems for the end user that range in severity from an annoyance
to complete account compromise. Some cross-site scripting vulnerabilities can be exploited
to manipulate or steal cookies, create requests that can be mistaken for those of a valid user,
compromise confidential information, or execute malicious code on the end user systems for
a variety of nefarious purposes. Other damaging attacks include the disclosure of end user
files, installation of Trojan horse programs, redirecting the user to some other page or site,
running "Active X" controls (under Microsoft Internet Explorer) from sites that a user perceives as
trustworthy, and modifying presentation of content.
Likelihood of Exploit
High to Very High
Enabling Factors for Exploitation
Cross-site scripting attacks may occur anywhere that possibly malicious users are allowed to post
unregulated material to a trusted web site for the consumption of other valid users, commonly on
places such as bulletin-board web sites which provide web based mailing list-style functionality.
Stored XSS got its start with web sites that offered a "guestbook" to visitors. Attackers would
include JavaScript in their guestbook entries, and all subsequent visitors to the guestbook page
would execute the malicious code. As the examples demonstrate, XSS vulnerabilities are caused
by code that includes unvalidated data in an HTTP response.
Detection Methods
Automated Static Analysis
Moderate
Use automated static analysis tools that target this type of weakness. Many modern techniques
use data flow analysis to minimize the number of false positives. This is not a perfect solution,
since 100% accuracy and coverage are not feasible, especially when multiple components are
involved.
Black Box
Moderate
Use the XSS Cheat Sheet [REF-14] or automated test-generation tools to help launch a wide
variety of attacks against your web application. The Cheat Sheet contains many subtle XSS
variations that are specifically targeted against weak XSS defenses.
With Stored XSS, the indirection caused by the data store can make it more difficult to find the
problem. The tester must first inject the XSS string into the data store, then find the appropriate
application functionality in which the XSS string is sent to other users of the application. These
are two distinct steps in which the activation of the XSS can take place minutes, hours, or days
after the XSS was originally injected into the data store.
Demonstrative Examples
Example 1:
This example covers a Reflected XSS (Type 1) scenario.

94
CWE Version 1.8.1
CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting')

The following JSP code segment reads an employee ID, eid, from an HTTP request and displays it
to the user.
JSP Example: Bad Code

<% String eid = request.getParameter("eid"); %>


...
Employee ID: <%= eid %>

The following ASP.NET code segment reads an employee ID number from an HTTP request and
displays it to the user.
ASP.NET Example: Bad Code

...

CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting')


protected System.Web.UI.WebControls.TextBox Login;
protected System.Web.UI.WebControls.Label EmployeeID;
...
EmployeeID.Text = Login.Text;
... (HTML follows) ...
<p><asp:label id="EmployeeID" runat="server" /></p>
...

The code in this example operates correctly if the Employee ID variable contains only standard
alphanumeric text. If it has a value that includes meta-characters or source code, then the code will
be executed by the web browser as it displays the HTTP response. Initially this might not appear to
be much of a vulnerability. After all, why would someone enter a URL that causes malicious code
to run on their own computer? The real danger is that an attacker will create the malicious URL,
then use e-mail or social engineering tricks to lure victims into visiting a link to the URL. When
victims click the link, they unwittingly reflect the malicious content through the vulnerable web
application back to their own computers.
Example 2:
This example covers a Stored XSS (Type 2) scenario.
The following JSP code segment queries a database for an employee with a given ID and prints
the corresponding employee's name.
JSP Example: Bad Code

<%
...
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from emp where id="+eid);
if (rs != null) {
rs.next();
String name = rs.getString("name");
%>
Employee Name: <%= name %>

The following ASP.NET code segment queries a database for an employee with a given employee
ID and prints the name corresponding with the ID.
ASP.NET Example: Bad Code

protected System.Web.UI.WebControls.Label EmployeeName;


...
string query = "select * from emp where id=" + eid;
sda = new SqlDataAdapter(query, conn);
sda.Fill(dt);
string name = dt.Rows[0]["Name"];
...
EmployeeName.Text = name;

This code can appear less dangerous because the value of name is read from a database, whose
contents are apparently managed by the application. However, if the value of name originates from
user-supplied data, then the database can be a conduit for malicious content. Without proper input
validation on all data stored in the database, an attacker can execute malicious commands in the
user's web browser.
Observed Examples
95
CWE Version 1.8.1
CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting')

Reference Description
CVE-2006-3211 Stored XSS in a guestbook application using a javascript: URI in a bbcode img tag.
CVE-2006-3295 Chain: library file is not protected against a direct request (CWE-425), leading to reflected
XSS.
CVE-2006-3568 Stored XSS in a guestbook application.
CVE-2006-4308 Chain: only checks "javascript:" tag
CVE-2007-5727 Chain: only removes SCRIPT tags, enabling XSS
CVE-2008-0971 Stored XSS in a security product.
CVE-2008-4730 Reflected XSS not properly handled when generating an error message
CVE-2008-5080 Chain: protection mechanism failure allows XSS
CVE-2008-5249 Stored XSS using a wiki page.
CVE-2008-5734 Reflected XSS sent through email message.
CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting')

CVE-2008-5770 Reflected XSS using the PATH_INFO in a URL


Potential Mitigations
Architecture and Design
Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides
constructs that make this weakness easier to avoid.
Examples of libraries and frameworks that make it easier to generate properly encoded output
include Microsoft's Anti-XSS library, the OWASP ESAPI Encoding module, and Apache Wicket.
Implementation
Architecture and Design
Understand the context in which your data will be used and the encoding that will be expected.
This is especially important when transmitting data between different components, or when
generating outputs that can contain multiple encodings at the same time, such as web pages or
multi-part mail messages. Study all expected communication protocols and data representations
to determine the required encoding strategies.
For any data that will be output to another web page, especially any data that was received from
external inputs, use the appropriate encoding on all non-alphanumeric characters.
Parts of the same output document may require different encodings, which will vary depending on
whether the output is in the:
HTML body
Element attributes (such as src="XYZ")
URIs
JavaScript sections
Cascading Style Sheets and style property
etc. Note that HTML Entity Encoding is only appropriate for the HTML body.
Consult the XSS Prevention Cheat Sheet [REF-16] for more details on the types of encoding and
escaping that are needed.
Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are
duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side
checks by modifying values after the checks have been performed, or by changing the client to
remove the client-side checks entirely. Then, these modified values would be submitted to the
server.
Implementation
Use and specify a strong character encoding such as ISO-8859-1 or UTF-8. When an encoding
is not specified, the web browser may choose a different encoding by guessing which encoding is
actually being used by the web page. This can open you up to subtle XSS attacks related to that
encoding. See CWE-116 for more mitigations related to encoding/escaping.
Implementation
With Struts, you should write all data from form beans with the bean's filter attribute set to true.

96
CWE Version 1.8.1
CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting')

Implementation
To help mitigate XSS attacks against the user's session cookie, set the session cookie to be
HttpOnly. In browsers that support the HttpOnly feature (such as more recent versions of Internet
Explorer and Firefox), this attribute can prevent the user's session cookie from being accessible
to malicious client-side scripts that use document.cookie. This is not a complete solution, since
HttpOnly is not supported by all browsers. More importantly, XMLHTTPRequest and other
powerful browser technologies provide read access to HTTP headers, including the Set-Cookie
header in which the HttpOnly flag is set.
Implementation
Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a

CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting')


whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not
strictly conform to specifications, or transform it into something that does. Do not rely exclusively
on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). However, blacklists
can be useful for detecting potential attacks or determining which inputs are so malformed that
they should be rejected outright.
When performing input validation, consider all potentially relevant properties, including length,
type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency
across related fields, and conformance to business rules. As an example of business rule logic,
"boat" may be syntactically valid because it only contains alphanumeric characters, but it is not
valid if you are expecting colors such as "red" or "blue."
When dynamically constructing web pages, use stringent whitelists that limit the character set
based on the expected value of the parameter in the request. All input should be validated
and cleansed, not just parameters that the user is supposed to specify, but all data in the
request, including hidden fields, cookies, headers, the URL itself, and so forth. A common
mistake that leads to continuing XSS vulnerabilities is to validate only fields that are expected
to be redisplayed by the site. It is common to see data from the request that is reflected by the
application server or the application that the development team did not anticipate. Also, a field
that is not currently reflected may be used by a future developer. Therefore, validating ALL parts
of the HTTP request is recommended.
Note that proper output encoding, escaping, and quoting is the most effective solution for
preventing XSS, although input validation may provide some defense-in-depth. This is because
it effectively limits what will appear in output. Input validation will not always prevent XSS,
especially if you are required to support free-form text fields that could contain arbitrary
characters. For example, in a chat application, the heart emoticon ("<3") would likely pass
the validation step, since it is commonly used. However, it cannot be directly inserted into the
web page because it contains the "<" character, which would need to be escaped or otherwise
handled. In this case, stripping the "<" might reduce the risk of XSS, but it would produce
incorrect behavior because the emoticon would not be recorded. This might seem to be a minor
inconvenience, but it would be more important in a mathematical forum that wants to represent
inequalities.
Even if you make a mistake in your validation (such as forgetting one out of 100 input fields),
appropriate encoding is still likely to protect you from injection-based attacks. As long as it is not
done in isolation, input validation is still a useful technique, since it may significantly reduce your
attack surface, allow you to detect some attacks, and provide other security benefits that proper
encoding does not address.
Ensure that you perform input validation at well-defined interfaces within the application. This will
help protect the application even if a component is reused or moved elsewhere.
Operation
Use an application firewall that can detect attacks against this weakness. This might not catch all
attacks, and it might require some effort for customization. However, it can be beneficial in cases
in which the code cannot be fixed (because it is controlled by a third party), as an emergency
prevention measure while more comprehensive software assurance measures are applied, or to
provide defense in depth.

97
CWE Version 1.8.1
CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting')

Background Details
The same origin policy states that browsers should limit the resources accessible to scripts running
on a given web site , or "origin", to the resources associated with that web site on the client-side,
and not the client-side resources of any other sites or "origins". The goal is to prevent one site from
being able to modify or read the contents of an unrelated site. Since the World Wide Web involves
interactions between many sites, this policy is important for browsers to enforce.
The Domain of a website when referring to XSS is roughly equivalent to the resources associated
with that website on the client-side of the connection. That is, the domain can be thought of as all
resources the browser is storing for the user's interactions with this particular site.
Weakness Ordinalities
Resultant (where the weakness is typically related to the presence of some other weaknesses)
CWE-79: Failure to Preserve Web Page Structure ('Cross-site Scripting')

Relationships
Nature Type ID Name Page
ChildOf 20 Improper Input Validation 700 15
ChildOf 74 Failure to Sanitize Data into a Different Plane ('Injection') 699 79
1000
PeerOf 352 Cross-Site Request Forgery (CSRF) 1000 427
ChildOf 442 Web Problems 699 535
CanPrecede 494 Download of Code Without Integrity Check 1000 595
ChildOf 712 OWASP Top Ten 2007 Category A1 - Cross Site Scripting 629 816
(XSS)
ChildOf 722 OWASP Top Ten 2004 Category A1 - Unvalidated Input 711 820
ChildOf 725 OWASP Top Ten 2004 Category A4 - Cross-Site 711 822
Scripting (XSS) Flaws
ChildOf 751 2009 Top 25 - Insecure Interaction Between Components 750 842
ChildOf 801 2010 Top 25 - Insecure Interaction Between Components 800 903
ParentOf 80 Improper Sanitization of Script-Related HTML Tags in a 699 99
Web Page (Basic XSS) 1000
ParentOf 81 Improper Sanitization of Script in an Error Message Web 699 101
Page 1000
ParentOf 83 Improper Neutralization of Script in Attributes in a Web 699 103
Page 1000
ParentOf 84 Failure to Resolve Encoded URI Schemes in a Web Page 699 104
1000
ParentOf 85 Doubled Character XSS Manipulations 699 105
1000
ParentOf 86 Improper Neutralization of Invalid Characters in Identifiers 699 106
in Web Pages 1000
ParentOf 87 Failure to Sanitize Alternate XSS Syntax 699 107
1000
CanFollow 113 Failure to Sanitize CRLF Sequences in HTTP Headers 1000 147
('HTTP Response Splitting')
CanFollow 184 Incomplete Blacklist 1000 692 243
MemberOf 635 Weaknesses Used by NVD 635 708

Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Node ID Fit Mapped Node Name
PLOVER Cross-site scripting (XSS)
7 Pernicious Kingdoms Cross-site Scripting
CLASP Cross-site scripting
OWASP Top Ten 2007 A1 Exact Cross Site Scripting (XSS)
OWASP Top Ten 2004 A1 CWE More Specific Unvalidated Input
OWASP Top Ten 2004 A4 Exact Cross-Site Scripting (XSS) Flaws
WASC 8 Cross-site Scripting

98
CWE Version 1.8.1
CWE-80: Improper Sanitization of Script-Related HTML Tags in a Web Page (Basic XSS)

Related Attack Patterns


CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
18 Embedding Scripts in Nonscript Elements
19 Embedding Scripts within Scripts
32 Embedding Scripts in HTTP Query Strings
63 Simple Script Injection
85 Client Network Footprinting (using AJAX/XSS)
86 Embedding Script (XSS ) in HTTP Headers
91 XSS in IMG Tags
106 Cross Site Scripting through Log Files
198 Cross-Site Scripting in Error Pages
199 Cross-Site Scripting Using Alternate Syntax
209 Cross-Site Scripting Using MIME Type Mismatch
232 Exploitation of Privilege/Trust
243 Cross-Site Scripting in Attributes
244 Cross-Site Scripting via Encoded URI Schemes
245 Cross-Site Scripting Using Doubled Characters, e.g. %3C%3Cscript
246 Cross-Site Scripting Using Flash

Related HTML Tags in a Web Page (Basic XSS)


247 Cross-Site Scripting with Masking through Invalid Characters in Identifiers

CWE-80: Improper Sanitization of Script-


References
[REF-15] Jeremiah Grossman, Robert "RSnake" Hansen, Petko "pdp" D. Petkov, Anton Rager and
Seth Fogie. "XSS Attacks". Syngress. 2007.
[REF-17] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software Security".
"Sin 2: Web-Server Related Vulnerabilities (XSS, XSRF, and Response Splitting)." Page 31.
McGraw-Hill. 2010.
[REF-17] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software Security".
"Sin 3: Web-Client Related Vulnerabilities (XSS)." Page 63. McGraw-Hill. 2010.
"Cross-site scripting". Wikipedia. 2008-08-26. < http://en.wikipedia.org/wiki/Cross-site_scripting >.
[REF-11] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 13, "Web-Specific Input
Issues" Page 413. 2nd Edition. Microsoft. 2002.
[REF-14] RSnake. "XSS (Cross Site Scripting) Cheat Sheet". < http://ha.ckers.org/xss.html >.
Microsoft. "Mitigating Cross-site Scripting With HTTP-only Cookies". < http://msdn.microsoft.com/
en-us/library/ms533046.aspx >.
Mark Curphey, Microsoft. "Anti-XSS 3.0 Beta and CAT.NET Community Technology Preview now
Live!". < http://blogs.msdn.com/cisg/archive/2008/12/15/anti-xss-3-0-beta-and-cat-net-community-
technology-preview-now-live.aspx >.
"OWASP Enterprise Security API (ESAPI) Project". < http://www.owasp.org/index.php/ESAPI >.
Ivan Ristic. "XSS Defense HOWTO". < http://blog.modsecurity.org/2008/07/do-you-know-how.html
>.
OWASP. "Web Application Firewall". < http://www.owasp.org/index.php/Web_Application_Firewall
>.
Web Application Security Consortium. "Web Application Firewall Evaluation Criteria". < http://
www.webappsec.org/projects/wafec/v1/wasc-wafec-v1.0.html >.
RSnake. "Firefox Implements httpOnly And is Vulnerable to XMLHTTPRequest". 2007-07-19.
"XMLHttpRequest allows reading HTTPOnly cookies". Mozilla. < https://bugzilla.mozilla.org/
show_bug.cgi?id=380418 >.
"Apache Wicket". < http://wicket.apache.org/ >.
[REF-16] OWASP. "XSS (Cross Site Scripting) Prevention Cheat Sheet". < http://www.owasp.org/
index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet >.

CWE-80: Improper Sanitization of Script-Related HTML


Tags in a Web Page (Basic XSS)
Weakness ID: 80 (Weakness Variant) Status: Incomplete
Description

99
CWE Version 1.8.1
CWE-80: Improper Sanitization of Script-Related HTML Tags in a Web Page (Basic XSS)

Summary
The software receives input from an upstream component, but it does not sanitize or incorrectly
sanitizes special characters such as "<", ">", and "&" that could be interpreted as web-scripting
elements when they are sent to a downstream component that processes web pages.
Extended Description
This may allow such characters to be treated as control characters, which are executed client-
side in the context of the user's session. Although this can be classified as an injection problem,
the more pertinent issue is the failure to convert such special characters to respective context-
appropriate entities before displaying them to the user.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Likelihood of Exploit
High to Very High
Related HTML Tags in a Web Page (Basic XSS)

Demonstrative Examples
In the following example, a guestbook comment isn't properly sanitized for script-related tags
CWE-80: Improper Sanitization of Script-

before being displayed in a client browser.


JSP Example: Bad Code

<% for (Iterator i = guestbook.iterator(); i.hasNext(); ) {


Entry e = (Entry) i.next(); %>
<p>Entry #<%= e.getId() %></p>
<p><%= e.getText() %></p>
<%
} %>

Observed Examples
Reference Description
CVE-2002-0938 XSS in parameter in a link.
CVE-2002-1495 XSS in web-based email product via attachment filenames.
CVE-2003-1136 HTML injection in posted message.
CVE-2004-2171 XSS not quoted in error page.
Potential Mitigations
Carefully check each input parameter against a rigorous positive specification (white list)
defining the specific characters and format allowed. All input should be sanitized, not just
parameters that the user is supposed to specify, but all data in the request, including hidden fields,
cookies, headers, the URL itself, and so forth. A common mistake that leads to continuing XSS
vulnerabilities is to validate only fields that are expected to be redisplayed by the site. We often
encounter data from the request that is reflected by the application server or the application that
the development team did not anticipate. Also, a field that is not currently reflected may be used by
a future developer. Therefore, validating ALL parts of the HTTP request is recommended.
This involves "HTML Entity Encoding" all non-alphanumeric characters from data that was received
from the user and is now being written to the request.
With Struts, you should write all data from form beans with the bean's filter attribute set to true.
Additionally, to help mitigate XSS attacks against the user's session cookie, set the session cookie
to be HttpOnly. In browsers that support the HttpOnly feature (such as Internet Explorer), this
attribute prevents the user's session cookie from being accessed by client-side scripts, including
scripts inserted due to a XSS attack.
Weakness Ordinalities
Primary (where the weakness exists independent of other weaknesses)
Relationships

100
CWE Version 1.8.1
CWE-81: Improper Sanitization of Script in an Error Message Web Page

Nature Type ID Name Page


ChildOf 79 Failure to Preserve Web Page Structure ('Cross-site 699 92
Scripting') 1000
MemberOf 630 Weaknesses Examined by SAMATE 630 705

Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Basic XSS
Related Attack Patterns

CWE-81: Improper Sanitization of Script in an Error Message Web Page


CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
18 Embedding Scripts in Nonscript Elements
White Box Definitions
A weakness where the code path has:
1. start statement that accepts input from HTML page
2. end statement that publishes a data item to HTML where
a. the input is part of the data item and
b. the input contains XSS syntax

CWE-81: Improper Sanitization of Script in an Error


Message Web Page
Weakness ID: 81 (Weakness Variant) Status: Incomplete
Description
Summary
The software receives input from an upstream component, but it does not sanitize or incorrectly
sanitizes special characters that could be interpreted as web-scripting elements when they are
sent to an error page.
Extended Description
Error pages may include customized 403 Forbidden or 404 Not Found pages.
When an attacker can trigger an error that contains unsanitized input, then cross-site scripting
attacks may be possible.
Time of Introduction
• Implementation
• Operation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-2002-0840 XSS in default error page from Host: header.
CVE-2002-1053 XSS in error message.
CVE-2002-1700 XSS in error page from targeted parameter.
Potential Mitigations
Do not write user-controlled input to error pages.

101
CWE Version 1.8.1
CWE-82: Improper Sanitization of Script in Attributes of IMG Tags in a Web Page

Carefully check each input parameter against a rigorous positive specification (white list)
defining the specific characters and format allowed. All input should be sanitized, not just
parameters that the user is supposed to specify, but all data in the request, including hidden fields,
cookies, headers, the URL itself, and so forth. A common mistake that leads to continuing XSS
vulnerabilities is to validate only fields that are expected to be redisplayed by the site. We often
encounter data from the request that is reflected by the application server or the application that
the development team did not anticipate. Also, a field that is not currently reflected may be used by
a future developer. Therefore, validating ALL parts of the HTTP request is recommended.
This involves "HTML Entity Encoding" all non-alphanumeric characters from data that was received
CWE-82: Improper Sanitization of Script in Attributes of IMG Tags in a Web Page

from the user and is now being written to the request.


With Struts, you should write all data from form beans with the bean's filter attribute set to true.
Additionally, to help mitigate XSS attacks against the user's session cookie, set the session cookie
to be HttpOnly. In browsers that support the HttpOnly feature (such as Internet Explorer), this
attribute prevents the user's session cookie from being accessed by client-side scripts, including
scripts inserted due to a XSS attack.
Weakness Ordinalities
Resultant (where the weakness is typically related to the presence of some other weaknesses)
Relationships
Nature Type ID Name Page
ChildOf 79 Failure to Preserve Web Page Structure ('Cross-site 699 92
Scripting') 1000
CanAlsoBe 209 Information Exposure Through an Error Message 1000 276
CanAlsoBe 390 Detection of Error Condition Without Action 1000 474

Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER XSS in error pages
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
198 Cross-Site Scripting in Error Pages

CWE-82: Improper Sanitization of Script in Attributes of


IMG Tags in a Web Page
Weakness ID: 82 (Weakness Variant) Status: Incomplete
Description
Summary
The web application does not filter or incorrectly filters scripting elements within attributes of
HTML IMG tags, such as the src attribute.
Extended Description
Attackers can embed XSS exploits into the values for IMG attributes (e.g. SRC) that is streamed
and then executed in a victim's browser. Note that when the page is loaded into a user's
browsers, the exploit will automatically execute.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-2002-1649 javascript URI scheme in IMG tag.

102
CWE Version 1.8.1
CWE-83: Improper Neutralization of Script in Attributes in a Web Page

Reference Description
CVE-2002-1803 javascript URI scheme in IMG tag.
CVE-2002-1804 javascript URI scheme in IMG tag.
CVE-2002-1805 javascript URI scheme in IMG tag.
CVE-2002-1806 javascript URI scheme in IMG tag.
CVE-2002-1807 javascript URI scheme in IMG tag.
CVE-2002-1808 javascript URI scheme in IMG tag.
CVE-2006-3211 Stored XSS in a guestbook application using a javascript: URI in a bbcode img tag.
Potential Mitigations
see the vulnerability category "Cross-site scripting (XSS)"
Relationships

CWE-83: Improper Neutralization of Script in Attributes in a Web Page


Nature Type ID Name Page
ChildOf 83 Improper Neutralization of Script in Attributes in a Web Page 699 103
1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Script in IMG tags
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
18 Embedding Scripts in Nonscript Elements
91 XSS in IMG Tags

CWE-83: Improper Neutralization of Script in Attributes in a


Web Page
Weakness ID: 83 (Weakness Variant) Status: Draft
Description
Summary
The software does not neutralize or incorrectly neutralizes "javascript:" or other URIs from
dangerous attributes within tags, such as onmouseover, onload, onerror, or style.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-2001-0520 Bypass filtering of SCRIPT tags using onload in BODY, href in A, BUTTON, INPUT, and
others.
CVE-2002-1493 guestbook XSS in STYLE or IMG SRC attributes.
CVE-2002-1495 XSS in web-based email product via onmouseover event.
CVE-2002-1681 XSS via script in <P> tag.
CVE-2002-1965 Javascript in onerror attribute of IMG tag.
CVE-2003-1136 Javascript in onmouseover attribute in e-mail address or URL.
CVE-2004-1935 Onload, onmouseover, and other events in an e-mail attachment.
CVE-2005-0945 Onmouseover and onload events in img, link, and mail tags.
Potential Mitigations

103
CWE Version 1.8.1
CWE-84: Failure to Resolve Encoded URI Schemes in a Web Page

Carefully check each input parameter against a rigorous positive specification (white list) defining
the specific characters and format allowed. All input should be sanitized, not just parameters that
the user is supposed to specify, but all data in the request, including tag attributes, hidden fields,
cookies, headers, the URL itself, and so forth. A common mistake that leads to continuing XSS
vulnerabilities is to validate only fields that are expected to be redisplayed by the site. We often
encounter data from the request that is reflected by the application server or the application that
the development team did not anticipate. Also, a field that is not currently reflected may be used by
a future developer. Therefore, validating ALL parts of the HTTP request is recommended.
This involves "HTML Entity Encoding" all non-alphanumeric characters from data that was received
from the user and is now being written to the request.
With Struts, you should write all data from form beans with the bean's filter attribute set to true.
Additionally, to help mitigate XSS attacks against the user's session cookie, set the session cookie
CWE-84: Failure to Resolve Encoded URI Schemes in a Web Page

to be HttpOnly. In browsers that support the HttpOnly feature (such as Internet Explorer), this
attribute prevents the user's session cookie from being accessed by client-side scripts, including
scripts inserted due to a XSS attack.
Weakness Ordinalities
Primary (where the weakness exists independent of other weaknesses)
Relationships
Nature Type ID Name Page
ChildOf 79 Failure to Preserve Web Page Structure ('Cross-site 699 92
Scripting') 1000
ParentOf 82 Improper Sanitization of Script in Attributes of IMG Tags in a 699 102
Web Page 1000
Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER XSS using Script in Attributes
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
18 Embedding Scripts in Nonscript Elements
243 Cross-Site Scripting in Attributes

CWE-84: Failure to Resolve Encoded URI Schemes in a


Web Page
Weakness ID: 84 (Weakness Variant) Status: Draft
Description
Summary
The web application fails to filter user-controlled input for executable script disguised with URI
encodings.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-2002-0117 Encoded "javascript" in IMG tag.
CVE-2002-0118 Encoded "javascript" in IMG tag.
CVE-2005-0563 Cross-site scripting (XSS) vulnerability in Microsoft Outlook Web Access (OWA)
component in Exchange Server 5.5 allows remote attackers to inject arbitrary web script or

104
CWE Version 1.8.1
CWE-85: Doubled Character XSS Manipulations

Reference Description
HTML via an email message with an encoded javascript: URL ("jav&#X41sc&#0010;ript:")
in an IMG tag.
CVE-2005-0692 Encoded script within BBcode IMG tag.
CVE-2005-2276 Cross-site scripting (XSS) vulnerability in Novell Groupwise WebAccess 6.5 before July 11,
2005 allows remote attackers to inject arbitrary web script or HTML via an e-mail message
with an encoded javascript URI (e.g. "j&#X41vascript" in an IMG tag).
Potential Mitigations
Resolve all URIs to absolute or canonical representations before processing.
Carefully check each input parameter against a rigorous positive specification (white list) defining
the specific characters and format allowed. All input should be sanitized, not just parameters that
the user is supposed to specify, but all data in the request, including tag attributes, hidden fields,
cookies, headers, the URL itself, and so forth. A common mistake that leads to continuing XSS
vulnerabilities is to validate only fields that are expected to be redisplayed by the site. We often
encounter data from the request that is reflected by the application server or the application that
the development team did not anticipate. Also, a field that is not currently reflected may be used by
a future developer. Therefore, validating ALL parts of the HTTP request is recommended.

CWE-85: Doubled Character XSS Manipulations


This involves "HTML Entity Encoding" all non-alphanumeric characters from data that was received
from the user and is now being written to the request.
With Struts, you should write all data from form beans with the bean's filter attribute set to true.
Additionally, to help mitigate XSS attacks against the user's session cookie, set the session cookie
to be HttpOnly. In browsers that support the HttpOnly feature (such as Internet Explorer), this
attribute prevents the user's session cookie from being accessed by client-side scripts, including
scripts inserted due to a XSS attack.
Weakness Ordinalities
Primary (where the weakness exists independent of other weaknesses)
Relationships
Nature Type ID Name Page
ChildOf 79 Failure to Preserve Web Page Structure ('Cross-site 699 92
Scripting') 1000
Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER XSS using Script Via Encoded URI Schemes
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
18 Embedding Scripts in Nonscript Elements
32 Embedding Scripts in HTTP Query Strings
244 Cross-Site Scripting via Encoded URI Schemes

CWE-85: Doubled Character XSS Manipulations


Weakness ID: 85 (Weakness Variant) Status: Draft
Description
Summary
The web application fails to filter user-controlled input for executable script disguised using
doubling of the involved characters.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All

105
CWE Version 1.8.1
CWE-86: Improper Neutralization of Invalid Characters in Identifiers in Web Pages

Observed Examples
Reference Description
CVE-2000-0116 Encoded "javascript" in IMG tag.
CVE-2001-1157 Extra "<" in front of SCRIPT tag.
CVE-2002-2086 XSS using "<script".
Potential Mitigations
Resolve all filtered input to absolute or canonical representations before processing.
Carefully check each input parameter against a rigorous positive specification (white list) defining
CWE-86: Improper Neutralization of Invalid Characters in Identifiers in Web Pages

the specific characters and format allowed. All input should be sanitized, not just parameters that
the user is supposed to specify, but all data in the request, including tag attributes, hidden fields,
cookies, headers, the URL itself, and so forth. A common mistake that leads to continuing XSS
vulnerabilities is to validate only fields that are expected to be redisplayed by the site. We often
encounter data from the request that is reflected by the application server or the application that
the development team did not anticipate. Also, a field that is not currently reflected may be used by
a future developer. Therefore, validating ALL parts of the HTTP request is recommended.
This involves "HTML Entity Encoding" all non-alphanumeric characters from data that was received
from the user and is now being written to the request.
With Struts, you should write all data from form beans with the bean's filter attribute set to true.
Additionally, to help mitigate XSS attacks against the user's session cookie, set the session cookie
to be HttpOnly. In browsers that support the HttpOnly feature (such as Internet Explorer), this
attribute prevents the user's session cookie from being accessed by client-side scripts, including
scripts inserted due to a XSS attack.
Weakness Ordinalities
Primary (where the weakness exists independent of other weaknesses)
Relationships
Nature Type ID Name Page
ChildOf 79 Failure to Preserve Web Page Structure ('Cross-site 699 92
Scripting') 1000
PeerOf 675 Duplicate Operations on Resource 1000 759

Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER DOUBLE - Doubled character XSS manipulations, e.g. "<script"
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
32 Embedding Scripts in HTTP Query Strings
245 Cross-Site Scripting Using Doubled Characters, e.g. %3C%3Cscript

CWE-86: Improper Neutralization of Invalid Characters in


Identifiers in Web Pages
Weakness ID: 86 (Weakness Variant) Status: Draft
Description
Summary
The software does not neutralize or incorrectly neutralizes invalid characters or byte sequences in
the middle of tag names, URI schemes, and other identifiers.
Extended Description
Some web browsers may remove these sequences, resulting in output that may have unintended
control implications. For example, the software may attempt to remove a "javascript:" URI
scheme, but a "java%00script:" URI may bypass this check and still be rendered as active
javascript by some browsers, allowing XSS or other attacks.

106
CWE Version 1.8.1
CWE-87: Failure to Sanitize Alternate XSS Syntax

Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-2004-0595 XSS filter doesn't filter null characters before looking for dangerous tags, which are ignored
by web browsers. Multiple Interpretation Error (MIE) and validate-before-cleanse.
Potential Mitigations
see the vulnerability category "Cross-site scripting (XSS)"
Relationships
Nature Type ID Name Page
ChildOf 79 Failure to Preserve Web Page Structure ('Cross-site 699 92
Scripting') 1000
PeerOf 184 Incomplete Blacklist 1000 243

CWE-87: Failure to Sanitize Alternate XSS Syntax


ChildOf 436 Interpretation Conflict 1000 530

Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Invalid Characters in Identifiers
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
18 Embedding Scripts in Nonscript Elements
32 Embedding Scripts in HTTP Query Strings
63 Simple Script Injection
73 User-Controlled Filename
85 Client Network Footprinting (using AJAX/XSS)
86 Embedding Script (XSS ) in HTTP Headers
247 Cross-Site Scripting with Masking through Invalid Characters in Identifiers

CWE-87: Failure to Sanitize Alternate XSS Syntax


Weakness ID: 87 (Weakness Variant) Status: Draft
Description
Summary
The software fails to adequately filter user-controlled input for alternate script syntax.
Time of Introduction
• Implementation
Applicable Platforms
Languages
• All
Demonstrative Examples
In the following example, an XSS sanitization routine checks for the lower-case "script" string but
fails to account for alternate strings ("SCRIPT", for example).
Java Example: Bad Code

public String sanitize(String input, String mask) {


return input.replaceAll("script", mask);
}

Observed Examples
Reference Description
CVE-2002-0738 XSS using "&={script}".
Potential Mitigations
Resolve all filtered input to absolute or canonical representations before processing.
107
CWE Version 1.8.1
CWE-88: Argument Injection or Modification

Carefully check each input parameter against a rigorous positive specification (white list) defining
the specific characters and format allowed. All input should be sanitized, not just parameters that
the user is supposed to specify, but all data in the request, including tag attributes, hidden fields,
cookies, headers, the URL itself, and so forth. A common mistake that leads to continuing XSS
vulnerabilities is to validate only fields that are expected to be redisplayed by the site. We often
encounter data from the request that is reflected by the application server or the application that
the development team did not anticipate. Also, a field that is not currently reflected may be used by
a future developer. Therefore, validating ALL parts of the HTTP request is recommended.
This involves "HTML Entity Encoding" all non-alphanumeric characters from data that was received
from the user and is now being written to the request.
With Struts, you should write all data from form beans with the bean's filter attribute set to true.
Additionally, to help mitigate XSS attacks against the user's session cookie, set the session cookie
to be HttpOnly. In browsers that support the HttpOnly feature (such as Internet Explorer), this
attribute prevents the user's session cookie from being accessed by client-side scripts, including
scripts inserted due to a XSS attack.
Relationships
Nature Type ID Name Page
CWE-88: Argument Injection or Modification

ChildOf 79 Failure to Preserve Web Page Structure ('Cross-site 699 92


Scripting') 1000
Taxonomy Mappings
Mapped Taxonomy Name Mapped Node Name
PLOVER Alternate XSS syntax
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
199 Cross-Site Scripting Using Alternate Syntax

CWE-88: Argument Injection or Modification


Weakness ID: 88 (Weakness Base) Status: Draft
Description
Summary
The software does not sufficiently delimit the arguments being passed to a component in another
control sphere, allowing alternate arguments to be provided, leading to potentially security-
relevant changes.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• All
Observed Examples
Reference Description
CVE-1999-0113 Canonical Example
CVE-2001-0150
CVE-2001-0667
CVE-2001-1246 Language interpreter's mail function accepts another argument that is concatenated
to a string used in a dangerous popen() call. Since there is no sanitization against this
argument, both OS Command Injection (CWE-78) and Argument Injection (CWE-88) are
possible.
CVE-2002-0985
CVE-2003-0907
CVE-2004-0121
CVE-2004-0411 Web browser doesn't filter "-" when invoking various commands, allowing command-line
switches to be specified.

108
CWE Version 1.8.1
CWE-88: Argument Injection or Modification

Reference Description
CVE-2004-0473 Web browser doesn't filter "-" when invoking various commands, allowing command-line
switches to be specified.
CVE-2004-0480
CVE-2004-0489
CVE-2005-4699 Argument injection vulnerability in TellMe 1.2 and earlier allows remote attackers to modify
command line arguments for the Whois program and obtain sensitive information via "--"
style options in the q_Host parameter.
CVE-2006-1865 Beagle before 0.2.5 can produce certain insecure command lines to launch external
helper applications while indexing, which allows attackers to execute arbitrary commands.
NOTE: it is not immediately clear whether this issue involves argument injection, shell
metacharacters, or other issues.
CVE-2006-2056 Argument injection vulnerability in Internet Explorer 6 for Windows XP SP2 allows user-
assisted remote attackers to modify command line arguments to an invoked mail client via
" (double quote) characters in a mailto: scheme handler, as demonstrated by launching
Microsoft Outlook with an arbitrary filename as an attachment. NOTE: it is not clear
whether this issue is implementation-specific or a problem in the Microsoft API.
CVE-2006-2057 Argument injection vulnerability in Mozilla Firefox 1.0.6 allows user-assisted remote
attackers to modify command line arguments to an invoked mail client via " (double quote)

CWE-88: Argument Injection or Modification


characters in a mailto: scheme handler, as demonstrated by launching Microsoft Outlook
with an arbitrary filename as an attachment. NOTE: it is not clear whether this issue is
implementation-specific or a problem in the Microsoft API.
CVE-2006-2058 Argument injection vulnerability in Avant Browser 10.1 Build 17 allows user-assisted
remote attackers to modify command line arguments to an invoked mail client via " (double
quote) characters in a mailto: scheme handler, as demonstrated by launching Microsoft
Outlook with an arbitrary filename as an attachment. NOTE: it is not clear whether this
issue is implementation-specific or a problem in the Microsoft API.
CVE-2006-2312 Argument injection vulnerability in the URI handler in Skype 2.0.*.104 and 2.5.*.0 through
2.5.*.78 for Windows allows remote authorized attackers to download arbitrary files via a
URL that contains certain command-line switches.
CVE-2006-3015 Argument injection vulnerability in WinSCP 3.8.1 build 328 allows remote attackers to
upload or download arbitrary files via encoded spaces and double-quote characters in a
scp or sftp URI.
CVE-2006-4692 Argument injection vulnerability in the Windows Object Packager (packager.exe) in
Microsoft Windows XP SP1 and SP2 and Server 2003 SP1 and earlier allows remote
user-assisted attackers to execute arbitrary commands via a crafted file with a "/" (slash)
character in the filename of the Command Line property, followed by a valid file extension,
which causes the command before the slash to be executed, aka "Object Packager
Dialogue Spoofing Vulnerability."
CVE-2006-6597 Argument injection vulnerability in HyperAccess 8.4 allows user-assisted remote attackers
to execute arbitrary vbscript and commands via the /r option in a telnet:// URI, which is
configured to use hawin32.exe.
CVE-2007-0882 Argument injection vulnerability in the telnet daemon (in.telnetd) in Solaris 10 and 11
(SunOS 5.10 and 5.11) misinterprets certain client "-f" sequences as valid requests for
the login program to skip authentication, which allows remote attackers to log into certain
accounts, as demonstrated by the bin account.
Potential Mitigations
Architecture and Design
Input Validation
Understand all the potential areas where untrusted inputs can enter your software: parameters or
arguments, cookies, anything read from the network, environment variables, request headers as
well as content, URL components, e-mail, files, databases, and any external systems that provide
data to the application. Perform input validation at well-defined interfaces.
Architecture and Design
Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy (i.e., use
a whitelist). Reject any input that does not strictly conform to specifications, or transform it into
something that does. Use a blacklist to reject any unexpected inputs and detect potential attacks.

109
CWE Version 1.8.1
CWE-88: Argument Injection or Modification

Architecture and Design


Do not rely exclusively on blacklist validation to detect malicious input or to encode output
(CWE-184). There are too many ways to encode the same character, so you're likely to miss
some variants.
Implementation
Directly convert your input type into the expected data type, such as using a conversion function
that translates a string into a number. After converting to the expected data type, ensure that the
input's values fall within the expected range of allowable values and that multi-field consistencies
are maintained.
Implementation
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated (CWE-180, CWE-181). Make sure that your application does not
inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass
whitelist schemes by introducing dangerous inputs after they have been checked. Use libraries
such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This
will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are
CWE-88: Argument Injection or Modification

allowed to contain properly-encoded dangerous content.


Implementation
When exchanging data between components, ensure that both components are using the same
character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the
encoding you are using whenever the protocol allows you to do so.
Implementation
When your application combines data from multiple sources, perform the validation after the
sources have been combined. The individual data elements may pass the validation step but
violate the intended restrictions after they have been combined.
Testing
Use automated static analysis tools that target this type of weakness. Many modern techniques
use data flow analysis to minimize the number of false positives. This is not a perfect solution,
since 100% accuracy and coverage are not feasible.
Testing
Use dynamic tools and techniques that interact with the software using large test suites with
many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The
software's operation may slow down, but it should not become unstable, crash, or generate
incorrect results.
Weakness Ordinalities
Primary (where the weakness exists independent of other weaknesses)
Relationships
Nature Type ID Name Page
ChildOf 77 Improper Sanitization of Special Elements used in a 699 82
Command ('Command Injection') 1000
ChildOf 634 Weaknesses that Affect System Processes 631 708
ChildOf 741 CERT C Secure Coding Section 07 - Characters and Strings 734 835
(STR)
ChildOf 744 CERT C Secure Coding Section 10 - Environment (ENV) 734 837
CanAlsoBe 78 Improper Sanitization of Special Elements used in an OS 1000 86
Command ('OS Command Injection')
ParentOf 622 Unvalidated Function Hook Arguments 1000 698

Relationship Notes
At one layer of abstraction, this can overlap other weaknesses that have whitespace problems, e.g.
injection of javascript into attributes of HTML tags.
Affected Resources
• System Process

110
CWE Version 1.8.1
CWE-89: Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection')

Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Node ID Mapped Node Name
PLOVER Argument Injection or Modification
CERT C Secure Coding ENV03-C Sanitize the environment when invoking external programs
CERT C Secure Coding ENV04-C Do not call system() if you do not need a command processor
CERT C Secure Coding STR02-C Sanitize data passed to complex subsystems
WASC 30 Mail Command Injection
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
41 Using Meta-characters in E-mail Headers to Inject Malicious Payloads
88 OS Command Injection
133 Try All Common Application Switches and Options
References
Steven Christey. "Argument injection issues". < http://www.securityfocus.com/archive/1/

CWE-89: Improper Sanitization of Special Elements


archive/1/460089/100/100/threaded >.

used in an SQL Command ('SQL Injection')


CWE-89: Improper Sanitization of Special Elements used in
an SQL Command ('SQL Injection')
Weakness ID: 89 (Weakness Base) Status: Draft
Description
Summary
The software constructs all or part of an SQL command using externally-influenced input from an
upstream component, but it does not sanitize or incorrectly sanitizes special elements that could
modify the intended SQL command when it is sent to a downstream component.
Extended Description
Without sufficient removal or quoting of SQL syntax in user-controllable inputs, the generated
SQL query can cause those inputs to be interpreted as SQL instead of ordinary user data. This
can be used to alter query logic to bypass security checks, or to insert additional statements that
modify the back-end database, possibly including execution of system commands.
SQL injection has become a common issue with database-driven web sites. The flaw is easily
detected, and easily exploited, and as such, any site or software package with even a minimal
user base is likely to be subject to an attempted attack of this kind. This flaw depends on the fact
that SQL makes no real distinction between the control and data planes.
Time of Introduction
• Architecture and Design
• Implementation
• Operation
Applicable Platforms
Languages
• All
Technology Classes
• Database-Server
Modes of Introduction
This weakness typically appears in data-rich applications that save user inputs in a database.
Common Consequences
Confidentiality
Since SQL databases generally hold sensitive data, loss of confidentiality is a frequent problem
with SQL injection vulnerabilities.

111
CWE Version 1.8.1
CWE-89: Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection')

Authentication
If poor SQL commands are used to check user names and passwords, it may be possible to
connect to a system as another user with no previous knowledge of the password.
Authorization
If authorization information is held in a SQL database, it may be possible to change this
information through the successful exploitation of a SQL injection vulnerability.
Integrity
Just as it may be possible to read sensitive information, it is also possible to make changes or
even delete this information with a SQL injection attack.
Likelihood of Exploit
Very High
Enabling Factors for Exploitation
The application dynamically generates queries that contain user input.
Detection Methods
Automated Static Analysis
CWE-89: Improper Sanitization of Special Elements

This weakness can often be detected using automated static analysis tools. Many modern tools
use data flow analysis or constraint-based techniques to minimize the number of false positives.
used in an SQL Command ('SQL Injection')

Automated static analysis might not be able to recognize when proper input validation is being
performed, leading to false positives - i.e., warnings that do not have any security consequences
or do not require any code changes.
Automated static analysis might not be able to detect the usage of custom API functions or third-
party libraries that indirectly invoke SQL commands, leading to false negatives - especially if the
API/library code is not available for analysis.
Manual Analysis
Manual analysis can be useful for finding this weakness, but it might not achieve desired code
coverage within limited time constraints. This becomes difficult for weaknesses that must be
considered for all inputs, since the attack surface can be too large.
Demonstrative Examples
Example 1:
In 2008, a large number of web servers were compromised using the same SQL injection attack
string. This single string worked against many different programs. The SQL injection was then
used to modify the web sites to serve malicious code. [1]
Example 2:
The following code dynamically constructs and executes a SQL query that searches for items
matching a specified name. The query restricts the items displayed to those where owner matches
the user name of the currently-authenticated user.
C# Example: Bad Code

...
string userName = ctx.getAuthenticatedUserName();
string query = "SELECT * FROM items WHERE owner = '" + userName + "' AND itemname = '" + ItemName.Text + "'";
sda = new SqlDataAdapter(query, conn);
DataTable dt = new DataTable();
sda.Fill(dt);
...

The query that this code intends to execute follows:


SELECT * FROM items WHERE owner = <userName> AND itemname = <itemName>;

However, because the query is constructed dynamically by concatenating a constant base query
string and a user input string, the query only behaves correctly if itemName does not contain a
single-quote character. If an attacker with the user name wiley enters the string:
Attack

name' OR 'a'='a

for itemName, then the query becomes the following:


112
CWE Version 1.8.1
CWE-89: Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection')

Attack

SELECT * FROM items WHERE owner = 'wiley' AND itemname = 'name' OR 'a'='a';

The addition of the:


Attack

OR 'a'='a'

condition causes the WHERE clause to always evaluate to true, so the query becomes logically
equivalent to the much simpler query:
Attack

SELECT * FROM items;

This simplification of the query allows the attacker to bypass the requirement that the query only
return items owned by the authenticated user; the query now returns all entries stored in the items
table, regardless of their specified owner.
Example 3:

CWE-89: Improper Sanitization of Special Elements


This example examines the effects of a different malicious value passed to the query constructed
and executed in the previous example.

used in an SQL Command ('SQL Injection')


If an attacker with the user name wiley enters the string:
Attack

name'; DELETE FROM items; --

for itemName, then the query becomes the following two queries:
SQL Example: Attack

SELECT * FROM items WHERE owner = 'wiley' AND itemname = 'name';


DELETE FROM items;
--'

Many database servers, including Microsoft(R) SQL Server 2000, allow multiple SQL statements
separated by semicolons to be executed at once. While this attack string results in an error on
Oracle and other database servers that do not allow the batch-execution of statements separated
by semicolons, on databases that do allow batch execution, this type of attack allows the attacker
to execute arbitrary commands against the database.
Notice the trailing pair of hyphens (--), which specifies to most database servers that the remainder
of the statement is to be treated as a comment and not executed. In this case the comment
character serves to remove the trailing single-quote left over from the modified query. On a
database where comments are not allowed to be used in this way, the general attack could still be
made effective using a trick similar to the one shown in the previous example.
If an attacker enters the string
Attack

name'; DELETE FROM items; SELECT * FROM items WHERE 'a'='a

Then the following three valid statements will be created:


Attack

SELECT * FROM items WHERE owner = 'wiley' AND itemname = 'name';


DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';

One traditional approach to preventing SQL injection attacks is to handle them as an input
validation problem and either accept only characters from a whitelist of safe values or identify and
escape a blacklist of potentially malicious values. Whitelisting can be a very effective means of
enforcing strict input validation rules, but parameterized SQL statements require less maintenance
and can offer more guarantees with respect to security. As is almost always the case, blacklisting
is riddled with loopholes that make it ineffective at preventing SQL injection attacks. For example,
attackers can:
Target fields that are not quoted

113
CWE Version 1.8.1
CWE-89: Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection')

Find ways to bypass the need for certain escaped meta-characters


Use stored procedures to hide the injected meta-characters.
Manually escaping characters in input to SQL queries can help, but it will not make your application
secure from SQL injection attacks.
Another solution commonly proposed for dealing with SQL injection attacks is to use stored
procedures. Although stored procedures prevent some types of SQL injection attacks, they fail to
protect against many others. For example, the following PL/SQL procedure is vulnerable to the
same SQL injection attack shown in the first example.
Bad Code

procedure get_item ( itm_cv IN OUT ItmCurTyp, usr in varchar2, itm in varchar2)


is open itm_cv for
' SELECT * FROM items WHERE ' || 'owner = '|| usr || ' AND itemname = ' || itm || ';
end get_item;

Stored procedures typically help prevent SQL injection attacks by limiting the types of statements
that can be passed to their parameters. However, there are many ways around the limitations
CWE-89: Improper Sanitization of Special Elements

and many interesting statements that can still be passed to stored procedures. Again, stored
procedures can prevent some exploits, but they will not make your application secure against SQL
used in an SQL Command ('SQL Injection')

injection attacks.
Example 4:
MS SQL has a built in function that enables shell command execution. An SQL injection in such a
context could be disastrous. For example, a query of the form:
Bad Code

SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='$user_input' ORDER BY PRICE

Where $user_input is taken from the user and unfiltered.


If the user provides the string:
Attack

' exec master..xp_cmdshell 'vol' --

The query will take the following form: "


Attack

SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='' exec master..xp_cmdshell 'vol' --' ORDER BY
PRICE

Now, this query can be broken down into:


[1] a first SQL query: SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY=''
[2] a second SQL query, which executes a shell command: exec master..xp_cmdshell 'vol'
[3] an MS SQL comment: --' ORDER BY PRICE
As can be seen, the malicious input changes the semantics of the query into a query, a shell
command execution and a comment.
Example 5:
This code intends to print a message summary given the message ID.
PHP Example: Bad Code

$id = $_COOKIE["mid"];
mysql_query("SELECT MessageID, Subject FROM messages WHERE MessageID = '$id'");

The programmer may have skipped any input validation on $id under the assumption that attackers
cannot modify the cookie. However, this is easy to do with custom client code or even in the web
browser.
While $id is wrapped in single quotes in the call to mysql_query(), an attacker could simply change
the incoming mid cookie to:
Attack

1432' or '1' = '1

114
CWE Version 1.8.1
CWE-89: Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection')

This would produce the resulting query:


Result

SELECT MessageID, Subject FROM messages WHERE MessageID = '1432' or '1' = '1'

Not only will this retrieve message number 1432, it will retrieve all other messages.
In this case, the programmer could apply a simple modification to the code to eliminate the SQL
injection:
PHP Example: Good Code

$id = intval($_COOKIE["mid"]);
mysql_query("SELECT MessageID, Subject FROM messages WHERE MessageID = '$id'");

However, if this code is intended to support multiple users with different message boxes, the code
might also need an access control check (CWE-285) to ensure that the application user has the
permission to see that message.
Example 6:
This example attempts to take a last name provided by a user and enter it into a database.

CWE-89: Improper Sanitization of Special Elements


Perl Example: Bad Code

$userKey = getUserID();

used in an SQL Command ('SQL Injection')


$name = getUserInput();
# ensure only letters, hyphens and apostrophe are allowed
$name = whiteList($name, "^a-zA-z'-$");
$query = "INSERT INTO last_names VALUES('$userKey', '$name')";

While the programmer applies a whitelist to the user input, it has shortcomings. First of all, the
user is still allowed to provide hyphens which are used as comment structures in SQL. If a user
specifies -- then the remainder of the statement will be treated as a comment, which may bypass
security logic. Furthermore, the whitelist permits the apostrophe which is also a data / command
separator in SQL. If a user supplies a name with an apostrophe, they may be able to alter the
structure of the whole statement and even change control flow of the program, possibly accessing
or modifying confidential information. In this situation, both the hyphen and apostrophe are
legitimate characters for a last name and permitting them is required. Instead, a programmer may
want to use a prepared statement or apply an encoding routine to the input to prevent any data /
directive misinterpretations.
Observed Examples
Reference Description
CVE-2003-0377 SQL injection in security product, using a crafted group name.
CVE-2004-0366 chain: SQL injection in library intended for database authentication allows SQL injection
and authentication bypass.
CVE-2007-6602 SQL injection via user name.
CVE-2008-2223 SQL injection through an ID that was supposed to be numeric.
CVE-2008-2380 SQL injection in authentication library.
CVE-2008-2790 SQL injection through an ID that was supposed to be numeric.
CVE-2008-5817 SQL injection via user name or password fields.
Potential Mitigations
Architecture and Design
Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides
constructs that make this weakness easier to avoid.
For example, consider using persistence layers such as Hibernate or Enterprise Java Beans,
which can provide significant protection against SQL injection if used properly.

115
CWE Version 1.8.1
CWE-89: Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection')

Architecture and Design


Parameterization
If available, use structured mechanisms that automatically enforce the separation between
data and code. These mechanisms may be able to provide the relevant quoting, encoding, and
validation automatically, instead of relying on the developer to provide this capability at every
point where output is generated.
Process SQL queries using prepared statements, parameterized queries, or stored procedures.
These features should accept parameters or variables and support strong typing. Do not
dynamically construct and execute query strings within these features using "exec" or similar
functionality, since you may re-introduce the possibility of SQL injection.
Architecture and Design
Follow the principle of least privilege when creating user accounts to a SQL database. The
database users should only have the minimum privileges necessary to use their account. If the
requirements of the system indicate that a user can read and modify their own data, then limit
their privileges so they cannot read/write others' data. Use the strictest permissions possible on
all database objects, such as execute-only for stored procedures.
CWE-89: Improper Sanitization of Special Elements

Architecture and Design


used in an SQL Command ('SQL Injection')

For any security checks that are performed on the client side, ensure that these checks are
duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side
checks by modifying values after the checks have been performed, or by changing the client to
remove the client-side checks entirely. Then, these modified values would be submitted to the
server.
Implementation
If you need to use dynamically-generated query strings in spite of the risk, use proper encoding
and escaping of inputs. Instead of building your own implementation, such features may be
available in the database or programming language. For example, the Oracle DBMS_ASSERT
package can check or enforce that parameters have certain properties that make them less
vulnerable to SQL injection. For MySQL, the mysql_real_escape_string() API function is available
in both C and PHP.

116
CWE Version 1.8.1
CWE-89: Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection')

Implementation
Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a
whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not
strictly conform to specifications, or transform it into something that does. Do not rely exclusively
on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). However, blacklists
can be useful for detecting potential attacks or determining which inputs are so malformed that
they should be rejected outright.
When performing input validation, consider all potentially relevant properties, including length,
type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency
across related fields, and conformance to business rules. As an example of business rule logic,
"boat" may be syntactically valid because it only contains alphanumeric characters, but it is not
valid if you are expecting colors such as "red" or "blue."
When constructing SQL query strings, use stringent whitelists that limit the character set based on
the expected value of the parameter in the request. This will indirectly limit the scope of an attack,
but this technique is less important than proper output encoding and escaping.

CWE-89: Improper Sanitization of Special Elements


Note that proper output encoding, escaping, and quoting is the most effective solution for
preventing SQL injection, although input validation may provide some defense-in-depth. This is

used in an SQL Command ('SQL Injection')


because it effectively limits what will appear in output. Input validation will not always prevent
SQL injection, especially if you are required to support free-form text fields that could contain
arbitrary characters. For example, the name "O'Reilly" would likely pass the validation step, since
it is a common last name in the English language. However, it cannot be directly inserted into the
database because it contains the "'" apostrophe character, which would need to be escaped or
otherwise handled. In this case, stripping the apostrophe might reduce the risk of SQL injection,
but it would produce incorrect behavior because the wrong name would be recorded.
When feasible, it may be safest to disallow meta-characters entirely, instead of escaping them.
This will provide some defense in depth. After the data is entered into the database, later
processes may neglect to escape meta-characters before use, and you may not have control over
those processes.
Testing
Implementation
Use automated static analysis tools that target this type of weakness. Many modern techniques
use data flow analysis to minimize the number of false positives. This is not a perfect solution,
since 100% accuracy and coverage are not feasible.
Testing
Use dynamic tools and techniques that interact with the software using large test suites with
many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The
software's operation may slow down, but it should not become unstable, crash, or generate
incorrect results.
Operation
Use an application firewall that can detect attacks against this weakness. This might not catch all
attacks, and it might require some effort for customization. However, it can be beneficial in cases
in which the code cannot be fixed (because it is controlled by a third party), as an emergency
prevention measure while more comprehensive software assurance measures are applied, or to
provide defense in depth.
Relationships
Nature Type ID Name Page
ChildOf 20 Improper Input Validation 700 15
ChildOf 77 Improper Sanitization of Special Elements used in a 699 82
Command ('Command Injection') 1000
ChildOf 713 OWASP Top Ten 2007 Category A2 - Injection Flaws 629 816
ChildOf 722 OWASP Top Ten 2004 Category A1 - Unvalidated Input 711 820
ChildOf 727 OWASP Top Ten 2004 Category A6 - Injection Flaws 711 823
ChildOf 751 2009 Top 25 - Insecure Interaction Between Components 750 842
117
CWE Version 1.8.1
CWE-89: Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection')

Nature Type ID Name Page


ChildOf 801 2010 Top 25 - Insecure Interaction Between Components 800 903
CanFollow 456 Missing Initialization 1000 544
ParentOf 564 SQL Injection: Hibernate 699 643
1000
MemberOf 630 Weaknesses Examined by SAMATE 630 705
MemberOf 635 Weaknesses Used by NVD 635 708

Relationship Notes
SQL injection can be resultant from special character mismanagement, MAID, or blacklist/whitelist
problems. It can be primary to authentication errors.
Taxonomy Mappings
Mapped Taxonomy Name Node ID Fit Mapped Node Name
PLOVER SQL injection
7 Pernicious Kingdoms SQL Injection
CLASP SQL injection
CWE-89: Improper Sanitization of Special Elements

OWASP Top Ten 2007 A2 CWE More Specific Injection Flaws


OWASP Top Ten 2004 A1 CWE More Specific Unvalidated Input
OWASP Top Ten 2004 A6 CWE More Specific Injection Flaws
used in an SQL Command ('SQL Injection')

WASC 19 SQL Injection


Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
7 Blind SQL Injection
66 SQL Injection
108 Command Line Execution through SQL Injection
109 Object Relational Mapping Injection
110 SQL Injection through SOAP Parameter Tampering
White Box Definitions
A weakness where the code path has:
1. start statement that accepts input and
2. end statement that performs an SQL command where
a. the input is part of the SQL command and
b. input contains SQL syntax (esp. query separator)
References
[REF-17] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software Security".
"Sin 1: SQL Injection." Page 3. McGraw-Hill. 2010.
[REF-11] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 12, "Database Input Issues"
Page 397. 2nd Edition. Microsoft. 2002.
OWASP. "SQL Injection Prevention Cheat Sheet". < http://www.owasp.org/index.php/
SQL_Injection_Prevention_Cheat_Sheet >.
Steven Friedl. "SQL Injection Attacks by Example". 2007-10-10. < http://www.unixwiz.net/techtips/
sql-injection.html >.
Ferruh Mavituna. "SQL Injection Cheat Sheet". 2007-03-15. < http://ferruh.mavituna.com/sql-
injection-cheatsheet-oku/ >.
David Litchfield, Chris Anley, John Heasman and Bill Grindlay. "The Database Hacker's Handbook:
Defending Database Servers". Wiley. 2005-07-14.
David Litchfield. "The Oracle Hacker's Handbook: Hacking and Defending Oracle". Wiley.
2007-01-30.
Microsoft. "SQL Injection". December 2008. < http://msdn.microsoft.com/en-us/library/
ms161953.aspx >.
Microsoft Security Vulnerability Research & Defense. "SQL Injection Attack". < http://
blogs.technet.com/swi/archive/2008/05/29/sql-injection-attack.aspx >.
Michael Howard. "Giving SQL Injection the Respect it Deserves". 2008-05-15. < http://
blogs.msdn.com/sdl/archive/2008/05/15/giving-sql-injection-the-respect-it-deserves.aspx >.

118
CWE Version 1.8.1
CWE-90: Failure to Sanitize Data into LDAP Queries ('LDAP Injection')

CWE-90: Failure to Sanitize Data into LDAP Queries ('LDAP


Injection')
Weakness ID: 90 (Weakness Base) Status: Draft
Description
Summary
The software does not sufficiently sanitize special elements that are used in LDAP queries or
responses, allowing attackers to modify the syntax, contents, or commands of the LDAP query
before it is executed.
Time of Introduction
• Architecture and Design

CWE-90: Failure to Sanitize Data into LDAP Queries ('LDAP Injection')


• Implementation
Applicable Platforms
Languages
• All
Technology Classes
• Database-Server
Demonstrative Examples
In the code excerpt below, user input data (address) isn't properly sanitized before it's used to
construct an LDAP query.
Java Example: Bad Code

context = new InitialDirContext(env);


String searchFilter = "StreetAddress=" + address;
NamingEnumeration answer = context.search(searchBase, searchFilter, searchCtls);

Potential Mitigations
Assume all input is malicious. Use an appropriate combination of black lists and white lists to filter
or quote LDAP syntax from user-controlled input.
Relationships
Nature Type ID Name Page
ChildOf 77 Improper Sanitization of Special Elements used in a 699 82
Command ('Command Injection') 1000
ChildOf 713 OWASP Top Ten 2007 Category A2 - Injection Flaws 629 816

Relationship Notes
Factors: resultant to special character mismanagement, MAID, or blacklist/whitelist problems. Can
be primary to authentication and verification errors.
Research Gaps
Under-reported. This is likely found very frequently by third party code auditors, but there are very
few publicly reported examples.
Taxonomy Mappings
Mapped Taxonomy Name Node ID Fit Mapped Node Name
PLOVER LDAP injection
OWASP Top Ten 2007 A2 CWE More Specific Injection Flaws
WASC 29 LDAP Injection
References
SPI Dynamics. "Web Applications and LDAP Injection".

CWE-91: XML Injection (aka Blind XPath Injection)


Weakness ID: 91 (Weakness Base) Status: Draft
Description
Summary

119
CWE Version 1.8.1
CWE-92: DEPRECATED: Improper Sanitization of Custom Special Characters

The software does not properly filter or quote special characters or reserved words that are used
in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is
processed by an end system.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• All
CWE-92: DEPRECATED: Improper Sanitization of Custom Special Characters

Potential Mitigations
Assume all input is malicious. Use an appropriate combination of black lists and white lists to
ensure only valid and expected input is processed by the system.
Relationships
Nature Type ID Name Page
ChildOf 74 Failure to Sanitize Data into a Different Plane ('Injection') 699 79
1000
ChildOf 713 OWASP Top Ten 2007 Category A2 - Injection Flaws 629 816
ChildOf 727 OWASP Top Ten 2004 Category A6 - Injection Flaws 711 823
ParentOf 643 Improper Neutralization of Data within XPath Expressions 699 721
('XPath injection') 1000
ParentOf 652 Improper Neutralization of Data within XQuery Expressions 699 732
('XQuery Injection') 1000
Research Gaps
Under-reported. This is likely found regularly by third party code auditors, but there are very few
publicly reported examples.
Theoretical Notes
In vulnerability theory terms, this is a representation-specific case of a Data/Directive Boundary
Error.
Taxonomy Mappings
Mapped Taxonomy Name Node ID Fit Mapped Node Name
PLOVER XML injection (aka Blind Xpath injection)
OWASP Top Ten 2007 A2 CWE More Specific Injection Flaws
OWASP Top Ten 2004 A6 CWE More Specific Injection Flaws
WASC 23 XML Injection
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
83 XPath Injection
References
Amit Klein. "Blind XPath Injection". 2004-05-19. < http://www.modsecurity.org/archive/amit/blind-
xpath-injection.pdf >.
Maintenance Notes
The description for this entry is generally applicable to XML, but the name includes "blind XPath
injection" which is more closely associated with CWE-643. Therefore this entry might need to be
deprecated or converted to a general category - although injection into raw XML is not covered by
CWE-643 or CWE-652.

CWE-92: DEPRECATED: Improper Sanitization of Custom


Special Characters
Weakness ID: 92 (Deprecated Weakness Base) Status: Deprecated
Description
Summary

120
CWE Version 1.8.1
CWE-93: Failure to Sanitize CRLF Sequences ('CRLF Injection')

The software uses a custom or proprietary language or representation, but when it receives input
from an upstream component, it does not sanitize or incorrectly sanitizes special elements when
they are sent to a downstream component.
Extended Description
This allows attackers to modify the syntax, content, or commands before they are processed by a
downstream component.
Maintenance Notes
This and some other CWE entries were distinct in PLOVER but effectively have overlap in
CWE. PLOVER sometimes defined "other" and "miscellaneous" categories in order to satisfy
exhaustiveness requirements for taxonomies. Within the context of CWE, the use of a more
abstract entry is preferred in mapping situations.

CWE-93: Failure to Sanitize CRLF Sequences ('CRLF

CWE-93: Failure to Sanitize CRLF Sequences ('CRLF Injection')


Injection')
Weakness ID: 93 (Weakness Base) Status: Draft
Description
Summary
The software uses CRLF (carriage return line feeds) as a special element, e.g. to separate lines
or records, but it does not properly sanitize CRLF sequences from inputs.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• All
Likelihood of Exploit
Medium to High
Demonstrative Examples
If user input data that eventually makes it to a log message isn't checked for CRLF characters, it
may be possible for an attacker to forge entries in a log file.
Java Example: Bad Code

logger.info("User's street address: " + request.getParameter("streetAddress"));

Observed Examples
Reference Description
CVE-2002-1771 CRLF injection enables spam proxy (add mail headers) using email address or name.
CVE-2002-1783 CRLF injection in API function arguments modify headers for outgoing requests.
CVE-2004-1513 Spoofed entries in web server log file via carriage returns
CVE-2004-1687 Chain: HTTP response splitting via CRLF in parameter related to URL.
CVE-2005-1951 Chain: Application accepts CRLF in an object ID, allowing HTTP response splitting.
CVE-2006-4624 Chain: inject fake log entries with fake timestamps using CRLF injection
Potential Mitigations
Avoid using CRLF as a special sequence.
Appropriately filter or quote CRLF sequences in user-controlled input.
Weakness Ordinalities
Primary (where the weakness exists independent of other weaknesses)
Relationships
Nature Type ID Name Page
ChildOf 74 Failure to Sanitize Data into a Different Plane ('Injection') 699 79
1000
CanPrecede 117 Improper Output Sanitization for Logs 1000 158
ChildOf 713 OWASP Top Ten 2007 Category A2 - Injection Flaws 629 816

121
CWE Version 1.8.1
CWE-94: Failure to Control Generation of Code ('Code Injection')

Nature Type ID Name Page


ParentOf 113 Failure to Sanitize CRLF Sequences in HTTP Headers 1000 147
('HTTP Response Splitting')
CanAlsoBe 144 Improper Neutralization of Line Delimiters 1000 203
CanAlsoBe 145 Improper Neutralization of Section Delimiters 1000 204

Research Gaps
Probably under-studied, although gaining more prominence in 2005 as a result of interest in HTTP
response splitting.
Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Node ID Fit Mapped Node Name
CWE-94: Failure to Control Generation of Code ('Code Injection')

PLOVER CRLF Injection


OWASP Top Ten 2007 A2 CWE More Specific Injection Flaws
WASC 24 HTTP Request Splitting
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
15 Command Delimiters
81 Web Logs Tampering
References
Ulf Harnhammar. "CRLF Injection". Bugtraq. 2002-05-07. < http://marc.info/?
l=bugtraq&m=102088154213630&w=2 >.

CWE-94: Failure to Control Generation of Code ('Code


Injection')
Weakness ID: 94 (Weakness Class) Status: Draft
Description
Summary
The product does not sufficiently filter code (control-plane) syntax from user-controlled input (data
plane) when that input is used within code that the product generates.
Extended Description
When software allows a user's input to contain code syntax, it might be possible for an attacker
to craft the code in such a way that it will alter the intended control flow of the software. Such an
alteration could lead to arbitrary code execution.
Injection problems encompass a wide variety of issues -- all mitigated in very different ways. For
this reason, the most effective way to discuss these weaknesses is to note the distinct features
which classify them as injection weaknesses. The most important issue to note is that all injection
problems share one thing in common -- i.e., they allow for the injection of control plane data into
the user-controlled data plane. This means that the execution of the process may be altered
by sending code in through legitimate data channels, using no other mechanism. While buffer
overflows, and many other flaws, involve the use of some further issue to gain execution, injection
problems need only for the data to be parsed. The most classic instantiations of this category of
weakness are SQL injection and format string vulnerabilities.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms
Languages
• Interpreted languages (Sometimes)
Common Consequences
Confidentiality
The injected code could access restricted data / files

122
CWE Version 1.8.1
CWE-94: Failure to Control Generation of Code ('Code Injection')

Authentication
In some cases, injectable code controls authentication; this may lead to a remote vulnerability
Access Control
Injected code can access resources that the attacker is directly prevented from accessing
Integrity
Code injection attacks can lead to loss of data integrity in nearly all cases as the control-plane
data injected is always incidental to data recall or writing. Additionally, code injection can often
result in the execution of arbitrary code.
Accountability
Often the actions performed by injected control code are unlogged.
Likelihood of Exploit
Medium

CWE-94: Failure to Control Generation of Code ('Code Injection')


Demonstrative Examples
This example attempts to write user messages to a message file and allow users to view them.
PHP Example: Bad Code

$MessageFile = "cwe-94/messages.out";
if ($_GET["action"] == "NewMessage") {
$name = $_GET["name"];
$message = $_GET["message"];
$handle = fopen($MessageFile, "a+");
fwrite($handle, "<b>$name</b> says '$message'<hr>\n");
fclose($handle);
echo "Message Saved!<p>\n";
}
else if ($_GET["action"] == "ViewMessages") {
include($MessageFile);
}

While the programmer intends for the MessageFile to only include data, an attacker can provide a
message such as:
Attack

name=h4x0r
message=%3C?php%20system(%22/bin/ls%20-l%22);?%3E

which will decode to the following:


Attack

<?php system("/bin/ls -l");?>

The programmer thought they were just including the contents of a regular data file, but PHP
parsed it and executed the code. Now, this code is executed any time people view messages.
Notice that XSS (CWE-79) is also possible in this situation.
Potential Mitigations
Architecture and Design
Refactor your program so that you do not have to dynamically generate code.
Architecture and Design
Run your code in a "jail" or similar sandbox environment that enforces strict boundaries between
the process and the operating system. This may effectively restrict which code can be executed
by your software.
Examples include the Unix chroot jail and AppArmor. In general, managed code may provide
some protection.
This may not be a feasible solution, and it only limits the impact to the operating system; the rest
of your application may still be subject to compromise.
Be careful to avoid CWE-243 and other weaknesses related to jails.

123
CWE Version 1.8.1
CWE-94: Failure to Control Generation of Code ('Code Injection')

Implementation
Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a
whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not
strictly conform to specifications, or transform it into something that does. Do not rely exclusively
on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). However, blacklists
can be useful for detecting potential attacks or determining which inputs are so malformed that
they should be rejected outright.
When performing input validation, consider all potentially relevant properties, including length,
type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency
across related fields, and conformance to business rules. As an example of business rule logic,
"boat" may be syntactically valid because it only contains alphanumeric characters, but it is not
valid if you are expecting colors such as "red" or "blue."
CWE-94: Failure to Control Generation of Code ('Code Injection')

To reduce the likelihood of code injection, use stringent whitelists that limit which constructs are
allowed. If you are dynamically constructing code that invokes a function, then verifying that
the input is alphanumeric might be insufficient. An attacker might still be able to reference a
dangerous function that you did not intend to allow, such as system(), exec(), or exit().
Testing
Use automated static analysis tools that target this type of weakness. Many modern techniques
use data flow analysis to minimize the number of false positives. This is not a perfect solution,
since 100% accuracy and coverage are not feasible.
Testing
Use dynamic tools and techniques that interact with the software using large test suites with
many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The
software's operation may slow down, but it should not become unstable, crash, or generate
incorrect results.
Operation
Run the code in an environment that performs automatic taint propagation and prevents any
command execution that uses tainted variables, such as Perl's "-T" switch. This will force you to
perform validation steps that remove the taint, although you must be careful to correctly validate
your inputs so that you do not accidentally mark dangerous inputs as untainted (see CWE-183
and CWE-184).
Relationships
Nature Type ID Name Page
ChildOf 74 Failure to Sanitize Data into a Different Plane ('Injection') 699 79
1000
ChildOf 691 Insufficient Control Flow Management 1000 782
ChildOf 752 2009 Top 25 - Risky Resource Management 750 842
ParentOf 95 Improper Sanitization of Directives in Dynamically Evaluated 699 125
Code ('Eval Injection') 1000
ParentOf 96 Improper Neutralization of Directives in Statically Saved Code 699 127
('Static Code Injection') 1000
CanFollow 98 Improper Control of Filename for Include/Require Statement 699 129
in PHP Program ('PHP File Inclusion') 1000
ParentOf 621 Variable Extraction Error 1000 697
ParentOf 627 Dynamic Variable Evaluation 699 702
1000
MemberOf 635 Weaknesses Used by NVD 635 708

Research Gaps
Many of these weaknesses are under-studied and under-researched, and terminology is not
sufficiently precise.
Taxonomy Mappings
Mapped Taxonomy Name Node ID Mapped Node Name
PLOVER CODE Code Evaluation and Injection

124
CWE Version 1.8.1
CWE-95: Improper Sanitization of Directives in Dynamically Evaluated Code ('Eval Injection')

Related Attack Patterns


CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
35 Leverage Executable Code in Nonexecutable Files
77 Manipulating User-Controlled Variables

CWE-95: Improper Sanitization of Directives in


Dynamically Evaluated Code ('Eval Injection')
Weakness ID: 95 (Weakness Base) Status: Incomplete
Description
Summary
The software receives input from an upstream component, but it does not sanitize or incorrectly
sanitizes code syntax before using the input in a dynamic evaluation call (e.g. "eval").
Extended Description
This may allow an attacker to execute arbitrary code, or at least modify what code can be
executed.

CWE-95: Improper Sanitization of Directives in


Time of Introduction

Dynamically Evaluated Code ('Eval Injection')


• Architecture and Design
• Implementation
Applicable Platforms
Languages
• Java
• Javascript
• Python
• Perl
• PHP
• Ruby
• Interpreted Languages
Modes of Introduction
This weakness is prevalent in handler/dispatch procedures that might want to invoke a large
number of functions, or set a large number of variables.
Likelihood of Exploit
Medium
Demonstrative Examples
edit-config.pl: This CGI script is used to modify settings in a configuration file.
Perl Example: Bad Code

use CGI qw(:standard);


sub config_file_add_key {
my ($fname, $key, $arg) = @_;
# code to add a field/key to a file goes here
}
sub config_file_set_key {
my ($fname, $key, $arg) = @_;
# code to set key to a particular file goes here
}
sub config_file_delete_key {
my ($fname, $key, $arg) = @_;
# code to delete key from a particular file goes here
}
sub handleConfigAction {
my ($fname, $action) = @_;
my $key = param('key');
my $val = param('val');
# this is super-efficient code, especially if you have to invoke
# any one of dozens of different functions!
my $code = "config_file_$action_key(\$fname, \$key, \$val);";
eval($code);
}
125
CWE Version 1.8.1
CWE-95: Improper Sanitization of Directives in Dynamically Evaluated Code ('Eval Injection')

$configfile = "/home/cwe/config.txt";
print header;
if (defined(param('action'))) {
handleConfigAction($configfile, param('action'));
}
else {
print "No action specified!\n";
}

The script intends to take the 'action' parameter and invoke one of a variety of functions
based on the value of that parameter - config_file_add_key(), config_file_set_key(), or
config_file_delete_key(). It could set up a conditional to invoke each function separately, but eval()
is a powerful way of doing the same thing in fewer lines of code, especially when a large number
of functions or variables are involved. Unfortunately, in this case, the attacker can provide other
values in the action parameter, such as: add_key(",","); system("/bin/ls"); This would produce the
following string in handleConfigAction(): config_file_add_key(",","); system("/bin/ls"); Any arbitrary
Perl code could be added after the attacker has "closed off" the construction of the original function
call, in order to prevent parsing errors from causing the malicious eval() to fail before the attacker's
payload is activated. This particular manipulation would fail after the system() call, because the
CWE-95: Improper Sanitization of Directives in
Dynamically Evaluated Code ('Eval Injection')

"_key(\$fname, \$key, \$val)" portion of the string would cause an error, but this is irrelevant to the
attack because the payload has already been activated.
Observed Examples
Reference Description
CVE-2001-1471 chain: Resultant eval injection. An invalid value prevents initialization of variables, which
can be modified by attacker and later injected into PHP eval statement.
CVE-2002-1750 Eval injection in Perl program.
CVE-2002-1752 Direct code injection into Perl eval function.
CVE-2002-1753 Eval injection in Perl program.
CVE-2005-1527 Direct code injection into Perl eval function.
CVE-2005-1921 MFV. code injection into PHP eval statement using nested constructs that should not be
nested.
CVE-2005-2498 MFV. code injection into PHP eval statement using nested constructs that should not be
nested.
CVE-2005-2837 Direct code injection into Perl eval function.
CVE-2005-3302 Code injection into Python eval statement from a field in a formatted file.
CVE-2007-1253 Eval injection in Python program.
CVE-2008-5071 Eval injection in PHP program.
CVE-2008-5305 Eval injection in Perl program using an ID that should only contain hyphens and numbers.
Potential Mitigations
Architecture and Design
Implementation
If possible, refactor your code so that it does not need to use eval() at all.
Implementation
Input Validation
Assume all input is malicious. Use an appropriate combination of black lists and white lists to
ensure only valid and expected input is processed by the system.
Architecture and Design
Do not rely exclusively on blacklist validation to detect malicious input or to encode output
(CWE-184). There are too many ways to encode the same character, so you're likely to miss
some variants.

126
CWE Version 1.8.1
CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')

Implementation
Inputs should be decoded and canonicalized to the application's current internal representation
before being validated (CWE-180, CWE-181). Make sure that your application does not
inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass
whitelist schemes by introducing dangerous inputs after they have been checked. Use libraries
such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This
will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are
allowed to contain properly-encoded dangerous content.
Other Notes
Factors: special character errors can play a role in increasing the variety of code that can be
injected, although some vulnerabilities do not require special characters at all, e.g. when a single
function without arguments can be referenced and a terminator character is not necessary.
Weakness Ordinalities
Primary (where the weakness exists independent of other weaknesses)
Relationships

in Statically Saved Code ('Static Code Injection')


Nature Type ID Name Page

CWE-96: Improper Neutralization of Directives


ChildOf 94 Failure to Control Generation of Code ('Code Injection') 699 122
1000
ChildOf 714 OWASP Top Ten 2007 Category A3 - Malicious File 629 817
Execution
ChildOf 727 OWASP Top Ten 2004 Category A6 - Injection Flaws 711 823

Research Gaps
This issue is probably under-reported. Most relevant CVEs have been for Perl and PHP, but eval
injection applies to most interpreted languages. Javascript eval injection is likely to be heavily
under-reported.
Causal Nature
Explicit (an explicit weakness resulting from behavior of the developer)
Taxonomy Mappings
Mapped Taxonomy Name Node ID Fit Mapped Node Name
PLOVER Direct Dynamic Code Evaluation ('Eval
Injection')
OWASP Top Ten 2007 A3 CWE More Specific Malicious File Execution
OWASP Top Ten 2004 A6 CWE More Specific Injection Flaws
Related Attack Patterns
CAPEC-ID Attack Pattern Name (CAPEC Version 1.5)
35 Leverage Executable Code in Nonexecutable Files
References
< http://www.rubycentral.com/book/taint.html >.

CWE-96: Improper Neutralization of Directives in Statically


Saved Code ('Static Code Injection')
Weakness ID: 96 (Weakness Base) Status: Draft
Description
Summary
The software receives input from an upstream component, but it does not neutralize or incorrectly
neutralizes code syntax before inserting the input into an executable resource, such as a library,
configuration file, or template.
Time of Introduction
• Architecture and Design
• Implementation
Applicable Platforms

127
CWE Version 1.8.1
CWE-97: Failure to Sanitize Server-Side Includes (SSI) Within a Web Page

Languages
• PHP
• Perl
• All Interpreted Languages
Observed Examples
Reference Description
CVE-2002-0495 Perl code directly injected into CGI library file from parameters to another CGI program.
CVE-2003-0395 PHP code from User-Agent HTTP header directly inserted into log file implemented as
PHP script.
CVE-2005-1876 Direct PHP code injection into supporting template file.
CVE-2005-1894 Direct code injection into PHP script that can be accessed by attacker.
CWE-97: Failure to Sanitize Server-Side Includes (SSI) Within a Web Page

Potential Mitigations
Assume all input is malicious. Use an appropriate combination of black lists and white lists to filter
code syntax from user-controlled input.
Avoid writing user-controlled input to code files.
Perform output validation to filter all code syntax from data written to non-code files.
Other Notes
"HTML injection" (see XSS) could be thought of as an example of this, but it is executed on the
client side, not the server side. Server-Side Includes (SSI) are an example of direct static code
injection.
This issue is most frequently found in PHP applications that allow users to set configuration
variables that are stored within executable php files. Technically, this could also be performed in
some compiled code (e.g. by byte-patching an executable), although it is highly unlikely.