Java Code Examples for javax.servlet.http.HttpServletRequest#getHeaders()

The following examples show how to use javax.servlet.http.HttpServletRequest#getHeaders() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@PostConstruct
public void init() {
    entries = new ArrayList<>();
    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
    HttpServletRequest request = (HttpServletRequest) context.getRequest();
    
    Enumeration<String> namesIt = request.getHeaderNames();
    while (namesIt.hasMoreElements()) {
        String name = namesIt.nextElement();
        Enumeration<String> valueIt = request.getHeaders(name);
        while (valueIt.hasMoreElements()) {
            String value = valueIt.nextElement();
            entries.add(new HeaderEntry(name, value));
        }
    }
}
 
Example 2
/**
 * 解析head中的token
 * @param request
 */
private String extractHeaderToken(HttpServletRequest request) {
    Enumeration<String> headers = request.getHeaders(CommonConstant.TOKEN_HEADER);
    while (headers.hasMoreElements()) {
        String value = headers.nextElement();
        if ((value.toLowerCase().startsWith(CommonConstant.BEARER_TYPE))) {
            String authHeaderValue = value.substring(CommonConstant.BEARER_TYPE.length()).trim();
            int commaIndex = authHeaderValue.indexOf(',');
            if (commaIndex > 0) {
                authHeaderValue = authHeaderValue.substring(0, commaIndex);
            }
            return authHeaderValue;
        }
    }
    return null;
}
 
Example 3
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
	
		String param = "";
		java.util.Enumeration<String> headers = request.getHeaders("Referer");
		
		if (headers != null && headers.hasMoreElements()) {
			param = headers.nextElement(); // just grab first element
		}
		
		// URL Decode the header value since req.getHeaders() doesn't. Unlike req.getParameters().
		param = java.net.URLDecoder.decode(param, "UTF-8");

		String bar = new Test().doSomething(request, param);
		
response.setHeader("X-XSS-Protection", "0");
		response.getWriter().println(bar);
	}
 
Example 4
Source Project: MaxKey   File: BearerTokenExtractor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Extract the OAuth bearer token from a header.
 * 
 * @param request The request.
 * @return The token, or null if no OAuth authorization header was supplied.
 */
protected String extractHeaderToken(HttpServletRequest request) {
	Enumeration<String> headers = request.getHeaders("Authorization");
	while (headers.hasMoreElements()) { // typically there is only one (most servers enforce that)
		String value = headers.nextElement();
		if ((value.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) {
			String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
			// Add this here for the auth details later. Would be better to change the signature of this method.
			request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE,
			value.substring(0, OAuth2AccessToken.BEARER_TYPE.length()).trim());
			int commaIndex = authHeaderValue.indexOf(',');
			if (commaIndex > 0) {
				authHeaderValue = authHeaderValue.substring(0, commaIndex);
			}
			return authHeaderValue;
		}
	}

	return null;
}
 
Example 5
Source Project: Tomcat7.0.67   File: WebSocketServlet.java    License: Apache License 2.0 5 votes vote down vote up
private List<String> getTokensFromHeader(HttpServletRequest req,
        String headerName) {
    List<String> result = new ArrayList<String>();

    Enumeration<String> headers = req.getHeaders(headerName);
    while (headers.hasMoreElements()) {
        String header = headers.nextElement();
        String[] tokens = header.split(",");
        for (String token : tokens) {
            result.add(token.trim());
        }
    }
    return result;
}
 
Example 6
private void echo(HttpServletRequest request, HttpServletResponse response) throws IOException {
	response.setStatus(HttpServletResponse.SC_OK);
	response.setContentType(request.getContentType());
	response.setContentLength(request.getContentLength());
	for (Enumeration<String> e1 = request.getHeaderNames(); e1.hasMoreElements();) {
		String headerName = e1.nextElement();
		for (Enumeration<String> e2 = request.getHeaders(headerName); e2.hasMoreElements();) {
			String headerValue = e2.nextElement();
			response.addHeader(headerName, headerValue);
		}
	}
	StreamUtils.copy(request.getInputStream(), response.getOutputStream());
}
 
Example 7
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
	
		String param = "";
		java.util.Enumeration<String> headers = request.getHeaders("BenchmarkTest01217");
		
		if (headers != null && headers.hasMoreElements()) {
			param = headers.nextElement(); // just grab first element
		}
		
		// URL Decode the header value since req.getHeaders() doesn't. Unlike req.getParameters().
		param = java.net.URLDecoder.decode(param, "UTF-8");

		String bar = new Test().doSomething(request, param);
		
		String sql = "SELECT * from USERS where USERNAME='foo' and PASSWORD='"+ bar +"'";
				
		try {
			java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
			statement.addBatch( sql );
			int[] counts = statement.executeBatch();
            org.owasp.benchmark.helpers.DatabaseHelper.printResults(sql, counts, response);
		} catch (java.sql.SQLException e) {
			if (org.owasp.benchmark.helpers.DatabaseHelper.hideSQLErrors) {
        		response.getWriter().println(
"Error processing request."
);
        		return;
        	}
			else throw new ServletException(e);
		}
	}
 
Example 8
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	response.setContentType("text/html;charset=UTF-8");

	String param = "";
	java.util.Enumeration<String> headers = request.getHeaders("BenchmarkTest00309");
	
	if (headers != null && headers.hasMoreElements()) {
		param = headers.nextElement(); // just grab first element
	}
	
	// URL Decode the header value since req.getHeaders() doesn't. Unlike req.getParameters().
	param = java.net.URLDecoder.decode(param, "UTF-8");
	
	
	String bar = "safe!";
	java.util.HashMap<String,Object> map92785 = new java.util.HashMap<String,Object>();
	map92785.put("keyA-92785", "a_Value"); // put some stuff in the collection
	map92785.put("keyB-92785", param); // put it in a collection
	map92785.put("keyC", "another_Value"); // put some stuff in the collection
	bar = (String)map92785.get("keyB-92785"); // get it back out
	bar = (String)map92785.get("keyA-92785"); // get safe value back out
	
	
	String cmd = org.owasp.benchmark.helpers.Utils.getInsecureOSCommandString(this.getClass().getClassLoader());
       
	String[] argsEnv = { bar };
	Runtime r = Runtime.getRuntime();

	try {
		Process p = r.exec(cmd, argsEnv);
		org.owasp.benchmark.helpers.Utils.printOSCommandResults(p, response);
	} catch (IOException e) {
		System.out.println("Problem executing cmdi - TestCase");
		response.getWriter().println(
		  org.owasp.esapi.ESAPI.encoder().encodeForHTML(e.getMessage())
		);
		return;
	}
}
 
Example 9
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");

		String param = "";
		java.util.Enumeration<String> headers = request.getHeaders("BenchmarkTest02095");
		
		if (headers != null && headers.hasMoreElements()) {
			param = headers.nextElement(); // just grab first element
		}
		
		// URL Decode the header value since req.getHeaders() doesn't. Unlike req.getParameters().
		param = java.net.URLDecoder.decode(param, "UTF-8");

		String bar = doSomething(request, param);
		
		String sql = "SELECT * from USERS where USERNAME='foo' and PASSWORD='"+ bar +"'";
				
		try {
			java.sql.Statement statement =  org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
			statement.execute( sql, java.sql.Statement.RETURN_GENERATED_KEYS );
            org.owasp.benchmark.helpers.DatabaseHelper.printResults(statement, sql, response);
		} catch (java.sql.SQLException e) {
			if (org.owasp.benchmark.helpers.DatabaseHelper.hideSQLErrors) {
        		response.getWriter().println(
"Error processing request."
);
        		return;
        	}
			else throw new ServletException(e);
		}
	}
 
Example 10
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");

		String param = "";
		java.util.Enumeration<String> headers = request.getHeaders("BenchmarkTest02088");
		
		if (headers != null && headers.hasMoreElements()) {
			param = headers.nextElement(); // just grab first element
		}
		
		// URL Decode the header value since req.getHeaders() doesn't. Unlike req.getParameters().
		param = java.net.URLDecoder.decode(param, "UTF-8");

		String bar = doSomething(request, param);
		
		String sql = "SELECT * from USERS where USERNAME=? and PASSWORD='"+ bar +"'";
				
		try {
			java.sql.Connection connection = org.owasp.benchmark.helpers.DatabaseHelper.getSqlConnection();
			java.sql.PreparedStatement statement = connection.prepareStatement( sql,
				java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY );
				statement.setString(1, "foo");
			statement.execute();
            org.owasp.benchmark.helpers.DatabaseHelper.printResults(statement, sql, response);
		} catch (java.sql.SQLException e) {
			if (org.owasp.benchmark.helpers.DatabaseHelper.hideSQLErrors) {
        		response.getWriter().println(
"Error processing request."
);
        		return;
        	}
			else throw new ServletException(e);
		}
	}
 
Example 11
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
	
		String param = "";
		java.util.Enumeration<String> names = request.getHeaderNames();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			
			if(org.owasp.benchmark.helpers.Utils.commonHeaders.contains(name)){
				continue;
			}
			
			java.util.Enumeration<String> values = request.getHeaders(name);
			if (values != null && values.hasMoreElements()) {
				param = name;
				break;
			}
		}
		// Note: We don't URL decode header names because people don't normally do that
		
		
		String bar;
		String guess = "ABC";
		char switchTarget = guess.charAt(2);
		
		// Simple case statement that assigns param to bar on conditions 'A', 'C', or 'D'
		switch (switchTarget) {
		  case 'A':
		        bar = param;
		        break;
		  case 'B': 
		        bar = "bobs_your_uncle";
		        break;
		  case 'C':
		  case 'D':        
		        bar = param;
		        break;
		  default:
		        bar = "bobs_your_uncle";
		        break;
		}
		
		
		// FILE URIs are tricky because they are different between Mac and Windows because of lack of standardization.
		// Mac requires an extra slash for some reason.
		String startURIslashes = "";
        if (System.getProperty("os.name").indexOf("Windows") != -1)
	        if (System.getProperty("os.name").indexOf("Windows") != -1)
	        	startURIslashes = "/";
	        else startURIslashes = "//";

		try {
			java.net.URI fileURI = new java.net.URI("file", null, startURIslashes 
				+ org.owasp.benchmark.helpers.Utils.testfileDir.replace('\\', java.io.File.separatorChar).replace(' ', '_') + bar, null, null);
			java.io.File fileTarget = new java.io.File(fileURI);
            response.getWriter().println(
"Access to file: '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(fileTarget.toString()) + "' created." 
);
            if (fileTarget.exists()) {
            response.getWriter().println(
" And file already exists."
);
            } else { response.getWriter().println(
" But file doesn't exist yet."
); }
		} catch (java.net.URISyntaxException e) {
			throw new ServletException(e);
		}
	}
 
Example 12
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
	
		String param = "";
		java.util.Enumeration<String> names = request.getHeaderNames();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			
			if(org.owasp.benchmark.helpers.Utils.commonHeaders.contains(name)){
				continue;
			}
			
			java.util.Enumeration<String> values = request.getHeaders(name);
			if (values != null && values.hasMoreElements()) {
				param = name;
				break;
			}
		}
		// Note: We don't URL decode header names because people don't normally do that
		
		
		String bar;
		String guess = "ABC";
		char switchTarget = guess.charAt(1); // condition 'B', which is safe
		
		// Simple case statement that assigns param to bar on conditions 'A', 'C', or 'D'
		switch (switchTarget) {
		  case 'A':
		        bar = param;
		        break;
		  case 'B': 
		        bar = "bob";
		        break;
		  case 'C':
		  case 'D':        
		        bar = param;
		        break;
		  default:
		        bar = "bob's your uncle";
		        break;
		}
		
		
		// javax.servlet.http.HttpSession.setAttribute(java.lang.String,java.lang.Object^)
		request.getSession().setAttribute( "userid", bar);
				
		response.getWriter().println(
		"Item: 'userid' with value: '" + org.owasp.benchmark.helpers.Utils.encodeForHTML(bar)
			+ "' saved in session."
);
	}
 
Example 13
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");

		String param = "";
		java.util.Enumeration<String> names = request.getHeaderNames();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			
			if(org.owasp.benchmark.helpers.Utils.commonHeaders.contains(name)){
				continue;
			}
			
			java.util.Enumeration<String> values = request.getHeaders(name);
			if (values != null && values.hasMoreElements()) {
				param = name;
				break;
			}
		}
		// Note: We don't URL decode header names because people don't normally do that

		String bar = doSomething(request, param);
		
		byte[] bytes = new byte[10];
		new java.util.Random().nextBytes(bytes);
        String rememberMeKey = org.owasp.esapi.ESAPI.encoder().encodeForBase64(bytes, true);

		String user = "Byron";
		String fullClassName = this.getClass().getName();
		String testCaseNumber = fullClassName.substring(fullClassName.lastIndexOf('.')+1+"BenchmarkTest".length());
		user+= testCaseNumber;
		
		String cookieName = "rememberMe" + testCaseNumber;
		
		boolean foundUser = false;
		javax.servlet.http.Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; !foundUser && i < cookies.length; i++) {
				javax.servlet.http.Cookie cookie = cookies[i];
				if (cookieName.equals(cookie.getName())) {
					if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
						foundUser = true;
					}
				}
			}
		}
		
		if (foundUser) {
			response.getWriter().println(
"Welcome back: " + user + "<br/>"
);
			
		} else {			
			javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
			rememberMe.setSecure(true);
//			rememberMe.setPath("/benchmark/" + this.getClass().getSimpleName());
			rememberMe.setPath(request.getRequestURI()); // i.e., set path to JUST this servlet 
														 // e.g., /benchmark/sql-01/BenchmarkTest01001
			request.getSession().setAttribute(cookieName, rememberMeKey);
			response.addCookie(rememberMe);
			response.getWriter().println(
				user + " has been remembered with cookie: " + rememberMe.getName() 
					+ " whose value is: " + rememberMe.getValue() + "<br/>"
			);
		}

		response.getWriter().println(
		"Weak Randomness Test java.util.Random.nextBytes() executed"
		);
	}
 
Example 14
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	response.setContentType("text/html;charset=UTF-8");

	String param = "";
	java.util.Enumeration<String> headers = request.getHeaders("BenchmarkTest00305");
	
	if (headers != null && headers.hasMoreElements()) {
		param = headers.nextElement(); // just grab first element
	}
	
	// URL Decode the header value since req.getHeaders() doesn't. Unlike req.getParameters().
	param = java.net.URLDecoder.decode(param, "UTF-8");
	
	
	// Chain a bunch of propagators in sequence
	String a99928 = param; //assign
	StringBuilder b99928 = new StringBuilder(a99928);  // stick in stringbuilder
	b99928.append(" SafeStuff"); // append some safe content
	b99928.replace(b99928.length()-"Chars".length(),b99928.length(),"Chars"); //replace some of the end content
	java.util.HashMap<String,Object> map99928 = new java.util.HashMap<String,Object>();
	map99928.put("key99928", b99928.toString()); // put in a collection
	String c99928 = (String)map99928.get("key99928"); // get it back out
	String d99928 = c99928.substring(0,c99928.length()-1); // extract most of it
	String e99928 = new String( org.apache.commons.codec.binary.Base64.decodeBase64(
	    org.apache.commons.codec.binary.Base64.encodeBase64( d99928.getBytes() ) )); // B64 encode and decode it
	String f99928 = e99928.split(" ")[0]; // split it on a space
	org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing();
	String g99928 = "barbarians_at_the_gate";  // This is static so this whole flow is 'safe'
	String bar = thing.doSomething(g99928); // reflection
	
	
	String cmd = "";	
	String a1 = "";
	String a2 = "";
	String[] args = null;
	String osName = System.getProperty("os.name");
	
	if (osName.indexOf("Windows") != -1) {
       	a1 = "cmd.exe";
       	a2 = "/c";
       	cmd = "echo ";
       	args = new String[]{a1, a2, cmd, bar};
       } else {
       	a1 = "sh";
       	a2 = "-c";
       	cmd = org.owasp.benchmark.helpers.Utils.getOSCommandString("ls ");
       	args = new String[]{a1, a2, cmd + bar};
       }
       
       String[] argsEnv = { "foo=bar" };
       
	Runtime r = Runtime.getRuntime();

	try {
		Process p = r.exec(args, argsEnv, new java.io.File(System.getProperty("user.dir")));
		org.owasp.benchmark.helpers.Utils.printOSCommandResults(p, response);
	} catch (IOException e) {
		System.out.println("Problem executing cmdi - TestCase");
		response.getWriter().println(
		  org.owasp.esapi.ESAPI.encoder().encodeForHTML(e.getMessage())
		);
		return;
	}
}
 
Example 15
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");

		String param = "";
		java.util.Enumeration<String> names = request.getHeaderNames();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			
			if(org.owasp.benchmark.helpers.Utils.commonHeaders.contains(name)){
				continue;
			}
			
			java.util.Enumeration<String> values = request.getHeaders(name);
			if (values != null && values.hasMoreElements()) {
				param = name;
				break;
			}
		}
		// Note: We don't URL decode header names because people don't normally do that

		String bar = doSomething(request, param);
		
		try {
			double rand = java.security.SecureRandom.getInstance("SHA1PRNG").nextDouble();
			
			String rememberMeKey = Double.toString(rand).substring(2); // Trim off the 0. at the front.
			
			String user = "SafeDonna";
			String fullClassName = this.getClass().getName();
			String testCaseNumber = fullClassName.substring(fullClassName.lastIndexOf('.')+1+"BenchmarkTest".length());
			user+= testCaseNumber;
			
			String cookieName = "rememberMe" + testCaseNumber;
			
			boolean foundUser = false;
			javax.servlet.http.Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				for (int i = 0; !foundUser && i < cookies.length; i++) {
					javax.servlet.http.Cookie cookie = cookies[i];
					if (cookieName.equals(cookie.getName())) {
						if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
							foundUser = true;
						}
					}
				}
			}

			
			if (foundUser) {
				response.getWriter().println(
"Welcome back: " + user + "<br/>"
);
			
			} else {			
				javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
				rememberMe.setSecure(true);
	//			rememberMe.setPath("/benchmark/" + this.getClass().getSimpleName());
				rememberMe.setPath(request.getRequestURI()); // i.e., set path to JUST this servlet 
															 // e.g., /benchmark/sql-01/BenchmarkTest01001
				request.getSession().setAttribute(cookieName, rememberMeKey);
response.addCookie(rememberMe);
response.getWriter().println(
user + " has been remembered with cookie: " + rememberMe.getName() 
						+ " whose value is: " + rememberMe.getValue() + "<br/>"
);
			}
	    } catch (java.security.NoSuchAlgorithmException e) {
			System.out.println("Problem executing SecureRandom.nextDouble() - TestCase");
			throw new ServletException(e);
	    }
		response.getWriter().println(
"Weak Randomness Test java.security.SecureRandom.nextDouble() executed"
);
	}
 
Example 16
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
	
		String param = "";
		java.util.Enumeration<String> headers = request.getHeaders("BenchmarkTest01185");
		
		if (headers != null && headers.hasMoreElements()) {
			param = headers.nextElement(); // just grab first element
		}
		
		// URL Decode the header value since req.getHeaders() doesn't. Unlike req.getParameters().
		param = java.net.URLDecoder.decode(param, "UTF-8");

		String bar = new Test().doSomething(request, param);
		
		byte[] input = new byte[1000];
		String str = "?";
		Object inputParam = param;
		if (inputParam instanceof String) str = ((String) inputParam);
		if (inputParam instanceof java.io.InputStream) {
			int i = ((java.io.InputStream) inputParam).read(input);
			if (i == -1) {
				response.getWriter().println(
"This input source requires a POST, not a GET. Incompatible UI for the InputStream source."
);
				return;
			}			
			str = new String(input, 0, i);
		}
		if ("".equals(str)) str="No cookie value supplied";
		javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie("SomeCookie", str);
		
		cookie.setSecure(false);
//		cookie.setPath("/benchmark/" + this.getClass().getSimpleName());
		cookie.setPath(request.getRequestURI()); // i.e., set path to JUST this servlet
												 // e.g., /benchmark/sql-01/BenchmarkTest01001
		response.addCookie(cookie);

        response.getWriter().println(
			"Created cookie: 'SomeCookie': with value: '"
			+ org.owasp.esapi.ESAPI.encoder().encodeForHTML(str) + "' and secure flag set to: false"
		);
	}
 
Example 17
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
	
		String param = "";
		java.util.Enumeration<String> headers = request.getHeaders("BenchmarkTest00274");
		
		if (headers != null && headers.hasMoreElements()) {
			param = headers.nextElement(); // just grab first element
		}
		
		// URL Decode the header value since req.getHeaders() doesn't. Unlike req.getParameters().
		param = java.net.URLDecoder.decode(param, "UTF-8");
		
		
		String bar = org.springframework.web.util.HtmlUtils.htmlEscape(param);
		
		
		try {
		    java.util.Properties benchmarkprops = new java.util.Properties();
		    benchmarkprops.load(this.getClass().getClassLoader().getResourceAsStream("benchmark.properties"));
			String algorithm = benchmarkprops.getProperty("hashAlg1", "SHA512");
			java.security.MessageDigest md = java.security.MessageDigest.getInstance(algorithm);
			byte[] input = { (byte)'?' };
			Object inputParam = bar;
			if (inputParam instanceof String) input = ((String) inputParam).getBytes();
			if (inputParam instanceof java.io.InputStream) {
				byte[] strInput = new byte[1000];
				int i = ((java.io.InputStream) inputParam).read(strInput);
				if (i == -1) {
					response.getWriter().println(
"This input source requires a POST, not a GET. Incompatible UI for the InputStream source."
);
					return;
				}
				input = java.util.Arrays.copyOf(strInput, i);
			}			
			md.update(input);
			
			byte[] result = md.digest();
			java.io.File fileTarget = new java.io.File(
					new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir),"passwordFile.txt");
			java.io.FileWriter fw = new java.io.FileWriter(fileTarget,true); //the true will append the new data
			    fw.write("hash_value=" + org.owasp.esapi.ESAPI.encoder().encodeForBase64(result, true) + "\n");
			fw.close();
			response.getWriter().println(
"Sensitive value '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(input)) + "' hashed and stored<br/>"
);

		} catch (java.security.NoSuchAlgorithmException e) {
			System.out.println("Problem executing hash - TestCase");
			throw new ServletException(e);
		}
		
		response.getWriter().println(
"Hash Test java.security.MessageDigest.getInstance(java.lang.String) executed"
);
	}
 
Example 18
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// some code
		response.setContentType("text/html;charset=UTF-8");
		

		String param = "";
		java.util.Enumeration<String> headers = request.getHeaders("BenchmarkTest00016");
		
		if (headers != null && headers.hasMoreElements()) {
			param = headers.nextElement(); // just grab first element
		}
		
		// URL Decode the header value since req.getHeaders() doesn't. Unlike req.getParameters().
		param = java.net.URLDecoder.decode(param, "UTF-8");

		
		byte[] input = new byte[1000];
		String str = "?";
		Object inputParam = param;
		if (inputParam instanceof String) str = ((String) inputParam);
		if (inputParam instanceof java.io.InputStream) {
			int i = ((java.io.InputStream) inputParam).read(input);
			if (i == -1) {
				response.getWriter().println(
"This input source requires a POST, not a GET. Incompatible UI for the InputStream source."
);
				return;
			}			
			str = new String(input, 0, i);
		}
		if ("".equals(str)) str="No cookie value supplied";
		javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie("SomeCookie", str);
		
		cookie.setSecure(true);
//		cookie.setPath("/benchmark/" + this.getClass().getSimpleName());
		cookie.setPath(request.getRequestURI()); // i.e., set path to JUST this servlet
												 // e.g., /benchmark/sql-01/BenchmarkTest01001
		response.addCookie(cookie);

		response.getWriter().println(
			"Created cookie: 'SomeCookie': with value: '"
			+ org.owasp.esapi.ESAPI.encoder().encodeForHTML(str) + "' and secure flag set to: true"
		);
	}
 
Example 19
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	response.setContentType("text/html;charset=UTF-8");

	String param = "";
	java.util.Enumeration<String> headers = request.getHeaders("BenchmarkTest00293");
	
	if (headers != null && headers.hasMoreElements()) {
		param = headers.nextElement(); // just grab first element
	}
	
	// URL Decode the header value since req.getHeaders() doesn't. Unlike req.getParameters().
	param = java.net.URLDecoder.decode(param, "UTF-8");
	
	
	String bar = "";
	if (param != null) {
		bar = new String( org.apache.commons.codec.binary.Base64.decodeBase64(
		org.apache.commons.codec.binary.Base64.encodeBase64( param.getBytes() ) ));
	}
	
	
	java.util.List<String> argList = new java.util.ArrayList<String>();
	
	String osName = System.getProperty("os.name");
       if (osName.indexOf("Windows") != -1) {
       	argList.add("cmd.exe");
       	argList.add("/c");
       } else {
       	argList.add("sh");
       	argList.add("-c");
       }
       argList.add("echo " + bar);

	ProcessBuilder pb = new ProcessBuilder();

	pb.command(argList);
	
	try {
		Process p = pb.start();
		org.owasp.benchmark.helpers.Utils.printOSCommandResults(p, response);
	} catch (IOException e) {
		System.out.println("Problem executing cmdi - java.lang.ProcessBuilder(java.util.List) Test Case");
           throw new ServletException(e);
	}
}
 
Example 20
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
	
		String param = "";
		java.util.Enumeration<String> names = request.getHeaderNames();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			
			if(org.owasp.benchmark.helpers.Utils.commonHeaders.contains(name)){
				continue;
			}
			
			java.util.Enumeration<String> values = request.getHeaders(name);
			if (values != null && values.hasMoreElements()) {
				param = name;
				break;
			}
		}
		// Note: We don't URL decode header names because people don't normally do that

		String bar = new Test().doSomething(request, param);
		
		int r = new java.util.Random().nextInt();
		String rememberMeKey = Integer.toString(r);
		
		String user = "Ingrid";
		String fullClassName = this.getClass().getName();
		String testCaseNumber = fullClassName.substring(fullClassName.lastIndexOf('.')+1+"BenchmarkTest".length());
		user+= testCaseNumber;
		
		String cookieName = "rememberMe" + testCaseNumber;
		
		boolean foundUser = false;
		javax.servlet.http.Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; !foundUser && i < cookies.length; i++) {
				javax.servlet.http.Cookie cookie = cookies[i];
				if (cookieName.equals(cookie.getName())) {
					if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
						foundUser = true;
					}
				}
			}
		}
		
		if (foundUser) {
			response.getWriter().println(
"Welcome back: " + user + "<br/>"
);
		} else {			
			javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
			rememberMe.setSecure(true);
//			rememberMe.setPath("/benchmark/" + this.getClass().getSimpleName());
			rememberMe.setPath(request.getRequestURI()); // i.e., set path to JUST this servlet 
														 // e.g., /benchmark/sql-01/BenchmarkTest01001
			request.getSession().setAttribute(cookieName, rememberMeKey);
			response.addCookie(rememberMe);
			response.getWriter().println(
				user + " has been remembered with cookie: " + rememberMe.getName() 
					+ " whose value is: " + rememberMe.getValue() + "<br/>"
			);
		}
				
		response.getWriter().println(
"Weak Randomness Test java.util.Random.nextInt() executed"
);

	}