Model the Heartbleed handler: allocate a buffer by the DECLARED payload length, overwrite only the bytes that actually arrived, return the declared length — and print exactly how many bytes leak for a 16-byte payload declaring the maximum, then show the fixed handler refusing it.
Model the Heartbleed handler: allocate a buffer by the DECLARED payload length, overwrite only the bytes that actually arrived, return the declared length — and print exactly how many bytes leak for a 16-byte payload declaring the maximum, then show the fixed handler refusing it.
Answer
MEMORY = bytearray(b'K' * 65535) MAX_PAYLOAD = 65535 def buggy(payload, declared): buf = bytearray(MEMORY[:declared]) buf[: len(payload)] = payload return bytes(buf) def fixed(payload, declared): if declared != len(payload): return None return bytes(payload) request = b'A' * 16 reply = buggy(request, MAX_PAYLOAD) print('returned', len(reply)) print('leaked', len(reply) - len(request)) print('first leaked byte', chr(reply[16])) print('fixed handler', fixed(request, MAX_PAYLOAD))
Stallings & Brown 5e ch22 §22.3–22.4; RFC 2818