Skip to content

Instantly share code, notes, and snippets.

@smourier
Created March 20, 2023 11:27
Show Gist options
  • Save smourier/d7dabccb2c0473eb08c295e30141f46f to your computer and use it in GitHub Desktop.
Save smourier/d7dabccb2c0473eb08c295e30141f46f to your computer and use it in GitHub Desktop.
Read EFI Variable
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
namespace ConsoleApp2
{
internal class Program
{
// code must be ran as admin
static void Main()
{
Type privilegeType;
if (RuntimeInformation.FrameworkDescription.Contains("Framework"))
{
privilegeType = Type.GetType("System.Security.AccessControl.Privilege");
}
else
{
// on .NET Core, add the System.Security.AccessControl nuget package otherwise null will be returned
privilegeType = Type.GetType("System.Security.AccessControl.Privilege, System.Security.AccessControl");
}
var privilege = Activator.CreateInstance(privilegeType, "SeSystemEnvironmentPrivilege");
privilegeType.GetMethod("Enable").Invoke(privilege, null);
var inputSize = 256;
var ptr = Marshal.AllocHGlobal(inputSize);
try
{
var outputSize = GetFirmwareEnvironmentVariable("PlatformLangCodes", "{8be4df61-93ca-11d2-aa0d-00e098032b8c}", ptr, inputSize);
if (Marshal.GetLastWin32Error() != 0)
throw new Win32Exception(Marshal.GetLastWin32Error());
Console.WriteLine(ToHexaDump(ptr, outputSize));
}
finally
{
Marshal.FreeHGlobal(ptr);
privilegeType.GetMethod("Revert").Invoke(privilege, null);
}
}
[DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int GetFirmwareEnvironmentVariable(string lpName, string lpGuid, IntPtr pBuffer, int nSize);
public static string ToHexaDump(IntPtr ptr, int bufferSize, bool addHeader = true)
{
if (ptr == IntPtr.Zero)
throw new ArgumentException(null, nameof(ptr));
if (bufferSize < 0)
throw new ArgumentOutOfRangeException(nameof(bufferSize));
var sb = new StringBuilder();
if (addHeader)
{
// 0 1 2 3 4 5 6 7
// 01234567890123456789012345678901234567890123456789012345678901234567890123456789
sb.AppendLine("Offset 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 0123456789ABCDEF");
sb.AppendLine("-------- ----------------------------------------------- ----------------");
}
for (var i = 0; i < bufferSize; i += 16)
{
sb.AppendFormat("{0:X8} ", i);
int j;
for (j = 0; (j < 16) && ((i + j) < bufferSize); j++)
{
sb.AppendFormat("{0:X2} ", Marshal.ReadByte(ptr, i + j));
}
sb.Append(' ');
if (j < 16)
{
sb.Append(new string(' ', 3 * (16 - j)));
}
for (j = 0; j < 16 && (i + j) < bufferSize; j++)
{
var b = Marshal.ReadByte(ptr, i + j);
if (b > 31 && b < 128)
{
sb.Append((char)b);
}
else
{
sb.Append('.');
}
}
sb.AppendLine();
}
return sb.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment