1import pickle, resource
2
3# Limit memory for safe testing
4soft, hard = resource.getrlimit(resource.RLIMIT_AS)
5resource.setrlimit(resource.RLIMIT_AS, (512*1024*1024, hard))
6
7try:
8 with open('malicious.pkl', 'rb') as f:
9 pickle.load(f)
10except MemoryError:
11 print("OOM: 12-byte file triggered multi-GB allocation!")
12finally:
13 resource.setrlimit(resource.RLIMIT_AS, (soft, hard))
1# CPython Lib/pickle.py, line 1383
2def load_bytearray8(self):
3 len, = unpack('<Q', self.read(8))
4 if len > maxsize:
5 raise UnpicklingError("...")
6 b = bytearray(len) # PRE-ALLOCATES (vulnerable)
7 self.readinto(b) # reads data (too late)
8 self.append(b)