예제 #1
0
        private static IEnumerable <SecurityRule> Merge(SecurityRule rule, SecurityRule[] rules)
        {
            List <SecurityRule> result = new List <SecurityRule>();

            result.Add(rule);

            Collections.addAll(result, rules);

            return(result);
        }
예제 #2
0
        private void AddSecurityRule(string resourceGroupName, string nsgName, string securityRuleName,
                                     int priority, string description, string protocol, string access, string direction,
                                     string sourcePortRange      = "*", string sourceAddressPrefix      = "*",
                                     string destinationPortRange = "*", string destinationAddressPrefix = "*")
        {
            var securityRule = new SecurityRule(protocol: protocol, sourceAddressPrefix: sourceAddressPrefix,
                                                destinationAddressPrefix: destinationAddressPrefix, access: access,
                                                direction: direction, description: description, sourcePortRange: sourcePortRange,
                                                destinationPortRange: destinationPortRange, priority: priority, name: securityRuleName);

            WrappedNetworkClient.SecurityRules.CreateOrUpdate(resourceGroupName, nsgName, securityRuleName, securityRule);
        }
        public static bool Check(SecurityRule sg, ICollection <string> failedPredicateNames)
        {
            var failed = false;

            foreach (var check in _checks)
            {
                if (!check(sg))
                {
                    failedPredicateNames.Add(check.Method.Name);
                    failed = true;
                }
            }
            return(!failed);
        }
예제 #4
0
 private void CompareSecurityRule(SecurityRule rule1, SecurityRule rule2)
 {
     Assert.Equal(rule1.Name, rule2.Name);
     Assert.Equal(rule1.Etag, rule2.Etag);
     Assert.Equal(rule1.Access, rule2.Access);
     Assert.Equal(rule1.Description, rule2.Description);
     Assert.Equal(rule1.DestinationAddressPrefix, rule2.DestinationAddressPrefix);
     Assert.Equal(rule1.DestinationPortRange, rule2.DestinationPortRange);
     Assert.Equal(rule1.Direction, rule2.Direction);
     Assert.Equal(rule1.Protocol, rule2.Protocol);
     Assert.Equal(rule1.ProvisioningState, rule2.ProvisioningState);
     Assert.Equal(rule1.SourceAddressPrefix, rule2.SourceAddressPrefix);
     Assert.Equal(rule1.SourcePortRange, rule2.SourcePortRange);
 }
예제 #5
0
        public async Task SetRule(Guid entityId, RuleSubject subject, SecurityRule rule)
        {
            var entityRule = await GetRule(entityId, subject, rule);

            if (entityRule != null)
            {
                entityRule.Rule = rule;
                await Update(entityRule);

                return;
            }

            await Add(new EntitySecurityRule
            {
                EntityId = entityId,
                Subject  = subject,
                Rule     = rule,
            });
        }
예제 #6
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldPassThroughRequestToAnUnsecuredPath() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldPassThroughRequestToAnUnsecuredPath()
        {
            // given
            SecurityRule rule = mock(typeof(SecurityRule));

            when(rule.ForUriPath()).thenReturn("/some-path");

            FilterChain filterChain = mock(typeof(FilterChain));

            SecurityFilter securityFilter = new SecurityFilter(rule);

            HttpServletRequest request = mock(typeof(HttpServletRequest));

            when(request.ContextPath).thenReturn("/some-other-path");

            // when
            securityFilter.DoFilter(request, mock(typeof(HttpServletResponse)), filterChain);

            // then
            verify(filterChain).doFilter(any(typeof(HttpServletRequest)), any(typeof(HttpServletResponse)));
        }
예제 #7
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldActivateRuleThatRejectsTheRequestForAMatchingPath() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldActivateRuleThatRejectsTheRequestForAMatchingPath()
        {
            // given
            SecurityRule rule = mock(typeof(SecurityRule));

            when(rule.ForUriPath()).thenReturn("/some-path");
            when(rule.IsAuthorized(any(typeof(HttpServletRequest)))).thenReturn(false);

            FilterChain filterChain = mock(typeof(FilterChain));

            SecurityFilter securityFilter = new SecurityFilter(rule);

            HttpServletRequest request = mock(typeof(HttpServletRequest));

            when(request.ContextPath).thenReturn("/some-path");

            // when
            securityFilter.DoFilter(request, mock(typeof(HttpServletResponse)), filterChain);

            // then
            verify(filterChain, never()).doFilter(any(typeof(HttpServletRequest)), any(typeof(HttpServletResponse)));
        }
예제 #8
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldRemoveRules() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldRemoveRules()
        {
            // given
            SecurityRule securityRule1 = mock(typeof(SecurityRule));

            when(securityRule1.ForUriPath()).thenReturn("/securityRule1");

            SecurityRule securityRule2 = mock(typeof(SecurityRule));

            when(securityRule2.ForUriPath()).thenReturn("/securityRule2");

            SecurityFilter securityFilter = new SecurityFilter(securityRule1, securityRule2);

            HttpServletRequest  request     = mock(typeof(HttpServletRequest));
            HttpServletResponse response    = mock(typeof(HttpServletResponse));
            FilterChain         filterChain = mock(typeof(FilterChain));

            // when
            securityFilter.Destroy();
            securityFilter.DoFilter(request, response, filterChain);

            // then
            verify(filterChain).doFilter(request, response);
        }
        /// <summary>
        /// The Put network security rule operation creates/updates a security rule in
        /// the specified network security group
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='networkSecurityGroupName'>
        /// The name of the network security group.
        /// </param>
        /// <param name='securityRuleName'>
        /// The name of the security rule.
        /// </param>
        /// <param name='securityRuleParameters'>
        /// Parameters supplied to the create/update network security rule operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public async Task <AzureOperationResponse <SecurityRule> > BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (networkSecurityGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
            }
            if (securityRuleName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleName");
            }
            if (securityRuleParameters == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleParameters");
            }
            if (securityRuleParameters != null)
            {
                securityRuleParameters.Validate();
            }
            if (this.Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            if (this.Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            // Tracing
            bool   shouldTrace  = ServiceClientTracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
                tracingParameters.Add("securityRuleName", securityRuleName);
                tracingParameters.Add("securityRuleParameters", securityRuleParameters);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(invocationId, this, "BeginCreateOrUpdate", tracingParameters);
            }
            // Construct URL
            var baseUrl = this.Client.BaseUri.AbsoluteUri;
            var url     = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}").ToString();

            url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
            url = url.Replace("{networkSecurityGroupName}", Uri.EscapeDataString(networkSecurityGroupName));
            url = url.Replace("{securityRuleName}", Uri.EscapeDataString(securityRuleName));
            url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
            List <string> queryParameters = new List <string>();

            if (this.Client.ApiVersion != null)
            {
                queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (queryParameters.Count > 0)
            {
                url += "?" + string.Join("&", queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage httpRequest = new HttpRequestMessage();

            httpRequest.Method     = new HttpMethod("PUT");
            httpRequest.RequestUri = new Uri(url);
            // Set Headers
            httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
            if (this.Client.AcceptLanguage != null)
            {
                if (httpRequest.Headers.Contains("accept-language"))
                {
                    httpRequest.Headers.Remove("accept-language");
                }
                httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach (var header in customHeaders)
                {
                    if (httpRequest.Headers.Contains(header.Key))
                    {
                        httpRequest.Headers.Remove(header.Key);
                    }
                    httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            // Serialize Request
            string requestContent = JsonConvert.SerializeObject(securityRuleParameters, this.Client.SerializationSettings);

            httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
            httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (shouldTrace)
            {
                ServiceClientTracing.SendRequest(invocationId, httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

            if (shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
            }
            HttpStatusCode statusCode = httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            if ((int)statusCode != 200 && (int)statusCode != 201)
            {
                var    ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
                string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                CloudError errorBody = JsonConvert.DeserializeObject <CloudError>(responseContent, this.Client.DeserializationSettings);
                if (errorBody != null)
                {
                    ex      = new CloudException(errorBody.Message);
                    ex.Body = errorBody;
                }
                ex.Request  = new HttpRequestMessageWrapper(httpRequest, null);
                ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent);
                if (shouldTrace)
                {
                    ServiceClientTracing.Error(invocationId, ex);
                }
                throw ex;
            }
            // Create Result
            var result = new AzureOperationResponse <SecurityRule>();

            result.Request  = httpRequest;
            result.Response = httpResponse;
            if (httpResponse.Headers.Contains("x-ms-request-id"))
            {
                result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)statusCode == 200)
            {
                string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                result.Body = JsonConvert.DeserializeObject <SecurityRule>(responseContent, this.Client.DeserializationSettings);
            }
            // Deserialize Response
            if ((int)statusCode == 201)
            {
                string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                result.Body = JsonConvert.DeserializeObject <SecurityRule>(responseContent, this.Client.DeserializationSettings);
            }
            if (shouldTrace)
            {
                ServiceClientTracing.Exit(invocationId, result);
            }
            return(result);
        }
예제 #10
0
 internal ForbiddenRuleDecorator(SecurityRule rule)
 {
     this.InnerRule = rule;
 }
예제 #11
0
 public SecurityFilter(SecurityRule rule, params SecurityRule[] rules) : this(Merge(rule, rules))
 {
 }
예제 #12
0
 /// <summary>
 /// Creates or updates a security rule in the specified network security group.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='networkSecurityGroupName'>
 /// The name of the network security group.
 /// </param>
 /// <param name='securityRuleName'>
 /// The name of the security rule.
 /// </param>
 /// <param name='securityRuleParameters'>
 /// Parameters supplied to the create or update network security rule
 /// operation.
 /// </param>
 public static SecurityRule BeginCreateOrUpdate(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters)
 {
     return(operations.BeginCreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters).GetAwaiter().GetResult());
 }
예제 #13
0
 /// <summary>
 /// Creates or updates a security rule in the specified network security group.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='networkSecurityGroupName'>
 /// The name of the network security group.
 /// </param>
 /// <param name='securityRuleName'>
 /// The name of the security rule.
 /// </param>
 /// <param name='securityRuleParameters'>
 /// Parameters supplied to the create or update network security rule
 /// operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <SecurityRule> BeginCreateOrUpdateAsync(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
예제 #14
0
 public async Task SetEntityPermission(Guid entityId, RuleSubject subject, SecurityRule rule)
 {
     await SetEntityPermissions(entityId, subject, new List <SecurityRule> {
         rule
     });
 }
 /// <summary>
 /// The Put network security rule operation creates/updates a security
 /// rule in the specified network security group
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Network.ISecurityRuleOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group.
 /// </param>
 /// <param name='networkSecurityGroupName'>
 /// Required. The name of the network security group.
 /// </param>
 /// <param name='securityRuleName'>
 /// Required. The name of the security rule.
 /// </param>
 /// <param name='securityRuleParameters'>
 /// Required. Parameters supplied to the create/update network security
 /// rule operation
 /// </param>
 /// <returns>
 /// Response for PUT SecurityRule Api service call
 /// </returns>
 public static Task <SecurityRulePutResponse> BeginCreateOrUpdatingAsync(this ISecurityRuleOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters)
 {
     return(operations.BeginCreateOrUpdatingAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, CancellationToken.None));
 }
 public CustomList <SecurityRule> GetAlltblSecurityRule()
 {
     return(SecurityRule.doSearch(String.Empty));
 }
        public void ViewNsgRuleApiTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler3 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var resourcesClient         = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1);
                var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);
                var computeManagementClient = NetworkManagementTestUtilities.GetComputeManagementClientWithHandler(context, handler3);

                string location = "westcentralus";

                string resourceGroupName = TestUtilities.GenerateName();
                resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
                                                              new ResourceGroup
                {
                    Location = location
                });

                string virtualMachineName       = TestUtilities.GenerateName();
                string networkInterfaceName     = TestUtilities.GenerateName();
                string networkSecurityGroupName = virtualMachineName + "-nsg";

                //Deploy VM with template
                Deployments.CreateVm(
                    resourcesClient: resourcesClient,
                    resourceGroupName: resourceGroupName,
                    location: location,
                    virtualMachineName: virtualMachineName,
                    storageAccountName: TestUtilities.GenerateName(),
                    networkInterfaceName: networkInterfaceName,
                    networkSecurityGroupName: networkSecurityGroupName,
                    diagnosticsStorageAccountName: TestUtilities.GenerateName(),
                    deploymentName: TestUtilities.GenerateName()
                    );

                string         networkWatcherName = TestUtilities.GenerateName();
                NetworkWatcher properties         = new NetworkWatcher();
                properties.Location = location;

                //Create network Watcher
                var createNetworkWatcher = networkManagementClient.NetworkWatchers.CreateOrUpdate(resourceGroupName, networkWatcherName, properties);

                var    getVm          = computeManagementClient.VirtualMachines.Get(resourceGroupName, virtualMachineName);
                string localIPAddress = networkManagementClient.NetworkInterfaces.Get(resourceGroupName, networkInterfaceName).IpConfigurations.FirstOrDefault().PrivateIPAddress;

                string securityRule1 = TestUtilities.GenerateName();

                // Add a security rule
                var SecurityRule = new SecurityRule()
                {
                    Name        = securityRule1,
                    Access      = SecurityRuleAccess.Deny,
                    Description = "Test outbound security rule",
                    DestinationAddressPrefix = "*",
                    DestinationPortRange     = "80",
                    Direction           = SecurityRuleDirection.Outbound,
                    Priority            = 501,
                    Protocol            = SecurityRuleProtocol.Tcp,
                    SourceAddressPrefix = "*",
                    SourcePortRange     = "*",
                };

                var nsg = networkManagementClient.NetworkSecurityGroups.Get(resourceGroupName, networkSecurityGroupName);
                nsg.SecurityRules.Add(SecurityRule);
                networkManagementClient.NetworkSecurityGroups.CreateOrUpdate(resourceGroupName, networkSecurityGroupName, nsg);

                SecurityGroupViewParameters sgvProperties = new SecurityGroupViewParameters()
                {
                    TargetResourceId = getVm.Id
                };

                //Get view security group rules
                var viewNSGRules = networkManagementClient.NetworkWatchers.GetVMSecurityRules(resourceGroupName, networkWatcherName, sgvProperties);

                //Verify effective security rule defined earlier
                var getEffectiveSecurityRule = viewNSGRules.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.EffectiveSecurityRules.Where(x => x.Name == "UserRule_" + securityRule1);
                Assert.Equal("Tcp", getEffectiveSecurityRule.FirstOrDefault().Protocol);
                Assert.Equal(501, getEffectiveSecurityRule.FirstOrDefault().Priority);
                Assert.Equal("Deny", getEffectiveSecurityRule.FirstOrDefault().Access);
                Assert.Equal("Outbound", getEffectiveSecurityRule.FirstOrDefault().Direction);
                Assert.Equal("0.0.0.0/0", getEffectiveSecurityRule.FirstOrDefault().DestinationAddressPrefix);
                Assert.Equal("80-80", getEffectiveSecurityRule.FirstOrDefault().DestinationPortRange);
                Assert.Equal("0.0.0.0/0", getEffectiveSecurityRule.FirstOrDefault().SourceAddressPrefix);
                Assert.Equal("0-65535", getEffectiveSecurityRule.FirstOrDefault().SourcePortRange);

                //Verify 6 default rules
                var getDefaultSecurityRule1 = viewNSGRules.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "AllowVnetInBound");
                Assert.Equal("*", getDefaultSecurityRule1.FirstOrDefault().Protocol);
                Assert.Equal(65000, getDefaultSecurityRule1.FirstOrDefault().Priority);
                Assert.Equal("Allow", getDefaultSecurityRule1.FirstOrDefault().Access);
                Assert.Equal("Inbound", getDefaultSecurityRule1.FirstOrDefault().Direction);
                Assert.Equal("VirtualNetwork", getDefaultSecurityRule1.FirstOrDefault().DestinationAddressPrefix);
                Assert.Equal("*", getDefaultSecurityRule1.FirstOrDefault().DestinationPortRange);
                Assert.Equal("VirtualNetwork", getDefaultSecurityRule1.FirstOrDefault().SourceAddressPrefix);
                Assert.Equal("*", getDefaultSecurityRule1.FirstOrDefault().SourcePortRange);

                var getDefaultSecurityRule2 = viewNSGRules.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "AllowAzureLoadBalancerInBound");
                Assert.Equal("*", getDefaultSecurityRule2.FirstOrDefault().Protocol);
                Assert.Equal(65001, getDefaultSecurityRule2.FirstOrDefault().Priority);
                Assert.Equal("Allow", getDefaultSecurityRule2.FirstOrDefault().Access);
                Assert.Equal("Inbound", getDefaultSecurityRule2.FirstOrDefault().Direction);
                Assert.Equal("*", getDefaultSecurityRule2.FirstOrDefault().DestinationAddressPrefix);
                Assert.Equal("*", getDefaultSecurityRule2.FirstOrDefault().DestinationPortRange);
                Assert.Equal("AzureLoadBalancer", getDefaultSecurityRule2.FirstOrDefault().SourceAddressPrefix);
                Assert.Equal("*", getDefaultSecurityRule2.FirstOrDefault().SourcePortRange);

                var getDefaultSecurityRule3 = viewNSGRules.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "DenyAllInBound");
                Assert.Equal("*", getDefaultSecurityRule3.FirstOrDefault().Protocol);
                Assert.Equal(65500, getDefaultSecurityRule3.FirstOrDefault().Priority);
                Assert.Equal("Deny", getDefaultSecurityRule3.FirstOrDefault().Access);
                Assert.Equal("Inbound", getDefaultSecurityRule3.FirstOrDefault().Direction);
                Assert.Equal("*", getDefaultSecurityRule3.FirstOrDefault().DestinationAddressPrefix);
                Assert.Equal("*", getDefaultSecurityRule3.FirstOrDefault().DestinationPortRange);
                Assert.Equal("*", getDefaultSecurityRule3.FirstOrDefault().SourceAddressPrefix);
                Assert.Equal("*", getDefaultSecurityRule3.FirstOrDefault().SourcePortRange);

                var getDefaultSecurityRule4 = viewNSGRules.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "AllowVnetOutBound");
                Assert.Equal("*", getDefaultSecurityRule4.FirstOrDefault().Protocol);
                Assert.Equal(65000, getDefaultSecurityRule4.FirstOrDefault().Priority);
                Assert.Equal("Allow", getDefaultSecurityRule4.FirstOrDefault().Access);
                Assert.Equal("Outbound", getDefaultSecurityRule4.FirstOrDefault().Direction);
                Assert.Equal("VirtualNetwork", getDefaultSecurityRule4.FirstOrDefault().DestinationAddressPrefix);
                Assert.Equal("*", getDefaultSecurityRule4.FirstOrDefault().DestinationPortRange);
                Assert.Equal("VirtualNetwork", getDefaultSecurityRule4.FirstOrDefault().SourceAddressPrefix);
                Assert.Equal("*", getDefaultSecurityRule4.FirstOrDefault().SourcePortRange);

                var getDefaultSecurityRule5 = viewNSGRules.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "AllowInternetOutBound");
                Assert.Equal("*", getDefaultSecurityRule5.FirstOrDefault().Protocol);
                Assert.Equal(65001, getDefaultSecurityRule5.FirstOrDefault().Priority);
                Assert.Equal("Allow", getDefaultSecurityRule5.FirstOrDefault().Access);
                Assert.Equal("Outbound", getDefaultSecurityRule5.FirstOrDefault().Direction);
                Assert.Equal("Internet", getDefaultSecurityRule5.FirstOrDefault().DestinationAddressPrefix);
                Assert.Equal("*", getDefaultSecurityRule5.FirstOrDefault().DestinationPortRange);
                Assert.Equal("*", getDefaultSecurityRule5.FirstOrDefault().SourceAddressPrefix);
                Assert.Equal("*", getDefaultSecurityRule5.FirstOrDefault().SourcePortRange);

                var getDefaultSecurityRule6 = viewNSGRules.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "DenyAllOutBound");
                Assert.Equal("*", getDefaultSecurityRule6.FirstOrDefault().Protocol);
                Assert.Equal(65500, getDefaultSecurityRule6.FirstOrDefault().Priority);
                Assert.Equal("Deny", getDefaultSecurityRule6.FirstOrDefault().Access);
                Assert.Equal("Outbound", getDefaultSecurityRule6.FirstOrDefault().Direction);
                Assert.Equal("*", getDefaultSecurityRule6.FirstOrDefault().DestinationAddressPrefix);
                Assert.Equal("*", getDefaultSecurityRule6.FirstOrDefault().DestinationPortRange);
                Assert.Equal("*", getDefaultSecurityRule6.FirstOrDefault().SourceAddressPrefix);
                Assert.Equal("*", getDefaultSecurityRule6.FirstOrDefault().SourcePortRange);
            }
        }
        /// <summary>
        /// The Put network security rule operation creates/updates a security rule in
        /// the specified network security group
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='networkSecurityGroupName'>
        /// The name of the network security group.
        /// </param>
        /// <param name='securityRuleName'>
        /// The name of the security rule.
        /// </param>
        /// <param name='securityRuleParameters'>
        /// Parameters supplied to the create/update network security rule operation
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public async Task <AzureOperationResponse <SecurityRule> > CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Send Request
            AzureOperationResponse <SecurityRule> response = await BeginCreateOrUpdateWithHttpMessagesAsync(
                resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, customHeaders, cancellationToken);

            return(await this.Client.GetPutOrPatchOperationResultAsync <SecurityRule>(response,
                                                                                      customHeaders,
                                                                                      cancellationToken));
        }
예제 #19
0
        public async Task Create_derived_item()
        {
            using (var server = CreateServerWithAuthentication())
                using (server.Host.Services
                       .GetRequiredService <ISecurityImpersonationService>()
                       .ImpersonateUser("User1"))
                {
                    var context = GetEntityContext <TestEntityContext>(server);

                    #region create root

                    var rootItem = await context.Commands.Add(new TestEntity
                    {
                        Name = "root"
                    });

                    #endregion

                    #region create

                    var item = await context.Commands.Add(new DerivedTestEntity
                    {
                        Name = "gigi"
                    }, rootItem);

                    #endregion

                    //#region AsQueryable retreive

                    //Assert.NotEqual(Guid.Empty, item.Id);
                    //var foundItem = context.Query
                    //    .AsQueryable<DerivedTestEntity>()
                    //    .FirstOrDefault(x => x.Id == item.Id);

                    //Assert.NotNull(foundItem);
                    //Assert.Equal(item.Id, foundItem.Id);
                    //Assert.Equal(item.Name, foundItem.Name);

                    //#endregion

                    #region GetItem retreive

                    var foundItem = await context.Query.GetItem <DerivedTestEntity>(item.Id);

                    Assert.NotNull(foundItem);
                    Assert.Equal(item.Id, foundItem.Id);
                    Assert.Equal(item.Name, foundItem.Name);

                    var foundItems = await context.Query.GetItems <TestEntity>("/root/gigi");

                    Assert.NotEmpty(foundItems);
                    Assert.Contains(foundItems, x => x.Id == item.Id);
                    Assert.Contains(foundItems, x => x.Name == item.Name);

                    #endregion

                    #region GetChild retreive

                    foundItem = await context.Query.GetChild <DerivedTestEntity>(rootItem);

                    Assert.NotNull(foundItem);
                    Assert.Equal(item.Id, foundItem.Id);
                    Assert.Equal(item.Name, foundItem.Name);

                    #endregion

                    #region filtered GetChild retreive

                    foundItem = await context.Query.GetChild <DerivedTestEntity>(rootItem, x => x.Name == "gigio");

                    Assert.Null(foundItem);

                    foundItem = await context.Query.GetChild <DerivedTestEntity>(rootItem, x => x.Name == "gigi");

                    Assert.NotNull(foundItem);
                    Assert.Equal(item.Id, foundItem.Id);
                    Assert.Equal(item.Name, foundItem.Name);

                    #endregion

                    #region Update

                    var itemToUpdate = await context.Query.GetItem <DerivedTestEntity>(item.Id);

                    itemToUpdate.Name = "gigi-new";
                    var updatedItem = await context.Commands.Update(itemToUpdate);

                    Assert.NotNull(updatedItem);
                    Assert.Equal(itemToUpdate.Name, updatedItem.Name);

                    #endregion

                    #region partial update

                    var partialUpdatedItem = await context.Commands.Update <DerivedTestEntity, string>(itemToUpdate.Id, x => x.Val2, "val-2");

                    Assert.NotNull(partialUpdatedItem);
                    Assert.Equal("val-2", partialUpdatedItem.Val2);

                    var partialUpdatedItem2 = await context.Commands.Update <DerivedTestEntity, string>(itemToUpdate.Id, x => x.Val2, null);

                    Assert.NotNull(partialUpdatedItem2);
                    Assert.Null(partialUpdatedItem2.Val2);

                    #endregion

                    #region Rename

                    await context.Commands.Rename(rootItem, "root-new");

                    var renamedRootItems = await context.Query.GetItems <TestEntity>("/root-new");

                    var renamedRootItem = renamedRootItems.FirstOrDefault(x => x.Id == rootItem.Id);
                    Assert.NotNull(renamedRootItem);

                    var renamedItems = await context.Query.GetItems <DerivedTestEntity>("/root-new/gigi");

                    var renamedItem = renamedItems.FirstOrDefault(x => x.Id == item.Id);
                    Assert.NotNull(renamedItem);

                    #endregion

                    #region Move

                    var rootItem2 = await context.Commands.Add(new TestEntity
                    {
                        Name = "root2"
                    });

                    await context.Commands.Move(rootItem, rootItem2);

                    var movedItems = await context.Query.GetItems <DerivedTestEntity>("/root2/root-new/gigi");

                    var movedItem = movedItems.FirstOrDefault(x => x.Id == item.Id);
                    Assert.NotNull(movedItem);

                    await context.Commands.Move(movedItem, rootItem2);

                    var secondMovedItems = await context.Query.GetItems <DerivedTestEntity>("/root2/gigi");

                    var secondMovedItem = secondMovedItems.FirstOrDefault(x => x.Id == item.Id);
                    Assert.NotNull(secondMovedItem);

                    #endregion

                    #region permissions

                    await context.Commands.SetEntityPermission(rootItem2.Id, RuleSubject.User("User1"), SecurityRule.DenyRead(true));

                    var readDeniedItem = await context.Query.GetItem <TestEntity>(rootItem2.Id);

                    Assert.Null(readDeniedItem);

                    await context.Commands.ClearEntityPermissions(rootItem2.Id, RuleSubject.User("User1"));

                    readDeniedItem = await context.Query.GetItem <TestEntity>(rootItem2.Id);

                    Assert.NotNull(readDeniedItem);

                    #endregion

                    #region delete

                    await context.Commands.Delete(rootItem2);

                    var foundItemAfterDelete = await context.Query
                                               .GetItem <DerivedTestEntity>(item.Id);

                    Assert.Null(foundItemAfterDelete);

                    #endregion

                    #region filtered delete

                    await context.Commands.Add(new DerivedTestEntity()
                    {
                        Name = "derived-entity-to-delete"
                    });

                    Assert.NotNull(await context.Query.GetItem <DerivedTestEntity>(x => x.Name == "derived-entity-to-delete"));

                    await context.Commands.Delete <DerivedTestEntity>(x => x.Name == "derived-entity-to-delete");

                    Assert.Null(await context.Query.GetItem <DerivedTestEntity>(x => x.Name == "derived-entity-to-delete"));

                    #endregion
                }
        }
예제 #20
0
        public async Task SecurityRuleWithRulesApiTest()
        {
            string resourceGroupName = Recording.GenerateAssetName("csmrg");

            string location = await NetworkManagementTestUtilities.GetResourceLocation(ResourceManagementClient, "Microsoft.Network/networkSecurityGroups");

            await ResourceGroupsOperations.CreateOrUpdateAsync(resourceGroupName, new ResourceGroup(location));

            string networkSecurityGroupName = Recording.GenerateAssetName("azsmnet");
            string securityRule1            = Recording.GenerateAssetName("azsmnet");
            string securityRule2            = Recording.GenerateAssetName("azsmnet");
            string destinationPortRange     = "123-3500";

            NetworkSecurityGroup networkSecurityGroup = new NetworkSecurityGroup()
            {
                Location      = location,
                SecurityRules =
                {
                    new SecurityRule()
                    {
                        Name        = securityRule1,
                        Access      = SecurityRuleAccess.Allow,
                        Description = "Test security rule",
                        DestinationAddressPrefix = "*",
                        DestinationPortRange     = destinationPortRange,
                        Direction           = SecurityRuleDirection.Inbound,
                        Priority            = 500,
                        Protocol            = SecurityRuleProtocol.Tcp,
                        SourceAddressPrefix = "*",
                        SourcePortRange     = "655"
                    }
                }
            };

            // Put Nsg
            NetworkSecurityGroupsCreateOrUpdateOperation putNsgResponseOperation = await NetworkManagementClient.NetworkSecurityGroups.StartCreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, networkSecurityGroup);

            Response <NetworkSecurityGroup> putNsgResponse = await WaitForCompletionAsync(putNsgResponseOperation);

            Assert.AreEqual("Succeeded", putNsgResponse.Value.ProvisioningState.ToString());

            // Get NSG
            Response <NetworkSecurityGroup> getNsgResponse = await NetworkManagementClient.NetworkSecurityGroups.GetAsync(resourceGroupName, networkSecurityGroupName);

            Assert.AreEqual(networkSecurityGroupName, getNsgResponse.Value.Name);

            // Get SecurityRule
            Response <SecurityRule> getSecurityRuleResponse = await NetworkManagementClient.SecurityRules.GetAsync(resourceGroupName, networkSecurityGroupName, securityRule1);

            Assert.AreEqual(securityRule1, getSecurityRuleResponse.Value.Name);

            CompareSecurityRule(getNsgResponse.Value.SecurityRules[0], getSecurityRuleResponse);

            // Add a new security rule
            SecurityRule SecurityRule = new SecurityRule()
            {
                Name        = securityRule2,
                Access      = SecurityRuleAccess.Deny,
                Description = "Test outbound security rule",
                DestinationAddressPrefix = "*",
                DestinationPortRange     = destinationPortRange,
                Direction           = SecurityRuleDirection.Outbound,
                Priority            = 501,
                Protocol            = SecurityRuleProtocol.Udp,
                SourceAddressPrefix = "*",
                SourcePortRange     = "656",
            };

            SecurityRulesCreateOrUpdateOperation putSecurityRuleResponseOperation = await NetworkManagementClient.SecurityRules.StartCreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, securityRule2, SecurityRule);

            Response <SecurityRule> putSecurityRuleResponse = await WaitForCompletionAsync(putSecurityRuleResponseOperation);

            Assert.AreEqual("Succeeded", putSecurityRuleResponse.Value.ProvisioningState.ToString());

            // Get NSG
            getNsgResponse = await NetworkManagementClient.NetworkSecurityGroups.GetAsync(resourceGroupName, networkSecurityGroupName);

            // Get the SecurityRule2
            Response <SecurityRule> getSecurityRule2Response = await NetworkManagementClient.SecurityRules.GetAsync(resourceGroupName, networkSecurityGroupName, securityRule2);

            Assert.AreEqual(securityRule2, getSecurityRule2Response.Value.Name);

            // Verify the security rule
            Assert.AreEqual(SecurityRuleAccess.Deny, getSecurityRule2Response.Value.Access);
            Assert.AreEqual("Test outbound security rule", getSecurityRule2Response.Value.Description);
            Assert.AreEqual("*", getSecurityRule2Response.Value.DestinationAddressPrefix);
            Assert.AreEqual(destinationPortRange, getSecurityRule2Response.Value.DestinationPortRange);
            Assert.AreEqual(SecurityRuleDirection.Outbound, getSecurityRule2Response.Value.Direction);
            Assert.AreEqual(501, getSecurityRule2Response.Value.Priority);
            Assert.AreEqual(SecurityRuleProtocol.Udp, getSecurityRule2Response.Value.Protocol);
            Assert.AreEqual("Succeeded", getSecurityRule2Response.Value.ProvisioningState.ToString());
            Assert.AreEqual("*", getSecurityRule2Response.Value.SourceAddressPrefix);
            Assert.AreEqual("656", getSecurityRule2Response.Value.SourcePortRange);

            CompareSecurityRule(getNsgResponse.Value.SecurityRules[1], getSecurityRule2Response);

            // List all SecurityRules
            AsyncPageable <SecurityRule> getsecurityRulesAP = NetworkManagementClient.SecurityRules.ListAsync(resourceGroupName, networkSecurityGroupName);
            List <SecurityRule>          getsecurityRules   = await getsecurityRulesAP.ToEnumerableAsync();

            Assert.AreEqual(2, getsecurityRules.Count());
            CompareSecurityRule(getNsgResponse.Value.SecurityRules[0], getsecurityRules.ElementAt(0));
            CompareSecurityRule(getNsgResponse.Value.SecurityRules[1], getsecurityRules.ElementAt(1));

            // Delete a SecurityRule
            await NetworkManagementClient.SecurityRules.StartDeleteAsync(resourceGroupName, networkSecurityGroupName, securityRule2);

            getsecurityRulesAP = NetworkManagementClient.SecurityRules.ListAsync(resourceGroupName, networkSecurityGroupName);
            getsecurityRules   = await getsecurityRulesAP.ToEnumerableAsync();

            Has.One.EqualTo(getsecurityRules);

            // Delete NSG
            await NetworkManagementClient.NetworkSecurityGroups.StartDeleteAsync(resourceGroupName, networkSecurityGroupName);

            // List NSG
            AsyncPageable <NetworkSecurityGroup> listNsgResponseAP = NetworkManagementClient.NetworkSecurityGroups.ListAsync(resourceGroupName);
            List <NetworkSecurityGroup>          listNsgResponse   = await listNsgResponseAP.ToEnumerableAsync();

            Assert.IsEmpty(listNsgResponse);
        }
        public async Task NetworkSecurityGroupWithRulesApiTest()
        {
            string resourceGroupName = Recording.GenerateAssetName("csmrg");

            string location = await NetworkManagementTestUtilities.GetResourceLocation(ResourceManagementClient, "Microsoft.Network/networkSecurityGroups");

            await ResourceGroupsOperations.CreateOrUpdateAsync(resourceGroupName, new ResourceGroup(location));

            string networkSecurityGroupName = Recording.GenerateAssetName("azsmnet");
            string securityRule1            = Recording.GenerateAssetName("azsmnet");
            string securityRule2            = Recording.GenerateAssetName("azsmnet");

            string destinationPortRange = "123-3500";

            NetworkSecurityGroup networkSecurityGroup = new NetworkSecurityGroup()
            {
                Location      = location,
                SecurityRules =
                {
                    new SecurityRule()
                    {
                        Name        = securityRule1,
                        Access      = SecurityRuleAccess.Allow,
                        Description = "Test security rule",
                        DestinationAddressPrefix = "*",
                        DestinationPortRange     = destinationPortRange,
                        Direction           = SecurityRuleDirection.Inbound,
                        Priority            = 500,
                        Protocol            = SecurityRuleProtocol.Tcp,
                        SourceAddressPrefix = "*",
                        SourcePortRange     = "655"
                    }
                }
            };

            // Put Nsg
            NetworkSecurityGroupsCreateOrUpdateOperation putNsgResponseOperation = await NetworkManagementClient.NetworkSecurityGroups.StartCreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, networkSecurityGroup);

            Response <NetworkSecurityGroup> putNsgResponse = await WaitForCompletionAsync(putNsgResponseOperation);

            Assert.AreEqual("Succeeded", putNsgResponse.Value.ProvisioningState.ToString());

            // Get NSG
            Response <NetworkSecurityGroup> getNsgResponse = await NetworkManagementClient.NetworkSecurityGroups.GetAsync(resourceGroupName, networkSecurityGroupName);

            Assert.AreEqual(networkSecurityGroupName, getNsgResponse.Value.Name);
            Assert.AreEqual(6, getNsgResponse.Value.DefaultSecurityRules.Count);
            Assert.AreEqual("AllowVnetInBound", getNsgResponse.Value.DefaultSecurityRules[0].Name);
            Assert.AreEqual("AllowAzureLoadBalancerInBound", getNsgResponse.Value.DefaultSecurityRules[1].Name);
            Assert.AreEqual("DenyAllInBound", getNsgResponse.Value.DefaultSecurityRules[2].Name);
            Assert.AreEqual("AllowVnetOutBound", getNsgResponse.Value.DefaultSecurityRules[3].Name);
            Assert.AreEqual("AllowInternetOutBound", getNsgResponse.Value.DefaultSecurityRules[4].Name);
            Assert.AreEqual("DenyAllOutBound", getNsgResponse.Value.DefaultSecurityRules[5].Name);

            // Verify the security rule
            Assert.AreEqual(SecurityRuleAccess.Allow, getNsgResponse.Value.SecurityRules[0].Access);
            Assert.AreEqual("Test security rule", getNsgResponse.Value.SecurityRules[0].Description);
            Assert.AreEqual("*", getNsgResponse.Value.SecurityRules[0].DestinationAddressPrefix);
            Assert.AreEqual(destinationPortRange, getNsgResponse.Value.SecurityRules[0].DestinationPortRange);
            Assert.AreEqual(SecurityRuleDirection.Inbound, getNsgResponse.Value.SecurityRules[0].Direction);
            Assert.AreEqual(500, getNsgResponse.Value.SecurityRules[0].Priority);
            Assert.AreEqual(SecurityRuleProtocol.Tcp, getNsgResponse.Value.SecurityRules[0].Protocol);
            Assert.AreEqual("Succeeded", getNsgResponse.Value.SecurityRules[0].ProvisioningState.ToString());
            Assert.AreEqual("*", getNsgResponse.Value.SecurityRules[0].SourceAddressPrefix);
            Assert.AreEqual("655", getNsgResponse.Value.SecurityRules[0].SourcePortRange);

            // List NSG
            AsyncPageable <NetworkSecurityGroup> listNsgResponseAP = NetworkManagementClient.NetworkSecurityGroups.ListAsync(resourceGroupName);
            List <NetworkSecurityGroup>          listNsgResponse   = await listNsgResponseAP.ToEnumerableAsync();

            Has.One.EqualTo(listNsgResponse);
            Assert.AreEqual(networkSecurityGroupName, listNsgResponse.First().Name);
            Assert.AreEqual(6, listNsgResponse.First().DefaultSecurityRules.Count);
            Assert.AreEqual("AllowVnetInBound", listNsgResponse.First().DefaultSecurityRules[0].Name);
            Assert.AreEqual("AllowAzureLoadBalancerInBound", listNsgResponse.First().DefaultSecurityRules[1].Name);
            Assert.AreEqual("DenyAllInBound", listNsgResponse.First().DefaultSecurityRules[2].Name);
            Assert.AreEqual("AllowVnetOutBound", listNsgResponse.First().DefaultSecurityRules[3].Name);
            Assert.AreEqual("AllowInternetOutBound", listNsgResponse.First().DefaultSecurityRules[4].Name);
            Assert.AreEqual("DenyAllOutBound", listNsgResponse.First().DefaultSecurityRules[5].Name);
            Assert.AreEqual(getNsgResponse.Value.Etag, listNsgResponse.First().Etag);

            // List NSG in a subscription
            AsyncPageable <NetworkSecurityGroup> listNsgSubsciptionResponseAP = NetworkManagementClient.NetworkSecurityGroups.ListAllAsync();
            List <NetworkSecurityGroup>          listNsgSubsciptionResponse   = await listNsgSubsciptionResponseAP.ToEnumerableAsync();

            Assert.IsNotEmpty(listNsgSubsciptionResponse);

            // Add a new security rule
            var SecurityRule = new SecurityRule()
            {
                Name        = securityRule2,
                Access      = SecurityRuleAccess.Deny,
                Description = "Test outbound security rule",
                DestinationAddressPrefix = "*",
                DestinationPortRange     = destinationPortRange,
                Direction           = SecurityRuleDirection.Outbound,
                Priority            = 501,
                Protocol            = SecurityRuleProtocol.Udp,
                SourceAddressPrefix = "*",
                SourcePortRange     = "656",
            };

            networkSecurityGroup.SecurityRules.Add(SecurityRule);

            putNsgResponseOperation = await NetworkManagementClient.NetworkSecurityGroups.StartCreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, networkSecurityGroup);
            await WaitForCompletionAsync(putNsgResponseOperation);

            // Get NSG
            getNsgResponse = await NetworkManagementClient.NetworkSecurityGroups.GetAsync(resourceGroupName, networkSecurityGroupName);

            // Verify the security rule
            Assert.AreEqual(SecurityRuleAccess.Deny, getNsgResponse.Value.SecurityRules[1].Access);
            Assert.AreEqual("Test outbound security rule", getNsgResponse.Value.SecurityRules[1].Description);
            Assert.AreEqual("*", getNsgResponse.Value.SecurityRules[1].DestinationAddressPrefix);
            Assert.AreEqual(destinationPortRange, getNsgResponse.Value.SecurityRules[1].DestinationPortRange);
            Assert.AreEqual(SecurityRuleDirection.Outbound, getNsgResponse.Value.SecurityRules[1].Direction);
            Assert.AreEqual(501, getNsgResponse.Value.SecurityRules[1].Priority);
            Assert.AreEqual(SecurityRuleProtocol.Udp, getNsgResponse.Value.SecurityRules[1].Protocol);
            Assert.AreEqual("Succeeded", getNsgResponse.Value.SecurityRules[1].ProvisioningState.ToString());
            Assert.AreEqual("*", getNsgResponse.Value.SecurityRules[1].SourceAddressPrefix);
            Assert.AreEqual("656", getNsgResponse.Value.SecurityRules[1].SourcePortRange);

            // List Default Security Groups
            AsyncPageable <SecurityRule> listDefaultSecurityGroupsAP = NetworkManagementClient.DefaultSecurityRules.ListAsync(resourceGroupName, networkSecurityGroupName);
            List <SecurityRule>          listDefaultSecurityGroups   = await listDefaultSecurityGroupsAP.ToEnumerableAsync();

            Assert.IsNotEmpty(listDefaultSecurityGroups);

            // Get Defaul Security Group
            Response <SecurityRule> getDefaultSecurityGroups = await NetworkManagementClient.DefaultSecurityRules.GetAsync(resourceGroupName, networkSecurityGroupName, listDefaultSecurityGroups.First().Name);

            Assert.AreEqual(listDefaultSecurityGroups.First().Name, getDefaultSecurityGroups.Value.Name);

            // Delete NSG
            await NetworkManagementClient.NetworkSecurityGroups.StartDeleteAsync(resourceGroupName, networkSecurityGroupName);

            // List NSG
            listNsgResponseAP = NetworkManagementClient.NetworkSecurityGroups.ListAsync(resourceGroupName);
            listNsgResponse   = await listNsgResponseAP.ToEnumerableAsync();

            Assert.IsEmpty(listNsgResponse);
        }
예제 #22
0
        public void VerifyIpFlowApiTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler3 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient         = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1);
                var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);
                var computeManagementClient = NetworkManagementTestUtilities.GetComputeManagementClientWithHandler(context, handler3);

                string location = "eastus";

                string resourceGroupName = TestUtilities.GenerateName();
                resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
                                                              new ResourceGroup
                {
                    Location = location
                });

                string virtualMachineName1      = TestUtilities.GenerateName();
                string networkInterfaceName1    = TestUtilities.GenerateName();
                string networkSecurityGroupName = virtualMachineName1 + "-nsg";

                //Deploy VM with a template
                Deployments.CreateVm(
                    resourcesClient: resourcesClient,
                    resourceGroupName: resourceGroupName,
                    location: location,
                    virtualMachineName: virtualMachineName1,
                    storageAccountName: TestUtilities.GenerateName(),
                    networkInterfaceName: networkInterfaceName1,
                    networkSecurityGroupName: networkSecurityGroupName,
                    diagnosticsStorageAccountName: TestUtilities.GenerateName(),
                    deploymentName: TestUtilities.GenerateName()
                    );

                string         networkWatcherName = TestUtilities.GenerateName();
                NetworkWatcher properties         = new NetworkWatcher();
                properties.Location = location;

                //Create network Watcher
                var createNetworkWatcher = networkManagementClient.NetworkWatchers.CreateOrUpdate(resourceGroupName, networkWatcherName, properties);

                var    getVm1         = computeManagementClient.VirtualMachines.Get(resourceGroupName, virtualMachineName1);
                string localIPAddress = networkManagementClient.NetworkInterfaces.Get(resourceGroupName, networkInterfaceName1).IpConfigurations.FirstOrDefault().PrivateIPAddress;


                string securityRule1 = TestUtilities.GenerateName();

                // Add a security rule
                var SecurityRule = new SecurityRule()
                {
                    Name        = securityRule1,
                    Access      = SecurityRuleAccess.Deny,
                    Description = "Test outbound security rule",
                    DestinationAddressPrefix = "*",
                    DestinationPortRange     = "80",
                    Direction           = SecurityRuleDirection.Outbound,
                    Priority            = 501,
                    Protocol            = SecurityRuleProtocol.Tcp,
                    SourceAddressPrefix = "*",
                    SourcePortRange     = "*",
                };

                var nsg = networkManagementClient.NetworkSecurityGroups.Get(resourceGroupName, networkSecurityGroupName);
                nsg.SecurityRules.Add(SecurityRule);
                networkManagementClient.NetworkSecurityGroups.CreateOrUpdate(resourceGroupName, networkSecurityGroupName, nsg);

                VerificationIPFlowParameters ipFlowProperties = new VerificationIPFlowParameters()
                {
                    TargetResourceId = getVm1.Id,
                    Direction        = "Outbound",
                    Protocol         = "TCP",
                    LocalPort        = "80",
                    RemotePort       = "80",
                    LocalIPAddress   = localIPAddress,
                    RemoteIPAddress  = "12.11.12.14"
                };

                //Verify IP flow from a VM to a location given the configured  rule
                var verifyIpFlow = networkManagementClient.NetworkWatchers.VerifyIPFlow(resourceGroupName, networkWatcherName, ipFlowProperties);

                //Verify validity of the result
                Assert.Equal("Deny", verifyIpFlow.Access);
                Assert.Equal("securityRules/" + securityRule1, verifyIpFlow.RuleName);
            }
        }
 public static string Name(this SecurityRule rule)
 {
     return(EnumerationExtensions.GetDescription(rule));
 }
        public async Task ViewNsgRuleApiTest()
        {
            string resourceGroupName = Recording.GenerateAssetName("azsmnet");

            string location = "westus2";
            await ResourceGroupsOperations.CreateOrUpdateAsync(resourceGroupName, new ResourceGroup(location));

            string virtualMachineName       = Recording.GenerateAssetName("azsmnet");
            string networkInterfaceName     = Recording.GenerateAssetName("azsmnet");
            string networkSecurityGroupName = virtualMachineName + "-nsg";

            //Deploy VM with template
            await CreateVm(
                resourcesClient : ResourceManagementClient,
                resourceGroupName : resourceGroupName,
                location : location,
                virtualMachineName : virtualMachineName,
                storageAccountName : Recording.GenerateAssetName("azsmnet"),
                networkInterfaceName : networkInterfaceName,
                networkSecurityGroupName : networkSecurityGroupName,
                diagnosticsStorageAccountName : Recording.GenerateAssetName("azsmnet"),
                deploymentName : Recording.GenerateAssetName("azsmnet"),
                adminPassword : Recording.GenerateAlphaNumericId("AzureSDKNetworkTest#")
                );

            //TODO:There is no need to perform a separate create NetworkWatchers operation
            //Create network Watcher
            //string networkWatcherName = Recording.GenerateAssetName("azsmnet");
            //NetworkWatcher properties = new NetworkWatcher { Location = location };
            //Response<NetworkWatcher> createNetworkWatcher = await NetworkManagementClient.NetworkWatchers.CreateOrUpdateAsync(resourceGroupName, networkWatcherName, properties);

            Response <VirtualMachine> getVm = await ComputeManagementClient.VirtualMachines.GetAsync(resourceGroupName, virtualMachineName);

            string localIPAddress = NetworkManagementClient.NetworkInterfaces.GetAsync(resourceGroupName, networkInterfaceName).Result.Value.IpConfigurations.FirstOrDefault().PrivateIPAddress;

            string securityRule1 = Recording.GenerateAssetName("azsmnet");

            // Add a security rule
            SecurityRule SecurityRule = new SecurityRule()
            {
                Name        = securityRule1,
                Access      = SecurityRuleAccess.Deny,
                Description = "Test outbound security rule",
                DestinationAddressPrefix = "*",
                DestinationPortRange     = "80",
                Direction           = SecurityRuleDirection.Outbound,
                Priority            = 501,
                Protocol            = SecurityRuleProtocol.Tcp,
                SourceAddressPrefix = "*",
                SourcePortRange     = "*",
            };

            Response <NetworkSecurityGroup> nsg = await NetworkManagementClient.NetworkSecurityGroups.GetAsync(resourceGroupName, networkSecurityGroupName);

            nsg.Value.SecurityRules.Add(SecurityRule);
            NetworkSecurityGroupsCreateOrUpdateOperation createOrUpdateOperation = await NetworkManagementClient.NetworkSecurityGroups.StartCreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, nsg);

            Response <NetworkSecurityGroup> networkSecurityGroup = await WaitForCompletionAsync(createOrUpdateOperation);

            //Get view security group rules
            SecurityGroupViewParameters sgvProperties = new SecurityGroupViewParameters(getVm.Value.Id);
            NetworkWatchersGetVMSecurityRulesOperation viewNSGRulesOperation = await NetworkManagementClient.NetworkWatchers.StartGetVMSecurityRulesAsync("NetworkWatcherRG", "NetworkWatcher_westus2", sgvProperties);

            Response <SecurityGroupViewResult> viewNSGRules = await WaitForCompletionAsync(viewNSGRulesOperation);

            //Verify effective security rule defined earlier
            IEnumerable <EffectiveNetworkSecurityRule> getEffectiveSecurityRule = viewNSGRules.Value.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.EffectiveSecurityRules.Where(x => x.Name == "UserRule_" + securityRule1);

            Assert.AreEqual("Tcp", getEffectiveSecurityRule.FirstOrDefault().Protocol);
            Assert.AreEqual(501, getEffectiveSecurityRule.FirstOrDefault().Priority);
            Assert.AreEqual("Deny", getEffectiveSecurityRule.FirstOrDefault().Access);
            Assert.AreEqual("Outbound", getEffectiveSecurityRule.FirstOrDefault().Direction);
            Assert.AreEqual("0.0.0.0/0", getEffectiveSecurityRule.FirstOrDefault().DestinationAddressPrefix);
            Assert.AreEqual("80-80", getEffectiveSecurityRule.FirstOrDefault().DestinationPortRange);
            Assert.AreEqual("0.0.0.0/0", getEffectiveSecurityRule.FirstOrDefault().SourceAddressPrefix);
            Assert.AreEqual("0-65535", getEffectiveSecurityRule.FirstOrDefault().SourcePortRange);

            //Verify 6 default rules
            IEnumerable <SecurityRule> getDefaultSecurityRule1 = viewNSGRules.Value.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "AllowVnetInBound");

            Assert.AreEqual("*", getDefaultSecurityRule1.FirstOrDefault().Protocol);
            Assert.AreEqual(65000, getDefaultSecurityRule1.FirstOrDefault().Priority);
            Assert.AreEqual("Allow", getDefaultSecurityRule1.FirstOrDefault().Access);
            Assert.AreEqual("Inbound", getDefaultSecurityRule1.FirstOrDefault().Direction);
            Assert.AreEqual("VirtualNetwork", getDefaultSecurityRule1.FirstOrDefault().DestinationAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule1.FirstOrDefault().DestinationPortRange);
            Assert.AreEqual("VirtualNetwork", getDefaultSecurityRule1.FirstOrDefault().SourceAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule1.FirstOrDefault().SourcePortRange);

            IEnumerable <SecurityRule> getDefaultSecurityRule2 = viewNSGRules.Value.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "AllowAzureLoadBalancerInBound");

            Assert.AreEqual("*", getDefaultSecurityRule2.FirstOrDefault().Protocol);
            Assert.AreEqual(65001, getDefaultSecurityRule2.FirstOrDefault().Priority);
            Assert.AreEqual("Allow", getDefaultSecurityRule2.FirstOrDefault().Access);
            Assert.AreEqual("Inbound", getDefaultSecurityRule2.FirstOrDefault().Direction);
            Assert.AreEqual("*", getDefaultSecurityRule2.FirstOrDefault().DestinationAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule2.FirstOrDefault().DestinationPortRange);
            Assert.AreEqual("AzureLoadBalancer", getDefaultSecurityRule2.FirstOrDefault().SourceAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule2.FirstOrDefault().SourcePortRange);

            IEnumerable <SecurityRule> getDefaultSecurityRule3 = viewNSGRules.Value.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "DenyAllInBound");

            Assert.AreEqual("*", getDefaultSecurityRule3.FirstOrDefault().Protocol);
            Assert.AreEqual(65500, getDefaultSecurityRule3.FirstOrDefault().Priority);
            Assert.AreEqual("Deny", getDefaultSecurityRule3.FirstOrDefault().Access);
            Assert.AreEqual("Inbound", getDefaultSecurityRule3.FirstOrDefault().Direction);
            Assert.AreEqual("*", getDefaultSecurityRule3.FirstOrDefault().DestinationAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule3.FirstOrDefault().DestinationPortRange);
            Assert.AreEqual("*", getDefaultSecurityRule3.FirstOrDefault().SourceAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule3.FirstOrDefault().SourcePortRange);

            IEnumerable <SecurityRule> getDefaultSecurityRule4 = viewNSGRules.Value.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "AllowVnetOutBound");

            Assert.AreEqual("*", getDefaultSecurityRule4.FirstOrDefault().Protocol);
            Assert.AreEqual(65000, getDefaultSecurityRule4.FirstOrDefault().Priority);
            Assert.AreEqual("Allow", getDefaultSecurityRule4.FirstOrDefault().Access);
            Assert.AreEqual("Outbound", getDefaultSecurityRule4.FirstOrDefault().Direction);
            Assert.AreEqual("VirtualNetwork", getDefaultSecurityRule4.FirstOrDefault().DestinationAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule4.FirstOrDefault().DestinationPortRange);
            Assert.AreEqual("VirtualNetwork", getDefaultSecurityRule4.FirstOrDefault().SourceAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule4.FirstOrDefault().SourcePortRange);

            IEnumerable <SecurityRule> getDefaultSecurityRule5 = viewNSGRules.Value.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "AllowInternetOutBound");

            Assert.AreEqual("*", getDefaultSecurityRule5.FirstOrDefault().Protocol);
            Assert.AreEqual(65001, getDefaultSecurityRule5.FirstOrDefault().Priority);
            Assert.AreEqual("Allow", getDefaultSecurityRule5.FirstOrDefault().Access);
            Assert.AreEqual("Outbound", getDefaultSecurityRule5.FirstOrDefault().Direction);
            Assert.AreEqual("Internet", getDefaultSecurityRule5.FirstOrDefault().DestinationAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule5.FirstOrDefault().DestinationPortRange);
            Assert.AreEqual("*", getDefaultSecurityRule5.FirstOrDefault().SourceAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule5.FirstOrDefault().SourcePortRange);

            IEnumerable <SecurityRule> getDefaultSecurityRule6 = viewNSGRules.Value.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "DenyAllOutBound");

            Assert.AreEqual("*", getDefaultSecurityRule6.FirstOrDefault().Protocol);
            Assert.AreEqual(65500, getDefaultSecurityRule6.FirstOrDefault().Priority);
            Assert.AreEqual("Deny", getDefaultSecurityRule6.FirstOrDefault().Access);
            Assert.AreEqual("Outbound", getDefaultSecurityRule6.FirstOrDefault().Direction);
            Assert.AreEqual("*", getDefaultSecurityRule6.FirstOrDefault().DestinationAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule6.FirstOrDefault().DestinationPortRange);
            Assert.AreEqual("*", getDefaultSecurityRule6.FirstOrDefault().SourceAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule6.FirstOrDefault().SourcePortRange);
        }
        public async Task VerifyIpFlowApiTest()
        {
            string resourceGroupName = Recording.GenerateAssetName("azsmnet");

            string location = "westus2";
            await ResourceGroupsOperations.CreateOrUpdateAsync(resourceGroupName, new ResourceGroup(location));

            string virtualMachineName1      = Recording.GenerateAssetName("azsmnet");
            string networkInterfaceName1    = Recording.GenerateAssetName("azsmnet");
            string networkSecurityGroupName = virtualMachineName1 + "-nsg";

            //Deploy VM with a template
            await CreateVm(
                resourcesClient : ResourceManagementClient,
                resourceGroupName : resourceGroupName,
                location : location,
                virtualMachineName : virtualMachineName1,
                storageAccountName : Recording.GenerateAssetName("azsmnet"),
                networkInterfaceName : networkInterfaceName1,
                networkSecurityGroupName : networkSecurityGroupName,
                diagnosticsStorageAccountName : Recording.GenerateAssetName("azsmnet"),
                deploymentName : Recording.GenerateAssetName("azsmnet"),
                adminPassword : Recording.GenerateAlphaNumericId("AzureSDKNetworkTest#")
                );

            //TODO:There is no need to perform a separate create NetworkWatchers operation
            //Create network Watcher
            //string networkWatcherName = Recording.GenerateAssetName("azsmnet");
            //NetworkWatcher properties = new NetworkWatcher { Location = location };
            //await NetworkManagementClient.NetworkWatchers.CreateOrUpdateAsync(resourceGroupName, networkWatcherName, properties);

            Response <VirtualMachine> getVm1 = await ComputeManagementClient.VirtualMachines.GetAsync(resourceGroupName, virtualMachineName1);

            string localIPAddress = NetworkManagementClient.NetworkInterfaces.GetAsync(resourceGroupName, networkInterfaceName1).Result.Value.IpConfigurations.FirstOrDefault().PrivateIPAddress;

            string securityRule1 = Recording.GenerateAssetName("azsmnet");

            // Add a security rule
            SecurityRule SecurityRule = new SecurityRule()
            {
                Name        = securityRule1,
                Access      = SecurityRuleAccess.Deny,
                Description = "Test outbound security rule",
                DestinationAddressPrefix = "*",
                DestinationPortRange     = "80",
                Direction           = SecurityRuleDirection.Outbound,
                Priority            = 501,
                Protocol            = SecurityRuleProtocol.Tcp,
                SourceAddressPrefix = "*",
                SourcePortRange     = "*",
            };

            Response <NetworkSecurityGroup> nsg = await NetworkManagementClient.NetworkSecurityGroups.GetAsync(resourceGroupName, networkSecurityGroupName);

            nsg.Value.SecurityRules.Add(SecurityRule);
            NetworkSecurityGroupsCreateOrUpdateOperation createOrUpdateOperation = await NetworkManagementClient.NetworkSecurityGroups.StartCreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, nsg);

            await WaitForCompletionAsync(createOrUpdateOperation);

            VerificationIPFlowParameters ipFlowProperties = new VerificationIPFlowParameters(getVm1.Value.Id, "Outbound", "TCP", "80", "80", localIPAddress, "12.11.12.14");

            //Verify IP flow from a VM to a location given the configured  rule
            NetworkWatchersVerifyIPFlowOperation verifyIpFlowOperation = await NetworkManagementClient.NetworkWatchers.StartVerifyIPFlowAsync("NetworkWatcherRG", "NetworkWatcher_westus2", ipFlowProperties);

            Response <VerificationIPFlowResult> verifyIpFlow = await WaitForCompletionAsync(verifyIpFlowOperation);

            //Verify validity of the result
            Assert.AreEqual("Deny", verifyIpFlow.Value.Access.ToString());
            Assert.AreEqual("securityRules/" + securityRule1, verifyIpFlow.Value.RuleName);
        }
예제 #26
0
 public async Task DeleteRule(Guid entityId, RuleSubject subject, SecurityRule rule)
 {
     await Delete(Filter(entityId, subject, rule));
 }
        public void NetworkSecurityGroupWithRulesApiTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient         = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1);
                var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);

                var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/networkSecurityGroups");

                string resourceGroupName = TestUtilities.GenerateName("csmrg");
                resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
                                                              new ResourceGroup
                {
                    Location = location
                });

                string networkSecurityGroupName = TestUtilities.GenerateName();
                string securityRule1            = TestUtilities.GenerateName();
                string securityRule2            = TestUtilities.GenerateName();

                string destinationPortRange = "123-3500";

                var networkSecurityGroup = new NetworkSecurityGroup()
                {
                    Location      = location,
                    SecurityRules = new List <SecurityRule>()
                    {
                        new SecurityRule()
                        {
                            Name        = securityRule1,
                            Access      = SecurityRuleAccess.Allow,
                            Description = "Test security rule",
                            DestinationAddressPrefix = "*",
                            DestinationPortRange     = destinationPortRange,
                            Direction           = SecurityRuleDirection.Inbound,
                            Priority            = 500,
                            Protocol            = SecurityRuleProtocol.Tcp,
                            SourceAddressPrefix = "*",
                            SourcePortRange     = "655"
                        }
                    }
                };

                // Put Nsg
                var putNsgResponse = networkManagementClient.NetworkSecurityGroups.CreateOrUpdate(resourceGroupName, networkSecurityGroupName, networkSecurityGroup);
                Assert.Equal("Succeeded", putNsgResponse.ProvisioningState);

                // Get NSG
                var getNsgResponse = networkManagementClient.NetworkSecurityGroups.Get(resourceGroupName, networkSecurityGroupName);
                Assert.Equal(networkSecurityGroupName, getNsgResponse.Name);
                Assert.Equal(6, getNsgResponse.DefaultSecurityRules.Count);
                Assert.Equal("AllowVnetInBound", getNsgResponse.DefaultSecurityRules[0].Name);
                Assert.Equal("AllowAzureLoadBalancerInBound", getNsgResponse.DefaultSecurityRules[1].Name);
                Assert.Equal("DenyAllInBound", getNsgResponse.DefaultSecurityRules[2].Name);
                Assert.Equal("AllowVnetOutBound", getNsgResponse.DefaultSecurityRules[3].Name);
                Assert.Equal("AllowInternetOutBound", getNsgResponse.DefaultSecurityRules[4].Name);
                Assert.Equal("DenyAllOutBound", getNsgResponse.DefaultSecurityRules[5].Name);

                // Verify the security rule
                Assert.Equal(SecurityRuleAccess.Allow, getNsgResponse.SecurityRules[0].Access);
                Assert.Equal("Test security rule", getNsgResponse.SecurityRules[0].Description);
                Assert.Equal("*", getNsgResponse.SecurityRules[0].DestinationAddressPrefix);
                Assert.Equal(destinationPortRange, getNsgResponse.SecurityRules[0].DestinationPortRange);
                Assert.Equal(SecurityRuleDirection.Inbound, getNsgResponse.SecurityRules[0].Direction);
                Assert.Equal(500, getNsgResponse.SecurityRules[0].Priority);
                Assert.Equal(SecurityRuleProtocol.Tcp, getNsgResponse.SecurityRules[0].Protocol);
                Assert.Equal("Succeeded", getNsgResponse.SecurityRules[0].ProvisioningState);
                Assert.Equal("*", getNsgResponse.SecurityRules[0].SourceAddressPrefix);
                Assert.Equal("655", getNsgResponse.SecurityRules[0].SourcePortRange);

                // List NSG
                var listNsgResponse = networkManagementClient.NetworkSecurityGroups.List(resourceGroupName);
                Assert.Single(listNsgResponse);
                Assert.Equal(networkSecurityGroupName, listNsgResponse.First().Name);
                Assert.Equal(6, listNsgResponse.First().DefaultSecurityRules.Count);
                Assert.Equal("AllowVnetInBound", listNsgResponse.First().DefaultSecurityRules[0].Name);
                Assert.Equal("AllowAzureLoadBalancerInBound", listNsgResponse.First().DefaultSecurityRules[1].Name);
                Assert.Equal("DenyAllInBound", listNsgResponse.First().DefaultSecurityRules[2].Name);
                Assert.Equal("AllowVnetOutBound", listNsgResponse.First().DefaultSecurityRules[3].Name);
                Assert.Equal("AllowInternetOutBound", listNsgResponse.First().DefaultSecurityRules[4].Name);
                Assert.Equal("DenyAllOutBound", listNsgResponse.First().DefaultSecurityRules[5].Name);
                Assert.Equal(getNsgResponse.Etag, listNsgResponse.First().Etag);

                // List NSG in a subscription
                var listNsgSubsciptionResponse = networkManagementClient.NetworkSecurityGroups.ListAll();
                Assert.NotEmpty(listNsgSubsciptionResponse);

                // Add a new security rule
                var SecurityRule = new SecurityRule()
                {
                    Name        = securityRule2,
                    Access      = SecurityRuleAccess.Deny,
                    Description = "Test outbound security rule",
                    DestinationAddressPrefix = "*",
                    DestinationPortRange     = destinationPortRange,
                    Direction           = SecurityRuleDirection.Outbound,
                    Priority            = 501,
                    Protocol            = SecurityRuleProtocol.Udp,
                    SourceAddressPrefix = "*",
                    SourcePortRange     = "656",
                };

                networkSecurityGroup.SecurityRules.Add(SecurityRule);

                putNsgResponse = networkManagementClient.NetworkSecurityGroups.CreateOrUpdate(resourceGroupName, networkSecurityGroupName, networkSecurityGroup);

                // Get NSG
                getNsgResponse = networkManagementClient.NetworkSecurityGroups.Get(resourceGroupName, networkSecurityGroupName);

                // Verify the security rule
                Assert.Equal(SecurityRuleAccess.Deny, getNsgResponse.SecurityRules[1].Access);
                Assert.Equal("Test outbound security rule", getNsgResponse.SecurityRules[1].Description);
                Assert.Equal("*", getNsgResponse.SecurityRules[1].DestinationAddressPrefix);
                Assert.Equal(destinationPortRange, getNsgResponse.SecurityRules[1].DestinationPortRange);
                Assert.Equal(SecurityRuleDirection.Outbound, getNsgResponse.SecurityRules[1].Direction);
                Assert.Equal(501, getNsgResponse.SecurityRules[1].Priority);
                Assert.Equal(SecurityRuleProtocol.Udp, getNsgResponse.SecurityRules[1].Protocol);
                Assert.Equal("Succeeded", getNsgResponse.SecurityRules[1].ProvisioningState);
                Assert.Equal("*", getNsgResponse.SecurityRules[1].SourceAddressPrefix);
                Assert.Equal("656", getNsgResponse.SecurityRules[1].SourcePortRange);

                // List Default Security Groups
                var listDefaultSecurityGroups = networkManagementClient.DefaultSecurityRules.List(resourceGroupName, networkSecurityGroupName);
                Assert.NotEmpty(listDefaultSecurityGroups);

                // Get Defaul Security Group
                var getDefaultSecurityGroups = networkManagementClient.DefaultSecurityRules.Get(resourceGroupName, networkSecurityGroupName, listDefaultSecurityGroups.First().Name);
                Assert.Equal(listDefaultSecurityGroups.First().Name, getDefaultSecurityGroups.Name);

                // Delete NSG
                networkManagementClient.NetworkSecurityGroups.Delete(resourceGroupName, networkSecurityGroupName);

                // List NSG
                listNsgResponse = networkManagementClient.NetworkSecurityGroups.List(resourceGroupName);
                Assert.Empty(listNsgResponse);
            }
        }
예제 #28
0
        public void SecurityRuleWithRulesApiTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var resourcesClient         = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1);
                var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);

                var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/networkSecurityGroups");

                string resourceGroupName = TestUtilities.GenerateName("csmrg");
                resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
                                                              new ResourceGroup
                {
                    Location = location
                });

                string networkSecurityGroupName = TestUtilities.GenerateName();
                string securityRule1            = TestUtilities.GenerateName();
                string securityRule2            = TestUtilities.GenerateName();

                string destinationPortRange = "123-3500";

                var networkSecurityGroup = new NetworkSecurityGroup()
                {
                    Location      = location,
                    SecurityRules = new List <SecurityRule>()
                    {
                        new SecurityRule()
                        {
                            Name        = securityRule1,
                            Access      = SecurityRuleAccess.Allow,
                            Description = "Test security rule",
                            DestinationAddressPrefix = "*",
                            DestinationPortRange     = destinationPortRange,
                            Direction           = SecurityRuleDirection.Inbound,
                            Priority            = 500,
                            Protocol            = SecurityRuleProtocol.Tcp,
                            SourceAddressPrefix = "*",
                            SourcePortRange     = "655"
                        }
                    }
                };

                // Put Nsg
                var putNsgResponse = networkManagementClient.NetworkSecurityGroups.CreateOrUpdate(resourceGroupName, networkSecurityGroupName, networkSecurityGroup);
                Assert.Equal("Succeeded", putNsgResponse.ProvisioningState);

                // Get NSG
                var getNsgResponse = networkManagementClient.NetworkSecurityGroups.Get(resourceGroupName, networkSecurityGroupName);
                Assert.Equal(networkSecurityGroupName, getNsgResponse.Name);

                // Get SecurityRule
                var getSecurityRuleResponse = networkManagementClient.SecurityRules.Get(resourceGroupName, networkSecurityGroupName, securityRule1);
                Assert.Equal(securityRule1, getSecurityRuleResponse.Name);

                this.CompareSecurityRule(getNsgResponse.SecurityRules[0], getSecurityRuleResponse);

                // Add a new security rule
                var SecurityRule = new SecurityRule()
                {
                    Name        = securityRule2,
                    Access      = SecurityRuleAccess.Deny,
                    Description = "Test outbound security rule",
                    DestinationAddressPrefix = "*",
                    DestinationPortRange     = destinationPortRange,
                    Direction           = SecurityRuleDirection.Outbound,
                    Priority            = 501,
                    Protocol            = SecurityRuleProtocol.Udp,
                    SourceAddressPrefix = "*",
                    SourcePortRange     = "656",
                };

                var putSecurityRuleResponse = networkManagementClient.SecurityRules.CreateOrUpdate(resourceGroupName, networkSecurityGroupName, securityRule2, SecurityRule);
                Assert.Equal("Succeeded", putSecurityRuleResponse.ProvisioningState);

                // Get NSG
                getNsgResponse = networkManagementClient.NetworkSecurityGroups.Get(resourceGroupName, networkSecurityGroupName);

                // Get the SecurityRule2
                var getSecurityRule2Response = networkManagementClient.SecurityRules.Get(resourceGroupName, networkSecurityGroupName, securityRule2);
                Assert.Equal(securityRule2, getSecurityRule2Response.Name);

                // Verify the security rule
                Assert.Equal(SecurityRuleAccess.Deny, getSecurityRule2Response.Access);
                Assert.Equal("Test outbound security rule", getSecurityRule2Response.Description);
                Assert.Equal("*", getSecurityRule2Response.DestinationAddressPrefix);
                Assert.Equal(destinationPortRange, getSecurityRule2Response.DestinationPortRange);
                Assert.Equal(SecurityRuleDirection.Outbound, getSecurityRule2Response.Direction);
                Assert.Equal(501, getSecurityRule2Response.Priority);
                Assert.Equal(SecurityRuleProtocol.Udp, getSecurityRule2Response.Protocol);
                Assert.Equal("Succeeded", getSecurityRule2Response.ProvisioningState);
                Assert.Equal("*", getSecurityRule2Response.SourceAddressPrefix);
                Assert.Equal("656", getSecurityRule2Response.SourcePortRange);

                this.CompareSecurityRule(getNsgResponse.SecurityRules[1], getSecurityRule2Response);

                // List all SecurityRules
                var getsecurityRules = networkManagementClient.SecurityRules.List(resourceGroupName, networkSecurityGroupName);

                Assert.Equal(2, getsecurityRules.Count());
                this.CompareSecurityRule(getNsgResponse.SecurityRules[0], getsecurityRules.ElementAt(0));
                this.CompareSecurityRule(getNsgResponse.SecurityRules[1], getsecurityRules.ElementAt(1));

                // Delete a SecurityRule
                networkManagementClient.SecurityRules.Delete(resourceGroupName, networkSecurityGroupName, securityRule2);

                getsecurityRules = networkManagementClient.SecurityRules.List(resourceGroupName, networkSecurityGroupName);

                Assert.Single(getsecurityRules);

                // Delete NSG
                networkManagementClient.NetworkSecurityGroups.Delete(resourceGroupName, networkSecurityGroupName);

                // List NSG
                var listNsgResponse = networkManagementClient.NetworkSecurityGroups.List(resourceGroupName);
                Assert.Empty(listNsgResponse);
            }
        }
        public virtual SecurityRulesCreateOrUpdateOperation StartCreateOrUpdate(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (networkSecurityGroupName == null)
            {
                throw new ArgumentNullException(nameof(networkSecurityGroupName));
            }
            if (securityRuleName == null)
            {
                throw new ArgumentNullException(nameof(securityRuleName));
            }
            if (securityRuleParameters == null)
            {
                throw new ArgumentNullException(nameof(securityRuleParameters));
            }

            using var scope = _clientDiagnostics.CreateScope("SecurityRulesOperations.StartCreateOrUpdate");
            scope.Start();
            try
            {
                var originalResponse = RestClient.CreateOrUpdate(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, cancellationToken);
                return(new SecurityRulesCreateOrUpdateOperation(_clientDiagnostics, _pipeline, RestClient.CreateCreateOrUpdateRequest(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters).Request, originalResponse));
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
 /// <summary>
 /// The Put network security rule operation creates/updates a security
 /// rule in the specified network security group
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Network.ISecurityRuleOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group.
 /// </param>
 /// <param name='networkSecurityGroupName'>
 /// Required. The name of the network security group.
 /// </param>
 /// <param name='securityRuleName'>
 /// Required. The name of the security rule.
 /// </param>
 /// <param name='securityRuleParameters'>
 /// Required. Parameters supplied to the create/update network security
 /// rule operation
 /// </param>
 /// <returns>
 /// Response for PUT SecurityRule Api service call
 /// </returns>
 public static SecurityRulePutResponse BeginCreateOrUpdating(this ISecurityRuleOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters)
 {
     return(Task.Factory.StartNew((object s) =>
     {
         return ((ISecurityRuleOperations)s).BeginCreateOrUpdatingAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters);
     }
                                  , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }