2020-09-23 03:54:32 +02:00
package validation
import (
"fmt"
"os"
"regexp"
"strings"
2020-10-05 21:39:44 +02:00
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
2020-09-23 03:54:32 +02:00
)
func validateAllowlists ( o * options . Options ) [ ] string {
msgs := [ ] string { }
2022-09-11 17:09:32 +02:00
msgs = append ( msgs , validateAuthRoutes ( o ) ... )
msgs = append ( msgs , validateAuthRegexes ( o ) ... )
2020-09-23 03:54:32 +02:00
msgs = append ( msgs , validateTrustedIPs ( o ) ... )
if len ( o . TrustedIPs ) > 0 && o . ReverseProxy {
_ , err := fmt . Fprintln ( os . Stderr , "WARNING: mixing --trusted-ip with --reverse-proxy is a potential security vulnerability. An attacker can inject a trusted IP into an X-Real-IP or X-Forwarded-For header if they aren't properly protected outside of oauth2-proxy" )
if err != nil {
panic ( err )
}
}
return msgs
}
2022-09-11 17:09:32 +02:00
// validateAuthRoutes validates method=path routes passed with options.SkipAuthRoutes
func validateAuthRoutes ( o * options . Options ) [ ] string {
2020-09-23 03:54:32 +02:00
msgs := [ ] string { }
for _ , route := range o . SkipAuthRoutes {
var regex string
2020-10-05 21:39:44 +02:00
parts := strings . SplitN ( route , "=" , 2 )
2020-09-23 03:54:32 +02:00
if len ( parts ) == 1 {
regex = parts [ 0 ]
} else {
2020-10-05 21:39:44 +02:00
regex = parts [ 1 ]
2020-09-23 03:54:32 +02:00
}
_ , err := regexp . Compile ( regex )
if err != nil {
msgs = append ( msgs , fmt . Sprintf ( "error compiling regex /%s/: %v" , regex , err ) )
}
}
return msgs
}
// validateRegex validates regex paths passed with options.SkipAuthRegex
2022-09-11 17:09:32 +02:00
func validateAuthRegexes ( o * options . Options ) [ ] string {
return validateRegexes ( o . SkipAuthRegex )
2020-09-23 03:54:32 +02:00
}
// validateTrustedIPs validates IP/CIDRs for IP based allowlists
func validateTrustedIPs ( o * options . Options ) [ ] string {
msgs := [ ] string { }
for i , ipStr := range o . TrustedIPs {
if nil == ip . ParseIPNet ( ipStr ) {
msgs = append ( msgs , fmt . Sprintf ( "trusted_ips[%d] (%s) could not be recognized" , i , ipStr ) )
}
}
return msgs
}
2022-09-11 17:09:32 +02:00
// validateAPIRoutes validates regex paths passed with options.ApiRoutes
func validateAPIRoutes ( o * options . Options ) [ ] string {
return validateRegexes ( o . APIRoutes )
}
// validateRegexes validates all regexes and returns a list of messages in case of error
func validateRegexes ( regexes [ ] string ) [ ] string {
msgs := [ ] string { }
for _ , regex := range regexes {
_ , err := regexp . Compile ( regex )
if err != nil {
msgs = append ( msgs , fmt . Sprintf ( "error compiling regex /%s/: %v" , regex , err ) )
}
}
return msgs
}