Repository navigation
Expand file tree
/
Copy pathTryOpenKbd.cs
More file actions
47 lines (43 loc) · 2.49 KB
/
Copy pathTryOpenKbd.cs
File metadata and controls
47 lines (43 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Can userspace read the RAW keyboard report - the one containing Apple's fn bit
// (vendor usage 0xFF00:0x03)? Tries every access combination that might work.
using System;
using System.Runtime.InteropServices;
class TryOpenKbd {
const uint GENERIC_READ = 0x80000000, GENERIC_WRITE = 0x40000000;
const uint SHARE_R = 1, SHARE_W = 2, OPEN_EXISTING = 3;
static readonly IntPtr INVALID = new IntPtr(-1);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern IntPtr CreateFile(string p, uint a, uint s, IntPtr sa, uint d, uint f, IntPtr t);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool ReadFile(IntPtr h, byte[] b, int n, out int r, IntPtr o);
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
static void Try(string label, string path, uint access, uint share) {
IntPtr h = CreateFile(path, access, share, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
if (h == INVALID) {
int e = Marshal.GetLastWin32Error();
Console.WriteLine(string.Format(" {0,-34} FAILED err={1} {2}", label, e,
e == 5 ? "(ACCESS_DENIED - held exclusively by the OS)" : ""));
return;
}
Console.WriteLine(string.Format(" {0,-34} OPENED", label));
if ((access & GENERIC_READ) != 0) {
var buf = new byte[10];
int got;
bool ok = ReadFile(h, buf, buf.Length, out got, IntPtr.Zero);
Console.WriteLine(string.Format(" ReadFile -> {0} err={1}", ok, ok ? 0 : Marshal.GetLastWin32Error()));
}
CloseHandle(h);
}
static void Main(string[] argv) {
string kbd = @"\\?\hid#{00001124-0000-1000-8000-00805f9b34fb}_vid&0001004c_pid&029c&col01#b&2d27471b&5&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}";
Console.WriteLine("Attempting raw access to the Magic Keyboard's keyboard collection (COL01):");
Try("GENERIC_READ, share R|W", kbd, GENERIC_READ, SHARE_R | SHARE_W);
Try("GENERIC_READ, share R", kbd, GENERIC_READ, SHARE_R);
Try("GENERIC_READ, no sharing", kbd, GENERIC_READ, 0);
Try("GENERIC_R|W, share R|W", kbd, GENERIC_READ | GENERIC_WRITE, SHARE_R | SHARE_W);
Try("no access (query only)", kbd, 0, SHARE_R | SHARE_W);
Console.WriteLine();
Console.WriteLine("Also trying the \\kbd suffixed interface Windows itself uses:");
Try("GENERIC_READ on \\kbd", kbd + @"\kbd", GENERIC_READ, SHARE_R | SHARE_W);
}
}