Prometheus 作为监控工具,暴露了大量的系统监控数据和配置信息,这些数据可能包含敏感信息。Prometheus 默认没有身份验证,任何能够访问 Prometheus Web 界面的人都可以查看和查询这些数据。
此外Prometheus Web 界面的/debug/pprof/接口存在信息泄露漏洞
如果整改需要重新注释掉net/http/pprof,以及相关代码块,重新编译,比较麻烦,也可以采用这种身份验证来限制访问/debug/pprof/的方式来整改。
步骤如下:
1、创建 Basic Auth 配置文件
首先,我们需要为 Prometheus 创建一个配置文件web_auth.yml,该文件将包含 Basic Auth 用户名和密码。由于 Basic Auth 要求密码以加密的形式存储,我们使用 bcrypt 加密算法来生成加密密码。这里使用python生成(新建一个getPasswd.py,安装 bcrypt
库 pip install bcrypt )
pip install bcrypt
import getpass
import bcrypt
def generate_hashed_password():
"""
生成加密后的 bcrypt 密码
"""
try:
# 获取用户输入的密码
password = getpass.getpass("请输入密码: ")
# 确保密码不为空
if not password:
print("密码不能为空,请重新输入。")
return
# 使用 bcrypt 加密密码
hashed_password = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt())
# 输出加密后的密码
print("\n加密后的密码是:")
print(hashed_password.decode())
except Exception as e:
print(f"发生错误: {e}")
if __name__ == "__main__":
generate_hashed_password()
如图 运行 getPasswd.py脚本,输入你的密码,getPasswd.py 然后脚本将输出加密后的密码。
在Prometheus目录下创建web_auth.yml
配置文件,并将用户名和加密后的密码写入该文件:
用户名可以自己设置,也可以配置多个。
basic_auth_users:
admin: $2b$12$Wo0adjhgjYiqSstP1fhg0avQOgD5oKYoeDbrqewq596prhMZXTVLZTzgfaeG
可以使用promtool工具检查一下这个配置文件
./promtool check web-config ./web_auth.yml
如图:
2、启动 Prometheus 时指定该配置文件
在 Prometheus 启动时,需要指定配置文件 web.yml
。
我这里是使用服务的方式启动的,将 --web.config.file
参数添加到 ExecStart
行,指向web_auth.yml 配置文件。(如果是容器或者直接运行二进制文件启动,也是同理加入如下参数)
./prometheus --web.config.file=/your/path/xxxxx/web_auth.yml
如图:
3、 重新加载 systemd
配置
修改完服务文件后,您需要重新加载 systemd
配置,以便使更改生效:
sudo systemctl daemon-reload
4、重启 Prometheus 服务
sudo systemctl restart prometheus
5、 验证
我们再访问 Prometheus Web 界面和/debug/pprof/ 浏览器会跳出来让输入用户名密码。
6、可以加入抓取目标的身份验证
通过在 scrape_configs
中添加 basic_auth
来实现对其他服务的身份验证。 也就是配置了 basic_auth
后,它会在抓取数据时发送带有用户名和密码的 HTTP 请求。Prometheus 会使用 Authorization
HTTP 头部进行身份验证,
例如,如果用户名是 your_username
,密码是 your_password
,Prometheus 会将它们拼接成 your_username:your_password
,然后进行 Base64 编码。最终,这个编码后的字符串会作为 Authorization
头部的一部分发送到目标服务。
在 scrape_configs
中使用 basic_auth
配置,主要是为了让 Prometheus 在抓取需要身份验证的目标时,能够提供正确的 用户名和密码。这对于访问需要保护的监控端点非常有用,可以防止未经授权的访问。
配置如下:
在prometheus.yml 中加入 basic_auth 配置
- job_name: "prometheus"
basic_auth:
username: admin
password: yourpasswd
static_configs:
- targets: ["localhost:9090"]
7、在 Grafana 的数据源配置中提供相应的认证信息。
如果Grafana 中选择 Prometheus 作为数据源,并且该 Prometheus 实例启用了 基本身份验证(Basic Auth),则需要在 Grafana 的数据源配置中提供相应的认证信息,在 Grafana 配置 Prometheus 数据源时,可以在数据源设置中配置用户名和密码,确保 Grafana 能够通过身份验证连接到 Prometheus 实例。
如图: