forked from visma-prodsec/confused
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pip.go
99 lines (92 loc) · 2.34 KB
/
pip.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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
)
// PythonLookup represents a collection of python packages to be tested for dependency confusion.
type PythonLookup struct {
Packages []string
Verbose bool
}
// NewPythonLookup constructs a `PythonLookup` struct and returns it
func NewPythonLookup(verbose bool) PackageResolver {
return &PythonLookup{Packages: []string{}, Verbose: verbose}
}
// ReadPackagesFromFile reads package information from a python `requirements.txt` file
//
// Returns any errors encountered
func (p *PythonLookup) ReadPackagesFromFile(filename string) error {
rawfile, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
line := ""
for _, l := range strings.Split(string(rawfile), "\n") {
l = strings.TrimSpace(l)
if strings.HasPrefix(l, "#") {
continue
}
if len(l) > 0 {
// Support line continuation
if strings.HasSuffix(l, "\\") {
line += l[:len(l) - 1]
continue
}
line += l
pkgrow := strings.FieldsFunc(line, p.pipSplit)
if len(pkgrow) > 0 {
p.Packages = append(p.Packages, strings.TrimSpace(pkgrow[0]))
}
// reset the line variable
line = ""
}
}
return nil
}
// PackagesNotInPublic determines if a python package does not exist in the pypi package repository.
//
// Returns a slice of strings with any python packages not in the pypi package repository
func (p *PythonLookup) PackagesNotInPublic() []string {
notavail := []string{}
for _, pkg := range p.Packages {
if !p.isAvailableInPublic(pkg) {
notavail = append(notavail, pkg)
}
}
return notavail
}
func (p *PythonLookup) pipSplit(r rune) bool {
delims := []rune{
'=',
'<',
'>',
'!',
' ',
'~',
'#',
'[',
}
return inSlice(r, delims)
}
// isAvailableInPublic determines if a python package exists in the pypi package repository.
//
// Returns true if the package exists in the pypi package repository.
func (p *PythonLookup) isAvailableInPublic(pkgname string) bool {
if p.Verbose {
fmt.Print("Checking: https://pypi.org/project/" + pkgname + "/ : ")
}
resp, err := http.Get("https://pypi.org/project/" + pkgname + "/")
if err != nil {
fmt.Printf(" [W] Error when trying to request https://pypi.org/project/"+pkgname+"/ : %s\n", err)
return false
}
if p.Verbose {
fmt.Printf("%s\n", resp.Status)
}
if resp.StatusCode == http.StatusOK {
return true
}
return false
}