Skip to content

Instantly share code, notes, and snippets.

@thotypous
Created September 1, 2013 02:18
Show Gist options
  • Save thotypous/6401888 to your computer and use it in GitHub Desktop.
Save thotypous/6401888 to your computer and use it in GitHub Desktop.
LuaJIT script to read Linux kernel memory in ARM architecture using /dev/mem
local ffi = require("ffi")
local C = ffi.C
ffi.cdef[[
static const int O_RDONLY = 0;
static const int SEEK_SET = 0;
int open(const char *, int, ...);
int close(int);
long int lseek(int, long int, int) __attribute__((__nothrow__, __leaf__));
int read(int, void *, unsigned int);
]]
function getVar(var_pattern)
local page_offset, phys_start, var_addr, value
for line in io.lines("/proc/kallsyms") do
local addr, symb = line:match("^(%x+) [^ ]+ (.+)$")
if symb == "_stext" then
page_offset = tonumber(addr, 16) - 0x8000 -- see arch/arm/kernel/ldlinux.lds
elseif symb and symb:match(var_pattern) then
var_addr = tonumber(addr, 16)
break
end
end
for line in io.lines("/proc/iomem") do
phys_start = line:match("^(%x+)-%x+ : System RAM")
if phys_start then
phys_start = tonumber(phys_start, 16)
break
end
end
if var_addr and page_offset and phys_start then
local data = ffi.new("int[1]")
local fd = C.open("/dev/mem", C.O_RDONLY)
C.lseek(fd, var_addr + phys_start - page_offset, C.SEEK_SET)
if C.read(fd, data, ffi.sizeof(data)) ~= -1 then
value = data[0]
end
C.close(fd)
end
return value
end
print(bit.tohex(getVar("getpid")))
print(bit.tohex(getVar("^last_FL_duty")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment