-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
defan.go
87 lines (73 loc) · 1.98 KB
/
defan.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
/*
defango - URL / IP / Email defanging with Golang. Make IoC harmless.
This repository is under MIT License https://github.com/edoardottt/defango/blob/main/LICENSE
*/
package defango
import (
"errors"
"net/url"
"strings"
)
var (
ErrUnsupportedInputType = errors.New("unsupported input type")
)
// IP returns a defanged IP.
// Support both IPv4 and IPv6.
func IP(input string) string {
result := ""
if strings.Contains(input, "::") { // IPv6 with double column
index := strings.Index(input, "::")
result = strings.ReplaceAll(input[:index], ":", "[:]") +
"[::]" +
strings.ReplaceAll(input[index+2:], ":", "[:]")
} else { // Full IPv6 or IPv4
result = strings.ReplaceAll(strings.ReplaceAll(input, ".", "[.]"), ":", "[:]")
}
return result
}
// URL returns a defanged URL.
// Accept string and url.URL.
// For security reasons, if the url is not formatted in a proper way
// the result is an empty string with a non-nil error.
func URL(input interface{}) (string, error) {
switch v := input.(type) {
case string:
return defangURL(v)
case url.URL:
return defangURL(v.String())
default:
return "", ErrUnsupportedInputType
}
}
func defangURL(input string) (string, error) {
result := ""
if strings.Contains(input, "://") { // handle protocol
result += defangProtocols(input) + "://"
result += strings.ReplaceAll(
strings.ReplaceAll(
input[strings.Index(input, "://")+3:], ".", "[.]"),
":", "[:]")
} else {
result += strings.ReplaceAll(strings.ReplaceAll(input, ".", "[.]"), ":", "[:]")
}
return result, nil
}
func defangProtocols(input string) string {
protoMap := map[string]string{
"http": "hxxp",
"https": "hxxps",
"ftp": "fxp",
"file": "fxle",
}
proto := input[:strings.Index(input, "://")]
protoDefanged, ok := protoMap[proto]
if ok {
return protoDefanged
} else {
return proto
}
}
// Email returns a defanged email address/link.
func Email(input string) string {
return strings.ReplaceAll(strings.ReplaceAll(input, ".", "[.]"), ":", "[:]")
}