/// <summary>
        /// Uses the Github API to checks the Wireshark repo for an updated manuf file. If found, downloads
        /// and converts into the smaller binary format and compresses.
        /// </summary>
        /// <param name="pathToManufBinFile">Path of the manuf.bin.zip file. If exists will be used to see if an update is available. If doesn't exist will always download and create one.</param>
        /// <param name="testReadbackOfFile">True to force a readback/parse of the newly generated file to ensure it works.</param>
        /// <returns>Returns true if file was downloaded and updated, false if already have latest version</returns>
        public static async Task <bool> UpdateManufBin(string pathToManufBinFile, string wiresharkGithub = WIRESHARK_GITHUB_API, bool testReadbackOfFile = false)
        {
            string existingManufSha = "";

            if (File.Exists(pathToManufBinFile))
            {
                using (var zipFile = ZipFile.OpenRead(pathToManufBinFile))
                    using (var shaEntry = zipFile.GetEntry("manuf.sha").Open())
                        using (var shaStreamReader = new StreamReader(shaEntry, Encoding.UTF8))
                        {
                            existingManufSha = await shaStreamReader.ReadToEndAsync();
                        }
            }

            string manufDownloadLink;
            string manufLatestSha;

            // query github API for meta data about manuf file
            var httpRequest = WebRequest.CreateHttp(wiresharkGithub);

            httpRequest.UserAgent = "manuf";
            using (var httpResponse = await httpRequest.GetResponseAsync())
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
                {
                    var repoMetadata = await streamReader.ReadToEndAsync();

                    var contentsJson = DeserializeJson <GithubApiFileEntry[]>(repoMetadata);
                    var manufMeta    = contentsJson.FirstOrDefault(e => e.name == "manuf");
                    manufLatestSha    = manufMeta.sha;
                    manufDownloadLink = manufMeta.download_url;
                }


            // we already have the latest based on sha comparison
            if (existingManufSha == manufLatestSha)
            {
                return(false);
            }

            // download latest manuf and parse into vendor infos
            var manufParser = new WiresharkManufReader();

            using (var manufMemStream = new MemoryStream())
            {
                // download manuf file into memory stream
                using (var httpResponse = await WebRequest.CreateHttp(manufDownloadLink).GetResponseAsync())
                    using (var manufStream = httpResponse.GetResponseStream())
                    {
                        await manufStream.CopyToAsync(manufMemStream);

                        manufMemStream.Position = 0;
                    }

                // parse mem stream into vendor infos
                await manufParser.Init(manufMemStream);
            }

            // write vendor info into binary format into temp file
            var outputFile = Path.GetTempFileName();

            using (var outFileStream = File.OpenWrite(outputFile))
            {
                var vendorWriter = new MacVendorBinaryWriter(manufParser);
                vendorWriter.Write(outFileStream);
            }

            // true to test readback of file..
            if (testReadbackOfFile)
            {
                var vendorReader = new MacVendorBinaryReader();

                // test read back binary format of vendor info
                using (var fileReadStream = File.OpenRead(outputFile))
                {
                    await vendorReader.Init(fileReadStream);

                    var entries = vendorReader.GetEntries();
                }
                if (vendorReader.GetEntries().Count() != manufParser.GetEntries().Count())
                {
                    throw new Exception("Something wrong with writing or reading");
                }
                foreach (var entry in vendorReader.GetEntries())
                {
                    //Console.WriteLine(entry);
                }
            }

            File.Delete(pathToManufBinFile);
            using (var zipFileStream = ZipFile.Open(pathToManufBinFile, ZipArchiveMode.Create))
            {
                zipFileStream.CreateEntryFromFile(outputFile, "manuf.bin");
                var shaEntry = zipFileStream.CreateEntry("manuf.sha");
                using (var shaStreamWriter = new StreamWriter(shaEntry.Open(), Encoding.UTF8))
                {
                    shaStreamWriter.Write(manufLatestSha);
                }
            }

            File.Delete(outputFile);

            return(true);
        }
Exemplo n.º 2
0
        private static void Main(string[] args)
        {
            // Retrieve the device list
            var devices = LibPcapLiveDeviceList.Instance;

            // If no devices were found print an error
            if (devices.Count < 1)
            {
                Console.WriteLine("No devices were found on this machine");
                return;
            }

            Console.WriteLine("The following devices are available on this machine:");
            Console.WriteLine("----------------------------------------------------");
            Console.WriteLine();

            int i = 0;

            // Print out the available devices
            foreach (var dev in devices)
            {
                Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description);
                foreach (var address in dev.Addresses)
                {
                    Console.WriteLine($"{address}");
                }
                i++;
            }

            Console.WriteLine();
            Console.Write("-- Please choose a device for sending the ARP request: ");
            i = int.Parse(Console.ReadLine());

            var       device = devices[i];
            IPAddress startIPAddress;
            IPAddress stopIPAddress;

            // loop until a valid ip address is parsed
            while (true)
            {
                Console.Write("-- Please enter Start IP address to be resolved by ARP: ");
                if (IPAddress.TryParse(Console.ReadLine(), out startIPAddress))
                {
                    break;
                }

                Console.WriteLine("Bad IP address format, please try again");
            }
            // loop until a valid ip address is parsed
            while (true)
            {
                Console.Write("-- Please enter Stop IP address to be resolved by ARP: ");
                if (System.Net.IPAddress.TryParse(Console.ReadLine(), out stopIPAddress))
                {
                    break;
                }

                Console.WriteLine("Bad IP address format, please try again");
            }
            ArpForIpConflict arper = new ArpForIpConflict(device);

            arper.ResolvedEvent += ArpForIpConflict_ResolvedEvent;

            var         ipAddresses  = GenerateIPAddresses(startIPAddress, stopIPAddress);
            List <Task> resolveTasks = new List <Task>();

            arper.OpenAndApplyFilter();
            foreach (var ipAddress in ipAddresses)
            {
                var request = arper.BuildRequest(ipAddress);
                arper.Resolve(request, ipAddress);
            }
            arper.Close();
            Console.WriteLine("Exit Scan");

            Console.WriteLine("Print Result");
            var IPAddressPhysicalAddressLookup = IPAddressPhysicalAddressMapList.ToLookup(l => l.iPAddress, l => l.physicalAddress).Where(lu => lu.Count() > 1);
            var reader = new WiresharkManufReader();

            using (var manufTxtFile = File.OpenRead("manuf.txt"))
            {
                reader.Init(manufTxtFile).Wait();
            }
            var addressMatcher = new AddressMatcher(reader);

            Console.ForegroundColor = ConsoleColor.Red;
            // Iterate through each IGrouping in the Lookup and output the contents.
            foreach (var IPAddressPhysicalAddressGroup in IPAddressPhysicalAddressLookup)
            {
                // Print the key value of the IGrouping.
                Console.WriteLine($"IP:{IPAddressPhysicalAddressGroup.Key}");
                // Iterate through each value in the IGrouping and print its value.
                foreach (var physicalAddress in IPAddressPhysicalAddressGroup)
                {
                    var vendorInfo = addressMatcher.FindInfo(physicalAddress);
                    if (vendorInfo != null)
                    {
                        Console.WriteLine($"\t{physicalAddress}\t{vendorInfo.Organization}");
                    }
                    else
                    {
                        Console.WriteLine($"\t{physicalAddress}");
                    }
                }
            }
            Console.ForegroundColor = ConsoleColor.White;

            Console.WriteLine("Press Enter To Exit");
            Console.ReadLine();
        }