本节书摘来异步社区《Java编码指南:编写安全可靠程序的75条建议》一书中的第1章,第1.6节,作者:【美】Fred Long(弗雷德•朗), Dhruv Mohindra(德鲁•莫欣达), Robert C.Seacord(罗伯特 C.西科德), Dean F.Sutherland(迪恩 F.萨瑟兰), David Svoboda(大卫•斯沃博达),更多章节内容可以访问云栖社区“异步社区”公众号查看。
适当的输入检查可以防止恶意数据插入数据库等子系统。虽然不同的子系统需要不同类型的数据无害化处理,但是子系统最终要接收的输入形式都很明确,因此可以很清楚地知道需要什么样的数据无害化处理。
有几个用于输出数据的子系统。HTML渲染器是一种常见的用于显示程序输出的子系统。发送给输出子系统的数据,来源似乎都很可靠。然而,假设输出数据不必做无害化处理,是很危险的,因为这些数据可能间接来源于一个不可信的来源,并且可能包含恶意的内容。如果没能正确地处理传递给输出子系统的数据,就会让多种类型的攻击有机可乘。例如,HTML渲染器易受HTML注入攻击和跨站脚本(XSS)攻击[OWASP 2011]。因此,用于防止此类攻击的输出无害化处理,和输入无害化处理一样重要。
和输入验证一样,数据应该在消除恶意字符之前被标准化。正确编码所有输出字符,其中那些已知的、不会由于绕过数据验证而导致安全漏洞的字符除外。更多信息参见《The CERT® Oracle® Secure Coding Standard for Java™》[Long 2012]的“IDS01-J. Normalize strings before validating them”。
下面的违规代码示例使用基于Java EE的Spring框架中的模型-视图-控制器(Model-View-Controller,MVC)概念,向用户显示了没有经过编码或转义的数据。因为数据会被发送到Web浏览器,所以该代码容易受到HTML注入攻击和XSS攻击。
@RequestMapping("/getnotifications.htm") public ModelAndView getNotifications( HttpServletRequest request, HttpServletResponse response) { 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", notification.getId()); map.put("message", notification.getMessage()); list.add(map); } mv.addObject("Notifications", list); } catch (Throwable t) { // Log to file and handle } return mv; }``` ####合规解决方案 下面的合规解决方案定义了一个ValidateOutput类,这个类首先将输出规范化到了一个已知的字符集,然后使用白名单的对数据做了无害化处理,最后对所有未指明的数据值进行编码,强制执行了双重检查机制。注意,所需的白名单模式将根据不同字段的具体需求而变化[OWASP 2013]。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> list = new ArrayList>(); List notificationList = NotificationService.getNotificationsForUserId( serDetails.getPersonId());
for (Notification notification: notificationList) { Map map = new HashMap(); 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;}`当接受危险的字符如双引号和尖括号时,必须对输出进行编码和转义。即使在输入白名单中不允许出现这样的字符,也要对输出进行转义,因为这样就提供了一个二级防御。注意,确切的转义序列会发生变化,具体取决于该输出将要被嵌入的地方。例如,HTML标签属性值、CSS、URL或者脚本中都可能会出现不可信输出,不同情况下的输出编码例程也会有所不同。另外,在有些上下文中,无法安全地使用不可信的数据。
在输出被显示前或被传递到可信边界前,没能对其进行编码或转义,导致任意代码的执行。
据2006年1月报道,Apache GERONIMO-1474漏洞允许攻击者提交包含JavaScript的URL。网络访问日志查看器(Web Access Log Viewer)未能对跳转到管理员控制台的数据进行无害化处理,从而促成了一个典型的XSS攻击。
相关资源:七夕情人节表白HTML源码(两款)