diff --git a/src/main/java/org/owasp/esapi/AccessControlRule.java b/src/main/java/org/owasp/esapi/AccessControlRule.java
index b89af4e48..51458ff3b 100644
--- a/src/main/java/org/owasp/esapi/AccessControlRule.java
+++ b/src/main/java/org/owasp/esapi/AccessControlRule.java
@@ -2,7 +2,7 @@
public interface AccessControlRule
{
- void setPolicyParameters(P policyParameter);
- P getPolicyParameters();
- boolean isAuthorized(R runtimeParameter) throws Exception;
+ void setPolicyParameters(P policyParameter);
+ P getPolicyParameters();
+ boolean isAuthorized(R runtimeParameter) throws Exception;
}
diff --git a/src/main/java/org/owasp/esapi/AccessController.java b/src/main/java/org/owasp/esapi/AccessController.java
index 15dfb5d7f..2aa8e84e0 100644
--- a/src/main/java/org/owasp/esapi/AccessController.java
+++ b/src/main/java/org/owasp/esapi/AccessController.java
@@ -66,70 +66,70 @@
*/
public interface AccessController {
- /**
- * isAuthorized executes the AccessControlRule
- * that is identified by key and listed in the
- * resources/ESAPI-AccessControlPolicy.xml file. It returns
- * true if the AccessControlRule decides that the operation
- * should be allowed. Otherwise, it returns false. Any exception thrown by
- * the AccessControlRule must result in false. If
- * key does not map to an AccessControlRule, then
- * false is returned.
- *
- * Developers should call isAuthorized to control execution flow. For
- * example, if you want to decide whether to display a UI widget in the
- * browser using the same logic that you will use to enforce permissions
- * on the server, then isAuthorized is the method that you want to use.
- *
- * Typically, assertAuthorized should be used to enforce permissions on the
- * server.
- *
- * @param key key maps to
- * <AccessControlPolicy><AccessControlRules>
- * <AccessControlRule name="key"
- * @param runtimeParameter runtimeParameter can contain anything that
- * the AccessControlRule needs from the runtime system.
- * @return Returns true if and only if the AccessControlRule specified
- * by key exists and returned true.
- * Otherwise returns false
- */
- boolean isAuthorized(Object key, Object runtimeParameter);
-
- /**
- * assertAuthorized executes the AccessControlRule
- * that is identified by key and listed in the
- * resources/ESAPI-AccessControlPolicy.xml file. It does
- * nothing if the AccessControlRule decides that the operation
- * should be allowed. Otherwise, it throws an
- * org.owasp.esapi.errors.AccessControlException. Any exception
- * thrown by the AccessControlRule will also result in an
- * AccesControlException. If key does not map to
- * an AccessControlRule, then an AccessControlException
- * is thrown.
- *
- * Developers should call {@code assertAuthorized} to enforce privileged access to
- * the system. It should be used to answer the question: "Should execution
- * continue." Ideally, the call to assertAuthorized should
- * be integrated into the application framework so that it is called
- * automatically.
- *
- * @param key key maps to
- * <AccessControlPolicy><AccessControlRules>
- * <AccessControlRule name="key"
- * @param runtimeParameter runtimeParameter can contain anything that
- * the AccessControlRule needs from the runtime system.
- */
- void assertAuthorized(Object key, Object runtimeParameter)
- throws AccessControlException;
+ /**
+ * isAuthorized executes the AccessControlRule
+ * that is identified by key and listed in the
+ * resources/ESAPI-AccessControlPolicy.xml file. It returns
+ * true if the AccessControlRule decides that the operation
+ * should be allowed. Otherwise, it returns false. Any exception thrown by
+ * the AccessControlRule must result in false. If
+ * key does not map to an AccessControlRule, then
+ * false is returned.
+ *
+ * Developers should call isAuthorized to control execution flow. For
+ * example, if you want to decide whether to display a UI widget in the
+ * browser using the same logic that you will use to enforce permissions
+ * on the server, then isAuthorized is the method that you want to use.
+ *
+ * Typically, assertAuthorized should be used to enforce permissions on the
+ * server.
+ *
+ * @param key key maps to
+ * <AccessControlPolicy><AccessControlRules>
+ * <AccessControlRule name="key"
+ * @param runtimeParameter runtimeParameter can contain anything that
+ * the AccessControlRule needs from the runtime system.
+ * @return Returns true if and only if the AccessControlRule specified
+ * by key exists and returned true.
+ * Otherwise returns false
+ */
+ boolean isAuthorized(Object key, Object runtimeParameter);
+
+ /**
+ * assertAuthorized executes the AccessControlRule
+ * that is identified by key and listed in the
+ * resources/ESAPI-AccessControlPolicy.xml file. It does
+ * nothing if the AccessControlRule decides that the operation
+ * should be allowed. Otherwise, it throws an
+ * org.owasp.esapi.errors.AccessControlException. Any exception
+ * thrown by the AccessControlRule will also result in an
+ * AccesControlException. If key does not map to
+ * an AccessControlRule, then an AccessControlException
+ * is thrown.
+ *
+ * Developers should call {@code assertAuthorized} to enforce privileged access to
+ * the system. It should be used to answer the question: "Should execution
+ * continue." Ideally, the call to assertAuthorized should
+ * be integrated into the application framework so that it is called
+ * automatically.
+ *
+ * @param key key maps to
+ * <AccessControlPolicy><AccessControlRules>
+ * <AccessControlRule name="key"
+ * @param runtimeParameter runtimeParameter can contain anything that
+ * the AccessControlRule needs from the runtime system.
+ */
+ void assertAuthorized(Object key, Object runtimeParameter)
+ throws AccessControlException;
-
+
-
- /*** Below this line has been deprecated as of ESAPI 1.6 ***/
-
-
-
-
+
+ /*** Below this line has been deprecated as of ESAPI 1.6 ***/
+
+
+
+
/**
* Checks if the current user is authorized to access the referenced URL. Generally, this method should be invoked in the
* application's controller or a filter as follows:
@@ -140,10 +140,10 @@ void assertAuthorized(Object key, Object runtimeParameter)
* exception would be logged.
*
* @param url
- * the URL as returned by request.getRequestURI().toString()
+ * the URL as returned by request.getRequestURI().toString()
*
* @return
- * true, if is authorized for URL
+ * true, if is authorized for URL
*/
@Deprecated
boolean isAuthorizedForURL(String url);
@@ -155,10 +155,10 @@ void assertAuthorized(Object key, Object runtimeParameter)
* AccessControlException is not thrown, this method should return true.
*
* @param functionName
- * the name of the function
+ * the name of the function
*
* @return
- * true, if is authorized for function
+ * true, if is authorized for function
*/
@Deprecated
boolean isAuthorizedForFunction(String functionName);
@@ -175,10 +175,10 @@ void assertAuthorized(Object key, Object runtimeParameter)
* (e.g., Read, Write, etc.), or the name of the function the data is being passed to.
*
* @param data
- * The actual object or object identifier being accessed or a reference to the object being accessed.
+ * The actual object or object identifier being accessed or a reference to the object being accessed.
*
* @return
- * true, if is authorized for the data
+ * true, if is authorized for the data
*/
@Deprecated
boolean isAuthorizedForData(String action, Object data);
@@ -190,10 +190,10 @@ void assertAuthorized(Object key, Object runtimeParameter)
* is not thrown, this method should return true.
*
* @param filepath
- * the path of the file to be checked, including filename
+ * the path of the file to be checked, including filename
*
* @return
- * true, if is authorized for the file
+ * true, if is authorized for the file
*/
@Deprecated
boolean isAuthorizedForFile(String filepath);
@@ -206,10 +206,10 @@ void assertAuthorized(Object key, Object runtimeParameter)
* AccessControlException is not thrown, this method should return true.
*
* @param serviceName
- * the service name
+ * the service name
*
* @return
- * true, if is authorized for the service
+ * true, if is authorized for the service
*/
@Deprecated
boolean isAuthorizedForService(String serviceName);
@@ -229,16 +229,16 @@ void assertAuthorized(Object key, Object runtimeParameter)
*
Use available information to make an access control decision
*
*
Ideally, this policy would be data driven
- *
You can use the current User, roles, data type, data name, time of day, etc.
- *
Access control decisions must deny by default
+ *
You can use the current User, roles, data type, data name, time of day, etc.
+ *
Access control decisions must deny by default
*
*
If access is not permitted, throw an AccessControlException with details
*
* @param url
- * the URL as returned by request.getRequestURI().toString()
+ * the URL as returned by request.getRequestURI().toString()
*
* @throws AccessControlException
- * if access is not permitted
+ * if access is not permitted
*/
@Deprecated
void assertAuthorizedForURL(String url) throws AccessControlException;
@@ -257,17 +257,17 @@ void assertAuthorized(Object key, Object runtimeParameter)
*
Use available information to make an access control decision
*
*
Ideally, this policy would be data driven
- *
You can use the current User, roles, data type, data name, time of day, etc.
- *
Access control decisions must deny by default
+ *
You can use the current User, roles, data type, data name, time of day, etc.
+ *
Access control decisions must deny by default
*
*
If access is not permitted, throw an AccessControlException with details
*
*
* @param functionName
- * the function name
+ * the function name
*
* @throws AccessControlException
- * if access is not permitted
+ * if access is not permitted
*/
@Deprecated
void assertAuthorizedForFunction(String functionName) throws AccessControlException;
@@ -283,8 +283,8 @@ void assertAuthorized(Object key, Object runtimeParameter)
*
Use available information to make an access control decision
*
*
Ideally, this policy would be data driven
- *
You can use the current User, roles, data type, data name, time of day, etc.
- *
Access control decisions must deny by default
+ *
You can use the current User, roles, data type, data name, time of day, etc.
+ *
Access control decisions must deny by default
*
*
If access is not permitted, throw an AccessControlException with details
*
@@ -294,10 +294,10 @@ void assertAuthorized(Object key, Object runtimeParameter)
* (e.g., Read, Write, etc.), or the name of the function the data is being passed to.
*
* @param data
- * The actual object or object identifier being accessed or a reference to the object being accessed.
+ * The actual object or object identifier being accessed or a reference to the object being accessed.
*
* @throws AccessControlException
- * if access is not permitted
+ * if access is not permitted
*/
@Deprecated
void assertAuthorizedForData(String action, Object data) throws AccessControlException;
@@ -315,14 +315,14 @@ void assertAuthorized(Object key, Object runtimeParameter)
*
Use available information to make an access control decision
*
*
Ideally, this policy would be data driven
- *
You can use the current User, roles, data type, data name, time of day, etc.
- *
Access control decisions must deny by default
+ *
You can use the current User, roles, data type, data name, time of day, etc.
+ *
Access control decisions must deny by default
*
*
If access is not permitted, throw an AccessControlException with details
*
*
* @param filepath
- * Path to the file to be checked
+ * Path to the file to be checked
* @throws AccessControlException if access is denied
*/
@Deprecated
@@ -341,18 +341,18 @@ void assertAuthorized(Object key, Object runtimeParameter)
*
Use available information to make an access control decision
*
*
Ideally, this policy would be data driven
- *
You can use the current User, roles, data type, data name, time of day, etc.
- *
Access control decisions must deny by default
+ *
You can use the current User, roles, data type, data name, time of day, etc.
+ *
Access control decisions must deny by default
*
*
If access is not permitted, throw an AccessControlException with details
*
*
* @param serviceName
- * the service name
+ * the service name
*
* @throws AccessControlException
- * if access is not permitted
- */
+ * if access is not permitted
+ */
@Deprecated
void assertAuthorizedForService(String serviceName) throws AccessControlException;
diff --git a/src/main/java/org/owasp/esapi/AccessReferenceMap.java b/src/main/java/org/owasp/esapi/AccessReferenceMap.java
index 4fd74e01e..f9e8cdc83 100644
--- a/src/main/java/org/owasp/esapi/AccessReferenceMap.java
+++ b/src/main/java/org/owasp/esapi/AccessReferenceMap.java
@@ -63,34 +63,34 @@
*/
public interface AccessReferenceMap extends Serializable {
- /**
- * Get an iterator through the direct object references. No guarantee is made as
- * to the order of items returned.
- *
- * @return the iterator
- */
- Iterator iterator();
+ /**
+ * Get an iterator through the direct object references. No guarantee is made as
+ * to the order of items returned.
+ *
+ * @return the iterator
+ */
+ Iterator iterator();
- /**
- * Get a safe indirect reference to use in place of a potentially sensitive
- * direct object reference. Developers should use this call when building
- * URL's, form fields, hidden fields, etc... to help protect their private
- * implementation information.
- *
- * @param directReference
- * the direct reference
- *
- * @return
- * the indirect reference
- */
- K getIndirectReference(T directReference);
+ /**
+ * Get a safe indirect reference to use in place of a potentially sensitive
+ * direct object reference. Developers should use this call when building
+ * URL's, form fields, hidden fields, etc... to help protect their private
+ * implementation information.
+ *
+ * @param directReference
+ * the direct reference
+ *
+ * @return
+ * the indirect reference
+ */
+ K getIndirectReference(T directReference);
- /**
- * Get the original direct object reference from an indirect reference.
- * Developers should use this when they get an indirect reference from a
- * request to translate it back into the real direct reference. If an
- * invalid indirect reference is requested, then an AccessControlException is
- * thrown.
+ /**
+ * Get the original direct object reference from an indirect reference.
+ * Developers should use this when they get an indirect reference from a
+ * request to translate it back into the real direct reference. If an
+ * invalid indirect reference is requested, then an AccessControlException is
+ * thrown.
*
* If a type is implied the requested object will be cast to that type, if the
* object is not of the requested type, a AccessControlException will be thrown to
@@ -122,55 +122,55 @@ public interface AccessReferenceMap extends Serializable {
* // ...
* }
*
- *
- * @param indirectReference
- * the indirect reference
- *
- * @return
- * the direct reference
- *
- * @throws AccessControlException
- * if no direct reference exists for the specified indirect reference
+ *
+ * @param indirectReference
+ * the indirect reference
+ *
+ * @return
+ * the direct reference
+ *
+ * @throws AccessControlException
+ * if no direct reference exists for the specified indirect reference
* @throws ClassCastException
* if the implied type is not the same as the referenced object type
- */
- T getDirectReference(K indirectReference) throws AccessControlException;
+ */
+ T getDirectReference(K indirectReference) throws AccessControlException;
- /**
- * Adds a direct reference to the AccessReferenceMap, then generates and returns
- * an associated indirect reference.
- *
- * @param direct
- * the direct reference
- *
- * @return
- * the corresponding indirect reference
- */
- K addDirectReference(T direct);
-
- /**
- * Removes a direct reference and its associated indirect reference from the AccessReferenceMap.
- *
- * @param direct
- * the direct reference to remove
- *
- * @return
- * the corresponding indirect reference
- *
- * @throws AccessControlException
+ /**
+ * Adds a direct reference to the AccessReferenceMap, then generates and returns
+ * an associated indirect reference.
+ *
+ * @param direct
+ * the direct reference
+ *
+ * @return
+ * the corresponding indirect reference
+ */
+ K addDirectReference(T direct);
+
+ /**
+ * Removes a direct reference and its associated indirect reference from the AccessReferenceMap.
+ *
+ * @param direct
+ * the direct reference to remove
+ *
+ * @return
+ * the corresponding indirect reference
+ *
+ * @throws AccessControlException
* if the reference does not exist.
- */
- K removeDirectReference(T direct) throws AccessControlException;
+ */
+ K removeDirectReference(T direct) throws AccessControlException;
- /**
- * Updates the access reference map with a new set of direct references, maintaining
- * any existing indirect references associated with items that are in the new list.
- * New indirect references could be generated every time, but that
- * might mess up anything that previously used an indirect reference, such
- * as a URL parameter.
- *
- * @param directReferences
- * a Set of direct references to add
- */
- void update(Set directReferences);
+ /**
+ * Updates the access reference map with a new set of direct references, maintaining
+ * any existing indirect references associated with items that are in the new list.
+ * New indirect references could be generated every time, but that
+ * might mess up anything that previously used an indirect reference, such
+ * as a URL parameter.
+ *
+ * @param directReferences
+ * a Set of direct references to add
+ */
+ void update(Set directReferences);
}
diff --git a/src/main/java/org/owasp/esapi/Authenticator.java b/src/main/java/org/owasp/esapi/Authenticator.java
index 57c090a46..bbc07ab90 100644
--- a/src/main/java/org/owasp/esapi/Authenticator.java
+++ b/src/main/java/org/owasp/esapi/Authenticator.java
@@ -59,92 +59,92 @@
*/
public interface Authenticator {
- /**
- * Clears the current User. This allows the thread to be reused safely.
+ /**
+ * Clears the current User. This allows the thread to be reused safely.
*
* This clears all threadlocal variables from the thread. This should ONLY be called after
* all possible ESAPI operations have concluded. If you clear too early, many calls will
* fail, including logging, which requires the user identity.
- */
- void clearCurrent();
+ */
+ void clearCurrent();
- /**
- * Calls login with the *current* request and response.
- * @return Authenticated {@code User} if login is successful.
- * @see HTTPUtilities#setCurrentHTTP(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
- */
- User login() throws AuthenticationException;
-
- /**
- * This method should be called for every HTTP request, to login the current user either from the session of HTTP
+ /**
+ * Calls login with the *current* request and response.
+ * @return Authenticated {@code User} if login is successful.
+ * @see HTTPUtilities#setCurrentHTTP(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
+ */
+ User login() throws AuthenticationException;
+
+ /**
+ * This method should be called for every HTTP request, to login the current user either from the session of HTTP
* request. This method will set the current user so that getCurrentUser() will work properly.
- *
- * Authenticates the user's credentials from the HttpServletRequest if
- * necessary, creates a session if necessary, and sets the user as the
- * current user.
- *
- * Specification: The implementation should do the following:
- * 1) Check if the User is already stored in the session
- * a. If so, check that session absolute and inactivity timeout have not expired
- * b. Step 2 may not be required if 1a has been satisfied
- * 2) Verify User credentials
- * a. It is recommended that you use
- * loginWithUsernameAndPassword(HttpServletRequest, HttpServletResponse) to verify credentials
- * 3) Set the last host of the User (ex. user.setLastHostAddress(address) )
- * 4) Verify that the request is secure (ex. over SSL)
- * 5) Verify the User account is allowed to be logged in
- * a. Verify the User is not disabled, expired or locked
- * 6) Assign User to session variable
- *
- * @param request
- * the current HTTP request
- * @param response
- * the HTTP response
- *
- * @return
- * the User
- *
- * @throws AuthenticationException
- * if the credentials are not verified, or if the account is disabled, locked, expired, or timed out
- */
- User login(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException;
+ *
+ * Authenticates the user's credentials from the HttpServletRequest if
+ * necessary, creates a session if necessary, and sets the user as the
+ * current user.
+ *
+ * Specification: The implementation should do the following:
+ * 1) Check if the User is already stored in the session
+ * a. If so, check that session absolute and inactivity timeout have not expired
+ * b. Step 2 may not be required if 1a has been satisfied
+ * 2) Verify User credentials
+ * a. It is recommended that you use
+ * loginWithUsernameAndPassword(HttpServletRequest, HttpServletResponse) to verify credentials
+ * 3) Set the last host of the User (ex. user.setLastHostAddress(address) )
+ * 4) Verify that the request is secure (ex. over SSL)
+ * 5) Verify the User account is allowed to be logged in
+ * a. Verify the User is not disabled, expired or locked
+ * 6) Assign User to session variable
+ *
+ * @param request
+ * the current HTTP request
+ * @param response
+ * the HTTP response
+ *
+ * @return
+ * the User
+ *
+ * @throws AuthenticationException
+ * if the credentials are not verified, or if the account is disabled, locked, expired, or timed out
+ */
+ User login(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException;
- /**
- * Verify that the supplied password matches the password for this user. Password should
- * be stored as a hash. By default, this method verifies password hashes created via the
+ /**
+ * Verify that the supplied password matches the password for this user. Password should
+ * be stored as a hash. By default, this method verifies password hashes created via the
* {@code hashPassword(password, accountName)} method in this class, however see WARNING
* the {@code hashPassword} method.
*
- * This method is typically used for "reauthentication" for the most sensitive functions, such
- * as transactions, changing email address, and changing other account information.
- *
- * @param user
- * the user who requires verification
- * @param password
- * the hashed user-supplied password
- *
- * @return
- * true, if the password is correct for the specified user
+ * This method is typically used for "reauthentication" for the most sensitive functions, such
+ * as transactions, changing email address, and changing other account information.
+ *
+ * @param user
+ * the user who requires verification
+ * @param password
+ * the hashed user-supplied password
+ *
+ * @return
+ * true, if the password is correct for the specified user
*
* @see #hashPassword(String password, String accountName)
- */
- boolean verifyPassword(User user, String password);
-
- /**
- * Logs out the current user.
- *
- * This is usually done by calling User.logout on the current User.
- */
+ */
+ boolean verifyPassword(User user, String password);
+
+ /**
+ * Logs out the current user.
+ *
+ * This is usually done by calling User.logout on the current User.
+ */
void logout();
- /**
- * Creates a new User with the information provided. Implementations should check
- * accountName and password for proper format and strength against brute force
- * attacks ( verifyAccountNameStrength(String), verifyPasswordStrength(String, String) ).
- *
- * Two copies of the new password are required to encourage user interface designers to
- * include a "re-type password" field in their forms. Implementations should verify that
- * both are the same.
+ /**
+ * Creates a new User with the information provided. Implementations should check
+ * accountName and password for proper format and strength against brute force
+ * attacks ( verifyAccountNameStrength(String), verifyPasswordStrength(String, String) ).
+ *
+ * Two copies of the new password are required to encourage user interface designers to
+ * include a "re-type password" field in their forms. Implementations should verify that
+ * both are the same.
*
* WARNING: The implementation of this method as defined in the
* default reference implementation class, {@code FileBasedAuthenticator},
@@ -152,122 +152,122 @@ public interface Authenticator {
* to replace the default reference implementation class with your own custom
* implementation that uses a stronger password hashing algorithm.
* See class comments in * {@code FileBasedAuthenticator} for further details.
- *
- * @param accountName
- * the account name of the new user
- * @param password1
- * the password of the new user
- * @param password2
- * the password of the new user. This field is to encourage user interface designers to include two password fields in their forms.
- *
- * @return
- * the User that has been created
- *
- * @throws AuthenticationException
- * if user creation fails due to any of the qualifications listed in this method's description
- */
- User createUser(String accountName, String password1, String password2) throws AuthenticationException;
+ *
+ * @param accountName
+ * the account name of the new user
+ * @param password1
+ * the password of the new user
+ * @param password2
+ * the password of the new user. This field is to encourage user interface designers to include two password fields in their forms.
+ *
+ * @return
+ * the User that has been created
+ *
+ * @throws AuthenticationException
+ * if user creation fails due to any of the qualifications listed in this method's description
+ */
+ User createUser(String accountName, String password1, String password2) throws AuthenticationException;
- /**
- * Generate a strong password. Implementations should use a large character set that does not
- * include confusing characters, such as i I 1 l 0 o and O. There are many algorithms to
- * generate strong memorable passwords that have been studied in the past.
- *
- * @return
- * a password with strong password strength
- */
- String generateStrongPassword();
+ /**
+ * Generate a strong password. Implementations should use a large character set that does not
+ * include confusing characters, such as i I 1 l 0 o and O. There are many algorithms to
+ * generate strong memorable passwords that have been studied in the past.
+ *
+ * @return
+ * a password with strong password strength
+ */
+ String generateStrongPassword();
- /**
- * Generate strong password that takes into account the user's information and old password. Implementations
- * should verify that the new password does not include information such as the username, fragments of the
- * old password, and other information that could be used to weaken the strength of the password.
- *
- * @param user
- * the user whose information to use when generating password
- * @param oldPassword
- * the old password to use when verifying strength of new password. The new password may be checked for fragments of oldPassword.
- *
- * @return
- * a password with strong password strength
- */
- String generateStrongPassword(User user, String oldPassword);
+ /**
+ * Generate strong password that takes into account the user's information and old password. Implementations
+ * should verify that the new password does not include information such as the username, fragments of the
+ * old password, and other information that could be used to weaken the strength of the password.
+ *
+ * @param user
+ * the user whose information to use when generating password
+ * @param oldPassword
+ * the old password to use when verifying strength of new password. The new password may be checked for fragments of oldPassword.
+ *
+ * @return
+ * a password with strong password strength
+ */
+ String generateStrongPassword(User user, String oldPassword);
- /**
- * Changes the password for the specified user. This requires the current password, as well as
- * the password to replace it with. The new password should be checked against old hashes to be sure the new password does not closely resemble or equal any recent passwords for that User.
- * Password strength should also be verified. This new password must be repeated to ensure that the user has typed it in correctly.
- *
- * @param user
- * the user to change the password for
- * @param currentPassword
- * the current password for the specified user
- * @param newPassword
- * the new password to use
- * @param newPassword2
- * a verification copy of the new password
- *
- * @throws AuthenticationException
- * if any errors occur
- */
- void changePassword(User user, String currentPassword, String newPassword, String newPassword2) throws AuthenticationException;
-
- /**
- * Returns the User matching the provided accountId. If the accoundId is not found, an Anonymous
- * User or null may be returned.
- *
- * @param accountId
- * the account id
- *
- * @return
- * the matching User object, or the Anonymous User if no match exists
- */
- User getUser(long accountId);
-
- /**
- * Returns the User matching the provided accountName. If the accoundId is not found, an Anonymous
- * User or null may be returned.
- *
- * @param accountName
- * the account name
- *
- * @return
- * the matching User object, or the Anonymous User if no match exists
- */
- User getUser(String accountName);
+ /**
+ * Changes the password for the specified user. This requires the current password, as well as
+ * the password to replace it with. The new password should be checked against old hashes to be sure the new password does not closely resemble or equal any recent passwords for that User.
+ * Password strength should also be verified. This new password must be repeated to ensure that the user has typed it in correctly.
+ *
+ * @param user
+ * the user to change the password for
+ * @param currentPassword
+ * the current password for the specified user
+ * @param newPassword
+ * the new password to use
+ * @param newPassword2
+ * a verification copy of the new password
+ *
+ * @throws AuthenticationException
+ * if any errors occur
+ */
+ void changePassword(User user, String currentPassword, String newPassword, String newPassword2) throws AuthenticationException;
+
+ /**
+ * Returns the User matching the provided accountId. If the accoundId is not found, an Anonymous
+ * User or null may be returned.
+ *
+ * @param accountId
+ * the account id
+ *
+ * @return
+ * the matching User object, or the Anonymous User if no match exists
+ */
+ User getUser(long accountId);
+
+ /**
+ * Returns the User matching the provided accountName. If the accoundId is not found, an Anonymous
+ * User or null may be returned.
+ *
+ * @param accountName
+ * the account name
+ *
+ * @return
+ * the matching User object, or the Anonymous User if no match exists
+ */
+ User getUser(String accountName);
- /**
- * Gets a collection containing all the existing user names.
- *
- * @return
- * a set of all user names
- */
- Set getUserNames();
+ /**
+ * Gets a collection containing all the existing user names.
+ *
+ * @return
+ * a set of all user names
+ */
+ Set getUserNames();
- /**
- * Returns the currently logged in User.
- *
- * @return
- * the matching User object, or the Anonymous User if no match
- * exists
- */
- User getCurrentUser();
+ /**
+ * Returns the currently logged in User.
+ *
+ * @return
+ * the matching User object, or the Anonymous User if no match
+ * exists
+ */
+ User getCurrentUser();
- /**
- * Sets the currently logged in User.
- *
- * @param user
- * the user to set as the current user
- */
- void setCurrentUser(User user);
+ /**
+ * Sets the currently logged in User.
+ *
+ * @param user
+ * the user to set as the current user
+ */
+ void setCurrentUser(User user);
- /**
- * Returns a string representation of the hashed password, using the
- * accountName as the salt. The salt helps to prevent against "rainbow"
- * table attacks where the attacker pre-calculates hashes for known strings.
- * This method specifies the use of the user's account name as the "salt"
- * value. The Encryptor.hash method can be used if a different salt is
- * required.
+ /**
+ * Returns a string representation of the hashed password, using the
+ * accountName as the salt. The salt helps to prevent against "rainbow"
+ * table attacks where the attacker pre-calculates hashes for known strings.
+ * This method specifies the use of the user's account name as the "salt"
+ * value. The Encryptor.hash method can be used if a different salt is
+ * required.
*
* WARNING: The implementation of this method as defined in the
* default reference implementation class, {@code FileBasedAuthenticator},
@@ -275,71 +275,71 @@ public interface Authenticator {
* meant to be an example implementation and generally should be avoided
* and replaced with your own implementation. See class comments in
* {@code FileBasedAuthenticator} for further details.
- *
- * @param password
- * the password to hash
- * @param accountName
- * the account name to use as the salt
- *
- * @return
- * the hashed password
+ *
+ * @param password
+ * the password to hash
+ * @param accountName
+ * the account name to use as the salt
+ *
+ * @return
+ * the hashed password
* @throws EncryptionException
*
* @see org.owasp.esapi.reference.FileBasedAuthenticator FileBasedAuthenticator,
* the default reference implementation of this interface.
- */
- String hashPassword(String password, String accountName) throws EncryptionException;
+ */
+ String hashPassword(String password, String accountName) throws EncryptionException;
- /**
- * Removes the account of the specified accountName.
- *
- * @param accountName
- * the account name to remove
- *
- * @throws AuthenticationException
- * the authentication exception if user does not exist
- */
- void removeUser(String accountName) throws AuthenticationException;
+ /**
+ * Removes the account of the specified accountName.
+ *
+ * @param accountName
+ * the account name to remove
+ *
+ * @throws AuthenticationException
+ * the authentication exception if user does not exist
+ */
+ void removeUser(String accountName) throws AuthenticationException;
- /**
- * Ensures that the account name passes site-specific complexity requirements, like minimum length.
- *
- * @param accountName
- * the account name
- *
- * @throws AuthenticationException
- * if account name does not meet complexity requirements
- */
- void verifyAccountNameStrength(String accountName) throws AuthenticationException;
+ /**
+ * Ensures that the account name passes site-specific complexity requirements, like minimum length.
+ *
+ * @param accountName
+ * the account name
+ *
+ * @throws AuthenticationException
+ * if account name does not meet complexity requirements
+ */
+ void verifyAccountNameStrength(String accountName) throws AuthenticationException;
- /**
- * Ensures that the password meets site-specific complexity requirements, like length or number
- * of character sets. This method takes the old password so that the algorithm can analyze the
- * new password to see if it is too similar to the old password. Note that this has to be
- * invoked when the user has entered the old password, as the list of old
- * credentials stored by ESAPI is all hashed.
- * Additionally, the user object is taken in order to verify the password and account name differ.
- *
- * @param oldPassword
- * the old password
- * @param newPassword
- * the new password
- * @param user
- * the user
- *
- * @throws AuthenticationException
- * if newPassword is too similar to oldPassword or if newPassword does not meet complexity requirements
- */
- void verifyPasswordStrength(String oldPassword, String newPassword, User user) throws AuthenticationException;
+ /**
+ * Ensures that the password meets site-specific complexity requirements, like length or number
+ * of character sets. This method takes the old password so that the algorithm can analyze the
+ * new password to see if it is too similar to the old password. Note that this has to be
+ * invoked when the user has entered the old password, as the list of old
+ * credentials stored by ESAPI is all hashed.
+ * Additionally, the user object is taken in order to verify the password and account name differ.
+ *
+ * @param oldPassword
+ * the old password
+ * @param newPassword
+ * the new password
+ * @param user
+ * the user
+ *
+ * @throws AuthenticationException
+ * if newPassword is too similar to oldPassword or if newPassword does not meet complexity requirements
+ */
+ void verifyPasswordStrength(String oldPassword, String newPassword, User user) throws AuthenticationException;
- /**
- * Determine if the account exists.
- *
- * @param accountName
- * the account name
- *
- * @return true, if the account exists
- */
- boolean exists(String accountName);
+ /**
+ * Determine if the account exists.
+ *
+ * @param accountName
+ * the account name
+ *
+ * @return true, if the account exists
+ */
+ boolean exists(String accountName);
}
diff --git a/src/main/java/org/owasp/esapi/ESAPI.java b/src/main/java/org/owasp/esapi/ESAPI.java
index e11239c75..283156edf 100644
--- a/src/main/java/org/owasp/esapi/ESAPI.java
+++ b/src/main/java/org/owasp/esapi/ESAPI.java
@@ -26,171 +26,171 @@
* Use the set methods to override the reference implementations with instances of any custom ESAPI implementations.
*/
public final class ESAPI {
- private static String securityConfigurationImplName = System.getProperty("org.owasp.esapi.SecurityConfiguration", "org.owasp.esapi.reference.DefaultSecurityConfiguration");
-
- /**
- * prevent instantiation of this class
- */
- private ESAPI() {
- }
-
- /**
- * Clears the current User, HttpRequest, and HttpResponse associated with the current thread. This method
- * MUST be called as some containers do not properly clear threadlocal variables when the execution of
- * a thread is complete. The suggested approach is to put this call in a finally block inside a filter.
- *
- * The advantages of having identity everywhere are worth the risk here.
- */
- public static void clearCurrent() {
- authenticator().clearCurrent();
- httpUtilities().clearCurrent();
- }
-
- /**
- * Get the current HTTP Servlet Request being processed.
- * @return the current HTTP Servlet Request.
- */
- public static HttpServletRequest currentRequest() {
- return httpUtilities().getCurrentRequest();
- }
-
- /**
- * Get the current HTTP Servlet Response being generated.
- * @return the current HTTP Servlet Response.
- */
- public static HttpServletResponse currentResponse() {
- return httpUtilities().getCurrentResponse();
- }
-
- /**
- * @return the current ESAPI AccessController object being used to maintain the access control rules for this application.
- */
- public static AccessController accessController() {
+ private static String securityConfigurationImplName = System.getProperty("org.owasp.esapi.SecurityConfiguration", "org.owasp.esapi.reference.DefaultSecurityConfiguration");
+
+ /**
+ * prevent instantiation of this class
+ */
+ private ESAPI() {
+ }
+
+ /**
+ * Clears the current User, HttpRequest, and HttpResponse associated with the current thread. This method
+ * MUST be called as some containers do not properly clear threadlocal variables when the execution of
+ * a thread is complete. The suggested approach is to put this call in a finally block inside a filter.
+ *
+ * The advantages of having identity everywhere are worth the risk here.
+ */
+ public static void clearCurrent() {
+ authenticator().clearCurrent();
+ httpUtilities().clearCurrent();
+ }
+
+ /**
+ * Get the current HTTP Servlet Request being processed.
+ * @return the current HTTP Servlet Request.
+ */
+ public static HttpServletRequest currentRequest() {
+ return httpUtilities().getCurrentRequest();
+ }
+
+ /**
+ * Get the current HTTP Servlet Response being generated.
+ * @return the current HTTP Servlet Response.
+ */
+ public static HttpServletResponse currentResponse() {
+ return httpUtilities().getCurrentResponse();
+ }
+
+ /**
+ * @return the current ESAPI AccessController object being used to maintain the access control rules for this application.
+ */
+ public static AccessController accessController() {
return ObjFactory.make( securityConfiguration().getAccessControlImplementation(), "AccessController" );
- }
+ }
- /**
- * @return the current ESAPI Authenticator object being used to authenticate users for this application.
- */
- public static Authenticator authenticator() {
+ /**
+ * @return the current ESAPI Authenticator object being used to authenticate users for this application.
+ */
+ public static Authenticator authenticator() {
return ObjFactory.make( securityConfiguration().getAuthenticationImplementation(), "Authenticator" );
- }
+ }
- /**
+ /**
* The ESAPI Encoder is primarilly used to provide output encoding to
* prevent Cross-Site Scripting (XSS).
- * @return the current ESAPI Encoder object being used to encode and decode data for this application.
- */
- public static Encoder encoder() {
+ * @return the current ESAPI Encoder object being used to encode and decode data for this application.
+ */
+ public static Encoder encoder() {
return ObjFactory.make( securityConfiguration().getEncoderImplementation(), "Encoder" );
- }
+ }
- /**
- * @return the current ESAPI Encryptor object being used to encrypt and decrypt data for this application.
- */
- public static Encryptor encryptor() {
+ /**
+ * @return the current ESAPI Encryptor object being used to encrypt and decrypt data for this application.
+ */
+ public static Encryptor encryptor() {
return ObjFactory.make( securityConfiguration().getEncryptionImplementation(), "Encryptor" );
- }
+ }
- /**
- * @return the current ESAPI Executor object being used to safely execute OS commands for this application.
- */
- public static Executor executor() {
+ /**
+ * @return the current ESAPI Executor object being used to safely execute OS commands for this application.
+ */
+ public static Executor executor() {
return ObjFactory.make( securityConfiguration().getExecutorImplementation(), "Executor" );
- }
+ }
- /**
- * @return the current ESAPI HTTPUtilities object being used to safely access HTTP requests and responses
- * for this application.
- */
- public static HTTPUtilities httpUtilities() {
+ /**
+ * @return the current ESAPI HTTPUtilities object being used to safely access HTTP requests and responses
+ * for this application.
+ */
+ public static HTTPUtilities httpUtilities() {
return ObjFactory.make( securityConfiguration().getHTTPUtilitiesImplementation(), "HTTPUtilities" );
- }
+ }
- /**
- * @return the current ESAPI IntrusionDetector being used to monitor for intrusions in this application.
- */
- public static IntrusionDetector intrusionDetector() {
+ /**
+ * @return the current ESAPI IntrusionDetector being used to monitor for intrusions in this application.
+ */
+ public static IntrusionDetector intrusionDetector() {
return ObjFactory.make( securityConfiguration().getIntrusionDetectionImplementation(), "IntrusionDetector" );
- }
-
- /**
- * Get the current LogFactory being used by ESAPI. If there isn't one yet, it will create one, and then
- * return this same LogFactory from then on.
- * @return The current LogFactory being used by ESAPI.
- */
- private static LogFactory logFactory() {
+ }
+
+ /**
+ * Get the current LogFactory being used by ESAPI. If there isn't one yet, it will create one, and then
+ * return this same LogFactory from then on.
+ * @return The current LogFactory being used by ESAPI.
+ */
+ private static LogFactory logFactory() {
return ObjFactory.make( securityConfiguration().getLogImplementation(), "LogFactory" );
- }
-
- /**
- * @param clazz The class to associate the logger with.
- * @return The current Logger associated with the specified class.
- */
- public static Logger getLogger(Class clazz) {
- return logFactory().getLogger(clazz);
- }
-
- /**
- * @param moduleName The module to associate the logger with.
- * @return The current Logger associated with the specified module.
- */
- public static Logger getLogger(String moduleName) {
- return logFactory().getLogger(moduleName);
- }
-
- /**
- * @return The default Logger.
- */
- public static Logger log() {
+ }
+
+ /**
+ * @param clazz The class to associate the logger with.
+ * @return The current Logger associated with the specified class.
+ */
+ public static Logger getLogger(Class clazz) {
+ return logFactory().getLogger(clazz);
+ }
+
+ /**
+ * @param moduleName The module to associate the logger with.
+ * @return The current Logger associated with the specified module.
+ */
+ public static Logger getLogger(String moduleName) {
+ return logFactory().getLogger(moduleName);
+ }
+
+ /**
+ * @return The default Logger.
+ */
+ public static Logger log() {
return logFactory().getLogger("DefaultLogger");
}
-
- /**
- * @return the current ESAPI Randomizer being used to generate random numbers in this application.
- */
- public static Randomizer randomizer() {
+
+ /**
+ * @return the current ESAPI Randomizer being used to generate random numbers in this application.
+ */
+ public static Randomizer randomizer() {
return ObjFactory.make( securityConfiguration().getRandomizerImplementation(), "Randomizer" );
- }
+ }
private static volatile SecurityConfiguration overrideConfig = null;
- /**
- * @return the current ESAPI SecurityConfiguration being used to manage the security configuration for
- * ESAPI for this application.
- */
- public static SecurityConfiguration securityConfiguration() {
- // copy the volatile into a non-volatile to prevent TOCTTOU race condition
- SecurityConfiguration override = overrideConfig;
- if ( override != null ) {
- return override;
+ /**
+ * @return the current ESAPI SecurityConfiguration being used to manage the security configuration for
+ * ESAPI for this application.
+ */
+ public static SecurityConfiguration securityConfiguration() {
+ // copy the volatile into a non-volatile to prevent TOCTTOU race condition
+ SecurityConfiguration override = overrideConfig;
+ if ( override != null ) {
+ return override;
}
return ObjFactory.make( securityConfigurationImplName, "SecurityConfiguration" );
- }
+ }
- /**
- * @return the current ESAPI Validator being used to validate data in this application.
- */
- public static Validator validator() {
+ /**
+ * @return the current ESAPI Validator being used to validate data in this application.
+ */
+ public static Validator validator() {
return ObjFactory.make( securityConfiguration().getValidationImplementation(), "Validator" );
- }
+ }
// TODO: This should probably use the SecurityManager or some value within the current
// securityConfiguration to determine if this method is allowed to be called. This could
diff --git a/src/main/java/org/owasp/esapi/EncoderConstants.java b/src/main/java/org/owasp/esapi/EncoderConstants.java
index 1498d5ea7..724b15ad4 100644
--- a/src/main/java/org/owasp/esapi/EncoderConstants.java
+++ b/src/main/java/org/owasp/esapi/EncoderConstants.java
@@ -11,107 +11,107 @@
* @see User
*/
public class EncoderConstants {
- /**
- * !$*-.=?@_
- */
- public final static char[] CHAR_PASSWORD_SPECIALS = { '!', '$', '*', '-', '.', '=', '?', '@', '_' };
- public final static Set PASSWORD_SPECIALS;
- static {
- PASSWORD_SPECIALS = CollectionsUtil.arrayToSet(CHAR_PASSWORD_SPECIALS);
- }
-
- /**
- * a-b
- */
- public final static char[] CHAR_LOWERS = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
- public final static Set LOWERS;
- static {
- LOWERS = CollectionsUtil.arrayToSet(CHAR_PASSWORD_SPECIALS);
- }
-
- /**
- * A-Z
- */
- public final static char[] CHAR_UPPERS = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
- public final static Set UPPERS;
- static {
- UPPERS = CollectionsUtil.arrayToSet(CHAR_UPPERS);
- }
- /**
- * 0-9
- */
- public final static char[] CHAR_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
- public final static Set DIGITS;
- static {
- DIGITS = CollectionsUtil.arrayToSet(CHAR_DIGITS);
- }
-
- /**
- * !$*+-.=?@^_|~
- */
- public final static char[] CHAR_SPECIALS = { '!', '$', '*', '+', '-', '.', '=', '?', '@', '^', '_', '|', '~' };
- public final static Set SPECIALS;
- static {
- SPECIALS = CollectionsUtil.arrayToSet(CHAR_SPECIALS);
- }
-
- /**
- * CHAR_LOWERS union CHAR_UPPERS
- */
- public final static char[] CHAR_LETTERS = StringUtilities.union(CHAR_LOWERS, CHAR_UPPERS);
- public final static Set LETTERS;
- static {
- LETTERS = CollectionsUtil.arrayToSet(CHAR_LETTERS);
- }
-
- /**
- * CHAR_LETTERS union CHAR_DIGITS
- */
- public final static char[] CHAR_ALPHANUMERICS = StringUtilities.union(CHAR_LETTERS, CHAR_DIGITS);
- public final static Set ALPHANUMERICS;
- static {
- ALPHANUMERICS = CollectionsUtil.arrayToSet(CHAR_ALPHANUMERICS);
- }
-
- /**
- * Password character set, is alphanumerics (without l, i, I, o, O, and 0)
- * selected specials like + (bad for URL encoding, | is like i and 1,
- * etc...)
- */
- public final static char[] CHAR_PASSWORD_LOWERS = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
- public final static Set PASSWORD_LOWERS;
- static {
- PASSWORD_LOWERS = CollectionsUtil.arrayToSet(CHAR_ALPHANUMERICS);
- }
-
- /**
- *
- */
- public final static char[] CHAR_PASSWORD_UPPERS = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
- public final static Set PASSWORD_UPPERS;
- static {
- PASSWORD_UPPERS = CollectionsUtil.arrayToSet(CHAR_PASSWORD_UPPERS);
- }
-
- /**
- * 2-9
- */
- public final static char[] CHAR_PASSWORD_DIGITS = { '2', '3', '4', '5', '6', '7', '8', '9' };
- public final static Set PASSWORD_DIGITS;
- static {
- PASSWORD_DIGITS = CollectionsUtil.arrayToSet(CHAR_PASSWORD_DIGITS);
- }
-
- /**
- * CHAR_PASSWORD_LOWERS union CHAR_PASSWORD_UPPERS
- */
- public final static char[] CHAR_PASSWORD_LETTERS = StringUtilities.union( CHAR_PASSWORD_LOWERS, CHAR_PASSWORD_UPPERS );
- public final static Set PASSWORD_LETTERS;
- static {
- PASSWORD_LETTERS = CollectionsUtil.arrayToSet(CHAR_PASSWORD_LETTERS);
- }
+ /**
+ * !$*-.=?@_
+ */
+ public final static char[] CHAR_PASSWORD_SPECIALS = { '!', '$', '*', '-', '.', '=', '?', '@', '_' };
+ public final static Set PASSWORD_SPECIALS;
+ static {
+ PASSWORD_SPECIALS = CollectionsUtil.arrayToSet(CHAR_PASSWORD_SPECIALS);
+ }
+
+ /**
+ * a-b
+ */
+ public final static char[] CHAR_LOWERS = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
+ public final static Set LOWERS;
+ static {
+ LOWERS = CollectionsUtil.arrayToSet(CHAR_PASSWORD_SPECIALS);
+ }
+
+ /**
+ * A-Z
+ */
+ public final static char[] CHAR_UPPERS = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
+ public final static Set UPPERS;
+ static {
+ UPPERS = CollectionsUtil.arrayToSet(CHAR_UPPERS);
+ }
+ /**
+ * 0-9
+ */
+ public final static char[] CHAR_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
+ public final static Set DIGITS;
+ static {
+ DIGITS = CollectionsUtil.arrayToSet(CHAR_DIGITS);
+ }
+
+ /**
+ * !$*+-.=?@^_|~
+ */
+ public final static char[] CHAR_SPECIALS = { '!', '$', '*', '+', '-', '.', '=', '?', '@', '^', '_', '|', '~' };
+ public final static Set SPECIALS;
+ static {
+ SPECIALS = CollectionsUtil.arrayToSet(CHAR_SPECIALS);
+ }
+
+ /**
+ * CHAR_LOWERS union CHAR_UPPERS
+ */
+ public final static char[] CHAR_LETTERS = StringUtilities.union(CHAR_LOWERS, CHAR_UPPERS);
+ public final static Set LETTERS;
+ static {
+ LETTERS = CollectionsUtil.arrayToSet(CHAR_LETTERS);
+ }
+
+ /**
+ * CHAR_LETTERS union CHAR_DIGITS
+ */
+ public final static char[] CHAR_ALPHANUMERICS = StringUtilities.union(CHAR_LETTERS, CHAR_DIGITS);
+ public final static Set ALPHANUMERICS;
+ static {
+ ALPHANUMERICS = CollectionsUtil.arrayToSet(CHAR_ALPHANUMERICS);
+ }
+
+ /**
+ * Password character set, is alphanumerics (without l, i, I, o, O, and 0)
+ * selected specials like + (bad for URL encoding, | is like i and 1,
+ * etc...)
+ */
+ public final static char[] CHAR_PASSWORD_LOWERS = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
+ public final static Set PASSWORD_LOWERS;
+ static {
+ PASSWORD_LOWERS = CollectionsUtil.arrayToSet(CHAR_ALPHANUMERICS);
+ }
+
+ /**
+ *
+ */
+ public final static char[] CHAR_PASSWORD_UPPERS = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
+ public final static Set PASSWORD_UPPERS;
+ static {
+ PASSWORD_UPPERS = CollectionsUtil.arrayToSet(CHAR_PASSWORD_UPPERS);
+ }
+
+ /**
+ * 2-9
+ */
+ public final static char[] CHAR_PASSWORD_DIGITS = { '2', '3', '4', '5', '6', '7', '8', '9' };
+ public final static Set PASSWORD_DIGITS;
+ static {
+ PASSWORD_DIGITS = CollectionsUtil.arrayToSet(CHAR_PASSWORD_DIGITS);
+ }
+
+ /**
+ * CHAR_PASSWORD_LOWERS union CHAR_PASSWORD_UPPERS
+ */
+ public final static char[] CHAR_PASSWORD_LETTERS = StringUtilities.union( CHAR_PASSWORD_LOWERS, CHAR_PASSWORD_UPPERS );
+ public final static Set PASSWORD_LETTERS;
+ static {
+ PASSWORD_LETTERS = CollectionsUtil.arrayToSet(CHAR_PASSWORD_LETTERS);
+ }
- private EncoderConstants() {
- // prevent instantiation
- }
+ private EncoderConstants() {
+ // prevent instantiation
+ }
}
diff --git a/src/main/java/org/owasp/esapi/EncryptedProperties.java b/src/main/java/org/owasp/esapi/EncryptedProperties.java
index 9e1a857ac..fbec7e2c1 100644
--- a/src/main/java/org/owasp/esapi/EncryptedProperties.java
+++ b/src/main/java/org/owasp/esapi/EncryptedProperties.java
@@ -38,75 +38,75 @@
*/
public interface EncryptedProperties {
- /**
- * Gets the property value from the encrypted store, decrypts it, and
- * returns the plaintext value to the caller.
- *
- * @param key
- * the name of the property to get
- *
- * @return
- * The decrypted property value. null if the key is not set.
- *
- * @throws EncryptionException
- * if the property could not be decrypted
- */
- String getProperty(String key) throws EncryptionException;
+ /**
+ * Gets the property value from the encrypted store, decrypts it, and
+ * returns the plaintext value to the caller.
+ *
+ * @param key
+ * the name of the property to get
+ *
+ * @return
+ * The decrypted property value. null if the key is not set.
+ *
+ * @throws EncryptionException
+ * if the property could not be decrypted
+ */
+ String getProperty(String key) throws EncryptionException;
- /**
- * Encrypts the plaintext property value and stores the ciphertext value
- * in the encrypted store.
- *
- * @param key
- * the name of the property to set
- * @param value
- * the value of the property to set
- *
- * @return
- * the previously encrypted property value for the specified key, or
- * {@code null} if it did not have one.
- *
- * @throws EncryptionException
- * if the property could not be encrypted
- */
- String setProperty(String key, String value) throws EncryptionException;
-
- /**
- * Returns a {@code Set} view of properties. The {@code Set} is backed by a
- * {@code java.util.Hashtable}, so changes to the {@code Hashtable} are
- * reflected in the {@code Set}, and vice-versa. The {@code Set} supports element
- * removal (which removes the corresponding entry from the {@code Hashtable},
- * but not element addition.
- *
- * @return
- * a set view of the properties contained in this map.
- */
- Set> keySet();
-
- /**
- * Reads a property list (key and element pairs) from the input stream.
- *
- * @param in
- * the input stream that contains the properties file
- *
- * @throws IOException
- * Signals that an I/O exception has occurred.
- */
- void load(InputStream in) throws IOException;
-
- /**
- * Writes this property list (key and element pairs) in this Properties table to
- * the output stream in a format suitable for loading into a Properties table using the load method.
- *
- * @param out
- * the output stream that contains the properties file
- * @param comments
- * a description of the property list (ex. "Encrypted Properties File").
- *
- * @throws IOException
- * Signals that an I/O exception has occurred.
- */
- void store(OutputStream out, String comments) throws IOException;
-
-
+ /**
+ * Encrypts the plaintext property value and stores the ciphertext value
+ * in the encrypted store.
+ *
+ * @param key
+ * the name of the property to set
+ * @param value
+ * the value of the property to set
+ *
+ * @return
+ * the previously encrypted property value for the specified key, or
+ * {@code null} if it did not have one.
+ *
+ * @throws EncryptionException
+ * if the property could not be encrypted
+ */
+ String setProperty(String key, String value) throws EncryptionException;
+
+ /**
+ * Returns a {@code Set} view of properties. The {@code Set} is backed by a
+ * {@code java.util.Hashtable}, so changes to the {@code Hashtable} are
+ * reflected in the {@code Set}, and vice-versa. The {@code Set} supports element
+ * removal (which removes the corresponding entry from the {@code Hashtable},
+ * but not element addition.
+ *
+ * @return
+ * a set view of the properties contained in this map.
+ */
+ Set> keySet();
+
+ /**
+ * Reads a property list (key and element pairs) from the input stream.
+ *
+ * @param in
+ * the input stream that contains the properties file
+ *
+ * @throws IOException
+ * Signals that an I/O exception has occurred.
+ */
+ void load(InputStream in) throws IOException;
+
+ /**
+ * Writes this property list (key and element pairs) in this Properties table to
+ * the output stream in a format suitable for loading into a Properties table using the load method.
+ *
+ * @param out
+ * the output stream that contains the properties file
+ * @param comments
+ * a description of the property list (ex. "Encrypted Properties File").
+ *
+ * @throws IOException
+ * Signals that an I/O exception has occurred.
+ */
+ void store(OutputStream out, String comments) throws IOException;
+
+
}
diff --git a/src/main/java/org/owasp/esapi/Encryptor.java b/src/main/java/org/owasp/esapi/Encryptor.java
index 6c83fef60..64134849b 100644
--- a/src/main/java/org/owasp/esapi/Encryptor.java
+++ b/src/main/java/org/owasp/esapi/Encryptor.java
@@ -57,177 +57,177 @@
*/
public interface Encryptor {
- /**
- * Returns a string representation of the hash of the provided plaintext and
- * salt. The salt helps to protect against a rainbow table attack by mixing
- * in some extra data with the plaintext. Some good choices for a salt might
- * be an account name or some other string that is known to the application
- * but not to an attacker.
- * See
- * this article for more information about hashing as it pertains to password schemes.
- *
- * @param plaintext
- * the plaintext String to encrypt
- * @param salt
- * the salt to add to the plaintext String before hashing
- *
- * @return
- * the encrypted hash of 'plaintext' stored as a String
- *
- * @throws EncryptionException
- * if the specified hash algorithm could not be found or another problem exists with
- * the hashing of 'plaintext'
- */
- String hash(String plaintext, String salt) throws EncryptionException;
+ /**
+ * Returns a string representation of the hash of the provided plaintext and
+ * salt. The salt helps to protect against a rainbow table attack by mixing
+ * in some extra data with the plaintext. Some good choices for a salt might
+ * be an account name or some other string that is known to the application
+ * but not to an attacker.
+ * See
+ * this article for more information about hashing as it pertains to password schemes.
+ *
+ * @param plaintext
+ * the plaintext String to encrypt
+ * @param salt
+ * the salt to add to the plaintext String before hashing
+ *
+ * @return
+ * the encrypted hash of 'plaintext' stored as a String
+ *
+ * @throws EncryptionException
+ * if the specified hash algorithm could not be found or another problem exists with
+ * the hashing of 'plaintext'
+ */
+ String hash(String plaintext, String salt) throws EncryptionException;
- /**
- * Returns a string representation of the hash of the provided plaintext and
- * salt. The salt helps to protect against a rainbow table attack by mixing
- * in some extra data with the plaintext. Some good choices for a salt might
- * be an account name or some other string that is known to the application
- * but not to an attacker.
- * See
- * this article for more information about hashing as it pertains to password schemes.
- *
- * @param plaintext
- * the plaintext String to encrypt
- * @param salt
- * the salt to add to the plaintext String before hashing
- * @param iterations
- * the number of times to iterate the hash
- *
- * @return
- * the encrypted hash of 'plaintext' stored as a String
- *
- * @throws EncryptionException
- * if the specified hash algorithm could not be found or another problem exists with
- * the hashing of 'plaintext'
- */
- String hash(String plaintext, String salt, int iterations) throws EncryptionException;
-
- /**
- * Encrypts the provided plaintext bytes using the cipher transformation
- * specified by the property Encryptor.CipherTransformation
- * and the master encryption key as specified by the property
- * {@code Encryptor.MasterKey} as defined in the ESAPI.properties file.
- *
- *
- * @param plaintext The {@code PlainText} to be encrypted.
- * @return the {@code CipherText} object from which the raw ciphertext, the
- * IV, the cipher transformation, and many other aspects about
- * the encryption detail may be extracted.
- * @throws EncryptionException Thrown if something should go wrong such as
- * the JCE provider cannot be found, the cipher algorithm,
- * cipher mode, or padding scheme not being supported, specifying
- * an unsupported key size, specifying an IV of incorrect length,
- * etc.
- * @see #encrypt(SecretKey, PlainText)
- * @since 2.0
- */
- CipherText encrypt(PlainText plaintext) throws EncryptionException;
+ /**
+ * Returns a string representation of the hash of the provided plaintext and
+ * salt. The salt helps to protect against a rainbow table attack by mixing
+ * in some extra data with the plaintext. Some good choices for a salt might
+ * be an account name or some other string that is known to the application
+ * but not to an attacker.
+ * See
+ * this article for more information about hashing as it pertains to password schemes.
+ *
+ * @param plaintext
+ * the plaintext String to encrypt
+ * @param salt
+ * the salt to add to the plaintext String before hashing
+ * @param iterations
+ * the number of times to iterate the hash
+ *
+ * @return
+ * the encrypted hash of 'plaintext' stored as a String
+ *
+ * @throws EncryptionException
+ * if the specified hash algorithm could not be found or another problem exists with
+ * the hashing of 'plaintext'
+ */
+ String hash(String plaintext, String salt, int iterations) throws EncryptionException;
+
+ /**
+ * Encrypts the provided plaintext bytes using the cipher transformation
+ * specified by the property Encryptor.CipherTransformation
+ * and the master encryption key as specified by the property
+ * {@code Encryptor.MasterKey} as defined in the ESAPI.properties file.
+ *
+ *
+ * @param plaintext The {@code PlainText} to be encrypted.
+ * @return the {@code CipherText} object from which the raw ciphertext, the
+ * IV, the cipher transformation, and many other aspects about
+ * the encryption detail may be extracted.
+ * @throws EncryptionException Thrown if something should go wrong such as
+ * the JCE provider cannot be found, the cipher algorithm,
+ * cipher mode, or padding scheme not being supported, specifying
+ * an unsupported key size, specifying an IV of incorrect length,
+ * etc.
+ * @see #encrypt(SecretKey, PlainText)
+ * @since 2.0
+ */
+ CipherText encrypt(PlainText plaintext) throws EncryptionException;
- /**
- * Encrypts the provided plaintext bytes using the cipher transformation
- * specified by the property Encryptor.CipherTransformation
- * as defined in the ESAPI.properties file and the
- * specified secret key.
- *
- * This method is similar to {@link #encrypt(PlainText)} except that it
- * permits a specific {@code SecretKey} to be used for encryption.
- *
- * @param key The {@code SecretKey} to use for encrypting the plaintext.
- * @param plaintext The byte stream to be encrypted. Note if a Java
- * {@code String} is to be encrypted, it should be converted
- * using {@code "some string".getBytes("UTF-8")}.
- * @return the {@code CipherText} object from which the raw ciphertext, the
- * IV, the cipher transformation, and many other aspects about
- * the encryption detail may be extracted.
- * @throws EncryptionException Thrown if something should go wrong such as
- * the JCE provider cannot be found, the cipher algorithm,
- * cipher mode, or padding scheme not being supported, specifying
- * an unsupported key size, specifying an IV of incorrect length,
- * etc.
- * @see #encrypt(PlainText)
- * @since 2.0
- */
- CipherText encrypt(SecretKey key, PlainText plaintext)
- throws EncryptionException;
+ /**
+ * Encrypts the provided plaintext bytes using the cipher transformation
+ * specified by the property Encryptor.CipherTransformation
+ * as defined in the ESAPI.properties file and the
+ * specified secret key.
+ *
+ * This method is similar to {@link #encrypt(PlainText)} except that it
+ * permits a specific {@code SecretKey} to be used for encryption.
+ *
+ * @param key The {@code SecretKey} to use for encrypting the plaintext.
+ * @param plaintext The byte stream to be encrypted. Note if a Java
+ * {@code String} is to be encrypted, it should be converted
+ * using {@code "some string".getBytes("UTF-8")}.
+ * @return the {@code CipherText} object from which the raw ciphertext, the
+ * IV, the cipher transformation, and many other aspects about
+ * the encryption detail may be extracted.
+ * @throws EncryptionException Thrown if something should go wrong such as
+ * the JCE provider cannot be found, the cipher algorithm,
+ * cipher mode, or padding scheme not being supported, specifying
+ * an unsupported key size, specifying an IV of incorrect length,
+ * etc.
+ * @see #encrypt(PlainText)
+ * @since 2.0
+ */
+ CipherText encrypt(SecretKey key, PlainText plaintext)
+ throws EncryptionException;
- /**
- * Decrypts the provided {@link CipherText} using the information from it
- * and the master encryption key as specified by the property
- * {@code Encryptor.MasterKey} as defined in the {@code ESAPI.properties}
- * file.
- *
- * @param ciphertext The {@code CipherText} object to be decrypted.
- * @return The {@code PlainText} object resulting from decrypting the specified
- * ciphertext. Note that it it is desired to convert the returned
- * plaintext byte array to a Java String is should be done using
- * {@code new String(byte[], "UTF-8");} rather than simply using
- * {@code new String(byte[]);} which uses native encoding and may
- * not be portable across hardware and/or OS platforms.
- * @throws EncryptionException Thrown if something should go wrong such as
- * the JCE provider cannot be found, the cipher algorithm,
- * cipher mode, or padding scheme not being supported, specifying
- * an unsupported key size, or incorrect encryption key was
- * specified or a {@code PaddingException} occurs.
- * @see #decrypt(SecretKey, CipherText)
- */
- PlainText decrypt(CipherText ciphertext) throws EncryptionException;
-
- /**
- * Decrypts the provided {@link CipherText} using the information from it
- * and the specified secret key.
- *
- * This decrypt method is similar to {@link #decrypt(CipherText)} except that
- * it allows decrypting with a secret key other than the master secret key.
- *
- * @param key The {@code SecretKey} to use for encrypting the plaintext.
- * @param ciphertext The {@code CipherText} object to be decrypted.
- * @return The {@code PlainText} object resulting from decrypting the specified
- * ciphertext. Note that it it is desired to convert the returned
- * plaintext byte array to a Java String is should be done using
- * {@code new String(byte[], "UTF-8");} rather than simply using
- * {@code new String(byte[]);} which uses native encoding and may
- * not be portable across hardware and/or OS platforms.
- * @throws EncryptionException Thrown if something should go wrong such as
- * the JCE provider cannot be found, the cipher algorithm,
- * cipher mode, or padding scheme not being supported, specifying
- * an unsupported key size, or incorrect encryption key was
- * specified or a {@code PaddingException} occurs.
- * @see #decrypt(CipherText)
- */
- PlainText decrypt(SecretKey key, CipherText ciphertext) throws EncryptionException;
-
- /**
- * Create a digital signature for the provided data and return it in a
- * string.
- *
- * Limitations: A new public/private key pair used for ESAPI 2.0 digital
- * signatures with this method and {@link #verifySignature(String, String)}
- * are dynamically created when the default reference implementation class,
- * {@link org.owasp.esapi.reference.crypto.JavaEncryptor} is first created.
- * Because this key pair is not persisted nor is the public key shared,
- * this method and the corresponding {@link #verifySignature(String, String)}
- * can not be used with expected results across JVM instances. This limitation
- * will be addressed in ESAPI 2.1.
- *
- *
- * @param data
- * the data to sign
- *
- * @return
- * the digital signature stored as a String
- *
- * @throws EncryptionException
- * if the specified signature algorithm cannot be found
- */
- String sign(String data) throws EncryptionException;
+ /**
+ * Decrypts the provided {@link CipherText} using the information from it
+ * and the master encryption key as specified by the property
+ * {@code Encryptor.MasterKey} as defined in the {@code ESAPI.properties}
+ * file.
+ *
+ * @param ciphertext The {@code CipherText} object to be decrypted.
+ * @return The {@code PlainText} object resulting from decrypting the specified
+ * ciphertext. Note that it it is desired to convert the returned
+ * plaintext byte array to a Java String is should be done using
+ * {@code new String(byte[], "UTF-8");} rather than simply using
+ * {@code new String(byte[]);} which uses native encoding and may
+ * not be portable across hardware and/or OS platforms.
+ * @throws EncryptionException Thrown if something should go wrong such as
+ * the JCE provider cannot be found, the cipher algorithm,
+ * cipher mode, or padding scheme not being supported, specifying
+ * an unsupported key size, or incorrect encryption key was
+ * specified or a {@code PaddingException} occurs.
+ * @see #decrypt(SecretKey, CipherText)
+ */
+ PlainText decrypt(CipherText ciphertext) throws EncryptionException;
+
+ /**
+ * Decrypts the provided {@link CipherText} using the information from it
+ * and the specified secret key.
+ *
+ * This decrypt method is similar to {@link #decrypt(CipherText)} except that
+ * it allows decrypting with a secret key other than the master secret key.
+ *
+ * @param key The {@code SecretKey} to use for encrypting the plaintext.
+ * @param ciphertext The {@code CipherText} object to be decrypted.
+ * @return The {@code PlainText} object resulting from decrypting the specified
+ * ciphertext. Note that it it is desired to convert the returned
+ * plaintext byte array to a Java String is should be done using
+ * {@code new String(byte[], "UTF-8");} rather than simply using
+ * {@code new String(byte[]);} which uses native encoding and may
+ * not be portable across hardware and/or OS platforms.
+ * @throws EncryptionException Thrown if something should go wrong such as
+ * the JCE provider cannot be found, the cipher algorithm,
+ * cipher mode, or padding scheme not being supported, specifying
+ * an unsupported key size, or incorrect encryption key was
+ * specified or a {@code PaddingException} occurs.
+ * @see #decrypt(CipherText)
+ */
+ PlainText decrypt(SecretKey key, CipherText ciphertext) throws EncryptionException;
+
+ /**
+ * Create a digital signature for the provided data and return it in a
+ * string.
+ *
+ * Limitations: A new public/private key pair used for ESAPI 2.0 digital
+ * signatures with this method and {@link #verifySignature(String, String)}
+ * are dynamically created when the default reference implementation class,
+ * {@link org.owasp.esapi.reference.crypto.JavaEncryptor} is first created.
+ * Because this key pair is not persisted nor is the public key shared,
+ * this method and the corresponding {@link #verifySignature(String, String)}
+ * can not be used with expected results across JVM instances. This limitation
+ * will be addressed in ESAPI 2.1.
+ *
+ *
+ * @param data
+ * the data to sign
+ *
+ * @return
+ * the digital signature stored as a String
+ *
+ * @throws EncryptionException
+ * if the specified signature algorithm cannot be found
+ */
+ String sign(String data) throws EncryptionException;
- /**
- * Verifies a digital signature (created with the sign method) and returns
- * the boolean result.
+ /**
+ * Verifies a digital signature (created with the sign method) and returns
+ * the boolean result.
*
* Limitations: A new public/private key pair used for ESAPI 2.0 digital
* signatures with this method and {@link #sign(String)}
@@ -238,79 +238,79 @@ CipherText encrypt(SecretKey key, PlainText plaintext)
* can not be used with expected results across JVM instances. This limitation
* will be addressed in ESAPI 2.1.
*
- * @param signature
- * the signature to verify against 'data'
- * @param data
- * the data to verify against 'signature'
- *
- * @return
- * true, if the signature is verified, false otherwise
- */
- boolean verifySignature(String signature, String data);
+ * @param signature
+ * the signature to verify against 'data'
+ * @param data
+ * the data to verify against 'signature'
+ *
+ * @return
+ * true, if the signature is verified, false otherwise
+ */
+ boolean verifySignature(String signature, String data);
- /**
- * Creates a seal that binds a set of data and includes an expiration timestamp.
- *
- * @param data
- * the data to seal
- * @param timestamp
- * the absolute expiration date of the data, expressed as seconds since the epoch
- *
- * @return
- * the seal
- *
+ /**
+ * Creates a seal that binds a set of data and includes an expiration timestamp.
+ *
+ * @param data
+ * the data to seal
+ * @param timestamp
+ * the absolute expiration date of the data, expressed as seconds since the epoch
+ *
+ * @return
+ * the seal
+ *
* @throws IntegrityException
- */
- String seal(String data, long timestamp) throws IntegrityException;
+ */
+ String seal(String data, long timestamp) throws IntegrityException;
- /**
- * Unseals data (created with the seal method) and throws an exception
- * describing any of the various problems that could exist with a seal, such
- * as an invalid seal format, expired timestamp, or decryption error.
- *
- * @param seal
- * the sealed data
- *
- * @return
- * the original (unsealed) data
- *
- * @throws EncryptionException
- * if the unsealed data cannot be retrieved for any reason
- */
- String unseal( String seal ) throws EncryptionException;
-
- /**
- * Verifies a seal (created with the seal method) and throws an exception
- * describing any of the various problems that could exist with a seal, such
- * as an invalid seal format, expired timestamp, or data mismatch.
- *
- * @param seal
- * the seal to verify
- *
- * @return
- * true, if the seal is valid. False otherwise
- */
- boolean verifySeal(String seal);
-
- /**
- * Gets an absolute timestamp representing an offset from the current time to be used by
- * other functions in the library.
- *
- * @param offset
- * the offset to add to the current time
- *
- * @return
- * the absolute timestamp
- */
- long getRelativeTimeStamp( long offset );
-
- /**
- * Gets a timestamp representing the current date and time to be used by
- * other functions in the library.
- *
- * @return
- * a timestamp representing the current time
- */
- long getTimeStamp();
+ /**
+ * Unseals data (created with the seal method) and throws an exception
+ * describing any of the various problems that could exist with a seal, such
+ * as an invalid seal format, expired timestamp, or decryption error.
+ *
+ * @param seal
+ * the sealed data
+ *
+ * @return
+ * the original (unsealed) data
+ *
+ * @throws EncryptionException
+ * if the unsealed data cannot be retrieved for any reason
+ */
+ String unseal( String seal ) throws EncryptionException;
+
+ /**
+ * Verifies a seal (created with the seal method) and throws an exception
+ * describing any of the various problems that could exist with a seal, such
+ * as an invalid seal format, expired timestamp, or data mismatch.
+ *
+ * @param seal
+ * the seal to verify
+ *
+ * @return
+ * true, if the seal is valid. False otherwise
+ */
+ boolean verifySeal(String seal);
+
+ /**
+ * Gets an absolute timestamp representing an offset from the current time to be used by
+ * other functions in the library.
+ *
+ * @param offset
+ * the offset to add to the current time
+ *
+ * @return
+ * the absolute timestamp
+ */
+ long getRelativeTimeStamp( long offset );
+
+ /**
+ * Gets a timestamp representing the current date and time to be used by
+ * other functions in the library.
+ *
+ * @return
+ * a timestamp representing the current time
+ */
+ long getTimeStamp();
}
\ No newline at end of file
diff --git a/src/main/java/org/owasp/esapi/ExecuteResult.java b/src/main/java/org/owasp/esapi/ExecuteResult.java
index e9835e300..33bf0b13c 100644
--- a/src/main/java/org/owasp/esapi/ExecuteResult.java
+++ b/src/main/java/org/owasp/esapi/ExecuteResult.java
@@ -26,50 +26,50 @@
*/
public class ExecuteResult {
- private final int exitValue;
- private final String output;
- private final String errors;
+ private final int exitValue;
+ private final String output;
+ private final String errors;
- /**
- * Constructs an ExecuteResult from the given values.
- *
- * @param exitValue
- * the code from java.lang.Process.exitValue()
- * @param output
- * the contents read from java.lang.Process.getInputStream()
- * @param errors
- * the contents read from java.lang.Process.getErrorStream()
- */
- public ExecuteResult(int exitValue, String output, String errors) {
- this.exitValue = exitValue;
- this.output = output;
- this.errors = errors;
- }
+ /**
+ * Constructs an ExecuteResult from the given values.
+ *
+ * @param exitValue
+ * the code from java.lang.Process.exitValue()
+ * @param output
+ * the contents read from java.lang.Process.getInputStream()
+ * @param errors
+ * the contents read from java.lang.Process.getErrorStream()
+ */
+ public ExecuteResult(int exitValue, String output, String errors) {
+ this.exitValue = exitValue;
+ this.output = output;
+ this.errors = errors;
+ }
- /**
- * @return the code from java.lang.Process.exitValue()
- */
- public int getExitValue() {
- return exitValue;
- }
+ /**
+ * @return the code from java.lang.Process.exitValue()
+ */
+ public int getExitValue() {
+ return exitValue;
+ }
- /**
- * @return the contents read from java.lang.Process.getInputStream()
- */
- public String getOutput() {
- return output;
- }
+ /**
+ * @return the contents read from java.lang.Process.getInputStream()
+ */
+ public String getOutput() {
+ return output;
+ }
- /**
- * @return the contents read from java.lang.Process.getErrorStream()
- */
- public String getErrors() {
- return errors;
- }
-
- @Override
- public String toString() {
- return "ExecuteResult[exitValue="+exitValue+",output="+output+",errors="+errors+"]";
- }
+ /**
+ * @return the contents read from java.lang.Process.getErrorStream()
+ */
+ public String getErrors() {
+ return errors;
+ }
+
+ @Override
+ public String toString() {
+ return "ExecuteResult[exitValue="+exitValue+",output="+output+",errors="+errors+"]";
+ }
}
diff --git a/src/main/java/org/owasp/esapi/Executor.java b/src/main/java/org/owasp/esapi/Executor.java
index b475da90d..7ad5ba4df 100644
--- a/src/main/java/org/owasp/esapi/Executor.java
+++ b/src/main/java/org/owasp/esapi/Executor.java
@@ -41,38 +41,38 @@
*/
public interface Executor {
- /**
- * Invokes the specified executable with default workdir and codec and not logging parameters.
- *
- * @param executable
- * the command to execute
- * @param params
- * the parameters of the command being executed
- */
- ExecuteResult executeSystemCommand(File executable, List params) throws ExecutorException;
+ /**
+ * Invokes the specified executable with default workdir and codec and not logging parameters.
+ *
+ * @param executable
+ * the command to execute
+ * @param params
+ * the parameters of the command being executed
+ */
+ ExecuteResult executeSystemCommand(File executable, List params) throws ExecutorException;
- /**
- * Executes a system command after checking that the executable exists and
- * escaping all the parameters to ensure that injection is impossible.
- * Implementations must change to the specified working
- * directory before invoking the command.
- *
- * @param executable
- * the command to execute
- * @param params
- * the parameters of the command being executed
- * @param workdir
- * the working directory
- * @param codec
- * the codec to use to encode for the particular OS in use
- * @param logParams
- * use false if any parameters contains sensitive or confidential information
- *
- * @return the output of the command being run
- *
- * @throws ExecutorException
- * the service exception
- */
- ExecuteResult executeSystemCommand(File executable, List params, File workdir, Codec codec, boolean logParams, boolean redirectErrorStream) throws ExecutorException;
+ /**
+ * Executes a system command after checking that the executable exists and
+ * escaping all the parameters to ensure that injection is impossible.
+ * Implementations must change to the specified working
+ * directory before invoking the command.
+ *
+ * @param executable
+ * the command to execute
+ * @param params
+ * the parameters of the command being executed
+ * @param workdir
+ * the working directory
+ * @param codec
+ * the codec to use to encode for the particular OS in use
+ * @param logParams
+ * use false if any parameters contains sensitive or confidential information
+ *
+ * @return the output of the command being run
+ *
+ * @throws ExecutorException
+ * the service exception
+ */
+ ExecuteResult executeSystemCommand(File executable, List params, File workdir, Codec codec, boolean logParams, boolean redirectErrorStream) throws ExecutorException;
}
diff --git a/src/main/java/org/owasp/esapi/HTTPUtilities.java b/src/main/java/org/owasp/esapi/HTTPUtilities.java
index c1b83f5c4..a4091eda7 100644
--- a/src/main/java/org/owasp/esapi/HTTPUtilities.java
+++ b/src/main/java/org/owasp/esapi/HTTPUtilities.java
@@ -36,27 +36,27 @@
*/
public interface HTTPUtilities
{
- // All implied static final as this is an interface
+ // All implied static final as this is an interface
String REMEMBER_TOKEN_COOKIE_NAME = "rtoken";
int MAX_COOKIE_LEN = 4096; // From RFC 2109
- int MAX_COOKIE_PAIRS = 20; // From RFC 2109
- String CSRF_TOKEN_NAME = "ctoken";
- String ESAPI_STATE = "estate";
+ int MAX_COOKIE_PAIRS = 20; // From RFC 2109
+ String CSRF_TOKEN_NAME = "ctoken";
+ String ESAPI_STATE = "estate";
- int PARAMETER = 0;
- int HEADER = 1;
- int COOKIE = 2;
+ int PARAMETER = 0;
+ int HEADER = 1;
+ int COOKIE = 2;
- /**
+ /**
* Calls addCookie with the *current* request.
*
* @param cookie The cookie to add
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
*/
void addCookie(Cookie cookie);
- /**
+ /**
* Add a cookie to the response after ensuring that there are no encoded or
* illegal characters in the name and name and value. This method also sets
* the secure and HttpOnly flags on the cookie.
@@ -66,7 +66,7 @@ public interface HTTPUtilities
*/
void addCookie(HttpServletResponse response, Cookie cookie);
- /**
+ /**
* Adds the current user's CSRF token (see User.getCSRFToken()) to the URL for purposes of preventing CSRF attacks.
* This method should be used on all URLs to be put into all links and forms the application generates.
*
@@ -78,7 +78,7 @@ public interface HTTPUtilities
/**
* Calls addHeader with the *current* request.
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
*/
void addHeader(String name, String value);
@@ -95,49 +95,49 @@ public interface HTTPUtilities
*/
void addHeader(HttpServletResponse response, String name, String value);
- /**
+ /**
* Calls assertSecureRequest with the *current* request.
- * @see HTTPUtilities#assertSecureRequest(HttpServletRequest)
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
- */
- void assertSecureRequest() throws AccessControlException;
+ * @see HTTPUtilities#assertSecureRequest(HttpServletRequest)
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ */
+ void assertSecureRequest() throws AccessControlException;
- /**
+ /**
* Calls assertSecureChannel with the *current* request.
- * @see HTTPUtilities#assertSecureChannel(HttpServletRequest)
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
- */
- void assertSecureChannel() throws AccessControlException;
+ * @see HTTPUtilities#assertSecureChannel(HttpServletRequest)
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ */
+ void assertSecureChannel() throws AccessControlException;
- /**
- * Ensures that the request uses both SSL and POST to protect any sensitive parameters
- * in the querystring from being sniffed, logged, bookmarked, included in referer header, etc...
- * This method should be called for any request that contains sensitive data from a web form.
+ /**
+ * Ensures that the request uses both SSL and POST to protect any sensitive parameters
+ * in the querystring from being sniffed, logged, bookmarked, included in referer header, etc...
+ * This method should be called for any request that contains sensitive data from a web form.
*
* @param request
* @throws AccessControlException if security constraints are not met
- */
+ */
void assertSecureRequest(HttpServletRequest request) throws AccessControlException;
- /**
- * Ensures the use of SSL to protect any sensitive parameters in the request and
- * any sensitive data in the response. This method should be called for any request
- * that contains sensitive data from a web form or will result in sensitive data in the
- * response page.
+ /**
+ * Ensures the use of SSL to protect any sensitive parameters in the request and
+ * any sensitive data in the response. This method should be called for any request
+ * that contains sensitive data from a web form or will result in sensitive data in the
+ * response page.
*
* @param request
* @throws AccessControlException if security constraints are not met
- */
+ */
void assertSecureChannel(HttpServletRequest request) throws AccessControlException;
- /**
+ /**
* Calls changeSessionIdentifier with the *current* request.
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
*/
- HttpSession changeSessionIdentifier() throws AuthenticationException;
+ HttpSession changeSessionIdentifier() throws AuthenticationException;
- /**
+ /**
* Invalidate the existing session after copying all of its contents to a newly created session with a new session id.
* Note that this is different from logging out and creating a new session identifier that does not contain the
* existing session contents. Care should be taken to use this only when the existing session does not contain
@@ -150,34 +150,34 @@ public interface HTTPUtilities
HttpSession changeSessionIdentifier(HttpServletRequest request) throws AuthenticationException;
/**
- * Clears the current HttpRequest and HttpResponse associated with the current thread.
+ * Clears the current HttpRequest and HttpResponse associated with the current thread.
*
- * @see ESAPI#clearCurrent()
- */
+ * @see ESAPI#clearCurrent()
+ */
void clearCurrent();
/**
- * Decrypts an encrypted hidden field value and returns the cleartext. If the field does not decrypt properly,
- * an IntrusionException is thrown to indicate tampering.
+ * Decrypts an encrypted hidden field value and returns the cleartext. If the field does not decrypt properly,
+ * an IntrusionException is thrown to indicate tampering.
*
- * @param encrypted hidden field value to decrypt
- * @return decrypted hidden field value stored as a String
- */
- String decryptHiddenField(String encrypted);
+ * @param encrypted hidden field value to decrypt
+ * @return decrypted hidden field value stored as a String
+ */
+ String decryptHiddenField(String encrypted);
/**
- * Takes an encrypted querystring and returns a Map containing the original parameters.
+ * Takes an encrypted querystring and returns a Map containing the original parameters.
*
- * @param encrypted the encrypted querystring to decrypt
- * @return a Map object containing the decrypted querystring
- * @throws EncryptionException
- */
+ * @param encrypted the encrypted querystring to decrypt
+ * @return a Map object containing the decrypted querystring
+ * @throws EncryptionException
+ */
Map decryptQueryString(String encrypted) throws EncryptionException;
/**
* Calls decryptStateFromCookie with the *current* request.
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
*/
Map decryptStateFromCookie() throws EncryptionException;
@@ -186,7 +186,7 @@ public interface HTTPUtilities
*
* @param request
* @return a map containing the decrypted cookie state value
- * @throws EncryptionException
+ * @throws EncryptionException
*/
Map decryptStateFromCookie(HttpServletRequest request) throws EncryptionException;
@@ -197,22 +197,22 @@ public interface HTTPUtilities
* @return the encrypted value of the hidden field
* @throws EncryptionException
*/
- String encryptHiddenField(String value) throws EncryptionException;
+ String encryptHiddenField(String value) throws EncryptionException;
- /**
- * Takes a querystring (everything after the question mark in the URL) and returns an encrypted string containing the parameters.
+ /**
+ * Takes a querystring (everything after the question mark in the URL) and returns an encrypted string containing the parameters.
*
- * @param query the querystring to encrypt
- * @return encrypted querystring stored as a String
- * @throws EncryptionException
- */
- String encryptQueryString(String query) throws EncryptionException;
+ * @param query the querystring to encrypt
+ * @return encrypted querystring stored as a String
+ * @throws EncryptionException
+ */
+ String encryptQueryString(String query) throws EncryptionException;
- /**
- * Calls encryptStateInCookie with the *current* response.
+ /**
+ * Calls encryptStateInCookie with the *current* response.
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
- */
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ */
void encryptStateInCookie(Map cleartext) throws EncryptionException;
/**
@@ -229,28 +229,28 @@ public interface HTTPUtilities
void encryptStateInCookie(HttpServletResponse response, Map cleartext) throws EncryptionException;
/**
- * Calls getCookie with the *current* response.
- *
- * @param name The cookie to get
+ * Calls getCookie with the *current* response.
+ *
+ * @param name The cookie to get
* @return the requested cookie value
* @throws ValidationException
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
- */
- String getCookie(String name) throws ValidationException;
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ */
+ String getCookie(String name) throws ValidationException;
- /**
+ /**
* A safer replacement for getCookies() in HttpServletRequest that returns the canonicalized
* value of the named cookie after "global" validation against the
* general type defined in ESAPI.properties. This should not be considered a replacement for
* more specific validation.
*
* @param request
- * @param name The cookie to get
+ * @param name The cookie to get
* @return the requested cookie value
* @throws ValidationException
*/
- String getCookie(HttpServletRequest request, String name) throws ValidationException;
+ String getCookie(HttpServletRequest request, String name) throws ValidationException;
/**
* Returns the current user's CSRF token. If there is no current user then return null.
@@ -259,44 +259,44 @@ public interface HTTPUtilities
*/
String getCSRFToken();
- /**
+ /**
* Retrieves the current HttpServletRequest
*
* @return the current request
*/
HttpServletRequest getCurrentRequest();
- /**
+ /**
* Retrieves the current HttpServletResponse
*
* @return the current response
*/
HttpServletResponse getCurrentResponse();
- /**
- * Calls getFileUploads with the *current* request, default upload directory, and default allowed file extensions
+ /**
+ * Calls getFileUploads with the *current* request, default upload directory, and default allowed file extensions
*
* @return List of new File objects from upload
* @throws ValidationException if the file fails validation
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
- */
- List getFileUploads() throws ValidationException;
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ */
+ List getFileUploads() throws ValidationException;
/**
- * Call getFileUploads with the specified request, default upload directory, and default allowed file extensions
+ * Call getFileUploads with the specified request, default upload directory, and default allowed file extensions
*
* @return List of new File objects from upload
* @throws ValidationException if the file fails validation
- */
- List getFileUploads(HttpServletRequest request) throws ValidationException;
+ */
+ List getFileUploads(HttpServletRequest request) throws ValidationException;
/**
- * Call getFileUploads with the specified request, specified upload directory, and default allowed file extensions
+ * Call getFileUploads with the specified request, specified upload directory, and default allowed file extensions
*
* @return List of new File objects from upload
* @throws ValidationException if the file fails validation
- */
+ */
List getFileUploads(HttpServletRequest request, File finalDir) throws ValidationException;
@@ -306,7 +306,7 @@ public interface HTTPUtilities
* possibly virus checking, and path and name checks. Refer to the file checking methods in Validator for more
* information.
*
- * This method uses {@link HTTPUtilities#getCurrentRequest()} to obtain the {@link HttpServletRequest} object
+ * This method uses {@link HTTPUtilities#getCurrentRequest()} to obtain the {@link HttpServletRequest} object
*
* @param request
* @return List of new File objects from upload
@@ -315,12 +315,12 @@ public interface HTTPUtilities
List getFileUploads(HttpServletRequest request, File destinationDir, List allowedExtensions) throws ValidationException;
- /**
- * Calls getHeader with the *current* request.
+ /**
+ * Calls getHeader with the *current* request.
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
- */
- String getHeader(String name) throws ValidationException;
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ */
+ String getHeader(String name) throws ValidationException;
/**
* A safer replacement for getHeader() in HttpServletRequest that returns the canonicalized
@@ -332,14 +332,14 @@ public interface HTTPUtilities
* @param name
* @return the requested header value
*/
- String getHeader(HttpServletRequest request, String name) throws ValidationException;
+ String getHeader(HttpServletRequest request, String name) throws ValidationException;
- /**
- * Calls getParameter with the *current* request.
+ /**
+ * Calls getParameter with the *current* request.
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
- */
- String getParameter(String name) throws ValidationException;
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ */
+ String getParameter(String name) throws ValidationException;
/**
* A safer replacement for getParameter() in HttpServletRequest that returns the canonicalized
@@ -353,12 +353,12 @@ public interface HTTPUtilities
*/
String getParameter(HttpServletRequest request, String name) throws ValidationException;
- /**
- * Calls killAllCookies with the *current* request and response.
+ /**
+ * Calls killAllCookies with the *current* request and response.
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
- */
- void killAllCookies();
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ */
+ void killAllCookies();
/**
* Kill all cookies received in the last request from the browser. Note that new cookies set by the application in
@@ -369,12 +369,12 @@ public interface HTTPUtilities
*/
void killAllCookies(HttpServletRequest request, HttpServletResponse response);
- /**
- * Calls killCookie with the *current* request and response.
+ /**
+ * Calls killCookie with the *current* request and response.
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
- */
- void killCookie(String name);
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ */
+ void killCookie(String name);
/**
* Kills the specified cookie by setting a new cookie that expires immediately. Note that this
@@ -386,12 +386,12 @@ public interface HTTPUtilities
*/
void killCookie(HttpServletRequest request, HttpServletResponse response, String name);
- /**
- * Calls logHTTPRequest with the *current* request and logger.
+ /**
+ * Calls logHTTPRequest with the *current* request and logger.
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
- */
- void logHTTPRequest();
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ */
+ void logHTTPRequest();
/**
* Format the Source IP address, URL, URL parameters, and all form
@@ -420,11 +420,11 @@ public interface HTTPUtilities
*/
void logHTTPRequest(HttpServletRequest request, Logger logger, List parameterNamesToObfuscate);
- /**
- * Calls sendForward with the *current* request and response.
+ /**
+ * Calls sendForward with the *current* request and response.
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
- */
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ */
void sendForward(String location) throws AccessControlException, ServletException, IOException;
/**
@@ -443,11 +443,11 @@ public interface HTTPUtilities
void sendForward(HttpServletRequest request, HttpServletResponse response, String location) throws AccessControlException, ServletException, IOException;
- /**
- * Calls sendRedirect with the *current* response.
+ /**
+ * Calls sendRedirect with the *current* response.
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
- */
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ */
void sendRedirect(String location) throws AccessControlException, IOException;
@@ -464,25 +464,25 @@ public interface HTTPUtilities
*/
void sendRedirect(HttpServletResponse response, String location) throws AccessControlException, IOException;
- /**
- * Calls setContentType with the *current* request and response.
+ /**
+ * Calls setContentType with the *current* request and response.
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
- */
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ */
void setContentType();
/**
- * Set the content type character encoding header on every HttpServletResponse in order to limit
- * the ways in which the input data can be represented. This prevents
- * malicious users from using encoding and multi-byte escape sequences to
- * bypass input validation routines.
+ * Set the content type character encoding header on every HttpServletResponse in order to limit
+ * the ways in which the input data can be represented. This prevents
+ * malicious users from using encoding and multi-byte escape sequences to
+ * bypass input validation routines.
*
- * Implementations of this method should set the content type header to a safe value for your environment.
+ * Implementations of this method should set the content type header to a safe value for your environment.
* The default is text/html; charset=UTF-8 character encoding, which is the default in early
- * versions of HTML and HTTP. See RFC 2047 (http://ds.internic.net/rfc/rfc2045.txt) for more
- * information about character encoding and MIME.
+ * versions of HTML and HTTP. See RFC 2047 (http://ds.internic.net/rfc/rfc2045.txt) for more
+ * information about character encoding and MIME.
*
- * The DefaultHTTPUtilities reference implementation sets the content type as specified.
+ * The DefaultHTTPUtilities reference implementation sets the content type as specified.
*
* @param response The servlet response to set the content type for.
*/
@@ -498,11 +498,11 @@ public interface HTTPUtilities
void setCurrentHTTP(HttpServletRequest request, HttpServletResponse response);
- /**
- * Calls setHeader with the *current* response.
+ /**
+ * Calls setHeader with the *current* response.
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
- */
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ */
void setHeader(String name, String value);
/**
@@ -518,11 +518,11 @@ public interface HTTPUtilities
void setHeader(HttpServletResponse response, String name, String value);
- /**
- * Calls setNoCacheHeaders with the *current* response.
+ /**
+ * Calls setNoCacheHeaders with the *current* response.
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
- */
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ */
void setNoCacheHeaders();
@@ -556,14 +556,14 @@ public interface HTTPUtilities
*/
void setNoCacheHeaders(HttpServletResponse response);
- /**
- * Calls setNoCacheHeaders with the *current* response.
- *
- * ~DEPRECATED~ Per Kevin Wall, storing passwords with reversible encryption is contrary to *many*
- * company's stated security policies.
+ /**
+ * Calls setNoCacheHeaders with the *current* response.
+ *
+ * ~DEPRECATED~ Per Kevin Wall, storing passwords with reversible encryption is contrary to *many*
+ * company's stated security policies.
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
- */
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ */
@Deprecated
String setRememberToken(String password, int maxAge, String domain, String path);
@@ -574,49 +574,49 @@ public interface HTTPUtilities
/**
- * Set a cookie containing the current User's remember me token for automatic authentication. The use of remember me tokens
- * is generally not recommended, but this method will help do it as safely as possible. The user interface should strongly warn
+ * Set a cookie containing the current User's remember me token for automatic authentication. The use of remember me tokens
+ * is generally not recommended, but this method will help do it as safely as possible. The user interface should strongly warn
* the user that this should only be enabled on computers where no other users will have access.
*
* Implementations should save the user's remember me data in an encrypted cookie and send it to the user.
* Any old remember me cookie should be destroyed first. Setting this cookie should keep the user
- * logged in until the maxAge passes, the password is changed, or the cookie is deleted.
- * If the cookie exists for the current user, it should automatically be used by ESAPI to
+ * logged in until the maxAge passes, the password is changed, or the cookie is deleted.
+ * If the cookie exists for the current user, it should automatically be used by ESAPI to
* log the user in, if the data is valid and not expired.
*
- * The ESAPI reference implementation, DefaultHTTPUtilities.setRememberToken() implements all these suggestions.
+ * The ESAPI reference implementation, DefaultHTTPUtilities.setRememberToken() implements all these suggestions.
*
* The username can be retrieved with: User username = ESAPI.authenticator().getCurrentUser();
*
*~DEPRECATED~ Per Kevin Wall, storing passwords with reversible encryption is contrary to *many*
- * company's stated security policies.
+ * company's stated security policies.
*
* @param request
* @param password the user's password
* @param response
* @param maxAge the length of time that the token should be valid for in relative seconds
- * @param domain the domain to restrict the token to or null
- * @param path the path to restrict the token to or null
- * @return encrypted "Remember Me" token stored as a String
- */
+ * @param domain the domain to restrict the token to or null
+ * @param path the path to restrict the token to or null
+ * @return encrypted "Remember Me" token stored as a String
+ */
@Deprecated
String setRememberToken(HttpServletRequest request, HttpServletResponse response, String password, int maxAge, String domain, String path);
- /**
- * Calls verifyCSRFToken with the *current* request.
+ /**
+ * Calls verifyCSRFToken with the *current* request.
*
- * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
- */
+ * @see HTTPUtilities#setCurrentHTTP(HttpServletRequest, HttpServletResponse)
+ */
void verifyCSRFToken();
/**
* Checks the CSRF token in the URL (see User.getCSRFToken()) against the user's CSRF token and
- * throws an IntrusionException if it is missing.
+ * throws an IntrusionException if it is missing.
*
* @param request
* @throws IntrusionException if CSRF token is missing or incorrect
- */
+ */
void verifyCSRFToken(HttpServletRequest request) throws IntrusionException;
/**
diff --git a/src/main/java/org/owasp/esapi/IntrusionDetector.java b/src/main/java/org/owasp/esapi/IntrusionDetector.java
index 6a14ec3c3..2a1388332 100644
--- a/src/main/java/org/owasp/esapi/IntrusionDetector.java
+++ b/src/main/java/org/owasp/esapi/IntrusionDetector.java
@@ -38,10 +38,10 @@ public interface IntrusionDetector {
* the current user's security exceptions. If the User has reached any security thresholds, the appropriate security action can be taken and logged.
*
* @param exception
- * the exception thrown
+ * the exception thrown
*
* @throws IntrusionException
- * the intrusion exception
+ * the intrusion exception
*/
void addException(Exception exception) throws IntrusionException;
@@ -51,12 +51,12 @@ public interface IntrusionDetector {
* the current user's security event. If the User has reached any security thresholds, the appropriate security action can be taken and logged.
*
* @param eventName
- * the event to add
+ * the event to add
* @param logMessage
- * the message to log with the event
+ * the message to log with the event
*
* @throws IntrusionException
- * the intrusion exception
+ * the intrusion exception
*/
void addEvent(String eventName, String logMessage) throws IntrusionException;
diff --git a/src/main/java/org/owasp/esapi/LogFactory.java b/src/main/java/org/owasp/esapi/LogFactory.java
index e3736986d..edde286c2 100644
--- a/src/main/java/org/owasp/esapi/LogFactory.java
+++ b/src/main/java/org/owasp/esapi/LogFactory.java
@@ -28,33 +28,33 @@
*
*/
public interface LogFactory {
-
- /**
- * Gets the logger associated with the specified module name. The module name is used by the logger to log which
- * module is generating the log events. The implementation of this method should return any preexisting Logger
- * associated with this module name, rather than creating a new Logger.
- *
- * The JavaLogFactory reference implementation meets these requirements.
- *
- * @param moduleName
- * The name of the module requesting the logger.
- * @return
- * The Logger associated with this module.
- */
- Logger getLogger(String moduleName);
-
- /**
- * Gets the logger associated with the specified class. The class is used by the logger to log which
- * class is generating the log events. The implementation of this method should return any preexisting Logger
- * associated with this class name, rather than creating a new Logger.
- *
- * The JavaLogFactory reference implementation meets these requirements.
- *
- * @param clazz
- * The name of the class requesting the logger.
- * @return
- * The Logger associated with this class.
- */
- Logger getLogger(Class clazz);
-
+
+ /**
+ * Gets the logger associated with the specified module name. The module name is used by the logger to log which
+ * module is generating the log events. The implementation of this method should return any preexisting Logger
+ * associated with this module name, rather than creating a new Logger.
+ *
+ * The JavaLogFactory reference implementation meets these requirements.
+ *
+ * @param moduleName
+ * The name of the module requesting the logger.
+ * @return
+ * The Logger associated with this module.
+ */
+ Logger getLogger(String moduleName);
+
+ /**
+ * Gets the logger associated with the specified class. The class is used by the logger to log which
+ * class is generating the log events. The implementation of this method should return any preexisting Logger
+ * associated with this class name, rather than creating a new Logger.
+ *
+ * The JavaLogFactory reference implementation meets these requirements.
+ *
+ * @param clazz
+ * The name of the class requesting the logger.
+ * @return
+ * The Logger associated with this class.
+ */
+ Logger getLogger(Class clazz);
+
}
diff --git a/src/main/java/org/owasp/esapi/Logger.java b/src/main/java/org/owasp/esapi/Logger.java
index 2e3ec3399..0f41e7376 100644
--- a/src/main/java/org/owasp/esapi/Logger.java
+++ b/src/main/java/org/owasp/esapi/Logger.java
@@ -92,89 +92,89 @@
*/
public interface Logger {
- // All implied static final as this is an interface
-
- /**
+ // All implied static final as this is an interface
+
+ /**
* A security type of log event that has succeeded. This is one of 6 predefined
* ESAPI logging events. New events can be added.
*/
- EventType SECURITY_SUCCESS = new EventType( "SECURITY SUCCESS", true);
+ EventType SECURITY_SUCCESS = new EventType( "SECURITY SUCCESS", true);
- /**
+ /**
* A security type of log event that has failed. This is one of 6 predefined
* ESAPI logging events. New events can be added.
*/
- EventType SECURITY_FAILURE = new EventType( "SECURITY FAILURE", false);
+ EventType SECURITY_FAILURE = new EventType( "SECURITY FAILURE", false);
- /**
- * A security type of log event that is associated with an audit trail of some type,
- * but the log event is not specifically something that has either succeeded or failed
- * or that is irrelevant in the case of this logged message.
- */
- // CHECKME: Should the Boolean for this be 'null' or 'true'? See EVENT_UNSPECIFIED.
- EventType SECURITY_AUDIT = new EventType( "SECURITY AUDIT", null);
+ /**
+ * A security type of log event that is associated with an audit trail of some type,
+ * but the log event is not specifically something that has either succeeded or failed
+ * or that is irrelevant in the case of this logged message.
+ */
+ // CHECKME: Should the Boolean for this be 'null' or 'true'? See EVENT_UNSPECIFIED.
+ EventType SECURITY_AUDIT = new EventType( "SECURITY AUDIT", null);
- /**
+ /**
* A non-security type of log event that has succeeded. This is one of 6 predefined
* ESAPI logging events. New events can be added.
*/
- EventType EVENT_SUCCESS = new EventType( "EVENT SUCCESS", true);
-
- /**
+ EventType EVENT_SUCCESS = new EventType( "EVENT SUCCESS", true);
+
+ /**
* A non-security type of log event that has failed. This is one of 6 predefined
* ESAPI logging events. New events can be added.
*/
- EventType EVENT_FAILURE = new EventType( "EVENT FAILURE", false);
+ EventType EVENT_FAILURE = new EventType( "EVENT FAILURE", false);
- /**
+ /**
* A non-security type of log event that is unspecified. This is one of 6 predefined
* ESAPI logging events. New events can be added.
*/
- EventType EVENT_UNSPECIFIED = new EventType( "EVENT UNSPECIFIED", null);
+ EventType EVENT_UNSPECIFIED = new EventType( "EVENT UNSPECIFIED", null);
- /**
- * Defines the type of log event that is being generated. The Logger interface defines 6 types of Log events:
- * SECURITY_SUCCESS, SECURITY_FAILURE, EVENT_SUCCESS, EVENT_FAILURE, EVENT_UNSPECIFIED.
+ /**
+ * Defines the type of log event that is being generated. The Logger interface defines 6 types of Log events:
+ * SECURITY_SUCCESS, SECURITY_FAILURE, EVENT_SUCCESS, EVENT_FAILURE, EVENT_UNSPECIFIED.
* Your implementation can extend or change this list if desired.
- */
- class EventType {
-
- private String type;
- private Boolean success = null;
-
- public EventType (String name, Boolean newSuccess) {
- this.type = name;
- this.success = newSuccess;
- }
-
- public Boolean isSuccess() {
- return success;
- }
-
+ */
+ class EventType {
+
+ private String type;
+ private Boolean success = null;
+
+ public EventType (String name, Boolean newSuccess) {
+ this.type = name;
+ this.success = newSuccess;
+ }
+
+ public Boolean isSuccess() {
+ return success;
+ }
+
/**
* Convert the {@code EventType} to a string.
* @return The event type name.
*/
- @Override
+ @Override
public String toString() {
- return this.type;
- }
- }
-
- /*
+ return this.type;
+ }
+ }
+
+ /*
* The Logger interface defines 6 logging levels: FATAL, ERROR, WARNING, INFO, DEBUG, TRACE. It also
* supports ALL, which logs all events, and OFF, which disables all logging.
* Your implementation can extend or change this list if desired.
*/
-
- /** OFF indicates that no messages should be logged. This level is initialized to Integer.MAX_VALUE. */
- int OFF = Integer.MAX_VALUE;
+
+ /** OFF indicates that no messages should be logged. This level is initialized to Integer.MAX_VALUE. */
+ int OFF = Integer.MAX_VALUE;
- /** FATAL indicates that only FATAL messages should be logged. This level is initialized to 1000. */
- int FATAL = 1000;
+ /** FATAL indicates that only FATAL messages should be logged. This level is initialized to 1000. */
+ int FATAL = 1000;
- /** ERROR indicates that ERROR messages and above should be logged.
- * This level is initialized to 800. */
+ /** ERROR indicates that ERROR messages and above should be logged.
+ * This level is initialized to 800. */
int ERROR = 800;
/** WARNING indicates that WARNING messages and above should be logged.
@@ -213,216 +213,216 @@ public String toString() {
*/
int getESAPILevel();
- /**
+ /**
* Log a fatal event if 'fatal' level logging is enabled.
*
* @param type
- * the type of event
+ * the type of event
* @param message
- * the message to log
+ * the message to log
*/
- void fatal(EventType type, String message);
-
- /**
+ void fatal(EventType type, String message);
+
+ /**
* Log a fatal level security event if 'fatal' level logging is enabled
* and also record the stack trace associated with the event.
*
* @param type
- * the type of event
+ * the type of event
* @param message
- * the message to log
+ * the message to log
* @param throwable
- * the exception to be logged
+ * the exception to be logged
*/
- void fatal(EventType type, String message, Throwable throwable);
+ void fatal(EventType type, String message, Throwable throwable);
- /**
- * Allows the caller to determine if messages logged at this level
- * will be discarded, to avoid performing expensive processing.
- *
- * @return true if fatal level messages will be output to the log
- */
- boolean isFatalEnabled();
+ /**
+ * Allows the caller to determine if messages logged at this level
+ * will be discarded, to avoid performing expensive processing.
+ *
+ * @return true if fatal level messages will be output to the log
+ */
+ boolean isFatalEnabled();
- /**
+ /**
* Log an error level security event if 'error' level logging is enabled.
*
* @param type
- * the type of event
+ * the type of event
* @param message
- * the message to log
+ * the message to log
*/
- void error(EventType type, String message);
-
- /**
+ void error(EventType type, String message);
+
+ /**
* Log an error level security event if 'error' level logging is enabled
* and also record the stack trace associated with the event.
*
* @param type
- * the type of event
+ * the type of event
* @param message
- * the message to log
+ * the message to log
* @param throwable
- * the exception to be logged
+ * the exception to be logged
*/
- void error(EventType type, String message, Throwable throwable);
+ void error(EventType type, String message, Throwable throwable);
- /**
- * Allows the caller to determine if messages logged at this level
- * will be discarded, to avoid performing expensive processing.
- *
- * @return true if error level messages will be output to the log
- */
- boolean isErrorEnabled();
+ /**
+ * Allows the caller to determine if messages logged at this level
+ * will be discarded, to avoid performing expensive processing.
+ *
+ * @return true if error level messages will be output to the log
+ */
+ boolean isErrorEnabled();
- /**
+ /**
* Log a warning level security event if 'warning' level logging is enabled.
*
* @param type
- * the type of event
+ * the type of event
* @param message
- * the message to log
+ * the message to log
*/
- void warning(EventType type, String message);
-
- /**
+ void warning(EventType type, String message);
+
+ /**
* Log a warning level security event if 'warning' level logging is enabled
* and also record the stack trace associated with the event.
*
* @param type
- * the type of event
+ * the type of event
* @param message
- * the message to log
+ * the message to log
* @param throwable
- * the exception to be logged
+ * the exception to be logged
*/
- void warning(EventType type, String message, Throwable throwable);
+ void warning(EventType type, String message, Throwable throwable);
- /**
- * Allows the caller to determine if messages logged at this level
- * will be discarded, to avoid performing expensive processing.
- *
- * @return true if warning level messages will be output to the log
- */
- boolean isWarningEnabled();
+ /**
+ * Allows the caller to determine if messages logged at this level
+ * will be discarded, to avoid performing expensive processing.
+ *
+ * @return true if warning level messages will be output to the log
+ */
+ boolean isWarningEnabled();
- /**
+ /**
* Log an info level security event if 'info' level logging is enabled.
*
* @param type
- * the type of event
+ * the type of event
* @param message
- * the message to log
+ * the message to log
*/
- void info(EventType type, String message);
-
- /**
+ void info(EventType type, String message);
+
+ /**
* Log an info level security event if 'info' level logging is enabled
* and also record the stack trace associated with the event.
*
* @param type
- * the type of event
+ * the type of event
* @param message
- * the message to log
+ * the message to log
* @param throwable
- * the exception to be logged
+ * the exception to be logged
*/
- void info(EventType type, String message, Throwable throwable);
+ void info(EventType type, String message, Throwable throwable);
- /**
- * Allows the caller to determine if messages logged at this level
- * will be discarded, to avoid performing expensive processing.
- *
- * @return true if info level messages will be output to the log
- */
- boolean isInfoEnabled();
+ /**
+ * Allows the caller to determine if messages logged at this level
+ * will be discarded, to avoid performing expensive processing.
+ *
+ * @return true if info level messages will be output to the log
+ */
+ boolean isInfoEnabled();
- /**
+ /**
* Log a debug level security event if 'debug' level logging is enabled.
*
* @param type
- * the type of event
+ * the type of event
* @param message
- * the message to log
+ * the message to log
*/
- void debug(EventType type, String message);
-
- /**
+ void debug(EventType type, String message);
+
+ /**
* Log a debug level security event if 'debug' level logging is enabled
* and also record the stack trace associated with the event.
*
* @param type
- * the type of event
+ * the type of event
* @param message
- * the message to log
+ * the message to log
* @param throwable
- * the exception to be logged
+ * the exception to be logged
*/
- void debug(EventType type, String message, Throwable throwable);
+ void debug(EventType type, String message, Throwable throwable);
- /**
- * Allows the caller to determine if messages logged at this level
- * will be discarded, to avoid performing expensive processing.
- *
- * @return true if debug level messages will be output to the log
- */
- boolean isDebugEnabled();
+ /**
+ * Allows the caller to determine if messages logged at this level
+ * will be discarded, to avoid performing expensive processing.
+ *
+ * @return true if debug level messages will be output to the log
+ */
+ boolean isDebugEnabled();
- /**
+ /**
* Log a trace level security event if 'trace' level logging is enabled.
*
* @param type
- * the type of event
+ * the type of event
* @param message
- * the message to log
+ * the message to log
*/
- void trace(EventType type, String message);
-
- /**
+ void trace(EventType type, String message);
+
+ /**
* Log a trace level security event if 'trace' level logging is enabled
* and also record the stack trace associated with the event.
*
* @param type
- * the type of event
+ * the type of event
* @param message
- * the message to log
+ * the message to log
* @param throwable
- * the exception to be logged
+ * the exception to be logged
*/
- void trace(EventType type, String message, Throwable throwable);
+ void trace(EventType type, String message, Throwable throwable);
- /**
- * Allows the caller to determine if messages logged at this level
- * will be discarded, to avoid performing expensive processing.
- *
- * @return true if trace level messages will be output to the log
- */
- boolean isTraceEnabled();
+ /**
+ * Allows the caller to determine if messages logged at this level
+ * will be discarded, to avoid performing expensive processing.
+ *
+ * @return true if trace level messages will be output to the log
+ */
+ boolean isTraceEnabled();
- /**
+ /**
* Log an event regardless of what logging level is enabled.
*
* Note that logging will not occur if the underlying logging implementation has logging disabled.
*
* @param type
- * the type of event
+ * the type of event
* @param message
- * the message to log
+ * the message to log
*/
- void always(EventType type, String message);
-
- /**
+ void always(EventType type, String message);
+
+ /**
* Log an event regardless of what logging level is enabled
* and also record the stack trace associated with the event.
*
* Note that logging will not occur if the underlying logging implementation has logging disabled.
*
* @param type
- * the type of event
+ * the type of event
* @param message
- * the message to log
+ * the message to log
* @param throwable
- * the exception to be logged
+ * the exception to be logged
*/
- void always(EventType type, String message, Throwable throwable);
+ void always(EventType type, String message, Throwable throwable);
}
diff --git a/src/main/java/org/owasp/esapi/PreparedString.java b/src/main/java/org/owasp/esapi/PreparedString.java
index ba26087f6..d0695e4a5 100644
--- a/src/main/java/org/owasp/esapi/PreparedString.java
+++ b/src/main/java/org/owasp/esapi/PreparedString.java
@@ -38,100 +38,100 @@
* @since June 1, 2007
*/
public class PreparedString {
- char parameterCharacter = '?';
- Codec codec = null;
- String[] parameters = null;
- ArrayList parts = new ArrayList();
- private final static char[] IMMUNE = {};
+ char parameterCharacter = '?';
+ Codec codec = null;
+ String[] parameters = null;
+ ArrayList parts = new ArrayList();
+ private final static char[] IMMUNE = {};
- /**
- * Create a PreparedString with the supplied template and Codec. The template should use the
- * default parameter placeholder character (?) in the place where actual parameters are to be inserted.
- * The supplied Codec will be used to escape characters in calls to set, unless a specific Codec is
- * provided to override it.
- * @param template
- * @param codec
- */
- public PreparedString( String template, Codec codec ) {
- this.codec = codec;
- split( template, parameterCharacter );
- }
+ /**
+ * Create a PreparedString with the supplied template and Codec. The template should use the
+ * default parameter placeholder character (?) in the place where actual parameters are to be inserted.
+ * The supplied Codec will be used to escape characters in calls to set, unless a specific Codec is
+ * provided to override it.
+ * @param template
+ * @param codec
+ */
+ public PreparedString( String template, Codec codec ) {
+ this.codec = codec;
+ split( template, parameterCharacter );
+ }
- /**
- * Create a PreparedString with the supplied template, parameter placeholder character, and Codec. The parameter character
- * can be any character, but should not be one that will be used in the template. The parameter character can safely
- * be used in a parameter passed into the set methods.
- * @param template
- * @param parameterCharacter
- * @param codec
- */
- public PreparedString( String template, char parameterCharacter, Codec codec ) {
- this.codec = codec;
- this.parameterCharacter = parameterCharacter;
- split( template, parameterCharacter );
- }
+ /**
+ * Create a PreparedString with the supplied template, parameter placeholder character, and Codec. The parameter character
+ * can be any character, but should not be one that will be used in the template. The parameter character can safely
+ * be used in a parameter passed into the set methods.
+ * @param template
+ * @param parameterCharacter
+ * @param codec
+ */
+ public PreparedString( String template, char parameterCharacter, Codec codec ) {
+ this.codec = codec;
+ this.parameterCharacter = parameterCharacter;
+ split( template, parameterCharacter );
+ }
- /**
- * Split a string with a particular character.
- * @param str
- * @param c
- */
- private void split( String str, char c ) {
- int index = 0;
- int pcount = 0;
- for ( int i = 0; i < str.length(); i++ ) {
- if ( str.charAt(i) == c ) {
- pcount++;
- parts.add( str.substring(index,i) );
- index = i + 1;
- }
- }
- parts.add( str.substring(index) );
- parameters = new String[pcount];
- }
-
- /**
- * Set the parameter at index with supplied value using the default Codec to escape.
- * @param index
- * @param value
- */
- public void set( int index, String value ) {
- if ( index < 1 || index > parameters.length ) {
- throw new IllegalArgumentException( "Attempt to set parameter " + index + " on a PreparedString with only " + parameters.length + " placeholders" );
- }
- String encoded = codec.encode( IMMUNE, value );
- parameters[index-1] = encoded;
- }
-
- /**
- * Set the parameter at index with supplied value using the supplied Codec to escape.
- * @param index
- * @param value
- * @param codec
- */
- public void set( int index, String value, Codec codec ) {
- if ( index < 1 || index > parameters.length ) {
- throw new IllegalArgumentException( "Attempt to set parameter " + index + " on a PreparedString with only " + parameters.length + " placeholders" );
- }
- String encoded = codec.encode( IMMUNE, value );
- parameters[index-1] = encoded;
- }
-
- /**
- * Render the PreparedString by combining the template with properly escaped parameters.
- */
- public String toString() {
- for ( int ix = 0; ix < parameters.length; ix++ ) {
- if ( parameters[ix] == null ) {
- throw new RuntimeException( "Attempt to render PreparedString without setting parameter " + ( ix + 1 ));
- }
- }
- StringBuilder sb = new StringBuilder();
- int i = 0;
- for ( int p=0; p < parts.size(); p++ ) {
- sb.append( parts.get( p ) );
- if ( i < parameters.length ) sb.append( parameters[i++] );
- }
- return sb.toString();
- }
+ /**
+ * Split a string with a particular character.
+ * @param str
+ * @param c
+ */
+ private void split( String str, char c ) {
+ int index = 0;
+ int pcount = 0;
+ for ( int i = 0; i < str.length(); i++ ) {
+ if ( str.charAt(i) == c ) {
+ pcount++;
+ parts.add( str.substring(index,i) );
+ index = i + 1;
+ }
+ }
+ parts.add( str.substring(index) );
+ parameters = new String[pcount];
+ }
+
+ /**
+ * Set the parameter at index with supplied value using the default Codec to escape.
+ * @param index
+ * @param value
+ */
+ public void set( int index, String value ) {
+ if ( index < 1 || index > parameters.length ) {
+ throw new IllegalArgumentException( "Attempt to set parameter " + index + " on a PreparedString with only " + parameters.length + " placeholders" );
+ }
+ String encoded = codec.encode( IMMUNE, value );
+ parameters[index-1] = encoded;
+ }
+
+ /**
+ * Set the parameter at index with supplied value using the supplied Codec to escape.
+ * @param index
+ * @param value
+ * @param codec
+ */
+ public void set( int index, String value, Codec codec ) {
+ if ( index < 1 || index > parameters.length ) {
+ throw new IllegalArgumentException( "Attempt to set parameter " + index + " on a PreparedString with only " + parameters.length + " placeholders" );
+ }
+ String encoded = codec.encode( IMMUNE, value );
+ parameters[index-1] = encoded;
+ }
+
+ /**
+ * Render the PreparedString by combining the template with properly escaped parameters.
+ */
+ public String toString() {
+ for ( int ix = 0; ix < parameters.length; ix++ ) {
+ if ( parameters[ix] == null ) {
+ throw new RuntimeException( "Attempt to render PreparedString without setting parameter " + ( ix + 1 ));
+ }
+ }
+ StringBuilder sb = new StringBuilder();
+ int i = 0;
+ for ( int p=0; p < parts.size(); p++ ) {
+ sb.append( parts.get( p ) );
+ if ( i < parameters.length ) sb.append( parameters[i++] );
+ }
+ return sb.toString();
+ }
}
diff --git a/src/main/java/org/owasp/esapi/Randomizer.java b/src/main/java/org/owasp/esapi/Randomizer.java
index e1a0b811f..1d991b164 100644
--- a/src/main/java/org/owasp/esapi/Randomizer.java
+++ b/src/main/java/org/owasp/esapi/Randomizer.java
@@ -30,63 +30,63 @@
*/
public interface Randomizer {
- /**
- * Gets a random string of a desired length and character set. The use of java.security.SecureRandom
- * is recommended because it provides a cryptographically strong pseudo-random number generator.
- * If SecureRandom is not used, the pseudo-random number generator used should comply with the
- * statistical random number generator tests specified in
- * FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1.
- *
- * @param length
- * the length of the string
- * @param characterSet
- * the set of characters to include in the created random string
- *
- * @return
- * the random string of the desired length and character set
- */
- String getRandomString(int length, char[] characterSet);
+ /**
+ * Gets a random string of a desired length and character set. The use of java.security.SecureRandom
+ * is recommended because it provides a cryptographically strong pseudo-random number generator.
+ * If SecureRandom is not used, the pseudo-random number generator used should comply with the
+ * statistical random number generator tests specified in
+ * FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1.
+ *
+ * @param length
+ * the length of the string
+ * @param characterSet
+ * the set of characters to include in the created random string
+ *
+ * @return
+ * the random string of the desired length and character set
+ */
+ String getRandomString(int length, char[] characterSet);
- /**
- * Returns a random boolean. The use of java.security.SecureRandom
- * is recommended because it provides a cryptographically strong pseudo-random number generator.
- * If SecureRandom is not used, the pseudo-random number generator used should comply with the
- * statistical random number generator tests specified in
- * FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1.
- *
- * @return
- * true or false, randomly
- */
- boolean getRandomBoolean();
+ /**
+ * Returns a random boolean. The use of java.security.SecureRandom
+ * is recommended because it provides a cryptographically strong pseudo-random number generator.
+ * If SecureRandom is not used, the pseudo-random number generator used should comply with the
+ * statistical random number generator tests specified in
+ * FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1.
+ *
+ * @return
+ * true or false, randomly
+ */
+ boolean getRandomBoolean();
- /**
- * Gets the random integer in the range of [min, max). The use of java.security.SecureRandom
- * is recommended because it provides a cryptographically strong pseudo-random number generator.
- * If SecureRandom is not used, the pseudo-random number generator used should comply with the
- * statistical random number generator tests specified in
- * FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1.
- *
- * @param min
- * the minimum integer that will be returned, inclusive
- * @param max
- * the maximum integer that will be returned, exclusive
- *
- * @return
- * the random integer
- */
- int getRandomInteger(int min, int max);
+ /**
+ * Gets the random integer in the range of [min, max). The use of java.security.SecureRandom
+ * is recommended because it provides a cryptographically strong pseudo-random number generator.
+ * If SecureRandom is not used, the pseudo-random number generator used should comply with the
+ * statistical random number generator tests specified in
+ * FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1.
+ *
+ * @param min
+ * the minimum integer that will be returned, inclusive
+ * @param max
+ * the maximum integer that will be returned, exclusive
+ *
+ * @return
+ * the random integer
+ */
+ int getRandomInteger(int min, int max);
- /**
- * Gets the random long. The use of java.security.SecureRandom
- * is recommended because it provides a cryptographically strong pseudo-random number generator.
- * If SecureRandom is not used, the pseudo-random number generator used should comply with the
- * statistical random number generator tests specified in
- * FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1.
- *
- * @return
- * the random long
- */
+ /**
+ * Gets the random long. The use of java.security.SecureRandom
+ * is recommended because it provides a cryptographically strong pseudo-random number generator.
+ * If SecureRandom is not used, the pseudo-random number generator used should comply with the
+ * statistical random number generator tests specified in
+ * FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1.
+ *
+ * @return
+ * the random long
+ */
long getRandomLong();
@@ -96,30 +96,30 @@ public interface Randomizer {
* then merely append "." + extension.
*
* @param extension
- * extension to add to the random filename
+ * extension to add to the random filename
*
* @return
- * a random unguessable filename ending with the specified extension
+ * a random unguessable filename ending with the specified extension
*/
String getRandomFilename( String extension );
- /**
- * Gets the random real in the range of [min, max]. The use of java.security.SecureRandom
- * is recommended because it provides a cryptographically strong pseudo-random number generator.
- * If SecureRandom is not used, the pseudo-random number generator used should comply with the
- * statistical random number generator tests specified in
- * FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1.
- *
- * @param min
- * the minimum real number that will be returned, inclusive
- * @param max
- * the maximum real number that will be returned, inclusive
- *
- * @return
- * the random real
- */
- float getRandomReal(float min, float max);
+ /**
+ * Gets the random real in the range of [min, max]. The use of java.security.SecureRandom
+ * is recommended because it provides a cryptographically strong pseudo-random number generator.
+ * If SecureRandom is not used, the pseudo-random number generator used should comply with the
+ * statistical random number generator tests specified in
+ * FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1.
+ *
+ * @param min
+ * the minimum real number that will be returned, inclusive
+ * @param max
+ * the maximum real number that will be returned, inclusive
+ *
+ * @return
+ * the random real
+ */
+ float getRandomReal(float min, float max);
/**
* Generates a random GUID. This method could use a hash of random Strings, the current time,
@@ -130,16 +130,16 @@ public interface Randomizer {
* see the Internet-Draft UUIDs and GUIDs
* or the standards body definition at ISO/IEC 11578:1996.
* @return
- * the GUID
+ * the GUID
*
* @throws
- * EncryptionException if hashing or encryption fails
+ * EncryptionException if hashing or encryption fails
*/
String getRandomGUID() throws EncryptionException;
/**
* Generates a specified number of random bytes.
- * @param n The requested number of random bytes.
+ * @param n The requested number of random bytes.
* @return The {@code n} random bytes are returned.
*/
byte[] getRandomBytes(int n);
diff --git a/src/main/java/org/owasp/esapi/SafeFile.java b/src/main/java/org/owasp/esapi/SafeFile.java
index 7df86bb38..fba5a94e7 100644
--- a/src/main/java/org/owasp/esapi/SafeFile.java
+++ b/src/main/java/org/owasp/esapi/SafeFile.java
@@ -30,78 +30,78 @@
*/
public class SafeFile extends File {
- private static final long serialVersionUID = 1L;
- private static final Pattern PERCENTS_PAT = Pattern.compile("(%)([0-9a-fA-F])([0-9a-fA-F])");
- private static final Pattern FILE_BLACKLIST_PAT = Pattern.compile("([\\\\/:*?<>|^])");
- private static final Pattern DIR_BLACKLIST_PAT = Pattern.compile("([*?<>|^])");
+ private static final long serialVersionUID = 1L;
+ private static final Pattern PERCENTS_PAT = Pattern.compile("(%)([0-9a-fA-F])([0-9a-fA-F])");
+ private static final Pattern FILE_BLACKLIST_PAT = Pattern.compile("([\\\\/:*?<>|^])");
+ private static final Pattern DIR_BLACKLIST_PAT = Pattern.compile("([*?<>|^])");
- public SafeFile(String path) throws ValidationException {
- super(path);
- doDirCheck(this.getParent());
- doFileCheck(this.getName());
- }
+ public SafeFile(String path) throws ValidationException {
+ super(path);
+ doDirCheck(this.getParent());
+ doFileCheck(this.getName());
+ }
- public SafeFile(String parent, String child) throws ValidationException {
- super(parent, child);
- doDirCheck(this.getParent());
- doFileCheck(this.getName());
- }
+ public SafeFile(String parent, String child) throws ValidationException {
+ super(parent, child);
+ doDirCheck(this.getParent());
+ doFileCheck(this.getName());
+ }
- public SafeFile(File parent, String child) throws ValidationException {
- super(parent, child);
- doDirCheck(this.getParent());
- doFileCheck(this.getName());
- }
+ public SafeFile(File parent, String child) throws ValidationException {
+ super(parent, child);
+ doDirCheck(this.getParent());
+ doFileCheck(this.getName());
+ }
- public SafeFile(URI uri) throws ValidationException {
- super(uri);
- doDirCheck(this.getParent());
- doFileCheck(this.getName());
- }
+ public SafeFile(URI uri) throws ValidationException {
+ super(uri);
+ doDirCheck(this.getParent());
+ doFileCheck(this.getName());
+ }
-
- private void doDirCheck(String path) throws ValidationException {
- Matcher m1 = DIR_BLACKLIST_PAT.matcher( path );
- if ( null != m1 && m1.find() ) {
- throw new ValidationException( "Invalid directory", "Directory path (" + path + ") contains illegal character: " + m1.group() );
- }
+
+ private void doDirCheck(String path) throws ValidationException {
+ Matcher m1 = DIR_BLACKLIST_PAT.matcher( path );
+ if ( null != m1 && m1.find() ) {
+ throw new ValidationException( "Invalid directory", "Directory path (" + path + ") contains illegal character: " + m1.group() );
+ }
- Matcher m2 = PERCENTS_PAT.matcher( path );
- if (null != m2 && m2.find() ) {
- throw new ValidationException( "Invalid directory", "Directory path (" + path + ") contains encoded characters: " + m2.group() );
- }
-
- int ch = containsUnprintableCharacters(path);
- if (ch != -1) {
- throw new ValidationException("Invalid directory", "Directory path (" + path + ") contains unprintable character: " + ch);
- }
- }
-
- private void doFileCheck(String path) throws ValidationException {
- Matcher m1 = FILE_BLACKLIST_PAT.matcher( path );
- if ( m1.find() ) {
- throw new ValidationException( "Invalid directory", "Directory path (" + path + ") contains illegal character: " + m1.group() );
- }
+ Matcher m2 = PERCENTS_PAT.matcher( path );
+ if (null != m2 && m2.find() ) {
+ throw new ValidationException( "Invalid directory", "Directory path (" + path + ") contains encoded characters: " + m2.group() );
+ }
+
+ int ch = containsUnprintableCharacters(path);
+ if (ch != -1) {
+ throw new ValidationException("Invalid directory", "Directory path (" + path + ") contains unprintable character: " + ch);
+ }
+ }
+
+ private void doFileCheck(String path) throws ValidationException {
+ Matcher m1 = FILE_BLACKLIST_PAT.matcher( path );
+ if ( m1.find() ) {
+ throw new ValidationException( "Invalid directory", "Directory path (" + path + ") contains illegal character: " + m1.group() );
+ }
- Matcher m2 = PERCENTS_PAT.matcher( path );
- if ( m2.find() ) {
- throw new ValidationException( "Invalid file", "File path (" + path + ") contains encoded characters: " + m2.group() );
- }
-
- int ch = containsUnprintableCharacters(path);
- if (ch != -1) {
- throw new ValidationException("Invalid file", "File path (" + path + ") contains unprintable character: " + ch);
- }
- }
+ Matcher m2 = PERCENTS_PAT.matcher( path );
+ if ( m2.find() ) {
+ throw new ValidationException( "Invalid file", "File path (" + path + ") contains encoded characters: " + m2.group() );
+ }
+
+ int ch = containsUnprintableCharacters(path);
+ if (ch != -1) {
+ throw new ValidationException("Invalid file", "File path (" + path + ") contains unprintable character: " + ch);
+ }
+ }
- private int containsUnprintableCharacters(String s) {
- for (int i = 0; i < s.length(); i++) {
- char ch = s.charAt(i);
- if (((int) ch) < 32 || ((int) ch) > 126) {
- return (int) ch;
- }
- }
- return -1;
- }
+ private int containsUnprintableCharacters(String s) {
+ for (int i = 0; i < s.length(); i++) {
+ char ch = s.charAt(i);
+ if (((int) ch) < 32 || ((int) ch) > 126) {
+ return (int) ch;
+ }
+ }
+ return -1;
+ }
}
diff --git a/src/main/java/org/owasp/esapi/SecurityConfiguration.java b/src/main/java/org/owasp/esapi/SecurityConfiguration.java
index 27c4af964..2e084a05b 100644
--- a/src/main/java/org/owasp/esapi/SecurityConfiguration.java
+++ b/src/main/java/org/owasp/esapi/SecurityConfiguration.java
@@ -52,76 +52,76 @@
*/
public interface SecurityConfiguration extends EsapiPropertyLoader {
- /**
- * Gets the application name, used for logging
- *
- * @return the name of the current application
+ /**
+ * Gets the application name, used for logging
+ *
+ * @return the name of the current application
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getApplicationName();
-
- /**
- * Returns the fully qualified classname of the ESAPI Logging implementation.
+ */
+ @Deprecated
+ String getApplicationName();
+
+ /**
+ * Returns the fully qualified classname of the ESAPI Logging implementation.
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getLogImplementation();
-
- /**
- * Returns the fully qualified classname of the ESAPI Authentication implementation.
+ */
+ @Deprecated
+ String getLogImplementation();
+
+ /**
+ * Returns the fully qualified classname of the ESAPI Authentication implementation.
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getAuthenticationImplementation();
-
- /**
- * Returns the fully qualified classname of the ESAPI Encoder implementation.
+ */
+ @Deprecated
+ String getAuthenticationImplementation();
+
+ /**
+ * Returns the fully qualified classname of the ESAPI Encoder implementation.
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getEncoderImplementation();
-
- /**
- * Returns the fully qualified classname of the ESAPI Access Control implementation.
+ */
+ @Deprecated
+ String getEncoderImplementation();
+
+ /**
+ * Returns the fully qualified classname of the ESAPI Access Control implementation.
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getAccessControlImplementation();
-
- /**
- * Returns the fully qualified classname of the ESAPI Intrusion Detection implementation.
+ */
+ @Deprecated
+ String getAccessControlImplementation();
+
+ /**
+ * Returns the fully qualified classname of the ESAPI Intrusion Detection implementation.
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getIntrusionDetectionImplementation();
-
- /**
- * Returns the fully qualified classname of the ESAPI Randomizer implementation.
+ */
+ @Deprecated
+ String getIntrusionDetectionImplementation();
+
+ /**
+ * Returns the fully qualified classname of the ESAPI Randomizer implementation.
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getRandomizerImplementation();
-
- /**
- * Returns the fully qualified classname of the ESAPI Encryption implementation.
+ */
+ @Deprecated
+ String getRandomizerImplementation();
+
+ /**
+ * Returns the fully qualified classname of the ESAPI Encryption implementation.
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getEncryptionImplementation();
-
- /**
- * Returns the fully qualified classname of the ESAPI Validation implementation.
+ */
+ @Deprecated
+ String getEncryptionImplementation();
+
+ /**
+ * Returns the fully qualified classname of the ESAPI Validation implementation.
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getValidationImplementation();
-
- /**
- * Returns the validation pattern for a particular type
- * @param typeName
- * @return the validation pattern
- */
+ */
+ @Deprecated
+ String getValidationImplementation();
+
+ /**
+ * Returns the validation pattern for a particular type
+ * @param typeName
+ * @return the validation pattern
+ */
Pattern getValidationPattern( String typeName );
/**
@@ -134,164 +134,164 @@ public interface SecurityConfiguration extends EsapiPropertyLoader {
* @see java.text.DateFormat#setLenient(boolean)
* @deprecated Use SecurityConfiguration.getBooleanProp("appropriate_esapi_prop_name") instead.
*/
- @Deprecated
+ @Deprecated
boolean getLenientDatesAccepted();
-
- /**
- * Returns the fully qualified classname of the ESAPI OS Execution implementation.
+
+ /**
+ * Returns the fully qualified classname of the ESAPI OS Execution implementation.
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getExecutorImplementation();
-
- /**
- * Returns the fully qualified classname of the ESAPI HTTPUtilities implementation.
+ */
+ @Deprecated
+ String getExecutorImplementation();
+
+ /**
+ * Returns the fully qualified classname of the ESAPI HTTPUtilities implementation.
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getHTTPUtilitiesImplementation();
-
- /**
- * Gets the master key. This password is used to encrypt/decrypt other files or types
- * of data that need to be protected by your application.
- *
- * @return the current master key
+ */
+ @Deprecated
+ String getHTTPUtilitiesImplementation();
+
+ /**
+ * Gets the master key. This password is used to encrypt/decrypt other files or types
+ * of data that need to be protected by your application.
+ *
+ * @return the current master key
* @deprecated Use SecurityConfiguration.getByteArrayProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- byte[] getMasterKey();
+ */
+ @Deprecated
+ byte[] getMasterKey();
- /**
+ /**
* Retrieves the upload directory as specified in the ESAPI.properties file.
* @return the upload directory
*/
File getUploadDirectory();
-
+
/**
* Retrieves the temp directory to use when uploading files, as specified in ESAPI.properties.
* @return the temp directory
*/
File getUploadTempDirectory();
- /**
- * Gets the key length to use in cryptographic operations declared in the ESAPI properties file.
+ /**
+ * Gets the key length to use in cryptographic operations declared in the ESAPI properties file.
* Note that this corresponds to the ESAPI property Encryptor.EncryptionKeyLength which is
* considered the default key size that ESAPI will use for symmetric
* ciphers supporting multiple key sizes. (Note that there is also an Encryptor.MinEncryptionKeyLength,
* which is the minimum key size (in bits) that ESAPI will support
* for encryption. (There is no miminimum for decryption.)
- *
- * @return the key length (in bits)
+ *
+ * @return the key length (in bits)
* @deprecated Use SecurityConfiguration.getIntProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
+ */
+ @Deprecated
int getEncryptionKeyLength();
- /**
- * Gets the master salt that is used to salt stored password hashes and any other location
- * where a salt is needed.
- *
- * @return the current master salt
+ /**
+ * Gets the master salt that is used to salt stored password hashes and any other location
+ * where a salt is needed.
+ *
+ * @return the current master salt
* @deprecated Use SecurityConfiguration.getByteArrayProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- byte[] getMasterSalt();
-
- /**
- * Gets the allowed executables to run with the Executor.
- *
- * @return a list of the current allowed file extensions
- */
- List getAllowedExecutables();
-
- /**
- * Gets the allowed file extensions for files that are uploaded to this application.
- *
- * @return a list of the current allowed file extensions
- */
- List getAllowedFileExtensions();
-
- /**
- * Gets the maximum allowed file upload size.
- *
- * @return the current allowed file upload size
+ */
+ @Deprecated
+ byte[] getMasterSalt();
+
+ /**
+ * Gets the allowed executables to run with the Executor.
+ *
+ * @return a list of the current allowed file extensions
+ */
+ List getAllowedExecutables();
+
+ /**
+ * Gets the allowed file extensions for files that are uploaded to this application.
+ *
+ * @return a list of the current allowed file extensions
+ */
+ List getAllowedFileExtensions();
+
+ /**
+ * Gets the maximum allowed file upload size.
+ *
+ * @return the current allowed file upload size
* @deprecated Use SecurityConfiguration.getIntProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- int getAllowedFileUploadSize();
-
- /**
- * Gets the name of the password parameter used during user authentication.
- *
- * @return the name of the password parameter
+ */
+ @Deprecated
+ int getAllowedFileUploadSize();
+
+ /**
+ * Gets the name of the password parameter used during user authentication.
+ *
+ * @return the name of the password parameter
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getPasswordParameterName();
-
- /**
- * Gets the name of the username parameter used during user authentication.
- *
- * @return the name of the username parameter
+ */
+ @Deprecated
+ String getPasswordParameterName();
+
+ /**
+ * Gets the name of the username parameter used during user authentication.
+ *
+ * @return the name of the username parameter
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getUsernameParameterName();
-
- /**
- * Gets the encryption algorithm used by ESAPI to protect data. This is
- * mostly used for compatibility with ESAPI 1.4; ESAPI 2.0 prefers to
- * use "cipher transformation" since it supports multiple cipher modes
- * and padding schemes.
- *
- * @return the current encryption algorithm
+ */
+ @Deprecated
+ String getUsernameParameterName();
+
+ /**
+ * Gets the encryption algorithm used by ESAPI to protect data. This is
+ * mostly used for compatibility with ESAPI 1.4; ESAPI 2.0 prefers to
+ * use "cipher transformation" since it supports multiple cipher modes
+ * and padding schemes.
+ *
+ * @return the current encryption algorithm
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getEncryptionAlgorithm();
-
- /**
- * Retrieve the cipher transformation. In general, the cipher transformation
- * is a specification of cipher algorithm, cipher mode, and padding scheme
- * and in general, is a {@code String} that takes the following form:
- *
- * where cipher_alg is the JCE cipher algorithm (e.g., "DESede"),
- * cipher_mode is the cipher mode (e.g., "CBC", "CFB", "CTR", etc.),
- * and padding_scheme is the cipher padding scheme (e.g., "NONE" for
- * no padding, "PKCS5Padding" for PKCS#5 padding, etc.) and where
- * [bits] is an optional bit size that applies to certain cipher
- * modes such as {@code CFB} and {@code OFB}. Using modes such as CFB and
- * OFB, block ciphers can encrypt data in units smaller than the cipher's
- * actual block size. When requesting such a mode, you may optionally
- * specify the number of bits to be processed at a time. This generally must
- * be an integral multiple of 8-bits so that it can specify a whole number
- * of octets.
- *
- * NOTE: Occasionally, in cryptographic literature, you may also
- * see the key size (in bits) specified after the cipher algorithm in the
- * cipher transformation. Generally, this is done to account for cipher
- * algorithms that have variable key sizes. The Blowfish cipher for example
- * supports key sizes from 32 to 448 bits. So for Blowfish, you might see
- * a cipher transformation something like this:
- *
- * "Blowfish-192/CFB8/PKCS5Padding"
- *
- * in the cryptographic literature. It should be noted that the Java
- * Cryptography Extensions (JCE) do not generally support this (at least
- * not the reference JCE implementation of "SunJCE"), and therefore it
- * should be avoided.
- * @return The cipher transformation.
+ */
+ @Deprecated
+ String getEncryptionAlgorithm();
+
+ /**
+ * Retrieve the cipher transformation. In general, the cipher transformation
+ * is a specification of cipher algorithm, cipher mode, and padding scheme
+ * and in general, is a {@code String} that takes the following form:
+ *
+ * where cipher_alg is the JCE cipher algorithm (e.g., "DESede"),
+ * cipher_mode is the cipher mode (e.g., "CBC", "CFB", "CTR", etc.),
+ * and padding_scheme is the cipher padding scheme (e.g., "NONE" for
+ * no padding, "PKCS5Padding" for PKCS#5 padding, etc.) and where
+ * [bits] is an optional bit size that applies to certain cipher
+ * modes such as {@code CFB} and {@code OFB}. Using modes such as CFB and
+ * OFB, block ciphers can encrypt data in units smaller than the cipher's
+ * actual block size. When requesting such a mode, you may optionally
+ * specify the number of bits to be processed at a time. This generally must
+ * be an integral multiple of 8-bits so that it can specify a whole number
+ * of octets.
+ *
+ * NOTE: Occasionally, in cryptographic literature, you may also
+ * see the key size (in bits) specified after the cipher algorithm in the
+ * cipher transformation. Generally, this is done to account for cipher
+ * algorithms that have variable key sizes. The Blowfish cipher for example
+ * supports key sizes from 32 to 448 bits. So for Blowfish, you might see
+ * a cipher transformation something like this:
+ *
+ * "Blowfish-192/CFB8/PKCS5Padding"
+ *
+ * in the cryptographic literature. It should be noted that the Java
+ * Cryptography Extensions (JCE) do not generally support this (at least
+ * not the reference JCE implementation of "SunJCE"), and therefore it
+ * should be avoided.
+ * @return The cipher transformation.
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
+ */
+ @Deprecated
String getCipherTransformation();
/**
@@ -300,21 +300,21 @@ public interface SecurityConfiguration extends EsapiPropertyLoader {
* you may normally want to use AES/CBC/PKCS5Padding, but have some legacy
* encryption where you have ciphertext that was encrypted using 3DES.
*
- * @param cipherXform The new cipher transformation. See
- * {@link #getCipherTransformation} for format. If
- * {@code null} is passed as the parameter, the cipher
- * transformation will be set to the the default taken
- * from the property {@code Encryptor.CipherTransformation}
- * in the {@code ESAPI.properties} file. BEWARE:
- * there is NO sanity checking here (other than
- * the empty string, and then, only if Java assertions are
- * enabled), so if you set this wrong, you will not get
- * any errors until you later try to use it to encrypt
- * or decrypt data.
- * @return The previous cipher transformation is returned for convenience,
- * with the assumption that you may wish to restore it once you have
- * completed the encryption / decryption with the new cipher
- * transformation.
+ * @param cipherXform The new cipher transformation. See
+ * {@link #getCipherTransformation} for format. If
+ * {@code null} is passed as the parameter, the cipher
+ * transformation will be set to the the default taken
+ * from the property {@code Encryptor.CipherTransformation}
+ * in the {@code ESAPI.properties} file. BEWARE:
+ * there is NO sanity checking here (other than
+ * the empty string, and then, only if Java assertions are
+ * enabled), so if you set this wrong, you will not get
+ * any errors until you later try to use it to encrypt
+ * or decrypt data.
+ * @return The previous cipher transformation is returned for convenience,
+ * with the assumption that you may wish to restore it once you have
+ * completed the encryption / decryption with the new cipher
+ * transformation.
* @deprecated To be replaced by new class in ESAPI 2.1, but here if you need it
* until then. Details of replacement forthcoming to ESAPI-Dev
* list. Most likely to be replaced by a new CTOR for
@@ -340,12 +340,12 @@ public interface SecurityConfiguration extends EsapiPropertyLoader {
* @see org.owasp.esapi.crypto.SecurityProviderLoader
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
*/
- @Deprecated
+ @Deprecated
String getPreferredJCEProvider();
// TODO - DISCUSS: Where should this web page (below) go? Maybe with the Javadoc? But where?
-// Think it makes more sense as part of the release notes, but OTOH, I
-// really don't want to rewrite this as a Wiki page either.
+// Think it makes more sense as part of the release notes, but OTOH, I
+// really don't want to rewrite this as a Wiki page either.
/**
* Determines whether the {@code CipherText} should be used with a Message
* Authentication Code (MAC). Generally this makes for a more robust cryptographic
@@ -356,10 +356,10 @@ public interface SecurityConfiguration extends EsapiPropertyLoader {
*
* "Why Is OWASP Changing ESAPI Encryption?".
*
- * @return {@code true} if a you want a MAC to be used, otherwise {@code false}.
+ * @return {@code true} if a you want a MAC to be used, otherwise {@code false}.
* @deprecated Use SecurityConfiguration.getBooleanProp("appropriate_esapi_prop_name") instead.
*/
- @Deprecated
+ @Deprecated
boolean useMACforCipherText();
/**
@@ -373,11 +373,11 @@ public interface SecurityConfiguration extends EsapiPropertyLoader {
* Controlled by the property {@code Encryptor.PlainText.overwrite} in
* the {@code ESAPI.properties} file.
*
- * @return True if it is OK to overwrite the {@code PlainText} objects
- * after encrypting, false otherwise.
+ * @return True if it is OK to overwrite the {@code PlainText} objects
+ * after encrypting, false otherwise.
* @deprecated Use SecurityConfiguration.getBooleanProp("appropriate_esapi_prop_name") instead.
*/
- @Deprecated
+ @Deprecated
boolean overwritePlainText();
/**
@@ -402,7 +402,7 @@ public interface SecurityConfiguration extends EsapiPropertyLoader {
* This method will be removed in a future release as it is now moot since
* it can only legitimately have the single value of "random".
*/
- @Deprecated
+ @Deprecated
String getIVType();
/**
@@ -441,185 +441,185 @@ public interface SecurityConfiguration extends EsapiPropertyLoader {
*/
List getAdditionalAllowedCipherModes();
- /**
- * Gets the hashing algorithm used by ESAPI to hash data.
- *
- * @return the current hashing algorithm
+ /**
+ * Gets the hashing algorithm used by ESAPI to hash data.
+ *
+ * @return the current hashing algorithm
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getHashAlgorithm();
-
- /**
- * Gets the hash iterations used by ESAPI to hash data.
- *
- * @return the current hashing algorithm
+ */
+ @Deprecated
+ String getHashAlgorithm();
+
+ /**
+ * Gets the hash iterations used by ESAPI to hash data.
+ *
+ * @return the current hashing algorithm
* @deprecated Use SecurityConfiguration.getIntProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- int getHashIterations();
-
- /**
- * Retrieve the Pseudo Random Function (PRF) used by the ESAPI
- * Key Derivation Function (KDF).
- *
- * @return The KDF PRF algorithm name.
+ */
+ @Deprecated
+ int getHashIterations();
+
+ /**
+ * Retrieve the Pseudo Random Function (PRF) used by the ESAPI
+ * Key Derivation Function (KDF).
+ *
+ * @return The KDF PRF algorithm name.
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getKDFPseudoRandomFunction();
-
- /**
- * Gets the character encoding scheme supported by this application. This is used to set the
- * character encoding scheme on requests and responses when setCharacterEncoding() is called
- * on SafeRequests and SafeResponses. This scheme is also used for encoding/decoding URLs
- * and any other place where the current encoding scheme needs to be known.
- *
- * Note: This does not get the configured response content type. That is accessed by calling
- * getResponseContentType().
- *
- * @return the current character encoding scheme
+ */
+ @Deprecated
+ String getKDFPseudoRandomFunction();
+
+ /**
+ * Gets the character encoding scheme supported by this application. This is used to set the
+ * character encoding scheme on requests and responses when setCharacterEncoding() is called
+ * on SafeRequests and SafeResponses. This scheme is also used for encoding/decoding URLs
+ * and any other place where the current encoding scheme needs to be known.
+ *
+ * Note: This does not get the configured response content type. That is accessed by calling
+ * getResponseContentType().
+ *
+ * @return the current character encoding scheme
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getCharacterEncoding();
-
- /**
- * Return true if multiple encoding is allowed
- *
- * @return whether multiple encoding is allowed when canonicalizing data
+ */
+ @Deprecated
+ String getCharacterEncoding();
+
+ /**
+ * Return true if multiple encoding is allowed
+ *
+ * @return whether multiple encoding is allowed when canonicalizing data
* @deprecated Use SecurityConfiguration.getBooleanProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- boolean getAllowMultipleEncoding();
-
- /**
- * Return true if mixed encoding is allowed
- *
- * @return whether mixed encoding is allowed when canonicalizing data
+ */
+ @Deprecated
+ boolean getAllowMultipleEncoding();
+
+ /**
+ * Return true if mixed encoding is allowed
+ *
+ * @return whether mixed encoding is allowed when canonicalizing data
* @deprecated Use SecurityConfiguration.getBooleanProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- boolean getAllowMixedEncoding();
-
- /**
- * Returns the List of Codecs to use when canonicalizing data
- *
- * @return the codec list
- */
- List getDefaultCanonicalizationCodecs();
-
- /**
- * Gets the digital signature algorithm used by ESAPI to generate and verify signatures.
- *
- * @return the current digital signature algorithm
+ */
+ @Deprecated
+ boolean getAllowMixedEncoding();
+
+ /**
+ * Returns the List of Codecs to use when canonicalizing data
+ *
+ * @return the codec list
+ */
+ List getDefaultCanonicalizationCodecs();
+
+ /**
+ * Gets the digital signature algorithm used by ESAPI to generate and verify signatures.
+ *
+ * @return the current digital signature algorithm
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getDigitalSignatureAlgorithm();
-
- /**
- * Gets the digital signature key length used by ESAPI to generate and verify signatures.
- *
- * @return the current digital signature key length
+ */
+ @Deprecated
+ String getDigitalSignatureAlgorithm();
+
+ /**
+ * Gets the digital signature key length used by ESAPI to generate and verify signatures.
+ *
+ * @return the current digital signature key length
* @deprecated Use SecurityConfiguration.getIntProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- int getDigitalSignatureKeyLength();
-
- /**
- * Gets the random number generation algorithm used to generate random numbers where needed.
- *
- * @return the current random number generation algorithm
+ */
+ @Deprecated
+ int getDigitalSignatureKeyLength();
+
+ /**
+ * Gets the random number generation algorithm used to generate random numbers where needed.
+ *
+ * @return the current random number generation algorithm
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getRandomAlgorithm();
-
- /**
- * Gets the number of login attempts allowed before the user's account is locked. If this
- * many failures are detected within the alloted time period, the user's account will be locked.
- *
- * @return the number of failed login attempts that cause an account to be locked
+ */
+ @Deprecated
+ String getRandomAlgorithm();
+
+ /**
+ * Gets the number of login attempts allowed before the user's account is locked. If this
+ * many failures are detected within the alloted time period, the user's account will be locked.
+ *
+ * @return the number of failed login attempts that cause an account to be locked
* @deprecated Use SecurityConfiguration.getIntProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- int getAllowedLoginAttempts();
-
- /**
- * Gets the maximum number of old password hashes that should be retained. These hashes can
- * be used to ensure that the user doesn't reuse the specified number of previous passwords
- * when they change their password.
- *
- * @return the number of old hashed passwords to retain
+ */
+ @Deprecated
+ int getAllowedLoginAttempts();
+
+ /**
+ * Gets the maximum number of old password hashes that should be retained. These hashes can
+ * be used to ensure that the user doesn't reuse the specified number of previous passwords
+ * when they change their password.
+ *
+ * @return the number of old hashed passwords to retain
* @deprecated Use SecurityConfiguration.getIntProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- int getMaxOldPasswordHashes();
-
- /**
- * Allows for complete disabling of all intrusion detection mechanisms
- *
- * @return true if intrusion detection should be disabled
+ */
+ @Deprecated
+ int getMaxOldPasswordHashes();
+
+ /**
+ * Allows for complete disabling of all intrusion detection mechanisms
+ *
+ * @return true if intrusion detection should be disabled
* @deprecated Use SecurityConfiguration.getBooleanProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- boolean getDisableIntrusionDetection();
-
- /**
- * Gets the intrusion detection quota for the specified event.
- *
- * @param eventName the name of the event whose quota is desired
- *
- * @return the Quota that has been configured for the specified type of event
- */
- Threshold getQuota(String eventName);
-
- /**
- * Gets a file from the resource directory
+ */
+ @Deprecated
+ boolean getDisableIntrusionDetection();
+
+ /**
+ * Gets the intrusion detection quota for the specified event.
+ *
+ * @param eventName the name of the event whose quota is desired
+ *
+ * @return the Quota that has been configured for the specified type of event
+ */
+ Threshold getQuota(String eventName);
+
+ /**
+ * Gets a file from the resource directory
*
* @param filename The file name resource.
* @return A {@code File} object representing the specified file name or null if not found.
*/
File getResourceFile( String filename );
- /**
- * Returns true if session cookies are required to have HttpOnly flag set.
+ /**
+ * Returns true if session cookies are required to have HttpOnly flag set.
* @deprecated Use SecurityConfiguration.getBooleanProp("appropriate_esapi_prop_name") instead.
*/
- @Deprecated
+ @Deprecated
boolean getForceHttpOnlySession() ;
- /**
- * Returns true if session cookies are required to have Secure flag set.
+ /**
+ * Returns true if session cookies are required to have Secure flag set.
* @deprecated Use SecurityConfiguration.getBooleanProp("appropriate_esapi_prop_name") instead.
*/
- @Deprecated
+ @Deprecated
boolean getForceSecureSession() ;
- /**
- * Returns true if new cookies are required to have HttpOnly flag set.
+ /**
+ * Returns true if new cookies are required to have HttpOnly flag set.
* @deprecated Use SecurityConfiguration.getBooleanProp("appropriate_esapi_prop_name") instead.
*/
- @Deprecated
+ @Deprecated
boolean getForceHttpOnlyCookies() ;
- /**
- * Returns true if new cookies are required to have Secure flag set.
+ /**
+ * Returns true if new cookies are required to have Secure flag set.
* @deprecated Use SecurityConfiguration.getBooleanProp("appropriate_esapi_prop_name") instead.
*/
- @Deprecated
+ @Deprecated
boolean getForceSecureCookies() ;
- /**
- * Returns the maximum allowable HTTP header size.
+ /**
+ * Returns the maximum allowable HTTP header size.
* @deprecated Use SecurityConfiguration.getIntProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- int getMaxHttpHeaderSize() ;
+ */
+ @Deprecated
+ int getMaxHttpHeaderSize() ;
- /**
- * Gets an InputStream to a file in the resource directory
+ /**
+ * Gets an InputStream to a file in the resource directory
*
* @param filename A file name in the resource directory.
* @return An {@code InputStream} to the specified file name in the resource directory.
@@ -627,142 +627,142 @@ public interface SecurityConfiguration extends EsapiPropertyLoader {
*/
InputStream getResourceStream( String filename ) throws IOException;
- /**
- * Sets the ESAPI resource directory.
- *
- * @param dir The location of the resource directory.
- */
- void setResourceDirectory(String dir);
-
- /**
- * Gets the content type for responses used when setSafeContentType() is called.
- *
- * Note: This does not get the configured character encoding scheme. That is accessed by calling
- * getCharacterEncoding().
- *
- * @return The current content-type set for responses.
+ /**
+ * Sets the ESAPI resource directory.
+ *
+ * @param dir The location of the resource directory.
+ */
+ void setResourceDirectory(String dir);
+
+ /**
+ * Gets the content type for responses used when setSafeContentType() is called.
+ *
+ * Note: This does not get the configured character encoding scheme. That is accessed by calling
+ * getCharacterEncoding().
+ *
+ * @return The current content-type set for responses.
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getResponseContentType();
-
- /**
- * This method returns the configured name of the session identifier,
- * likely "JSESSIONID" though this can be overridden.
- *
- * @return The name of the session identifier, like "JSESSIONID"
+ */
+ @Deprecated
+ String getResponseContentType();
+
+ /**
+ * This method returns the configured name of the session identifier,
+ * likely "JSESSIONID" though this can be overridden.
+ *
+ * @return The name of the session identifier, like "JSESSIONID"
* @deprecated Use SecurityConfiguration.getStringProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- String getHttpSessionIdName();
-
- /**
- * Gets the length of the time to live window for remember me tokens (in milliseconds).
- *
- * @return The time to live length for generated "remember me" tokens.
- */
+ */
+ @Deprecated
+ String getHttpSessionIdName();
+
+ /**
+ * Gets the length of the time to live window for remember me tokens (in milliseconds).
+ *
+ * @return The time to live length for generated "remember me" tokens.
+ */
// OPEN ISSUE: Can we replace w/ SecurityConfiguration.getIntProp("appropriate_esapi_prop_name") instead?
- long getRememberTokenDuration();
-
-
- /**
- * Gets the idle timeout length for sessions (in milliseconds). This is the amount of time that a session
- * can live before it expires due to lack of activity. Applications or frameworks could provide a reauthenticate
- * function that enables a session to continue after reauthentication.
- *
- * @return The session idle timeout length.
+ long getRememberTokenDuration();
+
+
+ /**
+ * Gets the idle timeout length for sessions (in milliseconds). This is the amount of time that a session
+ * can live before it expires due to lack of activity. Applications or frameworks could provide a reauthenticate
+ * function that enables a session to continue after reauthentication.
+ *
+ * @return The session idle timeout length.
* @deprecated Use SecurityConfiguration.getIntProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- int getSessionIdleTimeoutLength();
-
- /**
- * Gets the absolute timeout length for sessions (in milliseconds). This is the amount of time that a session
- * can live before it expires regardless of the amount of user activity. Applications or frameworks could
- * provide a reauthenticate function that enables a session to continue after reauthentication.
- *
- * @return The session absolute timeout length.
+ */
+ @Deprecated
+ int getSessionIdleTimeoutLength();
+
+ /**
+ * Gets the absolute timeout length for sessions (in milliseconds). This is the amount of time that a session
+ * can live before it expires regardless of the amount of user activity. Applications or frameworks could
+ * provide a reauthenticate function that enables a session to continue after reauthentication.
+ *
+ * @return The session absolute timeout length.
* @deprecated Use SecurityConfiguration.getIntProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- int getSessionAbsoluteTimeoutLength();
-
-
- /**
- * Returns whether HTML entity encoding should be applied to log entries.
- *
- * @return True if log entries are to be HTML Entity encoded. False otherwise.
+ */
+ @Deprecated
+ int getSessionAbsoluteTimeoutLength();
+
+
+ /**
+ * Returns whether HTML entity encoding should be applied to log entries.
+ *
+ * @return True if log entries are to be HTML Entity encoded. False otherwise.
* @deprecated Use SecurityConfiguration.getBooleanProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- boolean getLogEncodingRequired();
-
- /**
- * Returns whether ESAPI should log the application name. This might be clutter in some
- * single-server/single-app environments.
- *
- * @return True if ESAPI should log the application name, False otherwise
+ */
+ @Deprecated
+ boolean getLogEncodingRequired();
+
+ /**
+ * Returns whether ESAPI should log the application name. This might be clutter in some
+ * single-server/single-app environments.
+ *
+ * @return True if ESAPI should log the application name, False otherwise
* @deprecated Use SecurityConfiguration.getBooleanProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- boolean getLogApplicationName();
-
- /**
- * Returns whether ESAPI should log the server IP. This might be clutter in some
- * single-server environments.
- *
- * @return True if ESAPI should log the server IP and port, False otherwise
+ */
+ @Deprecated
+ boolean getLogApplicationName();
+
+ /**
+ * Returns whether ESAPI should log the server IP. This might be clutter in some
+ * single-server environments.
+ *
+ * @return True if ESAPI should log the server IP and port, False otherwise
* @deprecated Use SecurityConfiguration.getBooleanProp("appropriate_esapi_prop_name") instead.
- */
- @Deprecated
- boolean getLogServerIP();
-
- /**
- * Models a simple threshold as a count and an interval, along with a set of actions to take if
- * the threshold is exceeded. These thresholds are used to define when the accumulation of a particular event
- * has met a set number within the specified time period. Once a threshold value has been met, various
- * actions can be taken at that point.
- */
- class Threshold {
-
- /** The name of this threshold. */
- public String name = null;
-
- /** The count at which this threshold is triggered. */
- public int count = 0;
-
- /**
- * The time frame within which 'count' number of actions has to be detected in order to
- * trigger this threshold.
- */
- public long interval = 0;
-
- /**
- * The list of actions to take if the threshold is met. It is expected that this is a list of Strings, but
- * your implementation could have this be a list of any type of 'actions' you wish to define.
- */
- public List actions = null;
-
- /**
- * Constructs a threshold that is composed of its name, its threshold count, the time window for
- * the threshold, and the actions to take if the threshold is triggered.
- *
- * @param name The name of this threshold.
- * @param count The count at which this threshold is triggered.
- * @param interval The time frame within which 'count' number of actions has to be detected in order to
- * trigger this threshold.
- * @param actions The list of actions to take if the threshold is met.
- */
- public Threshold(String name, int count, long interval, List actions) {
- this.name = name;
- this.count = count;
- this.interval = interval;
- this.actions = actions;
- }
- }
-
- /**
- * Returns the default working directory for executing native processes with Runtime.exec().
- */
- File getWorkingDirectory();
+ */
+ @Deprecated
+ boolean getLogServerIP();
+
+ /**
+ * Models a simple threshold as a count and an interval, along with a set of actions to take if
+ * the threshold is exceeded. These thresholds are used to define when the accumulation of a particular event
+ * has met a set number within the specified time period. Once a threshold value has been met, various
+ * actions can be taken at that point.
+ */
+ class Threshold {
+
+ /** The name of this threshold. */
+ public String name = null;
+
+ /** The count at which this threshold is triggered. */
+ public int count = 0;
+
+ /**
+ * The time frame within which 'count' number of actions has to be detected in order to
+ * trigger this threshold.
+ */
+ public long interval = 0;
+
+ /**
+ * The list of actions to take if the threshold is met. It is expected that this is a list of Strings, but
+ * your implementation could have this be a list of any type of 'actions' you wish to define.
+ */
+ public List actions = null;
+
+ /**
+ * Constructs a threshold that is composed of its name, its threshold count, the time window for
+ * the threshold, and the actions to take if the threshold is triggered.
+ *
+ * @param name The name of this threshold.
+ * @param count The count at which this threshold is triggered.
+ * @param interval The time frame within which 'count' number of actions has to be detected in order to
+ * trigger this threshold.
+ * @param actions The list of actions to take if the threshold is met.
+ */
+ public Threshold(String name, int count, long interval, List actions) {
+ this.name = name;
+ this.count = count;
+ this.interval = interval;
+ this.actions = actions;
+ }
+ }
+
+ /**
+ * Returns the default working directory for executing native processes with Runtime.exec().
+ */
+ File getWorkingDirectory();
}
diff --git a/src/main/java/org/owasp/esapi/StringUtilities.java b/src/main/java/org/owasp/esapi/StringUtilities.java
index 634287ad1..19a29f7c9 100644
--- a/src/main/java/org/owasp/esapi/StringUtilities.java
+++ b/src/main/java/org/owasp/esapi/StringUtilities.java
@@ -27,31 +27,31 @@
*/
public class StringUtilities {
- private static final Pattern p = Pattern.compile( "\\s");
- public static String replaceLinearWhiteSpace( String input ) {
- return p.matcher(input).replaceAll( " " );
- }
-
- /**
- * Removes all unprintable characters from a string
- * and replaces with a space.
- * @param input
- * @return the stripped value
- */
- public static String stripControls( String input ) {
- StringBuilder sb = new StringBuilder();
- for ( int i=0; i 0x20 && c < 0x7f ) {
- sb.append( c );
- } else {
- sb.append( ' ' );
- }
- }
- return sb.toString();
- }
-
-
+ private static final Pattern p = Pattern.compile( "\\s");
+ public static String replaceLinearWhiteSpace( String input ) {
+ return p.matcher(input).replaceAll( " " );
+ }
+
+ /**
+ * Removes all unprintable characters from a string
+ * and replaces with a space.
+ * @param input
+ * @return the stripped value
+ */
+ public static String stripControls( String input ) {
+ StringBuilder sb = new StringBuilder();
+ for ( int i=0; i 0x20 && c < 0x7f ) {
+ sb.append( c );
+ } else {
+ sb.append( ' ' );
+ }
+ }
+ return sb.toString();
+ }
+
+
/**
* Union multiple character arrays.
*
@@ -59,14 +59,14 @@ public static String stripControls( String input ) {
* @return the union of the char[]s
*/
public static char[] union(char[]... list) {
- StringBuilder sb = new StringBuilder();
-
- for (char[] characters : list) {
- for ( char c : characters ) {
- if ( !contains( sb, c ) )
- sb.append( c );
- }
- }
+ StringBuilder sb = new StringBuilder();
+
+ for (char[] characters : list) {
+ for ( char c : characters ) {
+ if ( !contains( sb, c ) )
+ sb.append( c );
+ }
+ }
char[] toReturn = new char[sb.length()];
sb.getChars(0, sb.length(), toReturn, 0);
@@ -75,11 +75,11 @@ public static char[] union(char[]... list) {
}
- /**
+ /**
* Returns true if the character is contained in the provided StringBuilder.
- * @param input The input
- * @param c The character to check for to see if {@code input} contains.
- * @return True if the specified character is contained; false otherwise.
+ * @param input The input
+ * @param c The character to check for to see if {@code input} contains.
+ * @return True if the specified character is contained; false otherwise.
*/
public static boolean contains(StringBuilder input, char c) {
for (int i = 0; i < input.length(); i++) {
@@ -171,24 +171,24 @@ public static int getLevenshteinDistance (String s, String t) {
* trimming of leading and trailing whitespace). Usually used with
* assertions, as in
*
- * assert StringUtils.notNullOrEmpty(cipherXform, true) :
- * "Cipher transformation may not be null or empty!";
+ * assert StringUtils.notNullOrEmpty(cipherXform, true) :
+ * "Cipher transformation may not be null or empty!";
*
* or an equivalent runtime check that throws an {@code IllegalArgumentException}.
*
- * @param str The {@code String} to be checked.
- * @param trim If {@code true}, the string is first trimmed before checking
- * to see if it is empty, otherwise it is not.
- * @return True if the string is null or empty (after possible
- * trimming); otherwise false.
+ * @param str The {@code String} to be checked.
+ * @param trim If {@code true}, the string is first trimmed before checking
+ * to see if it is empty, otherwise it is not.
+ * @return True if the string is null or empty (after possible
+ * trimming); otherwise false.
* @since 2.0
*/
public static boolean notNullOrEmpty(String str, boolean trim) {
- if ( trim ) {
- return !( str == null || str.trim().equals("") );
- } else {
- return !( str == null || str.equals("") );
- }
+ if ( trim ) {
+ return !( str == null || str.trim().equals("") );
+ } else {
+ return !( str == null || str.equals("") );
+ }
}
/**
diff --git a/src/main/java/org/owasp/esapi/User.java b/src/main/java/org/owasp/esapi/User.java
index 480e97135..8e46a97e2 100644
--- a/src/main/java/org/owasp/esapi/User.java
+++ b/src/main/java/org/owasp/esapi/User.java
@@ -41,24 +41,24 @@
*/
public interface User extends Principal, Serializable {
- /**
- * @return the locale
- */
- Locale getLocale();
+ /**
+ * @return the locale
+ */
+ Locale getLocale();
- /**
- * @param locale the locale to set
- */
- void setLocale(Locale locale);
+ /**
+ * @param locale the locale to set
+ */
+ void setLocale(Locale locale);
/**
* Adds a role to this user's account.
*
* @param role
- * the role to add
+ * the role to add
*
* @throws AuthenticationException
- * the authentication exception
+ * the authentication exception
*/
void addRole(String role) throws AuthenticationException;
@@ -66,10 +66,10 @@ public interface User extends Principal, Serializable {
* Adds a set of roles to this user's account.
*
* @param newRoles
- * the new roles to add
+ * the new roles to add
*
* @throws AuthenticationException
- * the authentication exception
+ * the authentication exception
*/
void addRoles(Set newRoles) throws AuthenticationException;
@@ -78,14 +78,14 @@ public interface User extends Principal, Serializable {
* passwords, and the strength of the new password.
*
* @param oldPassword
- * the old password
+ * the old password
* @param newPassword1
- * the new password
+ * the new password
* @param newPassword2
- * the new password - used to verify that the new password was typed correctly
+ * the new password - used to verify that the new password was typed correctly
*
* @throws AuthenticationException
- * if newPassword1 does not match newPassword2, if oldPassword does not match the stored old password, or if the new password does not meet complexity requirements
+ * if newPassword1 does not match newPassword2, if oldPassword does not match the stored old password, or if the new password does not meet complexity requirements
* @throws EncryptionException
*/
void changePassword(String oldPassword, String newPassword1, String newPassword2) throws AuthenticationException, EncryptionException;
@@ -146,14 +146,14 @@ public interface User extends Principal, Serializable {
*/
String getLastHostAddress();
- /**
+ /**
* Returns the date of the last failed login time for a user. This date should be used in a message to users after a
* successful login, to notify them of potential attack activity on their account.
*
* @return date of the last failed login
*
* @throws AuthenticationException
- * the authentication exception
+ * the authentication exception
*/
Date getLastFailedLoginTime() throws AuthenticationException;
@@ -190,7 +190,7 @@ public interface User extends Principal, Serializable {
* Adds a session for this User.
*
* @param s
- * The session to associate with this user.
+ * The session to associate with this user.
*/
void addSession( HttpSession s );
@@ -198,7 +198,7 @@ public interface User extends Principal, Serializable {
* Removes a session for this User.
*
* @param s
- * The session to remove from being associated with this user.
+ * The session to remove from being associated with this user.
*/
void removeSession( HttpSession s );
@@ -238,7 +238,7 @@ public interface User extends Principal, Serializable {
* Checks if this user's account is assigned a particular role.
*
* @param role
- * the role for which to check
+ * the role for which to check
*
* @return true, if role has been assigned to user
*/
@@ -272,7 +272,7 @@ public interface User extends Principal, Serializable {
*
* A session may timeout prior to ESAPI's configuration setting due to
* the servlet container setting for session-timeout in web.xml. The
- * following is an example of a web.xml session-timeout set for one hour.
+ * following is an example of a web.xml session-timeout set for one hour.
*
*
* 60
@@ -292,9 +292,9 @@ public interface User extends Principal, Serializable {
* Login with password.
*
* @param password
- * the password
+ * the password
* @throws AuthenticationException
- * if login fails
+ * if login fails
*/
void loginWithPassword(String password) throws AuthenticationException;
@@ -307,9 +307,9 @@ public interface User extends Principal, Serializable {
* Removes a role from this user's account.
*
* @param role
- * the role to remove
+ * the role to remove
* @throws AuthenticationException
- * the authentication exception
+ * the authentication exception
*/
void removeRole(String role) throws AuthenticationException;
@@ -322,7 +322,7 @@ public interface User extends Principal, Serializable {
* @return the new CSRF token
*
* @throws AuthenticationException
- * the authentication exception
+ * the authentication exception
*/
String resetCSRFToken() throws AuthenticationException;
@@ -338,16 +338,16 @@ public interface User extends Principal, Serializable {
*
* @param expirationTime the new expiration time
*/
- void setExpirationTime(Date expirationTime);
+ void setExpirationTime(Date expirationTime);
- /**
+ /**
* Sets the roles for this account.
*
* @param roles
- * the new roles
+ * the new roles
*
* @throws AuthenticationException
- * the authentication exception
+ * the authentication exception
*/
void setRoles(Set roles) throws AuthenticationException;
@@ -363,80 +363,80 @@ public interface User extends Principal, Serializable {
*/
void unlock();
- /**
- * Verify that the supplied password matches the password for this user. This method
- * is typically used for "reauthentication" for the most sensitive functions, such
- * as transactions, changing email address, and changing other account information.
- *
- * @param password
- * the password that the user entered
- *
- * @return true, if the password passed in matches the account's password
- *
- * @throws EncryptionException
- */
- boolean verifyPassword(String password) throws EncryptionException;
-
- /**
- * Set the time of the last failed login for this user.
- *
- * @param lastFailedLoginTime the date and time when the user just failed to login correctly.
- */
- void setLastFailedLoginTime(Date lastFailedLoginTime);
-
- /**
- * Set the last remote host address used by this user.
- *
- * @param remoteHost The address of the user's current source host.
- */
- void setLastHostAddress(String remoteHost) throws AuthenticationHostException;
-
- /**
- * Set the time of the last successful login for this user.
- *
- * @param lastLoginTime the date and time when the user just successfully logged in.
- */
- void setLastLoginTime(Date lastLoginTime);
-
- /**
- * Set the time of the last password change for this user.
- *
- * @param lastPasswordChangeTime the date and time when the user just successfully changed his/her password.
- */
- void setLastPasswordChangeTime(Date lastPasswordChangeTime);
-
- /**
- * Returns the hashmap used to store security events for this user. Used by the
- * IntrusionDetector.
- */
- HashMap getEventMap();
-
-
- /**
- * The ANONYMOUS user is used to represent an unidentified user. Since there is
- * always a real user, the ANONYMOUS user is better than using null to represent
- * this.
- */
+ /**
+ * Verify that the supplied password matches the password for this user. This method
+ * is typically used for "reauthentication" for the most sensitive functions, such
+ * as transactions, changing email address, and changing other account information.
+ *
+ * @param password
+ * the password that the user entered
+ *
+ * @return true, if the password passed in matches the account's password
+ *
+ * @throws EncryptionException
+ */
+ boolean verifyPassword(String password) throws EncryptionException;
+
+ /**
+ * Set the time of the last failed login for this user.
+ *
+ * @param lastFailedLoginTime the date and time when the user just failed to login correctly.
+ */
+ void setLastFailedLoginTime(Date lastFailedLoginTime);
+
+ /**
+ * Set the last remote host address used by this user.
+ *
+ * @param remoteHost The address of the user's current source host.
+ */
+ void setLastHostAddress(String remoteHost) throws AuthenticationHostException;
+
+ /**
+ * Set the time of the last successful login for this user.
+ *
+ * @param lastLoginTime the date and time when the user just successfully logged in.
+ */
+ void setLastLoginTime(Date lastLoginTime);
+
+ /**
+ * Set the time of the last password change for this user.
+ *
+ * @param lastPasswordChangeTime the date and time when the user just successfully changed his/her password.
+ */
+ void setLastPasswordChangeTime(Date lastPasswordChangeTime);
+
+ /**
+ * Returns the hashmap used to store security events for this user. Used by the
+ * IntrusionDetector.
+ */
+ HashMap getEventMap();
+
+
+ /**
+ * The ANONYMOUS user is used to represent an unidentified user. Since there is
+ * always a real user, the ANONYMOUS user is better than using null to represent
+ * this.
+ */
User ANONYMOUS = new User() {
- private static final long serialVersionUID = -1850916950784965502L;
+ private static final long serialVersionUID = -1850916950784965502L;
- private String csrfToken = "";
- private Set