Codebase list python-faraday / 408d244
Imported Upstream version 1.0.12 Sophie Brun 8 years ago
107 changed file(s) with 12141 addition(s) and 3535 deletion(s). Raw diff Collapse all Expand all
88
99 New features in the latest update
1010 =====================================
11
12 Aug 05, 2015:
13 ---
14
15 * Added CWE database and integration with vulns creation
16 * Added ENTER shortcut on modals
17 * Progress bar for workspace in the dashboard
18 * Bug fixing in workspaces and status report components
19 * Unit testing for vulns, status report and workspaces components
20 * Debian 8.1 support
21
1122
1223 Jun 30, 2015:
1324 ---
0 1.0.11
0 1.0.12
345345 def send_cmd(self, cmd):
346346 data = {"cmd": cmd}
347347 new_cmd = cmd
348 output_file = None
348349 try:
349350 response = requests.post(self.url_input,
350351 data=json.dumps(data),
0 cwe,name,desc_summary,description,resolution,exploitation,references
1 CWE-119,EN-Improper Restriction of Operations within the Bounds of a Memory Buffer (Type: Class),"The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.","Certain languages allow direct addressing of memory locations and do not automatically ensure that these locations are valid for the memory buffer that is being referenced. This can cause read or write operations to be performed on memory locations that may be associated with other variables, data structures, or internal program data.
2 As a result, an attacker may be able to execute arbitrary code, alter the intended control flow, read sensitive information, or cause the system to crash.",,High,"Writing Secure Code: Chapter 5, ""Public Enemy #1: The Buffer Overrun"" Page 127; Chapter 14, ""Prevent I18N Buffer Overruns"" Page 441
3 Using the Strsafe.h Functions: http://msdn.microsoft.com/en-us/library/ms647466.aspx
4 Safe C String Library v1.0.3: http://www.zork.org/safestr/
5 Address Space Layout Randomization in Windows Vista: http://blogs.msdn.com/michael_howard/archive/2006/05/26/address-space-layout-randomization-in-windows-vista.aspx
6 Limiting buffer overflows with ExecShield: http://www.redhat.com/magazine/009jul05/features/execshield/
7 PaX: http://en.wikipedia.org/wiki/PaX
8 Understanding DEP as a mitigation technology part 1: http://blogs.technet.com/b/srd/archive/2009/06/12/understanding-dep-as-a-mitigation-technology-part-1.aspx
9 The Art of Software Security Assessment: Chapter 5, ""Memory Corruption"", Page 167.
10 The Art of Software Security Assessment: Chapter 5, ""Protection Mechanisms"", Page 189."
11 CWE-123,EN-Write-what-where Condition (Type: Base),"Any condition where the attacker has the ability to write an arbitrary value to an arbitrary location, often as the result of a buffer overflow.","A buffer overflow condition exists when a program attempts to put more data in a buffer than it can hold, or when a program attempts to put data in a memory area outside of the boundaries of a buffer. The simplest type of error, and the most common cause of buffer overflows, is the ""classic"" case in which the program copies the buffer without restricting how much is copied. Other variants exist, but the existence of a classic overflow strongly suggests that the programmer is not considering even the most basic of security protections.",,High,"24 Deadly Sins of Software Security: ""Sin 5: Buffer Overruns."" Page 89"
12 CWE-129,EN-Improper Validation of Array Index (Type: Base),"The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array.","This typically occurs when the pointer or its index is decremented to a position before the buffer, when pointer arithmetic results in a position before the beginning of the valid memory location, or when a negative index is used. This may result in exposure of sensitive information or possibly a crash.",,High,"Writing Secure Code: Chapter 5, ""Array Indexing Errors"" Page 144
13 Top 25 Series - Rank 14 - Improper Validation of Array Index: http://blogs.sans.org/appsecstreetfighter/2010/03/12/top-25-series-rank-14-improper-validation-of-array-index/
14 Address Space Layout Randomization in Windows Vista: http://blogs.msdn.com/michael_howard/archive/2006/05/26/address-space-layout-randomization-in-windows-vista.aspx
15 PaX: http://en.wikipedia.org/wiki/PaX
16 Understanding DEP as a mitigation technology part 1: http://blogs.technet.com/b/srd/archive/2009/06/12/understanding-dep-as-a-mitigation-technology-part-1.aspx
17 Least Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html
18 24 Deadly Sins of Software Security: ""Sin 5: Buffer Overruns."" Page 89"
19 CWE-194,EN-Unexpected Sign Extension (Type: Base),"The software performs an operation on a number that causes it to be sign extended when it is transformed into a larger data type. When the original number is negative, this can produce unexpected values that lead to resultant weaknesses.",This can happen in signed and unsigned cases.,,High,"C Language Issues for Application Security: http://www.informit.com/articles/article.aspx?p=686170&seqNum=6
20 Integral Security: http://www.ddj.com/security/193501774"
21 CWE-20,EN-Improper Input Validation (Type: Class),The product does not validate or incorrectly validates input that can affect the control flow or data flow of a program.,"When software does not 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.",,High,"Input Validation with ESAPI - Very Important: http://manicode.blogspot.com/2008/08/input-validation-with-esapi.html
22 OWASP Enterprise Security API (ESAPI) Project: http://www.owasp.org/index.php/ESAPI
23 Hacking Exposed Web Applications, Second Edition: Input Validation Attacks
24 Input validation or output filtering, which is better?: http://jeremiahgrossman.blogspot.com/2007/01/input-validation-or-output-filtering.html
25 The importance of input validation: http://searchsoftwarequality.techtarget.com/tip/0,289483,sid92_gci1214373,00.html
26 Writing Secure Code: Chapter 10, ""All Input Is Evil!"" Page 341"
27 CWE-200,EN-Information Exposure (Type: Class),An information exposure is the intentional or unintentional disclosure of information to an actor that is not explicitly authorized to have access to that information.,"The information either
28 is regarded as sensitive within the product's own functionality, such as a private message; or
29 provides information about the product or its environment that could be useful in an attack but is normally not available to the attacker, such as the installation path of a product that is remotely accessible.
30 Many information exposures are resultant (e.g. PHP script error revealing the full path of the program), but they can also be primary (e.g. timing discrepancies in cryptography). There are many different types of problems that involve information exposures. Their severity can range widely depending on the type of information that is revealed.",,High,Mobile App Top 10 List: http://www.veracode.com/blog/2010/12/mobile-app-top-10-list/
31 CWE-209,EN-Information Exposure Through an Error Message (Type: Base),"The software generates an error message that includes sensitive information about its environment, users, or associated data.","The sensitive information may be valuable information on its own (such as a password), or it may be useful for launching other, more deadly attacks. If an attack fails, an attacker may use error information provided by the server to launch another more focused attack. For example, an attempt to exploit a path traversal weakness (CWE-22) might yield the full pathname of the installed application. In turn, this could be used to select the proper number of "".."" sequences to navigate to the targeted file. An attack using SQL injection (CWE-89) might not initially succeed, but an error message could reveal the malformed query, which would expose query logic and possibly even passwords or other sensitive information used within the query.",,High,"Information Leakage: http://www.webappsec.org/projects/threat/classes/information_leakage.shtml
32 Secure Programming with Static Analysis: Section 9.2, page 326.
33 Writing Secure Code: Chapter 16, ""General Good Practices."" Page 415
34 24 Deadly Sins of Software Security: ""Sin 11: Failure to Handle Errors Correctly."" Page 183
35 24 Deadly Sins of Software Security: ""Sin 12: Information Leakage."" Page 191
36 Top 25 Series - Rank 16 - Information Exposure Through an Error Message: http://software-security.sans.org/blog/2010/03/17/top-25-series-rank-16-information-exposure-through-an-error-message
37 The Art of Software Security Assessment: Chapter 3, ""Overly Verbose Error Messages"", Page 75."
38 CWE-234,EN-Failure to Handle Missing Parameter (Type: Variant),"If too few arguments are sent to a function, the function will still pop the expected number of arguments from the stack. Potentially, a variable number of arguments could be exhausted in a function as well.",This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.,,High,
39 CWE-242,EN-Use of Inherently Dangerous Function (Type: Base),The program calls a function that can never be guaranteed to work safely.,"Certain functions behave in dangerous ways regardless of how they are used. Functions in this category were often implemented without taking security concerns into account. The gets() function is unsafe because it does not perform bounds checking on the size of its input. An attacker can easily send arbitrarily-sized input to gets() and overflow the destination buffer. Similarly, the >> operator is unsafe to use when reading into a statically-allocated character array because it does not perform bounds checking on the size of its input. An attacker can easily send arbitrarily-sized input to the >> operator and overflow the destination buffer.",,High,"Herb Schildt's C++ Programming Cookbook: Chapter 5. Working with I/O
40 Writing Secure Code: Chapter 5, ""gets and fgets"" Page 163"
41 CWE-243,EN-Creation of chroot Jail Without Changing Working Directory (Type: Variant),"The program uses the chroot() system call to create a jail, but does not change the working directory afterward. This does not prevent access to files outside of the jail.","Improper use of chroot() may allow attackers to escape from the chroot jail. The chroot() function call does not change the process's current working directory, so relative paths may still refer to file system resources outside of the chroot jail after chroot() has been called.",,High,
42 CWE-268,EN-Privilege Chaining (Type: Base),"Two distinct privileges, roles, capabilities, or rights can be combined in a way that allows an entity to perform unsafe actions that would not be allowed without that combination.","Just as neglecting to include functionality for the management of password aging is dangerous, so is allowing password aging to continue unchecked. Passwords must be given a maximum life span, after which a user is required to update with a new and different password.",,High,Least Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html
43 CWE-271,EN-Privilege Dropping / Lowering Errors (Type: Class),The software does not drop privileges before passing control of a resource to an actor that does not have those privileges.,"In some contexts, a system executing with elevated permissions will hand off a process/file/etc. to another process or user. If the privileges of an entity are not reduced, then elevated privileges are spread throughout a system and possibly to an attacker.",,High,"24 Deadly Sins of Software Security: ""Sin 16: Executing Code With Too Much Privilege."" Page 243
44 The Art of Software Security Assessment: Chapter 9, ""Dropping Privileges Permanently"", Page 479."
45 CWE-285,EN-Improper Authorization (Type: Class),The software does not perform or incorrectly performs an authorization check when an actor attempts to access a resource or perform an action.,"Assuming a user with a given identity, authorization is the process of determining whether that user can access a given resource, based on the user's privileges and any permissions or other access-control specifications that apply to the resource.
46 When access control checks are not applied consistently - or not at all - users are able to access data or perform actions that they should not be allowed to perform. This can lead to a wide range of problems, including information exposures, denial of service, and arbitrary code execution.",,High,"Role Based Access Control and Role Based Security: http://csrc.nist.gov/groups/SNS/rbac/
47 Writing Secure Code: Chapter 4, ""Authorization"" Page 114; Chapter 6, ""Determining Appropriate Access Control"" Page 171
48 Top 25 Series - Rank 5 - Improper Access Control (Authorization): http://blogs.sans.org/appsecstreetfighter/2010/03/04/top-25-series-rank-5-improper-access-control-authorization/
49 OWASP Enterprise Security API (ESAPI) Project: http://www.owasp.org/index.php/ESAPI
50 Authentication using JAAS: http://www.javaranch.com/journal/2008/04/authentication-using-JAAS.html
51 The Art of Software Security Assessment: Chapter 2, ""Common Vulnerabilities of Authorization"", Page 39.
52 The Art of Software Security Assessment: Chapter 11, ""ACL Inheritance"", Page 649."
53 CWE-291,EN-Reliance on IP Address for Authentication (Type: Variant),The software uses an IP address for authentication.,"IP addresses can be easily spoofed. Attackers can forge the source IP address of the packets they send, but response packets will return to the forged IP address. To see the response packets, the attacker has to sniff the traffic between the victim machine and the forged IP address. In order to accomplish the required sniffing, attackers typically attempt to locate themselves on the same subnet as the victim machine. Attackers may be able to circumvent this requirement by using source routing, but source routing is disabled across much of the Internet today. In summary, IP address verification can be a useful part of an authentication scheme, but it should not be the single factor required for authentication.",,High,
54 CWE-292,EN-DEPRECATED (Duplicate): Trusting Self-reported DNS Name (Type: Variant),This entry has been deprecated because it was a duplicate of CWE-350. All content has been transferred to CWE-350.,"IP addresses can be easily spoofed. Attackers can forge the source IP address of the packets they send, but response packets will return to the forged IP address. To see the response packets, the attacker has to sniff the traffic between the victim machine and the forged IP address. In order to accomplish the required sniffing, attackers typically attempt to locate themselves on the same subnet as the victim machine. Attackers may be able to circumvent this requirement by using source routing, but source routing is disabled across much of the Internet today. In summary, IP address verification can be a useful part of an authentication scheme, but it should not be the single factor required for authentication.",,High,
55 CWE-293,EN-Using Referer Field for Authentication (Type: Variant),"The referer field in HTTP requests can be easily modified and, as such, is not a valid means of message integrity checking.","IP addresses can be easily spoofed. Attackers can forge the source IP address of the packets they send, but response packets will return to the forged IP address. To see the response packets, the attacker has to sniff the traffic between the victim machine and the forged IP address. In order to accomplish the required sniffing, attackers typically attempt to locate themselves on the same subnet as the victim machine. Attackers may be able to circumvent this requirement by using source routing, but source routing is disabled across much of the Internet today. In summary, IP address verification can be a useful part of an authentication scheme, but it should not be the single factor required for authentication.",,High,"The Art of Software Security Assessment: Chapter 17, ""Referer Request Header"", Page 1030."
56 CWE-294,EN-Authentication Bypass by Capture-replay (Type: Base),A capture-replay flaw exists when the design of the software makes it possible for a malicious user to sniff network traffic and bypass authentication by replaying it to the server in question to the same effect as the original message (or with minor changes).,"Capture-replay attacks are common and can be difficult to defeat without cryptography. They are a subset of network injection attacks that rely on observing previously-sent valid commands, then changing them slightly if necessary and resending the same commands to the server.",,High,
57 CWE-297,EN-Improper Validation of Certificate with Host Mismatch (Type: Variant),"The software communicates with a host that provides a certificate, but the software does not properly ensure that the certificate is actually associated with that host.","Even if a certificate is well-formed, signed, and follows the chain of trust, it may simply be a valid certificate for a different site than the site that the software is interacting with. If the certificate's host-specific data is not properly checked - such as the Common Name (CN) in the Subject or the Subject Alternative Name (SAN) extension of an X.509 certificate - it may be possible for a redirection or spoofing attack to allow a malicious host with a valid certificate to provide data, impersonating a trusted host. In order to ensure data integrity, the certificate must be valid and it must pertain to the site that is being accessed.
58 Even if the software attempts to check the hostname, it is still possible to incorrectly check the hostname. For example, attackers could create a certificate with a name that begins with a trusted name followed by a NUL byte, which could cause some string-based comparisons to only examine the portion that contains the trusted name.",,High,"The Most Dangerous Code in the World: Validating SSL Certificates in Non-Browser Software: http://www.cs.utexas.edu/~shmat/shmat_ccs12.pdf
59 Why Eve and Mallory Love Android: An Analysis of Android SSL (In)Security: http://www2.dcsec.uni-hannover.de/files/android/p50-fahl.pdf
60 Secure programming with the OpenSSL API, Part 2: Secure handshake: http://www.ibm.com/developerworks/library/l-openssl2/index.html
61 An Introduction to OpenSSL Programming (Part I): http://www.rtfm.com/openssl-examples/part1.pdf
62 24 Deadly Sins of Software Security: ""Sin 23: Improper Use of PKI, Especially SSL."" Page 347"
63 CWE-308,EN-Use of Single-factor Authentication (Type: Base),The use of single-factor authentication can lead to unnecessary risk of compromise when compared with the benefits of a dual-factor authentication scheme.,"While the use of multiple authentication schemes is simply piling on more complexity on top of authentication, it is inestimably valuable to have such measures of redundancy. The use of weak, reused, and common passwords is rampant on the internet. Without the added protection of multiple authentication schemes, a single mistake can result in the compromise of an account. For this reason, if multiple schemes are possible and also easy to use, they should be implemented and required.",,High,
64 CWE-321,EN-Use of Hard-coded Cryptographic Key (Type: Base),The use of a hard-coded cryptographic key significantly increases the possibility that encrypted data may be recovered.,"This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
65 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. Incomplete filtering, such as removal of ""./"" sequences, can ultimately produce valid "".."" sequences due to a collapse into unsafe value (CWE-182).",,High,
66 CWE-322,EN-Key Exchange without Entity Authentication (Type: Base),The software performs a key exchange with an actor without verifying the identity of that actor.,"Performing a key exchange will preserve the integrity of the information sent between two entities, but this will not guarantee that the entities are who they claim they are. This may enable a set of ""man-in-the-middle"" attacks. Typically, this involves a victim client that contacts a malicious server that is impersonating a trusted server. If the client skips authentication or ignores an authentication failure, the malicious server may request authentication information from the user. The malicious server can then use this authentication information to log in to the trusted server using the victim's credentials, sniff traffic between the victim and trusted server, etc.",,High,"24 Deadly Sins of Software Security: ""Sin 23: Improper Use of PKI, Especially SSL."" Page 347
67 The Art of Software Security Assessment: Chapter 2, ""Untrustworthy Credentials"", Page 37."
68 CWE-323,"EN-Reusing a Nonce, Key Pair in Encryption (Type: Base)",Nonces should be used for the present occasion and only once.,"Performing a key exchange will preserve the integrity of the information sent between two entities, but this will not guarantee that the entities are who they claim they are. This may enable a set of ""man-in-the-middle"" attacks. Typically, this involves a victim client that contacts a malicious server that is impersonating a trusted server. If the client skips authentication or ignores an authentication failure, the malicious server may request authentication information from the user. The malicious server can then use this authentication information to log in to the trusted server using the victim's credentials, sniff traffic between the victim and trusted server, etc.",,High,
69 CWE-360,EN-Trust of System Event Data (Type: Base),Security based on event locations are insecure and can be spoofed.,"Events are a messaging system which may provide control data to programs listening for events. Events often do not have any type of authentication framework to allow them to be verified from a trusted source. Any application, in Windows, on a given desktop can send a message to any window on the same desktop. There is no authentication framework for these messages. Therefore, any message can be used to manipulate any process on the desktop if the process does not check the validity and safeness of those messages.",,High,
70 CWE-378,EN-Creation of Temporary File With Insecure Permissions (Type: Base),"Opening temporary files without appropriate measures or controls can leave the file, its contents and any function that it impacts vulnerable to attack.","If the revocation status of a certificate is not checked before each action that requires privileges, the system may be subject to a race condition. If a certificate is revoked after the initial check, all subsequent actions taken with the owner of the revoked certificate will lose all benefits guaranteed by the certificate. In fact, it is almost certain that the use of a revoked certificate indicates malicious activity.",,High,
71 CWE-416,EN-Use After Free (Type: Base),"Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.","The use of previously-freed memory can have any number of adverse consequences, ranging from the corruption of valid data to the execution of arbitrary code, depending on the instantiation and timing of the flaw. The simplest way data corruption may occur involves the system's reuse of the freed memory. Use-after-free errors have two common and sometimes overlapping causes:
72 Error conditions and other exceptional circumstances.
73 Confusion over which part of the program is responsible for freeing the memory.
74 In this scenario, the memory in question is allocated to another pointer validly at some point after it has been freed. The original pointer to the freed memory is used again and points to somewhere within the new allocation. As the data is changed, it corrupts the validly used memory; this induces undefined behavior in the process.
75 If the newly allocated data chances to hold a class, in C++ for example, various function pointers may be scattered within the heap data. If one of these function pointers is overwritten with an address to valid shellcode, execution of arbitrary code can be achieved.",,High,"24 Deadly Sins of Software Security: ""Sin 8: C++ Catastrophes."" Page 143"
76 CWE-457,EN-Use of Uninitialized Variable (Type: Variant),"The code uses a variable that has not been initialized, leading to unpredictable or unintended results.","In some languages such as C and C++, stack variables are not initialized by default. They generally contain junk data with the contents of stack memory before the function was invoked. An attacker can sometimes control or read these contents. In other languages or conditions, a variable that is not explicitly initialized can be given a default value that has security implications, depending on the logic of the program. The presence of an uninitialized variable can sometimes indicate a typographic error in the code.",,High,"Exploiting Uninitialized Data: http://www.felinemenace.org/~mercy/papers/UBehavior/UBehavior.zip
77 MS08-014 : The Case of the Uninitialized Stack Variable Vulnerability: http://blogs.technet.com/swi/archive/2008/03/11/the-case-of-the-uninitialized-stack-variable-vulnerability.aspx
78 24 Deadly Sins of Software Security: ""Sin 8: C++ Catastrophes."" Page 143
79 The Art of Software Security Assessment: Chapter 7, ""Variable Initialization"", Page 312."
80 CWE-467,EN-Use of sizeof() on a Pointer Type (Type: Variant),"The code calls sizeof() on a malloced pointer type, which always returns the wordsize/8. This can produce an unexpected result if the programmer intended to determine how much memory has been allocated.","Data-structure sentinels are often used to mark the structure of data. A common example of this is the null character at the end of strings or a special sentinel to mark the end of a linked list. It is dangerous to allow this type of control data to be easily accessible. Therefore, it is important to protect from the addition or modification of sentinels.",,High,EXP01-A. Do not take the sizeof a pointer to determine the size of a type: https://www.securecoding.cert.org/confluence/display/seccode/EXP01-A.+Do+not+take+the+sizeof+a+pointer+to+determine+the+size+of+a+type
81 CWE-486,EN-Comparison of Classes by Name (Type: Variant),"The program compares classes by name, which can cause it to use the wrong class when multiple classes can have the same name.","If the decision to trust the methods and data of an object is based on the name of a class, it is possible for malicious users to send objects of the same name as trusted classes and thereby gain the trust afforded to known classes and types.",,High,
82 CWE-493,EN-Critical Public Variable Without Final Modifier (Type: Variant),"The product has a critical public variable that is not final, which allows the variable to be modified to contain unexpected values.","If a field is non-final and public, it can be changed once the value is set by any function that has access to the class which contains the field. This could lead to a vulnerability if other parts of the program make assumptions about the contents of that field.",,High,
83 CWE-499,EN-Serializable Class Containing Sensitive Data (Type: Variant),"The code contains a class with sensitive data, but the class does not explicitly deny serialization. The data can be accessed by serializing the class through another class.","Serializable classes are effectively open classes since data cannot be hidden in them. Classes that do not explicitly deny serialization can be serialized by any other class, which can then in turn use the data stored inside it.",,High,
84 CWE-500,EN-Public Static Field Not Marked Final (Type: Variant),"An object contains a public static field that is not marked final, which might allow it to be modified in unexpected ways.",Public static variables can be read without an accessor and changed without a mutator by any classes in the application.,,High,
85 CWE-515,EN-Covert Storage Channel (Type: Base),A covert storage channel transfers information through the setting of bits by one program and the reading of those bits by another. What distinguishes this case from that of ordinary operation is that the bits are used to convey encoded information.,"Covert storage channels occur when out-of-band data is stored in messages for the purpose of memory reuse. Covert channels are frequently classified as either storage or timing channels. Examples would include using a file intended to hold only audit information to convey user passwords--using the name of a file or perhaps status bits associated with it that can be read by all users to signal the contents of the file. Steganography, concealing information in such a manner that no one but the intended recipient knows of the existence of the message, is a good example of a covert storage channel.",,High,
86 CWE-639,EN-Authorization Bypass Through User-Controlled Key (Type: Base),The system's authorization functionality does not prevent one user from gaining access to another user's data or record by modifying the key value identifying the data.,"Retrieval of a user record occurs in the system based on some key value that is under user control. The key would typically identify a user related record stored in the system and would be used to lookup that record for presentation to the user. It is likely that an attacker would have to be an authenticated user in the system. However, the authorization process would not properly check the data access operation to ensure that the authenticated user performing the operation has sufficient entitlements to perform the requested data access, hence bypassing any other authorization checks present in the system. One manifestation of this weakness would be if a system used sequential or otherwise easily guessable session ids that would allow one user to easily switch to another user's session and read/modify their data.",,High,
87 CWE-640,EN-Weak Password Recovery Mechanism for Forgotten Password (Type: Base),"The software contains a mechanism for users to recover or change their passwords without knowing the original password, but the mechanism is weak.","It is common for an application to have a mechanism that provides a means for a user to gain access to their account in the event they forget their password. Very often the password recovery mechanism is weak, which has the effect of making it more likely that it would be possible for a person other than the legitimate system user to gain access to that user's account.
88 This weakness may be that the security question is too easy to guess or find an answer to (e.g. because it is too common). Or there might be an implementation weakness in the password recovery mechanism code that may for instance trick the system into e-mailing the new password to an e-mail account other than that of the user. There might be no throttling done on the rate of password resets so that a legitimate user can be denied service by an attacker if an attacker tries to recover their password in a rapid succession. The system may send the original password to the user rather than generating a new temporary password. In summary, password recovery functionality, if not carefully designed and implemented can often become the system's weakest link that can be misused in a way that would allow an attacker to gain unauthorized access to the system. Weak password recovery schemes completely undermine a strong password authentication scheme.",,High,"24 Deadly Sins of Software Security: ""Sin 19: Use of Weak Password-Based Systems."" Page 279"
89 CWE-642,EN-External Control of Critical State Data (Type: Class),"The software stores security-critical state information about its users, or the software itself, in a location that is accessible to unauthorized actors.","If an attacker can modify the state information without detection, then it could be used to perform unauthorized actions or access unexpected resources, since the application programmer does not expect that the state can be changed.
90 State information can be stored in various locations such as a cookie, in a hidden web form field, input parameter or argument, an environment variable, a database record, within a settings file, etc. All of these locations have the potential to be modified by an attacker. When this state information is used to control security or determine resource usage, then it may create a vulnerability. For example, an application may perform authentication, then save the state in an ""authenticated=true"" cookie. An attacker may simply create this cookie in order to bypass the authentication.",,High,"Top 10 2007-Insecure Direct Object Reference: http://www.owasp.org/index.php/Top_10_2007-A4
91 HMAC: http://en.wikipedia.org/wiki/Hmac
92 24 Deadly Sins of Software Security: ""Sin 4: Use of Magic URLs, Predictable Cookies, and Hidden Form Fields."" Page 75"
93 CWE-643,EN-Improper Neutralization of Data within XPath Expressions (XPath Injection) (Type: Base),"The software uses external input to dynamically construct an XPath expression used to retrieve data from an XML database, but it does not neutralize or incorrectly neutralizes that input. This allows an attacker to control the structure of the query.","The net effect is that the attacker will have control over the information selected from the XML database and may use that ability to control application flow, modify logic, retrieve unauthorized data, or bypass important checks (e.g. authentication).",,High,"XPath Injection: http://www.webappsec.org/projects/threat/classes/xpath_injection.shtml
94 The Art of Software Security Assessment: Chapter 17, ""XPath Injection"", Page 1070."
95 CWE-644,EN-Improper Neutralization of HTTP Headers for Scripting Syntax (Type: Variant),"The application does not neutralize or incorrectly neutralizes web scripting syntax in HTTP headers that can be used by web browser components that can process raw headers, such as Flash.","An attacker may be able to conduct cross-site scripting and other attacks against users who have these components enabled.
96 If an application does not neutralize user controlled data being placed in the header of an HTTP response coming from the server, the header may contain a script that will get executed in the client's browser context, potentially resulting in a cross site scripting vulnerability or possibly an HTTP response splitting attack. It is important to carefully control data that is being placed both in HTTP response header and in the HTTP response body to ensure that no scripting syntax is present, taking various encodings into account.",,High,
97 CWE-645,EN-Overly Restrictive Account Lockout Mechanism (Type: Base),"The software contains an account lockout protection mechanism, but the mechanism is too restrictive and can be triggered too easily. This allows attackers to deny service to legitimate users by causing their accounts to be locked out.","Account lockout is a security feature often present in applications as a countermeasure to the brute force attack on the password based authentication mechanism of the system. After a certain number of failed login attempts, the users' account may be disabled for a certain period of time or until it is unlocked by an administrator. Other security events may also possibly trigger account lockout. However, an attacker may use this very security feature to deny service to legitimate system users. It is therefore important to ensure that the account lockout security mechanism is not overly restrictive.",,High,
98 CWE-646,EN-Reliance on File Name or Extension of Externally-Supplied File (Type: Variant),"The software allows a file to be uploaded, but it relies on the file name or extension of the file to determine the appropriate behaviors. This could be used by attackers to cause the file to be misclassified and processed in a dangerous fashion.","An application might use the file name or extension of of a user-supplied file to determine the proper course of action, such as selecting the correct process to which control should be passed, deciding what data should be made available, or what resources should be allocated. If the attacker can cause the code to misclassify the supplied file, then the wrong action could occur. For example, an attacker could supply a file that ends in a "".php.gif"" extension that appears to be a GIF image, but would be processed as PHP code. In extreme cases, code execution is possible, but the attacker could also cause exhaustion of resources, denial of service, exposure of debug or system data (including application source code), or being bound to a particular server side process. This weakness may be due to a vulnerability in any of the technologies used by the web and application servers, due to misconfiguration, or resultant from another flaw in the application itself.",,High,
99 CWE-647,EN-Use of Non-Canonical URL Paths for Authorization Decisions (Type: Variant),The software defines policy namespaces and makes authorization decisions based on the assumption that a URL is canonical. This can allow a non-canonical URL to bypass the authorization.,"If an application defines policy namespaces and makes authorization decisions based on the URL, but it does not require or convert to a canonical URL before making the authorization decision, then it opens the application to attack. For example, if the application only wants to allow access to http://www.example.com/mypage, then the attacker might be able to bypass this restriction using equivalent URLs such as:
100 http://WWW.EXAMPLE.COM/mypage
101 http://www.example.com/%6Dypage (alternate encoding)
102 http://192.168.1.1/mypage (IP address)
103 http://www.example.com/mypage/ (trailing /)
104 http://www.example.com:80/mypage
105 Therefore it is important to specify access control policy that is based on the path information in some canonical form with all alternate encodings rejected (which can be accomplished by a default deny rule).",,High,
106 CWE-649,EN-Reliance on Obfuscation or Encryption of Security-Relevant Inputs without Integrity Checking (Type: Base),"The software uses obfuscation or encryption of inputs that should not be mutable by an external actor, but the software does not use integrity checks to detect if those inputs have been modified.","When an application relies on obfuscation or incorrectly applied / weak encryption to protect client-controllable tokens or parameters, that may have an effect on the user state, system state, or some decision made on the server. Without protecting the tokens/parameters for integrity, the application is vulnerable to an attack where an adversary blindly traverses the space of possible values of the said token/parameter in order to attempt to gain an advantage. The goal of the attacker is to find another admissible value that will somehow elevate his or her privileges in the system, disclose information or change the behavior of the system in some way beneficial to the attacker. If the application does not protect these critical tokens/parameters for integrity, it will not be able to determine that these values have been tampered with. Measures that are used to protect data for confidentiality should not be relied upon to provide the integrity service.",,High,
107 CWE-650,EN-Trusting HTTP Permission Methods on the Server Side (Type: Variant),"The server contains a protection mechanism that assumes that any URI that is accessed using HTTP GET will not cause a state change to the associated resource. This might allow attackers to bypass intended access restrictions and conduct resource modification and deletion attacks, since some applications allow GET to modify state.","An application may disallow the HTTP requests to perform DELETE, PUT and POST operations on the resource representation, believing that it will be enough to prevent unintended resource alterations. Even though the HTTP GET specification requires that GET requests should not have side effects, there is nothing in the HTTP protocol itself that prevents the HTTP GET method from performing more than just query of the data. For instance, it is a common practice with REST based Web Services to have HTTP GET requests modifying resources on the server side. Whenever that happens however, the access control needs to be properly enforced in the application. No assumptions should be made that only HTTP DELETE, PUT, and POST methods have the power to alter the representation of the resource being accessed in the request.",,High,
108 CWE-652,EN-Improper Neutralization of Data within XQuery Expressions (XQuery Injection) (Type: Base),"The software uses external input to dynamically construct an XQuery expression used to retrieve data from an XML database, but it does not neutralize or incorrectly neutralizes that input. This allows an attacker to control the structure of the query.","The net effect is that the attacker will have control over the information selected from the XML database and may use that ability to control application flow, modify logic, retrieve unauthorized data, or bypass important checks (e.g. authentication).",,High,
109 CWE-676,EN-Use of Potentially Dangerous Function (Type: Base),"The program invokes a potentially dangerous function that could introduce a vulnerability if it is used incorrectly, but the function can also be used safely.","Typically, a product defines its control sphere within the code itself, or through configuration by the product's administrator. In some cases, an external party can change the definition of the control sphere. This is typically a resultant weakness.",,High,"Security Development Lifecycle (SDL) Banned Function Calls: http://msdn.microsoft.com/en-us/library/bb288454.aspx
110 Writing Secure Code: Chapter 5, ""Safe String Handling"" Page 156, 160
111 The Art of Software Security Assessment: Chapter 8, ""C String Handling"", Page 388."
112 CWE-682,EN-Incorrect Calculation (Type: Class),The software performs a calculation that generates incorrect or unintended results that are later used in security-critical decisions or resource management..,"When software performs a security-critical calculation incorrectly, it might lead to incorrect resource allocations, incorrect privilege assignments, or failed comparisons among other things. Many of the direct results of an incorrect calculation can lead to even larger problems such as failed protection mechanisms or even arbitrary code execution.",,High,"SafeInt: http://safeint.codeplex.com/
113 24 Deadly Sins of Software Security: ""Sin 7: Integer Overflows."" Page 119
114 The Art of Software Security Assessment: Chapter 6, ""Signed Integer Boundaries"", Page 220."
115 CWE-78,EN-Improper Neutralization of Special Elements used in an OS Command (OS Command Injection) (Type: Base),"The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component..","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 does not follow the principle of least privilege, because the attacker-controlled commands may run with special system privileges that increases the amount of damage.
116 There are at least two subtypes of OS command injection:
117 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 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.
118 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.
119 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.",,High,"Exploiting Software: How to Break Code
120 Meta-Character Vulnerabilities: http://www.cs.purdue.edu/homes/cs390s/slides/week09.pdf
121 OS Commanding: http://projects.webappsec.org/OS-Commanding
122 The World Wide Web Security FAQ: http://www.w3.org/Security/Faq/wwwsf4.html
123 Security Issues in Perl Scripts: http://www.cgisecurity.com/lib/sips.html
124 24 Deadly Sins of Software Security: ""Sin 10: Command Injection."" Page 171
125 Top 25 Series - Rank 9 - OS Command Injection: http://blogs.sans.org/appsecstreetfighter/2010/02/24/top-25-series-rank-9-os-command-injection/
126 OWASP Enterprise Security API (ESAPI) Project: http://www.owasp.org/index.php/ESAPI
127 Least Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html
128 The Art of Software Security Assessment: Chapter 8, ""Shell Metacharacters"", Page 425."
129 CWE-784,EN-Reliance on Cookies without Validation and Integrity Checking in a Security Decision (Type: Variant),"The application uses a protection mechanism that relies on the existence or values of a cookie, but it does not properly ensure that the cookie is valid for the associated user.","Attackers can easily modify cookies, within the browser or by implementing the client-side code outside of the browser. Attackers can bypass protection mechanisms such as authorization and authentication by modifying the cookie to contain an expected value.",,High,"Unforgivable Vulnerabilities: http://cve.mitre.org/docs/docs-2007/unforgivable.pdf
130 Writing Secure Code: Chapter 13, ""Sensitive Data in Cookies and Fields"" Page 435"
131 CWE-862,EN-Missing Authorization (Type: Class),The software does not perform an authorization check when an actor attempts to access a resource or perform an action.,"Assuming a user with a given identity, authorization is the process of determining whether that user can access a given resource, based on the user's privileges and any permissions or other access-control specifications that apply to the resource.
132 When access control checks are not applied, users are able to access data or perform actions that they should not be allowed to perform. This can lead to a wide range of problems, including information exposures, denial of service, and arbitrary code execution.",,High,"Role Based Access Control and Role Based Security: http://csrc.nist.gov/groups/SNS/rbac/
133 Writing Secure Code: Chapter 4, ""Authorization"" Page 114; Chapter 6, ""Determining Appropriate Access Control"" Page 171
134 Top 25 Series - Rank 5 - Improper Access Control (Authorization): http://blogs.sans.org/appsecstreetfighter/2010/03/04/top-25-series-rank-5-improper-access-control-authorization/
135 OWASP Enterprise Security API (ESAPI) Project: http://www.owasp.org/index.php/ESAPI
136 Authentication using JAAS: http://www.javaranch.com/journal/2008/04/authentication-using-JAAS.html
137 The Art of Software Security Assessment: Chapter 2, ""Common Vulnerabilities of Authorization"", Page 39."
138 CWE-863,EN-Incorrect Authorization (Type: Class),"The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.","Assuming a user with a given identity, authorization is the process of determining whether that user can access a given resource, based on the user's privileges and any permissions or other access-control specifications that apply to the resource.
139 When access control checks are incorrectly applied, users are able to access data or perform actions that they should not be allowed to perform. This can lead to a wide range of problems, including information exposures, denial of service, and arbitrary code execution.",,High,"Role Based Access Control and Role Based Security: http://csrc.nist.gov/groups/SNS/rbac/
140 Writing Secure Code: Chapter 4, ""Authorization"" Page 114; Chapter 6, ""Determining Appropriate Access Control"" Page 171
141 Top 25 Series - Rank 5 - Improper Access Control (Authorization): http://blogs.sans.org/appsecstreetfighter/2010/03/04/top-25-series-rank-5-improper-access-control-authorization/
142 Authentication using JAAS: http://www.javaranch.com/journal/2008/04/authentication-using-JAAS.html
143 OWASP Enterprise Security API (ESAPI) Project: http://www.owasp.org/index.php/ESAPI
144 The Art of Software Security Assessment: Chapter 2, ""Common Vulnerabilities of Authorization"", Page 39."
145 CWE-99,EN-Improper Control of Resource Identifiers (Resource Injection) (Type: Base),"The software receives input from an upstream component, but it does not restrict or incorrectly restricts the input before it is used as an identifier for a resource that may be outside the intended sphere of control.",This may enable an attacker to access or modify otherwise protected system resources.,,High,
146 CWE-120,EN-Buffer Copy without Checking Size of Input (Classic Buffer Overflow) (Type: Base),"The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.","A buffer overflow condition exists when a program attempts to put more data in a buffer than it can hold, or when a program attempts to put data in a memory area outside of the boundaries of a buffer. The simplest type of error, and the most common cause of buffer overflows, is the ""classic"" case in which the program copies the buffer without restricting how much is copied. Other variants exist, but the existence of a classic overflow strongly suggests that the programmer is not considering even the most basic of security protections.",,High to Very High,"Writing Secure Code: Chapter 5, ""Public Enemy #1: The Buffer Overrun"" Page 127
147 24 Deadly Sins of Software Security: ""Sin 5: Buffer Overruns."" Page 89
148 Using the Strsafe.h Functions: http://msdn.microsoft.com/en-us/library/ms647466.aspx
149 Safe C String Library v1.0.3: http://www.zork.org/safestr/
150 Address Space Layout Randomization in Windows Vista: http://blogs.msdn.com/michael_howard/archive/2006/05/26/address-space-layout-randomization-in-windows-vista.aspx
151 Limiting buffer overflows with ExecShield: http://www.redhat.com/magazine/009jul05/features/execshield/
152 PaX: http://en.wikipedia.org/wiki/PaX
153 Top 25 Series - Rank 3 - Classic Buffer Overflow: http://software-security.sans.org/blog/2010/03/02/top-25-series-rank-3-classic-buffer-overflow/
154 Understanding DEP as a mitigation technology part 1: http://blogs.technet.com/b/srd/archive/2009/06/12/understanding-dep-as-a-mitigation-technology-part-1.aspx
155 Least Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html
156 The Art of Software Security Assessment: Chapter 3, ""Nonexecutable Stack"", Page 76.
157 The Art of Software Security Assessment: Chapter 5, ""Protection Mechanisms"", Page 189.
158 The Art of Software Security Assessment: Chapter 8, ""C String Handling"", Page 388."
159 CWE-122,EN-Heap-based Buffer Overflow (Type: Variant),"A heap overflow condition is a buffer overflow, where the buffer that can be overwritten is allocated in the heap portion of memory, generally meaning that the buffer was allocated using a routine such as malloc().","A buffer overflow condition exists when a program attempts to put more data in a buffer than it can hold, or when a program attempts to put data in a memory area outside of the boundaries of a buffer. The simplest type of error, and the most common cause of buffer overflows, is the ""classic"" case in which the program copies the buffer without restricting how much is copied. Other variants exist, but the existence of a classic overflow strongly suggests that the programmer is not considering even the most basic of security protections.",,High to Very High,"Writing Secure Code: Chapter 5, ""Heap Overruns"" Page 138
160 24 Deadly Sins of Software Security: ""Sin 5: Buffer Overruns."" Page 89
161 The Art of Software Security Assessment: Chapter 3, ""Nonexecutable Stack"", Page 76.
162 The Art of Software Security Assessment: Chapter 5, ""Protection Mechanisms"", Page 189."
163 CWE-131,EN-Incorrect Calculation of Buffer Size (Type: Base),"The software does not correctly calculate the size to be used when allocating a buffer, which could lead to a buffer overflow.","If an attacker can manipulate the length parameter associated with an input such that it is inconsistent with the actual length of the input, this can be leveraged to cause the target application to behave in unexpected, and possibly, malicious ways. One of the possible motives for doing so is to pass in arbitrarily large input to the application. Another possible motivation is the modification of application state by including invalid data for subsequent properties of the application. Such weaknesses commonly lead to attacks such as buffer overflows and execution of arbitrary code.",,High to Very High,"SafeInt: http://safeint.codeplex.com/
164 Top 25 Series - Rank 18 - Incorrect Calculation of Buffer Size: http://software-security.sans.org/blog/2010/03/19/top-25-series-rank-18-incorrect-calculation-of-buffer-size
165 Address Space Layout Randomization in Windows Vista: http://blogs.msdn.com/michael_howard/archive/2006/05/26/address-space-layout-randomization-in-windows-vista.aspx
166 Understanding DEP as a mitigation technology part 1: http://blogs.technet.com/b/srd/archive/2009/06/12/understanding-dep-as-a-mitigation-technology-part-1.aspx
167 PaX: http://en.wikipedia.org/wiki/PaX
168 Least Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html
169 Writing Secure Code: Chapter 20, ""Integer Overflows"" Page 620
170 24 Deadly Sins of Software Security: ""Sin 5: Buffer Overruns."" Page 89
171 The Art of Software Security Assessment: Chapter 8, ""Incrementing Pointers Incorrectly"", Page 401."
172 CWE-22,EN-Improper Limitation of a Pathname to a Restricted Directory (Path Traversal) (Type: Class),"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 neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.","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.
173 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.",,High to Very High,"Writing Secure Code: Chapter 11, ""Directory Traversal and Using Parent Paths (..)"" Page 370
174 OWASP Enterprise Security API (ESAPI) Project: http://www.owasp.org/index.php/ESAPI
175 Testing for Path Traversal (OWASP-AZ-001): http://www.owasp.org/index.php/Testing_for_Path_Traversal_(OWASP-AZ-001)
176 Top 25 Series - Rank 7 - Path Traversal: http://blogs.sans.org/appsecstreetfighter/2010/03/09/top-25-series-rank-7-path-traversal/
177 Least Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html
178 The Art of Software Security Assessment: Chapter 9, ""Filenames and Paths"", Page 503."
179 CWE-311,EN-Missing Encryption of Sensitive Data (Type: Base),The software does not encrypt sensitive or critical information before storage or transmission.,"The lack of proper data encryption passes up the guarantees of confidentiality, integrity, and accountability that properly implemented encryption conveys.",,High to Very High,"Writing Secure Code: Chapter 9, ""Protecting Secret Data"" Page 299
180 24 Deadly Sins of Software Security: ""Sin 17: Failure to Protect Stored Data."" Page 253
181 Top 25 Series - Rank 10 - Missing Encryption of Sensitive Data: http://blogs.sans.org/appsecstreetfighter/2010/02/26/top-25-series-rank-10-missing-encryption-of-sensitive-data/
182 The Art of Software Security Assessment: Chapter 2, ""Common Vulnerabilities of Encryption"", Page 43.
183 SECURITY REQUIREMENTS FOR CRYPTOGRAPHIC MODULES: http://csrc.nist.gov/publications/fips/fips140-2/fips1402.pdf"
184 CWE-464,EN-Addition of Data Structure Sentinel (Type: Base),The accidental addition of a data-structure sentinel can cause serious programming logic problems.,"Data-structure sentinels are often used to mark the structure of data. A common example of this is the null character at the end of strings or a special sentinel to mark the end of a linked list. It is dangerous to allow this type of control data to be easily accessible. Therefore, it is important to protect from the addition or modification of sentinels.",,High to Very High,
185 CWE-67,EN-Improper Handling of Windows Device Names (Type: Variant),"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 exposure when the application attempts to process the pathname as a regular file.","Not properly handling 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.",,High to Very High,"Writing Secure Code
186 The Art of Software Security Assessment: Chapter 11, ""Device Files"", Page 666."
187 CWE-73,EN-External Control of File Name or Path (Type: Class),The software allows user input to control or influence paths or file names that are used in filesystem operations.,"This could allow an attacker to access or modify system files or other files that are critical to the application.
188 Path manipulation errors occur when the following two conditions are met:
189 1. An attacker can specify a path used in an operation on the filesystem.
190 2. By specifying the resource, the attacker gains a capability that would not otherwise be permitted.
191 For example, the program may give the attacker the ability to overwrite the specified file or run with a configuration controlled by the attacker.",,High to Very High,OWASP Enterprise Security API (ESAPI) Project: http://www.owasp.org/index.php/ESAPI
192 CWE-76,EN-Improper Neutralization of Equivalent Special Elements (Type: Base),"The software properly neutralizes certain special elements, but it improperly neutralizes equivalent special elements.","The software may have a fixed list of special characters it believes is complete. However, there may be alternate encodings, or representations that also have the same meaning. For example, the software may filter out a leading slash (/) to prevent absolute path names, but does not account for a tilde (~) followed by a user name, which on some *nix systems could be expanded to an absolute pathname. Alternately, the software might filter a dangerous ""-e"" command-line switch when calling an external program, but it might not account for ""--exec"" or other switches that have the same semantics.",,High to Very High,
193 CWE-79,EN-Improper Neutralization of Input During Web Page Generation (Cross-site Scripting) (Type: Base),The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.,"Cross-site scripting (XSS) vulnerabilities occur when:
194 1. Untrusted data enters a web application, typically from a web request.
195 2. The web application dynamically generates a web page that contains this untrusted data.
196 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.
197 4. A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
198 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.
199 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.
200 There are three main kinds of XSS:
201 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.
202 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 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.
203 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.
204 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.""
205 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.",,High to Very High,"XSS Attacks
206 24 Deadly Sins of Software Security: ""Sin 2: Web-Server Related Vulnerabilities (XSS, XSRF, and Response Splitting)."" Page 31
207 24 Deadly Sins of Software Security: ""Sin 3: Web-Client Related Vulnerabilities (XSS)."" Page 63
208 Cross-site scripting: http://en.wikipedia.org/wiki/Cross-site_scripting
209 Writing Secure Code: Chapter 13, ""Web-Specific Input Issues"" Page 413
210 XSS (Cross Site Scripting) Cheat Sheet: http://ha.ckers.org/xss.html
211 Mitigating Cross-site Scripting With HTTP-only Cookies: http://msdn.microsoft.com/en-us/library/ms533046.aspx
212 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
213 OWASP Enterprise Security API (ESAPI) Project: http://www.owasp.org/index.php/ESAPI
214 XSS Defense HOWTO: http://blog.modsecurity.org/2008/07/do-you-know-how.html
215 Web Application Firewall: http://www.owasp.org/index.php/Web_Application_Firewall
216 Web Application Firewall Evaluation Criteria: http://www.webappsec.org/projects/wafec/v1/wasc-wafec-v1.0.html
217 Firefox Implements httpOnly And is Vulnerable to XMLHTTPRequest
218 XMLHttpRequest allows reading HTTPOnly cookies: https://bugzilla.mozilla.org/show_bug.cgi?id=380418
219 Apache Wicket: http://wicket.apache.org/
220 XSS (Cross Site Scripting) Prevention Cheat Sheet: http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
221 DOM based XSS Prevention Cheat Sheet: http://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet
222 Top 25 series - Rank 1 - Cross Site Scripting: http://blogs.sans.org/appsecstreetfighter/2010/02/22/top-25-series-rank-1-cross-site-scripting/
223 The Art of Software Security Assessment: Chapter 17, ""Cross Site Scripting"", Page 1071."
224 CWE-80,EN-Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS) (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes 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.","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 improper conversion of such special characters to respective context-appropriate entities before displaying them to the user.",,High to Very High,
225 CWE-98,EN-Improper Control of Filename for Include/Require Statement in PHP Program (PHP Remote File Inclusion) (Type: Base),"The PHP application receives input from an upstream component, but it does not restrict or incorrectly restricts the input before its usage in ""require,"" ""include,"" or similar functions.","In certain versions and configurations of PHP, this can allow an attacker to specify a URL to a remote location from which the software will obtain the code to execute. In other cases in association with path traversal, the attacker can specify a local file that may contain executable statements that can be parsed by PHP.",,High to Very High,"Testing for Path Traversal (OWASP-AZ-001): http://www.owasp.org/index.php/Testing_for_Path_Traversal_(OWASP-AZ-001)
226 Least Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html
227 A Study in Scarlet: http://www.cgisecurity.com/lib/studyinscarlet.txt
228 Suhosin: http://www.hardened-php.net/suhosin/
229 Top 25 Series - Rank 13 - PHP File Inclusion: http://blogs.sans.org/appsecstreetfighter/2010/03/11/top-25-series-rank-13-php-file-inclusion/"
230 CWE-188,EN-Reliance on Data/Memory Layout (Type: Base),"The software makes invalid assumptions about how protocol data or memory is organized at a lower level, resulting in unintended program behavior.","For example, an attacker might succeed in authentication by providing a small password that matches the associated portion of the larger, correct password.",,Low,"The Art of Software Security Assessment: Chapter 6, ""Structure Padding"", Page 284."
231 CWE-197,EN-Numeric Truncation Error (Type: Base),Truncation errors occur when a primitive is cast to a primitive of a smaller size and data is lost in the conversion.,"When a primitive is cast to a smaller primitive, the high order bits of the large value are lost in the conversion, potentially resulting in an unexpected value that is not equal to the original value. This value may be required as an index into a buffer, a loop iterator, or simply necessary state data. In any case, the value cannot be trusted and the system will be in an undefined state. While this method may be employed viably to isolate the low bits of a value, this usage is rare, and truncation usually implies that an implementation error has occurred.",,Low,"The Art of Software Security Assessment: Chapter 6, ""Truncation"", Page 259."
232 CWE-252,EN-Unchecked Return Value (Type: Base),"The software does not check the return value from a method or function, which can prevent it from detecting unexpected states and conditions.","Two common programmer assumptions are ""this function call can never fail"" and ""it doesn't matter if this function call fails"". If an attacker can force the function to fail or otherwise return a value that is not expected, then the subsequent program logic could lead to a vulnerability, because the software is not in a state that the programmer assumes. For example, if the program calls a function to drop privileges but does not check the return code to ensure that privileges were successfully dropped, then the program will continue to operate with the higher privileges.",,Low,"The Art of Software Security Assessment: Chapter 7, ""Program Building Blocks"" Page 341.
233 Writing Secure Code: Chapter 20, ""Checking Returns"" Page 624
234 24 Deadly Sins of Software Security: ""Sin 11: Failure to Handle Errors Correctly."" Page 183
235 ERR10-CPP. Check for error conditions: https://www.securecoding.cert.org/confluence/display/cplusplus/ERR10-CPP.+Check+for+error+conditions"
236 CWE-253,EN-Incorrect Check of Function Return Value (Type: Base),"The software incorrectly checks a return value from a function, which prevents the software from detecting errors or exceptional conditions.","Two common programmer assumptions are ""this function call can never fail"" and ""it doesn't matter if this function call fails"". If an attacker can force the function to fail or otherwise return a value that is not expected, then the subsequent program logic could lead to a vulnerability, because the software is not in a state that the programmer assumes. For example, if the program calls a function to drop privileges but does not check the return code to ensure that privileges were successfully dropped, then the program will continue to operate with the higher privileges.",,Low,"The Art of Software Security Assessment: Chapter 7, ""Return Value Testing and Interpretation"", Page 340."
237 CWE-296,EN-Improper Following of a Certificates Chain of Trust (Type: Base),"The software does not follow, or incorrectly follows, the chain of trust for a certificate back to a trusted root certificate, resulting in incorrect trust of any resource that is associated with that certificate.","If a system does not follow the chain of trust of a certificate to a root server, the certificate loses all usefulness as a metric of trust. Essentially, the trust gained from a certificate is derived from a chain of trust -- with a reputable trusted entity at the end of that list. The end user must trust that reputable source, and this reputable source must vouch for the resource in question through the medium of the certificate.
238 In some cases, this trust traverses several entities who vouch for one another. The entity trusted by the end user is at one end of this trust chain, while the certificate-wielding resource is at the other end of the chain. If the user receives a certificate at the end of one of these trust chains and then proceeds to check only that the first link in the chain, no real trust has been derived, since the entire chain must be traversed back to a trusted source to verify the certificate.
239 There are several ways in which the chain of trust might be broken, including but not limited to:
240 Any certificate in the chain is self-signed, unless it the root.
241 Not every intermediate certificate is checked, starting from the original certificate all the way up to the root certificate.
242 An intermediate, CA-signed certificate does not have the expected Basic Constraints or other important extensions.
243 The root certificate has been compromised or authorized to the wrong party.",,Low,"The Most Dangerous Code in the World: Validating SSL Certificates in Non-Browser Software: http://www.cs.utexas.edu/~shmat/shmat_ccs12.pdf
244 24 Deadly Sins of Software Security: ""Sin 23: Improper Use of PKI, Especially SSL."" Page 347"
245 CWE-298,EN-Improper Validation of Certificate Expiration (Type: Variant),"A certificate expiration is not validated or is incorrectly validated, so trust may be assigned to certificates that have been abandoned due to age.","When the expiration of a certificate is not taken into account, no trust has necessarily been conveyed through it. Therefore, the validity of the certificate cannot be verified and all benefit of the certificate is lost.",,Low,"24 Deadly Sins of Software Security: ""Sin 23: Improper Use of PKI, Especially SSL."" Page 347"
246 CWE-324,EN-Use of a Key Past its Expiration Date (Type: Base),"The product uses a cryptographic key or password past its expiration date, which diminishes its safety significantly by increasing the timing window for cracking attacks against that key.","While the expiration of keys does not necessarily ensure that they are compromised, it is a significant concern that keys which remain in use for prolonged periods of time have a decreasing probability of integrity. For this reason, it is important to replace keys within a period of time proportional to their strength.",,Low,"24 Deadly Sins of Software Security: ""Sin 23: Improper Use of PKI, Especially SSL."" Page 347"
247 CWE-379,EN-Creation of Temporary File in Directory with Incorrect Permissions (Type: Base),The software creates a temporary file in a directory whose permissions allow unintended actors to determine the file's existence or otherwise access that file.,"On some operating systems, the fact that the temporary file exists may be apparent to any user with sufficient privileges to access that directory. Since the file is visible, the application that is using the temporary file could be known. If one has access to list the processes on the system, the attacker has gained information about what the user is doing at that time. By correlating this with the applications the user is running, an attacker could potentially discover what a user's actions are. From this, higher levels of security could be breached.",,Low,"The Art of Software Security Assessment: Chapter 9, ""Temporary Files"", Page 538."
248 CWE-462,EN-Duplicate Key in Associative List (Alist) (Type: Base),Duplicate keys in associative lists can lead to non-unique keys being mistaken for an error.,"A duplicate key entry -- if the alist is designed properly -- could be used as a constant time replace function. However, duplicate key entries could be inserted by mistake. Because of this ambiguity, duplicate key entries in an association list are not recommended and should not be allowed.",,Low,
249 CWE-479,EN-Signal Handler Use of a Non-reentrant Function (Type: Variant),The program defines a signal handler that calls a non-reentrant function.,"Non-reentrant functions are functions that cannot safely be called, interrupted, and then recalled before the first call has finished without resulting in memory corruption. This can lead to an unexpected system state an unpredictable results with a variety of potential consequences depending on context, including denial of service and code execution.
250 Many functions are not reentrant, but some of them can result in the corruption of memory if they are used in a signal handler. The function call syslog() is an example of this. In order to perform its functionality, it allocates a small amount of memory as ""scratch space."" If syslog() is suspended by a signal call and the signal handler calls syslog(), the memory used by both of these functions enters an undefined, and possibly, exploitable state. Implementations of malloc() and free() manage metadata in global structures in order to track which memory is allocated versus which memory is available, but they are non-reentrant. Simultaneous calls to these functions can cause corruption of the metadata.",,Low,"The Art of Software Security Assessment: Chapter 13, ""Signal Vulnerabilities"", Page 791."
251 CWE-480,EN-Use of Incorrect Operator (Type: Base),"The programmer accidentally uses the wrong operator, which changes the application logic in security-relevant ways.","Non-reentrant functions are functions that cannot safely be called, interrupted, and then recalled before the first call has finished without resulting in memory corruption. This can lead to an unexpected system state an unpredictable results with a variety of potential consequences depending on context, including denial of service and code execution.
252 Many functions are not reentrant, but some of them can result in the corruption of memory if they are used in a signal handler. The function call syslog() is an example of this. In order to perform its functionality, it allocates a small amount of memory as ""scratch space."" If syslog() is suspended by a signal call and the signal handler calls syslog(), the memory used by both of these functions enters an undefined, and possibly, exploitable state. Implementations of malloc() and free() manage metadata in global structures in order to track which memory is allocated versus which memory is available, but they are non-reentrant. Simultaneous calls to these functions can cause corruption of the metadata.",,Low,"The Art of Software Security Assessment: Chapter 6, ""Typos"", Page 289."
253 CWE-481,EN-Assigning instead of Comparing (Type: Variant),The code uses an operator for assignment when the intention was to perform a comparison.,"In many languages the compare statement is very close in appearance to the assignment statement and are often confused. This bug is generally the result of a typo and usually causes obvious problems with program execution. If the comparison is in an if statement, the if statement will usually evaluate the value of the right-hand side of the predicate.",,Low,"The Art of Software Security Assessment: Chapter 6, ""Typos"", Page 289."
254 CWE-482,EN-Comparing instead of Assigning (Type: Variant),The code uses an operator for comparison when the intention was to perform an assignment.,"In many languages, the compare statement is very close in appearance to the assignment statement; they are often confused.",,Low,"The Art of Software Security Assessment: Chapter 6, ""Typos"", Page 289."
255 CWE-483,EN-Incorrect Block Delimitation (Type: Variant),"The code does not explicitly delimit a block that is intended to contain 2 or more statements, creating a logic error.","In some languages, braces (or other delimiters) are optional for blocks. When the delimiter is omitted, it is possible to insert a logic error in which a statement is thought to be in a block but is not. In some cases, the logic error can have security implications.",,Low,
256 CWE-641,EN-Improper Restriction of Names for Files and Other Resources (Type: Base),"The application constructs the name of a file or other resource using input from an upstream component, but does not restrict or incorrectly restricts the resulting name.","This may produce resultant weaknesses. For instance, if the names of these resources contain scripting characters, it is possible that a script may get executed in the client's browser if the application ever displays the name of the resource on a dynamically generated web page. Alternately, if the resources are consumed by some application parser, a specially crafted name can exploit some vulnerability internal to the parser, potentially resulting in execution of arbitrary code on the server machine. The problems will vary based on the context of usage of such malformed resource names and whether vulnerabilities are present in or assumptions are made by the targeted technology that would make code execution possible.",,Low,
257 CWE-648,EN-Incorrect Use of Privileged APIs (Type: Base),The application does not conform to the API requirements for a function call that requires extra privileges. This could allow attackers to gain privileges by causing the function to be called incorrectly.,"When an application contains certain functions that perform operations requiring an elevated level of privilege, the caller of a privileged API must be careful to:
258 ensure that assumptions made by the APIs are valid, such as validity of arguments
259 account for known weaknesses in the design/implementation of the API
260 call the API from a safe context
261 If the caller of the API does not follow these requirements, then it may allow a malicious user or process to elevate their privilege, hijack the process, or steal sensitive data.
262 For instance, it is important to know if privileged APIs do not shed their privileges before returning to the caller or if the privileged function might make certain assumptions about the data, context or state information passed to it by the caller. It is important to always know when and how privileged APIs can be called in order to ensure that their elevated level of privilege cannot be exploited.",,Low,
263 CWE-762,EN-Mismatched Memory Management Routines (Type: Variant),"The application attempts to return a memory resource to the system, but it calls a release function that is not compatible with the function that was originally used to allocate that resource.","This weakness can be generally described as mismatching memory management routines, such as:
264 The memory was allocated on the stack (automatically), but it was deallocated using the memory management routine free() (CWE-590), which is intended for explicitly allocated heap memory.
265 The memory was allocated explicitly using one set of memory management functions, and deallocated using a different set. For example, memory might be allocated with malloc() in C++ instead of the new operator, and then deallocated with the delete operator.
266 When the memory management functions are mismatched, the consequences may be as severe as code execution, memory corruption, or program crash. Consequences and ease of exploit will vary depending on the implementation of the routines and the object being managed.",,Low,"boost C++ Library Smart Pointers: http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/smart_ptr.htm
267 Valgrind: http://valgrind.org/"
268 CWE-783,EN-Operator Precedence Logic Error (Type: Variant),The program uses an expression in which operator precedence causes incorrect logic to be used.,"While often just a bug, operator precedence logic errors can have serious consequences if they are used in security-critical code, such as making an authentication decision.",,Low,"EXP00-C. Use parentheses for precedence of operation: https://www.securecoding.cert.org/confluence/display/seccode/EXP00-C.+Use+parentheses+for+precedence+of+operation
269 The Art of Software Security Assessment: Chapter 6, ""Precedence"", Page 287."
270 CWE-789,EN-Uncontrolled Memory Allocation (Type: Variant),"The product allocates memory based on an untrusted size value, but it does not validate or incorrectly validates the size, allowing arbitrary amounts of memory to be allocated.","This typically occurs when a pointer or its index is decremented to a position before the buffer, when pointer arithmetic results in a position before the beginning of the valid memory location, or when a negative index is used. These problems may be resultant from missing sentinel values (CWE-463) or trusting a user-influenced input length variable.",,Low,"The Art of Software Security Assessment: Chapter 10, ""Resource Limits"", Page 574."
271 CWE-333,EN-Improper Handling of Insufficient Entropy in TRNG (Type: Variant),True random number generators (TRNG) generally have a limited source of entropy and therefore can fail or block.,The rate at which true random numbers can be generated is limited. It is important that one uses them only when they are needed for security.,,Low to Medium,
272 CWE-367,EN-Time-of-check Time-of-use (TOCTOU) Race Condition (Type: Base),"The software checks the state of a resource before using that resource, but the resource's state can change between the check and the use in a way that invalidates the results of the check. This can cause the software to perform invalid actions when the resource is in an unexpected state.","This weakness can be security-relevant when an attacker can influence the state of the resource between check and use. This can happen with shared resources such as files, memory, or even variables in multithreaded programs.",,Low to Medium,"Portably Solving File TOCTTOU Races with Hardness Amplification: http://www.usenix.org/events/fast08/tech/tsafrir.html
273 24 Deadly Sins of Software Security: ""Sin 13: Race Conditions."" Page 205
274 The Art of Software Security Assessment: Chapter 9, ""TOCTOU"", Page 527."
275 CWE-404,EN-Improper Resource Shutdown or Release (Type: Base),The program does not release or incorrectly releases a resource before it is made available for re-use.,"When a resource is created or allocated, the developer is responsible for properly releasing the resource as well as accounting for all potential paths of expiration or invalidation, such as a set period of time or revocation.",,Low to Medium,"24 Deadly Sins of Software Security: ""Sin 8: C++ Catastrophes."" Page 143"
276 CWE-407,EN-Algorithmic Complexity (Type: Base),"An algorithm in a product has an inefficient worst-case computational complexity that may be detrimental to system performance and can be triggered by an attacker, typically using crafted manipulations that ensure that the worst case is being reached.","In the absence of a policy to restrict asymmetric resource consumption, the application or system cannot distinguish between legitimate transmissions and traffic intended to serve as an amplifying attack on target systems. Systems can often be configured to restrict the amount of traffic sent out on behalf of a client, based on the client's origin or access level. This is usually defined in a resource allocation policy. In the absence of a mechanism to keep track of transmissions, the system or application can be easily abused to transmit asymmetrically greater traffic than the request or client should be permitted to.",,Low to Medium,Algorithmic Complexity Attacks: http://www.cs.rice.edu/~scrosby/hash/CrosbyWallach_UsenixSec2003/index.html
277 CWE-415,EN-Double Free (Type: Variant),"The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations.","When a program calls free() twice with the same argument, the program's memory management data structures become corrupted. This corruption can cause the program to crash or, in some circumstances, cause two later calls to malloc() to return the same pointer. If malloc() returns the same value twice and the program later gives the attacker control over the data that is written into this doubly-allocated memory, the program becomes vulnerable to a buffer overflow attack.",,Low to Medium,"24 Deadly Sins of Software Security: ""Sin 8: C++ Catastrophes."" Page 143
278 The Art of Software Security Assessment: Chapter 7, ""Double Frees"", Page 379."
279 CWE-59,EN-Improper Link Resolution Before File Access (Link Following) (Type: Base),"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.","Some functions that offer security features supported by the OS are not available on all versions of the OS in common use. Likewise, functions are often deprecated or made obsolete for security reasons and should not be used.",,Low to Medium,"The Art of Software Security Assessment: Chapter 9, ""Symbolic Link Attacks"", Page 518."
280 CWE-601,EN-URL Redirection to Untrusted Site (Open Redirect) (Type: Variant),"A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.","An http parameter may contain a URL value and could cause the web application to redirect the request to the specified URL. By modifying the URL value to a malicious site, an attacker may successfully launch a phishing scam and steal user credentials. Because the server name in the modified link is identical to the original site, phishing attempts have a more trustworthy appearance.",,Low to Medium,"Exploitable Redirects on the Web: Identification, Prevalence, and Defense: http://www.cs.indiana.edu/cgi-pub/cshue/research/woot08.pdf
281 Open redirect vulnerabilities: definition and prevention: http://www.net-security.org/dl/insecure/INSECURE-Mag-17.pdf
282 Top 25 Series - Rank 23 - Open Redirect: http://software-security.sans.org/blog/2010/03/25/top-25-series-rank-23-open-redirect
283 OWASP Enterprise Security API (ESAPI) Project: http://www.owasp.org/index.php/ESAPI"
284 CWE-749,EN-Exposed Dangerous Method or Function (Type: Base),"The software provides an Applications Programming Interface (API) or similar interface for interaction with external actors, but the interface includes a dangerous method or function that is not properly restricted.","This weakness can lead to a wide variety of resultant weaknesses, depending on the behavior of the exposed method. It can apply to any number of technologies and approaches, such as ActiveX controls, Java functions, IOCTLs, and so on.
285 The exposure can occur in a few different ways:
286 1) The function/method was never intended to be exposed to outside actors.
287 2) The function/method was only intended to be accessible to a limited set of actors, such as Internet-based access from a single web site.",,Low to Medium,"No description: http://msdn.microsoft.com/workshop/components/activex/safety.asp
288 No description: http://msdn.microsoft.com/workshop/components/activex/security.asp"
289 CWE-755,EN-Improper Handling of Exceptional Conditions (Type: Class),The software does not handle or incorrectly handles an exceptional condition.,"The programmer may assume that certain events or conditions will never occur or do not need to be worried about, such as low memory conditions, lack of access to resources due to restrictive permissions, or misbehaving clients or components. However, attackers may intentionally trigger these unusual conditions, thus violating the programmer's assumptions, possibly introducing instability, incorrect behavior, or a vulnerability.
290 Note that this entry is not exclusively about the use of exceptions and exception handling, which are mechanisms for both checking and handling unusual or unexpected conditions.",,Low to Medium,
291 CWE-766,EN-Critical Variable Declared Public (Type: Variant),The software declares a critical variable or field to be public when intended security policy requires it to be private.,"When software is operating in a concurrent environment and repeatedly unlocks a critical resource, the consequences will vary based on the type of lock, the lock's implementation, and the resource being protected. In some situations such as with semaphores, the resources are pooled and extra calls to unlock will increase the count for the number of available resources, likely resulting in a crash or unpredictable behavior when the system nears capacity.",,Low to Medium,
292 CWE-767,EN-Access to Critical Private Variable via Public Method (Type: Variant),The software defines a public method that reads or modifies a private variable.,"If an attacker modifies the variable to contain unexpected values, this could violate assumptions from other parts of the code. Additionally, if an attacker can read the private variable, it may expose sensitive information or make it easier to launch further attacks.",,Low to Medium,
293 CWE-776,EN-Improper Restriction of Recursive Entity References in DTDs (XML Entity Expansion) (Type: Variant),"The software uses XML documents and allows their structure to be defined with a Document Type Definition (DTD), but it does not properly control the number of recursive definitions of entities.","If the DTD contains a large number of nested or recursive entities, this can lead to explosive growth of data when parsed, causing a denial of service.",,Low to Medium,"Multiple vendors XML parser (and SOAP/WebServices server) Denial of Service attack using DTD: http://www.securityfocus.com/archive/1/303509
294 XML security: Preventing XML bombs: http://searchsoftwarequality.techtarget.com/expert/KnowledgebaseAnswer/0,289625,sid92_gci1168442,00.html?asrc=SS_CLA_302%20%20558&psrc=CLT_92#
295 Dismantling an XML-Bomb: http://blog.didierstevens.com/2008/09/23/dismantling-an-xml-bomb/
296 XML Entity Expansion: http://projects.webappsec.org/XML-Entity-Expansion
297 Tip: Configure SAX parsers for secure processing: http://www.ibm.com/developerworks/xml/library/x-tipcfsx.html
298 XML Denial of Service Attacks and Defenses: http://msdn.microsoft.com/en-us/magazine/ee335713.aspx
299 Preventing Entity Expansion Attacks in JAXB: http://blog.bdoughan.com/2011/03/preventing-entity-expansion-attacks-in.html"
300 CWE-777,EN-Regular Expression without Anchors (Type: Variant),"The software uses a regular expression to perform neutralization, but the regular expression is not anchored and may allow malicious or malformed data to slip through.","When performing tasks such as whitelist validation, data is examined and possibly modified to ensure that it is well-formed and adheres to a list of safe values. If the regular expression is not anchored, malicious or malformed data may be included before or after any string matching the regular expression. The type of malicious data that is allowed will depend on the context of the application and which anchors are omitted from the regular expression.",,Low to Medium,
301 CWE-779,EN-Logging of Excessive Data (Type: Base),"The software logs too much information, making log files hard to process and possibly hindering recovery efforts or forensic analysis after an attack.","While logging is a good practice in general, and very high levels of logging are appropriate for debugging stages of development, too much logging in a production environment might hinder a system administrator's ability to detect anomalous conditions. This can provide cover for an attacker while attempting to penetrate a system, clutter the audit trail for forensic analysis, or make it more difficult to debug problems in a production environment.",,Low to Medium,
302 CWE-781,EN-Improper Address Validation in IOCTL with METHOD_NEITHER I/O Control Code (Type: Variant),"The software defines an IOCTL that uses METHOD_NEITHER for I/O, but it does not validate or incorrectly validates the addresses that are provided.","When an IOCTL uses the METHOD_NEITHER option for I/O control, it is the responsibility of the IOCTL to validate the addresses that have been supplied to it. If validation is missing or incorrect, attackers can supply arbitrary memory addresses, leading to code execution or a denial of service.",,Low to Medium,"Exploiting Common Flaws in Drivers: http://reversemode.com/index.php?option=com_content&task=view&id=38&Itemid=1
303 Remote and Local Exploitation of Network Drivers: https://www.blackhat.com/presentations/bh-usa-07/Bulygin/Presentation/bh-usa-07-bulygin.pdf
304 Windows driver vulnerabilities: the METHOD_NEITHER odyssey: http://www.net-security.org/dl/insecure/INSECURE-Mag-18.pdf
305 Buffer Descriptions for I/O Control Codes: http://msdn.microsoft.com/en-us/library/ms795857.aspx
306 Using Neither Buffered Nor Direct I/O: http://msdn.microsoft.com/en-us/library/cc264614.aspx
307 Securing Device Objects: http://msdn.microsoft.com/en-us/library/ms794722.aspx
308 No description: http://www.piotrbania.com/all/articles/ewdd.pdf"
309 CWE-782,EN-Exposed IOCTL with Insufficient Access Control (Type: Variant),"The software implements an IOCTL with functionality that should be restricted, but it does not properly enforce access control for the IOCTL.","When an IOCTL contains privileged functionality and is exposed unnecessarily, attackers may be able to access this functionality by invoking the IOCTL. Even if the functionality is benign, if the programmer has assumed that the IOCTL would only be accessed by a trusted process, there may be little or no validation of the incoming data, exposing weaknesses that would never be reachable if the attacker cannot call the IOCTL directly.
310 The implementations of IOCTLs will differ between operating system types and versions, so the methods of attack and prevention may vary widely.",,Low to Medium,Securing Device Objects: http://msdn.microsoft.com/en-us/library/ms794722.aspx
311 CWE-117,EN-Improper Output Neutralization for Logs (Type: Base),The software does not neutralize or incorrectly neutralizes output that is written to logs.,"This can allow an attacker to forge log entries or inject malicious content into logs.
312 Log forging vulnerabilities occur when:
313 Data enters an application from an untrusted source.
314 The data is written to an application or system log file.",,Medium,"Exploiting Software: How to Break Code
315 The night the log was forged: http://doc.novsu.ac.ru/oreilly/tcpip/puis/ch10_05.htm
316 OWASP TOP 10: http://www.owasp.org/index.php/Top_10_2007"
317 CWE-124,EN-Buffer Underwrite (Buffer Underflow) (Type: Base),The software writes to a buffer using an index or pointer that references a memory location prior to the beginning of the buffer.,"This typically occurs when a pointer or its index is decremented to a position before the buffer, when pointer arithmetic results in a position before the beginning of the valid memory location, or when a negative index is used.",,Medium,"Buffer UNDERFLOWS: What do you know about it?: http://seclists.org/vuln-dev/2004/Jan/0022.html
318 24 Deadly Sins of Software Security: ""Sin 5: Buffer Overruns."" Page 89"
319 CWE-128,EN-Wrap-around Error (Type: Base),"Wrap around errors occur whenever a value is incremented past the maximum value for its type and therefore ""wraps around"" to a very small, negative, or undefined value.","This typically occurs when the pointer or its index is decremented to a position before the buffer, when pointer arithmetic results in a position before the beginning of the valid memory location, or when a negative index is used. This may result in exposure of sensitive information or possibly a crash.",,Medium,"24 Deadly Sins of Software Security: ""Sin 5: Buffer Overruns."" Page 89
320 The Art of Software Security Assessment: Chapter 6, ""Signed Integer Boundaries"", Page 220."
321 CWE-170,EN-Improper Null Termination (Type: Base),The software does not terminate or incorrectly terminates a string or array with a null character or equivalent terminator.,"Null termination errors frequently occur in two different ways. An off-by-one error could cause a null to be written out of bounds, leading to an overflow. Or, a program could use a strncpy() function call incorrectly, which prevents a null terminator from being added at all. Other scenarios are possible.",,Medium,
322 CWE-190,EN-Integer Overflow or Wraparound (Type: Base),"The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.","An integer overflow or wraparound occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may wrap to become a very small or negative number. While this may be intended behavior in circumstances that rely on wrapping, it can have security consequences if the wrap is unexpected. This is especially the case if the integer overflow can be triggered using user-supplied inputs. This becomes security-critical when the result is used to control looping, make a security decision, or determine the offset or size in behaviors such as memory allocation, copying, concatenation, etc.",,Medium,"An overview of common programming security vulnerabilities and possible solutions: http://fort-knox.org/thesis.pdf
323 Basic Integer Overflows: http://www.phrack.org/issues.html?issue=60&id=10#article
324 Writing Secure Code: Chapter 20, ""Integer Overflows"" Page 620
325 24 Deadly Sins of Software Security: ""Sin 7: Integer Overflows."" Page 119
326 SafeInt: http://safeint.codeplex.com/
327 Top 25 Series - Rank 17 - Integer Overflow Or Wraparound: http://software-security.sans.org/blog/2010/03/18/top-25-series-rank-17-integer-overflow-or-wraparound
328 The Art of Software Security Assessment: Chapter 6, ""Signed Integer Boundaries"", Page 220."
329 CWE-196,EN-Unsigned to Signed Conversion Error (Type: Variant),An unsigned-to-signed conversion error takes place when a large unsigned primitive is used as a signed value.,It is dangerous to rely on implicit casts between signed and unsigned numbers because the result can take on an unexpected value and violate assumptions made by the program.,,Medium,"The Art of Software Security Assessment: Chapter 6, ""Type Conversions"", Page 223."
330 CWE-202,EN-Exposure of Sensitive Data Through Data Queries (Type: Variant),"When trying to keep information confidential, an attacker can often infer some of the information by using statistics.","In situations where data should not be tied to individual users, but a large number of users should be able to make queries that ""scrub"" the identity of users, it may be possible to get information about a user -- e.g., by specifying search terms that are known to be unique to that user.",,Medium,
331 CWE-250,EN-Execution with Unnecessary Privileges (Type: Class),"The software performs an operation at a privilege level that is higher than the minimum level required, which creates new weaknesses or amplifies the consequences of other weaknesses.","New weaknesses can be exposed because running with extra privileges, such as root or Administrator, can disable the normal security checks being performed by the operating system or surrounding environment. Other pre-existing weaknesses can turn into security vulnerabilities if they occur while operating at raised privileges.
332 Privilege management functions can behave in some less-than-obvious ways, and they have different quirks on different platforms. These inconsistencies are particularly pronounced if you are transitioning from one non-root user to another. Signal handlers and spawned processes run at the privilege of the owning process, so if a process is running as root when a signal fires or a sub-process is executed, the signal handler or sub-process will operate with root privileges.",,Medium,"The Protection of Information in Computer Systems: http://web.mit.edu/Saltzer/www/publications/protection/
333 Least Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html
334 Writing Secure Code: Chapter 7, ""Running with Least Privilege"" Page 207
335 Federal Desktop Core Configuration: http://nvd.nist.gov/fdcc/index.cfm
336 24 Deadly Sins of Software Security: ""Sin 16: Executing Code With Too Much Privilege."" Page 243
337 The Art of Software Security Assessment: Chapter 9, ""Privilege Vulnerabilities"", Page 477."
338 CWE-269,EN-Improper Privilege Management (Type: Base),"The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.","Just as neglecting to include functionality for the management of password aging is dangerous, so is allowing password aging to continue unchecked. Passwords must be given a maximum life span, after which a user is required to update with a new and different password.",,Medium,"24 Deadly Sins of Software Security: ""Sin 16: Executing Code With Too Much Privilege."" Page 243
339 The Art of Software Security Assessment: Chapter 9, ""Dropping Privileges Permanently"", Page 479."
340 CWE-273,EN-Improper Check for Dropped Privileges (Type: Base),The software attempts to drop privileges but does not check or incorrectly checks to see if the drop succeeded.,"If the drop fails, the software will continue to run with the raised privileges, which might provide additional access to unprivileged users.",,Medium,
341 CWE-276,EN-Incorrect Default Permissions (Type: Variant),"The software, upon installation, sets incorrect permissions for an object that exposes it to an unintended actor.","If the drop fails, the software will continue to run with the raised privileges, which might provide additional access to unprivileged users.",,Medium,"The Art of Software Security Assessment: Chapter 3, ""Insecure Defaults"", Page 69."
342 CWE-299,EN-Improper Check for Certificate Revocation (Type: Variant),"The software does not check or incorrectly checks the revocation status of a certificate, which may cause it to use a certificate that has been compromised.","An improper check for certificate revocation is a far more serious flaw than related certificate failures. This is because the use of any revoked certificate is almost certainly malicious. The most common reason for certificate revocation is compromise of the system in question, with the result that no legitimate servers will be using a revoked certificate, unless they are sorely out of sync.",,Medium,"24 Deadly Sins of Software Security: ""Sin 23: Improper Use of PKI, Especially SSL."" Page 347"
343 CWE-301,EN-Reflection Attack in an Authentication Protocol (Type: Variant),Simple authentication protocols are subject to reflection attacks if a malicious user can use the target machine to impersonate a trusted user.,"A mutual authentication protocol requires each party to respond to a random challenge by the other party by encrypting it with a pre-shared key. Often, however, such protocols employ the same pre-shared key for communication with a number of different entities. A malicious user or an attacker can easily compromise this protocol without possessing the correct key by employing a reflection attack on the protocol.",,Medium,"The Art of Software Security Assessment: Chapter 2, ""Insufficient Validation"", Page 38."
344 CWE-329,EN-Not Using a Random IV with CBC Mode (Type: Variant),Not using a random initialization Vector (IV) with Cipher Block Chaining (CBC) Mode causes algorithms to be susceptible to dictionary attacks.,"This weakness is especially dangerous when the hash is used in security algorithms that require the one-way property to hold. For example, if an authentication system takes an incoming password and generates a hash, then compares the hash to another hash that it has stored in its authentication database, then the ability to create a collision could allow an attacker to provide an alternate password that produces the same target hash, bypassing authentication.",,Medium,"The Art of Software Security Assessment: Chapter 2, ""Initialization Vectors"", Page 42."
345 CWE-332,EN-Insufficient Entropy in PRNG (Type: Variant),"The lack of entropy available for, or used by, a Pseudo-Random Number Generator (PRNG) can be a stability and security threat.","When software generates predictable values in a context requiring unpredictability, it may be possible for an attacker to guess the next value that will be generated, and use this guess to impersonate another user or access sensitive information.",,Medium,SECURITY REQUIREMENTS FOR CRYPTOGRAPHIC MODULES: http://csrc.nist.gov/publications/fips/fips140-2/fips1402.pdf
346 CWE-338,EN-Use of Cryptographically Weak PRNG (Type: Base),"The product uses a Pseudo-Random Number Generator (PRNG) in a security context, but the PRNG is not cryptographically strong.",The rate at which true random numbers can be generated is limited. It is important that one uses them only when they are needed for security.,,Medium,"24 Deadly Sins of Software Security: ""Sin 20: Weak Random Numbers."" Page 299"
347 CWE-353,EN-Missing Support for Integrity Check (Type: Base),"The software uses a transmission protocol that does not include a mechanism for verifying the integrity of the data during transmission, such as a checksum.","If integrity check values or ""checksums"" are omitted from a protocol, there is no way of determining if data has been corrupted in transmission. The lack of checksum functionality in a protocol removes the first application-level check of data that can be used. The end-to-end philosophy of checks states that integrity checks should be performed at the lowest level that they can be completely implemented. Excluding further sanity checks and input validation performed by applications, the protocol's checksum is the most important level of checksum, since it can be performed more completely than at any previous level and takes into account entire messages, as opposed to single packets.",,Medium,"24 Deadly Sins of Software Security: ""Sin 15: Not Updating Easily."" Page 231"
348 CWE-354,EN-Improper Validation of Integrity Check Value (Type: Base),"The software does not validate or incorrectly validates the integrity check values or ""checksums"" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.",Improper validation of checksums before use results in an unnecessary risk that can easily be mitigated. The protocol specification describes the algorithm used for calculating the checksum. It is then a simple matter of implementing the calculation and verifying that the calculated checksum and the received checksum match. Improper verification of the calculated checksum and the received checksum can lead to far greater consequences.,,Medium,
349 CWE-362,EN-Concurrent Execution using Shared Resource with Improper Synchronization (Race Condition) (Type: Class),"The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.","This can have security implications when the expected synchronization is in security-critical code, such as recording whether a user is authenticated or modifying important state information that should not be influenced by an outsider.
350 A race condition occurs within concurrent environments, and is effectively a property of a code sequence. Depending on the context, a code sequence may be in the form of a function call, a small number of instructions, a series of program invocations, etc.
351 A race condition violates these properties, which are closely related:
352 Exclusivity - the code sequence is given exclusive access to the shared resource, i.e., no other code sequence can modify properties of the shared resource before the original sequence has completed execution.
353 Atomicity - the code sequence is behaviorally atomic, i.e., no other thread or process can concurrently execute the same sequence of instructions (or a subset) against the same resource.
354 A race condition exists when an ""interfering code sequence"" can still access the shared resource, violating exclusivity. Programmers may assume that certain code sequences execute too quickly to be affected by an interfering code sequence; when they are not, this violates atomicity. For example, the single ""x++"" statement may appear atomic at the code layer, but it is actually non-atomic at the instruction layer, since it involves a read (the original value of x), followed by a computation (x+1), followed by a write (save the result to x).
355 The interfering code sequence could be ""trusted"" or ""untrusted."" A trusted interfering code sequence occurs within the program; it cannot be modified by the attacker, and it can only be invoked indirectly. An untrusted interfering code sequence can be authored directly by the attacker, and typically it is external to the vulnerable program.",,Medium,"24 Deadly Sins of Software Security: ""Sin 13: Race Conditions."" Page 205
356 volatile - Multithreaded Programmer's Best Friend: http://www.ddj.com/cpp/184403766
357 Thread-safe webapps using Spring: http://www.javalobby.org/articles/thread-safe/index.jsp
358 Prevent race conditions: http://www.ibm.com/developerworks/library/l-sprace.html
359 Race Conditions, Files, and Security Flaws; or the Tortoise and the Hare Redux: http://www.cs.ucdavis.edu/research/tech-reports/1995/CSE-95-9.pdf
360 Secure Programming for Linux and Unix HOWTO: http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/avoid-race.html
361 Discovering and Exploiting Named Pipe Security Flaws for Fun and Profit: http://www.blakewatts.com/namedpipepaper.html
362 On Race Vulnerabilities in Web Applications: http://security.dico.unimi.it/~roberto/pubs/dimva08-web.pdf
363 Avoiding Race Conditions and Insecure File Operations: http://developer.apple.com/documentation/Security/Conceptual/SecureCodingGuide/Articles/RaceConditions.html
364 Top 25 Series - Rank 25 - Race Conditions: http://blogs.sans.org/appsecstreetfighter/2010/03/26/top-25-series-rank-25-race-conditions/
365 Least Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html"
366 CWE-364,EN-Signal Handler Race Condition (Type: Base),The software uses a signal handler that introduces a race condition.,"Race conditions frequently occur in signal handlers, since signal handlers support asynchronous actions. These race conditions have a variety of root causes and symptoms. Attackers may be able to exploit a signal handler race condition to cause the software state to be corrupted, possibly leading to a denial of service or even code execution.
367 These issues occur when non-reentrant functions, or state-sensitive actions occur in the signal handler, where they may be called at any time. These behaviors can violate assumptions being made by the ""regular"" code that is interrupted, or by other signal handlers that may also be invoked. If these functions are called at an inopportune moment - such as while a non-reentrant function is already running - memory corruption could occur that may be exploitable for code execution. Another signal race condition commonly found occurs when free is called within a signal handler, resulting in a double free and therefore a write-what-where condition. Even if a given pointer is set to NULL after it has been freed, a race condition still exists between the time the memory was freed and the pointer was set to NULL. This is especially problematic if the same signal handler has been set for more than one signal -- since it means that the signal handler itself may be reentered.
368 There are several known behaviors related to signal handlers that have received the label of ""signal handler race condition"":
369 Shared state (e.g. global data or static variables) that are accessible to both a signal handler and ""regular"" code
370 Shared state between a signal handler and other signal handlers
371 Use of non-reentrant functionality within a signal handler - which generally implies that shared state is being used. For example, malloc() and free() are non-reentrant because they may use global or static data structures for managing memory, and they are indirectly used by innocent-seeming functions such as syslog(); these functions could be exploited for memory corruption and, possibly, code execution.
372 Association of the same signal handler function with multiple signals - which might imply shared state, since the same code and resources are accessed. For example, this can be a source of double-free and use-after-free weaknesses.
373 Use of setjmp and longjmp, or other mechanisms that prevent a signal handler from returning control back to the original functionality
374 While not technically a race condition, some signal handlers are designed to be called at most once, and being called more than once can introduce security problems, even when there are not any concurrent calls to the signal handler. This can be a source of double-free and use-after-free weaknesses.
375 Signal handler vulnerabilities are often classified based on the absence of a specific protection mechanism, although this style of classification is discouraged in CWE because programmers often have a choice of several different mechanisms for addressing the weakness. Such protection mechanisms may preserve exclusivity of access to the shared resource, and behavioral atomicity for the relevant code:
376 Avoiding shared state
377 Using synchronization in the signal handler
378 Using synchronization in the regular code
379 Disabling or masking other signals, which provides atomicity (which effectively ensures exclusivity)",,Medium,"Delivering Signals for Fun and Profit: http://lcamtuf.coredump.cx/signals.txt
380 Race Condition: Signal Handling: http://www.fortify.com/vulncat/en/vulncat/cpp/race_condition_signal_handling.html
381 24 Deadly Sins of Software Security: ""Sin 13: Race Conditions."" Page 205
382 The Art of Software Security Assessment: Chapter 13, ""Signal Vulnerabilities"", Page 791."
383 CWE-365,EN-Race Condition in Switch (Type: Base),"The code contains a switch statement in which the switched variable can be modified while the switch is still executing, resulting in unexpected behavior.","Race conditions frequently occur in signal handlers, since signal handlers support asynchronous actions. These race conditions have a variety of root causes and symptoms. Attackers may be able to exploit a signal handler race condition to cause the software state to be corrupted, possibly leading to a denial of service or even code execution.
384 These issues occur when non-reentrant functions, or state-sensitive actions occur in the signal handler, where they may be called at any time. These behaviors can violate assumptions being made by the ""regular"" code that is interrupted, or by other signal handlers that may also be invoked. If these functions are called at an inopportune moment - such as while a non-reentrant function is already running - memory corruption could occur that may be exploitable for code execution. Another signal race condition commonly found occurs when free is called within a signal handler, resulting in a double free and therefore a write-what-where condition. Even if a given pointer is set to NULL after it has been freed, a race condition still exists between the time the memory was freed and the pointer was set to NULL. This is especially problematic if the same signal handler has been set for more than one signal -- since it means that the signal handler itself may be reentered.
385 There are several known behaviors related to signal handlers that have received the label of ""signal handler race condition"":
386 Shared state (e.g. global data or static variables) that are accessible to both a signal handler and ""regular"" code
387 Shared state between a signal handler and other signal handlers
388 Use of non-reentrant functionality within a signal handler - which generally implies that shared state is being used. For example, malloc() and free() are non-reentrant because they may use global or static data structures for managing memory, and they are indirectly used by innocent-seeming functions such as syslog(); these functions could be exploited for memory corruption and, possibly, code execution.
389 Association of the same signal handler function with multiple signals - which might imply shared state, since the same code and resources are accessed. For example, this can be a source of double-free and use-after-free weaknesses.
390 Use of setjmp and longjmp, or other mechanisms that prevent a signal handler from returning control back to the original functionality
391 While not technically a race condition, some signal handlers are designed to be called at most once, and being called more than once can introduce security problems, even when there are not any concurrent calls to the signal handler. This can be a source of double-free and use-after-free weaknesses.
392 Signal handler vulnerabilities are often classified based on the absence of a specific protection mechanism, although this style of classification is discouraged in CWE because programmers often have a choice of several different mechanisms for addressing the weakness. Such protection mechanisms may preserve exclusivity of access to the shared resource, and behavioral atomicity for the relevant code:
393 Avoiding shared state
394 Using synchronization in the signal handler
395 Using synchronization in the regular code
396 Disabling or masking other signals, which provides atomicity (which effectively ensures exclusivity)",,Medium,"24 Deadly Sins of Software Security: ""Sin 13: Race Conditions."" Page 205"
397 CWE-366,EN-Race Condition within a Thread (Type: Base),"If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.","Race conditions frequently occur in signal handlers, since signal handlers support asynchronous actions. These race conditions have a variety of root causes and symptoms. Attackers may be able to exploit a signal handler race condition to cause the software state to be corrupted, possibly leading to a denial of service or even code execution.
398 These issues occur when non-reentrant functions, or state-sensitive actions occur in the signal handler, where they may be called at any time. These behaviors can violate assumptions being made by the ""regular"" code that is interrupted, or by other signal handlers that may also be invoked. If these functions are called at an inopportune moment - such as while a non-reentrant function is already running - memory corruption could occur that may be exploitable for code execution. Another signal race condition commonly found occurs when free is called within a signal handler, resulting in a double free and therefore a write-what-where condition. Even if a given pointer is set to NULL after it has been freed, a race condition still exists between the time the memory was freed and the pointer was set to NULL. This is especially problematic if the same signal handler has been set for more than one signal -- since it means that the signal handler itself may be reentered.
399 There are several known behaviors related to signal handlers that have received the label of ""signal handler race condition"":
400 Shared state (e.g. global data or static variables) that are accessible to both a signal handler and ""regular"" code
401 Shared state between a signal handler and other signal handlers
402 Use of non-reentrant functionality within a signal handler - which generally implies that shared state is being used. For example, malloc() and free() are non-reentrant because they may use global or static data structures for managing memory, and they are indirectly used by innocent-seeming functions such as syslog(); these functions could be exploited for memory corruption and, possibly, code execution.
403 Association of the same signal handler function with multiple signals - which might imply shared state, since the same code and resources are accessed. For example, this can be a source of double-free and use-after-free weaknesses.
404 Use of setjmp and longjmp, or other mechanisms that prevent a signal handler from returning control back to the original functionality
405 While not technically a race condition, some signal handlers are designed to be called at most once, and being called more than once can introduce security problems, even when there are not any concurrent calls to the signal handler. This can be a source of double-free and use-after-free weaknesses.
406 Signal handler vulnerabilities are often classified based on the absence of a specific protection mechanism, although this style of classification is discouraged in CWE because programmers often have a choice of several different mechanisms for addressing the weakness. Such protection mechanisms may preserve exclusivity of access to the shared resource, and behavioral atomicity for the relevant code:
407 Avoiding shared state
408 Using synchronization in the signal handler
409 Using synchronization in the regular code
410 Disabling or masking other signals, which provides atomicity (which effectively ensures exclusivity)",,Medium,"24 Deadly Sins of Software Security: ""Sin 13: Race Conditions."" Page 205
411 The Art of Software Security Assessment: Chapter 13, ""Race Conditions"", Page 759."
412 CWE-369,EN-Divide By Zero (Type: Base),The product divides a value by zero.,"This weakness typically occurs when an unexpected value is provided to the product, or if an error occurs that is not properly detected. It frequently occurs in calculations involving physical dimensions such as size, length, width, and height.",,Medium,"No description: http://www.cprogramming.com/tutorial/exceptions.html
413 No description: http://msdn.microsoft.com/en-us/library/ms173160(VS.80).aspx"
414 CWE-370,EN-Missing Check for Certificate Revocation after Initial Check (Type: Base),"The software does not check the revocation status of a certificate after its initial revocation check, which can cause the software to perform privileged actions even after the certificate is revoked at a later time.","If the revocation status of a certificate is not checked before each action that requires privileges, the system may be subject to a race condition. If a certificate is revoked after the initial check, all subsequent actions taken with the owner of the revoked certificate will lose all benefits guaranteed by the certificate. In fact, it is almost certain that the use of a revoked certificate indicates malicious activity.",,Medium,"24 Deadly Sins of Software Security: ""Sin 13: Race Conditions."" Page 205"
415 CWE-374,EN-Passing Mutable Objects to an Untrusted Method (Type: Base),"Sending non-cloned mutable data as an argument may result in that data being altered or deleted by the called function, thereby putting the calling function into an undefined state.","If the revocation status of a certificate is not checked before each action that requires privileges, the system may be subject to a race condition. If a certificate is revoked after the initial check, all subsequent actions taken with the owner of the revoked certificate will lose all benefits guaranteed by the certificate. In fact, it is almost certain that the use of a revoked certificate indicates malicious activity.",,Medium,"Does Java pass by reference or pass by value?: http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
416 Java: The Complete Reference, J2SE 5th Edition"
417 CWE-375,EN-Returning a Mutable Object to an Untrusted Caller (Type: Base),"Sending non-cloned mutable data as a return value may result in that data being altered or deleted by the calling function, thereby putting the class in an undefined state.","If the revocation status of a certificate is not checked before each action that requires privileges, the system may be subject to a race condition. If a certificate is revoked after the initial check, all subsequent actions taken with the owner of the revoked certificate will lose all benefits guaranteed by the certificate. In fact, it is almost certain that the use of a revoked certificate indicates malicious activity.",,Medium,
418 CWE-385,EN-Covert Timing Channel (Type: Base),"Covert timing channels convey information by modulating some aspect of system behavior over time, so that the program receiving the information can observe system behavior and infer protected information.","In some instances, knowing when data is transmitted between parties can provide a malicious user with privileged information. Also, externally monitoring the timing of operations can potentially reveal sensitive data. For example, a cryptographic operation can expose its internal state if the time it takes to perform the operation varies, based on the state.
419 Covert channels are frequently classified as either storage or timing channels. Some examples of covert timing channels are the system's paging rate, the time a certain transaction requires to execute, and the time it takes to gain access to a shared bus.",,Medium,
420 CWE-390,EN-Detection of Error Condition Without Action (Type: Class),"The software detects a specific error, but takes no actions to handle the error.","In some instances, knowing when data is transmitted between parties can provide a malicious user with privileged information. Also, externally monitoring the timing of operations can potentially reveal sensitive data. For example, a cryptographic operation can expose its internal state if the time it takes to perform the operation varies, based on the state.
421 Covert channels are frequently classified as either storage or timing channels. Some examples of covert timing channels are the system's paging rate, the time a certain transaction requires to execute, and the time it takes to gain access to a shared bus.",,Medium,"24 Deadly Sins of Software Security: ""Sin 11: Failure to Handle Errors Correctly."" Page 183"
422 CWE-391,EN-Unchecked Error Condition (Type: Base),Ignoring exceptions and other error conditions may allow an attacker to induce unexpected behavior unnoticed.,"In some instances, knowing when data is transmitted between parties can provide a malicious user with privileged information. Also, externally monitoring the timing of operations can potentially reveal sensitive data. For example, a cryptographic operation can expose its internal state if the time it takes to perform the operation varies, based on the state.
423 Covert channels are frequently classified as either storage or timing channels. Some examples of covert timing channels are the system's paging rate, the time a certain transaction requires to execute, and the time it takes to gain access to a shared bus.",,Medium,
424 CWE-401,EN-Improper Release of Memory Before Removing Last Reference (Memory Leak) (Type: Base),"The software does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory.",This is often triggered by improper handling of malformed data or unexpectedly interrupted sessions.,,Medium,How to Break Software Security
425 CWE-460,EN-Improper Cleanup on Thrown Exception (Type: Variant),"The product does not clean up its state or incorrectly cleans up its state when an exception is thrown, leading to unexpected state or control flow.","In some languages such as C and C++, stack variables are not initialized by default. They generally contain junk data with the contents of stack memory before the function was invoked. An attacker can sometimes control or read these contents. In other languages or conditions, a variable that is not explicitly initialized can be given a default value that has security implications, depending on the logic of the program. The presence of an uninitialized variable can sometimes indicate a typographic error in the code.",,Medium,
426 CWE-468,EN-Incorrect Pointer Scaling (Type: Base),"In C and C++, one may often accidentally refer to the wrong memory due to the semantics of when math operations are implicitly scaled.","Data-structure sentinels are often used to mark the structure of data. A common example of this is the null character at the end of strings or a special sentinel to mark the end of a linked list. It is dangerous to allow this type of control data to be easily accessible. Therefore, it is important to protect from the addition or modification of sentinels.",,Medium,"The Art of Software Security Assessment: Chapter 6, ""Pointer Arithmetic"", Page 277."
427 CWE-469,EN-Use of Pointer Subtraction to Determine Size (Type: Base),"The application subtracts one pointer from another in order to determine size, but this calculation can be incorrect if the pointers do not exist in the same memory chunk.","Data-structure sentinels are often used to mark the structure of data. A common example of this is the null character at the end of strings or a special sentinel to mark the end of a linked list. It is dangerous to allow this type of control data to be easily accessible. Therefore, it is important to protect from the addition or modification of sentinels.",,Medium,
428 CWE-476,EN-NULL Pointer Dereference (Type: Base),"A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.","NULL pointer dereference issues can occur through a number of flaws, including race conditions, and simple programming omissions.",,Medium,
429 CWE-484,EN-Omitted Break Statement in Switch (Type: Base),"The program omits a break statement within a switch or similar construct, causing code associated with multiple conditions to execute. This can cause problems when the programmer only intended to execute code associated with one condition.",This can lead to critical code executing in situations where it should not.,,Medium,"The Art of Software Security Assessment: Chapter 7, ""Switch Statements"", Page 337."
430 CWE-487,EN-Reliance on Package-level Scope (Type: Variant),"Java packages are not inherently closed; therefore, relying on them for code security is not a good practice.","If the decision to trust the methods and data of an object is based on the name of a class, it is possible for malicious users to send objects of the same name as trusted classes and thereby gain the trust afforded to known classes and types.",,Medium,
431 CWE-492,EN-Use of Inner Class Containing Sensitive Data (Type: Variant),Inner classes are translated into classes that are accessible at package scope and may expose code that the programmer intended to keep private to attackers.,"Data can ""bleed"" from one session to another through member variables of singleton objects, such as Servlets, and objects from a shared pool.
432 In the case of Servlets, developers sometimes do not understand that, unless a Servlet implements the SingleThreadModel interface, the Servlet is a singleton; there is only one instance of the Servlet, and that single instance is used and re-used to handle multiple requests that are processed simultaneously by different threads. A common result is that developers use Servlet member fields in such a way that one user may inadvertently see another user's data. In other words, storing user data in Servlet member fields introduces a data access race condition.",,Medium,
433 CWE-494,EN-Download of Code Without Integrity Check (Type: Base),The product downloads source code or an executable from a remote location and executes the code without sufficiently verifying the origin and integrity of the code.,"An attacker can execute malicious code by compromising the host server, performing DNS spoofing, or modifying the code in transit.",,Medium,"Introduction to Code Signing: http://msdn.microsoft.com/en-us/library/ms537361(VS.85).aspx
434 Authenticode: http://msdn.microsoft.com/en-us/library/ms537359(v=VS.85).aspx
435 Code Signing Guide: http://developer.apple.com/documentation/Security/Conceptual/CodeSigningGuide/Introduction/chapter_1_section_1.html
436 Secure Software Updates: Disappointments and New Challenges: http://prisms.cs.umass.edu/~kevinfu/papers/secureupdates-hotsec06.pdf
437 24 Deadly Sins of Software Security: ""Sin 18: The Sins of Mobile Code."" Page 267
438 Top 25 Series - Rank 20 - Download of Code Without Integrity Check: http://blogs.sans.org/appsecstreetfighter/2010/04/05/top-25-series-rank-20-download-code-integrity-check/
439 Least Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html"
440 CWE-498,EN-Cloneable Class Containing Sensitive Information (Type: Variant),"The code contains a class with sensitive data, but the class is cloneable. The data can then be accessed by cloning the class.","Cloneable classes are effectively open classes, since data cannot be hidden in them. Classes that do not explicitly deny cloning can be cloned by any other class without running the constructor.",,Medium,
441 CWE-502,EN-Deserialization of Untrusted Data (Type: Variant),The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.,"It is often convenient to serialize objects for communication or to save them for later use. However, deserialized data or code can often be modified without using the provided accessor functions if it does not use cryptography to protect itself. Furthermore, any cryptography would still be client-side security -- which is a dangerous security assumption.
442 Data that is untrusted can not be trusted to be well-formed.",,Medium,"Unserializing user-supplied data, a bad idea: http://heine.familiedeelstra.com/security/unserialize
443 Why Python Pickle is Insecure: http://nadiana.com/python-pickle-insecure"
444 CWE-532,EN-Information Exposure Through Log Files (Type: Variant),Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information.,"While logging all information may be helpful during development stages, it is important that logging levels be set appropriately before a product ships so that sensitive user data and system information are not accidentally exposed to potential attackers.",,Medium,
445 CWE-602,EN-Client-Side Enforcement of Server-Side Security (Type: Base),The software is composed of a server that relies on the client to implement a mechanism that is intended to protect the server.,"When the server relies on protection mechanisms placed on the client side, an attacker can modify the client-side behavior to bypass the protection mechanisms resulting in potentially unexpected interactions between the client and server. The consequences will vary, depending on what the mechanisms are trying to protect.",,Medium,"Writing Secure Code: Chapter 23, ""Client-Side Security Is an Oxymoron"" Page 687"
446 CWE-665,EN-Improper Initialization (Type: Base),"The software does not initialize or incorrectly initializes a resource, which might leave the resource in an unexpected state when it is accessed or used.","This can have security implications when the associated resource is expected to have certain properties or values, such as a variable that determines whether a user has been authenticated or not.",,Medium,"Exploiting Uninitialized Data: http://www.felinemenace.org/~mercy/papers/UBehavior/UBehavior.zip
447 MS08-014 : The Case of the Uninitialized Stack Variable Vulnerability: http://blogs.technet.com/swi/archive/2008/03/11/the-case-of-the-uninitialized-stack-variable-vulnerability.aspx
448 The Art of Software Security Assessment: Chapter 7, ""Variable Initialization"", Page 312."
449 CWE-754,EN-Improper Check for Unusual or Exceptional Conditions (Type: Class),The software does not check or improperly checks for unusual or exceptional conditions that are not expected to occur frequently during day to day operation of the software.,"The programmer may assume that certain events or conditions will never occur or do not need to be worried about, such as low memory conditions, lack of access to resources due to restrictive permissions, or misbehaving clients or components. However, attackers may intentionally trigger these unusual conditions, thus violating the programmer's assumptions, possibly introducing instability, incorrect behavior, or a vulnerability.
450 Note that this entry is not exclusively about the use of exceptions and exception handling, which are mechanisms for both checking and handling unusual or unexpected conditions.",,Medium,"The Art of Software Security Assessment: Chapter 7, ""Program Building Blocks"" Page 341
451 The Art of Software Security Assessment: Chapter 1, ""Exceptional Conditions,"" Page 22
452 24 Deadly Sins of Software Security: ""Sin 11: Failure to Handle Errors Correctly."" Page 183
453 Top 25 Series - Rank 15 - Improper Check for Unusual or Exceptional Conditions: http://blogs.sans.org/appsecstreetfighter/2010/03/15/top-25-series-rank-15-improper-check-for-unusual-or-exceptional-conditions/"
454 CWE-778,EN-Insufficient Logging (Type: Base),"When a security-critical event occurs, the software either does not record the event or omits important details about the event when logging it.","When security-critical events are not logged properly, such as a failed login attempt, this can make malicious behavior more difficult to detect and may hinder forensic analysis after an attack succeeds.",,Medium,"The Art of Software Security Assessment: Chapter 2, ""Accountability"", Page 40."
455 CWE-780,EN-Use of RSA Algorithm without OAEP (Type: Variant),"The software uses the RSA algorithm but does not incorporate Optimal Asymmetric Encryption Padding (OAEP), which might weaken the encryption.",Padding schemes are often used with cryptographic algorithms to make the plaintext less predictable and complicate attack efforts. The OAEP scheme is often used with RSA to nullify the impact of predictable common text.,,Medium,"RSA Problem: http://people.csail.mit.edu/rivest/RivestKaliski-RSAProblem.pdf
456 Optimal Asymmetric Encryption Padding: http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding"
457 CWE-908,EN-Use of Uninitialized Resource (Type: Base),The software uses a resource that has not been properly initialized.,This can have security implications when the associated resource is expected to have certain properties or values.,,Medium,Exploiting Uninitialized Data: http://www.felinemenace.org/~mercy/papers/UBehavior/UBehavior.zip
458 CWE-909,EN-Missing Initialization of Resource (Type: Base),The software does not initialize a critical resource.,"Many resources require initialization before they can be properly used. If a resource is not initialized, it could contain unpredictable or expired data, or it could be initialized to defaults that are invalid. This can have security implications when the resource is expected to have certain properties or values.",,Medium,
459 CWE-910,EN-Use of Expired File Descriptor (Type: Base),The software uses or accesses a file descriptor after it has been closed.,"After a file descriptor for a particular file or device has been released, it can be reused. The code might not write to the original file, since the reused file descriptor might reference a different file or device.",,Medium,
460 CWE-911,EN-Improper Update of Reference Count (Type: Base),"The software uses a reference count to manage a resource, but it does not update or incorrectly updates the reference count.","Reference counts can be used when tracking how many objects contain a reference to a particular resource, such as in memory management or garbage collection. When the reference count reaches zero, the resource can be de-allocated or reused because there are no more objects that use it. If the reference count accidentally reaches zero, then the resource might be released too soon, even though it is still in use. If all objects no longer use the resource, but the reference count is not zero, then the resource might not ever be released.",,Medium,Windows Kernel Reference Count Vulnerabilities - Case Study: http://j00ru.vexillium.org/dump/zn_slides.pdf
461 CWE-94,EN-Improper Control of Generation of Code (Code Injection) (Type: Class),"The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.","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.
462 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.",,Medium,"24 Deadly Sins of Software Security: ""Sin 3: Web-Client Related Vulnerabilities (XSS)."" Page 63"
463 CWE-95,EN-Improper Neutralization of Directives in Dynamically Evaluated Code (Eval Injection) (Type: Base),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes code syntax before using the input in a dynamic evaluation call (e.g. ""eval"").","This may allow an attacker to execute arbitrary code, or at least modify what code can be executed.",,Medium,"No description: http://www.rubycentral.com/book/taint.html
464 The Art of Software Security Assessment: Chapter 18, ""Inline Evaluation"", Page 1095."
465 CWE-287,EN-Improper Authentication (Type: Class),"When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.",Users can be assigned to the wrong group (class) of permissions resulting in unintended access rights to sensitive objects.,,Medium to High,"Weak Password Brings 'Happiness' to Twitter Hacker: http://www.wired.com/threatlevel/2009/01/professed-twitt/
466 Top 10 2007-Broken Authentication and Session Management: http://www.owasp.org/index.php/Top_10_2007-A7
467 Guide to Authentication: http://www.owasp.org/index.php/Guide_to_Authentication
468 Authentication: http://msdn.microsoft.com/en-us/library/aa374735(VS.85).aspx
469 Writing Secure Code: Chapter 4, ""Authentication"" Page 109"
470 CWE-306,EN-Missing Authentication for Critical Function (Type: Variant),The software does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.,"Authentication techniques should follow the algorithms that define them exactly, otherwise authentication can be bypassed or more easily subjected to brute force attacks.",,Medium to High,"The Art of Software Security Assessment: Chapter 2, ""Common Vulnerabilities of Authentication,"" Page 36
471 Top 25 Series - Rank 19 - Missing Authentication for Critical Function: http://blogs.sans.org/appsecstreetfighter/2010/02/23/top-25-series-rank-19-missing-authentication-for-critical-function/
472 OWASP Enterprise Security API (ESAPI) Project: http://www.owasp.org/index.php/ESAPI"
473 CWE-319,EN-Cleartext Transmission of Sensitive Information (Type: Base),The software transmits sensitive or security-critical data in cleartext in a communication channel that can be sniffed by unauthorized actors.,"Many communication channels can be ""sniffed"" by attackers during data transmission. For example, network traffic can often be sniffed by any attacker who has access to a network interface. This significantly lowers the difficulty of exploitation by attackers.",,Medium to High,"Top 10 2007-Insecure Communications: http://www.owasp.org/index.php/Top_10_2007-A9
474 Writing Secure Code: Chapter 9, ""Protecting Secret Data"" Page 299
475 24 Deadly Sins of Software Security: ""Sin 22: Failing to Protect Network Traffic."" Page 337
476 Mobile App Top 10 List: http://www.veracode.com/blog/2010/12/mobile-app-top-10-list/"
477 CWE-327,EN-Use of a Broken or Risky Cryptographic Algorithm (Type: Base),The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the exposure of sensitive information.,The use of a non-standard algorithm is dangerous because a determined attacker may be able to break the algorithm and compromise whatever data has been protected. Well-known techniques may exist to break the algorithm.,,Medium to High,"Applied Cryptography: http://www.schneier.com/book-applied.html
478 Handbook of Applied Cryptography: http://www.cacr.math.uwaterloo.ca/hac/
479 Avoiding bogus encryption products: Snake Oil FAQ: http://www.faqs.org/faqs/cryptography-faq/snake-oil/
480 SECURITY REQUIREMENTS FOR CRYPTOGRAPHIC MODULES: http://csrc.nist.gov/publications/fips/fips140-2/fips1402.pdf
481 Microsoft Scraps Old Encryption in New Code: http://www.eweek.com/c/a/Security/Microsoft-Scraps-Old-Encryption-in-New-Code/
482 Writing Secure Code: Chapter 8, ""Cryptographic Foibles"" Page 259
483 24 Deadly Sins of Software Security: ""Sin 21: Using the Wrong Cryptography."" Page 315
484 Top 25 Series - Rank 24 - Use of a Broken or Risky Cryptographic Algorithm: http://blogs.sans.org/appsecstreetfighter/2010/03/25/top-25-series-rank-24-use-of-a-broken-or-risky-cryptographic-algorithm/
485 The Art of Software Security Assessment: Chapter 2, ""Insufficient or Obsolete Encryption"", Page 44."
486 CWE-330,EN-Use of Insufficiently Random Values (Type: Class),The software may use insufficiently random numbers or values in a security context that depends on unpredictable numbers.,"When software generates predictable values in a context requiring unpredictability, it may be possible for an attacker to guess the next value that will be generated, and use this guess to impersonate another user or access sensitive information.",,Medium to High,"SECURITY REQUIREMENTS FOR CRYPTOGRAPHIC MODULES: http://csrc.nist.gov/publications/fips/fips140-2/fips1402.pdf
487 Building Secure Software: How to Avoid Security Problems the Right Way
488 Writing Secure Code: Chapter 8, ""Using Poor Random Numbers"" Page 259
489 24 Deadly Sins of Software Security: ""Sin 20: Weak Random Numbers."" Page 299"
490 CWE-400,EN-Uncontrolled Resource Consumption (Resource Exhaustion) (Type: Base),"The software does not properly restrict the size or amount of resources that are requested or influenced by an actor, which can be used to consume more resources than intended.","Limited resources include memory, file system storage, database connection pool entries, or CPU. If an attacker can trigger the allocation of these limited resources, but the number or size of the resources is not controlled, then the attacker could cause a denial of service that consumes all available resources. This would prevent valid users from accessing the software, and it could potentially have an impact on the surrounding environment. For example, a memory exhaustion attack against an application could slow down the application as well as its host operating system.
491 Resource exhaustion problems have at least two common causes:
492 Error conditions and other exceptional circumstances
493 Confusion over which part of the program is responsible for releasing the resource",,Medium to High,"Detection and Prediction of Resource-Exhaustion Vulnerabilities: http://homepages.di.fc.ul.pt/~nuno/PAPERS/ISSRE08.pdf
494 Resource exhaustion: http://cr.yp.to/docs/resources.html
495 Resource exhaustion: http://homes.cerias.purdue.edu/~pmeunier/secprog/sanitized/class1/6.resource%20exhaustion.ppt
496 Writing Secure Code: Chapter 17, ""Protecting Against Denial of Service Attacks"" Page 517"
497 CWE-434,EN-Unrestricted Upload of File with Dangerous Type (Type: Base),The software allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment.,"If code is stored in a file with an extension such as "".inc"" or "".pl"", and the web server does not have a handler for that extension, then the server will likely send the contents of the file directly to the requester without the pre-processing that was expected. When that file contains sensitive information such as database credentials, this may allow the attacker to compromise the application or associated components.",,Medium to High,"Dynamic File Uploads, Security and You: http://shsc.info/FileUploadSecurity
498 8 Basic Rules to Implement Secure File Uploads: http://blogs.sans.org/appsecstreetfighter/2009/12/28/8-basic-rules-to-implement-secure-file-uploads/
499 Top 25 Series - Rank 8 - Unrestricted Upload of Dangerous File Type: http://blogs.sans.org/appsecstreetfighter/2010/02/25/top-25-series-rank-8-unrestricted-upload-of-dangerous-file-type/
500 Least Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html
501 The Art of Software Security Assessment: Chapter 17, ""File Uploading"", Page 1068."
502 CWE-64,EN-Windows Shortcut Following (.LNK) (Type: Variant),"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.",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.,,Medium to High,
503 CWE-681,EN-Incorrect Conversion between Numeric Types (Type: Base),"When converting from one data type to another, such as long to integer, data can be omitted or translated in a way that produces unexpected values. If the resulting values are used in a sensitive context, then dangerous behaviors may occur.","Typically, a product defines its control sphere within the code itself, or through configuration by the product's administrator. In some cases, an external party can change the definition of the control sphere. This is typically a resultant weakness.",,Medium to High,"The Art of Software Security Assessment: Chapter 6, ""Type Conversions"", Page 223."
504 CWE-732,EN-Incorrect Permission Assignment for Critical Resource (Type: Class),The software specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors.,"When a resource is given a permissions setting that provides access to a wider range of actors than required, it could lead to the exposure of sensitive information, or the modification of that resource by unintended parties. This is especially dangerous when the resource is related to program configuration, execution or sensitive user data.",,Medium to High,"The Art of Software Security Assessment: Chapter 9, ""File Permissions."" Page 495.
505 Building Secure Software: How to Avoid Security Problems the Right Way: Chapter 8, ""Access Control."" Page 194.
506 Top 25 Series - Rank 21 - Incorrect Permission Assignment for Critical Response: http://software-security.sans.org/blog/2010/03/24/top-25-series-rank-21-incorrect-permission-assignment-for-critical-response
507 Federal Desktop Core Configuration: http://nvd.nist.gov/fdcc/index.cfm"
508 CWE-770,EN-Allocation of Resources Without Limits or Throttling (Type: Base),"The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on how many resources can be allocated, in violation of the intended security policy for that actor.","Command injection vulnerabilities typically occur when:
509 1. Data enters the application from an untrusted source.
510 2. The data is part of a string that is executed as a command by the application.
511 3. By executing the command, the application gives an attacker a privilege or capability that the attacker would not otherwise have.",,Medium to High,"Real-Life Example of a 'Business Logic Defect' (Screen Shots!): http://h30501.www3.hp.com/t5/Following-the-White-Rabbit-A/Real-Life-Example-of-a-Business-Logic-Defect-Screen-Shots/ba-p/22581
512 Detection and Prediction of Resource-Exhaustion Vulnerabilities: http://homepages.di.fc.ul.pt/~nuno/PAPERS/ISSRE08.pdf
513 Resource exhaustion: http://cr.yp.to/docs/resources.html
514 Resource exhaustion: http://homes.cerias.purdue.edu/~pmeunier/secprog/sanitized/class1/6.resource%20exhaustion.ppt
515 Writing Secure Code: Chapter 17, ""Protecting Against Denial of Service Attacks"" Page 517
516 Top 25 Series - Rank 22 - Allocation of Resources Without Limits or Throttling: http://blogs.sans.org/appsecstreetfighter/2010/03/23/top-25-series-rank-22-allocation-of-resources-without-limits-or-throttling/
517 The Art of Software Security Assessment: Chapter 10, ""Resource Limits"", Page 574."
518 CWE-771,EN-Missing Reference to Active Allocated Resource (Type: Base),"The software does not properly maintain a reference to a resource that has been allocated, which prevents the resource from being reclaimed.","This does not necessarily apply in languages or frameworks that automatically perform garbage collection, since the removal of all references may act as a signal that the resource is ready to be reclaimed.",,Medium to High,
519 CWE-772,EN-Missing Release of Resource after Effective Lifetime (Type: Base),"The software does not release a resource after its effective lifetime has ended, i.e., after the resource is no longer needed.","When a resource is not released after use, it can allow attackers to cause a denial of service.",,Medium to High,
520 CWE-773,EN-Missing Reference to Active File Descriptor or Handle (Type: Variant),"The software does not properly maintain references to a file descriptor or handle, which prevents that file descriptor/handle from being reclaimed.","This can cause the software to consume all available file descriptors or handles, which can prevent other processes from performing critical file processing operations.",,Medium to High,
521 CWE-774,EN-Allocation of File Descriptors or Handles Without Limits or Throttling (Type: Variant),"The software allocates file descriptors or handles on behalf of an actor without imposing any restrictions on how many descriptors can be allocated, in violation of the intended security policy for that actor.","This can cause the software to consume all available file descriptors or handles, which can prevent other processes from performing critical file processing operations.",,Medium to High,"The Art of Software Security Assessment: Chapter 10, ""Resource Limits"", Page 574."
522 CWE-775,EN-Missing Release of File Descriptor or Handle after Effective Lifetime (Type: Variant),"The software does not release a file descriptor or handle after its effective lifetime has ended, i.e., after the file descriptor/handle is no longer needed.","When a file descriptor or handle is not released after use (typically by explicitly closing it), attackers can cause a denial of service by consuming all available file descriptors/handles, or otherwise preventing other system processes from obtaining their own file descriptors/handles.",,Medium to High,"The Art of Software Security Assessment: Chapter 10, ""File Descriptor Leaks"", Page 582."
523 CWE-804,EN-Guessable CAPTCHA (Type: Base),"The software uses a CAPTCHA challenge, but the challenge can be guessed or automatically recognized by a non-human actor.","An automated attacker could bypass the intended protection of the CAPTCHA challenge and perform actions at a higher frequency than humanly possible, such as launching spam attacks.
524 There can be several different causes of a guessable CAPTCHA:
525 An audio or visual image that does not have sufficient distortion from the unobfuscated source image.
526 A question is generated that with a format that can be automatically recognized, such as a math question.
527 A question for which the number of possible answers is limited, such as birth years or favorite sports teams.
528 A general-knowledge or trivia question for which the answer can be accessed using a data base, such as country capitals or popular actors.
529 Other data associated with the CAPTCHA may provide hints about its contents, such as an image whose filename contains the word that is used in the CAPTCHA.",,Medium to High,Insufficient Anti-automation: http://projects.webappsec.org/Insufficient+Anti-automation
530 CWE-805,EN-Buffer Access with Incorrect Length Value (Type: Base),"The software uses a sequential operation to read or write a buffer, but it uses an incorrect length value that causes it to access memory that is outside of the bounds of the buffer.","When the length value exceeds the size of the destination, a buffer overflow could occur.",,Medium to High,"Writing Secure Code: Chapter 6, ""Why ACLs Are Important"" Page 171
531 Address Space Layout Randomization in Windows Vista: http://blogs.msdn.com/michael_howard/archive/2006/05/26/address-space-layout-randomization-in-windows-vista.aspx
532 Limiting buffer overflows with ExecShield: http://www.redhat.com/magazine/009jul05/features/execshield/
533 PaX: http://en.wikipedia.org/wiki/PaX
534 Top 25 Series - Rank 12 - Buffer Access with Incorrect Length Value: http://blogs.sans.org/appsecstreetfighter/2010/03/11/top-25-series-rank-12-buffer-access-with-incorrect-length-value/
535 Safe C String Library v1.0.3: http://www.zork.org/safestr/
536 Using the Strsafe.h Functions: http://msdn.microsoft.com/en-us/library/ms647466.aspx
537 Understanding DEP as a mitigation technology part 1: http://blogs.technet.com/b/srd/archive/2009/06/12/understanding-dep-as-a-mitigation-technology-part-1.aspx
538 Least Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html"
539 CWE-806,EN-Buffer Access Using Size of Source Buffer (Type: Variant),"The software uses the size of a source buffer when reading from or writing to a destination buffer, which may cause it to access memory that is outside of the bounds of the buffer.","When the size of the destination is smaller than the size of the source, a buffer overflow could occur.",,Medium to High,"Using the Strsafe.h Functions: http://msdn.microsoft.com/en-us/library/ms647466.aspx
540 Safe C String Library v1.0.3: http://www.zork.org/safestr/
541 Address Space Layout Randomization in Windows Vista: http://blogs.msdn.com/michael_howard/archive/2006/05/26/address-space-layout-randomization-in-windows-vista.aspx
542 Limiting buffer overflows with ExecShield: http://www.redhat.com/magazine/009jul05/features/execshield/
543 PaX: http://en.wikipedia.org/wiki/PaX
544 Understanding DEP as a mitigation technology part 1: http://blogs.technet.com/b/srd/archive/2009/06/12/understanding-dep-as-a-mitigation-technology-part-1.aspx"
545 CWE-807,EN-Reliance on Untrusted Inputs in a Security Decision (Type: Base),"The application uses a protection mechanism that relies on the existence or values of an input, but the input can be modified by an untrusted actor in a way that bypasses the protection mechanism.","Developers may assume that inputs such as cookies, environment variables, and hidden form fields cannot be modified. However, an attacker could change these inputs using customized clients or other attacks. This change might not be detected. When security decisions such as authentication and authorization are made based on the values of these inputs, attackers can bypass the security of the software.
546 Without sufficient encryption, integrity checking, or other mechanism, any input that originates from an outsider cannot be trusted.",,Medium to High,"Top 25 Series - Rank 6 - Reliance on Untrusted Inputs in a Security Decision: http://blogs.sans.org/appsecstreetfighter/2010/03/05/top-25-series-rank-6-reliance-on-untrusted-inputs-in-a-security-decision/
547 HMAC: http://en.wikipedia.org/wiki/Hmac
548 Understanding ASP.NET View State: http://msdn.microsoft.com/en-us/library/ms972976.aspx
549 OWASP Enterprise Security API (ESAPI) Project: http://www.owasp.org/index.php/ESAPI"
550 CWE-93,EN-Improper Neutralization of CRLF Sequences (CRLF Injection) (Type: Base),"The software uses CRLF (carriage return line feeds) as a special element, e.g. to separate lines or records, but it does not neutralize or incorrectly neutralizes CRLF sequences from inputs.","Since an implicit intent does not specify a particular application to receive the data, any application can process the intent by using an Intent Filter for that intent. This can allow untrusted applications to obtain sensitive data.",,Medium to High,CRLF Injection: http://marc.info/?l=bugtraq&m=102088154213630&w=2
551 CWE-102,EN-Struts: Duplicate Validation Forms (Type: Variant),"The application uses multiple validation forms with the same name, which might cause the Struts Validator to validate a form that the programmer does not expect.","If two validation forms have the same name, the Struts Validator arbitrarily chooses one of the forms to use for input validation and discards the other. This decision might not correspond to the programmer's expectations, possibly leading to resultant weaknesses. Moreover, it indicates that the validation logic is not up-to-date, and can indicate that other, more subtle validation errors are present.",,Unknown,
552 CWE-103,EN-Struts: Incomplete validate() Method Definition (Type: Variant),"The application has a validator form that either does not define a validate() method, or defines a validate() method but does not call super.validate().","If you do not call super.validate(), the Validation Framework cannot check the contents of the form against a validation form. In other words, the validation framework will be disabled for the given form.",,Unknown,
553 CWE-104,EN-Struts: Form Bean Does Not Extend Validation Class (Type: Variant),"If a form bean does not extend an ActionForm subclass of the Validator framework, it can expose the application to other weaknesses related to insufficient input validation.","If you do not call super.validate(), the Validation Framework cannot check the contents of the form against a validation form. In other words, the validation framework will be disabled for the given form.",,Unknown,
554 CWE-105,EN-Struts: Form Field Without Validator (Type: Variant),"The application has a form field that is not validated by a corresponding validation form, which can introduce other weaknesses related to insufficient input validation.","If you do not call super.validate(), the Validation Framework cannot check the contents of the form against a validation form. In other words, the validation framework will be disabled for the given form.",,Unknown,
555 CWE-106,EN-Struts: Plug-in Framework not in Use (Type: Variant),"When an application does not use an input validation framework such as the Struts Validator, there is a greater risk of introducing weaknesses related to insufficient input validation.","If you do not call super.validate(), the Validation Framework cannot check the contents of the form against a validation form. In other words, the validation framework will be disabled for the given form.",,Unknown,
556 CWE-107,EN-Struts: Unused Validation Form (Type: Variant),An unused validation form indicates that validation logic is not up-to-date.,It is easy for developers to forget to update validation logic when they remove or rename action form mappings. One indication that validation logic is not being properly maintained is the presence of an unused validation form.,,Unknown,
557 CWE-108,EN-Struts: Unvalidated Action Form (Type: Variant),Every Action Form must have a corresponding validation form.,"If a Struts Action Form Mapping specifies a form, it must have a validation form defined under the Struts Validator.",,Unknown,
558 CWE-109,EN-Struts: Validator Turned Off (Type: Variant),"Automatic filtering via a Struts bean has been turned off, which disables the Struts Validator and custom validation logic. This exposes the application to other weaknesses related to insufficient input validation.","If a Struts Action Form Mapping specifies a form, it must have a validation form defined under the Struts Validator.",,Unknown,
559 CWE-11,EN-ASP.NET Misconfiguration: Creating Debug Binary (Type: Variant),Debugging messages help attackers learn about the system and plan a form of attack.,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.,,Unknown,
560 CWE-110,EN-Struts: Validator Without Form Field (Type: Variant),Validation fields that do not appear in forms they are associated with indicate that the validation logic is out of date.,It is easy for developers to forget to update validation logic when they make changes to an ActionForm class. One indication that validation logic is not being properly maintained is inconsistencies between the action form and the validation form.,,Unknown,
561 CWE-111,EN-Direct Use of Unsafe JNI (Type: Base),"When a Java application uses the Java Native Interface (JNI) to call code written in another programming language, it can expose the application to weaknesses in that code, even if those weaknesses cannot occur in Java.","Many safety features that programmers may take for granted simply do not apply for native code, so you must carefully review all such code for potential problems. The languages used to implement native code may be more susceptible to buffer overflows and other attacks. Native code is unprotected by the security features enforced by the runtime environment, such as strong typing and array bounds checking.",,Unknown,"Fortify Descriptions: http://vulncat.fortifysoftware.com
562 The Java(TM) Tutorial: The Java Native Interface: http://java.sun.com/docs/books/tutorial/native1.1/"
563 CWE-112,EN-Missing XML Validation (Type: Base),The software accepts XML from an untrusted source but does not validate the XML against the proper schema.,"Most successful attacks begin with a violation of the programmer's assumptions. By accepting an XML document without validating it against a DTD or XML schema, the programmer leaves a door open for attackers to provide unexpected, unreasonable, or malicious input.",,Unknown,
564 CWE-113,EN-Improper Neutralization of CRLF Sequences in HTTP Headers (HTTP Response Splitting) (Type: Base),"The software receives data from an upstream component, but does not neutralize or incorrectly neutralizes CR and LF characters before the data is included in outgoing HTTP headers.","Including unvalidated data in an HTTP header allows an attacker to specify the entirety of the HTTP response rendered by the browser. When an HTTP request contains unexpected CR (carriage return, also given by %0d or \r) and LF (line feed, also given by %0a or \n) characters the server may respond with an output stream that is interpreted as two different HTTP responses (instead of one). An attacker can control the second response and mount attacks such as cross-site scripting and cache poisoning attacks.
565 HTTP response splitting weaknesses may be present when:
566 Data enters a web application through an untrusted source, most frequently an HTTP request.
567 The data is included in an HTTP response header sent to a web user without being validated for malicious characters.",,Unknown,"OWASP TOP 10: http://www.owasp.org/index.php/Top_10_2007
568 24 Deadly Sins of Software Security: ""Sin 2: Web-Server Related Vulnerabilities (XSS, XSRF, and Response Splitting)."" Page 31"
569 CWE-114,EN-Process Control (Type: Base),Executing commands or loading libraries from an untrusted source or in an untrusted environment can cause an application to execute malicious commands (and payloads) on behalf of an attacker.,"Process control vulnerabilities take two forms: 1. An attacker can change the command that the program executes: the attacker explicitly controls what the command is. 2. An attacker can change the environment in which the command executes: the attacker implicitly controls what the command means. Process control vulnerabilities of the first type occur when either data enters the application from an untrusted source and the data is used as part of a string representing a command that is executed by the application. By executing the command, the application gives an attacker a privilege or capability that the attacker would not otherwise have.",,Unknown,
570 CWE-115,EN-Misinterpretation of Input (Type: Base),"The software misinterprets an input, whether from an attacker or another product, in a security-relevant fashion.","Process control vulnerabilities take two forms: 1. An attacker can change the command that the program executes: the attacker explicitly controls what the command is. 2. An attacker can change the environment in which the command executes: the attacker implicitly controls what the command means. Process control vulnerabilities of the first type occur when either data enters the application from an untrusted source and the data is used as part of a string representing a command that is executed by the application. By executing the command, the application gives an attacker a privilege or capability that the attacker would not otherwise have.",,Unknown,
571 CWE-118,EN-Improper Access of Indexable Resource (Range Error) (Type: Class),"The software does not restrict or incorrectly restricts operations within the boundaries of a resource that is accessed using an index or pointer, such as memory or files.","This can allow an attacker to forge log entries or inject malicious content into logs.
572 Log forging vulnerabilities occur when:
573 Data enters an application from an untrusted source.
574 The data is written to an application or system log file.",,Unknown,
575 CWE-12,EN-ASP.NET Misconfiguration: Missing Custom Error Page (Type: Variant),An ASP .NET application must enable custom error pages in order to prevent attackers from mining information from the framework's built-in responses.,"Certain languages allow direct addressing of memory locations and do not automatically ensure that these locations are valid for the memory buffer that is being referenced. This can cause read or write operations to be performed on memory locations that may be associated with other variables, data structures, or internal program data.
576 As a result, an attacker may be able to execute arbitrary code, alter the intended control flow, read sensitive information, or cause the system to crash.",,Unknown,"19 Deadly Sins of Software Security
577 ASP.NET Misconfiguration: Missing Custom Error Handling: http://www.owasp.org/index.php/ASP.NET_Misconfiguration:_Missing_Custom_Error_Handling"
578 CWE-125,EN-Out-of-bounds Read (Type: Base),"The software reads data past the end, or before the beginning, of the intended buffer.","This typically occurs when the pointer or its index is incremented or decremented to a position beyond the bounds of the buffer or when pointer arithmetic results in a position outside of the valid memory location to name a few. This may result in corruption of sensitive information, a crash, or code execution among other things.",,Unknown,"24 Deadly Sins of Software Security: ""Sin 5: Buffer Overruns."" Page 89"
579 CWE-126,EN-Buffer Over-read (Type: Variant),The software reads from a buffer using buffer access mechanisms such as indexes or pointers that reference memory locations after the targeted buffer.,This typically occurs when the pointer or its index is incremented to a position beyond the bounds of the buffer or when pointer arithmetic results in a position outside of the valid memory location to name a few. This may result in exposure of sensitive information or possibly a crash.,,Unknown,
580 CWE-127,EN-Buffer Under-read (Type: Variant),The software reads from a buffer using buffer access mechanisms such as indexes or pointers that reference memory locations prior to the targeted buffer.,"This typically occurs when the pointer or its index is decremented to a position before the buffer, when pointer arithmetic results in a position before the beginning of the valid memory location, or when a negative index is used. This may result in exposure of sensitive information or possibly a crash.",,Unknown,
581 CWE-13,EN-ASP.NET Misconfiguration: Password in Configuration File (Type: Variant),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.,"This typically occurs when the pointer or its index is decremented to a position before the buffer, when pointer arithmetic results in a position before the beginning of the valid memory location, or when a negative index is used. This may result in exposure of sensitive information or possibly a crash.",,Unknown,"How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI: http://msdn.microsoft.com/en-us/library/ms998280.aspx
582 How To: Encrypt Configuration Sections in ASP.NET 2.0 Using RSA: http://msdn.microsoft.com/en-us/library/ms998283.aspx
583 .NET Framework Developer's Guide - Securing Connection Strings: http://msdn.microsoft.com/en-us/library/89211k9b(VS.80).aspx"
584 CWE-130,EN-Improper Handling of Length Parameter Inconsistency (Type: Variant),"The software parses a formatted message or structure, but it does not handle or incorrectly handles a length field that is inconsistent with the actual length of the associated data.","If an attacker can manipulate the length parameter associated with an input such that it is inconsistent with the actual length of the input, this can be leveraged to cause the target application to behave in unexpected, and possibly, malicious ways. One of the possible motives for doing so is to pass in arbitrarily large input to the application. Another possible motivation is the modification of application state by including invalid data for subsequent properties of the application. Such weaknesses commonly lead to attacks such as buffer overflows and execution of arbitrary code.",,Unknown,
585 CWE-132,EN-DEPRECATED (Duplicate): Miscalculated Null Termination (Type: Base),This entry has been deprecated because it was a duplicate of CWE-170. All content has been transferred to CWE-170.,"If an attacker can manipulate the length parameter associated with an input such that it is inconsistent with the actual length of the input, this can be leveraged to cause the target application to behave in unexpected, and possibly, malicious ways. One of the possible motives for doing so is to pass in arbitrarily large input to the application. Another possible motivation is the modification of application state by including invalid data for subsequent properties of the application. Such weaknesses commonly lead to attacks such as buffer overflows and execution of arbitrary code.",,Unknown,
586 CWE-135,EN-Incorrect Calculation of Multi-Byte String Length (Type: Base),The software does not correctly calculate the length of strings that can contain wide or multi-byte characters.,"If an attacker can manipulate the length parameter associated with an input such that it is inconsistent with the actual length of the input, this can be leveraged to cause the target application to behave in unexpected, and possibly, malicious ways. One of the possible motives for doing so is to pass in arbitrarily large input to the application. Another possible motivation is the modification of application state by including invalid data for subsequent properties of the application. Such weaknesses commonly lead to attacks such as buffer overflows and execution of arbitrary code.",,Unknown,"Writing Secure Code: Chapter 5, ""Unicode and ANSI Buffer Size Mismatches"" Page 153"
587 CWE-138,EN-Improper Neutralization of Special Elements (Type: Class),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as control elements or syntactic markers when they are sent to a downstream component.","Most languages and protocols have their own special elements such as characters and reserved words. These special elements can carry control implications. If software does not prevent external control or influence over the inclusion of such special elements, the control flow of the program may be altered from what was intended. For example, both Unix and Windows interpret the symbol < (""less than"") as meaning ""read input from a file"".",,Unknown,
588 CWE-14,EN-Compiler Removal of Code to Clear Buffers (Type: Base),"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.""","This compiler optimization error occurs when:
589 1. Secret data are stored in memory.
590 2. The secret data are scrubbed from memory by overwriting its contents.
591 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.",,Unknown,"Writing Secure Code: Chapter 9, ""A Compiler Optimization Caveat"" Page 322
592 When scrubbing secrets in memory doesn't work: http://cert.uni-stuttgart.de/archive/bugtraq/2002/11/msg00046.html
593 Some Bad News and Some Good News: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncode/html/secure10102002.asp
594 GNU GCC: Optimizer Removes Code Necessary for Security: http://www.derkeiler.com/Mailing-Lists/securityfocus/bugtraq/2002-11/0257.html"
595 CWE-140,EN-Improper Neutralization of Delimiters (Type: Base),The software does not neutralize or incorrectly neutralizes delimiters.,"This compiler optimization error occurs when:
596 1. Secret data are stored in memory.
597 2. The secret data are scrubbed from memory by overwriting its contents.
598 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.",,Unknown,
599 CWE-141,EN-Improper Neutralization of Parameter/Argument Delimiters (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as parameter or argument delimiters when they are sent to a downstream component.","As data is parsed, an injected/absent/malformed delimiter may cause the process to take unexpected actions.",,Unknown,"The Art of Software Security Assessment: Chapter 8, ""Embedded Delimiters"", Page 408.
600 The Art of Software Security Assessment: Chapter 10, ""IFS"", Page 604."
601 CWE-142,EN-Improper Neutralization of Value Delimiters (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as value delimiters when they are sent to a downstream component.","As data is parsed, an injected/absent/malformed delimiter may cause the process to take unexpected actions.",,Unknown,"The Art of Software Security Assessment: Chapter 8, ""Embedded Delimiters"", Page 408."
602 CWE-143,EN-Improper Neutralization of Record Delimiters (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as record delimiters when they are sent to a downstream component.","As data is parsed, an injected/absent/malformed delimiter may cause the process to take unexpected actions.",,Unknown,"The Art of Software Security Assessment: Chapter 8, ""Embedded Delimiters"", Page 408."
603 CWE-144,EN-Improper Neutralization of Line Delimiters (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as line delimiters when they are sent to a downstream component.","As data is parsed, an injected/absent/malformed delimiter may cause the process to take unexpected actions.",,Unknown,"The Art of Software Security Assessment: Chapter 8, ""Embedded Delimiters"", Page 408."
604 CWE-145,EN-Improper Neutralization of Section Delimiters (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as section delimiters when they are sent to a downstream component.","As data is parsed, an injected/absent/malformed delimiter may cause the process to take unexpected actions.
605 One example of a section delimiter is the boundary string in a multipart MIME message. In many cases, doubled line delimiters can serve as a section delimiter.",,Unknown,"The Art of Software Security Assessment: Chapter 8, ""Embedded Delimiters"", Page 408."
606 CWE-146,EN-Improper Neutralization of Expression/Command Delimiters (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as expression or command delimiters when they are sent to a downstream component.","As data is parsed, an injected/absent/malformed delimiter may cause the process to take unexpected actions.",,Unknown,"The Art of Software Security Assessment: Chapter 8, ""Embedded Delimiters"", Page 408."
607 CWE-147,EN-Improper Neutralization of Input Terminators (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as input terminators when they are sent to a downstream component.","For example, a ""."" in SMTP signifies the end of mail message data, whereas a null character can be used for the end of a string.",,Unknown,
608 CWE-148,EN-Improper Neutralization of Input Leaders (Type: Variant),"The application does not properly handle when a leading character or sequence (""leader"") is missing or malformed, or if multiple leaders are used when only one should be allowed.","For example, a ""."" in SMTP signifies the end of mail message data, whereas a null character can be used for the end of a string.",,Unknown,
609 CWE-149,EN-Improper Neutralization of Quoting Syntax (Type: Variant),"Quotes injected into an application can be used to compromise a system. As data are parsed, an injected/absent/duplicate/malformed use of quotes may cause the process to take unexpected actions.","For example, a ""."" in SMTP signifies the end of mail message data, whereas a null character can be used for the end of a string.",,Unknown,
610 CWE-15,EN-External Control of System or Configuration Setting (Type: Base),One or more system settings or configuration elements can be externally controlled by a user.,"Allowing external control of system settings can disrupt service or cause an application to behave in unexpected, and potentially malicious ways.",,Unknown,
611 CWE-150,"EN-Improper Neutralization of Escape, Meta, or Control Sequences (Type: Variant)","The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as escape, meta, or control character sequences when they are sent to a downstream component.","As data is parsed, an injected/absent/malformed delimiter may cause the process to take unexpected actions.",,Unknown,
612 CWE-151,EN-Improper Neutralization of Comment Delimiters (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as comment delimiters when they are sent to a downstream component.","As data is parsed, an injected/absent/malformed delimiter may cause the process to take unexpected actions.",,Unknown,
613 CWE-152,EN-Improper Neutralization of Macro Symbols (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as macro symbols when they are sent to a downstream component.","As data is parsed, an injected/absent/malformed delimiter may cause the process to take unexpected actions.",,Unknown,
614 CWE-153,EN-Improper Neutralization of Substitution Characters (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as substitution characters when they are sent to a downstream component.","As data is parsed, an injected/absent/malformed delimiter may cause the process to take unexpected actions.",,Unknown,
615 CWE-154,EN-Improper Neutralization of Variable Name Delimiters (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as variable name delimiters when they are sent to a downstream component.","As data is parsed, an injected delimiter may cause the process to take unexpected actions that result in an attack. Example: ""$"" for an environment variable.",,Unknown,
616 CWE-155,EN-Improper Neutralization of Wildcards or Matching Symbols (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as wildcards or matching symbols when they are sent to a downstream component.","As data is parsed, an injected element may cause the process to take unexpected actions.",,Unknown,
617 CWE-156,EN-Improper Neutralization of Whitespace (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as whitespace when they are sent to a downstream component.","This can include space, tab, etc.",,Unknown,
618 CWE-157,EN-Failure to Sanitize Paired Delimiters (Type: Variant),"The software does not properly handle the characters that are used to mark the beginning and ending of a group of entities, such as parentheses, brackets, and braces.","This can include space, tab, etc.",,Unknown,
619 CWE-158,EN-Improper Neutralization of Null Byte or NUL Character (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes NUL characters or null bytes when they are sent to a downstream component.","As data is parsed, an injected NUL character or null byte may cause the software to believe the input is terminated earlier than it actually is, or otherwise cause the input to be misinterpreted. This could then be used to inject potentially dangerous input that occurs after the null byte or otherwise bypass validation routines and other protection mechanisms.",,Unknown,"The Art of Software Security Assessment: Chapter 8, ""NUL Character Injection"", Page 411."
620 CWE-159,EN-Failure to Sanitize Special Element (Type: Class),Weaknesses in this attack-focused category do not properly filter and interpret special elements in user-controlled input which could cause adverse effect on the software behavior and integrity.,"As data is parsed, an injected NUL character or null byte may cause the software to believe the input is terminated earlier than it actually is, or otherwise cause the input to be misinterpreted. This could then be used to inject potentially dangerous input that occurs after the null byte or otherwise bypass validation routines and other protection mechanisms.",,Unknown,
621 CWE-160,EN-Improper Neutralization of Leading Special Elements (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes leading special elements that could be interpreted in unexpected ways when they are sent to a downstream component.","As data is parsed, improperly handled leading special elements may cause the process to take unexpected actions that result in an attack.",,Unknown,
622 CWE-161,EN-Improper Neutralization of Multiple Leading Special Elements (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes multiple leading special elements that could be interpreted in unexpected ways when they are sent to a downstream component.","As data is parsed, improperly handled multiple leading special elements may cause the process to take unexpected actions that result in an attack.",,Unknown,
623 CWE-162,EN-Improper Neutralization of Trailing Special Elements (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes trailing special elements that could be interpreted in unexpected ways when they are sent to a downstream component.","As data is parsed, improperly handled trailing special elements may cause the process to take unexpected actions that result in an attack.",,Unknown,
624 CWE-163,EN-Improper Neutralization of Multiple Trailing Special Elements (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes multiple trailing special elements that could be interpreted in unexpected ways when they are sent to a downstream component.","As data is parsed, improperly handled multiple trailing special elements may cause the process to take unexpected actions that result in an attack.",,Unknown,
625 CWE-164,EN-Improper Neutralization of Internal Special Elements (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes internal special elements that could be interpreted in unexpected ways when they are sent to a downstream component.","As data is parsed, improperly handled internal special elements may cause the process to take unexpected actions that result in an attack.",,Unknown,
626 CWE-165,EN-Improper Neutralization of Multiple Internal Special Elements (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes multiple internal special elements that could be interpreted in unexpected ways when they are sent to a downstream component.","As data is parsed, improperly handled multiple internal special elements may cause the process to take unexpected actions that result in an attack.",,Unknown,
627 CWE-166,EN-Improper Handling of Missing Special Element (Type: Base),"The software receives input from an upstream component, but it does not handle or incorrectly handles when an expected special element is missing.","As data is parsed, improperly handled multiple internal special elements may cause the process to take unexpected actions that result in an attack.",,Unknown,
628 CWE-167,EN-Improper Handling of Additional Special Element (Type: Base),"The software receives input from an upstream component, but it does not handle or incorrectly handles when an additional unexpected special element is missing.","As data is parsed, improperly handled multiple internal special elements may cause the process to take unexpected actions that result in an attack.",,Unknown,
629 CWE-168,EN-Improper Handling of Inconsistent Special Elements (Type: Base),The software does not handle when an inconsistency exists between two or more special characters or reserved words.,"An example of this problem would be if paired characters appear in the wrong order, or if the special characters are not properly nested.",,Unknown,
630 CWE-172,EN-Encoding Error (Type: Class),"The software does not properly encode or decode the data, resulting in unexpected values.","Null termination errors frequently occur in two different ways. An off-by-one error could cause a null to be written out of bounds, leading to an overflow. Or, a program could use a strncpy() function call incorrectly, which prevents a null terminator from being added at all. Other scenarios are possible.",,Unknown,
631 CWE-173,EN-Improper Handling of Alternate Encoding (Type: Variant),The software does not properly handle when an input uses an alternate encoding that is valid for the control sphere to which the input is being sent.,"Null termination errors frequently occur in two different ways. An off-by-one error could cause a null to be written out of bounds, leading to an overflow. Or, a program could use a strncpy() function call incorrectly, which prevents a null terminator from being added at all. Other scenarios are possible.",,Unknown,
632 CWE-174,EN-Double Decoding of the Same Data (Type: Variant),"The software decodes the same input twice, which can limit the effectiveness of any protection mechanism that occurs in between the decoding operations.","Null termination errors frequently occur in two different ways. An off-by-one error could cause a null to be written out of bounds, leading to an overflow. Or, a program could use a strncpy() function call incorrectly, which prevents a null terminator from being added at all. Other scenarios are possible.",,Unknown,
633 CWE-175,EN-Improper Handling of Mixed Encoding (Type: Variant),The software does not properly handle when the same input uses several different (mixed) encodings.,"Null termination errors frequently occur in two different ways. An off-by-one error could cause a null to be written out of bounds, leading to an overflow. Or, a program could use a strncpy() function call incorrectly, which prevents a null terminator from being added at all. Other scenarios are possible.",,Unknown,
634 CWE-176,EN-Improper Handling of Unicode Encoding (Type: Variant),The software does not properly handle when an input contains Unicode encoding.,"Null termination errors frequently occur in two different ways. An off-by-one error could cause a null to be written out of bounds, leading to an overflow. Or, a program could use a strncpy() function call incorrectly, which prevents a null terminator from being added at all. Other scenarios are possible.",,Unknown,"The Art of Software Security Assessment: Chapter 8, ""Character Sets and Unicode"", Page 446."
635 CWE-177,EN-Improper Handling of URL Encoding (Hex Encoding) (Type: Variant),The software does not properly handle when all or part of an input has been URL encoded.,"Null termination errors frequently occur in two different ways. An off-by-one error could cause a null to be written out of bounds, leading to an overflow. Or, a program could use a strncpy() function call incorrectly, which prevents a null terminator from being added at all. Other scenarios are possible.",,Unknown,
636 CWE-178,EN-Improper Handling of Case Sensitivity (Type: Base),"The software does not properly account for differences in case sensitivity when accessing or determining the properties of a resource, leading to inconsistent results.","Improperly handled case sensitive data can lead to several possible consequences, including:
637 case-insensitive passwords reducing the size of the key space, making brute force attacks easier
638 bypassing filters or access controls using alternate names
639 multiple interpretation errors using alternate names.",,Unknown,
640 CWE-179,EN-Incorrect Behavior Order: Early Validation (Type: Base),"The software validates input before applying protection mechanisms that modify the input, which could allow an attacker to bypass the validation via dangerous inputs that only arise after the modification.","Software needs to validate data at the proper time, after data has been canonicalized and cleansed. Early validation is susceptible to various manipulations that result in dangerous inputs that are produced by canonicalization and cleansing.",,Unknown,"The Art of Software Security Assessment: Chapter 8, ""Escaping Metacharacters"", Page 439."
641 CWE-180,EN-Incorrect Behavior Order: Validate Before Canonicalize (Type: Base),"The software validates input before it is canonicalized, which prevents the software from detecting data that becomes invalid after the canonicalization step.","This can be used by an attacker to bypass the validation and launch attacks that expose weaknesses that would otherwise be prevented, such as injection.",,Unknown,
642 CWE-181,EN-Incorrect Behavior Order: Validate Before Filter (Type: Base),"The software validates data before it has been filtered, which prevents the software from detecting data that becomes invalid after the filtering step.","This can be used by an attacker to bypass the validation and launch attacks that expose weaknesses that would otherwise be prevented, such as injection.",,Unknown,
643 CWE-182,EN-Collapse of Data into Unsafe Value (Type: Base),"The software filters data in a way that causes it to be reduced or ""collapsed"" into an unsafe value that violates an expected security property.","This can be used by an attacker to bypass the validation and launch attacks that expose weaknesses that would otherwise be prevented, such as injection.",,Unknown,"The Art of Software Security Assessment: Chapter 8, ""Character Stripping Vulnerabilities"", Page 437."
644 CWE-183,EN-Permissive Whitelist (Type: Base),"An application uses a ""whitelist"" of acceptable values, but the whitelist includes at least one unsafe value, leading to resultant weaknesses.","This can be used by an attacker to bypass the validation and launch attacks that expose weaknesses that would otherwise be prevented, such as injection.",,Unknown,"The Art of Software Security Assessment: Chapter 8, ""Eliminating Metacharacters"", Page 435."
645 CWE-184,EN-Incomplete Blacklist (Type: Base),"An application uses a ""blacklist"" of prohibited values, but the blacklist is incomplete.","If an incomplete blacklist is used as a security mechanism, then the software may allow unintended values to pass into the application logic.",,Unknown,"Exploiting Software: How to Break Code
646 Blacklist defenses as a breeding ground for vulnerability variants: http://seclists.org/fulldisclosure/2006/Feb/0040.html
647 The Art of Software Security Assessment: Chapter 8, ""Eliminating Metacharacters"", Page 435."
648 CWE-185,EN-Incorrect Regular Expression (Type: Class),The software specifies a regular expression in a way that causes data to be improperly matched or compared.,"When the regular expression is used in protection mechanisms such as filtering or validation, this may allow an attacker to bypass the intended restrictions on the incoming data.",,Unknown,"Writing Secure Code: Chapter 10, ""Using Regular Expressions for Checking Input"" Page 350"
649 CWE-186,EN-Overly Restrictive Regular Expression (Type: Base),"A regular expression is overly restrictive, which prevents dangerous values from being detected.","When the regular expression is used in protection mechanisms such as filtering or validation, this may allow an attacker to bypass the intended restrictions on the incoming data.",,Unknown,
650 CWE-187,EN-Partial Comparison (Type: Base),"The software performs a comparison that only examines a portion of a factor before determining whether there is a match, such as a substring, leading to resultant weaknesses.","For example, an attacker might succeed in authentication by providing a small password that matches the associated portion of the larger, correct password.",,Unknown,
651 CWE-191,EN-Integer Underflow (Wrap or Wraparound) (Type: Base),"The product subtracts one value from another, such that the result is less than the minimum allowable integer value, which produces a value that is not equal to the correct result.",This can happen in signed and unsigned cases.,,Unknown,"24 Deadly Sins of Software Security: ""Sin 7: Integer Overflows."" Page 119"
652 CWE-193,EN-Off-by-one Error (Type: Base),"A product calculates or uses an incorrect maximum or minimum value that is 1 more, or 1 less, than the correct value.",This can happen in signed and unsigned cases.,,Unknown,"Third Generation Exploits: http://www.blackhat.com/presentations/bh-europe-01/halvar-flake/bh-europe-01-halvarflake.ppt
653 Off-by-one errors: a brief explanation: http://marc.theaimsgroup.com/?l=secprog&m=108379742110553&w=2
654 The Frame Pointer Overwrite: http://kaizo.org/mirrors/phrack/phrack55/P55-08
655 Exploiting Software: How to Break Code (The buffer overflow chapter)
656 24 Deadly Sins of Software Security: ""Sin 5: Buffer Overruns."" Page 89
657 The Art of Software Security Assessment: Chapter 5, ""Off-by-One Errors"", Page 180."
658 CWE-195,EN-Signed to Unsigned Conversion Error (Type: Variant),"A signed-to-unsigned conversion error takes place when a signed primitive is used as an unsigned value, usually as a size variable.",It is dangerous to rely on implicit casts between signed and unsigned numbers because the result can take on an unexpected value and violate assumptions made by the program.,,Unknown,"The Art of Software Security Assessment: Chapter 6, ""Type Conversions"", Page 223."
659 CWE-198,EN-Use of Incorrect Byte Ordering (Type: Base),"The software receives input from an upstream component, but it does not account for byte ordering (e.g. big-endian and little-endian) when processing the input, causing an incorrect number or value to be used.","When a primitive is cast to a smaller primitive, the high order bits of the large value are lost in the conversion, potentially resulting in an unexpected value that is not equal to the original value. This value may be required as an index into a buffer, a loop iterator, or simply necessary state data. In any case, the value cannot be trusted and the system will be in an undefined state. While this method may be employed viably to isolate the low bits of a value, this usage is rare, and truncation usually implies that an implementation error has occurred.",,Unknown,
660 CWE-201,EN-Information Exposure Through Sent Data (Type: Variant),The accidental exposure of sensitive information through sent data refers to the transmission of data which are either sensitive in and of itself or useful in the further exploitation of the system through standard data channels.,"The information either
661 is regarded as sensitive within the product's own functionality, such as a private message; or
662 provides information about the product or its environment that could be useful in an attack but is normally not available to the attacker, such as the installation path of a product that is remotely accessible.
663 Many information exposures are resultant (e.g. PHP script error revealing the full path of the program), but they can also be primary (e.g. timing discrepancies in cryptography). There are many different types of problems that involve information exposures. Their severity can range widely depending on the type of information that is revealed.",,Unknown,
664 CWE-203,EN-Information Exposure Through Discrepancy (Type: Class),"The product behaves differently or sends different responses in a way that exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not.","In situations where data should not be tied to individual users, but a large number of users should be able to make queries that ""scrub"" the identity of users, it may be possible to get information about a user -- e.g., by specifying search terms that are known to be unique to that user.",,Unknown,
665 CWE-204,EN-Response Discrepancy Information Exposure (Type: Base),The software provides different responses to incoming requests in a way that allows an actor to determine system state information that is outside of that actor's control sphere.,"This issue frequently occurs during authentication, where a difference in failed-login messages could allow an attacker to determine if the username is valid or not. These exposures can be inadvertent (bug) or intentional (design).",,Unknown,"24 Deadly Sins of Software Security: ""Sin 12: Information Leakage."" Page 191"
666 CWE-205,EN-Information Exposure Through Behavioral Discrepancy (Type: Base),The product's actions indicate important differences based on (1) the internal state of the product or (2) differences from other products in the same class.,"For example, attacks such as OS fingerprinting rely heavily on both behavioral and response discrepancies.",,Unknown,
667 CWE-206,EN-Information Exposure of Internal State Through Behavioral Inconsistency (Type: Variant),"Two separate operations in a product cause the product to behave differently in a way that is observable to an attacker and reveals security-relevant information about the internal state of the product, such as whether a particular operation was successful or not.","For example, attacks such as OS fingerprinting rely heavily on both behavioral and response discrepancies.",,Unknown,
668 CWE-207,EN-Information Exposure Through an External Behavioral Inconsistency (Type: Variant),"The product behaves differently than other products like it, in a way that is observable to an attacker and exposes security-relevant information about which product is being used.","For example, attacks such as OS fingerprinting rely heavily on both behavioral and response discrepancies.",,Unknown,
669 CWE-208,EN-Information Exposure Through Timing Discrepancy (Type: Base),"Two separate operations in a product require different amounts of time to complete, in a way that is observable to an actor and reveals security-relevant information about the state of the product, such as whether a particular operation was successful or not.","For example, attacks such as OS fingerprinting rely heavily on both behavioral and response discrepancies.",,Unknown,
670 CWE-210,EN-Information Exposure Through Self-generated Error Message (Type: Base),The software identifies an error condition and creates its own diagnostic or error messages that contain sensitive information.,"The sensitive information may be valuable information on its own (such as a password), or it may be useful for launching other, more deadly attacks. If an attack fails, an attacker may use error information provided by the server to launch another more focused attack. For example, an attempt to exploit a path traversal weakness (CWE-22) might yield the full pathname of the installed application. In turn, this could be used to select the proper number of "".."" sequences to navigate to the targeted file. An attack using SQL injection (CWE-89) might not initially succeed, but an error message could reveal the malformed query, which would expose query logic and possibly even passwords or other sensitive information used within the query.",,Unknown,"24 Deadly Sins of Software Security: ""Sin 12: Information Leakage."" Page 191
671 The Art of Software Security Assessment: Chapter 3, ""Overly Verbose Error Messages"", Page 75."
672 CWE-211,EN-Information Exposure Through Externally-generated Error Message (Type: Base),"The software performs an operation that triggers an external diagnostic or error message that is not directly generated by the software, such as an error generated by the programming language interpreter that the software uses. The error can contain sensitive system information.","The sensitive information may be valuable information on its own (such as a password), or it may be useful for launching other, more deadly attacks. If an attack fails, an attacker may use error information provided by the server to launch another more focused attack. For example, an attempt to exploit a path traversal weakness (CWE-22) might yield the full pathname of the installed application. In turn, this could be used to select the proper number of "".."" sequences to navigate to the targeted file. An attack using SQL injection (CWE-89) might not initially succeed, but an error message could reveal the malformed query, which would expose query logic and possibly even passwords or other sensitive information used within the query.",,Unknown,
673 CWE-212,EN-Improper Cross-boundary Removal of Sensitive Data (Type: Base),"The software uses a resource that contains sensitive data, but it does not properly remove that data before it stores, transfers, or shares the resource with actors in another control sphere.","Resources that may contain sensitive data include documents, packets, messages, databases, etc. While this data may be useful to an individual user or small set of users who share the resource, it may need to be removed before the resource can be shared outside of the trusted group. The process of removal is sometimes called cleansing or scrubbing.
674 For example, software that is used for editing documents might not remove sensitive data such as reviewer comments or the local pathname where the document is stored. Or, a proxy might not remove an internal IP address from headers before making an outgoing request to an Internet site.",,Unknown,
675 CWE-213,EN-Intentional Information Exposure (Type: Base),A product's design or configuration explicitly requires the publication of information that could be regarded as sensitive by an administrator.,"Resources that may contain sensitive data include documents, packets, messages, databases, etc. While this data may be useful to an individual user or small set of users who share the resource, it may need to be removed before the resource can be shared outside of the trusted group. The process of removal is sometimes called cleansing or scrubbing.
676 For example, software that is used for editing documents might not remove sensitive data such as reviewer comments or the local pathname where the document is stored. Or, a proxy might not remove an internal IP address from headers before making an outgoing request to an Internet site.",,Unknown,
677 CWE-214,EN-Information Exposure Through Process Environment (Type: Variant),"A process is invoked with sensitive arguments, environment variables, or other elements that can be seen by other processes on the operating system.","Many operating systems allow a user to list information about processes that are owned by other users. This information could include command line arguments or environment variable settings. When this data contains sensitive information such as credentials, it might allow other users to launch an attack against the software or related resources.",,Unknown,
678 CWE-215,EN-Information Exposure Through Debug Information (Type: Variant),The application contains debugging code that can expose sensitive information to untrusted parties.,"Many operating systems allow a user to list information about processes that are owned by other users. This information could include command line arguments or environment variable settings. When this data contains sensitive information such as credentials, it might allow other users to launch an attack against the software or related resources.",,Unknown,
679 CWE-216,EN-Containment Errors (Container Errors) (Type: Class),"This tries to cover various problems in which improper data are included within a ""container.""","Many operating systems allow a user to list information about processes that are owned by other users. This information could include command line arguments or environment variable settings. When this data contains sensitive information such as credentials, it might allow other users to launch an attack against the software or related resources.",,Unknown,
680 CWE-217,EN-DEPRECATED: Failure to Protect Stored Data from Modification (Type: Base),This weakness has been deprecated because it incorporated and confused multiple weaknesses. The issues formerly covered in this weakness can be found at CWE-766 and CWE-767.,"Many operating systems allow a user to list information about processes that are owned by other users. This information could include command line arguments or environment variable settings. When this data contains sensitive information such as credentials, it might allow other users to launch an attack against the software or related resources.",,Unknown,
681 CWE-218,EN-DEPRECATED (Duplicate): Failure to provide confidentiality for stored data (Type: Base),This weakness has been deprecated because it was a duplicate of CWE-493. All content has been transferred to CWE-493.,"Many operating systems allow a user to list information about processes that are owned by other users. This information could include command line arguments or environment variable settings. When this data contains sensitive information such as credentials, it might allow other users to launch an attack against the software or related resources.",,Unknown,
682 CWE-219,EN-Sensitive Data Under Web Root (Type: Variant),"The application stores sensitive data under the web document root with insufficient access control, which might make it accessible to untrusted parties.","Many operating systems allow a user to list information about processes that are owned by other users. This information could include command line arguments or environment variable settings. When this data contains sensitive information such as credentials, it might allow other users to launch an attack against the software or related resources.",,Unknown,
683 CWE-220,EN-Sensitive Data Under FTP Root (Type: Variant),"The application stores sensitive data under the FTP document root with insufficient access control, which might make it accessible to untrusted parties.","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.
684 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.",,Unknown,
685 CWE-221,EN-Information Loss or Omission (Type: Class),"The software does not record, or improperly records, security-relevant information that leads to an incorrect decision or hampers later analysis.","This can be resultant, e.g. a buffer overflow might trigger a crash before the product can log the event.",,Unknown,
686 CWE-222,EN-Truncation of Security-relevant Information (Type: Base),"The application truncates the display, recording, or processing of security-relevant information in a way that can obscure the source or nature of an attack.","This can be resultant, e.g. a buffer overflow might trigger a crash before the product can log the event.",,Unknown,
687 CWE-223,EN-Omission of Security-relevant Information (Type: Base),"The application does not record or display information that would be important for identifying the source or nature of an attack, or determining if an action is safe.","This can be resultant, e.g. a buffer overflow might trigger a crash before the product can log the event.",,Unknown,"The Art of Software Security Assessment: Chapter 2, ""Accountability"", Page 40."
688 CWE-224,EN-Obscured Security-relevant Information by Alternate Name (Type: Base),"The software records security-relevant information according to an alternate name of the affected entity, instead of the canonical name.","This can be resultant, e.g. a buffer overflow might trigger a crash before the product can log the event.",,Unknown,Writing Secure Code
689 CWE-225,EN-DEPRECATED (Duplicate): General Information Management Problems (Type: Base),This weakness can be found at CWE-199.,"This can be resultant, e.g. a buffer overflow might trigger a crash before the product can log the event.",,Unknown,
690 CWE-226,EN-Sensitive Information Uncleared Before Release (Type: Base),"The software does not fully clear previously used information in a data structure, file, or other resource, before making that resource available to a party in another control sphere.","This typically results from new data that is not as long as the old data, which leaves portions of the old data still available. Equivalent errors can occur in other situations where the length of data is variable but the associated data structure is not. If memory is not cleared after use, it may allow unintended actors to read the data when the memory is reallocated.",,Unknown,
691 CWE-227,EN-Improper Fulfillment of API Contract (API Abuse) (Type: Class),The software uses an API in a manner contrary to its intended use.,"An API is a contract between a caller and a callee. The most common forms of API misuse occurs when the caller does not honor its end of this contract. For example, if a program does not call chdir() after calling chroot(), it violates the contract that specifies how to change the active root directory in a secure fashion. Another good example of library abuse is expecting the callee to return trustworthy DNS information to the caller. In this case, the caller misuses the callee API by making certain assumptions about its behavior (that the return value can be used for authentication purposes). One can also violate the caller-callee contract from the other side. For example, if a coder subclasses SecureRandom and returns a non-random value, the contract is violated.",,Unknown,
692 CWE-228,EN-Improper Handling of Syntactically Invalid Structure (Type: Class),The product does not handle or incorrectly handles input that is not syntactically well-formed with respect to the associated specification.,"An API is a contract between a caller and a callee. The most common forms of API misuse occurs when the caller does not honor its end of this contract. For example, if a program does not call chdir() after calling chroot(), it violates the contract that specifies how to change the active root directory in a secure fashion. Another good example of library abuse is expecting the callee to return trustworthy DNS information to the caller. In this case, the caller misuses the callee API by making certain assumptions about its behavior (that the return value can be used for authentication purposes). One can also violate the caller-callee contract from the other side. For example, if a coder subclasses SecureRandom and returns a non-random value, the contract is violated.",,Unknown,
693 CWE-229,EN-Improper Handling of Values (Type: Base),"The software does not properly handle when the expected number of values for parameters, fields, or arguments is not provided in input, or if those values are undefined.","An API is a contract between a caller and a callee. The most common forms of API misuse occurs when the caller does not honor its end of this contract. For example, if a program does not call chdir() after calling chroot(), it violates the contract that specifies how to change the active root directory in a secure fashion. Another good example of library abuse is expecting the callee to return trustworthy DNS information to the caller. In this case, the caller misuses the callee API by making certain assumptions about its behavior (that the return value can be used for authentication purposes). One can also violate the caller-callee contract from the other side. For example, if a coder subclasses SecureRandom and returns a non-random value, the contract is violated.",,Unknown,
694 CWE-23,EN-Relative Path Traversal (Type: Base),"The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as "".."" that can resolve to a location that is outside of that directory.",This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.,,Unknown,"OWASP Attack listing: http://www.owasp.org/index.php/Relative_Path_Traversal
695 The Art of Software Security Assessment: Chapter 9, ""Filenames and Paths"", Page 503."
696 CWE-230,EN-Improper Handling of Missing Values (Type: Variant),"The software does not handle or incorrectly handles when a parameter, field, or argument name is specified, but the associated value is missing, i.e. it is empty, blank, or null.",This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.,,Unknown,
697 CWE-231,EN-Improper Handling of Extra Values (Type: Variant),The software does not handle or incorrectly handles when more values are provided than expected.,This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.,,Unknown,
698 CWE-232,EN-Improper Handling of Undefined Values (Type: Variant),"The software does not handle or incorrectly handles when a value is not defined or supported for the associated parameter, field, or argument name.",This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.,,Unknown,
699 CWE-233,EN-Improper Handling of Parameters (Type: Base),"The software does not properly handle when the expected number of parameters, fields, or arguments is not provided in input, or if those parameters are undefined.",This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.,,Unknown,
700 CWE-235,EN-Improper Handling of Extra Parameters (Type: Variant),"The software does not handle or incorrectly handles when the number of parameters, fields, or arguments with the same name exceeds the expected amount.",This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.,,Unknown,
701 CWE-236,EN-Improper Handling of Undefined Parameters (Type: Variant),"The software does not handle or incorrectly handles when a particular parameter, field, or argument name is not defined or supported by the product.",This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.,,Unknown,
702 CWE-237,EN-Improper Handling of Structural Elements (Type: Base),The software does not handle or incorrectly handles inputs that are related to complex structures.,This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.,,Unknown,
703 CWE-238,EN-Improper Handling of Incomplete Structural Elements (Type: Variant),The software does not handle or incorrectly handles when a particular structural element is not completely specified.,This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.,,Unknown,
704 CWE-239,EN-Failure to Handle Incomplete Element (Type: Variant),The software does not properly handle when a particular element is not completely specified.,This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.,,Unknown,
705 CWE-24,EN-Path Traversal: ../filedir (Type: Variant),"The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize ""../"" sequences that can resolve to a location that is outside of that directory.","This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
706 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 protection schemes in environments for which ""/"" is supported but not the primary separator, such as Windows, which uses ""\"" but can also accept ""/"".",,Unknown,
707 CWE-240,EN-Improper Handling of Inconsistent Structural Elements (Type: Variant),"The software does not handle or incorrectly handles when two or more structural elements should be consistent, but are not.","This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
708 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 protection schemes in environments for which ""/"" is supported but not the primary separator, such as Windows, which uses ""\"" but can also accept ""/"".",,Unknown,
709 CWE-241,EN-Improper Handling of Unexpected Data Type (Type: Base),"The software does not handle or incorrectly handles when a particular element is not the expected type, e.g. it expects a digit (0-9) but is provided with a letter (A-Z).","This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
710 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 protection schemes in environments for which ""/"" is supported but not the primary separator, such as Windows, which uses ""\"" but can also accept ""/"".",,Unknown,
711 CWE-244,EN-Improper Clearing of Heap Memory Before Release (Heap Inspection) (Type: Variant),"Using realloc() to resize buffers that store sensitive information can leave the sensitive information exposed to attack, because it is not removed from memory.","When sensitive data such as a password or an encryption key is not removed from memory, it could be exposed to an attacker using a ""heap inspection"" attack that reads the sensitive data using memory dumps or other methods. The realloc() function is commonly used to increase the size of a block of allocated memory. This operation often requires copying the contents of the old memory block into a new and larger block. This operation leaves the contents of the original block intact but inaccessible to the program, preventing the program from being able to scrub sensitive data from memory. If an attacker can later examine the contents of a memory dump, the sensitive data could be exposed.",,Unknown,
712 CWE-245,EN-J2EE Bad Practices: Direct Management of Connections (Type: Variant),"The J2EE application directly manages connections, instead of using the container's connection management facilities.","When sensitive data such as a password or an encryption key is not removed from memory, it could be exposed to an attacker using a ""heap inspection"" attack that reads the sensitive data using memory dumps or other methods. The realloc() function is commonly used to increase the size of a block of allocated memory. This operation often requires copying the contents of the old memory block into a new and larger block. This operation leaves the contents of the original block intact but inaccessible to the program, preventing the program from being able to scrub sensitive data from memory. If an attacker can later examine the contents of a memory dump, the sensitive data could be exposed.",,Unknown,
713 CWE-246,EN-J2EE Bad Practices: Direct Use of Sockets (Type: Variant),The J2EE application directly uses sockets instead of using framework method calls.,"When sensitive data such as a password or an encryption key is not removed from memory, it could be exposed to an attacker using a ""heap inspection"" attack that reads the sensitive data using memory dumps or other methods. The realloc() function is commonly used to increase the size of a block of allocated memory. This operation often requires copying the contents of the old memory block into a new and larger block. This operation leaves the contents of the original block intact but inaccessible to the program, preventing the program from being able to scrub sensitive data from memory. If an attacker can later examine the contents of a memory dump, the sensitive data could be exposed.",,Unknown,
714 CWE-247,EN-DEPRECATED (Duplicate): Reliance on DNS Lookups in a Security Decision (Type: Base),This entry has been deprecated because it was a duplicate of CWE-350. All content has been transferred to CWE-350.,"When sensitive data such as a password or an encryption key is not removed from memory, it could be exposed to an attacker using a ""heap inspection"" attack that reads the sensitive data using memory dumps or other methods. The realloc() function is commonly used to increase the size of a block of allocated memory. This operation often requires copying the contents of the old memory block into a new and larger block. This operation leaves the contents of the original block intact but inaccessible to the program, preventing the program from being able to scrub sensitive data from memory. If an attacker can later examine the contents of a memory dump, the sensitive data could be exposed.",,Unknown,
715 CWE-248,EN-Uncaught Exception (Type: Base),"An exception is thrown from a function, but it is not caught.","When an exception is not caught, it may cause the program to crash or expose sensitive information.",,Unknown,
716 CWE-249,EN-DEPRECATED: Often Misused: Path Manipulation (Type: Variant),This entry has been deprecated because of name confusion and an accidental combination of multiple weaknesses. Most of its content has been transferred to CWE-785.,"When an exception is not caught, it may cause the program to crash or expose sensitive information.",,Unknown,
717 CWE-25,EN-Path Traversal: /../filedir (Type: Variant),"The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize ""/../"" sequences that can resolve to a location that is outside of that directory.","This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
718 Sometimes a program checks for ""../"" at the beginning of the input, so a ""/../"" can bypass that check.",,Unknown,
719 CWE-26,EN-Path Traversal: /dir/../filename (Type: Variant),"The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize ""/dir/../filename"" sequences that can resolve to a location that is outside of that directory.","This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
720 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.",,Unknown,
721 CWE-260,EN-Password in Configuration File (Type: Variant),The software stores a password in a configuration file that might be accessible to actors who do not know the password.,"This can result in compromise of the system for which the password is used. An attacker could gain access to this file and learn the stored password or worse yet, change the password to one of their choosing.",,Unknown,Building Secure Software: How to Avoid Security Problems the Right Way
722 CWE-261,EN-Weak Cryptography for Passwords (Type: Variant),Obscuring a password with a trivial encoding does not protect the password.,"This can result in compromise of the system for which the password is used. An attacker could gain access to this file and learn the stored password or worse yet, change the password to one of their choosing.",,Unknown,"Building Secure Software: How to Avoid Security Problems the Right Way
723 24 Deadly Sins of Software Security: ""Sin 19: Use of Weak Password-Based Systems."" Page 279"
724 CWE-266,EN-Incorrect Privilege Assignment (Type: Base),"A product incorrectly assigns a privilege to a particular actor, creating an unintended sphere of control for that actor.","Just as neglecting to include functionality for the management of password aging is dangerous, so is allowing password aging to continue unchecked. Passwords must be given a maximum life span, after which a user is required to update with a new and different password.",,Unknown,Least Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html
725 CWE-267,EN-Privilege Defined With Unsafe Actions (Type: Base),"A particular privilege, role, capability, or right can be used to perform unsafe actions that were not intended, even when it is assigned to the correct entity.","Just as neglecting to include functionality for the management of password aging is dangerous, so is allowing password aging to continue unchecked. Passwords must be given a maximum life span, after which a user is required to update with a new and different password.",,Unknown,Least Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html
726 CWE-27,EN-Path Traversal: dir/../../filename (Type: Variant),"The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize multiple internal ""../"" sequences that can resolve to a location that is outside of that directory.","This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
727 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.",,Unknown,
728 CWE-270,EN-Privilege Context Switching Error (Type: Base),The software does not properly manage privileges while it is switching between different contexts that have different privileges or spheres of control.,"This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
729 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.",,Unknown,"Writing Secure Code: Chapter 7, ""Running with Least Privilege"" Page 207
730 Least Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html"
731 CWE-272,EN-Least Privilege Violation (Type: Base),The elevated privilege level required to perform operations such as chroot() should be dropped immediately after the operation is performed.,"In some contexts, a system executing with elevated permissions will hand off a process/file/etc. to another process or user. If the privileges of an entity are not reduced, then elevated privileges are spread throughout a system and possibly to an attacker.",,Unknown,
732 CWE-274,EN-Improper Handling of Insufficient Privileges (Type: Base),"The software does not handle or incorrectly handles when it has insufficient privileges to perform an operation, leading to resultant weaknesses.","If the drop fails, the software will continue to run with the raised privileges, which might provide additional access to unprivileged users.",,Unknown,
733 CWE-277,EN-Insecure Inherited Permissions (Type: Variant),A product defines a set of insecure permissions that are inherited by objects that are created by the program.,"If the drop fails, the software will continue to run with the raised privileges, which might provide additional access to unprivileged users.",,Unknown,
734 CWE-278,EN-Insecure Preserved Inherited Permissions (Type: Variant),"A product inherits a set of insecure permissions for an object, e.g. when copying from an archive file, without user awareness or involvement.","If the drop fails, the software will continue to run with the raised privileges, which might provide additional access to unprivileged users.",,Unknown,
735 CWE-279,EN-Incorrect Execution-Assigned Permissions (Type: Variant),"While it is executing, the software sets the permissions of an object in a way that violates the intended permissions that have been specified by the user.","If the drop fails, the software will continue to run with the raised privileges, which might provide additional access to unprivileged users.",,Unknown,
736 CWE-28,EN-Path Traversal: ..\filedir (Type: Variant),"The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize ""..\"" sequences that can resolve to a location that is outside of that directory.","This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
737 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.",,Unknown,
738 CWE-280,EN-Improper Handling of Insufficient Permissions or Privileges (Type: Base),The application does not handle or incorrectly handles when it has insufficient privileges to access resources or functionality as specified by their permissions. This may cause it to follow unexpected code paths that may leave the application in an invalid state.,"This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
739 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.",,Unknown,
740 CWE-281,EN-Improper Preservation of Permissions (Type: Base),"The software does not preserve permissions or incorrectly preserves permissions when copying, restoring, or sharing objects, which can cause them to have less restrictive permissions than intended.","This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
741 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.",,Unknown,
742 CWE-282,EN-Improper Ownership Management (Type: Class),"The software assigns the wrong ownership, or does not properly verify the ownership, of an object or resource.","This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
743 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.",,Unknown,
744 CWE-283,EN-Unverified Ownership (Type: Base),The software does not properly verify that a critical resource is owned by the proper entity.,"This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
745 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.",,Unknown,
746 CWE-284,EN-Improper Access Control (Type: Class),The software does not restrict or incorrectly restricts access to a resource from an unauthorized actor.,"Access control involves the use of several protection mechanisms such as authentication (proving the identity of an actor) authorization (ensuring that a given actor can access a resource), and accountability (tracking of activities that were performed). When any mechanism is not applied or otherwise fails, attackers can compromise the security of the software by gaining privileges, reading sensitive information, executing commands, evading detection, etc.
747 There are two distinct behaviors that can introduce access control weaknesses:
748 Specification: incorrect privileges, permissions, ownership, etc. are explicitly specified for either the user or the resource (for example, setting a password file to be world-writable, or giving administrator capabilities to a guest user). This action could be performed by the program or the administrator.
749 Enforcement: the mechanism contains errors that prevent it from properly enforcing the specified access control requirements (e.g., allowing the user to specify their own privileges, or allowing a syntactically-incorrect ACL to produce insecure settings). This problem occurs within the program itself, in that it does not actually enforce the intended security policy that the administrator specifies.",,Unknown,"Writing Secure Code: Chapter 6, ""Determining Appropriate Access Control"" Page 171
750 24 Deadly Sins of Software Security: ""Sin 17: Failure to Protect Stored Data."" Page 253"
751 CWE-286,EN-Incorrect User Management (Type: Class),The software does not properly manage a user within its environment.,Users can be assigned to the wrong group (class) of permissions resulting in unintended access rights to sensitive objects.,,Unknown,
752 CWE-288,EN-Authentication Bypass Using an Alternate Path or Channel (Type: Base),"A product requires authentication, but the product has an alternate path or channel that does not require authentication.",Users can be assigned to the wrong group (class) of permissions resulting in unintended access rights to sensitive objects.,,Unknown,
753 CWE-289,EN-Authentication Bypass by Alternate Name (Type: Variant),"The software performs authentication based on the name of a resource being accessed, or the name of the actor performing the access, but it does not properly check all possible names for that resource or actor.",Users can be assigned to the wrong group (class) of permissions resulting in unintended access rights to sensitive objects.,,Unknown,
754 CWE-29,EN-Path Traversal: \..\filename (Type: Variant),"The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory.","This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
755 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.",,Unknown,
756 CWE-290,EN-Authentication Bypass by Spoofing (Type: Base),This attack-focused weakness is caused by improperly implemented authentication schemes that are subject to spoofing attacks.,"This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
757 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.",,Unknown,"The Art of Software Security Assessment: Chapter 3, ""Spoofing and Identification"", Page 72."
758 CWE-295,EN-Improper Certificate Validation (Type: Base),"The software does not validate, or incorrectly validates, a certificate.","When a certificate is invalid or malicious, it might allow an attacker to spoof a trusted entity by using a man-in-the-middle (MITM) attack. The software might connect to a malicious host while believing it is a trusted host, or the software might be deceived into accepting spoofed data that appears to originate from a trusted host.",,Unknown,"Why Eve and Mallory Love Android: An Analysis of Android SSL (In)Security: http://www2.dcsec.uni-hannover.de/files/android/p50-fahl.pdf
759 Computer Security: Art and Science"
760 CWE-30,EN-Path Traversal: \dir\..\filename (Type: Variant),"The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\dir\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory.","This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
761 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.",,Unknown,
762 CWE-300,EN-Channel Accessible by Non-Endpoint (Man-in-the-Middle) (Type: Class),"The product does not adequately verify the identity of actors at both ends of a communication channel, or does not adequately ensure the integrity of the channel, in a way that allows the channel to be accessed or influenced by an actor that is not an endpoint.","In order to establish secure communication between two parties, it is often important to adequately verify the identity of entities at each end of the communication channel. Inadequate or inconsistent verification may result in insufficient or incorrect identification of either communicating entity. This can have negative consequences such as misplaced trust in the entity at the other end of the channel. An attacker can leverage this by interposing between the communicating entities and masquerading as the original entity. In the absence of sufficient verification of identity, such an attacker can eavesdrop and potentially modify the communication between the original entities.",,Unknown,Computer Security: Art and Science
763 CWE-302,EN-Authentication Bypass by Assumed-Immutable Data (Type: Variant),"The authentication scheme or implementation uses key data elements that are assumed to be immutable, but can be controlled or modified by the attacker.","A mutual authentication protocol requires each party to respond to a random challenge by the other party by encrypting it with a pre-shared key. Often, however, such protocols employ the same pre-shared key for communication with a number of different entities. A malicious user or an attacker can easily compromise this protocol without possessing the correct key by employing a reflection attack on the protocol.",,Unknown,
764 CWE-303,EN-Incorrect Implementation of Authentication Algorithm (Type: Base),"The requirements for the software dictate the use of an established authentication algorithm, but the implementation of the algorithm is incorrect.",This incorrect implementation may allow authentication to be bypassed.,,Unknown,
765 CWE-304,EN-Missing Critical Step in Authentication (Type: Base),"The software implements an authentication technique, but it skips a step that weakens the technique.","Authentication techniques should follow the algorithms that define them exactly, otherwise authentication can be bypassed or more easily subjected to brute force attacks.",,Unknown,
766 CWE-305,EN-Authentication Bypass by Primary Weakness (Type: Base),"The authentication algorithm is sound, but the implemented mechanism can be bypassed as the result of a separate weakness that is primary to the authentication error.","Authentication techniques should follow the algorithms that define them exactly, otherwise authentication can be bypassed or more easily subjected to brute force attacks.",,Unknown,
767 CWE-307,EN-Improper Restriction of Excessive Authentication Attempts (Type: Base),"The software does not implement sufficient measures to prevent multiple failed authentication attempts within in a short time frame, making it more susceptible to brute force attacks.","Authentication techniques should follow the algorithms that define them exactly, otherwise authentication can be bypassed or more easily subjected to brute force attacks.",,Unknown,"Weak Password Brings 'Happiness' to Twitter Hacker: http://www.wired.com/threatlevel/2009/01/professed-twitt/
768 OWASP Enterprise Security API (ESAPI) Project: http://www.owasp.org/index.php/ESAPI"
769 CWE-31,EN-Path Traversal: dir\..\..\filename (Type: Variant),"The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize 'dir\..\..\filename' (multiple internal backslash dot dot) sequences that can resolve to a location that is outside of that directory.","This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
770 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.",,Unknown,"24 Deadly Sins of Software Security: ""Sin 20: Weak Random Numbers."" Page 299"
771 CWE-312,EN-Cleartext Storage of Sensitive Information (Type: Base),The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere.,"Because the information is stored in cleartext, attackers could potentially read it. Even if the information is encoded in a way that is not human-readable, certain techniques could determine which encoding is being used, then decode the information.",,Unknown,"Writing Secure Code: Chapter 9, ""Protecting Secret Data"" Page 299
772 The Art of Software Security Assessment: Chapter 2, ""Common Vulnerabilities of Encryption"", Page 43.
773 Mobile App Top 10 List: http://www.veracode.com/blog/2010/12/mobile-app-top-10-list/"
774 CWE-313,EN-Cleartext Storage in a File or on Disk (Type: Variant),"The application stores sensitive information in cleartext in a file, or on disk.","The sensitive information could be read by attackers with access to the file, or with physical or administrator access to the raw disk. Even if the information is encoded in a way that is not human-readable, certain techniques could determine which encoding is being used, then decode the information.",,Unknown,
775 CWE-314,EN-Cleartext Storage in the Registry (Type: Variant),The application stores sensitive information in cleartext in the registry.,"Attackers can read the information by accessing the registry key. Even if the information is encoded in a way that is not human-readable, certain techniques could determine which encoding is being used, then decode the information.",,Unknown,
776 CWE-315,EN-Cleartext Storage of Sensitive Information in a Cookie (Type: Variant),The application stores sensitive information in cleartext in a cookie.,"Attackers can use widely-available tools to view the cookie and read the sensitive information. Even if the information is encoded in a way that is not human-readable, certain techniques could determine which encoding is being used, then decode the information.",,Unknown,
777 CWE-316,EN-Cleartext Storage of Sensitive Information in Memory (Type: Variant),The application stores sensitive information in cleartext in memory.,"The sensitive memory might be saved to disk, stored in a core dump, or remain uncleared if the application crashes, or if the programmer does not properly clear the memory before freeing it.
778 It could be argued that such problems are usually only exploitable by those with administrator privileges. However, swapping could cause the memory to be written to disk and leave it accessible to physical attack afterwards. Core dump files might have insecure permissions or be stored in archive files that are accessible to untrusted people. Or, uncleared sensitive memory might be inadvertently exposed to attackers due to another weakness.",,Unknown,
779 CWE-317,EN-Cleartext Storage of Sensitive Information in GUI (Type: Variant),The application stores sensitive information in cleartext within the GUI.,"An attacker can often obtain data from a GUI, even if hidden, by using an API to directly access GUI objects such as windows and menus. Even if the information is encoded in a way that is not human-readable, certain techniques could determine which encoding is being used, then decode the information.",,Unknown,
780 CWE-318,EN-Cleartext Storage of Sensitive Information in Executable (Type: Variant),The application stores sensitive information in cleartext in an executable.,"Attackers can reverse engineer binary code to obtain secret data. This is especially easy when the cleartext is plain ASCII. Even if the information is encoded in a way that is not human-readable, certain techniques could determine which encoding is being used, then decode the information.",,Unknown,
781 CWE-32,EN-Path Traversal: ... (Triple Dot) (Type: Variant),"The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '...' (triple dot) sequences that can resolve to a location that is outside of that directory.","This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
782 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. Incomplete filtering, such as removal of ""./"" sequences, can ultimately produce valid "".."" sequences due to a collapse into unsafe value (CWE-182).",,Unknown,
783 CWE-325,EN-Missing Required Cryptographic Step (Type: Base),"The software does not implement a required step in a cryptographic algorithm, resulting in weaker encryption than advertised by that algorithm.","Cryptographic implementations should follow the algorithms that define them exactly, otherwise encryption can be weaker than expected.",,Unknown,
784 CWE-326,EN-Inadequate Encryption Strength (Type: Class),"The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required.",A weak encryption scheme can be subjected to brute force attacks that have a reasonable chance of succeeding using current attack methods and resources.,,Unknown,"Writing Secure Code: Chapter 8, ""Cryptographic Foibles"" Page 259
785 24 Deadly Sins of Software Security: ""Sin 21: Using the Wrong Cryptography."" Page 315"
786 CWE-328,EN-Reversible One-Way Hash (Type: Base),"The product uses a hashing algorithm that produces a hash value that can be used to determine the original input, or to find an input that can produce the same hash, more efficiently than brute force techniques.","This weakness is especially dangerous when the hash is used in security algorithms that require the one-way property to hold. For example, if an authentication system takes an incoming password and generates a hash, then compares the hash to another hash that it has stored in its authentication database, then the ability to create a collision could allow an attacker to provide an alternate password that produces the same target hash, bypassing authentication.",,Unknown,"MD5 considered harmful today: http://www.phreedom.org/research/rogue-ca/
787 The Art of Software Security Assessment: Chapter 2, ""Common Vulnerabilities of Integrity"", Page 47.
788 RFC2898 - PKCS #5: Password-Based Cryptography Specification Version 2.0: http://tools.ietf.org/html/rfc2898
789 How To Safely Store A Password: http://codahale.com/how-to-safely-store-a-password/
790 Tarsnap - The scrypt key derivation function and encryption utility: http://www.tarsnap.com/scrypt.html
791 How Companies Can Beef Up Password Security (interview with Thomas H. Ptacek): http://krebsonsecurity.com/2012/06/how-companies-can-beef-up-password-security/
792 Password security: past, present, future: http://www.openwall.com/presentations/PHDays2012-Password-Security/
793 Our password hashing has no clothes: http://www.troyhunt.com/2012/06/our-password-hashing-has-no-clothes.html
794 Should we really use bcrypt/scrypt?: http://www.analyticalengine.net/2012/06/should-we-really-use-bcryptscrypt/"
795 CWE-33,EN-Path Traversal: .... (Multiple Dot) (Type: Variant),"The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '....' (multiple dot) sequences that can resolve to a location that is outside of that directory.","This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
796 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. Incomplete filtering, such as removal of ""./"" sequences, can ultimately produce valid "".."" sequences due to a collapse into unsafe value (CWE-182).",,Unknown,
797 CWE-331,EN-Insufficient Entropy (Type: Base),"The software uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others.","When software generates predictable values in a context requiring unpredictability, it may be possible for an attacker to guess the next value that will be generated, and use this guess to impersonate another user or access sensitive information.",,Unknown,Building Secure Software: How to Avoid Security Problems the Right Way
798 CWE-334,EN-Small Space of Random Values (Type: Base),"The number of possible random values is smaller than needed by the product, making it more susceptible to brute force attacks.",The rate at which true random numbers can be generated is limited. It is important that one uses them only when they are needed for security.,,Unknown,"SECURITY REQUIREMENTS FOR CRYPTOGRAPHIC MODULES: http://csrc.nist.gov/publications/fips/fips140-2/fips1402.pdf
799 24 Deadly Sins of Software Security: ""Sin 20: Weak Random Numbers."" Page 299"
800 CWE-335,EN-PRNG Seed Error (Type: Class),A Pseudo-Random Number Generator (PRNG) uses seeds incorrectly.,The rate at which true random numbers can be generated is limited. It is important that one uses them only when they are needed for security.,,Unknown,"24 Deadly Sins of Software Security: ""Sin 20: Weak Random Numbers."" Page 299"
801 CWE-336,EN-Same Seed in PRNG (Type: Base),"A PRNG uses the same seed each time the product is initialized. If an attacker can guess (or knows) the seed, then he/she may be able to determine the ""random"" number produced from the PRNG.",The rate at which true random numbers can be generated is limited. It is important that one uses them only when they are needed for security.,,Unknown,SECURITY REQUIREMENTS FOR CRYPTOGRAPHIC MODULES: http://csrc.nist.gov/publications/fips/fips140-2/fips1402.pdf
802 CWE-337,EN-Predictable Seed in PRNG (Type: Base),"A PRNG is initialized from a predictable seed, e.g. using process ID or system time.",The rate at which true random numbers can be generated is limited. It is important that one uses them only when they are needed for security.,,Unknown,"SECURITY REQUIREMENTS FOR CRYPTOGRAPHIC MODULES: http://csrc.nist.gov/publications/fips/fips140-2/fips1402.pdf
803 24 Deadly Sins of Software Security: ""Sin 20: Weak Random Numbers."" Page 299"
804 CWE-339,EN-Small Seed Space in PRNG (Type: Base),A PRNG uses a relatively small space of seeds.,The rate at which true random numbers can be generated is limited. It is important that one uses them only when they are needed for security.,,Unknown,SECURITY REQUIREMENTS FOR CRYPTOGRAPHIC MODULES: http://csrc.nist.gov/publications/fips/fips140-2/fips1402.pdf
805 CWE-34,EN-Path Traversal: ....// (Type: Variant),"The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '....//' (doubled dot dot slash) sequences that can resolve to a location that is outside of that directory.","This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
806 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.",,Unknown,
807 CWE-340,EN-Predictability Problems (Type: Class),Weaknesses in this category are related to schemes that generate numbers or identifiers that are more predictable than required by the application.,"This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
808 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.",,Unknown,"24 Deadly Sins of Software Security: ""Sin 20: Weak Random Numbers."" Page 299"
809 CWE-341,EN-Predictable from Observable State (Type: Base),"A number or object is predictable based on observations that the attacker can make about the state of the system or network, such as time, process ID, etc.","This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
810 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.",,Unknown,"SECURITY REQUIREMENTS FOR CRYPTOGRAPHIC MODULES: http://csrc.nist.gov/publications/fips/fips140-2/fips1402.pdf
811 24 Deadly Sins of Software Security: ""Sin 20: Weak Random Numbers."" Page 299"
812 CWE-342,EN-Predictable Exact Value from Previous Values (Type: Base),An exact value or random number can be precisely predicted by observing previous values.,"This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
813 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.",,Unknown,"SECURITY REQUIREMENTS FOR CRYPTOGRAPHIC MODULES: http://csrc.nist.gov/publications/fips/fips140-2/fips1402.pdf
814 24 Deadly Sins of Software Security: ""Sin 20: Weak Random Numbers."" Page 299"
815 CWE-343,EN-Predictable Value Range from Previous Values (Type: Base),"The software's random number generator produces a series of values which, when observed, can be used to infer a relatively small range of possibilities for the next value that could be generated.","The output of a random number generator should not be predictable based on observations of previous values. In some cases, an attacker cannot predict the exact value that will be produced next, but can narrow down the possibilities significantly. This reduces the amount of effort to perform a brute force attack. For example, suppose the product generates random numbers between 1 and 100, but it always produces a larger value until it reaches 100. If the generator produces an 80, then the attacker knows that the next value will be somewhere between 81 and 100. Instead of 100 possibilities, the attacker only needs to consider 20.",,Unknown,"SECURITY REQUIREMENTS FOR CRYPTOGRAPHIC MODULES: http://csrc.nist.gov/publications/fips/fips140-2/fips1402.pdf
816 Strange Attractors and TCP/IP Sequence Number Analysis: http://www.bindview.com/Services/Razor/Papers/2001/tcpseq.cfm
817 24 Deadly Sins of Software Security: ""Sin 20: Weak Random Numbers."" Page 299"
818 CWE-344,EN-Use of Invariant Value in Dynamically Changing Context (Type: Base),"The product uses a constant value, name, or reference, but this value can (or should) vary across different environments.","The output of a random number generator should not be predictable based on observations of previous values. In some cases, an attacker cannot predict the exact value that will be produced next, but can narrow down the possibilities significantly. This reduces the amount of effort to perform a brute force attack. For example, suppose the product generates random numbers between 1 and 100, but it always produces a larger value until it reaches 100. If the generator produces an 80, then the attacker knows that the next value will be somewhere between 81 and 100. Instead of 100 possibilities, the attacker only needs to consider 20.",,Unknown,SECURITY REQUIREMENTS FOR CRYPTOGRAPHIC MODULES: http://csrc.nist.gov/publications/fips/fips140-2/fips1402.pdf
819 CWE-345,EN-Insufficient Verification of Data Authenticity (Type: Class),"The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.","The output of a random number generator should not be predictable based on observations of previous values. In some cases, an attacker cannot predict the exact value that will be produced next, but can narrow down the possibilities significantly. This reduces the amount of effort to perform a brute force attack. For example, suppose the product generates random numbers between 1 and 100, but it always produces a larger value until it reaches 100. If the generator produces an 80, then the attacker knows that the next value will be somewhere between 81 and 100. Instead of 100 possibilities, the attacker only needs to consider 20.",,Unknown,"24 Deadly Sins of Software Security: ""Sin 15: Not Updating Easily."" Page 231"
820 CWE-346,EN-Origin Validation Error (Type: Base),The software does not properly verify that the source of data or communication is valid.,"The output of a random number generator should not be predictable based on observations of previous values. In some cases, an attacker cannot predict the exact value that will be produced next, but can narrow down the possibilities significantly. This reduces the amount of effort to perform a brute force attack. For example, suppose the product generates random numbers between 1 and 100, but it always produces a larger value until it reaches 100. If the generator produces an 80, then the attacker knows that the next value will be somewhere between 81 and 100. Instead of 100 possibilities, the attacker only needs to consider 20.",,Unknown,
821 CWE-347,EN-Improper Verification of Cryptographic Signature (Type: Base),"The software does not verify, or incorrectly verifies, the cryptographic signature for data.","The output of a random number generator should not be predictable based on observations of previous values. In some cases, an attacker cannot predict the exact value that will be produced next, but can narrow down the possibilities significantly. This reduces the amount of effort to perform a brute force attack. For example, suppose the product generates random numbers between 1 and 100, but it always produces a larger value until it reaches 100. If the generator produces an 80, then the attacker knows that the next value will be somewhere between 81 and 100. Instead of 100 possibilities, the attacker only needs to consider 20.",,Unknown,
822 CWE-348,EN-Use of Less Trusted Source (Type: Base),"The software has two different sources of the same data or information, but it uses the source that has less support for verification, is less trusted, or is less resistant to attack.","The output of a random number generator should not be predictable based on observations of previous values. In some cases, an attacker cannot predict the exact value that will be produced next, but can narrow down the possibilities significantly. This reduces the amount of effort to perform a brute force attack. For example, suppose the product generates random numbers between 1 and 100, but it always produces a larger value until it reaches 100. If the generator produces an 80, then the attacker knows that the next value will be somewhere between 81 and 100. Instead of 100 possibilities, the attacker only needs to consider 20.",,Unknown,
823 CWE-349,EN-Acceptance of Extraneous Untrusted Data With Trusted Data (Type: Base),"The software, when processing trusted data, accepts any untrusted data that is also included with the trusted data, treating the untrusted data as if it were trusted.","The output of a random number generator should not be predictable based on observations of previous values. In some cases, an attacker cannot predict the exact value that will be produced next, but can narrow down the possibilities significantly. This reduces the amount of effort to perform a brute force attack. For example, suppose the product generates random numbers between 1 and 100, but it always produces a larger value until it reaches 100. If the generator produces an 80, then the attacker knows that the next value will be somewhere between 81 and 100. Instead of 100 possibilities, the attacker only needs to consider 20.",,Unknown,
824 CWE-35,EN-Path Traversal: .../...// (Type: Variant),"The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '.../...//' (doubled triple dot slash) sequences that can resolve to a location that is outside of that directory.","This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.
825 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.",,Unknown,
826 CWE-350,EN-Reliance on Reverse DNS Resolution for a Security-Critical Action (Type: Variant),"The software performs reverse DNS resolution on an IP address to obtain the hostname and make a security decision, but it does not properly ensure that the IP address is truly associated with the hostname.","When the software performs a reverse DNS resolution for an IP address, if an attacker controls the server for that IP address, then the attacker can cause the server to return an arbitrary hostname. As a result, the attacker may be able to bypass authentication, cause the wrong hostname to be recorded in log files to hide activities, or perform other attacks.
827 Attackers can spoof DNS names by either (1) compromising a DNS server and modifying its records (sometimes called DNS cache poisoning), or (2) having legitimate control over a DNS server associated with their IP address.
828 Since DNS names can be easily spoofed or misreported, and it may be difficult for the software to detect if a trusted DNS server has not been compromised, they do not constitute a valid authentication mechanism.",,Unknown,"24 Deadly Sins of Software Security: ""Sin 15: Not Updating Easily."" Page 231
829 24 Deadly Sins of Software Security: ""Sin 24: Trusting Network Name Resolution."" Page 361
830 The Art of Software Security Assessment: Chapter 16, ""DNS Spoofing"", Page 1002."
831 CWE-351,EN-Insufficient Type Distinction (Type: Base),The software does not properly distinguish between different types of elements in a way that leads to insecure behavior.,"When the software performs a reverse DNS resolution for an IP address, if an attacker controls the server for that IP address, then the attacker can cause the server to return an arbitrary hostname. As a result, the attacker may be able to bypass authentication, cause the wrong hostname to be recorded in log files to hide activities, or perform other attacks.
832 Attackers can spoof DNS names by either (1) compromising a DNS server and modifying its records (sometimes called DNS cache poisoning), or (2) having legitimate control over a DNS server associated with their IP address.
833 Since DNS names can be easily spoofed or misreported, and it may be difficult for the software to detect if a trusted DNS server has not been compromised, they do not constitute a valid authentication mechanism.",,Unknown,
834 CWE-356,EN-Product UI does not Warn User of Unsafe Actions (Type: Base),The software's user interface does not warn the user before undertaking an unsafe action on behalf of that user. This makes it easier for attackers to trick users into inflicting damage to their system.,"Software systems should warn users that a potentially dangerous action may occur if the user proceeds. For example, if the user downloads a file from an unknown source and attempts to execute the file on their machine, then the application's GUI can indicate that the file is unsafe.",,Unknown,
835 CWE-357,EN-Insufficient UI Warning of Dangerous Operations (Type: Base),"The user interface provides a warning to a user regarding dangerous or sensitive operations, but the warning is not noticeable enough to warrant attention.","Software systems should warn users that a potentially dangerous action may occur if the user proceeds. For example, if the user downloads a file from an unknown source and attempts to execute the file on their machine, then the application's GUI can indicate that the file is unsafe.",,Unknown,
836 CWE-358,EN-Improperly Implemented Security Check for Standard (Type: Base),"The software does not implement or incorrectly implements one or more security-relevant checks as specified by the design of a standardized algorithm, protocol, or technique.","Software systems should warn users that a potentially dangerous action may occur if the user proceeds. For example, if the user downloads a file from an unknown source and attempts to execute the file on their machine, then the application's GUI can indicate that the file is unsafe.",,Unknown,
837 CWE-359,EN-Privacy Violation (Type: Class),"Mishandling private information, such as customer passwords or social security numbers, can compromise user privacy and is often illegal.","Software systems should warn users that a potentially dangerous action may occur if the user proceeds. For example, if the user downloads a file from an unknown source and attempts to execute the file on their machine, then the application's GUI can indicate that the file is unsafe.",,Unknown,"AOL man pleads guilty to selling 92m email addies: http://www.theregister.co.uk/2005/02/07/aol_email_theft/
838 Safe Harbor Privacy Framework: http://www.export.gov/safeharbor/
839 Financial Privacy: The Gramm-Leach Bliley Act (GLBA): http://www.ftc.gov/privacy/glbact/index.html
840 Health Insurance Portability and Accountability Act (HIPAA): http://www.hhs.gov/ocr/hipaa/
841 California SB-1386: http://info.sen.ca.gov/pub/01-02/bill/sen/sb_1351-1400/sb_1386_bill_20020926_chaptered.html
842 SECURITY REQUIREMENTS FOR CRYPTOGRAPHIC MODULES: http://csrc.nist.gov/publications/fips/fips140-2/fips1402.pdf
843 Mobile App Top 10 List: http://www.veracode.com/blog/2010/12/mobile-app-top-10-list/"
844 CWE-36,EN-Absolute Path Traversal (Type: Base),"The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as ""/abs/path"" that can resolve to a location that is outside of that directory.",This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.,,Unknown,"The Art of Software Security Assessment: Chapter 9, ""Filenames and Paths"", Page 503."
845 CWE-363,EN-Race Condition Enabling Link Following (Type: Base),"The software checks the status of a file or directory before accessing it, which produces a race condition in which the file can be replaced with a link before the access is performed, causing the software to access the wrong file.","While developers might expect that there is a very narrow time window between the time of check and time of use, there is still a race condition. An attacker could cause the software to slow down (e.g. with memory consumption), causing the time window to become larger. Alternately, in some situations, the attacker could win the race by performing a large number of attacks.",,Unknown,"The Art of Software Security Assessment: Chapter 9, ""Race Conditions"", Page 526."
846 CWE-368,EN-Context Switching Race Condition (Type: Base),"A product performs a series of non-atomic actions to switch between contexts that cross privilege or other security boundaries, but a race condition allows an attacker to modify or misrepresent the product's behavior during the switch.","This is commonly seen in web browser vulnerabilities in which the attacker can perform certain actions while the browser is transitioning from a trusted to an untrusted domain, or vice versa, and the browser performs the actions on one domain using the trust level and resources of the other domain.",,Unknown,"24 Deadly Sins of Software Security: ""Sin 13: Race Conditions."" Page 205"
847 CWE-37,EN-Path Traversal: /absolute/pathname/here (Type: Variant),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.,"This weakness typically occurs when an unexpected value is provided to the product, or if an error occurs that is not properly detected. It frequently occurs in calculations involving physical dimensions such as size, length, width, and height.",,Unknown,
848 CWE-372,EN-Incomplete Internal State Distinction (Type: Base),"The software does not properly determine which state it is in, causing it to assume it is in state X when in fact it is in state Y, causing it to perform incorrect operations in a security-relevant manner.","If the revocation status of a certificate is not checked before each action that requires privileges, the system may be subject to a race condition. If a certificate is revoked after the initial check, all subsequent actions taken with the owner of the revoked certificate will lose all benefits guaranteed by the certificate. In fact, it is almost certain that the use of a revoked certificate indicates malicious activity.",,Unknown,
849 CWE-373,EN-DEPRECATED: State Synchronization Error (Type: Base),This entry was deprecated because it overlapped the same concepts as race condition (CWE-362) and Improper Synchronization (CWE-662).,"If the revocation status of a certificate is not checked before each action that requires privileges, the system may be subject to a race condition. If a certificate is revoked after the initial check, all subsequent actions taken with the owner of the revoked certificate will lose all benefits guaranteed by the certificate. In fact, it is almost certain that the use of a revoked certificate indicates malicious activity.",,Unknown,
850 CWE-377,EN-Insecure Temporary File (Type: Base),Creating and using insecure temporary files can leave application and system data vulnerable to attack.,"If the revocation status of a certificate is not checked before each action that requires privileges, the system may be subject to a race condition. If a certificate is revoked after the initial check, all subsequent actions taken with the owner of the revoked certificate will lose all benefits guaranteed by the certificate. In fact, it is almost certain that the use of a revoked certificate indicates malicious activity.",,Unknown,"Writing Secure Code: Chapter 23, ""Creating Temporary Files Securely"" Page 682
851 The Art of Software Security Assessment: Chapter 9, ""Temporary Files"", Page 538.
852 The Art of Software Security Assessment: Chapter 11, ""File Squatting"", Page 662."
853 CWE-38,EN-Path Traversal: \absolute\pathname\here (Type: Variant),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.,"On some operating systems, the fact that the temporary file exists may be apparent to any user with sufficient privileges to access that directory. Since the file is visible, the application that is using the temporary file could be known. If one has access to list the processes on the system, the attacker has gained information about what the user is doing at that time. By correlating this with the applications the user is running, an attacker could potentially discover what a user's actions are. From this, higher levels of security could be breached.",,Unknown,
854 CWE-382,EN-J2EE Bad Practices: Use of System.exit() (Type: Variant),"A J2EE application uses System.exit(), which also shuts down its container.","On some operating systems, the fact that the temporary file exists may be apparent to any user with sufficient privileges to access that directory. Since the file is visible, the application that is using the temporary file could be known. If one has access to list the processes on the system, the attacker has gained information about what the user is doing at that time. By correlating this with the applications the user is running, an attacker could potentially discover what a user's actions are. From this, higher levels of security could be breached.",,Unknown,
855 CWE-383,EN-J2EE Bad Practices: Direct Use of Threads (Type: Variant),Thread management in a Web application is forbidden in some circumstances and is always highly error prone.,"Thread management in a web application is forbidden by the J2EE standard in some circumstances and is always highly error prone. Managing threads is difficult and is likely to interfere in unpredictable ways with the behavior of the application container. Even without interfering with the container, thread management usually leads to bugs that are hard to detect and diagnose like deadlock, race conditions, and other synchronization errors.",,Unknown,
856 CWE-386,EN-Symbolic Name not Mapping to Correct Object (Type: Base),"A constant symbolic reference to an object is used, even though the reference can resolve to a different object over time.","In some instances, knowing when data is transmitted between parties can provide a malicious user with privileged information. Also, externally monitoring the timing of operations can potentially reveal sensitive data. For example, a cryptographic operation can expose its internal state if the time it takes to perform the operation varies, based on the state.
857 Covert channels are frequently classified as either storage or timing channels. Some examples of covert timing channels are the system's paging rate, the time a certain transaction requires to execute, and the time it takes to gain access to a shared bus.",,Unknown,
858 CWE-39,EN-Path Traversal: C:dirname (Type: Variant),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.,"In some instances, knowing when data is transmitted between parties can provide a malicious user with privileged information. Also, externally monitoring the timing of operations can potentially reveal sensitive data. For example, a cryptographic operation can expose its internal state if the time it takes to perform the operation varies, based on the state.
859 Covert channels are frequently classified as either storage or timing channels. Some examples of covert timing channels are the system's paging rate, the time a certain transaction requires to execute, and the time it takes to gain access to a shared bus.",,Unknown,
860 CWE-392,EN-Missing Report of Error Condition (Type: Base),The software encounters an error but does not provide a status code or return value to indicate that an error has occurred.,"In some instances, knowing when data is transmitted between parties can provide a malicious user with privileged information. Also, externally monitoring the timing of operations can potentially reveal sensitive data. For example, a cryptographic operation can expose its internal state if the time it takes to perform the operation varies, based on the state.
861 Covert channels are frequently classified as either storage or timing channels. Some examples of covert timing channels are the system's paging rate, the time a certain transaction requires to execute, and the time it takes to gain access to a shared bus.",,Unknown,
862 CWE-393,EN-Return of Wrong Status Code (Type: Base),"A function or operation returns an incorrect return value or status code that does not indicate an error, but causes the product to modify its behavior based on the incorrect result.","This can lead to unpredictable behavior. If the function is used to make security-critical decisions or provide security-critical information, then the wrong status code can cause the software to assume that an action is safe, even when it is not.",,Unknown,
863 CWE-394,EN-Unexpected Status Code or Return Value (Type: Base),"The software does not properly check when a function or operation returns a value that is legitimate for the function, but is not expected by the software.","This can lead to unpredictable behavior. If the function is used to make security-critical decisions or provide security-critical information, then the wrong status code can cause the software to assume that an action is safe, even when it is not.",,Unknown,
864 CWE-395,EN-Use of NullPointerException Catch to Detect NULL Pointer Dereference (Type: Base),Catching NullPointerException should not be used as an alternative to programmatic checks to prevent dereferencing a null pointer.,"This can lead to unpredictable behavior. If the function is used to make security-critical decisions or provide security-critical information, then the wrong status code can cause the software to assume that an action is safe, even when it is not.",,Unknown,
865 CWE-396,EN-Declaration of Catch for Generic Exception (Type: Base),Catching overly broad exceptions promotes complex error handling code that is more likely to contain security vulnerabilities.,"Multiple catch blocks can get ugly and repetitive, but ""condensing"" catch blocks by catching a high-level class like Exception can obscure exceptions that deserve special treatment or that should not be caught at this point in the program. Catching an overly broad exception essentially defeats the purpose of Java's typed exceptions, and can become particularly dangerous if the program grows and begins to throw new types of exceptions. The new exception types will not receive any attention.",,Unknown,"24 Deadly Sins of Software Security: ""Sin 9: Catching Exceptions."" Page 157"
866 CWE-397,EN-Declaration of Throws for Generic Exception (Type: Base),Throwing overly broad exceptions promotes complex error handling code that is more likely to contain security vulnerabilities.,"Declaring a method to throw Exception or Throwable makes it difficult for callers to perform proper error handling and error recovery. Java's exception mechanism, for example, is set up to make it easy for callers to anticipate what can go wrong and write code to handle each specific exceptional circumstance. Declaring that a method throws a generic form of exception defeats this system.",,Unknown,
867 CWE-398,EN-Indicator of Poor Code Quality (Type: Class),"The code has features that do not directly introduce a weakness or vulnerability, but indicate that the product has not been carefully developed or maintained.","Programs are more likely to be secure when good development practices are followed. If a program is complex, difficult to maintain, not portable, or shows evidence of neglect, then there is a higher likelihood that weaknesses are buried in the code.",,Unknown,
868 CWE-40,EN-Path Traversal: \\UNC\share\name\ (Windows UNC Share) (Type: Variant),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.,"Programs are more likely to be secure when good development practices are followed. If a program is complex, difficult to maintain, not portable, or shows evidence of neglect, then there is a higher likelihood that weaknesses are buried in the code.",,Unknown,"The Art of Software Security Assessment: Chapter 11, ""Filelike Objects"", Page 664."
869 CWE-402,EN-Transmission of Private Resources into a New Sphere (Resource Leak) (Type: Class),The software makes resources available to untrusted parties when those resources are only intended to be accessed by the software.,This is often triggered by improper handling of malformed data or unexpectedly interrupted sessions.,,Unknown,
870 CWE-403,EN-Exposure of File Descriptor to Unintended Control Sphere (File Descriptor Leak) (Type: Base),"A process does not close sensitive file descriptors before invoking a child process, which allows the child to perform unauthorized I/O operations using those descriptors.","When a new process is forked or executed, the child process inherits any open file descriptors. When the child process has fewer privileges than the parent process, this might introduce a vulnerability if the child process can access the file descriptor but does not have the privileges to access the associated file.",,Unknown,"File descriptors and setuid applications: https://blogs.oracle.com/paulr/entry/file_descriptors_and_setuid_applications
871 Introduction to Secure Coding Guide: https://developer.apple.com/library/mac/#documentation/security/conceptual/SecureCodingGuide/Articles/AccessControl.html"
872 CWE-405,EN-Asymmetric Resource Consumption (Amplification) (Type: Class),Software that does not appropriately monitor or control resource consumption can lead to adverse system performance.,"This situation is amplified if the software allows malicious users or attackers to consume more resources than their access level permits. Exploiting such a weakness can lead to asymmetric resource consumption, aiding in amplification attacks against the system or the network.",,Unknown,
873 CWE-406,EN-Insufficient Control of Network Message Volume (Network Amplification) (Type: Base),"The software does not sufficiently monitor or control transmitted network traffic volume, so that an actor can cause the software to transmit more traffic than should be allowed for that actor.","In the absence of a policy to restrict asymmetric resource consumption, the application or system cannot distinguish between legitimate transmissions and traffic intended to serve as an amplifying attack on target systems. Systems can often be configured to restrict the amount of traffic sent out on behalf of a client, based on the client's origin or access level. This is usually defined in a resource allocation policy. In the absence of a mechanism to keep track of transmissions, the system or application can be easily abused to transmit asymmetrically greater traffic than the request or client should be permitted to.",,Unknown,
874 CWE-408,EN-Incorrect Behavior Order: Early Amplification (Type: Base),The software allows an entity to perform a legitimate but expensive operation before authentication or authorization has taken place.,"In the absence of a policy to restrict asymmetric resource consumption, the application or system cannot distinguish between legitimate transmissions and traffic intended to serve as an amplifying attack on target systems. Systems can often be configured to restrict the amount of traffic sent out on behalf of a client, based on the client's origin or access level. This is usually defined in a resource allocation policy. In the absence of a mechanism to keep track of transmissions, the system or application can be easily abused to transmit asymmetrically greater traffic than the request or client should be permitted to.",,Unknown,
875 CWE-409,EN-Improper Handling of Highly Compressed Data (Data Amplification) (Type: Base),The software does not handle or incorrectly handles a compressed input with a very high compression ratio that produces a large output.,"An example of data amplification is a ""decompression bomb,"" a small ZIP file that can produce a large amount of data when it is decompressed.",,Unknown,
876 CWE-41,EN-Improper Resolution of Path Equivalence (Type: Base),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.,"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.",,Unknown,
877 CWE-410,EN-Insufficient Resource Pool (Type: Base),"The software's resource pool is not large enough to handle peak demand, which allows an attacker to prevent others from accessing the resource by using a (relatively) large number of requests for resources.","Frequently the consequence is a ""flood"" of connection or sessions.",,Unknown,"Writing Secure Code: Chapter 17, ""Protecting Against Denial of Service Attacks"" Page 517"
878 CWE-412,EN-Unrestricted Externally Accessible Lock (Type: Base),"The software properly checks for the existence of a lock, but the lock can be externally controlled or influenced by an actor that is outside of the intended sphere of control.","This prevents the software from acting on associated resources or performing other behaviors that are controlled by the presence of the lock. Relevant locks might include an exclusive lock or mutex, or modifying a shared resource that is treated as a lock. If the lock can be held for an indefinite period of time, then the denial of service could be permanent.",,Unknown,
879 CWE-413,EN-Improper Resource Locking (Type: Base),The software does not lock or does not correctly lock a resource when the software must have exclusive access to the resource.,"When a resource is not properly locked, an attacker could modify the resource while it is being operated on by the software. This might violate the software's assumption that the resource will not change, potentially leading to unexpected behaviors.",,Unknown,
880 CWE-414,EN-Missing Lock Check (Type: Base),A product does not check to see if a lock is present before performing sensitive operations on a resource.,"When a resource is not properly locked, an attacker could modify the resource while it is being operated on by the software. This might violate the software's assumption that the resource will not change, potentially leading to unexpected behaviors.",,Unknown,
881 CWE-419,EN-Unprotected Primary Channel (Type: Base),"The software uses a primary channel for administration or restricted functionality, but it does not properly protect the channel.","The use of previously-freed memory can have any number of adverse consequences, ranging from the corruption of valid data to the execution of arbitrary code, depending on the instantiation and timing of the flaw. The simplest way data corruption may occur involves the system's reuse of the freed memory. Use-after-free errors have two common and sometimes overlapping causes:
882 Error conditions and other exceptional circumstances.
883 Confusion over which part of the program is responsible for freeing the memory.
884 In this scenario, the memory in question is allocated to another pointer validly at some point after it has been freed. The original pointer to the freed memory is used again and points to somewhere within the new allocation. As the data is changed, it corrupts the validly used memory; this induces undefined behavior in the process.
885 If the newly allocated data chances to hold a class, in C++ for example, various function pointers may be scattered within the heap data. If one of these function pointers is overwritten with an address to valid shellcode, execution of arbitrary code can be achieved.",,Unknown,
886 CWE-42,EN-Path Equivalence: filename. (Trailing Dot) (Type: Variant),A software system that accepts path input in the form of 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.,"The use of previously-freed memory can have any number of adverse consequences, ranging from the corruption of valid data to the execution of arbitrary code, depending on the instantiation and timing of the flaw. The simplest way data corruption may occur involves the system's reuse of the freed memory. Use-after-free errors have two common and sometimes overlapping causes:
887 Error conditions and other exceptional circumstances.
888 Confusion over which part of the program is responsible for freeing the memory.
889 In this scenario, the memory in question is allocated to another pointer validly at some point after it has been freed. The original pointer to the freed memory is used again and points to somewhere within the new allocation. As the data is changed, it corrupts the validly used memory; this induces undefined behavior in the process.
890 If the newly allocated data chances to hold a class, in C++ for example, various function pointers may be scattered within the heap data. If one of these function pointers is overwritten with an address to valid shellcode, execution of arbitrary code can be achieved.",,Unknown,
891 CWE-420,EN-Unprotected Alternate Channel (Type: Base),"The software protects a primary channel, but it does not use the same level of protection for an alternate channel.","The use of previously-freed memory can have any number of adverse consequences, ranging from the corruption of valid data to the execution of arbitrary code, depending on the instantiation and timing of the flaw. The simplest way data corruption may occur involves the system's reuse of the freed memory. Use-after-free errors have two common and sometimes overlapping causes:
892 Error conditions and other exceptional circumstances.
893 Confusion over which part of the program is responsible for freeing the memory.
894 In this scenario, the memory in question is allocated to another pointer validly at some point after it has been freed. The original pointer to the freed memory is used again and points to somewhere within the new allocation. As the data is changed, it corrupts the validly used memory; this induces undefined behavior in the process.
895 If the newly allocated data chances to hold a class, in C++ for example, various function pointers may be scattered within the heap data. If one of these function pointers is overwritten with an address to valid shellcode, execution of arbitrary code can be achieved.",,Unknown,
896 CWE-421,EN-Race Condition During Access to Alternate Channel (Type: Base),"The product opens an alternate channel to communicate with an authorized user, but the channel is accessible to other actors.",This creates a race condition that allows an attacker to access the channel before the authorized user does.,,Unknown,"Discovering and Exploiting Named Pipe Security Flaws for Fun and Profit: http://www.blakewatts.com/namedpipepaper.html
897 24 Deadly Sins of Software Security: ""Sin 13: Race Conditions."" Page 205"
898 CWE-422,EN-Unprotected Windows Messaging Channel (Shatter) (Type: Variant),"The software does not properly verify the source of a message in the Windows Messaging System while running at elevated privileges, creating an alternate channel through which an attacker can directly send a message to the product.",This creates a race condition that allows an attacker to access the channel before the authorized user does.,,Unknown,"Exploiting design flaws in the Win32 API for privilege escalation. Or... Shatter Attacks - How to break Windows: http://web.archive.org/web/20060115174629/http://security.tombom.co.uk/shatter.html
899 The Art of Software Security Assessment: Chapter 2, ""Design Review."" Page 34.
900 The Art of Software Security Assessment: Chapter 12, ""Shatter Attacks"", Page 694."
901 CWE-423,EN-DEPRECATED (Duplicate): Proxied Trusted Channel (Type: Base),This entry has been deprecated because it was a duplicate of CWE-441. All content has been transferred to CWE-441.,This creates a race condition that allows an attacker to access the channel before the authorized user does.,,Unknown,
902 CWE-424,EN-Improper Protection of Alternate Path (Type: Class),The product does not sufficiently protect all possible paths that a user can take to access restricted functionality or resources.,This creates a race condition that allows an attacker to access the channel before the authorized user does.,,Unknown,
903 CWE-425,EN-Direct Request (Forced Browsing) (Type: Base),"The web application does not adequately enforce appropriate authorization on all restricted URLs, scripts, or files.",Web applications susceptible to direct request attacks often make the false assumption that such resources can only be reached through a given navigation path and so only apply authorization at certain points in the path.,,Unknown,
904 CWE-427,EN-Uncontrolled Search Path Element (Type: Base),"The product uses a fixed or controlled search path to find resources, but one or more locations in that path can be under the control of unintended actors.","Although this weakness can occur with any type of resource, it is frequently introduced when a product uses a directory search path to find executables or code libraries, but the path contains a directory that can be modified by an attacker, such as ""/tmp"" or the current working directory.
905 In Windows-based systems, when the LoadLibrary or LoadLibraryEx function is called with a DLL name that does not contain a fully qualified path, the function follows a search order that includes two path elements that might be uncontrolled:
906 the directory from which the program has been loaded
907 the current working directory.
908 In some cases, the attack can be conducted remotely, such as when SMB or WebDAV network shares are used.
909 In some Unix-based systems, a PATH might be created that contains an empty element, e.g. by splicing an empty variable into the PATH. This empty element can be interpreted as equivalent to the current working directory, which might be an untrusted search element.",,Unknown,"Double clicking on MS Office documents from Windows Explorer may execute arbitrary programs in some cases
910 ACROS Security: Remote Binary Planting in Apple iTunes for Windows (ASPR #2010-08-18-1)
911 Automatic Detection of Vulnerable Dynamic Component Loadings: http://www.cs.ucdavis.edu/research/tech-reports/2010/CSE-2010-2.pdf
912 Dynamic-Link Library Search Order: http://msdn.microsoft.com/en-us/library/ms682586%28v=VS.85%29.aspx
913 Dynamic-Link Library Security: http://msdn.microsoft.com/en-us/library/ff919712%28VS.85%29.aspx
914 An update on the DLL-preloading remote attack vector: http://blogs.technet.com/b/srd/archive/2010/08/23/an-update-on-the-dll-preloading-remote-attack-vector.aspx
915 Insecure Library Loading Could Allow Remote Code Execution: http://www.microsoft.com/technet/security/advisory/2269637.mspx
916 Application DLL Load Hijacking: http://blog.rapid7.com/?p=5325
917 DLL Hijacking: Facts and Fiction: http://threatpost.com/en_us/blogs/dll-hijacking-facts-and-fiction-082610"
918 CWE-428,EN-Unquoted Search Path or Element (Type: Base),"The product uses a search path that contains an unquoted element, in which the element contains whitespace or other separators. This can cause the product to access resources in a parent path.","If a malicious individual has access to the file system, it is possible to elevate privileges by inserting such a file as ""C:\Program.exe"" to be run by a privileged program making use of WinExec.",,Unknown,"The Art of Software Security Assessment: Chapter 11, ""Process Loading"", Page 654."
919 CWE-43,EN-Path Equivalence: filename.... (Multiple Trailing Dot) (Type: Variant),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.,"If a malicious individual has access to the file system, it is possible to elevate privileges by inserting such a file as ""C:\Program.exe"" to be run by a privileged program making use of WinExec.",,Unknown,
920 CWE-430,EN-Deployment of Wrong Handler (Type: Base),"The wrong ""handler"" is assigned to process an object.","An example of deploying the wrong handler would be calling a servlet to reveal source code of a .JSP file, or automatically ""determining"" type of the object even if it is contradictory to an explicitly specified type.",,Unknown,"The Art of Software Security Assessment: Chapter 3, ""File Handlers"", Page 74."
921 CWE-431,EN-Missing Handler (Type: Base),A handler is not available or implemented.,"When an exception is thrown and not caught, the process has given up an opportunity to decide if a given failure or event is worth a change in execution.",,Unknown,"The Art of Software Security Assessment: Chapter 3, ""File Handlers"", Page 74."
922 CWE-432,EN-Dangerous Signal Handler not Disabled During Sensitive Operations (Type: Base),"The application uses a signal handler that shares state with other signal handlers, but it does not properly mask or prevent those signal handlers from being invoked while the original signal handler is still running.","During the execution of a signal handler, it can be interrupted by another handler when a different signal is sent. If the two handlers share state - such as global variables - then an attacker can corrupt the state by sending another signal before the first handler has completed execution.",,Unknown,
923 CWE-433,EN-Unparsed Raw Web Content Delivery (Type: Variant),The software stores raw content or supporting code under the web document root with an extension that is not specifically handled by the server.,"If code is stored in a file with an extension such as "".inc"" or "".pl"", and the web server does not have a handler for that extension, then the server will likely send the contents of the file directly to the requester without the pre-processing that was expected. When that file contains sensitive information such as database credentials, this may allow the attacker to compromise the application or associated components.",,Unknown,"The Art of Software Security Assessment: Chapter 3, ""File Handlers"", Page 74."
924 CWE-435,EN-Interaction Error (Type: Class),"An interaction error occurs when two entities work correctly when running independently, but they interact in unexpected ways when they are run together.","This could apply to products, systems, components, etc.",,Unknown,
925 CWE-436,EN-Interpretation Conflict (Type: Base),"Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state.","This is generally found in proxies, firewalls, anti-virus software, and other intermediary devices that allow, deny, or modify traffic based on how the client or server is expected to behave.",,Unknown,"On Interpretation Conflict Vulnerabilities
926 Insertion, Evasion, and Denial of Service: Eluding Network Intrusion Detection: http://www.insecure.org/stf/secnet_ids/secnet_ids.pdf
927 0x00 vs ASP file upload scripts: http://www.security-assessment.com/Whitepapers/0x00_vs_ASP_File_Uploads.pdf
928 Poison NULL byte
929 Re: Corsaire Security Advisory - Multiple vendor MIME RFC2047 encoding: http://marc.theaimsgroup.com/?l=bugtraq&m=109525864717484&w=2"
930 CWE-437,EN-Incomplete Model of Endpoint Features (Type: Base),"A product acts as an intermediary or monitor between two or more endpoints, but it does not have a complete model of an endpoint's features, behaviors, or state, potentially causing the product to perform incorrect actions based on this incomplete model.","This is generally found in proxies, firewalls, anti-virus software, and other intermediary devices that allow, deny, or modify traffic based on how the client or server is expected to behave.",,Unknown,
931 CWE-439,EN-Behavioral Change in New Version or Environment (Type: Base),"A's behavior or functionality changes with a new version of A, or a new environment, which is not known (or manageable) by B.","This is generally found in proxies, firewalls, anti-virus software, and other intermediary devices that allow, deny, or modify traffic based on how the client or server is expected to behave.",,Unknown,
932 CWE-44,EN-Path Equivalence: file.name (Internal Dot) (Type: Variant),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.,"This is generally found in proxies, firewalls, anti-virus software, and other intermediary devices that allow, deny, or modify traffic based on how the client or server is expected to behave.",,Unknown,
933 CWE-440,EN-Expected Behavior Violation (Type: Base),"A feature, API, or function being used by a product behaves differently than the product expects.","This is generally found in proxies, firewalls, anti-virus software, and other intermediary devices that allow, deny, or modify traffic based on how the client or server is expected to behave.",,Unknown,
934 CWE-441,EN-Unintended Proxy or Intermediary (Confused Deputy) (Type: Class),"The software receives a request, message, or directive from an upstream component, but the software does not sufficiently preserve the original source of the request before forwarding the request to an external actor that is outside of the software's control sphere. This causes the software to appear to be the source of the request, leading it to act as a proxy or other intermediary between the upstream component and the external actor.","If an attacker cannot directly contact a target, but the software has access to the target, then the attacker can send a request to the software and have it be forwarded from the target. The request would appear to be coming from the software's system, not the attacker's system. As a result, the attacker can bypass access controls (such as firewalls) or hide the source of malicious requests, since the requests would not be coming directly from the attacker.
935 Since proxy functionality and message-forwarding often serve a legitimate purpose, this issue only becomes a vulnerability when:
936 The software runs with different privileges or on a different system, or otherwise has different levels of access than the upstream component;
937 The attacker is prevented from making the request directly to the target; and
938 The attacker can create a request that the proxy does not explicitly intend to be forwarded on the behalf of the requester. Such a request might point to an unexpected hostname, port number, or service. Or, the request might be sent to an allowed service, but the request could contain disallowed directives, commands, or resources.",,Unknown,The Confused Deputy (or why capabilities might have been invented): http://www.cap-lore.com/CapTheory/ConfusedDeputy.html
939 CWE-443,EN-DEPRECATED (Duplicate): HTTP response splitting (Type: Base),This weakness can be found at CWE-113.,"If an attacker cannot directly contact a target, but the software has access to the target, then the attacker can send a request to the software and have it be forwarded from the target. The request would appear to be coming from the software's system, not the attacker's system. As a result, the attacker can bypass access controls (such as firewalls) or hide the source of malicious requests, since the requests would not be coming directly from the attacker.
940 Since proxy functionality and message-forwarding often serve a legitimate purpose, this issue only becomes a vulnerability when:
941 The software runs with different privileges or on a different system, or otherwise has different levels of access than the upstream component;
942 The attacker is prevented from making the request directly to the target; and
943 The attacker can create a request that the proxy does not explicitly intend to be forwarded on the behalf of the requester. Such a request might point to an unexpected hostname, port number, or service. Or, the request might be sent to an allowed service, but the request could contain disallowed directives, commands, or resources.",,Unknown,
944 CWE-444,EN-Inconsistent Interpretation of HTTP Requests (HTTP Request Smuggling) (Type: Base),"When malformed or abnormal HTTP requests are interpreted by one or more entities in the data flow between the user and the web server, such as a proxy or firewall, they can be interpreted inconsistently, allowing the attacker to ""smuggle"" a request to one device without the other device being aware of it.","If an attacker cannot directly contact a target, but the software has access to the target, then the attacker can send a request to the software and have it be forwarded from the target. The request would appear to be coming from the software's system, not the attacker's system. As a result, the attacker can bypass access controls (such as firewalls) or hide the source of malicious requests, since the requests would not be coming directly from the attacker.
945 Since proxy functionality and message-forwarding often serve a legitimate purpose, this issue only becomes a vulnerability when:
946 The software runs with different privileges or on a different system, or otherwise has different levels of access than the upstream component;
947 The attacker is prevented from making the request directly to the target; and
948 The attacker can create a request that the proxy does not explicitly intend to be forwarded on the behalf of the requester. Such a request might point to an unexpected hostname, port number, or service. Or, the request might be sent to an allowed service, but the request could contain disallowed directives, commands, or resources.",,Unknown,HTTP Request Smuggling: http://www.cgisecurity.com/lib/HTTP-Request-Smuggling.pdf
949 CWE-446,EN-UI Discrepancy for Security Feature (Type: Base),"The user interface does not correctly enable or configure a security feature, but the interface provides feedback that causes the user to believe that the feature is in a secure state.","When the user interface does not properly reflect what the user asks of it, then it can lead the user into a false sense of security. For example, the user might check a box to enable a security option to enable encrypted communications, but the software does not actually enable the encryption. Alternately, the user might provide a ""restrict ALL'"" access control rule, but the software only implements ""restrict SOME"".",,Unknown,
950 CWE-447,EN-Unimplemented or Unsupported Feature in UI (Type: Base),"A UI function for a security feature appears to be supported and gives feedback to the user that suggests that it is supported, but the underlying functionality is not implemented.","When the user interface does not properly reflect what the user asks of it, then it can lead the user into a false sense of security. For example, the user might check a box to enable a security option to enable encrypted communications, but the software does not actually enable the encryption. Alternately, the user might provide a ""restrict ALL'"" access control rule, but the software only implements ""restrict SOME"".",,Unknown,
951 CWE-448,EN-Obsolete Feature in UI (Type: Base),A UI function is obsolete and the product does not warn the user.,"When the user interface does not properly reflect what the user asks of it, then it can lead the user into a false sense of security. For example, the user might check a box to enable a security option to enable encrypted communications, but the software does not actually enable the encryption. Alternately, the user might provide a ""restrict ALL'"" access control rule, but the software only implements ""restrict SOME"".",,Unknown,
952 CWE-449,EN-The UI Performs the Wrong Action (Type: Base),The UI performs the wrong action with respect to the user's request.,"When the user interface does not properly reflect what the user asks of it, then it can lead the user into a false sense of security. For example, the user might check a box to enable a security option to enable encrypted communications, but the software does not actually enable the encryption. Alternately, the user might provide a ""restrict ALL'"" access control rule, but the software only implements ""restrict SOME"".",,Unknown,
953 CWE-45,EN-Path Equivalence: file...name (Multiple Internal Dot) (Type: Variant),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.,"When the user interface does not properly reflect what the user asks of it, then it can lead the user into a false sense of security. For example, the user might check a box to enable a security option to enable encrypted communications, but the software does not actually enable the encryption. Alternately, the user might provide a ""restrict ALL'"" access control rule, but the software only implements ""restrict SOME"".",,Unknown,
954 CWE-450,EN-Multiple Interpretations of UI Input (Type: Base),The UI has multiple interpretations of user input but does not prompt the user when it selects the less secure interpretation.,"When the user interface does not properly reflect what the user asks of it, then it can lead the user into a false sense of security. For example, the user might check a box to enable a security option to enable encrypted communications, but the software does not actually enable the encryption. Alternately, the user might provide a ""restrict ALL'"" access control rule, but the software only implements ""restrict SOME"".",,Unknown,
955 CWE-451,EN-UI Misrepresentation of Critical Information (Type: Base),"The UI does not properly represent critical information to the user, allowing the information - or its source - to be obscured or spoofed. This is often a component in phishing attacks.","When the user interface does not properly reflect what the user asks of it, then it can lead the user into a false sense of security. For example, the user might check a box to enable a security option to enable encrypted communications, but the software does not actually enable the encryption. Alternately, the user might provide a ""restrict ALL'"" access control rule, but the software only implements ""restrict SOME"".",,Unknown,
956 CWE-453,EN-Insecure Default Variable Initialization (Type: Base),"The software, by default, initializes an internal variable with an insecure or less secure value than is possible.","When the user interface does not properly reflect what the user asks of it, then it can lead the user into a false sense of security. For example, the user might check a box to enable a security option to enable encrypted communications, but the software does not actually enable the encryption. Alternately, the user might provide a ""restrict ALL'"" access control rule, but the software only implements ""restrict SOME"".",,Unknown,
957 CWE-454,EN-External Initialization of Trusted Variables or Data Stores (Type: Base),The software initializes critical internal variables or data stores using inputs that can be modified by untrusted actors.,"A software system should be reluctant to trust variables that have been initialized outside of its trust boundary, especially if they are initialized by users. They may have been initialized incorrectly. If an attacker can initialize the variable, then he/she can influence what the vulnerable system will do.",,Unknown,
958 CWE-455,EN-Non-exit on Failed Initialization (Type: Base),"The software does not exit or otherwise modify its operation when security-relevant errors occur during initialization, such as when a configuration file has a format error, which can cause the software to execute in a less secure fashion than intended by the administrator.","A software system should be reluctant to trust variables that have been initialized outside of its trust boundary, especially if they are initialized by users. They may have been initialized incorrectly. If an attacker can initialize the variable, then he/she can influence what the vulnerable system will do.",,Unknown,
959 CWE-456,EN-Missing Initialization of a Variable (Type: Base),"The software does not initialize critical variables, which causes the execution environment to use unexpected values.","A software system should be reluctant to trust variables that have been initialized outside of its trust boundary, especially if they are initialized by users. They may have been initialized incorrectly. If an attacker can initialize the variable, then he/she can influence what the vulnerable system will do.",,Unknown,"The Art of Software Security Assessment: Chapter 7, ""Variable Initialization"", Page 312."
960 CWE-458,EN-DEPRECATED: Incorrect Initialization (Type: Base),"This weakness has been deprecated because its name and description did not match. The description duplicated CWE-454, while the name suggested a more abstract initialization problem. Please refer to CWE-665 for the more abstract problem.","In some languages such as C and C++, stack variables are not initialized by default. They generally contain junk data with the contents of stack memory before the function was invoked. An attacker can sometimes control or read these contents. In other languages or conditions, a variable that is not explicitly initialized can be given a default value that has security implications, depending on the logic of the program. The presence of an uninitialized variable can sometimes indicate a typographic error in the code.",,Unknown,
961 CWE-459,EN-Incomplete Cleanup (Type: Base),"The software does not properly ""clean up"" and remove temporary or supporting resources after they have been used.","In some languages such as C and C++, stack variables are not initialized by default. They generally contain junk data with the contents of stack memory before the function was invoked. An attacker can sometimes control or read these contents. In other languages or conditions, a variable that is not explicitly initialized can be given a default value that has security implications, depending on the logic of the program. The presence of an uninitialized variable can sometimes indicate a typographic error in the code.",,Unknown,
962 CWE-46,EN-Path Equivalence: filename (Trailing Space) (Type: Variant),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.,"In some languages such as C and C++, stack variables are not initialized by default. They generally contain junk data with the contents of stack memory before the function was invoked. An attacker can sometimes control or read these contents. In other languages or conditions, a variable that is not explicitly initialized can be given a default value that has security implications, depending on the logic of the program. The presence of an uninitialized variable can sometimes indicate a typographic error in the code.",,Unknown,
963 CWE-463,EN-Deletion of Data Structure Sentinel (Type: Base),The accidental deletion of a data-structure sentinel can cause serious programming logic problems.,"Often times data-structure sentinels are used to mark structure of the data structure. A common example of this is the null character at the end of strings. Another common example is linked lists which may contain a sentinel to mark the end of the list. It is dangerous to allow this type of control data to be easily accessible. Therefore, it is important to protect from the deletion or modification outside of some wrapper interface which provides safety.",,Unknown,"The Art of Software Security Assessment: Chapter 8, ""NUL-Termination Problems"", Page 452."
964 CWE-466,EN-Return of Pointer Value Outside of Expected Range (Type: Base),A function can return a pointer to memory that is outside of the buffer that the pointer is expected to reference.,"Data-structure sentinels are often used to mark the structure of data. A common example of this is the null character at the end of strings or a special sentinel to mark the end of a linked list. It is dangerous to allow this type of control data to be easily accessible. Therefore, it is important to protect from the addition or modification of sentinels.",,Unknown,"24 Deadly Sins of Software Security: ""Sin 5: Buffer Overruns."" Page 89"
965 CWE-47,EN-Path Equivalence: filename (Leading Space) (Type: Variant),A software system that accepts path input in the form of leading 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.,"Data-structure sentinels are often used to mark the structure of data. A common example of this is the null character at the end of strings or a special sentinel to mark the end of a linked list. It is dangerous to allow this type of control data to be easily accessible. Therefore, it is important to protect from the addition or modification of sentinels.",,Unknown,
966 CWE-470,EN-Use of Externally-Controlled Input to Select Classes or Code (Unsafe Reflection) (Type: Base),"The application uses external input with reflection to select which classes or code to use, but it does not sufficiently prevent the input from selecting improper classes or code.","If the application uses external inputs to determine which class to instantiate or which method to invoke, then an attacker could supply values to select unexpected classes or methods. If this occurs, then the attacker could create control flow paths that were not intended by the developer. These paths could bypass authentication or access control checks, or otherwise cause the application to behave in an unexpected manner. This situation becomes a doomsday scenario if the attacker can upload files into a location that appears on the application's classpath (CWE-427) or add new entries to the application's classpath (CWE-426). Under either of these conditions, the attacker can use reflection to introduce new, malicious behavior into the application.",,Unknown,
967 CWE-471,EN-Modification of Assumed-Immutable Data (MAID) (Type: Base),The software does not properly protect an assumed-immutable element from being modified by an attacker.,"If the application uses external inputs to determine which class to instantiate or which method to invoke, then an attacker could supply values to select unexpected classes or methods. If this occurs, then the attacker could create control flow paths that were not intended by the developer. These paths could bypass authentication or access control checks, or otherwise cause the application to behave in an unexpected manner. This situation becomes a doomsday scenario if the attacker can upload files into a location that appears on the application's classpath (CWE-427) or add new entries to the application's classpath (CWE-426). Under either of these conditions, the attacker can use reflection to introduce new, malicious behavior into the application.",,Unknown,
968 CWE-472,EN-External Control of Assumed-Immutable Web Parameter (Type: Base),"The web application does not sufficiently verify inputs that are assumed to be immutable but are actually externally controllable, such as hidden form fields.","If a web product does not properly protect assumed-immutable values from modification in hidden form fields, parameters, cookies, or URLs, this can lead to modification of critical data. Web applications often mistakenly make the assumption that data passed to the client in hidden fields or cookies is not susceptible to tampering. Improper validation of data that are user-controllable can lead to the application processing incorrect, and often malicious, input.
969 For example, custom cookies commonly store session data or persistent data across sessions. This kind of session data is normally involved in security related decisions on the server side, such as user authentication and access control. Thus, the cookies might contain sensitive data such as user credentials and privileges. This is a dangerous practice, as it can often lead to improper reliance on the value of the client-provided cookie by the server side application.",,Unknown,"24 Deadly Sins of Software Security: ""Sin 4: Use of Magic URLs, Predictable Cookies, and Hidden Form Fields."" Page 75
970 The Art of Software Security Assessment: Chapter 17, ""Embedding State in HTML and URLs"", Page 1032."
971 CWE-473,EN-PHP External Variable Modification (Type: Variant),"A PHP application does not properly protect against the modification of variables from external sources, such as query parameters or cookies. This can expose the application to numerous weaknesses that would not exist otherwise.","If a web product does not properly protect assumed-immutable values from modification in hidden form fields, parameters, cookies, or URLs, this can lead to modification of critical data. Web applications often mistakenly make the assumption that data passed to the client in hidden fields or cookies is not susceptible to tampering. Improper validation of data that are user-controllable can lead to the application processing incorrect, and often malicious, input.
972 For example, custom cookies commonly store session data or persistent data across sessions. This kind of session data is normally involved in security related decisions on the server side, such as user authentication and access control. Thus, the cookies might contain sensitive data such as user credentials and privileges. This is a dangerous practice, as it can often lead to improper reliance on the value of the client-provided cookie by the server side application.",,Unknown,
973 CWE-474,EN-Use of Function with Inconsistent Implementations (Type: Base),"The code uses a function that has inconsistent implementations across operating systems and versions, which might cause security-relevant portability problems.","If a web product does not properly protect assumed-immutable values from modification in hidden form fields, parameters, cookies, or URLs, this can lead to modification of critical data. Web applications often mistakenly make the assumption that data passed to the client in hidden fields or cookies is not susceptible to tampering. Improper validation of data that are user-controllable can lead to the application processing incorrect, and often malicious, input.
974 For example, custom cookies commonly store session data or persistent data across sessions. This kind of session data is normally involved in security related decisions on the server side, such as user authentication and access control. Thus, the cookies might contain sensitive data such as user credentials and privileges. This is a dangerous practice, as it can often lead to improper reliance on the value of the client-provided cookie by the server side application.",,Unknown,
975 CWE-475,EN-Undefined Behavior for Input to API (Type: Base),The behavior of this function is undefined unless its control parameter is set to a specific value.,"If a web product does not properly protect assumed-immutable values from modification in hidden form fields, parameters, cookies, or URLs, this can lead to modification of critical data. Web applications often mistakenly make the assumption that data passed to the client in hidden fields or cookies is not susceptible to tampering. Improper validation of data that are user-controllable can lead to the application processing incorrect, and often malicious, input.
976 For example, custom cookies commonly store session data or persistent data across sessions. This kind of session data is normally involved in security related decisions on the server side, such as user authentication and access control. Thus, the cookies might contain sensitive data such as user credentials and privileges. This is a dangerous practice, as it can often lead to improper reliance on the value of the client-provided cookie by the server side application.",,Unknown,
977 CWE-477,EN-Use of Obsolete Functions (Type: Base),"The code uses deprecated or obsolete functions, which suggests that the code has not been actively reviewed or maintained.","NULL pointer dereference issues can occur through a number of flaws, including race conditions, and simple programming omissions.",,Unknown,
978 CWE-478,EN-Missing Default Case in Switch Statement (Type: Variant),"The code does not have a default case in a switch statement, which might lead to complex logical errors and resultant weaknesses.","NULL pointer dereference issues can occur through a number of flaws, including race conditions, and simple programming omissions.",,Unknown,"The Art of Software Security Assessment: Chapter 7, ""Switch Statements"", Page 337."
979 CWE-48,EN-Path Equivalence: file name (Internal Whitespace) (Type: Variant),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.,"Non-reentrant functions are functions that cannot safely be called, interrupted, and then recalled before the first call has finished without resulting in memory corruption. This can lead to an unexpected system state an unpredictable results with a variety of potential consequences depending on context, including denial of service and code execution.
980 Many functions are not reentrant, but some of them can result in the corruption of memory if they are used in a signal handler. The function call syslog() is an example of this. In order to perform its functionality, it allocates a small amount of memory as ""scratch space."" If syslog() is suspended by a signal call and the signal handler calls syslog(), the memory used by both of these functions enters an undefined, and possibly, exploitable state. Implementations of malloc() and free() manage metadata in global structures in order to track which memory is allocated versus which memory is available, but they are non-reentrant. Simultaneous calls to these functions can cause corruption of the metadata.",,Unknown,
981 CWE-485,EN-Insufficient Encapsulation (Type: Class),The product does not sufficiently encapsulate critical data or functionality.,"Encapsulation is about drawing strong boundaries. In a web browser that might mean ensuring that your mobile code cannot be abused by other mobile code. On the server it might mean differentiation between validated data and unvalidated data, between one user's data and another's, or between data users are allowed to see and data that they are not.",,Unknown,
982 CWE-488,EN-Exposure of Data Element to Wrong Session (Type: Variant),"The product does not sufficiently enforce boundaries between the states of different sessions, causing data to be provided to, or used by, the wrong session.","Data can ""bleed"" from one session to another through member variables of singleton objects, such as Servlets, and objects from a shared pool.
983 In the case of Servlets, developers sometimes do not understand that, unless a Servlet implements the SingleThreadModel interface, the Servlet is a singleton; there is only one instance of the Servlet, and that single instance is used and re-used to handle multiple requests that are processed simultaneously by different threads. A common result is that developers use Servlet member fields in such a way that one user may inadvertently see another user's data. In other words, storing user data in Servlet member fields introduces a data access race condition.",,Unknown,
984 CWE-489,EN-Leftover Debug Code (Type: Base),The application can be deployed with active debugging code that can create unintended entry points.,"Data can ""bleed"" from one session to another through member variables of singleton objects, such as Servlets, and objects from a shared pool.
985 In the case of Servlets, developers sometimes do not understand that, unless a Servlet implements the SingleThreadModel interface, the Servlet is a singleton; there is only one instance of the Servlet, and that single instance is used and re-used to handle multiple requests that are processed simultaneously by different threads. A common result is that developers use Servlet member fields in such a way that one user may inadvertently see another user's data. In other words, storing user data in Servlet member fields introduces a data access race condition.",,Unknown,
986 CWE-49,EN-Path Equivalence: filename/ (Trailing Slash) (Type: Variant),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.,"Data can ""bleed"" from one session to another through member variables of singleton objects, such as Servlets, and objects from a shared pool.
987 In the case of Servlets, developers sometimes do not understand that, unless a Servlet implements the SingleThreadModel interface, the Servlet is a singleton; there is only one instance of the Servlet, and that single instance is used and re-used to handle multiple requests that are processed simultaneously by different threads. A common result is that developers use Servlet member fields in such a way that one user may inadvertently see another user's data. In other words, storing user data in Servlet member fields introduces a data access race condition.",,Unknown,
988 CWE-491,EN-Public cloneable() Method Without Final (Object Hijack) (Type: Variant),"A class has a cloneable() method that is not declared final, which allows an object to be created without calling the constructor. This can cause the object to be in an unexpected state.","Data can ""bleed"" from one session to another through member variables of singleton objects, such as Servlets, and objects from a shared pool.
989 In the case of Servlets, developers sometimes do not understand that, unless a Servlet implements the SingleThreadModel interface, the Servlet is a singleton; there is only one instance of the Servlet, and that single instance is used and re-used to handle multiple requests that are processed simultaneously by different threads. A common result is that developers use Servlet member fields in such a way that one user may inadvertently see another user's data. In other words, storing user data in Servlet member fields introduces a data access race condition.",,Unknown,"OWASP , Attack Category : Mobile code: object hijack: http://www.owasp.org/index.php/Mobile_code:_object_hijack"
990 CWE-495,EN-Private Array-Typed Field Returned From A Public Method (Type: Variant),"The product has a method that is declared public, but returns a reference to a private array, which could then be modified in unexpected ways.","An attacker can execute malicious code by compromising the host server, performing DNS spoofing, or modifying the code in transit.",,Unknown,
991 CWE-496,EN-Public Data Assigned to Private Array-Typed Field (Type: Variant),Assigning public data to a private array is equivalent to giving public access to the array.,"An attacker can execute malicious code by compromising the host server, performing DNS spoofing, or modifying the code in transit.",,Unknown,
992 CWE-497,EN-Exposure of System Data to an Unauthorized Control Sphere (Type: Variant),Exposing system data or debugging information helps an adversary learn about the system and form an attack plan.,"An information exposure occurs when system data or debugging information leaves the program through an output stream or logging function that makes it accessible to unauthorized parties. An attacker can also cause errors to occur by submitting unusual requests to the web application. The response to these errors can reveal detailed system information, deny service, cause security mechanisms to fail, and crash the server. An attacker can use error messages that reveal technologies, operating systems, and product versions to tune the attack against known vulnerabilities in these technologies. An application may use diagnostic methods that provide significant implementation details such as stack traces as part of its error handling mechanism.",,Unknown,
993 CWE-5,EN-J2EE Misconfiguration: Data Transmission Without Encryption (Type: Variant),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.,"Serializable classes are effectively open classes since data cannot be hidden in them. Classes that do not explicitly deny serialization can be serialized by any other class, which can then in turn use the data stored inside it.",,Unknown,
994 CWE-50,EN-Path Equivalence: //multiple/leading/slash (Type: Variant),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.,"Serializable classes are effectively open classes since data cannot be hidden in them. Classes that do not explicitly deny serialization can be serialized by any other class, which can then in turn use the data stored inside it.",,Unknown,
995 CWE-501,EN-Trust Boundary Violation (Type: Base),The product mixes trusted and untrusted data in the same data structure or structured message.,"By combining trusted and untrusted data in the same data structure, it becomes easier for programmers to mistakenly trust unvalidated data.",,Unknown,
996 CWE-506,EN-Embedded Malicious Code (Type: Class),The application contains code that appears to be malicious in nature.,"Malicious flaws have acquired colorful names, including Trojan horse, trapdoor, timebomb, and logic-bomb. A developer might insert malicious code with the intent to subvert the security of an application or its host system at some time in the future. It generally refers to a program that performs a useful service but exploits rights of the program's user in a way the user does not intend.",,Unknown,
997 CWE-507,EN-Trojan Horse (Type: Base),"The software appears to contain benign or useful functionality, but it also contains code that is hidden from normal operation that violates the intended security policy of the user or the system administrator.","Malicious flaws have acquired colorful names, including Trojan horse, trapdoor, timebomb, and logic-bomb. A developer might insert malicious code with the intent to subvert the security of an application or its host system at some time in the future. It generally refers to a program that performs a useful service but exploits rights of the program's user in a way the user does not intend.",,Unknown,"Writing Secure Code: Chapter 7, ""Viruses, Trojans, and Worms In a Nutshell"" Page 208"
998 CWE-508,EN-Non-Replicating Malicious Code (Type: Base),Non-replicating malicious code only resides on the target system or software that is attacked; it does not attempt to spread to other systems.,"Malicious flaws have acquired colorful names, including Trojan horse, trapdoor, timebomb, and logic-bomb. A developer might insert malicious code with the intent to subvert the security of an application or its host system at some time in the future. It generally refers to a program that performs a useful service but exploits rights of the program's user in a way the user does not intend.",,Unknown,
999 CWE-509,EN-Replicating Malicious Code (Virus or Worm) (Type: Base),"Replicating malicious code, including viruses and worms, will attempt to attack other systems once it has successfully compromised the target system or software.","Malicious flaws have acquired colorful names, including Trojan horse, trapdoor, timebomb, and logic-bomb. A developer might insert malicious code with the intent to subvert the security of an application or its host system at some time in the future. It generally refers to a program that performs a useful service but exploits rights of the program's user in a way the user does not intend.",,Unknown,
1000 CWE-51,EN-Path Equivalence: /multiple//internal/slash (Type: Variant),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.,"Malicious flaws have acquired colorful names, including Trojan horse, trapdoor, timebomb, and logic-bomb. A developer might insert malicious code with the intent to subvert the security of an application or its host system at some time in the future. It generally refers to a program that performs a useful service but exploits rights of the program's user in a way the user does not intend.",,Unknown,
1001 CWE-510,EN-Trapdoor (Type: Base),"A trapdoor is a hidden piece of code that responds to a special input, allowing its user access to resources without passing through the normal security enforcement mechanism.","Malicious flaws have acquired colorful names, including Trojan horse, trapdoor, timebomb, and logic-bomb. A developer might insert malicious code with the intent to subvert the security of an application or its host system at some time in the future. It generally refers to a program that performs a useful service but exploits rights of the program's user in a way the user does not intend.",,Unknown,
1002 CWE-511,EN-Logic/Time Bomb (Type: Base),"The software contains code that is designed to disrupt the legitimate operation of the software (or its environment) when a certain time passes, or when a certain logical condition is met.","When the time bomb or logic bomb is detonated, it may perform a denial of service such as crashing the system, deleting critical data, or degrading system response time. This bomb might be placed within either a replicating or non-replicating Trojan horse.",,Unknown,Mobile App Top 10 List: http://www.veracode.com/blog/2010/12/mobile-app-top-10-list/
1003 CWE-512,EN-Spyware (Type: Base),"The software collects personally identifiable information about a human user or the user's activities, but the software accesses this information using other resources besides itself, and it does not require that user's explicit approval or direct input into the software.","""Spyware"" is a commonly used term with many definitions and interpretations. In general, it is meant to software that collects information or installs functionality that human users might not allow if they were fully aware of the actions being taken by the software. For example, a user might expect that tax software would collect a social security number and include it when filing a tax return, but that same user would not expect gaming software to obtain the social security number from that tax software's data.",,Unknown,
1004 CWE-514,EN-Covert Channel (Type: Class),A covert channel is a path that can be used to transfer information in a way not intended by the system's designers.,Typically the system has not given authorization for the transmission and has no knowledge of its occurrence.,,Unknown,
1005 CWE-516,EN-DEPRECATED (Duplicate): Covert Timing Channel (Type: Base),This weakness can be found at CWE-385.,"Covert storage channels occur when out-of-band data is stored in messages for the purpose of memory reuse. Covert channels are frequently classified as either storage or timing channels. Examples would include using a file intended to hold only audit information to convey user passwords--using the name of a file or perhaps status bits associated with it that can be read by all users to signal the contents of the file. Steganography, concealing information in such a manner that no one but the intended recipient knows of the existence of the message, is a good example of a covert storage channel.",,Unknown,
1006 CWE-52,EN-Path Equivalence: /multiple/trailing/slash// (Type: Variant),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.,"Covert storage channels occur when out-of-band data is stored in messages for the purpose of memory reuse. Covert channels are frequently classified as either storage or timing channels. Examples would include using a file intended to hold only audit information to convey user passwords--using the name of a file or perhaps status bits associated with it that can be read by all users to signal the contents of the file. Steganography, concealing information in such a manner that no one but the intended recipient knows of the existence of the message, is a good example of a covert storage channel.",,Unknown,
1007 CWE-520,EN-.NET Misconfiguration: Use of Impersonation (Type: Variant),Allowing a .NET application to run at potentially escalated levels of access to the underlying operating and file systems can be dangerous and result in various forms of attacks.,"Covert storage channels occur when out-of-band data is stored in messages for the purpose of memory reuse. Covert channels are frequently classified as either storage or timing channels. Examples would include using a file intended to hold only audit information to convey user passwords--using the name of a file or perhaps status bits associated with it that can be read by all users to signal the contents of the file. Steganography, concealing information in such a manner that no one but the intended recipient knows of the existence of the message, is a good example of a covert storage channel.",,Unknown,
1008 CWE-521,EN-Weak Password Requirements (Type: Base),"The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts.","An authentication mechanism is only as strong as its credentials. For this reason, it is important to require users to have strong passwords. Lack of password complexity significantly reduces the search space when trying to guess user's passwords, making brute-force attacks easier.",,Unknown,"24 Deadly Sins of Software Security: ""Sin 19: Use of Weak Password-Based Systems."" Page 279"
1009 CWE-522,EN-Insufficiently Protected Credentials (Type: Base),This weakness occurs when the application transmits or stores authentication credentials and uses an insecure method that is susceptible to unauthorized interception and/or retrieval.,"An authentication mechanism is only as strong as its credentials. For this reason, it is important to require users to have strong passwords. Lack of password complexity significantly reduces the search space when trying to guess user's passwords, making brute-force attacks easier.",,Unknown,"24 Deadly Sins of Software Security: ""Sin 19: Use of Weak Password-Based Systems."" Page 279"
1010 CWE-523,EN-Unprotected Transport of Credentials (Type: Variant),Login pages not using adequate measures to protect the user name and password while they are in transit from the client to the server.,"An authentication mechanism is only as strong as its credentials. For this reason, it is important to require users to have strong passwords. Lack of password complexity significantly reduces the search space when trying to guess user's passwords, making brute-force attacks easier.",,Unknown,
1011 CWE-524,EN-Information Exposure Through Caching (Type: Variant),"The application uses a cache to maintain a pool of objects, threads, connections, pages, or passwords to minimize the time it takes to access them or the resources to which they connect. If implemented improperly, these caches can allow access to unauthorized information or cause a denial of service vulnerability.","An authentication mechanism is only as strong as its credentials. For this reason, it is important to require users to have strong passwords. Lack of password complexity significantly reduces the search space when trying to guess user's passwords, making brute-force attacks easier.",,Unknown,
1012 CWE-525,EN-Information Exposure Through Browser Caching (Type: Variant),"For each web page, the application should have an appropriate caching policy specifying the extent to which the page and its form fields should be cached.","An authentication mechanism is only as strong as its credentials. For this reason, it is important to require users to have strong passwords. Lack of password complexity significantly reduces the search space when trying to guess user's passwords, making brute-force attacks easier.",,Unknown,
1013 CWE-526,EN-Information Exposure Through Environmental Variables (Type: Variant),Environmental variables may contain sensitive information about a remote server.,"An authentication mechanism is only as strong as its credentials. For this reason, it is important to require users to have strong passwords. Lack of password complexity significantly reduces the search space when trying to guess user's passwords, making brute-force attacks easier.",,Unknown,
1014 CWE-527,EN-Exposure of CVS Repository to an Unauthorized Control Sphere (Type: Variant),The product stores a CVS repository in a directory or other container that is accessible to actors outside of the intended control sphere.,"Information contained within a CVS subdirectory on a web server or other server could be recovered by an attacker and used for malicious purposes. This information may include usernames, filenames, path root, and IP addresses.",,Unknown,
1015 CWE-528,EN-Exposure of Core Dump File to an Unauthorized Control Sphere (Type: Variant),The product generates a core dump file in a directory that is accessible to actors outside of the intended control sphere.,"Information contained within a CVS subdirectory on a web server or other server could be recovered by an attacker and used for malicious purposes. This information may include usernames, filenames, path root, and IP addresses.",,Unknown,
1016 CWE-529,EN-Exposure of Access Control List Files to an Unauthorized Control Sphere (Type: Variant),The product stores access control list files in a directory or other container that is accessible to actors outside of the intended control sphere.,Exposure of these access control list files may give the attacker information about the configuration of the site or system. This information may then be used to bypass the intended security policy or identify trusted systems from which an attack can be launched.,,Unknown,
1017 CWE-53,EN-Path Equivalence: \multiple\\internal\backslash (Type: Variant),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.,Exposure of these access control list files may give the attacker information about the configuration of the site or system. This information may then be used to bypass the intended security policy or identify trusted systems from which an attack can be launched.,,Unknown,
1018 CWE-530,EN-Exposure of Backup File to an Unauthorized Control Sphere (Type: Variant),A backup file is stored in a directory that is accessible to actors outside of the intended control sphere.,"Often, old files are renamed with an extension such as .~bk to distinguish them from production files. The source code for old files that have been renamed in this manner and left in the webroot can often be retrieved. This renaming may have been performed automatically by the web server, or manually by the administrator.",,Unknown,
1019 CWE-531,EN-Information Exposure Through Test Code (Type: Variant),"Accessible test applications can pose a variety of security risks. Since developers or administrators rarely consider that someone besides themselves would even know about the existence of these applications, it is common for them to contain sensitive information or functions.","Often, old files are renamed with an extension such as .~bk to distinguish them from production files. The source code for old files that have been renamed in this manner and left in the webroot can often be retrieved. This renaming may have been performed automatically by the web server, or manually by the administrator.",,Unknown,
1020 CWE-533,EN-Information Exposure Through Server Log Files (Type: Variant),"A server.log file was found. This can give information on whatever application left the file. Usually this can give full path names and system information, and sometimes usernames and passwords.","While logging all information may be helpful during development stages, it is important that logging levels be set appropriately before a product ships so that sensitive user data and system information are not accidentally exposed to potential attackers.",,Unknown,
1021 CWE-534,EN-Information Exposure Through Debug Log Files (Type: Variant),The application does not sufficiently restrict access to a log file that is used for debugging.,"While logging all information may be helpful during development stages, it is important that logging levels be set appropriately before a product ships so that sensitive user data and system information are not accidentally exposed to potential attackers.",,Unknown,
1022 CWE-535,EN-Information Exposure Through Shell Error Message (Type: Variant),"A command shell error message indicates that there exists an unhandled exception in the web application code. In many cases, an attacker can leverage the conditions that cause these errors in order to gain unauthorized access to the system.","While logging all information may be helpful during development stages, it is important that logging levels be set appropriately before a product ships so that sensitive user data and system information are not accidentally exposed to potential attackers.",,Unknown,
1023 CWE-536,EN-Information Exposure Through Servlet Runtime Error Message (Type: Variant),A servlet error message indicates that there exists an unhandled exception in your web application code and may provide useful information to an attacker.,"While logging all information may be helpful during development stages, it is important that logging levels be set appropriately before a product ships so that sensitive user data and system information are not accidentally exposed to potential attackers.",,Unknown,
1024 CWE-537,EN-Information Exposure Through Java Runtime Error Message (Type: Variant),"In many cases, an attacker can leverage the conditions that cause unhandled exception errors in order to gain unauthorized access to the system.","While logging all information may be helpful during development stages, it is important that logging levels be set appropriately before a product ships so that sensitive user data and system information are not accidentally exposed to potential attackers.",,Unknown,
1025 CWE-538,EN-File and Directory Information Exposure (Type: Base),The product stores sensitive information in files or directories that are accessible to actors outside of the intended control sphere.,"While logging all information may be helpful during development stages, it is important that logging levels be set appropriately before a product ships so that sensitive user data and system information are not accidentally exposed to potential attackers.",,Unknown,"24 Deadly Sins of Software Security: ""Sin 12: Information Leakage."" Page 191"
1026 CWE-539,EN-Information Exposure Through Persistent Cookies (Type: Variant),Persistent cookies are cookies that are stored on the browser's hard drive. This can cause security and privacy issues depending on the information stored in the cookie and how it is accessed.,"Cookies are small bits of data that are sent by the web application but stored locally in the browser. This lets the application use the cookie to pass information between pages and store variable information. The web application controls what information is stored in a cookie and how it is used. Typical types of information stored in cookies are session Identifiers, personalization and customization information, and in rare cases even usernames to enable automated logins. There are two different types of cookies: session cookies and persistent cookies. Session cookies just live in the browser's memory, and are not stored anywhere, but persistent cookies are stored on the browser's hard drive.",,Unknown,
1027 CWE-54,EN-Path Equivalence: filedir\ (Trailing Backslash) (Type: Variant),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.,"Cookies are small bits of data that are sent by the web application but stored locally in the browser. This lets the application use the cookie to pass information between pages and store variable information. The web application controls what information is stored in a cookie and how it is used. Typical types of information stored in cookies are session Identifiers, personalization and customization information, and in rare cases even usernames to enable automated logins. There are two different types of cookies: session cookies and persistent cookies. Session cookies just live in the browser's memory, and are not stored anywhere, but persistent cookies are stored on the browser's hard drive.",,Unknown,
1028 CWE-540,EN-Information Exposure Through Source Code (Type: Variant),Source code on a web server often contains sensitive information and should generally not be accessible to users.,"There are situations where it is critical to remove source code from an area or server. For example, obtaining Perl source code on a system allows an attacker to understand the logic of the script and extract extremely useful information such as code bugs or logins and passwords.",,Unknown,
1029 CWE-541,EN-Information Exposure Through Include Source Code (Type: Variant),"If an include file source is accessible, the file can contain usernames and passwords, as well as sensitive information pertaining to the application and system.","There are situations where it is critical to remove source code from an area or server. For example, obtaining Perl source code on a system allows an attacker to understand the logic of the script and extract extremely useful information such as code bugs or logins and passwords.",,Unknown,
1030 CWE-542,EN-Information Exposure Through Cleanup Log Files (Type: Variant),The application does not properly protect or delete a log file related to cleanup.,"There are situations where it is critical to remove source code from an area or server. For example, obtaining Perl source code on a system allows an attacker to understand the logic of the script and extract extremely useful information such as code bugs or logins and passwords.",,Unknown,
1031 CWE-543,EN-Use of Singleton Pattern Without Synchronization in a Multithreaded Context (Type: Variant),The software uses the singleton pattern when creating a resource within a multithreaded environment.,The use of a singleton pattern may not be thread-safe.,,Unknown,Thread-Specifc Storage for C/C++: http://www.cs.wustl.edu/~schmidt/PDF/TSS-pattern.pdf
1032 CWE-544,EN-Missing Standardized Error Handling Mechanism (Type: Base),"The software does not use a standardized method for handling errors throughout the code, which might introduce inconsistent error handling and resultant weaknesses.","If the application handles error messages individually, on a one-by-one basis, this is likely to result in inconsistent error handling. The causes of errors may be lost. Also, detailed information about the causes of an error may be unintentionally returned to the user.",,Unknown,
1033 CWE-545,EN-Use of Dynamic Class Loading (Type: Variant),Dynamically loaded code has the potential to be malicious.,"If the application handles error messages individually, on a one-by-one basis, this is likely to result in inconsistent error handling. The causes of errors may be lost. Also, detailed information about the causes of an error may be unintentionally returned to the user.",,Unknown,
1034 CWE-546,EN-Suspicious Comment (Type: Variant),"The code contains comments that suggest the presence of bugs, incomplete functionality, or weaknesses.","Many suspicious comments, such as BUG, HACK, FIXME, LATER, LATER2, TODO, in the code indicate missing security functionality and checking. Others indicate code problems that programmers should fix, such as hard-coded variables, error handling, not using stored procedures, and performance issues.",,Unknown,
1035 CWE-547,"EN-Use of Hard-coded, Security-relevant Constants (Type: Variant)","The program uses hard-coded constants instead of symbolic names for security-critical values, which increases the likelihood of mistakes during code maintenance or security policy change.","If the developer does not find all occurrences of the hard-coded constants, an incorrect policy decision may be made if one of the constants is not changed. Making changes to these values will require code changes that may be difficult or impossible once the system is released to the field. In addition, these hard-coded values may become available to attackers if the code is ever disclosed.",,Unknown,
1036 CWE-548,EN-Information Exposure Through Directory Listing (Type: Variant),"A directory listing is inappropriately exposed, yielding potentially sensitive information to attackers.",A directory listing provides an attacker with the complete index of all the resources located inside of the directory. The specific risks and consequences vary depending on which files are listed and accessible.,,Unknown,
1037 CWE-549,EN-Missing Password Field Masking (Type: Variant),"The software does not mask passwords during entry, increasing the potential for attackers to observe and capture passwords.",A directory listing provides an attacker with the complete index of all the resources located inside of the directory. The specific risks and consequences vary depending on which files are listed and accessible.,,Unknown,"24 Deadly Sins of Software Security: ""Sin 19: Use of Weak Password-Based Systems."" Page 279"
1038 CWE-55,EN-Path Equivalence: /./ (Single Dot Directory) (Type: Variant),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.,A directory listing provides an attacker with the complete index of all the resources located inside of the directory. The specific risks and consequences vary depending on which files are listed and accessible.,,Unknown,
1039 CWE-550,EN-Information Exposure Through Server Error Message (Type: Variant),"Certain conditions, such as network failure, will cause a server error message to be displayed.","While error messages in and of themselves are not dangerous, per se, it is what an attacker can glean from them that might cause eventual problems.",,Unknown,
1040 CWE-551,EN-Incorrect Behavior Order: Authorization Before Parsing and Canonicalization (Type: Base),"If a web server does not fully parse requested URLs before it examines them for authorization, it may be possible for an attacker to bypass authorization protection.","For instance, the character strings /./ and / both mean current directory. If /SomeDirectory is a protected directory and an attacker requests /./SomeDirectory, the attacker may be able to gain access to the resource if /./ is not converted to / before the authorization check is performed.",,Unknown,
1041 CWE-552,EN-Files or Directories Accessible to External Parties (Type: Base),Files or directories are accessible in the environment that should not be.,"For instance, the character strings /./ and / both mean current directory. If /SomeDirectory is a protected directory and an attacker requests /./SomeDirectory, the attacker may be able to gain access to the resource if /./ is not converted to / before the authorization check is performed.",,Unknown,
1042 CWE-553,EN-Command Shell in Externally Accessible Directory (Type: Variant),A possible shell file exists in /cgi-bin/ or other accessible directories. This is extremely dangerous and can be used by an attacker to execute commands on the web server.,"For instance, the character strings /./ and / both mean current directory. If /SomeDirectory is a protected directory and an attacker requests /./SomeDirectory, the attacker may be able to gain access to the resource if /./ is not converted to / before the authorization check is performed.",,Unknown,
1043 CWE-554,EN-ASP.NET Misconfiguration: Not Using Input Validation Framework (Type: Variant),The ASP.NET application does not use an input validation framework.,"For instance, the character strings /./ and / both mean current directory. If /SomeDirectory is a protected directory and an attacker requests /./SomeDirectory, the attacker may be able to gain access to the resource if /./ is not converted to / before the authorization check is performed.",,Unknown,
1044 CWE-555,EN-J2EE Misconfiguration: Plaintext Password in Configuration File (Type: Variant),The J2EE application stores a plaintext password in a configuration file.,"Storing a plaintext password in a configuration file allows anyone who can read the file to access the password-protected resource, making it an easy target for attackers.",,Unknown,
1045 CWE-556,EN-ASP.NET Misconfiguration: Use of Identity Impersonation (Type: Variant),Configuring an ASP.NET application to run with impersonated credentials may give the application unnecessary privileges.,The use of impersonated credentials allows an ASP.NET application to run with either the privileges of the client on whose behalf it is executing or with arbitrary privileges granted in its configuration.,,Unknown,
1046 CWE-558,EN-Use of getlogin() in Multithreaded Application (Type: Variant),"The application uses the getlogin() function in a multithreaded context, potentially causing it to return incorrect values.","The getlogin() function returns a pointer to a string that contains the name of the user associated with the calling process. The function is not reentrant, meaning that if it is called from another process, the contents are not locked out and the value of the string can be changed by another process. This makes it very risky to use because the username can be changed by other processes, so the results of the function cannot be trusted.",,Unknown,
1047 CWE-56,EN-Path Equivalence: filedir* (Wildcard) (Type: Variant),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.,"The getlogin() function returns a pointer to a string that contains the name of the user associated with the calling process. The function is not reentrant, meaning that if it is called from another process, the contents are not locked out and the value of the string can be changed by another process. This makes it very risky to use because the username can be changed by other processes, so the results of the function cannot be trusted.",,Unknown,
1048 CWE-560,EN-Use of umask() with chmod-style Argument (Type: Variant),The product calls umask() with an incorrect argument that is specified as if it is an argument to chmod().,"The getlogin() function returns a pointer to a string that contains the name of the user associated with the calling process. The function is not reentrant, meaning that if it is called from another process, the contents are not locked out and the value of the string can be changed by another process. This makes it very risky to use because the username can be changed by other processes, so the results of the function cannot be trusted.",,Unknown,
1049 CWE-561,EN-Dead Code (Type: Variant),"The software contains dead code, which can never be executed.",Dead code is source code that can never be executed in a running program. The surrounding code makes it impossible for a section of code to ever be executed.,,Unknown,
1050 CWE-562,EN-Return of Stack Variable Address (Type: Base),"A function returns the address of a stack variable, which will cause unintended program behavior, typically in the form of a crash.",Dead code is source code that can never be executed in a running program. The surrounding code makes it impossible for a section of code to ever be executed.,,Unknown,
1051 CWE-563,EN-Unused Variable (Type: Variant),"The variable's value is assigned but never used, making it a dead store.","It is likely that the variable is simply vestigial, but it is also possible that the unused variable points out a bug.",,Unknown,
1052 CWE-564,EN-SQL Injection: Hibernate (Type: Variant),Using Hibernate to execute a dynamic SQL statement built with user-controlled input can allow an attacker to modify the statement's meaning or to execute arbitrary SQL commands.,"It is likely that the variable is simply vestigial, but it is also possible that the unused variable points out a bug.",,Unknown,
1053 CWE-565,EN-Reliance on Cookies without Validation and Integrity Checking (Type: Base),"The application relies on the existence or values of cookies when performing security-critical operations, but it does not properly ensure that the setting is valid for the associated user.","Attackers can easily modify cookies, within the browser or by implementing the client-side code outside of the browser. Reliance on cookies without detailed validation and integrity checking can allow attackers to bypass authentication, conduct injection attacks such as SQL injection and cross-site scripting, or otherwise modify inputs in unexpected ways.",,Unknown,
1054 CWE-566,EN-Authorization Bypass Through User-Controlled SQL Primary Key (Type: Variant),"The software uses a database table that includes records that should not be accessible to an actor, but it executes a SQL statement with a primary key that can be controlled by that actor.","When a user can set a primary key to any value, then the user can modify the key to point to unauthorized records.
1055 Database access control errors occur when:
1056 Data enters a program from an untrusted source.
1057 The data is used to specify the value of a primary key in a SQL query.
1058 The untrusted source does not have the permissions to be able to access all rows in the associated table.",,Unknown,
1059 CWE-567,EN-Unsynchronized Access to Shared Data in a Multithreaded Context (Type: Base),"The product does not properly synchronize shared data, such as static variables across threads, which can lead to undefined behavior and unpredictable data changes.","Within servlets, shared static variables are not protected from concurrent access, but servlets are multithreaded. This is a typical programming mistake in J2EE applications, since the multithreading is handled by the framework. When a shared variable can be influenced by an attacker, one thread could wind up modifying the variable to contain data that is not valid for a different thread that is also using the data within the variable.
1060 Note that this weakness is not unique to servlets.",,Unknown,
1061 CWE-568,EN-finalize() Method Without super.finalize() (Type: Variant),The software contains a finalize() method that does not call super.finalize().,The Java Language Specification states that it is a good practice for a finalize() method to call super.finalize().,,Unknown,
1062 CWE-57,EN-Path Equivalence: fakedir/../realdir/filename (Type: Variant),"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.",The Java Language Specification states that it is a good practice for a finalize() method to call super.finalize().,,Unknown,
1063 CWE-570,EN-Expression is Always False (Type: Variant),The software contains an expression that will always evaluate to false.,The Java Language Specification states that it is a good practice for a finalize() method to call super.finalize().,,Unknown,
1064 CWE-571,EN-Expression is Always True (Type: Variant),The software contains an expression that will always evaluate to true.,The Java Language Specification states that it is a good practice for a finalize() method to call super.finalize().,,Unknown,
1065 CWE-572,EN-Call to Thread run() instead of start() (Type: Variant),"The program calls a thread's run() method instead of calling start(), which causes the code to run in the thread of the caller instead of the callee.","In most cases a direct call to a Thread object's run() method is a bug. The programmer intended to begin a new thread of control, but accidentally called run() instead of start(), so the run() method will execute in the caller's thread of control.",,Unknown,
1066 CWE-573,EN-Improper Following of Specification by Caller (Type: Class),"The software does not follow or incorrectly follows the specifications as required by the implementation language, environment, framework, protocol, or platform.","When leveraging external functionality, such as an API, it is important that the caller does so in accordance with the requirements of the external functionality or else unintended behaviors may result, possibly leaving the system vulnerable to any number of exploits.",,Unknown,
1067 CWE-574,EN-EJB Bad Practices: Use of Synchronization Primitives (Type: Variant),The program violates the Enterprise JavaBeans (EJB) specification by using thread synchronization primitives.,"The Enterprise JavaBeans specification requires that every bean provider follow a set of programming guidelines designed to ensure that the bean will be portable and behave consistently in any EJB container. In this case, the program violates the following EJB guideline: ""An enterprise bean must not use thread synchronization primitives to synchronize execution of multiple instances."" The specification justifies this requirement in the following way: ""This rule is required to ensure consistent runtime semantics because while some EJB containers may use a single JVM to execute all enterprise bean's instances, others may distribute the instances across multiple JVMs.""",,Unknown,
1068 CWE-575,EN-EJB Bad Practices: Use of AWT Swing (Type: Variant),The program violates the Enterprise JavaBeans (EJB) specification by using AWT/Swing.,"The Enterprise JavaBeans specification requires that every bean provider follow a set of programming guidelines designed to ensure that the bean will be portable and behave consistently in any EJB container. In this case, the program violates the following EJB guideline: ""An enterprise bean must not use the AWT functionality to attempt to output information to a display, or to input information from a keyboard."" The specification justifies this requirement in the following way: ""Most servers do not allow direct interaction between an application program and a keyboard/display attached to the server system.""",,Unknown,
1069 CWE-576,EN-EJB Bad Practices: Use of Java I/O (Type: Variant),The program violates the Enterprise JavaBeans (EJB) specification by using the java.io package.,"The Enterprise JavaBeans specification requires that every bean provider follow a set of programming guidelines designed to ensure that the bean will be portable and behave consistently in any EJB container. In this case, the program violates the following EJB guideline: ""An enterprise bean must not use the java.io package to attempt to access files and directories in the file system."" The specification justifies this requirement in the following way: ""The file system APIs are not well-suited for business components to access data. Business components should use a resource manager API, such as JDBC, to store data.""",,Unknown,
1070 CWE-577,EN-EJB Bad Practices: Use of Sockets (Type: Variant),The program violates the Enterprise JavaBeans (EJB) specification by using sockets.,"The Enterprise JavaBeans specification requires that every bean provider follow a set of programming guidelines designed to ensure that the bean will be portable and behave consistently in any EJB container. In this case, the program violates the following EJB guideline: ""An enterprise bean must not attempt to listen on a socket, accept connections on a socket, or use a socket for multicast."" The specification justifies this requirement in the following way: ""The EJB architecture allows an enterprise bean instance to be a network socket client, but it does not allow it to be a network server. Allowing the instance to become a network server would conflict with the basic function of the enterprise bean-- to serve the EJB clients.""",,Unknown,
1071 CWE-578,EN-EJB Bad Practices: Use of Class Loader (Type: Variant),The program violates the Enterprise JavaBeans (EJB) specification by using the class loader.,"The Enterprise JavaBeans specification requires that every bean provider follow a set of programming guidelines designed to ensure that the bean will be portable and behave consistently in any EJB container. In this case, the program violates the following EJB guideline: ""The enterprise bean must not attempt to create a class loader; obtain the current class loader; set the context class loader; set security manager; create a new security manager; stop the JVM; or change the input, output, and error streams."" The specification justifies this requirement in the following way: ""These functions are reserved for the EJB container. Allowing the enterprise bean to use these functions could compromise security and decrease the container's ability to properly manage the runtime environment.""",,Unknown,
1072 CWE-579,EN-J2EE Bad Practices: Non-serializable Object Stored in Session (Type: Variant),"The application stores a non-serializable object as an HttpSession attribute, which can hurt reliability.","The Enterprise JavaBeans specification requires that every bean provider follow a set of programming guidelines designed to ensure that the bean will be portable and behave consistently in any EJB container. In this case, the program violates the following EJB guideline: ""The enterprise bean must not attempt to create a class loader; obtain the current class loader; set the context class loader; set security manager; create a new security manager; stop the JVM; or change the input, output, and error streams."" The specification justifies this requirement in the following way: ""These functions are reserved for the EJB container. Allowing the enterprise bean to use these functions could compromise security and decrease the container's ability to properly manage the runtime environment.""",,Unknown,
1073 CWE-58,EN-Path Equivalence: Windows 8.3 Filename (Type: Variant),"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.","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.",,Unknown,"Writing Secure Code
1074 The Art of Software Security Assessment: Chapter 11, ""DOS 8.3 Filenames"", Page 673."
1075 CWE-580,EN-clone() Method Without super.clone() (Type: Variant),The software contains a clone() method that does not call super.clone() to obtain the new object.,"All implementations of clone() should obtain the new object by calling super.clone(). If a class does not follow this convention, a subclass's clone() method will return an object of the wrong type.",,Unknown,
1076 CWE-581,EN-Object Model Violation: Just One of Equals and Hashcode Defined (Type: Base),The software does not maintain equal hashcodes for equal objects.,"Java objects are expected to obey a number of invariants related to equality. One of these invariants is that equal objects must have equal hashcodes. In other words, if a.equals(b) == true then a.hashCode() == b.hashCode().",,Unknown,
1077 CWE-582,"EN-Array Declared Public, Final, and Static (Type: Variant)","The program declares an array public, final, and static, which is not sufficient to prevent the array's contents from being modified.","Because arrays are mutable objects, the final constraint requires that the array object itself be assigned only once, but makes no guarantees about the values of the array elements. Since the array is public, a malicious program can change the values stored in the array. As such, in most cases an array declared public, final and static is a bug.",,Unknown,
1078 CWE-583,EN-finalize() Method Declared Public (Type: Variant),The program violates secure coding principles for mobile code by declaring a finalize() method public.,"A program should never call finalize explicitly, except to call super.finalize() inside an implementation of finalize(). In mobile code situations, the otherwise error prone practice of manual garbage collection can become a security threat if an attacker can maliciously invoke one of your finalize() methods because it is declared with public access.",,Unknown,
1079 CWE-584,EN-Return Inside Finally Block (Type: Base),"The code has a return statement inside a finally block, which will cause any thrown exception in the try block to be discarded.","A program should never call finalize explicitly, except to call super.finalize() inside an implementation of finalize(). In mobile code situations, the otherwise error prone practice of manual garbage collection can become a security threat if an attacker can maliciously invoke one of your finalize() methods because it is declared with public access.",,Unknown,
1080 CWE-585,EN-Empty Synchronized Block (Type: Variant),The software contains an empty synchronized block.,An empty synchronized block does not actually accomplish any synchronization and may indicate a troubled section of code. An empty synchronized block can occur because code no longer needed within the synchronized block is commented out without removing the synchronized block.,,Unknown,Intrinsic Locks and Synchronization (in Java): http://java.sun.com/docs/books/tutorial/essential/concurrency/locksync.html
1081 CWE-586,EN-Explicit Call to Finalize() (Type: Variant),The software makes an explicit call to the finalize() method from outside the finalizer.,"While the Java Language Specification allows an object's finalize() method to be called from outside the finalizer, doing so is usually a bad idea. For example, calling finalize() explicitly means that finalize() will be called more than once: the first time will be the explicit call and the last time will be the call that is made after the object is garbage collected.",,Unknown,
1082 CWE-587,EN-Assignment of a Fixed Address to a Pointer (Type: Base),The software sets a pointer to a specific address other than NULL or 0.,Using a fixed address is not portable because that address will probably not be valid in all environments or platforms.,,Unknown,
1083 CWE-588,EN-Attempt to Access Child of a Non-structure Pointer (Type: Variant),Casting a non-structure type to a structure type and accessing a field can lead to memory access errors or data corruption.,Using a fixed address is not portable because that address will probably not be valid in all environments or platforms.,,Unknown,
1084 CWE-589,EN-Call to Non-ubiquitous API (Type: Variant),The software uses an API function that does not exist on all versions of the target platform. This could cause portability problems or inconsistencies that allow denial of service or other consequences.,"Some functions that offer security features supported by the OS are not available on all versions of the OS in common use. Likewise, functions are often deprecated or made obsolete for security reasons and should not be used.",,Unknown,
1085 CWE-590,EN-Free of Memory not on the Heap (Type: Variant),"The application calls free() on a pointer to memory that was not allocated using associated heap allocation functions such as malloc(), calloc(), or realloc().","When free() is called on an invalid pointer, the program's memory management data structures may become corrupted. This corruption can cause the program to crash or, in some circumstances, an attacker may be able to cause free() to operate on controllable memory locations to modify critical program variables or execute code.",,Unknown,Valgrind: http://valgrind.org/
1086 CWE-591,EN-Sensitive Data Storage in Improperly Locked Memory (Type: Variant),"The application stores sensitive data in memory that is not locked, or that has been incorrectly locked, which might cause the memory to be written to swap files on disk by the virtual memory manager. This can make the data more accessible to external actors.","On Windows systems the VirtualLock function can lock a page of memory to ensure that it will remain present in memory and not be swapped to disk. However, on older versions of Windows, such as 95, 98, or Me, the VirtualLock() function is only a stub and provides no protection. On POSIX systems the mlock() call ensures that a page will stay resident in memory but does not guarantee that the page will not appear in the swap. Therefore, it is unsuitable for use as a protection mechanism for sensitive data. Some platforms, in particular Linux, do make the guarantee that the page will not be swapped, but this is non-standard and is not portable. Calls to mlock() also require supervisor privilege. Return values for both of these calls must be checked to ensure that the lock operation was actually successful.",,Unknown,
1087 CWE-592,EN-Authentication Bypass Issues (Type: Class),"The software does not properly perform authentication, allowing it to be bypassed through various methods.","On Windows systems the VirtualLock function can lock a page of memory to ensure that it will remain present in memory and not be swapped to disk. However, on older versions of Windows, such as 95, 98, or Me, the VirtualLock() function is only a stub and provides no protection. On POSIX systems the mlock() call ensures that a page will stay resident in memory but does not guarantee that the page will not appear in the swap. Therefore, it is unsuitable for use as a protection mechanism for sensitive data. Some platforms, in particular Linux, do make the guarantee that the page will not be swapped, but this is non-standard and is not portable. Calls to mlock() also require supervisor privilege. Return values for both of these calls must be checked to ensure that the lock operation was actually successful.",,Unknown,"The Art of Software Security Assessment: Chapter 2, ""Untrustworthy Credentials"", Page 37."
1088 CWE-593,EN-Authentication Bypass: OpenSSL CTX Object Modified after SSL Objects are Created (Type: Variant),The software modifies the SSL context after connection creation has begun.,"If the program modifies the SSL_CTX object after creating SSL objects from it, there is the possibility that older SSL objects created from the original context could all be affected by that change.",,Unknown,
1089 CWE-594,EN-J2EE Framework: Saving Unserializable Objects to Disk (Type: Variant),When the J2EE container attempts to write unserializable objects to disk there is no guarantee that the process will complete successfully.,"If the program modifies the SSL_CTX object after creating SSL objects from it, there is the possibility that older SSL objects created from the original context could all be affected by that change.",,Unknown,
1090 CWE-595,EN-Comparison of Object References Instead of Object Contents (Type: Base),"The program compares object references instead of the contents of the objects themselves, preventing it from detecting equivalent objects.","If the program modifies the SSL_CTX object after creating SSL objects from it, there is the possibility that older SSL objects created from the original context could all be affected by that change.",,Unknown,
1091 CWE-596,EN-Incorrect Semantic Object Comparison (Type: Base),The software does not correctly compare two objects based on their conceptual content.,"If the program modifies the SSL_CTX object after creating SSL objects from it, there is the possibility that older SSL objects created from the original context could all be affected by that change.",,Unknown,
1092 CWE-597,EN-Use of Wrong Operator in String Comparison (Type: Variant),"The product uses the wrong operator when comparing a string, such as using ""=="" when the equals() method should be used instead.","In Java, using == or != to compare two strings for equality actually compares two objects for equality, not their values. Chances are good that the two references will never be equal. While this weakness often only affects program correctness, if the equality is used for a security decision, it could be leveraged to affect program security.",,Unknown,"The Art of Software Security Assessment: Chapter 6, ""Typos"", Page 289."
1093 CWE-598,EN-Information Exposure Through Query Strings in GET Request (Type: Variant),"The web application uses the GET method to process requests that contain sensitive information, which can expose that information through the browser's history, Referers, web logs, and other sources.","In Java, using == or != to compare two strings for equality actually compares two objects for equality, not their values. Chances are good that the two references will never be equal. While this weakness often only affects program correctness, if the equality is used for a security decision, it could be leveraged to affect program security.",,Unknown,
1094 CWE-599,EN-Missing Validation of OpenSSL Certificate (Type: Variant),The software uses OpenSSL and trusts or uses a certificate without using the SSL_get_verify_result() function to ensure that the certificate satisfies all necessary security requirements.,"This could allow an attacker to use an invalid certificate to claim to be a trusted host, use expired certificates, or conduct other attacks that could be detected if the certificate is properly validated.",,Unknown,
1095 CWE-6,EN-J2EE Misconfiguration: Insufficient Session-ID Length (Type: Variant),The J2EE application is configured to use an insufficient session ID length.,"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.",,Unknown,No description: http://www.securiteam.com/securityreviews/5TP0F0UEVQ.html
1096 CWE-600,EN-Uncaught Exception in Servlet (Type: Base),"The Servlet does not catch all exceptions, which may reveal sensitive debugging information.","When a Servlet throws an exception, the default error response the Servlet container sends back to the user typically includes debugging information. This information is of great value to an attacker. 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.",,Unknown,
1097 CWE-603,EN-Use of Client-Side Authentication (Type: Base),"A client/server product performs authentication within client code but not in server code, allowing server-side authentication to be bypassed via a modified client that omits the authentication check.",Client-side authentication is extremely weak and may be breached easily. Any attacker may read the source code and reverse-engineer the authentication mechanism to access parts of the application which would otherwise be protected.,,Unknown,"The Art of Software Security Assessment: Chapter 2, ""Untrustworthy Credentials"", Page 37."
1098 CWE-605,EN-Multiple Binds to the Same Port (Type: Base),"When multiple sockets are allowed to bind to the same port, other services on that port may be stolen or spoofed.",Client-side authentication is extremely weak and may be breached easily. Any attacker may read the source code and reverse-engineer the authentication mechanism to access parts of the application which would otherwise be protected.,,Unknown,
1099 CWE-606,EN-Unchecked Input for Loop Condition (Type: Base),"The product does not properly check inputs that are used for loop conditions, potentially leading to a denial of service because of excessive looping.",Client-side authentication is extremely weak and may be breached easily. Any attacker may read the source code and reverse-engineer the authentication mechanism to access parts of the application which would otherwise be protected.,,Unknown,"The Art of Software Security Assessment: Chapter 7, ""Looping Constructs"", Page 327."
1100 CWE-607,EN-Public Static Final Field References Mutable Object (Type: Variant),"A public or protected static final field references a mutable object, which allows the object to be changed by malicious code, or accidentally from another package.",Client-side authentication is extremely weak and may be breached easily. Any attacker may read the source code and reverse-engineer the authentication mechanism to access parts of the application which would otherwise be protected.,,Unknown,
1101 CWE-608,EN-Struts: Non-private Field in ActionForm Class (Type: Variant),"An ActionForm class contains a field that has not been declared private, which can be accessed without using a setter or getter.",Client-side authentication is extremely weak and may be breached easily. Any attacker may read the source code and reverse-engineer the authentication mechanism to access parts of the application which would otherwise be protected.,,Unknown,
1102 CWE-609,EN-Double-Checked Locking (Type: Base),"The program uses double-checked locking to access a resource without the overhead of explicit synchronization, but the locking is insufficient.","Double-checked locking refers to the situation where a programmer checks to see if a resource has been initialized, grabs a lock, checks again to see if the resource has been initialized, and then performs the initialization if it has not occurred yet. This should not be done, as is not guaranteed to work in all languages and on all architectures. In summary, other threads may not be operating inside the synchronous block and are not guaranteed to see the operations execute in the same order as they would appear inside the synchronous block.",,Unknown,"The ""Double-Checked Locking is Broken"" Declaration: http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
1103 JSR 133 (Java Memory Model) FAQ: http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#dcl
1104 The Art of Software Security Assessment: Chapter 13, ""Threading Vulnerabilities"", Page 815."
1105 CWE-610,EN-Externally Controlled Reference to a Resource in Another Sphere (Type: Class),The product uses an externally controlled name or reference that resolves to a resource that is outside of the intended control sphere.,,,Unknown,
1106 CWE-611,EN-Improper Restriction of XML External Entity Reference (XXE) (Type: Variant),"The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.","XML documents optionally contain a Document Type Definition (DTD), which, among other features, enables the definition of XML entities. It is possible to define an entity by providing a substitution string in the form of a URI. The XML parser can access the contents of this URI and embed these contents back into the XML document for further processing.
1107 By submitting an XML file that defines an external entity with a file:// URI, an attacker can cause the processing application to read the contents of a local file. For example, a URI such as ""file:///c:/winnt/win.ini"" designates (in Windows) the file C:\Winnt\win.ini, or file:///etc/passwd designates the password file in Unix-based systems. Using URIs with other schemes such as http://, the attacker can force the application to make outgoing requests to servers that the attacker cannot reach directly, which can be used to bypass firewall restrictions or hide the source of attacks such as port scanning.
1108 Once the content of the URI is read, it is fed back into the application that is processing the XML. This application may echo back the data (e.g. in an error message), thereby exposing the file contents.",,Unknown,"XML External Entity (XXE) Processing: https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing
1109 XML External Entity Attacks (XXE): https://www.owasp.org/images/5/5d/XML_Exteral_Entity_Attack.pdf
1110 XXE (Xml eXternal Entity) Attack: http://www.securiteam.com/securitynews/6D0100A5PU.html
1111 XML External Entities (XXE) Attack: http://projects.webappsec.org/w/page/13247003/XML%20External%20Entities
1112 XML Denial of Service Attacks and Defenses: http://msdn.microsoft.com/en-us/magazine/ee335713.aspx
1113 Preventing XXE in PHP: http://websec.io/2012/08/27/Preventing-XEE-in-PHP.html"
1114 CWE-612,EN-Information Exposure Through Indexing of Private Data (Type: Variant),"The product performs an indexing routine against private documents, but does not sufficiently verify that the actors who can access the index also have the privileges to access the private documents.","When an indexing routine is applied against a group of private documents, and that index's results are available to outsiders who do not have access to those documents, then outsiders might be able to obtain sensitive information by conducting targeted searches. The risk is especially dangerous if search results include surrounding text that was not part of the search query. This issue can appear in search engines that are not configured (or implemented) to ignore critical files that should remain hidden; even without permissions to download these files directly, the remote user could read them.",,Unknown,
1115 CWE-613,EN-Insufficient Session Expiration (Type: Base),"According to WASC, ""Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization.""","When an indexing routine is applied against a group of private documents, and that index's results are available to outsiders who do not have access to those documents, then outsiders might be able to obtain sensitive information by conducting targeted searches. The risk is especially dangerous if search results include surrounding text that was not part of the search query. This issue can appear in search engines that are not configured (or implemented) to ignore critical files that should remain hidden; even without permissions to download these files directly, the remote user could read them.",,Unknown,
1116 CWE-614,EN-Sensitive Cookie in HTTPS Session Without Secure Attribute (Type: Variant),"The Secure attribute for sensitive cookies in HTTPS sessions is not set, which could cause the user agent to send those cookies in plaintext over an HTTP session.","When an indexing routine is applied against a group of private documents, and that index's results are available to outsiders who do not have access to those documents, then outsiders might be able to obtain sensitive information by conducting targeted searches. The risk is especially dangerous if search results include surrounding text that was not part of the search query. This issue can appear in search engines that are not configured (or implemented) to ignore critical files that should remain hidden; even without permissions to download these files directly, the remote user could read them.",,Unknown,
1117 CWE-615,EN-Information Exposure Through Comments (Type: Variant),"While adding general comments is very useful, some programmers tend to leave important data, such as: filenames related to the web application, old links or links which were not meant to be browsed by users, old code fragments, etc.","An attacker who finds these comments can map the application's structure and files, expose hidden parts of the site, and study the fragments of code to reverse engineer the application, which may help develop further attacks against the site.",,Unknown,
1118 CWE-616,EN-Incomplete Identification of Uploaded File Variables (PHP) (Type: Variant),"The PHP application uses an old method for processing uploaded files by referencing the four global variables that are set for each file (e.g. $varname, $varname_size, $varname_name, $varname_type). These variables could be overwritten by attackers, causing the application to process unauthorized files.","These global variables could be overwritten by POST requests, cookies, or other methods of populating or overwriting these variables. This could be used to read or process arbitrary files by providing values such as ""/etc/passwd"".",,Unknown,"A Study in Scarlet - section 5, ""File Upload"""
1119 CWE-617,EN-Reachable Assertion (Type: Variant),"The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary.","For example, if a server handles multiple simultaneous connections, and an assert() occurs in one single connection that causes all other connections to be dropped, this is a reachable assertion that leads to a denial of service.",,Unknown,
1120 CWE-618,EN-Exposed Unsafe ActiveX Method (Type: Base),"An ActiveX control is intended for use in a web browser, but it exposes dangerous methods that perform actions that are outside of the browser's security model (e.g. the zone or domain).","ActiveX controls can exercise far greater control over the operating system than typical Java or javascript. Exposed methods can be subject to various vulnerabilities, depending on the implemented behaviors of those methods, and whether input validation is performed on the provided arguments. If there is no integrity checking or origin validation, this method could be invoked by attackers.",,Unknown,"No description: http://msdn.microsoft.com/workshop/components/activex/safety.asp
1121 No description: http://msdn.microsoft.com/workshop/components/activex/security.asp
1122 The Art of Software Security Assessment: Chapter 12, ""ActiveX Security"", Page 749."
1123 CWE-619,EN-Dangling Database Cursor (Cursor Injection) (Type: Base),"If a database cursor is not closed properly, then it could become accessible to other users while retaining the same privileges that were originally assigned, leaving the cursor ""dangling.""","For example, an improper dangling cursor could arise from unhandled exceptions. The impact of the issue depends on the cursor's role, but SQL injection attacks are commonly possible.",,Unknown,"The Oracle Hacker's Handbook
1124 Cursor Injection: http://www.databasesecurity.com/dbsec/cursor-injection.pdf"
1125 CWE-62,EN-UNIX Hard Link (Type: Variant),"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.","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.",,Unknown,"The Art of Software Security Assessment: Chapter 9, ""Hard Links"", Page 518."
1126 CWE-620,EN-Unverified Password Change (Type: Variant),"When setting a new password for a user, the product does not require knowledge of the original password, or using another form of authentication.","This could be used by an attacker to change passwords for another user, thus gaining the privileges associated with that user.",,Unknown,"24 Deadly Sins of Software Security: ""Sin 19: Use of Weak Password-Based Systems."" Page 279"
1127 CWE-621,EN-Variable Extraction Error (Type: Base),"The product uses external input to determine the names of variables into which information is extracted, without verifying that the names of the specified variables are valid. This could cause the program to overwrite unintended variables.","For example, in PHP, calling extract() or import_request_variables() without the proper arguments could allow arbitrary global variables to be overwritten, including superglobals. Similar functionality might be possible in other interpreted languages, including custom languages.",,Unknown,
1128 CWE-622,EN-Improper Validation of Function Hook Arguments (Type: Variant),"A product adds hooks to user-accessible API functions, but does not properly validate the arguments. This could lead to resultant vulnerabilities.","Such hooks can be used in defensive software that runs with privileges, such as anti-virus or firewall, which hooks kernel calls. When the arguments are not validated, they could be used to bypass the protection scheme or attack the product itself.",,Unknown,
1129 CWE-623,EN-Unsafe ActiveX Control Marked Safe For Scripting (Type: Variant),"An ActiveX control is intended for restricted use, but it has been marked as safe-for-scripting.","This might allow attackers to use dangerous functionality via a web page that accesses the control, which can lead to different resultant vulnerabilities, depending on the control's behavior.",,Unknown,"No description: http://msdn.microsoft.com/workshop/components/activex/safety.asp
1130 No description: http://msdn.microsoft.com/workshop/components/activex/security.asp
1131 No description: http://support.microsoft.com/kb/240797
1132 Writing Secure Code: Chapter 16, ""What ActiveX Components Are Safe for Initialization and Safe for Scripting?"" Page 510
1133 The Art of Software Security Assessment: Chapter 12, ""ActiveX Security"", Page 749."
1134 CWE-624,EN-Executable Regular Expression Error (Type: Base),"The product uses a regular expression that either (1) contains an executable component with user-controlled inputs, or (2) allows a user to enable execution by inserting pattern modifiers.","Case (2) is possible in the PHP preg_replace() function, and possibly in other languages when a user-controlled input is inserted into a string that is later parsed as a regular expression.",,Unknown,
1135 CWE-625,EN-Permissive Regular Expression (Type: Base),The product uses a regular expression that does not sufficiently restrict the set of allowed values.,"This effectively causes the regexp to accept substrings that match the pattern, which produces a partial comparison to the target. In some cases, this can lead to other weaknesses. Common errors include:
1136 not identifying the beginning and end of the target string
1137 using wildcards instead of acceptable character ranges
1138 others",,Unknown,"The Art of Software Security Assessment: Chapter 8, ""Character Stripping Vulnerabilities"", Page 437."
1139 CWE-626,EN-Null Byte Interaction Error (Poison Null Byte) (Type: Variant),The product does not properly handle null bytes or NUL characters when passing data between different representations or components.,"A null byte (NUL character) can have different meanings across representations or languages. For example, it is a string terminator in standard C libraries, but Perl and PHP strings do not treat it as a terminator. When two representations are crossed - such as when Perl or PHP invokes underlying C functionality - this can produce an interaction error with unexpected results. Similar issues have been reported for ASP. Other interpreters written in C might also be affected.",,Unknown,"Poison NULL byte: http://insecure.org/news/P55-07.txt
1140 0x00 vs ASP file upload scripts: http://www.security-assessment.com/Whitepapers/0x00_vs_ASP_File_Uploads.pdf
1141 ShAnKaR: multiple PHP application poison NULL byte vulnerability: http://seclists.org/fulldisclosure/2006/Sep/0185.html"
1142 CWE-627,EN-Dynamic Variable Evaluation (Type: Base),"In a language where the user can influence the name of a variable at runtime, if the variable names are not controlled, an attacker can read or write to arbitrary variables, or access arbitrary functions.","The resultant vulnerabilities depend on the behavior of the application, both at the crossover point and in any control/data flow that is reachable by the related variables or functions.",,Unknown,"Dynamic Evaluation Vulnerabilities in PHP applications: http://seclists.org/fulldisclosure/2006/May/0035.html
1143 A Study In Scarlet: Exploiting Common Vulnerabilities in PHP Applications: http://www.securereality.com.au/studyinscarlet.txt"
1144 CWE-628,EN-Function Call with Incorrectly Specified Arguments (Type: Base),"The product calls a function, procedure, or routine with arguments that are not correctly specified, leading to always-incorrect behavior and resultant weaknesses.","There are multiple ways in which this weakness can be introduced, including:
1145 the wrong variable or reference;
1146 an incorrect number of arguments;
1147 incorrect order of arguments;
1148 wrong type of arguments; or
1149 wrong value.",,Unknown,
1150 CWE-636,EN-Not Failing Securely (Failing Open) (Type: Class),"When the product encounters an error condition or failure, its design requires it to fall back to a state that is less secure than other options that are available, such as selecting the weakest encryption algorithm or using the most permissive access control restrictions.","By entering a less secure state, the product inherits the weaknesses associated with that state, making it easier to compromise. At the least, it causes administrators to have a false sense of security. This weakness typically occurs as a result of wanting to ""fail functional"" to minimize administration and support costs, instead of ""failing safe.""",,Unknown,"The Protection of Information in Computer Systems: http://web.mit.edu/Saltzer/www/publications/protection/
1151 Failing Securely: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/349.html"
1152 CWE-637,EN-Unnecessary Complexity in Protection Mechanism (Not Using Economy of Mechanism) (Type: Class),"The software uses a more complex mechanism than necessary, which could lead to resultant weaknesses when the mechanism is not correctly understood, modeled, configured, implemented, or used.","Security mechanisms should be as simple as possible. Complex security mechanisms may engender partial implementations and compatibility problems, with resulting mismatches in assumptions and implemented security. A corollary of this principle is that data specifications should be as simple as possible, because complex data specifications result in complex validation code. Complex tasks and systems may also need to be guarded by complex security checks, so simple systems should be preferred.",,Unknown,"The Protection of Information in Computer Systems: http://web.mit.edu/Saltzer/www/publications/protection/
1153 Economy of Mechanism: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/348.html"
1154 CWE-638,EN-Not Using Complete Mediation (Type: Class),"The software does not perform access checks on a resource every time the resource is accessed by an entity, which can create resultant weaknesses if that entity's rights or privileges change over time.",,,Unknown,"The Protection of Information in Computer Systems: http://web.mit.edu/Saltzer/www/publications/protection/
1155 Complete Mediation: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/346.html"
1156 CWE-65,EN-Windows Hard Link (Type: Variant),"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.","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.",,Unknown,"The Art of Software Security Assessment: Chapter 11, ""Links"", Page 676."
1157 CWE-651,EN-Information Exposure Through WSDL File (Type: Variant),The Web services architecture may require exposing a WSDL file that contains information on the publicly accessible services and how callers of these services should interact with them (e.g. what parameters they expect and what types they return).,"An information exposure may occur if any of the following apply:
1158 The WSDL file is accessible to a wider audience than intended.
1159 The WSDL file contains information on the methods/services that should not be publicly accessible or information about deprecated methods. This problem is made more likely due to the WSDL often being automatically generated from the code.
1160 Information in the WSDL file helps guess names/locations of methods/resources that should not be publicly accessible.",,Unknown,
1161 CWE-653,EN-Insufficient Compartmentalization (Type: Base),"The product does not sufficiently compartmentalize functionality or processes that require different privilege levels, rights, or permissions.","When a weakness occurs in functionality that is accessible by lower-privileged users, then without strong boundaries, an attack might extend the scope of the damage to higher-privileged users.",,Unknown,"The Protection of Information in Computer Systems: http://web.mit.edu/Saltzer/www/publications/protection/
1162 Separation of Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/357.html"
1163 CWE-654,EN-Reliance on a Single Factor in a Security Decision (Type: Base),"A protection mechanism relies exclusively, or to a large extent, on the evaluation of a single condition or the integrity of a single object or entity in order to make a decision about granting access to restricted resources or functionality.","When a weakness occurs in functionality that is accessible by lower-privileged users, then without strong boundaries, an attack might extend the scope of the damage to higher-privileged users.",,Unknown,"The Protection of Information in Computer Systems: http://web.mit.edu/Saltzer/www/publications/protection/
1164 Separation of Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/357.html"
1165 CWE-655,EN-Insufficient Psychological Acceptability (Type: Base),"The software has a protection mechanism that is too difficult or inconvenient to use, encouraging non-malicious users to disable or bypass the mechanism, whether by accident or on purpose.","When a weakness occurs in functionality that is accessible by lower-privileged users, then without strong boundaries, an attack might extend the scope of the damage to higher-privileged users.",,Unknown,"The Protection of Information in Computer Systems: http://web.mit.edu/Saltzer/www/publications/protection/
1166 Psychological Acceptability: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/354.html
1167 Usability of Security: A Case Study: http://reports-archive.adm.cs.cmu.edu/anon/1998/CMU-CS-98-155.pdf
1168 24 Deadly Sins of Software Security: ""Sin 14: Poor Usability."" Page 217"
1169 CWE-656,EN-Reliance on Security Through Obscurity (Type: Base),"The software uses a protection mechanism whose strength depends heavily on its obscurity, such that knowledge of its algorithms or key data is sufficient to defeat the mechanism.","This reliance on ""security through obscurity"" can produce resultant weaknesses if an attacker is able to reverse engineer the inner workings of the mechanism. Note that obscurity can be one small part of defense in depth, since it can create more work for an attacker; however, it is a significant risk if used as the primary means of protection.",,Unknown,"RFC: 793, TRANSMISSION CONTROL PROTOCOL: http://www.ietf.org/rfc/rfc0793.txt
1170 The Protection of Information in Computer Systems: http://web.mit.edu/Saltzer/www/publications/protection/
1171 Never Assuming that Your Secrets Are Safe: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/352.html"
1172 CWE-657,EN-Violation of Secure Design Principles (Type: Class),The product violates well-established principles for secure design.,"This can introduce resultant weaknesses or make it easier for developers to introduce related weaknesses during implementation. Because code is centered around design, it can be resource-intensive to fix design problems.",,Unknown,"The Protection of Information in Computer Systems: http://web.mit.edu/Saltzer/www/publications/protection/
1173 Design Principles: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/358.html"
1174 CWE-66,EN-Improper Handling of File Names that Identify Virtual Resources (Type: Base),"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.","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.",,Unknown,
1175 CWE-662,EN-Improper Synchronization (Type: Base),"The software attempts to use a shared resource in an exclusive manner, but does not prevent or incorrectly prevents use of the resource by another thread or process.","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.",,Unknown,
1176 CWE-663,EN-Use of a Non-reentrant Function in a Concurrent Context (Type: Base),The software calls a non-reentrant function in a concurrent context in which a competing code sequence (e.g. thread or signal handler) may have an opportunity to call the same function or otherwise influence its state.,"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.",,Unknown,"Java Concurrency API: http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html
1177 Use reentrant functions for safer signal handling: http://www.ibm.com/developerworks/linux/library/l-reent.html"
1178 CWE-664,EN-Improper Control of a Resource Through its Lifetime (Type: Class),"The software does not maintain or incorrectly maintains control over a resource throughout its lifetime of creation, use, and release.","Resources often have explicit instructions on how to be created, used and destroyed. When software does not follow these instructions, it can lead to unexpected behaviors and potentially exploitable states.
1179 Even without explicit instructions, various principles are expected to be adhered to, such as ""Do not use an object until after its creation is complete,"" or ""do not use an object after it has been slated for destruction.""",,Unknown,
1180 CWE-666,EN-Operation on Resource in Wrong Phase of Lifetime (Type: Base),"The software performs an operation on a resource at the wrong phase of the resource's lifecycle, which can lead to unexpected behaviors.","When a developer wants to initialize, use or release a resource, it is important to follow the specifications outlined for how to operate on that resource and to ensure that the resource is in the expected state. In this case, the software wants to perform a normally valid operation, initialization, use or release, on a resource when it is in the incorrect phase of its lifetime.",,Unknown,
1181 CWE-667,EN-Improper Locking (Type: Base),"The software does not properly acquire a lock on a resource, or it does not properly release a lock on a resource, leading to unexpected resource state changes and behaviors.","When a developer wants to initialize, use or release a resource, it is important to follow the specifications outlined for how to operate on that resource and to ensure that the resource is in the expected state. In this case, the software wants to perform a normally valid operation, initialization, use or release, on a resource when it is in the incorrect phase of its lifetime.",,Unknown,
1182 CWE-668,EN-Exposure of Resource to Wrong Sphere (Type: Class),"The product exposes a resource to the wrong control sphere, providing unintended actors with inappropriate access to the resource.","Resources such as files and directories may be inadvertently exposed through mechanisms such as insecure permissions, or when a program accidentally operates on the wrong object. For example, a program may intend that private files can only be provided to a specific user. This effectively defines a control sphere that is intended to prevent attackers from accessing these private files. If the file permissions are insecure, then parties other than the user will be able to access those files.
1183 A separate control sphere might effectively require that the user can only access the private files, but not any other files on the system. If the program does not ensure that the user is only requesting private files, then the user might be able to access other files on the system.
1184 In either case, the end result is that a resource has been exposed to the wrong party.",,Unknown,
1185 CWE-669,EN-Incorrect Resource Transfer Between Spheres (Type: Class),"The product does not properly transfer a resource/behavior to another sphere, or improperly imports a resource/behavior from another sphere, in a manner that provides unintended control over that resource.","Resources such as files and directories may be inadvertently exposed through mechanisms such as insecure permissions, or when a program accidentally operates on the wrong object. For example, a program may intend that private files can only be provided to a specific user. This effectively defines a control sphere that is intended to prevent attackers from accessing these private files. If the file permissions are insecure, then parties other than the user will be able to access those files.
1186 A separate control sphere might effectively require that the user can only access the private files, but not any other files on the system. If the program does not ensure that the user is only requesting private files, then the user might be able to access other files on the system.
1187 In either case, the end result is that a resource has been exposed to the wrong party.",,Unknown,
1188 CWE-670,EN-Always-Incorrect Control Flow Implementation (Type: Class),"The code contains a control flow path that does not reflect the algorithm that the path is intended to implement, leading to incorrect behavior any time this path is navigated.","This weakness captures cases in which a particular code segment is always incorrect with respect to the algorithm that it is implementing. For example, if a C programmer intends to include multiple statements in a single block but does not include the enclosing braces (CWE-483), then the logic is always incorrect. This issue is in contrast to most weaknesses in which the code usually behaves correctly, except when it is externally manipulated in malicious ways.",,Unknown,
1189 CWE-671,EN-Lack of Administrator Control over Security (Type: Class),The product uses security features in a way that prevents the product's administrator from tailoring security settings to reflect the environment in which the product is being used. This introduces resultant weaknesses or prevents it from operating at a level of security that is desired by the administrator.,"If the product's administrator does not have the ability to manage security-related decisions at all times, then protecting the product from outside threats - including the product's developer - can become impossible. For example, a hard-coded account name and password cannot be changed by the administrator, thus exposing that product to attacks that the administrator can not prevent.",,Unknown,
1190 CWE-672,EN-Operation on a Resource after Expiration or Release (Type: Base),"The software uses, accesses, or otherwise operates on a resource after that resource has been expired, released, or revoked.","If the product's administrator does not have the ability to manage security-related decisions at all times, then protecting the product from outside threats - including the product's developer - can become impossible. For example, a hard-coded account name and password cannot be changed by the administrator, thus exposing that product to attacks that the administrator can not prevent.",,Unknown,
1191 CWE-673,EN-External Influence of Sphere Definition (Type: Class),The product does not prevent the definition of control spheres from external actors.,"Typically, a product defines its control sphere within the code itself, or through configuration by the product's administrator. In some cases, an external party can change the definition of the control sphere. This is typically a resultant weakness.",,Unknown,
1192 CWE-674,EN-Uncontrolled Recursion (Type: Base),"The product does not properly control the amount of recursion that takes place, which consumes excessive resources, such as allocated memory or the program stack.","Typically, a product defines its control sphere within the code itself, or through configuration by the product's administrator. In some cases, an external party can change the definition of the control sphere. This is typically a resultant weakness.",,Unknown,
1193 CWE-675,EN-Duplicate Operations on Resource (Type: Class),"The product performs the same operation on a resource two or more times, when the operation should only be applied once.","Typically, a product defines its control sphere within the code itself, or through configuration by the product's administrator. In some cases, an external party can change the definition of the control sphere. This is typically a resultant weakness.",,Unknown,
1194 CWE-683,EN-Function Call With Incorrect Order of Arguments (Type: Variant),"The software calls a function, procedure, or routine, but the caller specifies the arguments in an incorrect order, leading to resultant weaknesses.","While this weakness might be caught by the compiler in some languages, it can occur more frequently in cases in which the called function accepts variable numbers or types of arguments, such as format strings in C. It also can occur in languages or environments that do not enforce strong typing.",,Unknown,
1195 CWE-684,EN-Incorrect Provision of Specified Functionality (Type: Base),"The code does not function according to its published specifications, potentially leading to incorrect usage.","When providing functionality to an external party, it is important that the software behaves in accordance with the details specified. When requirements of nuances are not documented, the functionality may produce unintended behaviors for the caller, possibly leading to an exploitable state.",,Unknown,
1196 CWE-685,EN-Function Call With Incorrect Number of Arguments (Type: Variant),"The software calls a function, procedure, or routine, but the caller specifies too many arguments, or too few arguments, which may lead to undefined behavior and resultant weaknesses.","When providing functionality to an external party, it is important that the software behaves in accordance with the details specified. When requirements of nuances are not documented, the functionality may produce unintended behaviors for the caller, possibly leading to an exploitable state.",,Unknown,
1197 CWE-686,EN-Function Call With Incorrect Argument Type (Type: Variant),"The software calls a function, procedure, or routine, but the caller specifies an argument that is the wrong data type, which may lead to resultant weaknesses.","This weakness is most likely to occur in loosely typed languages, or in strongly typed languages in which the types of variable arguments cannot be enforced at compilation time, or where there is implicit casting.",,Unknown,
1198 CWE-687,EN-Function Call With Incorrectly Specified Argument Value (Type: Variant),"The software calls a function, procedure, or routine, but the caller specifies an argument that contains the wrong value, which may lead to resultant weaknesses.","This weakness is most likely to occur in loosely typed languages, or in strongly typed languages in which the types of variable arguments cannot be enforced at compilation time, or where there is implicit casting.",,Unknown,
1199 CWE-688,EN-Function Call With Incorrect Variable or Reference as Argument (Type: Variant),"The software calls a function, procedure, or routine, but the caller specifies the wrong variable or reference as one of the arguments, which may lead to undefined behavior and resultant weaknesses.","This weakness is most likely to occur in loosely typed languages, or in strongly typed languages in which the types of variable arguments cannot be enforced at compilation time, or where there is implicit casting.",,Unknown,
1200 CWE-69,EN-Improper Handling of Windows ::DATA Alternate Data Stream (Type: Variant),"The software does not properly prevent access to, or detect usage of, alternate data streams (ADS).","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.",,Unknown,"Windows NTFS Alternate Data Streams: http://www.securityfocus.com/infocus/1822
1201 Writing Secure Code"
1202 CWE-691,EN-Insufficient Control Flow Management (Type: Class),"The code does not sufficiently manage its control flow during execution, creating conditions in which the control flow can be modified in unexpected ways.","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.",,Unknown,
1203 CWE-693,EN-Protection Mechanism Failure (Type: Class),The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.,"This weakness covers three distinct situations. A ""missing"" protection mechanism occurs when the application does not define any mechanism against a certain class of attack. An ""insufficient"" protection mechanism might provide some defenses - for example, against the most common attacks - but it does not protect against everything that is intended. Finally, an ""ignored"" mechanism occurs when a mechanism is available and in active use within the product, but the developer has not applied it in some code path.",,Unknown,
1204 CWE-694,EN-Use of Multiple Resources with Duplicate Identifier (Type: Base),"The software uses multiple resources that can have the same identifier, in a context in which unique identifiers are required.","If the software assumes that each resource has a unique identifier, the software could operate on the wrong resource if attackers can cause multiple resources to be associated with the same identifier.",,Unknown,
1205 CWE-695,EN-Use of Low-Level Functionality (Type: Base),The software uses low-level functionality that is explicitly prohibited by the framework or specification under which the software is supposed to operate.,"The use of low-level functionality can violate the specification in unexpected ways that effectively disable built-in protection mechanisms, introduce exploitable inconsistencies, or otherwise expose the functionality to attack.",,Unknown,
1206 CWE-696,EN-Incorrect Behavior Order (Type: Class),"The software performs multiple related behaviors, but the behaviors are performed in the wrong order in ways which may produce resultant weaknesses.","The use of low-level functionality can violate the specification in unexpected ways that effectively disable built-in protection mechanisms, introduce exploitable inconsistencies, or otherwise expose the functionality to attack.",,Unknown,
1207 CWE-697,EN-Insufficient Comparison (Type: Class),"The software compares two entities in a security-relevant context, but the comparison is insufficient, which may lead to resultant weaknesses.","This weakness class covers several possibilities:
1208 the comparison checks one factor incorrectly;
1209 the comparison should consider multiple factors, but it does not check some of those factors at all.",,Unknown,
1210 CWE-698,EN-Execution After Redirect (EAR) (Type: Base),"The web application sends a redirect to another location, but instead of exiting, it executes additional code.","This weakness class covers several possibilities:
1211 the comparison checks one factor incorrectly;
1212 the comparison should consider multiple factors, but it does not check some of those factors at all.",,Unknown,Fear the EAR: Discovering and Mitigating Execution After Redirect Vulnerabilities: http://cs.ucsb.edu/~bboe/public/pubs/fear-the-ear-ccs2011.pdf
1213 CWE-7,EN-J2EE Misconfiguration: Missing Custom Error Page (Type: Variant),The default error page of a web application should not display sensitive information about the software system.,"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.",,Unknown,19 Deadly Sins of Software Security
1214 CWE-703,EN-Improper Check or Handling of Exceptional Conditions (Type: Class),The software does not properly anticipate or handle exceptional conditions that rarely occur during normal operation of the software.,"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.",,Unknown,"A Taxonomy of Security Faults in the UNIX Operating System: http://ftp.cerias.purdue.edu/pub/papers/taimur-aslam/aslam-taxonomy-msthesis.pdf
1215 Use of A Taxonomy of Security Faults: http://csrc.nist.gov/nissc/1996/papers/NISSC96/paper057/PAPER.PDF
1216 24 Deadly Sins of Software Security: ""Sin 8: C++ Catastrophes."" Page 143"
1217 CWE-704,EN-Incorrect Type Conversion or Cast (Type: Class),"The software does not correctly convert an object, resource or structure from one type to a different type.","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.",,Unknown,
1218 CWE-705,EN-Incorrect Control Flow Scoping (Type: Class),The software does not properly return control flow to the proper location after it has completed a task or detected an unusual condition.,"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.",,Unknown,
1219 CWE-706,EN-Use of Incorrectly-Resolved Name or Reference (Type: Class),"The software uses a name or reference to access a resource, but the name/reference resolves to a resource that is outside of the intended control sphere.","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.",,Unknown,
1220 CWE-707,EN-Improper Enforcement of Message or Data Structure (Type: Class),The software does not enforce or incorrectly enforces that structured messages or data are well-formed before being read from an upstream component or sent to a downstream component.,"If a message is malformed it may cause the message to be incorrectly interpreted.
1221 This weakness typically applies in cases where the product prepares a control message that another process must act on, such as a command or query, and malicious input that was intended as data, can enter the control plane instead. However, this weakness also applies to more general cases where there are not always control implications.",,Unknown,
1222 CWE-708,EN-Incorrect Ownership Assignment (Type: Base),"The software assigns an owner to a resource, but the owner is outside of the intended control sphere.",This may allow the resource to be manipulated by actors outside of the intended control sphere.,,Unknown,
1223 CWE-71,EN-Apple .DS_Store (Type: Variant),"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.",This may allow the resource to be manipulated by actors outside of the intended control sphere.,,Unknown,
1224 CWE-710,EN-Coding Standards Violation (Type: Class),"The software does not follow certain coding rules for development, which can lead to resultant weaknesses or increase the severity of the associated vulnerabilities.",This may allow the resource to be manipulated by actors outside of the intended control sphere.,,Unknown,
1225 CWE-72,EN-Improper Handling of Apple HFS+ Alternate Data Stream Path (Type: Variant),The software does not properly handle special paths that may identify the data or resource fork of a file on the HFS+ file system.,"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.",,Unknown,No description: http://docs.info.apple.com/article.html?artnum=300422
1226 CWE-733,EN-Compiler Optimization Removal or Modification of Security-critical Code (Type: Base),The developer builds a security-critical protection mechanism into the software but the compiler optimizes the program such that the mechanism is removed or modified.,"When a resource is given a permissions setting that provides access to a wider range of actors than required, it could lead to the exposure of sensitive information, or the modification of that resource by unintended parties. This is especially dangerous when the resource is related to program configuration, execution or sensitive user data.",,Unknown,"Writing Secure Code: Chapter 9, ""A Compiler Optimization Caveat"" Page 322"
1227 CWE-75,EN-Failure to Sanitize Special Elements into a Different Plane (Special Element Injection) (Type: Class),The software does not adequately filter user-controlled input for special elements with control implications.,"This weakness can lead to a wide variety of resultant weaknesses, depending on the behavior of the exposed method. It can apply to any number of technologies and approaches, such as ActiveX controls, Java functions, IOCTLs, and so on.
1228 The exposure can occur in a few different ways:
1229 1) The function/method was never intended to be exposed to outside actors.
1230 2) The function/method was only intended to be accessible to a limited set of actors, such as Internet-based access from a single web site.",,Unknown,
1231 CWE-756,EN-Missing Custom Error Page (Type: Class),"The software does not return custom error pages to the user, possibly exposing sensitive information.","The programmer may assume that certain events or conditions will never occur or do not need to be worried about, such as low memory conditions, lack of access to resources due to restrictive permissions, or misbehaving clients or components. However, attackers may intentionally trigger these unusual conditions, thus violating the programmer's assumptions, possibly introducing instability, incorrect behavior, or a vulnerability.
1232 Note that this entry is not exclusively about the use of exceptions and exception handling, which are mechanisms for both checking and handling unusual or unexpected conditions.",,Unknown,
1233 CWE-757,EN-Selection of Less-Secure Algorithm During Negotiation (Algorithm Downgrade) (Type: Class),"A protocol or its implementation supports interaction between multiple actors and allows those actors to negotiate which algorithm should be used as a protection mechanism such as encryption or authentication, but it does not select the strongest algorithm that is available to both parties.","When a security mechanism can be forced to downgrade to use a less secure algorithm, this can make it easier for attackers to compromise the software by exploiting weaker algorithm. The victim might not be aware that the less secure algorithm is being used. For example, if an attacker can force a communications channel to use cleartext instead of strongly-encrypted data, then the attacker could read the channel by sniffing, instead of going through extra effort of trying to decrypt the data using brute force techniques.",,Unknown,
1234 CWE-758,"EN-Reliance on Undefined, Unspecified, or Implementation-Defined Behavior (Type: Class)","The software uses an API function, data structure, or other entity in a way that relies on properties that are not always guaranteed to hold for that entity.","This can lead to resultant weaknesses when the required properties change, such as when the software is ported to a different platform or if an interaction error (CWE-435) occurs.",,Unknown,
1235 CWE-759,EN-Use of a One-Way Hash without a Salt (Type: Base),"The software uses a one-way cryptographic hash against an input that should not be reversible, such as a password, but the software does not also use a salt as part of the input.","This makes it easier for attackers to pre-compute the hash value using dictionary attack techniques such as rainbow tables.
1236 It should be noted that, despite common perceptions, the use of a good salt with a hash does not sufficiently increase the effort for an attacker who is targeting an individual password, or who has a large amount of computing resources available, such as with cloud-based services or specialized, inexpensive hardware. Offline password cracking can still be effective if the hash function is not expensive to compute; many cryptographic functions are designed to be efficient and can be vulnerable to attacks using massive computing resources, even if the hash is cryptographically strong. The use of a salt only slightly increases the computing requirements for an attacker compared to other strategies such as adaptive hash functions. See CWE-916 for more details.",,Unknown,"bcrypt: http://bcrypt.sourceforge.net/
1237 Tarsnap - The scrypt key derivation function and encryption utility: http://www.tarsnap.com/scrypt.html
1238 RFC2898 - PKCS #5: Password-Based Cryptography Specification Version 2.0: http://tools.ietf.org/html/rfc2898
1239 How Companies Can Beef Up Password Security (interview with Thomas H. Ptacek): http://krebsonsecurity.com/2012/06/how-companies-can-beef-up-password-security/
1240 Speed Hashing: http://www.codinghorror.com/blog/2012/04/speed-hashing.html
1241 Password security: past, present, future: http://www.openwall.com/presentations/PHDays2012-Password-Security/
1242 Password Storage Cheat Sheet: https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet
1243 Enough With The Rainbow Tables: What You Need To Know About Secure Password Schemes: http://www.securityfocus.com/blogs/262
1244 The Importance of Being Canonical: http://erratasec.blogspot.com/2009/02/importance-of-being-canonical.html
1245 Password Hashing: http://phpsec.org/articles/2005/password-hashing.html
1246 Rainbow Hash Cracking: http://www.codinghorror.com/blog/archives/000949.html
1247 Rainbow table: http://en.wikipedia.org/wiki/Rainbow_table
1248 Writing Secure Code: Chapter 9, ""Creating a Salted Hash"" Page 302
1249 The Art of Software Security Assessment: Chapter 2, ""Salt Values"", Page 46.
1250 How To Safely Store A Password: http://codahale.com/how-to-safely-store-a-password/
1251 Our password hashing has no clothes: http://www.troyhunt.com/2012/06/our-password-hashing-has-no-clothes.html
1252 Should we really use bcrypt/scrypt?: http://www.analyticalengine.net/2012/06/should-we-really-use-bcryptscrypt/"
1253 CWE-760,EN-Use of a One-Way Hash with a Predictable Salt (Type: Base),"The software uses a one-way cryptographic hash against an input that should not be reversible, such as a password, but the software uses a predictable salt as part of the input.","This makes it easier for attackers to pre-compute the hash value using dictionary attack techniques such as rainbow tables, effectively disabling the protection that an unpredictable salt would provide.
1254 It should be noted that, despite common perceptions, the use of a good salt with a hash does not sufficiently increase the effort for an attacker who is targeting an individual password, or who has a large amount of computing resources available, such as with cloud-based services or specialized, inexpensive hardware. Offline password cracking can still be effective if the hash function is not expensive to compute; many cryptographic functions are designed to be efficient and can be vulnerable to attacks using massive computing resources, even if the hash is cryptographically strong. The use of a salt only slightly increases the computing requirements for an attacker compared to other strategies such as adaptive hash functions. See CWE-916 for more details.",,Unknown,"bcrypt: http://bcrypt.sourceforge.net/
1255 Tarsnap - The scrypt key derivation function and encryption utility: http://www.tarsnap.com/scrypt.html
1256 RFC2898 - PKCS #5: Password-Based Cryptography Specification Version 2.0: http://tools.ietf.org/html/rfc2898
1257 How Companies Can Beef Up Password Security (interview with Thomas H. Ptacek): http://krebsonsecurity.com/2012/06/how-companies-can-beef-up-password-security/
1258 Speed Hashing: http://www.codinghorror.com/blog/2012/04/speed-hashing.html
1259 Password security: past, present, future: http://www.openwall.com/presentations/PHDays2012-Password-Security/
1260 Password Storage Cheat Sheet: https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet
1261 Enough With The Rainbow Tables: What You Need To Know About Secure Password Schemes: http://www.securityfocus.com/blogs/262
1262 The Importance of Being Canonical: http://erratasec.blogspot.com/2009/02/importance-of-being-canonical.html
1263 Password Hashing: http://phpsec.org/articles/2005/password-hashing.html
1264 Rainbow Hash Cracking: http://www.codinghorror.com/blog/archives/000949.html
1265 Rainbow table: http://en.wikipedia.org/wiki/Rainbow_table
1266 Writing Secure Code: Chapter 9, ""Creating a Salted Hash"" Page 302
1267 The Art of Software Security Assessment: Chapter 2, ""Salt Values"", Page 46.
1268 How To Safely Store A Password: http://codahale.com/how-to-safely-store-a-password/
1269 Our password hashing has no clothes: http://www.troyhunt.com/2012/06/our-password-hashing-has-no-clothes.html
1270 Should we really use bcrypt/scrypt?: http://www.analyticalengine.net/2012/06/should-we-really-use-bcryptscrypt/"
1271 CWE-761,EN-Free of Pointer not at Start of Buffer (Type: Variant),"The application calls free() on a pointer to a memory resource that was allocated on the heap, but the pointer is not at the start of the buffer.","This can cause the application to crash, or in some cases, modify critical program variables or execute code.
1272 This weakness often occurs when the memory is allocated explicitly on the heap with one of the malloc() family functions and free() is called, but pointer arithmetic has caused the pointer to be in the interior or end of the buffer.",,Unknown,"boost C++ Library Smart Pointers: http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/smart_ptr.htm
1273 Valgrind: http://valgrind.org/"
1274 CWE-763,EN-Release of Invalid Pointer or Reference (Type: Base),"The application attempts to return a memory resource to the system, but calls the wrong release function or calls the appropriate release function incorrectly.","This weakness can take several forms, such as:
1275 The memory was allocated, explicitly or implicitly, via one memory management method and deallocated using a different, non-compatible function (CWE-762).
1276 The function calls or memory management routines chosen are appropriate, however they are used incorrectly, such as in CWE-761.",,Unknown,"boost C++ Library Smart Pointers: http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/smart_ptr.htm
1277 Valgrind: http://valgrind.org/"
1278 CWE-764,EN-Multiple Locks of a Critical Resource (Type: Variant),"The software locks a critical resource more times than intended, leading to an unexpected state in the system.","When software is operating in a concurrent environment and repeatedly locks a critical resource, the consequences will vary based on the type of lock, the lock's implementation, and the resource being protected. In some situations such as with semaphores, the resources are pooled and extra locking calls will reduce the size of the total available pool, possibly leading to degraded performance or a denial of service. If this can be triggered by an attacker, it will be similar to an unrestricted lock (CWE-412). In the context of a binary lock, it is likely that any duplicate locking attempts will never succeed since the lock is already held and progress may not be possible.",,Unknown,
1279 CWE-765,EN-Multiple Unlocks of a Critical Resource (Type: Variant),"The software unlocks a critical resource more times than intended, leading to an unexpected state in the system.","When software is operating in a concurrent environment and repeatedly unlocks a critical resource, the consequences will vary based on the type of lock, the lock's implementation, and the resource being protected. In some situations such as with semaphores, the resources are pooled and extra calls to unlock will increase the count for the number of available resources, likely resulting in a crash or unpredictable behavior when the system nears capacity.",,Unknown,
1280 CWE-785,EN-Use of Path Manipulation Function without Maximum-sized Buffer (Type: Variant),"The software invokes a function for normalizing paths or file names, but it provides an output buffer that is smaller than the maximum possible size, such as PATH_MAX.","Passing an inadequately-sized output buffer to a path manipulation function can result in a buffer overflow. Such functions include realpath(), readlink(), PathAppend(), and others.",,Unknown,
1281 CWE-786,EN-Access of Memory Location Before Start of Buffer (Type: Base),The software reads or writes to a buffer using an index or pointer that references a memory location prior to the beginning of the buffer.,"This typically occurs when a pointer or its index is decremented to a position before the buffer, when pointer arithmetic results in a position before the beginning of the valid memory location, or when a negative index is used.",,Unknown,
1282 CWE-787,EN-Out-of-bounds Write (Type: Base),"The software writes data past the end, or before the beginning, of the intended buffer.","This typically occurs when the pointer or its index is incremented or decremented to a position beyond the bounds of the buffer or when pointer arithmetic results in a position outside of the valid memory location to name a few. This may result in corruption of sensitive information, a crash, or code execution among other things.",,Unknown,
1283 CWE-788,EN-Access of Memory Location After End of Buffer (Type: Base),The software reads or writes to a buffer using an index or pointer that references a memory location after the end of the buffer.,"This typically occurs when a pointer or its index is decremented to a position before the buffer, when pointer arithmetic results in a position before the beginning of the valid memory location, or when a negative index is used. These problems may be resultant from missing sentinel values (CWE-463) or trusting a user-influenced input length variable.",,Unknown,
1284 CWE-790,EN-Improper Filtering of Special Elements (Type: Class),"The software receives data from an upstream component, but does not filter or incorrectly filters special elements before sending it to a downstream component.","Cross-site scripting (XSS) vulnerabilities occur when:
1285 1. Untrusted data enters a web application, typically from a web request.
1286 2. The web application dynamically generates a web page that contains this untrusted data.
1287 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.
1288 4. A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
1289 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.
1290 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.
1291 There are three main kinds of XSS:
1292 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.
1293 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 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.
1294 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.
1295 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.""
1296 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.",,Unknown,
1297 CWE-791,EN-Incomplete Filtering of Special Elements (Type: Base),"The software receives data from an upstream component, but does not completely filter special elements before sending it to a downstream component.","Cross-site scripting (XSS) vulnerabilities occur when:
1298 1. Untrusted data enters a web application, typically from a web request.
1299 2. The web application dynamically generates a web page that contains this untrusted data.
1300 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.
1301 4. A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
1302 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.
1303 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.
1304 There are three main kinds of XSS:
1305 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.
1306 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 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.
1307 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.
1308 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.""
1309 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.",,Unknown,
1310 CWE-792,EN-Incomplete Filtering of One or More Instances of Special Elements (Type: Variant),"The software receives data from an upstream component, but does not completely filter one or more instances of special elements before sending it to a downstream component.","Incomplete filtering of this nature involves either
1311 only filtering a single instance of a special element when more exist, or
1312 not filtering all instances or all elements where multiple special elements exist.",,Unknown,
1313 CWE-793,EN-Only Filtering One Instance of a Special Element (Type: Variant),"The software receives data from an upstream component, but only filters a single instance of a special element before sending it to a downstream component.","Incomplete filtering of this nature may be location-dependent, as in only the first or last element is filtered.",,Unknown,
1314 CWE-794,EN-Incomplete Filtering of Multiple Instances of Special Elements (Type: Variant),"The software receives data from an upstream component, but does not filter all instances of a special element before sending it to a downstream component.","Incomplete filtering of this nature may be applied to
1315 sequential elements (special elements that appear next to each other) or
1316 non-sequential elements (special elements that appear multiple times in different locations).",,Unknown,
1317 CWE-795,EN-Only Filtering Special Elements at a Specified Location (Type: Base),"The software receives data from an upstream component, but only accounts for special elements at a specified location, thereby missing remaining special elements that may exist before sending it to a downstream component.","A filter might only account for instances of special elements when they occur:
1318 relative to a marker (e.g. ""at the beginning/end of string; the second argument""), or
1319 at an absolute position (e.g. ""byte number 10"").
1320 This may leave special elements in the data that did not match the filter position, but still may be dangerous.",,Unknown,
1321 CWE-796,EN-Only Filtering Special Elements Relative to a Marker (Type: Variant),"The software receives data from an upstream component, but only accounts for special elements positioned relative to a marker (e.g. ""at the beginning/end of a string; the second argument""), thereby missing remaining special elements that may exist before sending it to a downstream component.","A filter might only account for instances of special elements when they occur:
1322 relative to a marker (e.g. ""at the beginning/end of string; the second argument""), or
1323 at an absolute position (e.g. ""byte number 10"").
1324 This may leave special elements in the data that did not match the filter position, but still may be dangerous.",,Unknown,
1325 CWE-797,EN-Only Filtering Special Elements at an Absolute Position (Type: Variant),"The software receives data from an upstream component, but only accounts for special elements at an absolute position (e.g. ""byte number 10""), thereby missing remaining special elements that may exist before sending it to a downstream component.","A filter might only account for instances of special elements when they occur:
1326 relative to a marker (e.g. ""at the beginning/end of string; the second argument""), or
1327 at an absolute position (e.g. ""byte number 10"").
1328 This may leave special elements in the data that did not match the filter position, but still may be dangerous.",,Unknown,
1329 CWE-799,EN-Improper Control of Interaction Frequency (Type: Class),"The software does not properly limit the number or frequency of interactions that it has with an actor, such as the number of incoming requests.","This can allow the actor to perform actions more frequently than expected. The actor could be a human or an automated process such as a virus or bot. This could be used to cause a denial of service, compromise program logic (such as limiting humans to a single vote), or other consequences. For example, an authentication routine might not limit the number of times an attacker can guess a password. Or, a web site might conduct a poll but only expect humans to vote a maximum of once a day.",,Unknown,Insufficient Anti-automation: http://projects.webappsec.org/Insufficient+Anti-automation
1330 CWE-8,EN-J2EE Misconfiguration: Entity Bean Declared Remote (Type: Variant),"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.","This can allow the actor to perform actions more frequently than expected. The actor could be a human or an automated process such as a virus or bot. This could be used to cause a denial of service, compromise program logic (such as limiting humans to a single vote), or other consequences. For example, an authentication routine might not limit the number of times an attacker can guess a password. Or, a web site might conduct a poll but only expect humans to vote a maximum of once a day.",,Unknown,
1331 CWE-81,EN-Improper Neutralization of Script in an Error Message Web Page (Type: Variant),"The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special characters that could be interpreted as web-scripting elements when they are sent to an error page.","Error pages may include customized 403 Forbidden or 404 Not Found pages.
1332 When an attacker can trigger an error that contains unneutralized input, then cross-site scripting attacks may be possible.",,Unknown,"24 Deadly Sins of Software Security: ""Sin 11: Failure to Handle Errors Correctly."" Page 183"
1333 CWE-82,EN-Improper Neutralization of Script in Attributes of IMG Tags in a Web Page (Type: Variant),"The web application does not neutralize or incorrectly neutralizes scripting elements within attributes of HTML IMG tags, such as the src attribute.","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.",,Unknown,
1334 CWE-820,EN-Missing Synchronization (Type: Base),The software utilizes a shared resource in a concurrent manner but does not attempt to synchronize access to the resource.,"If access to a shared resource is not synchronized, then the resource may not be in a state that is expected by the software. This might lead to unexpected or insecure behaviors, especially if an attacker can influence the shared resource.",,Unknown,
1335 CWE-821,EN-Incorrect Synchronization (Type: Base),The software utilizes a shared resource in a concurrent manner but it does not correctly synchronize access to the resource.,"If access to a shared resource is not correctly synchronized, then the resource may not be in a state that is expected by the software. This might lead to unexpected or insecure behaviors, especially if an attacker can influence the shared resource.",,Unknown,
1336 CWE-822,EN-Untrusted Pointer Dereference (Type: Base),"The program obtains a value from an untrusted source, converts this value to a pointer, and dereferences the resulting pointer.","An attacker can supply a pointer for memory locations that the program is not expecting. If the pointer is dereferenced for a write operation, the attack might allow modification of critical program state variables, cause a crash, or execute code. If the dereferencing operation is for a read, then the attack might allow reading of sensitive data, cause a crash, or set a program variable to an unexpected value (since the value will be read from an unexpected memory location).
1337 There are several variants of this weakness, including but not necessarily limited to:
1338 The untrusted value is directly invoked as a function call.
1339 In OS kernels or drivers where there is a boundary between ""userland"" and privileged memory spaces, an untrusted pointer might enter through an API or system call (see CWE-781 for one such example).
1340 Inadvertently accepting the value from an untrusted control sphere when it did not have to be accepted as input at all. This might occur when the code was originally developed to be run by a single user in a non-networked environment, and the code is then ported to or otherwise exposed to a networked environment.",,Unknown,
1341 CWE-823,EN-Use of Out-of-range Pointer Offset (Type: Base),"The program performs pointer arithmetic on a valid pointer, but it uses an offset that can point outside of the intended range of valid memory locations for the resulting pointer.","While a pointer can contain a reference to any arbitrary memory location, a program typically only intends to use the pointer to access limited portions of memory, such as contiguous memory used to access an individual array.
1342 Programs may use offsets in order to access fields or sub-elements stored within structured data. The offset might be out-of-range if it comes from an untrusted source, is the result of an incorrect calculation, or occurs because of another error.
1343 If an attacker can control or influence the offset so that it points outside of the intended boundaries of the structure, then the attacker may be able to read or write to memory locations that are used elsewhere in the program. As a result, the attack might change the state of the software as accessed through program variables, cause a crash or instable behavior, and possibly lead to code execution.",,Unknown,"The Art of Software Security Assessment: Chapter 6, ""Pointer Arithmetic"", Page 277."
1344 CWE-824,EN-Access of Uninitialized Pointer (Type: Base),The program accesses or uses a pointer that has not been initialized.,"If the pointer contains an uninitialized value, then the value might not point to a valid memory location. This could cause the program to read from or write to unexpected memory locations, leading to a denial of service. If the uninitialized pointer is used as a function call, then arbitrary functions could be invoked. If an attacker can influence the portion of uninitialized memory that is contained in the pointer, this weakness could be leveraged to execute code or perform other attacks.
1345 Depending on memory layout, associated memory management behaviors, and program operation, the attacker might be able to influence the contents of the uninitialized pointer, thus gaining more fine-grained control of the memory location to be accessed.",,Unknown,"The Art of Software Security Assessment: Chapter 7, ""Variable Initialization"", Page 312."
1346 CWE-825,EN-Expired Pointer Dereference (Type: Base),"The program dereferences a pointer that contains a location for memory that was previously valid, but is no longer valid.","When a program releases memory, but it maintains a pointer to that memory, then the memory might be re-allocated at a later time. If the original pointer is accessed to read or write data, then this could cause the program to read or modify data that is in use by a different function or process. Depending on how the newly-allocated memory is used, this could lead to a denial of service, information exposure, or code execution.",,Unknown,
1347 CWE-826,EN-Premature Release of Resource During Expected Lifetime (Type: Base),The program releases a resource that is still intended to be used by the program itself or another actor.,"This weakness focuses on errors in which the program should not release a resource, but performs the release anyway. This is different than a weakness in which the program releases a resource at the appropriate time, but it maintains a reference to the resource, which it later accesses. For this weaknesses, the resource should still be valid upon the subsequent access.
1348 When a program releases a resource that is still being used, it is possible that operations will still be taken on this resource, which may have been repurposed in the meantime, leading to issues similar to CWE-825. Consequences may include denial of service, information exposure, or code execution.",,Unknown,
1349 CWE-827,EN-Improper Control of Document Type Definition (Type: Base),"The software does not restrict a reference to a Document Type Definition (DTD) to the intended control sphere. This might allow attackers to reference arbitrary DTDs, possibly causing the software to expose files, consume excessive system resources, or execute arbitrary http requests on behalf of the attacker.","As DTDs are processed, they might try to read or include files on the machine performing the parsing. If an attacker is able to control the DTD, then the attacker might be able to specify sensitive resources or requests or provide malicious content.
1350 For example, the SOAP specification prohibits SOAP messages from containing DTDs.",,Unknown,Apache CXF Security Advisory (CVE-2010-2076): http://svn.apache.org/repos/asf/cxf/trunk/security/CVE-2010-2076.pdf
1351 CWE-828,EN-Signal Handler with Functionality that is not Asynchronous-Safe (Type: Base),"The software defines a signal handler that contains code sequences that are not asynchronous-safe, i.e., the functionality is not reentrant, or it can be interrupted.","This can lead to an unexpected system state with a variety of potential consequences depending on context, including denial of service and code execution.
1352 Signal handlers are typically intended to interrupt normal functionality of a program, or even other signals, in order to notify the process of an event. When a signal handler uses global or static variables, or invokes functions that ultimately depend on such state or its associated metadata, then it could corrupt system state that is being used by normal functionality. This could subject the program to race conditions or other weaknesses that allow an attacker to cause the program state to be corrupted. While denial of service is frequently the consequence, in some cases this weakness could be leveraged for code execution.
1353 There are several different scenarios that introduce this issue:
1354 Invocation of non-reentrant functions from within the handler. One example is malloc(), which modifies internal global variables as it manages memory. Very few functions are actually reentrant.
1355 Code sequences (not necessarily function calls) contain non-atomic use of global variables, or associated metadata or structures, that can be accessed by other functionality of the program, including other signal handlers. Frequently, the same function is registered to handle multiple signals.
1356 The signal handler function is intended to run at most one time, but instead it can be invoked multiple times. This could happen by repeated delivery of the same signal, or by delivery of different signals that have the same handler function (CWE-831).
1357 Note that in some environments or contexts, it might be possible for the signal handler to be interrupted itself.
1358 If both a signal handler and the normal behavior of the software have to operate on the same set of state variables, and a signal is received in the middle of the normal execution's modifications of those variables, the variables may be in an incorrect or corrupt state during signal handler execution, and possibly still incorrect or corrupt upon return.",,Unknown,"Delivering Signals for Fun and Profit: http://lcamtuf.coredump.cx/signals.txt
1359 Race Condition: Signal Handling: http://www.fortify.com/vulncat/en/vulncat/cpp/race_condition_signal_handling.html"
1360 CWE-829,EN-Inclusion of Functionality from Untrusted Control Sphere (Type: Class),"The software imports, requires, or includes executable functionality (such as a library) from a source that is outside of the intended control sphere.","When including third-party functionality, such as a web widget, library, or other source of functionality, the software must effectively trust that functionality. Without sufficient protection mechanisms, the functionality could be malicious in nature (either by coming from an untrusted source, being spoofed, or being modified in transit from a trusted source). The functionality might also contain its own weaknesses, or grant access to additional functionality and state information that should be kept private to the base system, such as system state information, sensitive application data, or the DOM of a web application.
1361 This might lead to many different consequences depending on the included functionality, but some examples include injection of malware, information exposure by granting excessive privileges or permissions to the untrusted functionality, DOM-based XSS vulnerabilities, stealing user's cookies, or open redirect to malware (CWE-601).",,Unknown,"OWASP Enterprise Security API (ESAPI) Project: http://www.owasp.org/index.php/ESAPI
1362 Least Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html"
1363 CWE-83,EN-Improper Neutralization of Script in Attributes in a Web Page (Type: Variant),"The software does not neutralize or incorrectly neutralizes ""javascript:"" or other URIs from dangerous attributes within tags, such as onmouseover, onload, onerror, or style.","When including third-party functionality, such as a web widget, library, or other source of functionality, the software must effectively trust that functionality. Without sufficient protection mechanisms, the functionality could be malicious in nature (either by coming from an untrusted source, being spoofed, or being modified in transit from a trusted source). The functionality might also contain its own weaknesses, or grant access to additional functionality and state information that should be kept private to the base system, such as system state information, sensitive application data, or the DOM of a web application.
1364 This might lead to many different consequences depending on the included functionality, but some examples include injection of malware, information exposure by granting excessive privileges or permissions to the untrusted functionality, DOM-based XSS vulnerabilities, stealing user's cookies, or open redirect to malware (CWE-601).",,Unknown,
1365 CWE-830,EN-Inclusion of Web Functionality from an Untrusted Source (Type: Base),"The software includes web functionality (such as a web widget) from another domain, which causes it to operate within the domain of the software, potentially granting total access and control of the software to the untrusted source.","Including third party functionality in a web-based environment is risky, especially if the source of the functionality is untrusted.
1366 Even if the third party is a trusted source, the software may still be exposed to attacks and malicious behavior if that trusted source is compromised, or if the code is modified in transmission from the third party to the software.
1367 This weakness is common in ""mashup"" development on the web, which may include source functionality from other domains. For example, Javascript-based web widgets may be inserted by using '<SCRIPT SRC=""http://other.domain.here"">' tags, which causes the code to run in the domain of the software, not the remote site from which the widget was loaded. As a result, the included code has access to the local DOM, including cookies and other data that the developer might not want the remote site to be able to access.
1368 Such dependencies may be desirable, or even required, but sometimes programmers are not aware that a dependency exists.",,Unknown,Third-Party Web Widget Security FAQ: http://jeremiahgrossman.blogspot.com/2010/07/third-party-web-widget-security-faq.html
1369 CWE-831,EN-Signal Handler Function Associated with Multiple Signals (Type: Base),The software defines a function that is used as a handler for more than one signal.,"While sometimes intentional and safe, when the same function is used to handle multiple signals, a race condition could occur if the function uses any state outside of its local declaration, such as global variables or non-reentrant functions, or has any side effects.
1370 An attacker could send one signal that invokes the handler function; in many OSes, this will typically prevent the same signal from invoking the handler again, at least until the handler function has completed execution. However, the attacker could then send a different signal that is associated with the same handler function. This could interrupt the original handler function while it is still executing. If there is shared state, then the state could be corrupted. This can lead to a variety of potential consequences depending on context, including denial of service and code execution.
1371 Another rarely-explored possibility arises when the signal handler is only designed to be executed once (if at all). By sending multiple signals, an attacker could invoke the function more than once. This may generate extra, unintended side effects. A race condition might not even be necessary; the attacker could send one signal, wait until it is handled, then send the other signal.",,Unknown,"Delivering Signals for Fun and Profit: http://lcamtuf.coredump.cx/signals.txt
1372 Race Condition: Signal Handling: http://www.fortify.com/vulncat/en/vulncat/cpp/race_condition_signal_handling.html"
1373 CWE-832,EN-Unlock of a Resource that is not Locked (Type: Base),The software attempts to unlock a resource that is not locked.,"Depending on the locking functionality, an unlock of a non-locked resource might cause memory corruption or other modification to the resource (or its associated metadata that is used for tracking locks).",,Unknown,
1374 CWE-833,EN-Deadlock (Type: Base),"The software contains multiple threads or executable segments that are waiting for each other to release a necessary lock, resulting in deadlock.","Depending on the locking functionality, an unlock of a non-locked resource might cause memory corruption or other modification to the resource (or its associated metadata that is used for tracking locks).",,Unknown,"The Art of Software Security Assessment: Chapter 13, ""Synchronization Problems"" / ""Starvation and Deadlocks"", Page 760
1375 The Art of Software Security Assessment: Chapter 13, ""Starvation and Deadlocks"", Page 760.
1376 Secure Coding in C and C++: Chapter 7, ""Concurrency"", section ""Mutual Exclusion and Deadlock"", Page 248."
1377 CWE-834,EN-Excessive Iteration (Type: Base),The software performs an iteration or loop without sufficiently limiting the number of times that the loop is executed.,"If the iteration can be influenced by an attacker, this weakness could allow attackers to consume excessive resources such as CPU or memory. In many cases, a loop does not need to be infinite in order to cause enough resource consumption to adversely affect the software or its host system; it depends on the amount of resources consumed per iteration.",,Unknown,"The Art of Software Security Assessment: Chapter 7, ""Looping Constructs"", Page 327."
1378 CWE-835,EN-Loop with Unreachable Exit Condition (Infinite Loop) (Type: Base),"The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.","If the loop can be influenced by an attacker, this weakness could allow attackers to consume excessive resources such as CPU or memory.",,Unknown,"The Art of Software Security Assessment: Chapter 7, ""Looping Constructs"", Page 327."
1379 CWE-836,EN-Use of Password Hash Instead of Password for Authentication (Type: Base),"The software records password hashes in a data store, receives a hash of a password from a client, and compares the supplied hash to the hash obtained from the data store.","Some authentication mechanisms rely on the client to generate the hash for a password, possibly to reduce load on the server or avoid sending the password across the network. However, when the client is used to generate the hash, an attacker can bypass the authentication by obtaining a copy of the hash, e.g. by using SQL injection to compromise a database of authentication credentials, or by exploiting an information exposure. The attacker could then use a modified client to replay the stolen hash without having knowledge of the original password.
1380 As a result, the server-side comparison against a client-side hash does not provide any more security than the use of passwords without hashing.",,Unknown,
1381 CWE-837,"EN-Improper Enforcement of a Single, Unique Action (Type: Base)","The software requires that an actor should only be able to perform an action once, or to have only one unique action, but the software does not enforce or improperly enforces this restriction.","In various applications, a user is only expected to perform a certain action once, such as voting, requesting a refund, or making a purchase. When this restriction is not enforced, sometimes this can have security implications. For example, in a voting application, an attacker could attempt to ""stuff the ballot box"" by voting multiple times. If these votes are counted separately, then the attacker could directly affect who wins the vote. This could have significant business impact depending on the purpose of the software.",,Unknown,
1382 CWE-838,EN-Inappropriate Encoding for Output Context (Type: Base),"The software uses or specifies an encoding when generating output to a downstream component, but the specified encoding is not the same as the encoding that is expected by the downstream component.","This weakness can cause the downstream component to use a decoding method that produces different data than what the software intended to send. When the wrong encoding is used - even if closely related - the downstream component could decode the data incorrectly. This can have security consequences when the provided boundaries between control and data are inadvertently broken, because the resulting data could introduce control characters or special elements that were not sent by the software. The resulting data could then be used to bypass protection mechanisms such as input validation, and enable injection attacks.
1383 While using output encoding is essential for ensuring that communications between components are accurate, the use of the wrong encoding - even if closely related - could cause the downstream component to misinterpret the output.
1384 For example, HTML entity encoding is used for elements in the HTML body of a web page. However, a programmer might use entity encoding when generating output for that is used within an attribute of an HTML tag, which could contain functional Javascript that is not affected by the HTML encoding.
1385 While web applications have received the most attention for this problem, this weakness could potentially apply to any type of software that uses a communications stream that could support multiple encodings.",,Unknown,"Injection-safe templating languages: http://manicode.blogspot.com/2010/06/injection-safe-templating-languages_30.html
1386 Can we please stop saying that XSS is boring and easy to fix!: http://diniscruz.blogspot.com/2010/09/can-we-please-stop-saying-that-xss-is.html
1387 Canoe: XSS prevention via context-aware output encoding: http://blog.ivanristic.com/2010/09/introducing-canoe-context-aware-output-encoding-for-xss-prevention.html
1388 What is the Future of Automated XSS Defense Tools?: http://software-security.sans.org/downloads/appsec-2011-files/manico-appsec-future-tools.pdf
1389 XSS Attacks: Preventing XSS Attacks
1390 DOM based XSS Prevention Cheat Sheet: http://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet
1391 OWASP Enterprise Security API (ESAPI) Project: http://www.owasp.org/index.php/ESAPI"
1392 CWE-839,EN-Numeric Range Comparison Without Minimum Check (Type: Base),"The program checks a value to ensure that it does not exceed a maximum, but it does not verify that the value exceeds the minimum.","Some programs use signed integers or floats even when their values are only expected to be positive or 0. An input validation check might assume that the value is positive, and only check for the maximum value. If the value is negative, but the code assumes that the value is positive, this can produce an error. The error may have security consequences if the negative value is used for memory allocation, array access, buffer access, etc. Ultimately, the error could lead to a buffer overflow or other type of memory corruption.
1393 The use of a negative number in a positive-only context could have security implications for other types of resources. For example, a shopping cart might check that the user is not requesting more than 10 items, but a request for -3 items could cause the application to calculate a negative price and credit the attacker's account.",,Unknown,"The Art of Software Security Assessment: Chapter 6, ""Type Conversion Vulnerabilities"" Page 246.
1394 The Art of Software Security Assessment: Chapter 6, ""Comparisons"", Page 265."
1395 CWE-84,EN-Improper Neutralization of Encoded URI Schemes in a Web Page (Type: Variant),The web application improperly neutralizes user-controlled input for executable script disguised with URI encodings.,"Some programs use signed integers or floats even when their values are only expected to be positive or 0. An input validation check might assume that the value is positive, and only check for the maximum value. If the value is negative, but the code assumes that the value is positive, this can produce an error. The error may have security consequences if the negative value is used for memory allocation, array access, buffer access, etc. Ultimately, the error could lead to a buffer overflow or other type of memory corruption.
1396 The use of a negative number in a positive-only context could have security implications for other types of resources. For example, a shopping cart might check that the user is not requesting more than 10 items, but a request for -3 items could cause the application to calculate a negative price and credit the attacker's account.",,Unknown,
1397 CWE-841,EN-Improper Enforcement of Behavioral Workflow (Type: Base),"The software supports a session in which more than one behavior must be performed by an actor, but it does not properly ensure that the actor performs the behaviors in the required sequence.","By performing actions in an unexpected order, or by omitting steps, an attacker could manipulate the business logic of the software or cause it to enter an invalid state. In some cases, this can also expose resultant weaknesses.
1398 For example, a file-sharing protocol might require that an actor perform separate steps to provide a username, then a password, before being able to transfer files. If the file-sharing server accepts a password command followed by a transfer command, without any username being provided, the software might still perform the transfer.
1399 Note that this is different than CWE-696, which focuses on when the software performs actions in the wrong sequence; this entry is closely related, but it is focused on ensuring that the actor performs actions in the correct sequence.
1400 Workflow-related behaviors include:
1401 Steps are performed in the expected order.
1402 Required steps are not omitted.
1403 Steps are not interrupted.
1404 Steps are performed in a timely fashion.",,Unknown,"Business Logic Flaws and Yahoo Games: http://jeremiahgrossman.blogspot.com/2006/12/business-logic-flaws.html
1405 Seven Business Logic Flaws That Put Your Website At Risk: http://www.whitehatsec.com/home/assets/WP_bizlogic092407.pdf
1406 Business Logic Flaws: http://www.whitehatsec.com/home/solutions/BL_auction.html
1407 Insufficient Process Validation: http://projects.webappsec.org/w/page/13246943/Insufficient-Process-Validation
1408 Defying Logic: Theory, Design, and Implementation of Complex Systems for Testing Application Logic: http://www.slideshare.net/RafalLos/defying-logic-business-logic-testing-with-automation
1409 Real-Life Example of a 'Business Logic Defect' (Screen Shots!): http://h30501.www3.hp.com/t5/Following-the-White-Rabbit-A/Real-Life-Example-of-a-Business-Logic-Defect-Screen-Shots/ba-p/22581
1410 Toward Automated Detection of Logic Vulnerabilities in Web Applications: http://www.usenix.org/events/sec10/tech/full_papers/Felmetsger.pdf
1411 Designing a Framework Method for Secure Business Application Logic Integrity in e-Commerce Systems: http://ijns.femto.com.tw/contents/ijns-v12-n1/ijns-2011-v12-n1-p29-41.pdf"
1412 CWE-842,EN-Placement of User into Incorrect Group (Type: Base),The software or the administrator places a user into an incorrect group.,"If the incorrect group has more access or privileges than the intended group, the user might be able to bypass intended security policy to access unexpected resources or perform unexpected actions. The access-control system might not be able to detect malicious usage of this group membership.",,Unknown,
1413 CWE-843,EN-Access of Resource Using Incompatible Type (Type Confusion) (Type: Base),"The program allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type.","When the program accesses the resource using an incompatible type, this could trigger logical errors because the resource does not have expected properties. In languages without memory safety, such as C and C++, type confusion can lead to out-of-bounds memory access.
1414 While this weakness is frequently associated with unions when parsing data with many different embedded object types in C, it can be present in any application that can interpret the same variable or memory location in multiple ways.
1415 This weakness is not unique to C and C++. For example, errors in PHP applications can be triggered by providing array parameters when scalars are expected, or vice versa. Languages such as Perl, which perform automatic conversion of a variable of one type when it is accessed as if it were another type, can also contain these issues.",,Unknown,"Attacking Interoperability: http://www.azimuthsecurity.com/resources/bh2009_dowd_smith_dewey.pdf
1416 The Art of Software Security Assessment: Chapter 7, ""Type Confusion"", Page 319."
1417 CWE-85,EN-Doubled Character XSS Manipulations (Type: Variant),The web application does not filter user-controlled input for executable script disguised using doubling of the involved characters.,"When the program accesses the resource using an incompatible type, this could trigger logical errors because the resource does not have expected properties. In languages without memory safety, such as C and C++, type confusion can lead to out-of-bounds memory access.
1418 While this weakness is frequently associated with unions when parsing data with many different embedded object types in C, it can be present in any application that can interpret the same variable or memory location in multiple ways.
1419 This weakness is not unique to C and C++. For example, errors in PHP applications can be triggered by providing array parameters when scalars are expected, or vice versa. Languages such as Perl, which perform automatic conversion of a variable of one type when it is accessed as if it were another type, can also contain these issues.",,Unknown,
1420 CWE-86,EN-Improper Neutralization of Invalid Characters in Identifiers in Web Pages (Type: Variant),"The software does not neutralize or incorrectly neutralizes invalid characters or byte sequences in the middle of tag names, URI schemes, and other identifiers.","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.",,Unknown,
1421 CWE-87,EN-Improper Neutralization of Alternate XSS Syntax (Type: Variant),The software does not neutralize or incorrectly neutralizes user-controlled input for alternate script syntax.,"Assuming a user with a given identity, authorization is the process of determining whether that user can access a given resource, based on the user's privileges and any permissions or other access-control specifications that apply to the resource.
1422 When access control checks are incorrectly applied, users are able to access data or perform actions that they should not be allowed to perform. This can lead to a wide range of problems, including information exposures, denial of service, and arbitrary code execution.",,Unknown,
1423 CWE-88,EN-Argument Injection or Modification (Type: Base),"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.","Assuming a user with a given identity, authorization is the process of determining whether that user can access a given resource, based on the user's privileges and any permissions or other access-control specifications that apply to the resource.
1424 When access control checks are incorrectly applied, users are able to access data or perform actions that they should not be allowed to perform. This can lead to a wide range of problems, including information exposures, denial of service, and arbitrary code execution.",,Unknown,"Argument injection issues: http://www.securityfocus.com/archive/1/archive/1/460089/100/100/threaded
1425 The Art of Software Security Assessment: Chapter 10, ""The Argument Array"", Page 567."
1426 CWE-9,EN-J2EE Misconfiguration: Weak Access Permissions for EJB Methods (Type: Variant),"If elevated access rights are assigned to EJB methods, then an attacker can take advantage of the permissions to exploit the software system.","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.
1427 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.",,Unknown,
1428 CWE-90,EN-Improper Neutralization of Special Elements used in an LDAP Query (LDAP Injection) (Type: Base),"The software constructs all or part of an LDAP query using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended LDAP query when it is sent to a downstream component.","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.
1429 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.",,Unknown,Web Applications and LDAP Injection
1430 CWE-91,EN-XML Injection (aka Blind XPath Injection) (Type: Base),"The software does not properly neutralize special elements 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.","Within XML, special elements could include reserved words or characters such as ""<"", "">"", """""", and ""&"", which could then be used to add new data or modify XML syntax.",,Unknown,"Blind XPath Injection: http://www.modsecurity.org/archive/amit/blind-xpath-injection.pdf
1431 The Art of Software Security Assessment: Chapter 17, ""XML Injection"", Page 1069."
1432 CWE-912,EN-Hidden Functionality (Type: Class),"The software contains functionality that is not documented, not part of the specification, and not accessible through an interface or command sequence that is obvious to the software's users or administrators.","Hidden functionality can take many forms, such as intentionally malicious code, ""Easter Eggs"" that contain extraneous functionality such as games, developer-friendly shortcuts that reduce maintenance or support costs such as hard-coded accounts, etc. From a security perspective, even when the functionality is not intentionally malicious or damaging, it can increase the software's attack surface and expose additional weaknesses beyond what is already exposed by the intended functionality. Even if it is not easily accessible, the hidden functionality could be useful for attacks that modify the control flow of the application.",,Unknown,
1433 CWE-913,EN-Improper Control of Dynamically-Managed Code Resources (Type: Class),"The software does not properly restrict reading from or writing to dynamically-managed code resources such as variables, objects, classes, attributes, functions, or executable instructions or statements.","Many languages offer powerful features that allow the programmer to dynamically create or modify existing code, or resources used by code such as variables and objects. While these features can offer significant flexibility and reduce development time, they can be extremely dangerous if attackers can directly influence these code resources in unexpected ways.",,Unknown,
1434 CWE-914,EN-Improper Control of Dynamically-Identified Variables (Type: Base),The software does not properly restrict reading from or writing to dynamically-identified variables.,"Many languages offer powerful features that allow the programmer to access arbitrary variables that are specified by an input string. While these features can offer significant flexibility and reduce development time, they can be extremely dangerous if attackers can modify unintended variables that have security implications.",,Unknown,
1435 CWE-915,EN-Improperly Controlled Modification of Dynamically-Determined Object Attributes (Type: Base),"The software receives input from an upstream component that specifies multiple attributes, properties, or fields that are to be initialized or updated in an object, but it does not properly control which attributes can be modified.","If the object contains attributes that were only intended for internal use, then their unexpected modification could lead to a vulnerability.
1436 This weakness is sometimes known by the language-specific mechanisms that make it possible, such as mass assignment, autobinding, or object injection.",,Unknown,"Shocking News in PHP Exploitation: http://www.suspekt.org/downloads/POC2009-ShockingNewsInPHPExploitation.pdf
1437 ""Two Security Vulnerabilities in the Spring Framework's MVC"" pdf (from 2008): http://blog.diniscruz.com/2011/07/two-security-vulnerabilities-in-spring.html
1438 Two Security Vulnerabilities in the Spring Framework's MVC: http://o2platform.files.wordpress.com/2011/07/ounce_springframework_vulnerabilities.pdf
1439 Best Practices for ASP.NET MVC: http://blogs.msdn.com/b/aspnetue/archive/2010/09/17/second_2d00_post.aspx
1440 Mass assignment in Rails applications: http://blog.mhartl.com/2008/09/21/mass-assignment-in-rails-applications/
1441 Secure your Rails apps!: http://pragtob.wordpress.com/2012/03/06/secure-your-rails-apps/
1442 Ruby On Rails Security Guide: http://guides.rubyonrails.org/security.html#mass-assignment
1443 Mass Assignment Vulnerability in ASP.NET MVC: http://freshbrewedcode.com/joshbush/2012/03/05/mass-assignment-aspnet-mvc/
1444 6 Ways To Avoid Mass Assignment in ASP.NET MVC: http://odetocode.com/blogs/scott/archive/2012/03/11/complete-guide-to-mass-assignment-in-asp-net-mvc.aspx
1445 PHP Object Injection: https://www.owasp.org/index.php/PHP_Object_Injection
1446 Unserializing user-supplied data, a bad idea: http://heine.familiedeelstra.com/security/unserialize
1447 Why Python Pickle is Insecure: http://nadiana.com/python-pickle-insecure"
1448 CWE-916,EN-Use of Password Hash With Insufficient Computational Effort (Type: Base),"The software generates a hash for a password, but it uses a scheme that does not provide a sufficient level of computational effort that would make password cracking attacks infeasible or expensive.","Many password storage mechanisms compute a hash and store the hash, instead of storing the original password in plaintext. In this design, authentication involves accepting an incoming password, computing its hash, and comparing it to the stored hash.
1449 Many hash algorithms are designed to execute quickly with minimal overhead, even cryptographic hashes. However, this efficiency is a problem for password storage, because it can reduce an attacker's workload for brute-force password cracking. If an attacker can obtain the hashes through some other method (such as SQL injection on a database that stores hashes), then the attacker can store the hashes offline and use various techniques to crack the passwords by computing hashes efficiently. Without a built-in workload, modern attacks can compute large numbers of hashes, or even exhaust the entire space of all possible passwords, within a very short amount of time, using massively-parallel computing (such as cloud computing) and GPU, ASIC, or FPGA hardware. In such a scenario, an efficient hash algorithm helps the attacker.
1450 There are several properties of a hash scheme that are relevant to its strength against an offline, massively-parallel attack:
1451 The amount of CPU time required to compute the hash (""stretching"")
1452 The amount of memory required to compute the hash (""memory-hard"" operations)
1453 Including a random value, along with the password, as input to the hash computation (""salting"")
1454 Given a hash, there is no known way of determining a password that produces this hash value, other than by guessing possible passwords (""one-way"" hashing)
1455 Relative to the number of all possible hashes that can be generated by the scheme, there is a low likelihood of producing the same hash for multiple different inputs (""collision resistance"")
1456 Note that the security requirements for the software may vary depending on the environment and the value of the passwords. Different schemes might not provide all of these properties, yet may still provide sufficient security for the environment. Conversely, a solution might be very strong in preserving one property, which still being very weak for an attack against another property, or it might not be able to significantly reduce the efficiency of a massively-parallel attack.",,Unknown,"bcrypt: http://bcrypt.sourceforge.net/
1457 Tarsnap - The scrypt key derivation function and encryption utility: http://www.tarsnap.com/scrypt.html
1458 RFC2898 - PKCS #5: Password-Based Cryptography Specification Version 2.0: http://tools.ietf.org/html/rfc2898
1459 How Companies Can Beef Up Password Security (interview with Thomas H. Ptacek): http://krebsonsecurity.com/2012/06/how-companies-can-beef-up-password-security/
1460 Speed Hashing: http://www.codinghorror.com/blog/2012/04/speed-hashing.html
1461 Password security: past, present, future: http://www.openwall.com/presentations/PHDays2012-Password-Security/
1462 Password Storage Cheat Sheet: https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet
1463 Enough With The Rainbow Tables: What You Need To Know About Secure Password Schemes: http://www.securityfocus.com/blogs/262
1464 How To Safely Store A Password: http://codahale.com/how-to-safely-store-a-password/
1465 Password hashing at scale: http://www.openwall.com/presentations/YaC2012-Password-Hashing-At-Scale/
1466 New developments in password hashing: ROM-port-hard functions: http://www.openwall.com/presentations/ZeroNights2012-New-In-Password-Hashing/
1467 The Importance of Being Canonical: http://erratasec.blogspot.com/2009/02/importance-of-being-canonical.html
1468 Our password hashing has no clothes: http://www.troyhunt.com/2012/06/our-password-hashing-has-no-clothes.html
1469 Should we really use bcrypt/scrypt?: http://www.analyticalengine.net/2012/06/should-we-really-use-bcryptscrypt/"
1470 CWE-917,EN-Improper Neutralization of Special Elements used in an Expression Language Statement (Expression Language Injection) (Type: Base),"The software constructs all or part of an expression language (EL) statement in a Java Server Page (JSP) using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended EL statement before it is executed.","Many password storage mechanisms compute a hash and store the hash, instead of storing the original password in plaintext. In this design, authentication involves accepting an incoming password, computing its hash, and comparing it to the stored hash.
1471 Many hash algorithms are designed to execute quickly with minimal overhead, even cryptographic hashes. However, this efficiency is a problem for password storage, because it can reduce an attacker's workload for brute-force password cracking. If an attacker can obtain the hashes through some other method (such as SQL injection on a database that stores hashes), then the attacker can store the hashes offline and use various techniques to crack the passwords by computing hashes efficiently. Without a built-in workload, modern attacks can compute large numbers of hashes, or even exhaust the entire space of all possible passwords, within a very short amount of time, using massively-parallel computing (such as cloud computing) and GPU, ASIC, or FPGA hardware. In such a scenario, an efficient hash algorithm helps the attacker.
1472 There are several properties of a hash scheme that are relevant to its strength against an offline, massively-parallel attack:
1473 The amount of CPU time required to compute the hash (""stretching"")
1474 The amount of memory required to compute the hash (""memory-hard"" operations)
1475 Including a random value, along with the password, as input to the hash computation (""salting"")
1476 Given a hash, there is no known way of determining a password that produces this hash value, other than by guessing possible passwords (""one-way"" hashing)
1477 Relative to the number of all possible hashes that can be generated by the scheme, there is a low likelihood of producing the same hash for multiple different inputs (""collision resistance"")
1478 Note that the security requirements for the software may vary depending on the environment and the value of the passwords. Different schemes might not provide all of these properties, yet may still provide sufficient security for the environment. Conversely, a solution might be very strong in preserving one property, which still being very weak for an attack against another property, or it might not be able to significantly reduce the efficiency of a massively-parallel attack.",,Unknown,"Expression Language Injection: http://www.mindedsecurity.com/fileshare/ExpressionLanguageInjection.pdf
1479 Remote Code with Expression Language Injection: http://danamodio.com/application-security/discoveries/spring-remote-code-with-expression-language-injection/"
1480 CWE-918,EN-Server-Side Request Forgery (SSRF) (Type: Base),"The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.","By providing URLs to unexpected hosts or ports, attackers can make it appear that the server is sending the request, possibly bypassing access controls such as firewalls that prevent the attackers from accessing the URLs directly. The server can be used as a proxy to conduct port scanning of hosts in internal networks, use other URLs such as that can access documents on the system (using file://), or use other protocols such as gopher:// or tftp://, which may provide greater control over the contents of requests.",,Unknown,"SSRF vs. Business-critical applications: XXE tunneling in SAP: https://media.blackhat.com/bh-us-12/Briefings/Polyakov/BH_US_12_Polyakov_SSRF_Business_Slides.pdf
1481 SSRF vs. Business-critical Applications. Part 1: XXE Tunnelling in SAP NetWeaver: http://erpscan.com/wp-content/uploads/2012/08/SSRF-vs-Businness-critical-applications-whitepaper.pdf
1482 Cross Site Port Attacks - XSPA - Part 1: http://www.riyazwalikar.com/2012/11/cross-site-port-attacks-xspa-part-1.html
1483 Cross Site Port Attacks - XSPA - Part 2: http://www.riyazwalikar.com/2012/11/cross-site-port-attacks-xspa-part-2.html
1484 Cross Site Port Attacks - XSPA - Part 3: http://www.riyazwalikar.com/2012/11/cross-site-port-attacks-xspa-part-3.html
1485 SSRF attacks and sockets: smorgasbord of vulnerabilities: http://www.slideshare.net/d0znpp/ssrf-attacks-and-sockets-smorgasbord-of-vulnerabilities
1486 SSRF bible. Cheatsheet: https://docs.google.com/document/d/1v1TkWZtrhzRLy0bYXBcdLUedXGb9njTNIJXa3u9akHM/edit?pli=1#
1487 Web Portals: Gateway To Information, Or A Hole In Our Perimeter Defenses: http://www.shmoocon.org/2008/presentations/Web%20portals,%20gateway%20to%20information.ppt"
1488 CWE-92,EN-DEPRECATED: Improper Sanitization of Custom Special Characters (Type: Base),"This entry has been deprecated. It originally came from PLOVER, which 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-75 is a more appropriate mapping.","By providing URLs to unexpected hosts or ports, attackers can make it appear that the server is sending the request, possibly bypassing access controls such as firewalls that prevent the attackers from accessing the URLs directly. The server can be used as a proxy to conduct port scanning of hosts in internal networks, use other URLs such as that can access documents on the system (using file://), or use other protocols such as gopher:// or tftp://, which may provide greater control over the contents of requests.",,Unknown,
1489 CWE-920,EN-Improper Restriction of Power Consumption (Type: Base),"The software operates in an environment in which power is a limited resource that cannot be automatically replenished, but the software does not properly restrict the amount of power that its operation consumes.","In environments such as embedded or mobile devices, power can be a limited resource such as a battery, which cannot be automatically replenished by the software itself, and the device might not always be directly attached to a reliable power source. If the software uses too much power too quickly, then this could cause the device (and subsequently, the software) to stop functioning until power is restored, or increase the financial burden on the device owner because of increased power costs.
1490 Normal operation of an application will consume power. However, in some cases, an attacker could cause the application to consume more power than intended, using components such as:
1491 Display
1492 CPU
1493 Disk I/O
1494 GPS
1495 Sound
1496 Microphone
1497 USB interface",,Unknown,
1498 CWE-921,EN-Storage of Sensitive Data in a Mechanism without Access Control (Type: Base),The software stores sensitive information in a file system or device that does not have built-in access control.,"While many modern file systems or devices utilize some form of access control in order to restrict access to data, not all storage mechanisms have this capability. For example, memory cards, floppy disks, CDs, and USB devices are typically made accessible to any user within the system. This can become a problem when sensitive data is stored in these mechanisms in a multi-user environment, because anybody on the system can read or write this data.
1499 On Android devices, external storage is typically globally readable and writable by other applications on the device. External storage may also be easily accessible through the mobile device's USB connection or physically accessible through the device's memory card port.",,Unknown,Security Tips: http://developer.android.com/training/articles/security-tips.html#StoringData
1500 CWE-922,EN-Insecure Storage of Sensitive Information (Type: Class),The software stores sensitive information without properly limiting read or write access by unauthorized actors.,"If read access is not properly restricted, then attackers can steal the sensitive information. If write access is not properly restricted, then attackers can modify and possibly delete the data, causing incorrect results and possibly a denial of service.",,Unknown,
1501 CWE-923,EN-Improper Authentication of Endpoint in a Communication Channel (Type: Class),"The software establishes a communication channel to (or from) an endpoint for privileged or protected operations, but it does not properly authenticate the endpoint to ensure it is associated with the identity of the intended actor.","Attackers might be able to spoof the intended endpoint from a different system or process, thus gaining the same level of access as the intended endpoint.
1502 While this issue frequently involves authentication between network-based clients and servers, other types of communication channels and endpoints can have this weakness.",,Unknown,
1503 CWE-924,EN-Improper Enforcement of Message Integrity During Transmission in a Communication Channel (Type: Class),"The software establishes a communication channel with an endpoint and receives a message from that endpoint, but it does not sufficiently ensure that the message was not modified during transmission.",A man-in-the-middle (MITM) attacker might be able to modify the message and spoof the endpoint.,,Unknown,
1504 CWE-925,EN-Improper Verification of Intent by Broadcast Receiver (Type: Variant),"The Android application uses a Broadcast Receiver that receives an Intent but does not properly verify that the Intent came from an authorized source, e.g. by checking the action string.","Certain types of Intents, identified by action string, can only be broadcast by the operating system itself, not by third-party applications. However, when an application declares the ability for a component to receive broadcast messages, in most cases a malicious application can send an Intent with a non-reserved action string to that receiving component.",,Unknown,
1505 CWE-926,EN-Improper Restriction of Content Provider Export to Other Applications (Type: Variant),The Android application uses a Content Provider that does not properly restrict which applications can access the data that is offered by the Content Provider.,"Android's Content Provider mechanism can be used to share data with other applications or internally within the same application. If access to the Content Provider is not restricted to only the expected applications, then malicious applications might be able to access the sensitive data.
1506 This weakness could be expressed in several different ways:
1507 The Content Provider is only intended for internal use by the application, and thus does not need to be exported.
1508 In Android before 4.2, the Content Provider is automatically exported unless it has been explicitly declared as NOT exported.
1509 The Content Provider is intended for external use by some applications, but it does not properly limit access, e.g. by exporting with excessive permissions.",,Unknown,No description: http://developer.android.com/training/articles/security-tips.html#ContentProviders
1510 CWE-927,EN-Use of Implicit Intent for Sensitive Communication (Type: Variant),The Android application uses an implicit intent for transmitting sensitive data to other applications.,"Since an implicit intent does not specify a particular application to receive the data, any application can process the intent by using an Intent Filter for that intent. This can allow untrusted applications to obtain sensitive data.",,Unknown,"Analyzing Inter-Application Communication in Android: http://www.cs.berkeley.edu/~afelt/intentsecurity-mobisys.pdf
1511 Security Tips: http://developer.android.com/training/articles/security-tips.html#ContentProviders"
1512 CWE-96,EN-Improper Neutralization of Directives in Statically Saved Code (Static Code Injection) (Type: Base),"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.","This may allow an attacker to execute arbitrary code, or at least modify what code can be executed.",,Unknown,
1513 CWE-97,EN-Improper Neutralization of Server-Side Includes (SSI) Within a Web Page (Type: Variant),"The software generates a web page, but does not neutralize or incorrectly neutralizes user-controllable input that could be interpreted as a server-side include (SSI) directive.","This may allow an attacker to execute arbitrary code, or at least modify what code can be executed.",,Unknown,
1514 CWE-116,EN-Improper Encoding or Escaping of Output (Type: Class),"The software prepares a structured message for communication with another component, but encoding or escaping of the data is either missing or done incorrectly. As a result, the intended structure of the message is not preserved.","Improper encoding or escaping can allow attackers to change the commands that are sent to another component, inserting malicious commands instead.
1515 Most software follows a certain protocol that uses structured messages for communication between components, such as queries or commands. These structured messages can contain raw data interspersed with metadata or control information. For example, ""GET /index.html HTTP/1.1"" is a structured message containing a command (""GET"") with a single argument (""/index.html"") and metadata about which protocol version is being used (""HTTP/1.1"").
1516 If an application uses attacker-supplied inputs to construct a structured message without properly encoding or escaping, then the attacker could insert special characters that will cause the data to be interpreted as control information or metadata. Consequently, the component that receives the output will perform the wrong operations, or otherwise interpret the data incorrectly.",,Very High,"OWASP Enterprise Security API (ESAPI) Project: http://www.owasp.org/index.php/ESAPI
1517 Input validation or output filtering, which is better?: http://jeremiahgrossman.blogspot.com/2007/01/input-validation-or-output-filtering.html
1518 Output Sanitization: http://www.analyticalengine.net/archives/58
1519 Sanitizing user data: How and where to do it: http://www.diovo.com/2008/09/sanitizing-user-data-how-and-where-to-do-it/
1520 Input validation or output filtering, which is better?: http://jeremiahgrossman.blogspot.com/2007/01/input-validation-or-output-filtering.html
1521 Input Validation - Not That Important: http://manicode.blogspot.com/2008/08/input-validation-not-that-important.html
1522 Preventing XSS with Correct Output Encoding: http://phed.org/2008/05/19/preventing-xss-with-correct-output-encoding/
1523 Writing Secure Code: Chapter 11, ""Canonical Representation Issues"" Page 363"
1524 CWE-121,EN-Stack-based Buffer Overflow (Type: Variant),"A stack-based buffer overflow condition is a condition where the buffer being overwritten is allocated on the stack (i.e., is a local variable or, rarely, a parameter to a function).","A buffer overflow condition exists when a program attempts to put more data in a buffer than it can hold, or when a program attempts to put data in a memory area outside of the boundaries of a buffer. The simplest type of error, and the most common cause of buffer overflows, is the ""classic"" case in which the program copies the buffer without restricting how much is copied. Other variants exist, but the existence of a classic overflow strongly suggests that the programmer is not considering even the most basic of security protections.",,Very High,"Writing Secure Code: Chapter 5, ""Stack Overruns"" Page 129
1525 24 Deadly Sins of Software Security: ""Sin 5: Buffer Overruns."" Page 89
1526 The Art of Software Security Assessment: Chapter 3, ""Nonexecutable Stack"", Page 76.
1527 The Art of Software Security Assessment: Chapter 5, ""Protection Mechanisms"", Page 189."
1528 CWE-134,EN-Uncontrolled Format String (Type: Base),"The software uses externally-controlled format strings in printf-style functions, which can lead to buffer overflows or data representation problems.","If an attacker can manipulate the length parameter associated with an input such that it is inconsistent with the actual length of the input, this can be leveraged to cause the target application to behave in unexpected, and possibly, malicious ways. One of the possible motives for doing so is to pass in arbitrarily large input to the application. Another possible motivation is the modification of application state by including invalid data for subsequent properties of the application. Such weaknesses commonly lead to attacks such as buffer overflows and execution of arbitrary code.",,Very High,"Format String Vulnerabilities in Perl Programs: http://www.securityfocus.com/archive/1/418460/30/0/threaded
1529 Programming Language Format String Vulnerabilities: http://www.ddj.com/dept/security/197002914
1530 Format String Attacks: http://www.thenewsh.com/~newsham/format-string-attacks.pdf
1531 Writing Secure Code: Chapter 5, ""Format String Bugs"" Page 147
1532 24 Deadly Sins of Software Security: ""Sin 6: Format String Problems."" Page 109
1533 The Art of Software Security Assessment: Chapter 8, ""C Format Strings"", Page 422."
1534 CWE-256,EN-Plaintext Storage of a Password (Type: Variant),Storing a password in plaintext may result in a system compromise.,"Two common programmer assumptions are ""this function call can never fail"" and ""it doesn't matter if this function call fails"". If an attacker can force the function to fail or otherwise return a value that is not expected, then the subsequent program logic could lead to a vulnerability, because the software is not in a state that the programmer assumes. For example, if the program calls a function to drop privileges but does not check the return code to ensure that privileges were successfully dropped, then the program will continue to operate with the higher privileges.",,Very High,Building Secure Software: How to Avoid Security Problems the Right Way
1535 CWE-257,EN-Storing Passwords in a Recoverable Format (Type: Base),"The storage of passwords in a recoverable format makes them subject to password reuse attacks by malicious users. If a system administrator can recover a password directly, or use a brute force search on the available information, the administrator can use the password on other accounts.","Two common programmer assumptions are ""this function call can never fail"" and ""it doesn't matter if this function call fails"". If an attacker can force the function to fail or otherwise return a value that is not expected, then the subsequent program logic could lead to a vulnerability, because the software is not in a state that the programmer assumes. For example, if the program calls a function to drop privileges but does not check the return code to ensure that privileges were successfully dropped, then the program will continue to operate with the higher privileges.",,Very High,
1536 CWE-258,EN-Empty Password in Configuration File (Type: Variant),Using an empty string as a password is insecure.,"Two common programmer assumptions are ""this function call can never fail"" and ""it doesn't matter if this function call fails"". If an attacker can force the function to fail or otherwise return a value that is not expected, then the subsequent program logic could lead to a vulnerability, because the software is not in a state that the programmer assumes. For example, if the program calls a function to drop privileges but does not check the return code to ensure that privileges were successfully dropped, then the program will continue to operate with the higher privileges.",,Very High,Building Secure Software: How to Avoid Security Problems the Right Way
1537 CWE-259,EN-Use of Hard-coded Password (Type: Base),"The software contains a hard-coded password, which it uses for its own inbound authentication or for outbound communication to external components.","A hard-coded password typically leads to a significant authentication failure that can be difficult for the system administrator to detect. Once detected, it can be difficult to fix, so the administrator may be forced into disabling the product entirely. There are two main variations:
1538 Inbound: the software contains an authentication mechanism that checks for a hard-coded password.
1539 Outbound: the software connects to another system or component, and it contains hard-coded password for connecting to that component.
1540 In the Inbound variant, a default administration account is created, and a simple password is hard-coded into the product and associated with that account. This hard-coded password is the same for each installation of the product, and it usually cannot be changed or disabled by system administrators without manually modifying the program, or otherwise patching the software. If the password is ever discovered or published (a common occurrence on the Internet), then anybody with knowledge of this password can access the product. Finally, since all installations of the software will have the same password, even across different organizations, this enables massive attacks such as worms to take place.
1541 The Outbound variant applies to front-end systems that authenticate with a back-end service. The back-end service may require a fixed password which can be easily discovered. The programmer may simply hard-code those back-end credentials into the front-end software. Any user of that program may be able to extract the password. Client-side systems with hard-coded passwords pose even more of a threat, since the extraction of a password from a binary is usually very simple.",,Very High,"24 Deadly Sins of Software Security: ""Sin 19: Use of Weak Password-Based Systems."" Page 279"
1542 CWE-309,EN-Use of Password System for Primary Authentication (Type: Base),"The use of password systems as the primary means of authentication may be subject to several flaws or shortcomings, each reducing the effectiveness of the mechanism.","While the use of multiple authentication schemes is simply piling on more complexity on top of authentication, it is inestimably valuable to have such measures of redundancy. The use of weak, reused, and common passwords is rampant on the internet. Without the added protection of multiple authentication schemes, a single mistake can result in the compromise of an account. For this reason, if multiple schemes are possible and also easy to use, they should be implemented and required.",,Very High,
1543 CWE-74,EN-Improper Neutralization of Special Elements in Output Used by a Downstream Component (Injection) (Type: Class),"The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.","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.",,Very High,
1544 CWE-77,EN-Improper Neutralization of Special Elements used in a Command (Command Injection) (Type: Class),"The software constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.","Command injection vulnerabilities typically occur when:
1545 1. Data enters the application from an untrusted source.
1546 2. The data is part of a string that is executed as a command by the application.
1547 3. By executing the command, the application gives an attacker a privilege or capability that the attacker would not otherwise have.",,Very High,"Exploiting Software: How to Break Code
1548 24 Deadly Sins of Software Security: ""Sin 10: Command Injection."" Page 171"
1549 CWE-798,EN-Use of Hard-coded Credentials (Type: Base),"The software contains hard-coded credentials, such as a password or cryptographic key, which it uses for its own inbound authentication, outbound communication to external components, or encryption of internal data.","Hard-coded credentials typically create a significant hole that allows an attacker to bypass the authentication that has been configured by the software administrator. This hole might be difficult for the system administrator to detect. Even if detected, it can be difficult to fix, so the administrator may be forced into disabling the product entirely. There are two main variations:
1550 Inbound: the software contains an authentication mechanism that checks the input credentials against a hard-coded set of credentials.
1551 Outbound: the software connects to another system or component, and it contains hard-coded credentials for connecting to that component.
1552 In the Inbound variant, a default administration account is created, and a simple password is hard-coded into the product and associated with that account. This hard-coded password is the same for each installation of the product, and it usually cannot be changed or disabled by system administrators without manually modifying the program, or otherwise patching the software. If the password is ever discovered or published (a common occurrence on the Internet), then anybody with knowledge of this password can access the product. Finally, since all installations of the software will have the same password, even across different organizations, this enables massive attacks such as worms to take place.
1553 The Outbound variant applies to front-end systems that authenticate with a back-end service. The back-end service may require a fixed password which can be easily discovered. The programmer may simply hard-code those back-end credentials into the front-end software. Any user of that program may be able to extract the password. Client-side systems with hard-coded passwords pose even more of a threat, since the extraction of a password from a binary is usually very simple.",,Very High,"Writing Secure Code: Chapter 8, ""Key Management Issues"" Page 272
1554 Top 25 Series - Rank 11 - Hardcoded Credentials: http://blogs.sans.org/appsecstreetfighter/2010/03/10/top-25-series-rank-11-hardcoded-credentials/
1555 Mobile App Top 10 List: http://www.veracode.com/blog/2010/12/mobile-app-top-10-list/"
1556 CWE-89,EN-Improper Neutralization of Special Elements used in an SQL Command (SQL Injection) (Type: Base),"The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.","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.
1557 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.",,Very High,"24 Deadly Sins of Software Security: ""Sin 1: SQL Injection."" Page 3
1558 Writing Secure Code: Chapter 12, ""Database Input Issues"" Page 397
1559 SQL Injection Prevention Cheat Sheet: http://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
1560 SQL Injection Attacks by Example: http://www.unixwiz.net/techtips/sql-injection.html
1561 SQL Injection Cheat Sheet: http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/
1562 The Database Hacker's Handbook: Defending Database Servers
1563 The Oracle Hacker's Handbook: Hacking and Defending Oracle
1564 SQL Injection: http://msdn.microsoft.com/en-us/library/ms161953.aspx
1565 SQL Injection Attack: http://blogs.technet.com/swi/archive/2008/05/29/sql-injection-attack.aspx
1566 Giving SQL Injection the Respect it Deserves: http://blogs.msdn.com/sdl/archive/2008/05/15/giving-sql-injection-the-respect-it-deserves.aspx
1567 Top 25 Series - Rank 2 - SQL Injection: http://blogs.sans.org/appsecstreetfighter/2010/03/01/top-25-series-rank-2-sql-injection/
1568 Least Privilege: https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html
1569 The Art of Software Security Assessment: Chapter 8, ""SQL Queries"", Page 431.
1570 The Art of Software Security Assessment: Chapter 17, ""SQL Injection"", Page 1061."
1571 CWE-262,EN-Not Using Password Aging (Type: Variant),"If no mechanism is in place for managing password aging, users will have no incentive to update passwords in a timely manner.","This can result in compromise of the system for which the password is used. An attacker could gain access to this file and learn the stored password or worse yet, change the password to one of their choosing.",,Very Low,"24 Deadly Sins of Software Security: ""Sin 19: Use of Weak Password-Based Systems."" Page 279"
1572 CWE-263,EN-Password Aging with Long Expiration (Type: Base),Allowing password aging to occur unchecked can result in the possibility of diminished password integrity.,"Just as neglecting to include functionality for the management of password aging is dangerous, so is allowing password aging to continue unchecked. Passwords must be given a maximum life span, after which a user is required to update with a new and different password.",,Very Low,"24 Deadly Sins of Software Security: ""Sin 19: Use of Weak Password-Based Systems."" Page 279"
1573 CWE-768,ES-Incorrect Short Circuit Evaluation (Type: Variant),"The software contains a conditional statement with multiple logical expressions in which one of the non-leading expressions may produce side effects. This may lead to an unexpected state in the program after the execution of the conditional, because short-circuiting logic may prevent the side effects from occurring.",,"Usage of short circuit evaluation, though well-defined in the C standard, may alter control flow in a way that introduces logic errors that are difficult to detect, possibly causing errors later during the software's execution. If an attacker can discover such an inconsistency, it may be exploitable to gain arbitrary control over a system.
1574 If the first condition of an ""or"" statement is assumed to be true under normal circumstances, or if the first condition of an ""and"" statement is assumed to be false, then any subsequent conditional may contain its own logic errors that are not detected during code review or testing.
1575 Finally, the usage of short circuit evaluation may decrease the maintainability of the code.",Very Low,
1576 ,Metadatos,"250+ Archivos conteniendo metadatos: Usuarios, Carpetas, fechas de edicion y modificacion, software usado, Direccion de impresoras locales",,"Datos privados son revelados a traves de los metadatos de documentos hosteados en el dominio (PDF, WORD). Datos como nombres de usuario, versiones de sistemas operativos, versiones de software utilizados, fechas y horas de cada modificacion del documento, direcciones de red de impresoras, etc. Se recomienda limpiar de metadatos documentos que luego seran publicados en internet",,
1577 ,ES-Session Cookie without Secure flag set,"La cookie no tiene la marca de ""Secure"". Esto instruye al navegador que dicha cookie puede ser solo accedida por canales SSL.",,Si es posible se deberia habilitar la flag Secure para esta cookie,Low,
1578 ,ES-Session Cookie without HttpOnly flag Set,"La cookie de sesion no esta marcada como HTTPOnly, cuando una cookie es marcada de esta manera da instruccion al navegador que esa cookie puede ser accedida solamente por el servdor y no por script del lado del cliente. Es una importante proteccion de seguridad para las cookies de sesion",,Si es posible se deberia habilitar la flag HTTPOnly para esta cookie,Low,
1579 ,ES-Apache httpd Remote Denial of Service,"* Alerta generada por el flag del servidor: ver: 2.2.15 *
1580 Se ha detectado un problema en las versiones de apache 1.3.0, 2.0.x hasta 2.0.64 y 2.2.X hasta 2.2.19 que mediante una herramienta automatizada un atacante usand una moderada cantidad de request puede causar un uso significativo de memoria y CPU en el servidor. Datos: http://seclists.org/fulldisclosure/2011/Aug/175.",,Actualizar version de apache,Medium,
1581 ,ES-Robots.txt,Robots.txt revela directorios sensibles. Un atacante busca directamente robots.txt para encontrar puntos desde donde comenzar su ataque.,,"Es conveniente manejar nombres de directorios que no describan el contenido, en especial en directorios sensibles. Por ejemplo en lugar de /setup o /app_data llamar al directorio /Dir_Code1. De esta manera no revelar a un atacante que clase de informacion contiene un directorio, que se intenta ocultar de los buscadores (mediante robots.txt)
1582 Otra practica que se me ocurre es la utilizacion de parametros. Por ejemplo:
1583 Disallow: /*AB/$
1584 Esto desactivará cualquier carpeta que termine con ""AB"" por ejemplo /sourceAB/. Evitando pasar cualquier dato a un atacante y centralizando las carpetas sensibles y ocultandolas simplemente colocando ""AB"" al final.",Info,
1585 ,ES-Typical Login Web,"Archivo de Login nombrado de manera ""comun"".",,Esto facilita a los robots de ataque encontrar paginas sensibles. Se recomienda no usar nombres estandard para paginas de login.,,
1586 ,ES-Credentials en Texto Plano,Las Credenciales de usuario son trasmitidas por un canal sin cifrar y puede ser interceptada.,,Es altamente recomendable que las paginas de login se fuerzen a usar SSL (https),Medium,
1587 ,ES-Parametro __VIEWSTATE sin encriptar,"El parametro ""__VIEWSTATE"" no esta encriptado. Para reducir las posibilidades que alguien intercepte informacion guardada en ViewState es bueno encriptarlo.",,"Se recomienda encriptar el parametro ""__VIEWSTATE"", para hacer esto se debe setear el tipo de validacion a 3DES. Editar Web.Config y agregar la siguiente linea bajo <system.web>
1588 <machineKey validation=""3DES""/>",,
1589 ,ES-Insecure Captcha,"La resolucion del Captcha esta incluida en el mismo codigo:
1590
1591 <img id=""ctl01_mainContent_imgCaptcha"" src=""http://test-www.bancofalabella.com.co/Data/Sites/1/ImgTemp/ImageFormat_THHvB.png""
1592 style=""border-width:0px;"" />
1593
1594 Siendo la respuesta THHvB
1595
1596 Facilitando la manera de automatizar un script para atacar el form",,Se recomienda implementar un sistema de Captcha que la resolucion no se incluya en el codigo.,,
1597 ,"ES-Mensaje de error de la aplicacion
1598 (Application error message)","El server responde con mensajes de error internos que no deberián mostrarse, facilitando de esta manera informacion que puede ser sensible o util para un atacante. Pudiendo de esta manera obtener datos para mejorar su vector de ataque",,"Se recomienda deshabilitar los mensajes de error, para no proporcionar información de la tecnología o software implementado.
1599
1600 ",Low,
1601 ,ES-Apache httpOnly Cookie Disclosure,"El servidor Apache version 2.2.X hasta la 2.2.21 no restringe correctamente la informacion mostrada en la contrsuccion del error "" Bad Request "" (aka 400) permitiendo a un atacante obtener los parametros de HTTPOnly.
1602 Datos: http://fd.the-wildcat.de/apache_e36a9cf46c.php",,Actualizar el apache. La version 2.2.22 es la primer version que soluciona este problema.,Medium,
1603 ,ES-Input de Contraseña con Autocompletar,"Un form de login con autocompletar sugiere un problema de seguridad, sobretodo para los usuarios que utilizan el servicio desde computadoras publicas.",,"Se recomienta establecer el input con Autocomplete OFF:
1604 <INPUT TYPE=""password"" AUTOCOMPLETE=""off"">",Low,
1605 ,ES-Archivos de Backup,"Los archivos de Backup pueden contener codigo fuente de script, archivos de configuracion u otra informacion sensible que puede ayudar a un atacante a conocer el servidor y preparar ataques mas avanzados o especificos.",,Remover el/los archivo(s) si no son requeridos en el servidor en produccion. Como un paso adicional es recomendado implementar una politica de seguridad para no permitir la creacion de archivos de backup en directorios accesibles desde la web.,,
1606 ,ES-Possible sensitive directories,"Un posible directorio sensible fue encotnrado. Este directorio no esta directamente linkeado en el servidor Web.Se chekeo usando nombres comunes para directorios de configuracion, backups, bajadas de bases de datos, paginas de administracion, archivos temporales, etc. Usar nombres comunes de directorios para almacenar este tipo de informacion facilita a usuarios maliciosos buscar archivos sensibles.",,"Se recomienda llamar a estos directorios de manera no estandard, por ejemplo:
1607 config-->c0nfig05
1608 backup-->b4ccup
1609 Aunque es aun mas recomendabl, de ser posible, no dejar directorios de backup, configuracion, etc accesibles directamente desde la web",,
1610 ,ES-Slow HTTP Denial of Service Attack,"Los ataques conocidos como ""Slowloris"" y ""Slow HTTP POST DoS"" se basan en el hecho de que el protocolo HTTP, por diseño, requiere que las consultas esten completamente recividas por el servidor antes de poder ser procesadas. Si la consulta HTTP no esta completa, o si la tranferencia es muy lenta, el servidor mantiene recursos ocupados esperando el resto de la informacion. Si el servidor mantiene demasiados recursos ocupados, esto crea una denegacion de servicio.",,Es importante establecer los tiempos de espera del servidor. Se adjunta link de recomendacion para evitar este tipo de ataques: https://community.qualys.com/blogs/securitylabs/2011/11/02/how-to-protect-against-slow-http-attacks,Medium,
1611 ,ES-Clickjacking,"No se encuentra ningún tipo de impedimento para evitar que la web sea embebida dentro de un iframe. Esta restricción es importante ya que un atacante podría engañar a un usuario autenticado a realizar operaciones mediante un engaño llamado Clickjacking donde la víctima se le presenta una web, posiblemente con algun juego, utilizando algunos engaños de interfaz la victima podria ser engañada a aprobar una venta. Ref:http://javascript.info/tutorial/clickjacking",,"Todos los browsers modernos son capaces de interpretar los valores seteados en X-Frame-Options, si los mismos son incluidos en el Header del servidor.",Low,
1612 ,"ES-XSS Cross Site Scripting
1613 (Secuencias de comandos en sitios cruzados)","Es posible injectar tags html y código javascript malicioso, por una falta en la comprobación de los datos ingresados en los parameros. De esta forma, un atacante podría ejecutar código que le permita obtener las cookies del usuario atacado, y de esa forma, tomar control de su cuenta.",,"Recomendamos filtrar todos los parámetros en búsqueda de posibles injecciones, y escapar todos los datos de entrada que se vayan a mostrar en la respuesta.",High,
1614 ,ES-SSL 2.0 Obsolete Protocol,"El servicio remoto encripta el trafico utilizando una version obsoleta del protocolo SSL con errores y debilidades conocidas. Un atacante puede explotar estas vulneravilidades y conducir a un ataque de ""man in the middle"" o desencriptar la comunicaciones entre el servicio afectado y los clientes.",,Se recomienda desactivar SSL 2.0 y usar SSL 3.0 o TLS 1.0 en su lugar.,High,
1615 ,"ES-OPTIONS method is enabled
1616 (Metodo OPTIONS activado)",El metodo HTTP OPTIONS esta activado en el servidor. El metodo OPTIONS provee una lista de los metodos que son soportados por el servidor web. El metodo OPTIONS puede exponer informasion sensible que puede ayudar a un usuario malicioso a preparar ataques mas avanzados,,Es recomendado desactivar el metodo OPTIONS en un servidor en produccion.,Low,
1617 ,ES-TLS1/SSLv3 Renegotiation Vulnerability,"Una vulnerabilidad en la manera que el protocol SSL and TLS acepta pedidos renegociaciones pueden permitir a un atacante inyectar texto plano en ect plaintext into an application protocol stream. This could result in a situation where the attacker may be able to issue commands to the server that appear to be coming from a legitimate source. This issue affects SSL version 3.0 and newer and TLS version 1.0 and newer.
1618 A remote, unauthenticated attacker may be able to inject an arbitrary amount of chosen plaintext into the beginning of the application protocol stream. This could allow and attacker to issue HTTP requests, or take action impersonating the user, among other consequences.",,http://www.g-sec.lu/practicaltls.pdf,,
1619 ,ES-File Inclusion,Es posible que un atacante remoto incluya un archivo de recursos locales o remotos y / o la ejecución de código de script arbitrario con los privilegios del servidor web.,,"Editar el código fuente para asegurarse de que la entrada esté correctamente validada. Cuando es posible, se recomienda hacer una lista de nombres de archivos aceptados y restringir la entrada a la lista.
1620
1621 En PHP, la opción allow_url_fopen normalmente permite a un programador para abrir, incluir o utilizan de alguna manera un archivo remoto a través de una URL en lugar de una ruta de archivo local. Se recomienda desactivar esta opción de php.ini.",,
1622 CWE-319,"ES-Credenciales enviadas por un canal en texto plano
1623 (User Credentials Sent in Clear Text)","Las credenciales de usuario se transmiten sobre un canal sin cifrar. Esta información siempre debe ser transferida a través de un canal cifrado (HTTPS) para evitar ser interceptados por usuarios maliciosos.
1624
1625 Una tercera persona puede ser capaz de leer las credenciales de usuario mediante la interceptación de una conexión no cifrada de HTTP.",,"Debido que las credenciales del usuario son considerados información confidencial, siempre debe ser transferido al servidor a través de una conexión segura (HTTPS).",Medium,
1626 ,ES-URL Redirection,"Este script es vulnerable a los ataques de redireccion por URL
1627
1628 La redireccion por URL es comunmente usado para pishing y suplantacion de identidad, ya que confunde al usuario a que sitio esta ingresando realmente. Un atacante puede redireccionar una visita desde un sitio valido hasta un servidor preparado por el, para poder hacer ataques como por ejemplo de pishin o distribucion de malware.",,"El script debe filtrar los sitios destinos del redirect, manteniendolo siempre dentro de los dominios validos.",,
1629 ,ES-Apache Server Status Enabled,"Server Status es una opcion de debug que muestra informacion sensible del servidor, como numero de peticiones, url de las peticiones, uso de memoria, threads, etc",,"Es recomendable desactivar esta opcion en servidores en produccion, o de ser necesaria la utilizacion de la misma, securizar la carpeta con contraseña o renombrarla para que no sea de facil ubicacion",,
1630 ,ES-Microsoft IIS tilde directory enumeration,"Es posible detectar nombres cortos de archivosy directorios cuyo nombrado sea en formato 8.3 en Windows usando vectores en varias versiones de Microsoft IIS. For instance, it is possible to detect all short-names of "".aspx"" files as they have 4 letters in their extensions. This can be a major issue especially for the .Net websites which are vulnerable to direct URL access as an attacker can find important files and folders that they are not normally visible.",,There is a way to disable Windows 8.3 short name creation.You can create a registry key named NtfsDisable8dot3NameCreation in HKLMSYSTEMCurrentControlSetControlFileSystem and set it to 1. That should disable short names creation. Refer to this Microsoft TechNet article to read more about the solution.,,
1631 ,ES-SQL Injection,"Debido al incorrecto filtrado de parámetros es posible ejecutar comandos SQL en la base de datos situada en el servidor mediante manipulación de parámetros. Un atacante podría utilizar esta técnica para extraer/modificar/eliminar el contenido de la base de datos, el único limitante son los privilegios del usuario utilizado por la web application aunque en muchos casos es posible, gracias a una inyeccion de SQL, es posible catapultar un acceso al sistema operativo.",,"Se debe modificar la aplicación para filtrar caracteres en los campos de input antes de ser enviados como consulta al servidor de base de datos.
1632 Es importante que se sigan buenas prácticas de programación, en todos los sitios desarrollados, y sobre todos los parámetros, y no solo sobre aquellos que sean vulnerables actualmente.
1633 Guía de cómo evitar estos ataques (en inglés): https://www.owasp.org/index.php/Guide_to_SQL_Injection",Very High,
1634 ,ES-ASP.NET debugging enabled,"El modo depuracion de ASP.NET esta activado en el servidor. Es recomendado desactivar este modo en servidores en produccion. Por defecto en la instalacion de IIS este modo esta desactivado, si fue activado para diagnosticar errores es conveniente luego desactivarlo.",,"Es posible que el modo debug muestre datos sensibles del servidor.
1635 Mas informacion de como desactivar el modo debug:
1636 http://support.microsoft.com/default.aspx?scid=kb;es-us;815157",,
1637 ,ES-Unicode tranfsormation Issues,"La pagina es vulnerable a varias tranformaciones de Unicode como ""Best-Fit Mappings"", ""Overlong byte sequences"" y ""Ill-formed sequences"".
1638 Best-Fit Mappings ocurre cuando el caracter X es tranformado por un totalmente diferente caracter Y. En general, best-fit mappings occure cuando el caracter es transcodeado entre Unicode y otro encodificado.
1639
1640 ************************************
1641
1642 ""Overlong byte sequences"" (no la forma corta) - UTF-8 allows for different representations of characters that also have a shorter form. For security reasons, a UTF-8 decoder must not accept UTF-8 sequences that are longer than necessary to encode a character. For example, the character U+000A (line feed) must be accepted from a UTF-8 stream only in the form 0x0A, but not in any of the following five possible overlong forms:
1643 0xC0 0x8A
1644 0xE0 0x80 0x8A
1645 0xF0 0x80 0x80 0x8A
1646 0xF8 0x80 0x80 0x80 0x8A
1647 0xFC 0x80 0x80 0x80 0x80 0x8A
1648
1649 Ill-Formed Subsequences As REQUIRED by UNICODE 3.0, and noted in the Unicode Technical Report #36, if a leading byte is followed by an invalid successor byte, then it should NOT consume it.
1650
1651
1652 Software vulnerabilities arise when Best-Fit mappings occur. For example, characters can be manipulated to bypass string handling filters, such as cross-site scripting (XSS) or SQL Injection filters, WAF's, and IDS devices. Overlong UTF-8 sequence could be abused to bypass UTF-8 substring tests that look only for the shortest possible encoding.",,"Se debe identificar el origen de esta tranformacion Unicode y reparar el problema. Se deja links a paginas con informacion:
1653 Links with more information:
1654 http://www.blackhat.com/presentations/bh-usa-09/WEBER/BHUSA09-Weber-UnicodeSecurityPreview-PAPER.pdf
1655 http://www.cl.cam.ac.uk/~mgk25/unicode.html
1656 http://sirdarckcat.blogspot.ro/2009/10/couple-of-unicode-issues-on-php-and.html
1657 http://www.unicode.org/reports/tr36/",,
1658 ,"ES-File Upload XSS
1659 (Subida dearchivo de secuencias de comandos de sitios curzados)","El Script es vulnerable a XSS (Cross-site scripting). La aplicacion permite la carga de archivos y se subio un archivo conteniendo lenguaje HTML. Cuando este tipo de archivos es permitido en la carga, Lugo se pueden ejecutar o linkear, mostrando codigo o acciones malociosas en dicha web.
1660
1661 Usuarios maliciosos pueden inyectar: JavaScript, VBScript, ActiveX, HTML o Flash en esta aplicacion vulnerable y engañar a un usuario para obtener informacion de el, tambien se puede robar datos de la sesion, asi como las cookies de la misma. Dependiendo del codigo que se pueda ejecutar, tambien se puede ganar acceso al wevidor web, archivos de configuracion o hasta ejecucion de binarios en el sistema operativo host.",,"Se deben restringir los tipos de archivos aceptados en el sistema de Carga: chekear la extension y solo aceptar ciertos tipos de archivos. Se recomienda una Whitelist en lugar de Un blacklist (es mejor especificar listado unico de extensiones permitidas, sobre un listado de denegadas). Tambien se debe chekear doble extensiones como .php.png. Chekear archivos sin nombre como "".htaccess"" (en ASP.NET, se debe chekear archivos de configuracion como web.config). Cambiar los permisos sobre la carpeta upload (de carga) para que los archivos no puedan ser ejecutados ahi. Si es posible, renombre los archivos que son subidos al servidor.
1662 Links con mas informacion:
1663 https://www.owasp.org/index.php/Unrestricted_File_Upload
1664 https://www.owasp.org/index.php/Testing_for_Stored_Cross_site_scripting_(OWASP-DV-002)",,
1665 ,ES-jQuery cross site scripting,"Esta pagina esta usando una version obsoleta de jQuery la cual es vulnerable a Cross Site Scripting. Muchos sitios estan utilisando la seleccion de elementos usando location.hash lo que permite la ejecucion de scripts en la pagina. El problema fue solucionado en la vercion jQuery 1.6.3 o superior.
1666 Usuarios malociosos pueden inyectar JavaScript, VBScript, ActiveX, HTML o Flash en la aplicacion vulnerable, pudiendo asi engañar a un usuario para sacarle informacion sensible.",,"Update to the latest version of jQuery.
1667 More info: http://ma.la/jquery_xss/
1668 http://blog.jquery.com/2011/09/01/jquery-1-6-3-released/",,
1669 ,ES-Host Header Attack,"Un atacante puede manipular el header Host y causar que la aplicacion se comporte de maneras inesperadas. Programadores aveces creen en el header host y programas el codigo basado en el: (_SERVER[""HTTP_HOST""] in PHP). Esto tambien se refleja en portales como joombla o wordpress donde los plugins y ejecucion de script, ejemplos:
1670
1671 <link href=""http://_SERVER['HOST']"" (Joomla)
1672
1673 ...haciendo un apend de keys secretas y tokens:
1674 <a href=""http://_SERVER['HOST']?token=topsecret""> (Django, Gallery y otros)
1675 ....e importante directamente scripts:
1676 <script src=""http://_SERVER['HOST']/misc/jquery.js?v=1.4.4""> (Various)",,"La aplicacion web deberia usar una variable ""SERVER_NAME"" en lugar de basarse en le Host header.",High,
1677 ,ES-Login Page password-guessing attack,"Un problema común con el que se encuentran los programadores web son los ataques de fuerza bruta de logins. Un ataque de fuerza bruta es un intento de adivinar la contraseña por sistemáticamente probar todas las posibles combinaciones de números, letras y símbolos hasta descubrir la convencional correcta. Este ataque se mejora utilizando diccionarios con palabras comunes y combinaciones de las mismas
1678
1679 Esta pagina de Login no tiene ninguna protección contra este ataque ya que se probaron 20 logins inválidos y el servidor no bloqueo el acceso para seguir intentando. Tampoco dispone de ninguna protección para evitar los intentos de login automáticos (como un captcha).",,"Es recomendable implementar algun tipo de bloqueo de intentos de login tras un numero de fallos en los intentos.
1680 Mas información:
1681 https://www.owasp.org/index.php/Blocking_Brute_Force_Attacks",,
1682 ,ES-Error page web server version disclosure (Pagina de error mostrando version de servidor ),Pidiendo una pagina que no existe el servidor responde con un error. En esta pagina de error se encuentran datos que contienen version del servidor web y/o modulos activados en este. Dicha informacion puede ser usada para mejorar las tacticas del atacante sabiendo a que se enfrenta,,Se debe configurar paginas de error customizadas evitando mostrar esta informacion.,Low,
1683 ,ES-Weak SSL,"El servidor esta utiizando un cifrado SSL dèbil.
1684
1685 Weak SSL ciphers (SSL2 on port 443):
1686
1687 SSL2_CK_RC4_128_EXPORT40_WITH_MD5 - Low strength
1688 SSL2_CK_RC2_128_CBC_EXPORT40_WITH_MD5 - Low strength
1689 SSL2_CK_DES_64_CBC_WITH_MD5 - Low strength
1690
1691 Weak SSL ciphers (SSL3 on port 443):
1692
1693 SSL3_CK_RSA_RC4_40_MD5 - Low strength
1694 SSL3_CK_RSA_RC2_40_MD5 - Low strength
1695 SSL3_CK_RSA_DES_40_CBC_SHA - Low strength
1696 SSL3_CK_RSA_DES_64_CBC_SHA - Low strength
1697 SSL3_CK_EDH_RSA_DES_40_CBC_SHA - Low strength
1698 SSL3_CK_EDH_RSA_DES_64_CBC_SHA - Low strength
1699
1700 Weak SSL ciphers (TLS1 on port 443):
1701
1702 TLS1_CK_RSA_EXPORT_WITH_RC4_40_MD5 - Low strength
1703 TLS1_CK_RSA_EXPORT_WITH_RC2_CBC_40_MD5 - Low strength
1704 TLS1_CK_RSA_EXPORT_WITH_DES40_CBC_SHA - Low strength
1705 TLS1_CK_RSA_WITH_DES_CBC_SHA - Low strength
1706 TLS1_CK_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA - Low strength
1707 TLS1_CK_DHE_RSA_WITH_DES_CBC_SHA - Low strength",,Reconfigurar el servidor para encriptado mas fuerte.,,
1708 ,ES-CRIME SSL/TLS attack,"Compression Ratio Info-leak Made Easy (CRIME) es un exploit contra las cookies secretas del servidor sobre conexiones usando protocolos HTTPS y SPDY que tambien esten usando compresion de datos. Cuando se recupera el contenido de la cookie de autentificacion, permite a un atacante robar la sesion, permitiendo iniciar otros ataques.
1709
1710 CRIME es un ataque del lado cliente, pero el servidor puede proteger al cliente rechazando la combinacion de estas opciones. Para CRIME, la debilidad es la compresion Deflate.",,"CRIME puede ser combatido previniendo el uso de compresion, tanto del lado del cliente, desactivando la compresion de las peticiones HTTPS, o del lado del servidor previniendo el uso de compresion de datos en las transacciones que utilicen el protocolo TLS.
1711
1712 Referencias WEB.
1713 http://blogs.cisco.com/security/breach-crime-and-blackhat/
1714 http://en.wikipedia.org/wiki/CRIME_(security_exploit)
1715 http://isecpartners.com/blog/2012/september/details-on-the-crime-attack.aspx",High,
1716 ,ES-Transaccion Insegura de HTTPS a HTTP en el form POST,La pagina segura (https) contiene un form que realiza el post sobre una pagina insegura (http). Esto puede confundir al usuario y hacerle creer que su datos son enviados encriptados cuando en realidad no.,,El destino del FORM debe apuntar a una pagina segura (https),,
1717 ,ES-Trace Method is Enabled (Metodo TRACE activado),"El metodo Trace esta habilitado en el servidor. En precencia de otras vulnerabilidades cross-domain en los navegadores web, informacion sensible del campo header puede ser leida desde cualquier dominio que soporte metodo HTTP TRACE.
1718
1719 Un atacante poria abusar de la funcionabilidad HTTP TRACE para ganar acceso a la informacion de los headers HTTP como las cookies y datos de autenticacion.",,"Se recomienda desactivar el metodo TRACE en el servidor web.
1720
1721 Referencias WEB:
1722 http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1723 http://www.cgisecurity.com/lib/WH-WhitePaper_XST_ebook.pdf",Low,
1724 ,ES-Public Key SSL < 2048 bits (Certificado de llave Publica SSL menor de 2048 Bits),"El certificado SSL usado por el servidor contiene una llave publica de menos de 2048 bits de largo
1725
1726 Los nuevos estandares de de la Industria de Certificados para SSL (SSL Certificates Industry) seteados por Certification Authority/Browser (CA/B) Forum requiere que los certificados expedidos despues de enero 1 del 2014. Deben ser al menos de 2048-bit largo. Con el incremento del poder de procesamiento de las computadoras, cualquier certificado menor de 2048-bit es riesgoso de ser comprometido por personas mal intecionadas con poder de procesamiento.",,"Si se tiene cualquier certificado de 1024-bito certificados con menos de 2048-bit de largo, sera necesario que se migre a 2048-bit.
1727
1728 New Standard: https://www.cabforum.org/wp-content/uploads/Baseline_Requirements_V1.pdf",,
1729 ,ES-Ruby on Rails CookieStore session cookie persistence,"Ruby on Rails contiene un fallo en su diseño que podria permitir a atacantes facilitar el acceso a las aplicaciones. El problema esta en mecanicsmo de la CookieStore en guardar la cookie en el lado del cliente, mientras no guarda la entrada correspondiente en el lado del servidor. Cuando la aplicacion termina la sesion, Ruby on Rails no tiene manera de trackear esto y verdaderamente invalidad la cookie con la configuracion por defecto. Esto significa que persiste ""de por vida"" y puede ser usada para acceder a aplicaciones inclusive cuando se piensa que se termino la sesion.",,"Actualmente, no se conocen actualizaciones o parches para corregir esta vulnerabilidad. Si es posible migrar temporalmente implementando un sistema de autenticacion mas seguro (e.g. ActiveRecordStore).",,
1730 ,EN-Metadatos,"250+ Archivos conteniendo metadatos: Usuarios, Carpetas, fechas de edicion y modificacion, software usado, Direccion de impresoras locales",,"Datos privados son revelados a traves de los metadatos de documentos hosteados en el dominio (PDF, WORD). Datos como nombres de usuario, versiones de sistemas operativos, versiones de software utilizados, fechas y horas de cada modificacion del documento, direcciones de red de impresoras, etc. Se recomienda limpiar de metadatos documentos que luego seran publicados en internet",,
1731 ,EN-Session Cookie without Secure flag set,"This cookie does not have the Secure flag set. When a cookie is set with the Secure flag, it instructs the browser that the cookie can only be accessed over secure SSL channels. This is an important security protection for session cookies.",,"If possible, you should set the Secure flag for this cookie.",low,
1732 ,EN-Session Cookie without HttpOnly flag Set,"This cookie does not have the HTTPOnly flag set. When a cookie is set with the HTTPOnly flag, it instructs the browser that the cookie can only be accessed by the server and not by client-side scripts. This is an important security protection for session cookies.",,"If possible, you should set the HTTPOnly flag for this cookie.",Low,
1733 ,EN-Apache httpd Remote Denial of Service,"* Alerta generada por el flag del servidor: ver: 2.2.15 *
1734 Se ha detectado un problema en las versiones de apache 1.3.0, 2.0.x hasta 2.0.64 y 2.2.X hasta 2.2.19 que mediante una herramienta automatizada un atacante usand una moderada cantidad de request puede causar un uso significativo de memoria y CPU en el servidor. Datos: http://seclists.org/fulldisclosure/2011/Aug/175.",,Actualizar version de apache,,
1735 ,EN-Robots.txt,Robots.txt revela directorios sensibles. Un atacante busca directamente robots.txt para encontrar puntos desde donde comenzar su ataque.,,"Es conveniente manejar nombres de directorios que no describan el contenido, en especial en directorios sensibles. Por ejemplo en lugar de /setup o /app_data llamar al directorio /Dir_Code1. De esta manera no revelar a un atacante que clase de informacion contiene un directorio, que se intenta ocultar de los buscadores (mediante robots.txt)
1736 Otra practica que se me ocurre es la utilizacion de parametros. Por ejemplo:
1737 Disallow: /*AB/$
1738 Esto desactivará cualquier carpeta que termine con ""AB"" por ejemplo /sourceAB/. Evitando pasar cualquier dato a un atacante y centralizando las carpetas sensibles y ocultandolas simplemente colocando ""AB"" al final.",,
1739 ,EN-Typical Login Web,"Archivo de Login nombrado de manera ""comun"".",,Esto facilita a los robots de ataque encontrar paginas sensibles. Se recomienda no usar nombres estandard para paginas de login.,,
1740 ,EN-Credentials in Plain Text,La pagina de login viaja sobre texto plano,,Es altamente recomendable que las paginas de login se fuerzen a usar SSL (https),Medium,
1741 ,EN-Unencrypted __VIEWSTATE parameter,"El parametro ""__VIEWSTATE"" no esta encriptado. Para reducir las posibilidades que alguien intercepte informacion guardada en ViewState es bueno encriptarlo.",,"Se recomienda encriptar el parametro ""__VIEWSTATE"", para hacer esto se debe setear el tipo de validacion a 3DES. Editar Web.Config y agregar la siguiente linea bajo <system.web>
1742 <machineKey validation=""3DES""/>",,
1743 ,EN-Insecure Captcha,"La resolucion del Captcha esta incluida en el mismo codigo:
1744
1745 <img id=""ctl01_mainContent_imgCaptcha"" src=""http://test-www.bancofalabella.com.co/Data/Sites/1/ImgTemp/ImageFormat_THHvB.png""
1746 style=""border-width:0px;"" />
1747
1748 Siendo la respuesta THHvB
1749
1750 Facilitando la manera de automatizar un script para atacar el form",,Se recomienda implementar un sistema de Captcha que la resolucion no se incluya en el codigo.,,
1751 ,EN-Application error message,"This page contains an error/warning message that may disclose sensitive information.The message can also contain the location of the file that produced the unhandled exception.
1752
1753 The error messages may disclose sensitive information. This information can be used to launch further attacks.",,Review the source code for this script. The application need to show generic errors.,,
1754 ,EN-Apache httpOnly Cookie Disclosure,"El servidor Apache version 2.2.X hasta la 2.2.21 no restringe correctamente la informacion mostrada en la contrsuccion del error "" Bad Request "" (aka 400) permitiendo a un atacante obtener los parametros de HTTPOnly.
1755 Datos: http://fd.the-wildcat.de/apache_e36a9cf46c.php",,Actualizar el apache. La version 2.2.22 es la primer version que soluciona este problema.,,
1756 ,EN-Input Password with Autocomplete Enable,"Autocomplete allows the browser to predict the value. When a user starts to type in a field, the browser should display options to fill in the field, based on earlier typed values. If an attacker gain access to a computer its possible of get credentials back.",,"You should include the attribute Autocomplete OFF:
1757 <INPUT TYPE=""password"" AUTOCOMPLETE=""off"">",Low,
1758 ,Backup FilesEN-,"Backup files can contain script sources, configuration files or other sensitive information that may help an malicious user to prepare more advanced attacks",,"Remove the file(s) if they are not required on your website. As an additional step, it is recommended to implement a security policy within your organization to disallow creation of backup files in directories accessible from the web.",,
1759 ,EN-Sesintive directory,"A possible sensitive directory has been found. This directory is not directly linked from the website.This check looks for common sensitive resources like backup directories, database dumps, administration pages, temporary directories. Each one of these directories could help an attacker to learn more about his target.",,,,
1760 ,EN-Slow HTTP Denial of Service Attack,"Slowloris and Slow HTTP POST DoS attacks rely on the fact that the HTTP protocol, by design, requires requests to be completely received by the server before they are processed. If an HTTP request is not complete, or if the transfer rate is very low, the server keeps its resources busy waiting for the rest of the data. If the server keeps too many resources busy, this creates a denial of service.",,It's important to configure the timout values on the Webserver. Here is a link to a guide on how to prevent this kind of attack: https://community.qualys.com/blogs/securitylabs/2011/11/02/how-to-protect-against-slow-http-attacks,Medium,
1761 ,EN-Clickjacking,"It might be possible for a web page controlled by an attacker to load the content of this response within an iframe on the attacker's page. This may enable a ""clickjacking"" attack, in which the attacker's page overlays the target application's interface with a different interface provided by the attacker. By inducing victim users to perform actions such as mouse clicks and keystrokes, the attacker can cause them to unwittingly carry out actions within the application that is being targeted. This technique allows the attacker to circumvent defenses against cross-site request forgery, and may result in unauthorized actions. Ref:http://javascript.info/tutorial/clickjacking",,"To effectively prevent framing attacks, the application should return a response header with the name X-Frame-Options and the value DENY to prevent framing altogether, or the value SAMEORIGIN to allow framing only by pages on the same origin as the response itself.",Low,
1762 ,EN-OPTIONS method is enabled,"HTTP OPTIONS method is enabled on this web server. The OPTIONS method provides a list of the methods that are supported by the web server, it represents a request for information about the communication options available on the request/response chain identified by the Request-URI.
1763 The OPTIONS method may expose sensitive information that may help an malicious user to prepare more advanced attacks.",,It's recommended to disable OPTIONS Method on the web server.,Low,
1764 ,EN-TLS1/SSLv3 Renegotiation Vulnerability,"A vulnerability in the way SSL and TLS protocols allow renegotiation requests may allow an attacker to inject plaintext into an application protocol stream. This could result in a situation where the attacker may be able to issue commands to the server that appear to be coming from a legitimate source. This issue affects SSL version 3.0 and newer and TLS version 1.0 and newer.
1765 A remote, unauthenticated attacker may be able to inject an arbitrary amount of chosen plaintext into the beginning of the application protocol stream. This could allow and attacker to issue HTTP requests, or take action impersonating the user, among other consequences.",,http://www.g-sec.lu/practicaltls.pdf,,
1766 ,EN-Email address found,One or more email addresses have been found on this page. The majority of spam comes from email addresses harvested off the internet. The spam-bots (also known as email harvesters and email extractors) are programs that scour the internet looking for email addresses on any website they come across. Spambot programs look for strings like [email protected] and then record any addresses found.,,,,
1767 ,EN-File Inclusion,It is possible for a remote attacker to include a file from local or remote resources and/or execute arbitrary script code with the privileges of the webserver.,,"Edit the source code to ensure that input is properly validated. Where is possible, it is recommended to make a list of accepted filenames and restrict the input to that list.
1768
1769 For PHP, the option allow_url_fopen would normally allow a programmer to open, include or otherwise use a remote file using a URL rather than a local file path. It is recommended to disable this option from php.ini.",,
1770 ,EN-User Credentials Sent in Clear Text,"Vulnerability description
1771 User credentials are transmitted over an unencrypted channel. This information should always be transferred via an encrypted channel (HTTPS) to avoid being intercepted by malicious users.
1772
1773 The impact of this vulnerability
1774 A third party may be able to read the user credentials by intercepting an unencrypted HTTP connection.",,"Because user credentials are considered sensitive information, should always be transferred to the server over an encrypted connection (HTTPS).",,
1775 ,EN-URL Redirection,"This script is possibly vulnerable to URL redirection attacks.
1776
1777 URL redirection is sometimes used as a part of phishing attacks that confuse visitors about which web site they are visiting.
1778
1779 The impact of this vulnerability
1780 A remote attacker can redirect users from your website to a specified URL. This problem may assist an attacker to conduct phishing attacks, trojan distribution, spammers.",,Your script should properly sanitize user input.,,
1781 ,EN-Microsoft IIS tilde directory enumeration,"It is possible to detect short names of files and directories which have an 8.3 file naming scheme equivalent in Windows by using some vectors in several versions of Microsoft IIS. For instance, it is possible to detect all short-names of "".aspx"" files as they have 4 letters in their extensions. This can be a major issue especially for the .Net websites which are vulnerable to direct URL access as an attacker can find important files and folders that they are not normally visible.",,There is a way to disable Windows 8.3 short name creation.You can create a registry key named NtfsDisable8dot3NameCreation in HKLMSYSTEMCurrentControlSetControlFileSystem and set it to 1. That should disable short names creation. Refer to this Microsoft TechNet article to read more about the solution.,,
1782 ,EN-SQL Injection,"SQL injection is a vulnerability that allows an attacker to alter back-end SQL statements by manipulating the user input. An SQL injection occurs when web applications accept user input that is directly placed into a SQL statement and doesn't properly filter out dangerous characters.
1783
1784 This is one of the most common application layer attacks currently being used on the Internet. Despite the fact that it is relatively easy to protect against, there is a large number of web applications vulnerable.
1785
1786 An attacker may execute arbitrary SQL statements on the vulnerable system. This may compromise the integrity of your database and/or expose sensitive information.
1787
1788 Depending on the back-end database in use, SQL injection vulnerabilities lead to varying levels of data/system access for the attacker. It may be possible to not only manipulate existing queries, but to UNION in arbitrary data, use sub selects, or append additional queries. In some cases, it may be possible to read in or write out to files, or to execute shell commands on the underlying operating system.
1789
1790 Certain SQL Servers such as Microsoft SQL Server contain stored and extended procedures (database server functions). If an attacker can obtain access to these procedures it may be possible to compromise the entire machine.",,"Your script should filter metacharacters from user input.
1791 Check detailed information for more information about fixing this vulnerability.
1792 Detailed information",,
1793 ,EN-ASP.NET debugging enabled,"ASP.NET debugging is enabled on this application. It is recommended to disable debug mode before deploying a production application. By default, debugging is disabled, and although debugging is frequently enabled to troubleshoot a problem, it is also frequently not disabled again after the problem is resolved.",,"It may be possible to disclose sensitive information about the web sever the ASP.NET application.
1794 More information on how to fix it:
1795 http://support.microsoft.com/default.aspx?scid=kb;en-us;815157",,
1796 ,EN-Unicode tranformation Issues,"This page is vulnerable to various Unicode transformation issues such as Best-Fit Mappings, Overlong byte sequences, Ill-formed sequences.
1797 Best-Fit Mappings occurs when a character X gets transformed to an entirely different character Y. In general, best-fit mappings occur when characters are transcoded between Unicode and another encoding.
1798
1799 Overlong byte sequences (non-shortest form) - UTF-8 allows for different representations of characters that also have a shorter form. For security reasons, a UTF-8 decoder must not accept UTF-8 sequences that are longer than necessary to encode a character. For example, the character U+000A (line feed) must be accepted from a UTF-8 stream only in the form 0x0A, but not in any of the following five possible overlong forms:
1800 0xC0 0x8A
1801 0xE0 0x80 0x8A
1802 0xF0 0x80 0x80 0x8A
1803 0xF8 0x80 0x80 0x80 0x8A
1804 0xFC 0x80 0x80 0x80 0x80 0x8A
1805
1806 Ill-Formed Subsequences As REQUIRED by UNICODE 3.0, and noted in the Unicode Technical Report #36, if a leading byte is followed by an invalid successor byte, then it should NOT consume it.
1807
1808
1809 Software vulnerabilities arise when Best-Fit mappings occur. For example, characters can be manipulated to bypass string handling filters, such as cross-site scripting (XSS) or SQL Injection filters, WAF's, and IDS devices. Overlong UTF-8 sequence could be abused to bypass UTF-8 substring tests that look only for the shortest possible encoding.",,"Identiy the source of these Unicode transformation issues and fix them. Consult the web references bellow for more information.
1810 Links with more information:
1811 http://www.blackhat.com/presentations/bh-usa-09/WEBER/BHUSA09-Weber-UnicodeSecurityPreview-PAPER.pdf
1812 http://www.cl.cam.ac.uk/~mgk25/unicode.html
1813 http://sirdarckcat.blogspot.ro/2009/10/couple-of-unicode-issues-on-php-and.html
1814 http://www.unicode.org/reports/tr36/",,
1815 ,EN-File Upload XSS,"This script is possibly vulnerable to XSS (Cross-site scripting). The web application allows file upload and Acunetix WVS was able to upload a file containing HTML content. When HTML files are allowed, XSS payload can be injected in the file uploaded. Check Attack details for more information about this attack.
1816
1817 Malicious users may inject JavaScript, VBScript, ActiveX, HTML or Flash into a vulnerable application to fool a user in order to gather data from them. An attacker can steal the session cookie and take over the account, impersonating the user. It is also possible to modify the content of the page presented to the user.",,"Restrict file types accepted for upload: check the file extension and only allow certain files to be uploaded. Use a whitelist approach instead of a blacklist. Check for double extensions such as .php.png. Check for files without a filename like .htaccess (on ASP.NET, check for configuration files like web.config). Change the permissions on the upload folder so the files within it are not executable. If possible, rename the files that are uploaded.
1818
1819 https://www.owasp.org/index.php/Unrestricted_File_Upload
1820 https://www.owasp.org/index.php/Testing_for_Stored_Cross_site_scripting_(OWASP-DV-002)",,
1821 ,EN-Possible virtual host found,"Virtual hosting is a method for hosting multiple domain names (with separate handling of each name) on a single server (or pool of servers). This allows one server to share its resources, such as memory and processor cycles, without requiring all services provided to use the same host name.
1822
1823 This web server is responding differently when the Host header is manipulated and various common virtual hosts are tested. This could indicate there is a Virtual Host present.",,Consult the virtual host configuration and check if this virtual host should be publicly accessible,,
1824 ,EN-Host header attack,"An attacker can manipulate the Host header as seen by the web application and cause the application to behave in unexpected ways.
1825 Developers often resort to the exceedingly untrustworthy HTTP Host header (_SERVER[""HTTP_HOST""] in PHP).
1826 Even otherwise-secure applications trust this value enough to write it to the page without HTML-encoding it with code equivalent to:
1827
1828 <link href=""http://_SERVER['HOST']"" (Joomla)
1829 ...and append secret keys and tokens to links containing it:
1830
1831 <a href=""http://_SERVER['HOST']?token=topsecret""> (Django, Gallery, others)
1832 ....and even directly import scripts from it:
1833
1834 <script src=""http://_SERVER['HOST']/misc/jquery.js?v=1.4.4""> (Various)
1835
1836 Host header *********evilhostDx5oMrAd.com was reflected inside a A tag (href attribute).",,"The web application should use the SERVER_NAME instead of the Host header. It should also create a dummy vhost that catches all requests with unrecognized Host headers. This can also be done under Nginx by specifying a non-wildcard SERVER_NAME, and under Apache by using a non-wildcard serverName and turning the UseCanonicalName directive on. Consult references for detailed information.",,
1837 ,EN-jQuery cross site scripting,"This page is using an older version of jQuery that is vulnerable to a Cross Site Scripting vulnerability. Many sites are using to select elements using location.hash that allows someone to inject script into the page. This problem was fixed in jQuery 1.6.3 and up.
1838 Malicious users may inject JavaScript, VBScript, ActiveX, HTML or Flash into a vulnerable application to fool a user in order to gather data from them. An attacker can steal the session cookie and take over the account, impersonating the user. It is also possible to modify the content of the page presented to the user.",,"Update to the latest version of jQuery.
1839 More info: http://ma.la/jquery_xss/
1840 http://blog.jquery.com/2011/09/01/jquery-1-6-3-released/",,
1841 ,EN-Login Page password-guessing attack,"A common threat web developers face is a password-guessing attack known as a brute force attack. A brute-force attack is an attempt to discover a password by systematically trying every possible combination of letters, numbers, and symbols until you discover the one correct combination that works.
1842
1843 This login page doesn't have any protection against password-guessing attacks (brute force attacks). It's recommended to implement some type of account lockout after a defined number of incorrect password attempts. Consult Web references for more information about fixing this problem.
1844
1845 The scanner tested 10 invalid credentials and no account lockout was detected.",,"It's recommended to implement some type of account lockout after a defined number of incorrect password attempts.
1846 More info:
1847 https://www.owasp.org/index.php/Blocking_Brute_Force_Attacks",,
1848 ,EN-Error page web server version disclosure,"By requesting a page that doesn't exist, an error page was returned. This error page contains the web server version number and a list of modules enabled on this server. This information can be used to conduct further attacks. Possible sensitive information disclosure.",,"If you are using Apache, you can setup a custom 404 page by following the instructions provided in the References section.",,
1849 ,EN-SSL weak ciphers,"The remote host supports the use of SSL ciphers that offer either weak encryption or no encryption at all.
1850 This vulnerability affects Server.",,Reconfigure the affected application to avoid use of weak ciphers.,,
1851 ,EN-CRIME SSL/TLS attack,"Compression Ratio Info-leak Made Easy (CRIME) is a security exploit against secret web cookies over connections using the HTTPS and SPDY protocols that also use data compression. When used to recover the content of secret authentication cookies, it allows an attacker to perform session hijacking on an authenticated web session, allowing the launching of further attacks.
1852
1853 CRIME is a client-side attack, but the server can protect the client by refusing to use the feature combinations which can be attacked. For CRIME, the weakness is Deflate compression. This alert is issued if the server accepts Deflate compression.
1854
1855 An attacker can perform session hijacking on an authenticated web session, allowing the launching of further attacks.",,"CRIME can be defeated by preventing the use of compression, either at the client end, by the browser disabling the compression of HTTPS requests, or by the website preventing the use of data compression on such transactions using the protocol negotiation features of the TLS protocol. As detailed in The Transport Layer Security (TLS) Protocol Version 1.2, the client sends a list of compression algorithms in its ClientHello message, and the server picks one of them and sends it back in its ServerHello message. The server can only choose a compression method the client has offered, so if the client only offers 'none' (no compression), the data will not be compressed. Similarly, since 'no compression' must be allowed by all TLS clients, a server can always refuse to use compression.
1856
1857 Web references
1858 http://en.wikipedia.org/wiki/CRIME_(security_exploit)
1859 http://isecpartners.com/blog/2012/september/details-on-the-crime-attack.aspx",,
1860 ,EN-Insecure transition from HTTPS to HTTP in form post,"This secure (https) page contains a form that is posting to an insecure (http) page. This could confuse users who may think their data is encrypted when in fact it's not.
1861 Impact: Possible information disclosure.",,The form target should point to a secure (https) page.,,
1862 ,EN-TRACE method is enabled,"HTTP TRACE method is enabled on this web server. In the presence of other cross-domain vulnerabilities in web browsers, sensitive header information could be read from any domains that support the HTTP TRACE method.
1863
1864 Attackers may abuse HTTP TRACE functionality to gain access to information in HTTP headers such as cookies and authentication data.",,"Disable TRACE Method on the web server.
1865
1866 Web references
1867 http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1868 http://www.cgisecurity.com/lib/WH-WhitePaper_XST_ebook.pdf",,
1869 ,EN-SSL certificate public key less than 2048 bit,"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.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",,"If you have any 1024-bit certificates or certificates with less than 2048-bit key length, you will need to migrate to 2048-bit key length.
1870
1871 New Standard: https://www.cabforum.org/wp-content/uploads/Baseline_Requirements_V1.pdf",,
1872 ,EN-Ruby on Rails CookieStore session cookie persistence,"Debido que las credenciales del usuario son considerados información confidencial, siempre debe ser transferido al servidor a través de una conexión segura (HTTPS).",,"Currently, there are no known upgrades or patches to correct this vulnerability. It is possible to temporarily mitigate the flaw by implementing the following workaround: switch to a more secure authentication management systems (e.g. ActiveRecordStore).",,
1873 ,EN-Remote Code Execution - ms_08_067 netapi,"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.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",,,High,
1874 ,EN-Windows Print Spooler Components Vulnerability - MS13-001,"The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.Certain languages allow direct addressing of memory locations and do not automatically ensure that these locations are valid for the memory buffer that is being referenced. This can cause read or write operations to be performed on memory locations that may be associated with other variables, data structures, or internal program data.","Certain languages allow direct addressing of memory locations and do not automatically ensure that these locations are valid for the memory buffer that is being referenced. This can cause read or write operations to be performed on memory locations that may be associated with other variables, data structures, or internal program data.
1875 As a result, an attacker may be able to execute arbitrary code, alter the intended control flow, read sensitive information, or cause the system to crash.",,High,
1876 ,ES-Credenciales Repetidas,Existen multiples credeciales repetidas para un mismo acceso.,"Tener credenciales repetidas de un mismo servidor o acceso, posibilita a un atacante tener mayor impacto, pues utilizando un mismo password puede ingresar a distintos servicios o áreas",Evitar utilizar mismas credenciales en distintos servicios,High,
1877 ,ES-Ftp Anonimo,Es servicio de FTP posee el usuario : anonymous,"Los servidores FTP anónimos ofrecen sus servicios libremente a todos los usuarios, permiten acceder a sus archivos sin necesidad de tener un 'USER ID' o una cuenta de usuario. Es la manera más cómoda fuera del servicio web de permitir que todo el mundo tenga acceso a cierta información sin que para ello el administrador de un sistema tenga que crear una cuenta para cada usuario.
1878
1879 Si un servidor posee servicio 'FTP anonymous' solamente con teclear la palabra «anonymous», cuando pregunte por tu usuario tendrás acceso a ese sistema. No se necesita ninguna contraseña preestablecida, aunque tendrás que introducir una sólo para ese momento, normalmente se suele utilizar la dirección de correo electrónico propia.",Evitar usuario anonimo,Medium,
1880 ,ES-Credenciales débiles Tomcat,"Se detectaron credenciales por defecto en servidores Tomcat, ejecutándose con privilegios elevados.
1881 Un atacante que intente loguearse con una lista de usuarios por defecto podría comprometer el servicio.
1882 En este caso en particular el usuario “admin” es muy común en servidores Tomcat, y cuenta con privilegios para ejecutar código, por lo que debe ser protegido con una contraseña fuerte.",,Aplicar una política de seguridad al servidor que obligue el uso de contraseñas de acuerdo con las políticas de seguridad interna.,High,
1883 ,ES-Wpad Spoofing,"En los ambientes Windows ante una falla a resolver un nombre de host,
1884 realizan una segunda búsqueda utilizando NetBios. La naturaleza de este
1885 pedido realizado utilizando broadcast es inseguro si no se tienen
1886 recaudos.
1887
1888 Un atacante podría utilizar esta vulnerabilidad para
1889 registrar el dominio WPAD en netbios con el fin de redirigir y modificar
1890 el tráfico de las workstations con las que comparte el segmento de red.
1891 Este ataque podría derivar en la captura de credenciales o hashes que
1892 le brinden acceso a sistemas críticos.",,"Deshabilitar la configuración automática de proxy en los equipos
1893 windows, y registrar el nombre de domino wpad, para que ningún equipo de
1894 la red pueda impersonarlo.",High,
1895 ,ES-Servicio de Telnet,"Las credenciales de usuario se transmiten sobre un canal sin cifrar (servicio telnet).
1896 Un atacante capaz de interceptar el tráfico entre los hosts y el usuario remoto, será capaz de obtener las credenciales utilizadas.",,"Reemplazar los servicios que permiten el envío de credenciales en texto plano, por aquellos que lo hacen de forma cifrada. En este caso, existen diferentes alternativas para reemplazar los servicios de administración remota, como por ejemplo ssh o rdp.",Medium,
1897 ,ES-Tokens cacheados,"Fue posible impersonar diferentes usuarios de dominio, incluido un administrador de dominio, a través de los tokens de acceso cacheados en el servidor.",,"No existe un parche para resolver este tipo de situaciones, ya que los tokens de acceso son propios de la arquitectura de Windows. Sin embargo es posible implementar algunas medidas a nivel operativo para mitigar en gran parte el impacto del cacheo de tokens. Recomendamos:
1898 > Asegurarse que usuarios con altos privilegios (especialmente administradores) tengan una cuenta específica para tareas de administración y otra para loguearse en sus sistemas.
1899 > Ejecutar aquellas tareas que requieran mayores privilegios utilizando la aplicación “RunAs”.
1900 > Asegurarse que los Domain Admins sólo sean utilizados para administrar el dominio. Crear diferentes cuentas de dominio y asignarle autorización administrativa solo para la unidad de negocio correspondiente.
1901 > Asegurarse que las cuentas administrativas de ambientes de desarrollo y test sean diferentes a las de los sistemas críticos de producción.
1902 > Ejecutar los servicios necesarios para el correcto funcionamiento de la unidad de negocio en un equipo diferente al Controlador de Dominio.
1903 > Utilizar la opción de Active Directory “Account is sensitive and cannot be delegated” (sólo aplica a los logueos interactivos, pero ayuda a reforzar la seguridad de la cuenta).
1904
1905 Referencias:
1906 http://carnal0wnage.attackresearch.com/2008/05/token-passing-with-incognito-part-2.html
1907 http://pentestmonkey.net/uncategorized/from-local-admin-to-domain-admin
1908 http://www.offensive-security.com/metasploit-unleashed/Fun_With_Incognito",High,
1909 ,ES-Denegacion de Servicios(DOS),"un ataque de denegación de servicios, también llamado ataque DoS (de las siglas en inglés Denial of Service) o DDoS (de Distributed Denial of Service), es un ataque a un sistema de computadoras o red que causa que un servicio o recurso sea inaccesible a los usuarios legítimos. Normalmente provoca la pérdida de la conectividad de la red por el consumo del ancho de banda de la red de la víctima o sobrecarga de los recursos computacionales del sistema de la víctima",,La forma de prevenirlo: https://www.owasp.org/index.php/Denial_of_Service,High,
1910 ,ES-Revelacion de Informacion (Information Disclosure),Se puede obtener una información sensible del usuario. Esto podría ayudar a un atacante a tener control de una base de datos ó permitirle escalar hacia otro vector de ataque.,,"Determinar si esta información debería ser accesible desde la red, sin estar protegida por credenciales.",Medium,
1911 ,ES-Sitio sin Informar,,,/reclamaciones/home/index. ,,
1912 ,ES-Listado de Directorios,Muestra directorios que no deberian ser publicos,,Evitar que dichos directorios sean publicos,Medium,
1913 ,ES-Shell,"Una shell es parte de codigo programado en (PHP,Python,Ruby,etc) que una vez que es subido al host victima, puede ser utilizado para subir, bajar, borrar archivos.",,"Evitar entradas que posibiliten subir imagenes o codigo al servidor, sin ser adecuadamente controlado",,
1914 ,ES-Path Disclosure,Permite ver la ruta a archivos u aplicaciones que no deberian ser mostradas,,"Puede solucionarse desactivando los mensajes de error :
1915 En PHP modificando el archivo php.ini ( display_errors = 'off' )
1916 En Apache modificando el archivo httpd.conf ( php_flag display_errors off)",,
1917 ,ES-File Upload,Es posible subir código o imagenes sin ser fitradas adecuadamente.,,Evitar campos para subir archivos que no sean correctamente filtrados,,
1918 ,ES-Metodo Put habilitado (Put File Allow),"Sube, carga o realiza un upload de un recurso especificado (archivo), es el camino más eficiente para subir archivos a un servidor.",,"Evitar que el metodo PUT se encuentre con libre acceso a cualquier tipo de usuario, restringir acceso.",,
1919 ,ES-Leer Archivos (Read files),,,,,
1920 ,ES-Usuarios por defecto(default users),"Se debe evitar utilizar usuarios y contraseñas por defecto, pues el sistema puede quedar suseptible a un ataque de fuerza bruta o de diccionario.",,Cambiar usuarios y contraseñas de acuerdo a las politicas de la empresa,,
1921 ,ES-Sslstrip Attack,"Dado que la página no esta utilizando https para proteger sus credenciales, el panel de ingreso esta implementedo mediante http, y no https, es posible modificar los recursos obtenidos, si el atacante logra intereceptar la comunicación entre ambos sitios. ",,"Cargar todos los recursos a través de https, para los recursos externos recomendamos incluir los mismo de la siguiente manera src=""//dominio.com/recurso.js"" de esta manera el navegador automaticamete incluye el protocolo http o https segun la conexion inicial que genera.",High,
1922 ,ES-Enumerar Usuarios,,,,Medium,
1923 ,ES-Login User HTTP,"Las credenciales de usuario y contraseña, viajan en texto plano con lo cual un atacante podría obtener dichas credenciales para un posterior acceso",,Utilizar HTTPS para autenticar usuarios,Medium,
1924 ,ES-Falta de Control de Acceso,Se puede acceder a parte del sitio sin una sesion valida,,Validar correctamente la sesiones del sitio verifiquen que el usuario poseen una sesion valida,Medium,
1925 ,ES-Cookie Reutilization,La cookie puede ser modificada y reutilizada para hacer nuevas consultas o impersonar usuarios,,Evitar ,Medium,
1926 ,ES-Credenciales Debiles md5,"Se detecto que dentro del request se envía el nombre de usuario y la contraseña hasheada. Si bien la contraseña utiliza una funcion de md5, lo hace sin salt para protegerla.
1927 Con lo cual un atacante que la intercepte, puede decifrar el md5 para luego obtener la contraseña en texto plano junto con el usuario para acceder al sistema.",,"Aplicar una política de seguridad al servidor que obligue el uso de contraseñas de acuerdo con las políticas de seguridad interna.
1928 Se recomienda un cifrado mas robusto con la funcion salt",High,
1929 ,ES-CSRF,"Un ataque CSRF fuerza al navegador web validado de una víctima a enviar una petición a una aplicación web vulnerable, la cual entonces realiza la acción elegida a través de la víctima. Al contrario que en los ataques XSS, los cuales explotan la confianza que un usuario tiene en un sitio en particular, el cross site request forgery explota la confianza que un sitio tiene en un usuario en particular.",,"Recomendamos la imprementacion de un feature anti-csrf con el fin de autenticar todoslos request,en particual aquellas peticiones sensibles como por ejemplo el cambiode contraseñas y asignacion de roles (dar permisos de administrador a un usuario). El framework de ASP.net cuenta con este feature llamado viewstate (https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Viewstate_.28ASP.NET.29)",Medium,
1930 ,ES-SSL weak ciphers (Cifrado debil),El servidor remoto soporta el uso de SSL pero ofrece una encriptacion debil,,Reconfigurar el servidor web con un nivel de encriptacion mayor,Medium,
1931 ,EN-Android Debugging Activated,The Application has enabled Debugging in it's manifiest. This feature allows an attacker to debug native code and sensitive information could be retrived using this vector,,Set to false debuging features in production releases,,
1932 ,EN-Flash Crossdomain policy,The application publishes a Flash cross-domain policy which allows access from any domain.,,The policy must include the domains which are allowed by the Flash cross-domain policy,Medium,
1933 ,EN-Session Token in URL,The Session token is included in the URL. This could leak the session token,,Session tokens should only be included using safe channels,Medium,
1934 ,ES-Token de Session en URL,"Información sensible dentro de las URLs puede ser guardado en distintas lugares, por ejemplo en la información del navegador del usuario, en el webserver, o en cualquier proxy o reverse proxy. Las URLs se pueden ver en las pantallas, puede ser guardadas como favoritos o pueden ser enviada entre los usuarios. Esta información puede ser obtenida también como referer, en el histórico de la ultima pagina desde donde se ingresa a otra pagina. Guardar la sesiones en las URLs incrementa que esa información sea captura por un atacante para luego impersonarse como un usuario valido.",,La aplicación debería utilizar otros mecanismos para el envió de las sessiones como cookies o campos ocultos enviados a traves de métodos de POST ,Medium,
1935 ,ES-Autenticacion sin HTTPS,"La aplicación web no utiliza HTTPS para la autenticación de usuarios al sistema. Las credenciales de usuario y contraseña, viajan en texto plano con lo cual un atacante podría obtener dichas credenciales para un posterior acceso",,Siempre utilizar HTTPS para autenticar usuarios,High,
1936 ,Es-Version Obsoleta / Desactualizada,"El servidor se encuentra utilizando una versión de Apache Tomcat MUY desactualizada (Apache Tomcat/4.1.31), la cual es vulnerable a multiples vulnerabilidades publicas. Actualmente la ultima versión estable es la 8.0.9 ",,"Recomendación actualizar y desactivar los mensajes de error del servidor, que puedan brindar información extra a un atacante",Medium,
1937 ,ES-Numero de Tarjeta en Texto Plano,"La respuesta del servidor, contiene el numero de tarjeta de crédito y otra información sensible que debería evitarse enviar en texto plano.",,Utilizar HTTPS en todo el sitio en donde la información sensible pueda ser expuesta.,High,
1938 ,ES-Server Version Discloure,El servidor web responde con la version del sistema facilitando a un atacante saber contra que se enfrenta,,"Filtrar en las respuestas del servidor, cualquier dato que demuestre la version del servidor y del sistema operativo del mismo",Low,
1939 ,EN-Insecure crossdomain.xml file,"The browser security model normally prevents web content from one domain from accessing data from another domain. This is commonly known as the ""same origin policy"". URL policy files grant cross-domain permissions for reading data. They permit operations that are not permitted by default. The URL policy file is located, by default, in the root directory of the target server, with the name crossdomain.xml (for example, at www.example.com/crossdomain.xml).
1940
1941 When a domain is specified in crossdomain.xml file, the site declares that it is willing to allow the operators of any servers in that domain to obtain any document on the server where the policy file resides. The crossdomain.xml file deployed on this website opens the server to all domains (use of a single asterisk ""*"" as a pure wildcard is supported) like so:
1942 <cross-domain-policy>
1943 <allow-access-from domain=""*"" />
1944 </cross-domain-policy>
1945 This practice is suitable for public servers, but should not be used for sites located behind a firewall because it could permit access to protected areas. It should not be used for sites that require authentication in the form of passwords or cookies. Sites that use the common practice of authentication based on cookies to access private or user-specific data should be especially careful when using cross-domain policy files.
1946
1947 Using an insecure cross-domain policy file could expose your site to various attacks.",,"Carefully evaluate which sites will be allowed to make cross-domain calls. Consider network topology and any authentication mechanisms that will be affected by the configuration or implementation of the cross-domain policy.
1948 ",Medium,
1949 ,ES-Archivo crossdomain.xml inseguro,"El modelo de seguridad del navegador normalmente previene el contenido web de ser accedido desde otro dominio. Esto comunmente es conocido como ""same origin policy"" (""politica del mismo origen""). Lo politica de archivos URL garantiza acceso cross-dominio para leer datos. Permiten operaciones que no son permitidas por defecto. La politica de acceso de archivo URL esta localizado, por defecto, en el directorio raiz del servidor destino, con el nombre crossdomain.xml (por ejemplo en www.ejemplo.com/crossdomain.xml).
1950
1951 Cuando un dominio es especificado en el archivo crossdomain.xml, el sitio declara que esta dispuesto a dar acceso a operadores de cualqueir server en ese dominio para obtener cualquier documento donde la regla reside. El archivo crossdomain.xml desplegado en este servidor web abre el servidor a todos los dominios (uso de un unico asterisco ""*"" de comodin es soportado) Como por ejemplo:
1952 <cross-domain-policy>
1953 <allow-access-from domain=""*"" />
1954 </cross-domain-policy>
1955
1956 Esta practica es correcta para servidores publicos, pero no deberia ser usada en servidores que se encuentran tras un firewall porque puede permitir acceso a areas protejidas. No deberia ser usada para sitios que requieren autenticacion en forma de contraseñas o cookies. ",,"Detenidamente evaluar que sitios deben tener permitido el acceso cross-dominio. Considerar la topologia de red y todos los mecanismos de autenticacion afectados por la configuracion o implementacion de la politica cross-domain.
1957 ",Medium,
1958 ,EN-BREACH attack,"This web application is potentially vulnerable to the BREACH attack.
1959 An attacker with the ability to:
1960 Inject partial chosen plaintext into a victim's requests
1961 Measure the size of encrypted traffic
1962 can leverage information leaked by compression to recover targeted parts of the plaintext.
1963
1964 BREACH (Browser Reconnaissance & Exfiltration via Adaptive Compression of Hypertext) is a category of vulnerabilities and not a specific instance affecting a specific piece of software. To be vulnerable, a web application must:
1965
1966 Be served from a server that uses HTTP-level compression
1967 Reflect user-input in HTTP response bodies
1968 Reflect a secret (such as a CSRF token) in HTTP response bodies
1969
1970
1971 This alert was issued because the following conditions were met:
1972 The page content is served via HTTPS
1973 The server is using HTTP-level compression
1974 URL encoded GET input next was reflected into the HTTP response body.
1975 HTTP response body contains a secret named csrfmiddlewaretoken",,"The mitigations are ordered by effectiveness (not by their practicality - as this may differ from one application to another).
1976
1977 Disabling HTTP compression
1978 Separating secrets from user input
1979 Randomizing secrets per request
1980 Masking secrets (effectively randomizing by XORing with a random secret per request)
1981 Protecting vulnerable pages with CSRF
1982 Length hiding (by adding random number of bytes to the responses)
1983 Rate-limiting the requests
1984
1985 More information http://breachattack.com/",,
1986 ,ES-Archivos de backup en servidor de producción,"La aplicación web tiene multiples archivos de buckup disponibles para ser descargados, los cuales brindan información de la tecnología que se utiliza en el sitio, así como código fuente de las aplicaciones, nombres de usuarios, rutas de acceso y multiple información sensible del mismo.",,"Es recomendable aplicar buenas politicas deprotección de información sensible, evitando exponer buckups y otra información del sitio web",Very High,
1987 ,ES-Exposición de información a través del listado de directorios,"Estos directorios no deberian estar publicos, pues exponen información sensible del tipo de tecnología utilizada, código de programación, información sobre rutas de acceso a distintos lugares, particularmente en este caso podemos listar toda la información del servidor sin ningun tipo de restricción",,Siempre evitar que se puedan listar directorios de manera externa y sin permisos,High,
1988 ,ES-Archivos con información sensible,"Es posible acceder a archivos con información sensible, podemos ver el ""log error"" y dentro de este rutas de acceso, nombres de usuario, etc . Con lo cual un atacante con tiempo podría intentar obtener credeciales de un servicio ssh, ftp,o similar para luego crackearlo.
1989 ",,Evitar exponer toda información sensible del sistema,High,
1990 ,ES-Revelación de IP interno,"La aplicación expone ip/s interno, con lo cual si por algun vector de ataque un atacante logra acceder al servidor o servicio podría continuar la explotación por dicho vector",,Evitar exponer toda información sensible y privada del sistemadel sistema,Low,
1991 ,ES-Archivos e información de desarollo en ambientes productivos,"Podemos ver código de programacion, con ejemplos concretos del funcionamiento interno y
1992 de la lógica utilizada a la hora de programar, dejando en evidencia
1993 informacion como nombres de usuarios, email, dni, telefonos, etc ",,Evitar exponer toda información sensible y privada del sistemadel sistema,High,
1994 ,ES-Sentencias SQL sin Prepared Statement,Se detecto que se utilizan una mala implementacion de sentencias SQL concatenando las variables manualmente pudiendo un atacante realizar ataques de SQL Injection,,"Utilizar para la sentencia de SQL Prepared Statement
1995 Reference:
1996 https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet#Prepared_Statement_Examples",High,
1997 ,ES-Mysql lectura y escritura de archivos,Es posible utilizar mysql server para la lectura y escritura de archivos en el servidor,,"Seguir los siguientes lineamientos para el hardening de Mysql Server
1998 https://www.owasp.org/index.php/Testing_for_MySQL#Read_from_a_File",High,
1999 ,ES-Servidor productivo y desarrollo,"Por lo que pudimos observar este servidor sirve tanto para produccion como desarrollo, contiene muchisima informacion y pruebas que deberian ser eliminadas.",,"Eliminar el contenido de desarrollo, dejar solo lo necesario para el entorno productivo",High,
2000 ,ES-Servidor productivo y desarrollo,"Por lo que pudimos observar este servidor sirve tanto para produccion como desarrollo, contiene muchisima informacion y pruebas que deberian ser eliminadas.",,"Eliminar el contenido de desarrollo, dejar solo lo necesario para el entorno productivo",High,
2001 ,EN-Internal IP Address Disclosure,A string matching an internal IPv4 address was found on this page. This may disclose information about the IP addressing scheme of the internal network. This information can be used to conduct further attacks.,,Prevent this information from being displayed to the user,Low,
2002 ,ES-Internal IP Address Disclosure,Una cadena coincidente con una direccion interna de IPv4 fue encontrada en esta pagina. Esto lleva a divulgar informacion sensible acerca del esquema de la red interna. Esta informacion puede ser usada para generar ataques especificos.,,Se recomienda prevenir que esta informacion sea mostrada al usuario,Low,
2003 ,EN-ASP.NET MAC disabled,"By default, the serialized value is signed by the server to prevent tampering by the user; however, this behavior can be disabled by setting the Page.EnableViewStateMac property to false. If this is done, then an attacker can modify the contents of the ViewState and cause arbitrary data to be deserialized and processed by the server. If the ViewState contains any items that are critical to the server's processing of the request, then this may result in a security exposure.",,Set the Page.EnableViewStateMac property to true on any pages where the ViewState is not currently signed.,Low,
2004 ,ES-Cisco ASA Error,"El Cisco ASA es vulnerable a un Information Leak (CVE-2014-3392), un atacante podria obtener credenciales em base a un error.",,Actualizar a la ultima version del firmware del CISCO ASA,High,
2005 ,ES-Listado de directorios,"Evitar listar directorios, muchas veces a partir de aqui se pueden realizar distintos vectores de ataques, por claves almacenadas en archivos ocultos o por tener acceso a archivos de configuracion. ",,"Evitar listar directorios, es recomendable que se desabiliten o se resguarden con algun tipo de autenticacion.",Low,
2006 ,EN-Cifrado Debil (SSL weak ciphers),"El host remoto es compatible con el uso de sistemas de cifrado SSL que ofrecen ya sea cifrado debil o sin cifrado en absoluto.
2007 Esta vulnerabilidad afecta Server.",,Vuelva a configurar la aplicacion afectada para evitar el uso de cifrados debiles.,Medium,
5353 elif [ "$os" = "Ubuntu 13.04" ]; then
5454 version="ubuntu13-04-$arch"
5555 down=1
56 elif [[ "$os" =~ "Ubuntu 14.04".*|"Ubuntu 14.10".*|"Ubuntu Vivid Vervet (development branch)"|"Debian 8.0".*|"Ubuntu 15".* ]]; then
56 elif [[ "$os" =~ "Ubuntu 14.04".*|"Ubuntu 14.10".*|"Ubuntu Vivid Vervet (development branch)"|"Debian 8.".*|"Ubuntu 15".* ]]; then
5757 version="ubuntu13-10-$arch"
5858 down=1
5959 # Install pip from github.
0 #!/usr/bin/env python2.7
1 '''
2 Faraday Penetration Test IDE
3 Copyright (C) 2014 Infobyte LLC (http://www.infobytesec.com/)
4 See the file 'doc/LICENSE' for the license information
5
6 '''
7 import argparse
8 import os
9 from couchdbkit import Server, designer
10 import json
11 import csv
12
13
14 def main():
15
16 #arguments parser
17 parser = argparse.ArgumentParser(prog='pushExecutiveReports', epilog="Example: ./%(prog)s.py")
18 parser.add_argument('-c', '--couchdburi', action='store', type=str,
19 dest='couchdb',default="http://127.0.0.1:5984",
20 help='Couchdb URL (default http://127.0.0.1:5984)')
21
22 #arguments put in variables
23 args = parser.parse_args()
24
25 #default value from ENV COUCHDB
26 couchdb = os.environ.get('COUCHDB')
27 #Else from argument
28 if not couchdb:
29 couchdb = args.couchdb
30 __serv = Server(uri = couchdb)
31
32 # reports = os.path.join(os.getcwd(), "views", "reports")
33 workspace = __serv.get_or_create_db("cwe")
34 # designer.push(reports, workspace, atomic = False)
35
36 with open('data/cwe.csv', 'r') as csvfile:
37 cwereader = csv.reader(csvfile, delimiter=',')
38 header = cwereader.next()
39 for cwe in cwereader:
40 cwe_doc = dict(zip(header, cwe))
41 workspace.save_doc(cwe_doc)
42
43 if __name__ == "__main__":
44 main()
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 describe('StatusReport modalNewVulnCtrl', function() {
5 var $controller,
6 vm,
7 $scope;
8
9 var $cweFact,
10 cweFact,
11 targetFactMock;
12
13 var returnPromise;
14
15 var modalInstance;
16
17 beforeEach(function () {
18 module('faradayApp');
19
20 inject(function(_$rootScope_, _$controller_, _$q_) {
21 // The injector unwraps the underscores (_) from around the parameter names when matching
22 $scope = _$rootScope_.$new();
23 returnPromise = function(res) {
24 var deferred = _$q_.defer();
25 deferred.resolve(res);
26 return deferred.promise;
27 }
28
29 rejectPromise = function(res) {
30 var deferred = _$q_.defer();
31 deferred.reject(res);
32 return deferred.promise;
33 }
34
35 targetFactMock = {
36 getTargets: function(ws) {
37 return returnPromise([
38 {
39 _id: "1",
40 name: "host1",
41 hostnames: ['test1.faradaysec.com'],
42 services:[
43 {
44 _id: "1.1.1",
45 name: "srv1"
46 },
47 {
48 _id: "1.1.2",
49 name: "srv2"
50 }
51 ]
52 },
53 {
54 _id: "2",
55 name: "host2",
56 hostnames: ['test2.faradaysec.com'],
57 services:[
58 {
59 _id: "2.1.1",
60 name: "srv1"
61 },
62 {
63 _id: "2.1.2",
64 name: "srv2"
65 }
66 ]
67 },
68 {
69 _id: "3",
70 name: "host3",
71 hostnames: ['test3.faradaysec.com'],
72 services:[
73 {
74 _id: "3.1.1",
75 name: "srv1"
76 },
77 {
78 _id: "3.1.2",
79 name: "srv2"
80 }
81 ]
82 }
83 ])
84 }
85 }
86
87 cweFactMock = {
88 get: function() {
89 return returnPromise([]);
90 }
91 }
92
93 modalInstance = {
94 close: jasmine.createSpy('modalInstance.close'),
95 dismiss: jasmine.createSpy('modalInstance.dismiss')
96 }
97
98 $controller = _$controller_('modalNewVulnCtrl', {
99 $scope: $scope,
100 $modalInstance: modalInstance,
101 EASEOFRESOLUTION: ['simple', 'moderate', 'hard'],
102 severities: ['low', 'medium', 'high'],
103 workspace: 'test',
104 targetFact: targetFactMock,
105 cweFact: cweFactMock
106 });
107
108 });
109 });
110
111
112 describe('Modal controller init function', function() {
113 beforeEach(function() {
114 vm = $controller;
115 });
116 it('controller variables loaded', function() {
117 $scope.$apply();
118 vm.targets.forEach(function(target, j) {
119 expect(target.name).toEqual("host" + (j + 1));
120 expect(target.hostnames).toEqual(["test" + (j + 1) + ".faradaysec.com"]);
121 target.services.forEach(function(services, k) {
122 expect(services._id).toEqual((j + 1) + ".1." + (k + 1));
123 expect(services.name).toEqual("srv" + (k + 1));
124 });
125 });
126 });
127 });
128
129 describe('Modal controller functions', function() {
130 beforeEach(function() {
131 vm = $controller;
132 });
133 it('object changed after execution of toggleImpact function', function() {
134 $scope.$apply();
135 expect(vm.data.impact['accountability']).toEqual(false);
136 vm.toggleImpact('accountability');
137 expect(vm.data.impact['accountability']).toEqual(true);
138 });
139 it('add variable to data.refs after execution of newReference function', function() {
140 $scope.$apply();
141 vm.new_ref = "This is a new Reference";
142 vm.newReference();
143 expect(vm.data.refs).toContain({value: 'This is a new Reference'});
144
145 vm.new_ref = "This is another reference";
146 vm.newReference();
147 expect(vm.data.refs).toContain({value: 'This is another reference'});
148 });
149 it('selected is true of data.parent object execution of setTarget function', function() {
150 $scope.$apply();
151 var target = vm.targets[0];
152 vm.setTarget(target);
153 expect(vm.data.parent).toEqual(target);
154 expect(vm.data.parent.selected_modalNewCtrl).toEqual(true);
155
156 //if a service is the target
157 var service_target = target.services[0];
158 vm.setTarget(target.services[0]);
159 expect(vm.data.parent).toEqual(service_target);
160 expect(vm.data.parent.selected_modalNewCtrl).toEqual(true);
161 });
162 it('variables have proper values after execution of ok function', function() {
163 $scope.$apply();
164 var vuln = {
165 data: "data",
166 desc: "desc",
167 easeofresolution: "simple",
168 evidence: {"name": "evidence", "type":"image/vnd.microsoft.icon"},
169 impact: {
170 "accountability": true,
171 "availability": true,
172 "confidentiality": false,
173 "integrity": false
174 },
175 method: "method",
176 name: "name",
177 owned: true,
178 params: "params",
179 parent: {"_id":"d037090bfc65d5d94e95c9da29a2803249a65e0b","type":"Service"},
180 path: "path",
181 pname: "pname",
182 query: "query",
183 refs: [{value: "ref1"}, {value: "ref2"}],
184 request: "request",
185 resolution: "resolution",
186 response: "response",
187 severity: "info",
188 type: "VulnerabilityWeb",
189 website: "website"
190 };
191
192 for(var key in vuln){
193 if (vuln.hasOwnProperty(key)) {
194 vm.data[key] = vuln[key];
195 }
196 }
197 vm.ok();
198 expect(vm.data.data).toEqual('data');
199 expect(vm.data.desc).toEqual('desc');
200 expect(vm.data.easeofresolution).toEqual('simple');
201 expect(vm.data.evidence).toEqual({"name": "evidence", "type": "image/vnd.microsoft.icon"});
202 expect(vm.data.impact).toEqual({"accountability": true, "availability": true, "confidentiality": false, "integrity": false});
203 expect(vm.data.method).toEqual('method');
204 expect(vm.data.name).toEqual('name');
205 expect(vm.data.owned).toEqual(true);
206 expect(vm.data.params).toEqual('params');
207 expect(vm.data.parent).toEqual('d037090bfc65d5d94e95c9da29a2803249a65e0b');
208 expect(vm.data.path).toEqual('path');
209 expect(vm.data.pname).toEqual('pname');
210 expect(vm.data.query).toEqual('query');
211 expect(vm.data.refs).toContain('ref1');
212 expect(vm.data.refs).toContain('ref2');
213 expect(vm.data.request).toEqual('request');
214 expect(vm.data.resolution).toEqual('resolution');
215 expect(vm.data.response).toEqual('response');
216 expect(vm.data.severity).toEqual('info');
217 expect(vm.data.type).toEqual('VulnerabilityWeb');
218 expect(vm.data.website).toEqual('website');
219 });
220 });
221 });
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 describe('statusReportCtrl', function() {
5 var $controller,
6 $scope;
7
8 var $vulnsManager,
9 vulnsManagerMock,
10 $hostsManager,
11 hostsManagerMock,
12 $workspacesFact,
13 workspacesFactMock,
14 vuln1, vuln2, vuln3;
15
16 var returnPromise;
17
18 var fakeModal = {
19 result: {
20 then: function(confirmCallback, cancelCallback) {
21 //Store the callbacks for later when the user clicks on the OK or Cancel button of the dialog
22 this.confirmCallBack = confirmCallback;
23 this.cancelCallback = cancelCallback;
24 }
25 },
26 close: function(item) {
27 //The user clicked OK on the modal dialog, call the stored confirm callback with the selected item
28 this.result.confirmCallBack(item);
29 },
30 dismiss: function(type) {
31 //The user clicked cancel on the modal dialog, call the stored cancel callback
32 if (this.result.cancelCallback) this.result.cancelCallback(type);
33 }
34 };
35
36 beforeEach(function () {
37 module('faradayApp');
38
39 inject(function(_$rootScope_, _$controller_, _$q_, _$modal_) {
40 // The injector unwraps the underscores (_) from around the parameter names when matching
41 $scope = _$rootScope_.$new();
42 // workspaces variables
43 vuln1 = {
44 "_id": "1.2.3.4",
45 "_rev": "1-abe16726389e434ca3f37384ea76128e",
46 "name": "Internet Key Exchange (IKE) Aggressive Mode with Pre-Shared Key",
47 "parent": "1.2.3",
48 "resolution": "Be careful",
49 "refs": [
50 "CVE-2002-1623",
51 "7423",
52 "OSVDB:3820, CERT:886601"
53 ],
54 "metadata": {
55 "update_time": 1429643049.395857,
56 "update_user": "john",
57 "update_action": 0,
58 "creator": "john",
59 "create_time": 1429643049.395857,
60 "update_controller_action": "ModelControler.newVuln",
61 "owner": "john"
62 },
63 "owned": false,
64 "severity": "med",
65 "type": "Vulnerability",
66 "owner": "john",
67 "desc": "I'm scared!",
68 "data": "",
69 "description": "I'm scared!"
70 };
71 vuln2 = {
72 "_id": "1.2.3.5",
73 "_rev": "1-abe16726389e434ca3f37384ea76128e",
74 "name": "Another vuln",
75 "parent": "1.2.3",
76 "resolution": "Be careful",
77 "refs": [
78 "CVE-2002-1623",
79 "7423",
80 "OSVDB:3820, CERT:886601"
81 ],
82 "metadata": {
83 "update_time": 1429643049.395857,
84 "update_user": "john",
85 "update_action": 0,
86 "creator": "john",
87 "create_time": 1429643049.395857,
88 "update_controller_action": "ModelControler.newVuln",
89 "owner": "john"
90 },
91 "owned": false,
92 "severity": "med",
93 "type": "Vulnerability",
94 "owner": "john",
95 "desc": "I'm scared!",
96 "data": "",
97 "description": "I'm scared!"
98 };
99 vuln3 = {
100 "_id": "6.7.8.9",
101 "_rev": "3-f34c61eca3cb5ffc5654f710774708af",
102 "desc": "It was possible to identify the remote service by its banner.",
103 "metadata": {
104 "update_time": 1407530638.669383,
105 "update_user": "",
106 "update_action": 0,
107 "creator": "",
108 "create_time": 1407530638.669383,
109 "update_controller_action": "No model controller call",
110 "owner": ""
111 },
112 "name": "Service Detection",
113 "obj_id": "008cba9b11897f2d52c53dd953d75fa233a7fffe",
114 "owned": false,
115 "owner": "",
116 "parent": "6.7.8",
117 "refs": [
118 ],
119 "severity": "low",
120 "type": "VulnerabilityWeb",
121 "method": "",
122 "params": "",
123 "path": "",
124 "pname": "",
125 "query": "",
126 "request": "",
127 "response": "",
128 "website": "test.test.com"
129 };
130
131
132 returnPromise = function(res) {
133 var deferred = _$q_.defer();
134 deferred.resolve(res);
135 return deferred.promise;
136 }
137
138 rejectPromise = function(res) {
139 var deferred = _$q_.defer();
140 deferred.reject(res);
141 return deferred.promise;
142 }
143
144 workspacesFactMock = {
145 list: function() {
146 return returnPromise(['ws1', 'ws2'])
147 }
148 }
149
150 hostsManagerMock = {
151 }
152
153 vulnsManagerMock = {
154 vulns: [],
155 getVulns: function(workspace) {
156 vulnsManagerMock.vulns = [vuln1, vuln2, vuln3];
157 return returnPromise(vulnsManagerMock.vulns);
158 },
159 deleteVuln: function(vuln) {
160 if (vuln._id === "1.2.3.4" ||
161 vuln._id === "1.2.3.5" ||
162 vuln._id === "6.7.8.9") {
163 for (var i = 0; i < vulnsManagerMock.vulns.length; i++) {
164 var v = vulnsManagerMock.vulns[i];
165 if (v._id == vuln._id) {
166 vulnsManagerMock.vulns.splice(i, 1);
167 break;
168 }
169 };
170 return returnPromise(vulnsManagerMock.vulns);
171 } else {
172 return rejectPromise("error");
173 }
174 },
175 createVuln: function(workspace, vuln) {
176 vuln["id"] = "1.2.3.6";
177 vulnsManagerMock.vulns.push(vuln);
178 return returnPromise(vuln);
179 },
180 updateVuln: function(vuln, vulnData) {
181 if (vuln._id === "1.2.3.4" ||
182 vuln._id === "1.2.3.5" ||
183 vuln._id === "6.7.8.9") {
184 angular.extend(vuln, vulnData);
185 return returnPromise();
186 } else {
187 return rejectPromise("error");
188 }
189 }
190
191 };
192
193 // fakeModal
194 spyOn(_$modal_, 'open').and.returnValue(fakeModal);
195
196 $controller = _$controller_('statusReportCtrl', {
197 $scope: $scope,
198 vulnsManager: vulnsManagerMock,
199 hostsManager: hostsManagerMock,
200 workspacesFact: workspacesFactMock,
201 $routeParams: {wsId: 'ws1'},
202 $modal: _$modal_
203 });
204 });
205 });
206
207
208 describe('Status report init function without filter', function() {
209 it('vulns loaded after execution', function() {
210 $scope.$apply();
211 expect($scope.vulns.length).toEqual(3);
212 expect($scope.vulns).toContain(vuln1);
213 expect($scope.vulns).toContain(vuln2);
214 expect($scope.vulns).toContain(vuln3);
215 });
216 });
217
218 describe('Status report vuln deletion - remove method', function() {
219 it('remove valid vuln id 1.2.3.4', function() {
220 $scope.remove([vuln1]);
221 $scope.$apply();
222
223 expect($scope.vulns.length).toEqual(2);
224 expect($scope.vulns).not.toContain(vuln1);
225 expect($scope.vulns).toContain(vuln2);
226 expect($scope.vulns).toContain(vuln3);
227 });
228 it('remove invalid vuln id 9.9.9.9', function() {
229 vuln = {"_id": "9.9.9.9"}
230 $scope.remove([vuln]);
231 $scope.$apply();
232
233 expect($scope.vulns.length).toEqual(3);
234 expect($scope.vulns).toContain(vuln1);
235 expect($scope.vulns).toContain(vuln2);
236 expect($scope.vulns).toContain(vuln3);
237 });
238 it('remove valid id 1.2.3.4 and invalid id 9.9.9.9', function() {
239 vuln = {"_id": "9.9.9.9"}
240 $scope.remove([vuln1, vuln]);
241 $scope.$apply();
242
243 expect($scope.vulns.length).toEqual(2);
244 expect($scope.vulns).not.toContain(vuln1);
245 expect($scope.vulns).toContain(vuln2);
246 expect($scope.vulns).toContain(vuln3);
247 });
248 it('remove valid vulns ids', function() {
249 $scope.remove([vuln1, vuln2]);
250 $scope.$apply();
251
252 expect($scope.vulns.length).toEqual(1);
253 expect($scope.vulns).not.toContain(vuln1);
254 expect($scope.vulns).not.toContain(vuln2);
255 expect($scope.vulns).toContain(vuln3);
256 });
257 });
258
259 describe('Status report vuln deletion - delete method (modal)', function() {
260 it('call delete with no vulns selected', function() {
261 // we need $scope.vulns to have all the vulns before calling
262 // the delete method
263 $scope.$apply();
264 $scope.delete();
265 $scope.$apply();
266
267 expect($scope.vulns.length).toEqual(3);
268 expect($scope.vulns).toContain(vuln1);
269 expect($scope.vulns).toContain(vuln2);
270 expect($scope.vulns).toContain(vuln3);
271 });
272 it('call delete with a valid vuln (1.2.3.4) selected and accept modal', function() {
273 // we need $scope.vulns to have all the vulns before calling
274 // the delete method
275 vuln1.selected_statusreport_controller = true;
276 $scope.$apply();
277 $scope.delete();
278 fakeModal.close();
279 $scope.$apply();
280
281 expect($scope.vulns.length).toEqual(2);
282 expect($scope.vulns).not.toContain(vuln1);
283 expect($scope.vulns).toContain(vuln2);
284 expect($scope.vulns).toContain(vuln3);
285 });
286 it('call delete with a valid vuln (1.2.3.4) selected and cancel modal', function() {
287 // we need $scope.vulns to have all the vulns before calling
288 // the delete method
289 vuln1.selected_statusreport_controller = true;
290 $scope.$apply();
291 $scope.delete();
292 fakeModal.dismiss();
293 $scope.$apply();
294
295 expect($scope.vulns.length).toEqual(3);
296 expect($scope.vulns).toContain(vuln1);
297 expect($scope.vulns).toContain(vuln2);
298 expect($scope.vulns).toContain(vuln3);
299 });
300 it('call delete with valid vulns selected and accept modal', function() {
301 vuln1.selected_statusreport_controller = true;
302 vuln2.selected_statusreport_controller = true;
303 $scope.$apply();
304 $scope.delete();
305 fakeModal.close();
306 $scope.$apply();
307
308 expect($scope.vulns.length).toEqual(1);
309 expect($scope.vulns).not.toContain(vuln1);
310 expect($scope.vulns).not.toContain(vuln2);
311 expect($scope.vulns).toContain(vuln3);
312 });
313 });
314
315 describe('Status report vuln creation - insert method', function() {
316 it('create a valid vuln', function() {
317 var vulnNew = {
318 "name": "Just a test vuln",
319 "parent": "1.2.3",
320 "resolution": "Be careful",
321 "refs": [
322 "test"
323 ],
324 "metadata": {
325 "update_time": 1429643049.395857,
326 "update_user": "john",
327 "update_action": 0,
328 "creator": "john",
329 "create_time": 1429643049.395857,
330 "update_controller_action": "",
331 "owner": "john"
332 },
333 "owned": false,
334 "severity": "med",
335 "type": "Vulnerability",
336 "owner": "john",
337 "desc": "Test!",
338 "data": "",
339 "description": "Test!"
340 };
341 $scope.insert(vulnNew);
342 $scope.$apply();
343
344 expect($scope.vulns.length).toEqual(4);
345 expect($scope.vulns).toContain(vulnNew);
346 });
347 it('create a duplicated vuln', function() {
348 var vulnNew = {
349 "name": "Just a test vuln",
350 "parent": "1.2.3",
351 "resolution": "Be careful",
352 "refs": [
353 "test"
354 ],
355 "metadata": {
356 "update_time": 1429643049.395857,
357 "update_user": "john",
358 "update_action": 0,
359 "creator": "john",
360 "create_time": 1429643049.395857,
361 "update_controller_action": "",
362 "owner": "john"
363 },
364 "owned": false,
365 "severity": "med",
366 "type": "Vulnerability",
367 "owner": "john",
368 "desc": "Test!",
369 "data": "",
370 "description": "Test!"
371 };
372
373 // we change the mock to simulate an error during creation
374 spyOn(vulnsManagerMock, 'createVuln').and.returnValue(
375 rejectPromise("error"));
376 $scope.insert(vulnNew);
377 $scope.$apply();
378
379 expect($scope.vulns.length).toEqual(3);
380 expect($scope.vulns).not.toContain(vulnNew);
381 });
382 });
383
384 describe('Status report vuln creation - new method (modal)', function() {
385 it('create a valid vuln and accept modal', function() {
386 var vulnNew = {
387 "name": "Just a test vuln",
388 "parent": "1.2.3",
389 "resolution": "Be careful",
390 "refs": [
391 "test"
392 ],
393 "metadata": {
394 "update_time": 1429643049.395857,
395 "update_user": "john",
396 "update_action": 0,
397 "creator": "john",
398 "create_time": 1429643049.395857,
399 "update_controller_action": "",
400 "owner": "john"
401 },
402 "owned": false,
403 "severity": "med",
404 "type": "Vulnerability",
405 "owner": "john",
406 "desc": "Test!",
407 "data": "",
408 "description": "Test!"
409 };
410 $scope.new();
411 fakeModal.close(vulnNew);
412 $scope.$apply();
413
414 expect($scope.vulns.length).toEqual(4);
415 expect($scope.vulns).toContain(vulnNew);
416 });
417 it('create a valid vuln but cancel modal', function() {
418 var vulnNew = {
419 "name": "Just a test vuln",
420 "parent": "1.2.3",
421 "resolution": "Be careful",
422 "refs": [
423 "test"
424 ],
425 "metadata": {
426 "update_time": 1429643049.395857,
427 "update_user": "john",
428 "update_action": 0,
429 "creator": "john",
430 "create_time": 1429643049.395857,
431 "update_controller_action": "",
432 "owner": "john"
433 },
434 "owned": false,
435 "severity": "med",
436 "type": "Vulnerability",
437 "owner": "john",
438 "desc": "Test!",
439 "data": "",
440 "description": "Test!"
441 };
442
443 $scope.new();
444 fakeModal.dismiss();
445 $scope.$apply();
446
447 expect($scope.vulns.length).toEqual(3);
448 expect($scope.vulns).not.toContain(vulnNew);
449 });
450 });
451
452 describe('Status report vuln edition - update method', function() {
453 //TODO: test each editable property
454 });
455
456 describe('Status report vuln edition - edit method (modal)', function() {
457 it('edit a vuln and accept modal', function() {
458 var vulnData = {
459 "name": "Changed name",
460 "resolution": "New resolution",
461 "refs": [
462 "test",
463 "another ref"
464 ],
465 "owned": true,
466 "severity": "high"
467 };
468
469 vuln1.selected_statusreport_controller = true;
470
471 $scope.$apply();
472 $scope.edit();
473 fakeModal.close(vulnData);
474 $scope.$apply();
475
476 expect($scope.vulns.length).toEqual(3);
477 $scope.vulns.forEach(function(vuln) {
478 if (vuln._id == "1.2.3.4") {
479 expect(vuln.name).toEqual("Changed name");
480 expect(vuln.resolution).toEqual("New resolution");
481 expect(vuln.refs.length).toEqual(2);
482 expect(vuln.owned).toEqual(true);
483 expect(vuln.severity).toEqual("high");
484
485 }
486 });
487
488 });
489 it('edit a valid vuln but cancel modal', function() {
490 var vulnData = {
491 "name": "Changed name",
492 "resolution": "New resolution",
493 "refs": [
494 "test",
495 "another ref"
496 ],
497 "owned": true,
498 "severity": "high"
499 };
500 vuln1.selected_statusreport_controller = true;
501 $scope.$apply();
502 //$scope.edit();
503 //fakeModal.dismiss();
504 //$scope.$apply();
505
506 expect($scope.vulns.length).toEqual(3);
507 $scope.vulns.forEach(function(vuln) {
508 if (vuln._id == "1.2.3.4") {
509 expect(vuln.name).not.toEqual("Changed name");
510 expect(vuln.resolution).not.toEqual("New resolution");
511 expect(vuln.refs.length).not.toEqual(2);
512 expect(vuln.owned).not.toEqual(true);
513 expect(vuln.severity).not.toEqual("high");
514
515 }
516 });
517 });
518 });
519 });
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 describe('Vulnerability Object', function() {
5 var Vuln,
6 $httpBackend,
7 BASEURL;
8
9 var new_data,
10 new_name,
11 new_id,
12 new_id_parent,
13 new_full_id,
14 old_data,
15 old_name,
16 old_id,
17 old_id_parent,
18 old_full_id;
19
20 // Set up the module
21 beforeEach(module('faradayApp'));
22
23 beforeEach(inject(function($injector, _$httpBackend_, _$q_, _Vuln_, _attachmentsFact_) {
24 $httpBackend = _$httpBackend_;
25 $q = _$q_;
26 Vuln = _Vuln_;
27 attachmentsFact = _attachmentsFact_;
28 BASEURL = 'http://localhost:9876/';
29
30 new_name = "new name";
31 new_desc = "new desc";
32 new_id = CryptoJS.SHA1(new_name + "." + new_desc).toString();
33 new_id_parent = CryptoJS.SHA1("parent").toString();
34 new_full_id = new_id_parent + "." + new_id;
35
36 new_data = {
37 "data": "data",
38 "desc": new_desc,
39 "easeofresolution": "easeofresolution",
40 "impact": "impact",
41 "name": new_name,
42 "owned": false,
43 "parent": new_id_parent,
44 "refs": "refs",
45 "resolution": "resolution",
46 "severity": "severity",
47 "ws": "ws"
48 };
49
50 // this is used to create a web vuln that "already exists"
51 var now = new Date(),
52 old_date = now.getTime();
53
54 old_name = "old name";
55 old_desc = "old desc";
56 old_id = CryptoJS.SHA1(old_name + "." + old_desc).toString();
57 old_id_parent = CryptoJS.SHA1("parent").toString();
58 old_full_id = old_id_parent + "." + old_id;
59
60 old_data = {
61 "_id": old_full_id,
62 "_rev": "1-lalalala",
63 "data": "data",
64 "desc": old_desc,
65 "easeofresolution": "easeofresolution",
66 "impact": "impact",
67 "metadata": {
68 "update_time": old_date,
69 "update_user": "update_user",
70 "update_action": "update_action",
71 "creator": "creator",
72 "create_time": old_date,
73 "update_controller_action": "update_controller_action",
74 "owner": "owner"
75 },
76 "name": old_name,
77 "owned": false,
78 "parent": old_id_parent,
79 "refs": "refs",
80 "resolution": "resolution",
81 "severity": "severity",
82 "ws": "ws"
83 };
84 }));
85
86 afterEach(function() {
87 $httpBackend.verifyNoOutstandingExpectation();
88 $httpBackend.verifyNoOutstandingRequest();
89 });
90
91 describe('CRUD with invalid data', function() {
92 it('Setting new object', function() {
93 delete new_data.name;
94
95 expect(function() { new Vuln('ws', new_data); }).toThrowError(Error, "Unable to create Vuln without a name");
96 });
97 });
98
99 describe('CRUD with valid data', function() {
100 it('Setting new object', function() {
101 vuln = new Vuln('ws', new_data);
102
103 expect(vuln._id).toBeDefined();
104 expect(vuln._id).toEqual(new_full_id);
105 expect(vuln.type).toEqual("Vulnerability");
106
107 for(var prop in new_data) {
108 if(new_data.hasOwnProperty(prop)) {
109 expect(vuln[prop]).toEqual(new_data[prop]);
110 }
111 }
112 });
113
114 it('Setting existing object', function() {
115 vuln = new Vuln('ws', old_data);
116
117 expect(vuln._id).toBeDefined();
118 expect(vuln._id).toEqual(old_full_id);
119
120 for(var prop in old_data) {
121 if(old_data.hasOwnProperty(prop)) {
122 if(prop != "metadata") expect(vuln[prop]).toEqual(old_data[prop]);
123 }
124 }
125 });
126
127 it('Saving new object', function() {
128 var url = BASEURL + "ws/" + new_full_id;
129 var vuln = new Vuln('ws', new_data);
130
131 $httpBackend.expect('PUT', url).respond(201, {"rev": "1234"});
132
133 vuln.save();
134
135 $httpBackend.flush();
136
137 expect(vuln._rev).toEqual("1234");
138 });
139
140 it('Saving existing object', function() {
141 var url = BASEURL + "ws/" + old_full_id;
142 var vuln = new Vuln('ws', old_data);
143
144 $httpBackend.expect('PUT', url).respond(201, {"rev": "1234"});
145
146 vuln.save();
147
148 $httpBackend.flush();
149
150 expect(vuln._rev).toEqual("1234");
151 });
152
153 it('Updating object', function() {
154 var url = BASEURL + "ws/" + new_full_id;
155 var vuln = new Vuln('ws', new_data);
156
157 $httpBackend.expect('PUT', url).respond(201, {"rev": "1234"});
158
159 delete old_data._id;
160 delete old_data._rev;
161 vuln.update(old_data);
162
163 $httpBackend.flush();
164
165 expect(vuln._rev).toEqual("1234");
166
167 for(var prop in old_data) {
168 if(old_data.hasOwnProperty(prop)) {
169 if(prop != "metadata") expect(vuln[prop]).toEqual(old_data[prop]);
170 }
171 }
172 });
173
174 it('Deleting object', function() {
175 var url = BASEURL + "ws/" + old_full_id + "?rev=" + old_data._rev;
176 var vuln = new Vuln('ws', old_data);
177
178 $httpBackend.expect('DELETE', url).respond(200);
179
180 vuln.remove();
181
182 $httpBackend.flush();
183 });
184 });
185 });
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 describe('vulnsManager', function() {
5 var vulnsManager,
6 Vuln,
7 WebVuln,
8 hostsManager,
9 $filter,
10 $httpBackend,
11 $q,
12 BASEURL,
13 vuln1,
14 hosts, interfaces,
15 hostnames = [];
16
17 // Set up the module
18 beforeEach(module('faradayApp'));
19
20 beforeEach(inject(function($injector, _vulnsManager_, _Vuln_, _WebVuln_) {
21
22 vuln1 = {
23 "_id": "1.e29ba38bfa81e7f9050f6517babc14cf32cacdff",
24 "_rev": "1-abe16726389e434ca3f37384ea76128e",
25 "_attachments": {},
26 "desc": "I'm scared!",
27 "data": "",
28 "easeofresolution": 'trivial',
29 "impact": {
30 "availability": false,
31 "accountability": false,
32 "confidentiality": false,
33 "integrity": false
34 },
35 "metadata": {
36 "update_time": 1429643049.395857,
37 "update_user": "",
38 "update_action": 0,
39 "creator": "",
40 "create_time": 1429643049.395857,
41 "update_controller_action": "ModelControler.newVuln",
42 "owner": ""
43 },
44 "name": "Internet Key Exchange (IKE) Aggressive Mode with Pre-Shared Key",
45 "obj_id": "e29ba38bfa81e7f9050f6517babc14cf32cacdff",
46 "owned": false,
47 "owner": "john",
48 "parent": "1",
49 "resolution": "Be careful",
50 "refs": [
51 "CVE-2002-1623",
52 "7423",
53 "OSVDB:3820, CERT:886601"
54 ],
55 "severity": "med",
56 "type": "Vulnerability",
57 "ws": "ws"
58 };
59
60 hosts = {
61 "total_rows": 1,
62 "offset": 0,
63 "rows": [
64 {
65 "_id": "1",
66 "value": {
67 "name": "Host parent"
68 }
69 }
70 ]
71 };
72
73 interfaces = {
74 "total_rows": 3,
75 "offset": 0,
76 "rows": [
77 {
78 "_id": "1.2",
79 "value": {
80 "parent": "1",
81 "hostnames": [
82 "h21",
83 "h22",
84 "h23"
85 ]
86 }
87 }, {
88 "_id": "1.3",
89 "value": {
90 "parent": "1",
91 "hostnames": [
92 "h31",
93 "h32",
94 "h33"
95 ]
96 }
97 }, {
98 "_id": "1.4",
99 "value": {
100 "parent": "1",
101 "hostnames": [
102 "h41",
103 "h42",
104 "h43"
105 ]
106 }
107 }
108 ]
109 };
110
111 interfaces.rows.forEach(function(interf) {
112 hostnames = hostnames.concat(interf.value.hostnames);
113 });
114
115 hostsManagerMock = {
116 getHosts: function(ws) {
117 var deferred = _$q_.defer();
118 deferred.resolve(hosts);
119 return deferred.promise;
120 },
121 getallInterfaces: function() {
122 var deferred = _$q_.defer();
123 deferred.resolve(interfaces);
124 return deferred.promise;
125 }
126 };
127
128 $filter = $injector.get('$filter');
129 $httpBackend = $injector.get('$httpBackend');
130 $q = $injector.get('$q');
131 $rootScope = $injector.get('$rootScope');
132 hostsManager = hostsManagerMock;
133 vulnsManager = _vulnsManager_;
134 Vuln = _Vuln_;
135 WebVuln = _WebVuln_;
136 BASEURL = 'http://localhost:9876/';
137 }));
138
139 afterEach(function() {
140 $httpBackend.verifyNoOutstandingExpectation();
141 $httpBackend.verifyNoOutstandingRequest();
142 });
143
144 describe('Basic usage', function() {
145 it('getVulns', function() {
146 var vuln = {
147 "total_rows": 1,
148 "offset": 0,
149 "rows":[
150 {
151 "id": "1.2.3.8b4ffaedb84dd60d5f43c58eba66a7651458c8de",
152 "key":"4b84b15bff6ee5796152495a230e45e3d7e947d9.34ac3ea37a2854ce00f2d97c648bf3a7cc27ebca",
153 "value": vuln1
154 }
155 ]
156 };
157
158
159 var vulns;
160
161 $httpBackend.expect('GET', BASEURL + 'ws/_design/vulns/_view/all').respond(200, vuln);
162 $httpBackend.expect('GET', BASEURL + 'ws/_design/hosts/_view/hosts').respond(200, hosts);
163 $httpBackend.expect('GET', BASEURL + 'ws/_design/interfaces/_view/interfaces').respond(200, interfaces);
164
165 vulnsManager.getVulns("ws")
166 .then(function(vs) {
167 vulns = vs;
168 });
169
170 $httpBackend.flush();
171
172 expect(vulns.length).toEqual(1);
173 expect(vulnsManager.vulns.length).toEqual(1);
174
175 // promise is resolved correctly
176 vulns.forEach(function(v) {
177 for(var prop in vuln1) {
178 expect(v[prop]).toEqual(vuln1[prop]);
179 }
180 expect(v["target"]).toEqual(hosts.rows[0].value.name);
181 expect(v["hostnames"]).toEqual(hostnames);
182 });
183
184 // array is updated correctly
185 vulnsManager.vulns.forEach(function(v) {
186 for(var prop in vuln1) {
187 expect(v[prop]).toEqual(vuln1[prop]);
188 }
189 expect(v["target"]).toEqual(hosts.rows[0].value.name);
190 expect(v["hostnames"]).toEqual(hostnames);
191 });
192 });
193
194 it('createVuln', function() {
195 var id = vuln1._id,
196 vuln = vuln1;
197 delete vuln._id;
198 delete vuln._rev;
199
200 var resp = {
201 "total_rows":1,
202 "offset":0,
203 "rows":[
204 {
205 "id": "1.2.3.8b4ffaedb84dd60d5f43c58eba66a7651458c8de",
206 "key":"4b84b15bff6ee5796152495a230e45e3d7e947d9.34ac3ea37a2854ce00f2d97c648bf3a7cc27ebca",
207 "value": vuln1
208 }
209 ]
210 };
211
212 var vulns = [];
213
214 // insert new vuln in Couch
215 $httpBackend.expect('PUT', BASEURL + "ws/" + id).respond(201, {"rev": "1234"});
216 $httpBackend.expect('GET', BASEURL + 'ws/_design/hosts/_view/hosts').respond(200, hosts);
217 $httpBackend.expect('GET', BASEURL + 'ws/_design/interfaces/_view/interfaces').respond(200, interfaces);
218
219 var lala = vulnsManager.createVuln("ws", vuln);
220
221 $httpBackend.flush();
222 $rootScope.$apply();
223
224 expect(vulns.length).toEqual(1);
225 expect(vulns[0]._id).toEqual(id);
226 expect(vulnsManager.vulns[0]._id).toEqual(id);
227 });
228
229 it('deleteVuln', function() {
230 var id = vuln1._id;
231 var vuln = angular.copy(vuln1);
232 delete vuln._id;
233 delete vuln._rev;
234
235 var respInsert = {
236 "total_rows":1,
237 "offset":0,
238 "rows":[
239 {
240 "id": "1.2.3.8b4ffaedb84dd60d5f43c58eba66a7651458c8de",
241 "key":"4b84b15bff6ee5796152495a230e45e3d7e947d9.34ac3ea37a2854ce00f2d97c648bf3a7cc27ebca",
242 "value": vuln1
243 }
244 ]
245 };
246
247 var respDelete = {
248 "total_rows":0,
249 "offset":0,
250 "rows":[]
251 };
252
253 // insert new vuln in Couch
254 $httpBackend.expect('PUT', BASEURL + "ws/" + id).respond(201, {"rev": vuln1._rev});
255 // getVulns
256 $httpBackend.expect('GET', BASEURL + 'ws/_design/vulns/_view/all').respond(200, respInsert);
257
258 vulnsManager.createVuln("ws", vuln);
259
260 $httpBackend.flush();
261
262 // delete vuln
263 $httpBackend.expect('DELETE', BASEURL + 'ws/' + id + "?rev=" + vuln1._rev).respond(200);
264 // getVulns
265 $httpBackend.expect('GET', BASEURL + 'ws/_design/vulns/_view/all').respond(200, respDelete);
266
267 vulnsManager.deleteVuln("ws", vulnsManager.vulns[0]);
268 $httpBackend.flush();
269
270 expect(vulnsManager.vulns.length).toEqual(0);
271 });
272
273 it('updateVuln', function() {
274 var id = vuln1._id;
275 var vuln = angular.copy(vuln1);
276 delete vuln._id;
277 delete vuln._rev;
278
279 var vulnMod = {
280 "_id": "1.2.3.e29ba38bfa81e7f9050f6517babc14cf32cacdff",
281 "_rev": "1-abe16726389e434ca3f37384ea76128e",
282 "desc": "Hello World!",
283 "data": "",
284 "metadata": {
285 "update_time": 1429643049.395857,
286 "update_user": "",
287 "update_action": 0,
288 "creator": "UI Web",
289 "create_time": 1429643049.395857,
290 "update_controller_action": "ModelControler.newVuln",
291 "owner": ""
292 },
293 "name": "Something something dark side",
294 "owned": false,
295 "owner": "",
296 "parent": "1.2.3",
297 "resolution": "Be careful",
298 "refs": [
299 "CVE-2002-1623",
300 "7423",
301 "OSVDB:3820, CERT:886601"
302 ],
303 "severity": "med",
304 "type": "Vulnerability",
305 "ws": "ws"
306 };
307
308 var respInsert = {
309 "total_rows":1,
310 "offset":0,
311 "rows":[
312 {
313 "id": "1.2.3.8b4ffaedb84dd60d5f43c58eba66a7651458c8de",
314 "key":"4b84b15bff6ee5796152495a230e45e3d7e947d9.34ac3ea37a2854ce00f2d97c648bf3a7cc27ebca",
315 "value": vuln1
316 }
317 ]
318 };
319
320 var respUpdate = {
321 "total_rows":1,
322 "offset":0,
323 "rows":[
324 {
325 "id": "1.2.3.8b4ffaedb84dd60d5f43c58eba66a7651458c8de",
326 "key":"4b84b15bff6ee5796152495a230e45e3d7e947d9.34ac3ea37a2854ce00f2d97c648bf3a7cc27ebca",
327 "value": vulnMod
328 }
329 ]
330 };
331
332 // insert new vuln in Couch
333 $httpBackend.expect('PUT', BASEURL + "ws/" + id).respond(201, {"rev": "1234"});
334 // getVulns
335 $httpBackend.expect('GET', BASEURL + 'ws/_design/vulns/_view/all').respond(200, respInsert);
336 // call to insert
337 vulnsManager.createVuln("ws", vuln);
338 $httpBackend.flush();
339
340 // update vuln
341 $httpBackend.expect('PUT', BASEURL + 'ws/' + id).respond(200, {"rev": "2345"});
342 // getVulns
343 $httpBackend.expect('GET', BASEURL + 'ws/_design/vulns/_view/all').respond(200, respUpdate);
344
345 var vulns = vulnsManager.updateVuln(vuln.ws, vulnsManager.vulns[0], vulnMod);
346 $httpBackend.flush();
347
348 expect(vulnsManager.vulns.length).toEqual(1);
349
350 for(var prop in vulnMod) {
351 if(vulnMod.hasOwnProperty(prop)) {
352 if(prop != "metadata") expect(vulnsManager.vulns[0][prop]).toEqual(vulnMod[prop]);
353 }
354 }
355 });
356 });
357 });
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 describe('WebVuln', function() {
5 var WebVuln,
6 $httpBackend,
7 BASEURL;
8
9 var new_data,
10 new_name,
11 new_website,
12 new_path,
13 new_id,
14 new_id_parent,
15 new_full_id,
16 old_data,
17 old_name,
18 old_website,
19 old_path,
20 old_id,
21 old_id_parent,
22 old_full_id;
23
24 // Set up the module
25 beforeEach(module('faradayApp'));
26
27 beforeEach(inject(function($injector, _WebVuln_) {
28 $httpBackend = $injector.get('$httpBackend');
29 WebVuln = _WebVuln_;
30 BASEURL = 'http://localhost:9876/';
31
32 new_name = "new name";
33 new_website = "new website";
34 new_path = "new path";
35 new_desc = "new desc";
36 new_id = CryptoJS.SHA1(new_name + "." + new_website + "." + new_path + "." + new_desc).toString();
37 new_id_parent = CryptoJS.SHA1("parent").toString();
38 new_full_id = new_id_parent + "." + new_id;
39
40 new_data = {
41 "data": "data",
42 "desc": new_desc,
43 "easeofresolution": "easeofresolution",
44 "impact": "impact",
45 "method": "method",
46 "name": new_name,
47 "owned": false,
48 "params": "params",
49 "parent": new_id_parent,
50 "path": new_path,
51 "pname": "pname",
52 "query": "query",
53 "refs": "refs",
54 "request": "request",
55 "resolution": "resolution",
56 "response": "response",
57 "severity": "severity",
58 "website": new_website,
59 "ws": "ws"
60 };
61
62 // this is used to create a web vuln that "already exists"
63 var now = new Date(),
64 old_date = now.getTime();
65
66 old_name = "old name";
67 old_website = "old website";
68 old_path = "old path";
69 old_desc = "old desc";
70 old_id = CryptoJS.SHA1(old_name + "." + old_website + "." + old_path + "." + old_desc).toString();
71 old_id_parent = CryptoJS.SHA1("parent").toString();
72 old_full_id = old_id_parent + "." + old_id;
73
74 old_data = {
75 "_id": old_full_id,
76 "_rev": "1-lalalal",
77 "data": "data",
78 "desc": old_desc,
79 "easeofresolution": "easeofresolution",
80 "impact": "impact",
81 "metadata": {
82 "update_time": old_date,
83 "update_user": "update_user",
84 "update_action": "update_action",
85 "creator": "creator",
86 "create_time": old_date,
87 "update_controller_action": "update_controller_action",
88 "owner": "owner"
89 },
90 "method": "method",
91 "name": old_name,
92 "owned": false,
93 "params": "params",
94 "parent": old_id_parent,
95 "path": old_path,
96 "pname": "pname",
97 "query": "query",
98 "refs": "refs",
99 "request": "request",
100 "resolution": "resolution",
101 "response": "response",
102 "severity": "severity",
103 "website": old_website,
104 "ws": "ws"
105 };
106 }));
107
108 afterEach(function() {
109 $httpBackend.verifyNoOutstandingExpectation();
110 $httpBackend.verifyNoOutstandingRequest();
111 });
112
113 describe('CRUD with invalid data', function() {
114 it('Setting new object', function() {
115 delete new_data.name;
116
117 expect(function() { new WebVuln('ws', new_data); }).toThrowError(Error, "Unable to create Vuln without a name");
118 });
119 });
120
121 describe('CRUD with valid data', function() {
122 it('Setting new object', function() {
123 vuln = new WebVuln('ws', new_data);
124
125 expect(vuln._id).toBeDefined();
126 expect(vuln._id).toEqual(new_full_id);
127 expect(vuln.type).toEqual("VulnerabilityWeb");
128
129 for(var prop in new_data) {
130 if(new_data.hasOwnProperty(prop)) {
131 expect(vuln[prop]).toEqual(new_data[prop]);
132 }
133 }
134 });
135
136 it('Setting existing object', function() {
137 vuln = new WebVuln('ws', old_data);
138
139 expect(vuln._id).toBeDefined();
140 expect(vuln._id).toEqual(old_full_id);
141
142 for(var prop in old_data) {
143 if(old_data.hasOwnProperty(prop)) {
144 if(prop != "metadata") expect(vuln[prop]).toEqual(old_data[prop]);
145 }
146 }
147 });
148
149 it('Saving new object', function() {
150 var url = BASEURL + "ws/" + new_full_id;
151 var vuln = new WebVuln('ws', new_data);
152
153 $httpBackend.expect('PUT', url).respond(201, {"rev": "1234"});
154
155 vuln.save();
156
157 $httpBackend.flush();
158
159 expect(vuln._rev).toEqual("1234");
160 });
161
162 it('Saving existing object', function() {
163 var url = BASEURL + "ws/" + old_full_id;
164 var vuln = new WebVuln('ws', old_data);
165
166 $httpBackend.expect('PUT', url).respond(201, {"rev": "1234"});
167
168 vuln.save();
169
170 $httpBackend.flush();
171
172 expect(vuln._rev).toEqual("1234");
173 });
174
175 it('Updating object', function() {
176 var url = BASEURL + "ws/" + new_full_id;
177 var vuln = new WebVuln('ws', new_data);
178
179 $httpBackend.expect('PUT', url).respond(201, {"rev": "1234"});
180
181 delete old_data._id;
182 delete old_data._rev;
183 vuln.update(old_data);
184
185 $httpBackend.flush();
186
187 expect(vuln._rev).toEqual("1234");
188
189 for(var prop in old_data) {
190 if(old_data.hasOwnProperty(prop)) {
191 if(prop != "metadata") expect(vuln[prop]).toEqual(old_data[prop]);
192 }
193 }
194 });
195
196 it('Deleting object', function() {
197 var url = BASEURL + "ws/" + old_full_id + "?rev=" + old_data._rev;
198 var vuln = new WebVuln('ws', old_data);
199
200 $httpBackend.expect('DELETE', url).respond(200);
201
202 vuln.remove();
203
204 $httpBackend.flush();
205 });
206 });
207 });
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 describe('workspacesCtrl', function() {
5 var $controller,
6 $scope;
7
8 // workspaces variables
9 var tmp_ws1 = {
10 "_id": "ws1",
11 "_rev": "2-bd88abf79cf2b7e8b419cd4387c64bef",
12 "children": [],
13 "customer": "",
14 "description": "Testing Workspaces",
15 "duration": {
16 "start": 1410832741.48194,
17 "end": 1410832741.48194
18 },
19 "name": "ws1",
20 "sdate": 1410832741.48194,
21 "scope": "",
22 "selected": true,
23 "type": "Workspace"
24 };
25 var tmp_ws2 = {
26 "_id": "ws2",
27 "_rev": "10-bd88abf79cf2b7e8b419cd4387c64bef",
28 "children": [],
29 "customer": "",
30 "description": "Nuevo",
31 "duration": {
32 "startDate": 141083274148194,
33 "endDate": 141083274148194
34 },
35 "name": "ws2",
36 "sdate": 1410832741.48194,
37 "scope": "",
38 "selected": true,
39 "type": "Workspace",
40 };
41 var tmp_ws3 = {
42 "_id": "ws3",
43 "_rev": "2-bd88abf79cf2b7e8b419cd4387c64bef",
44 "children": [],
45 "customer": "",
46 "description": "Testing Workspaces",
47 "duration": {
48 "start": 1410832741.48194,
49 "end": 1410832741.48194
50 },
51 "name": "ws3",
52 "sdate": 1410832741.48194,
53 "scope": "",
54 "selected": true,
55 "type": "Workspace"
56 };
57
58 var $workspacesFact,
59 workspacesFactMock;
60
61 beforeEach(function () {
62 module('faradayApp');
63
64 inject(function(_$rootScope_, _$controller_, _$q_) {
65 // The injector unwraps the underscores (_) from around the parameter names when matching
66 $scope = _$rootScope_.$new();
67
68 dashboardSrvMock = {
69 getObjectsCount: function(ws) {
70 var deferred = _$q_.defer();
71 deferred.resolve([
72 {"key":"hosts","value":2},
73 {"key":"interfaces","value":2},
74 {"key":"services","value":1},
75 {"key":"total vulns","value":3},
76 {"key":"vulns","value":1},
77 {"key":"web vulns","value":2}
78 ]);
79 return deferred.promise;
80 }
81 };
82 workspacesFactMock = {
83 list: function(callback) {
84 var deferred = _$q_.defer();
85 deferred.resolve(['ws1', 'ws2']);
86 return deferred.promise;
87 },
88 update: function(workspace) {
89 var deferred = _$q_.defer();
90 deferred.resolve({
91 "_id": "ws2",
92 "_rev": "36-e56619bfa3a9ee9b09650d3fc8878d2c",
93 "children": [],
94 "customer": "",
95 "description": "Nuevo",
96 "duration": {
97 "start": 141083274148194,
98 "end": 141083274148194
99 },
100 "name": "ws2",
101 "sdate": 1410832741.48194,
102 "scope": "Nuevo Scope",
103 "selected": true,
104 "type": "Workspace",
105 });
106 return deferred.promise;
107 },
108 get: function(workspace_name){
109 var objs = {
110 "ws1" : tmp_ws1,
111 "ws2" : tmp_ws2
112 };
113 var deferred = _$q_.defer();
114 deferred.resolve(objs[workspace_name]);
115 return deferred.promise;
116 },
117 put: function(workspace) {
118 var deferred = _$q_.defer();
119 deferred.resolve("");
120 return deferred.promise;
121 },
122 delete: function(workspace_name) {
123 var deferred = _$q_.defer();
124 deferred.resolve(workspace_name);
125 return deferred.promise;
126 },
127 exists: function(workspace_name){
128 return false;
129 }
130
131 };
132
133 $controller = _$controller_('workspacesCtrl', {
134 $scope: $scope,
135 dashboardSrv: dashboardSrvMock,
136 workspacesFact: workspacesFactMock
137 });
138 });
139 });
140
141
142 describe('Workspaces init function', function() {
143 beforeEach(function() {
144 spyOn(workspacesFactMock, 'get').and.callThrough();
145 });
146 it('variables are defined after execution', function() {
147 $scope.$apply();
148 expect($scope.wss).toBeDefined();
149 expect($scope.objects).toBeDefined();
150 expect($scope.workspaces).toBeDefined();
151 expect($scope.hash).toBeDefined();
152 });
153 it('variables have proper values after execution', function() {
154 $scope.$apply();
155 expect($scope.wss).toEqual(['ws1', 'ws2']);
156 expect($scope.objects).not.toEqual({});
157 expect($scope.workspaces).not.toEqual([]);
158 expect($scope.minDate).not.toEqual({});
159 expect($scope.dateOptions).not.toEqual({});
160 expect($scope.hash).not.toEqual(null);
161 expect(workspacesFactMock.get).toHaveBeenCalled();
162 $scope.workspaces.forEach(function(ws){
163 expect(ws.selected).toEqual(false);
164 });
165 expect($scope.workspaces.length).toEqual(2);
166 expect($scope.workspaces).toContain(tmp_ws1);
167 expect($scope.workspaces).toContain(tmp_ws2);
168 });
169 });
170
171 describe('Workspace update function', function() {
172 beforeEach(function() {
173 spyOn(workspacesFactMock, 'update').and.callThrough();
174 });
175 it('variables are defined after execution of update function', function() {
176
177 $scope.update(tmp_ws2);
178 $scope.$apply();
179 expect(workspacesFactMock.update).toHaveBeenCalled();
180
181 expect(workspace._id).toBeDefined();
182 expect(workspace._rev).toBeDefined();
183 expect(workspace.children).toBeDefined();
184 expect(workspace.customer).toBeDefined();
185 expect(workspace.description).toBeDefined();
186 expect(workspace.duration.start).toBeDefined();
187 expect(workspace.duration.end).toBeDefined();
188 expect(workspace.name).toBeDefined();
189 expect(workspace.sdate).toBeDefined();
190 expect(workspace.scope).toBeDefined();
191 expect(workspace.selected).not.toBeDefined();
192 expect(workspace.type).toBeDefined();
193 });
194 it('variables changed after execution of update function', function() {
195 var tmp_ws2_modified = {
196 "_id": "ws2",
197 "_rev": "10-bd88abf79cf2b7e8b419cd4387c64bef",
198 "children": [],
199 "customer": "",
200 "description": "Nuevo",
201 "duration": {
202 "start": 141083274148194,
203 "end": 141083274148194
204 },
205 "name": "ws2",
206 "sdate": 1410832741.48194,
207 "scope": "Nuevo Scope",
208 "selected": true,
209 "type": "Workspace",
210 };
211 $scope.$apply();
212 $scope.update(tmp_ws2_modified);
213 $scope.$apply();
214 for(var i = 0; i < $scope.workspaces.length; i++){
215 if($scope.workspaces[i]._id == workspace._id){
216 expect($scope.workspaces[i].description).toEqual(workspace.description);
217 expect($scope.workspaces[i]._rev).not.toEqual(workspace._rev);
218 expect($scope.workspaces[i].duration.start).toEqual(workspace.duration.start);
219 expect($scope.workspaces[i].duration.end).toEqual(workspace.duration.end);
220 expect($scope.workspaces[i].scope).toEqual(workspace.scope);
221 }
222 }
223 });
224 });
225
226 describe('Workspaces inserts in $scope.wss', function() {
227 beforeEach(function() {
228 spyOn(workspacesFactMock, 'put').and.callThrough();
229 spyOn($scope, 'onSuccessInsert').and.callThrough();
230 });
231 it('if put Mock is called after execution of insert function', function() {
232 $scope.insert(tmp_ws1);
233 $scope.$apply();
234
235 expect(workspacesFactMock.put).toHaveBeenCalledWith(tmp_ws1);
236 expect($scope.onSuccessInsert).toHaveBeenCalledWith(tmp_ws1);
237 });
238 it('variables update properly after execution of onSuccessInsert function', function() {
239 // define wss after execution
240 // if it is not defined, push to $scope.wss fails
241 $scope.wss = [];
242 $scope.$apply();
243 $scope.onSuccessInsert(tmp_ws3);
244 $scope.$apply();
245
246 expect($scope.wss).toContain(tmp_ws3.name);
247 expect($scope.workspaces).toContain(tmp_ws3);
248 });
249 });
250
251 describe('Workspaces object creation', function() {
252 it('tests if workspaces create object is consistent', function() {
253 var date = new Date();
254 workspace = $scope.create('wname','wdesc', date, date, '');
255 $scope.$apply();
256
257 expect(workspace._id).toBeDefined();
258 expect(workspace._rev).not.toBeDefined();
259 expect(workspace.customer).toBeDefined();
260 expect(workspace.sdate).toBeDefined();
261 expect(workspace.name).toBeDefined();
262 // find out if this variable is being used
263 // is defined as undefined
264 expect(workspace.fdate).toBeUndefined();
265
266 expect(workspace.type).toBeDefined();
267 expect(workspace.children).toBeDefined();
268 expect(workspace.duration.start).toBeDefined();
269 expect(workspace.duration.end).toBeDefined();
270 expect(workspace.scope).toBeDefined();
271 expect(workspace.description).toBeDefined();
272
273 expect(workspace.name).toEqual('wname');
274 expect(workspace._id).toEqual('wname');
275 expect(workspace.description).toEqual('wdesc');
276 expect(workspace.duration.start).toEqual(date.getTime());
277 expect(workspace.duration.end).toEqual(date.getTime());
278 expect(workspace.scope).toEqual('');
279 });
280 });
281
282 describe('Workspaces removal properly', function() {
283 beforeEach(function() {
284 spyOn(workspacesFactMock, 'delete').and.callThrough();
285 });
286 it('tests if workspaces in scope.wss are removed after execution of remove function', function() {
287 $scope.remove('ws1');
288 $scope.$apply();
289
290 expect(workspacesFactMock.delete).toHaveBeenCalled();
291 expect($scope.wss).not.toContain('ws1');
292 });
293 it('tests if workspaces in scope.workspaces are removed after execution of onSuccessDelete function', function() {
294 $scope.onSuccessGet(tmp_ws3);
295 $scope.$apply();
296 $scope.onSuccessDelete('ws1');
297 $scope.$apply();
298
299 expect($scope.workspaces).not.toContain(tmp_ws1);
300 });
301 });
302
303 });
0 // // Faraday Penetration Test IDE
1 // // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // // See the file 'doc/LICENSE' for the license information
3
4 // describe('workspacesFact', function() {
5 // var $httpBackend, createFactory;
6
7 // // Set up the module
8 // beforeEach(module('faradayApp'));
9
10 // beforeEach(inject(function($injector) {
11 // // Set up the mock http service responses
12 // $httpBackend = $injector.get('$httpBackend');
13 // var $workspacesFact = $injector.get('workspacesFact');
14
15 // createFactory = function() {
16 // return $injector.get('workspacesFact', {'BASEURL' : 'http://localhost:9876/',
17 // '$http': $httpBackend});
18 // };
19 // }));
20
21
22 // afterEach(function() {
23 // $httpBackend.verifyNoOutstandingExpectation();
24 // $httpBackend.verifyNoOutstandingRequest();
25 // });
26
27 // describe('Workspaces Service CRUD', function() {
28 // it('Tests if factory is well created', function() {
29 // fact = createFactory();
30 // });
31
32 // it('Tests if existence is well asked', function() {
33 // $httpBackend.when('HEAD', 'http://localhost:9876/tuvieja')
34 // .respond(200, '');
35
36 // $httpBackend.expectHEAD('http://localhost:9876/tuvieja');
37 // fact = createFactory();
38 // workspace_exists = fact.exists('tuvieja');
39 // expect(workspace_exists).toBe(true);
40 // $httpBackend.flush();
41 // });
42
43 // it('Tests if OK Inserts are well done', function() {
44 // var workspace = {
45 // "_id": "test_workspace",
46 // "customer": "",
47 // "sdate": 1415901244.040532,
48 // "name": "test_workspace",
49 // "fdate": 1415901244.040532,
50 // "type": "Workspace",
51 // "children": [
52 // ],
53 // "description": ""
54 // };
55
56 // $httpBackend.expectPUT('http://localhost:9876/test_workspace',
57 // workspace).respond(200, {"ok": true});
58
59 // $httpBackend.expectPUT('http://localhost:9876/test_workspace/test_workspace',
60 // workspace).respond(200, {"ok": true});
61
62 // fact = createFactory();
63 // var workspace_exists = false;
64 // onSuccess = function(){ workspace_exists = true;};
65
66 // fact.put(workspace, onSuccess);
67 // $httpBackend.flush();
68 // expect(workspace_exists).toBe(true);
69 // });
70
71 // it('Tests if OK Delete are well done', function() {
72 // $httpBackend.expectDELETE('http://localhost:9876/test_workspace').
73 // respond(200, {"ok": true});
74
75 // fact = createFactory();
76 // var workspace_exists = true;
77 // onSuccess = function(){ workspace_exists = false;};
78
79 // workspace_exists = fact.delete('test_workspace', onSuccess);
80 // $httpBackend.flush();
81 // expect(workspace_exists).toBe(false);
82 // });
83 // });
84
85 // });
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 module.exports = function(config){
5 config.set({
6
7 basePath : './',
8
9 files : [
10 '../views/reports/_attachments/script/jquery-1.11.2.js',
11 '../views/reports/_attachments/script/angular.js',
12 '../views/reports/_attachments/script/angular-mocks.js',
13 '../views/reports/_attachments/script/angular-route.js',
14 '../views/reports/_attachments/script/angular-selection-model.js',
15 '../views/reports/_attachments/script/*bootstrap*.js',
16 '../views/reports/_attachments/scripts/app.js',
17 '../views/reports/_attachments/scripts/**/*.js',
18 '../tests_web/faradayApp/components/**/*.js',
19 '../views/reports/_attachments/script/angular-file-upload-shim.js',
20 '../views/reports/_attachments/script/angular-file-upload.js',
21 '../views/reports/_attachments/script/ngClip.js',
22 '../views/reports/_attachments/script/angular-cookies.js',
23 '../views/reports/_attachments/script/ZeroClipboard.min.js',
24 '../views/reports/_attachments/script/mousetrap.js',
25 '../views/reports/_attachments/script/angular-hotkeys.js',
26 '../views/reports/_attachments/script/cryptojs-sha1.js'
27 ],
28
29 autoWatch : true,
30
31 frameworks: ['jasmine'],
32
33 browsers : ['Chrome'],
34
35 plugins : [
36 'karma-chrome-launcher',
37 'karma-firefox-launcher',
38 'karma-jasmine',
39 'karma-junit-reporter'
40 ],
41
42 junitReporter : {
43 outputFile: 'test_out/unit.xml',
44 suite: 'unit'
45 }
46
47 });
48 };
0 {
1 "name": "angular-seed",
2 "private": true,
3 "version": "0.0.0",
4 "description": "A starter project for AngularJS",
5 "repository": "https://github.com/angular/angular-seed",
6 "license": "MIT",
7 "devDependencies": {
8 "angular-mocks": "^1.3.0",
9 "http-server": "^0.6.1",
10 "jasmine-core": "^2.1.2",
11 "karma": "^0.12.28",
12 "karma-chrome-launcher": "^0.1.5",
13 "karma-jasmine": "^0.3.2",
14 "karma-junit-reporter": "^0.2.2",
15 "protractor": "^1.1.1",
16 "shelljs": "^0.2.6"
17 },
18 "scripts": {
19 "prestart": "npm install",
20 "start": "http-server -a localhost -p 8000 -c-1",
21 "pretest": "npm install",
22 "test": "node_modules/karma/bin/karma start karma.conf.js",
23 "test-single-run": "node_modules/karma/bin/karma start karma.conf.js --single-run",
24 "preupdate-webdriver": "npm install",
25 "update-webdriver": "webdriver-manager update",
26 "preprotractor": "npm run update-webdriver",
27 "protractor": "protractor e2e-tests/protractor.conf.js"
28 }
29 }
+0
-7
views/hosts/views/services/map.js less more
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 function(doc) {
5
6 }
+0
-7
views/hosts/views/services/reduce.js less more
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 function(keys, values, rereduce) {
5
6 }
303303 .item:nth-child(6) {-webkit-animation-delay: 0.6s;}
304304 .item:nth-child(7) {-webkit-animation-delay: 0.7s;}
305305
306 /* Icons on Home */
307 .icons-color-home{color: #B3B4B5;}
308 .fa.icons-size-home{font-size: 9em;}
309
306310 /* Datos con nro grande, titulo y texto */
307311 .dato1 {
308312 color: #858585;
500504 border:1px solid;
501505 }
502506 #compound .tablesorter thead th:last-child{width: 19%}
503 #compound .col-lg-6 article.panel{
507 article#compound.panel{
504508 height: 93px;
505509 padding-bottom: 428px;
506510 background: transparent;
507511 border: 0px solid;
508512 }
509 #compound article.panel-default table{margin-bottom: 0px}
510 #compound article.panel-default input{
513 article#compound.panel-default table{margin-bottom: 0px}
514 article#compound.panel-default input{
511515 width: 90px;
512516 float: right;
513517 }
514 #compound article.panel-default input.btn.btn-danger{width: 43px}
518 article#compound.panel-default input.btn.btn-danger{width: 43px}
515519 div.col-md-6.left-big-box{width: 45%;margin: -200px 0 5px}
516520 div.col-md-6.left-big-box table.table-striped.last-vuln td:nth-child(4){word-break: break-all;}
517521
610614 #vulns-by-price .main{width:100% !important;height: 180px !important;}
611615 #vulns .columna.unsexto{margin: auto;}
612616 #summarized .main{height:197px}
617 #summarized .panel.panel-default,#byservices .panel.panel-default{max-height: 239px}
613618 #byservices .main{height:197px}
614619 #byservices .alert, #summarized .alert{width: 100%}
615620 #compound header, #list header{min-height: 40px;}
644649 section .col-lg-2{margin: 0px -2% 0px 2px;padding-right: 1.9%;}
645650 .col-lg-6 .panel{margin-bottom: 10px}
646651 #list .col-lg-6, #vulns .col-lg-6, #vulns-by-price .col-lg-6{width: 55%;float: right;margin-bottom: 5px}
647 #compound .col-lg-6{width: 45%;}
648652
649653 .panel{margin-bottom: 1%!important}
650654 article.panel > span{
705709 color: #ffffff;
706710 text-decoration: none;
707711 }
712 a.ws-link span.impact-ok{top: 2px;left: -4px;color: #5cb85c;}
713 a.ws-link span.impact-del{top: 3px;left: 2px;color: #d9534f;}
708714 a.ws-link:hover {
709715 color: #ffffff;
710716 text-decoration: none;
729735 div.showPagination form#goToPageStatus{margin-top:-40px;}
730736 input.form-control.vuln_per_page{width: 10%;margin: auto}
731737 /* End */
732 div.col-md-12.reference{margin-top: 5px;}
738 .reference{margin-top: 5px;}
739 div.form-group.editArray{margin-bottom: 0px}
740 div.modal-footer.editArray{margin-top: 0px}
733741 input#vuln-refs{border-radius: 5px 0 0 5px}
734742 i.fa.fa-plus-circle{color: green;}
735743 i.fa.fa-minus-circle{color: red;cursor: pointer;}
748756 div.input-margin{margin: 4px 0;}
749757 div.col-md-8.protocol input#protocol{margin-top: 35px}
750758 div#treemap_container{margin: 5% auto 0}
751 div#compound div.showPagination{margin-bottom: 30px}
752 div#compound .showPagination input.form-control{width:110px;}
753 div#compound .showPagination div.form-group{margin-top: 10px;}
754 div#compound article.panel-default input{width: 90px;float: right}
755 div#compound .showPagination input#vuln-per-page{width: 75px!important;margin-right: 15%}
759 article#compound div.showPagination{margin-bottom: 30px}
760 article#compound .showPagination input.form-control{width:110px;}
761 article#compound .showPagination div.form-group{margin-top: 10px;}
762 article#compound.panel-default input{width: 90px;float: right}
763
764 article#compound .showPagination input#vuln-per-page{width: 75px!important;margin-right: 15%}
756765 aside .alert.alert-danger.alert-dismissible{
757766 position: fixed;
758767 top: 45%;
886895 text-align: center;
887896 width: 500px;
888897 }
898 div#workspace-progress-reference.center-lg-6{padding-top: 15px}
899 .col-lg-left{width: 46%!important;margin-top: -30px;}
900 .col-lg-right{width: 53%!important;padding-left: 0px!important;}
901 .no-margin-bottom{margin-bottom: 0px!important;}
902 .wrapword{
903 white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */
904 white-space: -pre-wrap; /* Opera 4-6 */
905 white-space: -o-pre-wrap; /* Opera 7 */
906 white-space: pre-wrap; /* css-3 */
907 word-wrap: break-word; /* Internet Explorer 5.5+ */
908 white-space: -webkit-pre-wrap; /* Newer versions of Chrome/Safari*/
909 word-break: break-all;
910 white-space: normal;
911 }
2323 <link rel="stylesheet" href="script/bootstrap.min.css">
2424 <link rel="stylesheet" href="script/bootstrap-theme.min.css">
2525 <link rel="stylesheet" type="text/css" href="styles/font-awesome.css" />
26 <link rel="stylesheet" type="text/css" href="styles/angular-hotkeys.css" />
2627
2728 <!-- Icons -->
2829 <link href="favicon.ico" rel="shortcut icon">
3031 <link href="images/site_preview.jpg" rel="image_src" />
3132
3233 <!-- Scripts -->
34 <script type="text/javascript" src="script/mousetrap.js"></script>
3335 <script type="text/javascript" src="script/jquery.js"></script>
3436 <script type="text/javascript" src="script/jquery.couch.js"></script>
3537 <script type="text/javascript" src="script/bootstrap.min.js"></script>
3638 <script type="text/javascript" src="script/angular.js"></script>
3739 <script type="text/javascript" src="script/angular-cookies.js"></script>
40 <script type="text/javascript" src="script/angular-hotkeys.js"></script>
3841 <script type="text/javascript" src="script/angular-route.js"></script>
3942 <script type="text/javascript" src="script/angular-selection-model.js"></script>
4043 <script type="text/javascript" src="script/angular-file-upload-shim.js"></script><!-- compatibility with older browsers -->
6467 <script type="text/javascript" src="scripts/commons/directives/contenteditable.js"></script>
6568 <script type="text/javascript" src="scripts/commons/controllers/modal.js"></script>
6669 <script type="text/javascript" src="scripts/commons/providers/commons.js"></script>
70 <script type="text/javascript" src="scripts/commons/filters/decodeURIComponent.js"></script>
71 <script type="text/javascript" src="scripts/commons/filters/encodeURIComponent.js"></script>
72 <script type="text/javascript" src="scripts/commons/filters/getByProperty.js"></script>
6773 <script type="text/javascript" src="scripts/commons/filters/orderObjectBy.js"></script>
6874 <script type="text/javascript" src="scripts/commons/filters/startFrom.js"></script>
75 <script type="text/javascript" src="scripts/commons/filters/integer.js"></script>
6976 <script type="text/javascript" src="scripts/fileExporter/directives/download.js"></script>
70 <script type="text/javascript" src="scripts/fileExporter/services/blob.js"></script>
71 <script type="text/javascript" src="scripts/fileExporter/services/click.js"></script>
77 <script type="text/javascript" src="scripts/fileExporter/providers/blob.js"></script>
78 <script type="text/javascript" src="scripts/fileExporter/providers/click.js"></script>
79 <script type="text/javascript" src="scripts/cwe/providers/CweService.js"></script>
7280 <script type="text/javascript" src="scripts/hosts/controllers/host.js"></script>
7381 <script type="text/javascript" src="scripts/hosts/controllers/hosts.js"></script>
7482 <script type="text/javascript" src="scripts/hosts/controllers/hostsModalEdit.js"></script>
7583 <script type="text/javascript" src="scripts/hosts/controllers/hostsModalNew.js"></script>
76 <script type="text/javascript" src="scripts/hosts/services/host.js"></script>
77 <script type="text/javascript" src="scripts/hosts/services/hosts.js"></script>
84 <script type="text/javascript" src="scripts/hosts/providers/host.js"></script>
85 <script type="text/javascript" src="scripts/hosts/providers/hosts.js"></script>
7886 <script type="text/javascript" src="scripts/navigation/controllers/navigationCtrl.js"></script>
79 <script type="text/javascript" src="scripts/notes/services/notes.js"></script>
87 <script type="text/javascript" src="scripts/notes/providers/notes.js"></script>
8088 <script type="text/javascript" src="scripts/services/controllers/serviceModalNew.js"></script>
8189 <script type="text/javascript" src="scripts/services/controllers/serviceModalEdit.js"></script>
8290 <script type="text/javascript" src="scripts/services/providers/services.js"></script>
8593 <script type="text/javascript" src="scripts/statusReport/controllers/modalEdit.js"></script>
8694 <script type="text/javascript" src="scripts/statusReport/controllers/modalNew.js"></script>
8795 <script type="text/javascript" src="scripts/statusReport/directives/textCollapse.js"></script>
88 <script type="text/javascript" src="scripts/statusReport/services/statusReport.js"></script>
89 <script type="text/javascript" src="scripts/statusReport/services/target.js"></script>
90 <script type="text/javascript" src="scripts/vulns/services/vulns.js"></script>
91 <script type="text/javascript" src="scripts/vulnsWeb/services/vulnsWeb.js"></script>
96 <script type="text/javascript" src="scripts/statusReport/providers/target.js"></script>
97 <script type="text/javascript" src="scripts/vulns/providers/vuln.js"></script>
98 <script type="text/javascript" src="scripts/vulns/providers/vulns.js"></script>
99 <script type="text/javascript" src="scripts/vulns/providers/web.js"></script>
92100 <script type="text/javascript" src="scripts/workspaces/controllers/workspaces.js"></script>
93 <script type="text/javascript" src="scripts/workspaces/services/workspaces.js"></script>
101 <script type="text/javascript" src="scripts/workspaces/controllers/workspacesModalEdit.js"></script>
102 <script type="text/javascript" src="scripts/workspaces/controllers/workspacesModalNew.js"></script>
103 <script type="text/javascript" src="scripts/workspaces/providers/workspaces.js"></script>
94104 <script type="text/javascript" src="scripts/dashboard/controllers/dashboard.js"></script>
95105 <script type="text/javascript" src="scripts/dashboard/controllers/graphicsBarCtrl.js"></script>
96106 <script type="text/javascript" src="scripts/dashboard/controllers/summarizedCtrl.js"></script>
97107 <script type="text/javascript" src="scripts/dashboard/controllers/vulnsbyprice.js"></script>
98 <script type="text/javascript" src="scripts/dashboard/services/dashboard.js"></script>
99 <script type="text/javascript" src="scripts/d3/services/d3.js"></script>
108 <script type="text/javascript" src="scripts/dashboard/controllers/workspaceProgress.js"></script>
109 <script type="text/javascript" src="scripts/dashboard/providers/dashboard.js"></script>
110 <script type="text/javascript" src="scripts/d3/providers/d3.js"></script>
100111 <script type="text/javascript" src="scripts/d3/directives/treemap.js"></script>
101112 <script type="text/javascript" src="scripts/d3/directives/bar.js"></script>
102113 <script type="text/javascript" src="scripts/d3/directives/cake.js"></script>
0 /*
1 * angular-hotkeys
2 *
3 * Automatic keyboard shortcuts for your angular apps
4 *
5 * (c) 2014 Wes Cruver
6 * License: MIT
7 */
8
9 (function() {
10
11 'use strict';
12
13 angular.module('cfp.hotkeys', []).provider('hotkeys', function($injector) {
14
15 /**
16 * Configurable setting to disable the cheatsheet entirely
17 * @type {Boolean}
18 */
19 this.includeCheatSheet = true;
20
21 /**
22 * Configurable setting to disable ngRoute hooks
23 * @type {Boolean}
24 */
25 this.useNgRoute = $injector.has('ngViewDirective');
26
27 /**
28 * Configurable setting for the cheat sheet title
29 * @type {String}
30 */
31
32 this.templateTitle = 'Keyboard Shortcuts:';
33
34 /**
35 * Configurable settings for the cheat sheet header and footer. Both are HTML, and the header
36 * overrides the normal title if specified.
37 * @type {String}
38 */
39 this.templateHeader = null;
40 this.templateFooter = null;
41
42 /**
43 * Cheat sheet template in the event you want to totally customize it.
44 * @type {String}
45 */
46 this.template = '<div class="cfp-hotkeys-container fade" ng-class="{in: helpVisible}" style="display: none;"><div class="cfp-hotkeys">' +
47 '<h4 class="cfp-hotkeys-title" ng-if="!header">{{ title }}</h4>' +
48 '<div ng-bind-html="header" ng-if="header"></div>' +
49 '<table><tbody>' +
50 '<tr ng-repeat="hotkey in hotkeys | filter:{ description: \'!$$undefined$$\' }">' +
51 '<td class="cfp-hotkeys-keys">' +
52 '<span ng-repeat="key in hotkey.format() track by $index" class="cfp-hotkeys-key">{{ key }}</span>' +
53 '</td>' +
54 '<td class="cfp-hotkeys-text">{{ hotkey.description }}</td>' +
55 '</tr>' +
56 '</tbody></table>' +
57 '<div ng-bind-html="footer" ng-if="footer"></div>' +
58 '<div class="cfp-hotkeys-close" ng-click="toggleCheatSheet()">×</div>' +
59 '</div></div>';
60
61 /**
62 * Configurable setting for the cheat sheet hotkey
63 * @type {String}
64 */
65 this.cheatSheetHotkey = '?';
66
67 /**
68 * Configurable setting for the cheat sheet description
69 * @type {String}
70 */
71 this.cheatSheetDescription = 'Show / hide this help menu';
72
73 this.$get = function ($rootElement, $rootScope, $compile, $window, $document) {
74
75 // monkeypatch Mousetrap's stopCallback() function
76 // this version doesn't return true when the element is an INPUT, SELECT, or TEXTAREA
77 // (instead we will perform this check per-key in the _add() method)
78 Mousetrap.prototype.stopCallback = function(event, element) {
79 // if the element has the class "mousetrap" then no need to stop
80 if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
81 return false;
82 }
83
84 return (element.contentEditable && element.contentEditable == 'true');
85 };
86
87 /**
88 * Convert strings like cmd into symbols like ⌘
89 * @param {String} combo Key combination, e.g. 'mod+f'
90 * @return {String} The key combination with symbols
91 */
92 function symbolize (combo) {
93 var map = {
94 command : '⌘',
95 shift : '⇧',
96 left : '←',
97 right : '→',
98 up : '↑',
99 down : '↓',
100 'return' : '↩',
101 backspace : '⌫'
102 };
103 combo = combo.split('+');
104
105 for (var i = 0; i < combo.length; i++) {
106 // try to resolve command / ctrl based on OS:
107 if (combo[i] === 'mod') {
108 if ($window.navigator && $window.navigator.platform.indexOf('Mac') >=0 ) {
109 combo[i] = 'command';
110 } else {
111 combo[i] = 'ctrl';
112 }
113 }
114
115 combo[i] = map[combo[i]] || combo[i];
116 }
117
118 return combo.join(' + ');
119 }
120
121 /**
122 * Hotkey object used internally for consistency
123 *
124 * @param {array} combo The keycombo. it's an array to support multiple combos
125 * @param {String} description Description for the keycombo
126 * @param {Function} callback function to execute when keycombo pressed
127 * @param {string} action the type of event to listen for (for mousetrap)
128 * @param {array} allowIn an array of tag names to allow this combo in ('INPUT', 'SELECT', and/or 'TEXTAREA')
129 * @param {Boolean} persistent Whether the hotkey persists navigation events
130 */
131 function Hotkey (combo, description, callback, action, allowIn, persistent) {
132 // TODO: Check that the values are sane because we could
133 // be trying to instantiate a new Hotkey with outside dev's
134 // supplied values
135
136 this.combo = combo instanceof Array ? combo : [combo];
137 this.description = description;
138 this.callback = callback;
139 this.action = action;
140 this.allowIn = allowIn;
141 this.persistent = persistent;
142 this._formated = null;
143 }
144
145 /**
146 * Helper method to format (symbolize) the key combo for display
147 *
148 * @return {[Array]} An array of the key combination sequence
149 * for example: "command+g c i" becomes ["⌘ + g", "c", "i"]
150 *
151 */
152 Hotkey.prototype.format = function() {
153 if(this._formated === null) {
154 // Don't show all the possible key combos, just the first one. Not sure
155 // of usecase here, so open a ticket if my assumptions are wrong
156 var combo = this.combo[0];
157
158 var sequence = combo.split(/[\s]/);
159 for (var i = 0; i < sequence.length; i++) {
160 sequence[i] = symbolize(sequence[i]);
161 }
162 this._formated = sequence;
163 }
164
165 return this._formated;
166 };
167
168 /**
169 * A new scope used internally for the cheatsheet
170 * @type {$rootScope.Scope}
171 */
172 var scope = $rootScope.$new();
173
174 /**
175 * Holds an array of Hotkey objects currently bound
176 * @type {Array}
177 */
178 scope.hotkeys = [];
179
180 /**
181 * Contains the state of the help's visibility
182 * @type {Boolean}
183 */
184 scope.helpVisible = false;
185
186 /**
187 * Holds the title string for the help menu
188 * @type {String}
189 */
190 scope.title = this.templateTitle;
191
192 /**
193 * Holds the header HTML for the help menu
194 * @type {String}
195 */
196 scope.header = this.templateHeader;
197
198 /**
199 * Holds the footer HTML for the help menu
200 * @type {String}
201 */
202 scope.footer = this.templateFooter;
203
204 /**
205 * Expose toggleCheatSheet to hotkeys scope so we can call it using
206 * ng-click from the template
207 * @type {function}
208 */
209 scope.toggleCheatSheet = toggleCheatSheet;
210
211
212 /**
213 * Holds references to the different scopes that have bound hotkeys
214 * attached. This is useful to catch when the scopes are `$destroy`d and
215 * then automatically unbind the hotkey.
216 *
217 * @type {Array}
218 */
219 var boundScopes = [];
220
221 if (this.useNgRoute) {
222 $rootScope.$on('$routeChangeSuccess', function (event, route) {
223 purgeHotkeys();
224
225 if (route && route.hotkeys) {
226 angular.forEach(route.hotkeys, function (hotkey) {
227 // a string was given, which implies this is a function that is to be
228 // $eval()'d within that controller's scope
229 // TODO: hotkey here is super confusing. sometimes a function (that gets turned into an array), sometimes a string
230 var callback = hotkey[2];
231 if (typeof(callback) === 'string' || callback instanceof String) {
232 hotkey[2] = [callback, route];
233 }
234
235 // todo: perform check to make sure not already defined:
236 // this came from a route, so it's likely not meant to be persistent
237 hotkey[5] = false;
238 _add.apply(this, hotkey);
239 });
240 }
241 });
242 }
243
244
245
246 // Auto-create a help menu:
247 if (this.includeCheatSheet) {
248 var document = $document[0];
249 var element = $rootElement[0];
250 var helpMenu = angular.element(this.template);
251 _add(this.cheatSheetHotkey, this.cheatSheetDescription, toggleCheatSheet);
252
253 // If $rootElement is document or documentElement, then body must be used
254 if (element === document || element === document.documentElement) {
255 element = document.body;
256 }
257
258 angular.element(element).append($compile(helpMenu)(scope));
259 }
260
261
262 /**
263 * Purges all non-persistent hotkeys (such as those defined in routes)
264 *
265 * Without this, the same hotkey would get recreated everytime
266 * the route is accessed.
267 */
268 function purgeHotkeys() {
269 var i = scope.hotkeys.length;
270 while (i--) {
271 var hotkey = scope.hotkeys[i];
272 if (hotkey && !hotkey.persistent) {
273 _del(hotkey);
274 }
275 }
276 }
277
278 /**
279 * Toggles the help menu element's visiblity
280 */
281 var previousEsc = false;
282
283 function toggleCheatSheet() {
284 scope.helpVisible = !scope.helpVisible;
285
286 // Bind to esc to remove the cheat sheet. Ideally, this would be done
287 // as a directive in the template, but that would create a nasty
288 // circular dependency issue that I don't feel like sorting out.
289 if (scope.helpVisible) {
290 previousEsc = _get('esc');
291 _del('esc');
292
293 // Here's an odd way to do this: we're going to use the original
294 // description of the hotkey on the cheat sheet so that it shows up.
295 // without it, no entry for esc will ever show up (#22)
296 _add('esc', previousEsc.description, toggleCheatSheet, null, ['INPUT', 'SELECT', 'TEXTAREA']);
297 } else {
298 _del('esc');
299
300 // restore the previously bound ESC key
301 if (previousEsc !== false) {
302 _add(previousEsc);
303 }
304 }
305 }
306
307 /**
308 * Creates a new Hotkey and creates the Mousetrap binding
309 *
310 * @param {string} combo mousetrap key binding
311 * @param {string} description description for the help menu
312 * @param {Function} callback method to call when key is pressed
313 * @param {string} action the type of event to listen for (for mousetrap)
314 * @param {array} allowIn an array of tag names to allow this combo in ('INPUT', 'SELECT', and/or 'TEXTAREA')
315 * @param {boolean} persistent if true, the binding is preserved upon route changes
316 */
317 function _add (combo, description, callback, action, allowIn, persistent) {
318
319 // used to save original callback for "allowIn" wrapping:
320 var _callback;
321
322 // these elements are prevented by the default Mousetrap.stopCallback():
323 var preventIn = ['INPUT', 'SELECT', 'TEXTAREA'];
324
325 // Determine if object format was given:
326 var objType = Object.prototype.toString.call(combo);
327
328 if (objType === '[object Object]') {
329 description = combo.description;
330 callback = combo.callback;
331 action = combo.action;
332 persistent = combo.persistent;
333 allowIn = combo.allowIn;
334 combo = combo.combo;
335 }
336
337 // description is optional:
338 if (description instanceof Function) {
339 action = callback;
340 callback = description;
341 description = '$$undefined$$';
342 } else if (angular.isUndefined(description)) {
343 description = '$$undefined$$';
344 }
345
346 // any items added through the public API are for controllers
347 // that persist through navigation, and thus undefined should mean
348 // true in this case.
349 if (persistent === undefined) {
350 persistent = true;
351 }
352 // if callback is defined, then wrap it in a function
353 // that checks if the event originated from a form element.
354 // the function blocks the callback from executing unless the element is specified
355 // in allowIn (emulates Mousetrap.stopCallback() on a per-key level)
356 if (typeof callback === 'function') {
357
358 // save the original callback
359 _callback = callback;
360
361 // make sure allowIn is an array
362 if (!(allowIn instanceof Array)) {
363 allowIn = [];
364 }
365
366 // remove anything from preventIn that's present in allowIn
367 var index;
368 for (var i=0; i < allowIn.length; i++) {
369 allowIn[i] = allowIn[i].toUpperCase();
370 index = preventIn.indexOf(allowIn[i]);
371 if (index !== -1) {
372 preventIn.splice(index, 1);
373 }
374 }
375
376 // create the new wrapper callback
377 callback = function(event) {
378 var shouldExecute = true;
379 var target = event.target || event.srcElement; // srcElement is IE only
380 var nodeName = target.nodeName.toUpperCase();
381
382 // check if the input has a mousetrap class, and skip checking preventIn if so
383 if ((' ' + target.className + ' ').indexOf(' mousetrap ') > -1) {
384 shouldExecute = true;
385 } else {
386 // don't execute callback if the event was fired from inside an element listed in preventIn
387 for (var i=0; i<preventIn.length; i++) {
388 if (preventIn[i] === nodeName) {
389 shouldExecute = false;
390 break;
391 }
392 }
393 }
394
395 if (shouldExecute) {
396 wrapApply(_callback.apply(this, arguments));
397 }
398 };
399 }
400
401 if (typeof(action) === 'string') {
402 Mousetrap.bind(combo, wrapApply(callback), action);
403 } else {
404 Mousetrap.bind(combo, wrapApply(callback));
405 }
406
407 var hotkey = new Hotkey(combo, description, callback, action, allowIn, persistent);
408 scope.hotkeys.push(hotkey);
409 return hotkey;
410 }
411
412 /**
413 * delete and unbind a Hotkey
414 *
415 * @param {mixed} hotkey Either the bound key or an instance of Hotkey
416 * @return {boolean} true if successful
417 */
418 function _del (hotkey) {
419 var combo = (hotkey instanceof Hotkey) ? hotkey.combo : hotkey;
420
421 Mousetrap.unbind(combo);
422
423 if (angular.isArray(combo)) {
424 var retStatus = true;
425 var i = combo.length;
426 while (i--) {
427 retStatus = _del(combo[i]) && retStatus;
428 }
429 return retStatus;
430 } else {
431 var index = scope.hotkeys.indexOf(_get(combo));
432
433 if (index > -1) {
434 // if the combo has other combos bound, don't unbind the whole thing, just the one combo:
435 if (scope.hotkeys[index].combo.length > 1) {
436 scope.hotkeys[index].combo.splice(scope.hotkeys[index].combo.indexOf(combo), 1);
437 } else {
438 scope.hotkeys.splice(index, 1);
439 }
440 return true;
441 }
442 }
443
444 return false;
445
446 }
447
448 /**
449 * Get a Hotkey object by key binding
450 *
451 * @param {[string]} combo the key the Hotkey is bound to
452 * @return {Hotkey} The Hotkey object
453 */
454 function _get (combo) {
455
456 var hotkey;
457
458 for (var i = 0; i < scope.hotkeys.length; i++) {
459 hotkey = scope.hotkeys[i];
460
461 if (hotkey.combo.indexOf(combo) > -1) {
462 return hotkey;
463 }
464 }
465
466 return false;
467 }
468
469 /**
470 * Binds the hotkey to a particular scope. Useful if the scope is
471 * destroyed, we can automatically destroy the hotkey binding.
472 *
473 * @param {Object} scope The scope to bind to
474 */
475 function bindTo (scope) {
476 // Only initialize once to allow multiple calls for same scope.
477 if (!(scope.$id in boundScopes)) {
478
479 // Add the scope to the list of bound scopes
480 boundScopes[scope.$id] = [];
481
482 scope.$on('$destroy', function () {
483 var i = boundScopes[scope.$id].length;
484 while (i--) {
485 _del(boundScopes[scope.$id].pop());
486 }
487 });
488 }
489 // return an object with an add function so we can keep track of the
490 // hotkeys and their scope that we added via this chaining method
491 return {
492 add: function (args) {
493 var hotkey;
494
495 if (arguments.length > 1) {
496 hotkey = _add.apply(this, arguments);
497 } else {
498 hotkey = _add(args);
499 }
500
501 boundScopes[scope.$id].push(hotkey);
502 return this;
503 }
504 };
505 }
506
507 /**
508 * All callbacks sent to Mousetrap are wrapped using this function
509 * so that we can force a $scope.$apply()
510 *
511 * @param {Function} callback [description]
512 * @return {[type]} [description]
513 */
514 function wrapApply (callback) {
515 // return mousetrap a function to call
516 return function (event, combo) {
517
518 // if this is an array, it means we provided a route object
519 // because the scope wasn't available yet, so rewrap the callback
520 // now that the scope is available:
521 if (callback instanceof Array) {
522 var funcString = callback[0];
523 var route = callback[1];
524 callback = function (event) {
525 route.scope.$eval(funcString);
526 };
527 }
528
529 // this takes place outside angular, so we'll have to call
530 // $apply() to make sure angular's digest happens
531 $rootScope.$apply(function() {
532 // call the original hotkey callback with the keyboard event
533 callback(event, _get(combo));
534 });
535 };
536 }
537
538
539 var publicApi = {
540 add : _add,
541 del : _del,
542 get : _get,
543 bindTo : bindTo,
544 template : this.template,
545 toggleCheatSheet : toggleCheatSheet,
546 includeCheatSheet : this.includeCheatSheet,
547 cheatSheetHotkey : this.cheatSheetHotkey,
548 cheatSheetDescription : this.cheatSheetDescription,
549 useNgRoute : this.useNgRoute,
550 purgeHotkeys : purgeHotkeys,
551 templateTitle : this.templateTitle
552 };
553
554 return publicApi;
555
556 };
557
558
559 })
560
561 .directive('hotkey', function (hotkeys) {
562 return {
563 restrict: 'A',
564 link: function (scope, el, attrs) {
565 var key, allowIn;
566
567 angular.forEach(scope.$eval(attrs.hotkey), function (func, hotkey) {
568 // split and trim the hotkeys string into array
569 allowIn = typeof attrs.hotkeyAllowIn === "string" ? attrs.hotkeyAllowIn.split(/[\s,]+/) : [];
570
571 key = hotkey;
572
573 hotkeys.add({
574 combo: hotkey,
575 description: attrs.hotkeyDescription,
576 callback: func,
577 action: attrs.hotkeyAction,
578 allowIn: allowIn
579 });
580 });
581
582 // remove the hotkey if the directive is destroyed:
583 el.bind('$destroy', function() {
584 hotkeys.del(key);
585 });
586 }
587 };
588 })
589
590 .run(function(hotkeys) {
591 // force hotkeys to run by injecting it. Without this, hotkeys only runs
592 // when a controller or something else asks for it via DI.
593 });
594
595 })();
0 /**
1 * @license AngularJS v1.2.23
2 * (c) 2010-2014 Google, Inc. http://angularjs.org
3 * License: MIT
4 */
5 (function(window, angular, undefined) {
6
7 'use strict';
8
9 /**
10 * @ngdoc object
11 * @name angular.mock
12 * @description
13 *
14 * Namespace from 'angular-mocks.js' which contains testing related code.
15 */
16 angular.mock = {};
17
18 /**
19 * ! This is a private undocumented service !
20 *
21 * @name $browser
22 *
23 * @description
24 * This service is a mock implementation of {@link ng.$browser}. It provides fake
25 * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr,
26 * cookies, etc...
27 *
28 * The api of this service is the same as that of the real {@link ng.$browser $browser}, except
29 * that there are several helper methods available which can be used in tests.
30 */
31 angular.mock.$BrowserProvider = function() {
32 this.$get = function() {
33 return new angular.mock.$Browser();
34 };
35 };
36
37 angular.mock.$Browser = function() {
38 var self = this;
39
40 this.isMock = true;
41 self.$$url = "http://server/";
42 self.$$lastUrl = self.$$url; // used by url polling fn
43 self.pollFns = [];
44
45 // TODO(vojta): remove this temporary api
46 self.$$completeOutstandingRequest = angular.noop;
47 self.$$incOutstandingRequestCount = angular.noop;
48
49
50 // register url polling fn
51
52 self.onUrlChange = function(listener) {
53 self.pollFns.push(
54 function() {
55 if (self.$$lastUrl != self.$$url) {
56 self.$$lastUrl = self.$$url;
57 listener(self.$$url);
58 }
59 }
60 );
61
62 return listener;
63 };
64
65 self.cookieHash = {};
66 self.lastCookieHash = {};
67 self.deferredFns = [];
68 self.deferredNextId = 0;
69
70 self.defer = function(fn, delay) {
71 delay = delay || 0;
72 self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId});
73 self.deferredFns.sort(function(a,b){ return a.time - b.time;});
74 return self.deferredNextId++;
75 };
76
77
78 /**
79 * @name $browser#defer.now
80 *
81 * @description
82 * Current milliseconds mock time.
83 */
84 self.defer.now = 0;
85
86
87 self.defer.cancel = function(deferId) {
88 var fnIndex;
89
90 angular.forEach(self.deferredFns, function(fn, index) {
91 if (fn.id === deferId) fnIndex = index;
92 });
93
94 if (fnIndex !== undefined) {
95 self.deferredFns.splice(fnIndex, 1);
96 return true;
97 }
98
99 return false;
100 };
101
102
103 /**
104 * @name $browser#defer.flush
105 *
106 * @description
107 * Flushes all pending requests and executes the defer callbacks.
108 *
109 * @param {number=} number of milliseconds to flush. See {@link #defer.now}
110 */
111 self.defer.flush = function(delay) {
112 if (angular.isDefined(delay)) {
113 self.defer.now += delay;
114 } else {
115 if (self.deferredFns.length) {
116 self.defer.now = self.deferredFns[self.deferredFns.length-1].time;
117 } else {
118 throw new Error('No deferred tasks to be flushed');
119 }
120 }
121
122 while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {
123 self.deferredFns.shift().fn();
124 }
125 };
126
127 self.$$baseHref = '';
128 self.baseHref = function() {
129 return this.$$baseHref;
130 };
131 };
132 angular.mock.$Browser.prototype = {
133
134 /**
135 * @name $browser#poll
136 *
137 * @description
138 * run all fns in pollFns
139 */
140 poll: function poll() {
141 angular.forEach(this.pollFns, function(pollFn){
142 pollFn();
143 });
144 },
145
146 addPollFn: function(pollFn) {
147 this.pollFns.push(pollFn);
148 return pollFn;
149 },
150
151 url: function(url, replace) {
152 if (url) {
153 this.$$url = url;
154 return this;
155 }
156
157 return this.$$url;
158 },
159
160 cookies: function(name, value) {
161 if (name) {
162 if (angular.isUndefined(value)) {
163 delete this.cookieHash[name];
164 } else {
165 if (angular.isString(value) && //strings only
166 value.length <= 4096) { //strict cookie storage limits
167 this.cookieHash[name] = value;
168 }
169 }
170 } else {
171 if (!angular.equals(this.cookieHash, this.lastCookieHash)) {
172 this.lastCookieHash = angular.copy(this.cookieHash);
173 this.cookieHash = angular.copy(this.cookieHash);
174 }
175 return this.cookieHash;
176 }
177 },
178
179 notifyWhenNoOutstandingRequests: function(fn) {
180 fn();
181 }
182 };
183
184
185 /**
186 * @ngdoc provider
187 * @name $exceptionHandlerProvider
188 *
189 * @description
190 * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors
191 * passed into the `$exceptionHandler`.
192 */
193
194 /**
195 * @ngdoc service
196 * @name $exceptionHandler
197 *
198 * @description
199 * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed
200 * into it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration
201 * information.
202 *
203 *
204 * ```js
205 * describe('$exceptionHandlerProvider', function() {
206 *
207 * it('should capture log messages and exceptions', function() {
208 *
209 * module(function($exceptionHandlerProvider) {
210 * $exceptionHandlerProvider.mode('log');
211 * });
212 *
213 * inject(function($log, $exceptionHandler, $timeout) {
214 * $timeout(function() { $log.log(1); });
215 * $timeout(function() { $log.log(2); throw 'banana peel'; });
216 * $timeout(function() { $log.log(3); });
217 * expect($exceptionHandler.errors).toEqual([]);
218 * expect($log.assertEmpty());
219 * $timeout.flush();
220 * expect($exceptionHandler.errors).toEqual(['banana peel']);
221 * expect($log.log.logs).toEqual([[1], [2], [3]]);
222 * });
223 * });
224 * });
225 * ```
226 */
227
228 angular.mock.$ExceptionHandlerProvider = function() {
229 var handler;
230
231 /**
232 * @ngdoc method
233 * @name $exceptionHandlerProvider#mode
234 *
235 * @description
236 * Sets the logging mode.
237 *
238 * @param {string} mode Mode of operation, defaults to `rethrow`.
239 *
240 * - `rethrow`: If any errors are passed into the handler in tests, it typically
241 * means that there is a bug in the application or test, so this mock will
242 * make these tests fail.
243 * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log`
244 * mode stores an array of errors in `$exceptionHandler.errors`, to allow later
245 * assertion of them. See {@link ngMock.$log#assertEmpty assertEmpty()} and
246 * {@link ngMock.$log#reset reset()}
247 */
248 this.mode = function(mode) {
249 switch(mode) {
250 case 'rethrow':
251 handler = function(e) {
252 throw e;
253 };
254 break;
255 case 'log':
256 var errors = [];
257
258 handler = function(e) {
259 if (arguments.length == 1) {
260 errors.push(e);
261 } else {
262 errors.push([].slice.call(arguments, 0));
263 }
264 };
265
266 handler.errors = errors;
267 break;
268 default:
269 throw new Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
270 }
271 };
272
273 this.$get = function() {
274 return handler;
275 };
276
277 this.mode('rethrow');
278 };
279
280
281 /**
282 * @ngdoc service
283 * @name $log
284 *
285 * @description
286 * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays
287 * (one array per logging level). These arrays are exposed as `logs` property of each of the
288 * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`.
289 *
290 */
291 angular.mock.$LogProvider = function() {
292 var debug = true;
293
294 function concat(array1, array2, index) {
295 return array1.concat(Array.prototype.slice.call(array2, index));
296 }
297
298 this.debugEnabled = function(flag) {
299 if (angular.isDefined(flag)) {
300 debug = flag;
301 return this;
302 } else {
303 return debug;
304 }
305 };
306
307 this.$get = function () {
308 var $log = {
309 log: function() { $log.log.logs.push(concat([], arguments, 0)); },
310 warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },
311 info: function() { $log.info.logs.push(concat([], arguments, 0)); },
312 error: function() { $log.error.logs.push(concat([], arguments, 0)); },
313 debug: function() {
314 if (debug) {
315 $log.debug.logs.push(concat([], arguments, 0));
316 }
317 }
318 };
319
320 /**
321 * @ngdoc method
322 * @name $log#reset
323 *
324 * @description
325 * Reset all of the logging arrays to empty.
326 */
327 $log.reset = function () {
328 /**
329 * @ngdoc property
330 * @name $log#log.logs
331 *
332 * @description
333 * Array of messages logged using {@link ngMock.$log#log}.
334 *
335 * @example
336 * ```js
337 * $log.log('Some Log');
338 * var first = $log.log.logs.unshift();
339 * ```
340 */
341 $log.log.logs = [];
342 /**
343 * @ngdoc property
344 * @name $log#info.logs
345 *
346 * @description
347 * Array of messages logged using {@link ngMock.$log#info}.
348 *
349 * @example
350 * ```js
351 * $log.info('Some Info');
352 * var first = $log.info.logs.unshift();
353 * ```
354 */
355 $log.info.logs = [];
356 /**
357 * @ngdoc property
358 * @name $log#warn.logs
359 *
360 * @description
361 * Array of messages logged using {@link ngMock.$log#warn}.
362 *
363 * @example
364 * ```js
365 * $log.warn('Some Warning');
366 * var first = $log.warn.logs.unshift();
367 * ```
368 */
369 $log.warn.logs = [];
370 /**
371 * @ngdoc property
372 * @name $log#error.logs
373 *
374 * @description
375 * Array of messages logged using {@link ngMock.$log#error}.
376 *
377 * @example
378 * ```js
379 * $log.error('Some Error');
380 * var first = $log.error.logs.unshift();
381 * ```
382 */
383 $log.error.logs = [];
384 /**
385 * @ngdoc property
386 * @name $log#debug.logs
387 *
388 * @description
389 * Array of messages logged using {@link ngMock.$log#debug}.
390 *
391 * @example
392 * ```js
393 * $log.debug('Some Error');
394 * var first = $log.debug.logs.unshift();
395 * ```
396 */
397 $log.debug.logs = [];
398 };
399
400 /**
401 * @ngdoc method
402 * @name $log#assertEmpty
403 *
404 * @description
405 * Assert that the all of the logging methods have no logged messages. If messages present, an
406 * exception is thrown.
407 */
408 $log.assertEmpty = function() {
409 var errors = [];
410 angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) {
411 angular.forEach($log[logLevel].logs, function(log) {
412 angular.forEach(log, function (logItem) {
413 errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' +
414 (logItem.stack || ''));
415 });
416 });
417 });
418 if (errors.length) {
419 errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or "+
420 "an expected log message was not checked and removed:");
421 errors.push('');
422 throw new Error(errors.join('\n---------\n'));
423 }
424 };
425
426 $log.reset();
427 return $log;
428 };
429 };
430
431
432 /**
433 * @ngdoc service
434 * @name $interval
435 *
436 * @description
437 * Mock implementation of the $interval service.
438 *
439 * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
440 * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
441 * time.
442 *
443 * @param {function()} fn A function that should be called repeatedly.
444 * @param {number} delay Number of milliseconds between each function call.
445 * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
446 * indefinitely.
447 * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
448 * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
449 * @returns {promise} A promise which will be notified on each iteration.
450 */
451 angular.mock.$IntervalProvider = function() {
452 this.$get = ['$rootScope', '$q',
453 function($rootScope, $q) {
454 var repeatFns = [],
455 nextRepeatId = 0,
456 now = 0;
457
458 var $interval = function(fn, delay, count, invokeApply) {
459 var deferred = $q.defer(),
460 promise = deferred.promise,
461 iteration = 0,
462 skipApply = (angular.isDefined(invokeApply) && !invokeApply);
463
464 count = (angular.isDefined(count)) ? count : 0;
465 promise.then(null, null, fn);
466
467 promise.$$intervalId = nextRepeatId;
468
469 function tick() {
470 deferred.notify(iteration++);
471
472 if (count > 0 && iteration >= count) {
473 var fnIndex;
474 deferred.resolve(iteration);
475
476 angular.forEach(repeatFns, function(fn, index) {
477 if (fn.id === promise.$$intervalId) fnIndex = index;
478 });
479
480 if (fnIndex !== undefined) {
481 repeatFns.splice(fnIndex, 1);
482 }
483 }
484
485 if (!skipApply) $rootScope.$apply();
486 }
487
488 repeatFns.push({
489 nextTime:(now + delay),
490 delay: delay,
491 fn: tick,
492 id: nextRepeatId,
493 deferred: deferred
494 });
495 repeatFns.sort(function(a,b){ return a.nextTime - b.nextTime;});
496
497 nextRepeatId++;
498 return promise;
499 };
500 /**
501 * @ngdoc method
502 * @name $interval#cancel
503 *
504 * @description
505 * Cancels a task associated with the `promise`.
506 *
507 * @param {promise} promise A promise from calling the `$interval` function.
508 * @returns {boolean} Returns `true` if the task was successfully cancelled.
509 */
510 $interval.cancel = function(promise) {
511 if(!promise) return false;
512 var fnIndex;
513
514 angular.forEach(repeatFns, function(fn, index) {
515 if (fn.id === promise.$$intervalId) fnIndex = index;
516 });
517
518 if (fnIndex !== undefined) {
519 repeatFns[fnIndex].deferred.reject('canceled');
520 repeatFns.splice(fnIndex, 1);
521 return true;
522 }
523
524 return false;
525 };
526
527 /**
528 * @ngdoc method
529 * @name $interval#flush
530 * @description
531 *
532 * Runs interval tasks scheduled to be run in the next `millis` milliseconds.
533 *
534 * @param {number=} millis maximum timeout amount to flush up until.
535 *
536 * @return {number} The amount of time moved forward.
537 */
538 $interval.flush = function(millis) {
539 now += millis;
540 while (repeatFns.length && repeatFns[0].nextTime <= now) {
541 var task = repeatFns[0];
542 task.fn();
543 task.nextTime += task.delay;
544 repeatFns.sort(function(a,b){ return a.nextTime - b.nextTime;});
545 }
546 return millis;
547 };
548
549 return $interval;
550 }];
551 };
552
553
554 /* jshint -W101 */
555 /* The R_ISO8061_STR regex is never going to fit into the 100 char limit!
556 * This directive should go inside the anonymous function but a bug in JSHint means that it would
557 * not be enacted early enough to prevent the warning.
558 */
559 var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
560
561 function jsonStringToDate(string) {
562 var match;
563 if (match = string.match(R_ISO8061_STR)) {
564 var date = new Date(0),
565 tzHour = 0,
566 tzMin = 0;
567 if (match[9]) {
568 tzHour = int(match[9] + match[10]);
569 tzMin = int(match[9] + match[11]);
570 }
571 date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
572 date.setUTCHours(int(match[4]||0) - tzHour,
573 int(match[5]||0) - tzMin,
574 int(match[6]||0),
575 int(match[7]||0));
576 return date;
577 }
578 return string;
579 }
580
581 function int(str) {
582 return parseInt(str, 10);
583 }
584
585 function padNumber(num, digits, trim) {
586 var neg = '';
587 if (num < 0) {
588 neg = '-';
589 num = -num;
590 }
591 num = '' + num;
592 while(num.length < digits) num = '0' + num;
593 if (trim)
594 num = num.substr(num.length - digits);
595 return neg + num;
596 }
597
598
599 /**
600 * @ngdoc type
601 * @name angular.mock.TzDate
602 * @description
603 *
604 * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.
605 *
606 * Mock of the Date type which has its timezone specified via constructor arg.
607 *
608 * The main purpose is to create Date-like instances with timezone fixed to the specified timezone
609 * offset, so that we can test code that depends on local timezone settings without dependency on
610 * the time zone settings of the machine where the code is running.
611 *
612 * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)
613 * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*
614 *
615 * @example
616 * !!!! WARNING !!!!!
617 * This is not a complete Date object so only methods that were implemented can be called safely.
618 * To make matters worse, TzDate instances inherit stuff from Date via a prototype.
619 *
620 * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is
621 * incomplete we might be missing some non-standard methods. This can result in errors like:
622 * "Date.prototype.foo called on incompatible Object".
623 *
624 * ```js
625 * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
626 * newYearInBratislava.getTimezoneOffset() => -60;
627 * newYearInBratislava.getFullYear() => 2010;
628 * newYearInBratislava.getMonth() => 0;
629 * newYearInBratislava.getDate() => 1;
630 * newYearInBratislava.getHours() => 0;
631 * newYearInBratislava.getMinutes() => 0;
632 * newYearInBratislava.getSeconds() => 0;
633 * ```
634 *
635 */
636 angular.mock.TzDate = function (offset, timestamp) {
637 var self = new Date(0);
638 if (angular.isString(timestamp)) {
639 var tsStr = timestamp;
640
641 self.origDate = jsonStringToDate(timestamp);
642
643 timestamp = self.origDate.getTime();
644 if (isNaN(timestamp))
645 throw {
646 name: "Illegal Argument",
647 message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string"
648 };
649 } else {
650 self.origDate = new Date(timestamp);
651 }
652
653 var localOffset = new Date(timestamp).getTimezoneOffset();
654 self.offsetDiff = localOffset*60*1000 - offset*1000*60*60;
655 self.date = new Date(timestamp + self.offsetDiff);
656
657 self.getTime = function() {
658 return self.date.getTime() - self.offsetDiff;
659 };
660
661 self.toLocaleDateString = function() {
662 return self.date.toLocaleDateString();
663 };
664
665 self.getFullYear = function() {
666 return self.date.getFullYear();
667 };
668
669 self.getMonth = function() {
670 return self.date.getMonth();
671 };
672
673 self.getDate = function() {
674 return self.date.getDate();
675 };
676
677 self.getHours = function() {
678 return self.date.getHours();
679 };
680
681 self.getMinutes = function() {
682 return self.date.getMinutes();
683 };
684
685 self.getSeconds = function() {
686 return self.date.getSeconds();
687 };
688
689 self.getMilliseconds = function() {
690 return self.date.getMilliseconds();
691 };
692
693 self.getTimezoneOffset = function() {
694 return offset * 60;
695 };
696
697 self.getUTCFullYear = function() {
698 return self.origDate.getUTCFullYear();
699 };
700
701 self.getUTCMonth = function() {
702 return self.origDate.getUTCMonth();
703 };
704
705 self.getUTCDate = function() {
706 return self.origDate.getUTCDate();
707 };
708
709 self.getUTCHours = function() {
710 return self.origDate.getUTCHours();
711 };
712
713 self.getUTCMinutes = function() {
714 return self.origDate.getUTCMinutes();
715 };
716
717 self.getUTCSeconds = function() {
718 return self.origDate.getUTCSeconds();
719 };
720
721 self.getUTCMilliseconds = function() {
722 return self.origDate.getUTCMilliseconds();
723 };
724
725 self.getDay = function() {
726 return self.date.getDay();
727 };
728
729 // provide this method only on browsers that already have it
730 if (self.toISOString) {
731 self.toISOString = function() {
732 return padNumber(self.origDate.getUTCFullYear(), 4) + '-' +
733 padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' +
734 padNumber(self.origDate.getUTCDate(), 2) + 'T' +
735 padNumber(self.origDate.getUTCHours(), 2) + ':' +
736 padNumber(self.origDate.getUTCMinutes(), 2) + ':' +
737 padNumber(self.origDate.getUTCSeconds(), 2) + '.' +
738 padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z';
739 };
740 }
741
742 //hide all methods not implemented in this mock that the Date prototype exposes
743 var unimplementedMethods = ['getUTCDay',
744 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
745 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',
746 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',
747 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',
748 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];
749
750 angular.forEach(unimplementedMethods, function(methodName) {
751 self[methodName] = function() {
752 throw new Error("Method '" + methodName + "' is not implemented in the TzDate mock");
753 };
754 });
755
756 return self;
757 };
758
759 //make "tzDateInstance instanceof Date" return true
760 angular.mock.TzDate.prototype = Date.prototype;
761 /* jshint +W101 */
762
763 angular.mock.animate = angular.module('ngAnimateMock', ['ng'])
764
765 .config(['$provide', function($provide) {
766
767 var reflowQueue = [];
768 $provide.value('$$animateReflow', function(fn) {
769 var index = reflowQueue.length;
770 reflowQueue.push(fn);
771 return function cancel() {
772 reflowQueue.splice(index, 1);
773 };
774 });
775
776 $provide.decorator('$animate', function($delegate, $$asyncCallback) {
777 var animate = {
778 queue : [],
779 enabled : $delegate.enabled,
780 triggerCallbacks : function() {
781 $$asyncCallback.flush();
782 },
783 triggerReflow : function() {
784 angular.forEach(reflowQueue, function(fn) {
785 fn();
786 });
787 reflowQueue = [];
788 }
789 };
790
791 angular.forEach(
792 ['enter','leave','move','addClass','removeClass','setClass'], function(method) {
793 animate[method] = function() {
794 animate.queue.push({
795 event : method,
796 element : arguments[0],
797 args : arguments
798 });
799 $delegate[method].apply($delegate, arguments);
800 };
801 });
802
803 return animate;
804 });
805
806 }]);
807
808
809 /**
810 * @ngdoc function
811 * @name angular.mock.dump
812 * @description
813 *
814 * *NOTE*: this is not an injectable instance, just a globally available function.
815 *
816 * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for
817 * debugging.
818 *
819 * This method is also available on window, where it can be used to display objects on debug
820 * console.
821 *
822 * @param {*} object - any object to turn into string.
823 * @return {string} a serialized string of the argument
824 */
825 angular.mock.dump = function(object) {
826 return serialize(object);
827
828 function serialize(object) {
829 var out;
830
831 if (angular.isElement(object)) {
832 object = angular.element(object);
833 out = angular.element('<div></div>');
834 angular.forEach(object, function(element) {
835 out.append(angular.element(element).clone());
836 });
837 out = out.html();
838 } else if (angular.isArray(object)) {
839 out = [];
840 angular.forEach(object, function(o) {
841 out.push(serialize(o));
842 });
843 out = '[ ' + out.join(', ') + ' ]';
844 } else if (angular.isObject(object)) {
845 if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {
846 out = serializeScope(object);
847 } else if (object instanceof Error) {
848 out = object.stack || ('' + object.name + ': ' + object.message);
849 } else {
850 // TODO(i): this prevents methods being logged,
851 // we should have a better way to serialize objects
852 out = angular.toJson(object, true);
853 }
854 } else {
855 out = String(object);
856 }
857
858 return out;
859 }
860
861 function serializeScope(scope, offset) {
862 offset = offset || ' ';
863 var log = [offset + 'Scope(' + scope.$id + '): {'];
864 for ( var key in scope ) {
865 if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) {
866 log.push(' ' + key + ': ' + angular.toJson(scope[key]));
867 }
868 }
869 var child = scope.$$childHead;
870 while(child) {
871 log.push(serializeScope(child, offset + ' '));
872 child = child.$$nextSibling;
873 }
874 log.push('}');
875 return log.join('\n' + offset);
876 }
877 };
878
879 /**
880 * @ngdoc service
881 * @name $httpBackend
882 * @description
883 * Fake HTTP backend implementation suitable for unit testing applications that use the
884 * {@link ng.$http $http service}.
885 *
886 * *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less
887 * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}.
888 *
889 * During unit testing, we want our unit tests to run quickly and have no external dependencies so
890 * we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or
891 * [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is
892 * to verify whether a certain request has been sent or not, or alternatively just let the
893 * application make requests, respond with pre-trained responses and assert that the end result is
894 * what we expect it to be.
895 *
896 * This mock implementation can be used to respond with static or dynamic responses via the
897 * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc).
898 *
899 * When an Angular application needs some data from a server, it calls the $http service, which
900 * sends the request to a real server using $httpBackend service. With dependency injection, it is
901 * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify
902 * the requests and respond with some testing data without sending a request to a real server.
903 *
904 * There are two ways to specify what test data should be returned as http responses by the mock
905 * backend when the code under test makes http requests:
906 *
907 * - `$httpBackend.expect` - specifies a request expectation
908 * - `$httpBackend.when` - specifies a backend definition
909 *
910 *
911 * # Request Expectations vs Backend Definitions
912 *
913 * Request expectations provide a way to make assertions about requests made by the application and
914 * to define responses for those requests. The test will fail if the expected requests are not made
915 * or they are made in the wrong order.
916 *
917 * Backend definitions allow you to define a fake backend for your application which doesn't assert
918 * if a particular request was made or not, it just returns a trained response if a request is made.
919 * The test will pass whether or not the request gets made during testing.
920 *
921 *
922 * <table class="table">
923 * <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr>
924 * <tr>
925 * <th>Syntax</th>
926 * <td>.expect(...).respond(...)</td>
927 * <td>.when(...).respond(...)</td>
928 * </tr>
929 * <tr>
930 * <th>Typical usage</th>
931 * <td>strict unit tests</td>
932 * <td>loose (black-box) unit testing</td>
933 * </tr>
934 * <tr>
935 * <th>Fulfills multiple requests</th>
936 * <td>NO</td>
937 * <td>YES</td>
938 * </tr>
939 * <tr>
940 * <th>Order of requests matters</th>
941 * <td>YES</td>
942 * <td>NO</td>
943 * </tr>
944 * <tr>
945 * <th>Request required</th>
946 * <td>YES</td>
947 * <td>NO</td>
948 * </tr>
949 * <tr>
950 * <th>Response required</th>
951 * <td>optional (see below)</td>
952 * <td>YES</td>
953 * </tr>
954 * </table>
955 *
956 * In cases where both backend definitions and request expectations are specified during unit
957 * testing, the request expectations are evaluated first.
958 *
959 * If a request expectation has no response specified, the algorithm will search your backend
960 * definitions for an appropriate response.
961 *
962 * If a request didn't match any expectation or if the expectation doesn't have the response
963 * defined, the backend definitions are evaluated in sequential order to see if any of them match
964 * the request. The response from the first matched definition is returned.
965 *
966 *
967 * # Flushing HTTP requests
968 *
969 * The $httpBackend used in production always responds to requests asynchronously. If we preserved
970 * this behavior in unit testing, we'd have to create async unit tests, which are hard to write,
971 * to follow and to maintain. But neither can the testing mock respond synchronously; that would
972 * change the execution of the code under test. For this reason, the mock $httpBackend has a
973 * `flush()` method, which allows the test to explicitly flush pending requests. This preserves
974 * the async api of the backend, while allowing the test to execute synchronously.
975 *
976 *
977 * # Unit testing with mock $httpBackend
978 * The following code shows how to setup and use the mock backend when unit testing a controller.
979 * First we create the controller under test:
980 *
981 ```js
982 // The controller code
983 function MyController($scope, $http) {
984 var authToken;
985
986 $http.get('/auth.py').success(function(data, status, headers) {
987 authToken = headers('A-Token');
988 $scope.user = data;
989 });
990
991 $scope.saveMessage = function(message) {
992 var headers = { 'Authorization': authToken };
993 $scope.status = 'Saving...';
994
995 $http.post('/add-msg.py', message, { headers: headers } ).success(function(response) {
996 $scope.status = '';
997 }).error(function() {
998 $scope.status = 'ERROR!';
999 });
1000 };
1001 }
1002 ```
1003 *
1004 * Now we setup the mock backend and create the test specs:
1005 *
1006 ```js
1007 // testing controller
1008 describe('MyController', function() {
1009 var $httpBackend, $rootScope, createController;
1010
1011 beforeEach(inject(function($injector) {
1012 // Set up the mock http service responses
1013 $httpBackend = $injector.get('$httpBackend');
1014 // backend definition common for all tests
1015 $httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'});
1016
1017 // Get hold of a scope (i.e. the root scope)
1018 $rootScope = $injector.get('$rootScope');
1019 // The $controller service is used to create instances of controllers
1020 var $controller = $injector.get('$controller');
1021
1022 createController = function() {
1023 return $controller('MyController', {'$scope' : $rootScope });
1024 };
1025 }));
1026
1027
1028 afterEach(function() {
1029 $httpBackend.verifyNoOutstandingExpectation();
1030 $httpBackend.verifyNoOutstandingRequest();
1031 });
1032
1033
1034 it('should fetch authentication token', function() {
1035 $httpBackend.expectGET('/auth.py');
1036 var controller = createController();
1037 $httpBackend.flush();
1038 });
1039
1040
1041 it('should send msg to server', function() {
1042 var controller = createController();
1043 $httpBackend.flush();
1044
1045 // now you don’t care about the authentication, but
1046 // the controller will still send the request and
1047 // $httpBackend will respond without you having to
1048 // specify the expectation and response for this request
1049
1050 $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
1051 $rootScope.saveMessage('message content');
1052 expect($rootScope.status).toBe('Saving...');
1053 $httpBackend.flush();
1054 expect($rootScope.status).toBe('');
1055 });
1056
1057
1058 it('should send auth header', function() {
1059 var controller = createController();
1060 $httpBackend.flush();
1061
1062 $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
1063 // check if the header was send, if it wasn't the expectation won't
1064 // match the request and the test will fail
1065 return headers['Authorization'] == 'xxx';
1066 }).respond(201, '');
1067
1068 $rootScope.saveMessage('whatever');
1069 $httpBackend.flush();
1070 });
1071 });
1072 ```
1073 */
1074 angular.mock.$HttpBackendProvider = function() {
1075 this.$get = ['$rootScope', createHttpBackendMock];
1076 };
1077
1078 /**
1079 * General factory function for $httpBackend mock.
1080 * Returns instance for unit testing (when no arguments specified):
1081 * - passing through is disabled
1082 * - auto flushing is disabled
1083 *
1084 * Returns instance for e2e testing (when `$delegate` and `$browser` specified):
1085 * - passing through (delegating request to real backend) is enabled
1086 * - auto flushing is enabled
1087 *
1088 * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified)
1089 * @param {Object=} $browser Auto-flushing enabled if specified
1090 * @return {Object} Instance of $httpBackend mock
1091 */
1092 function createHttpBackendMock($rootScope, $delegate, $browser) {
1093 var definitions = [],
1094 expectations = [],
1095 responses = [],
1096 responsesPush = angular.bind(responses, responses.push),
1097 copy = angular.copy;
1098
1099 function createResponse(status, data, headers, statusText) {
1100 if (angular.isFunction(status)) return status;
1101
1102 return function() {
1103 return angular.isNumber(status)
1104 ? [status, data, headers, statusText]
1105 : [200, status, data];
1106 };
1107 }
1108
1109 // TODO(vojta): change params to: method, url, data, headers, callback
1110 function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) {
1111 var xhr = new MockXhr(),
1112 expectation = expectations[0],
1113 wasExpected = false;
1114
1115 function prettyPrint(data) {
1116 return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
1117 ? data
1118 : angular.toJson(data);
1119 }
1120
1121 function wrapResponse(wrapped) {
1122 if (!$browser && timeout && timeout.then) timeout.then(handleTimeout);
1123
1124 return handleResponse;
1125
1126 function handleResponse() {
1127 var response = wrapped.response(method, url, data, headers);
1128 xhr.$$respHeaders = response[2];
1129 callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(),
1130 copy(response[3] || ''));
1131 }
1132
1133 function handleTimeout() {
1134 for (var i = 0, ii = responses.length; i < ii; i++) {
1135 if (responses[i] === handleResponse) {
1136 responses.splice(i, 1);
1137 callback(-1, undefined, '');
1138 break;
1139 }
1140 }
1141 }
1142 }
1143
1144 if (expectation && expectation.match(method, url)) {
1145 if (!expectation.matchData(data))
1146 throw new Error('Expected ' + expectation + ' with different data\n' +
1147 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data);
1148
1149 if (!expectation.matchHeaders(headers))
1150 throw new Error('Expected ' + expectation + ' with different headers\n' +
1151 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' +
1152 prettyPrint(headers));
1153
1154 expectations.shift();
1155
1156 if (expectation.response) {
1157 responses.push(wrapResponse(expectation));
1158 return;
1159 }
1160 wasExpected = true;
1161 }
1162
1163 var i = -1, definition;
1164 while ((definition = definitions[++i])) {
1165 if (definition.match(method, url, data, headers || {})) {
1166 if (definition.response) {
1167 // if $browser specified, we do auto flush all requests
1168 ($browser ? $browser.defer : responsesPush)(wrapResponse(definition));
1169 } else if (definition.passThrough) {
1170 $delegate(method, url, data, callback, headers, timeout, withCredentials);
1171 } else throw new Error('No response defined !');
1172 return;
1173 }
1174 }
1175 throw wasExpected ?
1176 new Error('No response defined !') :
1177 new Error('Unexpected request: ' + method + ' ' + url + '\n' +
1178 (expectation ? 'Expected ' + expectation : 'No more request expected'));
1179 }
1180
1181 /**
1182 * @ngdoc method
1183 * @name $httpBackend#when
1184 * @description
1185 * Creates a new backend definition.
1186 *
1187 * @param {string} method HTTP method.
1188 * @param {string|RegExp} url HTTP url.
1189 * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
1190 * data string and returns true if the data is as expected.
1191 * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
1192 * object and returns true if the headers match the current definition.
1193 * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
1194 * request is handled.
1195 *
1196 * - respond –
1197 * `{function([status,] data[, headers, statusText])
1198 * | function(function(method, url, data, headers)}`
1199 * – The respond method takes a set of static data to be returned or a function that can
1200 * return an array containing response status (number), response data (string), response
1201 * headers (Object), and the text for the status (string).
1202 */
1203 $httpBackend.when = function(method, url, data, headers) {
1204 var definition = new MockHttpExpectation(method, url, data, headers),
1205 chain = {
1206 respond: function(status, data, headers, statusText) {
1207 definition.response = createResponse(status, data, headers, statusText);
1208 }
1209 };
1210
1211 if ($browser) {
1212 chain.passThrough = function() {
1213 definition.passThrough = true;
1214 };
1215 }
1216
1217 definitions.push(definition);
1218 return chain;
1219 };
1220
1221 /**
1222 * @ngdoc method
1223 * @name $httpBackend#whenGET
1224 * @description
1225 * Creates a new backend definition for GET requests. For more info see `when()`.
1226 *
1227 * @param {string|RegExp} url HTTP url.
1228 * @param {(Object|function(Object))=} headers HTTP headers.
1229 * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1230 * request is handled.
1231 */
1232
1233 /**
1234 * @ngdoc method
1235 * @name $httpBackend#whenHEAD
1236 * @description
1237 * Creates a new backend definition for HEAD requests. For more info see `when()`.
1238 *
1239 * @param {string|RegExp} url HTTP url.
1240 * @param {(Object|function(Object))=} headers HTTP headers.
1241 * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1242 * request is handled.
1243 */
1244
1245 /**
1246 * @ngdoc method
1247 * @name $httpBackend#whenDELETE
1248 * @description
1249 * Creates a new backend definition for DELETE requests. For more info see `when()`.
1250 *
1251 * @param {string|RegExp} url HTTP url.
1252 * @param {(Object|function(Object))=} headers HTTP headers.
1253 * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1254 * request is handled.
1255 */
1256
1257 /**
1258 * @ngdoc method
1259 * @name $httpBackend#whenPOST
1260 * @description
1261 * Creates a new backend definition for POST requests. For more info see `when()`.
1262 *
1263 * @param {string|RegExp} url HTTP url.
1264 * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
1265 * data string and returns true if the data is as expected.
1266 * @param {(Object|function(Object))=} headers HTTP headers.
1267 * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1268 * request is handled.
1269 */
1270
1271 /**
1272 * @ngdoc method
1273 * @name $httpBackend#whenPUT
1274 * @description
1275 * Creates a new backend definition for PUT requests. For more info see `when()`.
1276 *
1277 * @param {string|RegExp} url HTTP url.
1278 * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
1279 * data string and returns true if the data is as expected.
1280 * @param {(Object|function(Object))=} headers HTTP headers.
1281 * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1282 * request is handled.
1283 */
1284
1285 /**
1286 * @ngdoc method
1287 * @name $httpBackend#whenJSONP
1288 * @description
1289 * Creates a new backend definition for JSONP requests. For more info see `when()`.
1290 *
1291 * @param {string|RegExp} url HTTP url.
1292 * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1293 * request is handled.
1294 */
1295 createShortMethods('when');
1296
1297
1298 /**
1299 * @ngdoc method
1300 * @name $httpBackend#expect
1301 * @description
1302 * Creates a new request expectation.
1303 *
1304 * @param {string} method HTTP method.
1305 * @param {string|RegExp} url HTTP url.
1306 * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
1307 * receives data string and returns true if the data is as expected, or Object if request body
1308 * is in JSON format.
1309 * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
1310 * object and returns true if the headers match the current expectation.
1311 * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1312 * request is handled.
1313 *
1314 * - respond –
1315 * `{function([status,] data[, headers, statusText])
1316 * | function(function(method, url, data, headers)}`
1317 * – The respond method takes a set of static data to be returned or a function that can
1318 * return an array containing response status (number), response data (string), response
1319 * headers (Object), and the text for the status (string).
1320 */
1321 $httpBackend.expect = function(method, url, data, headers) {
1322 var expectation = new MockHttpExpectation(method, url, data, headers);
1323 expectations.push(expectation);
1324 return {
1325 respond: function (status, data, headers, statusText) {
1326 expectation.response = createResponse(status, data, headers, statusText);
1327 }
1328 };
1329 };
1330
1331
1332 /**
1333 * @ngdoc method
1334 * @name $httpBackend#expectGET
1335 * @description
1336 * Creates a new request expectation for GET requests. For more info see `expect()`.
1337 *
1338 * @param {string|RegExp} url HTTP url.
1339 * @param {Object=} headers HTTP headers.
1340 * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1341 * request is handled. See #expect for more info.
1342 */
1343
1344 /**
1345 * @ngdoc method
1346 * @name $httpBackend#expectHEAD
1347 * @description
1348 * Creates a new request expectation for HEAD requests. For more info see `expect()`.
1349 *
1350 * @param {string|RegExp} url HTTP url.
1351 * @param {Object=} headers HTTP headers.
1352 * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1353 * request is handled.
1354 */
1355
1356 /**
1357 * @ngdoc method
1358 * @name $httpBackend#expectDELETE
1359 * @description
1360 * Creates a new request expectation for DELETE requests. For more info see `expect()`.
1361 *
1362 * @param {string|RegExp} url HTTP url.
1363 * @param {Object=} headers HTTP headers.
1364 * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1365 * request is handled.
1366 */
1367
1368 /**
1369 * @ngdoc method
1370 * @name $httpBackend#expectPOST
1371 * @description
1372 * Creates a new request expectation for POST requests. For more info see `expect()`.
1373 *
1374 * @param {string|RegExp} url HTTP url.
1375 * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
1376 * receives data string and returns true if the data is as expected, or Object if request body
1377 * is in JSON format.
1378 * @param {Object=} headers HTTP headers.
1379 * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1380 * request is handled.
1381 */
1382
1383 /**
1384 * @ngdoc method
1385 * @name $httpBackend#expectPUT
1386 * @description
1387 * Creates a new request expectation for PUT requests. For more info see `expect()`.
1388 *
1389 * @param {string|RegExp} url HTTP url.
1390 * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
1391 * receives data string and returns true if the data is as expected, or Object if request body
1392 * is in JSON format.
1393 * @param {Object=} headers HTTP headers.
1394 * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1395 * request is handled.
1396 */
1397
1398 /**
1399 * @ngdoc method
1400 * @name $httpBackend#expectPATCH
1401 * @description
1402 * Creates a new request expectation for PATCH requests. For more info see `expect()`.
1403 *
1404 * @param {string|RegExp} url HTTP url.
1405 * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
1406 * receives data string and returns true if the data is as expected, or Object if request body
1407 * is in JSON format.
1408 * @param {Object=} headers HTTP headers.
1409 * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1410 * request is handled.
1411 */
1412
1413 /**
1414 * @ngdoc method
1415 * @name $httpBackend#expectJSONP
1416 * @description
1417 * Creates a new request expectation for JSONP requests. For more info see `expect()`.
1418 *
1419 * @param {string|RegExp} url HTTP url.
1420 * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1421 * request is handled.
1422 */
1423 createShortMethods('expect');
1424
1425
1426 /**
1427 * @ngdoc method
1428 * @name $httpBackend#flush
1429 * @description
1430 * Flushes all pending requests using the trained responses.
1431 *
1432 * @param {number=} count Number of responses to flush (in the order they arrived). If undefined,
1433 * all pending requests will be flushed. If there are no pending requests when the flush method
1434 * is called an exception is thrown (as this typically a sign of programming error).
1435 */
1436 $httpBackend.flush = function(count) {
1437 $rootScope.$digest();
1438 if (!responses.length) throw new Error('No pending request to flush !');
1439
1440 if (angular.isDefined(count)) {
1441 while (count--) {
1442 if (!responses.length) throw new Error('No more pending request to flush !');
1443 responses.shift()();
1444 }
1445 } else {
1446 while (responses.length) {
1447 responses.shift()();
1448 }
1449 }
1450 $httpBackend.verifyNoOutstandingExpectation();
1451 };
1452
1453
1454 /**
1455 * @ngdoc method
1456 * @name $httpBackend#verifyNoOutstandingExpectation
1457 * @description
1458 * Verifies that all of the requests defined via the `expect` api were made. If any of the
1459 * requests were not made, verifyNoOutstandingExpectation throws an exception.
1460 *
1461 * Typically, you would call this method following each test case that asserts requests using an
1462 * "afterEach" clause.
1463 *
1464 * ```js
1465 * afterEach($httpBackend.verifyNoOutstandingExpectation);
1466 * ```
1467 */
1468 $httpBackend.verifyNoOutstandingExpectation = function() {
1469 $rootScope.$digest();
1470 if (expectations.length) {
1471 throw new Error('Unsatisfied requests: ' + expectations.join(', '));
1472 }
1473 };
1474
1475
1476 /**
1477 * @ngdoc method
1478 * @name $httpBackend#verifyNoOutstandingRequest
1479 * @description
1480 * Verifies that there are no outstanding requests that need to be flushed.
1481 *
1482 * Typically, you would call this method following each test case that asserts requests using an
1483 * "afterEach" clause.
1484 *
1485 * ```js
1486 * afterEach($httpBackend.verifyNoOutstandingRequest);
1487 * ```
1488 */
1489 $httpBackend.verifyNoOutstandingRequest = function() {
1490 if (responses.length) {
1491 throw new Error('Unflushed requests: ' + responses.length);
1492 }
1493 };
1494
1495
1496 /**
1497 * @ngdoc method
1498 * @name $httpBackend#resetExpectations
1499 * @description
1500 * Resets all request expectations, but preserves all backend definitions. Typically, you would
1501 * call resetExpectations during a multiple-phase test when you want to reuse the same instance of
1502 * $httpBackend mock.
1503 */
1504 $httpBackend.resetExpectations = function() {
1505 expectations.length = 0;
1506 responses.length = 0;
1507 };
1508
1509 return $httpBackend;
1510
1511
1512 function createShortMethods(prefix) {
1513 angular.forEach(['GET', 'DELETE', 'JSONP'], function(method) {
1514 $httpBackend[prefix + method] = function(url, headers) {
1515 return $httpBackend[prefix](method, url, undefined, headers);
1516 };
1517 });
1518
1519 angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {
1520 $httpBackend[prefix + method] = function(url, data, headers) {
1521 return $httpBackend[prefix](method, url, data, headers);
1522 };
1523 });
1524 }
1525 }
1526
1527 function MockHttpExpectation(method, url, data, headers) {
1528
1529 this.data = data;
1530 this.headers = headers;
1531
1532 this.match = function(m, u, d, h) {
1533 if (method != m) return false;
1534 if (!this.matchUrl(u)) return false;
1535 if (angular.isDefined(d) && !this.matchData(d)) return false;
1536 if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
1537 return true;
1538 };
1539
1540 this.matchUrl = function(u) {
1541 if (!url) return true;
1542 if (angular.isFunction(url.test)) return url.test(u);
1543 return url == u;
1544 };
1545
1546 this.matchHeaders = function(h) {
1547 if (angular.isUndefined(headers)) return true;
1548 if (angular.isFunction(headers)) return headers(h);
1549 return angular.equals(headers, h);
1550 };
1551
1552 this.matchData = function(d) {
1553 if (angular.isUndefined(data)) return true;
1554 if (data && angular.isFunction(data.test)) return data.test(d);
1555 if (data && angular.isFunction(data)) return data(d);
1556 if (data && !angular.isString(data)) return angular.equals(data, angular.fromJson(d));
1557 return data == d;
1558 };
1559
1560 this.toString = function() {
1561 return method + ' ' + url;
1562 };
1563 }
1564
1565 function createMockXhr() {
1566 return new MockXhr();
1567 }
1568
1569 function MockXhr() {
1570
1571 // hack for testing $http, $httpBackend
1572 MockXhr.$$lastInstance = this;
1573
1574 this.open = function(method, url, async) {
1575 this.$$method = method;
1576 this.$$url = url;
1577 this.$$async = async;
1578 this.$$reqHeaders = {};
1579 this.$$respHeaders = {};
1580 };
1581
1582 this.send = function(data) {
1583 this.$$data = data;
1584 };
1585
1586 this.setRequestHeader = function(key, value) {
1587 this.$$reqHeaders[key] = value;
1588 };
1589
1590 this.getResponseHeader = function(name) {
1591 // the lookup must be case insensitive,
1592 // that's why we try two quick lookups first and full scan last
1593 var header = this.$$respHeaders[name];
1594 if (header) return header;
1595
1596 name = angular.lowercase(name);
1597 header = this.$$respHeaders[name];
1598 if (header) return header;
1599
1600 header = undefined;
1601 angular.forEach(this.$$respHeaders, function(headerVal, headerName) {
1602 if (!header && angular.lowercase(headerName) == name) header = headerVal;
1603 });
1604 return header;
1605 };
1606
1607 this.getAllResponseHeaders = function() {
1608 var lines = [];
1609
1610 angular.forEach(this.$$respHeaders, function(value, key) {
1611 lines.push(key + ': ' + value);
1612 });
1613 return lines.join('\n');
1614 };
1615
1616 this.abort = angular.noop;
1617 }
1618
1619
1620 /**
1621 * @ngdoc service
1622 * @name $timeout
1623 * @description
1624 *
1625 * This service is just a simple decorator for {@link ng.$timeout $timeout} service
1626 * that adds a "flush" and "verifyNoPendingTasks" methods.
1627 */
1628
1629 angular.mock.$TimeoutDecorator = function($delegate, $browser) {
1630
1631 /**
1632 * @ngdoc method
1633 * @name $timeout#flush
1634 * @description
1635 *
1636 * Flushes the queue of pending tasks.
1637 *
1638 * @param {number=} delay maximum timeout amount to flush up until
1639 */
1640 $delegate.flush = function(delay) {
1641 $browser.defer.flush(delay);
1642 };
1643
1644 /**
1645 * @ngdoc method
1646 * @name $timeout#verifyNoPendingTasks
1647 * @description
1648 *
1649 * Verifies that there are no pending tasks that need to be flushed.
1650 */
1651 $delegate.verifyNoPendingTasks = function() {
1652 if ($browser.deferredFns.length) {
1653 throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' +
1654 formatPendingTasksAsString($browser.deferredFns));
1655 }
1656 };
1657
1658 function formatPendingTasksAsString(tasks) {
1659 var result = [];
1660 angular.forEach(tasks, function(task) {
1661 result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}');
1662 });
1663
1664 return result.join(', ');
1665 }
1666
1667 return $delegate;
1668 };
1669
1670 angular.mock.$RAFDecorator = function($delegate) {
1671 var queue = [];
1672 var rafFn = function(fn) {
1673 var index = queue.length;
1674 queue.push(fn);
1675 return function() {
1676 queue.splice(index, 1);
1677 };
1678 };
1679
1680 rafFn.supported = $delegate.supported;
1681
1682 rafFn.flush = function() {
1683 if(queue.length === 0) {
1684 throw new Error('No rAF callbacks present');
1685 }
1686
1687 var length = queue.length;
1688 for(var i=0;i<length;i++) {
1689 queue[i]();
1690 }
1691
1692 queue = [];
1693 };
1694
1695 return rafFn;
1696 };
1697
1698 angular.mock.$AsyncCallbackDecorator = function($delegate) {
1699 var callbacks = [];
1700 var addFn = function(fn) {
1701 callbacks.push(fn);
1702 };
1703 addFn.flush = function() {
1704 angular.forEach(callbacks, function(fn) {
1705 fn();
1706 });
1707 callbacks = [];
1708 };
1709 return addFn;
1710 };
1711
1712 /**
1713 *
1714 */
1715 angular.mock.$RootElementProvider = function() {
1716 this.$get = function() {
1717 return angular.element('<div ng-app></div>');
1718 };
1719 };
1720
1721 /**
1722 * @ngdoc module
1723 * @name ngMock
1724 * @packageName angular-mocks
1725 * @description
1726 *
1727 * # ngMock
1728 *
1729 * The `ngMock` module provides support to inject and mock Angular services into unit tests.
1730 * In addition, ngMock also extends various core ng services such that they can be
1731 * inspected and controlled in a synchronous manner within test code.
1732 *
1733 *
1734 * <div doc-module-components="ngMock"></div>
1735 *
1736 */
1737 angular.module('ngMock', ['ng']).provider({
1738 $browser: angular.mock.$BrowserProvider,
1739 $exceptionHandler: angular.mock.$ExceptionHandlerProvider,
1740 $log: angular.mock.$LogProvider,
1741 $interval: angular.mock.$IntervalProvider,
1742 $httpBackend: angular.mock.$HttpBackendProvider,
1743 $rootElement: angular.mock.$RootElementProvider
1744 }).config(['$provide', function($provide) {
1745 $provide.decorator('$timeout', angular.mock.$TimeoutDecorator);
1746 $provide.decorator('$$rAF', angular.mock.$RAFDecorator);
1747 $provide.decorator('$$asyncCallback', angular.mock.$AsyncCallbackDecorator);
1748 }]);
1749
1750 /**
1751 * @ngdoc module
1752 * @name ngMockE2E
1753 * @module ngMockE2E
1754 * @packageName angular-mocks
1755 * @description
1756 *
1757 * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.
1758 * Currently there is only one mock present in this module -
1759 * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.
1760 */
1761 angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) {
1762 $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
1763 }]);
1764
1765 /**
1766 * @ngdoc service
1767 * @name $httpBackend
1768 * @module ngMockE2E
1769 * @description
1770 * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of
1771 * applications that use the {@link ng.$http $http service}.
1772 *
1773 * *Note*: For fake http backend implementation suitable for unit testing please see
1774 * {@link ngMock.$httpBackend unit-testing $httpBackend mock}.
1775 *
1776 * This implementation can be used to respond with static or dynamic responses via the `when` api
1777 * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the
1778 * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch
1779 * templates from a webserver).
1780 *
1781 * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application
1782 * is being developed with the real backend api replaced with a mock, it is often desirable for
1783 * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch
1784 * templates or static files from the webserver). To configure the backend with this behavior
1785 * use the `passThrough` request handler of `when` instead of `respond`.
1786 *
1787 * Additionally, we don't want to manually have to flush mocked out requests like we do during unit
1788 * testing. For this reason the e2e $httpBackend flushes mocked out requests
1789 * automatically, closely simulating the behavior of the XMLHttpRequest object.
1790 *
1791 * To setup the application to run with this http backend, you have to create a module that depends
1792 * on the `ngMockE2E` and your application modules and defines the fake backend:
1793 *
1794 * ```js
1795 * myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
1796 * myAppDev.run(function($httpBackend) {
1797 * phones = [{name: 'phone1'}, {name: 'phone2'}];
1798 *
1799 * // returns the current list of phones
1800 * $httpBackend.whenGET('/phones').respond(phones);
1801 *
1802 * // adds a new phone to the phones array
1803 * $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
1804 * var phone = angular.fromJson(data);
1805 * phones.push(phone);
1806 * return [200, phone, {}];
1807 * });
1808 * $httpBackend.whenGET(/^\/templates\//).passThrough();
1809 * //...
1810 * });
1811 * ```
1812 *
1813 * Afterwards, bootstrap your app with this new module.
1814 */
1815
1816 /**
1817 * @ngdoc method
1818 * @name $httpBackend#when
1819 * @module ngMockE2E
1820 * @description
1821 * Creates a new backend definition.
1822 *
1823 * @param {string} method HTTP method.
1824 * @param {string|RegExp} url HTTP url.
1825 * @param {(string|RegExp)=} data HTTP request body.
1826 * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
1827 * object and returns true if the headers match the current definition.
1828 * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1829 * control how a matched request is handled.
1830 *
1831 * - respond –
1832 * `{function([status,] data[, headers, statusText])
1833 * | function(function(method, url, data, headers)}`
1834 * – The respond method takes a set of static data to be returned or a function that can return
1835 * an array containing response status (number), response data (string), response headers
1836 * (Object), and the text for the status (string).
1837 * - passThrough – `{function()}` – Any request matching a backend definition with
1838 * `passThrough` handler will be passed through to the real backend (an XHR request will be made
1839 * to the server.)
1840 */
1841
1842 /**
1843 * @ngdoc method
1844 * @name $httpBackend#whenGET
1845 * @module ngMockE2E
1846 * @description
1847 * Creates a new backend definition for GET requests. For more info see `when()`.
1848 *
1849 * @param {string|RegExp} url HTTP url.
1850 * @param {(Object|function(Object))=} headers HTTP headers.
1851 * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1852 * control how a matched request is handled.
1853 */
1854
1855 /**
1856 * @ngdoc method
1857 * @name $httpBackend#whenHEAD
1858 * @module ngMockE2E
1859 * @description
1860 * Creates a new backend definition for HEAD requests. For more info see `when()`.
1861 *
1862 * @param {string|RegExp} url HTTP url.
1863 * @param {(Object|function(Object))=} headers HTTP headers.
1864 * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1865 * control how a matched request is handled.
1866 */
1867
1868 /**
1869 * @ngdoc method
1870 * @name $httpBackend#whenDELETE
1871 * @module ngMockE2E
1872 * @description
1873 * Creates a new backend definition for DELETE requests. For more info see `when()`.
1874 *
1875 * @param {string|RegExp} url HTTP url.
1876 * @param {(Object|function(Object))=} headers HTTP headers.
1877 * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1878 * control how a matched request is handled.
1879 */
1880
1881 /**
1882 * @ngdoc method
1883 * @name $httpBackend#whenPOST
1884 * @module ngMockE2E
1885 * @description
1886 * Creates a new backend definition for POST requests. For more info see `when()`.
1887 *
1888 * @param {string|RegExp} url HTTP url.
1889 * @param {(string|RegExp)=} data HTTP request body.
1890 * @param {(Object|function(Object))=} headers HTTP headers.
1891 * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1892 * control how a matched request is handled.
1893 */
1894
1895 /**
1896 * @ngdoc method
1897 * @name $httpBackend#whenPUT
1898 * @module ngMockE2E
1899 * @description
1900 * Creates a new backend definition for PUT requests. For more info see `when()`.
1901 *
1902 * @param {string|RegExp} url HTTP url.
1903 * @param {(string|RegExp)=} data HTTP request body.
1904 * @param {(Object|function(Object))=} headers HTTP headers.
1905 * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1906 * control how a matched request is handled.
1907 */
1908
1909 /**
1910 * @ngdoc method
1911 * @name $httpBackend#whenPATCH
1912 * @module ngMockE2E
1913 * @description
1914 * Creates a new backend definition for PATCH requests. For more info see `when()`.
1915 *
1916 * @param {string|RegExp} url HTTP url.
1917 * @param {(string|RegExp)=} data HTTP request body.
1918 * @param {(Object|function(Object))=} headers HTTP headers.
1919 * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1920 * control how a matched request is handled.
1921 */
1922
1923 /**
1924 * @ngdoc method
1925 * @name $httpBackend#whenJSONP
1926 * @module ngMockE2E
1927 * @description
1928 * Creates a new backend definition for JSONP requests. For more info see `when()`.
1929 *
1930 * @param {string|RegExp} url HTTP url.
1931 * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1932 * control how a matched request is handled.
1933 */
1934 angular.mock.e2e = {};
1935 angular.mock.e2e.$httpBackendDecorator =
1936 ['$rootScope', '$delegate', '$browser', createHttpBackendMock];
1937
1938
1939 angular.mock.clearDataCache = function() {
1940 var key,
1941 cache = angular.element.cache;
1942
1943 for(key in cache) {
1944 if (Object.prototype.hasOwnProperty.call(cache,key)) {
1945 var handle = cache[key].handle;
1946
1947 handle && angular.element(handle.elem).off();
1948 delete cache[key];
1949 }
1950 }
1951 };
1952
1953
1954 if(window.jasmine || window.mocha) {
1955
1956 var currentSpec = null,
1957 isSpecRunning = function() {
1958 return !!currentSpec;
1959 };
1960
1961
1962 (window.beforeEach || window.setup)(function() {
1963 currentSpec = this;
1964 });
1965
1966 (window.afterEach || window.teardown)(function() {
1967 var injector = currentSpec.$injector;
1968
1969 angular.forEach(currentSpec.$modules, function(module) {
1970 if (module && module.$$hashKey) {
1971 module.$$hashKey = undefined;
1972 }
1973 });
1974
1975 currentSpec.$injector = null;
1976 currentSpec.$modules = null;
1977 currentSpec = null;
1978
1979 if (injector) {
1980 injector.get('$rootElement').off();
1981 injector.get('$browser').pollFns.length = 0;
1982 }
1983
1984 angular.mock.clearDataCache();
1985
1986 // clean up jquery's fragment cache
1987 angular.forEach(angular.element.fragments, function(val, key) {
1988 delete angular.element.fragments[key];
1989 });
1990
1991 MockXhr.$$lastInstance = null;
1992
1993 angular.forEach(angular.callbacks, function(val, key) {
1994 delete angular.callbacks[key];
1995 });
1996 angular.callbacks.counter = 0;
1997 });
1998
1999 /**
2000 * @ngdoc function
2001 * @name angular.mock.module
2002 * @description
2003 *
2004 * *NOTE*: This function is also published on window for easy access.<br>
2005 * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
2006 *
2007 * This function registers a module configuration code. It collects the configuration information
2008 * which will be used when the injector is created by {@link angular.mock.inject inject}.
2009 *
2010 * See {@link angular.mock.inject inject} for usage example
2011 *
2012 * @param {...(string|Function|Object)} fns any number of modules which are represented as string
2013 * aliases or as anonymous module initialization functions. The modules are used to
2014 * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an
2015 * object literal is passed they will be registered as values in the module, the key being
2016 * the module name and the value being what is returned.
2017 */
2018 window.module = angular.mock.module = function() {
2019 var moduleFns = Array.prototype.slice.call(arguments, 0);
2020 return isSpecRunning() ? workFn() : workFn;
2021 /////////////////////
2022 function workFn() {
2023 if (currentSpec.$injector) {
2024 throw new Error('Injector already created, can not register a module!');
2025 } else {
2026 var modules = currentSpec.$modules || (currentSpec.$modules = []);
2027 angular.forEach(moduleFns, function(module) {
2028 if (angular.isObject(module) && !angular.isArray(module)) {
2029 modules.push(function($provide) {
2030 angular.forEach(module, function(value, key) {
2031 $provide.value(key, value);
2032 });
2033 });
2034 } else {
2035 modules.push(module);
2036 }
2037 });
2038 }
2039 }
2040 };
2041
2042 /**
2043 * @ngdoc function
2044 * @name angular.mock.inject
2045 * @description
2046 *
2047 * *NOTE*: This function is also published on window for easy access.<br>
2048 * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
2049 *
2050 * The inject function wraps a function into an injectable function. The inject() creates new
2051 * instance of {@link auto.$injector $injector} per test, which is then used for
2052 * resolving references.
2053 *
2054 *
2055 * ## Resolving References (Underscore Wrapping)
2056 * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this
2057 * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable
2058 * that is declared in the scope of the `describe()` block. Since we would, most likely, want
2059 * the variable to have the same name of the reference we have a problem, since the parameter
2060 * to the `inject()` function would hide the outer variable.
2061 *
2062 * To help with this, the injected parameters can, optionally, be enclosed with underscores.
2063 * These are ignored by the injector when the reference name is resolved.
2064 *
2065 * For example, the parameter `_myService_` would be resolved as the reference `myService`.
2066 * Since it is available in the function body as _myService_, we can then assign it to a variable
2067 * defined in an outer scope.
2068 *
2069 * ```
2070 * // Defined out reference variable outside
2071 * var myService;
2072 *
2073 * // Wrap the parameter in underscores
2074 * beforeEach( inject( function(_myService_){
2075 * myService = _myService_;
2076 * }));
2077 *
2078 * // Use myService in a series of tests.
2079 * it('makes use of myService', function() {
2080 * myService.doStuff();
2081 * });
2082 *
2083 * ```
2084 *
2085 * See also {@link angular.mock.module angular.mock.module}
2086 *
2087 * ## Example
2088 * Example of what a typical jasmine tests looks like with the inject method.
2089 * ```js
2090 *
2091 * angular.module('myApplicationModule', [])
2092 * .value('mode', 'app')
2093 * .value('version', 'v1.0.1');
2094 *
2095 *
2096 * describe('MyApp', function() {
2097 *
2098 * // You need to load modules that you want to test,
2099 * // it loads only the "ng" module by default.
2100 * beforeEach(module('myApplicationModule'));
2101 *
2102 *
2103 * // inject() is used to inject arguments of all given functions
2104 * it('should provide a version', inject(function(mode, version) {
2105 * expect(version).toEqual('v1.0.1');
2106 * expect(mode).toEqual('app');
2107 * }));
2108 *
2109 *
2110 * // The inject and module method can also be used inside of the it or beforeEach
2111 * it('should override a version and test the new version is injected', function() {
2112 * // module() takes functions or strings (module aliases)
2113 * module(function($provide) {
2114 * $provide.value('version', 'overridden'); // override version here
2115 * });
2116 *
2117 * inject(function(version) {
2118 * expect(version).toEqual('overridden');
2119 * });
2120 * });
2121 * });
2122 *
2123 * ```
2124 *
2125 * @param {...Function} fns any number of functions which will be injected using the injector.
2126 */
2127
2128
2129
2130 var ErrorAddingDeclarationLocationStack = function(e, errorForStack) {
2131 this.message = e.message;
2132 this.name = e.name;
2133 if (e.line) this.line = e.line;
2134 if (e.sourceId) this.sourceId = e.sourceId;
2135 if (e.stack && errorForStack)
2136 this.stack = e.stack + '\n' + errorForStack.stack;
2137 if (e.stackArray) this.stackArray = e.stackArray;
2138 };
2139 ErrorAddingDeclarationLocationStack.prototype.toString = Error.prototype.toString;
2140
2141 window.inject = angular.mock.inject = function() {
2142 var blockFns = Array.prototype.slice.call(arguments, 0);
2143 var errorForStack = new Error('Declaration Location');
2144 return isSpecRunning() ? workFn.call(currentSpec) : workFn;
2145 /////////////////////
2146 function workFn() {
2147 var modules = currentSpec.$modules || [];
2148
2149 modules.unshift('ngMock');
2150 modules.unshift('ng');
2151 var injector = currentSpec.$injector;
2152 if (!injector) {
2153 injector = currentSpec.$injector = angular.injector(modules);
2154 }
2155 for(var i = 0, ii = blockFns.length; i < ii; i++) {
2156 try {
2157 /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */
2158 injector.invoke(blockFns[i] || angular.noop, this);
2159 /* jshint +W040 */
2160 } catch (e) {
2161 if (e.stack && errorForStack) {
2162 throw new ErrorAddingDeclarationLocationStack(e, errorForStack);
2163 }
2164 throw e;
2165 } finally {
2166 errorForStack = null;
2167 }
2168 }
2169 }
2170 };
2171 }
2172
2173
2174 })(window, window.angular);
1010 */
1111
1212 angular.module('selectionModel', []);
13
14
15 angular.module('selectionModel').directive('selectionModel', [
16 'selectionStack', 'uuidGen', 'selectionModelOptions',
17 function(selectionStack, uuidGen, selectionModelOptions) {
18 'use strict';
19 return {
20 restrict: 'A',
21 link: function(scope, element, attrs) {
22
23 /**
24 * Defaults from the options provider
25 *
26 * Use `selectionModelOptionsProvider` when configuring your module to
27 * set application wide defaults
28 */
29 var defaultOptions = selectionModelOptions.get()
30 , defaultSelectedAttribute = defaultOptions.selectedAttribute
31 , defaultSelectedClass = defaultOptions.selectedClass
32 , defaultType = defaultOptions.type
33 , defaultMode = defaultOptions.mode
34 , defaultCleanupStrategy = defaultOptions.cleanupStrategy;
35
36 /**
37 * The selection model type
38 *
39 * Controls how selections are presented on the underlying element. Use
40 * 'basic' (the default) to simplye assign a "selected" class to
41 * selected items. If set to 'checkbox' it'll also sync the checked
42 * state of the first checkbox child in each underlying `tr` or `li`
43 * element.
44 *
45 * Note that the 'checkbox' type assumes the first input child element
46 * will be the checkbox.
47 */
48 var smType = attrs.selectionModelType || defaultType;
49
50 /**
51 * The selection mode
52 *
53 * Supports 'single', 'multi[ple]', and 'multi[ple]-additive'. Single
54 * mode will only allow one item to be marked as selected at a time.
55 * Vanilla multi mode allows for multiple selectioned items but requires
56 * modifier keys to select more than one item at a time. Additive-multi
57 * mode allows for multiple items to be selected and will not deselect
58 * other items when a vanilla click is made. Additive multi also allows
59 * for de-selection without a modifier key (think of `'multi-additive'`
60 * as turning every click into a ctrl-click.
61 */
62 var smMode = attrs.selectionModelMode || defaultMode
63 , isMultiMode = /^multi(ple)?(-additive)?$/.test(smMode)
64 , isModeAdditive = /^multi(ple)?-additive/.test(smMode);
65
66 /**
67 * The item attribute to track selected status
68 *
69 * Use `selection-model-selected-attribute` to override the default
70 * attribute.
71 */
72 var selectedAttribute = attrs.selectionModelSelectedAttribute || defaultSelectedAttribute;
73
74 /**
75 * The selected class name
76 *
77 * Will be applied to dom items (e.g. `tr` or `li`) representing
78 * selected items. Use `selection-model-selected-class` to override the
79 * default class name.
80 */
81 var selectedClass = attrs.selectionModelSelectedClass || defaultSelectedClass;
82
83 /**
84 * The cleanup strategy
85 *
86 * How to handle items that are removed from the current view. By
87 * default no action is taken, you may set this to `deselect` to force
88 * items to be deselected when they are filtered away, paged away, or
89 * otherwise no longer visible on the client.
90 */
91 var cleanupStrategy = attrs.selectionModelCleanupStrategy || defaultCleanupStrategy;
92
93 /**
94 * The list of items
95 *
96 * selectionModel must be attached to the same element as an ngRepeat
97 */
98 var repeatLine = attrs.ngRepeat;
99 if(!repeatLine) {
100 throw 'selectionModel must be used along side ngRepeat';
101 }
102
103 /**
104 * The list of selected items
105 *
106 * If used should resolve to an (initially empty) array. Use this in
107 * your view as **read only** if you'd like to do something with just
108 * the selected items. Note that order is not guarenteed and any items
109 * added to this array programmatically are ignored.
110 */
111 var selectedItemsList = scope.$eval(attrs.selectionModelSelectedItems);
112
113 /**
114 * The last-click stack id
115 *
116 * There may be multiple selection models on the page and each will need
117 * independent click stacks.
118 */
119 var clickStackId = (function() {
120 if(!isMultiMode) {
121 return null;
122 }
123 var idAttr = 'data-selection-model-stack-id';
124 // Id may be cached on this element
125 var stackId = element.attr(idAttr);
126 if(stackId) {
127 return stackId;
128 }
129
130 // Otherwise it may be on the partent
131 stackId = element.parent().attr(idAttr);
132 if(stackId) {
133 element.attr(idAttr, stackId);
134 return stackId;
135 }
136
137 // welp guess we're the first, create a new one and cache it on this
138 // element (for us) and the parent element (for others)
139 stackId = uuidGen.create();
140 element.attr(idAttr, stackId);
141 element.parent().attr(idAttr, stackId);
142 return stackId;
143 }());
144
145 var repeatParts = repeatLine.split(' in ')
146 , smItem = scope.$eval(repeatParts[0]);
147
148 var updateDom = function() {
149 if(smItem[selectedAttribute]) {
150 element.addClass(selectedClass);
151 } else {
152 element.removeClass(selectedClass);
153 }
154
155 if('checkbox' === smType) {
156 var cb = element.find('input');
157 cb.prop('checked', smItem[selectedAttribute]);
158 }
159 };
160
161 var getAllVisibleItems = function() {
162 return scope.$eval(repeatParts[1]);
163 };
164
165 // Strips away filters - this lets us e.g. deselect items that are
166 // filtered out
167 var getAllItems = function() {
168 return scope.$eval(repeatParts[1].split('|')[0]);
169 };
170
171 var deselectAllItems = function() {
172 angular.forEach(getAllItems(), function(item) {
173 item[selectedAttribute] = false;
174 });
175 if(angular.isArray(selectedItemsList)) {
176 selectedItemsList.length = 0;
177 }
178 };
179
180 var selectItemsBetween = function(lastItem) {
181 var allItems = getAllVisibleItems()
182 , foundLastItem = false
183 , foundThisItem = false;
184
185 lastItem = lastItem || smItem;
186
187 angular.forEach(getAllVisibleItems(), function(item) {
188 foundThisItem = foundThisItem || item === smItem;
189 foundLastItem = foundLastItem || item === lastItem;
190 var inRange = (foundLastItem + foundThisItem) === 1;
191 if(inRange || item === smItem || item === lastItem) {
192 item[selectedAttribute] = true;
193 }
194 });
195 };
196
197 /**
198 * Item click handler
199 *
200 * Use the `ctrl` key to select/deselect while preserving the rest of
201 * your selection. Note your your selection mode must be set to
202 * `'multiple'` to allow for more than one selected item at a time. In
203 * single select mode you still must use the `ctrl` or `shitft` keys to
204 * deselect an item.
205 *
206 * The `shift` key allows you to select ranges of items at a time. Use
207 * `ctrl` + `shift` to select a range while preserving your existing
208 * selection. In single select mode `shift` behaves like `ctrl`.
209 *
210 * When an item is clicked with no modifier keys pressed it will be the
211 * only selected item.
212 *
213 * On Mac the `meta` key is treated as `ctrl`.
214 *
215 * Note that when using the `'checkbox'` selection model type clicking
216 * on a checkbox will have no effect on any row other than the one the
217 * checkbox is in.
218 */
219 var handleClick = function(event) {
220 var isCtrlKeyDown = event.ctrlKey || event.metaKey || isModeAdditive
221 , isShiftKeyDown = event.shiftKey
222 , target = event.target || event.srcElement
223 , isCheckboxClick = 'checkbox' === smType &&
224 'INPUT' === target.tagName &&
225 'checkbox' === target.type;
226
227 if(isCheckboxClick) {
228 event.stopPropagation();
229 }
230
231 // Select multiple allows for ranges - use shift key
232 if(isShiftKeyDown && isMultiMode && !isCheckboxClick) {
233 // Use ctrl+shift for additive ranges
234 if(!isCtrlKeyDown) {
235 scope.$apply(deselectAllItems);
236 }
237 selectItemsBetween(selectionStack.peek(clickStackId));
238 scope.$apply();
239 return;
240 }
241
242 // Use ctrl/shift without multi select to true toggle a row
243 if(isCtrlKeyDown || isShiftKeyDown || isCheckboxClick) {
244 var isSelected = !smItem[selectedAttribute];
245 if(!isMultiMode) {
246 deselectAllItems();
247 }
248 smItem[selectedAttribute] = isSelected;
249 if(smItem[selectedAttribute]) {
250 selectionStack.push(clickStackId, smItem);
251 }
252 scope.$apply();
253 return;
254 }
255
256 // Otherwise the clicked on row becomes the only selected item
257 deselectAllItems();
258 scope.$apply();
259
260 smItem[selectedAttribute] = true;
261 selectionStack.push(clickStackId, smItem);
262 scope.$apply();
263 };
264
265 element.on('click', handleClick);
266 if('checkbox' === smType) {
267 var elCb = element.find('input');
268 if(elCb[0] && 'checkbox' === elCb[0].type) {
269 element.find('input').on('click', handleClick);
270 }
271 }
272
273 // We might be coming in with a selection
274 updateDom();
275
276 // If we were given a cleanup strategy then setup a `'$destroy'`
277 // listener on the scope.
278 if('deselect' === cleanupStrategy) {
279 scope.$on('$destroy', function() {
280 smItem[selectedAttribute] = false;
281 });
282 }
283
284 scope.$watch(repeatParts[0] + '.' + selectedAttribute, function(newVal, oldVal) {
285 // Be mindful of programmatic changes to selected state
286 if(!isMultiMode && newVal && !oldVal) {
287 deselectAllItems();
288 smItem[selectedAttribute] = true;
289 }
290
291 if(angular.isArray(selectedItemsList)) {
292 var ixSmItem = selectedItemsList.indexOf(smItem);
293 if(smItem[selectedAttribute]) {
294 if(-1 === ixSmItem) {
295 selectedItemsList.push(smItem);
296 }
297 } else {
298 if(-1 < ixSmItem) {
299 selectedItemsList.splice(ixSmItem, 1);
300 }
301 }
302 }
303
304 updateDom();
305 });
306 }
307 };
308 }
309 ]);
310
13
14
15 /**
16 * Selection Model Ignore
17 *
18 * For clickable elements that don't directly interact with `selectionModel`.
19 *
20 * Useful for when you want to manually change the selection, or for things like
21 * "delete" buttons that belong under `ngRepeat` but shouldn't select an item
22 * when clicked.
23 *
24 * @package selectionModel
25 * @copyright 2014 Justin Russell, released under the MIT license
26 */
27
28 angular.module('selectionModel').directive('selectionModelIgnore', [
29 function() {
30 'use strict';
31 return {
32 restrict: 'A',
33 link: function(scope, element, attrs) {
34 element.on('click', function(event) {
35 event.selectionModelIgnore = true;
36
37 /**
38 * If jQuery is on the page `event` will actually be a jQuery Event
39 * and other handlers will only get to see a subset of the event
40 * properties that supported by all browsers. Our custom attribute
41 * will be dropped. We need to instead decorate the original event
42 * object.
43 *
44 * @see https://github.com/jtrussell/angular-selection-model/issues/27
45 */
46 if(event.originalEvent) {
47 event.originalEvent.selectionModelIgnore = true;
48 }
49 });
50 }
51 };
52 }
53 ]);
54
55
56 /**
57 * Selection Model - a selection aware companion for ngRepeat
58 *
59 * @package selectionModel
60 * @copyright 2014 Justin Russell, released under the MIT license
61 */
62
63 angular.module('selectionModel').directive('selectionModel', [
64 'selectionStack', 'uuidGen', 'selectionModelOptions',
65 function(selectionStack, uuidGen, selectionModelOptions) {
66 'use strict';
67 return {
68 restrict: 'A',
69 link: function(scope, element, attrs) {
70
71 /**
72 * Defaults from the options provider
73 *
74 * Use `selectionModelOptionsProvider` when configuring your module to
75 * set application wide defaults
76 */
77 var defaultOptions = selectionModelOptions.get()
78 , defaultSelectedAttribute = defaultOptions.selectedAttribute
79 , defaultSelectedClass = defaultOptions.selectedClass
80 , defaultType = defaultOptions.type
81 , defaultMode = defaultOptions.mode
82 , defaultCleanupStrategy = defaultOptions.cleanupStrategy;
83
84 /**
85 * The selection model type
86 *
87 * Controls how selections are presented on the underlying element. Use
88 * 'basic' (the default) to simplye assign a "selected" class to
89 * selected items. If set to 'checkbox' it'll also sync the checked
90 * state of the first checkbox child in each underlying `tr` or `li`
91 * element.
92 *
93 * Note that the 'checkbox' type assumes the first input child element
94 * will be the checkbox.
95 */
96 var smType = attrs.selectionModelType || defaultType;
97
98 /**
99 * The selection mode
100 *
101 * Supports 'single', 'multi[ple]', and 'multi[ple]-additive'. Single
102 * mode will only allow one item to be marked as selected at a time.
103 * Vanilla multi mode allows for multiple selectioned items but requires
104 * modifier keys to select more than one item at a time. Additive-multi
105 * mode allows for multiple items to be selected and will not deselect
106 * other items when a vanilla click is made. Additive multi also allows
107 * for de-selection without a modifier key (think of `'multi-additive'`
108 * as turning every click into a ctrl-click.
109 */
110 var smMode = attrs.selectionModelMode || defaultMode
111 , isMultiMode = /^multi(ple)?(-additive)?$/.test(smMode)
112 , isModeAdditive = /^multi(ple)?-additive/.test(smMode);
113
114 /**
115 * The item attribute to track selected status
116 *
117 * Use `selection-model-selected-attribute` to override the default
118 * attribute.
119 */
120 var selectedAttribute = attrs.selectionModelSelectedAttribute || defaultSelectedAttribute;
121
122 /**
123 * The selected class name
124 *
125 * Will be applied to dom items (e.g. `tr` or `li`) representing
126 * selected items. Use `selection-model-selected-class` to override the
127 * default class name.
128 */
129 var selectedClass = attrs.selectionModelSelectedClass || defaultSelectedClass;
130
131 /**
132 * The cleanup strategy
133 *
134 * How to handle items that are removed from the current view. By
135 * default no action is taken, you may set this to `deselect` to force
136 * items to be deselected when they are filtered away, paged away, or
137 * otherwise no longer visible on the client.
138 */
139 var cleanupStrategy = attrs.selectionModelCleanupStrategy || defaultCleanupStrategy;
140
141 /**
142 * The change callback
143 *
144 * To be executed whenever the item's selected state changes.
145 */
146 var smOnChange = attrs.selectionModelOnChange;
147
148 /**
149 * The list of items
150 *
151 * selectionModel must be attached to the same element as an ngRepeat
152 */
153 var repeatLine = attrs.ngRepeat;
154 if(!repeatLine) {
155 throw 'selectionModel must be used along side ngRepeat';
156 }
157
158 /**
159 * The list of selected items
160 *
161 * If used should resolve to an (initially empty) array. Use this in
162 * your view as **read only** if you'd like to do something with just
163 * the selected items. Note that order is not guarenteed and any items
164 * added to this array programmatically are ignored.
165 */
166 var selectedItemsList = scope.$eval(attrs.selectionModelSelectedItems);
167
168 /**
169 * The last-click stack id
170 *
171 * There may be multiple selection models on the page and each will need
172 * independent click stacks.
173 */
174 var clickStackId = (function() {
175 if(!isMultiMode) {
176 return null;
177 }
178 var idAttr = 'data-selection-model-stack-id';
179 // Id may be cached on this element
180 var stackId = element.attr(idAttr);
181 if(stackId) {
182 return stackId;
183 }
184
185 // Otherwise it may be on the partent
186 stackId = element.parent().attr(idAttr);
187 if(stackId) {
188 element.attr(idAttr, stackId);
189 return stackId;
190 }
191
192 // welp guess we're the first, create a new one and cache it on this
193 // element (for us) and the parent element (for others)
194 stackId = uuidGen.create();
195 element.attr(idAttr, stackId);
196 element.parent().attr(idAttr, stackId);
197 return stackId;
198 }());
199
200 var repeatParts = repeatLine.split(' in ')
201 , smItem = scope.$eval(repeatParts[0]);
202
203 var updateDom = function() {
204 if(smItem[selectedAttribute]) {
205 element.addClass(selectedClass);
206 } else {
207 element.removeClass(selectedClass);
208 }
209
210 if('checkbox' === smType) {
211 var cb = element.find('input');
212 cb.prop('checked', smItem[selectedAttribute]);
213 }
214 };
215
216 var getAllVisibleItems = function() {
217 return scope.$eval(repeatParts[1]);
218 };
219
220 // Strips away filters - this lets us e.g. deselect items that are
221 // filtered out
222 var getAllItems = function() {
223 return scope.$eval(repeatParts[1].split('|')[0]);
224 };
225
226 // Get us back to a "clean" state. Usually we'll want to skip
227 // deselection for items that are about to be selected again to avoid
228 // firing the `selection-mode-on-change` handler extra times.
229 //
230 // `except` param may be `undefined` (deselect all the things), a single
231 // item (don't deselect *that* item), or an array of two items (don't
232 // deselect anything between those items inclusively).
233 var deselectAllItemsExcept = function(except) {
234 var useSelectedArray = angular.isArray(selectedItemsList)
235 , isRange = angular.isArray(except) && 2 === except.length
236 , allItems = getAllItems()
237 , numItemsFound = 0
238 , doDeselect = false
239 , ixItem;
240 if(useSelectedArray) {
241 selectedItemsList.length = 0;
242 }
243 angular.forEach(allItems, function(item) {
244 if(isRange) {
245 ixItem = except.indexOf(item);
246 if(ixItem > -1) {
247 numItemsFound++;
248 doDeselect = false;
249 except.splice(ixItem, 1);
250 } else {
251 doDeselect = 1 !== numItemsFound;
252 }
253 } else {
254 doDeselect = item !== except;
255 }
256 if(doDeselect) {
257 item[selectedAttribute] = false;
258 } else {
259 if(useSelectedArray && item[selectedAttribute]) {
260 selectedItemsList.push(item);
261 }
262 }
263 });
264 };
265
266 var selectItemsBetween = function(lastItem) {
267 var allItems = getAllVisibleItems()
268 , foundLastItem = false
269 , foundThisItem = false;
270
271 lastItem = lastItem || smItem;
272
273 angular.forEach(getAllVisibleItems(), function(item) {
274 foundThisItem = foundThisItem || item === smItem;
275 foundLastItem = foundLastItem || item === lastItem;
276 var inRange = (foundLastItem + foundThisItem) === 1;
277 if(inRange || item === smItem || item === lastItem) {
278 item[selectedAttribute] = true;
279 }
280 });
281 };
282
283 /**
284 * Item click handler
285 *
286 * Use the `ctrl` key to select/deselect while preserving the rest of
287 * your selection. Note your your selection mode must be set to
288 * `'multiple'` to allow for more than one selected item at a time. In
289 * single select mode you still must use the `ctrl` or `shitft` keys to
290 * deselect an item.
291 *
292 * The `shift` key allows you to select ranges of items at a time. Use
293 * `ctrl` + `shift` to select a range while preserving your existing
294 * selection. In single select mode `shift` behaves like `ctrl`.
295 *
296 * When an item is clicked with no modifier keys pressed it will be the
297 * only selected item.
298 *
299 * On Mac the `meta` key is treated as `ctrl`.
300 *
301 * Note that when using the `'checkbox'` selection model type clicking
302 * on a checkbox will have no effect on any row other than the one the
303 * checkbox is in.
304 */
305 var handleClick = function(event) {
306
307 /**
308 * Set by the `selectionModelIgnore` directive
309 *
310 * Use `selectionModelIgnore` to cause `selectionModel` to selectively
311 * ignore clicks on elements. This is useful if you want to manually
312 * change a selection when certain things are clicked.
313 */
314 if(event.selectionModelIgnore || (event.originalEvent && event.originalEvent.selectionModelIgnore)) {
315 return;
316 }
317
318 // Never handle a single click twice.
319 if(event.selectionModelClickHandled || (event.originalEvent && event.originalEvent.selectionModelClickHandled)) {
320 return;
321 }
322 event.selectionModelClickHandled = true;
323 if(event.originalEvent) {
324 event.originalEvent.selectionModelClickHandled = true;
325 }
326
327 var isCtrlKeyDown = event.ctrlKey || event.metaKey || isModeAdditive
328 , isShiftKeyDown = event.shiftKey
329 , target = event.target || event.srcElement
330 , isCheckboxClick = 'checkbox' === smType &&
331 'INPUT' === target.tagName &&
332 'checkbox' === target.type;
333
334 /**
335 * Guard against label + checkbox clicks
336 *
337 * Clicking a label will cause a click event to also be fired on the
338 * associated input element. If that input is nearby (i.e. under the
339 * selection model element) we'll suppress the click on the label to
340 * avoid duplicate click events.
341 */
342 if('LABEL' === target.tagName) {
343 var labelFor = angular.element(target).attr('for');
344 if(labelFor) {
345 var childInputs = element[0].getElementsByTagName('INPUT'), ix;
346 for(ix = childInputs.length; ix--;) {
347 if(childInputs[ix].id === labelFor) {
348 return;
349 }
350 }
351 } else if(target.getElementsByTagName('INPUT').length) {
352 // Label has a nested input element, we'll handle the click on
353 // that element
354 return;
355 }
356 }
357
358 // Select multiple allows for ranges - use shift key
359 if(isShiftKeyDown && isMultiMode && !isCheckboxClick) {
360 // Use ctrl+shift for additive ranges
361 if(!isCtrlKeyDown) {
362 scope.$apply(function() {
363 deselectAllItemsExcept([smItem, selectionStack.peek(clickStackId)]);
364 });
365 }
366 selectItemsBetween(selectionStack.peek(clickStackId));
367 scope.$apply();
368 return;
369 }
370
371 // Use ctrl/shift without multi select to true toggle a row
372 if(isCtrlKeyDown || isShiftKeyDown || isCheckboxClick) {
373 var isSelected = !smItem[selectedAttribute];
374 if(!isMultiMode) {
375 deselectAllItemsExcept(smItem);
376 }
377 smItem[selectedAttribute] = isSelected;
378 if(smItem[selectedAttribute]) {
379 selectionStack.push(clickStackId, smItem);
380 }
381 scope.$apply();
382 return;
383 }
384
385 // Otherwise the clicked on row becomes the only selected item
386 deselectAllItemsExcept(smItem);
387 scope.$apply();
388
389 smItem[selectedAttribute] = true;
390 selectionStack.push(clickStackId, smItem);
391 scope.$apply();
392 };
393
394 /**
395 * Routine to keep the list of selected items up to date
396 *
397 * Adds/removes this item from `selectionModelSelectedItems`.
398 */
399 var updateSelectedItemsList = function() {
400 if(angular.isArray(selectedItemsList)) {
401 var ixSmItem = selectedItemsList.indexOf(smItem);
402 if(smItem[selectedAttribute]) {
403 if(-1 === ixSmItem) {
404 selectedItemsList.push(smItem);
405 }
406 } else {
407 if(-1 < ixSmItem) {
408 selectedItemsList.splice(ixSmItem, 1);
409 }
410 }
411 }
412 };
413
414 element.on('click', handleClick);
415 if('checkbox' === smType) {
416 var elCb = element.find('input');
417 if(elCb[0] && 'checkbox' === elCb[0].type) {
418 element.find('input').on('click', handleClick);
419 }
420 }
421
422 // We might be coming in with a selection
423 updateDom();
424 updateSelectedItemsList();
425
426 // If we were given a cleanup strategy then setup a `'$destroy'`
427 // listener on the scope.
428 if('deselect' === cleanupStrategy) {
429 scope.$on('$destroy', function() {
430 var oldSelectedStatus = smItem[selectedAttribute];
431 smItem[selectedAttribute] = false;
432 updateSelectedItemsList();
433 if(smOnChange && oldSelectedStatus) {
434 scope.$eval(smOnChange);
435 }
436 });
437 }
438
439 scope.$watch(repeatParts[0] + '.' + selectedAttribute, function(newVal, oldVal) {
440 // Be mindful of programmatic changes to selected state
441 if(newVal !== oldVal) {
442 if(!isMultiMode && newVal && !oldVal) {
443 deselectAllItemsExcept(smItem);
444 smItem[selectedAttribute] = true;
445 }
446 updateDom();
447 updateSelectedItemsList();
448
449 if(smOnChange) {
450 scope.$eval(smOnChange);
451 }
452 }
453 });
454 }
455 };
456 }
457 ]);
458
311459
312460 /**
313461 * Default options for the selection model directive
343491
344492
345493 }]);
346
494
347495
348496 angular.module('selectionModel').service('selectionStack', function() {
349497 'use strict';
381529
382530 return exports;
383531 });
384
385 /*jshint bitwise:false */
386
387 angular.module('selectionModel').service('uuidGen', function() {
388 'use strict';
389 var exports = {};
390 var uid = ['0', '0', '0'];
391
392 exports.create = function() {
393 var index = uid.length;
394 var digit;
395 while (index) {
396 index--;
397 digit = uid[index].charCodeAt(0);
398 if (digit === 57 /*'9'*/ ) {
399 uid[index] = 'A';
400 return uid.join('');
401 }
402 if (digit === 90 /*'Z'*/ ) {
403 uid[index] = '0';
404 } else {
405 uid[index] = String.fromCharCode(digit + 1);
406 return uid.join('');
407 }
408 }
409 uid.unshift('0');
410 return uid.join('');
411 };
412
413 return exports;
414 });
532
533 /*jshint bitwise:false */
534
535 angular.module('selectionModel').service('uuidGen', function() {
536 'use strict';
537 var exports = {};
538 var uid = ['0', '0', '0'];
539
540 exports.create = function() {
541 var index = uid.length;
542 var digit;
543 while (index) {
544 index--;
545 digit = uid[index].charCodeAt(0);
546 if (digit === 57 /*'9'*/ ) {
547 uid[index] = 'A';
548 return uid.join('');
549 }
550 if (digit === 90 /*'Z'*/ ) {
551 uid[index] = '0';
552 } else {
553 uid[index] = String.fromCharCode(digit + 1);
554 return uid.join('');
555 }
556 }
557 uid.unshift('0');
558 return uid.join('');
559 };
560
561 return exports;
562 });
0 /*global define:false */
1 /**
2 * Copyright 2015 Craig Campbell
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * Mousetrap is a simple keyboard shortcut library for Javascript with
17 * no external dependencies
18 *
19 * @version 1.5.2
20 * @url craig.is/killing/mice
21 */
22 (function(window, document, undefined) {
23
24 /**
25 * mapping of special keycodes to their corresponding keys
26 *
27 * everything in this dictionary cannot use keypress events
28 * so it has to be here to map to the correct keycodes for
29 * keyup/keydown events
30 *
31 * @type {Object}
32 */
33 var _MAP = {
34 8: 'backspace',
35 9: 'tab',
36 13: 'enter',
37 16: 'shift',
38 17: 'ctrl',
39 18: 'alt',
40 20: 'capslock',
41 27: 'esc',
42 32: 'space',
43 33: 'pageup',
44 34: 'pagedown',
45 35: 'end',
46 36: 'home',
47 37: 'left',
48 38: 'up',
49 39: 'right',
50 40: 'down',
51 45: 'ins',
52 46: 'del',
53 91: 'meta',
54 93: 'meta',
55 224: 'meta'
56 };
57
58 /**
59 * mapping for special characters so they can support
60 *
61 * this dictionary is only used incase you want to bind a
62 * keyup or keydown event to one of these keys
63 *
64 * @type {Object}
65 */
66 var _KEYCODE_MAP = {
67 106: '*',
68 107: '+',
69 109: '-',
70 110: '.',
71 111 : '/',
72 186: ';',
73 187: '=',
74 188: ',',
75 189: '-',
76 190: '.',
77 191: '/',
78 192: '`',
79 219: '[',
80 220: '\\',
81 221: ']',
82 222: '\''
83 };
84
85 /**
86 * this is a mapping of keys that require shift on a US keypad
87 * back to the non shift equivelents
88 *
89 * this is so you can use keyup events with these keys
90 *
91 * note that this will only work reliably on US keyboards
92 *
93 * @type {Object}
94 */
95 var _SHIFT_MAP = {
96 '~': '`',
97 '!': '1',
98 '@': '2',
99 '#': '3',
100 '$': '4',
101 '%': '5',
102 '^': '6',
103 '&': '7',
104 '*': '8',
105 '(': '9',
106 ')': '0',
107 '_': '-',
108 '+': '=',
109 ':': ';',
110 '\"': '\'',
111 '<': ',',
112 '>': '.',
113 '?': '/',
114 '|': '\\'
115 };
116
117 /**
118 * this is a list of special strings you can use to map
119 * to modifier keys when you specify your keyboard shortcuts
120 *
121 * @type {Object}
122 */
123 var _SPECIAL_ALIASES = {
124 'option': 'alt',
125 'command': 'meta',
126 'return': 'enter',
127 'escape': 'esc',
128 'plus': '+',
129 'mod': /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? 'meta' : 'ctrl'
130 };
131
132 /**
133 * variable to store the flipped version of _MAP from above
134 * needed to check if we should use keypress or not when no action
135 * is specified
136 *
137 * @type {Object|undefined}
138 */
139 var _REVERSE_MAP;
140
141 /**
142 * loop through the f keys, f1 to f19 and add them to the map
143 * programatically
144 */
145 for (var i = 1; i < 20; ++i) {
146 _MAP[111 + i] = 'f' + i;
147 }
148
149 /**
150 * loop through to map numbers on the numeric keypad
151 */
152 for (i = 0; i <= 9; ++i) {
153 _MAP[i + 96] = i;
154 }
155
156 /**
157 * cross browser add event method
158 *
159 * @param {Element|HTMLDocument} object
160 * @param {string} type
161 * @param {Function} callback
162 * @returns void
163 */
164 function _addEvent(object, type, callback) {
165 if (object.addEventListener) {
166 object.addEventListener(type, callback, false);
167 return;
168 }
169
170 object.attachEvent('on' + type, callback);
171 }
172
173 /**
174 * takes the event and returns the key character
175 *
176 * @param {Event} e
177 * @return {string}
178 */
179 function _characterFromEvent(e) {
180
181 // for keypress events we should return the character as is
182 if (e.type == 'keypress') {
183 var character = String.fromCharCode(e.which);
184
185 // if the shift key is not pressed then it is safe to assume
186 // that we want the character to be lowercase. this means if
187 // you accidentally have caps lock on then your key bindings
188 // will continue to work
189 //
190 // the only side effect that might not be desired is if you
191 // bind something like 'A' cause you want to trigger an
192 // event when capital A is pressed caps lock will no longer
193 // trigger the event. shift+a will though.
194 if (!e.shiftKey) {
195 character = character.toLowerCase();
196 }
197
198 return character;
199 }
200
201 // for non keypress events the special maps are needed
202 if (_MAP[e.which]) {
203 return _MAP[e.which];
204 }
205
206 if (_KEYCODE_MAP[e.which]) {
207 return _KEYCODE_MAP[e.which];
208 }
209
210 // if it is not in the special map
211
212 // with keydown and keyup events the character seems to always
213 // come in as an uppercase character whether you are pressing shift
214 // or not. we should make sure it is always lowercase for comparisons
215 return String.fromCharCode(e.which).toLowerCase();
216 }
217
218 /**
219 * checks if two arrays are equal
220 *
221 * @param {Array} modifiers1
222 * @param {Array} modifiers2
223 * @returns {boolean}
224 */
225 function _modifiersMatch(modifiers1, modifiers2) {
226 return modifiers1.sort().join(',') === modifiers2.sort().join(',');
227 }
228
229 /**
230 * takes a key event and figures out what the modifiers are
231 *
232 * @param {Event} e
233 * @returns {Array}
234 */
235 function _eventModifiers(e) {
236 var modifiers = [];
237
238 if (e.shiftKey) {
239 modifiers.push('shift');
240 }
241
242 if (e.altKey) {
243 modifiers.push('alt');
244 }
245
246 if (e.ctrlKey) {
247 modifiers.push('ctrl');
248 }
249
250 if (e.metaKey) {
251 modifiers.push('meta');
252 }
253
254 return modifiers;
255 }
256
257 /**
258 * prevents default for this event
259 *
260 * @param {Event} e
261 * @returns void
262 */
263 function _preventDefault(e) {
264 if (e.preventDefault) {
265 e.preventDefault();
266 return;
267 }
268
269 e.returnValue = false;
270 }
271
272 /**
273 * stops propogation for this event
274 *
275 * @param {Event} e
276 * @returns void
277 */
278 function _stopPropagation(e) {
279 if (e.stopPropagation) {
280 e.stopPropagation();
281 return;
282 }
283
284 e.cancelBubble = true;
285 }
286
287 /**
288 * determines if the keycode specified is a modifier key or not
289 *
290 * @param {string} key
291 * @returns {boolean}
292 */
293 function _isModifier(key) {
294 return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
295 }
296
297 /**
298 * reverses the map lookup so that we can look for specific keys
299 * to see what can and can't use keypress
300 *
301 * @return {Object}
302 */
303 function _getReverseMap() {
304 if (!_REVERSE_MAP) {
305 _REVERSE_MAP = {};
306 for (var key in _MAP) {
307
308 // pull out the numeric keypad from here cause keypress should
309 // be able to detect the keys from the character
310 if (key > 95 && key < 112) {
311 continue;
312 }
313
314 if (_MAP.hasOwnProperty(key)) {
315 _REVERSE_MAP[_MAP[key]] = key;
316 }
317 }
318 }
319 return _REVERSE_MAP;
320 }
321
322 /**
323 * picks the best action based on the key combination
324 *
325 * @param {string} key - character for key
326 * @param {Array} modifiers
327 * @param {string=} action passed in
328 */
329 function _pickBestAction(key, modifiers, action) {
330
331 // if no action was picked in we should try to pick the one
332 // that we think would work best for this key
333 if (!action) {
334 action = _getReverseMap()[key] ? 'keydown' : 'keypress';
335 }
336
337 // modifier keys don't work as expected with keypress,
338 // switch to keydown
339 if (action == 'keypress' && modifiers.length) {
340 action = 'keydown';
341 }
342
343 return action;
344 }
345
346 /**
347 * Converts from a string key combination to an array
348 *
349 * @param {string} combination like "command+shift+l"
350 * @return {Array}
351 */
352 function _keysFromString(combination) {
353 if (combination === '+') {
354 return ['+'];
355 }
356
357 combination = combination.replace(/\+{2}/g, '+plus');
358 return combination.split('+');
359 }
360
361 /**
362 * Gets info for a specific key combination
363 *
364 * @param {string} combination key combination ("command+s" or "a" or "*")
365 * @param {string=} action
366 * @returns {Object}
367 */
368 function _getKeyInfo(combination, action) {
369 var keys;
370 var key;
371 var i;
372 var modifiers = [];
373
374 // take the keys from this pattern and figure out what the actual
375 // pattern is all about
376 keys = _keysFromString(combination);
377
378 for (i = 0; i < keys.length; ++i) {
379 key = keys[i];
380
381 // normalize key names
382 if (_SPECIAL_ALIASES[key]) {
383 key = _SPECIAL_ALIASES[key];
384 }
385
386 // if this is not a keypress event then we should
387 // be smart about using shift keys
388 // this will only work for US keyboards however
389 if (action && action != 'keypress' && _SHIFT_MAP[key]) {
390 key = _SHIFT_MAP[key];
391 modifiers.push('shift');
392 }
393
394 // if this key is a modifier then add it to the list of modifiers
395 if (_isModifier(key)) {
396 modifiers.push(key);
397 }
398 }
399
400 // depending on what the key combination is
401 // we will try to pick the best event for it
402 action = _pickBestAction(key, modifiers, action);
403
404 return {
405 key: key,
406 modifiers: modifiers,
407 action: action
408 };
409 }
410
411 function _belongsTo(element, ancestor) {
412 if (element === document) {
413 return false;
414 }
415
416 if (element === ancestor) {
417 return true;
418 }
419
420 return _belongsTo(element.parentNode, ancestor);
421 }
422
423 function Mousetrap(targetElement) {
424 var self = this;
425
426 targetElement = targetElement || document;
427
428 if (!(self instanceof Mousetrap)) {
429 return new Mousetrap(targetElement);
430 }
431
432 /**
433 * element to attach key events to
434 *
435 * @type {Element}
436 */
437 self.target = targetElement;
438
439 /**
440 * a list of all the callbacks setup via Mousetrap.bind()
441 *
442 * @type {Object}
443 */
444 self._callbacks = {};
445
446 /**
447 * direct map of string combinations to callbacks used for trigger()
448 *
449 * @type {Object}
450 */
451 self._directMap = {};
452
453 /**
454 * keeps track of what level each sequence is at since multiple
455 * sequences can start out with the same sequence
456 *
457 * @type {Object}
458 */
459 var _sequenceLevels = {};
460
461 /**
462 * variable to store the setTimeout call
463 *
464 * @type {null|number}
465 */
466 var _resetTimer;
467
468 /**
469 * temporary state where we will ignore the next keyup
470 *
471 * @type {boolean|string}
472 */
473 var _ignoreNextKeyup = false;
474
475 /**
476 * temporary state where we will ignore the next keypress
477 *
478 * @type {boolean}
479 */
480 var _ignoreNextKeypress = false;
481
482 /**
483 * are we currently inside of a sequence?
484 * type of action ("keyup" or "keydown" or "keypress") or false
485 *
486 * @type {boolean|string}
487 */
488 var _nextExpectedAction = false;
489
490 /**
491 * resets all sequence counters except for the ones passed in
492 *
493 * @param {Object} doNotReset
494 * @returns void
495 */
496 function _resetSequences(doNotReset) {
497 doNotReset = doNotReset || {};
498
499 var activeSequences = false,
500 key;
501
502 for (key in _sequenceLevels) {
503 if (doNotReset[key]) {
504 activeSequences = true;
505 continue;
506 }
507 _sequenceLevels[key] = 0;
508 }
509
510 if (!activeSequences) {
511 _nextExpectedAction = false;
512 }
513 }
514
515 /**
516 * finds all callbacks that match based on the keycode, modifiers,
517 * and action
518 *
519 * @param {string} character
520 * @param {Array} modifiers
521 * @param {Event|Object} e
522 * @param {string=} sequenceName - name of the sequence we are looking for
523 * @param {string=} combination
524 * @param {number=} level
525 * @returns {Array}
526 */
527 function _getMatches(character, modifiers, e, sequenceName, combination, level) {
528 var i;
529 var callback;
530 var matches = [];
531 var action = e.type;
532
533 // if there are no events related to this keycode
534 if (!self._callbacks[character]) {
535 return [];
536 }
537
538 // if a modifier key is coming up on its own we should allow it
539 if (action == 'keyup' && _isModifier(character)) {
540 modifiers = [character];
541 }
542
543 // loop through all callbacks for the key that was pressed
544 // and see if any of them match
545 for (i = 0; i < self._callbacks[character].length; ++i) {
546 callback = self._callbacks[character][i];
547
548 // if a sequence name is not specified, but this is a sequence at
549 // the wrong level then move onto the next match
550 if (!sequenceName && callback.seq && _sequenceLevels[callback.seq] != callback.level) {
551 continue;
552 }
553
554 // if the action we are looking for doesn't match the action we got
555 // then we should keep going
556 if (action != callback.action) {
557 continue;
558 }
559
560 // if this is a keypress event and the meta key and control key
561 // are not pressed that means that we need to only look at the
562 // character, otherwise check the modifiers as well
563 //
564 // chrome will not fire a keypress if meta or control is down
565 // safari will fire a keypress if meta or meta+shift is down
566 // firefox will fire a keypress if meta or control is down
567 if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) {
568
569 // when you bind a combination or sequence a second time it
570 // should overwrite the first one. if a sequenceName or
571 // combination is specified in this call it does just that
572 //
573 // @todo make deleting its own method?
574 var deleteCombo = !sequenceName && callback.combo == combination;
575 var deleteSequence = sequenceName && callback.seq == sequenceName && callback.level == level;
576 if (deleteCombo || deleteSequence) {
577 self._callbacks[character].splice(i, 1);
578 }
579
580 matches.push(callback);
581 }
582 }
583
584 return matches;
585 }
586
587 /**
588 * actually calls the callback function
589 *
590 * if your callback function returns false this will use the jquery
591 * convention - prevent default and stop propogation on the event
592 *
593 * @param {Function} callback
594 * @param {Event} e
595 * @returns void
596 */
597 function _fireCallback(callback, e, combo, sequence) {
598
599 // if this event should not happen stop here
600 if (self.stopCallback(e, e.target || e.srcElement, combo, sequence)) {
601 return;
602 }
603
604 if (callback(e, combo) === false) {
605 _preventDefault(e);
606 _stopPropagation(e);
607 }
608 }
609
610 /**
611 * handles a character key event
612 *
613 * @param {string} character
614 * @param {Array} modifiers
615 * @param {Event} e
616 * @returns void
617 */
618 self._handleKey = function(character, modifiers, e) {
619 var callbacks = _getMatches(character, modifiers, e);
620 var i;
621 var doNotReset = {};
622 var maxLevel = 0;
623 var processedSequenceCallback = false;
624
625 // Calculate the maxLevel for sequences so we can only execute the longest callback sequence
626 for (i = 0; i < callbacks.length; ++i) {
627 if (callbacks[i].seq) {
628 maxLevel = Math.max(maxLevel, callbacks[i].level);
629 }
630 }
631
632 // loop through matching callbacks for this key event
633 for (i = 0; i < callbacks.length; ++i) {
634
635 // fire for all sequence callbacks
636 // this is because if for example you have multiple sequences
637 // bound such as "g i" and "g t" they both need to fire the
638 // callback for matching g cause otherwise you can only ever
639 // match the first one
640 if (callbacks[i].seq) {
641
642 // only fire callbacks for the maxLevel to prevent
643 // subsequences from also firing
644 //
645 // for example 'a option b' should not cause 'option b' to fire
646 // even though 'option b' is part of the other sequence
647 //
648 // any sequences that do not match here will be discarded
649 // below by the _resetSequences call
650 if (callbacks[i].level != maxLevel) {
651 continue;
652 }
653
654 processedSequenceCallback = true;
655
656 // keep a list of which sequences were matches for later
657 doNotReset[callbacks[i].seq] = 1;
658 _fireCallback(callbacks[i].callback, e, callbacks[i].combo, callbacks[i].seq);
659 continue;
660 }
661
662 // if there were no sequence matches but we are still here
663 // that means this is a regular match so we should fire that
664 if (!processedSequenceCallback) {
665 _fireCallback(callbacks[i].callback, e, callbacks[i].combo);
666 }
667 }
668
669 // if the key you pressed matches the type of sequence without
670 // being a modifier (ie "keyup" or "keypress") then we should
671 // reset all sequences that were not matched by this event
672 //
673 // this is so, for example, if you have the sequence "h a t" and you
674 // type "h e a r t" it does not match. in this case the "e" will
675 // cause the sequence to reset
676 //
677 // modifier keys are ignored because you can have a sequence
678 // that contains modifiers such as "enter ctrl+space" and in most
679 // cases the modifier key will be pressed before the next key
680 //
681 // also if you have a sequence such as "ctrl+b a" then pressing the
682 // "b" key will trigger a "keypress" and a "keydown"
683 //
684 // the "keydown" is expected when there is a modifier, but the
685 // "keypress" ends up matching the _nextExpectedAction since it occurs
686 // after and that causes the sequence to reset
687 //
688 // we ignore keypresses in a sequence that directly follow a keydown
689 // for the same character
690 var ignoreThisKeypress = e.type == 'keypress' && _ignoreNextKeypress;
691 if (e.type == _nextExpectedAction && !_isModifier(character) && !ignoreThisKeypress) {
692 _resetSequences(doNotReset);
693 }
694
695 _ignoreNextKeypress = processedSequenceCallback && e.type == 'keydown';
696 };
697
698 /**
699 * handles a keydown event
700 *
701 * @param {Event} e
702 * @returns void
703 */
704 function _handleKeyEvent(e) {
705
706 // normalize e.which for key events
707 // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
708 if (typeof e.which !== 'number') {
709 e.which = e.keyCode;
710 }
711
712 var character = _characterFromEvent(e);
713
714 // no character found then stop
715 if (!character) {
716 return;
717 }
718
719 // need to use === for the character check because the character can be 0
720 if (e.type == 'keyup' && _ignoreNextKeyup === character) {
721 _ignoreNextKeyup = false;
722 return;
723 }
724
725 self.handleKey(character, _eventModifiers(e), e);
726 }
727
728 /**
729 * called to set a 1 second timeout on the specified sequence
730 *
731 * this is so after each key press in the sequence you have 1 second
732 * to press the next key before you have to start over
733 *
734 * @returns void
735 */
736 function _resetSequenceTimer() {
737 clearTimeout(_resetTimer);
738 _resetTimer = setTimeout(_resetSequences, 1000);
739 }
740
741 /**
742 * binds a key sequence to an event
743 *
744 * @param {string} combo - combo specified in bind call
745 * @param {Array} keys
746 * @param {Function} callback
747 * @param {string=} action
748 * @returns void
749 */
750 function _bindSequence(combo, keys, callback, action) {
751
752 // start off by adding a sequence level record for this combination
753 // and setting the level to 0
754 _sequenceLevels[combo] = 0;
755
756 /**
757 * callback to increase the sequence level for this sequence and reset
758 * all other sequences that were active
759 *
760 * @param {string} nextAction
761 * @returns {Function}
762 */
763 function _increaseSequence(nextAction) {
764 return function() {
765 _nextExpectedAction = nextAction;
766 ++_sequenceLevels[combo];
767 _resetSequenceTimer();
768 };
769 }
770
771 /**
772 * wraps the specified callback inside of another function in order
773 * to reset all sequence counters as soon as this sequence is done
774 *
775 * @param {Event} e
776 * @returns void
777 */
778 function _callbackAndReset(e) {
779 _fireCallback(callback, e, combo);
780
781 // we should ignore the next key up if the action is key down
782 // or keypress. this is so if you finish a sequence and
783 // release the key the final key will not trigger a keyup
784 if (action !== 'keyup') {
785 _ignoreNextKeyup = _characterFromEvent(e);
786 }
787
788 // weird race condition if a sequence ends with the key
789 // another sequence begins with
790 setTimeout(_resetSequences, 10);
791 }
792
793 // loop through keys one at a time and bind the appropriate callback
794 // function. for any key leading up to the final one it should
795 // increase the sequence. after the final, it should reset all sequences
796 //
797 // if an action is specified in the original bind call then that will
798 // be used throughout. otherwise we will pass the action that the
799 // next key in the sequence should match. this allows a sequence
800 // to mix and match keypress and keydown events depending on which
801 // ones are better suited to the key provided
802 for (var i = 0; i < keys.length; ++i) {
803 var isFinal = i + 1 === keys.length;
804 var wrappedCallback = isFinal ? _callbackAndReset : _increaseSequence(action || _getKeyInfo(keys[i + 1]).action);
805 _bindSingle(keys[i], wrappedCallback, action, combo, i);
806 }
807 }
808
809 /**
810 * binds a single keyboard combination
811 *
812 * @param {string} combination
813 * @param {Function} callback
814 * @param {string=} action
815 * @param {string=} sequenceName - name of sequence if part of sequence
816 * @param {number=} level - what part of the sequence the command is
817 * @returns void
818 */
819 function _bindSingle(combination, callback, action, sequenceName, level) {
820
821 // store a direct mapped reference for use with Mousetrap.trigger
822 self._directMap[combination + ':' + action] = callback;
823
824 // make sure multiple spaces in a row become a single space
825 combination = combination.replace(/\s+/g, ' ');
826
827 var sequence = combination.split(' ');
828 var info;
829
830 // if this pattern is a sequence of keys then run through this method
831 // to reprocess each pattern one key at a time
832 if (sequence.length > 1) {
833 _bindSequence(combination, sequence, callback, action);
834 return;
835 }
836
837 info = _getKeyInfo(combination, action);
838
839 // make sure to initialize array if this is the first time
840 // a callback is added for this key
841 self._callbacks[info.key] = self._callbacks[info.key] || [];
842
843 // remove an existing match if there is one
844 _getMatches(info.key, info.modifiers, {type: info.action}, sequenceName, combination, level);
845
846 // add this call back to the array
847 // if it is a sequence put it at the beginning
848 // if not put it at the end
849 //
850 // this is important because the way these are processed expects
851 // the sequence ones to come first
852 self._callbacks[info.key][sequenceName ? 'unshift' : 'push']({
853 callback: callback,
854 modifiers: info.modifiers,
855 action: info.action,
856 seq: sequenceName,
857 level: level,
858 combo: combination
859 });
860 }
861
862 /**
863 * binds multiple combinations to the same callback
864 *
865 * @param {Array} combinations
866 * @param {Function} callback
867 * @param {string|undefined} action
868 * @returns void
869 */
870 self._bindMultiple = function(combinations, callback, action) {
871 for (var i = 0; i < combinations.length; ++i) {
872 _bindSingle(combinations[i], callback, action);
873 }
874 };
875
876 // start!
877 _addEvent(targetElement, 'keypress', _handleKeyEvent);
878 _addEvent(targetElement, 'keydown', _handleKeyEvent);
879 _addEvent(targetElement, 'keyup', _handleKeyEvent);
880 }
881
882 /**
883 * binds an event to mousetrap
884 *
885 * can be a single key, a combination of keys separated with +,
886 * an array of keys, or a sequence of keys separated by spaces
887 *
888 * be sure to list the modifier keys first to make sure that the
889 * correct key ends up getting bound (the last key in the pattern)
890 *
891 * @param {string|Array} keys
892 * @param {Function} callback
893 * @param {string=} action - 'keypress', 'keydown', or 'keyup'
894 * @returns void
895 */
896 Mousetrap.prototype.bind = function(keys, callback, action) {
897 var self = this;
898 keys = keys instanceof Array ? keys : [keys];
899 self._bindMultiple.call(self, keys, callback, action);
900 return self;
901 };
902
903 /**
904 * unbinds an event to mousetrap
905 *
906 * the unbinding sets the callback function of the specified key combo
907 * to an empty function and deletes the corresponding key in the
908 * _directMap dict.
909 *
910 * TODO: actually remove this from the _callbacks dictionary instead
911 * of binding an empty function
912 *
913 * the keycombo+action has to be exactly the same as
914 * it was defined in the bind method
915 *
916 * @param {string|Array} keys
917 * @param {string} action
918 * @returns void
919 */
920 Mousetrap.prototype.unbind = function(keys, action) {
921 var self = this;
922 return self.bind.call(self, keys, function() {}, action);
923 };
924
925 /**
926 * triggers an event that has already been bound
927 *
928 * @param {string} keys
929 * @param {string=} action
930 * @returns void
931 */
932 Mousetrap.prototype.trigger = function(keys, action) {
933 var self = this;
934 if (self._directMap[keys + ':' + action]) {
935 self._directMap[keys + ':' + action]({}, keys);
936 }
937 return self;
938 };
939
940 /**
941 * resets the library back to its initial state. this is useful
942 * if you want to clear out the current keyboard shortcuts and bind
943 * new ones - for example if you switch to another page
944 *
945 * @returns void
946 */
947 Mousetrap.prototype.reset = function() {
948 var self = this;
949 self._callbacks = {};
950 self._directMap = {};
951 return self;
952 };
953
954 /**
955 * should we stop this event before firing off callbacks
956 *
957 * @param {Event} e
958 * @param {Element} element
959 * @return {boolean}
960 */
961 Mousetrap.prototype.stopCallback = function(e, element) {
962 var self = this;
963
964 // if the element has the class "mousetrap" then no need to stop
965 if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
966 return false;
967 }
968
969 if (_belongsTo(element, self.target)) {
970 return false;
971 }
972
973 // stop for input, select, and textarea
974 return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA' || element.isContentEditable;
975 };
976
977 /**
978 * exposes _handleKey publicly so it can be overwritten by extensions
979 */
980 Mousetrap.prototype.handleKey = function() {
981 var self = this;
982 return self._handleKey.apply(self, arguments);
983 };
984
985 /**
986 * Init the global mousetrap functions
987 *
988 * This method is needed to allow the global mousetrap functions to work
989 * now that mousetrap is a constructor function.
990 */
991 Mousetrap.init = function() {
992 var documentMousetrap = Mousetrap(document);
993 for (var method in documentMousetrap) {
994 if (method.charAt(0) !== '_') {
995 Mousetrap[method] = (function(method) {
996 return function() {
997 return documentMousetrap[method].apply(documentMousetrap, arguments);
998 };
999 } (method));
1000 }
1001 }
1002 };
1003
1004 Mousetrap.init();
1005
1006 // expose mousetrap to the global object
1007 window.Mousetrap = Mousetrap;
1008
1009 // expose as a common js module
1010 if (typeof module !== 'undefined' && module.exports) {
1011 module.exports = Mousetrap;
1012 }
1013
1014 // expose mousetrap as an AMD module
1015 if (typeof define === 'function' && define.amd) {
1016 define(function() {
1017 return Mousetrap;
1018 });
1019 }
1020 }) (window, document);
77 async: false
88 });
99
10 var faradayApp = angular.module('faradayApp', ['ngRoute', 'selectionModel', 'ui.bootstrap', 'angularFileUpload', 'filter', 'ngClipboard', 'ngCookies'])
10 var faradayApp = angular.module('faradayApp', ['ngRoute', 'selectionModel', 'ui.bootstrap', 'angularFileUpload', 'filter', 'ngClipboard', 'ngCookies', 'cfp.hotkeys'])
1111 .constant("BASEURL", (function() {
1212 var url = window.location.origin + "/";
1313 return url;
1111 var deferred = $q.defer(),
1212 promises = [],
1313 tmp = {};
14 files.forEach(function(file) {
15 promises.push(attachmentsFact.loadAttachment(file));
16 });
14 for(var name in files) {
15 if(files.hasOwnProperty(name)) {
16 var file = files[name];
17 file.name = name;
18 promises.push(attachmentsFact.loadAttachment(file));
19 }
20 }
1721 $q.all(promises).then(function(attachments) {
1822 attachments.forEach(function(attachment) {
1923 tmp[attachment.filename] = attachment.value;
2222 $modalInstance.close();
2323 };
2424 }]);
25
26 angular.module('faradayApp')
27 .controller('commonsModalEditString', ['$scope', '$modalInstance', 'msg', function($scope, $modalInstance, msg) {
28 $scope.msg = msg;
29 $scope.data = {property: ''};
30
31 $scope.ok = function() {
32 $modalInstance.close($scope.data.property);
33 };
34
35 $scope.cancel = function() {
36 $modalInstance.dismiss();
37 }
38 }]);
39 angular.module('faradayApp')
40 .controller('commonsModalEditOptions', ['$scope', '$modalInstance', 'msg', 'options', function($scope, $modalInstance, msg, options) {
41 $scope.msg = msg;
42 $scope.options = options;
43 $scope.data = {property: ''};
44
45 $scope.ok = function() {
46 $modalInstance.close($scope.data.property);
47 };
48
49 $scope.cancel = function() {
50 $modalInstance.dismiss();
51 }
52 }]);
53 angular.module('faradayApp')
54 .controller('commonsModalEditArray', ['$scope', '$modalInstance', 'msg', function($scope, $modalInstance, msg) {
55 $scope.msg = msg;
56 $scope.data = {property: []};
57 $scope.new_value = "";
58
59 $scope.newValue = function() {
60 if ($scope.new_value != "") {
61 // we need to check if the ref already exists
62 if ($scope.data.property.filter(function(ref) {return ref.value === $scope.new_value}).length == 0) {
63 $scope.data.property.push({value: $scope.new_value});
64 $scope.new_value = "";
65 }
66 }
67 }
68
69 $scope.ok = function() {
70 // add the ref in new_ref, if there's any
71 $scope.newValue();
72 // convert refs to an array of strings
73 var values = [];
74 $scope.data.property.forEach(function(val) {
75 values.push(val.value);
76 });
77 $scope.data.property = values;
78
79 $modalInstance.close($scope.data.property);
80 };
81
82 $scope.cancel = function() {
83 $modalInstance.dismiss();
84 }
85 }]);
86 angular.module('faradayApp')
87 .controller('commonsModalEditObject', ['$scope', '$modalInstance', 'msg', 'options', function($scope, $modalInstance, msg, options) {
88 var data = [];
89 $scope.msg = msg;
90 $scope.options = options;
91 $scope.data = {};
92 $scope.impact = {
93 add: [],
94 del: []
95 };
96
97 $scope.addImpact = function(key) {
98 if($scope.impact.add.indexOf(key) === -1 && $scope.impact.del.indexOf(key) === -1) {
99 $scope.impact.add.push(key);
100 }
101 };
102
103 $scope.delImpact = function(key) {
104 if($scope.impact.del.indexOf(key) === -1 && $scope.impact.add.indexOf(key) === -1) {
105 $scope.impact.del.push(key);
106 }
107 };
108
109 $scope.del_backImpact = function(key) {
110 var i = $scope.impact.del.indexOf(key);
111 if(i != -1) {
112 $scope.impact.del.splice(i, 1);
113 }
114 };
115
116 $scope.add_backImpact = function(key) {
117 var i = $scope.impact.add.indexOf(key);
118 if(i != -1) {
119 $scope.impact.add.splice(i, 1);
120 }
121 };
122
123 $scope.ok = function() {
124 for(opt in $scope.options){
125 if($scope.impact.add.indexOf(opt) != -1) {
126 $scope.data[opt] = true;
127 }
128 if($scope.impact.del.indexOf(opt) != -1) {
129 $scope.data[opt] = false;
130 }
131 }
132 $modalInstance.close($scope.data);
133 };
134
135 $scope.cancel = function() {
136 $modalInstance.dismiss();
137 }
138 }]);
139 angular.module('faradayApp')
140 .controller('commonsModalEditCWE', ['$scope', '$modalInstance', 'msg', 'cweFact', function($scope, $modalInstance, msg, cweFact) {
141 $scope.cweList = [];
142 cweFact.get().then(function(data) {
143 $scope.cweList = data;
144 });
145 $scope.cweLimit = 5;
146 $scope.cwe_filter = "";
147 $scope.msg = msg;
148
149 $scope.data = {
150 name: "",
151 desc: "",
152 resolution: "",
153 refs: []
154 };
155
156 $scope.new_ref = "";
157
158 $scope.populate = function(item) {
159 for (var key in $scope.data) {
160 if (key != "refs" && item.hasOwnProperty(key) && $scope.data.hasOwnProperty(key)) {
161 $scope.data[key] = item[key];
162 }
163 }
164 // convert refs to an array of objects
165 var refs = [];
166 item.refs.forEach(function(ref) {
167 refs.push({value: ref});
168 });
169 $scope.data.refs = refs;
170 };
171
172 $scope.ok = function() {
173 if($scope.formCWE.$valid) {
174 // add the ref in new_ref, if there's any
175 $scope.newReference();
176 // convert refs to an array of strings
177 var refs = [];
178 $scope.data.refs.forEach(function(ref) {
179 refs.push(ref.value);
180 });
181 $scope.data.refs = refs;
182
183 $modalInstance.close($scope.data);
184 }
185 };
186
187 $scope.newReference = function() {
188 if ($scope.new_ref != "") {
189 // we need to check if the ref already exists
190 if ($scope.data.refs.filter(function(ref) {return ref.value === $scope.new_ref}).length == 0) {
191 $scope.data.refs.push({value: $scope.new_ref});
192 $scope.new_ref = "";
193 }
194 }
195 }
196
197 $scope.cancel = function() {
198 $modalInstance.dismiss();
199 }
200 }]);
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .filter('decodeURIComponent', function() {
6 return function(x) {
7 return decodeURIComponent(x);
8 };
9 });
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .filter('encodeURIComponent', function() {
6 return function(x) {
7 return encodeURIComponent(x);
8 };
9 });
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 // returns index of object in collection if found or -1
5 angular.module('faradayApp')
6 .filter('getByProperty', function() {
7 return function(propertyName, propertyValue, collection) {
8 var len = collection.length;
9
10 for(var i = 0; i < len; i++) {
11 if(collection[i][propertyName] == propertyValue) {
12 return i;
13 }
14 }
15 return -1;
16 }
17 });
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp').
5 filter('integer', function() {
6 return function(input) {
7 return parseInt(input);
8 }
9 });
1818 function compareItems(field) {
1919 return function(a, b) {
2020 var res;
21 a = a[field];
22 b = b[field];
21 if(field === 'metadata.create_time') {
22 var arrayField = field.split(".");
23 a = a[arrayField[0]][arrayField[1]];
24 b = b[arrayField[0]][arrayField[1]];
25 } else {
26 a = a[field];
27 b = b[field];
28 }
2329 if(typeof(a) == "string" && typeof(b) == "string") {
2430 a = a.toLowerCase();
2531 b = b.toLowerCase();
0 <!-- Faraday Penetration Test IDE -->
1 <!-- Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/) -->
2 <!-- See the file 'doc/LICENSE' for the license information -->
3
4 <div class="modal-header">
5 <h5>{{msg}}</h5>
6 </div>
7 <div class="modal-body">
8 <div class="form-group editArray">
9 <div class="input-group margin-bottom-sm">
10 <input type="text" class="form-control" ng-model="new_value"/>
11 <span class="input-group-addon cursor" ng-click="newValue()"><i class="fa fa-plus-circle"></i></span>
12 </div>
13 <div class="input-group margin-bottom-sm reference" ng-repeat="v in data.property">
14 <input type="text" class="form-control" ng-model="v.value"/>
15 <span class="input-group-addon cursor" ng-click="data.property.splice($index, 1)"><i class="fa fa-minus-circle"></i></span>
16 </div>
17 </div>
18 </div>
19 <div class="modal-footer editArray">
20 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
21 <button class="btn btn-success" ng-click="ok()">OK</button>
22 </div>
0 <!-- Faraday Penetration Test IDE -->
1 <!-- Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/) -->
2 <!-- See the file 'doc/LICENSE' for the license information -->
3
4 <form name="formCWE">
5 <div class="modal-header">
6 <h5>{{msg}}</h5>
7 </div>
8 <div class="modal-body">
9 <div class="form-group">
10 <h5>Search CWE database by typing in the field below</h5>
11 <input type="text" ng-model="cwe_selected" class="form-control input-sm" placeholder="Search for CWE" typeahead="cwe as cwe.name for cwe in cweList | filter:{name: $viewValue} | limitTo:10" typeahead-on-select="populate($item, $model, $label)">
12 </div>
13 <div class="form-group">
14 <h5>Name</h5>
15 <input type="text" ng-model="data.name" class="form-control input-sm" placeholder="Name" required/>
16 </div>
17 <div class="form-group">
18 <h5>Description</h5>
19 <textarea ng-model="data.desc" class="form-control" placeholder="Description" required></textarea>
20 </div>
21 <div class="form-group">
22 <h5>Resolution</h5>
23 <textarea ng-model="data.resolution" class="form-control" placeholder="Resolution"></textarea>
24 </div>
25 <div class="form-group editArray">
26 <h5>References</h5>
27 <div class="input-group margin-bottom-sm">
28 <input type="text" class="form-control" placeholder="Reference" ng-model="new_ref"/>
29 <span class="input-group-addon cursor" ng-click="newReference()"><i class="fa fa-plus-circle"></i></span>
30 </div>
31 <div class="input-group margin-bottom-sm reference" ng-repeat="reference in data.refs">
32 <input type="text" class="form-control" placeholder="Reference" ng-model="reference.value"/>
33 <span class="input-group-addon cursor" ng-click="data.refs.splice($index, 1)"><i class="fa fa-minus-circle"></i></span>
34 </div>
35 </div>
36 </div>
37 <div class="modal-footer">
38 <button class="btn btn-success" ng-click="ok()" ng-disabled="formCWE.$invalid">OK</button>
39 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
40 </div>
41 </form>
0 <!-- Faraday Penetration Test IDE -->
1 <!-- Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/) -->
2 <!-- See the file 'doc/LICENSE' for the license information -->
3
4 <div class="modal-header" hotkey="{enter:ok}">
5 <h5>{{msg}}</h5>
6 </div>
7 <div class="modal-body">
8 <div class="row">
9 <div class="col-md-4">
10 <h2 class="ws-label"><span class="label label-default" title="All Impacts">All Impacts</span></h2>
11 <div class="ws-list">
12 <a class="ws-link" ng-repeat="(key, value) in options" style="height:35px">
13 <p class="label label-primary ws-name" style="cursor:default;">
14 <span class="glyphicon glyphicon-ok impact-ok cursor" ng-click="addImpact(key)"></span>{{key}}
15 <span class="glyphicon glyphicon-remove impact-del cursor" ng-click="delImpact(key)"></span>
16 </p>
17 </a>
18 </div><!-- .ws-list -->
19 </div>
20 <div class="col-md-4">
21 <h2 class="ws-label"><span class="label label-default" title="Will add">Will add</span></h2>
22 <div ng-repeat="add in impact.add" class="normal-size" style="cursor: pointer;">
23 <h4><span class="label label-success" ng-click="add_backImpact(add)">{{add}}</span></h4>
24 </div><!-- .normal-size -->
25 </div>
26 <div class="col-md-4">
27 <h2 class="ws-label"><span class="label label-default" title="Will delete">Will delete</span></h2>
28 <div ng-repeat="del in impact.del" class="normal-size" style="cursor: pointer;">
29 <h4><span class="label label-danger" ng-click="del_backImpact(del)">{{del}}</span></h4>
30 </div><!-- .normal-size -->
31 </div>
32 </div>
33 </div>
34 <div class="modal-footer">
35 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
36 <button class="btn btn-success" ng-click="ok()">OK</button>
37 </div>
0 <!-- Faraday Penetration Test IDE -->
1 <!-- Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/) -->
2 <!-- See the file 'doc/LICENSE' for the license information -->
3
4 <div class="modal-header" hotkey="{enter:ok}">
5 <h5>{{msg}}</h5>
6 </div>
7 <div class="modal-body">
8 <select class="form-control" ng-model="data.property" ng-options="o as o for o in options">
9 </select>
10 </div>
11 <div class="modal-footer">
12 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
13 <button class="btn btn-success" ng-click="ok()">OK</button>
14 </div>
0 <!-- Faraday Penetration Test IDE -->
1 <!-- Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/) -->
2 <!-- See the file 'doc/LICENSE' for the license information -->
3
4 <form hotkey="{enter:ok}">
5 <div class="modal-header">
6 <h5>{{msg}}</h5>
7 </div>
8 <div class="modal-body">
9 <input type="text" ng-model="data.property" class="form-control"/>
10 </div>
11 <div class="modal-footer">
12 <button class="btn btn-success" ng-click="ok()">OK</button>
13 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
14 </div>
15 </form>
0 <!-- Faraday Penetration Test IDE -->
1 <!-- Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/) -->
2 <!-- See the file 'doc/LICENSE' for the license information -->
3
4 <div class="modal-header" hotkey="{enter:ok}">
5 <h5>{{msg}}</h5>
6 </div>
7 <div class="modal-body">
8 <textarea class="form-control" ng-model="data.property"></textarea>
9 </div>
10 <div class="modal-footer">
11 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
12 <button class="btn btn-success" ng-click="ok()">OK</button>
13 </div>
3434 <strong>Manage your projects</strong>
3535 </small>
3636 </a>
37 <a href="#/hosts" class="ws-link item animated flipInX">
38 <i class="fa fa-sitemap fa-5x icons-color-home icons-size-home"></i>
39 <span class="ws-name">Hosts</span>
40 <small>
41 Hosts and Services CRUD<br/>
42 <strong>Manage your hosts</strong>
43 </small>
44 </a>
3745 </div><!-- .ws-list -->
3846 </div><!-- .reports -->
3947 </div><!-- #reports-main --></div><!-- .right-main -->
11 <!-- Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/) -->
22 <!-- See the file 'doc/LICENSE' for the license information -->
33
4 <div class="modal-header">
4 <div class="modal-header" hotkey="{enter:ok}">
55 <h3 class="modal-title">Bulk deletion</h3>
66 </div>
77 <div class="modal-body">
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('cweFact', ['BASEURL', '$http', '$q', function(BASEURL, $http, $q) {
6 var cweFact = {};
7 cweFact.cweList = [];
8
9 cweFact.get = function() {
10 var deferred = $q.defer();
11 var cwe_url = BASEURL + 'cwe/_all_docs?include_docs=true';
12
13 $http.get(cwe_url).then(function(res) {
14 res.data.rows.forEach(function(obj) {
15 var c = {
16 id: obj.id,
17 cwe: obj.doc.cwe,
18 name: obj.doc.name,
19 desc: "Summary: " + obj.doc.desc_summary + "\n\n" + obj.doc.description,
20 resolution: obj.doc.resolution,
21 exploitation: obj.doc.exploitation,
22 refs: obj.doc.references
23 };
24 if (typeof(obj.doc.references) == "string") {
25 c.refs = [];
26 obj.doc.references.split('\n').forEach(function(ref) {
27 if (ref != "") {
28 c.refs.push(ref);
29 }
30 });
31 }
32 cweFact.cweList.push(c);
33 });
34 deferred.resolve(cweFact.cweList);
35 });
36
37 return deferred.promise;
38 };
39
40 return cweFact;
41 }]);
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('d3Service', ['BASEURL', '$document', '$q', '$rootScope',
6 function(BASEURL, $document, $q, $rootScope) {
7 var d = $q.defer();
8 function onScriptLoad() {
9 // Load client in the browser
10 $rootScope.$apply(function() { d.resolve(window.d3); });
11 }
12 // Create a script tag with d3 as the source
13 // and call our onScriptLoad callback when it
14 // has been loaded
15 var scriptTag = $document[0].createElement('script');
16 scriptTag.type = 'text/javascript';
17 scriptTag.async = true;
18 scriptTag.src = 'script/d3.v3.min.js';
19 scriptTag.onreadystatechange = function () {
20 if (this.readyState == 'complete') onScriptLoad();
21 }
22 scriptTag.onload = onScriptLoad;
23
24 var s = $document[0].getElementsByTagName('body')[0];
25 s.appendChild(scriptTag);
26
27 return {
28 d3: function() { return d.promise; }
29 };
30 }
31 ]);
+0
-32
views/reports/_attachments/scripts/d3/services/d3.js less more
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('d3Service', ['BASEURL', '$document', '$q', '$rootScope',
6 function(BASEURL, $document, $q, $rootScope) {
7 var d = $q.defer();
8 function onScriptLoad() {
9 // Load client in the browser
10 $rootScope.$apply(function() { d.resolve(window.d3); });
11 }
12 // Create a script tag with d3 as the source
13 // and call our onScriptLoad callback when it
14 // has been loaded
15 var scriptTag = $document[0].createElement('script');
16 scriptTag.type = 'text/javascript';
17 scriptTag.async = true;
18 scriptTag.src = 'script/d3.v3.min.js';
19 scriptTag.onreadystatechange = function () {
20 if (this.readyState == 'complete') onScriptLoad();
21 }
22 scriptTag.onload = onScriptLoad;
23
24 var s = $document[0].getElementsByTagName('body')[0];
25 s.appendChild(scriptTag);
26
27 return {
28 d3: function() { return d.promise; }
29 };
30 }
31 ]);
33
44 angular.module('faradayApp')
55 .controller('dashboardCtrl',
6 ['$scope', '$filter', '$route', '$routeParams', '$location', 'statusReportFact',
7 function($scope, $filter, $route, $routeParams, $location, statusReportFact) {
6 ['$scope', '$filter', '$route', '$routeParams', '$location', 'workspacesFact',
7 function($scope, $filter, $route, $routeParams, $location, workspacesFact) {
88 init = function() {
99 //current workspace
1010 $scope.workspace = $routeParams.wsId;
1111 $scope.workspaces = [];
1212
13 statusReportFact.getWorkspaces().then(function(wss) {
13 workspacesFact.list().then(function(wss) {
1414 $scope.workspaces = wss;
1515 });
1616 };
33
44 angular.module('faradayApp')
55 .controller('summarizedCtrl',
6 ['$scope', '$route', '$routeParams', '$modal', 'dashboardSrv', 'statusReportFact',
7 function($scope, $route, $routeParams, $modal, dashboardSrv, statusReportFact) {
6 ['$scope', '$route', '$routeParams', '$modal', 'dashboardSrv', 'vulnsManager',
7 function($scope, $route, $routeParams, $modal, dashboardSrv, vulnsManager) {
88 //current workspace
99 var workspace = $routeParams.wsId;
1010 $scope.servicesCount = [];
5656 }
5757
5858 // vuln table sorting
59 $scope.vulnSortField = 'date';
59 $scope.vulnSortField = 'metadata.create_time';
6060 $scope.vulnSortReverse = true;
6161 // toggles sort field and order
6262 $scope.vulnToggleSort = function(field) {
7474 $scope.vulnSortReverse = !$scope.vulnSortReverse;
7575 };
7676
77 if (workspace != undefined){
77 if(workspace != undefined) {
7878 $scope.workspace = workspace;
79
7980 dashboardSrv.getServicesCount(workspace).then(function(res){
8081 res.sort(function(a, b){
8182 return b.value - a.value;
8384 $scope.servicesCount = res;
8485
8586 });
87
8688 dashboardSrv.getObjectsCount(workspace).then(function(res){
8789 for(var i = res.length - 1; i >= 0; i--) {
8890 if(res[i].key === "interfaces") {
9193 }
9294 $scope.objectsCount = res;
9395 });
96
9497 dashboardSrv.getVulnerabilitiesCount(workspace).then(function(res){
9598 if (res.length > 0) {
9699 var tmp = [
128131 $scope.vulnsCount = tmp;
129132 }
130133 });
134
131135 dashboardSrv.getCommands(workspace).then(function(res){
132136 res.forEach(function(cmd){
133137 cmd.user = cmd.user || "unknown";
142146 });
143147 $scope.commands = res;
144148 });
149
145150 dashboardSrv.getHosts(workspace).then(function(res){
146151 dashboardSrv.getHostsByServicesCount(workspace).then(function(servicesCount){
147152 res.forEach(function(host){
169174 });
170175 });
171176 });
172 $scope.vulns = statusReportFact.getVulns(workspace);
173 $scope.vulns.sort(function(a,b){
174 return b.meta.create_time - a.meta.create_time;
175 });
176 $scope.vulns = $scope.vulns.splice(0,5);
177
178 vulnsManager.getVulns(workspace).then(function(vulns) {
179 $scope.vulns = vulns;
180 });
177181 }
178182
179183 $scope.numberOfPages = function() {
99 //current workspace
1010 $scope.workspace = $routeParams.wsId;
1111
12 $scope.prices = {
13 "critical": "5000",
14 "high": "3000",
15 "med": "1000",
16 "low": "500",
17 "info": "0",
18 "unclassified": "0"
19 };
12 $scope.prices = dashboardSrv.vulnPrices;
2013
2114 dashboardSrv.getVulnerabilities($scope.workspace).then(function(res) {
2215 $scope.vulns = res;
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .controller('workspaceProgressCtrl',
6 ['$scope', '$route', '$routeParams', 'workspacesFact',
7 function($scope, $route, $routeParams, workspacesFact) {
8 $scope.duration;
9 $scope.end;
10 $scope.start;
11 $scope.progress;
12 $scope.workspace;
13
14 init = function() {
15 $scope.workspace = $routeParams.wsId;
16 workspacesFact.getDuration($scope.workspace).then(function(duration) {
17 $scope.duration = duration;
18 $scope.progress = $scope.calculateProgress($scope.duration);
19 $scope.start = $scope.duration.start;
20 $scope.end = $scope.duration.end;
21 });
22 };
23
24 $scope.calculateProgress = function(duration) {
25 var partial = 0,
26 progress = 0,
27 today = new Date(),
28 total = 0;
29
30 if(duration.start == "" || duration.end == "") {
31 progress = null;
32 } else {
33 today = today.getTime();
34 partial = today - duration.start;
35 total = duration.end - duration.start;
36
37 if(today > duration.end) {
38 progress = 100;
39 } else if(duration.start < today && today <= duration.end && total > 0) {
40 progress = Math.round(partial * 100 / total);
41 }
42 }
43
44 return progress;
45 };
46
47 init();
48 }]);
0 <div id='list'>
1 <div class='col-lg-6'>
2 <article class='panel panel-default'>
3 <header>
4 <h2>Commands History
5 <span class="glyphicon glyphicon-info-sign" tooltip="Shows current WS' executed commands"></span>
6 </h2>
7 </header>
8 <div ng-if="commands.length == 0" class="alert alert-info alert-dismissible">
9 <button type="button" class="close" data-dismiss="alert">
10 <span aria-hidden="true">&times;</span>
11 <span class="sr-only">Close</span>
12 </button>
13 <p>No commands found yet.</p>
14 </div>
15 <table id="commands" ng-if="commands.length > 0" class="tablesorter table table-striped">
16 <thead>
17 <tr>
18 <th><a href="" ng-click="cmdToggleSort('user')">By</a></th>
19 <th><a href="" ng-click="cmdToggleSort('command')">Command</a></th>
20 <th><a href="" ng-click="cmdToggleSort('date')">Start Date</a></th>
21 <th><a href="" ng-click="cmdToggleSort('duration')">Duration</a></th>
22 </tr>
23 </thead>
24 <tbody>
25 <tr ng-repeat="cmd in commands | orderObjectBy:cmdSortField:cmdSortReverse">
26 <td><p tooltip="{{cmd.ip}}">{{cmd.user}}@{{cmd.hostname}}</p></td>
27 <td>{{cmd.command}}</td>
28 <td>{{cmd.date | date:"MM/dd/yyyy 'at' h:mma"}}</td>
29 <td ng-bind="cmd.duration || 'undefined'"></td>
30 </tr>
31 </tbody>
32 </table>
33 </article>
0 <article id='list' class='panel panel-default'>
1 <header>
2 <h2>Commands History
3 <span class="glyphicon glyphicon-info-sign" tooltip="Shows current WS' executed commands"></span>
4 </h2>
5 </header>
6 <div ng-if="commands.length == 0" class="alert alert-info alert-dismissible no-margin-bottom">
7 <button type="button" class="close" data-dismiss="alert">
8 <span aria-hidden="true">&times;</span>
9 <span class="sr-only">Close</span>
10 </button>
11 <p>No commands found yet.</p>
3412 </div>
35 </div>
13 <table id="commands" ng-if="commands.length > 0" class="tablesorter table table-striped">
14 <thead>
15 <tr>
16 <th><a href="" ng-click="cmdToggleSort('user')">By</a></th>
17 <th><a href="" ng-click="cmdToggleSort('command')">Command</a></th>
18 <th><a href="" ng-click="cmdToggleSort('date')">Start Date</a></th>
19 <th><a href="" ng-click="cmdToggleSort('duration')">Duration</a></th>
20 </tr>
21 </thead>
22 <tbody>
23 <tr ng-repeat="cmd in commands | orderObjectBy:cmdSortField:cmdSortReverse">
24 <td><p tooltip="{{cmd.ip}}">{{cmd.user}}@{{cmd.hostname}}</p></td>
25 <td class="wrapword">{{cmd.command}}</td>
26 <td>{{cmd.date | date:"MM/dd/yyyy 'at' h:mma"}}</td>
27 <td ng-bind="cmd.duration || 'undefined'"></td>
28 </tr>
29 </tbody>
30 </table>
31 </article>
0 <div id='compound'>
1 <div class='col-lg-6'>
2 <article class='panel panel-default'>
3 <header>
4 <h2><a href="#/hosts/ws/{{workspace}}">Hosts</a>
5 <span class="glyphicon glyphicon-info-sign" tooltip="All hosts, each one showing its service count and operating system. By clicking on a host IP you can access a list with all of its services"></span>
6 </h2>
7 </header>
8 <div ng-if="hosts.length == 0" class="alert alert-info alert-dismissible">
9 <button type="button" class="close" data-dismiss="alert">
10 <span aria-hidden="true">&times;</span>
11 <span class="sr-only">Close</span>
12 </button>
13 <p>No hosts found yet.</p>
14 </div>
15 <table id="hosts" ng-if="hosts.length > 0" class="tablesorter table table-striped">
16 <thead>
17 <tr>
18 <th><a href="" ng-click="hostToggleSort('name')">Host</a></th>
19 <th><a href="" ng-click="hostToggleSort('servicesCount')">Services</a></th>
20 <th><a href="" ng-click="hostToggleSort('os')">OS</a></th>
21 </tr>
22 </thead>
23 <tbody>
24 <tr ng-repeat="host in hosts | orderBy:hostSortField:hostSortReverse |
25 startFrom:currentPage*pageSize | limitTo:pageSize">
26 <td><a href="" class="host" ng-click="showServices(host.id)">{{host.name}}</a></td>
27 <td>{{host.servicesCount}}</td>
28 <td>
29 <img ng-if="host.icon != undefined" ng-src="../././reports/images/{{host.icon}}.png" tooltip="{{host.os}}"/>
30 <span ng-if="host.icon == undefined" class="glyphicon glyphicon-question-sign" tooltip="{{host.os}}"></span>
31 </td>
32 </tr>
33 </tbody>
34 </table>
35 <div class="showPagination" ng-show="showPagination">
36 <div class="form-group">
37 <ul class="pagination">
38 <li><a ng-hide="currentPage == 0" ng-click="currentPage=currentPage-1"><span aria-hidden="true">&laquo;</span><span class="sr-only">Previous</span></a></li>
39 <li><a>{{currentPage}}/{{numberOfPages()}}</a></li>
40 <li><a ng-hide="currentPage >= numberOfPages()" ng-click="currentPage=currentPage+1"><span aria-hidden="true">&raquo;</span><span class="sr-only">Next</span></a></li>
41 </ul>
42 <form name="goToPage" id="goToPageStatus">
43 <input type="number" min="0" max="{{numberOfPages()}}" class="form-control" ng-model="go_page" placeholder="Go to page"/>
44 <button class="btn btn-default" ng-click="go()">GO</button>
45 <input id="vuln-per-page" type="number" min="0" class="form-control vuln_per_page" ng-model="pagination" placeholder="Numbre page" />
46 </form>
47 </div>
48 </div>
49 </article>
0 <article id='compound' class='panel panel-default'>
1 <header>
2 <h2><a href="#/hosts/ws/{{workspace}}">Hosts</a>
3 <span class="glyphicon glyphicon-info-sign" tooltip="All hosts, each one showing its service count and operating system. By clicking on a host IP you can access a list with all of its services"></span>
4 </h2>
5 </header>
6 <div ng-if="hosts.length == 0" class="alert alert-info alert-dismissible no-margin-bottom">
7 <button type="button" class="close" data-dismiss="alert">
8 <span aria-hidden="true">&times;</span>
9 <span class="sr-only">Close</span>
10 </button>
11 <p>No hosts found yet.</p>
5012 </div>
51 </div>
13 <table id="hosts" ng-if="hosts.length > 0" class="tablesorter table table-striped">
14 <thead>
15 <tr>
16 <th><a href="" ng-click="hostToggleSort('name')">Host</a></th>
17 <th><a href="" ng-click="hostToggleSort('servicesCount')">Services</a></th>
18 <th><a href="" ng-click="hostToggleSort('os')">OS</a></th>
19 </tr>
20 </thead>
21 <tbody>
22 <tr ng-repeat="host in hosts | orderBy:hostSortField:hostSortReverse |
23 startFrom:currentPage*pageSize | limitTo:pageSize">
24 <td><a href="" class="host" ng-click="showServices(host.id)">{{host.name}}</a></td>
25 <td>{{host.servicesCount}}</td>
26 <td>
27 <img ng-if="host.icon != undefined" ng-src="../././reports/images/{{host.icon}}.png" tooltip="{{host.os}}"/>
28 <span ng-if="host.icon == undefined" class="glyphicon glyphicon-question-sign" tooltip="{{host.os}}"></span>
29 </td>
30 </tr>
31 </tbody>
32 </table>
33 <div class="showPagination" ng-show="showPagination">
34 <div class="form-group">
35 <ul class="pagination">
36 <li><a ng-hide="currentPage == 0" ng-click="currentPage=currentPage-1"><span aria-hidden="true">&laquo;</span><span class="sr-only">Previous</span></a></li>
37 <li><a>{{currentPage}}/{{numberOfPages()}}</a></li>
38 <li><a ng-hide="currentPage >= numberOfPages()" ng-click="currentPage=currentPage+1"><span aria-hidden="true">&raquo;</span><span class="sr-only">Next</span></a></li>
39 </ul>
40 <form name="goToPage" id="goToPageStatus">
41 <input type="number" min="0" max="{{numberOfPages()}}" class="form-control" ng-model="go_page" placeholder="Go to page"/>
42 <button class="btn btn-default" ng-click="go()">GO</button>
43 <input id="vuln-per-page" type="number" min="0" class="form-control vuln_per_page" ng-model="pagination" placeholder="Numbre page" />
44 </form>
45 </div>
46 </div>
47 </article>
2323 </div><!-- .reports -->
2424 <div ng-controller="graphicsBarCtrl" ng-include="'scripts/dashboard/partials/graphics-bar.html'"></div>
2525 <div ng-controller="summarizedCtrl" ng-include="'scripts/dashboard/partials/summarized.html'"></div>
26 <div ng-controller="summarizedCtrl" ng-include="'scripts/dashboard/partials/vulns-by-severity.html'"></div>
27 <div ng-controller="vulnsbypriceCtrl" ng-include="'scripts/dashboard/partials/vulns-by-price.html'"></div>
28 <div ng-controller="summarizedCtrl" ng-include="'scripts/dashboard/partials/last-vulns.html'"></div>
29 <div ng-controller="summarizedCtrl" ng-include="'scripts/dashboard/partials/compound.html'"></div>
30 <div ng-controller="summarizedCtrl" ng-include="'scripts/dashboard/partials/commands-list.html'"></div>
26 <div class="row">
27 <div class="col-lg-6 col-lg-left">
28 <div ng-controller="summarizedCtrl" ng-include="'scripts/dashboard/partials/last-vulns.html'"></div>
29 <div ng-controller="summarizedCtrl" ng-include="'scripts/dashboard/partials/compound.html'"></div>
30 </div>
31 <div class="col-lg-6 col-lg-right">
32 <div ng-controller="summarizedCtrl" ng-include="'scripts/dashboard/partials/vulns-by-severity.html'"></div>
33 <div ng-controller="vulnsbypriceCtrl" ng-include="'scripts/dashboard/partials/vulns-by-price.html'"></div>
34 <div ng-controller="summarizedCtrl" ng-include="'scripts/dashboard/partials/commands-list.html'"></div>
35 <div ng-controller="workspaceProgressCtrl" ng-include="'scripts/dashboard/partials/workspace-progress.html'"></div>
36 </div>
37 </div>
3138 </div><!-- #reports-main -->
3239 </div><!-- .right-main -->
3340 </section>
0 <div class='col-md-6 left-big-box'>
1 <article class='panel panel-default'>
2 <header>
3 <h2>Last Vulnerabilities
4 <span class="glyphicon glyphicon-info-sign" tooltip="Last vulnerabilities added"></span>
5 </h2>
6 </header>
7 <div ng-if="vulns.length == 0" class="alert alert-info alert-dismissible">
8 <button type="button" class="close" data-dismiss="alert">
9 <span aria-hidden="true">&times;</span>
10 <span class="sr-only">Close</span>
11 </button>
12 <p>No vulnerabilities found yet.</p>
13 </div>
14 <table ng-if="vulns.length > 0" class="tablesorter table table-striped last-vuln">
15 <thead>
16 <tr>
17 <th><a href="" ng-click="vulnToggleSort('date')">Date</a></th>
18 <th><a href="" ng-click="vulnToggleSort('target')">Target</a></th>
19 <th><a href="" ng-click="vulnToggleSort('severity')">Severity</a></th>
20 <th><a href="" ng-click="vulnToggleSort('name')">Name</a></th>
21 <th><a href="" ng-click="vulnToggleSort('web')">Web</a></th>
22 <th><a href="" ng-click="vulnToggleSort('easeofresolution')">Ease of resolution</a></th>
23 </tr>
24 </thead>
25 <tbody>
26 <tr ng-repeat="vuln in vulns | orderObjectBy:vulnSortField:vulnSortReverse">
27 <td>{{vuln.date | date:"MM/dd/yyyy 'at' h:mma"}}</td>
28 <td>{{vuln.target}}</td>
29 <td>{{vuln.severity}}</td>
30 <td>{{vuln.name}}</td>
31 <td>
32 <span class="glyphicon glyphicon-ok" ng-show="vuln.web"></span>
33 <span class="glyphicon glyphicon-remove" ng-show="!vuln.web"></span>
34 </td>
35 <td>{{vuln.easeofresolution}}</td>
36 </tr>
37 </tbody>
38 </table>
39 </article>
40 </div>
0 <article class='panel panel-default left-big-box'>
1 <header>
2 <h2>Last Vulnerabilities
3 <span class="glyphicon glyphicon-info-sign" tooltip="Last vulnerabilities added"></span>
4 </h2>
5 </header>
6 <div ng-if="vulns.length == 0" class="alert alert-info alert-dismissible no-margin-bottom">
7 <button type="button" class="close" data-dismiss="alert">
8 <span aria-hidden="true">&times;</span>
9 <span class="sr-only">Close</span>
10 </button>
11 <p>No vulnerabilities found yet.</p>
12 </div>
13 <table ng-if="vulns.length > 0" class="tablesorter table table-striped last-vuln">
14 <thead>
15 <tr>
16 <th><a href="" ng-click="vulnToggleSort('metadata.create_time')">Date</a></th>
17 <th><a href="" ng-click="vulnToggleSort('target')">Target</a></th>
18 <th><a href="" ng-click="vulnToggleSort('severity')">Severity</a></th>
19 <th><a href="" ng-click="vulnToggleSort('name')">Name</a></th>
20 <th><a href="" ng-click="vulnToggleSort('web')">Web</a></th>
21 <th><a href="" ng-click="vulnToggleSort('easeofresolution')">Ease of resolution</a></th>
22 </tr>
23 </thead>
24 <tbody>
25 <tr ng-repeat="vuln in vulns | orderObjectBy:vulnSortField:vulnSortReverse | limitTo:5">
26 <td>{{vuln.metadata.create_time * 1000 | date:"MM/dd/yyyy 'at' h:mma"}}</td>
27 <td>{{vuln.target}}</td>
28 <td>{{vuln.severity}}</td>
29 <td class="wrapword">{{vuln.name}}</td>
30 <td>
31 <span class="glyphicon glyphicon-ok" ng-show="vuln.web"></span>
32 <span class="glyphicon glyphicon-remove" ng-show="!vuln.web"></span>
33 </td>
34 <td>{{vuln.easeofresolution}}</td>
35 </tr>
36 </tbody>
37 </table>
38 </article>
11 <!-- Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/) -->
22 <!-- See the file 'doc/LICENSE' for the license information -->
33
4 <div class="modal-header">
4 <div class="modal-header" hotkey="{enter:ok}">
55 <h3>Services for {{name}} ({{hosts.length}} total)</h3>
66 </div>
77
11 <!-- Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/) -->
22 <!-- See the file 'doc/LICENSE' for the license information -->
33
4 <div class="modal-header">
4 <div class="modal-header" hotkey="{enter:ok}">
55 <h3>Services for {{name}} ({{services.length}} total)</h3>
66 </div>
77
11 <!-- Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/) -->
22 <!-- See the file 'doc/LICENSE' for the license information -->
33
4 <div class="modal-header">
4 <div class="modal-header" hotkey="{enter:ok}">
55 <h3>Top Services {{hola}}</h3>
66 </div>
77
0 <div id="vulns-by-price">
1 <div class="col-lg-6">
2 <article class="panel panel-default">
3 <header>
4 <h2>
5 Workspace's worth
6 <span class="glyphicon glyphicon-info-sign" tooltip="Total net worth of Workspace, according to current vulnerabilities' prices"></span>
7 </h2>
8 </header>
9 <div class="main">
10 <div class="center-lg-6"><h4><i class="fa fa-money fa-2x"></i> {{total | currency}} total</h4></div>
11 <div d3-horizontal-stacked-bar data="data" class="stackedbars"></div>
12 <div id="vulns-by-price-reference" class="center-lg-6">
13 <ul class="label-list">
14 <li ng-repeat="(severity, price) in prices" tooltip="Click on number to edit price"><span class="label vuln fondo-{{severity}}">{{severity}} $<span contenteditable="true" ng-model="prices[severity]"></span></span></li>
15 </ul>
16 </div><!-- #vulns-by-price-reference .center-lg-6 -->
17 </div>
18 </article>
19 </div><!-- .col-lg-6 -->
20 </div><!-- #vulns-by-price -->
0 <article id="vulns-by-price" class="panel panel-default">
1 <header>
2 <h2>
3 Workspace's worth
4 <span class="glyphicon glyphicon-info-sign" tooltip="Total net worth of Workspace, according to current vulnerabilities' prices"></span>
5 </h2>
6 </header>
7 <div class="main">
8 <div class="center-lg-6"><h4><i class="fa fa-money fa-2x"></i> {{total | currency}} total</h4></div>
9 <div d3-horizontal-stacked-bar data="data" class="stackedbars"></div>
10 <div id="vulns-by-price-reference" class="center-lg-6">
11 <ul class="label-list">
12 <li ng-repeat="(severity, price) in prices" tooltip="Click on number to edit price"><span class="label vuln fondo-{{severity}}">{{severity}} $<span contenteditable="true" ng-model="prices[severity]"></span></span></li>
13 </ul>
14 </div><!-- #vulns-by-price-reference .center-lg-6 -->
15 </div>
16 </article>
0 <div id='vulns'>
1 <div class='col-lg-6'>
2 <article class='panel panel-default'>
3 <header>
4 <h2>
5 <a href="../././reports/index.html#/status/ws/{{workspace}}" class="status-report">Vulnerabilities</a>
6 <span class="glyphicon glyphicon-info-sign" tooltip="Vulnerabilities count arranged by severity"></span>
7 </h2>
8 </header>
9 <div ng-if="vulnsCount.length == 0" class="alert alert-info alert-dismissible">
10 <button type="button" class="close" data-dismiss="alert">
11 <span aria-hidden="true">&times;</span>
12 <span class="sr-only">Close</span>
13 </button>
14 <p>No vulnerabilities found yet.</p>
15 </div>
16 <div class='main box'>
17 <div ng-repeat="vuln in vulnsCount" class="columna unsexto cursor">
18 <article class="dato2 fondo-{{vuln.key}}" ng-click="navigate('/status/ws/'+workspace+'/search/severity='+vuln.key)">
19 <section>
20 <div class="nro texto-blanco">{{vuln.value}}</div>
21 <div class="txt texto-blanco">{{vuln.key}}</div>
22 </section>
23 </article>
24 </div>
25 </div>
26 </article>
0 <article id='vulns' class='panel panel-default'>
1 <header>
2 <h2>
3 <a href="../././reports/index.html#/status/ws/{{workspace}}" class="status-report">Vulnerabilities</a>
4 <span class="glyphicon glyphicon-info-sign" tooltip="Vulnerabilities count arranged by severity"></span>
5 </h2>
6 </header>
7 <div ng-if="vulnsCount.length == 0" class="alert alert-info alert-dismissible no-margin-bottom">
8 <button type="button" class="close" data-dismiss="alert">
9 <span aria-hidden="true">&times;</span>
10 <span class="sr-only">Close</span>
11 </button>
12 <p>No vulnerabilities found yet.</p>
2713 </div>
28 </div>
14 <div class='main box'>
15 <div ng-repeat="vuln in vulnsCount" class="columna unsexto cursor">
16 <article class="dato2 fondo-{{vuln.key}}" ng-click="navigate('/status/ws/'+workspace+'/search/severity='+vuln.key)">
17 <section>
18 <div class="nro texto-blanco">{{vuln.value}}</div>
19 <div class="txt texto-blanco">{{vuln.key}}</div>
20 </section>
21 </article>
22 </div>
23 </div>
24 </article>
0 <article class="panel panel-default" id="workspace-progress">
1 <header>
2 <h2>
3 Workspace progress
4 <span class="glyphicon glyphicon-info-sign" tooltip="Workspace progress according to Scope dates"></span>
5 </h2>
6 </header>
7 <div>
8 <div id="workspace-progress-reference" class="center-lg-6" ng-if="progress">
9 <progressbar value="progress" class="progress-striped">{{progress}}%</progressbar>
10 <ul class="label-list">
11 <li><span class="label label-default">Start date: {{start | date:"MM/dd/yyyy"}}</span></li>
12 <li><span class="label label-default">End date: {{end | date:"MM/dd/yyyy"}}</span></li>
13 </ul>
14 </div><!-- #workspace-progress-reference .center-lg-6 -->
15 <div ng-if="!progress" class="alert alert-info alert-dismissible no-margin-bottom">
16 <button type="button" class="close" data-dismiss="alert">
17 <span aria-hidden="true">&times;</span>
18 <span class="sr-only">Close</span>
19 </button>
20 <p>Start date and end date are required</p>
21 </div><!-- ng-if -->
22 </div>
23 </article>
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('dashboardSrv', ['BASEURL', '$q', '$http', function(BASEURL, $q, $http) {
6 var dashboardSrv = {};
7
8 dashboardSrv._getView = function(url) {
9 var deferred = $q.defer();
10
11 $http.get(url).then(function(response){
12 res = response.data.rows;
13 deferred.resolve(res);
14 }, function(){
15 deferred.reject();
16 });
17
18 return deferred.promise;
19 };
20
21 dashboardSrv.vulnPrices = {
22 "critical": "5000",
23 "high": "3000",
24 "med": "1000",
25 "low": "500",
26 "info": "0",
27 "unclassified": "0"
28 };
29
30 dashboardSrv.getHostsByServicesCount = function(ws, id) {
31 var url = BASEURL + "/" + ws + "/_design/hosts/_view/byservicecount?group=true";
32 if (id != undefined){
33 url += "&key=\"" + id + "\"";
34 }
35 return dashboardSrv._getView(url);
36 };
37
38 dashboardSrv.getServicesCount = function(ws) {
39 var url = BASEURL + "/" + ws + "/_design/hosts/_view/byservices?group=true";
40 return dashboardSrv._getView(url);
41 };
42
43 dashboardSrv.getVulnerabilities = function(ws) {
44 var url = BASEURL + "/" + ws + "/_design/vulns/_view/all";
45 return dashboardSrv._getView(url);
46 };
47
48 dashboardSrv.getVulnerabilitiesCount = function(ws) {
49 var url = BASEURL + "/" + ws + "/_design/hosts/_view/vulns?group=true";
50 return dashboardSrv._getView(url);
51 };
52
53 dashboardSrv.getObjectsCount = function(ws) {
54 var url = BASEURL + "/" + ws + "/_design/hosts/_view/summarized?group=true";
55 return dashboardSrv._getView(url);
56 };
57
58 dashboardSrv.getCommands = function(ws) {
59 var deferred = $q.defer();
60 var url = BASEURL + "/" + ws + "/_design/commands/_view/list";
61 dashboardSrv._getView(url).then(function(res){
62 var tmp = [];
63 res.forEach(function(cmd){
64 var _cmd = cmd.value;
65 _cmd["command"] = cmd.key;
66 tmp.push(_cmd);
67 });
68 deferred.resolve(tmp);
69 }, function(){
70 deferred.reject();
71 });
72 return deferred.promise;
73 };
74
75 dashboardSrv.getHosts = function(ws) {
76 var deferred = $q.defer();
77 var url = BASEURL + "/" + ws + "/_design/hosts/_view/hosts";
78 dashboardSrv._getView(url).then(function(res){
79 var tmp = [];
80 res.forEach(function(host){
81 var _host = host.value;
82 _host["id"] = host.key;
83 tmp.push(_host);
84 });
85 deferred.resolve(tmp);
86 }, function(){
87 deferred.reject();
88 });
89 return deferred.promise;
90 };
91
92 dashboardSrv.getHost = function(ws, host_id) {
93 var deferred = $q.defer();
94 var url = BASEURL + "/" + ws + "/" + host_id;
95 $http.get(url).then(function(res){
96 deferred.resolve(res.data);
97 }, function(){
98 deferred.reject();
99 });
100 return deferred.promise;
101 };
102
103 dashboardSrv.getServicesByHost = function(ws, host_id) {
104 var deferred = $q.defer();
105 var url = BASEURL + "/" + ws + "/_design/services/_view/byhost?key=\"" + host_id + "\"";
106 dashboardSrv._getView(url).then(function(res){
107 var tmp = [];
108 res.forEach(function(service){
109 var _service = service.value;
110 _service["id"] = service.id;
111 _service["port"] = _service.ports[0];
112 tmp.push(_service);
113 });
114 deferred.resolve(tmp);
115 }, function(){
116 deferred.reject();
117 });
118 return deferred.promise;
119 }
120
121 dashboardSrv.getHostsByServicesName = function(ws, srv_name) {
122 var deferred = $q.defer();
123 var url = BASEURL + "/" + ws + "/_design/services/_view/byname?key=\"" + srv_name + "\"";
124 dashboardSrv._getView(url).then(function(res){
125 var dict = {};
126 var tmp = [];
127 res.forEach(function(srv){
128 tmp.push(dashboardSrv.getHost(ws, srv.value.hid));
129 });
130 $q.all(tmp).then(function(hosts){
131 var res = [];
132 hosts.sort(function(a, b){
133 if(a.name < b.name) return -1;
134 if(a.name > b.name) return 1;
135 return 0;
136 });
137 for (var i = 0; i < hosts.length; i++){
138 if (res.length == 0 || hosts[i].name != res[res.length - 1].name) {
139 res.push(hosts[i]);
140 }
141 }
142 deferred.resolve(res);
143 });
144 }, function(){
145 deferred.reject();
146 });
147 return deferred.promise;
148 };
149
150 dashboardSrv.getName = function(ws, id) {
151 var deferred = $q.defer();
152 url = BASEURL + "/" + ws + "/" + id;
153
154 $http.get(url).then(function(response){
155 res = response.data.name;
156 deferred.resolve(res);
157 }, function(){
158 deferred.reject();
159 });
160
161 return deferred.promise;
162 };
163
164
165 dashboardSrv.accumulate = function(_array, key, value) {
166 _array.forEach(function(obj){
167 if(obj.key == key) {
168 obj.value += value;
169 }
170 });
171 };
172
173 return dashboardSrv;
174 }]);
+0
-166
views/reports/_attachments/scripts/dashboard/services/dashboard.js less more
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('dashboardSrv', ['BASEURL', '$q', '$http', function(BASEURL, $q, $http) {
6 var dashboardSrv = {};
7
8 dashboardSrv._getView = function(url) {
9 var deferred = $q.defer();
10
11 $http.get(url).then(function(response){
12 res = response.data.rows;
13 deferred.resolve(res);
14 }, function(){
15 deferred.reject();
16 });
17
18 return deferred.promise;
19 };
20
21 dashboardSrv.getHostsByServicesCount = function(ws, id) {
22 var url = BASEURL + "/" + ws + "/_design/hosts/_view/byservicecount?group=true";
23 if (id != undefined){
24 url += "&key=\"" + id + "\"";
25 }
26 return dashboardSrv._getView(url);
27 };
28
29 dashboardSrv.getServicesCount = function(ws) {
30 var url = BASEURL + "/" + ws + "/_design/hosts/_view/byservices?group=true";
31 return dashboardSrv._getView(url);
32 };
33
34 dashboardSrv.getVulnerabilities = function(ws) {
35 var url = BASEURL + "/" + ws + "/_design/vulns/_view/all";
36 return dashboardSrv._getView(url);
37 };
38
39 dashboardSrv.getVulnerabilitiesCount = function(ws) {
40 var url = BASEURL + "/" + ws + "/_design/hosts/_view/vulns?group=true";
41 return dashboardSrv._getView(url);
42 };
43
44 dashboardSrv.getObjectsCount = function(ws) {
45 var url = BASEURL + "/" + ws + "/_design/hosts/_view/summarized?group=true";
46 return dashboardSrv._getView(url);
47 };
48
49 dashboardSrv.getCommands = function(ws) {
50 var deferred = $q.defer();
51 var url = BASEURL + "/" + ws + "/_design/commands/_view/list";
52 dashboardSrv._getView(url).then(function(res){
53 var tmp = [];
54 res.forEach(function(cmd){
55 var _cmd = cmd.value;
56 _cmd["command"] = cmd.key;
57 tmp.push(_cmd);
58 });
59 deferred.resolve(tmp);
60 }, function(){
61 deferred.reject();
62 });
63 return deferred.promise;
64 };
65
66 dashboardSrv.getHosts = function(ws) {
67 var deferred = $q.defer();
68 var url = BASEURL + "/" + ws + "/_design/hosts/_view/hosts";
69 dashboardSrv._getView(url).then(function(res){
70 var tmp = [];
71 res.forEach(function(host){
72 var _host = host.value;
73 _host["id"] = host.key;
74 tmp.push(_host);
75 });
76 deferred.resolve(tmp);
77 }, function(){
78 deferred.reject();
79 });
80 return deferred.promise;
81 };
82
83 dashboardSrv.getHost = function(ws, host_id) {
84 var deferred = $q.defer();
85 var url = BASEURL + "/" + ws + "/" + host_id;
86 $http.get(url).then(function(res){
87 deferred.resolve(res.data);
88 }, function(){
89 deferred.reject();
90 });
91 return deferred.promise;
92 };
93
94 dashboardSrv.getServicesByHost = function(ws, host_id) {
95 var deferred = $q.defer();
96 var url = BASEURL + "/" + ws + "/_design/services/_view/byhost?key=\"" + host_id + "\"";
97 dashboardSrv._getView(url).then(function(res){
98 var tmp = [];
99 res.forEach(function(service){
100 var _service = service.value;
101 _service["id"] = service.id;
102 _service["port"] = _service.ports[0];
103 tmp.push(_service);
104 });
105 deferred.resolve(tmp);
106 }, function(){
107 deferred.reject();
108 });
109 return deferred.promise;
110 }
111
112 dashboardSrv.getHostsByServicesName = function(ws, srv_name) {
113 var deferred = $q.defer();
114 var url = BASEURL + "/" + ws + "/_design/services/_view/byname?key=\"" + srv_name + "\"";
115 dashboardSrv._getView(url).then(function(res){
116 var dict = {};
117 var tmp = [];
118 res.forEach(function(srv){
119 tmp.push(dashboardSrv.getHost(ws, srv.value.hid));
120 });
121 $q.all(tmp).then(function(hosts){
122 var res = [];
123 hosts.sort(function(a, b){
124 if(a.name < b.name) return -1;
125 if(a.name > b.name) return 1;
126 return 0;
127 });
128 for (var i = 0; i < hosts.length; i++){
129 if (res.length == 0 || hosts[i].name != res[res.length - 1].name) {
130 res.push(hosts[i]);
131 }
132 }
133 deferred.resolve(res);
134 });
135 }, function(){
136 deferred.reject();
137 });
138 return deferred.promise;
139 };
140
141 dashboardSrv.getName = function(ws, id) {
142 var deferred = $q.defer();
143 url = BASEURL + "/" + ws + "/" + id;
144
145 $http.get(url).then(function(response){
146 res = response.data.name;
147 deferred.resolve(res);
148 }, function(){
149 deferred.reject();
150 });
151
152 return deferred.promise;
153 };
154
155
156 dashboardSrv.accumulate = function(_array, key, value) {
157 _array.forEach(function(obj){
158 if(obj.key == key) {
159 obj.value += value;
160 }
161 });
162 };
163
164 return dashboardSrv;
165 }]);
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('$blob', function() {
6 return {
7 fileToURL: function(content, t) {
8 var blob;
9 blob = new Blob([content], {type: t});
10 return (window.URL || window.webkitURL).createObjectURL(blob);
11 },
12 sanitizeFileName: function(name, extension) {
13 var nameRegExp = new RegExp("^[A-Za-z0-9_-]+$");
14 var extRegExp = new RegExp("^[A-Za-z]+$");
15 if(nameRegExp.test(name) && extRegExp.test(extension)) {
16 return "Faraday-" + name + "." + extension;
17 }
18 throw new Error("Invalid title or extension for file: " + name + "." + extension);
19 },
20 sanitizeFileType: function(type) {
21 var patt = new RegExp("^[a-z]+/[a-z+.-]+$");
22 if(patt.test(type)) {
23 return name;
24 }
25 throw new Error("Invalid type for file: " + type);
26 },
27 revoke: function(url) {
28 return (window.URL || window.webkitURL).revokeObjectURL(url);
29 }
30 };
31 });
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('$click', function() {
6 return {
7 on: function(element) {
8 var e = document.createEvent("MouseEvent");
9 e.initMouseEvent("click", false, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
10 element.dispatchEvent(e);
11 }
12 };
13 });
+0
-32
views/reports/_attachments/scripts/fileExporter/services/blob.js less more
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('$blob', function() {
6 return {
7 fileToURL: function(content, t) {
8 var blob;
9 blob = new Blob([content], {type: t});
10 return (window.URL || window.webkitURL).createObjectURL(blob);
11 },
12 sanitizeFileName: function(name, extension) {
13 var nameRegExp = new RegExp("^[A-Za-z0-9_-]+$");
14 var extRegExp = new RegExp("^[A-Za-z]+$");
15 if(nameRegExp.test(name) && extRegExp.test(extension)) {
16 return "Faraday-" + name + "." + extension;
17 }
18 throw new Error("Invalid title or extension for file: " + name + "." + extension);
19 },
20 sanitizeFileType: function(type) {
21 var patt = new RegExp("^[a-z]+/[a-z+.-]+$");
22 if(patt.test(type)) {
23 return name;
24 }
25 throw new Error("Invalid type for file: " + type);
26 },
27 revoke: function(url) {
28 return (window.URL || window.webkitURL).revokeObjectURL(url);
29 }
30 };
31 });
+0
-14
views/reports/_attachments/scripts/fileExporter/services/click.js less more
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('$click', function() {
6 return {
7 on: function(element) {
8 var e = document.createEvent("MouseEvent");
9 e.initMouseEvent("click", false, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
10 element.dispatchEvent(e);
11 }
12 };
13 });
33
44 angular.module('faradayApp')
55 .controller('hostCtrl',
6 ['$scope', '$filter', '$route', '$routeParams', '$modal', 'hostsManager', 'statusReportFact', 'dashboardSrv', 'servicesManager',
7 function($scope, $filter, $route, $routeParams, $modal, hostsManager, statusReportFact, dashboardSrv, servicesManager) {
6 ['$scope', '$filter', '$route', '$routeParams', '$modal', 'hostsManager', 'workspacesFact', 'dashboardSrv', 'servicesManager',
7 function($scope, $filter, $route, $routeParams, $modal, hostsManager, workspacesFact, dashboardSrv, servicesManager) {
88
99
1010 init = function() {
1414 //ID of current host
1515 var hostId = $routeParams.hidId;
1616 // load all workspaces
17 statusReportFact.getWorkspaces().then(function(wss) {
17 workspacesFact.list().then(function(wss) {
1818 $scope.workspaces = wss;
1919 });
2020 // current host
9393 controller: 'serviceModalEdit',
9494 size: 'lg',
9595 resolve: {
96 service: function(){
96 service: function() {
9797 return selected_service;
9898 },
9999 services: function() {
187187 });
188188 };
189189
190 $scope.checkAllServices = function() {
191 $scope.selectall = !$scope.selectall;
192
193 angular.forEach($filter('filter')($scope.services, $scope.query), function(service) {
194 service.selected = $scope.selectall;
195 });
196 };
197
190198 // toggles sort field and order
191199 $scope.toggleSort = function(field) {
192200 $scope.toggleSortField(field);
204212 }
205213
206214 init();
207 }]);
215 }]);
33
44 angular.module('faradayApp')
55 .controller('hostsCtrl',
6 ['$scope', '$filter', '$route', '$routeParams', '$modal', 'hostsManager', 'statusReportFact',
7 function($scope, $filter, $route, $routeParams, $modal, hostsManager, statusReportFact) {
6 ['$scope', '$filter', '$route', '$routeParams', '$modal', 'hostsManager', 'workspacesFact',
7 function($scope, $filter, $route, $routeParams, $modal, hostsManager, workspacesFact) {
88
99 init = function() {
1010 $scope.selectall = false;
1313 // current workspace
1414 $scope.workspace = $routeParams.wsId;
1515 // load all workspaces
16 statusReportFact.getWorkspaces().then(function(wss) {
16 workspacesFact.list().then(function(wss) {
1717 $scope.workspaces = wss;
1818 });
1919
22 <!-- See the file 'doc/LICENSE' for the license information -->
33
44 <form name="form" novalidate>
5 <div class="modal-header">
6 <div class="modal-button">
7 <button class="btn btn-success" ng-click="ok()" ng-disabled="form.$invalid">OK</button>
8 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
5 <div class="modal-header">
6 <div class="modal-button">
7 <button class="btn btn-success" ng-click="ok()" ng-disabled="form.$invalid">OK</button>
8 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
9 </div>
10 <h3 class="modal-title">Edit host</h3>
911 </div>
10 <h3 class="modal-title">Edit host</h3>
11 </div>
12 <div class="modal-body">
13 <div class="form-horizontal">
14 <div class="form-group">
15 <div class="col-md-12">
16 <label class="sr-only" for="name">Name</label>
17 <input type="text" class="form-control" id="name" placeholder="Name" ng-model="host.name" required/>
18 <span class="help-block normal-size">
19 Example: 192.168.0.1
20 </span>
21 </div>
22 </div><!-- .form-group -->
23 <div class="form-group">
24 <div class="col-md-12">
25 <label class="sr-only" for="description">Description</label>
26 <textarea class="form-control" id="description" placeholder="Description" ng-model="host.description"></textarea>
27 </div>
28 </div><!-- .form-group -->
29 <div class="form-group">
30 <div class="col-md-12">
31 <label class="sr-only" for="os">Operating System</label>
32 <input type="text" class="form-control" id="os" placeholder="Operating System" ng-model="host.os"/>
33 <span class="help-block normal-size">
34 Example: Linux 3.18.6-1-ARCH
35 </span>
36 </div>
37 </div><!-- .form-group -->
38 <div class="form-group">
39 <div class="col-md-12">
40 <div class="checkbox">
41 <label>
42 <input type="checkbox" id="owned" ng-model="host.owned"/>
43 <span class="normal-size">Owned</span>
44 </label>
45 </div><!-- .checkbox -->
46 </div>
47 </div><!-- .form-group -->
48 <div class="form-group">
49 <div class="col-md-12">
50 <h5>Hostnames</h5>
51 <span class="input-group-addon button-radius" ng-click="newHostnames($event)">Add Hostname</span>
52 </div>
53 <div class="col-md-12 input-margin" ng-repeat="hostname in interface.hostnames">
54 <div class="input-group margin-bottom-sm col-md-12">
55 <label class="sr-only" for="hostsnames">Hostname</label>
56 <input type="text" class="form-control" id="hostsnames" placeholder="Hostname" ng-model="hostname.key"/>
57 <span class="input-group-addon" ng-click="interface.hostnames.splice($index, 1)" ng-hide="interface.hostnames.length == 1"><i class="fa fa-minus-circle"></i></span>
12 <div class="modal-body">
13 <div class="form-horizontal">
14 <div class="form-group">
15 <div class="col-md-12">
16 <label class="sr-only" for="name">Name</label>
17 <input type="text" class="form-control" id="name" placeholder="Name" ng-model="host.name" required/>
18 <span class="help-block normal-size">
19 Example: 192.168.0.1
20 </span>
5821 </div>
59 </div>
60 </div><!-- .form-group -->
61 <div class="form-group">
62 <div class="col-md-6">
63 <label class="sr-only" for="ipv4">IP v4</label>
64 <input type="text" class="form-control" id="ipv4" placeholder="IP v4" ng-model="interface.ipv4.address"/>
65 </div>
66 <div class="col-md-6">
67 <label class="sr-only" for="ipv6">IP v6</label>
68 <input type="text" class="form-control" id="ipv6" placeholder="IP v6" ng-model="interface.ipv6.address"/>
69 </div>
70 </div><!-- .form-group -->
71 <div class="form-group">
72 <div class="col-md-12">
73 <label class="sr-only" for="mac">MAC</label>
74 <input type="text" class="form-control" id="mac" placeholder="MAC" ng-model="interface.mac"/>
75 </div>
76 </div><!-- .form-group -->
22 </div><!-- .form-group -->
23 <div class="form-group">
24 <div class="col-md-12">
25 <label class="sr-only" for="description">Description</label>
26 <textarea class="form-control" id="description" placeholder="Description" ng-model="host.description"></textarea>
27 </div>
28 </div><!-- .form-group -->
29 <div class="form-group">
30 <div class="col-md-12">
31 <label class="sr-only" for="os">Operating System</label>
32 <input type="text" class="form-control" id="os" placeholder="Operating System" ng-model="host.os"/>
33 <span class="help-block normal-size">
34 Example: Linux 3.18.6-1-ARCH
35 </span>
36 </div>
37 </div><!-- .form-group -->
38 <div class="form-group">
39 <div class="col-md-12">
40 <div class="checkbox">
41 <label>
42 <input type="checkbox" id="owned" ng-model="host.owned"/>
43 <span class="normal-size">Owned</span>
44 </label>
45 </div><!-- .checkbox -->
46 </div>
47 </div><!-- .form-group -->
48 <div class="form-group">
49 <div class="col-md-12">
50 <h5>Hostnames</h5>
51 <span class="input-group-addon button-radius" ng-click="newHostnames($event)">Add Hostname</span>
52 </div>
53 <div class="col-md-12 input-margin" ng-repeat="hostname in interface.hostnames">
54 <div class="input-group margin-bottom-sm col-md-12">
55 <label class="sr-only" for="hostsnames">Hostname</label>
56 <input type="text" class="form-control" id="hostsnames" placeholder="Hostname" ng-model="hostname.key"/>
57 <span class="input-group-addon" ng-click="interface.hostnames.splice($index, 1)" ng-hide="interface.hostnames.length == 1"><i class="fa fa-minus-circle"></i></span>
58 </div>
59 </div>
60 </div><!-- .form-group -->
61 <div class="form-group">
62 <div class="col-md-6">
63 <label class="sr-only" for="ipv4">IP v4</label>
64 <input type="text" class="form-control" id="ipv4" placeholder="IP v4" ng-model="interface.ipv4.address"/>
65 </div>
66 <div class="col-md-6">
67 <label class="sr-only" for="ipv6">IP v6</label>
68 <input type="text" class="form-control" id="ipv6" placeholder="IP v6" ng-model="interface.ipv6.address"/>
69 </div>
70 </div><!-- .form-group -->
71 <div class="form-group">
72 <div class="col-md-12">
73 <label class="sr-only" for="mac">MAC</label>
74 <input type="text" class="form-control" id="mac" placeholder="MAC" ng-model="interface.mac"/>
75 </div>
76 </div><!-- .form-group -->
77 </div>
78 </div><!-- .modal-body -->
79 <div class="modal-footer">
80 <div class="modal-button">
81 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
82 <button class="btn btn-success" ng-disabled="form.$invalid" ng-click="ok()">OK</button>
83 </div>
7784 </div>
78 </div><!-- .modal-body -->
79 <div class="modal-footer">
80 <div class="modal-button">
81 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
82 <button class="btn btn-success" ng-disabled="form.$invalid" ng-click="ok()">OK</button>
83 </div>
84 </div>
8585 </form>
22 <!-- See the file 'doc/LICENSE' for the license information -->
33
44 <form name="form" novalidate>
5 <div class="modal-header">
6 <div class="modal-button">
7 <button class="btn btn-success" ng-click="ok()" ng-disabled="form.$invalid">OK</button>
8 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
5 <div class="modal-header">
6 <div class="modal-button">
7 <button class="btn btn-success" ng-click="ok()" ng-disabled="form.$invalid">OK</button>
8 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
9 </div>
10 <h3 class="modal-title">New host</h3>
911 </div>
10 <h3 class="modal-title">New host</h3>
11 </div>
12 <div class="modal-body">
13 <div class="form-horizontal">
14 <div class="form-group">
15 <div class="col-md-12">
16 <label class="sr-only" for="name">Name</label>
17 <input type="text" class="form-control" id="name" placeholder="Name" ng-model="hostdata.name" required/>
18 <span class="help-block normal-size">
19 Example: 192.168.0.1
20 </span>
21 </div>
22 </div><!-- .form-group -->
23 <div class="form-group">
24 <div class="col-md-12">
25 <label class="sr-only" for="description">Description</label>
26 <textarea class="form-control" id="description" placeholder="Description" ng-model="hostdata.description"></textarea>
27 </div>
28 </div><!-- .form-group -->
29 <div class="form-group">
30 <div class="col-md-12">
31 <label class="sr-only" for="os">Operating System</label>
32 <input type="text" class="form-control" id="os" placeholder="Operating System" ng-model="hostdata.os"/>
33 <span class="help-block normal-size">
34 Example: Linux 3.18.6-1-ARCH
35 </span>
36 </div>
37 </div><!-- .form-group -->
38 <div class="form-group">
39 <div class="col-md-12">
40 <div class="checkbox">
41 <label>
42 <input type="checkbox" id="owned" ng-model="hostdata.owned"/>
43 <span class="normal-size">Owned</span>
44 </label>
45 </div><!-- .checkbox -->
46 </div>
47 </div><!-- .form-group -->
48 <div class="form-group">
49 <div class="col-md-12">
50 <h5>Hostnames</h5>
51 <span class="input-group-addon button-radius" ng-click="newHostnames($event)">Add Hostname</span>
52 </div>
53 <div class="col-md-12 input-margin" ng-repeat="hostname in interfaceData.hostnames">
54 <div class="input-group margin-bottom-sm col-md-12">
55 <label class="sr-only" for="hostsnames">Hostname</label>
56 <input type="text" class="form-control" id="hostsnames" placeholder="Hostname" ng-model="hostname.hostname"/>
57 <span class="input-group-addon" ng-click="interfaceData.hostnames.splice($index, 1)" ng-hide="interfaceData.hostnames.length == 1"><i class="fa fa-minus-circle"></i></span>
12 <div class="modal-body">
13 <div class="form-horizontal">
14 <div class="form-group">
15 <div class="col-md-12">
16 <label class="sr-only" for="name">Name</label>
17 <input type="text" class="form-control" id="name" placeholder="Name" ng-model="hostdata.name" required/>
18 <span class="help-block normal-size">
19 Example: 192.168.0.1
20 </span>
5821 </div>
59 </div>
60 </div><!-- .form-group -->
61 <div class="form-group">
62 <div class="col-md-6">
63 <label class="sr-only" for="ipv4">IP v4</label>
64 <input type="text" class="form-control" id="ipv4" placeholder="IP v4" ng-model="interfaceData.ipv4" ng-required="!interfaceData.ipv6"/>
65 </div>
66 <div class="col-md-6">
67 <label class="sr-only" for="ipv6">IP v6</label>
68 <input type="text" class="form-control" id="ipv6" placeholder="IP v6" ng-model="interfaceData.ipv6" ng-required="!interfaceData.ipv4"/>
69 </div>
70 </div><!-- .form-group -->
71 <div class="form-group">
72 <div class="col-md-12">
73 <label class="sr-only" for="mac">MAC</label>
74 <input type="text" class="form-control" id="mac" placeholder="MAC" ng-model="interfaceData.mac"/>
75 </div>
76 </div><!-- .form-group -->
22 </div><!-- .form-group -->
23 <div class="form-group">
24 <div class="col-md-12">
25 <label class="sr-only" for="description">Description</label>
26 <textarea class="form-control" id="description" placeholder="Description" ng-model="hostdata.description"></textarea>
27 </div>
28 </div><!-- .form-group -->
29 <div class="form-group">
30 <div class="col-md-12">
31 <label class="sr-only" for="os">Operating System</label>
32 <input type="text" class="form-control" id="os" placeholder="Operating System" ng-model="hostdata.os"/>
33 <span class="help-block normal-size">
34 Example: Linux 3.18.6-1-ARCH
35 </span>
36 </div>
37 </div><!-- .form-group -->
38 <div class="form-group">
39 <div class="col-md-12">
40 <div class="checkbox">
41 <label>
42 <input type="checkbox" id="owned" ng-model="hostdata.owned"/>
43 <span class="normal-size">Owned</span>
44 </label>
45 </div><!-- .checkbox -->
46 </div>
47 </div><!-- .form-group -->
48 <div class="form-group">
49 <div class="col-md-12">
50 <h5>Hostnames</h5>
51 <span class="input-group-addon button-radius" ng-click="newHostnames($event)">Add Hostname</span>
52 </div>
53 <div class="col-md-12 input-margin" ng-repeat="hostname in interfaceData.hostnames">
54 <div class="input-group margin-bottom-sm col-md-12">
55 <label class="sr-only" for="hostsnames">Hostname</label>
56 <input type="text" class="form-control" id="hostsnames" placeholder="Hostname" ng-model="hostname.hostname"/>
57 <span class="input-group-addon" ng-click="interfaceData.hostnames.splice($index, 1)" ng-hide="interfaceData.hostnames.length == 1"><i class="fa fa-minus-circle"></i></span>
58 </div>
59 </div>
60 </div><!-- .form-group -->
61 <div class="form-group">
62 <div class="col-md-6">
63 <label class="sr-only" for="ipv4">IP v4</label>
64 <input type="text" class="form-control" id="ipv4" placeholder="IP v4" ng-model="interfaceData.ipv4" ng-required="!interfaceData.ipv6"/>
65 </div>
66 <div class="col-md-6">
67 <label class="sr-only" for="ipv6">IP v6</label>
68 <input type="text" class="form-control" id="ipv6" placeholder="IP v6" ng-model="interfaceData.ipv6" ng-required="!interfaceData.ipv4"/>
69 </div>
70 </div><!-- .form-group -->
71 <div class="form-group">
72 <div class="col-md-12">
73 <label class="sr-only" for="mac">MAC</label>
74 <input type="text" class="form-control" id="mac" placeholder="MAC" ng-model="interfaceData.mac"/>
75 </div>
76 </div><!-- .form-group -->
77 </div>
78 </div><!-- .modal-body -->
79 <div class="modal-footer">
80 <div class="modal-button">
81 <button class="btn btn-success" ng-disabled="form.$invalid" ng-click="ok()">OK</button>
82 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
83 </div>
7784 </div>
78 </div><!-- .modal-body -->
79 <div class="modal-footer">
80 <div class="modal-button">
81 <button class="btn btn-success" ng-disabled="form.$invalid" ng-click="ok()">OK</button>
82 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
83 </div>
84 </div>
8585 </form>
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('Host', ['BASEURL', '$http', function(BASEURL, $http) {
6 Host = function(data){
7 if(data) {
8 this.set(data);
9 }
10 };
11
12 Host.prototype = {
13 // TODO: instead of using angular.extend, we should check
14 // the attributes we're assigning to the host
15 set: function(data) {
16 // if there's no ID, we need to generate it based on the host name
17 if(data._id === undefined){
18 data['_id'] = CryptoJS.SHA1(data.name).toString();
19 }
20 data.type = "Host";
21 angular.extend(this, data);
22 },
23 delete: function(ws) {
24 var self = this,
25 bulk = {docs:[]};
26 return $http.get(BASEURL + ws + '/_all_docs?startkey="' + self._id + '"&endkey="' + self._id + '.z"').then(function(all) {
27 all.data.rows.forEach(function(row) {
28 bulk.docs.push({
29 "_id": row.id,
30 "_rev": row.value.rev,
31 "_deleted": true
32 });
33 });
34
35 return $http.post(BASEURL + ws + "/_bulk_docs", JSON.stringify(bulk));
36 });
37 },
38 update: function(data, interfaceData, ws) {
39 var self = this;
40 bulk = {docs:[data,interfaceData]};
41 return $http.post(BASEURL + ws + "/_bulk_docs", JSON.stringify(bulk)).success(function(data){
42 if(data.id == self._id){
43 self._rev = data.rev;
44 } else {
45 interfaceData._rev = data.rev;
46 }
47 });
48 },
49 save: function(ws, interfaceData) {
50 var self = this;
51 bulk = {docs:[self,interfaceData]};
52 return $http.post(BASEURL + ws + "/_bulk_docs", JSON.stringify(bulk)).success(function(data){
53 if(data.id == self._id){
54 self._rev = data.rev;
55 } else {
56 interfaceData._rev = data.rev;
57 }
58 });
59 }
60 }
61
62 return Host;
63 }]);
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('hostsManager', ['BASEURL', '$http', '$q', 'Host', function(BASEURL, $http, $q, Host) {
6 var hostsManager = {};
7
8 hostsManager._objects = {};
9
10 hostsManager._get = function(id, data) {
11 var host = this._objects[id];
12
13 if(host) {
14 host.set(data);
15 } else {
16 host = new Host(data);
17 this._objects[id] = host;
18 }
19
20 return host;
21 };
22
23 hostsManager._search = function(id) {
24 return this._objects[id];
25 };
26
27 hostsManager._load = function(id, ws, deferred) {
28 var self = this;
29 $http.get(BASEURL + ws + '/' + id)
30 .success(function(data){
31 var host = self._get(data._id, data);
32 deferred.resolve(host);
33 })
34 .error(function(){
35 deferred.reject();
36 });
37 };
38
39 hostsManager.getHost = function(id, ws, force_reload) {
40 var deferred = $q.defer(),
41 host = this._search(id);
42 force_reload = force_reload || false;
43
44 if((host) && (!force_reload)) {
45 deferred.resolve(host);
46 } else {
47 this._load(id, ws, deferred);
48 }
49
50 return deferred.promise;
51 };
52
53 hostsManager.getHosts = function(ws) {
54 var deferred = $q.defer();
55 var self = this;
56 this._objects = {};
57
58 $http.get(BASEURL + ws + '/_design/hosts/_view/hosts')
59 .success(function(hostsArray) {
60 var hosts = [];
61 hostsArray.rows.forEach(function(hostData) {
62 var host = self._get(hostData.value._id, hostData.value);
63 hosts.push(host);
64 });
65 deferred.resolve(hosts);
66 })
67 .error(function() {
68 deferred.reject();
69 });
70 return deferred.promise;
71 };
72
73 hostsManager.deleteHost = function(id, ws) {
74 var deferred = $q.defer();
75 var self = this;
76 this.getHost(id, ws)
77 .then(function(host) {
78 host.delete(ws)
79 .then(function() {
80 delete self._objects[id];
81 deferred.resolve();
82 })
83 .catch(function() {
84 // host couldn't be deleted
85 deferred.reject("Error deleting host");
86 });
87 })
88 .catch(function() {
89 // host doesn't exist
90 deferred.reject("Host doesn't exist");
91 });
92 return deferred.promise;
93 };
94
95 hostsManager.createHost = function(hostData, interfaceData, ws) {
96 var deferred = $q.defer();
97 var self = this;
98
99 this.getHosts(ws)
100 .then(function(hosts) {
101 var host = new Host(hostData);
102 self.getHost(host._id, ws)
103 .then(function() {
104 deferred.reject("Host already exists");
105 })
106 .catch(function() {
107 // host doesn't exist, good to go
108 host.save(ws, interfaceData)
109 .then(function() {
110 host = self.getHost(host._id, ws);
111 deferred.resolve(host);
112 })
113 .catch(function() {
114 deferred.reject("Error: host couldn't be saved");
115 })
116 });
117 })
118 .catch(function() {
119 deferred.reject("Error creating host");
120 });
121
122 return deferred.promise;
123 };
124
125 hostsManager.updateHost = function(host, hostData, interfaceData, ws) {
126 var deferred = $q.defer(),
127 self = this;
128
129 this.getHost(host._id, ws)
130 .then(function(resp) {
131 resp.update(hostData, interfaceData, ws)
132 .then(function() {
133 // reload the host to update _rev
134 host = self._load(host._id, ws, deferred);
135 deferred.resolve(host);
136 })
137 .catch(function() {
138 deferred.reject("Error updating host");
139 });
140 })
141 .catch(function() {
142 // host doesn't exist
143 deferred.reject("Host doesn't exist");
144 });
145
146 return deferred.promise;
147 };
148
149 hostsManager.getAllInterfaces = function(ws) {
150 var deferred = $q.defer(),
151 self = this;
152
153 var url = BASEURL + ws + '/_design/interfaces/_view/interfaces';
154
155 $http.get(url)
156 .success(function(ints) {
157 var interfaces = [];
158
159 ints.rows.forEach(function(interf) {
160 interfaces.push(interf.value);
161 });
162
163 deferred.resolve(interfaces);
164 })
165 .error(function() {
166 deferred.reject("Unable to retrieve Interfaces");
167 });
168
169 return deferred.promise;
170 };
171
172 hostsManager.getInterfaces = function(ws, id) {
173 var deferred = $q.defer(),
174 self = this;
175
176 var url = BASEURL + ws + '/_design/interfaces/_view/interfaces?key=\"' + id + '\"';
177
178 $http.get(url)
179 .success(function(interfaces) {
180 deferred.resolve(interfaces.rows);
181 })
182 .error(function() {
183 deferred.reject("Unable to retrieve Interfaces for Host " + id);
184 });
185
186 return deferred.promise;
187 };
188
189 return hostsManager;
190 }]);
+0
-64
views/reports/_attachments/scripts/hosts/services/host.js less more
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('Host', ['BASEURL', '$http', function(BASEURL, $http) {
6 Host = function(data){
7 if(data) {
8 this.set(data);
9 }
10 };
11
12 Host.prototype = {
13 // TODO: instead of using angular.extend, we should check
14 // the attributes we're assigning to the host
15 set: function(data) {
16 // if there's no ID, we need to generate it based on the host name
17 if(data._id === undefined){
18 data['_id'] = CryptoJS.SHA1(data.name).toString();
19 }
20 data.type = "Host";
21 angular.extend(this, data);
22 },
23 delete: function(ws) {
24 var self = this,
25 bulk = {docs:[]};
26 return $http.get(BASEURL + ws + '/_all_docs?startkey="' + self._id + '"&endkey="' + self._id + '.z"').then(function(all) {
27 all.data.rows.forEach(function(row) {
28 bulk.docs.push({
29 "_id": row.id,
30 "_rev": row.value.rev,
31 "_deleted": true
32 });
33 });
34
35 return $http.post(BASEURL + ws + "/_bulk_docs", JSON.stringify(bulk));
36 });
37 },
38 update: function(data, interfaceData, ws) {
39 var self = this;
40 bulk = {docs:[data,interfaceData]};
41 return $http.post(BASEURL + ws + "/_bulk_docs", JSON.stringify(bulk)).success(function(data){
42 if(data.id == self._id){
43 self._rev = data.rev;
44 } else {
45 interfaceData._rev = data.rev;
46 }
47 });
48 },
49 save: function(ws, interfaceData) {
50 var self = this;
51 bulk = {docs:[self,interfaceData]};
52 return $http.post(BASEURL + ws + "/_bulk_docs", JSON.stringify(bulk)).success(function(data){
53 if(data.id == self._id){
54 self._rev = data.rev;
55 } else {
56 interfaceData._rev = data.rev;
57 }
58 });
59 }
60 }
61
62 return Host;
63 }]);
+0
-170
views/reports/_attachments/scripts/hosts/services/hosts.js less more
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('hostsManager', ['BASEURL', '$http', '$q', 'Host', function(BASEURL, $http, $q, Host) {
6 var hostsManager = {};
7
8 hostsManager._objects = {};
9 hostsManager._get = function(id, data) {
10 var host = this._objects[id];
11
12 if(host) {
13 host.set(data);
14 } else {
15 host = new Host(data);
16 this._objects[id] = host;
17 }
18
19 return host;
20 }
21
22 hostsManager._search = function(id) {
23 return this._objects[id];
24 }
25
26 hostsManager._load = function(id, ws, deferred) {
27 var self = this;
28 $http.get(BASEURL + '/' + ws + '/' + id)
29 .success(function(data){
30 var host = self._get(data._id, data);
31 deferred.resolve(host);
32 })
33 .error(function(){
34 deferred.reject();
35 });
36 }
37
38 hostsManager.getHost = function(id, ws, force_reload) {
39 var deferred = $q.defer();
40 var host = this._search(id);
41 force_reload = force_reload || false;
42 if((host) && (!force_reload)) {
43 deferred.resolve(host);
44 } else {
45 this._load(id, ws, deferred);
46 }
47 return deferred.promise;
48 }
49
50 // async method - this is the one to use from now on!
51 hostsManager.getHosts = function(ws) {
52 var deferred = $q.defer();
53 var self = this;
54 $http.get(BASEURL + '/' + ws + '/_design/hosts/_view/hosts')
55 .success(function(hostsArray){
56 var hosts = [];
57 hostsArray.rows.forEach(function(hostData){
58 var host = self._get(hostData.value._id, hostData.value);
59 hosts.push(host);
60 });
61 deferred.resolve(hosts);
62 })
63 .error(function(){
64 deferred.reject();
65 })
66 return deferred.promise;
67 }
68
69 // sync method - still used in statusReportFact
70 hostsManager.get = function(ws) {
71 hosts_url = BASEURL + ws + "/_design/hosts/_view/hosts";
72 var hosts = [];
73 //gets hosts json from couch
74 $.getJSON(hosts_url, function(data) {
75 $.each(data.rows, function(n, obj) {
76 hosts[obj.id] = {
77 "categories": obj.value.categories,
78 "default_gateway": obj.value.default_gateway,
79 "description": obj.value.description,
80 "metadata": obj.value.metadata,
81 "name": obj.value.name,
82 "os": obj.value.os,
83 "owned": obj.value.owned,
84 "owner": obj.value.owner
85 };
86 });
87 });
88 return hosts;
89 }
90
91 hostsManager.deleteHost = function(id, ws) {
92 var deferred = $q.defer();
93 var self = this;
94 this.getHost(id, ws).then(function(host) {
95 host.delete(ws).then(function() {
96 delete self._objects[id];
97 deferred.resolve();
98 }, function(){
99 // host couldn't be deleted
100 deferred.reject("Error deleting host");
101 });
102 }, function(){
103 // host doesn't exist
104 deferred.reject("Host doesn't exist");
105 });
106 return deferred.promise;
107 }
108
109 hostsManager.createHost = function(hostData, interfaceData, ws) {
110 var deferred = $q.defer();
111 var self = this;
112
113 this.getHosts(ws).then(function(hosts) {
114 var host = new Host(hostData);
115 self.getHost(host._id, ws).then(function() {
116 deferred.reject("Host already exists");
117 }, function() {
118 // host doesn't exist, good to go
119 host.save(ws, interfaceData).then(function(){
120 host = self.getHost(host._id, ws);
121 deferred.resolve(host);
122 }, function(){
123 // host couldn't be saved
124 deferred.reject("Error: host couldn't be saved");
125 })
126 });
127 });
128
129 return deferred.promise;
130 }
131
132 hostsManager.updateHost = function(host, hostData, interfaceData, ws) {
133 var deferred = $q.defer();
134 var self = this;
135 this.getHost(host._id, ws).then(function(resp) {
136 resp.update(hostData, interfaceData, ws).then(function() {
137 // we need to reload the host in order
138 // to update _rev
139 host = self._load(host._id, ws, deferred);
140 deferred.resolve(host);
141 })
142 }, function(){
143 // host doesn't exist
144 deferred.reject("Host doesn't exist");
145 });
146 return deferred.promise;
147 }
148
149 hostsManager.getInterfaces = function(ws, hostId){
150 var deferred = $q.defer();
151 var self = this;
152 if(hostId) {
153 var url = BASEURL + '/' + ws + '/_design/interfaces/_view/interfaces?key=\"' + hostId + '\"';
154 }else{
155 var url = BASEURL + '/' + ws + '/_design/interfaces/_view/interfaces';
156 }
157 $http.get(url)
158 .success(function(interfaceArray){
159 var interfaces = interfaceArray.rows;
160 deferred.resolve(interfaces);
161 })
162 .error(function(){
163 deferred.reject();
164 })
165 return deferred.promise;
166 }
167
168 return hostsManager;
169 }]);
1818 <img src="images/ico-workspaces-menu.svg" alt="Workspaces"/>
1919 </a>
2020 </li>
21 <li>
22 <a href="#/hosts/ws/{{workspace}}" class="workspaces" style="color: #ffffff !important" tooltip="Hosts" tooltip-placement="right">
23 <i class="fa fa-sitemap fa-5x"></i>
24 </a>
25 </li>
2126 </ul>
2227 </nav>
2328 <div ng-show="isIceweasel" class="alert alert-danger alert-dismissible">
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('notesFact', ['BASEURL', '$http', function(BASEURL, $http) {
6 var notesFact = {};
7
8 notesFact.getNotes = function(ws, parent) {
9 var noteIds = [];
10 var notes = [];
11 var note = {};
12 var params = JSON.stringify([parent, "Note"]);
13 var url = BASEURL + ws + "/_design/mapper/_view/byparentandtype?key=" + params;
14 $.getJSON(url, function(data) {
15 $.each(data.rows, function(n, obj) {
16 noteIds.push(obj.value);
17 });
18 });
19 noteIds.forEach(function(id) {
20 url = BASEURL + ws + "/" + id;
21 $.getJSON(url, function(data) {
22 note = {
23 "id": data._id,
24 "rev": data._rev,
25 "name": data.name,
26 "text": data.text
27 };
28 notes.push(note);
29 });
30 });
31 return notes;
32 };
33
34 // updates note if existing, creates otherwise
35 notesFact.putNote = function(ws, name, parent, text) {
36 var notes = notesFact.getNotes(ws, parent);
37 var note = {};
38 var exists = false;
39 var url = BASEURL + ws + "/";
40 var id = "";
41 var rev = "";
42
43 // we need to check the name fits before updating
44 if(notes.length) {
45 notes.forEach(function(note) {
46 if(note.name === name) {
47 id = note.id;
48 rev = note.rev;
49 url += note.id;
50 exists = true;
51 }
52 });
53 }
54
55 if(!exists) {
56 // insert
57 id = parent + "." + CryptoJS.SHA1("Message").toString();
58 url += id;
59 note = {
60 "name": name,
61 "parent": parent,
62 "owned": false,
63 "text": text,
64 "type": "Note"
65 };
66 } else {
67 // update
68 note = {
69 "_id": id,
70 "_rev": rev,
71 "name": name,
72 "parent": parent,
73 "owned": false,
74 "text": text,
75 "type": "Note"
76 };
77 }
78
79 $http.put(url, note);
80 };
81
82 return notesFact;
83 }]);
+0
-84
views/reports/_attachments/scripts/notes/services/notes.js less more
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('notesFact', ['BASEURL', '$http', function(BASEURL, $http) {
6 var notesFact = {};
7
8 notesFact.getNotes = function(ws, parent) {
9 var noteIds = [];
10 var notes = [];
11 var note = {};
12 var params = JSON.stringify([parent, "Note"]);
13 var url = BASEURL + ws + "/_design/mapper/_view/byparentandtype?key=" + params;
14 $.getJSON(url, function(data) {
15 $.each(data.rows, function(n, obj) {
16 noteIds.push(obj.value);
17 });
18 });
19 noteIds.forEach(function(id) {
20 url = BASEURL + ws + "/" + id;
21 $.getJSON(url, function(data) {
22 note = {
23 "id": data._id,
24 "rev": data._rev,
25 "name": data.name,
26 "text": data.text
27 };
28 notes.push(note);
29 });
30 });
31 return notes;
32 };
33
34 // updates note if existing, creates otherwise
35 notesFact.putNote = function(ws, name, parent, text) {
36 var notes = notesFact.getNotes(ws, parent);
37 var note = {};
38 var exists = false;
39 var url = BASEURL + ws + "/";
40 var id = "";
41 var rev = "";
42
43 // we need to check the name fits before updating
44 if(notes.length) {
45 notes.forEach(function(note) {
46 if(note.name === name) {
47 id = note.id;
48 rev = note.rev;
49 url += note.id;
50 exists = true;
51 }
52 });
53 }
54
55 if(!exists) {
56 // insert
57 id = parent + "." + CryptoJS.SHA1("Message").toString();
58 url += id;
59 note = {
60 "name": name,
61 "parent": parent,
62 "owned": false,
63 "text": text,
64 "type": "Note"
65 };
66 } else {
67 // update
68 note = {
69 "_id": id,
70 "_rev": rev,
71 "name": name,
72 "parent": parent,
73 "owned": false,
74 "text": text,
75 "type": "Note"
76 };
77 }
78
79 $http.put(url, note);
80 };
81
82 return notesFact;
83 }]);
66 ['$scope', '$modalInstance', '$routeParams', 'services','service', 'servicesManager', 'commonsFact', 'dashboardSrv',
77 function($scope, $modalInstance, $routeParams, services, service, servicesManager, commons, dashboardSrv) {
88
9 init = function(){
9 init = function() {
1010 // current Workspace
1111 var ws = $routeParams.wsId;
1212 // default scope (service)
1414 "ports": []
1515 };
1616
17 if(service.length == 1){
17 if(service.length == 1) {
1818 $scope.service = {
1919 "name": service[0].name,
2020 "description": service[0].description,
2626 "status": service[0].status,
2727 "version": service[0].version,
2828 };
29 }else{
29 } else {
3030 $scope.services_selected = service;
3131 }
3232 };
5858 <table class="status-report hosts-list table table-responsive">
5959 <thead>
6060 <tr>
61 <th><input type="checkbox" ng-model="selectall" ng-click="checkAll()"/></th>
61 <th><input type="checkbox" ng-model="selectall" ng-click="checkAllServices()"/></th>
6262 <th>
6363 <a href="" ng-click="toggleSort('name')">Name</a>
6464 </th>
22 <!-- See the file 'doc/LICENSE' for the license information -->
33
44 <form name="form" novalidate>
5 <div class="modal-header">
6 <div class="modal-button">
7 <button class="btn btn-success" ng-click="ok()" ng-disabled="form.$invalid">OK</button>
8 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
5 <div class="modal-header">
6 <div class="modal-button">
7 <button class="btn btn-success" ng-click="ok()" ng-disabled="form.$invalid">OK</button>
8 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
9 </div>
10 <h3 class="modal-title">Edit service</h3>
911 </div>
10 <h3 class="modal-title">Edit service</h3>
11 </div>
12 <div class="modal-body">
13 <div class="form-horizontal">
14 <div class="form-group">
15 <div class="col-md-12">
16 <label class="sr-only" for="name">Name</label>
17 <input type="text" class="form-control" id="name" placeholder="Name" ng-model="service.name" required/>
18 </div>
19 </div><!-- .form-group -->
20 <div class="form-group">
21 <div class="col-md-12">
22 <label class="sr-only" for="description">Description</label>
23 <textarea class="form-control" id="description" placeholder="Description" ng-model="service.description"></textarea>
24 </div>
25 </div><!-- .form-group -->
26 <div class="form-group">
27 <div class="col-md-12">
28 <div class="checkbox">
29 <label>
30 <input type="checkbox" id="owned" ng-model="service.owned"/>
31 <span class="normal-size">Owned</span>
32 </label>
33 </div><!-- .checkbox -->
34 </div>
35 </div><!-- .form-group -->
36 <div class="form-group">
37 <div class="col-md-3">
38 <h5>Ports</h5>
39 <span class="input-group-addon button-radius" ng-click="newPort($event)">Add Port</span>
40 <div class="input-margin" ng-repeat="port in service.ports">
41 <div class="input-group margin-bottom-sm">
42 <label class="sr-only" for="port">Ports</label>
43 <input type="number" class="form-control" id="port" placeholder="Port" ng-model="port.key"/>
44 <span class="input-group-addon" ng-click="service.ports.splice($index, 1)" ng-hide="service.ports.length == 1"><i class="fa fa-minus-circle"></i></span>
12 <div class="modal-body">
13 <div class="form-horizontal">
14 <div class="form-group">
15 <div class="col-md-12">
16 <label class="sr-only" for="name">Name</label>
17 <input type="text" class="form-control" id="name" placeholder="Name" ng-model="service.name" required/>
18 </div>
19 </div><!-- .form-group -->
20 <div class="form-group">
21 <div class="col-md-12">
22 <label class="sr-only" for="description">Description</label>
23 <textarea class="form-control" id="description" placeholder="Description" ng-model="service.description"></textarea>
24 </div>
25 </div><!-- .form-group -->
26 <div class="form-group">
27 <div class="col-md-12">
28 <div class="checkbox">
29 <label>
30 <input type="checkbox" id="owned" ng-model="service.owned"/>
31 <span class="normal-size">Owned</span>
32 </label>
33 </div><!-- .checkbox -->
34 </div>
35 </div><!-- .form-group -->
36 <div class="form-group">
37 <div class="col-md-3">
38 <h5>Ports</h5>
39 <span class="input-group-addon button-radius" ng-click="newPort($event)">Add Port</span>
40 <div class="input-margin" ng-repeat="port in service.ports">
41 <div class="input-group margin-bottom-sm">
42 <label class="sr-only" for="port">Ports</label>
43 <input type="number" class="form-control" id="port" placeholder="Port" ng-model="port.key"/>
44 <span class="input-group-addon" ng-click="service.ports.splice($index, 1)" ng-hide="service.ports.length == 1"><i class="fa fa-minus-circle"></i></span>
45 </div>
4546 </div>
4647 </div>
47 </div>
48 <div class="col-md-3 protocol">
49 <h5>Protocol</h5>
50 <label class="sr-only" for="protocol">Protocol</label>
51 <input type="text" class="form-control" id="protocol" placeholder="Protocol" ng-model="service.protocol"/>
52 </div>
53 <div class="col-md-3">
54 <h5>Version</h5>
55 <label class="sr-only" for="version">Version</label>
56 <input type="text" class="form-control" id="version" placeholder="Version" ng-model="service.version"/>
57 </div>
58 <div class="col-md-3">
59 <h5>Status</h5>
60 <label class="sr-only" for="status">Status</label>
61 <input type="text" class="form-control" id="status" placeholder="Status" ng-model="service.status"/>
62 </div>
63 </div><!-- .form-group -->
64 <div class="form-group">
65 <div class="reports col-md-12 col-sm-12 col-xs-12" ng-if="services_selected">
66 <h5><small>
67 Services to update
68 </small></h5>
69 <table class="status-report hosts-list table table-responsive">
70 <thead>
71 <tr>
72 <th>
73 <a href="" ng-click="toggleSort('name')">Name</a>
74 </th>
75 <th>
76 <a href="" ng-click="toggleSort('description')">Description</a>
77 </th>
78 <th>
79 <a href="" ng-click="toggleSort('ports')">Ports</a>
80 </th>
81 <th>
82 <a href="" ng-click="toggleSort('protocol')">Protocol</a>
83 </th>
84 <th>
85 <a href="" ng-click="toggleSort('status')">Status</a>
86 </th>
87 <th>Copy</th>
88 </tr>
89 </thead>
90 <tbody>
91 <tr ng-repeat="service in services_selected | filter:query | orderBy:sortField:reverse">
92 <td ng-bind="service.name"></td>
93 <td ng-bind="service.description || '-'"></td>
94 <td ng-bind="service.ports"></td>
95 <td ng-bind="service.protocol"></td>
96 <td ng-bind="service.status"></td>
97 <td><i class="fa fa-copy copy-icon fa-lg" ng-click="call(service);"></i></td>
98 </tr>
99 </tbody>
100 </table><!-- #hosts -->
48 <div class="col-md-3 protocol">
49 <h5>Protocol</h5>
50 <label class="sr-only" for="protocol">Protocol</label>
51 <input type="text" class="form-control" id="protocol" placeholder="Protocol" ng-model="service.protocol"/>
52 </div>
53 <div class="col-md-3">
54 <h5>Version</h5>
55 <label class="sr-only" for="version">Version</label>
56 <input type="text" class="form-control" id="version" placeholder="Version" ng-model="service.version"/>
57 </div>
58 <div class="col-md-3">
59 <h5>Status</h5>
60 <label class="sr-only" for="status">Status</label>
61 <input type="text" class="form-control" id="status" placeholder="Status" ng-model="service.status"/>
62 </div>
63 </div><!-- .form-group -->
64 <div class="form-group">
65 <div class="reports col-md-12 col-sm-12 col-xs-12" ng-if="services_selected">
66 <h5><small>
67 Services to update
68 </small></h5>
69 <table class="status-report hosts-list table table-responsive">
70 <thead>
71 <tr>
72 <th>
73 <a href="" ng-click="toggleSort('name')">Name</a>
74 </th>
75 <th>
76 <a href="" ng-click="toggleSort('description')">Description</a>
77 </th>
78 <th>
79 <a href="" ng-click="toggleSort('ports')">Ports</a>
80 </th>
81 <th>
82 <a href="" ng-click="toggleSort('protocol')">Protocol</a>
83 </th>
84 <th>
85 <a href="" ng-click="toggleSort('status')">Status</a>
86 </th>
87 <th>Copy</th>
88 </tr>
89 </thead>
90 <tbody>
91 <tr ng-repeat="service in services_selected | filter:query | orderBy:sortField:reverse">
92 <td ng-bind="service.name"></td>
93 <td ng-bind="service.description || '-'"></td>
94 <td ng-bind="service.ports"></td>
95 <td ng-bind="service.protocol"></td>
96 <td ng-bind="service.status"></td>
97 <td><i class="fa fa-copy copy-icon fa-lg" ng-click="call(service);"></i></td>
98 </tr>
99 </tbody>
100 </table><!-- #hosts -->
101 </div>
101102 </div>
102103 </div>
104 </div><!-- .modal-body -->
105 <div class="modal-footer">
106 <div class="modal-button">
107 <button class="btn btn-success" ng-disabled="form.$invalid" ng-click="ok()">OK</button>
108 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
109 </div>
103110 </div>
104 </div><!-- .modal-body -->
105 <div class="modal-footer">
106 <div class="modal-button">
107 <button class="btn btn-success" ng-disabled="form.$invalid" ng-click="ok()">OK</button>
108 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
109 </div>
110 </div>
111111 </form>
22 <!-- See the file 'doc/LICENSE' for the license information -->
33
44 <form name="form" novalidate>
5 <div class="modal-header">
6 <div class="modal-button">
7 <button class="btn btn-success" ng-click="ok()" ng-disabled="form.$invalid">OK</button>
8 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
5 <div class="modal-header">
6 <div class="modal-button">
7 <button class="btn btn-success" ng-click="ok()" ng-disabled="form.$invalid">OK</button>
8 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
9 </div>
10 <h3 class="modal-title">New service</h3>
911 </div>
10 <h3 class="modal-title">New service</h3>
11 </div>
12 <div class="modal-body">
13 <div class="form-horizontal">
14 <div class="form-group">
15 <div class="col-md-12">
16 <label class="sr-only" for="service">Name</label>
17 <input type="text" class="form-control" id="service" placeholder="Name" ng-model="service.name" required/>
18 </div>
19 </div><!-- .form-group -->
20 <div class="form-group">
21 <div class="col-md-12">
22 <label class="sr-only" for="description">Description</label>
23 <textarea class="form-control" id="description" placeholder="Description" ng-model="service.description"></textarea>
24 </div>
25 </div><!-- .form-group -->
26 <div class="form-group">
27 <div class="col-md-12">
28 <div class="checkbox">
29 <label>
30 <input type="checkbox" id="owned" ng-model="service.owned"/>
31 <span class="normal-size">Owned</span>
32 </label>
33 </div><!-- .checkbox -->
34 </div>
35 </div><!-- .form-group -->
36 <div class="form-group">
37 <div class="col-md-3">
38 <h5>Ports</h5>
39 <span class="input-group-addon button-radius" ng-click="newPort($event)">Add Port</span>
40 <div class="input-margin" ng-repeat="port in service.ports">
41 <div class="input-group margin-bottom-sm">
42 <label class="sr-only" for="port">Ports</label>
43 <input type="number" class="form-control" id="port" placeholder="Port" ng-model="port.key" required/>
44 <span class="input-group-addon" ng-click="service.ports.splice($index, 1)" ng-hide="service.ports.length == 1"><i class="fa fa-minus-circle"></i></span>
12 <div class="modal-body">
13 <div class="form-horizontal">
14 <div class="form-group">
15 <div class="col-md-12">
16 <label class="sr-only" for="service">Name</label>
17 <input type="text" class="form-control" id="service" placeholder="Name" ng-model="service.name" required/>
18 </div>
19 </div><!-- .form-group -->
20 <div class="form-group">
21 <div class="col-md-12">
22 <label class="sr-only" for="description">Description</label>
23 <textarea class="form-control" id="description" placeholder="Description" ng-model="service.description"></textarea>
24 </div>
25 </div><!-- .form-group -->
26 <div class="form-group">
27 <div class="col-md-12">
28 <div class="checkbox">
29 <label>
30 <input type="checkbox" id="owned" ng-model="service.owned"/>
31 <span class="normal-size">Owned</span>
32 </label>
33 </div><!-- .checkbox -->
34 </div>
35 </div><!-- .form-group -->
36 <div class="form-group">
37 <div class="col-md-3">
38 <h5>Ports</h5>
39 <span class="input-group-addon button-radius" ng-click="newPort($event)">Add Port</span>
40 <div class="input-margin" ng-repeat="port in service.ports">
41 <div class="input-group margin-bottom-sm">
42 <label class="sr-only" for="port">Ports</label>
43 <input type="number" class="form-control" id="port" placeholder="Port" ng-model="port.key" required/>
44 <span class="input-group-addon" ng-click="service.ports.splice($index, 1)" ng-hide="service.ports.length == 1"><i class="fa fa-minus-circle"></i></span>
45 </div>
4546 </div>
4647 </div>
47 </div>
48 <div class="col-md-3 protocol">
49 <h5>Protocol</h5>
50 <label class="sr-only" for="protocol">Protocol</label>
51 <input type="text" class="form-control" id="protocol" placeholder="Protocol" ng-model="service.protocol" required/>
52 </div>
53 <div class="col-md-3">
54 <h5>Version</h5>
55 <label class="sr-only" for="version">Version</label>
56 <input type="text" class="form-control" id="version" placeholder="Version" ng-model="service.version"/>
57 </div>
58 <div class="col-md-3">
59 <h5>Status</h5>
60 <label class="sr-only" for="status">Status</label>
61 <input type="text" class="form-control" id="status" placeholder="Status" ng-model="service.status"/>
62 </div>
63 </div><!-- .form-group -->
48 <div class="col-md-3 protocol">
49 <h5>Protocol</h5>
50 <label class="sr-only" for="protocol">Protocol</label>
51 <input type="text" class="form-control" id="protocol" placeholder="Protocol" ng-model="service.protocol" required/>
52 </div>
53 <div class="col-md-3">
54 <h5>Version</h5>
55 <label class="sr-only" for="version">Version</label>
56 <input type="text" class="form-control" id="version" placeholder="Version" ng-model="service.version"/>
57 </div>
58 <div class="col-md-3">
59 <h5>Status</h5>
60 <label class="sr-only" for="status">Status</label>
61 <input type="text" class="form-control" id="status" placeholder="Status" ng-model="service.status"/>
62 </div>
63 </div><!-- .form-group -->
64 </div>
65 </div><!-- .modal-body -->
66 <div class="modal-footer">
67 <div class="modal-button">
68 <button class="btn btn-success" ng-disabled="form.$invalid" ng-click="ok()">OK</button>
69 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
70 </div>
6471 </div>
65 </div><!-- .modal-body -->
66 <div class="modal-footer">
67 <div class="modal-button">
68 <button class="btn btn-success" ng-disabled="form.$invalid" ng-click="ok()">OK</button>
69 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
70 </div>
71 </div>
7272 </form>
5151 servicesManager.getServices = function(ws) {
5252 var deferred = $q.defer();
5353 var self = this;
54 this._objects = {};
55
5456 $http.get(BASEURL + '/' + ws + '/_design/services/_view/services')
5557 .success(function(servicesArray){
5658 var services = [];
6365 .error(function(){
6466 deferred.reject();
6567 })
68 return deferred.promise;
69 }
70
71 servicesManager.getServicesByHost = function(ws, host_id) {
72 var deferred = $q.defer();
73 var url = BASEURL + "/" + ws + "/_design/services/_view/byhost?key=\"" + host_id + "\"";
74 $http.get(url).then(function(res){
75 var promises = [];
76 res.data.rows.forEach(function(service){
77 promises.push(servicesManager.getService(service.id, ws, true));
78 });
79 $q.all(promises).then(function(services) {
80 deferred.resolve(services);
81 });
82 }, function(){
83 deferred.reject();
84 });
6685 return deferred.promise;
6786 }
6887
22 // See the file 'doc/LICENSE' for the license information
33
44 angular.module('faradayApp')
5 .controller('modalEditCtrl', ['$scope', '$modalInstance', 'EASEOFRESOLUTION', 'commonsFact', 'severities', 'vulns',
6 function($scope, $modalInstance, EASEOFRESOLUTION, commons, severities, vulns) {
7 $scope.easeofresolution = EASEOFRESOLUTION;
8 $scope.evidence = {};
9 $scope.icons = {};
10 $scope.severities = severities;
11 $scope.vulns = vulns;
12 $scope.web = false;
13 $scope.mixed = 0x00;
14 $scope.vulnc = 0;
15 $scope.vulnid = 0;
16 $scope.file_name_error = false;
17 $scope.p_impact = {
18 "accountability": false,
19 "availability": false,
20 "confidentiality": false,
21 "integrity": false
5 .controller('modalEditCtrl', ['$modalInstance', 'EASEOFRESOLUTION', 'commonsFact', 'severities', 'vuln', 'cweFact',
6 function($modalInstance, EASEOFRESOLUTION, commons, severities, vuln, cweFact) {
7
8 var vm = this;
9
10 vm.easeofresolution;
11 vm.new_ref;
12 vm.icons;
13 vm.cweList;
14 vm.cweLimit;
15 vm.cwe_filter;
16
17 vm.file_name_error;
18
19 vm.data;
20 vm.vuln;
21
22 init = function() {
23 vm.easeofresolution = EASEOFRESOLUTION;
24 vm.severities = severities;
25 vm.new_ref = "";
26 vm.icons = {};
27
28 vm.cweList = [];
29 cweFact.get().then(function(data) {
30 vm.cweList = data;
31 });
32 vm.cweLimit = 5;
33 vm.cwe_filter = "";
34
35 vm.file_name_error = false;
36
37 vm.data = {
38 _attachments: {},
39 data: "",
40 desc: "",
41 easeofresolution: undefined,
42 impact: {
43 accountability: false,
44 availability: false,
45 confidentiality: false,
46 integrity: false
47 },
48 name: "",
49 refs: {},
50 resolution: "",
51 severity: undefined,
52 method: "",
53 path: "",
54 pname: "",
55 params: "",
56 query: "",
57 request: "",
58 response: "",
59 website: ""
60 };
61
62 vm.vuln = angular.copy(vuln);
63
64 vm.populate(vm.vuln);
65
66 // TODO: EVIDENCE SHOUD BE LOADED ALREADY?
67 if(vm.vuln._attachments !== undefined) {
68 vm.data._attachments = vm.vuln._attachments;
69 vm.icons = commons.loadIcons(vm.data._attachments);
70 }
2271 };
23 $scope.impact = {
24 "accountability": false,
25 "availability": false,
26 "confidentiality": false,
27 "integrity": false
72
73 vm.selectedFiles = function(files, e) {
74 files.forEach(function(file) {
75 if(file.name.charAt(0) != "_") {
76 if(!vm.data._attachments.hasOwnProperty(file)) vm.data._attachments[file.name] = file;
77 } else {
78 vm.file_name_error = true;
79 }
80 });
81 vm.icons = commons.loadIcons(vm._attachments);
82 }
83
84 vm.removeEvidence = function(name) {
85 delete vm.data._attachments[name];
86 delete vm.icons[name];
87 }
88
89 vm.toggleImpact = function(key) {
90 vm.data.impact[key] = !vm.data.impact[key];
2891 };
29 var vuln_mask = {"VulnerabilityWeb": 0x01, "Vulnerability": 0x10};
30
31 $scope.pickVuln = function(v) {
32 $scope.p_name = v.name;
33 $scope.p_desc = v.desc;
34 $scope.p_data = v.data;
35 $scope.severitySelection = v.severity;
36 $scope.easeOfResolutionSelection = v.easeofresolution;
37 $scope.p_method = v.method;
38 $scope.p_pname = v.pname;
39 $scope.p_params = v.params;
40 $scope.p_path = v.path;
41 $scope.p_query = v.query;
42 $scope.p_website = v.website;
43 $scope.p_refs = v.refs;
44 $scope.p_request = v.request;
45 $scope.p_response = v.response;
46 $scope.p_resolution = v.resolution;
47
48 $scope.name = $scope.p_name;
49 $scope.data = $scope.p_data;
50 $scope.desc = $scope.p_desc;
51 $scope.method = $scope.p_method;
52 $scope.params = $scope.p_params;
53 $scope.path = $scope.p_path;
54 $scope.pname = $scope.p_pname;
55 $scope.query = $scope.p_query;
56 $scope.refs = $scope.p_refs;
57 $scope.request = $scope.p_request;
58 $scope.response = $scope.p_response;
59 $scope.resolution = $scope.p_resolution;
60 $scope.website = $scope.p_website;
61
62 for(var key in v.impact) {
63 $scope.impact[key] = v.impact[key];
64 $scope.p_impact[key] = v.impact[key];
65 }
66
92
93 vm.ok = function() {
94 // add the ref in new_ref, if there's any
95 vm.newReference();
96 // convert refs to an array of strings
97 var refs = [];
98 vm.data.refs.forEach(function(ref) {
99 refs.push(ref.value);
100 });
101 vm.data.refs = refs;
102 $modalInstance.close(vm.data);
67103 };
68104
69 $scope.toggleImpact = function(key) {
70 $scope.impact[key] = !$scope.impact[key];
105 vm.cancel = function() {
106 $modalInstance.dismiss('cancel');
71107 };
72108
73 $scope.call = function(){
74 $scope.refs = commons.arrayToObject($scope.refs);
75 };
76 vulnid_count=0
77 $scope.vulns.forEach(function(v) {
78 if(v.selected) {
79 if(typeof(v.attachments) != undefined && v.attachments != undefined) {
80 v.attachments.forEach(function(name) {
81 $scope.evidence[name] = {"name": name};
82 });
83 $scope.icons = commons.loadIcons($scope.evidence);
109 vm.newReference = function() {
110 if (vm.new_ref != "") {
111 // we need to check if the ref already exists
112 if (vm.data.refs.filter(function(ref) {return ref.value === vm.new_ref}).length == 0) {
113 vm.data.refs.push({value: vm.new_ref});
114 vm.new_ref = "";
84115 }
85 $scope.mixed = $scope.mixed | vuln_mask[v.type];
86 $scope.vulnc++;
87 $scope.vulnid = vulnid_count;
88 if (v.type === "VulnerabilityWeb") {
89 $scope.web = true;
90 //web
91 }
92
93116 }
94 vulnid_count++;
95
96
97 });
98
99 if ($scope.vulnc == 1) {
100 $scope.pickVuln($scope.vulns[$scope.vulnid]);
101 }
102
103 $scope.unit = $scope.vulnc == 1;
104
105 if ($scope.vulnc > 1) {
106 $scope.p_name = "";
107 $scope.p_desc = "";
108 $scope.p_data = "";
109 $scope.p_method = "";
110 $scope.p_pname = "";
111 $scope.p_params = "";
112 $scope.p_path = "";
113 $scope.p_query = "";
114 $scope.p_website = "";
115 $scope.p_refs = "";
116 $scope.p_request = "";
117 $scope.p_response = "";
118 $scope.p_resolution = "";
119117 }
120118
121 if($scope.mixed == 0x11) {
122 $scope.mixed = true;
123 } else {
124 $scope.mixed = false;
119 vm.populate = function(item) {
120 for (var key in vm.data) {
121 if (key != "refs" && item.hasOwnProperty(key) && vm.data.hasOwnProperty(key)) {
122 vm.data[key] = item[key];
123 }
124 }
125 // convert refs to an array of objects
126 var refs = [];
127 item.refs.forEach(function(ref) {
128 refs.push({value: ref});
129 });
130 vm.data.refs = refs;
125131 }
126132
127 $scope.isChecked = function(i) {
128 return i.selected;
129 };
130
131 $scope.ok = function() {
132 var res = {},
133 evidence = [];
134
135 for(var key in $scope.impact) {
136 $scope.impact[key] = Boolean($scope.impact[key]);
137 }
138
139 for(var key in $scope.evidence) {
140 if(Object.keys($scope.evidence[key]).length == 1) {
141 evidence.push(key);
142 } else {
143 evidence.push($scope.evidence[key]);
144 }
145 }
146
147 $scope.refs = commons.objectToArray($scope.refs);
148
149 if($scope.web) {
150 res = {
151 "data": $scope.data,
152 "desc": $scope.desc,
153 "easeofresolution": $scope.easeOfResolutionSelection,
154 "evidence": $scope.evidence,
155 "impact": $scope.impact,
156 "method": $scope.method,
157 "name": $scope.name,
158 "params": $scope.params,
159 "path": $scope.path,
160 "pname": $scope.pname,
161 "query": $scope.query,
162 "refs": $scope.refs,
163 "request": $scope.request,
164 "response": $scope.response,
165 "resolution": $scope.resolution,
166 "severity": $scope.severitySelection,
167 "vulns": $scope.vulns,
168 "website": $scope.website
169 };
170 } else {
171 res = {
172 "data": $scope.data,
173 "desc": $scope.desc,
174 "easeofresolution": $scope.easeOfResolutionSelection,
175 "evidence": $scope.evidence,
176 "impact": $scope.impact,
177 "name": $scope.name,
178 "refs": $scope.refs,
179 "resolution": $scope.resolution,
180 "severity": $scope.severitySelection,
181 "vulns": $scope.vulns
182 };
183 }
184
185 $modalInstance.close(res);
186 };
187
188 $scope.cancel = function() {
189 $modalInstance.dismiss('cancel');
190 };
191
192 $scope.refs = commons.arrayToObject($scope.refs);
193
194 $scope.newReference = function($event){
195 $scope.refs.push({key:''});
196 };
197
198 $scope.selectedFiles = function(files, e) {
199 files.forEach(function(file) {
200 if(file.name.charAt(0) != "_") {
201 if(!$scope.evidence.hasOwnProperty(file)) $scope.evidence[file.name] = file;
202 } else {
203 $scope.file_name_error = true;
204 }
205 });
206 $scope.icons = commons.loadIcons($scope.evidence);
207 }
208
209 $scope.removeEvidence = function(name) {
210 delete $scope.evidence[name];
211 delete $scope.icons[name];
212 }
133 init();
213134 }]);
22 // See the file 'doc/LICENSE' for the license information
33
44 angular.module('faradayApp')
5 .controller('modalNewCtrl',
6 ['$scope', '$modalInstance', '$filter', '$upload', 'EASEOFRESOLUTION', 'targetFact', 'commonsFact', 'severities', 'workspace', 'hostsManager',
7 function($scope, $modalInstance, $filter, $upload, EASEOFRESOLUTION, targetFact, commons, severities, workspace, hostsManager) {
8
9 $scope.typeOptions = [
10 {name:'Vulnerability', value:'Vulnerability'},
11 {name:'VulnerabilityWeb',value:'VulnerabilityWeb'}
12 ];
5 .controller('modalNewVulnCtrl',
6 ['$modalInstance', '$filter', '$upload', 'EASEOFRESOLUTION', 'commonsFact', 'severities', 'workspace', 'targetFact', 'cweFact',
7 function($modalInstance, $filter, $upload, EASEOFRESOLUTION, commons, severities, workspace, targetFact, cweFact) {
138
14 $scope.easeofresolution = EASEOFRESOLUTION;
15 $scope.vuln_type = $scope.typeOptions[0].value;
16 $scope.severities = severities;
17 $scope.workspace = workspace;
18 $scope.target_selected = null;
19 $scope.not_target_selected = false;
20 $scope.incompatible_vulnWeb = false;
21 $scope.refs = [{key:''}];
22 $scope.evidence = {};
23 $scope.icons = {};
24 $scope.showPagination = 1;
25 $scope.currentPage = 0;
26 $scope.pageSize = 5;
27 $scope.pagination = 10;
28 $scope.file_name_error = false;
29 $scope.impact = {
30 "accountability": false,
31 "availability": false,
32 "confidentiality": false,
33 "integrity": false
9 var vm = this;
10
11 vm.vuln_types;
12 vm.easeofresolution;
13 vm.workspace;
14 vm.new_ref;
15 vm.icons;
16 vm.cweList;
17 vm.cweLimit;
18 vm.cwe_filter;
19
20 vm.file_name_error;
21
22 vm.currentPage;
23 vm.newCurrentPage;
24 vm.pageSize;
25
26 vm.targets;
27 vm.target_filter;
28
29 vm.data;
30
31 init = function() {
32 vm.vuln_types = [
33 {name:'Vulnerability', value:'Vulnerability'},
34 {name:'Vulnerability Web', value:'VulnerabilityWeb'}
35 ];
36 vm.easeofresolution = EASEOFRESOLUTION;
37 vm.severities = severities;
38 vm.workspace = workspace;
39 vm.new_ref = "";
40 vm.icons = {};
41
42 vm.cweList = [];
43 cweFact.get().then(function(data) {
44 vm.cweList = data;
45 });
46 vm.cweLimit = 5;
47 vm.cwe_filter = "";
48
49 vm.file_name_error = false;
50
51 vm.pageSize = 5;
52 vm.currentPage = 0;
53 vm.newCurrentPage = 0;
54
55 vm.data = {
56 _attachments: {},
57 type: "Vulnerability",
58 data: "",
59 desc: "",
60 easeofresolution: undefined,
61 impact: {
62 accountability: false,
63 availability: false,
64 confidentiality: false,
65 integrity: false
66 },
67 name: "",
68 owned: false,
69 parent: undefined,
70 refs: [],
71 resolution: "",
72 severity: undefined,
73 method: "",
74 path: "",
75 pname: "",
76 params: "",
77 query: "",
78 request: "",
79 response: "",
80 website: ""
81 };
82
83 vm.targets = [];
84 vm.target_filter = "";
85
86 targetFact.getTargets(workspace).then(function(targets){
87 vm.targets = targets;
88 });
3489 };
3590
36
37 var name_selected,
38 host_selected,
39 d = {},
40 hosts = targetFact.getTarget($scope.workspace, true);
41
42 hosts.forEach(function(h) {
43 h.services = [];
44 d[h._id] = h;
45 });
46
47 hostsManager.getInterfaces($scope.workspace).then(function(resp){
48 $scope.interfaces = resp;
49 hosts.forEach(function(h){
50 $scope.interfaces.forEach(function(interface){
51 if(h._id == interface.value.parent){
52 h.hostnames = interface.value.hostnames;
53 }
54 });
91 vm.selectedFiles = function(files, e) {
92 files.forEach(function(file) {
93 if(file.name.charAt(0) != "_") {
94 if(!vm.data._attachments.hasOwnProperty(file)) vm.data._attachments[file.name] = file;
95 vm.file_name_error = false;
96 } else {
97 vm.file_name_error = true;
98 }
5599 });
56 });
57
58 var services = targetFact.getTarget($scope.workspace, false);
59
60 for(var i = 0; i < services.length; i++){
61 var host = [];
62 services[i].selected = false;
63 host = d[services[i].hid];
64 host.services.push(services[i]);
65 }
66
67 $scope.hosts_with_services = hosts;
68
69 $scope.numberOfPages = function() {
70 if(typeof(filteredData) == "undefined") return false;
71 var filteredData = $filter('filter')($scope.hosts_with_services,$scope.search_notes);
72 if (filteredData.length <= 10){
73 $scope.showPagination = 0;
74 } else {
75 $scope.showPagination = 1;
76 }
77
78 return Math.ceil(filteredData.length/$scope.pagination);
100 vm.icons = commons.loadIcons(vm.data._attachments);
79101 };
80102
81 $scope.selectedFiles = function(files, e) {
82 files.forEach(function(file) {
83 if(file.name.charAt(0) != "_") {
84 if(!$scope.evidence.hasOwnProperty(file)) $scope.evidence[file.name] = file;
85 } else {
86 $scope.file_name_error = true;
87 }
88 });
89 $scope.icons = commons.loadIcons($scope.evidence);
103 vm.removeEvidence = function(name) {
104 delete vm.data._attachments[name];
105 delete vm.icons[name];
90106 };
91107
92 $scope.removeEvidence = function(name) {
93 delete $scope.evidence[name];
94 delete $scope.icons[name];
108 vm.toggleImpact = function(key) {
109 vm.data.impact[key] = !vm.data.impact[key];
95110 };
96111
97 $scope.toggleImpact = function(key) {
98 $scope.impact[key] = !$scope.impact[key];
99 };
112 vm.ok = function() {
113 if (!(vm.data.type === "VulnerabilityWeb" && vm.data.parent.type === "Host")) {
114 // add the ref in new_ref, if there's any
115 vm.newReference();
100116
101 $scope.ok = function() {
102 if($scope.vuln_type == "VulnerabilityWeb" && host_selected == true){
103 $scope.incompatible_vulnWeb = true;
104 } else {
105 var res = {},
106 id = $scope.target_selected._id + "." + CryptoJS.SHA1($scope.name + "." + $scope.desc).toString(),
107 sha = CryptoJS.SHA1($scope.name + "." + $scope.desc).toString(),
108 myDate = new Date(),
109 myEpoch = myDate.getTime()/1000.0,
110 extra_vulns_prop = {},
111 arrayReferences = [];
117 // convert refs to an array of strings
118 var refs = [];
119 vm.data.refs.forEach(function(ref) {
120 refs.push(ref.value);
121 });
122 vm.data.refs = refs;
112123
113 for(var key in $scope.impact) {
114 $scope.impact[key] = Boolean($scope.impact[key]);
115 }
124 // delete selection
125 delete vm.data.parent.selected_modalNewCtrl;
116126
117 $scope.refs.forEach(function(r){
118 arrayReferences.push(r.key);
119 });
120
121 arrayReferences.filter(Boolean);
127 vm.data.parent = vm.data.parent._id;
122128
123 var res = {
124 "id": id,
125 "data": $scope.data,
126 "date": myEpoch,
127 "desc": $scope.desc,
128 "easeofresolution": $scope.easeOfResolutionSelection,
129 "evidence": $scope.evidence,
130 "impact": $scope.impact,
131 "meta": {
132 'create_time': myEpoch,
133 "update_time": myEpoch,
134 "update_user": 'UI Web',
135 'update_action': 0,
136 'creator': 'UI Web',
137 'create_time': myEpoch,
138 'update_controller_action': 'UI Web New',
139 'owner': 'anonymous'
140 },
141 "name": $scope.name,
142 "oid": sha,
143 "owned": false,
144 "owner": "",
145 "couch_parent": $scope.target_selected._id,
146 "refs": arrayReferences,
147 "resolution": $scope.resolution,
148 "status": $scope.vuln_type,
149 "severity": $scope.severitySelection,
150 "target": name_selected,
151 "type": $scope.vuln_type
152 }
153
154 if($scope.vuln_type == "VulnerabilityWeb") {
155 extra_vulns_prop = {
156 "path": $scope.path,
157 "pname": $scope.pname,
158 "query": $scope.query,
159 "request": $scope.request,
160 "resolution": $scope.resolution,
161 "response": $scope.response,
162 "web": true,
163 "website": $scope.website
164 };
165 } else {
166 extra_vulns_prop = {
167 "web": false
168 };
169 }
170
171 for(var key in extra_vulns_prop) {
172 res[key] = extra_vulns_prop[key];
173 }
174
175 $modalInstance.close(res);
129 $modalInstance.close(vm.data);
176130 }
177131 };
178132
179 $scope.cancel = function() {
133 vm.cancel = function() {
180134 $modalInstance.dismiss('cancel');
181135 };
182136
183 $scope.$parent.isopen = ($scope.$parent.default === $scope.item);
184
185 $scope.$watch('isopen', function (newvalue, oldvalue, $scope) {
186 $scope.$parent.isopen = newvalue;
187 });
188
189 $scope.selected = function(i,j){
190 if($scope.target_selected){
191 $scope.target_selected.selected = false;
137 vm.setTarget = function(target) {
138 if (vm.data.parent != undefined) {
139 delete vm.data.parent.selected_modalNewCtrl;
192140 }
193 if(j != null){
194 host_selected = false;
195 $scope.target_selected = j;
196 name_selected = i.name;
197 }else{
198 host_selected = true;
199 $scope.target_selected = i;
200 name_selected = i.name;
201 }
202 $scope.target_selected.selected = true;
203 $scope.not_target_selected = true;
141 target.selected_modalNewCtrl = true;
142 vm.data.parent = target;
204143 }
205144
206 $scope.go = function(){
207 if($scope.go_page < $scope.numberOfPages()+2 && $scope.go_page > -1){
208 $scope.currentPage = $scope.go_page;
145 vm.go = function() {
146 vm.currentPage = 0;
147 if(vm.newCurrentPage <= parseInt(vm.targets.length/vm.pageSize)
148 && vm.newCurrentPage > -1) {
149 vm.currentPage = vm.newCurrentPage;
209150 }
210151 }
211152
212 $scope.newReference = function($event){
213 $scope.refs.push({key:''});
214 $event.preventDefault();
153 vm.newReference = function() {
154 if (vm.new_ref != "") {
155 // we need to check if the ref already exists
156 if (vm.data.refs.filter(function(ref) {return ref.value === vm.new_ref}).length == 0) {
157 vm.data.refs.push({value: vm.new_ref});
158 vm.new_ref = "";
159 }
160 }
215161 }
162
163 vm.populate = function(item, model, label) {
164
165 for (var key in item) {
166 if (key != "refs" && vm.data.hasOwnProperty(key)) {
167 vm.data[key] = item[key];
168 }
169 }
170
171 // convert refs to an array of objects
172 var refs = [];
173 item.refs.forEach(function(ref) {
174 refs.push({value: ref});
175 });
176 vm.data.refs = refs;
177 }
178
179 init();
216180 }]);
33
44 angular.module('faradayApp')
55 .controller('statusReportCtrl',
6 ['$scope', '$filter', '$route', '$routeParams', '$location', '$modal', '$cookies','BASEURL', 'SEVERITIES', 'EASEOFRESOLUTION', 'statusReportFact', 'hostsManager',
7 function($scope, $filter, $route, $routeParams, $location, $modal, $cookies, BASEURL, SEVERITIES, EASEOFRESOLUTION, statusReportFact, hostsManager) {
6 ['$scope', '$filter', '$routeParams',
7 '$location', '$modal', '$cookies', '$q', 'BASEURL',
8 'SEVERITIES', 'EASEOFRESOLUTION', 'hostsManager',
9 'vulnsManager', 'workspacesFact',
10 function($scope, $filter, $routeParams,
11 $location, $modal, $cookies, $q, BASEURL,
12 SEVERITIES, EASEOFRESOLUTION, hostsManager,
13 vulnsManager, workspacesFact) {
14 $scope.baseurl;
15 $scope.columns;
16 $scope.easeofresolution;
17 $scope.expression;
18 $scope.interfaces;
19 $scope.reverse;
20 $scope.severities;
21 $scope.search;
22 $scope.searchParams;
23 $scope.sortField;
24 $scope.vulns;
25 $scope.workspaces;
26 $scope.currentPage;
27 $scope.newCurrentPage;
28 $scope.pageSize;
29 $scope.newPageSize;
30
31 $scope.vulnWebSelected;
32
833 init = function() {
934 $scope.baseurl = BASEURL;
1035 $scope.severities = SEVERITIES;
1136 $scope.easeofresolution = EASEOFRESOLUTION;
12
13 $scope.sortField = 'date';
37 $scope.sortField = 'metadata.create_time';
1438 $scope.reverse = true;
15 $scope.showPagination = 1;
39 $scope.vulns = [];
40
41 $scope.pageSize = 10;
1642 $scope.currentPage = 0;
17 // set custom pagination if is possible
18 if(typeof($cookies.pageSize) == "undefined") {
19 $scope.pageSize = 10;
20 $scope.pagination = 10;
21 } else {
43 $scope.newCurrentPage = 0;
44
45 if (!isNaN(parseInt($cookies.pageSize)))
2246 $scope.pageSize = parseInt($cookies.pageSize);
23 $scope.pagination = parseInt($cookies.pageSize);
24 }
47 $scope.newPageSize = $scope.pageSize;
2548
2649 // load all workspaces
27 statusReportFact.getWorkspaces().then(function(wss) {
50 workspacesFact.list().then(function(wss) {
2851 $scope.workspaces = wss;
2952 });
3053
3154 // current workspace
3255 $scope.workspace = $routeParams.wsId;
3356 $scope.interfaces = [];
34
35 $scope.getVulns = function() {
36 var vulnerabilities = statusReportFact.getVulns($scope.workspace);
37 hostsManager.getInterfaces($scope.workspace).then(function(interfaces){
38 interfaces.forEach(function(interface){
39 vulnerabilities.forEach(function(vuln){
40 if(vuln.parent == interface.value.parent){
41 vuln.hostnames = interface.value.hostnames;
42 }
43 });
44 });
45 });
46 return vulnerabilities;
47 };
48
4957 // current search
5058 $scope.search = $routeParams.search;
5159 $scope.searchParams = "";
5866 }
5967
6068 // load all vulnerabilities
61 $scope.vulns = $filter('filter')($scope.getVulns(), $scope.expression);
69 vulnsManager.getVulns($scope.workspace).then(function(vulns) {
70 $scope.vulns = vulnsManager.vulns;
71 });
6272
6373 // created object for columns cookie columns
6474 if(typeof($cookies.SRcolumns) != 'undefined'){
94104 "web": false,
95105 "website": false
96106 };
97 };
107
108 $scope.vulnWebSelected = false;
109 };
110
111 $scope.selectedVulns = function() {
112 selected = [];
113 $scope.vulns.forEach(function(vuln) {
114 if (vuln.selected_statusreport_controller) {
115 selected.push(vuln);
116 }
117 });
118 return selected;
119 }
120
98121
99122 // returns scope vulns as CSV obj
100123 // toggles column sort field
101 $scope.cleanCSV = function(field) {
124 cleanCSV = function(field) {
102125 return field.replace(/\n[ ]*\n/g, "").replace(/\"/g, "'").replace(/[\n\r]/g, "%0A").replace(/[,]/g, "%2c");
103 };
104 $scope.ToString = function(array){
105 return array.toString();
106126 };
107127
108128 $scope.toCSV = function() {
126146 "\"Query\", \"References\", \"Request\", \"Response\", \"Resolution\",\"Website\", "+
127147 "\"Ease of Resolution\", \"Impact\"\n";
128148
129 $scope.vulns.forEach(function(v) {
130 method = "";
131 website = "";
132 desc = "";
133 easeofres = "",
134 impact = JSON.stringify(v.impact),
135 text = "";
136 path = "";
137 pname = "";
138 params = "";
139 query = "";
140 refs = "";
141 request = "";
142 response = "";
143 resolution = "";
144 refs = $scope.ToString(v.refs);
145
146 if(typeof(v.desc) != "undefined" && v.desc != null) desc = $scope.cleanCSV(v.desc);
147 if(typeof(v.data) != "undefined" && v.data != null) text = $scope.cleanCSV(v.data);
148 if(typeof(v.resolution) != "undefined" && v.resolution != null) resolution = $scope.cleanCSV(v.resolution);
149 if(typeof(refs) != "undefined" && refs != null){
150 refs = $scope.cleanCSV(refs);
151 refs = refs.replace(/%2c/g,"%0A");
152 }
153 if(typeof(impact) != "undefined" && impact != null){
154 impact = $scope.cleanCSV(impact);
155 impact = impact.replace(/%2c/g,"%0A");
156 }
157 if(v.type === "VulnerabilityWeb") {
158 if(typeof(v.method) != "undefined" && v.method != null) method = $scope.cleanCSV(v.method);
159 if(typeof(v.website) != "undefined" && v.website != null) website = $scope.cleanCSV(v.website);
160 if(typeof(v.path) != "undefined" && v.path != null) path = $scope.cleanCSV(v.path);
161 if(typeof(v.pname) != "undefined" && v.pname != null) pname = $scope.cleanCSV(v.pname);
162 if(typeof(v.params) != "undefined" && v.params != null) params = $scope.cleanCSV(v.params);
163 if(typeof(v.query) != "undefined" && v.query != null) query = $scope.cleanCSV(v.query);
149 $scope.vulns.then(function(vs) {
150 forEach(function(v) {
151 method = "";
152 website = "";
153 desc = "";
154 easeofres = "",
155 impact = JSON.stringify(v.impact),
156 text = "";
157 path = "";
158 pname = "";
159 params = "";
160 query = "";
161 refs = "";
162 request = "";
163 response = "";
164 resolution = "";
165 refs = v.refs.toString();
166
167 if(typeof(v.desc) != "undefined" && v.desc != null) desc = cleanCSV(v.desc);
168 if(typeof(v.data) != "undefined" && v.data != null) text = cleanCSV(v.data);
169 if(typeof(v.resolution) != "undefined" && v.resolution != null) resolution = cleanCSV(v.resolution);
164170 if(typeof(refs) != "undefined" && refs != null){
165 refs = $scope.cleanCSV(refs);
171 refs = cleanCSV(refs);
166172 refs = refs.replace(/%2c/g,"%0A");
167173 }
168 if(typeof(v.request) != "undefined" && v.request != null) request = $scope.cleanCSV(v.request);
169 if(typeof(v.response) != "undefined" && v.response != null) response = $scope.cleanCSV(v.response);
170 if(typeof(v.resolution) != "undefined" && v.resolution != null) resolution = $scope.cleanCSV(v.resolution);
171 }
172
173 content += "\""+v.date+"\","+
174 " \""+v.web+"\","+
175 " \"Vulnerable\","+
176 " \""+v.severity+"\","+
177 " \""+v.name+"\","+
178 " \""+v.target+"\","+
179 " \""+desc+"\","+
180 " \""+text+"\","+
181 " \""+method+"\","+
182 " \""+path+"\","+
183 " \""+pname+"\","+
184 " \""+params+"\","+
185 " \""+query+"\","+
186 " \""+refs+"\","+
187 " \""+request+"\","+
188 " \""+response+"\","+
189 " \""+resolution+"\","+
190 " \""+website+"\","+
191 " \""+impact+"\","+
192 " \""+easeofres+"\""+
193 "\n";
174 if(typeof(impact) != "undefined" && impact != null){
175 impact = cleanCSV(impact);
176 impact = impact.replace(/%2c/g,"%0A");
177 }
178 if(v.type === "VulnerabilityWeb") {
179 if(typeof(v.method) != "undefined" && v.method != null) method = cleanCSV(v.method);
180 if(typeof(v.website) != "undefined" && v.website != null) website = cleanCSV(v.website);
181 if(typeof(v.path) != "undefined" && v.path != null) path = cleanCSV(v.path);
182 if(typeof(v.pname) != "undefined" && v.pname != null) pname = cleanCSV(v.pname);
183 if(typeof(v.params) != "undefined" && v.params != null) params = cleanCSV(v.params);
184 if(typeof(v.query) != "undefined" && v.query != null) query = cleanCSV(v.query);
185 if(typeof(refs) != "undefined" && refs != null){
186 refs = cleanCSV(refs);
187 refs = refs.replace(/%2c/g,"%0A");
188 }
189 if(typeof(v.request) != "undefined" && v.request != null) request = cleanCSV(v.request);
190 if(typeof(v.response) != "undefined" && v.response != null) response = cleanCSV(v.response);
191 if(typeof(v.resolution) != "undefined" && v.resolution != null) resolution = cleanCSV(v.resolution);
192 }
193
194 content += "\""+v.date+"\","+
195 " \""+v.web+"\","+
196 " \"Vulnerable\","+
197 " \""+v.severity+"\","+
198 " \""+v.name+"\","+
199 " \""+v.target+"\","+
200 " \""+desc+"\","+
201 " \""+text+"\","+
202 " \""+method+"\","+
203 " \""+path+"\","+
204 " \""+pname+"\","+
205 " \""+params+"\","+
206 " \""+query+"\","+
207 " \""+refs+"\","+
208 " \""+request+"\","+
209 " \""+response+"\","+
210 " \""+resolution+"\","+
211 " \""+website+"\","+
212 " \""+impact+"\","+
213 " \""+easeofres+"\""+
214 "\n";
215 });
194216 });
195217
196218 var obj = {
203225 return obj;
204226 };
205227
206 // deletes all vulns with selected == true
207 $scope.remove = function() {
208 var old = $scope.vulns;
209 $scope.vulns = [];
210
211 old.forEach(function(v) {
212 if(v.selected) {
213 statusReportFact.removeVulns($scope.workspace, v);
214 } else {
215 $scope.vulns.push(v);
216 }
217 });
218 };
219
220 // updates all vulns with selected == true
221 $scope.update = function(data) {
222 $scope.vulns = [];
223
224 data.vulns.forEach(function(v) {
225 if(v.selected) {
226 if(typeof(data.severity) == "string") v.severity = data.severity;
227 if(typeof(data.easeofresolution) == "string") v.easeofresolution = data.easeofresolution;
228 if(typeof(data.name) != "undefined") v.name = data.name;
229 if(typeof(data.desc) != "undefined") v.desc = data.desc;
230 if(typeof(data.data) != "undefined") v.data = data.data;
231 if(typeof(data.refs) != "undefined") v.refs = data.refs;
232 if(typeof(data.impact) != "undefined") v.impact = data.impact;
233 if(typeof(data.resolution) != "undefined") v.resolution = data.resolution;
234 v.evidence = data.evidence;
235 if(v.web) {
236 if(typeof(data.method) != "undefined") v.method = data.method;
237 if(typeof(data.params) != "undefined") v.params = data.params;
238 if(typeof(data.path) != "undefined") v.path = data.path;
239 if(typeof(data.pname) != "undefined") v.pname = data.pname;
240 if(typeof(data.query) != "undefined") v.query = data.query;
241 if(typeof(data.refs) != "undefined") v.refs = data.refs;
242 if(typeof(data.request) != "undefined") v.request = data.request;
243 if(typeof(data.response) != "undefined") v.response = data.response;
244 if(typeof(data.resolution) != "undefined") v.resolution = data.resolution;
245 if(typeof(data.website) != "undefined") v.website = data.website;
246 }
247
248 statusReportFact.putVulns($scope.workspace, v, function(rev, evidence) {
249 v.rev = rev;
250 v.attachments = evidence;
228 showMessage = function(msg) {
229 var modal = $modal.open({
230 templateUrl: 'scripts/commons/partials/modalKO.html',
231 controller: 'commonsModalKoCtrl',
232 resolve: {
233 msg: function() {
234 return msg;
235 }
236 }
237 });
238 }
239
240 // deletes the vulns in the array
241 $scope.remove = function(aVulns) {
242 aVulns.forEach(function(vuln) {
243 vulnsManager.deleteVuln(vuln)
244 .then(function() {})
245 .catch(function(errorMsg) {
246 // TODO: show errors somehow
247 console.log("Error deleting vuln " + vuln._id + ": " + errorMsg);
251248 });
252 v.selected = false;
253 }
254 $scope.vulns.push(v);
255249 });
256250 };
257251
258252 // action triggered from DELETE button
259253 $scope.delete = function() {
260 var selected = false;
261 var i = 0;
262
263 $scope.vulns.forEach(function(v) {
264 if(v.selected) {
265 selected = true;
266 i++;
267 }
268 });
269
270 if(selected) {
254 if($scope.selectedVulns().length > 0) {
271255 var modal = $modal.open({
272256 templateUrl: 'scripts/commons/partials/modalDelete.html',
273257 controller: 'commonsModalDelete',
275259 resolve: {
276260 msg: function() {
277261 var msg = "";
278 if(i == 1) {
262 if($scope.selectedVulns().length == 1) {
279263 msg = "A vulnerability will be deleted.";
280264 } else {
281 msg = i + " vulnerabilities will be deleted.";
265 msg = $scope.selectedVulns().length + " vulnerabilities will be deleted.";
282266 }
283267 msg += " This action cannot be undone. Are you sure you want to proceed?";
284268 return msg;
287271 });
288272
289273 modal.result.then(function() {
290 $scope.remove();
274 $scope.remove($scope.selectedVulns());
291275 });
292276 } else {
293 var modal = $modal.open({
294 templateUrl: 'scripts/commons/partials/modalKO.html',
295 controller: 'commonsModalKoCtrl',
296 resolve: {
297 msg: function() {
298 return 'No vulnerabilities were selected to delete';
299 }
300 }
301 });
277 showMessage('No vulnerabilities were selected to delete');
302278 }
303279 };
304280
305281 // action triggered from EDIT button
306282 $scope.edit = function() {
307 var selected = false;
308
309 $scope.vulns.forEach(function(v) {
310 if(v.selected) selected = true;
311 });
312
313 if(selected) {
283 if ($scope.selectedVulns().length == 1) {
314284 var modal = $modal.open({
315285 templateUrl: 'scripts/statusReport/partials/modalEdit.html',
316 controller: 'modalEditCtrl',
286 controller: 'modalEditCtrl as modal',
317287 size: 'lg',
318288 resolve: {
319289 severities: function() {
320290 return $scope.severities;
321291 },
322 vulns: function() {
323 return $scope.vulns;
292 vuln: function() {
293 return $scope.selectedVulns()[0];
324294 }
325295 }
326296 });
327
328297 modal.result.then(function(data) {
329 $scope.update(data);
298 vulnsManager.updateVuln($scope.selectedVulns()[0], data).then(function(){
299 }, function(errorMsg){
300 showMessage("Error updating vuln " + $scope.selectedVulns()[0].name + " (" + $scope.selectedVulns()[0]._id + "): " + errorMsg);
301 });
302
330303 });
331304 } else {
332 var modal = $modal.open({
333 templateUrl: 'scripts/commons/partials/modalKO.html',
334 controller: 'commonsModalKoCtrl',
335 resolve: {
336 msg: function() {
337 return 'At least one vulnerabilty must be selected in order to edit';
305 showMessage('A vulnierabilty must be selected in order to edit');
306 }
307 };
308
309 var editProperty = function(partial, controller, message, property, opts) {
310 if(opts == undefined) {
311 opts = {};
312 }
313 var resolve = {
314 msg: function() {
315 return message;
316 },
317 options: function() {
318 return opts.options;
319 }
320 };
321 var modal = $modal.open({
322 templateUrl: partial,
323 controller: controller,
324 size: 'lg',
325 resolve: resolve
326 });
327 modal.result.then(function(data) {
328 $scope.selectedVulns().forEach(function(vuln) {
329 obj = {};
330 obj[property] = data;
331
332 if (opts.callback != undefined){
333 obj = opts.callback(vuln, data);
334 }
335
336 vulnsManager.updateVuln(vuln, obj).then(function(vulns){
337 }, function(errorMsg){
338 // TODO: show errors somehow
339 console.log("Error updating vuln " + vuln._id + ": " + errorMsg);
340 });
341 });
342 });
343 }
344
345 $scope.editSeverity = function() {
346 editProperty(
347 'scripts/commons/partials/editOptions.html',
348 'commonsModalEditOptions',
349 'Enter the new severity:',
350 'severity',
351 {options: SEVERITIES});
352 }
353
354 $scope.editEaseofresolution = function() {
355 editProperty(
356 'scripts/commons/partials/editOptions.html',
357 'commonsModalEditOptions',
358 'Enter the new easeofresolution:',
359 'easeofresolution',
360 {options: EASEOFRESOLUTION});
361 }
362
363 $scope.editReferences = function() {
364 editProperty(
365 'scripts/commons/partials/editArray.html',
366 'commonsModalEditArray',
367 'Enter the new references:',
368 'refs',
369 {callback: function (vuln, refs) {
370 var references = vuln.refs.concat([]);
371 refs.forEach(function(ref) {
372 if(vuln.refs.indexOf(ref) == -1){
373 references.push(ref);
338374 }
339 }
340 });
341 }
342 };
375 });
376
377 return {'refs': references};
378 }}
379 );
380 }
381
382 $scope.editImpact = function() {
383 editProperty(
384 'scripts/commons/partials/editObject.html',
385 'commonsModalEditObject',
386 'Enter the new impact:',
387 'impact',
388 {
389 options: {
390 accountability: false,
391 availability: false,
392 confidentiality: false,
393 integrity: false
394 },
395 callback: function (vuln, impacts) {
396 var impact = {};
397 for(key in vuln.impact){
398 if(vuln.impact.hasOwnProperty(key)) {
399 impact[key] = vuln.impact[key];
400 if(impacts.hasOwnProperty(key)) {
401 impact[key] = impacts[key];
402 }
403 }
404 }
405 return {'impact': impact};
406 }
407 }
408 );
409 }
410
411 $scope.editString = function(property, message_word) {
412 var message;
413 if(message_word) {
414 message = 'Enter the new ' + message_word + ':';
415 } else {
416 message = 'Enter the new ' + property + ':';
417 }
418 editProperty(
419 'scripts/commons/partials/editString.html',
420 'commonsModalEditString',
421 message,
422 property);
423 }
424
425 $scope.editText = function(property, message_word) {
426 var message;
427 if(message_word) {
428 message = 'Enter the new ' + message_word + ':';
429 } else {
430 message = 'Enter the new ' + property + ':';
431 }
432 editProperty(
433 'scripts/commons/partials/editText.html',
434 'commonsModalEditString',
435 message,
436 property);
437 }
438
439 $scope.editCWE = function() {
440 var modal = $modal.open({
441 templateUrl: 'scripts/commons/partials/editCWE.html',
442 controller: 'commonsModalEditCWE',
443 size: 'lg',
444 resolve: {
445 msg: function() {
446 return 'CWE template';
447 }
448 }
449 });
450 modal.result.then(function(data) {
451 $scope.selectedVulns().forEach(function(vuln) {
452 var references = vuln.refs.concat([]);
453 data.refs.forEach(function(ref) {
454 if(vuln.refs.indexOf(ref) == -1){
455 references.push(ref);
456 }
457 });
458 data.refs = references;
459
460 vulnsManager.updateVuln(vuln, data).then(function(vulns){
461 }, function(errorMsg){
462 // TODO: show errors somehow
463 console.log("Error updating vuln " + vuln._id + ": " + errorMsg);
464 });
465 });
466 });
467 }
343468
344469 $scope.insert = function(vuln) {
345 statusReportFact.putVulns($scope.workspace, vuln, function(rev, evidence) {
346 vuln.rev = rev;
347 vuln.attachments = evidence;
348 });
470 vulnsManager.createVuln($scope.workspace, vuln).then(function() {
471 }, function(message) {
472 var msg = "The vulnerability couldn't be created";
473 if(message == "409") {
474 msg += " because a vulnerability with the same parameters already exists in this Workspace";
475 }
476 showMessage(msg);
477 });
478 /*
479 // this shouldnt be necessary, we should use Angular formatting options directly in the partial
349480 //formating the date
350481 var d = new Date(0);
351482 d.setUTCSeconds(vuln.date);
352483 d = d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear();
353484 vuln.date = d;
354 $scope.vulns.push(vuln);
485 */
355486 };
356487
357488 $scope.new = function() {
358 var modal = $modal.open({
359 templateUrl: 'scripts/statusReport/partials/modalNew.html',
360 controller: 'modalNewCtrl',
361 size: 'lg',
362 resolve: {
363 severities: function() {
364 return $scope.severities;
365 },
366 workspace: function() {
367 return $scope.workspace;
368 }
369 }
370 });
371
372 modal.result.then(function(data) {
373 $scope.insert(data);
374 });
489 var modal = $modal.open({
490 templateUrl: 'scripts/statusReport/partials/modalNew.html',
491 controller: 'modalNewVulnCtrl as modal',
492 size: 'lg',
493 resolve: {
494 severities: function() {
495 return $scope.severities;
496 },
497 workspace: function() {
498 return $scope.workspace;
499 }
500 }
501 });
502
503 modal.result.then(function(data) {
504 $scope.insert(data);
505 });
375506 };
376507
377508 $scope.checkAll = function() {
381512 $scope.selectall = false;
382513 }
383514
384 var orderObject = $filter('orderObjectBy')($scope.vulns, $scope.sortField, $scope.reverse);
385 var tmp_vulns = $filter('limitTo')(orderObject, $scope.pageSize, $scope.currentPage * $scope.pageSize);
386 angular.forEach($filter('filter')(tmp_vulns), function(v,k) {
387 v.selected = $scope.selectall;
388 });
389 };
390
391 $scope.numberOfPages = function() {
392 if($scope.vulns.length <= 10) {
393 $scope.showPagination = 0;
394 } else {
395 $scope.showPagination = 1;
396 }
397 return parseInt($scope.vulns.length/$scope.pageSize);
515 var tmp_vulns = $filter('orderObjectBy')($scope.vulns, $scope.sortField, $scope.reverse);
516 tmp_vulns = $filter('filter')(tmp_vulns, $scope.expression);
517 tmp_vulns = tmp_vulns.splice($scope.pageSize * $scope.currentPage, $scope.pageSize);
518 tmp_vulns.forEach(function(v,k) {
519 v.selected_statusreport_controller = $scope.selectall;
520 });
521
398522 };
399523
400524 $scope.go = function() {
401 if($scope.go_page < $scope.numberOfPages()+1 && $scope.go_page > -1) {
402 $scope.currentPage = $scope.go_page;
403 }
404 $scope.pageSize = $scope.pagination;
405 if($scope.go_page > $scope.numberOfPages()) {
406 $scope.currentPage = 0;
407 }
525 $scope.pageSize = $scope.newPageSize;
408526 $cookies.pageSize = $scope.pageSize;
527 $scope.currentPage = 0;
528 if($scope.newCurrentPage <= parseInt($scope.vulns.length/$scope.pageSize)
529 && $scope.newCurrentPage > -1 && !isNaN(parseInt($scope.newCurrentPage))) {
530 $scope.currentPage = $scope.newCurrentPage;
531 }
409532 };
410533
411534 // encodes search string in order to send it through URL
434557 for(var prop in chunks) {
435558 if(chunks.hasOwnProperty(prop)) {
436559 if(chunks.prop != "") {
437 encode += "&" + prop + "=" + chunks[prop];
560 encode += "&" + encodeURIComponent(prop) + "=" + encodeURIComponent(chunks[prop]);
438561 }
439562 }
440563 }
449572
450573 params.forEach(function(param) {
451574 i = param.indexOf("=");
452 decode[param.slice(0,i)] = param.slice(i+1);
575 decode[decodeURIComponent(param.slice(0,i))] = decodeURIComponent(param.slice(i+1));
453576 });
454577
455578 if(decode.hasOwnProperty("free")) {
513636 $scope.reverse = !$scope.reverse;
514637 };
515638
639 $scope.selectionChange = function() {
640 $scope.vulnWebSelected = $scope.selectedVulns().some(function(v) {
641 return v.type === "VulnerabilityWeb"
642 });
643 };
644
516645 init();
517646 }]);
22 <!-- See the file 'doc/LICENSE' for the license information -->
33
44 <form name="formEdit" novalidate>
5 <div class="modal-header">
6 <div class="modal-button">
7 <button class="btn btn-success" ng-click="ok()" ng-disabled="formEdit.$invalid">OK</button>
8 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
5 <div class="modal-header">
6 <div class="modal-button">
7 <button class="btn btn-success" ng-click="modal.ok()" ng-disabled="formEdit.$invalid">OK</button>
8 <button class="btn btn-danger" ng-click="modal.cancel()">Cancel</button>
9 </div>
10 <h3 class="modal-title">Vuln edit</h3>
911 </div>
10 <h3 class="modal-title">Bulk edit</h3>
11 </div>
12 <div class="modal-body">
13 <div ng-if="mixed">
14 <div class="alert alert-danger alert-dismissible" role="alert">
15 <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
16 <h5><strong>Hey!</strong> You have selected both vulnerabilities and web vulnerabilities. Please keep in mind that fields in red are specific for web vulnerabilities and these will not be added to regular vulnerabilities.</h5>
12 <div class="modal-body">
13 <div>
14 <h5><small>
15 Please choose a severity, name, description and data
16 </small></h5>
1717 </div>
18 </div><!-- ng-if -->
19 <div ng-if="!web">
20 <h5><small>
21 Please choose a severity, name, description and data
22 </small></h5>
23 </div><!-- ng-if -->
24 <div class="form-horizontal">
25 <div class="form-group">
26 <div class="col-md-6">
27 <h5>Severity</h5>
28 <select class="form-control" ng-model="severitySelection" ng-options="s as s for s in severities">
29 </select>
30 </div>
31 <div class="col-md-6">
32 <h5>Ease of Resolution</h5>
33 <select class="form-control" ng-model="easeOfResolutionSelection" ng-options="e as e for e in easeofresolution">
34 <option value=""></option>
35 </select>
36 </div>
37 </div><!-- .form-group -->
38 <div class="form-group">
39 <div class="col-md-12">
40 <label class="sr-only" for="vuln-name">Vuln name</label>
41 <input type="text" class="form-control" id="vuln-name" placeholder="Name" ng-model="name"/>
42 </div>
43 </div><!-- .form-group -->
44 <div class="form-group">
45 <div class="col-md-12">
46 <label class="sr-only" for="vuln-desc">Vuln description</label>
47 <textarea class="form-control" id="vuln-desc" placeholder="Description" value="{{p_desc}}" ng-model="desc"></textarea>
48 </div>
49 </div><!-- .form-group -->
50 <div class="form-group">
51 <div class="col-md-12">
52 <label class="sr-only" for="vuln-data">Vuln data</label>
53 <textarea class="form-control" id="vuln-data" placeholder="Data" value="{{p_data}}" ng-model="data"></textarea>
54 </div>
55 </div><!-- .form-group -->
56 <div class="form-group">
57 <div class="col-md-12">
58 <h4>References</h4>
59 <span class="input-group-addon button-radius" ng-click="newReference($event)">Add Reference</span>
60 </div>
61 <div class="col-md-12 reference" ng-repeat="reference in refs">
62 <div class="input-group margin-bottom-sm">
63 <label class="sr-only" for="vuln-refs">References</label>
64 <input type="text" class="form-control" id="vuln-refs" placeholder="Reference" ng-model="reference.key"/>
65 <span class="input-group-addon" ng-click="refs.splice($index, 1)"><i class="fa fa-minus-circle"></i></span>
18 <div class="form-horizontal">
19 <div class="form-group">
20 <div class="col-md-12">
21 <h5>CWE</h5>
22 <input type="text" ng-model="modal.cwe_selected" class="form-control input-sm" placeholder="Search for CWE" typeahead="cwe as cwe.name for cwe in modal.cweList | filter:{name: $viewValue} | limitTo:10" typeahead-on-select="modal.populate($item, $model, $label)">
6623 </div>
6724 </div>
68 </div><!-- .form-group -->
69 <div class="form-group">
70 <div class="col-md-12">
71 <label class="sr-only" for="vuln-resolution">Vuln Resolution</label>
72 <textarea class="form-control" id="vuln-resolution" placeholder="Resolution" ng-model="resolution"></textarea>
73 </div>
74 </div><!-- .form-group -->
75 <div ng-if="web">
7625 <div class="form-group">
77 <div class="col-md-4 has-error">
78 <label class="sr-only control-label" for="vuln-method">Method</label>
79 <input type="text" class="form-control input-error" id="vuln-method" value="{{p_method}}" placeholder="Method" ng-model="$parent.method"/>
26 <div class="col-md-6">
27 <h5>Severity</h5>
28 <select class="form-control" ng-model="modal.data.severity" ng-options="s as s for s in modal.severities" required>
29 </select>
8030 </div>
81 <div class="col-md-3 has-error">
82 <label class="sr-only control-label" for="vuln-pname">Param Name</label>
83 <input type="text" class="form-control input-error" id="vuln-pname" value="{{p_pname}}" placeholder="Param name" ng-model="$parent.pname"/>
84 </div>
85 <div class="col-md-5 has-error">
86 <label class="sr-only control-label" for="vuln-params">Params</label>
87 <input type="text" class="form-control input-error" id="vuln-params" value="{{p_params}}" placeholder="Params" ng-model="$parent.params"/>
31 <div class="col-md-6">
32 <h5>Ease of Resolution</h5>
33 <select class="form-control" ng-model="modal.data.easeofresolution" ng-options="e as e for e in modal.easeofresolution">
34 <option value=""></option>
35 </select>
8836 </div>
8937 </div><!-- .form-group -->
9038 <div class="form-group">
91 <div class="col-md-4 has-error">
92 <label class="sr-only control-label" for="vuln-path">Path</label>
93 <input type="text" class="form-control input-error" id="vuln-path" value="{{p_path}}" placeholder="Path" ng-model="$parent.path"/>
94 </div>
95 <div class="col-md-4 has-error">
96 <label class="sr-only control-label" for="vuln-query">Query</label>
97 <input type="text" class="form-control input-error" id="vuln-query" value="{{p_query}}"placeholder="Query" ng-model="$parent.query"/>
98 </div>
99 <div class="col-md-4 has-error">
100 <label class="sr-only control-label" for="vuln-website">Website</label>
101 <input type="text" class="form-control input-error" id="vuln-website" value="{{p_website}}" placeholder="Website" ng-model="$parent.website"/>
39 <div class="col-md-12">
40 <label class="sr-only" for="vuln-name">Vuln name</label>
41 <input type="text" class="form-control" id="vuln-name" placeholder="Name" ng-model="modal.data.name" required/>
10242 </div>
10343 </div><!-- .form-group -->
10444 <div class="form-group">
105 <div class="col-md-12 has-error">
106 <label class="sr-only control-label" for="vuln-request">Request</label>
107 <textarea class="form-control input-error" id="vuln-request" value="{{p_request}}" placeholder="Request" ng-model="$parent.request"></textarea>
45 <div class="col-md-12">
46 <label class="sr-only" for="vuln-desc">Vuln description</label>
47 <textarea class="form-control" id="vuln-desc" placeholder="Description" ng-model="modal.data.desc" required></textarea>
10848 </div>
10949 </div><!-- .form-group -->
11050 <div class="form-group">
111 <div class="col-md-12 has-error">
112 <label class="sr-only control-label" for="vuln-response">Response</label>
113 <textarea class="form-control input-error" id="vuln-response" value="{{p_response}}" placeholder="Response" ng-model="$parent.response"></textarea>
51 <div class="col-md-12">
52 <label class="sr-only" for="vuln-data">Vuln data</label>
53 <textarea class="form-control" id="vuln-data" placeholder="Data" ng-model="modal.data.data"></textarea>
11454 </div>
11555 </div><!-- .form-group -->
116 </div><!-- ng-if -->
117 </div><!-- .form-horizontal -->
56 <div class="form-group">
57 <div class="col-md-12">
58 <div class="input-group margin-bottom-sm">
59 <label class="sr-only" for="vuln-refs">References</label>
60 <input type="text" class="form-control" id="vuln-refs" placeholder="Reference" ng-model="modal.new_ref"/>
61 <span class="input-group-addon cursor" ng-click="modal.newReference()"><i class="fa fa-plus-circle"></i></span>
62 </div>
63 </div>
64 <div class="col-md-12 reference" ng-repeat="reference in modal.data.refs">
65 <div class="input-group margin-bottom-sm">
66 <label class="sr-only" for="vuln-refs">References</label>
67 <input type="text" class="form-control" id="vuln-refs" placeholder="Reference" ng-model="reference.value"/>
68 <span class="input-group-addon cursor" ng-click="modal.data.refs.splice($index, 1)"><i class="fa fa-minus-circle"></i></span>
69 </div>
70 </div>
71 </div><!-- .form-group -->
72 <div class="form-group">
73 <div class="col-md-12">
74 <label class="sr-only" for="vuln-resolution">Vuln Resolution</label>
75 <textarea class="form-control" id="vuln-resolution" placeholder="Resolution" ng-model="modal.data.resolution"></textarea>
76 </div>
77 </div><!-- .form-group -->
78 <div ng-if="modal.vuln.type === 'VulnerabilityWeb'">
79 <div class="form-group">
80 <div class="col-md-4">
81 <label class="sr-only control-label" for="vuln-method">Method</label>
82 <input type="text" class="form-control input-error" id="vuln-method" placeholder="Method" ng-model="modal.data.method"/>
83 </div>
84 <div class="col-md-3">
85 <label class="sr-only control-label" for="vuln-pname">Param Name</label>
86 <input type="text" class="form-control input-error" id="vuln-pname" placeholder="Param name" ng-model="modal.data.pname"/>
87 </div>
88 <div class="col-md-5">
89 <label class="sr-only control-label" for="vuln-params">Params</label>
90 <input type="text" class="form-control input-error" id="vuln-params" placeholder="Params" ng-model="modal.data.params"/>
91 </div>
92 </div><!-- .form-group -->
93 <div class="form-group">
94 <div class="col-md-4">
95 <label class="sr-only control-label" for="vuln-path">Path</label>
96 <input type="text" class="form-control input-error" id="vuln-path" placeholder="Path" ng-model="modal.data.path"/>
97 </div>
98 <div class="col-md-4">
99 <label class="sr-only control-label" for="vuln-query">Query</label>
100 <input type="text" class="form-control input-error" id="vuln-query" placeholder="Query" ng-model="modal.data.query"/>
101 </div>
102 <div class="col-md-4">
103 <label class="sr-only control-label" for="vuln-website">Website</label>
104 <input type="text" class="form-control input-error" id="vuln-website" placeholder="Website" ng-model="modal.data.website"/>
105 </div>
106 </div><!-- .form-group -->
107 <div class="form-group">
108 <div class="col-md-12">
109 <label class="sr-only control-label" for="vuln-request">Request</label>
110 <textarea class="form-control input-error" id="vuln-request" placeholder="Request" ng-model="modal.data.request"></textarea>
111 </div>
112 </div><!-- .form-group -->
113 <div class="form-group">
114 <div class="col-md-12">
115 <label class="sr-only control-label" for="vuln-response">Response</label>
116 <textarea class="form-control input-error" id="vuln-response" placeholder="Response" ng-model="modal.data.response"></textarea>
117 </div>
118 </div><!-- .form-group -->
119 </div><!-- ng-if -->
120 </div><!-- .form-horizontal -->
118121
119 <h4>Impact</h4>
120 <div ng-repeat="(key, value) in impact" class="normal-size" style="cursor: pointer;">
121 <h4><span ng-class="{'label label-default': !value, 'label label-success': value}" ng-click="toggleImpact(key)">{{key}}</span></h4>
122 </div><!-- .normal-size -->
122 <h4>Impact</h4>
123 <div ng-repeat="(key, value) in modal.data.impact" class="normal-size" style="cursor: pointer;">
124 <h4><span ng-class="{'label label-default': !value, 'label label-success': value}" ng-click="modal.toggleImpact(key)">{{key}}</span></h4>
125 </div><!-- .normal-size -->
123126
124 <div ng-if="vulnc == 1">
125 <h4>Evidence</h4>
126 <form>
127 <div class="alert alert-danger normal-size" role="alert" ng-if="file_name_error">
127 <div>
128 <h4>Evidence</h4>
129 <div class="alert alert-danger normal-size" role="alert" ng-if="modal.file_name_error">
128130 <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
129131 <span class="sr-only">Error:</span>
130132 Cannot upload evidence starting with underscore, please choose a different name for the file.
131133 </div>
132134 <div class="form-group normal-size">
133 <input type="file" id="evidence" ng-file-select ng-multiple="true" resetOnClick="false" ng-file-change="selectedFiles($files, $event)"/>
135 <input type="file" id="evidence" ng-file-select ng-multiple="true" resetOnClick="false" ng-file-change="modal.selectedFiles($files, $event)"/>
134136 <p class="help-block">Multiple files are allowed.</p>
135137 </div><!-- .form-group -->
136 </form>
137 <div id="evidenceFiles" class="normal-size" ng-if="evidence">
138 <ul>
139 <li ng-repeat="e in evidence | orderObjectBy:'name':true | orderBy:'name'">
140 <div class="btn-group">
141 <button type="button" class="btn btn-default">
142 <span class="fa {{icons[e.name]}}" title="Evidence {{e.name}}"></span> {{e.name}}
143 </button><!-- ng-repeat -->
144 <button type="button" class="btn btn-danger" ng-click="removeEvidence(e.name)">
145 <span class="glyphicon glyphicon-trash"></span>
146 </button>
147 </div>
148 </li>
149 </ul>
150 </div><!-- #evidenceFiles -->
151 </div><!-- ng-if -->
152
153 <h5><small>
154 Vulnerabilities to update
155 </small></h5>
156 <table class="csv-export status-report">
157 <thead>
158 <tr>
159 <th><a href="" ng-click="sortField = 'date'; reverse = !reverse">Date</a></th>
160 <th><a href="" ng-click="sortField = 'web'; reverse = !reverse">Web</a></th>
161 <th><a href="" ng-click="sortField = 'status'; reverse = !reverse">Status</a></th>
162 <th><a href="" ng-click="sortField = 'severity'; reverse = !reverse">Severity</a></th>
163 <th><a href="" ng-click="sortField = 'name'; reverse = !reverse">Name</a></th>
164 <th><a href="" ng-click="sortField = 'target'; reverse = !reverse">Target</a></th>
165 <th><a href="" ng-click="sortField = 'desc'; reverse = !reverse">Desc</a></th>
166 <th><a href="">Copy</a></th>
167 </tr>
168 </thead>
169 <tbody>
170 <tr ng-repeat="v in vulns | filter:isChecked | orderBy:sortField:reverse">
171 <td>{{v.date | date:'MM/dd/yyyy'}}</td>
172 <td>
173 <span class="glyphicon glyphicon-ok" ng-show="v.web"></span>
174 <span class="glyphicon glyphicon-remove" ng-show="!v.web"></span>
175 </td>
176 <td>Vulnerable</td>
177 <td>{{v.severity}}</td>
178 <td>{{v.name}}</td>
179 <td>{{v.target}}</td>
180 <td text-collapse text-collapse-max-length="50" text-collapse-text="{{v.desc}}"></td>
181 <td><i class="fa fa-copy copy-icon fa-lg" ng-click="pickVuln(v);call();"></i></td>
182 </tr>
183 </tbody>
184 </table><!-- #hosts -->
185 </div><!-- .modal-body -->
186 <div class="modal-footer">
187 <div class="modal-button">
188 <button class="btn btn-success" ng-click="ok()" ng-disabled="formEdit.$invalid">OK</button>
189 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
138 <div id="evidenceFiles" class="normal-size" ng-if="modal.data._attachments">
139 <ul>
140 <li ng-repeat="(name, file) in modal.data._attachments">
141 <div class="btn-group">
142 <button type="button" class="btn btn-default">
143 <span class="fa {{icons[name]}}" title="Evidence {{name | decodeURIComponent}}"></span> {{name | decodeURIComponent}}
144 </button><!-- ng-repeat -->
145 <button type="button" class="btn btn-danger" ng-click="modal.removeEvidence(name)">
146 <span class="glyphicon glyphicon-trash"></span>
147 </button>
148 </div>
149 </li>
150 </ul>
151 </div><!-- #evidenceFiles -->
152 </div><!-- ng-if -->
153 <div class="modal-footer">
154 <div class="modal-button">
155 <button class="btn btn-success" ng-click="modal.ok()" ng-disabled="formEdit.$invalid">OK</button>
156 <button class="btn btn-danger" ng-click="modal.cancel()">Cancel</button>
157 </div>
190158 </div>
191 </div>
192159 </form>
22 <!-- See the file 'doc/LICENSE' for the license information -->
33
44 <form name="form" novalidate>
5 <div class="modal-header">
6 <div class="modal-button">
7 <button class="btn btn-success" ng-click="ok()" ng-disabled="form.$invalid">OK</button>
8 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
5 <div class="modal-header">
6 <div class="modal-button">
7 <button class="btn btn-success" ng-click="modal.ok()" ng-disabled="form.$invalid">OK</button>
8 <button class="btn btn-danger" ng-click="modal.cancel()">Cancel</button>
9 </div>
10 <h3 class="modal-title">Vulnerability creation</h3>
911 </div>
10 <h3 class="modal-title">Vulnerability creation</h3>
11 </div>
12 <div class="modal-body">
13 <div class="form-horizontal">
14 <div class="form-group">
15 <div class="col-md-12">
16 <input type="text" ng-model="search_notes" class="form-control input-sm" placeholder="Search" ng-change="currentPage = 0">
17 <accordion close-others="true">
18 <accordion-group is-open="isopen" ng-repeat="host in hosts_with_services | filter:search_notes | startFrom:currentPage*pageSize | limitTo:pageSize">
19 <accordion-heading>
20 <a ng-click="selected(host,null)" ng-class="{'multi-selected': host.selected == true}">{{host.name}} ({{host.hostnames[0]}})</a>
21 <i class="pull-right glyphicon"
22 ng-class="{'glyphicon glyphicon-minus-sign': isopen, 'glyphicon glyphicon-plus-sign': !isopen}"></i>
23 </accordion-heading>
24 <div class="panel-body" ng-repeat="service in host.services">
25 <a ng-model="service" ng-click="selected(host,service)" ng-class="{'multi-selected': service.selected == true}">{{service.name}}</a>
26 </div>
27 </accordion-group>
28 </accordion>
29 <div class="showPagination" ng-show="showPagination">
30 <div class="form-group">
31 <ul class="pagination">
32 <li><a ng-hide="currentPage == 0" ng-click="currentPage=currentPage-1"><span aria-hidden="true">&laquo;</span><span class="sr-only">Previous</span></a></li>
33 <li><a>{{currentPage}}/{{numberOfPages()+1}}</a></li>
34 <li><a ng-hide="currentPage >= numberOfPages()+1" ng-click="currentPage=currentPage+1"><span aria-hidden="true">&raquo;</span><span class="sr-only">Next</span></a></li>
35 </ul>
36 <form name="goToPage">
37 <div class="col-md-2">
38 <input type="number" min="0" max="{{numberOfPages()+1}}" class="form-control" ng-model="go_page" placeholder="Go to page"/>
39 </div>
40 <button class="btn btn-danger" ng-click="go()">GO</button>
41 </form>
12 <div class="modal-body">
13 <div class="form-horizontal">
14 <div class="form-group">
15 <div class="col-md-12">
16 <input type="text" ng-model="modal.target_filter" class="form-control input-sm" placeholder="Search" ng-change="modal.currentPage = 0">
17 <accordion close-others="true">
18 <accordion-group is-open="isopen" ng-repeat="host in modal.targets_filtered = (modal.targets | filter:modal.target_filter) | startFrom:modal.currentPage*modal.pageSize | limitTo:modal.pageSize">
19 <accordion-heading>
20 <a ng-click="modal.setTarget(host)" ng-class="{'multi-selected': host.selected_modalNewCtrl == true}">{{host.name}} ({{host.hostnames[0]}})</a>
21 <i class="pull-right glyphicon"
22 ng-class="{'glyphicon glyphicon-minus-sign': isopen, 'glyphicon glyphicon-plus-sign': !isopen}"></i>
23 </accordion-heading>
24 <div class="panel-body" ng-repeat="service in host.services">
25 <a ng-model="service" ng-click="modal.setTarget(service)" ng-class="{'multi-selected': service.selected_modalNewCtrl == true}">{{service.name}}</a>
26 </div>
27 </accordion-group>
28 </accordion>
29 <div class="showPagination" ng-show="modal.targets_filtered.length > modal.pageSize">
30 <div class="form-group">
31 <ul class="pagination">
32 <li><a ng-hide="modal.currentPage <= 0" ng-click="modal.currentPage = modal.currentPage - 1"><span aria-hidden="true">&laquo;</span><span class="sr-only">Previous</span></a></li>
33 <li><a>{{modal.currentPage}}/{{ ((modal.targets_filtered.length / modal.pageSize) | integer)}}</a></li>
34 <li><a ng-hide="modal.currentPage >= ((modal.targets_filtered.length / modal.pageSize) | integer)" ng-click="modal.currentPage = modal.currentPage + 1"><span aria-hidden="true">&raquo;</span><span class="sr-only">Next</span></a></li>
35 </ul>
36 <ng-form name="goToPage">
37 <div class="col-md-2">
38 <input type="number" class="form-control" ng-model="modal.newCurrentPage" placeholder="Go to page"/>
39 </div>
40 <button class="btn btn-danger" ng-click="modal.go()">GO</button>
41 </ng-form>
42 </div>
4243 </div>
4344 </div>
4445 </div>
4546 </div>
46 </div>
47
48 <div class="alert alert-danger target_not_selected" role="alert" ng-hide="not_target_selected">
49 <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
50 <span class="sr-only">Error:</span>
51 There is no target selected
52 </div>
53 <div class="alert alert-danger target_not_selected" role="alert" ng-show="incompatible_vulnWeb">
54 <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
55 <span class="sr-only">Error:</span>
56 Vulnerability incompatible with host target, please select a service
57 </div>
58
59 <div class="form-horizontal">
60 <div class="form-group">
61 <div class="col-md-4">
62 <h5>Type</h5>
63 <select class="form-control" ng-model="vuln_type" ng-options="option.value as option.name for option in typeOptions">
64 </select>
47
48 <div class="alert alert-danger target_not_selected" role="alert" ng-hide="modal.data.parent != undefined">
49 <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
50 <span class="sr-only">Error:</span>
51 There is no target selected
6552 </div>
66 <div class="col-md-4">
67 <h5>Severity</h5>
68 <select class="form-control" ng-model="severitySelection" ng-options="s as s for s in severities" required>
69 </select>
53 <div class="alert alert-danger target_not_selected" role="alert" ng-show="modal.data.type === 'VulnerabilityWeb' && modal.data.parent.type === 'Host'">
54 <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
55 <span class="sr-only">Error:</span>
56 Vulnerability incompatible with host target, please select a service
57 </div>
58 <div class="form-horizontal">
59 <div class="form-group">
60 <div class="col-md-12">
61 <h5>CWE</h5>
62 <input type="text" ng-model="modal.cwe_selected" class="form-control input-sm" placeholder="Search for CWE" typeahead="cwe as cwe.name for cwe in modal.cweList | filter:{name: $viewValue} | limitTo:10" typeahead-on-select="modal.populate($item, $model, $label)">
63 </div>
7064 </div>
71 <div class="col-md-4">
72 <h5>Ease of Resolution</h5>
73 <select class="form-control" ng-model="easeOfResolutionSelection" ng-options="e as e for e in easeofresolution">
74 <option value=""></option>
75 </select>
76 </div>
77 </div><!-- .form-group -->
78 <div class="form-group">
79 <div class="col-md-12">
80 <label class="sr-only" for="vuln-name">Vuln name</label>
81 <input type="text" class="form-control" id="vuln-name" placeholder="Name" ng-model="name" required/>
82 </div>
83 </div><!-- .form-group -->
84 <div class="form-group">
85 <div class="col-md-12">
86 <label class="sr-only" for="vuln-desc">Vuln description</label>
87 <textarea class="form-control" id="vuln-desc" placeholder="Description" ng-model="desc" required></textarea>
88 </div>
89 </div><!-- .form-group -->
90 <div class="form-group">
91 <div class="col-md-12">
92 <label class="sr-only" for="vuln-data">Vuln data</label>
93 <textarea class="form-control" id="vuln-data" placeholder="Data" ng-model="data"></textarea>
94 </div>
95 </div><!-- .form-group -->
96 <div class="form-group">
97 <div class="col-md-12 reference" ng-repeat="reference in refs">
98 <div class="input-group margin-bottom-sm">
99 <label class="sr-only" for="vuln-refs">References</label>
100 <input type="text" class="form-control" id="vuln-refs" placeholder="Reference" ng-model="reference.key"/>
101 <span class="input-group-addon" ng-click="newReference($event)"><i class="fa fa-plus-circle"></i></span>
102 <span class="input-group-addon" ng-click="refs.splice($index, 1)" ng-hide="refs.length == 1"><i class="fa fa-minus-circle"></i></span>
103 </div>
104 </div>
105 </div><!-- .form-group -->
106 <div class="form-group">
107 <div class="col-md-12">
108 <label class="sr-only" for="vuln-resolution">Vuln Resolution</label>
109 <textarea class="form-control" id="vuln-resolution" placeholder="Resolution" ng-model="resolution"></textarea>
110 </div>
111 </div><!-- .form-group -->
112 </div>
113
114 <div class="animate-switch-container" ng-switch on="vuln_type">
115 <div class="animate-switch" ng-switch-when="VulnerabilityWeb">
116 <div class="form-horizontal">
117 <div class="form-group">
118 <div class="col-md-4">
119 <label class="sr-only control-label" for="vuln-method">Method</label>
120 <input type="text" class="form-control" id="vuln-method" placeholder="Method" ng-model="$parent.method"/>
121 </div>
122 <div class="col-md-3">
123 <label class="sr-only control-label" for="vuln-pname">Param Name</label>
124 <input type="text" class="form-control" id="vuln-pname" placeholder="Param name" ng-model="$parent.pname"/>
125 </div>
126 <div class="col-md-5">
127 <label class="sr-only control-label" for="vuln-params">Params</label>
128 <input type="text" class="form-control" id="vuln-params" placeholder="Params" ng-model="$parent.params"/>
129 </div>
130 </div><!-- .form-group -->
131 <div class="form-group">
132 <div class="col-md-4">
133 <label class="sr-only control-label" for="vuln-path">Path</label>
134 <input type="text" class="form-control" id="vuln-path" placeholder="Path" ng-model="$parent.path"/>
135 </div>
136 <div class="col-md-4">
137 <label class="sr-only control-label" for="vuln-query">Query</label>
138 <input type="text" class="form-control" id="vuln-query" placeholder="Query" ng-model="$parent.query"/>
139 </div>
140 <div class="col-md-4">
141 <label class="sr-only control-label" for="vuln-website">Website</label>
142 <input type="text" class="form-control" id="vuln-website" placeholder="Website" ng-model="$parent.website"/>
143 </div>
144 </div><!-- .form-group -->
145 <div class="form-group">
146 <div class="col-md-12">
147 <label class="sr-only control-label" for="vuln-request">Request</label>
148 <textarea class="form-control" id="vuln-request" placeholder="Request" ng-model="$parent.request"></textarea>
149 </div>
150 </div><!-- .form-group -->
151 <div class="form-group">
152 <div class="col-md-12">
153 <label class="sr-only control-label" for="vuln-response">Response</label>
154 <textarea class="form-control" id="vuln-response" placeholder="Response" ng-model="$parent.response"></textarea>
155 </div>
156 </div><!-- .form-group -->
157 </div><!-- .form-horizontal -->
158 </div><!-- .animate-switch -->
159 <div class="animate-switch" ng-switch-when="Vulnerability"></div>
160 </div><!-- .animate-switch-container -->
161
162 <h4>Impact</h4>
163 <div ng-repeat="(key, value) in impact" class="normal-size" style="cursor: pointer;">
164 <h4><span ng-class="{'label label-default': !value, 'label label-success': value}" ng-click="toggleImpact(key)">{{key}}</span></h4>
165 </div><!-- .normal-size -->
166
167 <h4>Evidence</h4>
168 <form>
169 <div class="alert alert-danger normal-size" role="alert" ng-if="file_name_error">
65 <div class="form-group">
66 <div class="col-md-4">
67 <h5>Type</h5>
68 <select class="form-control" ng-model="modal.data.type" ng-options="option.value as option.name for option in modal.vuln_types">
69 </select>
70 </div>
71 <div class="col-md-4">
72 <h5>Severity</h5>
73 <select class="form-control" ng-model="modal.data.severity" ng-options="s for s in modal.severities" required>
74 </select>
75 </div>
76 <div class="col-md-4">
77 <h5>Ease of Resolution</h5>
78 <select class="form-control" ng-model="modal.data.easeofresolution" ng-options="e for e in modal.easeofresolution">
79 <option value=""></option>
80 </select>
81 </div>
82 </div><!-- .form-group -->
83 <div class="form-group">
84 <div class="col-md-12">
85 <label class="sr-only" for="vuln-name">Vuln name</label>
86 <input type="text" class="form-control" id="vuln-name" placeholder="Name" ng-model="modal.data.name" required/>
87 </div>
88 </div><!-- .form-group -->
89 <div class="form-group">
90 <div class="col-md-12">
91 <label class="sr-only" for="vuln-desc">Vuln description</label>
92 <textarea class="form-control" id="vuln-desc" placeholder="Description" ng-model="modal.data.desc" required></textarea>
93 </div>
94 </div><!-- .form-group -->
95 <div class="form-group">
96 <div class="col-md-12">
97 <label class="sr-only" for="vuln-data">Vuln data</label>
98 <textarea class="form-control" id="vuln-data" placeholder="Data" ng-model="modal.data.data"></textarea>
99 </div>
100 </div><!-- .form-group -->
101 <div class="form-group">
102 <div class="col-md-12">
103 <div class="input-group margin-bottom-sm">
104 <label class="sr-only" for="vuln-refs">References</label>
105 <input type="text" class="form-control" id="vuln-refs" placeholder="Reference" ng-model="modal.new_ref"/>
106 <span class="input-group-addon cursor" ng-click="modal.newReference()"><i class="fa fa-plus-circle"></i></span>
107 </div>
108 </div>
109 <div class="col-md-12 reference" ng-repeat="reference in modal.data.refs">
110 <div class="input-group margin-bottom-sm">
111 <label class="sr-only" for="vuln-refs">References</label>
112 <input type="text" class="form-control" id="vuln-refs" placeholder="Reference" ng-model="reference.value"/>
113 <span class="input-group-addon cursor" ng-click="modal.data.refs.splice($index, 1)"><i class="fa fa-minus-circle"></i></span>
114 </div>
115 </div>
116 </div><!-- .form-group -->
117 <div class="form-group">
118 <div class="col-md-12">
119 <label class="sr-only" for="vuln-resolution">Vuln Resolution</label>
120 <textarea class="form-control" id="vuln-resolution" placeholder="Resolution" ng-model="modal.data.resolution"></textarea>
121 </div>
122 </div><!-- .form-group -->
123 </div>
124
125 <div class="animate-switch-container" ng-switch on="modal.data.type">
126 <div class="animate-switch" ng-switch-when="VulnerabilityWeb">
127 <div class="form-horizontal">
128 <div class="form-group">
129 <div class="col-md-4">
130 <label class="sr-only control-label" for="vuln-method">Method</label>
131 <input type="text" class="form-control" id="vuln-method" placeholder="Method" ng-model="modal.data.method"/>
132 </div>
133 <div class="col-md-3">
134 <label class="sr-only control-label" for="vuln-pname">Param Name</label>
135 <input type="text" class="form-control" id="vuln-pname" placeholder="Param name" ng-model="modal.data.pname"/>
136 </div>
137 <div class="col-md-5">
138 <label class="sr-only control-label" for="vuln-params">Params</label>
139 <input type="text" class="form-control" id="vuln-params" placeholder="Params" ng-model="modal.data.params"/>
140 </div>
141 </div><!-- .form-group -->
142 <div class="form-group">
143 <div class="col-md-4">
144 <label class="sr-only control-label" for="vuln-path">Path</label>
145 <input type="text" class="form-control" id="vuln-path" placeholder="Path" ng-model="modal.data.path"/>
146 </div>
147 <div class="col-md-4">
148 <label class="sr-only control-label" for="vuln-query">Query</label>
149 <input type="text" class="form-control" id="vuln-query" placeholder="Query" ng-model="modal.data.query"/>
150 </div>
151 <div class="col-md-4">
152 <label class="sr-only control-label" for="vuln-website">Website</label>
153 <input type="text" class="form-control" id="vuln-website" placeholder="Website" ng-model="modal.data.website"/>
154 </div>
155 </div><!-- .form-group -->
156 <div class="form-group">
157 <div class="col-md-12">
158 <label class="sr-only control-label" for="vuln-request">Request</label>
159 <textarea class="form-control" id="vuln-request" placeholder="Request" ng-model="modal.data.request"></textarea>
160 </div>
161 </div><!-- .form-group -->
162 <div class="form-group">
163 <div class="col-md-12">
164 <label class="sr-only control-label" for="vuln-response">Response</label>
165 <textarea class="form-control" id="vuln-response" placeholder="Response" ng-model="modal.data.response"></textarea>
166 </div>
167 </div><!-- .form-group -->
168 </div><!-- .form-horizontal -->
169 </div><!-- .animate-switch -->
170 <div class="animate-switch" ng-switch-when="Vulnerability"></div>
171 </div><!-- .animate-switch-container -->
172
173 <h4>Impact</h4>
174 <div ng-repeat="(key, value) in modal.data.impact" class="normal-size" style="cursor: pointer;">
175 <h4><span ng-class="{'label label-default': !value, 'label label-success': value}" ng-click="modal.toggleImpact(key)">{{key}}</span></h4>
176 </div><!-- .normal-size -->
177
178 <h4>Evidence</h4>
179 <div class="alert alert-danger normal-size" role="alert" ng-if="modal.file_name_error">
170180 <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
171181 <span class="sr-only">Error:</span>
172182 Cannot upload evidence starting with underscore, please choose a different name for the file.
173183 </div>
174184 <div class="form-group normal-size">
175 <input type="file" id="evidence" ng-file-select ng-multiple="true" resetOnClick="false" ng-file-change="selectedFiles($files, $event)"/>
185 <input type="file" id="evidence" ng-file-select ng-multiple="true" resetOnClick="false" ng-file-change="modal.selectedFiles($files, $event)"/>
176186 <p class="help-block">Multiple files are allowed.</p>
177187 </div><!-- .form-group -->
178 </form>
179 <div id="evidenceFiles" class="normal-size" ng-if="evidence">
180 <ul>
181 <li ng-repeat="e in evidence | orderObjectBy:'name':true | orderBy:'name'">
182 <div class="btn-group">
183 <button type="button" class="btn btn-default">
184 <span class="fa {{icons[e.name]}}" title="Evidence {{e.name}}"></span> {{e.name}}
185 </button><!-- ng-repeat -->
186 <button type="button" class="btn btn-danger" ng-click="removeEvidence(e.name)">
187 <span class="glyphicon glyphicon-trash"></span>
188 </button>
189 </div>
190 </li>
191 </ul>
192 </div><!-- #evidenceFiles -->
193 </div><!-- .modal-body -->
194 <div class="modal-footer">
195 <div class="modal-button">
196 <button class="btn btn-success" ng-disabled="form.$invalid" ng-click="ok()">OK</button>
197 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
188 <div id="evidenceFiles" class="normal-size" ng-if="modal.data._attachments">
189 <ul>
190 <li ng-repeat="e in modal.data._attachments | orderObjectBy:'name':true | orderBy:'name'">
191 <div class="btn-group">
192 <button type="button" class="btn btn-default">
193 <span class="fa {{icons[e.name]}}" title="Evidence {{e.name}}"></span> {{e.name}}
194 </button><!-- ng-repeat -->
195 <button type="button" class="btn btn-danger" ng-click="modal.removeEvidence(e.name)">
196 <span class="glyphicon glyphicon-trash"></span>
197 </button>
198 </div>
199 </li>
200 </ul>
201 </div><!-- #evidenceFiles -->
202 </div><!-- .modal-body -->
203 <div class="modal-footer">
204 <div class="modal-button">
205 <button class="btn btn-success" ng-disabled="form.$invalid" ng-click="modal.ok()">OK</button>
206 <button class="btn btn-danger" ng-click="modal.cancel()">Cancel</button>
207 </div>
198208 </div>
199 </div>
200209 </form>
2828 <span class="glyphicon glyphicon-trash"></span>
2929 Delete
3030 </button>
31 <button id="merge" type="button" class="btn btn-default" title="Edit selected vulns" ng-click="edit()">
32 <span class="glyphicon glyphicon-pencil"></span>
33 Edit
34 </button>
31 <div id="merge" class="btn-group btn-small-margin">
32 <button type="button" class="btn btn-default" title="Edit selected vulns" ng-click="edit()" ng-disabled="selectedVulns().length != 1">
33 <span class="glyphicon glyphicon-pencil"></span>
34 Edit
35 </button>
36 <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Actions" ng-hide="selectedVulns().length < 2">
37 <span class="caret"></span>
38 </button>
39 <ul class="dropdown-menu dropdown-menu-right" role="menu">
40 <li><a class="ws" ng-click="editString('name')">Edit name</a></li>
41 <li><a class="ws" ng-click="editText('desc', 'description')">Edit description</a></li>
42 <li><a class="ws" ng-click="editText('data')">Edit data</a></li>
43 <li><a class="ws" ng-click="editText('resolution')">Edit resolution</a></li>
44 <li><a class="ws" ng-click="editSeverity()">Edit severity</a></li>
45 <li><a class="ws" ng-click="editEaseofresolution()">Edit ease of resolution</a></li>
46 <li><a class="ws" ng-click="editReferences()">Add references</a></li>
47 <li><a class="ws" ng-click="editImpact()">Edit impact</a></li>
48 <li ng-show="vulnWebSelected" role="separator" class="divider"></li>
49 <li ng-show="vulnWebSelected"><a class="ws" ng-click="editString('method')">Edit method</a></li>
50 <li ng-show="vulnWebSelected"><a class="ws" ng-click="editString('pname', 'param name')">Edit param name</a></li>
51 <li ng-show="vulnWebSelected"><a class="ws" ng-click="editString('params', 'parameters')">Edit parameters</a></li>
52 <li ng-show="vulnWebSelected"><a class="ws" ng-click="editString('path')">Edit path</a></li>
53 <li ng-show="vulnWebSelected"><a class="ws" ng-click="editString('query')">Edit query</a></li>
54 <li ng-show="vulnWebSelected"><a class="ws" ng-click="editString('website')">Edit website</a></li>
55 <li ng-show="vulnWebSelected"><a class="ws" ng-click="editText('request')">Edit request</a></li>
56 <li ng-show="vulnWebSelected"><a class="ws" ng-click="editText('response')">Edit response</a></li>
57 <li role="separator" class="divider"></li>
58 <li><a class="ws" ng-click="editCWE()">From CWE</a></li>
59 </ul>
60 </div>
3561 <button id="new" type="button" class="btn btn-success" title="New Vulns" ng-click="new()">
3662 <span class="glyphicon glyphicon-plus-sign"></span>
3763 New
6894 <tr>
6995 <th><input type="checkbox" ng-model="selectall" ng-click="checkAll()"/></th>
7096 <th ng-if="columns.date">
71 <a href="" ng-click="toggleSort('date')">Date</a>
97 <a href="" ng-click="toggleSort('metadata.create_time')">Date</a>
7298 <a href="" ng-click="toggleShow('date', true)"><span class="glyphicon glyphicon-remove"></span></a>
7399 </th>
74100 <th ng-if="columns.target">
128154 <a href="" ng-click="toggleShow('resolution', true)"><span class="glyphicon glyphicon-remove"></span></a>
129155 </th>
130156 <th ng-if="columns.web">
131 <a href="" ng-click="toggleSort('web')">Web</a>
157 <a href="" ng-click="toggleSort('type')">Web</a>
132158 <a href="" ng-click="toggleShow('web', true)"><span class="glyphicon glyphicon-remove"></span></a>
133159 </th>
134160 <th ng-if="columns.website">
158184 </tr>
159185 </thead>
160186 <tbody>
161 <tr ng-repeat="v in vulns | orderObjectBy:sortField:reverse | startFrom:currentPage*pageSize | limitTo:pageSize"
187 <tr ng-repeat="v in filtered = (vulns | filter:expression) | orderObjectBy:sortField:reverse | startFrom:currentPage*pageSize | limitTo:pageSize"
162188 selection-model selection-model-type="checkbox"
163189 selection-model-mode="multiple-additive"
164 selection-model-selected-class="multi-selected">
190 selection-model-selected-attribute="selected_statusreport_controller"
191 selection-model-selected-class="multi-selected"
192 selection-model-on-change="selectionChange()">
165193 <td><input type="checkbox" name="{{v.id}}"/></td>
166 <td ng-if="columns.date">{{v.date | date:'MM/dd/yyyy'}}</td>
194 <td ng-if="columns.date">{{v.metadata.create_time * 1000 | date:'MM/dd/yyyy'}}</td>
167195 <td ng-if="columns.target">{{v.target}}</td>
168196 <td ng-if="columns.status">Vulnerable</td>
169197 <td ng-if="columns.severity"><span class="label vuln fondo-{{v.severity}}">{{v.severity}}</span></td>
179207 <td ng-if="columns.response" text-collapse text-collapse-max-length="100" text-collapse-text="{{v.response}}"></td>
180208 <td ng-if="columns.resolution">{{v.resolution}}</td>
181209 <td ng-if="columns.web">
182 <span class="glyphicon glyphicon-ok" ng-show="v.web"></span>
183 <span class="glyphicon glyphicon-remove" ng-show="!v.web"></span>
210 <span class="glyphicon glyphicon-ok" ng-show="v.type === 'VulnerabilityWeb'"></span>
211 <span class="glyphicon glyphicon-remove" ng-show="v.type !== 'VulnerabilityWeb'"></span>
184212 </td>
185213 <td ng-if="columns.website">{{v.website}}</td>
186 <td ng-if="columns.refs"><p ng-repeat="refs in v.refs">{{refs}}</p></td>
214 <td ng-if="columns.refs"><p ng-repeat="refs in v.refs track by $index">{{refs}}</p></td>
187215 <td ng-if="columns.evidence">
188 <div ng-repeat="e in v.attachments track by $index">
189 <a href="{{baseurl + workspace}}/{{ v.id}}/{{e}}" target="_blank">{{e}}</a>
216 <div ng-repeat="(name, file) in v._attachments track by $index">
217 <a ng-href="{{baseurl + workspace}}/{{v._id}}/{{name | encodeURIComponent}}" target="_blank">{{name | decodeURIComponent}}</a>
190218 </div>
191219 </td>
192220 <td ng-if="columns.impact">
195223 </div>
196224 </td>
197225 <td ng-if="columns.easeofresolution">{{v.easeofresolution}}</td>
198 <td ng-if="columns.hostnames"><p ng-repeat="hostname in v.hostnames">{{hostname}}</p></td>
226 <td ng-if="columns.hostnames"><p ng-repeat="hostname in v.hostnames track by $index">{{hostname}}</p></td>
199227 </tr>
200228 </tbody>
201229 </table><!-- #hosts -->
202 <div class="showPagination" ng-show="showPagination">
230 <div class="showPagination">
203231 <div class="form-group">
204232 <ul class="pagination">
205 <li><a ng-hide="currentPage == 0" ng-click="currentPage=currentPage-1"><span aria-hidden="true">&laquo;</span><span class="sr-only">Previous</span></a></li>
206 <li><a>{{currentPage}}/{{numberOfPages()}}</a></li>
207 <li><a ng-hide="currentPage >= numberOfPages()" ng-click="currentPage=currentPage+1"><span aria-hidden="true">&raquo;</span><span class="sr-only">Next</span></a></li>
233 <li><a ng-hide="currentPage <= 0" ng-click="currentPage = currentPage - 1"><span aria-hidden="true">&laquo;</span><span class="sr-only">Previous</span></a></li>
234 <li><a>{{currentPage}}/{{ ((filtered.length / pageSize) | integer)}}</a></li>
235 <li><a ng-hide="currentPage >= ((filtered.length / pageSize) | integer)" ng-click="currentPage = currentPage + 1"><span aria-hidden="true">&raquo;</span><span class="sr-only">Next</span></a></li>
208236 </ul>
209237 <form name="goToPage" id="goToPageStatus">
210238 <div class="col-md-2">
211 <input type="number" min="0" max="{{numberOfPages()}}" class="form-control" ng-model="go_page" placeholder="Go to page"/>
239 <input type="number" min="0" max="{{ (filtered.length / pageSize) | integer }}" class="form-control" ng-model="newCurrentPage" placeholder="Go to page"/>
212240 </div>
213241 <button class="btn btn-default" ng-click="go()">GO</button>
214 <input type="number" min="0" class="form-control vuln_per_page" ng-model="pagination" placeholder="Numbre page" />
242 <input type="number" min="0" class="form-control vuln_per_page" ng-model=newPageSize placeholder="Number page" />
215243 </form>
216244 </div>
217245 </div>
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('targetFact', ['BASEURL', '$q', 'hostsManager', 'servicesManager', function(BASEURL, $q, hostsManager, servicesManager) {
6 var targetFact = {};
7
8 targetFact.getTargets = function(workspace) {
9 var deferred = $q.defer();
10 var res = [];
11 var hosts_dict = {};
12 hostsManager.getHosts(workspace).then(function(hosts) {
13 hosts.forEach(function(host) {
14 host.hostnames = [];
15 host.services = [];
16 hosts_dict[host._id] = host;
17 res.push(host);
18 });
19 hostsManager.getAllInterfaces(workspace).then(function(interfaces) {
20 interfaces.forEach(function(interf) {
21 if (hosts_dict.hasOwnProperty(interf.parent)) {
22 hosts_dict[interf.parent].hostnames = hosts_dict[interf.parent].hostnames.concat(interf.hostnames);
23 }
24 });
25 }, function(err) {deferred.reject(err)});
26 servicesManager.getServices(workspace).then(function(services) {
27 services.forEach(function(service) {
28 host_id = service.parent.split(".")[0];
29 if (hosts_dict.hasOwnProperty(host_id)) {
30 hosts_dict[host_id].services.push(service);
31 }
32 });
33 }, function(err) {deferred.reject(err)});
34
35 deferred.resolve(res);
36
37 }, function(err) {deferred.reject(err)});
38
39 return deferred.promise;
40 };
41
42 return targetFact;
43 }]);
+0
-43
views/reports/_attachments/scripts/statusReport/services/statusReport.js less more
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('statusReportFact', ['vulnsFact', 'vulnsWebFact', 'hostsManager', 'workspacesFact', function(vulnsFact, vulnsWebFact, hostsManager, workspacesFact) {
6 var statusReportFact = {};
7
8 statusReportFact.getVulns = function(ws) {
9 var vulns = vulnsFact.get(ws);
10 var vulnsWeb = vulnsWebFact.get(ws);
11 var hosts = hostsManager.get(ws);
12 vulns.forEach(function(element, index, array) {
13 if (element.parent in hosts) {
14 element.target = hosts[element.parent].name;
15 }
16 });
17 vulnsWeb.forEach(function(element, index, array) {
18 if (element.parent in hosts) {
19 element.target = hosts[element.parent].name;
20 }
21 });
22 return vulnsWeb.concat(vulns);
23 };
24
25 statusReportFact.putVulns = function(ws, vuln, callback) {
26 if(vuln.web) {
27 vulnsWebFact.put(ws, vuln, callback);
28 } else {
29 vulnsFact.put(ws, vuln, callback);
30 }
31 };
32
33 statusReportFact.removeVulns = function(ws, vuln) {
34 vulnsFact.remove(ws, vuln);
35 };
36
37 statusReportFact.getWorkspaces = function() {
38 return workspacesFact.list();
39 };
40
41 return statusReportFact;
42 }]);
+0
-34
views/reports/_attachments/scripts/statusReport/services/target.js less more
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('targetFact', ['BASEURL', '$http', function(BASEURL, $http) {
6 var targetFact = {};
7
8 targetFact.getTarget = function(ws, need_hosts) {
9 if(need_hosts){
10 var hosts = [];
11 var url = BASEURL + ws + "/_design/hosts/_view/hosts";
12 $.getJSON(url, function(data) {
13 $.each(data.rows, function(n, obj) {
14 obj.value._id = obj.id;
15 hosts.push(obj.value);
16 });
17 });
18 return hosts;
19 }else{
20 var services = [];
21 var url = BASEURL + ws + "/_design/services/_view/byhost";
22 $.getJSON(url, function(data) {
23 $.each(data.rows, function(n, obj) {
24 obj.value._id = obj.id;
25 services.push(obj.value);
26 });
27 });
28 return services;
29 }
30 };
31
32 return targetFact;
33 }]);
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('Vuln', ['BASEURL', '$http', '$q', 'attachmentsFact',
6 function(BASEURL, $http, $q, attachmentsFact) {
7 Vuln = function(ws, data) {
8 var now = new Date(),
9 date = now.getTime() / 1000.0;
10
11 this._id = "";
12 this._rev = "";
13 this._attachments = {};
14 this.data = "";
15 this.desc = "";
16 this.easeofresolution = "";
17 this.hostnames = "";
18 this.impact = {
19 accountability: false,
20 availability: false,
21 confidentiality: false,
22 integrity: false
23 };
24 this.metadata = {
25 update_time: date,
26 update_user: "",
27 update_action: 0,
28 creator: "UI Web",
29 create_time: date,
30 update_controller_action: "UI Web New",
31 owner: ""
32 };
33 this.name = "";
34 this.obj_id = "";
35 this.owner = "";
36 this.owned = "";
37 this.parent = "";
38 this.refs = "";
39 this.resolution = "";
40 this.severity = "";
41 this.target = "";
42 this.type = "Vulnerability";
43 this.ws = "";
44
45 if(data) {
46 if(data.name === undefined || data.name === "") {
47 throw new Error("Unable to create Vuln without a name");
48 }
49 this.set(ws, data);
50 }
51 };
52
53 Vuln.prototype = {
54 public_properties: [
55 '_attachments', 'data', 'desc', 'easeofresolution',
56 'impact', 'name', 'owned', 'refs', 'resolution', 'severity'
57 ],
58 set: function(ws, data) {
59 var self = this;
60
61 // new vuln
62 if(data._id === undefined) {
63 var id = CryptoJS.SHA1(data.name + "." + data.desc).toString();
64 self._id = data.parent + "." + id;
65 self.obj_id = id;
66 } else {
67 self._id = data._id;
68 self.obj_id = data.obj_id;
69 if(data._rev !== undefined) self._rev = data._rev;
70 if(data.metadata !== undefined) self.metadata = data.metadata;
71 }
72
73 if(data.owner !== undefined) self.owner = data.owner;
74 self.ws = ws;
75 if(data.parent !== undefined) self.parent = data.parent;
76
77 self.public_properties.forEach(function(property) {
78 if(data[property] !== undefined) self[property] = data[property];
79 });
80 },
81 remove: function() {
82 var self = this,
83 url = BASEURL + self.ws + "/" + self._id + "?rev=" + self._rev;
84 return $http.delete(url);
85 },
86 _update: function(vuln, data) {
87 var deferred = $q.defer(),
88 self = this,
89 url = BASEURL + vuln.ws + "/" + vuln._id;
90
91 var now = new Date(),
92 date = now.getTime();
93
94 vuln.metadata.update_time = date;
95
96 vuln.public_properties.forEach(function(prop) {
97 if(data.hasOwnProperty(prop)) {
98 if(prop != "_attachments") vuln[prop] = data[prop];
99 }
100 });
101
102 if(data._attachments !== undefined) {
103 var files = {},
104 stubs = {};
105 vuln._attachments = {};
106
107 // the list of evidence may have mixed objects, some of them already in CouchDB, some of them new
108 // new attachments are of File type and need to be processed by attachmentsFact.loadAttachments
109 // old attachments are of type Object and they represent a Stub, nothing should be done to them
110 for(var name in data._attachments) {
111 if(data._attachments.hasOwnProperty(name)) {
112 if(data._attachments[name] instanceof File) {
113 files[name] = data._attachments[name];
114 } else {
115 stubs[name] = data._attachments[name];
116 }
117 }
118 }
119 angular.extend(vuln._attachments, stubs);
120 attachmentsFact.loadAttachments(files).then(function(atts) {
121 angular.extend(vuln._attachments, atts);
122 $http.put(url, vuln)
123 .success(function(response) {
124 self.set(self.ws, vuln);
125 self._rev = response.rev;
126 deferred.resolve();
127 })
128 .error(function() {
129 deferred.reject();
130 });
131 });
132 } else {
133 $http.put(url, vuln)
134 .success(function(response) {
135 self.set(self.ws, vuln);
136 self._rev = response.rev;
137 deferred.resolve();
138 })
139 .error(function() {
140 deferred.reject();
141 });
142 }
143
144 return deferred.promise;
145 },
146 update: function(data) {
147 var self = this,
148 vuln = new Vuln(self.ws, self);
149 return self._update(vuln, data);
150 },
151 populate: function() {
152 var deferred = $q.defer(),
153 self = this,
154 vuln = {};
155
156 vuln._id = self._id;
157 vuln.metadata = self.metadata;
158 vuln.obj_id = self.obj_id;
159 vuln.owner = self.owner;
160 vuln.parent = self.parent;
161 vuln.type = self.type;
162
163 self.public_properties.forEach(function(prop) {
164 if(prop !== "_attachments") vuln[prop] = self[prop];
165 });
166
167 if(self._attachments !== undefined) {
168 attachmentsFact.loadAttachments(self._attachments).then(function(atts) {
169 vuln._attachments = atts;
170 deferred.resolve(vuln);
171 }, function() {
172 deferred.reject("Unable to load attachments");
173 });
174 } else {
175 deferred.resolve(vuln);
176 }
177
178 return deferred.promise;
179 },
180 save: function() {
181 var deferred = $q.defer(),
182 loadAtt,
183 self = this,
184 url = BASEURL + self.ws + "/" + self._id;
185
186 self.populate().then(function(resp) {
187 $http.put(url, resp)
188 .success(function(data) {
189 self._rev = data.rev;
190 deferred.resolve(self);
191 })
192 .error(function(data, status, headers, config) {
193 deferred.reject(status);
194 });
195 }, function() {
196 deferred.reject();
197 });
198
199 return deferred.promise;
200 }
201 };
202
203 return Vuln;
204 }]);
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('vulnsManager',
6 ['Vuln', 'WebVuln', 'BASEURL', '$filter', '$http', '$q', 'attachmentsFact', 'hostsManager',
7 function(Vuln, WebVuln, BASEURL, $filter, $http, $q, attachmentsFact, hostsManager) {
8 var vulnsManager = {};
9
10 vulnsManager.vulns = [];
11 vulnsManager.vulns_indexes = {};
12
13 vulnsManager._loadHosts = function(hosts, interfaces) {
14 var res = {};
15
16 interfaces.forEach(function(interf) {
17 var host = interf.parent;
18 if(!res.hasOwnProperty(host)) res[host] = {};
19 if(!res[host].hasOwnProperty("hostnames")) res[host]["hostnames"] = [];
20 res[host]["hostnames"] = res[host]["hostnames"].concat(interf.hostnames);
21 });
22
23 hosts.forEach(function(host) {
24 if(!res.hasOwnProperty(host._id)) res[host._id] = {};
25 res[host._id]["target"] = host.name;
26 });
27
28 return res;
29 };
30
31 vulnsManager.createVuln = function(ws, data) {
32 var deferred = $q.defer(),
33 self = this;
34
35 try {
36 if(data.type == "Vulnerability") {
37 var vuln = new Vuln(ws, data);
38 } else {
39 var vuln = new WebVuln(ws, data);
40 }
41
42 vuln.save()
43 .then(function(resp) {
44 self.vulns_indexes[vuln._id] = self.vulns.length;
45 self.vulns.push(vuln);
46 var parents = [hostsManager.getHosts(ws), hostsManager.getAllInterfaces(ws)];
47
48 $q.all(parents)
49 .then(function(ps) {
50 var hosts = self._loadHosts(ps[0], ps[1]);
51
52 self.vulns.forEach(function(vuln) {
53 var pid = vuln.parent.split(".")[0];
54 if (hosts.hasOwnProperty(pid)) {
55 vuln.target = hosts[pid]["target"];
56 vuln.hostnames = hosts[pid]["hostnames"];
57 };
58 });
59 });
60
61 deferred.resolve(self.resp);
62 })
63 .catch(function(err) {
64 deferred.reject(err);
65 });
66 } catch(e) {
67 console.log(e.stack);
68 deferred.reject(e.name + ": " + e.message);
69 }
70
71 return deferred.promise;
72 };
73
74 vulnsManager.deleteVuln = function(vuln) {
75 var deferred = $q.defer();
76 self = this;
77 vuln.remove().then(function(){
78 var index = self.vulns_indexes[vuln._id];
79 for (var i = index + 1; i < self.vulns.length; i++) {
80 self.vulns_indexes[self.vulns[i]._id] = self.vulns_indexes[self.vulns[i]._id] - 1;
81 }
82 self.vulns.splice(self.vulns_indexes[vuln._id], 1);
83 delete self.vulns_indexes[vuln._id];
84 deferred.resolve();
85 }, function(err){
86 deferred.reject(err);
87 });
88
89 return deferred.promise
90 };
91
92 vulnsManager.getVulns = function(ws) {
93 var deferred = $q.defer(),
94 self = this;
95
96 $http.get(BASEURL + ws + '/_design/vulns/_view/all')
97 .success(function(data) {
98 self.vulns.splice(0, self.vulns.length);
99 self.vulns_indexes = {};
100 for(var i = 0; i < data.rows.length; i++) {
101 var vulnData = data.rows[i].value;
102 try {
103 if(vulnData.type == "Vulnerability") {
104 var vuln = new Vuln(ws, vulnData);
105 } else {
106 var vuln = new WebVuln(ws, vulnData);
107 }
108 self.vulns_indexes[vuln._id] = self.vulns.length;
109 self.vulns.push(vuln);
110 } catch(e) {
111 console.log(e.stack);
112 }
113 }
114
115 var parents = [hostsManager.getHosts(ws), hostsManager.getAllInterfaces(ws)];
116
117 $q.all(parents)
118 .then(function(ps) {
119 var hosts = self._loadHosts(ps[0], ps[1]);
120
121 self.vulns.forEach(function(vuln) {
122 var pid = vuln.parent.split(".")[0];
123 if (hosts.hasOwnProperty(pid)) {
124 vuln.target = hosts[pid]["target"];
125 vuln.hostnames = hosts[pid]["hostnames"];
126 }
127 });
128 });
129
130 deferred.resolve(self.vulns);
131 })
132 .error(function() {
133 deferred.reject("Unable to retrieve vulnerabilities from Couch");
134 });
135
136 return deferred.promise;
137 };
138
139 vulnsManager.updateVuln = function(vuln, data) {
140 var deferred = $q.defer();
141 self = this;
142 vuln.update(data).then(function(){
143 self.vulns[self.vulns_indexes[vuln._id]] = vuln;
144 }, function(err){
145 deferred.reject(err);
146 });
147 return deferred.promise
148 };
149
150 return vulnsManager;
151 }]);
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('WebVuln', ['Vuln', 'BASEURL', '$http', function(Vuln, BASEURL, $http) {
6 WebVuln = function(ws, data) {
7 if(data) {
8 if(data.name === undefined || data.name === "") {
9 throw new Error("Unable to create Vuln without a name");
10 }
11 this.set(ws, data);
12 }
13 };
14
15 var public_properties = [
16 'method', 'params', 'path', 'pname', 'query',
17 'request', 'response', 'website'
18 ];
19
20 WebVuln.prototype = new Vuln();
21
22 WebVuln.prototype.public_properties = Vuln.prototype.public_properties.concat(public_properties);
23
24 WebVuln.prototype.set = function(ws, data) {
25 var self = this;
26
27 Vuln.prototype.set.call(self, ws, data);
28
29 // new vuln
30 if(data._id === undefined) {
31 var id = CryptoJS.SHA1(data.name + "." + data.website + "." + data.path + "." + data.desc).toString();
32
33 self._id = data.parent + "." + id;
34 self.obj_id = id;
35 }
36
37 self.type = "VulnerabilityWeb";
38
39 public_properties.forEach(function(property) {
40 if(data[property] !== undefined) self[property] = data[property];
41 });
42 };
43
44 WebVuln.prototype.update = function(data) {
45 var self = this,
46 vuln = new WebVuln(self.ws, self);
47 return Vuln.prototype._update.call(self, vuln, data);
48 };
49
50 WebVuln.prototype.populate = function() {
51 var self = this,
52 vuln = Vuln.prototype.populate.call(self);
53
54 public_properties.forEach(function(property) {
55 vuln[property] = self[property];
56 });
57
58 return vuln;
59 };
60
61 return WebVuln;
62 }]);
+0
-116
views/reports/_attachments/scripts/vulns/services/vulns.js less more
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('vulnsFact', ['BASEURL', '$http', '$q', 'attachmentsFact', function(BASEURL, $http, $q, attachmentsFact) {
6 var vulnsFact = {};
7
8 vulnsFact.get = function(ws) {
9 var vulns = [];
10 vulns_url = BASEURL + ws +"/_design/vulns/_view/vulns";
11 // gets vulns json from couch
12 $.getJSON(vulns_url, function(data) {
13 $.each(data.rows, function(n, obj){
14 var evidence = [],
15 date = obj.value.date * 1000;
16 if(typeof(obj.value.attachments) != undefined && obj.value.attachments != undefined) {
17 for(var attachment in obj.value.attachments) {
18 evidence.push(attachment);
19 }
20 }
21 var v = {
22 "id": obj.id,
23 "rev": obj.value.rev,
24 "attachments": evidence,
25 "couch_parent": obj.value.parent,
26 "data": obj.value.data,
27 "date": date,
28 "delete": false,
29 "desc": obj.value.desc,
30 "easeofresolution": obj.value.easeofresolution,
31 "impact": obj.value.impact,
32 "meta": obj.value.meta,
33 "name": obj.value.name,
34 "oid": obj.value.oid,
35 "owned": obj.value.owned,
36 "owner": obj.value.owner,
37 "parent": obj.key.substring(0, obj.key.indexOf('.')),
38 "refs": obj.value.refs,
39 "resolution": obj.value.resolution,
40 "selected": false,
41 "severity": obj.value.severity,
42 "type": obj.value.type,
43 "web": false
44 };
45 vulns.push(v);
46 });
47 });
48 return vulns;
49 }
50
51 vulnsFact.put = function(ws, vuln, callback) {
52 var url = BASEURL + ws + "/" + vuln.id,
53 v = {
54 "_rev": vuln.rev,
55 "data": vuln.data,
56 "desc": vuln.desc,
57 "easeofresolution": vuln.easeofresolution,
58 "impact": vuln.impact,
59 "metadata": vuln.meta,
60 "name": vuln.name,
61 "obj_id": vuln.oid,
62 "owned": vuln.owned,
63 "owner": vuln.owner,
64 "parent": vuln.couch_parent,
65 "refs": vuln.refs,
66 "resolution": vuln.resolution,
67 "severity": vuln.severity,
68 "type": vuln.type
69 };
70 if(typeof(vuln.evidence) != undefined && vuln.evidence != undefined) {
71 // the list of evidence may have mixed objects, some of them already in CouchDB, some of them new
72 // new attachments are of File type and need to be processed by attachmentsFact.loadAttachments
73 // old attachments are of type String (file name) and need to be processed by attachmentsFact.getStubs
74 var stubs = [],
75 files = [],
76 names = [],
77 promises = [];
78 v._attachments = {};
79
80 for(var name in vuln.evidence) {
81 if(vuln.evidence[name] instanceof File) {
82 files.push(vuln.evidence[name]);
83 } else {
84 stubs.push(name);
85 }
86 }
87
88 if(stubs.length > 0) promises.push(attachmentsFact.getStubs(ws, vuln.id, stubs));
89 if(files.length > 0) promises.push(attachmentsFact.loadAttachments(files));
90
91 $q.all(promises).then(function(result) {
92 result.forEach(function(atts) {
93 for(var name in atts) {
94 v._attachments[name] = atts[name];
95 names.push(name);
96 }
97 });
98 $http.put(url, v).success(function(d, s, h, c) {
99 callback(d.rev, names);
100 });
101 });
102 } else {
103 $http.put(url, v).success(function(d, s, h, c) {
104 callback(d.rev, []);
105 });
106 }
107 };
108
109 vulnsFact.remove = function(ws, vuln) {
110 var url = BASEURL + ws + "/" + vuln.id + "?rev=" + vuln.rev;
111 $http.delete(url).success(function(d, s, h, c) {});
112 };
113
114 return vulnsFact;
115 }]);
+0
-134
views/reports/_attachments/scripts/vulnsWeb/services/vulnsWeb.js less more
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('vulnsWebFact', ['BASEURL', '$http', '$q', 'attachmentsFact', function(BASEURL, $http, $q, attachmentsFact) {
6 var vulnsWebFact = {};
7
8 vulnsWebFact.get = function(ws) {
9 var vulns = [];
10 vulns_url = BASEURL + ws +"/_design/vulns/_view/web";
11 // gets vulns json from couch
12 $.getJSON(vulns_url, function(data) {
13 $.each(data.rows, function(n, obj){
14 var evidence = [],
15 date = obj.value.date * 1000;
16 if(typeof(obj.value.attachments) != undefined && obj.value.attachments != undefined) {
17 for(var attachment in obj.value.attachments) {
18 evidence.push(attachment);
19 }
20 }
21 var v = {
22 "id": obj.id,
23 "rev": obj.value.rev,
24 "attachments": evidence,
25 "couch_parent": obj.value.parent,
26 "data": obj.value.data,
27 "date": date,
28 "delete": false,
29 "desc": obj.value.desc,
30 "easeofresolution": obj.value.easeofresolution,
31 "impact": obj.value.impact,
32 "meta": obj.value.meta,
33 "name": obj.value.name,
34 "oid": obj.value.oid,
35 "owned": obj.value.owned,
36 "owner": obj.value.owner,
37 "parent": obj.key.substring(0, obj.key.indexOf('.')),
38 "refs": obj.value.refs,
39 "resolution": obj.value.resolution,
40 "selected": false,
41 "severity": obj.value.severity,
42 "type": obj.value.type,
43 "web": true,
44 /*** specific fields of web vulns ***/
45 "method": obj.value.method,
46 "params": obj.value.params,
47 "path": obj.value.path,
48 "pname": obj.value.pname,
49 "query": obj.value.query,
50 "request": obj.value.request,
51 "response": obj.value.response,
52 "website": obj.value.website
53 };
54 vulns.push(v);
55 });
56 });
57 return vulns;
58 }
59
60 vulnsWebFact.put = function(ws, vuln, callback) {
61 var url = BASEURL + ws + "/" + vuln.id;
62 var v = {
63 "_rev": vuln.rev,
64 "data": vuln.data,
65 "desc": vuln.desc,
66 "easeofresolution": vuln.easeofresolution,
67 "impact": vuln.impact,
68 "metadata": vuln.meta,
69 "name": vuln.name,
70 "obj_id": vuln.oid,
71 "owned": vuln.owned,
72 "owner": vuln.owner,
73 "parent": vuln.couch_parent,
74 "refs": vuln.refs,
75 "resolution": vuln.resolution,
76 "severity": vuln.severity,
77 "type": vuln.type,
78 /*** specific fields of web vulns ***/
79 "method": vuln.method,
80 "params": vuln.params,
81 "path": vuln.path,
82 "pname": vuln.pname,
83 "query": vuln.query,
84 "request": vuln.request,
85 "response": vuln.response,
86 "website": vuln.website
87 };
88 if(typeof(vuln.evidence) != undefined && vuln.evidence != undefined) {
89 // the list of evidence may have mixed objects, some of them already in CouchDB, some of them new
90 // new attachments are of File type and need to be processed by attachmentsFact.loadAttachments
91 // old attachments are of type String (file name) and need to be processed by attachmentsFact.getStubs
92 var stubs = [],
93 files = [],
94 names = [],
95 promises = [];
96 v._attachments = {};
97
98 for(var name in vuln.evidence) {
99 if(vuln.evidence[name] instanceof File) {
100 files.push(vuln.evidence[name]);
101 } else {
102 stubs.push(name);
103 }
104 }
105
106 if(stubs.length > 0) promises.push(attachmentsFact.getStubs(ws, vuln.id, stubs));
107 if(files.length > 0) promises.push(attachmentsFact.loadAttachments(files));
108
109 $q.all(promises).then(function(result) {
110 result.forEach(function(atts) {
111 for(var name in atts) {
112 v._attachments[name] = atts[name];
113 names.push(name);
114 }
115 });
116 $http.put(url, v).success(function(d, s, h, c) {
117 callback(d.rev, names);
118 });
119 });
120 } else {
121 $http.put(url, v).success(function(d, s, h, c) {
122 callback(d.rev, []);
123 });
124 }
125 };
126
127 vulnsWebFact.remove = function(ws, vuln) {
128 var url = BASEURL + ws + "/" + vuln.id + "?rev=" + vuln.rev;
129 $http.delete(url).success(function(d, s, h, c) {});
130 };
131
132 return vulnsWebFact;
133 }]);
44 angular.module('faradayApp')
55 .controller('workspacesCtrl', ['$modal', '$scope', '$q', 'workspacesFact', 'dashboardSrv',
66 function($modal, $scope, $q, workspacesFact, dashboardSrv) {
7 $scope.workspaces = [];
8 $scope.wss = [];
9 $scope.objects = {};
10 // $scope.newworkspace = {};
7 $scope.hash;
8 $scope.objects;
9 $scope.workspaces;
10 $scope.wss;
11
12 $scope.init = function() {
13 $scope.objects = [];
14 $scope.workspaces = [];
15 $scope.wss = [];
16 // $scope.newworkspace = {};
17
18 var hash_tmp = window.location.hash.split("/")[1];
19 switch (hash_tmp){
20 case "status":
21 $scope.hash = "status";
22 break;
23 case "dashboard":
24 $scope.hash = "dashboard";
25 break;
26 case "hosts":
27 $scope.hash = "hosts";
28 break;
29 default:
30 $scope.hash = "";
31 }
32
33 // todo: refactor the following code
34 workspacesFact.list().then(function(wss) {
35 $scope.wss = wss;
36 var objects = {};
37 $scope.wss.forEach(function(ws){
38 workspacesFact.get(ws).then(function(resp) {
39 $scope.onSuccessGet(resp);
40 });
41 objects[ws] = dashboardSrv.getObjectsCount(ws);
42 });
43 $q.all(objects).then(function(os) {
44 for(var workspace in os) {
45 if(os.hasOwnProperty(workspace)) {
46 $scope.objects[workspace] = {
47 "total vulns": "-",
48 "hosts": "-",
49 "services": "-"
50 };
51 os[workspace].forEach(function(o) {
52 $scope.objects[workspace][o.key] = o.value;
53 });
54 }
55 }
56 });
57 });
58 };
1159
1260 $scope.onSuccessGet = function(workspace){
1361 if(workspace.sdate.toString().indexOf(".") != -1) workspace.sdate = workspace.sdate * 1000;
1664 };
1765
1866 $scope.onSuccessInsert = function(workspace){
19 workspace.sdate = workspace.sdate;
2067 $scope.wss.push(workspace.name);
2168 $scope.workspaces.push(workspace);
2269 };
4087 $scope.workspaces[i].description = workspace.description;
4188 $scope.workspaces[i].duration.start = workspace.duration.start;
4289 $scope.workspaces[i].duration.end = workspace.duration.end;
90 $scope.workspaces[i].scope = workspace.scope;
4391 break;
4492 }
4593 };
63111 }
64112 };
65113 };
66
67 // todo: refactor the following code
68 workspacesFact.list().then(function(wss) {
69 $scope.wss = wss;
70 var objects = {};
71 $scope.wss.forEach(function(ws){
72 workspacesFact.get(ws, $scope.onSuccessGet);
73 objects[ws] = dashboardSrv.getObjectsCount(ws);
74 });
75 $q.all(objects).then(function(os) {
76 for(var workspace in os) {
77 if(os.hasOwnProperty(workspace)) {
78 $scope.objects[workspace] = {
79 "total vulns": "-",
80 "hosts": "-",
81 "services": "-"
82 };
83 os[workspace].forEach(function(o) {
84 $scope.objects[workspace][o.key] = o.value;
85 });
86 }
87 }
88 });
89 });
90
91 var hash_tmp = window.location.hash.split("/")[1];
92 switch (hash_tmp){
93 case "status":
94 $scope.hash = "status";
95 break;
96 case "dashboard":
97 $scope.hash = "dashboard";
98 break;
99 case "hosts":
100 $scope.hash = "hosts";
101 break;
102 default:
103 $scope.hash = "";
104 }
105
106
114
107115 $scope.insert = function(workspace){
108116 delete workspace.selected;
109117 workspacesFact.put(workspace).then(function(resp){
112120 $scope.onFailInsert);
113121 };
114122
115 $scope.update = function(workspace){
116 if(typeof(workspace.duration.startDate) == "number") {
117 start = workspace.duration.startDate;
118 } else if(workspace.duration.startDate) {
119 start = workspace.duration.startDate.getTime();
123 $scope.update = function(ws){
124 if(typeof(ws.duration.start) == "number") {
125 start = ws.duration.start;
126 } else if(ws.duration.start) {
127 start = ws.duration.start.getTime();
120128 } else {start = "";}
121 if(typeof(workspace.duration.endDate) == "number") {
122 end = workspace.duration.endDate;
123 } else if(workspace.duration.endDate) {
124 end = workspace.duration.endDate.getTime();
129 if(typeof(ws.duration.end) == "number") {
130 end = ws.duration.end;
131 } else if(ws.duration.end) {
132 end = ws.duration.end.getTime();
125133 } else {end = "";}
126134 duration = {'start': start, 'end': end};
127135 workspace = {
128 "_id": workspace._id,
129 "_rev": workspace._rev,
130 "children": workspace.children,
131 "customer": workspace.customer,
132 "description": workspace.description,
136 "_id": ws._id,
137 "_rev": ws._rev,
138 "children": ws.children,
139 "customer": ws.customer,
140 "description": ws.description,
133141 "duration": duration,
134 "name": workspace.name,
135 "scope": workspace.scope,
136 "sdate": workspace.sdate,
137 "selected": workspace.selected,
138 "type": workspace.type
139 };
140 workspacesFact.update(workspace, $scope.onSuccessEdit);
142 "name": ws.name,
143 "scope": ws.scope,
144 "sdate": ws.sdate,
145 "type": ws.type
146 };
147 workspacesFact.update(workspace).then(function(workspace) {
148 $scope.onSuccessEdit(workspace);
149 });
141150 };
142151
143152 $scope.remove = function(workspace_name){
144 workspacesFact.delete(workspace_name, $scope.onSuccessDelete);
153 workspacesFact.delete(workspace_name).then(function(resp) {
154 $scope.onSuccessDelete(resp);
155 });
145156 };
146157
147158 // Modals methods
148159 $scope.new = function(){
149 $scope.newworkspace = {};
150
151160 $scope.modal = $modal.open({
152161 templateUrl: 'scripts/workspaces/partials/modalNew.html',
153 controller: 'workspacesCtrl',
154 scope: $scope,
162 controller: 'workspacesModalNew',
155163 size: 'lg'
156164 });
157165
162170
163171 };
164172
165 $scope.okNew = function(){
166 $scope.modal.close($scope.newworkspace);
167 };
168
169173 $scope.edit = function(){
170 var selected = false;
174 var workspace;
171175 $scope.workspaces.forEach(function(w) {
172176 if(w.selected) {
173 selected = true;
174 return;
175 }
176 });
177
178 if(selected){
179 $scope.workspaces.forEach(function(w){
180 if(w.selected){
181 $scope.newworkspace = w;
182 if($scope.newworkspace.duration){
183 $scope.newworkspace.duration.startDate = w.duration.start;
184 $scope.newworkspace.duration.endDate = w.duration.end;
185 }
186 }
187 });
188 $scope.modal = $modal.open({
177 workspace = w;
178 }
179 });
180
181 if(workspace){
182 var modal = $modal.open({
189183 templateUrl: 'scripts/workspaces/partials/modalEdit.html',
190 controller: 'workspacesCtrl',
191 scope: $scope,
192 size: 'lg'
193 });
194
195 $scope.modal.result.then(function(workspace) {
196 $scope.update(workspace);
184 controller: 'workspacesModalEdit',
185 size: 'lg',
186 resolve: {
187 ws: function() {
188 return workspace;
189 }
190 }
191 });
192
193 modal.result.then(function(workspace) {
194 if(workspace != undefined){
195 $scope.update(workspace);
196 }
197197 });
198198 } else {
199199 var modal = $modal.open({
207207 });
208208 }
209209
210 };
211
212 $scope.okEdit = function() {
213 $scope.modal.close($scope.newworkspace);
214 };
215
216
217 $scope.cancel = function() {
218 $scope.modal.close();
219210 };
220211
221212 $scope.delete = function() {
270261 if(start) start = start.getTime(); else start = "";
271262 workspace = {
272263 "_id": wname,
273 "_rev": "2-bd88abf79cf2b7e8b419cd4387c64bef",
274264 "customer": "",
275265 "sdate": (new Date).getTime(),
276266 "name": wname,
286276
287277 };
288278
289 //DATE PICKER
290 $scope.today = function() {
291 $scope.dt = new Date();
292 };
293 $scope.today();
294
295 $scope.clear = function () {
296 $scope.dt = null;
297 };
298
299 $scope.minDate = new Date();
300
301 $scope.open = function($event, isStart) {
302 $event.preventDefault();
303 $event.stopPropagation();
304
305 if(isStart) $scope.openedStart = true; else $scope.openedEnd = true;
306 };
307
308 $scope.dateOptions = {
309 formatYear: 'yy',
310 startingDay: 1
311 };
312
279 $scope.init();
313280 }]);
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .controller('workspacesModalEdit', ['$modalInstance', '$scope', 'ws',
6 function($modalInstance, $scope, ws) {
7 $scope.minDate;
8 $scope.dateOptions;
9 $scope.workspace;
10
11 init = function () {
12 $scope.minDate = new Date();
13 $scope.dateOptions = {
14 formatYear: 'yy',
15 startingDay: 1
16 };
17
18 $scope.workspace = angular.copy(ws);
19 };
20
21 //DATE PICKER
22 $scope.today = function() {
23 $scope.dt = new Date();
24 };
25 $scope.today();
26
27 $scope.clear = function () {
28 $scope.dt = null;
29 };
30
31 $scope.open = function($event, isStart) {
32 $event.preventDefault();
33 $event.stopPropagation();
34
35 if(isStart) $scope.openedStart = true; else $scope.openedEnd = true;
36 };
37
38 $scope.okEdit = function() {
39 $modalInstance.close($scope.workspace);
40 };
41
42 $scope.cancel = function() {
43 $modalInstance.dismiss('cancel');
44 };
45
46 init();
47 }]);
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .controller('workspacesModalNew', ['$modalInstance', '$scope',
6 function($modalInstance, $scope) {
7
8 $scope.minDate;
9 $scope.dateOptions;
10 $scope.workspace;
11
12 init = function () {
13 $scope.workspace = {
14 "description": "",
15 "name": "",
16 "scope": ""
17 };
18 };
19
20 //DATE PICKER
21 $scope.today = function() {
22 $scope.dt = new Date();
23 };
24 $scope.today();
25
26 $scope.clear = function () {
27 $scope.dt = null;
28 };
29
30 $scope.open = function($event, isStart) {
31 $event.preventDefault();
32 $event.stopPropagation();
33
34 if(isStart) $scope.openedStart = true; else $scope.openedEnd = true;
35 };
36
37 $scope.okNew = function(){
38 $modalInstance.close($scope.workspace);
39 };
40
41 $scope.cancel = function() {
42 $modalInstance.dismiss('cancel');
43 };
44
45 init();
46 }]);
11 <!-- Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/) -->
22 <!-- See the file 'doc/LICENSE' for the license information -->
33
4 <div class="modal-header">
5 <div class="modal-button">
6 <button class="btn btn-success" ng-click="okEdit()">OK</button>
7 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
4 <form>
5 <div class="modal-header">
6 <div class="modal-button">
7 <button class="btn btn-success" ng-click="okEdit()">OK</button>
8 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
9 </div>
10 <h3 class="modal-title">Edit Workspace: {{workspace.name}}</h3>
811 </div>
9 <h3 class="modal-title">Edit Workspace: {{newworkspace.name}}</h3>
10 </div>
11 <div class="modal-body">
12 <div class="form-horizontal">
13 <div class="form-group">
14 <div class="col-md-12">
15 <label class="sr-only" for="vuln-desc">Workspace Description</label>
16 <textarea class="form-control" id="vuln-desc"
17 placeholder="Description" value={{newworkspace.description}}
18 ng-model="newworkspace.description" required></textarea>
19 </div>
20 </div><!-- .form-group -->
21 <div class="form-group">
22 <div class="col-md-6">
23 <h5>Start Date</h5>
24 <label class="sr-only" for="work-start">Start Date</label>
25 <p class="input-group">
26 <input type="text" class="form-control" datepicker-popup="MM/dd/yyyy" ng-model="newworkspace.duration.startDate" is-open="openedStart" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" close-text="Close" placeholder="Start Date"/>
27 <span class="input-group-btn">
28 <button type="button" class="btn btn-default" ng-click="open($event,true)"><i class="glyphicon glyphicon-calendar"></i></button>
29 </span>
30 </p>
31 </div>
32 <div class="col-md-6">
33 <h5>End Date</h5>
34 <label class="sr-only" for="work-end">End Date</label>
35 <p class="input-group">
36 <input type="text" class="form-control" datepicker-popup="MM/dd/yyyy" ng-model="newworkspace.duration.endDate" is-open="openedEnd" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" close-text="Close" placeholder="End Date"/>
37 <span class="input-group-btn">
38 <button type="button" class="btn btn-default" ng-click="open($event)"><i class="glyphicon glyphicon-calendar"></i></button>
39 </span>
40 </p>
41 </div>
12 <div class="modal-body">
13 <div class="form-horizontal">
14 <div class="form-group">
15 <div class="col-md-12">
16 <label class="sr-only" for="vuln-desc">Workspace Description</label>
17 <textarea class="form-control" id="vuln-desc"
18 placeholder="Description" value={{workspace.description}}
19 ng-model="workspace.description" required></textarea>
20 </div>
21 </div><!-- .form-group -->
22 <div class="form-group">
23 <div class="col-md-6">
24 <h5>Start Date</h5>
25 <label class="sr-only" for="work-start">Start Date</label>
26 <p class="input-group">
27 <input type="text" class="form-control" datepicker-popup="MM/dd/yyyy" ng-model="workspace.duration.start" is-open="openedStart" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" close-text="Close" placeholder="Start Date"/>
28 <span class="input-group-btn">
29 <button type="button" class="btn btn-default" ng-click="open($event,true)"><i class="glyphicon glyphicon-calendar"></i></button>
30 </span>
31 </p>
32 </div>
33 <div class="col-md-6">
34 <h5>End Date</h5>
35 <label class="sr-only" for="work-end">End Date</label>
36 <p class="input-group">
37 <input type="text" class="form-control" datepicker-popup="MM/dd/yyyy" ng-model="workspace.duration.end" is-open="openedEnd" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" close-text="Close" placeholder="End Date"/>
38 <span class="input-group-btn">
39 <button type="button" class="btn btn-default" ng-click="open($event)"><i class="glyphicon glyphicon-calendar"></i></button>
40 </span>
41 </p>
42 </div>
4243
43 </div><!-- .form-group -->
44 <div class="form-group">
45 <div class="col-md-12">
46 <label class="sr-only" for="work-scope">Scope</label>
47 <textarea class="form-control" id="work-scope"
48 placeholder="Scope" ng-model="newworkspace.scope"
49 >
50 </textarea>
51 </div>
52 </div><!-- .form-group -->
53 </div><!-- .form-horizontal -->
54 </div><!-- .modal-body -->
44 </div><!-- .form-group -->
45 <div class="form-group">
46 <div class="col-md-12">
47 <label class="sr-only" for="work-scope">Scope</label>
48 <textarea class="form-control" id="work-scope"
49 placeholder="Scope" ng-model="workspace.scope"
50 >
51 </textarea>
52 </div>
53 </div><!-- .form-group -->
54 </div><!-- .form-horizontal -->
55 </div><!-- .modal-body -->
56 </form>
11 <!-- Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/) -->
22 <!-- See the file 'doc/LICENSE' for the license information -->
33
4 <div class="modal-header">
5 <div class="modal-button">
6 <button class="btn btn-success" ng-disabled="form.$invalid || date.$invalid" ng-click="okNew()">Save</button>
7 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
4 <form name="form">
5 <div class="modal-header">
6 <div class="modal-button">
7 <button class="btn btn-success" ng-disabled="form.$invalid || date.$invalid" ng-click="okNew()">Save</button>
8 <button class="btn btn-danger" ng-click="cancel()">Cancel</button>
9 </div>
10 <h3 class="modal-title">New Workspace</h3>
811 </div>
9 <h3 class="modal-title">New Workspace</h3>
10 </div>
11 <div class="modal-body">
12 <div class="form-horizontal">
12 <div class="modal-body">
13 <div class="form-horizontal">
14 <div class="form-group">
15 <div class="col-md-12">
16 <ng-form name="form" novalidate>
17 <label class="sr-only" for="wsp-name">Workspace Name</label>
18 <input type="text" class="form-control"
19 ng-pattern=/^[a-z][a-z0-9\_\$\(\)\+\-\/]*$/ id="vuln-name" placeholder="Workspace Name"
20 ng-model="workspace.name" required/>
21 <div ng-if="form.$invalid">
22 <div class="alert alert-danger target_not_selected" role="alert" ng-hide="">
23 <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
24 <span class="sr-only">Error:</span>
25 <button type="button" class="close" data-dismiss="alert"><span area-hidden="true">&times;</span><span class="sr-only">Close</span></button>
26 Workspace name should follow pattern [a-z][a-z0-9_$()+-/]*
27 </div>
28 </div>
29 </ng-form>
30 </div>
31 </div><!-- .form-group -->
32 <div class="form-group">
33 <div class="col-md-12">
34 <label class="sr-only" for="vuln-desc">Workspace Description</label>
35 <textarea class="form-control" id="vuln-desc"
36 placeholder="Description" ng-model="workspace.description"
37 >
38 </textarea>
39 </div>
40 </div><!-- .form-group -->
1341 <div class="form-group">
14 <div class="col-md-12">
15 <form name="form" novalidate>
16 <label class="sr-only" for="wsp-name">Workspace Name</label>
17 <input type="text" class="form-control"
18 ng-pattern=/^[a-z][a-z0-9\_\$\(\)\+\-\/]*$/ id="vuln-name" placeholder="Workspace Name"
19 ng-model="newworkspace.name" required/>
20 <div ng-if="form.$invalid">
21 <div class="alert alert-danger target_not_selected" role="alert" ng-hide="">
22 <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
23 <span class="sr-only">Error:</span>
24 <button type="button" class="close" data-dismiss="alert"><span area-hidden="true">&times;</span><span class="sr-only">Close</span></button>
25 Workspace name should follow pattern [a-z][a-z0-9_$()+-/]*
26 </div>
27 </div>
28 </form>
42 <ng-form name="date" novalidate>
43 <div class="col-md-6">
44 <label class="sr-only" for="work-start">Start Date</label>
45 <p class="input-group">
46 <input type="text" class="form-control" datepicker-popup="MM/dd/yyyy" ng-model="workspace.start" is-open="openedStart" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" close-text="Close" placeholder="Start Date" />
47 <span class="input-group-btn">
48 <button type="button" class="btn btn-default" ng-click="open($event,true)"><i class="glyphicon glyphicon-calendar"></i></button>
49 </span>
50 </p>
2951 </div>
52 <div class="col-md-6">
53 <label class="sr-only" for="work-end">End Date</label>
54 <p class="input-group">
55 <input type="text" class="form-control" datepicker-popup="MM/dd/yyyy" ng-model="workspace.end" is-open="openedEnd" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" close-text="Close" placeholder="End Date" />
56 <span class="input-group-btn">
57 <button type="button" class="btn btn-default" ng-click="open($event)"><i class="glyphicon glyphicon-calendar"></i></button>
58 </span>
59 </p>
60 </div>
61 <div ng-if="date.$invalid" class="col-md-12">
62 <div class="alert alert-danger target_not_selected" role="alert" ng-hide="">
63 <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
64 <span class="sr-only">Error:</span>
65 <button type="button" class="close" data-dismiss="alert"><span area-hidden="true">&times;</span><span class="sr-only">Close</span></button>
66 Invalid Date
67 </div>
68 </div>
69 </ng-form>
3070 </div><!-- .form-group -->
3171 <div class="form-group">
3272 <div class="col-md-12">
33 <label class="sr-only" for="vuln-desc">Workspace Description</label>
34 <textarea class="form-control" id="vuln-desc"
35 placeholder="Description" ng-model="newworkspace.description"
73 <label class="sr-only" for="work-scope">Scope</label>
74 <textarea class="form-control" id="work-scope"
75 placeholder="Scope" ng-model="workspace.scope"
3676 >
3777 </textarea>
3878 </div>
39 </div><!-- .form-group -->
40 <div class="form-group">
41 <form name="date" novalidate>
42 <div class="col-md-6">
43 <label class="sr-only" for="work-start">Start Date</label>
44 <p class="input-group">
45 <input type="text" class="form-control" datepicker-popup="MM/dd/yyyy" ng-model="newworkspace.start" is-open="openedStart" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" close-text="Close" placeholder="Start Date" />
46 <span class="input-group-btn">
47 <button type="button" class="btn btn-default" ng-click="open($event,true)"><i class="glyphicon glyphicon-calendar"></i></button>
48 </span>
49 </p>
50 </div>
51 <div class="col-md-6">
52 <label class="sr-only" for="work-end">End Date</label>
53 <p class="input-group">
54 <input type="text" class="form-control" datepicker-popup="MM/dd/yyyy" ng-model="newworkspace.end" is-open="openedEnd" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" close-text="Close" placeholder="End Date" />
55 <span class="input-group-btn">
56 <button type="button" class="btn btn-default" ng-click="open($event)"><i class="glyphicon glyphicon-calendar"></i></button>
57 </span>
58 </p>
59 </div>
60 <div ng-if="date.$invalid" class="col-md-12">
61 <div class="alert alert-danger target_not_selected" role="alert" ng-hide="">
62 <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
63 <span class="sr-only">Error:</span>
64 <button type="button" class="close" data-dismiss="alert"><span area-hidden="true">&times;</span><span class="sr-only">Close</span></button>
65 Invalid Date
66 </div>
67 </div>
68 </form>
69 </div><!-- .form-group -->
70 <div class="form-group">
71 <div class="col-md-12">
72 <label class="sr-only" for="work-scope">Scope</label>
73 <textarea class="form-control" id="work-scope"
74 placeholder="Scope" ng-model="newworkspace.scope"
75 >
76 </textarea>
77 </div>
78 </div><!-- .form-group -->
79 </div><!-- .form-horizontal -->
80 </div><!-- .modal-body -->
79 </div><!-- .form-group -->
80 </div><!-- .form-horizontal -->
81 </div><!-- .modal-body -->
82 </form>
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('workspacesFact', ['BASEURL', '$http', '$q', function(BASEURL, $http, $q) {
6 var workspacesFact = {};
7
8 workspacesFact.list = function() {
9 var url = BASEURL + "_all_dbs",
10 deferred = $q.defer();
11 deferred.resolve(
12 $http.get(url).
13 then(filterReservedWorkspaces, errorHandler).
14 then(filterInaccesibleWorkspaces, errorHandler)
15 );
16 return deferred.promise;
17 };
18
19 filterReservedWorkspaces = function(wss) {
20 var deferred = $q.defer();
21 deferred.resolve(wss.data.filter(function(ws) {
22 return ws.search(/^_/) < 0 && ws.search("cwe") < 0 && ws.search("reports") < 0;
23 }));
24 return deferred.promise;
25 };
26
27 filterInaccesibleWorkspaces = function(wss) {
28 var workspaces = [],
29 deferred = $q.defer();
30 wss.forEach(function(ws) {
31 workspaces.push($http.get(BASEURL + ws + "/" + ws).then(returnStatus, returnStatus));
32 });
33 $q.all(workspaces).then(function(resp) {
34 deferred.resolve(wss.filter(function(ws, index) {
35 return resp[index] == 200;
36 }));
37 });
38 return deferred.promise;
39 };
40
41 returnStatus = function(data) {
42 return $q.when(data.status);
43 };
44
45 workspacesFact.get = function(workspace_name) {
46 var deferred = $q.defer();
47 $http.get(BASEURL + workspace_name + '/' + workspace_name)
48 .success(function(data, status, headers, config) {
49 deferred.resolve(data);
50 })
51 .error(function() {
52 deferred.reject();
53 });
54 return deferred.promise;
55 };
56
57 workspacesFact.getDuration = function(workspace_name) {
58 var deferred = $q.defer();
59 workspacesFact.get(workspace_name).then(function(workspace) {
60 var ws = workspace;
61 var dur = {};
62
63 if(ws.hasOwnProperty('duration')) {
64 if(ws.duration.hasOwnProperty('start') && ws.duration.hasOwnProperty('end')) {
65 dur.start = ws.duration.start;
66 dur.end = ws.duration.end;
67 }
68 } else if(ws.hasOwnProperty('sdate') && ws.hasOwnProperty('fdate')) {
69 dur.start = ws.sdate;
70 dur.end = ws.fdate;
71 }
72 deferred.resolve(dur);
73 });
74 return deferred.promise;
75 };
76
77 workspacesFact.exists = function(workspace_name) {
78 var request = {
79 method: 'HEAD',
80 url: BASEURL + workspace_name
81 };
82 var exists_workspace = false;
83 return $http(request).success(function(data) {
84 exists_workspace = true;
85 });
86 };
87
88 errorHandler = function(response) {
89 if(typeof(response) == "object")
90 return $q.reject(response.data.reason.replace("file", "workspace"));
91 else if(typeof(response) == "string")
92 return $q.reject(response);
93 else
94 return $q.reject("Something bad happened");
95 };
96
97 workspacesFact.put = function(workspace) {
98 return createDatabase(workspace).
99 then(function(resp) { createWorkspaceDoc(resp, workspace); }, errorHandler).
100 then(function(resp) { uploadDocs(workspace.name); }, errorHandler);
101 };
102
103 createDatabase = function(workspace){
104 return $http.put(BASEURL + workspace.name, workspace);
105 };
106
107 createWorkspaceDoc = function(response, workspace){
108 $http.put(BASEURL + workspace.name + '/' + workspace.name, workspace).
109 success(function(data){
110 workspace._rev = data.rev;
111 }).
112 error(function(data) {
113 errorHandler;
114 });
115 };
116
117 uploadDocs = function(workspace) {
118 var files = {},
119 reports = BASEURL + 'reports/_design/reports';
120 $http.get(reports).
121 success(function(data) {
122 var attachments = data._attachments;
123 if(Object.keys(attachments).length > 0) {
124 for(var prop in attachments) {
125 if(attachments.hasOwnProperty(prop)) {
126 if(prop.indexOf("views/") > -1) {
127 files[prop] = $http.get(reports + "/" + prop);
128 }
129 }
130 }
131 }
132 $q.all(files).then(function(resp) {
133 var bulk = {docs:[]};
134 for(var file in files) {
135 if(files.hasOwnProperty(file)) {
136 var views = [],
137 parts = file.split("/"),
138 component = parts[1],
139 type = parts[2],
140 name = parts[3],
141 filename = parts[4].split(".")[0],
142 docIndex = indexOfDocument(bulk.docs, "_design/"+component);
143
144 if(docIndex == -1) {
145 bulk.docs.push({
146 _id: "_design/"+component,
147 language: "javascript",
148 views: {}
149 });
150 docIndex = bulk.docs.length - 1;
151 }
152
153 if(!bulk["docs"][docIndex]["views"].hasOwnProperty(name)) {
154 bulk["docs"][docIndex]["views"][name] = {};
155 }
156
157 bulk["docs"][docIndex]["views"][name][filename] = resp[file]["data"];
158 }
159 }
160 $http.post(BASEURL + workspace + "/_bulk_docs", JSON.stringify(bulk));
161 }, errorHandler);
162 }).
163 error(function(data) {
164 errorHandler;
165 });
166 };
167
168 indexOfDocument = function(list, name) {
169 var ret = -1;
170 list.forEach(function(item, index) {
171 if(item._id == name) {
172 ret = index;
173 }
174 });
175 return ret;
176 };
177
178 workspacesFact.update = function(workspace) {
179 var deferred = $q.defer();
180 document_url = BASEURL + workspace.name + '/' + workspace.name + '?rev=' + workspace._rev;
181 $http.put(document_url, workspace).success(function(data){
182 workspace._rev = data.rev;
183 deferred.resolve(workspace);
184 });
185 return deferred.promise;
186 };
187
188 workspacesFact.delete = function(workspace_name) {
189 var deferred = $q.defer();
190 var request = {
191 method: 'DELETE',
192 url: BASEURL + workspace_name
193 };
194 $http(request).success(function(data) {
195 deferred.resolve(workspace_name);
196 })
197 .error(function() {
198 deferred.reject();
199 });
200 return deferred.promise;
201 };
202 return workspacesFact;
203 }]);
+0
-167
views/reports/_attachments/scripts/workspaces/services/workspaces.js less more
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 angular.module('faradayApp')
5 .factory('workspacesFact', ['BASEURL', '$http', '$q', function(BASEURL, $http, $q) {
6 var workspacesFact = {};
7
8 workspacesFact.list = function() {
9 var url = BASEURL + "_all_dbs",
10 deferred = $q.defer();
11 deferred.resolve(
12 $http.get(url).
13 then(filterReservedWorkspaces, errorHandler).
14 then(filterInaccesibleWorkspaces, errorHandler)
15 );
16 return deferred.promise;
17 };
18
19 filterReservedWorkspaces = function(wss) {
20 var deferred = $q.defer();
21 deferred.resolve(wss.data.filter(function(ws) {
22 return ws.search(/^_/) < 0 && ws.search("cwe") < 0 && ws.search("reports") < 0;
23 }));
24 return deferred.promise;
25 };
26
27 filterInaccesibleWorkspaces = function(wss) {
28 var workspaces = [],
29 deferred = $q.defer();
30 wss.forEach(function(ws) {
31 workspaces.push($http.get(BASEURL + ws).then(returnStatus, returnStatus));
32 });
33 $q.all(workspaces).then(function(resp) {
34 deferred.resolve(wss.filter(function(ws, index) {
35 return resp[index] == 200;
36 }));
37 });
38 return deferred.promise;
39 };
40
41 returnStatus = function(data) {
42 return $q.when(data.status);
43 };
44
45 workspacesFact.get = function(workspace_name, onSuccess) {
46 return $http.get(BASEURL + workspace_name + '/' + workspace_name).
47 success(function(data, status, headers, config) {
48 onSuccess(data);
49 });
50 };
51
52 workspacesFact.exists = function(workspace_name) {
53 var request = {
54 method: 'HEAD',
55 url: BASEURL + workspace_name
56 };
57 var exists_workspace = false;
58 return $http(request).success(function(data) {
59 exists_workspace = true;
60 });
61 };
62
63 errorHandler = function(response) {
64 return $q.reject(response.data.reason.replace("file", "workspace"));
65 };
66
67 workspacesFact.put = function(workspace) {
68 return createDatabase(workspace).
69 then(function(resp) { createWorkspaceDoc(resp, workspace); }, errorHandler).
70 then(function(resp) { uploadDocs(workspace.name); }, errorHandler);
71 };
72
73 createDatabase = function(workspace){
74 return $http.put(BASEURL + workspace.name, workspace);
75 };
76
77 createWorkspaceDoc = function(response, workspace){
78 $http.put(BASEURL + workspace.name + '/' + workspace.name, workspace).
79 success(function(data){
80 workspace._rev = data.rev;
81 }).
82 error(function(data) {
83 errorHandler;
84 });
85 };
86
87 uploadDocs = function(workspace) {
88 var files = {},
89 reports = BASEURL + 'reports/_design/reports';
90 $http.get(reports).
91 success(function(data) {
92 var attachments = data._attachments;
93 if(Object.keys(attachments).length > 0) {
94 for(var prop in attachments) {
95 if(attachments.hasOwnProperty(prop)) {
96 if(prop.indexOf("views/") > -1) {
97 files[prop] = $http.get(reports + "/" + prop);
98 }
99 }
100 }
101 }
102 $q.all(files).then(function(resp) {
103 var bulk = {docs:[]};
104 for(var file in files) {
105 if(files.hasOwnProperty(file)) {
106 var views = [],
107 parts = file.split("/"),
108 component = parts[1],
109 type = parts[2],
110 name = parts[3],
111 filename = parts[4].split(".")[0],
112 docIndex = indexOfDocument(bulk.docs, "_design/"+component);
113
114 if(docIndex == -1) {
115 bulk.docs.push({
116 _id: "_design/"+component,
117 language: "javascript",
118 views: {}
119 });
120 docIndex = bulk.docs.length - 1;
121 }
122
123 if(!bulk["docs"][docIndex]["views"].hasOwnProperty(name)) {
124 bulk["docs"][docIndex]["views"][name] = {};
125 }
126
127 bulk["docs"][docIndex]["views"][name][filename] = resp[file]["data"];
128 }
129 }
130 $http.post(BASEURL + workspace + "/_bulk_docs", JSON.stringify(bulk));
131 }, errorHandler);
132 }).
133 error(function(data) {
134 errorHandler;
135 });
136 };
137
138 indexOfDocument = function(list, name) {
139 var ret = -1;
140 list.forEach(function(item, index) {
141 if(item._id == name) {
142 ret = index;
143 }
144 });
145 return ret;
146 };
147
148 workspacesFact.update = function(workspace, onSuccess) {
149 document_url = BASEURL + workspace.name + '/' + workspace.name + '?rev=' + workspace._rev;
150 return $http.put(document_url, workspace).success(function(data){
151 workspace._rev = data.rev;
152 onSuccess(workspace);
153 });
154 };
155
156 workspacesFact.delete = function(workspace_name, onSuccess) {
157 var request = {
158 method: 'DELETE',
159 url: BASEURL + workspace_name
160 };
161 return $http(request).success(function(data) {
162 onSuccess(workspace_name);
163 });
164 };
165 return workspacesFact;
166 }]);
0 .cfp-hotkeys-container {
1 display: table !important;
2 position: fixed;
3 width: 100%;
4 height: 100%;
5 top: 0;
6 left: 0;
7 color: #333;
8 font-size: 1em;
9 background-color: rgba(255,255,255,0.9);
10 }
11
12 .cfp-hotkeys-container.fade {
13 z-index: -1024;
14 visibility: hidden;
15 opacity: 0;
16 -webkit-transition: opacity 0.15s linear;
17 -moz-transition: opacity 0.15s linear;
18 -o-transition: opacity 0.15s linear;
19 transition: opacity 0.15s linear;
20 }
21
22 .cfp-hotkeys-container.fade.in {
23 z-index: 10002;
24 visibility: visible;
25 opacity: 1;
26 }
27
28 .cfp-hotkeys-title {
29 font-weight: bold;
30 text-align: center;
31 font-size: 1.2em;
32 }
33
34 .cfp-hotkeys {
35 width: 100%;
36 height: 100%;
37 display: table-cell;
38 vertical-align: middle;
39 }
40
41 .cfp-hotkeys table {
42 margin: auto;
43 color: #333;
44 }
45
46 .cfp-content {
47 display: table-cell;
48 vertical-align: middle;
49 }
50
51 .cfp-hotkeys-keys {
52 padding: 5px;
53 text-align: right;
54 }
55
56 .cfp-hotkeys-key {
57 display: inline-block;
58 color: #fff;
59 background-color: #333;
60 border: 1px solid #333;
61 border-radius: 5px;
62 text-align: center;
63 margin-right: 5px;
64 box-shadow: inset 0 1px 0 #666, 0 1px 0 #bbb;
65 padding: 5px 9px;
66 font-size: 1em;
67 }
68
69 .cfp-hotkeys-text {
70 padding-left: 10px;
71 font-size: 1em;
72 }
73
74 .cfp-hotkeys-close {
75 position: fixed;
76 top: 20px;
77 right: 20px;
78 font-size: 2em;
79 font-weight: bold;
80 padding: 5px 10px;
81 border: 1px solid #ddd;
82 border-radius: 5px;
83 min-height: 45px;
84 min-width: 45px;
85 text-align: center;
86 }
87
88 .cfp-hotkeys-close:hover {
89 background-color: #fff;
90 cursor: pointer;
91 }
92
93 @media all and (max-width: 500px) {
94 .cfp-hotkeys {
95 font-size: 0.8em;
96 }
97 }
98
99 @media all and (min-width: 750px) {
100 .cfp-hotkeys {
101 font-size: 1.2em;
102 }
103 }
44 if(doc.type == "Vulnerability" || doc.type == "VulnerabilityWeb"){
55 var easeofresolution = "trivial",
66 impact = {
7 "accountability": 0,
8 "availability": 0,
9 "confidentiality": 0,
10 "integrity": 0
7 "accountability": false,
8 "availability": false,
9 "confidentiality": false,
10 "integrity": false
1111 },
1212 resolution = "";
13 if(doc.easeofresolution != "undefined" && typeof(doc.easeofresolution) != "undefined") {
13 if(doc.easeofresolution !== undefined) {
1414 easeofresolution = doc.easeofresolution;
1515 }
16 if(doc.impact != "undefined" && typeof(doc.impact) != "undefined") {
16 if(doc.impact !== undefined) {
1717 impact = doc.impact;
1818 }
19 if(doc.resolution != "undefined" && typeof(doc.resolution) != "undefined") {
19 if(doc.resolution !== undefined) {
2020 resolution = doc.resolution;
2121 }
2222
2323 var obj = {
24 "rev": doc._rev,
25 "attachments": doc._attachments,
24 "_id": doc._id,
25 "_rev": doc._rev,
26 "_attachments": doc._attachments,
2627 "data": doc.data,
27 "date": doc.metadata.create_time,
2828 "desc": doc.desc,
2929 "easeofresolution": easeofresolution,
3030 "impact": impact,
31 "meta": doc.metadata,
31 "metadata": doc.metadata,
3232 "name": doc.name,
33 "oid": doc.obj_id,
33 "obj_id": doc.obj_id,
3434 "owned": doc.owned,
3535 "owner": doc.owner,
36 "path": doc.path,
3736 "parent": doc.parent,
3837 "refs": doc.refs,
3938 "resolution": resolution,
4039 "severity": doc.severity,
41 "status": doc.type,
42 "website": doc.website
40 "type": doc.type,
4341 };
42
43 if(doc.type == "VulnerabilityWeb") {
44 obj.method = doc.method;
45 obj.params = doc.params;
46 obj.path = doc.path;
47 obj.pname = doc.pname;
48 obj.query = doc.query;
49 obj.request = doc.request;
50 obj.response = doc.response;
51 obj.website = doc.website;
52 }
53
4454 emit(doc._id, obj);
4555 }
4656 }
44 if(doc.type == "Vulnerability"){
55 var easeofresolution = "trivial",
66 impact = {
7 "accountability": 0,
8 "availability": 0,
9 "confidentiality": 0,
10 "integrity": 0
7 "accountability": false,
8 "availability": false,
9 "confidentiality": false,
10 "integrity": false
1111 },
1212 resolution = "";
13 if(doc.easeofresolution != "undefined" && typeof(doc.easeofresolution) != "undefined") {
13 if(doc.easeofresolution !== undefined) {
1414 easeofresolution = doc.easeofresolution;
1515 }
16 if(doc.impact != "undefined" && typeof(doc.impact) != "undefined") {
16 if(doc.impact !== undefined) {
1717 impact = doc.impact;
1818 }
19 if(doc.resolution != "undefined" && typeof(doc.resolution) != "undefined") {
19 if(doc.resolution !== undefined) {
2020 resolution = doc.resolution;
2121 }
2222
2323 var obj = {
24 "rev": doc._rev,
25 "attachments": doc._attachments,
24 "_rev": doc._rev,
25 "_attachments": doc._attachments,
2626 "data": doc.data,
27 "date": doc.metadata.create_time,
2827 "desc": doc.desc,
2928 "easeofresolution": easeofresolution,
3029 "impact": impact,
31 "meta": doc.metadata,
30 "metadata": doc.metadata,
3231 "name": doc.name,
33 "oid": doc.obj_id,
32 "obj_id": doc.obj_id,
3433 "owned": doc.owned,
3534 "owner": doc.owner,
3635 "parent": doc.parent,
44 if(doc.type == "VulnerabilityWeb"){
55 var easeofresolution = "trivial",
66 impact = {
7 "accountability": 0,
8 "availability": 0,
9 "confidentiality": 0,
10 "integrity": 0
7 "accountability": false,
8 "availability": false,
9 "confidentiality": false,
10 "integrity": false
1111 },
1212 resolution = "";
13 if(doc.easeofresolution != "undefined" && typeof(doc.easeofresolution) != "undefined") {
13 if(doc.easeofresolution !== undefined) {
1414 easeofresolution = doc.easeofresolution;
1515 }
16 if(doc.impact != "undefined" && typeof(doc.impact) != "undefined") {
16 if(doc.impact !== undefined) {
1717 impact = doc.impact;
1818 }
19 if(doc.resolution != "undefined" && typeof(doc.resolution) != "undefined") {
19 if(doc.resolution !== undefined) {
2020 resolution = doc.resolution;
2121 }
2222
2323 var obj = {
24 "rev": doc._rev,
25 "attachments": doc._attachments,
24 "_rev": doc._rev,
25 "_attachments": doc._attachments,
2626 "data": doc.data,
27 "date": doc.metadata.create_time,
2827 "desc": doc.desc,
2928 "easeofresolution": easeofresolution,
3029 "impact": impact,
31 "meta": doc.metadata,
30 "metadata": doc.metadata,
3231 "name": doc.name,
33 "oid": doc.obj_id,
32 "obj_id": doc.obj_id,
3433 "owned": doc.owned,
3534 "owner": doc.owner,
3635 "parent": doc.parent,
+0
-145
views/reports/tests/faradayApp/components/workspaces/controllers/workspace_test.js less more
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 describe('workspacesCtrl', function() {
5 var $controller,
6 $scope;
7
8 var $workspacesFact,
9 workspacesFactMock;
10
11 var spyOnPutFactory;
12
13 spyOnPutFactory = jasmine.createSpy('Put Workspace Factory Spy');
14 spyOnDeleteFactory = jasmine.createSpy('Delete Workspace Factory Spy');
15 spyOnExistsFactory = jasmine.createSpy('Delete Workspace Factory Spy');
16 spyOnExistsFactory('test_workspace', function(){
17 return false;
18 });
19
20
21
22 beforeEach(function () {
23 workspacesFactMock = {
24 list: function(callback) {
25 callback(['ws1', 'ws2']);
26 },
27 get: function(workspace_name, onSuccess){
28 workspace = {
29 "_id": workspace_name,
30 "_rev": "2-bd88abf79cf2b7e8b419cd4387c64bef",
31 "customer": "",
32 "sdate": 1410832741.48194,
33 "name": workspace_name,
34 "fdate": 1410832741.48194,
35 "type": "Workspace",
36 "children": [
37 ],
38 "description": ""
39 };
40 onSuccess(workspace);
41 },
42 put: spyOnPutFactory,
43 delete: function(workspace, onSuccess) {
44 onSuccess(workspace);
45 },
46 exists: function(workspace_name){
47 return false;
48 }
49
50 };
51 module('faradayApp');
52 module(function($provide){
53 $provide.value('workspacesFact', workspacesFactMock);
54 });
55
56 inject(function(_$rootScope_, _$controller_, _workspacesFact_){
57 // The injector unwraps the underscores (_) from around the parameter names when matching
58 $scope = _$rootScope_.$new();
59 $controller = _$controller_('workspacesCtrl',
60 { $scope: $scope, workspacesFact: _workspacesFact_});
61 });
62 });
63
64
65 describe('Workspaces load in $scope.wss', function() {
66 it('tests if wss is loaded properly', function() {
67 expect($scope.wss).toEqual(['ws1', 'ws2']);
68 expect($scope.workspaces.length).toEqual(2);
69 });
70 });
71
72 describe('Workspaces inserts in $scope.wss', function() {
73 it('tests if duplicated inserts are avoided', function() {
74 // Replace the mock exists function
75 // to return that the workspace 'tuvieja' exists
76 workspacesFactMock.exists = function(workspace_name){ return true;};
77 workspace_name = 'tuvieja';
78 workspace = {
79 "_id": workspace_name,
80 "_rev": "2-bd88abf79cf2b7e8b419cd4387c64bef",
81 "customer": "",
82 "sdate": 1410832741.48194,
83 "name": workspace_name,
84 "fdate": 1410832741.48194,
85 "type": "Workspace",
86 "children": [
87 ],
88 "description": ""
89 };
90 $scope.insert(workspace);
91
92 expect($scope.wss).not.toContain(workspace_name);
93 expect($scope.wss.length).toEqual(2);
94 expect(spyOnPutFactory).not.toHaveBeenCalledWith(workspace);
95 });
96 it('tests if wss is updated properly', function() {
97 workspace_name = 'test_workspace';
98 workspace = {
99 "_id": workspace_name,
100 "_rev": "2-bd88abf79cf2b7e8b419cd4387c64bef",
101 "customer": "",
102 "sdate": 1410832741.48194,
103 "name": workspace_name,
104 "fdate": 1410832741.48194,
105 "type": "Workspace",
106 "children": [
107 ],
108 "description": ""
109 };
110 $scope.insert(workspace);
111
112 // http://jasmine.github.io/1.3/introduction.html#section-Matchers
113 expect(spyOnPutFactory).toHaveBeenCalledWith(workspace, $scope.onSuccessInsert);
114 });
115 });
116 describe('Workspaces removal in $scope.wss', function() {
117 it('tests if workspaces in scope.wss are removed ', function() {
118
119 $scope.remove('ws1');
120 expect($scope.wss).not.toContain('ws1');
121 expect($scope.workspaces['ws1']).not.toBeDefined();
122 });
123 });
124
125 describe('Workspaces object creation ', function() {
126 it('tests if workspaces create object is consistent', function() {
127 workspace = $scope.create('wname','wdesc');
128 workspace_properties = Object.keys(workspace);
129 expect(workspace_properties).toContain('_id');
130 expect(workspace_properties).toContain('name');
131 expect(workspace_properties).toContain('description');
132 expect(workspace_properties).toContain('customer');
133 expect(workspace_properties).toContain('sdate');
134 expect(workspace_properties).toContain('fdate');
135 expect(workspace_properties).toContain('type');
136 expect(workspace_properties).toContain('children');
137
138 expect(workspace.name).toEqual('wname');
139 expect(workspace._id).toEqual('wname');
140 expect(workspace.description).toEqual('wdesc');
141 });
142 });
143 });
144
+0
-86
views/reports/tests/faradayApp/components/workspaces/services/workspaces_test.js less more
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 describe('workspacesFact', function() {
5 var $httpBackend, createFactory;
6
7 // Set up the module
8 beforeEach(module('faradayApp'));
9
10 beforeEach(inject(function($injector) {
11 // Set up the mock http service responses
12 $httpBackend = $injector.get('$httpBackend');
13 var $workspacesFact = $injector.get('workspacesFact');
14
15 createFactory = function() {
16 return $injector.get('workspacesFact', {'BASEURL' : 'http://localhost:9876/',
17 '$http': $httpBackend});
18 };
19 }));
20
21
22 afterEach(function() {
23 $httpBackend.verifyNoOutstandingExpectation();
24 $httpBackend.verifyNoOutstandingRequest();
25 });
26
27 describe('Workspaces Service CRUD', function() {
28 it('Tests if factory is well created', function() {
29 fact = createFactory();
30 });
31
32 it('Tests if existence is well asked', function() {
33 $httpBackend.when('HEAD', 'http://localhost:9876/tuvieja')
34 .respond(200, '');
35
36 $httpBackend.expectHEAD('http://localhost:9876/tuvieja');
37 fact = createFactory();
38 workspace_exists = fact.exists('tuvieja');
39 expect(workspace_exists).toBe(true);
40 $httpBackend.flush();
41 });
42
43 it('Tests if OK Inserts are well done', function() {
44 var workspace = {
45 "_id": "test_workspace",
46 "customer": "",
47 "sdate": 1415901244.040532,
48 "name": "test_workspace",
49 "fdate": 1415901244.040532,
50 "type": "Workspace",
51 "children": [
52 ],
53 "description": ""
54 };
55
56 $httpBackend.expectPUT('http://localhost:9876/test_workspace',
57 workspace).respond(200, {"ok": true});
58
59 $httpBackend.expectPUT('http://localhost:9876/test_workspace/test_workspace',
60 workspace).respond(200, {"ok": true});
61
62 fact = createFactory();
63 var workspace_exists = false;
64 onSuccess = function(){ workspace_exists = true;};
65
66 fact.put(workspace, onSuccess);
67 $httpBackend.flush();
68 expect(workspace_exists).toBe(true);
69 });
70
71 it('Tests if OK Delete are well done', function() {
72 $httpBackend.expectDELETE('http://localhost:9876/test_workspace').
73 respond(200, {"ok": true});
74
75 fact = createFactory();
76 var workspace_exists = true;
77 onSuccess = function(){ workspace_exists = false;};
78
79 workspace_exists = fact.delete('test_workspace', onSuccess);
80 $httpBackend.flush();
81 expect(workspace_exists).toBe(false);
82 });
83 });
84
85 });
+0
-44
views/reports/tests/karma.conf.js less more
0 // Faraday Penetration Test IDE
1 // Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
2 // See the file 'doc/LICENSE' for the license information
3
4 module.exports = function(config){
5 config.set({
6
7 basePath : './',
8
9 files : [
10 '../_attachments/script/jquery-1.11.2.js',
11 '../_attachments/script/angular.js',
12 // '../_attachments/script/angular-mocks.js',
13 '../_attachments/script/angular-route.js',
14 '../_attachments/script/angular-selection-model.js',
15 '../_attachments/script/*bootstrap*.js',
16 '../_attachments/scripts/app.js',
17 '../_attachments/scripts/**/*.js',
18 '../tests/faradayApp/components/**/*.js',
19 '../_attachments/script/angular-file-upload-shim.js',
20 '../_attachments/script/angular-file-upload.js'
21
22 ],
23
24 autoWatch : true,
25
26 frameworks: ['jasmine'],
27
28 browsers : ['Chrome'],
29
30 plugins : [
31 'karma-chrome-launcher',
32 'karma-firefox-launcher',
33 'karma-jasmine',
34 'karma-junit-reporter'
35 ],
36
37 junitReporter : {
38 outputFile: 'test_out/unit.xml',
39 suite: 'unit'
40 }
41
42 });
43 };
+0
-30
views/reports/tests/package.json less more
0 {
1 "name": "angular-seed",
2 "private": true,
3 "version": "0.0.0",
4 "description": "A starter project for AngularJS",
5 "repository": "https://github.com/angular/angular-seed",
6 "license": "MIT",
7 "devDependencies": {
8 "angular-mocks": "^1.3.0",
9 "http-server": "^0.6.1",
10 "jasmine-core": "^2.1.2",
11 "karma": "^0.12.28",
12 "karma-chrome-launcher": "^0.1.5",
13 "karma-jasmine": "^0.3.2",
14 "karma-junit-reporter": "^0.2.2",
15 "protractor": "^1.1.1",
16 "shelljs": "^0.2.6"
17 },
18 "scripts": {
19 "prestart": "npm install",
20 "start": "http-server -a localhost -p 8000 -c-1",
21 "pretest": "npm install",
22 "test": "node_modules/karma/bin/karma start karma.conf.js",
23 "test-single-run": "node_modules/karma/bin/karma start karma.conf.js --single-run",
24 "preupdate-webdriver": "npm install",
25 "update-webdriver": "webdriver-manager update",
26 "preprotractor": "npm run update-webdriver",
27 "protractor": "protractor e2e-tests/protractor.conf.js"
28 }
29 }