none
How to get list of Endpoint Statistics and Dangerous Endpoints by using of Azure Mgmt SDK fluent RRS feed

  • Question

  • Hi All,

    I am using https://www.nuget.org/packages/Microsoft.Azure.Management.Fluent for getting resources in Azure with programmatically(C# .NET-Core Web app) and tried to get resources information by providing service principals as below...

    string subscriptionId = "xxx";
                string clientId = "xxx";
                string tenantId = "xxx";
                string clientSecret = "xxx";
    
                AzureCredentials cred = new AzureCredentialsFactory()
                    .FromServicePrincipal(
                    clientId,
                    clientSecret,
                    tenantId,
                    AzureEnvironment.AzureGlobalCloud
                    );
    
                var azure = Azure.Configure()
                                 .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                                 .Authenticate(cred)
                                 .WithSubscription(subscriptionId);

    Any sample code(C#.NET-Core Web app) to find out Endpoint Statistics( loop through open ports in NSG and list them in details) and Dangerous Endpoints(loop through open ports in NSG and identify ports like 3389/22).

    Pls, advice on above.

    Thanks

    • Moved by CoolDadTx Thursday, August 6, 2020 1:53 PM Azure related
    Thursday, August 6, 2020 4:35 AM

Answers

  • you should specify the resourceGroup by using the ListByResourcegroup() method:

    var interaces = azure.NetworkInterfaces.ListByResourceGroup("resourcegroup-name");
    foreach(var nic in interfaces)
    {
       //.......
    }
    • Marked as answer by ganirban_ece Saturday, August 8, 2020 5:49 PM
    • Unmarked as answer by ganirban_ece Saturday, August 8, 2020 6:01 PM
    • Marked as answer by ganirban_ece Saturday, August 8, 2020 6:01 PM
    Saturday, August 8, 2020 4:41 PM

All replies

  • Hi,

    I did a little sample on the fly "didnt test it yet" that I think will be a good starting point, I hope so! take a look to this code sample: 

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Linq;
    using Microsoft.Azure.Management.Fluent;
    using Microsoft.Azure.Management.Network;
    using Microsoft.Azure.Management.Network.Fluent;
    
    namespace AzureManagmentExample
    {
        public class NsgService
        {
            Microsoft.Azure.Management.Network.Fluent.NetworkManager networkManager;
            IAzure azure;
            Dictionary<string, object> nsgsProperties;
            public NsgService()
            {
                azure = Azure.Authenticate("{your authentication file}").WithDefaultSubscription();
            }
    
            public string GetNetworkId(string networkName) => azure.Networks.List().FirstOrDefault(n => n.Name == networkName)?.Id;
            
            public Dictionary<string, object> GetSubnetsNSGs(string networkId)
            {
                nsgsProperties = new Dictionary<string, object>();
                var nsgProperties = typeof(INetworkSecurityRule).GetProperties();
                foreach (var subnet in azure.Networks.GetById(networkId).Subnets)
                {
                    var nsg = subnet.Value.GetNetworkSecurityGroup();
                    foreach (var currentRule in nsg.SecurityRules)
                    {
                        var dict = new Dictionary<string, object>();
                        foreach (var property in nsgProperties)
                        {
                            var value = property.GetValue(currentRule.Value);
                            dict.Add(property.Name, value);
                        }
                        nsgsProperties.Add(nsg.Key, dict);
                    }
                }
    
                return nsgsProperties;
            }
        }
    }
    


    the code did nothing it is just demonstrating how you can loop through a virtual network subnets, and get the list of nsgs, and for each one we reflect on the INetworkSecurityGroup properties to get their values and store them on a dictionary, I'm waiting for your feedback!

    Best regards,

    Mouad.


    Thursday, August 6, 2020 9:46 AM
  • This forum is for C#-specific questions only. Please post questions related to using Azure in the Azure forums over on Microsoft Q&A.

    Michael Taylor http://www.michaeltaylorp3.net

    Thursday, August 6, 2020 1:53 PM
  • Thanks @Cherkaoui.Mouadfor response and help.

    I am not getting below code as..

     public string GetNetworkId(string networkName) => azure.Networks.List().FirstOrDefault(n => n.Name == networkName)?.Id;

    How and where the  string networkId is getting in below code..

    public Dictionary<string, object> GetSubnetsNSGs(string networkId)
    {
     //-- code
    }

    I am trying to working with sample code and find out solutions..

    Many Thanks,


    Thursday, August 6, 2020 3:19 PM
  • It is a pleasure, Welcome!

    for example our vnet is "vnet-eus":

    var nsgSvc = new NsgService();
    var vnetId = nsgSvc.GetNetworkId("vnet-eus");
    var subnetsNsgs = nsgSvc.GetSubnetsNSGs(vnetId);
    foreach(var current in subnetsNsgs){
       Console.WriteLine(current.Key);
       foreach(var value in current.Value) // Value here is a dictionary of string keys and object values
       {
           //......
       }
    }

    or we can then add new method like this:

    public Dictionary<string, object> GetSubnetsNSGsByName(string name) {
        var vnetId = GetNetworkId(name);
        return GetSubnetsNSGs(vnetId);
    } 
    and just pass the name as argument:

    var nsgSvc = new NsgService();
    var subnetsNsgs = nsgSvc.GetSubnetsNSGsByName("vnet-eus");

    also pay attention to the credential file path, it is hard codded :

    public NsgService()
    {
          azure = Azure.Authenticate("{your authentication file}").WithDefaultSubscription();
    }

    hope it helps!

    Best regards




    Thursday, August 6, 2020 3:27 PM
  • Thanks @Cherkaoui.Mouad,, for response and help...

    I am trying as below code..but not working ...

    string subscriptionId = "xxx"; string clientId = "xxx"; string tenantId = "xxx"; string clientSecret = "xxx";   Dictionary<string, object> nsgsProperties;

    AzureCredentials cred = new AzureCredentialsFactory() .FromServicePrincipal( clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud ); var azure = Azure.Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(cred) .WithSubscription(subscriptionId);

      foreach (var nic in azure.NetworkInterfaces.List())
                    {
                      var  nsgname = nic.NetworkSecurityGroupId.Substring(nic.NetworkSecurityGroupId.LastIndexOf('/') + 1);
                      string networkId = azure.Networks.List().FirstOrDefault(n => n.Name == nsgname)?.Id;
                        nsgsProperties = new Dictionary<string, object>();
                        var nsgProperties = typeof(INetworkSecurityRule).GetProperties();
                        foreach (var subnet in azure.Networks.GetById(networkId).Subnets)
                        {
                            var nsg = subnet.Value.GetNetworkSecurityGroup();
                            foreach (var currentRule in nsg.SecurityRules)
                            {
                                var dict = new Dictionary<string, object>();
                                foreach (var property in nsgProperties)
                                {
                                    var value = property.GetValue(currentRule.Value);
                                    dict.Add(property.Name, value);
                                }
                                nsgsProperties.Add(nsg.Key, dict);
                            }
                        }
                    }

    Above ,string networkId variable is not getting any value..
    Can any body help me ..

    Thanks,

    Thursday, August 6, 2020 3:56 PM
  • you should use the networkName in the predicate:

    string networkname = "vnet001"; // for example
    string networkId = azure.Networks.List().FirstOrDefault(n => n.Name == networkName)?.Id;
    

    also you can refactor the foreach code block this way:

    foreach (var nic in azure.NetworkInterfaces.List())
    {
        var nsg = azure.NetworkSecurityGroups.GetById(nic.NetworkSecurityGroupId);
        nsgsProperties = new Dictionary<string, object>();
        var nsgProperties = typeof(INetworkSecurityRule).GetProperties();
    
        foreach (var currentRule in nsg.SecurityRules)
        {
            var dict = new Dictionary<string, object>();
            foreach (var property in nsgProperties)
            {
                var value = property.GetValue(currentRule.Value);
                dict.Add(property.Name, value);
            }
            nsgsProperties.Add(nsg.Key, dict);
        }
    }


    Thursday, August 6, 2020 4:10 PM
  • Thanks @Cherkaoui.Mouad,, for response and help...

    I am using below code sample but not working fully.. 

    Dictionary<string, object> nsgsProperties;           
                try
                {
                    var credentials = GetShared.GetCredentials();
                    //Microsoft.Azure.Management.Network.Fluent.NetworkManager _networkManager;
                    var azure = Azure
                                .Configure()
                                .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                                .Authenticate(credentials)
                                .WithSubscription(subscriptionId);

                     foreach (var nsg in azure.Networks.List())

                    {
                        var networkName = nsg.Name;
                        var networkid = nsg.Id;
                     
                        nsgsProperties = new Dictionary<string, object>();
                       
                        foreach (var nic in azure.NetworkInterfaces.List().Where(n => n.Name == networkName))
                        {
                            var nsg1 = azure.NetworkSecurityGroups.GetById(nic.NetworkSecurityGroupId);
                            nsgsProperties = new Dictionary<string, object>();
                            var nsgProperties = typeof(INetworkSecurityRule).GetProperties();
                            foreach (var currentRule in nsg1.SecurityRules)
                            {
                                var dict = new Dictionary<string, object>();
                                foreach (var property in nsgProperties)
                                {
                                    var value = property.GetValue(currentRule.Value);
                                    dict.Add(property.Name, value);
                                }
                                nsgsProperties.Add(nsg1.Key, dict);
                            }
                        }                  
                        //security    
                    }

            catch (Exception ex)

                {
                    throw;

                }

    What i am thinking that should i iterates NSG also??

    Pls, advice.. 

    Thanks,

    Thursday, August 6, 2020 5:30 PM
  • ok, here is the code after refactoring and correction: 

    Dictionary<string, object> nsgsProperties;
    try
    {
        var credentials = GetShared.GetCredentials();
        //Microsoft.Azure.Management.Network.Fluent.NetworkManager _networkManager;
        var azure = Azure
                    .Configure()
                    .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                    .Authenticate(credentials)
                    .WithSubscription(subscriptionId);
    
        // loop through network
        foreach (var nic in azure.NetworkInterfaces.List())
        {
            // getting the network security group by its id
            var nsg = azure.NetworkSecurityGroups.GetById(nic.NetworkSecurityGroupId);
            
            nsgsProperties = new Dictionary<string, object>();
            var nsgProperties = typeof(INetworkSecurityRule).GetProperties();
            // since we already have an nsg object we can get its security rules
            // loop through the current security group rules 
            foreach (var currentRule in nsg.SecurityRules)
            {
                var dict = new Dictionary<string, object>();
                // loop through properties of the result
                foreach (var property in nsgProperties)
                {
                    var value = property.GetValue(currentRule.Value);
                    dict.Add(property.Name, value);
                }
                nsgsProperties.Add(nsg.Key, dict);
            }
        }
    
        //security    
    }
    catch (Exception ex)
    
    {
        throw;
    }


    Thursday, August 6, 2020 6:36 PM
  • Tried and still struggling...

    An unhandled exception occurred while processing the request.

    ValidationException: 'resourceGroupName' cannot be null.

    Microsoft.Azure.Management.Network.Fluent.NetworkSecurityGroupsOperations.GetWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string expand, Dictionary<string, List<string>> customHeaders, CancellationToken cancellationToken)

    In code, C#.net ..

     // loop through network
     
       foreach (var nic in azure.NetworkInterfaces.List())

    Thanks,

    Saturday, August 8, 2020 3:48 PM
  • you should specify the resourceGroup by using the ListByResourcegroup() method:

    var interaces = azure.NetworkInterfaces.ListByResourceGroup("resourcegroup-name");
    foreach(var nic in interfaces)
    {
       //.......
    }
    • Marked as answer by ganirban_ece Saturday, August 8, 2020 5:49 PM
    • Unmarked as answer by ganirban_ece Saturday, August 8, 2020 6:01 PM
    • Marked as answer by ganirban_ece Saturday, August 8, 2020 6:01 PM
    Saturday, August 8, 2020 4:41 PM
  • Note: 

    please close the open threads by marking the solutions as answers:

    Saturday, August 8, 2020 4:43 PM
  • Thanks @Cherkaoui.Mouad,, for response and help...

    Below is working code...

      var ntwrrkDetails = new List<EndTcpPorts>();  

     EndTcpPorts objEndTcpPorts;

      foreach (var nsg in azure.NetworkSecurityGroups.List())
                    {
                        objEndTcpPorts = new EndTcpPorts();
                        objEndTcpPorts.ResourceGroup = nsg.ResourceGroupName.ToString();

                        try
                        {
                            var rules = nsg.SecurityRules;
                            foreach (var r in rules)
                            {
                                try
                                {
                                    objEndTcpPorts.NSGName = r.Value.Name.ToString();
                                }
                                catch (Exception)
                                {
                                    objEndTcpPorts.NSGName = "";
                                }
                                if (r.Value.DestinationPortRanges != null)
                                {
                                    try
                                    {
                                        //get ports
                                        objEndTcpPorts.TcpPorts = r.Value.DestinationPortRange.ToString(); //((Microsoft.Azure.Management.ResourceManager.Fluent.Core.IndexableWrapper<Microsoft.Azure.Management.Network.Fluent.Models.SecurityRuleInner>)r.Value).Inner.Protocol.Value.ToString();
                                    }
                                    catch (Exception)
                                    {

                                        objEndTcpPorts.TcpPorts = "";
                                    }
                                }

                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                        
                        ntwrrkDetails.Add(objEndTcpPorts); // add to list
                    }

    Pls, close it..

    Thanks, 

    Saturday, August 8, 2020 5:45 PM
  • it was a pleasure, Welcome!

    good idea!

    Saturday, August 8, 2020 6:11 PM