c # - Sådan registreres den oprindelige MAC-adresse, efter at den er blevet spoofed?

Indlæg af Hanne Mølgaard Plasc

Problem



Vi bruger følgende kode til at hente aktiv MAC-adresse på en Windows-pc.


private static string macId()
{
    return identifier("Win32\_NetworkAdapterConfiguration", "MACAddress", "IPEnabled");
}

private static string identifier(string wmiClass, string wmiProperty, string wmiMustBeTrue)
{
    string result = "";
    System.Management.ManagementClass mc = new System.Management.ManagementClass(wmiClass);
    System.Management.ManagementObjectCollection moc = mc.GetInstances();
    foreach (System.Management.ManagementObject mo in moc)
    {
        if (mo[wmiMustBeTrue].ToString() == "True")
        {
            //Only get the first one
            if (result == "")
            {
                try
                {
                    result = mo[wmiProperty].ToString();
                    break;
                }
                catch
                {
                }
            }
        }
    }
    return result;
}
//Return a hardware identifier
private static string identifier(string wmiClass, string wmiProperty)
{
    string result = "";
    System.Management.ManagementClass mc = new System.Management.ManagementClass(wmiClass);
    System.Management.ManagementObjectCollection moc = mc.GetInstances();
    foreach (System.Management.ManagementObject mo in moc)
    {
        //Only get the first one
        if (result == "")
        {
            try
            {
                result = mo[wmiProperty].ToString();
                break;
            }
            catch
            {
            }
        }
    }
    return result;
}


Det virker fint at hente MAC-adressen. Problemet er, når MAC-adressen er spoofed, så returnerer den den spoofede MAC-adresse. Vi vil på en eller anden måde hente den oprindelige MAC-adresse, som er unik og tildelt på fabrikken. Er der nogen måde at gøre det på?

Bedste reference


Jeg ønsker at give et alternativ. Jeg ved ikke, om det virkelig svarer til 'en måde at identificere en hvilken som helst computer unikt'.

Denne metode spørger dog Win32\_BIOS-klassen i Systemmanagement og returnerer en streng med store chancer for at være unik. (Venter på at blive skuffet !!)


/// <summary>
/// BIOS IDentifier
/// </summary>
/// <returns></returns>
public static string BIOS\_ID()
{
    return    GetFirstIdentifier("Win32\_BIOS", "Manufacturer")
            + GetFirstIdentifier("Win32\_BIOS", "SMBIOSBIOSVersion")
            + GetFirstIdentifier("Win32\_BIOS", "IdentificationCode")
            + GetFirstIdentifier("Win32\_BIOS", "SerialNumber")
            + GetFirstIdentifier("Win32\_BIOS", "ReleaseDate")
            + GetFirstIdentifier("Win32\_BIOS", "Version");
}

/// <summary>
/// ManagementClass used to read the first specific properties
/// </summary>
/// <param name="wmiClass">Object Class to query</param>
/// <param name="wmiProperty">Property to get info</param>
/// <returns></returns>
private static string GetFirstIdentifier(string wmiClass, string wmiProperty)
{
    string result = string.Empty;
    ManagementClass mc = new System.Management.ManagementClass(wmiClass);
    ManagementObjectCollection moc = mc.GetInstances();
    foreach (ManagementObject mo in moc)
    {
        //Only get the first one
        if (string.IsNullOrEmpty(result))
        {
            try
            {
                if (mo[wmiProperty] != null) result = mo[wmiProperty].ToString();
                break;
            }
            catch
            {
            }
        }
    }
    return result.Trim();
}

Andre referencer 1


Der kan være to alternativer.



  1. Du kan få MAC-adressen ved hjælp af kodestykket, du gav før, og kontrollere, om MAC-adressen tilhører et NIC (Network Interface Card). Hvis det ikke tilhører en, så er MAC-adressen åbenbart spoofed. Her er koden, der finder NIC'en ved hjælp af en MAC-adresse


    using System.Net.Sockets;
    using System.Net;
    using System.Net.NetworkInformation;
    
    string localNicMac = "00:00:00:11:22:33".Replace(":", "-"); // Parse doesn't like colons
    
    var mac = PhysicalAddress.Parse(localNicMac);
    var localNic =
    NetworkInterface.GetAllNetworkInterfaces()
        .Where(nic => nic.GetPhysicalAddress().Equals(mac)) // Must use .Equals, not ==
        .SingleOrDefault();
    if (localNic == null)
    {
        throw new ArgumentException("Local NIC with the specified MAC could not be found.");
    }
    
    var ips =
        localNic.GetIPProperties().UnicastAddresses
        .Select(x => x.Address);
    

  2. Få netværkskortets adresse direkte.


    a. NWIF = dotnetClass "System.Net.NetworkInformation.NetworkInterface"  
    b. the\_Mac\_array = NWIF.GetAllNetworkInterfaces() -- this is an array of all the Networks  
    c. the\_PhysicalAddress\_Array = #()  
    d. for net in the\_Mac\_array where (net.NetworkInterfaceType.toString()) == "Ethernet" do append   the\_PhysicalAddress\_Array ((net.GetPhysicalAddress()).toString())  
    e. print the\_PhysicalAddress\_Array
    



((Jeg fandt det her http://snipplr.com/view/23006/)) [7]

Andre referencer 2


Jeg var nødt til at skrive noget lignende for lidt siden, fordi jeg brugte en række hardwareparametre til 'aktivering' af min software.


Tag et kig på, DeviceIoControl & OID\_802\_3\_PERMANENT\_ADDRESS.
Det er en masse interop-kode (min klasse til at håndtere den er ca. 200 linjer), men det giver mig den garanterede hardwarekode. [8] [9]


Nogle kodeuddrag til at komme i gang,


private const uint IOCTL\_NDIS\_QUERY\_GLOBAL\_STATS = 0x170002;

[DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool DeviceIoControl(
        SafeFileHandle hDevice,
        uint dwIoControlCode,
        ref int InBuffer,
        int nInBufferSize,
        byte[] OutBuffer,
        int nOutBufferSize,
        out int pBytesReturned,
        IntPtr lpOverlapped);

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
internal static extern SafeFileHandle CreateFile(
    string lpFileName,
    EFileAccess dwDesiredAccess,
    EFileShare dwShareMode,
    IntPtr lpSecurityAttributes,
    ECreationDisposition dwCreationDisposition,
    EFileAttributes dwFlagsAndAttributes,
    IntPtr hTemplateFile);

[Flags]
internal enum EFileAccess : uint
{
    Delete = 0x10000,
    ReadControl = 0x20000,
    WriteDAC = 0x40000,
    WriteOwner = 0x80000,
    Synchronize = 0x100000,

    StandardRightsRequired = 0xF0000,
    StandardRightsRead = ReadControl,
    StandardRightsWrite = ReadControl,
    StandardRightsExecute = ReadControl,
    StandardRightsAll = 0x1F0000,
    SpecificRightsAll = 0xFFFF,

    AccessSystemSecurity = 0x1000000,       // AccessSystemAcl access type

    MaximumAllowed = 0x2000000,         // MaximumAllowed access type

    GenericRead = 0x80000000,
    GenericWrite = 0x40000000,
    GenericExecute = 0x20000000,
    GenericAll = 0x10000000
}

// Open a file handle to the interface
using (SafeFileHandle handle = FileInterop.CreateFile(deviceName,
    FileInterop.EFileAccess.GenericRead | FileInterop.EFileAccess.GenericWrite,
    0, IntPtr.Zero, FileInterop.ECreationDisposition.OpenExisting,
    0, IntPtr.Zero))
{
    int bytesReturned;
    // Set the OID to query the permanent address
    // http://msdn.microsoft.com/en-us/library/windows/hardware/ff569074(v=vs.85).aspx
    int OID\_802\_3\_PERMANENT\_ADDRESS = 0x01010101;

    // Array to capture the mac address
    var address = new byte[6];
    if (DeviceIoControl(handle, IOCTL\_NDIS\_QUERY\_GLOBAL\_STATS,
        ref OID\_802\_3\_PERMANENT\_ADDRESS, sizeof(uint),
        address, 6, out bytesReturned, IntPtr.Zero))
    {
        // Attempt to parse the MAC address into a string
        // any exceptions will be passed onto the caller
        return BitConverter.ToString(address, 0, 6);
    }
}

Andre referencer 3


Nå, jeg ville ikke betjene alle mine penge på den rækkefølge, hvor NetworkInterface klasse lister NetworkInterfaces.
Mit moderkort har 2 adaptere, og ordren synes at skifte hver gang jeg genstarter.


Så her er et forslag, som fungerede for mig (BTW: kreditter går sandsynligvis til en anden awesome stackoverflow contributer, ty):


    public static string GetMACAddress()
    {
        NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
        //for each j you can get the MAC 
        PhysicalAddress address = nics[0].GetPhysicalAddress();
        byte[] bytes = address.GetAddressBytes();

        string macAddress = "";

        for (int i = 0; i < bytes.Length; i++)
        {
            // Format the physical address in hexadecimal. 
            macAddress += bytes[i].ToString("X2");
            // Insert a hyphen after each byte, unless we are at the end of the address. 
            if (i != bytes.Length - 1)
            {
                macAddress += "-";
            }
        }

        return macAddress;
    }