硬编码凭据¶
ID: js/hardcoded-credentials
Kind: path-problem
Security severity: 9.8
Severity: warning
Precision: high
Tags:
- security
- external/cwe/cwe-259
- external/cwe/cwe-321
- external/cwe/cwe-798
Query suites:
- javascript-code-scanning.qls
- javascript-security-extended.qls
- javascript-security-and-quality.qls
在源代码中包含未加密的硬编码身份验证凭据很危险,因为凭据很容易被发现。例如,代码可能是开源的,或者可能会泄露或意外公开,从而使攻击者能够看到凭据。这反过来可能使攻击者能够获得未经授权的访问权限,或者获取特权信息。
建议¶
从源代码中删除硬编码凭据,例如用户名、密码和证书。如有必要,将它们放在配置文件、环境变量或其他数据存储中。如果可能,将包含凭据数据的配置文件与源代码分开存储在安全位置,并限制访问权限。
如果凭据是占位符值,请确保该值明显是占位符,方法是使用 "SampleToken"
或 "MyPassword"
等名称。
示例¶
以下代码示例使用硬编码的身份验证标头连接到 HTTP 请求
let base64 = require('base-64');
let url = 'http://example.org/auth';
let username = 'user';
let password = 'passwd';
let headers = new Headers();
headers.append('Content-Type', 'text/json');
headers.append('Authorization', 'Basic' + base64.encode(username + ":" + password));
fetch(url, {
method:'GET',
headers: headers
})
.then(response => response.json())
.then(json => console.log(json))
.done();
相反,用户名和密码可以通过环境变量 username
和 password
提供,这些变量可以在外部设置,而无需在源代码中硬编码凭据。
let base64 = require('base-64');
let url = 'http://example.org/auth';
let username = process.env.USERNAME;
let password = process.env.PASSWORD;
let headers = new Headers();
headers.append('Content-Type', 'text/json');
headers.append('Authorization', 'Basic' + base64.encode(username + ":" + password));
fetch(url, {
method:'GET',
headers: headers
})
.then(response => response.json())
.then(json => console.log(json))
.done();
示例¶
以下代码示例使用 pg
包连接到 Postgres 数据库,并对用户名和密码进行硬编码
const pg = require("pg");
const client = new pg.Client({
user: "bob",
host: "database.server.com",
database: "mydb",
password: "correct-horse-battery-staple",
port: 3211
});
client.connect();
相反,用户名和密码可以通过环境变量 PGUSER
和 PGPASSWORD
提供,这些变量可以在外部设置,而无需在源代码中硬编码凭据。