用途
drupal-security 是一套 Drupal 安全技能,用于在开发过程中主动识别安全漏洞,而不是等到代码提交后再审查。当编写或编辑表单、控制器、插件,处理用户输入或查询参数,构建数据库查询,渲染用户提供的内容,或实现访问控制时,该技能会自动激活。
主要能力
SQL 注入防护
禁止将用户输入拼接到查询字符串中。不安全写法:
// VULNERABLE - SQL injection
$query = "SELECT * FROM users WHERE name = '" . $name . "'";
$result = $connection->query($query);
安全写法包括使用查询构造器:
// SAFE - parameterized query
$result = $connection->select('users', 'u')
->fields('u')
->condition('name', $name)
->execute();
或使用占位符:
// SAFE - placeholder
$result = $connection->query(
'SELECT * FROM {users} WHERE name = :name',
[':name' => $name]
);
XSS 防护
始终转义输出,信任渲染系统。不安全写法:
// VULNERABLE - raw HTML output
return ['#markup' => $user_input];
return ['#markup' => '<div>' . $title . '</div>'];
安全写法包括使用自动转义的纯文本、正确的渲染元素,以及依赖 Twig 自动转义:
// SAFE - plain text (auto-escaped)
return ['#plain_text' => $user_input];
// SAFE - use proper render elements
return [
'#type' => 'html_tag',
'#tag' => 'div',
'#value' => $title, // Escaped automatically
];
{{ variable }} // Escaped
{{ variable|raw }} // DANGEROUS - only for trusted HTML
对于仅管理员可见的内容,可使用 Xss 组件过滤但保留安全 HTML 标签:
use Drupal\Component\Utility\Xss;
// Filter but allow safe HTML tags
$safe = Xss::filterAdmin($user_html);
访问控制
始终校验权限。在 routing.yml 中声明权限要求:
my_module.admin:
path: '/admin/my-module'
requirements:
_permission: 'administer my_module' # Required!
在代码中检查权限:
if (!$this->currentUser->hasPermission('administer my_module')) {
throw new AccessDeniedHttpException();
}
实体查询必须检查访问权限:
$query = $this->entityTypeManager
->getStorage('node')
->getQuery()
->accessCheck(TRUE) // CRITICAL - never FALSE unless intentional
->condition('type', 'article');
CSRF 保护
表单自动包含 CSRF 令牌。对于自定义 AJAX,需要附带并在控制器中校验令牌:
// Include token in AJAX requests
$build['#attached']['drupalSettings']['myModule']['token'] =
\Drupal::csrfToken()->get('my_module_action');
// Validate in controller
if (!$this->csrfToken->validate($token, 'my_module_action')) {
throw new AccessDeniedHttpException('Invalid token');
}
文件上传安全
使用白名单校验扩展名与大小,并检查 MIME 类型,不单凭扩展名信任文件:
$validators = [
'file_validate_extensions' => ['pdf doc docx'], // Whitelist extensions
'file_validate_size' => [25600000], // 25MB limit
'FileSecurity' => [], // Drupal 10.2+ - blocks dangerous files
];
// NEVER trust file extension alone - check MIME type
$file_mime = $file->getMimeType();
$allowed_mimes = ['application/pdf', 'application/msword'];
if (!in_array($file_mime, $allowed_mimes)) {
// Reject file
}
敏感数据
不记录敏感信息,错误信息保持通用,密钥使用环境变量:
// NEVER log sensitive data
$this->logger->info('User @user logged in', ['@user' => $username]);
// NOT: $this->logger->info('Login: ' . $username . ':' . $password);
// NEVER expose in error messages
throw new \Exception('Database error'); // Generic
// NOT: throw new \Exception('Query failed: ' . $query);
// Use environment variables for secrets
$api_key = getenv('MY_API_KEY');
// NOT: $api_key = 'hardcoded-secret-key';
危险模式对照
发现以下模式时应立即警告:
| 模式 | 风险 | 修复 |
|---|---|---|
| SQL 中字符串拼接 | SQL 注入 | 使用查询构造器 |
| #markup 含变量 | XSS | 使用 #plain_text |
| accessCheck(FALSE) | 访问绕过 | 使用 accessCheck(TRUE) |
| 路由缺少 _permission | 未授权访问 | 添加权限 |
| Twig 中 {{ var|raw }} | XSS | 移除 |raw |
| 硬编码密码/密钥 | 凭据暴露 | 使用环境变量 |
| eval() 或 exec() | 代码注入 | 完全避免 |
| 对用户数据 unserialize() | 对象注入 | 使用 JSON |
安全评审提问
评审代码时始终询问:
- "Where does this data come from?"(用户输入 = 不可信)
- "Where does this data go?"(输出 = 需要转义)
- "Who should access this?"(需要权限)
- "What if this contains malicious input?"(验证/清理)
提交前安全清单
- 所有用户输入已验证/清理
- 所有输出已正确转义
- 路由具有权限要求
- 实体查询使用 accessCheck(TRUE)
- 无硬编码凭据
- 文件上传同时校验类型和扩展名
- 表单使用 Form API(自动 CSRF)
- 敏感数据未被记录
适用场景
适用于 Drupal 模块开发与代码审查,尤其在涉及表单、控制器、插件、数据库查询、用户输入处理、内容渲染、访问控制和文件上传的场景。
限制
该技能主要面向 Drupal 开发实践,需结合具体代码上下文使用。它提供的是安全编码规范与模式建议,不替代完整的安全审计工具或渗透测试。资料未提供具体版本兼容范围、安装方式或价格信息。