Skip to content

Commit

Permalink
Added more Cerberus reason for checking source ip (#24)
Browse files Browse the repository at this point in the history
* Impliment last public ip logic

* Change order of remoteAddr and x-forwarded-for

* Added more reason for checking source ip

---------

Co-authored-by: Pedram Sadeghian <pedram.sadeghian@snapp.cab>
  • Loading branch information
pedy4000 and Pedram Sadeghian authored Nov 4, 2023
1 parent 2c02df4 commit 7db7ce2
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions pkg/auth/authenticator.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@ const (
// CerberusReasonInvalidSourceIp means that source ip in remoteAddre is not valid
CerberusReasonInvalidSourceIp CerberusReason = "invalid-source-ip"

// CerberusReasonEmptySourceIp means that source ip is empty
CerberusReasonEmptySourceIp CerberusReason = "source-ip-empty"

// CerberusReasonBadIpList means that there is no valid public ip for validation
CerberusReasonNoValidIp CerberusReason = "no-valid-ip"

Expand Down Expand Up @@ -277,6 +280,9 @@ func (a *Authenticator) TestAccess(request *Request, wsvc ServicesCacheEntry) (b
if err != nil {
return false, CerberusReasonInvalidSourceIp, newExtraHeaders
}
if net.ParseIP(host) == nil {
return false, CerberusReasonEmptySourceIp, newExtraHeaders
}
ipList = append(ipList, host)

if token == "" {
Expand All @@ -291,8 +297,8 @@ func (a *Authenticator) TestAccess(request *Request, wsvc ServicesCacheEntry) (b

// Check x-forwarded-for header against IP allow list
if len(ac.Spec.IpAllowList) > 0 {
publicIp, err := lastPublicIp(ipList)
if err != nil {
publicIp := lastPublicIp(ipList)
if publicIp == "" {
return false, CerberusReasonNoValidIp, newExtraHeaders
}
ipAllowed, err := checkIP(publicIp, ac.Spec.IpAllowList)
Expand Down Expand Up @@ -405,14 +411,14 @@ func NewAuthenticator(logger logr.Logger) (*Authenticator, error) {

// lastPublicIp will identify the last valid public IP address within the list of IPs
// will return an error if it cannot find any valid public IP addresses in the input list.
func lastPublicIp(ips []string) (string, error) {
func lastPublicIp(ips []string) string {
for i := len(ips) - 1; i >= 0; i-- {
clientIP := net.ParseIP(ips[i])
if clientIP != nil && !clientIP.IsPrivate() {
return ips[i], nil
return ips[i]
}
}
return "", nil
return ""
}

// checkIP checks if given ip is a member of given CIDR networks or not
Expand Down

0 comments on commit 7db7ce2

Please sign in to comment.