Java RASP案例

wen java案例 2

Java RASP (Runtime Application Self-Protection) 典型案例

什么是RASP

RASP是一种在应用运行时嵌入的安全保护技术,能够实时监测和阻止攻击,与传统的WAF(Web应用防火墙)不同,RASP运行在应用内部,可以获取完整的上下文信息。

Java RASP案例

典型案例场景

案例1:SQL注入防护

攻击场景:

// 存在漏洞的代码
String username = request.getParameter("username");
String query = "SELECT * FROM users WHERE username = '" + username + "'";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);

RASP防护实现:

// RASP Hook实现SQL注入检测
public class SQLInjectionDetector {
    @Hook(targetMethod = "java.sql.Statement.executeQuery")
    public static void beforeExecuteQuery(String sql) {
        // 检测SQL注入特征
        if (containsSQLInjectionPatterns(sql)) {
            // 记录攻击日志
            SecurityLogger.logAttack("SQL Injection detected: " + sql);
            // 阻断执行
            throw new SecurityException("SQL Injection attack blocked");
        }
    }
    private static boolean containsSQLInjectionPatterns(String sql) {
        // 检测常见的SQL注入模式
        String[] patterns = {
            "'.*OR.*'1'='1",
            "'.*UNION.*SELECT",
            "'.*DROP.*TABLE",
            "'.*DELETE.*FROM",
            "'.*INSERT.*INTO",
            "'.*UPDATE.*SET",
            "--",
            "/*",
            "*/",
            "1=1",
            "sleep\\(",
            "waitfor\\s+delay"
        };
        for (String pattern : patterns) {
            if (sql.toUpperCase().matches(".*" + pattern + ".*")) {
                return true;
            }
        }
        return false;
    }
}

案例2:命令执行防护

攻击场景:

// 存在漏洞的代码
String cmd = request.getParameter("command");
Runtime.getRuntime().exec(cmd);

RASP防护实现:

// RASP Hook实现命令执行检测
public class CommandExecutionDetector {
    @Hook(targetClass = "java.lang.Runtime", targetMethod = "exec")
    public static void beforeExec(String command) {
        // 检测危险命令
        if (isDangerousCommand(command)) {
            SecurityLogger.logAttack("Command Injection detected: " + command);
            throw new SecurityException("Command execution blocked");
        }
    }
    private static boolean isDangerousCommand(String command) {
        // 黑名单命令列表
        String[] dangerousCommands = {
            "rm", "del", "format", "shutdown",
            "reboot", "chmod", "chown",
            "wget", "curl", "nc", "netcat",
            "bash", "cmd", "powershell",
            "eval", "exec", "system",
            "rundll32", "regsvr32"
        };
        String lowerCommand = command.toLowerCase();
        for (String dangerous : dangerousCommands) {
            if (lowerCommand.contains(dangerous)) {
                return true;
            }
        }
        return false;
    }
}

案例3:文件上传防护

攻击场景:

// 存在漏洞的代码
MultipartFile file = request.getFile("file");
String fileName = file.getOriginalFilename();
file.transferTo(new File("/uploads/" + fileName));

RASP防护实现:

// RASP Hook实现文件上传检测
public class FileUploadDetector {
    @Hook(targetMethod = "org.springframework.web.multipart.MultipartFile.transferTo")
    public static void beforeTransferTo(File destFile) {
        // 检查文件路径
        if (isPathTraversalAttack(destFile.getPath())) {
            SecurityLogger.logAttack("Path Traversal detected: " + destFile.getPath());
            throw new SecurityException("File upload blocked");
        }
        // 检查文件类型
        if (!isAllowedFileType(destFile.getName())) {
            SecurityLogger.logAttack("Unsafe file type: " + destFile.getName());
            throw new SecurityException("File type not allowed");
        }
    }
    private static boolean isPathTraversalAttack(String filePath) {
        return filePath.contains("..") || 
               filePath.contains("../") || 
               filePath.contains("..\\");
    }
    private static boolean isAllowedFileType(String fileName) {
        Set<String> allowedExtensions = new HashSet<>(Arrays.asList(
            "jpg", "jpeg", "png", "gif", "pdf", "doc", "docx", "xls", "xlsx"
        ));
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        return allowedExtensions.contains(extension);
    }
}

商业RASP产品案例

OpenRASP (百度)

  • 特点:开源免费
  • 关键功能
    // OpenRASP的配置示例
    {
      "hook": {
        "sql_database": {
          "enabled": true,
          "action": "block",
          "stack": true
        },
        "command_execution": {
          "enabled": true,
          "action": "block",
          "blacklist": ["rm", "del", "format"]
        }
      }
    }

Contrast Security

  • 特点:商业产品,IAST+RASP结合
  • 关键功能
    // Contrast RASP的注解式防护
    @Secure
    public class UserController {
        @Secure({SecureType.SQL_INJECTION, SecureType.XSS})
        public User getUser(@SecureParam String id) {
            // 自动包含安全防护
        }
    }

RASP与传统防护对比

特性 RASP WAF 传统代码审计
检测位置 应用内部 网络边界 代码层面
上下文理解 完全理解 有限理解 静态分析
实时性 实时 实时 非实时
误报率
部署复杂度

实际应用案例

某电商平台RASP部署效果:

  • 场景:防止SQL注入攻击订单系统
  • 实现:在JDBC层注入Hook
  • 效果:成功拦截了日均200+次的SQL注入尝试
  • 性能影响:<5ms的延迟增加

某金融系统RASP部署效果:

  • 场景:防止命令执行漏洞
  • 实现:在Runtime.exec方法处注入Hook
  • 效果:发现并修复了3个隐藏的命令注入漏洞
  • 告警准确率:99.7%

建议

  1. 选择适当的Hook点:关注关键的API调用
  2. 性能优化:使用缓存、异步处理等方式
  3. 精细策略:区分不同场景的安全策略
  4. 日志记录:完整的攻击记录和审计功能
  5. 灰度发布:逐步部署,减少影响

RASP技术通过运行时监控,能够有效补充传统安全防护的不足,为企业提供更深层次的防护能力。

抱歉,评论功能暂时关闭!