2020-02-18 22:15:09 +00:00
|
|
|
package authorization
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"strings"
|
2021-01-04 10:55:23 +00:00
|
|
|
|
|
|
|
"github.com/authelia/authelia/internal/configuration/schema"
|
2020-02-18 22:15:09 +00:00
|
|
|
)
|
|
|
|
|
2021-01-04 10:55:23 +00:00
|
|
|
func selectMatchingNetworkGroups(networks []string, aclNetworks []schema.ACLNetwork) []schema.ACLNetwork {
|
|
|
|
selectedNetworkGroups := []schema.ACLNetwork{}
|
|
|
|
|
|
|
|
for _, network := range networks {
|
|
|
|
for _, n := range aclNetworks {
|
|
|
|
for _, ng := range n.Name {
|
|
|
|
if network == ng {
|
|
|
|
selectedNetworkGroups = append(selectedNetworkGroups, n)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return selectedNetworkGroups
|
|
|
|
}
|
|
|
|
|
|
|
|
func isIPAddressOrCIDR(ip net.IP, network string) bool {
|
|
|
|
switch {
|
|
|
|
case ip.String() == network:
|
|
|
|
return true
|
|
|
|
case strings.Contains(network, "/"):
|
|
|
|
return parseCIDR(ip, network)
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func parseCIDR(ip net.IP, network string) bool {
|
2021-01-16 10:05:41 +00:00
|
|
|
_, ipNet, _ := net.ParseCIDR(network)
|
|
|
|
return ipNet.Contains(ip)
|
2021-01-04 10:55:23 +00:00
|
|
|
}
|
|
|
|
|
2020-02-18 22:15:09 +00:00
|
|
|
// isIPMatching check whether user's IP is in one of the network ranges.
|
2021-01-04 10:55:23 +00:00
|
|
|
func isIPMatching(ip net.IP, networks []string, aclNetworks []schema.ACLNetwork) bool {
|
2020-02-18 22:15:09 +00:00
|
|
|
// If no network is provided in the rule, we match any network
|
|
|
|
if len(networks) == 0 {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2021-01-04 10:55:23 +00:00
|
|
|
matchingNetworkGroups := selectMatchingNetworkGroups(networks, aclNetworks)
|
|
|
|
|
2020-02-18 22:15:09 +00:00
|
|
|
for _, network := range networks {
|
2021-01-04 10:55:23 +00:00
|
|
|
if net.ParseIP(network) == nil && !strings.Contains(network, "/") {
|
|
|
|
for _, n := range matchingNetworkGroups {
|
|
|
|
for _, network := range n.Networks {
|
|
|
|
if isIPAddressOrCIDR(ip, network) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
2020-02-18 22:15:09 +00:00
|
|
|
}
|
2021-01-04 10:55:23 +00:00
|
|
|
} else if isIPAddressOrCIDR(ip, network) {
|
2020-02-18 22:15:09 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
2020-05-05 19:35:32 +00:00
|
|
|
|
2020-02-18 22:15:09 +00:00
|
|
|
return false
|
|
|
|
}
|