File: scanning_manager.go

package info (click to toggle)
gitlab-agent 16.11.5-1
  • links: PTS, VCS
  • area: contrib
  • in suites: experimental
  • size: 7,072 kB
  • sloc: makefile: 193; sh: 55; ruby: 3
file content (264 lines) | stat: -rw-r--r-- 9,526 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package agent

import (
	"bytes"
	"compress/gzip"
	"context"
	"encoding/base64"
	"errors"
	"fmt"
	"io"
	"strconv"
	"strings"
	"time"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/module/starboard_vulnerability/agent/converter"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/module/starboard_vulnerability/agent/resources"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/tool/logz"
	"gitlab.com/gitlab-org/security-products/analyzers/trivy-k8s-wrapper/data/analyzers/report"
	"gitlab.com/gitlab-org/security-products/analyzers/trivy-k8s-wrapper/data/errorcodes"
	"gitlab.com/gitlab-org/security-products/analyzers/trivy-k8s-wrapper/prototool"
	"go.uber.org/zap"
	"google.golang.org/protobuf/proto"
	corev1 "k8s.io/api/core/v1"
	k8errors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/watch"
	"k8s.io/client-go/kubernetes"
)

const (
	labelTrivyVersion = "agent.gitlab.com/trivy-version"
	labelOcsNext      = "agent.gitlab.com/ocs-next"
	labelOcsNamespace = "agent.gitlab.com/ocs-ns"
	labelAgentID      = "agent.gitlab.com/agent-id"
)

var workloads = strings.Join([]string{
	kindPod,
	kindReplicaSet,
	kindReplicationController,
	kindStatefulSet,
	kindDaemonSet,
	kindCronJob,
	kindJob,
}, ",")

type scanningManager struct {
	kubeClientset        kubernetes.Interface
	resourcesManager     resources.Resources
	agentID              int64
	gitlabAgentNamespace string
	scanLogger           *zap.Logger
}

func (s *scanningManager) getScanningPodSpecs(podName string, targetNamespace string, ocsServiceAccountName string) (*corev1.Pod, error) {
	rq, err := s.resourcesManager.GetResources()
	if err != nil {
		return nil, err
	}

	return &corev1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:      podName,
			Namespace: s.gitlabAgentNamespace,
		},
		Spec: corev1.PodSpec{
			ServiceAccountName: ocsServiceAccountName,
			Containers: []corev1.Container{
				{
					Name:            "trivy",
					ImagePullPolicy: corev1.PullIfNotPresent,
					Resources: corev1.ResourceRequirements{
						Limits: corev1.ResourceList{
							corev1.ResourceMemory: rq.LimitsMemory,
							corev1.ResourceCPU:    rq.LimitsCPU,
						},
						Requests: corev1.ResourceList{
							corev1.ResourceMemory: rq.RequestsMemory,
							corev1.ResourceCPU:    rq.RequestsCPU,
						},
					},
					Image: trivyK8sWrapper,
					Env: []corev1.EnvVar{
						{
							Name:  "NAMESPACE",
							Value: targetNamespace,
						},
						{
							Name:  "GITLAB_AGENT_ID",
							Value: strconv.FormatInt(s.agentID, 10),
						},
						{
							Name:  "GITLAB_AGENT_NS",
							Value: s.gitlabAgentNamespace,
						},
						{
							Name:  "WORKLOADS",
							Value: workloads,
						},
					},
				},
			},
			RestartPolicy: corev1.RestartPolicyNever,
		},
	}, nil
}

// deleteChainedConfigmaps deletes a chain of configmaps (1 or more configmaps chained by labels) for a certain
// target scan namespace. We delete chained configmaps based on the label agent.gitlab.com/ocs-ns=<TARGET_NAMESPACE>
func (s *scanningManager) deleteChainedConfigmaps(ctx context.Context, targetNamespace string) error {
	labelSelector := fmt.Sprintf("%s=%s, %s=%d", labelOcsNamespace, targetNamespace, labelAgentID, s.agentID)
	cms, err := s.kubeClientset.CoreV1().ConfigMaps(s.gitlabAgentNamespace).
		List(ctx, metav1.ListOptions{LabelSelector: labelSelector})
	if err != nil {
		return fmt.Errorf("could not list existing configmaps: %w", err)
	}
	for _, cm := range cms.Items {
		if err := s.kubeClientset.CoreV1().ConfigMaps(s.gitlabAgentNamespace).Delete(ctx, cm.GetName(), metav1.DeleteOptions{}); err != nil {
			return fmt.Errorf("could not delete pre-existing ConfigMap: %w", err)
		}
	}
	return nil

}

// deployScanningPod deploys the scanning pod in the gitlab-agent namespace. If the pod already exists from a
// previous run it deletes it and exits with an error.
func (s *scanningManager) deployScanningPod(ctx context.Context, pod *corev1.Pod, podName string) error {
	if _, errP := s.kubeClientset.CoreV1().Pods(s.gitlabAgentNamespace).Create(ctx, pod, metav1.CreateOptions{}); errP != nil {
		// There could be a scenario where The previous OCS Scanning Pod was not deleted.
		// Delete the Pod to ensure that the next scan would be successful.
		if k8errors.IsAlreadyExists(errP) {
			s.scanLogger.Debug("OCS Scanning Pod already exists, deleting")
			if err := s.kubeClientset.CoreV1().Pods(s.gitlabAgentNamespace).Delete(ctx, podName, metav1.DeleteOptions{}); err != nil {
				return fmt.Errorf("could not delete pod: %w", err)
			}
			return errors.New("pod exists. Deleted Pod")
		}
		return errP
	}
	return nil
}

func (s *scanningManager) deleteScanningPod(podName string) error {
	// Using a separate context in the event that the context was canceled.
	deleteCtx, deleteCtxCancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer deleteCtxCancel()
	err := s.kubeClientset.CoreV1().Pods(s.gitlabAgentNamespace).Delete(deleteCtx, podName, metav1.DeleteOptions{})
	return err
}

func (s *scanningManager) watchScanningPod(ctx context.Context, podName string) (watch.Interface, error) {
	return s.kubeClientset.CoreV1().Pods(s.gitlabAgentNamespace).Watch(ctx, metav1.ListOptions{
		FieldSelector: fmt.Sprintf("metadata.name=%s", podName),
	})
}

var exitCodes = map[int32]string{
	errorcodes.KubeClient:           "failed to initialize a kube client",
	errorcodes.FlagsValidation:      "flags validation failed",
	errorcodes.TrivyVersion:         "failed to get Trivy scanner version",
	errorcodes.TrivyScan:            "failed to execute a Trivy scan",
	errorcodes.SizeLimit:            "trivy report size limit",
	errorcodes.DataConvertion:       "could not get a data converter",
	errorcodes.ToConsolidatedReport: "failed to convert Trivy to consolidated report",
	errorcodes.PrepareData:          "failed to prepare data",
	errorcodes.ChainedConfigmaps:    "failed to create chained ConfigMaps",
}

func (s *scanningManager) extractExitCodeError(code int32, reason string) error {
	if code == 0 {
		return nil
	}
	str, ok := exitCodes[code]
	if !ok {
		return fmt.Errorf("OCS Scanning pod exited with unknown exit code: %v, reason: %s", code, reason)
	}
	return fmt.Errorf("%s | Reason = %s", str, reason)
}

func (s *scanningManager) readChainedConfigmaps(ctx context.Context, targetNamespace string) ([]byte, string, error) {
	// we know the first ConfigMap name
	cmName := fmt.Sprintf("ocs-%s-%d-1", targetNamespace, s.agentID)
	var allData []byte
	trivyVersion := ""
	for {
		s.scanLogger.Info("Reading ConfigMap", logz.K8sObjectName(cmName))
		// Each namespace scan will return 1 vulnerability based on the response from ParsePodLogsToReport. As there are 2 namespaces this will result in 2 vulnerabilities to be transmitted to Gitlab.
		cm, err := s.kubeClientset.CoreV1().ConfigMaps(s.gitlabAgentNamespace).Get(ctx, cmName, metav1.GetOptions{})
		if err != nil {
			return nil, "", fmt.Errorf("could not read chained ConfigMap %s: %w", cmName, err)
		}
		bytes, ok := cm.BinaryData["data"]
		if !ok {
			return nil, "", errors.New("ConfigMap did not contain data field in binaryData")
		}
		allData = append(allData, bytes...)

		cmName, ok = cm.ObjectMeta.Labels[labelOcsNext]
		if !ok {
			// we are done
			// before breaking read the trivy version
			v, ok := cm.ObjectMeta.Labels[labelTrivyVersion]
			if !ok {
				s.scanLogger.Warn(fmt.Sprintf("Missing %s label from ConfigMap", labelTrivyVersion))
			} else {
				trivyVersion = v
			}
			break
		}
	}
	return allData, trivyVersion, nil
}

func (s *scanningManager) parseScaningPodPayload(data []byte, trivyVersion string) ([]*Payload, error) {
	gzDataBytes, err := base64.StdEncoding.DecodeString(string(data))
	if err != nil {
		return nil, fmt.Errorf("could not decode data: %w", err)
	}

	gzipReader, err := gzip.NewReader(bytes.NewReader(gzDataBytes))
	if err != nil {
		return nil, fmt.Errorf("could not initialize a gzip reader: %w", err)
	}

	protobufBytes, err := io.ReadAll(gzipReader)
	if err != nil {
		return nil, fmt.Errorf("could not read gzip data: %w", err)
	}

	payload := &prototool.Payload{}
	err = proto.Unmarshal(protobufBytes, payload)
	if err != nil {
		return nil, fmt.Errorf("could not read protobuffer format data: %w", err)
	}

	return s.toVulnerabilityAPIPayload(payload, trivyVersion)

}

// toVulnerabilityAPIPayload gets a prototool version of the Starboard Vulnerability payload and transforms it into
// a Starboard Vulnerability payload. This payload is what we expect at the create starboard vulnerability api
// https://docs.gitlab.com/ee/development/internal_api/#create-starboard-vulnerability
func (s *scanningManager) toVulnerabilityAPIPayload(p *prototool.Payload, trivyVersion string) ([]*Payload, error) {
	payloads := make([]*Payload, len(p.Vulnerabilities))
	protoConverter := converter.Converter{}
	for i, v := range p.Vulnerabilities {
		payloads[i] = &Payload{
			Vulnerability: &report.Vulnerability{
				Name:        v.Name,
				Message:     v.Message,
				Description: v.Description,
				Solution:    v.Solution,
				Severity:    protoConverter.ToSeverity(v.Severity),
				Confidence:  report.ParseConfidenceLevel(v.Confidence),
				Identifiers: protoConverter.ToIdentifiers(v.Identifiers),
				Links:       protoConverter.ToLinks(v.Links),
				Location:    protoConverter.ToLocation(v.Location),
			},
			Scanner: getTrivyScannerPayload(trivyVersion),
		}
	}
	return payloads, nil
}