/
registry.go
301 lines (265 loc) · 7.67 KB
/
registry.go
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// SPDX-License-Identifier: Apache-2.0
// Copyright 2023 Authors of KubeArmor
// Package registry contains scanner for image info
package registry
import (
"archive/tar"
"bufio"
"context"
_ "embed" // need for embedding
"encoding/base64"
"encoding/json"
"fmt"
"io"
"math/rand"
"os"
"path/filepath"
"strings"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/jsonmessage"
image "github.com/kubearmor/kubearmor-client/recommend/image"
"github.com/moby/term"
dockerTypes "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/registry"
kg "github.com/kubearmor/KubeArmor/KubeArmor/log"
"github.com/kubearmor/kubearmor-client/hacks"
log "github.com/sirupsen/logrus"
)
const karmorTempDirPattern = "karmor"
// Scanner represents a utility for scanning Docker registries
type Scanner struct {
authConfiguration authConfigurations
cli *client.Client // docker client
cache map[string]image.Info
}
// authConfigurations contains the configuration information's
type authConfigurations struct {
configPath string // stores path of docker config.json
authCreds []string
}
func getAuthStr(u, p string) string {
if u == "" || p == "" {
return ""
}
encodedJSON, err := json.Marshal(registry.AuthConfig{
Username: u,
Password: p,
})
if err != nil {
log.WithError(err).Fatal("failed to marshal credentials")
}
return base64.URLEncoding.EncodeToString(encodedJSON)
}
func (r *Scanner) loadDockerAuthConfigs() {
r.authConfiguration.authCreds = append(r.authConfiguration.authCreds, fmt.Sprintf("%s:%s", os.Getenv("DOCKER_USERNAME"), os.Getenv("DOCKER_PASSWORD")))
if r.authConfiguration.configPath != "" {
data, err := os.ReadFile(filepath.Clean(r.authConfiguration.configPath))
if err != nil {
return
}
confsWrapper := struct {
Auths map[string]registry.AuthConfig `json:"auths"`
}{}
err = json.Unmarshal(data, &confsWrapper)
if err != nil {
return
}
for _, conf := range confsWrapper.Auths {
data, _ := base64.StdEncoding.DecodeString(conf.Auth)
userPass := strings.SplitN(string(data), ":", 2)
r.authConfiguration.authCreds = append(r.authConfiguration.authCreds, getAuthStr(userPass[0], userPass[1]))
}
}
}
// New creates and initializes a new instance of the Scanner
func New(dockerConfigPath string) *Scanner {
var err error
scanner := Scanner{
authConfiguration: authConfigurations{
configPath: dockerConfigPath,
},
cache: make(map[string]image.Info),
}
if err != nil {
log.WithError(err).Error("could not create temp dir")
}
scanner.cli, err = client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
log.WithError(err).Fatal("could not create new docker client")
}
scanner.loadDockerAuthConfigs()
return &scanner
}
// Analyze performs analysis and caching of image information using the Scanner
func (r *Scanner) Analyze(img *image.Info) {
if val, ok := r.cache[img.Name]; ok {
log.WithFields(log.Fields{
"image": img.Name,
}).Infof("Image already scanned in this session, using cached informations for image")
img.Arch = val.Arch
img.DirList = val.DirList
img.FileList = val.FileList
img.Distro = val.Distro
img.Labels = val.Labels
img.OS = val.OS
img.RepoTags = val.RepoTags
return
}
tmpDir, err := os.MkdirTemp("", karmorTempDirPattern)
if err != nil {
log.WithError(err).Error("could not create temp dir")
}
defer func() {
err = os.RemoveAll(tmpDir)
if err != nil {
log.WithError(err).Error("failed to remove cache files")
}
}()
img.TempDir = tmpDir
err = r.pullImage(img.Name)
if err != nil {
log.Warn("Failed to pull image. Dumping generic policies.")
img.OS = "linux"
img.RepoTags = append(img.RepoTags, img.Name)
} else {
tarname := saveImageToTar(img.Name, r.cli, tmpDir)
img.FileList, img.DirList = extractTar(tarname, tmpDir)
img.GetImageInfo()
}
r.cache[img.Name] = *img
}
// The randomizer used in this function is not used for any cryptographic
// operation and hence safe to use.
func randString(n int) string {
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))] // #nosec
}
return string(b)
}
func (r *Scanner) pullImage(imageName string) (err error) {
log.WithFields(log.Fields{
"image": imageName,
}).Info("pulling image")
var out io.ReadCloser
for _, cred := range r.authConfiguration.authCreds {
out, err = r.cli.ImagePull(context.Background(), imageName,
dockerTypes.ImagePullOptions{
RegistryAuth: cred,
})
if err == nil {
break
}
}
if err != nil {
return err
}
defer func() {
if err := out.Close(); err != nil {
kg.Warnf("Error closing io stream %s\n", err)
}
}()
termFd, isTerm := term.GetFdInfo(os.Stderr)
err = jsonmessage.DisplayJSONMessagesStream(out, os.Stderr, termFd, isTerm, nil)
if err != nil {
log.WithError(err).Error("could not display json")
}
return
}
// Sanitize archive file pathing from "G305: Zip Slip vulnerability"
func sanitizeArchivePath(d, t string) (v string, err error) {
v = filepath.Join(d, t)
if strings.HasPrefix(v, filepath.Clean(d)) {
return v, nil
}
return "", fmt.Errorf("%s: %s", "content filepath is tainted", t)
}
func extractTar(tarname string, tempDir string) ([]string, []string) {
var fl []string
var dl []string
f, err := os.Open(filepath.Clean(tarname))
if err != nil {
log.WithError(err).WithFields(log.Fields{
"tar": tarname,
}).Fatal("os create failed")
}
defer hacks.CloseCheckErr(f, tarname)
tr := tar.NewReader(bufio.NewReader(f))
for {
hdr, err := tr.Next()
if err == io.EOF {
break // End of archive
}
if err != nil {
log.WithError(err).Fatal("tar next failed")
}
tgt, err := sanitizeArchivePath(tempDir, hdr.Name)
if err != nil {
log.WithError(err).WithFields(log.Fields{
"file": hdr.Name,
}).Error("ignoring file since it could not be sanitized")
continue
}
switch hdr.Typeflag {
case tar.TypeDir:
if _, err := os.Stat(tgt); err != nil {
if err := os.MkdirAll(tgt, 0750); err != nil {
log.WithError(err).WithFields(log.Fields{
"target": tgt,
}).Fatal("tar mkdirall")
}
}
dl = append(dl, tgt)
case tar.TypeReg:
f, err := os.OpenFile(filepath.Clean(tgt), os.O_CREATE|os.O_RDWR, os.FileMode(hdr.Mode))
if err != nil {
log.WithError(err).WithFields(log.Fields{
"target": tgt,
}).Error("tar open file")
} else {
// copy over contents
if _, err := io.CopyN(f, tr, 2e+9 /*2GB*/); err != io.EOF {
log.WithError(err).WithFields(log.Fields{
"target": tgt,
}).Fatal("tar io.Copy()")
}
}
hacks.CloseCheckErr(f, tgt)
if strings.HasSuffix(tgt, "layer.tar") { // deflate container image layer
ifl, idl := extractTar(tgt, tempDir)
fl = append(fl, ifl...)
dl = append(dl, idl...)
} else {
fl = append(fl, tgt)
}
}
}
return fl, dl
}
func saveImageToTar(imageName string, cli *client.Client, tempDir string) string {
imgdata, err := cli.ImageSave(context.Background(), []string{imageName})
if err != nil {
log.WithError(err).Fatal("could not save image")
}
defer func() {
if err := imgdata.Close(); err != nil {
kg.Warnf("Error closing io stream %s\n", err)
}
}()
tarname := filepath.Join(tempDir, randString(8)+".tar")
f, err := os.Create(filepath.Clean(tarname))
if err != nil {
log.WithError(err).Fatal("os create failed")
}
if _, err := io.CopyN(bufio.NewWriter(f), imgdata, 5e+9 /*5GB*/); err != io.EOF {
log.WithError(err).WithFields(log.Fields{
"tar": tarname,
}).Fatal("io.CopyN() failed")
}
hacks.CloseCheckErr(f, tarname)
log.WithFields(log.Fields{
"tar": tarname,
}).Info("dumped image to tar")
return tarname
}