Skip to content

Instantly share code, notes, and snippets.

@DavidVentura
Created January 26, 2020 22:04
Show Gist options
  • Save DavidVentura/eda6427c608694d0eaef0e9f5c513f35 to your computer and use it in GitHub Desktop.
Save DavidVentura/eda6427c608694d0eaef0e9f5c513f35 to your computer and use it in GitHub Desktop.
loopback device setup/teardown/offset in python
import ctypes
import fcntl
SetStatus64 = 0x4C04
GetStatus64 = 0x4C05
CLR_FD = 0x4C01
SET_FD = 0x4C00
NameSize = 64
KeySize = 32
class Info(ctypes.Structure):
_fields_ = (
('Device', ctypes.c_uint64),
('INode', ctypes.c_uint64),
('RDevice', ctypes.c_uint64),
('Offset', ctypes.c_uint64),
('SizeLimit', ctypes.c_uint64),
('Number', ctypes.c_uint32),
('EncryptType', ctypes.c_uint32),
('EncryptKeySize', ctypes.c_uint32),
('Flags', ctypes.c_uint32),
('FileName', ctypes.c_byte),
('CryptName', NameSize*ctypes.c_byte),
('EncryptKey', KeySize*ctypes.c_byte),
('Init', 2*ctypes.c_uint64),
)
def __repr__(self):
ret = []
for n, v in a._fields_:
ret.append(f'{n}: {getattr(self, n)}')
return '\n'.join(ret)
def set_offset(loop, offset):
a = Info()
fcntl.ioctl(loop, GetStatus64, a)
a.Offset = offset
fcntl.ioctl(loop, SetStatus64, a)
fd = open('disk.img')
loop = open('/dev/loop7')
# mount fd to loopback device
fcntl.ioctl(loop, SET_FD, fd.fileno())
set_offset(loop, 512*2048)
a = Info()
fcntl.ioctl(loop, GetStatus64, a)
print(a)
# unmount
fcntl.ioctl(loop, CLR_FD, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment