使用TerraScan静态扫描KubernetsIaC文件

terrascan

https://github.com/tenable/terrascan
在这里插入图片描述

Terrascan 是基础架构即代码的静态代码分析器。Terrascan 允许:

  • 将基础架构作为代码无缝扫描,以查找错误配置。
  • 监控已配置的云基础架构,以查找引入终端安全评估漂移的配置更改,并启用恢复到安全终端
  • 检测安全漏洞和违规行为。
  • 在配置云原生基础架构之前降低风险。
  • 提供在本地运行或与 CI\CD 集成的灵活性。

terrascan的基本原理是,通过内置的策略,对目标进行扫描。使用前需要下载策略库,而策略库是经常更新的。类似于扫描病毒需要下载病毒库。它还有一个特点是支持涵盖了IaC和容器领域的的文件扫描:

  • Terraform (HCL2)
  • AWS CloudFormation Templates (CFT)
  • Azure Resource Manager (ARM)
  • Kubernetes (JSON/YAML), Helm v3, and Kustomize
  • Dockerfiles

可见IaC中常用的Cfn,Terraform,以及容器领域的K8S,Helm,Kustomize,Dockerfile都有支持,
一个产品搞定,不需要再部署其他的工具,简化了CICD的设计。

安装(Linux)

# 下载
aria2c https://github.com/tenable/terrascan/releases/download/v1.19.1/terrascan_1.19.1_Linux_x86_64.tar.gz# 没有aria2c可以直接用wget
wget https://github.com/tenable/terrascan/releases/download/v1.19.1/terrascan_1.19.1_Linux_x86_64.tar.gz# 解压
tar -xzvf terrascan.tar.gz#安装
install terrascan /usr/local/bin && rm terrascan

命令帮助

Usage:terrascan [command]Available Commands:init        Initializes Terrascan and clones policies from the Terrascan GitHub repository.scan        Detect compliance and security violations across Infrastructure as Code.server      Run Terrascan as an API serverversion     Terrascan versionFlags:-c, --config-path string      config file path-l, --log-level string        log level (debug, info, warn, error, panic, fatal) (default "info")--log-output-dir string   directory path to write the log and output files-x, --log-type string         log output type (console, json) (default "console")-o, --output string           output type (human, json, yaml, xml, junit-xml, sarif, github-sarif) (default "human")--temp-dir string         temporary directory path to download remote repository,module and templates

init:下载策略库,即从策略库仓库 git clone到本地$HOME/.terrascan目录
scan:具体的scan命令,命令行方式使用
server:作为服务器,提供API供外部调用使用,方便和第三方系统整合

扫描参数

  • 指定路径(默认为当前路径) -d
  • 指定文件 -f
  • 指定远程存储路径 -r
    • git, s3, gcs, http, terraform-registry
    • -u 指定具体的url
  • 指定目标类型 -i

arm, cft, docker, helm, k8s, kustomize, terraform, tfplan

  -i, --iac-type string           iac type (arm, cft, docker, helm, k8s, kustomize, terraform, tfplan)--iac-version string        iac version (arm: v1, cft: v1, docker: v1, helm: v3, k8s: v1, kustomize: v2, v3, v4, terraform: v12, v13, v14, v15, tfplan: v1)
  • 指定输出格式
    • yaml, json, human(默认),xml

工作原理

初次执行时,先从github上下载对应的策略库,并根据策略库的要求检查目标文件。
也可以主动指定init命令更新策略库

命令行执行

  1. 测试用例文件
apiVersion: apps/v1
kind: Deployment
metadata:labels:app: nginxname: nginxnamespace: default
spec:replicas: 2revisionHistoryLimit: 10selector:matchLabels:app: nginxstrategy:rollingUpdate:maxSurge: 25%maxUnavailable: 25%type: RollingUpdatetemplate:metadata:labels:app: nginxspec:containers:- image: nginximagePullPolicy: Alwaysname: nginxresources: {}volumeMounts:- mountPath: /dataname: mytestrestartPolicy: Alwaysvolumes:- name: mytestpersistentVolumeClaim:claimName: my-test-pvc
  1. 执行命令行
terrascan scan -i k8s -f nginx.yaml 
terrascan scan -i k8s -f nginx.yaml -o json
terrascan scan -i k8s -f nginx.yaml -o yaml
  1. 检查结果
k8s@k8s-devp-master:~/yaml$ terrascan scan -i k8s -f nginx.yamlViolation Details -Description    :        Memory Limits Not Set in config file.File           :        nginx.yamlLine           :        1Severity       :        MEDIUM-----------------------------------------------------------------------Description    :        Apply Security Context to Your Pods and ContainersFile           :        nginx.yamlLine           :        1Severity       :        MEDIUM-----------------------------------------------------------------------Description    :        No readiness probe will affect automatic recovery in case of unexpected errorsFile           :        nginx.yamlLine           :        1Severity       :        LOW-----------------------------------------------------------------------Description    :        CPU Limits Not Set in config file.File           :        nginx.yamlLine           :        1Severity       :        MEDIUM-----------------------------------------------------------------------Description    :        Container images with readOnlyRootFileSystem set as false mounts the container root file system with write permissionsFile           :        nginx.yamlLine           :        1Severity       :        MEDIUM-----------------------------------------------------------------------Description    :        Memory Request Not Set in config file.File           :        nginx.yamlLine           :        1Severity       :        MEDIUM-----------------------------------------------------------------------Description    :        No liveness probe will ensure there is no recovery in case of unexpected errorsFile           :        nginx.yamlLine           :        1Severity       :        LOW-----------------------------------------------------------------------Description    :        Image without digest affects the integrity principle of image securityFile           :        nginx.yamlLine           :        1Severity       :        MEDIUM-----------------------------------------------------------------------Description    :        CPU Request Not Set in config file.File           :        nginx.yamlLine           :        1Severity       :        MEDIUM-----------------------------------------------------------------------Description    :        Minimize Admission of Root ContainersFile           :        nginx.yamlLine           :        1Severity       :        HIGH-----------------------------------------------------------------------Description    :        Default Namespace Should Not be UsedFile           :        nginx.yamlLine           :        1Severity       :        HIGH-----------------------------------------------------------------------Description    :        Containers Should Not Run with AllowPrivilegeEscalationFile           :        nginx.yamlLine           :        1Severity       :        HIGH-----------------------------------------------------------------------Description    :        Default seccomp profile not enabled will make the container to make non-essential system callsFile           :        nginx.yamlLine           :        1Severity       :        MEDIUM-----------------------------------------------------------------------Description    :        AppArmor profile not set to default or custom profile will make the container vulnerable to kernel level threatsFile           :        nginx.yamlLine           :        1Severity       :        MEDIUM-----------------------------------------------------------------------Description    :        No tag or container image with :Latest tag makes difficult to rollback and trackFile           :        nginx.yamlLine           :        1Severity       :        LOW-----------------------------------------------------------------------Scan Summary -File/Folder         :   /home/k8s/yaml/nginx.yamlIaC Type            :   k8sScanned At          :   2024-04-19 08:37:56.943717392 +0000 UTCPolicies Validated  :   42Violated Policies   :   15Low                 :   3Medium              :   9High                :   3

作为服务启动

  1. 启动
k8s@k8s-devp-master:~/yaml$ terrascan server -p 10888
2024-04-19T09:02:06.409Z        info    http-server/start.go:63 registering routes...
2024-04-19T09:02:06.409Z        info    http-server/start.go:75 Route GET - /health
2024-04-19T09:02:06.409Z        info    http-server/start.go:75 Route GET - /v1/providers
2024-04-19T09:02:06.409Z        info    http-server/start.go:75 Route POST - /v1/{iac}/{iacVersion}/{cloud}/local/file/scan
2024-04-19T09:02:06.409Z        info    http-server/start.go:75 Route POST - /v1/{iac}/{iacVersion}/{cloud}/remote/dir/scan
2024-04-19T09:02:06.409Z        info    http-server/start.go:75 Route POST - /v1/k8s/webhooks/{apiKey}/scan/validate
2024-04-19T09:02:06.409Z        info    http-server/start.go:109        http server listening at port 10888
  1. 执行

Server模式下,如何使用几乎没有任何说明,只能参考其源码猜测:
https://github.com/tenable/terrascan/blob/master/pkg/http-server/routes.go
https://github.com/tenable/terrascan/blob/master/pkg/http-server/file-scan_test.go

// Routes returns a slice of routes of API endpoints to be registered with
// http server
func (g *APIServer) Routes() []*Route {h := NewAPIHandler()routes := []*Route{{verb: "GET", path: "/health", fn: h.Health},{verb: "GET", path: versionedPath("/providers"), fn: h.iacProviders},{verb: "POST", path: versionedPath("/{iac}/{iacVersion}/{cloud}/local/file/scan"), fn: h.scanFile},{verb: "POST", path: versionedPath("/{iac}/{iacVersion}/{cloud}/remote/dir/scan"), fn: h.scanRemoteRepo},// k8s webhook Routes{verb: "POST", path: versionedPath("/k8s/webhooks/{apiKey}/scan/validate"), fn: h.validateK8SWebhook},}return routes
}
// http request of the type "/v1/{iacType}/{iacVersion}/{cloudType}/file/scan"url := fmt.Sprintf("/v1/%s/%s/%s/local/file/scan", tt.iacType, tt.iacVersion, tt.cloudType)

可以看到,它支持如下功能:

  • /providers:功能支持列表
  • /{iac}/{iacVersion}/{cloud}/local/file/scan:本地文件扫描
  • /{iac}/{iacVersion}/{cloud}/remote/dir/scan:远程目录扫描
  • /k8s/webhooks/{apiKey}/scan/validate:和Kubernetes整合用的webhook

功能列表获取

k8s@k8s-devp-master:~/yaml$ curl -X GET  -L http://localhost:10888/v1/providers
[{"type": "arm","versions": ["v1"],"defaultVersion": "v1"},{"type": "cft","versions": ["v1"],"defaultVersion": "v1"},{"type": "docker","versions": ["v1"],"defaultVersion": "v1"},{"type": "helm","versions": ["v3"],"defaultVersion": "v3"},{"type": "k8s","versions": ["v1"],"defaultVersion": "v1"},{"type": "kustomize","versions": ["v2","v3","v4"],"defaultVersion": "v4"},{"type": "terraform","versions": ["v12","v13","v14","v15"],"defaultVersion": "v15"},{"type": "tfplan","versions": ["v1"],"defaultVersion": "v1"}

根据以上结果可以拼接访问URL:

  • kubernetes扫描:http://localhost:10888/v1/k8s/v1/k8s/local/file/scan
  • Dockerfile扫描:http://localhost:10888/v1/docker/v1/docker/local/file/scan

另外文件扫描接口只支持multipart/form-data类型的文件上传,不能作为POST的数据直接上传。
命令行参考以下:
可以看到执行结果和命令行一样,json格式。file等信息是内部中间结果信息,可忽略。

 curl -X POST  -L http://localhost:10888/v1/k8s/v1/k8s/local/file/scan -F 'file=@./nginx.yaml'{"results": {"violations": [{"rule_name": "privilegeEscalationCheck","description": "Containers Should Not Run with AllowPrivilegeEscalation","rule_id": "AC_K8S_0085","severity": "HIGH","category": "Compliance Validation","resource_name": "nginx","resource_type": "kubernetes_deployment","file": "terrascan-3209226987.yaml","line": 1},{"rule_name": "secCompProfile","description": "Default seccomp profile not enabled will make the container to make non-essential system calls","rule_id": "AC_K8S_0080","severity": "MEDIUM","category": "Identity and Access Management","resource_name": "nginx","resource_type": "kubernetes_deployment","file": "terrascan-3209226987.yaml","line": 1},{"rule_name": "appArmorProfile","description": "AppArmor profile not set to default or custom profile will make the container vulnerable to kernel level threats","rule_id": "AC_K8S_0073","severity": "MEDIUM","category": "Identity and Access Management","resource_name": "nginx","resource_type": "kubernetes_deployment","file": "terrascan-3209226987.yaml","line": 1},{"rule_name": "imageWithoutDigest","description": "Image without digest affects the integrity principle of image security","rule_id": "AC_K8S_0069","severity": "MEDIUM","category": "Infrastructure Security","resource_name": "nginx","resource_type": "kubernetes_deployment","file": "terrascan-3209226987.yaml","line": 1},{"rule_name": "securityContextUsed","description": "Apply Security Context to Your Pods and Containers","rule_id": "AC_K8S_0064","severity": "MEDIUM","category": "Infrastructure Security","resource_name": "nginx","resource_type": "kubernetes_deployment","file": "terrascan-3209226987.yaml","line": 1},{"rule_name": "MemorylimitsCheck","description": "Memory Limits Not Set in config file.","rule_id": "AC_K8S_0100","severity": "MEDIUM","category": "Security Best Practices","resource_name": "nginx","resource_type": "kubernetes_deployment","file": "terrascan-3209226987.yaml","line": 1},{"rule_name": "runAsNonRootCheck","description": "Minimize Admission of Root Containers","rule_id": "AC_K8S_0087","severity": "HIGH","category": "Identity and Access Management","resource_name": "nginx","resource_type": "kubernetes_deployment","file": "terrascan-3209226987.yaml","line": 1},{"rule_name": "MemoryRequestsCheck","description": "Memory Request Not Set in config file.","rule_id": "AC_K8S_0099","severity": "MEDIUM","category": "Security Best Practices","resource_name": "nginx","resource_type": "kubernetes_deployment","file": "terrascan-3209226987.yaml","line": 1},{"rule_name": "nolivenessProbe","description": "No liveness probe will ensure there is no recovery in case of unexpected errors","rule_id": "AC_K8S_0070","severity": "LOW","category": "Security Best Practices","resource_name": "nginx","resource_type": "kubernetes_deployment","file": "terrascan-3209226987.yaml","line": 1},{"rule_name": "noReadinessProbe","description": "No readiness probe will affect automatic recovery in case of unexpected errors","rule_id": "AC_K8S_0072","severity": "LOW","category": "Security Best Practices","resource_name": "nginx","resource_type": "kubernetes_deployment","file": "terrascan-3209226987.yaml","line": 1},{"rule_name": "readOnlyFileSystem","description": "Container images with readOnlyRootFileSystem set as false mounts the container root file system with write permissions","rule_id": "AC_K8S_0078","severity": "MEDIUM","category": "Identity and Access Management","resource_name": "nginx","resource_type": "kubernetes_deployment","file": "terrascan-3209226987.yaml","line": 1},{"rule_name": "imageWithLatestTag","description": "No tag or container image with :Latest tag makes difficult to rollback and track","rule_id": "AC_K8S_0068","severity": "LOW","category": "Security Best Practices","resource_name": "nginx","resource_type": "kubernetes_deployment","file": "terrascan-3209226987.yaml","line": 1},{"rule_name": "otherNamespace","description": "Default Namespace Should Not be Used","rule_id": "AC_K8S_0086","severity": "HIGH","category": "Security Best Practices","resource_name": "nginx","resource_type": "kubernetes_deployment","file": "terrascan-3209226987.yaml","line": 1},{"rule_name": "CpulimitsCheck","description": "CPU Limits Not Set in config file.","rule_id": "AC_K8S_0098","severity": "MEDIUM","category": "Security Best Practices","resource_name": "nginx","resource_type": "kubernetes_deployment","file": "terrascan-3209226987.yaml","line": 1},{"rule_name": "CpuRequestsCheck","description": "CPU Request Not Set in config file.","rule_id": "AC_K8S_0097","severity": "MEDIUM","category": "Security Best Practices","resource_name": "nginx","resource_type": "kubernetes_deployment","file": "terrascan-3209226987.yaml","line": 1}],"skipped_violations": null,"scan_summary": {"file/folder": "/tmp/terrascan-3209226987.yaml","iac_type": "k8s","scanned_at": "2024-04-19 09:13:38.989530627 +0000 UTC","policies_validated": 42,"violated_policies": 15,"low": 3,"medium": 9,"high": 3}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/328165.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

使用图网络和视频嵌入预测物理场

文章目录 一、说明二、为什么要预测?三、流体动力学模拟的可视化四、DeepMind神经网络建模五、图形编码六、图形处理器七、图形解码器八、具有不同弹簧常数的轨迹可视化九、预测的物理编码和推出轨迹 一、说明 这是一篇国外流体力学专家在可视化流体物理属性的设计…

OpenAI新模型GPT-4o“炸裂登场” 响应速度堪比真人 关键还免费!

GPT-4o模型基于来自互联网的大量数据进行训练,更擅长处理文本和音频,并且支持50种语言。更值得一提的是,GPT-4o最快可以在232毫秒的时间内响应音频输入,几乎达到了人类的响应水平。 GPT-4o有多“炸裂”?核心能力有三 G…

幻兽帕鲁Palworld服务器手动部署

目录 帕鲁官方文档手动安装steamcmd通过steamcmd安装帕鲁后端客户端连接附录:PalServer.sh的启动项附录:配置文件 帕鲁官方文档 https://tech.palworldgame.com/ 手动安装steamcmd 创建steam用户 sudo useradd -m steam sudo passwd steam下载steamc…

自动化测试基础 --- Jmeter

前置环境安装 首先我们需要知道如何下载Jmeter 这里贴上下载网站Apache JMeter - Download Apache JMeter 我们直接解压,然后在bin目录下找到jemter.bat即可启动使用 成功打开之后就是这个界面 每次打开可以用这种方式切换成简体中文 或者直接修改properties文件修改对应的语言…

【linux】详解linux基本指令

目录 cat more less head tail 时间 cal find grep zip/unzip tar bc uname –r 关机 小编一共写了两篇linux基本指令,这两篇涵盖了大部分初学者的必备指令,这是第二篇,第一篇详见http://t.csdnimg.cn/HRlVt cat 适合查看小文…

5.神经网络-激活函数

目录 1. 激活函数不是阶跃函数 1.1 激活函数和阶跃函数都是非线性函数 1.2 激活函数不是阶跃函数 2. sigmoid 函数 2.1 sigmoid 函数表达式 2.2 sigmoid 函数 Python 实现 2.4 sigmoid 函数图 3. ReLU 函数 3.1 ReLU 函数表达式 3.2 ReLU 函数 Python 实现 3.4 ReLU…

接口自动化-requests库

requests库是用来发送请求的库,本篇用来讲解requests库的基本使用。 1.安装requests库 pip install requests 2.requests库底层方法的调用逻辑 (1)get / post / put / delete 四种方法底层调用 request方法 注意:data和json都…

边缘计算安全有多重要

德迅云安全研究发现边缘安全是对存储或处理在网络边缘的数据的保护。边缘可以用不同的方式定义,但一般来说,它包括企业直接控制之外的任何设备或位置。这可能包括传感器、连接物联网的设备和移动设备。 边缘计算正在彻底改变商业运作方式。这引发了对边缘…

WordPress原创插件:超链接点击访问统计

内容目录 一、详细介绍二、效果展示1.部分代码2.效果图展示 三、学习资料下载 一、详细介绍 一般我们都使用第三方统计服务(比如百度统计)来统计网站的访问量,使用此插件可以统计文章的浏览次数,那么,如果想统计网站外…

(规格参考)ADP5360ACBZ-1-R7 电量计 电池管理IC,ADP5072ACBZ 双通道直流开关稳压器,ADL5903ACPZN 射频检测器

1、ADP5360ACBZ-1-R7:具有超低功耗电量计、电池保护功能的先进电池管理PMIC 功能:电池保护 电池化学成份:锂离子/聚合物 电池数:1 故障保护:超温,过压 接口:I2C 工作温度:-40C ~ 85…

生活服务商家拥抱数字化,鸿运果系统加速“服务生意数字化”进程

在数字化转型的大潮中,生活服务商家正积极拥抱变革,以适应新的市场环境和消费者需求。鸿运果系统作为专业的“服务生意”数字化解决方案提供商,正助力商家加速数字化转型,推动行业向智能化、个性化服务转型。 数字化转型的背景 …

人才测评:计划管理能力与岗位胜任力素质测评

计划管理能力指的是什么? 计划管理能力,可以体现为从业者在精准制定好任务,或是根据任务的时间长,困难的程度来设定好完成的目标,一步一个脚印将工作完成好,并且能预估出可能出现的突发事件,将…

AI工具的热门与卓越:揭示AI技术的实际应用和影响

文章目录 每日一句正能量前言常用AI工具创新AI应用个人体验分享后记 每日一句正能量 我们在我们的劳动过程中学习思考,劳动的结果,我们认识了世界的奥妙,于是我们就真正来改变生活了。 前言 随着人工智能(AI)技术的快…

【Linux取经路】进程通信之匿名管道

文章目录 一、进程间通信介绍1.1 进程间通信是什么?1.2 进程间通信的目的1.3 进程通信该如何实现 二、管道2.1 匿名管道2.1.1 站在文件描述符角度深入理解管道2.1.2 接口使用2.1.3 PIPE_BUFFER 和 Pipe capacity2.1.4 管道中的四种情况2.1.5 管道特征总结 2.2 匿名管…

华为、小米、魅族都开始造车了!中国还有多少手机厂家要下场造车?2024如果创业适合干什么?2024最适合创业的细分行业

要说现在中国最火、声量最高的创业是什么?那一定是造车! 小米这样的手机公司在造车、创维这样的电视家电品牌在造车、甚至就连五粮液这样的白酒品牌也在造车!至于其他的还有什么做地产的恒大、做电动车的新日等等,数不数胜。而在手…

如何进行事务处理

1、问题背景 在数据库存储系统中,事务处理是一种保证多个数据库操作作为单个逻辑单元执行的技术。事务处理可以确保数据的一致性、完整性和隔离性。 在使用 Google Cloud Datastore 时,可以使用 datastore.transaction() 函数来进行事务处理。datastor…

DBeaver连接数据库

前言 DBeaver是一款免费和开源的数据库管理工具,为开发人员和数据库管理员提供了一个通用的数据库解决方案。以下是DBeaver的主要特点和功能: 跨平台支持:DBeaver支持Windows、Linux、macOS等主流操作系统,用户可以在不同的平台…

MATLAB公式推导和导出Latex格式的方法

最近在推机械臂正逆运动学公式,那个旋转矩阵乘起来是真滴多,手算算的脑浆疼。突然想起来MATLAB还有符号计算这个功能,于是翻了翻手册, 找到了这个利用MATLAB帮助计算公式并且直接导出Latex格式的办法。 先定义符号变量&#xff0…

我的职场加速器-高效工作从可道云teamOS开始

不论是作为管理者,还是普通打工人,在日常工作中,我们都需要一款既能够保障数据安全,又能够提升团队协作效率的平台。 近期,我体验了可道云teamOS,这款企业级云协作平台给我留下了深刻的印象。 一、极简风…

基于springboot+mybatis+vue的项目实战之前端

步骤: 1、项目准备:新建项目,并删除自带demo程序,修改application.properties. 2、使用Apifox准备好json数据的mock地址 3、编写基于vue的静态页面 4、运行 整个的目录结构如下: 0、项目准备 新建项目&#xff0…