Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Several subsystems exist for the purpose of outputting data. An HTML renderer is one common subsystem for displaying output. Data sent to an output subsystem may appear to originate from a trusted source. However, it is dangerous to assume that output sanitization is unnecessary, because such data may indirectly originate from an untrusted source and may include malicious content. Failure to properly sanitize data passed to an output subsystem can enable allow several types of attacks. For example, HTML renderers are prone to HTML injection and cross-site scripting (XSS) attacks [OWASP 2011] attacks. Output sanitization to prevent such attacks is as vital as input sanitization.

As with input validation, normalize data should be normalized before sanitizing it for malicious characters. Properly encode all output characters other than those known to be safe to avoid vulnerabilities caused by data that bypasses validation. See IDS01-J. Normalize strings before validating them for more information.

...

This compliant solution defines a ValidateOutput class that normalizes the output to a known character set, performs output sanitization using a whitelist, and encodes any nonspecified unspecified data values to enforce a double-checking mechanism. Note that the required whitelisting patterns may can vary according to the specific needs of different fields [OWASP 2008].

Code Block
bgColor#ccccff
public class ValidateOutput {
  // Allows only alphanumeric characters and spaces
  private static final Pattern pattern = Pattern.compile("^[a-zA-Z0-9\\s]{0,20}$");

  // Validates and encodes the input field based on a whitelist
  public String validate(String name, String input) throws ValidationException {
    String canonical = normalize(input);

    if (!pattern.matcher(canonical).matches()) {
      throw new ValidationException("Improper format in " + name + " field");
    }
    
    // Performs output encoding for nonvalid characters 
    canonical = HTMLEntityEncode(canonical);
    return canonical;
  }

  // Normalizes to known instances 	
  private String normalize(String input) {
    String canonical = java.text.Normalizer.normalize(input, Normalizer.Form.NFKC);
    return canonical;
  }

  // Encodes nonvalid data
  private static String HTMLEntityEncode(String input) {
    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < input.length(); i++) {
      char ch = input.charAt(i);
      if (Character.isLetterOrDigit(ch) || Character.isWhitespace(ch)) {
        sb.append(ch);
      } else {
        sb.append("&#" + (int)ch + ";");
      }
    }
    return sb.toString();
  }
}
 
// ...
 
@RequestMapping("/getnotifications.htm")
public ModelAndView getNotifications(HttpServletRequest request, HttpServletResponse response) {
  ValidateOutput vo = new ValidateOutput();

  ModelAndView mv = new ModelAndView();
  try {
    UserInfo userDetails = getUserInfo();
    List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
    List<Notification> notificationList = 
        NotificationService.getNotificationsForUserId(userDetails.getPersonId());
           
    for (Notification notification: notificationList) {
      Map<String,Object> map = new HashMap<String,Object>();
      map.put("id", vo.validate("id" ,notification.getId()));
      map.put("message", vo.validate("message", notification.getMessage()));
      list.add(map);
    }
            
     mv.addObject("Notifications",list);
  }
  catch(Throwable t){
    // Log to file and handle
  }
 
  return mv;
}

Also, see the method weblogic.servlet.security.Utils.encodeXSS() for more information on preventing XSS attacks. Output encoding and escaping is mandatory when accepting dangerous characters such as double quotes and angle braces. Even when input is white-listed to disallow such characters, output escaping is recommended because it provides a second level of defense. Note that the exact escape sequence can differ vary depending on where the output is embedded. For example, untrusted output may occur in an HTML value attribute, CSS, URL, or script; output encoding routine will be different in each case. It is also impossible to securely use untrusted data in some contexts. For example, untrusted output may occur in an HTML value attribute, CSS, URL or script and the output encoding routine will differ in each case. Consult the OWASP XSS (Cross Site Scripting) Prevention Cheat Sheet for more information on preventing XSS attacks.

...