Insecure hostname validation check
不安全的的主机名验证检查
描述
应用程序使用易于绕过的方法(如 startsWith 或 endsWith)执行不安全的主机名验证。攻击者可以通过注册与检查模式相匹配的域名来轻松绕过此检查。
同时使用 startsWith 和 endsWith 的组合检查同样是不安全的,因为攻击者仍可以创建带有随机中间输入且匹配受检模式的域名。
建议
为了确保对主机名进行安全的验证,请考虑以下实现方式。
-
实现正则表达式(Regex)验证:不要使用诸如
startsWith或endsWith的简单方法,而应选择正则表达式来执行彻底的主机名验证。正则表达式模式可以提供精确的匹配条件。 -
考虑标准化的验证库:利用已建立的、提供稳健主机名验证功能的库或框架。这些库通常维护良好,并会定期更新以解决潜在的安全缺陷。
-
实现白名单机制:如果您拥有的白名单主机数量有限,请考虑实现白名单机制,即应用程序仅接受已知且受信任的主机名。
import java.util.regex.*;
public class SubdomainValidator {
public static void main(String[] args) {
String userInput = "sub.example.com"; // replace this with user input
// Regular expression pattern to match subdomains of example.com
String pattern = "^([a-zA-Z0-9]+(-[a-zA-Z0-9]+)*\\.)+example\\.com$";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Create Matcher object
Matcher m = r.matcher(userInput);
// Check if input matches the pattern
if (m.find()) {
System.out.println("Valid subdomain of example.com");
} else {
System.out.println("Invalid subdomain of example.com");
}
}
}
import Foundation
func isValidSubdomain(_ userInput: String) -> Bool {
let pattern = #"^([a-zA-Z0-9]+(-[a-zA-Z0-9]+)*\.)+example\.com$"# // Regular expression pattern
let regex = try! NSRegularExpression(pattern: pattern)
let range = NSRange(location: 0, length: userInput.utf16.count)
return regex.firstMatch(in: userInput, options: [], range: range) != nil
}
let userInput = "sub.example.com" // replace this with user input
if isValidSubdomain(userInput) {
print("Valid subdomain of example.com")
} else {
print("Invalid subdomain of example.com")
}
import 'package:flutter/material.dart';
bool isValidSubdomain(String userInput) {
RegExp regex = RegExp(r'^([a-zA-Z0-9]+(-[a-zA-Z0-9]+)*\.)+example\.com$');
return regex.hasMatch(userInput);
}
void main() {
String userInput = "sub.example.com"; // replace this with user input
if (isValidSubdomain(userInput)) {
print("Valid subdomain of example.com");
} else {
print("Invalid subdomain of example.com");
}
}
链接
标准
- OWASP_MASVS_L1:
- MSTG_PLATFORM_2
- OWASP_MASVS_L2:
- MSTG_PLATFORM_2
- CWE_TOP_25:
- CWE_20
- PCI_STANDARDS:
- REQ_6_2
- REQ_6_3
- REQ_11_3
- OWASP_MASVS_v2_1:
- MASVS_CODE_4
- SOC2_CONTROLS:
- CC_2_1
- CC_4_1
- CC_7_1
- CC_7_2
- CC_7_4
- CC_7_5
- HIPAA_CONTROLS:
- SECURITY252
- SECURITY212
- SECURITY213