本文整理汇总了Java中org.owasp.esapi.ESAPI类的典型用法代码示例。如果您正苦于以下问题:Java ESAPI类的具体用法?Java ESAPI怎么用?Java ESAPI使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ESAPI类属于org.owasp.esapi包,在下文中一共展示了ESAPI类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: doGet
import org.owasp.esapi.ESAPI; //导入依赖的package包/类
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
Cookie cookie = new Cookie("name", unknown());
cookie.setValue(req.getParameter("p") + "x");
resp.setHeader("header", req.getParameter("h1"));
resp.addHeader("header", unknown());
callCookieSink(req.getParameter("h2"));
String encoded = ESAPI.encoder().encodeForURL(req.getParameter("h3"));
resp.addHeader("header", ESAPI.encoder().decodeFromURL(encoded));
// false positives
String safe = "x".concat("y");
Cookie safeCookie = new Cookie("name", safe);
safeCookie.setValue(safe + "x");
resp.setHeader("header", safe);
resp.addHeader("header", encoded.concat(safe));
HttpServletResponseWrapper resWrapper = new HttpServletResponseWrapper(resp);
resWrapper.setHeader("header2",req.getParameter("a"));
resWrapper.addHeader("header3",req.getParameter("b"));
}
示例2: setUp
import org.owasp.esapi.ESAPI; //导入依赖的package包/类
/**
* {@inheritDoc}
* @throws Exception
*/
protected void setUp() throws Exception {
//override default log configuration in ESAPI.properties to use Log4JLogFactory
UnitTestSecurityConfiguration tmpConfig = new UnitTestSecurityConfiguration((DefaultSecurityConfiguration) ESAPI.securityConfiguration());
tmpConfig.setLogImplementation( Log4JLogFactory.class.getName() );
ESAPI.override(tmpConfig);
//This ensures a clean logger between tests
testLogger = ESAPI.getLogger( "test ExampleExtendedLog4JLogFactory: " + testCount++ );
System.out.println("Test ExampleExtendedLog4JLogFactory logger: " + testLogger);
//declare this one as Log4JLogger to be able to use Log4J logging methods
log4JLogger = (Log4JLogger)ESAPI.getLogger( "test Log4JLogFactory: " + testCount);
System.out.println("Test Log4JLogFactory logger: " + log4JLogger);
}
示例3: initializeESAPI
import org.owasp.esapi.ESAPI; //导入依赖的package包/类
/**
* Initializes the OWASPI ESAPI library.
*/
protected static void initializeESAPI() {
Logger log = getLogger();
String systemPropertyKey = "org.owasp.esapi.SecurityConfiguration";
String opensamlConfigImpl = ESAPISecurityConfig.class.getName();
String currentValue = System.getProperty(systemPropertyKey);
if (currentValue == null || currentValue.isEmpty()) {
log.debug("Setting ESAPI SecurityConfiguration impl to OpenSAML internal class: {}", opensamlConfigImpl);
System.setProperty(systemPropertyKey, opensamlConfigImpl);
// We still need to call ESAPI.initialize() despite setting the system property, b/c within the ESAPI class
// the property is only evaluated once in a static initializer and stored. The initialize method however
// does overwrite the statically-set value from the system property. But still set the system property for
// consistency, so other callers can see what has been set.
ESAPI.initialize(opensamlConfigImpl);
} else {
log.debug("ESAPI SecurityConfiguration impl was already set non-null and non-empty via system property, leaving existing value in place: {}",
currentValue);
}
}
示例4: validate
import org.owasp.esapi.ESAPI; //导入依赖的package包/类
/**
* The idea is to do minimal validation on inputs.
*/
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
//
boolean validName = false, validEmail = false;
try {
validName = ESAPI.validator().isValidInput("TestForm_name", name, "name", 20, false);
validEmail = ESAPI.validator().isValidInput("TestForm_email", email, "email", 45, false);
} catch (IntrusionException e) {
log.severe(e.getMessage());
}
if (!validName) errors.add("name", new ActionMessage("TestForm.name.invalid"));
if (!validEmail) errors.add("email", new ActionMessage("TestForm.email.invalid"));
return errors;
}
示例5: putArticle
import org.owasp.esapi.ESAPI; //导入依赖的package包/类
@PostMapping("/putArticle")
@ResponseBody
public String putArticle(@RequestParam("artical") String artical, HttpServletRequest request) throws ValidationException {
String safeArtical = ESAPI.validator().getValidSafeHTML("htmlInput", artical, 1000, true);
return "{status:ok}";
}
示例6: populateVelocityContext
import org.owasp.esapi.ESAPI; //导入依赖的package包/类
/**
* Populate the Velocity context instance which will be used to render the POST body.
*
* @param velocityContext the Velocity context instance to populate with data
* @param messageContext the SAML message context source of data
* @param endpointURL endpoint URL to which to encode message
* @throws MessageEncodingException thrown if there is a problem encoding the message
*/
protected void populateVelocityContext(VelocityContext velocityContext, SAMLMessageContext messageContext,
String endpointURL) throws MessageEncodingException {
Encoder esapiEncoder = ESAPI.encoder();
String encodedEndpointURL = esapiEncoder.encodeForHTMLAttribute(endpointURL);
log.debug("Encoding action url of '{}' with encoded value '{}'", endpointURL, encodedEndpointURL);
velocityContext.put("action", encodedEndpointURL);
velocityContext.put("binding", getBindingURI());
log.debug("Marshalling and Base64 encoding SAML message");
if (messageContext.getOutboundSAMLMessage().getDOM() == null) {
marshallMessage(messageContext.getOutboundSAMLMessage());
}
try {
String messageXML = XMLHelper.nodeToString(messageContext.getOutboundSAMLMessage().getDOM());
String encodedMessage = Base64.encodeBytes(messageXML.getBytes("UTF-8"), Base64.DONT_BREAK_LINES);
if (messageContext.getOutboundSAMLMessage() instanceof RequestAbstractType) {
velocityContext.put("SAMLRequest", encodedMessage);
} else if (messageContext.getOutboundSAMLMessage() instanceof StatusResponseType) {
velocityContext.put("SAMLResponse", encodedMessage);
} else {
throw new MessageEncodingException(
"SAML message is neither a SAML RequestAbstractType or StatusResponseType");
}
} catch (UnsupportedEncodingException e) {
log.error("UTF-8 encoding is not supported, this VM is not Java compliant.");
throw new MessageEncodingException("Unable to encode message, UTF-8 encoding is not supported");
}
String relayState = messageContext.getRelayState();
if (checkRelayState(relayState)) {
String encodedRelayState = esapiEncoder.encodeForHTMLAttribute(relayState);
log.debug("Setting RelayState parameter to: '{}', encoded as '{}'", relayState, encodedRelayState);
velocityContext.put("RelayState", encodedRelayState);
}
}
示例7: stripXSS
import org.owasp.esapi.ESAPI; //导入依赖的package包/类
private String stripXSS(String value) {
if (value != null) {
// NOTE: It's highly recommended to use the ESAPI library and uncomment the following line to
// avoid encoded attacks.
value = ESAPI.encoder().canonicalize(value);
// Avoid null characters
value = value.replaceAll("\0", "");
// Remove all sections that match a pattern
for (Pattern scriptPattern : patterns){
value = scriptPattern.matcher(value).replaceAll("");
}
}
return value;
}
示例8: contextInitialized
import org.owasp.esapi.ESAPI; //导入依赖的package包/类
public void contextInitialized(ServletContextEvent event) {
/*
* Suppress noisy messages output by the ESAPI library. For more detail:
* https://stackoverflow.com/questions/45857064/how-to-suppress-messages-output-by-esapi-library
*/
PrintStream printStream = null;
OutputStream outputStream = null;
PrintStream original = System.out;
try {
outputStream = new OutputStream() {
public void write(int b) {
// Do nothing
}
};
printStream = new PrintStream(outputStream);
System.setOut(printStream);
System.setErr(printStream);
ESAPI.encoder();
} catch (Exception e) {
// Do nothing
} finally {
System.setOut(original);
Closer.close(printStream, outputStream);
}
}
示例9: decrypt
import org.owasp.esapi.ESAPI; //导入依赖的package包/类
@Override
public String decrypt(String cryptedText)
{
String clearText = null;
try
{
CipherText cipherText = CipherText.fromPortableSerializedBytes(Base64.decode(cryptedText));
clearText = ESAPI.encryptor().decrypt(cipherText).toString();
}
catch (EncryptionException e)
{
LOG.error("EsapiEncryptor.decrypt: "+e.getMessage(), e);
}
return clearText;
}
示例10: getProperty
import org.owasp.esapi.ESAPI; //导入依赖的package包/类
/**
* {@inheritDoc}
*
* @throws EncryptionRuntimeException Thrown if decryption fails.
*/
@Override
public synchronized String getProperty(String key) throws EncryptionRuntimeException {
int progressMark = 0;
try {
String encryptedValue = super.getProperty(key);
if(encryptedValue==null)
return null;
progressMark = 0;
byte[] serializedCiphertext = ESAPI.encoder().decodeFromBase64(encryptedValue);
progressMark++;
CipherText restoredCipherText = CipherText.fromPortableSerializedBytes(serializedCiphertext);
progressMark++;
PlainText plaintext = ESAPI.encryptor().decrypt(restoredCipherText);
return plaintext.toString();
} catch (Exception e) {
throw new EncryptionRuntimeException("Property retrieval failure",
"Couldn't retrieve encrypted property for property " + key +
GET_ERROR_MESSAGES[progressMark], e);
}
}
示例11: printResults
import org.owasp.esapi.ESAPI; //导入依赖的package包/类
public static void printResults(String query, int[] counts, HttpServletResponse response) throws IOException{
PrintWriter out = response.getWriter();
out.write("<!DOCTYPE html>\n<html>\n<body>\n<p>");
out.write("For query: " + ESAPI.encoder().encodeForHTML(query) + "<br>");
try {
if(counts.length > 0){
if(counts[0] == Statement.SUCCESS_NO_INFO){
out.write("The SQL query was processed successfully but the number of rows affected is unknown.");
System.out.println("The SQL query was processed successfully but the number of rows affected is unknown.");
}else if(counts[0] == Statement.EXECUTE_FAILED){
out.write("The SQL query failed to execute successfully and occurs only if a driver continues to process commands after a command fails");
System.out.println("The SQL query failed to execute successfully and occurs only if a driver continues to process commands after a command fails");
}else{
out.write("The number of affected rows are: " + counts[0]);
System.out.println("The number of affected rows are: " + counts[0]);
}
}
} finally {
out.write("</p>\n</body>\n</html>");
}
}
示例12: testUpdate
import org.owasp.esapi.ESAPI; //导入依赖的package包/类
/**
* Test of update method, of class org.owasp.esapi.AccessReferenceMap.
*
* @throws AuthenticationException
* the authentication exception
* @throws EncryptionException
*/
public void testUpdate() throws AuthenticationException, EncryptionException {
System.out.println("update");
IntegerAccessReferenceMap arm = new IntegerAccessReferenceMap();
Authenticator auth = ESAPI.authenticator();
String pass = auth.generateStrongPassword();
User u = auth.createUser( "armUpdate", pass, pass );
// test to make sure update returns something
arm.update(auth.getUserNames());
String indirect = arm.getIndirectReference( u.getAccountName() );
if ( indirect == null ) fail();
// test to make sure update removes items that are no longer in the list
auth.removeUser( u.getAccountName() );
arm.update(auth.getUserNames());
indirect = arm.getIndirectReference( u.getAccountName() );
if ( indirect != null ) fail();
// test to make sure old indirect reference is maintained after an update
arm.update(auth.getUserNames());
String newIndirect = arm.getIndirectReference( u.getAccountName() );
assertEquals(indirect, newIndirect);
}
示例13: loadESAPIPreferredJCEProvider
import org.owasp.esapi.ESAPI; //导入依赖的package包/类
/**
* Load the preferred JCE provider for ESAPI based on the <b>ESAPI.properties</b>
* property {@code Encryptor.PreferredJCEProvider}. If this property is null
* (i.e., unset) or set to an empty string, then no JCE provider is inserted
* at the "preferred" position and thus the Java VM continues to use whatever
* the default it was using for this (generally specified in the file
* {@code $JAVA_HOME/jre/security/java.security}).
* @return The actual preference position at which the provider was added,
* (which is expected to be 1) or -1 if the provider was not added
* because it is already installed at some other position. -1 is also
* returned if the {@code Encryptor.PreferredJCEProvider} was not set
* or set to an empty string, i.e., if the application <i>has</i> no
* preferred JCE provider.
* @exception NoSuchProviderException - thrown if the provider class
* could not be loaded or added to the {@code SecurityManager} or
* any other reason for failure.
* @see <a href="http://owasp-esapi-java.googlecode.com/svn/trunk/documentation/esapi4java-core-2.0-symmetric-crypto-user-guide.htm">
* ESAPI 2.0 Symmetric Encryption User Guide</a>
*/
public static int loadESAPIPreferredJCEProvider() throws NoSuchProviderException
{
String prefJCEProvider =
ESAPI.securityConfiguration().getPreferredJCEProvider();
try {
// If unset or set to empty string, then don't try to change it.
if ( prefJCEProvider == null || prefJCEProvider.trim().length() == 0) {
// Always log, per NSA suggestion.
logger.always(Logger.SECURITY_AUDIT, "No Encryptor.PreferredJCEProvider specified.");
return -1; // Unchanged; it is, whatever it is.
} else {
return insertProviderAt(prefJCEProvider, 1);
}
} catch (NoSuchProviderException ex) {
// Will already have logged with exception msg.
String msg = "failed to load *preferred* " + "JCE crypto provider, " + prefJCEProvider;
logger.always(Logger.SECURITY_AUDIT, msg); // Per NSA suggestion.
logger.error(Logger.SECURITY_FAILURE, msg);
throw ex;
}
}
示例14: hash
import org.owasp.esapi.ESAPI; //导入依赖的package包/类
/**
* {@inheritDoc}
*
* Hashes the data using the specified algorithm and the Java MessageDigest class. This method
* first adds the salt, a separator (":"), and the data, and then rehashes the specified number of iterations
* in order to help strengthen weak passwords.
*/
public String hash(String plaintext, String salt, int iterations) throws EncryptionException {
byte[] bytes = null;
try {
MessageDigest digest = MessageDigest.getInstance(hashAlgorithm);
digest.reset();
digest.update(ESAPI.securityConfiguration().getMasterSalt());
digest.update(salt.getBytes(encoding));
digest.update(plaintext.getBytes(encoding));
// rehash a number of times to help strengthen weak passwords
bytes = digest.digest();
for (int i = 0; i < iterations; i++) {
digest.reset();
bytes = digest.digest(bytes);
}
String encoded = ESAPI.encoder().encodeForBase64(bytes,false);
return encoded;
} catch (NoSuchAlgorithmException e) {
throw new EncryptionException("Internal error", "Can't find hash algorithm " + hashAlgorithm, e);
} catch (UnsupportedEncodingException ex) {
throw new EncryptionException("Internal error", "Can't find encoding for " + encoding, ex);
}
}
示例15: testAddEvent
import org.owasp.esapi.ESAPI; //导入依赖的package包/类
/**
* Test of addEvent method, of class org.owasp.esapi.IntrusionDetector.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testAddEvent() throws AuthenticationException {
System.out.println("addEvent");
String username = ESAPI.randomizer().getRandomString(8, EncoderConstants.CHAR_ALPHANUMERICS);
Authenticator auth = ESAPI.authenticator();
User user = auth.createUser(username, "addEvent", "addEvent");
user.enable();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
ESAPI.httpUtilities().setCurrentHTTP(request, response);
user.loginWithPassword("addEvent");
// Now generate some events to disable user account
for ( int i = 0; i < ESAPI.securityConfiguration().getQuota("event.test").count; i++ ) {
ESAPI.intrusionDetector().addEvent("test", "test message");
}
assertFalse( user.isEnabled() );
}