Repository: kubernetes-sigs/cloud-provider-azure
Pull request #5123 (2023-12-06 04:22:26)

[release-1.26] feat: Add annotation `service.beta.kubernetes.io/azure-allowed-ip-ranges`
<!--  Thanks for sending a pull request!  Here are some tips for you:

1. If this is your first time, please read our contributor guidelines: https://git.k8s.io/community/contributors/guide/first-contribution.md#your-first-contribution and developer guide https://git.k8s.io/community/contributors/devel/development.md#development-guide
2. Please label this pull request according to what type of issue you are addressing, especially if this is a release targeted pull request. For reference on required PR/issue labels, read here:
https://git.k8s.io/community/contributors/devel/sig-release/release.md#issuepr-kind-label
3. Ensure you have added or ran the appropriate tests for your PR: https://git.k8s.io/community/contributors/devel/sig-testing/testing.md
4. If you want *faster* PR reviews, read how: https://git.k8s.io/community/contributors/guide/pull-requests.md#best-practices-for-faster-reviews
5. If the PR is unfinished, see how to mark it: https://git.k8s.io/community/contributors/guide/pull-requests.md#marking-unfinished-pull-requests
-->

#### What type of PR is this?

<!--
Add one of the following kinds:
/kind bug
/kind cleanup
/kind documentation
/kind feature
/kind design

Optionally add one or more of the following kinds if applicable:
/kind api-change
/kind deprecation
/kind failing-test
/kind flake
/kind regression
-->
/kind feature
#### What this PR does / why we need it:

Cherry pick #4762

This PR introduces a new annotation `service.beta.kubernetes.io/azure-allowed-ip-ranges` to manage the LoadBalancer service access. Previously, it was impossible to restrict access using both IP ranges and service tags (trying to use `spec.loadBalancerSourceRanges` and `service.beta.kubernetes.io/azure-service-tags` together didn’t work as one might think). With these changes, we can use `service.beta.kubernetes.io/azure-allowed-ip-ranges` and `service.beta.kubernetes.io/azure-service-tags` simultaneously.

Use cases:
##### limit access with both IP ranges and service tags
``` yaml
apiVersion: v1
kind: Service
metadata:
  name: test-lb
  annotations:
    service.beta.kubernetes.io/azure-allowed-ip-ranges: "192.168.0.1/32,10.20.0.0/16"
    service.beta.kubernetes.io/azure-allowed-service-tags: "AzureCloud"
spec:
  type: LoadBalancer
  ports:
  - port: 80
  selector:
    app: nginx
```
<img width="1208" alt="image" src="https://github.com/kubernetes-sigs/cloud-provider-azure/assets/9134703/fa85bfd8-fe0b-4932-b3e3-75b5a83b1940">
As expected, three NSG rules will be created. Any source service with the IPs mentioned above, or those tagged with AzureCloud, will be able to access this LoadBalancer service.

##### specify both `spec.loadBalancerSourceRange` and the new annotation
``` yaml
apiVersion: v1
kind: Service
metadata:
  name: test-lb
  annotations:
    service.beta.kubernetes.io/azure-allowed-ip-ranges: "192.168.0.1/32,10.20.0.0/16"
spec:
  type: LoadBalancer
  loadBalancerSourceRanges:
    - 1.1.1.1/32
  ports:
  - port: 80
  selector:
    app: nginx
```
<img width="1512" alt="image" src="https://github.com/kubernetes-sigs/cloud-provider-azure/assets/9134703/d8d14595-5f23-4453-98ce-08a17cda04a1">
It doesn’t work, as expected.

##### specify `spec.loadBalancerSourceRange` and service tags annotation
``` yaml
apiVersion: v1
kind: Service
metadata:
  name: test-lb
  annotations:
    service.beta.kubernetes.io/azure-allowed-service-tags: "AzureCloud"
spec:
  type: LoadBalancer
  loadBalancerSourceRanges:
    - 1.1.1.1/32
  ports:
  - port: 80
  selector:
    app: nginx
```
<img width="1511" alt="image" src="https://github.com/kubernetes-sigs/cloud-provider-azure/assets/9134703/53c8c27d-048a-46dc-82c6-0673aa303f36">
Rather than blocking the process of creation or modification, it will generate a warning event.

#### Which issue(s) this PR fixes:
<!--
*Automatically closes linked issue when PR is merged.
Usage: `Fixes #<issue number>`, or `Fixes (paste link of issue)`.
_If PR is about `failing-tests or flakes`, please post the related issues/tests in a comment and do not use `Fixes`_*
-->
Fixes #

#### Special notes for your reviewer:

1.26 does not cherry-pick the IPv6 support.

#### Does this PR introduce a user-facing change?
<!--
If no, just write "NONE" in the release-note block below.
If yes, a release note is required:
Enter your extended release note in the block below. If the PR requires additional action from users switching to the new release, include the string "action required".

For more information on release notes see: https://git.k8s.io/community/contributors/guide/release-notes.md
-->
```release-note
Introduce the annotation `service.beta.kubernetes.io/azure-allowed-ip-ranges` to manage the LoadBalancer service access.
```

#### Additional documentation e.g., KEPs (Kubernetes Enhancement Proposals), usage docs, etc.:

<!--
This section can be blank if this pull request does not require a release note.

When adding links which point to resources within git repositories, like
KEPs or supporting documentation, please reference a specific commit and avoid
linking directly to the master branch. This ensures that links reference a
specific point in time, rather than a document that may change over time.

See here for guidance on getting permanent links to files: https://help.github.com/en/articles/getting-permanent-links-to-files

Please use the following format for linking documentation:
- [KEP]: <link>
- [Usage]: <link>
- [Other doc]: <link>
-->
```docs

```



Patch:
diff --git a/pkg/consts/consts.go b/pkg/consts/consts.go
index 030694959..060041db0 100644
--- a/pkg/consts/consts.go
+++ b/pkg/consts/consts.go
@@ -280,10 +280,15 @@ const (
 	// ServiceAnnotationIPTagsForPublicIP specifies the iptags used when dynamically creating a public ip
 	ServiceAnnotationIPTagsForPublicIP = "service.beta.kubernetes.io/azure-pip-ip-tags"
 
-	// ServiceAnnotationAllowedServiceTag is the annotation used on the service
+	// ServiceAnnotationAllowedServiceTags is the annotation used on the service
 	// to specify a list of allowed service tags separated by comma
 	// Refer https://docs.microsoft.com/en-us/azure/virtual-network/security-overview#service-tags for all supported service tags.
-	ServiceAnnotationAllowedServiceTag = "service.beta.kubernetes.io/azure-allowed-service-tags"
+	ServiceAnnotationAllowedServiceTags = "service.beta.kubernetes.io/azure-allowed-service-tags"
+
+	// ServiceAnnotationAllowedIPRanges is the annotation used on the service
+	// to specify a list of allowed IP Ranges separated by comma.
+	// It is compatible with both IPv4 and IPV6 CIDR formats.
+	ServiceAnnotationAllowedIPRanges = "service.beta.kubernetes.io/azure-allowed-ip-ranges"
 
 	// ServiceAnnotationDenyAllExceptLoadBalancerSourceRanges  denies all traffic to the load balancer except those
 	// within the service.Spec.LoadBalancerSourceRanges. Ref: https://github.com/kubernetes-sigs/cloud-provider-azure/issues/374.
diff --git a/pkg/provider/azure_loadbalancer.go b/pkg/provider/azure_loadbalancer.go
index 6d288785c..2af8fcea4 100644
--- a/pkg/provider/azure_loadbalancer.go
+++ b/pkg/provider/azure_loadbalancer.go
@@ -45,6 +45,7 @@ import (
 	azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache"
 	"sigs.k8s.io/cloud-provider-azure/pkg/consts"
 	"sigs.k8s.io/cloud-provider-azure/pkg/metrics"
+	"sigs.k8s.io/cloud-provider-azure/pkg/provider/loadbalancer"
 	"sigs.k8s.io/cloud-provider-azure/pkg/retry"
 )
 
@@ -2400,28 +2401,45 @@ func (az *Cloud) reconcileSecurityGroup(clusterName string, service *v1.Service,
 		destinationIPAddresses = append(destinationIPAddresses, additionalIPs...)
 	}
 
-	sourceRanges, err := servicehelpers.GetLoadBalancerSourceRanges(service)
+	accessControl, err := loadbalancer.NewAccessControl(service)
 	if err != nil {
+		klog.ErrorS(err, "Failed to parse access control configuration for service", "service", service.Name)
 		return nil, err
 	}
-	serviceTags := getServiceTags(service)
-	if len(serviceTags) != 0 {
-		delete(sourceRanges, consts.DefaultLoadBalancerSourceRanges)
-	}
 
-	var sourceAddressPrefixes []string
-	if (sourceRanges == nil || servicehelpers.IsAllowAll(sourceRanges)) && len(serviceTags) == 0 {
-		if !requiresInternalLoadBalancer(service) || len(service.Spec.LoadBalancerSourceRanges) > 0 {
-			sourceAddressPrefixes = []string{"Internet"}
-		}
-	} else {
-		for _, ip := range sourceRanges {
-			sourceAddressPrefixes = append(sourceAddressPrefixes, ip.String())
-		}
-		sourceAddressPrefixes = append(sourceAddressPrefixes, serviceTags...)
+	var (
+		sourceRanges          = accessControl.SourceRanges()
+		allowedServiceTags    = accessControl.AllowedServiceTags()
+		allowedIPRanges       = accessControl.AllowedIPRanges()
+		sourceAddressPrefixes = accessControl.IPV4Sources()
+	)
+
+	if len(sourceRanges) != 0 && len(allowedIPRanges) != 0 {
+		// Block the service and return error if both of spec.loadBalancerSourceRanges and annotation are specified
+		klog.Errorf("Service %s is using both of spec.loadBalancerSourceRanges and annotation %s.", service.Name, consts.ServiceAnnotationAllowedIPRanges)
+		return nil, fmt.Errorf(
+			"both of spec.loadBalancerSourceRanges and annotation %s are specified for service %s, which is not allowed",
+			consts.ServiceAnnotationAllowedIPRanges, service.Name,
+		)
+	}
+	if len(sourceRanges) != 0 && len(allowedServiceTags) != 0 {
+		// Suggesting to use aks custom annotation instead of spec.loadBalancerSourceRanges
+		klog.Warningf(
+			"Service %s is using both of spec.loadBalancerSourceRanges and annotation %s.",
+			service.Name, consts.ServiceAnnotationAllowedServiceTags,
+		)
+		az.Event(service, v1.EventTypeWarning, "ConflictConfiguration", fmt.Sprintf(
+			"Please use annotation %s instead of spec.loadBalancerSourceRanges while using %s annotation at the same time.",
+			consts.ServiceAnnotationAllowedIPRanges, consts.ServiceAnnotationAllowedServiceTags,
+		))
 	}
 
-	expectedSecurityRules, err := az.getExpectedSecurityRules(wantLb, ports, sourceAddressPrefixes, service, destinationIPAddresses, sourceRanges, backendIPAddresses, disableFloatingIP)
+	expectedSecurityRules, err := az.getExpectedSecurityRules(
+		wantLb, ports,
+		sourceAddressPrefixes, service,
+		destinationIPAddresses, sourceRanges,
+		backendIPAddresses, disableFloatingIP,
+	)
 	if err != nil {
 		return nil, err
 	}
@@ -2575,7 +2593,16 @@ func (az *Cloud) reconcileSecurityRules(sg network.SecurityGroup, service *v1.Se
 	return dirtySg, updatedRules, nil
 }
 
-func (az *Cloud) getExpectedSecurityRules(wantLb bool, ports []v1.ServicePort, sourceAddressPrefixes []string, service *v1.Service, destinationIPAddresses []string, sourceRanges utilnet.IPNetSet, backendIPAddresses []string, disableFloatingIP bool) ([]network.SecurityRule, error) {
+func (az *Cloud) getExpectedSecurityRules(
+	wantLb bool,
+	ports []v1.ServicePort,
+	sourceAddressPrefixes []string,
+	service *v1.Service,
+	destinationIPAddresses []string,
+	sourceRanges []netip.Prefix,
+	backendIPAddresses []string,
+	disableFloatingIP bool,
+) ([]network.SecurityRule, error) {
 	expectedSecurityRules := []network.SecurityRule{}
 
 	if wantLb {
@@ -2618,7 +2645,7 @@ func (az *Cloud) getExpectedSecurityRules(wantLb bool, ports []v1.ServicePort, s
 		}
 
 		shouldAddDenyRule := false
-		if len(sourceRanges) > 0 && !servicehelpers.IsAllowAll(sourceRanges) {
+		if len(sourceRanges) > 0 && !loadbalancer.IsCIDRsAllowAll(sourceRanges) {
 			if v, ok := service.Annotations[consts.ServiceAnnotationDenyAllExceptLoadBalancerSourceRanges]; ok && strings.EqualFold(v, consts.TrueAnnotationValue) {
 				shouldAddDenyRule = true
 			}
@@ -3327,7 +3354,7 @@ func getServiceTags(service *v1.Service) []string {
 		return nil
 	}
 
-	if serviceTags, found := service.Annotations[consts.ServiceAnnotationAllowedServiceTag]; found {
+	if serviceTags, found := service.Annotations[consts.ServiceAnnotationAllowedServiceTags]; found {
 		result := []string{}
 		tags := strings.Split(strings.TrimSpace(serviceTags), ",")
 		for _, tag := range tags {
diff --git a/pkg/provider/loadbalancer/accesscontrol.go b/pkg/provider/loadbalancer/accesscontrol.go
new file mode 100644
index 000000000..c71758469
--- /dev/null
+++ b/pkg/provider/loadbalancer/accesscontrol.go
@@ -0,0 +1,202 @@
+/*
+Copyright 2023 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package loadbalancer
+
+import (
+	"fmt"
+	"net/netip"
+	"strings"
+
+	v1 "k8s.io/api/core/v1"
+
+	"sigs.k8s.io/cloud-provider-azure/pkg/consts"
+)
+
+// IsInternal returns true if the given service is internal load balancer.
+func IsInternal(svc *v1.Service) bool {
+	value, found := svc.Annotations[consts.ServiceAnnotationLoadBalancerInternal]
+	return found && strings.ToLower(value) == "true"
+}
+
+// IsExternal returns true if the given service is external load balancer.
+func IsExternal(svc *v1.Service) bool {
+	return !IsInternal(svc)
+}
+
+// AllowedServiceTags returns the allowed service tags configured by user through AKS custom annotation.
+func AllowedServiceTags(svc *v1.Service) ([]string, error) {
+	const Sep = ","
+
+	value, found := svc.Annotations[consts.ServiceAnnotationAllowedServiceTags]
+	if !found {
+		return nil, nil
+	}
+
+	return strings.Split(strings.TrimSpace(value), Sep), nil
+}
+
+// AllowedIPRanges returns the allowed IP ranges configured by user through AKS custom annotation.
+func AllowedIPRanges(svc *v1.Service) ([]netip.Prefix, error) {
+	const Sep = ","
+
+	value, found := svc.Annotations[consts.ServiceAnnotationAllowedIPRanges]
+	if !found {
+		return nil, nil
+	}
+
+	rv, err := ParseCIDRs(strings.Split(strings.TrimSpace(value), Sep))
+	if err != nil {
+		return nil, fmt.Errorf("invalid service annotation %s:%s: %w", consts.ServiceAnnotationAllowedIPRanges, value, err)
+	}
+
+	return rv, nil
+}
+
+// SourceRanges returns the allowed IP ranges configured by user through `spec.LoadBalancerSourceRanges` and standard annotation.
+// If `spec.LoadBalancerSourceRanges` is not set, it will try to parse the annotation.
+func SourceRanges(svc *v1.Service) ([]netip.Prefix, error) {
+	if len(svc.Spec.LoadBalancerSourceRanges) > 0 {
+		rv, err := ParseCIDRs(svc.Spec.LoadBalancerSourceRanges)
+		if err != nil {
+			return nil, fmt.Errorf("invalid service.Spec.LoadBalancerSourceRanges [%v]: %w", svc.Spec.LoadBalancerSourceRanges, err)
+		}
+		return rv, nil
+	}
+
+	const Sep = ","
+	value, found := svc.Annotations[v1.AnnotationLoadBalancerSourceRangesKey]
+	if !found {
+		return nil, nil
+	}
+	rv, err := ParseCIDRs(strings.Split(strings.TrimSpace(value), Sep))
+	if err != nil {
+		return nil, fmt.Errorf("invalid service annotation %s:%s: %w", v1.AnnotationLoadBalancerSourceRangesKey, value, err)
+	}
+	return rv, nil
+}
+
+type AccessControl struct {
+	svc *v1.Service
+
+	// immutable redundant states.
+	sourceRanges       []netip.Prefix
+	allowedIPRanges    []netip.Prefix
+	allowedServiceTags []string
+}
+
+func NewAccessControl(svc *v1.Service) (*AccessControl, error) {
+	sourceRanges, err := SourceRanges(svc)
+	if err != nil {
+		return nil, err
+	}
+	allowedIPRanges, err := AllowedIPRanges(svc)
+	if err != nil {
+		return nil, err
+	}
+	allowedServiceTags, err := AllowedServiceTags(svc)
+	if err != nil {
+		return nil, err
+	}
+
+	return &AccessControl{
+		svc:                svc,
+		sourceRanges:       sourceRanges,
+		allowedIPRanges:    allowedIPRanges,
+		allowedServiceTags: allowedServiceTags,
+	}, nil
+}
+
+// SourceRanges returns the allowed IP ranges configured by user through `spec.LoadBalancerSourceRanges` and standard annotation.
+func (ac *AccessControl) SourceRanges() []netip.Prefix {
+	return ac.sourceRanges
+}
+
+// AllowedIPRanges returns the allowed IP ranges configured by user through AKS custom annotation.
+func (ac *AccessControl) AllowedIPRanges() []netip.Prefix {
+	return ac.allowedIPRanges
+}
+
+// AllowedServiceTags returns the allowed service tags configured by user through AKS custom annotation.
+func (ac *AccessControl) AllowedServiceTags() []string {
+	return ac.allowedServiceTags
+}
+
+// IsAllowFromInternet returns true if the given service is allowed to be accessed from internet.
+// To be specific,
+// 1. For all types of LB, it returns false if the given service is specified with `service tags` or `not allowed all IP ranges`.
+// 2. For internal LB, it returns true iff the given service is explicitly specified with `allowed all IP ranges`. Refer: https://github.com/kubernetes-sigs/cloud-provider-azure/issues/698
+func (ac *AccessControl) IsAllowFromInternet() bool {
+	if len(ac.allowedServiceTags) > 0 {
+		return false
+	}
+	if len(ac.sourceRanges) > 0 && !IsCIDRsAllowAll(ac.sourceRanges) {
+		return false
+	}
+	if len(ac.allowedIPRanges) > 0 && !IsCIDRsAllowAll(ac.allowedIPRanges) {
+		return false
+	}
+	if IsExternal(ac.svc) {
+		return true
+	}
+	// Internal LB with explicit allowedAll IP ranges is allowed to be accessed from internet.
+	return len(ac.allowedIPRanges) > 0 || len(ac.sourceRanges) > 0
+}
+
+// IPV4Sources returns the allowed sources for IPv4.
+func (ac *AccessControl) IPV4Sources() []string {
+	var rv []string
+
+	if ac.IsAllowFromInternet() {
+		rv = append(rv, "Internet")
+	}
+	for _, cidr := range ac.sourceRanges {
+		if cidr.Addr().Is4() {
+			rv = append(rv, cidr.String())
+		}
+	}
+	for _, cidr := range ac.allowedIPRanges {
+		if cidr.Addr().Is4() {
+			rv = append(rv, cidr.String())
+		}
+	}
+	rv = append(rv, ac.allowedServiceTags...)
+
+	return rv
+}
+
+// IPV6Sources returns the allowed sources for IPv6.
+func (ac *AccessControl) IPV6Sources() []string {
+	var (
+		rv []string
+	)
+	if ac.IsAllowFromInternet() {
+		rv = append(rv, "Internet")
+	}
+	for _, cidr := range ac.sourceRanges {
+		if cidr.Addr().Is6() {
+			rv = append(rv, cidr.String())
+		}
+	}
+	for _, cidr := range ac.allowedIPRanges {
+		if cidr.Addr().Is6() {
+			rv = append(rv, cidr.String())
+		}
+	}
+	rv = append(rv, ac.allowedServiceTags...)
+
+	return rv
+}
diff --git a/pkg/provider/loadbalancer/netip.go b/pkg/provider/loadbalancer/netip.go
new file mode 100644
index 000000000..c7e4632b6
--- /dev/null
+++ b/pkg/provider/loadbalancer/netip.go
@@ -0,0 +1,50 @@
+/*
+Copyright 2023 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package loadbalancer
+
+import (
+	"fmt"
+	"net/netip"
+)
+
+const (
+	IPv4AllowedAll = "0.0.0.0/0"
+	IPv6AllowedAll = "::/0"
+)
+
+// IsCIDRsAllowAll return true if the given IP Ranges covers all IPs.
+// It returns false if the given IP Ranges is empty.
+func IsCIDRsAllowAll(cidrs []netip.Prefix) bool {
+	for _, cidr := range cidrs {
+		if cidr.String() == IPv4AllowedAll || cidr.String() == IPv6AllowedAll {
+			return true
+		}
+	}
+	return false
+}
+
+func ParseCIDRs(parts []string) ([]netip.Prefix, error) {
+	var rv []netip.Prefix
+	for _, part := range parts {
+		prefix, err := netip.ParsePrefix(part)
+		if err != nil {
+			return nil, fmt.Errorf("invalid IP range %s: %w", part, err)
+		}
+		rv = append(rv, prefix)
+	}
+	return rv, nil
+}


Test patch:
diff --git a/pkg/provider/azure_loadbalancer_test.go b/pkg/provider/azure_loadbalancer_test.go
index ce25f964c..1bd426303 100644
--- a/pkg/provider/azure_loadbalancer_test.go
+++ b/pkg/provider/azure_loadbalancer_test.go
@@ -30,6 +30,7 @@ import (
 
 	"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-03-01/compute"
 	"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network"
+	"github.com/Azure/go-autorest/autorest/to"
 	"github.com/golang/mock/gomock"
 	"github.com/stretchr/testify/assert"
 	"golang.org/x/text/cases"
@@ -1472,7 +1473,7 @@ func TestGetServiceTags(t *testing.T) {
 			service: &v1.Service{
 				ObjectMeta: metav1.ObjectMeta{
 					Annotations: map[string]string{
-						consts.ServiceAnnotationAllowedServiceTag: "tag1",
+						consts.ServiceAnnotationAllowedServiceTags: "tag1",
 					},
 				},
 			},
@@ -1483,7 +1484,7 @@ func TestGetServiceTags(t *testing.T) {
 			service: &v1.Service{
 				ObjectMeta: metav1.ObjectMeta{
 					Annotations: map[string]string{
-						consts.ServiceAnnotationAllowedServiceTag: "tag1, tag2",
+						consts.ServiceAnnotationAllowedServiceTags: "tag1, tag2",
 					},
 				},
 			},
@@ -1494,7 +1495,7 @@ func TestGetServiceTags(t *testing.T) {
 			service: &v1.Service{
 				ObjectMeta: metav1.ObjectMeta{
 					Annotations: map[string]string{
-						consts.ServiceAnnotationAllowedServiceTag: ", tag1, ",
+						consts.ServiceAnnotationAllowedServiceTags: ", tag1, ",
 					},
 				},
 			},
@@ -3772,7 +3773,7 @@ func TestReconcileSecurityGroup(t *testing.T) {
 		},
 		{
 			desc:    "reconcileSecurityGroup shall not create unwanted security rules if there is service tags",
-			service: getTestService("test1", v1.ProtocolTCP, map[string]string{consts.ServiceAnnotationAllowedServiceTag: "tag"}, true, 80),
+			service: getTestService("test1", v1.ProtocolTCP, map[string]string{consts.ServiceAnnotationAllowedServiceTags: "tag"}, false, 80),
 			wantLb:  true,
 			lbIP:    pointer.String("1.1.1.1"),
 			existingSgs: map[string]network.SecurityGroup{"nsg": {
@@ -3982,6 +3983,226 @@ func TestReconcileSecurityGroup(t *testing.T) {
 				},
 			},
 		},
+		{
+			desc: "reconcileSecurityGroup shall create sgs while allowedIPRanges annotation is set for IPv4",
+			service: getTestService("svc", v1.ProtocolTCP, map[string]string{
+				consts.ServiceAnnotationAllowedIPRanges: "10.10.10.0/24,192.168.0.1/32",
+			}, false, 80),
+			existingSgs: map[string]network.SecurityGroup{"nsg": {
+				Name:                          pointer.String("nsg"),
+				SecurityGroupPropertiesFormat: &network.SecurityGroupPropertiesFormat{},
+			}},
+			lbIP:   to.StringPtr("10.0.0.1"),
+			wantLb: true,
+			expectedSg: &network.SecurityGroup{
+				Name: pointer.String("nsg"),
+				SecurityGroupPropertiesFormat: &network.SecurityGroupPropertiesFormat{
+					SecurityRules: &[]network.SecurityRule{
+						{
+							Name: pointer.String("asvc-TCP-80-10.10.10.0_24"),
+							SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
+								Protocol:                 network.SecurityRuleProtocol("Tcp"),
+								SourcePortRange:          pointer.String("*"),
+								DestinationPortRange:     pointer.String(strconv.Itoa(80)),
+								SourceAddressPrefix:      pointer.String("10.10.10.0/24"),
+								DestinationAddressPrefix: to.StringPtr("10.0.0.1"),
+								Access:                   network.SecurityRuleAccessAllow,
+								Priority:                 pointer.Int32(500),
+								Direction:                network.SecurityRuleDirection("Inbound"),
+							},
+						},
+						{
+							Name: pointer.String("asvc-TCP-80-192.168.0.1_32"),
+							SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
+								Protocol:                 network.SecurityRuleProtocol("Tcp"),
+								SourcePortRange:          pointer.String("*"),
+								DestinationPortRange:     pointer.String(strconv.Itoa(80)),
+								SourceAddressPrefix:      pointer.String("192.168.0.1/32"),
+								DestinationAddressPrefix: to.StringPtr("10.0.0.1"),
+								Access:                   network.SecurityRuleAccessAllow,
+								Priority:                 pointer.Int32(501),
+								Direction:                network.SecurityRuleDirection("Inbound"),
+							},
+						},
+					},
+				},
+			},
+		},
+		{
+			desc: "reconcileSecurityGroup shall create sgs while allowedIPRanges and serviceTags annotation is set",
+			service: getTestService("svc", v1.ProtocolTCP, map[string]string{
+				consts.ServiceAnnotationAllowedIPRanges:    "10.10.10.0/24,192.168.0.1/32",
+				consts.ServiceAnnotationAllowedServiceTags: "foo,bar",
+			}, false, 80),
+			existingSgs: map[string]network.SecurityGroup{"nsg": {
+				Name:                          pointer.String("nsg"),
+				SecurityGroupPropertiesFormat: &network.SecurityGroupPropertiesFormat{},
+			}},
+			lbIP:   to.StringPtr("10.0.0.1"),
+			wantLb: true,
+			expectedSg: &network.SecurityGroup{
+				Name: pointer.String("nsg"),
+				SecurityGroupPropertiesFormat: &network.SecurityGroupPropertiesFormat{
+					SecurityRules: &[]network.SecurityRule{
+						{
+							Name: pointer.String("asvc-TCP-80-10.10.10.0_24"),
+							SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
+								Protocol:                 network.SecurityRuleProtocol("Tcp"),
+								SourcePortRange:          pointer.String("*"),
+								DestinationPortRange:     pointer.String(strconv.Itoa(80)),
+								SourceAddressPrefix:      pointer.String("10.10.10.0/24"),
+								DestinationAddressPrefix: to.StringPtr("10.0.0.1"),
+								Access:                   network.SecurityRuleAccessAllow,
+								Priority:                 pointer.Int32(500),
+								Direction:                network.SecurityRuleDirection("Inbound"),
+							},
+						},
+						{
+							Name: pointer.String("asvc-TCP-80-192.168.0.1_32"),
+							SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
+								Protocol:                 network.SecurityRuleProtocol("Tcp"),
+								SourcePortRange:          pointer.String("*"),
+								DestinationPortRange:     pointer.String(strconv.Itoa(80)),
+								SourceAddressPrefix:      pointer.String("192.168.0.1/32"),
+								DestinationAddressPrefix: to.StringPtr("10.0.0.1"),
+								Access:                   network.SecurityRuleAccessAllow,
+								Priority:                 pointer.Int32(501),
+								Direction:                network.SecurityRuleDirection("Inbound"),
+							},
+						},
+						{
+							Name: pointer.String("asvc-TCP-80-foo"),
+							SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
+								Protocol:                 network.SecurityRuleProtocol("Tcp"),
+								SourcePortRange:          pointer.String("*"),
+								DestinationPortRange:     pointer.String(strconv.Itoa(80)),
+								SourceAddressPrefix:      pointer.String("foo"),
+								DestinationAddressPrefix: to.StringPtr("10.0.0.1"),
+								Access:                   network.SecurityRuleAccessAllow,
+								Priority:                 pointer.Int32(502),
+								Direction:                network.SecurityRuleDirection("Inbound"),
+							},
+						},
+						{
+							Name: pointer.String("asvc-TCP-80-bar"),
+							SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
+								Protocol:                 network.SecurityRuleProtocol("Tcp"),
+								SourcePortRange:          pointer.String("*"),
+								DestinationPortRange:     pointer.String(strconv.Itoa(80)),
+								SourceAddressPrefix:      pointer.String("bar"),
+								DestinationAddressPrefix: to.StringPtr("10.0.0.1"),
+								Access:                   network.SecurityRuleAccessAllow,
+								Priority:                 pointer.Int32(503),
+								Direction:                network.SecurityRuleDirection("Inbound"),
+							},
+						},
+					},
+				},
+			},
+		},
+		{
+			desc: "reconcileSecurityGroup shall create/update/delete sgs while allowedIPRanges and serviceTags annotation is set",
+			service: getTestService("svc", v1.ProtocolTCP, map[string]string{
+				consts.ServiceAnnotationAllowedIPRanges:    "10.10.10.0/24,192.168.0.1/32",
+				consts.ServiceAnnotationAllowedServiceTags: "foo,bar",
+			}, false, 80),
+			existingSgs: map[string]network.SecurityGroup{"nsg": {
+				Name: pointer.String("nsg"),
+				SecurityGroupPropertiesFormat: &network.SecurityGroupPropertiesFormat{
+					SecurityRules: &[]network.SecurityRule{
+						{
+							// will be kept
+							Name: pointer.String("asvc-TCP-80-192.168.0.1_32"),
+							SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
+								Protocol:                 network.SecurityRuleProtocol("Tcp"),
+								SourcePortRange:          pointer.String("*"),
+								DestinationPortRange:     pointer.String(strconv.Itoa(80)),
+								SourceAddressPrefix:      pointer.String("192.168.0.1/32"),
+								DestinationAddressPrefix: to.StringPtr("10.0.0.1"),
+								Access:                   network.SecurityRuleAccessAllow,
+								Priority:                 pointer.Int32(500),
+								Direction:                network.SecurityRuleDirection("Inbound"),
+							},
+						},
+						{
+							// will be removed: no longer in allowedIPRanges
+							Name: pointer.String("asvc-TCP-80-192.168.0.5_32"),
+							SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
+								Protocol:                 network.SecurityRuleProtocol("Tcp"),
+								SourcePortRange:          pointer.String("*"),
+								DestinationPortRange:     pointer.String(strconv.Itoa(80)),
+								SourceAddressPrefix:      pointer.String("192.168.0.5/32"),
+								DestinationAddressPrefix: to.StringPtr("10.0.0.1"),
+								Access:                   network.SecurityRuleAccessAllow,
+								Priority:                 pointer.Int32(501),
+								Direction:                network.SecurityRuleDirection("Inbound"),
+							},
+						},
+					},
+				},
+			}},
+			lbIP:   to.StringPtr("10.0.0.1"),
+			wantLb: true,
+			expectedSg: &network.SecurityGroup{
+				Name: pointer.String("nsg"),
+				SecurityGroupPropertiesFormat: &network.SecurityGroupPropertiesFormat{
+					SecurityRules: &[]network.SecurityRule{
+						{
+							Name: pointer.String("asvc-TCP-80-192.168.0.1_32"),
+							SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
+								Protocol:                 network.SecurityRuleProtocol("Tcp"),
+								SourcePortRange:          pointer.String("*"),
+								DestinationPortRange:     pointer.String(strconv.Itoa(80)),
+								SourceAddressPrefix:      pointer.String("192.168.0.1/32"),
+								DestinationAddressPrefix: to.StringPtr("10.0.0.1"),
+								Access:                   network.SecurityRuleAccessAllow,
+								Priority:                 pointer.Int32(500),
+								Direction:                network.SecurityRuleDirection("Inbound"),
+							},
+						},
+						{
+							Name: pointer.String("asvc-TCP-80-10.10.10.0_24"),
+							SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
+								Protocol:                 network.SecurityRuleProtocol("Tcp"),
+								SourcePortRange:          pointer.String("*"),
+								DestinationPortRange:     pointer.String(strconv.Itoa(80)),
+								SourceAddressPrefix:      pointer.String("10.10.10.0/24"),
+								DestinationAddressPrefix: to.StringPtr("10.0.0.1"),
+								Access:                   network.SecurityRuleAccessAllow,
+								Priority:                 pointer.Int32(501),
+								Direction:                network.SecurityRuleDirection("Inbound"),
+							},
+						},
+						{
+							Name: pointer.String("asvc-TCP-80-foo"),
+							SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
+								Protocol:                 network.SecurityRuleProtocol("Tcp"),
+								SourcePortRange:          pointer.String("*"),
+								DestinationPortRange:     pointer.String(strconv.Itoa(80)),
+								SourceAddressPrefix:      pointer.String("foo"),
+								DestinationAddressPrefix: to.StringPtr("10.0.0.1"),
+								Access:                   network.SecurityRuleAccessAllow,
+								Priority:                 pointer.Int32(502),
+								Direction:                network.SecurityRuleDirection("Inbound"),
+							},
+						},
+						{
+							Name: pointer.String("asvc-TCP-80-bar"),
+							SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
+								Protocol:                 network.SecurityRuleProtocol("Tcp"),
+								SourcePortRange:          pointer.String("*"),
+								DestinationPortRange:     pointer.String(strconv.Itoa(80)),
+								SourceAddressPrefix:      pointer.String("bar"),
+								DestinationAddressPrefix: to.StringPtr("10.0.0.1"),
+								Access:                   network.SecurityRuleAccessAllow,
+								Priority:                 pointer.Int32(503),
+								Direction:                network.SecurityRuleDirection("Inbound"),
+							},
+						},
+					},
+				},
+			},
+		},
 	}
 
 	for _, test := range testCases {
@@ -4066,6 +4287,102 @@ func TestReconcileSecurityGroupLoadBalancerSourceRanges(t *testing.T) {
 	assert.Equal(t, expectedSg, *sg)
 }
 
+func TestReconcileSecurityGroupForAllowedIPRanges(t *testing.T) {
+	var (
+		clusterName = "testCluster"
+		lbIPs       = "10.0.0.1"
+		lbName      = "lb-name"
+	)
+
+	t.Run("with spec.loadBalancerSourceRanges and IPRanges annotation specified", func(t *testing.T) {
+		var (
+			ctrl = gomock.NewController(t)
+			az   = GetTestCloud(ctrl)
+			svc  = v1.Service{
+				Spec: v1.ServiceSpec{
+					Type:                     v1.ServiceTypeLoadBalancer,
+					LoadBalancerSourceRanges: []string{"10.10.10.0/24"},
+					IPFamilies: []v1.IPFamily{
+						v1.IPv4Protocol,
+						v1.IPv6Protocol,
+					},
+					Ports: []v1.ServicePort{
+						{
+							Name:     "http",
+							Port:     80,
+							Protocol: v1.ProtocolTCP,
+						},
+					},
+				},
+				ObjectMeta: metav1.ObjectMeta{
+					Name: "test-svc",
+					Annotations: map[string]string{
+						consts.ServiceAnnotationAllowedIPRanges: "192.168.0.1/32",
+					},
+				},
+			}
+		)
+		defer ctrl.Finish()
+
+		mockSGClient := az.SecurityGroupsClient.(*mocksecuritygroupclient.MockInterface)
+		mockSGClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any()).Return(network.SecurityGroup{
+			Name: pointer.String("nsg"),
+			SecurityGroupPropertiesFormat: &network.SecurityGroupPropertiesFormat{
+				SecurityRules: &[]network.SecurityRule{},
+			},
+		}, nil)
+		_, err := az.reconcileSecurityGroup(clusterName, &svc, &lbIPs, &lbName, true)
+		assert.Error(t, err)
+		assert.EqualError(t, err, fmt.Sprintf(
+			"both of spec.loadBalancerSourceRanges and annotation %s are specified for service %s, which is not allowed",
+			consts.ServiceAnnotationAllowedIPRanges, svc.Name,
+		))
+	})
+
+	t.Run("with spec.loadBalancerSourceRanges and ServiceTags annotation specified", func(t *testing.T) {
+		var (
+			ctrl = gomock.NewController(t)
+			az   = GetTestCloud(ctrl)
+			svc  = v1.Service{
+				Spec: v1.ServiceSpec{
+					Type:                     v1.ServiceTypeLoadBalancer,
+					LoadBalancerSourceRanges: []string{"10.10.10.0/24"},
+					IPFamilies: []v1.IPFamily{
+						v1.IPv4Protocol,
+						v1.IPv6Protocol,
+					},
+					Ports: []v1.ServicePort{
+						{
+							Name:     "http",
+							Port:     80,
+							Protocol: v1.ProtocolTCP,
+						},
+					},
+				},
+				ObjectMeta: metav1.ObjectMeta{
+					Name: "test-svc",
+					Annotations: map[string]string{
+						consts.ServiceAnnotationAllowedServiceTags: "foo,bar",
+					},
+				},
+			}
+		)
+		defer ctrl.Finish()
+
+		mockSGClient := az.SecurityGroupsClient.(*mocksecuritygroupclient.MockInterface)
+		mockSGClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any()).Return(network.SecurityGroup{
+			Name: pointer.String("nsg"),
+			SecurityGroupPropertiesFormat: &network.SecurityGroupPropertiesFormat{
+				SecurityRules: &[]network.SecurityRule{},
+			},
+		}, nil)
+		mockSGClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)
+
+		_, err := az.reconcileSecurityGroup(clusterName, &svc, &lbIPs, &lbName, true)
+		assert.NoError(t, err)
+	})
+}
+
 func TestSafeDeletePublicIP(t *testing.T) {
 	ctrl := gomock.NewController(t)
 	defer ctrl.Finish()
diff --git a/pkg/provider/loadbalancer/accesscontrol_test.go b/pkg/provider/loadbalancer/accesscontrol_test.go
new file mode 100644
index 000000000..e21d564f8
--- /dev/null
+++ b/pkg/provider/loadbalancer/accesscontrol_test.go
@@ -0,0 +1,484 @@
+/*
+Copyright 2023 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package loadbalancer
+
+import (
+	"net/netip"
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+	v1 "k8s.io/api/core/v1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+
+	"sigs.k8s.io/cloud-provider-azure/pkg/consts"
+)
+
+func TestIsInternal(t *testing.T) {
+	{
+		svc := v1.Service{
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationLoadBalancerInternal: "true",
+				},
+			},
+		}
+		assert.True(t, IsInternal(&svc))
+	}
+	{
+		svc := v1.Service{
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationLoadBalancerInternal: "TRUE",
+				},
+			},
+		}
+		assert.True(t, IsInternal(&svc))
+	}
+	{
+		svc := v1.Service{
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationLoadBalancerInternal: "foobar",
+				},
+			},
+		}
+		assert.False(t, IsInternal(&svc))
+	}
+	{
+		svc := v1.Service{
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{},
+			},
+		}
+		assert.False(t, IsInternal(&svc))
+	}
+}
+
+func TestIsExternal(t *testing.T) {
+	{
+		svc := v1.Service{
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationLoadBalancerInternal: "true",
+				},
+			},
+		}
+		assert.False(t, IsExternal(&svc))
+	}
+	{
+		svc := v1.Service{
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationLoadBalancerInternal: "TRUE",
+				},
+			},
+		}
+		assert.False(t, IsExternal(&svc))
+	}
+	{
+		svc := v1.Service{
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationLoadBalancerInternal: "foobar",
+				},
+			},
+		}
+		assert.True(t, IsExternal(&svc))
+	}
+	{
+		svc := v1.Service{
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{},
+			},
+		}
+		assert.True(t, IsExternal(&svc))
+	}
+}
+
+func TestAllowedServiceTags(t *testing.T) {
+	t.Run("no annotation", func(t *testing.T) {
+		actual, err := AllowedServiceTags(&v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{},
+			},
+		})
+		assert.NoError(t, err)
+		assert.Empty(t, actual)
+	})
+	t.Run("with 1 service tag", func(t *testing.T) {
+		actual, err := AllowedServiceTags(&v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationAllowedServiceTags: "Microsoft.ContainerInstance/containerGroups",
+				},
+			},
+		})
+		assert.NoError(t, err)
+		assert.Equal(t, []string{"Microsoft.ContainerInstance/containerGroups"}, actual)
+	})
+	t.Run("with multiple service tags", func(t *testing.T) {
+		actual, err := AllowedServiceTags(&v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationAllowedServiceTags: "Microsoft.ContainerInstance/containerGroups,foo,bar",
+				},
+			},
+		})
+		assert.NoError(t, err)
+		assert.Equal(t, []string{"Microsoft.ContainerInstance/containerGroups", "foo", "bar"}, actual)
+	})
+}
+
+func TestAllowedIPRanges(t *testing.T) {
+	t.Run("no annotation", func(t *testing.T) {
+		actual, err := AllowedIPRanges(&v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{},
+			},
+		})
+		assert.NoError(t, err)
+		assert.Empty(t, actual)
+	})
+	t.Run("with 1 IPv4 range", func(t *testing.T) {
+		actual, err := AllowedIPRanges(&v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationAllowedIPRanges: "10.10.0.0/24",
+				},
+			},
+		})
+		assert.NoError(t, err)
+		assert.Equal(t, []netip.Prefix{netip.MustParsePrefix("10.10.0.0/24")}, actual)
+	})
+	t.Run("with 1 IPv6 range", func(t *testing.T) {
+		actual, err := AllowedIPRanges(&v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationAllowedIPRanges: "2001:db8::/32",
+				},
+			},
+		})
+		assert.NoError(t, err)
+		assert.Equal(t, []netip.Prefix{netip.MustParsePrefix("2001:db8::/32")}, actual)
+	})
+	t.Run("with multiple IP ranges", func(t *testing.T) {
+		actual, err := AllowedIPRanges(&v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationAllowedIPRanges: "10.10.0.0/24,2001:db8::/32",
+				},
+			},
+		})
+		assert.NoError(t, err)
+		assert.Equal(t, []netip.Prefix{
+			netip.MustParsePrefix("10.10.0.0/24"),
+			netip.MustParsePrefix("2001:db8::/32"),
+		}, actual)
+	})
+	t.Run("with invalid IP range", func(t *testing.T) {
+		_, err := AllowedIPRanges(&v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationAllowedIPRanges: "foobar",
+				},
+			},
+		})
+		assert.Error(t, err)
+	})
+}
+
+func TestSourceRanges(t *testing.T) {
+	t.Run("not specified in spec", func(t *testing.T) {
+		actual, err := SourceRanges(&v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+		})
+		assert.NoError(t, err)
+		assert.Empty(t, actual)
+	})
+	t.Run("specified in spec", func(t *testing.T) {
+		actual, err := SourceRanges(&v1.Service{
+			Spec: v1.ServiceSpec{
+				Type:                     v1.ServiceTypeLoadBalancer,
+				LoadBalancerSourceRanges: []string{"10.10.0.0/24", "2001:db8::/32"},
+			},
+		})
+		assert.NoError(t, err)
+		assert.Equal(t, []netip.Prefix{
+			netip.MustParsePrefix("10.10.0.0/24"),
+			netip.MustParsePrefix("2001:db8::/32"),
+		}, actual)
+	})
+	t.Run("specified in annotation", func(t *testing.T) {
+		actual, err := SourceRanges(&v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					v1.AnnotationLoadBalancerSourceRangesKey: "10.10.0.0/24,2001:db8::/32",
+				},
+			},
+		})
+		assert.NoError(t, err)
+		assert.Equal(t, []netip.Prefix{
+			netip.MustParsePrefix("10.10.0.0/24"),
+			netip.MustParsePrefix("2001:db8::/32"),
+		}, actual)
+	})
+	t.Run("specified in both spec and annotation", func(t *testing.T) {
+		actual, err := SourceRanges(&v1.Service{
+			Spec: v1.ServiceSpec{
+				Type:                     v1.ServiceTypeLoadBalancer,
+				LoadBalancerSourceRanges: []string{"10.10.0.0/24"},
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					v1.AnnotationLoadBalancerSourceRangesKey: "2001:db8::/32",
+				},
+			},
+		})
+		assert.NoError(t, err)
+		assert.Equal(t, []netip.Prefix{
+			netip.MustParsePrefix("10.10.0.0/24"),
+		}, actual, "spec should take precedence over annotation")
+	})
+	t.Run("with invalid IP range", func(t *testing.T) {
+		_, err := SourceRanges(&v1.Service{
+			Spec: v1.ServiceSpec{
+				Type:                     v1.ServiceTypeLoadBalancer,
+				LoadBalancerSourceRanges: []string{"foobar"},
+			},
+		})
+		assert.Error(t, err)
+	})
+}
+
+func TestAccessControl_IsAllowFromInternet(t *testing.T) {
+	t.Run("external LB", func(t *testing.T) {
+		svc := v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{},
+			},
+		}
+		t.Run("default", func(t *testing.T) {
+			ac, err := NewAccessControl(&svc)
+			assert.NoError(t, err)
+			assert.True(t, ac.IsAllowFromInternet())
+		})
+		t.Run("not allowed from all", func(t *testing.T) {
+			svc.Spec.LoadBalancerSourceRanges = []string{"10.10.10.0/24"}
+			ac, err := NewAccessControl(&svc)
+			assert.NoError(t, err)
+			assert.False(t, ac.IsAllowFromInternet())
+		})
+		t.Run("allowed from all", func(t *testing.T) {
+			svc.Spec.LoadBalancerSourceRanges = []string{"0.0.0.0/0"}
+			ac, err := NewAccessControl(&svc)
+			assert.NoError(t, err)
+			assert.True(t, ac.IsAllowFromInternet())
+		})
+	})
+
+	t.Run("internal LB", func(t *testing.T) {
+		svc := v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationLoadBalancerInternal: "true",
+				},
+			},
+		}
+		t.Run("default", func(t *testing.T) {
+			ac, err := NewAccessControl(&svc)
+			assert.NoError(t, err)
+			assert.False(t, ac.IsAllowFromInternet())
+		})
+		t.Run("not allowed from all", func(t *testing.T) {
+			svc.Spec.LoadBalancerSourceRanges = []string{"10.10.10.0/24"}
+			ac, err := NewAccessControl(&svc)
+			assert.NoError(t, err)
+			assert.False(t, ac.IsAllowFromInternet())
+		})
+		t.Run("allowed from all", func(t *testing.T) {
+			svc.Spec.LoadBalancerSourceRanges = []string{"0.0.0.0/0"}
+			ac, err := NewAccessControl(&svc)
+			assert.NoError(t, err)
+			assert.True(t, ac.IsAllowFromInternet())
+		})
+	})
+}
+
+func TestAccessControl_IPV4Sources(t *testing.T) {
+	t.Run("external LB", func(t *testing.T) {
+		svc := v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationAllowedIPRanges:    "10.10.10.0/24,192.168.0.1/32,2001:db8::/32,2002:db8::/32",
+					consts.ServiceAnnotationAllowedServiceTags: "foo,bar",
+				},
+			},
+		}
+		ac, err := NewAccessControl(&svc)
+		assert.NoError(t, err)
+		assert.Equal(t, []string{
+			"10.10.10.0/24",
+			"192.168.0.1/32",
+			"foo",
+			"bar",
+		}, ac.IPV4Sources())
+	})
+	t.Run("internal LB with Internet access", func(t *testing.T) {
+		svc := v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationLoadBalancerInternal: "true",
+					consts.ServiceAnnotationAllowedIPRanges:      "0.0.0.0/0",
+				},
+			},
+		}
+		ac, err := NewAccessControl(&svc)
+		assert.NoError(t, err)
+		assert.Equal(t, []string{
+			"Internet",
+			"0.0.0.0/0",
+		}, ac.IPV4Sources())
+	})
+	t.Run("internal LB without Internet access", func(t *testing.T) {
+		svc := v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationLoadBalancerInternal: "true",
+					consts.ServiceAnnotationAllowedIPRanges:      "10.10.10.0/24,192.168.0.1/32,2001:db8::/32,2002:db8::/32",
+					consts.ServiceAnnotationAllowedServiceTags:   "foo,bar",
+				},
+			},
+		}
+		ac, err := NewAccessControl(&svc)
+		assert.NoError(t, err)
+		assert.Equal(t, []string{
+			"10.10.10.0/24",
+			"192.168.0.1/32",
+			"foo",
+			"bar",
+		}, ac.IPV4Sources())
+	})
+}
+
+func TestAccessControl_IPV6Sources(t *testing.T) {
+	t.Run("external LB", func(t *testing.T) {
+		svc := v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationAllowedIPRanges:    "10.10.10.0/24,192.168.0.1/32,2001:db8::/32,2002:db8::/32",
+					consts.ServiceAnnotationAllowedServiceTags: "foo,bar",
+				},
+			},
+		}
+		ac, err := NewAccessControl(&svc)
+		assert.NoError(t, err)
+		assert.Equal(t, []string{
+			"2001:db8::/32",
+			"2002:db8::/32",
+			"foo",
+			"bar",
+		}, ac.IPV6Sources())
+	})
+	t.Run("internal LB with Internet access", func(t *testing.T) {
+		svc := v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationLoadBalancerInternal: "true",
+					consts.ServiceAnnotationAllowedIPRanges:      "::/0",
+				},
+			},
+		}
+		ac, err := NewAccessControl(&svc)
+		assert.NoError(t, err)
+		assert.Equal(t, []string{
+			"Internet",
+			"::/0",
+		}, ac.IPV6Sources())
+	})
+	t.Run("internal LB without Internet access", func(t *testing.T) {
+		svc := v1.Service{
+			Spec: v1.ServiceSpec{
+				Type: v1.ServiceTypeLoadBalancer,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Annotations: map[string]string{
+					consts.ServiceAnnotationLoadBalancerInternal: "true",
+					consts.ServiceAnnotationAllowedIPRanges:      "10.10.10.0/24,192.168.0.1/32,2001:db8::/32,2002:db8::/32",
+					consts.ServiceAnnotationAllowedServiceTags:   "foo,bar",
+				},
+			},
+		}
+		ac, err := NewAccessControl(&svc)
+		assert.NoError(t, err)
+		assert.Equal(t, []string{
+			"2001:db8::/32",
+			"2002:db8::/32",
+			"foo",
+			"bar",
+		}, ac.IPV6Sources())
+	})
+}
diff --git a/pkg/provider/loadbalancer/netip_test.go b/pkg/provider/loadbalancer/netip_test.go
new file mode 100644
index 000000000..c989eb277
--- /dev/null
+++ b/pkg/provider/loadbalancer/netip_test.go
@@ -0,0 +1,96 @@
+/*
+Copyright 2023 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package loadbalancer
+
+import (
+	"net/netip"
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+)
+
+func TestIsAllowAll(t *testing.T) {
+	assert.False(t, IsCIDRsAllowAll([]netip.Prefix{}))
+	assert.True(t, IsCIDRsAllowAll([]netip.Prefix{
+		netip.MustParsePrefix(IPv4AllowedAll),
+	}))
+	assert.True(t, IsCIDRsAllowAll([]netip.Prefix{
+		netip.MustParsePrefix(IPv6AllowedAll),
+	}))
+	assert.True(t, IsCIDRsAllowAll([]netip.Prefix{
+		netip.MustParsePrefix("1.1.1.1/32"),
+		netip.MustParsePrefix(IPv4AllowedAll),
+	}))
+	assert.True(t, IsCIDRsAllowAll([]netip.Prefix{
+		netip.MustParsePrefix("1.1.1.1/32"),
+		netip.MustParsePrefix(IPv6AllowedAll),
+	}))
+	assert.False(t, IsCIDRsAllowAll([]netip.Prefix{
+		netip.MustParsePrefix("1.1.1.1/32"),
+	}))
+}
+
+func TestParseCIDRs(t *testing.T) {
+	t.Run("empty", func(t *testing.T) {
+		actual, err := ParseCIDRs([]string{})
+		assert.NoError(t, err)
+		assert.Empty(t, actual)
+	})
+	t.Run("1 ipv4 cidr", func(t *testing.T) {
+		actual, err := ParseCIDRs([]string{
+			"10.10.10.0/24",
+		})
+		assert.NoError(t, err)
+		assert.Equal(t, []netip.Prefix{
+			netip.MustParsePrefix("10.10.10.0/24"),
+		}, actual)
+	})
+	t.Run("1 ipv6 cidr", func(t *testing.T) {
+		actual, err := ParseCIDRs([]string{
+			"2001:db8::/32",
+		})
+		assert.NoError(t, err)
+		assert.Equal(t, []netip.Prefix{
+			netip.MustParsePrefix("2001:db8::/32"),
+		}, actual)
+	})
+	t.Run("multiple cidrs", func(t *testing.T) {
+		actual, err := ParseCIDRs([]string{
+			"10.10.10.0/24",
+			"2001:db8::/32",
+		})
+		assert.NoError(t, err)
+		assert.Equal(t, []netip.Prefix{
+			netip.MustParsePrefix("10.10.10.0/24"),
+			netip.MustParsePrefix("2001:db8::/32"),
+		}, actual)
+	})
+	t.Run("invalid cidr", func(t *testing.T) {
+		{
+			_, err := ParseCIDRs([]string{""})
+			assert.Error(t, err)
+		}
+		{
+			_, err := ParseCIDRs([]string{"foo"})
+			assert.Error(t, err)
+		}
+		{
+			_, err := ParseCIDRs([]string{"10.10.10.0/24", "foo"})
+			assert.Error(t, err)
+		}
+	})
+}
diff --git a/tests/e2e/network/network_security_group.go b/tests/e2e/network/network_security_group.go
index bbb57724d..6c0c7a713 100644
--- a/tests/e2e/network/network_security_group.go
+++ b/tests/e2e/network/network_security_group.go
@@ -185,7 +185,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func(
 	It("can set source IP prefixes automatically according to corresponding service tag", func() {
 		By("Creating service and wait it to expose")
 		annotation := map[string]string{
-			consts.ServiceAnnotationAllowedServiceTag: "AzureCloud",
+			consts.ServiceAnnotationAllowedServiceTags: "AzureCloud",
 		}
 		utils.Logf("Creating service " + serviceName + " in namespace " + ns.Name)
 		service := utils.CreateLoadBalancerServiceManifest(serviceName, annotation, labels, ns.Name, ports)
@@ -335,6 +335,73 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func(
 		}
 	})
 
+	It("should support service annotation `service.beta.kubernetes.io/azure-allowed-ip-ranges`", func() {
+
+		// isSuperSet returns true if set1 is a superset of set2.
+		isSuperSet := func(set1, set2 []string) bool {
+			s1 := map[string]bool{}
+			for _, s := range set1 {
+				s1[s] = true
+			}
+			for _, s := range set2 {
+				if !s1[s] {
+					return false
+				}
+			}
+			return true
+		}
+
+		allowedIPRanges := []string{
+			"10.20.0.0/16",
+			"192.168.0.1/32",
+		}
+
+		ipFamilyPolicy := v1.IPFamilyPolicyPreferDualStack
+		svc := v1.Service{
+			Spec: v1.ServiceSpec{
+				Ports:          ports,
+				Type:           v1.ServiceTypeLoadBalancer,
+				Selector:       labels,
+				IPFamilyPolicy: &ipFamilyPolicy,
+			},
+			ObjectMeta: metav1.ObjectMeta{
+				Name:      serviceName,
+				Namespace: ns.Name,
+				Annotations: map[string]string{
+					consts.ServiceAnnotationAllowedIPRanges: strings.Join(allowedIPRanges, ","),
+				},
+				Labels: labels,
+			},
+		}
+
+		By("Creating load balancer service with allowed IP ranges")
+		_, err := cs.CoreV1().Services(ns.Name).Create(context.Background(), &svc, metav1.CreateOptions{})
+		Expect(err).NotTo(HaveOccurred())
+
+		By("Waiting for the service to be exposed")
+		_, err = utils.WaitServiceExposure(cs, ns.Name, serviceName, nil)
+		Expect(err).NotTo(HaveOccurred())
+
+		By("Validating if the corresponding IP prefix existing in nsg")
+		nsgs, err := tc.GetClusterSecurityGroups()
+		Expect(err).NotTo(HaveOccurred())
+
+		var sources []string
+
+		for _, nsg := range nsgs {
+
+			rules := nsg.SecurityRules
+			if rules == nil {
+				continue
+			}
+			for _, rule := range *rules {
+				if rule.SourceAddressPrefix != nil {
+					sources = append(sources, *rule.SourceAddressPrefix)
+				}
+			}
+		}
+		Expect(isSuperSet(sources, allowedIPRanges)).To(BeTrue(), "Expected %v to be a superset of %v", sources, allowedIPRanges)
+	})
 })
 
 func validateUnsharedSecurityRuleExists(nsgs []aznetwork.SecurityGroup, ip string, port string) bool {