public void CanWatchNetwork()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                string newName            = SdkContext.RandomResourceName("nw", 6);
                var    groupName          = SdkContext.RandomResourceName("rg", 6);
                var    resourcesGroupName = SdkContext.RandomResourceName("rg", 8);

                // Create network watcher
                var manager        = TestHelper.CreateNetworkManager();
                var computeManager = TestHelper.CreateComputeManager();

                // make sure Network Watcher is disabled in current subscription and region as only one can exist
                EnsureNetworkWatcherNotExists(manager.NetworkWatchers);

                var nw = manager.NetworkWatchers.Define(newName)
                         .WithRegion(REGION)
                         .WithNewResourceGroup(groupName)
                         .Create();

                // pre-create VMs to show topology on
                ICreatedResources <IVirtualMachine> virtualMachines = EnsureNetwork(manager, computeManager, resourcesGroupName);
                var       vm0      = virtualMachines.ElementAt(0);
                ITopology topology = nw.GetTopology(vm0.ResourceGroupName);
                Assert.Equal(11, topology.Resources.Count);
                Assert.True(topology.Resources.ContainsKey(vm0.PrimaryNetworkInterfaceId));
                Assert.Equal(4, topology.Resources[vm0.PrimaryNetworkInterfaceId].Associations.Count);

                ISecurityGroupView sgViewResult = nw.GetSecurityGroupView(virtualMachines.ElementAt(0).Id);
                Assert.Equal(1, sgViewResult.NetworkInterfaces.Count);
                Assert.Equal(virtualMachines.ElementAt(0).PrimaryNetworkInterfaceId,
                             sgViewResult.NetworkInterfaces.Keys.First());

                IFlowLogSettings flowLogSettings =
                    nw.GetFlowLogSettings(vm0.GetPrimaryNetworkInterface().NetworkSecurityGroupId);
                IStorageAccount storageAccount = EnsureStorageAccount(resourcesGroupName);
                flowLogSettings.Update()
                .WithLogging()
                .WithStorageAccount(storageAccount.Id)
                .WithRetentionPolicyDays(5)
                .WithRetentionPolicyEnabled()
                .Apply();
                Assert.True(flowLogSettings.Enabled);
                Assert.Equal(5, flowLogSettings.RetentionDays);
                Assert.Equal(storageAccount.Id, flowLogSettings.StorageId);

                INextHop nextHop = nw.NextHop().WithTargetResourceId(vm0.Id)
                                   .WithSourceIPAddress("10.0.0.4")
                                   .WithDestinationIPAddress("8.8.8.8")
                                   .Execute();
                Assert.Equal("System Route", nextHop.RouteTableId);
                Assert.Equal(NextHopType.Internet, nextHop.NextHopType);
                Assert.Null(nextHop.NextHopIpAddress);

                IVerificationIPFlow verificationIPFlow = nw.VerifyIPFlow()
                                                         .WithTargetResourceId(vm0.Id)
                                                         .WithDirection(Direction.Outbound)
                                                         .WithProtocol(Protocol.TCP)
                                                         .WithLocalIPAddress("10.0.0.4")
                                                         .WithRemoteIPAddress("8.8.8.8")
                                                         .WithLocalPort("443")
                                                         .WithRemotePort("443")
                                                         .Execute();
                Assert.Equal(Access.Allow, verificationIPFlow.Access);
                Assert.Equal("defaultSecurityRules/AllowInternetOutBound", verificationIPFlow.RuleName);

                // test packet capture
                IEnumerable <IPacketCapture> packetCaptures = nw.PacketCaptures.List();
                Assert.Empty(packetCaptures);
                IPacketCapture packetCapture = nw.PacketCaptures
                                               .Define("NewPacketCapture")
                                               .WithTarget(vm0.Id)
                                               .WithStorageAccountId(storageAccount.Id)
                                               .WithTimeLimitInSeconds(1500)
                                               .DefinePacketCaptureFilter()
                                               .WithProtocol(PcProtocol.TCP)
                                               .WithLocalIPAddresses(new List <string>()
                {
                    "127.0.0.1", "127.0.0.5"
                })
                                               .Attach()
                                               .Create();
                packetCaptures = nw.PacketCaptures.List();
                Assert.Single(packetCaptures);
                Assert.Equal("NewPacketCapture", packetCapture.Name);
                Assert.Equal(1500, packetCapture.TimeLimitInSeconds);
                Assert.Equal(PcProtocol.TCP.Value, packetCapture.Filters[0].Protocol);
                Assert.Equal("127.0.0.1;127.0.0.5", packetCapture.Filters[0].LocalIPAddress);
                //        Assert.assertEquals("Running", packetCapture.getStatus().packetCaptureStatus().toString());
                packetCapture.Stop();
                Assert.Equal("Stopped", packetCapture.GetStatus().PacketCaptureStatus.Value);
                nw.PacketCaptures.DeleteByName(packetCapture.Name);
                IConnectivityCheck connectivityCheck = nw.CheckConnectivity()
                                                       .ToDestinationResourceId(vm0.Id)
                                                       .ToDestinationPort(80)
                                                       .FromSourceVirtualMachine(virtualMachines.ElementAt(0).Id)
                                                       .Execute();
                Assert.Equal("Reachable", connectivityCheck.ConnectionStatus.ToString());

                computeManager.VirtualMachines.DeleteById(virtualMachines.ElementAt(1).Id);
                topology.Refresh();
                Assert.Equal(10, topology.Resources.Count);

                manager.ResourceManager.ResourceGroups.DeleteByName(nw.ResourceGroupName);
                manager.ResourceManager.ResourceGroups.DeleteByName(resourcesGroupName);
            }
        }
Пример #2
0
        /**
         * Azure Network sample for managing network watcher -
         *  - Create Network Watcher
         *	- Manage packet capture – track traffic to and from a virtual machine
         *      Create a VM
         *      Start a packet capture
         *      Stop a packet capture
         *      Get a packet capture
         *      Delete a packet capture
         *  - Verify IP flow – verify if traffic is allowed to or from a virtual machine
         *      Get the IP address of a NIC on a virtual machine
         *      Test IP flow on the NIC
         *  - Analyze next hop – get the next hop type and IP address for a virtual machine
         *  - Retrieve network topology for a resource group
         *  - Analyze Virtual Machine Security by examining effective network security rules applied to a VM
         *      Get security group view for the VM
         *  - Configure Network Security Group Flow Logs
         *      Get flow log settings
         *      Enable NSG flow log
         *      Disable NSG flow log
         *  - Delete network watcher
         */
        public static void RunSample(IAzure azure)
        {
            string nwName = SdkContext.RandomResourceName("nw", 8);

            string          userName          = "******";
            string          vnetName          = SdkContext.RandomResourceName("vnet", 20);
            string          subnetName        = "subnet1";
            string          nsgName           = SdkContext.RandomResourceName("nsg", 20);
            string          dnsLabel          = SdkContext.RandomResourceName("pipdns", 20);
            string          rgName            = SdkContext.RandomResourceName("rg", 24);
            string          saName            = SdkContext.RandomResourceName("sa", 24);
            string          vmName            = SdkContext.RandomResourceName("vm", 24);
            string          packetCaptureName = SdkContext.RandomResourceName("pc", 8);
            INetworkWatcher nw = null;

            try
            {
                //============================================================
                // Create network watcher
                Utilities.Log("Creating network watcher...");
                nw = azure.NetworkWatchers.Define(nwName)
                     .WithRegion(region)
                     .WithNewResourceGroup()
                     .Create();

                Utilities.Log("Created network watcher");
                // Print the network watcher
                Utilities.Print(nw);

                //============================================================
                // Manage packet capture – track traffic to and from a virtual machine

                // Create network security group, virtual network and VM; add packetCapture extension to enable packet capture
                Utilities.Log("Creating network security group...");
                INetworkSecurityGroup nsg = azure.NetworkSecurityGroups.Define(nsgName)
                                            .WithRegion(region)
                                            .WithNewResourceGroup(rgName)
                                            .DefineRule("DenyInternetInComing")
                                            .DenyInbound()
                                            .FromAddress("INTERNET")
                                            .FromAnyPort()
                                            .ToAnyAddress()
                                            .ToPort(443)
                                            .WithAnyProtocol()
                                            .Attach()
                                            .Create();
                Utilities.Log("Creating virtual network...");
                ICreatable <INetwork> virtualNetwork = azure.Networks.Define(vnetName)
                                                       .WithRegion(region)
                                                       .WithExistingResourceGroup(rgName)
                                                       .WithAddressSpace("192.168.0.0/16")
                                                       .DefineSubnet(subnetName)
                                                       .WithAddressPrefix("192.168.2.0/24")
                                                       .WithExistingNetworkSecurityGroup(nsg)
                                                       .Attach();
                Utilities.Log("Creating virtual machine...");
                IVirtualMachine vm = azure.VirtualMachines.Define(vmName)
                                     .WithRegion(region)
                                     .WithExistingResourceGroup(rgName)
                                     .WithNewPrimaryNetwork(virtualNetwork)
                                     .WithPrimaryPrivateIPAddressDynamic()
                                     .WithNewPrimaryPublicIPAddress(dnsLabel)
                                     .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer14_04_Lts)
                                     .WithRootUsername(userName)
                                     .WithRootPassword("Abcdef.123456")
                                     .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                     .DefineNewExtension("packetCapture")
                                     .WithPublisher("Microsoft.Azure.NetworkWatcher")
                                     .WithType("NetworkWatcherAgentLinux")
                                     .WithVersion("1.4")
                                     .WithMinorVersionAutoUpgrade()
                                     .Attach()
                                     .Create();

                // Create storage account
                Utilities.Log("Creating storage account...");
                IStorageAccount storageAccount = azure.StorageAccounts.Define(saName)
                                                 .WithRegion(region)
                                                 .WithExistingResourceGroup(rgName)
                                                 .Create();

                // Start a packet capture
                Utilities.Log("Creating packet capture...");
                IPacketCapture packetCapture = nw.PacketCaptures
                                               .Define(packetCaptureName)
                                               .WithTarget(vm.Id)
                                               .WithStorageAccountId(storageAccount.Id)
                                               .WithTimeLimitInSeconds(1500)
                                               .DefinePacketCaptureFilter()
                                               .WithProtocol(PcProtocol.TCP)
                                               .Attach()
                                               .Create();
                Utilities.Log("Created packet capture");
                Utilities.Print(packetCapture);

                // Stop a packet capture
                Utilities.Log("Stopping packet capture...");
                packetCapture.Stop();
                Utilities.Print(packetCapture);

                // Get a packet capture
                Utilities.Log("Getting packet capture...");
                IPacketCapture packetCapture1 = nw.PacketCaptures.GetByName(packetCaptureName);
                Utilities.Print(packetCapture1);

                // Delete a packet capture
                Utilities.Log("Deleting packet capture");
                nw.PacketCaptures.DeleteByName(packetCapture.Name);

                //============================================================
                // Verify IP flow – verify if traffic is allowed to or from a virtual machine
                // Get the IP address of a NIC on a virtual machine
                String ipAddress = vm.GetPrimaryNetworkInterface().PrimaryPrivateIP;
                // Test IP flow on the NIC
                Utilities.Log("Verifying IP flow for vm id " + vm.Id + "...");
                IVerificationIPFlow verificationIPFlow = nw.VerifyIPFlow()
                                                         .WithTargetResourceId(vm.Id)
                                                         .WithDirection(Direction.Outbound)
                                                         .WithProtocol(IpFlowProtocol.TCP)
                                                         .WithLocalIPAddress(ipAddress)
                                                         .WithRemoteIPAddress("8.8.8.8")
                                                         .WithLocalPort("443")
                                                         .WithRemotePort("443")
                                                         .Execute();
                Utilities.Print(verificationIPFlow);

                //============================================================
                // Analyze next hop – get the next hop type and IP address for a virtual machine
                Utilities.Log("Calculating next hop...");
                INextHop nextHop = nw.NextHop().WithTargetResourceId(vm.Id)
                                   .WithSourceIPAddress(ipAddress)
                                   .WithDestinationIPAddress("8.8.8.8")
                                   .Execute();
                Utilities.Print(nextHop);

                //============================================================
                // Retrieve network topology for a resource group
                Utilities.Log("Getting topology...");
                ITopology topology = nw.Topology()
                                     .WithTargetResourceGroup(rgName)
                                     .Execute();
                Utilities.Print(topology);

                //============================================================
                // Analyze Virtual Machine Security by examining effective network security rules applied to a VM
                // Get security group view for the VM
                Utilities.Log("Getting security group view for a vm");
                ISecurityGroupView sgViewResult = nw.GetSecurityGroupView(vm.Id);
                Utilities.Print(sgViewResult);

                //============================================================
                // Configure Network Security Group Flow Logs

                // Get flow log settings
                IFlowLogSettings flowLogSettings = nw.GetFlowLogSettings(nsg.Id);
                Utilities.Print(flowLogSettings);

                // Enable NSG flow log
                flowLogSettings.Update()
                .WithLogging()
                .WithStorageAccount(storageAccount.Id)
                .WithRetentionPolicyDays(5)
                .WithRetentionPolicyEnabled()
                .Apply();
                Utilities.Print(flowLogSettings);

                // Disable NSG flow log
                flowLogSettings.Update()
                .WithoutLogging()
                .Apply();
                Utilities.Print(flowLogSettings);

                //============================================================
                // Delete network watcher
                Utilities.Log("Deleting network watcher");
                azure.NetworkWatchers.DeleteById(nw.Id);
                Utilities.Log("Deleted network watcher");
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);
                    if (nw != null)
                    {
                        Utilities.Log("Deleting network watcher resource group: " + nw.ResourceGroupName);
                        azure.ResourceGroups.BeginDeleteByName(nw.ResourceGroupName);
                    }
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception ex)
                {
                    Utilities.Log(ex);
                }
            }
        }