使用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.mzph.cn/pingmian/13294.shtml

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

相关文章

10个必备功能跨境电商ERP开发全指南

跨境电商平台开发是当前电商行业的热门话题。随着全球贸易的不断发展,企业越来越关注并重视跨境电商ERP系统的开发和应用。在本文中,我们将深入探讨跨境电商ERP开发的必备功能,为您呈现全面的指南。 1. 跨境订单管理 跨境电商平台需要具备全…

go语言中Print,Printf和Println的区别

Print是Golang的fmt包中的内置函数,使用其操作数的默认格式打印格式并写入标准输出; Println是Golang的fmt包中的内置函数,用于在结尾处打印带有新行的消息到控制台。它需要零个或多个任意类型的参数,并使用空格分隔它们&#xff…

CST电磁仿真软件什么是Schematic?三维模型和电路协同仿真【小白必学教程】

什么是Schematic? 使用CST Design Studio进行的各种分析! Schematic 进行三维仿真时,有时需要将3D模型和电路图放在一起进行仿真分析。比如需要天线和匹配电路协同仿真,两者构成完整的电路图可以系统地分析In/0ut特性。按下3D工作界面下方…

docker本地(非公网)搭建gpt-4-all 和 GPTS 多模态对话页面(支持Chat Gpt4o「omni」)

文章目录 GPT-4o简介API-key的获取Linux环境部署gpt-4-all 和 GPTS 多模态访问测试 GPT-4o简介 新模型 GPT-4o,其中的「o」代表「omni」(即全面、全能的意思),这个模型同时具备文本、图片、视频和语音方面的能力 API-key的获取 …

在Ubuntu22.04搭建xfce远程桌面

由于Ubuntu22.04云服务器(带GPU)只开放部分端口,某些服务(如nacos)有Web前端需要访问,但是相应的端口并没有开放,只有SSH端口可以使用。于是,就在Ubuntu22.04上安装xfce桌面环境&…

JavaScript对象设计哲学:八种模式塑造高效代码

🔥 个人主页:空白诗 文章目录 一、引言 🚀二、Object 构造函数 🧱📌 基本用法📌 重要性📌 实际应用案例 三、对象字面量 📘📌 定义属性📌 定义方法&#x1f4…

2023年数维杯国际大学生数学建模挑战赛D题洗衣房清洁计算解题全过程论文及程序

2023年数维杯国际大学生数学建模挑战赛 D题 洗衣房清洁计算 原题再现: 洗衣房清洁是人们每天都要做的事情。洗衣粉的去污作用来源于一些表面活性剂。它们可以增加水的渗透性,并利用分子间静电排斥机制去除污垢颗粒。由于表面活性剂分子的存在&#xff…

如何修改照片的dpi值?在线图片更改dpi快捷方法

不少小伙不知道如何去改变图片分辨率,因为能用的到分辨率dpi的地方也不多,但是当我们在求职、考公或者是打印照片的时候,就经常看到会要求图片分辨率为300dpi以上了,本文将分享一款图片处理工具,它能快速完成修改图片分…

Vue3专栏项目 -- 三、使用vue-router 和 vuex(上)

前面我们开发了两个页面的组件,现在我们需要把它们分成几个页面了,那么一个网页多个页面我们都熟悉,针对不同的url渲染不同的html静态页面,这是web世界的基本工作方式。 有时候我们点击一个东西,地址栏的路由跳转&…

DOS学习-目录与文件应用操作经典案例-dir

欢迎关注我👆,收藏下次不迷路┗|`O′|┛ 嗷~~ 目录 一.前言 二.使用 三.练习 一.前言 dir是"directory"(目录)的缩写,它主要用于展示某个磁盘上的全部或特定文件目录。在DOS操作系统中&#…

【前段】开发五子棋小游戏全流程

使用前端技术开发五子棋小游戏 在这篇博文中,我们将详细介绍如何使用HTML、CSS和JavaScript开发一个简单的五子棋小游戏。我们将展示如何初始化棋盘、处理用户交互以及实现胜负判定。特别是,我们将着重介绍胜负判定的逻辑实现。 完整代码我放在了这里&a…

push to origin/master was rejected解决方案之一

如果你是git小白,并且其他帖子的方法都不行,可以一试 在你的远程库(我这个是gitee)设置中的邮箱设置里不勾这个选项 然后就没有然后了。

宣布推出 Search AI Lake 和 Elastic Cloud Serverless 以扩展低延迟搜索

作者:来自 Elastic Ken Exner 今天,我们很高兴地宣布 Search AI Lake 和 Elastic Cloud Serverless。 Search AI Lake 是一种针对实时应用程序进行优化的开创性云原生架构,它将扩展的存储容量与低延迟查询以及 Elasticsearch 强大的搜索和 AI…

视频监控平台智能边缘分析一体机视频存储平台打手机检测算法

智能边缘分析一体机的打手机检测算法是一种集成了先进图像处理、计算机视觉和人工智能技术的解决方案,专门用于实时监测和识别监控场景中的打手机行为。 在提到“打手机检测算法”时,可能是指一种能够识别和检测使用手机行为的算法。这种算法可以应用于多…

力扣HOT100 - 300. 最长递增子序列

解题思路&#xff1a; 动态规划 class Solution {public int lengthOfLIS(int[] nums) {if (nums.length 0) return 0;int[] dp new int[nums.length];int max 0;Arrays.fill(dp, 1);for (int i 0; i < nums.length; i) {for (int j 0; j < i; j) {if (nums[j] <…

文字生成数字员工!实在AI Agent化身“六边形战士”落地千行百业

2023年8月&#xff0c;实在智能在全行业首发“一句话生成数字员工”的实在AI Agent智能体产品&#xff0c;即实在Agent智能体&#xff0c;也是TARS-RPA Agent智能体数字员工&#xff0c;其同时具备LLM大模型的对话式交互能力和RPA的流程自动化能力&#xff0c;有“大脑”&#…

C# .Net8 switch 的用法

在 .net 8中&#xff0c;switch 不需要再和传统的写法一样了&#xff0c;会更加的方便 创建一个 .net 8 控制台项目 switch 的写法没必要和以前一样 namespace SwitchTest {internal class Program{static void Main(string[] args){int day 3;var week day switch{1 > &…

Go语言不再难!跟随ChatGPT轻松攻克编程难关

开发人员&#xff08;包括我在内&#xff09;通常偏好边学习边实践的方式。这不仅仅是我与LLM协作的核心准则之一&#xff0c;也是最关键的准则&#xff1a;因为你是在任务导向的学习过程中积累知识&#xff0c;这种学习方式不是预先的——它基于实时的、可感知的情境。 当资深…

安防监控视频平台EasyNVR级联视频上云系统EasyNVS出现“Login error”报错

EasyNVR安防视频云平台是旭帆科技TSINGSEE青犀旗下支持RTSP/Onvif协议接入的安防监控流媒体视频云平台。平台具备视频实时监控直播、云端录像、云存储、录像检索与回看、告警等视频能力&#xff0c;能对接入的视频流进行处理与多端分发&#xff0c;包括RTSP、RTMP、HTTP-FLV、W…

##21 深入理解文本处理:使用PyTorch进行NLP基础操作

文章目录 前言简介文本预处理实现分词构建词汇表 文本向量化构建简单的文本分类模型结论 前言 在现代深度学习应用中&#xff0c;文本处理是不可或缺的一部分&#xff0c;尤其在自然语言处理&#xff08;NLP&#xff09;领域。借助强大的框架如PyTorch&#xff0c;我们可以更加…