| 1 |
package jwt |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/base64" |
| 5 |
"encoding/json" |
| 6 |
"strings" |
| 7 |
|
| 8 |
jwtparser "github.com/golang-jwt/jwt/v5" |
| 9 |
|
| 10 |
"github.com/DefangLabs/secret-detector/pkg/detectors/helpers" |
| 11 |
"github.com/DefangLabs/secret-detector/pkg/secrets" |
| 12 |
) |
| 13 |
|
| 14 |
const ( |
| 15 |
Name = "jwt" |
| 16 |
secretType = "JSON Web Token" |
| 17 |
jwtRegex = `eyJ[A-Za-z0-9-_=]+\.eyJ[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*` |
| 18 |
) |
| 19 |
|
| 20 |
func init() { |
| 21 |
secrets.GetDetectorFactory().Register(Name, NewDetector) |
| 22 |
} |
| 23 |
|
| 24 |
type detector struct { |
| 25 |
secrets.Detector |
| 26 |
jwtParser *jwtparser.Parser |
| 27 |
} |
| 28 |
|
| 29 |
func NewDetector(config ...string) secrets.Detector { |
| 30 |
d := &detector{} |
| 31 |
d.jwtParser = &jwtparser.Parser{} |
| 32 |
d.Detector = helpers.NewRegexDetectorBuilder(secretType, jwtRegex).WithVerifier(d.isTokenValid).Build() |
| 33 |
return d |
| 34 |
} |
| 35 |
|
| 36 |
func (d *detector) isTokenValid(_, token string) bool { |
| 37 |
numberOfSegments := strings.Count(token, ".") + 1 |
| 38 |
if numberOfSegments == 2 { |
| 39 |
return d.ensureUnsignedTokenValidity(token) |
| 40 |
} else if numberOfSegments == 3 { |
| 41 |
return d.ensureSignedTokenValidity(token) |
| 42 |
} |
| 43 |
|
| 44 |
return false |
| 45 |
} |
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
func (d *detector) ensureUnsignedTokenValidity(token string) bool { |
| 51 |
parts := strings.Split(token, ".") |
| 52 |
if len(parts) != 2 { |
| 53 |
|
| 54 |
return false |
| 55 |
} |
| 56 |
|
| 57 |
header, headerOk := base64ToMap(parts[0]) |
| 58 |
if !headerOk { |
| 59 |
return false |
| 60 |
} |
| 61 |
if header["alg"] != "none" { |
| 62 |
return false |
| 63 |
} |
| 64 |
|
| 65 |
_, payloadOk := base64ToMap(parts[1]) |
| 66 |
return payloadOk |
| 67 |
|
| 68 |
} |
| 69 |
|
| 70 |
func (d *detector) ensureSignedTokenValidity(token string) bool { |
| 71 |
_, _, err := d.jwtParser.ParseUnverified(token, jwtparser.MapClaims{}) |
| 72 |
return err == nil |
| 73 |
} |
| 74 |
|
| 75 |
func base64ToMap(s string) (map[string]interface{}, bool) { |
| 76 |
bytes, err := base64.RawStdEncoding.DecodeString(s) |
| 77 |
if err != nil { |
| 78 |
return nil, false |
| 79 |
} |
| 80 |
|
| 81 |
var keyValueMap map[string]interface{} |
| 82 |
err = json.Unmarshal(bytes, &keyValueMap) |
| 83 |
if err != nil { |
| 84 |
return nil, false |
| 85 |
} |
| 86 |
return keyValueMap, true |
| 87 |
} |