-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecord.py
68 lines (51 loc) · 1.54 KB
/
record.py
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from enum import Enum
from utils import ByteReader, ByteWriter
class RecordContentType(Enum):
CHANGE_CIPHER_SPEC = 0x14
ALERT = 0x15
HANDSHAKE = 0x16
APPLICATION_DATA = 0x17
HEARTBEAT = 0x18
class RecordVersion(Enum):
SSL_3 = 0x0300
TLS_1 = 0x0301
TLS_1_1 = 0x0302
TLS_1_2 = 0x0303
TLS_1_3 = 0x0304
class Record:
def __init__(self,
content_type: RecordContentType,
version: RecordVersion,
data: bytes):
self.content_type = content_type
self.version = version
self.data = data
@property
def length(self) -> int:
return len(self.data)
@classmethod
def from_bytes(cls, data: bytes):
reader = ByteReader(data)
content_type = RecordContentType(reader.read_u8())
version = RecordVersion(reader.read_u16())
length = reader.read_u16()
data = reader.read_bytes(length)
return cls(content_type, version, data)
def to_bytes(self) -> bytes:
writer = ByteWriter()
writer.write_u8(self.content_type.value)
writer.write_u16(self.version.value)
writer.write_u16(self.length)
assert self.length == len(self.data)
data = writer.write_bytes(self.data)
return data
def __len__(self) -> int:
return len(self.to_bytes())
def __str__(self) -> str:
s = []
s.append("** Record **")
s.append(f"Content Type : {self.content_type.name}")
s.append(f"Version : {self.version.name}")
s.append(f"Length : {self.length}")
s.append(f"Data : 0x{self.data[:32].hex()} ...")
return "\n".join(s)