/
pypi.go
163 lines (138 loc) · 4.68 KB
/
pypi.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
package processor
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/jordan-wright/ossmalware/pkg/library"
)
const TypePyPI = "pypi"
const PyPISimpleURL = "https://pypi.org/simple/"
const BaseImagePyPI = "python:3-alpine"
var IgnoredHostsPyPI = []string{"pypi.org", "files.pythonhosted.org"}
var SysdigFiltersPyPI = []string{
"not (fd.sip.name=pypi.org or fd.cip.name=pypi.org)",
"not (fd.sip.name=files.pythonhosted.org or fd.cip.name=files.pythonhosted.org)",
}
// SysdigFiltersIgnorePyPI is the list of sysdig events that might appear
// suspicious, but are known parts of Python package installation.
//
// No, these aren't perfect, but the goal is catching the low-hanging fruit and
// we can iterate as we go.
var SysdigFiltersIgnorePyPI = []string{
"not (proc.exeline='uname -p')",
"not (proc.exeline='uname -rs')",
"not (proc.exeline contains '/usr/local/bin/python -c import sys, setuptools, tokenize; sys.argv[0]')",
"not (proc.exeline contains '/usr/local/bin/python -u -c import sys, setuptools, tokenize; sys.argv[0]')",
"not (fd.name contains '/usr/local/lib/python3.8/')", // Might need to make this more granular
"not (fd.name contains '/lib/' and evt.arg.flags contains O_RDONLY)",
}
type PyPIProcessor struct {
BaseProcessor
}
func NewPyPIProcessor() *PyPIProcessor {
return &PyPIProcessor{
BaseProcessor: BaseProcessor{
Output: &library.Output{},
},
}
}
// fetchMetadata is a temporary struct to only parse out the Python package
// version in cases where we don't already have it.
type fetchMetadata struct {
Info infoMetadata `json:"info"`
}
type infoMetadata struct {
Version string `json:"version"`
}
func (p *PyPIProcessor) fetchMetadata(pkg *library.Package, outputDir string) (string, error) {
url := fmt.Sprintf("https://pypi.org/pypi/%s", pkg.Name)
if pkg.Version != "" {
url += fmt.Sprintf("/%s", pkg.Version)
}
url += "/json"
log.Printf("fetching metadata for %s", url)
response, err := http.Get(url)
if err != nil {
return "", err
}
defer response.Body.Close()
metadata, err := ioutil.ReadAll(response.Body)
if err != nil {
return "", fmt.Errorf("error reading response body: %w", err)
}
var parsedMetadata fetchMetadata
err = json.Unmarshal(metadata, &parsedMetadata)
if err != nil {
return "", fmt.Errorf("error parsing metadata json: %w", err)
}
pkg.Version = parsedMetadata.Info.Version
metadataFilename := filepath.Join(outputDir, fmt.Sprintf("%s_metadata.json", pkg.ID()))
return metadataFilename, ioutil.WriteFile(metadataFilename, metadata, 0644)
}
func (p *PyPIProcessor) Process(ctx context.Context, cli *client.Client, pkg library.Package) (*library.Output, error) {
wd, _ := os.Getwd()
metadataPath, err := p.fetchMetadata(&pkg, wd)
if err != nil {
return nil, err
}
p.PackageID = pkg.ID()
p.Output.Files = append(p.Output.Files, metadataPath)
err = p.StartMonitoring(ctx, cli)
if err != nil {
return nil, err
}
log.Printf("Creating container: %s", p.PackageID)
resp, err := cli.ContainerCreate(ctx, &container.Config{
Image: BaseImagePyPI,
Tty: false,
Cmd: []string{"pip", "install", "--no-cache-dir", fmt.Sprintf("%s==%s", pkg.Name, pkg.Version)},
}, &container.HostConfig{NetworkMode: p.BaseProcessor.tcpdumpContainer.NetworkMode()}, nil, pkg.ID())
if err != nil {
p.StopMonitoring()
return nil, err
}
log.Printf("Starting container: %s", p.PackageID)
if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
p.StopMonitoring()
return nil, err
}
statusCh, errCh := cli.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning)
select {
case err := <-errCh:
if err != nil {
p.StopMonitoring()
return nil, err
}
case <-statusCh:
}
log.Printf("Removing container: %s", p.PackageID)
err = cli.ContainerRemove(ctx, resp.ID, types.ContainerRemoveOptions{})
if err != nil {
p.StopMonitoring()
return nil, err
}
err = p.StopMonitoring()
if err != nil {
return nil, err
}
p.Output.Package = pkg
sysdigIgnoredFilters := []string{}
for _, filter := range SysdigFiltersIgnorePyPI {
sysdigIgnoredFilters = append(sysdigIgnoredFilters, filter)
}
// To keep the logs clean, don't log this specific command
sysdigIgnoredFilters = append(sysdigIgnoredFilters, fmt.Sprintf("not ((evt.type=execve or evt.type=execveat) and proc.exeline='/usr/local/bin/python /usr/local/bin/pip install --no-cache-dir %s==%s')", pkg.Name, pkg.Version))
err = p.parseBehavior(sysdigIgnoredFilters, IgnoredHostsPyPI...)
if err != nil {
return nil, fmt.Errorf("error parsing output: %w", err)
}
return p.Output, nil
}