-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
ftp.go
103 lines (80 loc) · 2.34 KB
/
ftp.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
package ftp
import (
"context"
"net/url"
"regexp"
"strings"
"time"
"github.com/jlaffaye/ftp"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
)
type Scanner struct{}
// Ensure the Scanner satisfies the interface at compile time.
var _ detectors.Detector = (*Scanner)(nil)
var (
keyPat = regexp.MustCompile(`\bftp://[\S]{3,50}:([\S]{3,50})@[-.%\w\/:]+\b`)
)
// Keywords are used for efficiently pre-filtering chunks.
// Use identifiers in the secret preferably, or the provider name.
func (s Scanner) Keywords() []string {
return []string{"ftp://"}
}
// FromData will find and optionally verify URI secrets in a given set of bytes.
func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
dataStr := string(data)
matches := keyPat.FindAllStringSubmatch(dataStr, -1)
for _, match := range matches {
urlMatch := match[0]
password := match[1]
// Skip findings where the password only has "*" characters, this is a redacted password
if strings.Trim(password, "*") == "" {
continue
}
parsedURL, err := url.Parse(urlMatch)
if err != nil {
continue
}
if _, ok := parsedURL.User.Password(); !ok {
continue
}
if parsedURL.User.Username() == "anonymous" {
continue
}
rawURL, _ := url.Parse(urlMatch)
rawURL.Path = ""
redact := strings.TrimSpace(strings.Replace(rawURL.String(), password, "********", -1))
s := detectors.Result{
DetectorType: detectorspb.DetectorType_FTP,
Raw: []byte(rawURL.String()),
Redacted: redact,
}
if verify {
s.Verified = verifyFTP(ctx, parsedURL)
}
if !s.Verified {
// Skip unverified findings where the password starts with a `$` - it's almost certainly a variable.
if strings.HasPrefix(password, "$") {
continue
}
}
if detectors.IsKnownFalsePositive(string(s.Raw), []detectors.FalsePositive{"@ftp.freebsd.org"}, false) {
continue
}
results = append(results, s)
}
return results, nil
}
func verifyFTP(ctx context.Context, u *url.URL) bool {
host := u.Host
if !strings.Contains(host, ":") {
host = host + ":21"
}
c, err := ftp.Dial(host, ftp.DialWithTimeout(5*time.Second))
if err != nil {
return false
}
password, _ := u.User.Password()
err = c.Login(u.User.Username(), password)
return err == nil
}