2020-02-19 05:15:09 +07:00
|
|
|
package authorization
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"strings"
|
2021-01-04 17:55:23 +07:00
|
|
|
|
|
|
|
"github.com/authelia/authelia/internal/configuration/schema"
|
|
|
|
"github.com/authelia/authelia/internal/logging"
|
2020-02-19 05:15:09 +07:00
|
|
|
)
|
|
|
|
|
2021-01-04 17:55:23 +07: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 {
|
|
|
|
_, ipNet, err := net.ParseCIDR(network)
|
|
|
|
if err != nil {
|
|
|
|
logging.Logger().Errorf("Failed to parse network %s: %s", network, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if ipNet.Contains(ip) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-02-19 05:15:09 +07:00
|
|
|
// isIPMatching check whether user's IP is in one of the network ranges.
|
2021-01-04 17:55:23 +07:00
|
|
|
func isIPMatching(ip net.IP, networks []string, aclNetworks []schema.ACLNetwork) bool {
|
2020-02-19 05:15:09 +07:00
|
|
|
// If no network is provided in the rule, we match any network
|
|
|
|
if len(networks) == 0 {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2021-01-04 17:55:23 +07:00
|
|
|
matchingNetworkGroups := selectMatchingNetworkGroups(networks, aclNetworks)
|
|
|
|
|
2020-02-19 05:15:09 +07:00
|
|
|
for _, network := range networks {
|
2021-01-04 17:55:23 +07: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-19 05:15:09 +07:00
|
|
|
}
|
2021-01-04 17:55:23 +07:00
|
|
|
} else if isIPAddressOrCIDR(ip, network) {
|
2020-02-19 05:15:09 +07:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
2020-05-06 02:35:32 +07:00
|
|
|
|
2020-02-19 05:15:09 +07:00
|
|
|
return false
|
|
|
|
}
|