path
stringlengths
9
117
type
stringclasses
2 values
project
stringclasses
10 values
commit_hash
stringlengths
40
40
commit_message
stringlengths
1
137
ground_truth
stringlengths
0
2.74k
main_code
stringlengths
102
3.37k
context
stringlengths
0
14.7k
aioquic.connection/QuicConnection.__init__
Modified
aiortc~aioquic
93cc18fc683280ccff4d28c41aaab3ef68d85e00
[connection] add a ping() coroutine
<s>DatagramProtocol): def __init__( self, *, is_client: bool = True, certificate: Any = None, private_key: Any = None, alpn_protocols: Optional[List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: <0> if is_client: <1> assert ( <2> original_connection_id is None <3> ), "Cannot set original_connection_id for a client" <4> else: <5> assert certificate is not None, "SSL certificate is required for a server" <6> assert private_key is not None, "SSL private key is required for a server" <7> <8> self.alpn_protocols = alpn_protocols <9> self.certificate = certificate <10> self.is_client = is_client <11> self.host_cid = os.urandom(8) <12> self.peer_cid = os.urandom(8) <13> self.peer_cid_set = False <14> self.peer_token = b"" <15> self.private_key = private_key <16> self.secrets_log_file = secrets_log_file <17> self.server_name = server_name <18> self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} <19> <20> # counters for debugging <21> self._stateless_retry_count = 0 <22> self._version_negotiation_count = 0 <23> <24> self._loop = asyncio.get_event_loop() <25> self.__close: Optional[Dict] = None <26> self.__connected = asyncio.Event() <27> self.__epoch = tls.Epoch.INITIAL <28> self._local_idle_timeout = 60000 # milliseconds <29> self._local_max_data = 1048576 <30> self._local_max_data_used = 0 <31> self._local_max_stream_data</s>
===========below chunk 0=========== <s> def __init__( self, *, is_client: bool = True, certificate: Any = None, private_key: Any = None, alpn_protocols: Optional[List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 1 self._local_max_stream_data_bidi_remote = 1048576 self._local_max_stream_data_uni = 1048576 self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} ) self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._remote_idle_timeout = 0 # milliseconds self._remote_max_data = 0 self._remote_max_data_used = 0 self._remote_max_stream_data_bidi_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._spin_bit = False self._spin_bit_peer = False self._spin_highest_pn = 0 self.__send_pending_task: Optional[asyncio.Handle] = None self.__state = QuicConnectionState.FIRSTFLIGHT self._transport: Optional[asyncio.DatagramTransport] = None self._version: Optional[int] = None # callbacks if stream_handler is not None: self._stream_handler = stream_handler else: self._stream</s> ===========below chunk 1=========== <s> def __init__( self, *, is_client: bool = True, certificate: Any = None, private_key: Any = None, alpn_protocols: Optional[List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 2 <s> if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None # frame handlers self.__frame_handlers = [ self._handle_padding_frame, self._handle_padding_frame, self._handle_ack_frame, self._handle_ack_frame, self._handle_reset_stream_frame, self._handle_stop_sending_frame, self._handle_crypto_frame, self._handle_new_token_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_max_data_frame, self._handle_max_stream_data_frame, self._handle_max_streams_bidi_frame, self._handle_max_streams_uni_frame, self._handle_data_blocked_frame, self._handle_stream_data_blocked_frame, self._handle_streams_blocked_frame, self._handle_streams_blocked_frame, self._handle_new_connection_id_frame, self._handle_retire_</s> ===========below chunk 2=========== <s> def __init__( self, *, is_client: bool = True, certificate: Any = None, private_key: Any = None, alpn_protocols: Optional[List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 3 <s>id_frame, self._handle_path_challenge_frame, self._handle_path_response_frame, self._handle_connection_close_frame, self._handle_connection_close_frame, ] ===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.connection logger = logging.getLogger("quic") QuicConnectionAdapter(logger: Logger, extra: Mapping[str, Any]) QuicConnectionState() QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None) QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] at: aioquic.connection.QuicConnection supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20] _handle_ack_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_connection_close_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_crypto_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_data_blocked_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_max_data_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_max_stream_data_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_max_streams_bidi_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_max_streams_uni_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_new_connection_id_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_new_token_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None
aioquic.connection/QuicConnection._handle_ack_frame
Modified
aiortc~aioquic
93cc18fc683280ccff4d28c41aaab3ef68d85e00
[connection] add a ping() coroutine
<3>:<add> rangeset, _ = packet.pull_ack_frame(buf) <del> packet.pull_ack_frame(buf) <4>:<add> <add> # handle PING response <add> if ( <add> self._ping_packet_number is not None <add> and self._ping_packet_number in rangeset <add> ): <add> waiter = self._ping_waiter <add> self._ping_waiter = None <add> self._ping_packet_number = None <add> self._logger.info("Received PING response") <add> waiter.set_result(None) <add>
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _handle_ack_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle an ACK frame. <2> """ <3> packet.pull_ack_frame(buf) <4> if frame_type == QuicFrameType.ACK_ECN: <5> pull_uint_var(buf) <6> pull_uint_var(buf) <7> pull_uint_var(buf) <8>
===========unchanged ref 0=========== at: aioquic.connection QuicPacketSpace() at: aioquic.connection.QuicConnection.__init__ self.is_client = is_client self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} at: aioquic.connection.QuicConnection._initialize self.spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } at: aioquic.connection.QuicConnection._write_application self.packet_number += 1 at: aioquic.connection.QuicConnection._write_handshake self.packet_number += 1 at: aioquic.connection.QuicPacketSpace.__init__ self.crypto = CryptoPair() at: aioquic.crypto.CryptoPair setup_initial(cid: bytes, is_client: bool) -> None at: aioquic.stream QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0) at: aioquic.tls Epoch() ===========changed ref 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): + def ping(self) -> None: + """ + Pings the remote host and waits for the response. + """ + assert self._ping_waiter is None + self._ping_packet_number = None + self._ping_waiter = self._loop.create_future() + self._send_soon() + await asyncio.shield(self._ping_waiter) + ===========changed ref 1=========== # module: aioquic.rangeset class RangeSet(Sequence): + def __contains__(self, val: Any) -> bool: + for r in self.__ranges: + if val in r: + return True + return False + ===========changed ref 2=========== <s>DatagramProtocol): def __init__( self, *, is_client: bool = True, certificate: Any = None, private_key: Any = None, alpn_protocols: Optional[List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: if is_client: assert ( original_connection_id is None ), "Cannot set original_connection_id for a client" else: assert certificate is not None, "SSL certificate is required for a server" assert private_key is not None, "SSL private key is required for a server" self.alpn_protocols = alpn_protocols self.certificate = certificate self.is_client = is_client self.host_cid = os.urandom(8) self.peer_cid = os.urandom(8) self.peer_cid_set = False self.peer_token = b"" self.private_key = private_key self.secrets_log_file = secrets_log_file self.server_name = server_name self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} # counters for debugging self._stateless_retry_count = 0 self._version_negotiation_count = 0 self._loop = asyncio.get_event_loop() self.__close: Optional[Dict] = None self.__connected = asyncio.Event() self.__epoch = tls.Epoch.INITIAL self._local_idle_timeout = 60000 # milliseconds self._local_max_data = 1048576 self._local_max_data_used = 0 self._local_max_stream_data_bidi_local = 1048576 self._local_max_stream_data_bidi_remote = 1048576 self</s> ===========changed ref 3=========== <s> def __init__( self, *, is_client: bool = True, certificate: Any = None, private_key: Any = None, alpn_protocols: Optional[List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 1 <s>i_local = 1048576 self._local_max_stream_data_bidi_remote = 1048576 self._local_max_stream_data_uni = 1048576 self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} ) self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id + self._ping_packet_number: Optional[int] = None + self._ping_waiter: Optional[asyncio.Future[None]] = None self._remote_idle_timeout = 0 # milliseconds self._remote_max_data = 0 self._remote_max_data_used = 0 self._remote_max_stream_data_bidi_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._spin_bit = False self._spin_bit_peer = False self._spin_highest_pn = 0 self.__send_pending_task: Optional[asyncio.Handle] =</s> ===========changed ref 4=========== <s> def __init__( self, *, is_client: bool = True, certificate: Any = None, private_key: Any = None, alpn_protocols: Optional[List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 2 <s> self.__state = QuicConnectionState.FIRSTFLIGHT self._transport: Optional[asyncio.DatagramTransport] = None self._version: Optional[int] = None # callbacks if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None # frame handlers self.__frame_handlers = [ self._handle_padding_frame, self._handle_padding_frame, self._handle_ack_frame, self._handle_ack_frame, self._handle_reset_stream_frame, self._handle_stop_sending_frame, self._handle_crypto_frame, self._handle_new_token_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_max_data_frame, self._handle_max_stream_data_frame, self._handle_max_streams_bidi_frame, self._handle_max_streams_uni_frame, self._handle_data_blocked_frame, self._handle_stream_data_blocked_frame,</s>
aioquic.connection/QuicConnection._write_application
Modified
aiortc~aioquic
93cc18fc683280ccff4d28c41aaab3ef68d85e00
[connection] add a ping() coroutine
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _write_application(self, network_path: QuicNetworkPath) -> Iterator[bytes]: <0> epoch = tls.Epoch.ONE_RTT <1> space = self.spaces[epoch] <2> if not space.crypto.send.is_valid(): <3> return <4> <5> buf = Buffer(capacity=PACKET_MAX_SIZE) <6> capacity = buf.capacity - space.crypto.aead_tag_size <7> <8> while True: <9> # write header <10> push_uint8( <11> buf, <12> PACKET_FIXED_BIT <13> | (self._spin_bit << 5) <14> | (space.crypto.key_phase << 2) <15> | (PACKET_NUMBER_SEND_SIZE - 1), <16> ) <17> push_bytes(buf, self.peer_cid) <18> push_uint16(buf, self.packet_number) <19> header_size = buf.tell() <20> <21> # ACK <22> if self.send_ack[epoch] and space.ack_queue: <23> push_uint_var(buf, QuicFrameType.ACK) <24> packet.push_ack_frame(buf, space.ack_queue, 0) <25> self.send_ack[epoch] = False <26> <27> # PATH CHALLENGE <28> if ( <29> self.__epoch == tls.Epoch.ONE_RTT <30> and not network_path.is_validated <31> and network_path.local_challenge is None <32> ): <33> self._logger.info( <34> "Network path %s sending challenge", network_path.addr <35> ) <36> network_path.local_challenge = os.urandom(8) <37> push_uint_var(buf, QuicFrameType.PATH_CHALLENGE) <38> push_bytes(buf, network_path.local_challenge) <39> <40> # PATH RESPONSE <41> if network_path.remote_challenge is not None: <42> push_uint_var(</s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _write_application(self, network_path: QuicNetworkPath) -> Iterator[bytes]: # offset: 1 push_bytes(buf, network_path.remote_challenge) network_path.remote_challenge = None # CLOSE if self.__close and self.__epoch == epoch: push_close(buf, **self.__close) self.__close = None # STREAM for stream_id, stream in self.streams.items(): if isinstance(stream_id, int): # the frame data size is constrained by our peer's MAX_DATA and # the space available in the current packet frame_overhead = ( 3 + quic_uint_length(stream_id) + ( quic_uint_length(stream._send_start) if stream._send_start else 0 ) ) frame = stream.get_frame( min( capacity - buf.tell() - frame_overhead, self._remote_max_data - self._remote_max_data_used, ) ) if frame is not None: flags = QuicStreamFlag.LEN if frame.offset: flags |= QuicStreamFlag.OFF if frame.fin: flags |= QuicStreamFlag.FIN push_uint_var(buf, QuicFrameType.STREAM_BASE | flags) with push_stream_frame(buf, stream_id, frame.offset): push_bytes(buf, frame.data) self._remote_max_data_used += len(frame.data) packet_size = buf.tell() if packet_size > header_size: # encrypt data = buf.data yield space.crypto.encrypt_packet( data[0:header_size], data[header_size:packet_size] ) self.packet_number += 1 buf.seek(0) else: break ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) push_bytes(buf: Buffer, v: bytes) -> None push_uint8(buf: Buffer, v: int) -> None push_uint16(buf: Buffer, v: int) -> None at: aioquic.buffer.Buffer tell() -> int at: aioquic.connection PACKET_MAX_SIZE = 1280 SECRETS_LABELS = [ [ None, "QUIC_CLIENT_EARLY_TRAFFIC_SECRET", "QUIC_CLIENT_HANDSHAKE_TRAFFIC_SECRET", "QUIC_CLIENT_TRAFFIC_SECRET_0", ], [ None, None, "QUIC_SERVER_HANDSHAKE_TRAFFIC_SECRET", "QUIC_SERVER_TRAFFIC_SECRET_0", ], ] push_close(buf: Buffer, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None stream_is_client_initiated(stream_id: int) -> bool stream_is_unidirectional(stream_id: int) -> bool QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None) at: aioquic.connection.QuicConnection.__init__ self.is_client = is_client self.peer_cid = os.urandom(8) self.secrets_log_file = secrets_log_file self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} self.__close: Optional[Dict] = None self.__epoch = tls.Epoch.INITIAL ===========unchanged ref 1=========== self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} ) self._ping_packet_number: Optional[int] = None self._ping_waiter: Optional[asyncio.Future[None]] = None self._spin_bit = False at: aioquic.connection.QuicConnection._handle_ack_frame self._ping_waiter = None self._ping_packet_number = None at: aioquic.connection.QuicConnection._handle_crypto_frame self.__epoch = tls.Epoch.ONE_RTT self.__epoch = tls.Epoch.HANDSHAKE at: aioquic.connection.QuicConnection._initialize self.tls = tls.Context(is_client=self.is_client, logger=self._logger) self.send_ack = { tls.Epoch.INITIAL: False, tls.Epoch.HANDSHAKE: False, tls.Epoch.ONE_RTT: False, } self.spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self.packet_number = 0 at: aioquic.connection.QuicConnection._write_application self.packet_number += 1 at: aioquic.connection.QuicConnection._write_handshake self.__close = None self.packet_number += 1 at: aioquic.connection.QuicConnection.close self.__close = { "error_code": error_code, "frame_type": frame_type, "reason_phrase": reason_phrase, } at: aioquic.connection.QuicConnection.datagram_received self.peer_cid = header.source_cid self._spin_bit = self._spin_bit_peer self._spin_bit = not self._spin_bit_peer
tests.test_high_level/HighLevelTest.test_ping
Modified
aiortc~aioquic
773a0645acf2638beabc21f592212b07db01a8d7
[connection] add tentative API to trigger key update
<2>:<add> await client.ping()
# module: tests.test_high_level class HighLevelTest(TestCase): def test_ping(self): <0> async def run_client_ping(host, **kwargs): <1> async with connect(host, 4433, **kwargs) as client: <2> await client.ping() <3> <4> run( <5> asyncio.gather( <6> run_server(stateless_retry=False), run_client_ping("127.0.0.1") <7> ) <8> ) <9>
===========unchanged ref 0=========== at: aioquic.client connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnection, None] at: aioquic.connection.QuicConnection supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20] ping() -> None ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_high_level run_server(stateless_retry) at: tests.utils run(coro) ===========changed ref 0=========== # module: tests.test_high_level class HighLevelTest(TestCase): + def test_key_update(self): + async def run_client_key_update(host, **kwargs): + async with connect(host, 4433, **kwargs) as client: + await client.ping() + client.request_key_update() + await client.ping() + + run( + asyncio.gather( + run_server(stateless_retry=False), run_client_key_update("127.0.0.1") + ) + ) + ===========changed ref 1=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): + def request_key_update(self) -> None: + """ + Request an update of the encryption keys. + """ + if self.__epoch == tls.Epoch.ONE_RTT: + self.spaces[tls.Epoch.ONE_RTT].crypto.update_key() +
aioquic.connection/QuicConnection._write_application
Modified
aiortc~aioquic
0a61cd6999badbebf9304aca0e41613ff301eba2
[connection] ensure packets have sufficient padding
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _write_application(self, network_path: QuicNetworkPath) -> Iterator[bytes]: <0> epoch = tls.Epoch.ONE_RTT <1> space = self.spaces[epoch] <2> if not space.crypto.send.is_valid(): <3> return <4> <5> buf = Buffer(capacity=PACKET_MAX_SIZE) <6> capacity = buf.capacity - space.crypto.aead_tag_size <7> <8> while True: <9> # write header <10> push_uint8( <11> buf, <12> PACKET_FIXED_BIT <13> | (self._spin_bit << 5) <14> | (space.crypto.key_phase << 2) <15> | (PACKET_NUMBER_SEND_SIZE - 1), <16> ) <17> push_bytes(buf, self.peer_cid) <18> push_uint16(buf, self.packet_number) <19> header_size = buf.tell() <20> <21> # ACK <22> if self.send_ack[epoch] and space.ack_queue: <23> push_uint_var(buf, QuicFrameType.ACK) <24> packet.push_ack_frame(buf, space.ack_queue, 0) <25> self.send_ack[epoch] = False <26> <27> # PATH CHALLENGE <28> if ( <29> self.__epoch == tls.Epoch.ONE_RTT <30> and not network_path.is_validated <31> and network_path.local_challenge is None <32> ): <33> self._logger.info( <34> "Network path %s sending challenge", network_path.addr <35> ) <36> network_path.local_challenge = os.urandom(8) <37> push_uint_var(buf, QuicFrameType.PATH_CHALLENGE) <38> push_bytes(buf, network_path.local_challenge) <39> <40> # PATH RESPONSE <41> if network_path.remote_challenge is not None: <42> push_uint_var(</s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _write_application(self, network_path: QuicNetworkPath) -> Iterator[bytes]: # offset: 1 push_bytes(buf, network_path.remote_challenge) network_path.remote_challenge = None # PING if self._ping_waiter is not None and self._ping_packet_number is None: self._ping_packet_number = self.packet_number self._logger.info("Sending PING in packet %d", self.packet_number) push_uint_var(buf, QuicFrameType.PING) # CLOSE if self.__close and self.__epoch == epoch: push_close(buf, **self.__close) self.__close = None # STREAM for stream_id, stream in self.streams.items(): if isinstance(stream_id, int): # the frame data size is constrained by our peer's MAX_DATA and # the space available in the current packet frame_overhead = ( 3 + quic_uint_length(stream_id) + ( quic_uint_length(stream._send_start) if stream._send_start else 0 ) ) frame = stream.get_frame( min( capacity - buf.tell() - frame_overhead, self._remote_max_data - self._remote_max_data_used, ) ) if frame is not None: flags = QuicStreamFlag.LEN if frame.offset: flags |= QuicStreamFlag.OFF if frame.fin: flags |= QuicStreamFlag.FIN push_uint_var(buf, QuicFrameType.STREAM_BASE | flags) with push_stream_frame(buf, stream_id, frame.offset): push_bytes(buf, frame.data) self._remote_max_data_used += len(frame.data) packet_size = buf.tell() if</s> ===========below chunk 1=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _write_application(self, network_path: QuicNetworkPath) -> Iterator[bytes]: # offset: 2 <s>._remote_max_data_used += len(frame.data) packet_size = buf.tell() if packet_size > header_size: # encrypt data = buf.data yield space.crypto.encrypt_packet( data[0:header_size], data[header_size:packet_size] ) self.packet_number += 1 buf.seek(0) else: break ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) push_bytes(buf: Buffer, v: bytes) -> None push_uint8(buf: Buffer, v: int) -> None push_uint16(buf: Buffer, v: int) -> None at: aioquic.buffer.Buffer tell() -> int at: aioquic.connection PACKET_MAX_SIZE = 1280 push_close(buf: Buffer, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None) at: aioquic.connection.QuicConnection supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20] at: aioquic.connection.QuicConnection.__init__ self.peer_cid = os.urandom(8) self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} self.__close: Optional[Dict] = None self.__epoch = tls.Epoch.INITIAL self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} ) self._ping_packet_number: Optional[int] = None self._ping_waiter: Optional[asyncio.Future[None]] = None self._remote_max_data = 0 self._remote_max_data_used = 0 self._spin_bit = False at: aioquic.connection.QuicConnection._handle_ack_frame self._ping_waiter = None self._ping_packet_number = None ===========unchanged ref 1=========== at: aioquic.connection.QuicConnection._handle_crypto_frame self.__epoch = tls.Epoch.ONE_RTT self.__epoch = tls.Epoch.HANDSHAKE at: aioquic.connection.QuicConnection._handle_max_data_frame self._remote_max_data = max_data at: aioquic.connection.QuicConnection._initialize self.send_ack = { tls.Epoch.INITIAL: False, tls.Epoch.HANDSHAKE: False, tls.Epoch.ONE_RTT: False, } self.spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self.packet_number = 0 at: aioquic.connection.QuicConnection._write_application self.packet_number += 1 at: aioquic.connection.QuicConnection._write_handshake self.__close = None self.packet_number += 1 at: aioquic.connection.QuicConnection.close self.__close = { "error_code": error_code, "frame_type": frame_type, "reason_phrase": reason_phrase, } at: aioquic.connection.QuicConnection.datagram_received self.peer_cid = header.source_cid self._spin_bit = self._spin_bit_peer self._spin_bit = not self._spin_bit_peer at: aioquic.connection.QuicConnection.ping self._ping_packet_number = None self._ping_waiter = self._loop.create_future() at: aioquic.connection.QuicNetworkPath addr: NetworkAddress bytes_received: int = 0 bytes_sent: int = 0 is_validated: bool = False local_challenge: Optional[bytes] = None remote_challenge: Optional[bytes] = None
examples.interop/run
Modified
aiortc~aioquic
7d3fc46d691e8cc765e28e9adb72400036a5b0ce
[interop] add key update test to interop script
<0>:<del> results = [] <1>:<del> for name, host, port, path in IMPLEMENTATIONS: <2>:<del> if not only or name == only: <3>:<del> result = await run_one(name, host, port, path, **kwargs) <4>:<del> results.append((name, result)) <5>:<del> print("\n%s%s%s" % (name, " " * (20 - len(name)), result)) <6>:<add> configs = list(filter(lambda x: not only or x.name == only, CONFIGS)) <7>:<add> for config in configs: <add> for test_name, test_func in filter( <add> lambda x: x[0].startswith("test_"), globals().items() <add> ): <add> print("\n=== %s %s ===\n" % (config.name, test_name)) <add> try: <add> await asyncio.wait_for(test_func(config, **kwargs), timeout=5) <add> except asyncio.TimeoutError: <add> pass <del> # print results <8>:<add> print("") <del> print("") <9>:<del> for name, result in results: <10>:<del> print("%s%s%s" % (name, " " * (20 - len(name)), result)) <11>:<add> print_result(config)
# module: examples.interop def run(only=None, **kwargs): <0> results = [] <1> for name, host, port, path in IMPLEMENTATIONS: <2> if not only or name == only: <3> result = await run_one(name, host, port, path, **kwargs) <4> results.append((name, result)) <5> print("\n%s%s%s" % (name, " " * (20 - len(name)), result)) <6> <7> # print results <8> print("") <9> for name, result in results: <10> print("%s%s%s" % (name, " " * (20 - len(name)), result)) <11>
===========unchanged ref 0=========== at: aioquic.client connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnection, None] at: aioquic.connection.QuicConnection supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20] ping() -> None request_key_update() -> None at: asyncio.tasks wait_for(fut: _FutureT[_T], timeout: Optional[float], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T] at: examples.interop Result() ===========changed ref 0=========== # module: examples.interop + def test_handshake_and_close(config, **kwargs): + async with aioquic.connect(config.host, config.port, **kwargs) as connection: + config.result |= Result.H + if connection._stateless_retry_count == 1: + config.result |= Result.S + config.result |= Result.C + ===========changed ref 1=========== # module: examples.interop + def test_key_update(config, **kwargs): + async with aioquic.connect(config.host, config.port, **kwargs) as connection: + # cause some traffic + await connection.ping() + + # request key update + connection.request_key_update() + + # cause more traffic + await asyncio.wait_for(connection.ping(), timeout=5) + + config.result |= Result.U + ===========changed ref 2=========== # module: examples.interop + def test_version_negotiation(config, **kwargs): + async with aioquic.connect( + config.host, config.port, protocol_version=0x1A2A3A4A, **kwargs + ) as connection: + if connection._version_negotiation_count == 1: + config.result |= Result.V + ===========changed ref 3=========== # module: examples.interop + def test_data_transfer(config, **kwargs): + if config.path is None: + return + + async with aioquic.connect(config.host, config.port, **kwargs) as connection: + response1 = await http_request(connection, config.path) + response2 = await http_request(connection, config.path) + + if response1 and response2: + config.result |= Result.D + ===========changed ref 4=========== # module: examples.interop + def http_request(connection, path): + # perform HTTP/0.9 request + reader, writer = await connection.create_stream() + writer.write(("GET %s\r\n" % path).encode("utf8")) + writer.write_eof() + + return await reader.read() + ===========changed ref 5=========== # module: examples.interop + @dataclass + class Config: + name: str + host: str + port: int + path: str + result: Result = field(default_factory=lambda: Result(0)) + ===========changed ref 6=========== # module: examples.interop - def run_one(name, host, port, hq_path, **kwargs): - result = Result(0) - - print("\n==== %s ====\n" % name) - - # version negotiation - async with aioquic.connect( - host, port, protocol_version=0x1A2A3A4A, **kwargs - ) as connection: - if connection._version_negotiation_count == 1: - result |= Result.V - - # handshake + close - async with aioquic.connect(host, port, **kwargs) as connection: - result |= Result.H - result |= Result.C - if connection._stateless_retry_count == 1: - result |= Result.S - - # data transfer - if hq_path is not None: - async with aioquic.connect(host, port, **kwargs) as connection: - # perform HTTP/0.9 request - reader, writer = await connection.create_stream() - writer.write(("GET %s\r\n" % hq_path).encode("utf8")) - writer.write_eof() - - response1 = await reader.read() - - # perform HTTP/0.9 request - reader, writer = await connection.create_stream() - writer.write(("GET %s\r\n" % hq_path).encode("utf8")) - writer.write_eof() - - response2 = await reader.read() - - if response1 and response2: - result |= Result.D - - # spin bit - async with aioquic.connect(host, port, **kwargs) as connection: - spin_bits = set() - for i in range(4): - reader, writer = await connection.create_stream() - writer.write_eof() - await asyncio.sleep(0.5) - spin_bits.add(connection._spin_bit_peer</s> ===========changed ref 7=========== # module: examples.interop - def run_one(name, host, port, hq_path, **kwargs): # offset: 1 <s>eof() - await asyncio.sleep(0.5) - spin_bits.add(connection._spin_bit_peer) - if len(spin_bits) == 2: - result |= Result.P - - return result - ===========changed ref 8=========== # module: examples.interop + CONFIGS = [ - IMPLEMENTATIONS = [ + Config("aioquic", "quic.aiortc.org", 4434, "/"), - ("aioquic", "quic.aiortc.org", 4434, "/"), + Config("ats", "quic.ogre.com", 4434, "/"), - ("ats", "quic.ogre.com", 4434, "/"), + Config("f5", "208.85.208.226", 4433, "/"), - ("f5", "208.85.208.226", 4433, "/"), + Config("lsquic", "http3-test.litespeedtech.com", 4434, None), - ("lsquic", "http3-test.litespeedtech.com", 4434, None), + Config("mvfst", "fb.mvfst.net", 4433, "/"), - ("mvfst", "fb.mvfst.net", 4433, "/"), + Config("ngtcp2", "nghttp2.org", 4434, None), - ("ngtcp2", "nghttp2.org", 4434, None), + Config("ngx_quic", "cloudflare-quic.com", 443, None), - ("ngx_quic", "cloudflare-quic.com", 443, None), + Config("picoquic", "test.privateoctopus.com", 4434, "/"), - ("picoquic", "test.privateoctopus.com", 4434, "/"), + Config("quant", "quant.eggert.org", 4434, "/"), - ("quant", "quant.eggert.org", 4434, "/"), + Config("quic-go", "quic.seemann.io", 443, "/"), - ("quic-go", "quic.seemann.io", 443, "/"), + Config("quiche", "quic.tech", 4433, "/"), - ("quiche", "quic.</s>
examples.interop/test_key_update
Modified
aiortc~aioquic
b651bfb632025280f78d4ba2f0c645a99b9d236e
[interop] add more servers
<8>:<add> await connection.ping() <del> await asyncio.wait_for(connection.ping(), timeout=5)
# module: examples.interop def test_key_update(config, **kwargs): <0> async with aioquic.connect(config.host, config.port, **kwargs) as connection: <1> # cause some traffic <2> await connection.ping() <3> <4> # request key update <5> connection.request_key_update() <6> <7> # cause more traffic <8> await asyncio.wait_for(connection.ping(), timeout=5) <9> <10> config.result |= Result.U <11>
===========unchanged ref 0=========== at: aioquic.client connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnection, None] at: aioquic.connection.QuicConnection supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20] ping() -> None request_key_update() -> None ===========changed ref 0=========== # module: examples.interop CONFIGS = [ Config("aioquic", "quic.aiortc.org", 4434, "/"), Config("ats", "quic.ogre.com", 4434, "/"), Config("f5", "208.85.208.226", 4433, "/"), + Config("gquic", "quic.rocks", 4433, "/"), Config("lsquic", "http3-test.litespeedtech.com", 4434, None), Config("mvfst", "fb.mvfst.net", 4433, "/"), Config("ngtcp2", "nghttp2.org", 4434, None), Config("ngx_quic", "cloudflare-quic.com", 443, None), + Config("pandora", "pandora.cm.in.tum.de", 4433, "/"), Config("picoquic", "test.privateoctopus.com", 4434, "/"), Config("quant", "quant.eggert.org", 4434, "/"), Config("quic-go", "quic.seemann.io", 443, "/"), Config("quiche", "quic.tech", 4433, "/"), Config("quicker", "quicker.edm.uhasselt.be", 4433, "/"), Config("quicly", "kazuhooku.com", 4434, "/"), Config("quinn", "ralith.com", 4433, "/"), Config("winquic", "quic.westus.cloudapp.azure.com", 4434, "/"), ]
aioquic.tls/pull_key_share
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<1>:<del> data_length = pull_uint16(buf) <2>:<del> data = pull_bytes(buf, data_length) <3>:<add> data = pull_opaque(buf, 2)
# module: aioquic.tls def pull_key_share(buf: Buffer) -> KeyShareEntry: <0> group = pull_group(buf) <1> data_length = pull_uint16(buf) <2> data = pull_bytes(buf, data_length) <3> return (group, data) <4>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) pull_bytes(buf: Buffer, length: int) -> bytes ===========changed ref 0=========== # module: aioquic.tls # KeyShareEntry KeyShareEntry = Tuple[Group, bytes] + # PRE SHARED KEY + + PskIdentity = Tuple[bytes, int] + ===========changed ref 1=========== # module: aioquic.tls + def pull_opaque(buf: Buffer, capacity: int) -> bytes: + """ + Pull an opaque value prefixed by a length. + """ + with pull_block(buf, capacity) as length: + return pull_bytes(buf, length) +
aioquic.tls/push_key_share
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<1>:<del> with push_block(buf, 2): <2>:<add> push_opaque(buf, 2, value[1]) <del> push_bytes(buf, value[1])
# module: aioquic.tls def push_key_share(buf: Buffer, value: KeyShareEntry) -> None: <0> push_group(buf, value[0]) <1> with push_block(buf, 2): <2> push_bytes(buf, value[1]) <3>
===========unchanged ref 0=========== at: aioquic.buffer push_bytes(buf: Buffer, v: bytes) -> None at: aioquic.tls push_block(buf: Buffer, capacity: int) -> Generator ===========changed ref 0=========== # module: aioquic.tls + def push_opaque(buf: Buffer, capacity: int, value: bytes) -> None: + """ + Push an opaque value prefix by a length. + """ + with push_block(buf, capacity): + push_bytes(buf, value) + ===========changed ref 1=========== # module: aioquic.tls # KeyShareEntry KeyShareEntry = Tuple[Group, bytes] + # PRE SHARED KEY + + PskIdentity = Tuple[bytes, int] + ===========changed ref 2=========== # module: aioquic.tls + def pull_opaque(buf: Buffer, capacity: int) -> bytes: + """ + Pull an opaque value prefixed by a length. + """ + with pull_block(buf, capacity) as length: + return pull_bytes(buf, length) + ===========changed ref 3=========== # module: aioquic.tls def pull_key_share(buf: Buffer) -> KeyShareEntry: group = pull_group(buf) - data_length = pull_uint16(buf) - data = pull_bytes(buf, data_length) + data = pull_opaque(buf, 2) return (group, data)
aioquic.tls/pull_alpn_protocol
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<0>:<del> length = pull_uint8(buf) <1>:<add> return pull_opaque(buf, 1).decode("ascii") <del> return pull_bytes(buf, length).decode("ascii")
# module: aioquic.tls # ALPN def pull_alpn_protocol(buf: Buffer) -> str: <0> length = pull_uint8(buf) <1> return pull_bytes(buf, length).decode("ascii") <2>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_group(buf: Buffer) -> Group at: typing Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') ===========changed ref 0=========== # module: aioquic.tls + def push_opaque(buf: Buffer, capacity: int, value: bytes) -> None: + """ + Push an opaque value prefix by a length. + """ + with push_block(buf, capacity): + push_bytes(buf, value) + ===========changed ref 1=========== # module: aioquic.tls # KeyShareEntry KeyShareEntry = Tuple[Group, bytes] + # PRE SHARED KEY + + PskIdentity = Tuple[bytes, int] + ===========changed ref 2=========== # module: aioquic.tls def push_key_share(buf: Buffer, value: KeyShareEntry) -> None: push_group(buf, value[0]) - with push_block(buf, 2): + push_opaque(buf, 2, value[1]) - push_bytes(buf, value[1]) ===========changed ref 3=========== # module: aioquic.tls + def pull_opaque(buf: Buffer, capacity: int) -> bytes: + """ + Pull an opaque value prefixed by a length. + """ + with pull_block(buf, capacity) as length: + return pull_bytes(buf, length) + ===========changed ref 4=========== # module: aioquic.tls def pull_key_share(buf: Buffer) -> KeyShareEntry: group = pull_group(buf) - data_length = pull_uint16(buf) - data = pull_bytes(buf, data_length) + data = pull_opaque(buf, 2) return (group, data)
aioquic.tls/push_alpn_protocol
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<0>:<del> data = protocol.encode("ascii") <1>:<del> push_uint8(buf, len(data)) <2>:<del> push_bytes(buf, data) <3>:<add> push_opaque(buf, 1, protocol.encode("ascii"))
# module: aioquic.tls def push_alpn_protocol(buf: Buffer, protocol: str) -> None: <0> data = protocol.encode("ascii") <1> push_uint8(buf, len(data)) <2> push_bytes(buf, data) <3>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls push_group = push_uint16 KeyShareEntry = Tuple[Group, bytes] ===========changed ref 0=========== # module: aioquic.tls # ALPN def pull_alpn_protocol(buf: Buffer) -> str: - length = pull_uint8(buf) + return pull_opaque(buf, 1).decode("ascii") - return pull_bytes(buf, length).decode("ascii") ===========changed ref 1=========== # module: aioquic.tls + def push_opaque(buf: Buffer, capacity: int, value: bytes) -> None: + """ + Push an opaque value prefix by a length. + """ + with push_block(buf, capacity): + push_bytes(buf, value) + ===========changed ref 2=========== # module: aioquic.tls # KeyShareEntry KeyShareEntry = Tuple[Group, bytes] + # PRE SHARED KEY + + PskIdentity = Tuple[bytes, int] + ===========changed ref 3=========== # module: aioquic.tls def push_key_share(buf: Buffer, value: KeyShareEntry) -> None: push_group(buf, value[0]) - with push_block(buf, 2): + push_opaque(buf, 2, value[1]) - push_bytes(buf, value[1]) ===========changed ref 4=========== # module: aioquic.tls + def pull_opaque(buf: Buffer, capacity: int) -> bytes: + """ + Pull an opaque value prefixed by a length. + """ + with pull_block(buf, capacity) as length: + return pull_bytes(buf, length) + ===========changed ref 5=========== # module: aioquic.tls def pull_key_share(buf: Buffer) -> KeyShareEntry: group = pull_group(buf) - data_length = pull_uint16(buf) - data = pull_bytes(buf, data_length) + data = pull_opaque(buf, 2) return (group, data)
aioquic.tls/pull_client_hello
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<4>:<del> session_id_length = pull_uint8(buf) <8>:<add> session_id=pull_opaque(buf, 1), <del> session_id=pull_bytes(buf, session_id_length), <14>:<add> after_psk = False <add> <15>:<add> # pre_shared_key MUST be last <add> nonlocal after_psk <add> assert not after_psk <add> <30>:<del> with pull_block(buf, 2) as length: <31>:<add> hello.server_name = pull_opaque(buf, 2).decode("ascii") <del> hello.server_name = pull_bytes(
# module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: <0> assert pull_uint8(buf) == HandshakeType.CLIENT_HELLO <1> with pull_block(buf, 3): <2> assert pull_uint16(buf) == TLS_VERSION_1_2 <3> client_random = pull_bytes(buf, 32) <4> session_id_length = pull_uint8(buf) <5> <6> hello = ClientHello( <7> random=client_random, <8> session_id=pull_bytes(buf, session_id_length), <9> cipher_suites=pull_list(buf, 2, pull_cipher_suite), <10> compression_methods=pull_list(buf, 1, pull_compression_method), <11> ) <12> <13> # extensions <14> def pull_extension(buf: Buffer) -> None: <15> extension_type = pull_uint16(buf) <16> extension_length = pull_uint16(buf) <17> if extension_type == ExtensionType.KEY_SHARE: <18> hello.key_share = pull_list(buf, 2, pull_key_share) <19> elif extension_type == ExtensionType.SUPPORTED_VERSIONS: <20> hello.supported_versions = pull_list(buf, 1, pull_uint16) <21> elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS: <22> hello.signature_algorithms = pull_list(buf, 2, pull_signature_algorithm) <23> elif extension_type == ExtensionType.SUPPORTED_GROUPS: <24> hello.supported_groups = pull_list(buf, 2, pull_group) <25> elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES: <26> hello.key_exchange_modes = pull_list(buf, 1, pull_key_exchange_mode) <27> elif extension_type == ExtensionType.SERVER_NAME: <28> with pull_block(buf, 2): <29> assert pull_uint8(buf) == 0 <30> with pull_block(buf, 2) as length: <31> hello.server_name = pull_bytes(</s>
===========below chunk 0=========== # module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: # offset: 1 elif extension_type == ExtensionType.ALPN: hello.alpn_protocols = pull_list(buf, 2, pull_alpn_protocol) else: hello.other_extensions.append( (extension_type, pull_bytes(buf, extension_length)) ) pull_list(buf, 2, pull_extension) return hello ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) pull_bytes(buf: Buffer, length: int) -> bytes push_bytes(buf: Buffer, v: bytes) -> None pull_uint16(buf: Buffer) -> int at: aioquic.tls CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeyExchangeMode(x: Union[str, bytes, bytearray], base: int) KeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) push_extension(buf: Buffer, extension_type: int) -> Generator KeyShareEntry = Tuple[Group, bytes] PskIdentity = Tuple[bytes, int] ===========unchanged ref 1=========== at: dataclasses field(*, default_factory: Callable[[], _T], init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> _T field(*, init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> Any field(*, default: _T, init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> _T dataclass(*, init: bool=..., repr: bool=..., eq: bool=..., order: bool=..., unsafe_hash: bool=..., frozen: bool=...) -> Callable[[Type[_T]], Type[_T]] dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]] dataclass(_cls: Type[_T]) -> Type[_T] at: typing Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.tls + def push_psk_binder(buf: Buffer, binder: bytes) -> None: + push_opaque(buf, 1, binder) + ===========changed ref 1=========== # module: aioquic.tls + def pull_psk_binder(buf: Buffer) -> bytes: + return pull_opaque(buf, 1) + ===========changed ref 2=========== # module: aioquic.tls + def push_psk_identity(buf: Buffer, entry: PskIdentity) -> None: + push_opaque(buf, 2, entry[0]) + push_uint32(buf, entry[1]) + ===========changed ref 3=========== # module: aioquic.tls + def pull_psk_identity(buf: Buffer) -> PskIdentity: + identity = pull_opaque(buf, 2) + obfuscated_ticket_age = pull_uint32(buf) + return (identity, obfuscated_ticket_age) + ===========changed ref 4=========== # module: aioquic.tls # ALPN def pull_alpn_protocol(buf: Buffer) -> str: - length = pull_uint8(buf) + return pull_opaque(buf, 1).decode("ascii") - return pull_bytes(buf, length).decode("ascii") ===========changed ref 5=========== # module: aioquic.tls def push_alpn_protocol(buf: Buffer, protocol: str) -> None: - data = protocol.encode("ascii") - push_uint8(buf, len(data)) - push_bytes(buf, data) + push_opaque(buf, 1, protocol.encode("ascii")) ===========changed ref 6=========== # module: aioquic.tls + def push_opaque(buf: Buffer, capacity: int, value: bytes) -> None: + """ + Push an opaque value prefix by a length. + """ + with push_block(buf, capacity): + push_bytes(buf, value) + ===========changed ref 7=========== # module: aioquic.tls # KeyShareEntry KeyShareEntry = Tuple[Group, bytes] + # PRE SHARED KEY + + PskIdentity = Tuple[bytes, int] + ===========changed ref 8=========== # module: aioquic.tls def push_key_share(buf: Buffer, value: KeyShareEntry) -> None: push_group(buf, value[0]) - with push_block(buf, 2): + push_opaque(buf, 2, value[1]) - push_bytes(buf, value[1]) ===========changed ref 9=========== # module: aioquic.tls + def pull_opaque(buf: Buffer, capacity: int) -> bytes: + """ + Pull an opaque value prefixed by a length. + """ + with pull_block(buf, capacity) as length: + return pull_bytes(buf, length) + ===========changed ref 10=========== # module: aioquic.tls def pull_key_share(buf: Buffer) -> KeyShareEntry: group = pull_group(buf) - data_length = pull_uint16(buf) - data = pull_bytes(buf, data_length) + data = pull_opaque(buf, 2) return (group, data) ===========changed ref 11=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None + pre_shared_key: Optional[OfferedPsks] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list)
aioquic.tls/push_client_hello
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<4>:<del> with push_block(buf, 1): <5>:<add> push_opaque(buf, 1, hello.session_id) <del> push_bytes(buf, hello.session_id) <30>:<del> with push_block(buf, 2): <31>:<add> push_opaque(buf, 2, hello.server_name.encode("ascii")) <del> push_bytes(buf, hello.server_name.encode("ascii"))
# module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: <0> push_uint8(buf, HandshakeType.CLIENT_HELLO) <1> with push_block(buf, 3): <2> push_uint16(buf, TLS_VERSION_1_2) <3> push_bytes(buf, hello.random) <4> with push_block(buf, 1): <5> push_bytes(buf, hello.session_id) <6> push_list(buf, 2, push_cipher_suite, hello.cipher_suites) <7> push_list(buf, 1, push_compression_method, hello.compression_methods) <8> <9> # extensions <10> with push_block(buf, 2): <11> with push_extension(buf, ExtensionType.KEY_SHARE): <12> push_list(buf, 2, push_key_share, hello.key_share) <13> <14> with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): <15> push_list(buf, 1, push_uint16, hello.supported_versions) <16> <17> with push_extension(buf, ExtensionType.SIGNATURE_ALGORITHMS): <18> push_list(buf, 2, push_signature_algorithm, hello.signature_algorithms) <19> <20> with push_extension(buf, ExtensionType.SUPPORTED_GROUPS): <21> push_list(buf, 2, push_group, hello.supported_groups) <22> <23> with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): <24> push_list(buf, 1, push_key_exchange_mode, hello.key_exchange_modes) <25> <26> if hello.server_name is not None: <27> with push_extension(buf, ExtensionType.SERVER_NAME): <28> with push_block(buf, 2): <29> push_uint8(buf, 0) <30> with push_block(buf, 2): <31> push_bytes(buf, hello.server_name.encode("ascii")) <32> <33> if hello.alpn_protocols is not None: <34> with</s>
===========below chunk 0=========== # module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: # offset: 1 push_list(buf, 2, push_alpn_protocol, hello.alpn_protocols) for extension_type, extension_value in hello.other_extensions: with push_extension(buf, extension_type): push_bytes(buf, extension_value) ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) pull_bytes(buf: Buffer, length: int) -> bytes pull_uint8(buf: Buffer) -> int pull_uint16(buf: Buffer) -> int at: aioquic.tls TLS_VERSION_1_2 = 0x0303 ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_cipher_suite(buf: Buffer) -> CipherSuite pull_compression_method(buf: Buffer) -> CompressionMethod pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode pull_group(buf: Buffer) -> Group pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm pull_block(buf: Buffer, capacity: int) -> Generator pull_list(buf: Buffer, capacity: int, func: Callable[[Buffer], T]) -> List[T] pull_opaque(buf: Buffer, capacity: int) -> bytes pull_key_share(buf: Buffer) -> KeyShareEntry pull_alpn_protocol(buf: Buffer) -> str pull_psk_identity(buf: Buffer) -> PskIdentity pull_psk_binder(buf: Buffer) -> bytes OfferedPsks(identities: List[PskIdentity], binders: List[bytes]) ===========unchanged ref 1=========== ClientHello(random: bytes, session_id: bytes, cipher_suites: List[CipherSuite], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, key_exchange_modes: Optional[List[KeyExchangeMode]]=None, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list)) at: aioquic.tls.ClientHello alpn_protocols: Optional[List[str]] = None key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None ===========changed ref 0=========== # module: aioquic.tls + @dataclass + class OfferedPsks: + identities: List[PskIdentity] + binders: List[bytes] + ===========changed ref 1=========== # module: aioquic.tls + def pull_psk_binder(buf: Buffer) -> bytes: + return pull_opaque(buf, 1) + ===========changed ref 2=========== # module: aioquic.tls + def pull_psk_identity(buf: Buffer) -> PskIdentity: + identity = pull_opaque(buf, 2) + obfuscated_ticket_age = pull_uint32(buf) + return (identity, obfuscated_ticket_age) + ===========changed ref 3=========== # module: aioquic.tls # ALPN def pull_alpn_protocol(buf: Buffer) -> str: - length = pull_uint8(buf) + return pull_opaque(buf, 1).decode("ascii") - return pull_bytes(buf, length).decode("ascii") ===========changed ref 4=========== # module: aioquic.tls + def pull_opaque(buf: Buffer, capacity: int) -> bytes: + """ + Pull an opaque value prefixed by a length. + """ + with pull_block(buf, capacity) as length: + return pull_bytes(buf, length) + ===========changed ref 5=========== # module: aioquic.tls def pull_key_share(buf: Buffer) -> KeyShareEntry: group = pull_group(buf) - data_length = pull_uint16(buf) - data = pull_bytes(buf, data_length) + data = pull_opaque(buf, 2) return (group, data) ===========changed ref 6=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None + pre_shared_key: Optional[OfferedPsks] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) ===========changed ref 7=========== # module: aioquic.tls + def push_psk_binder(buf: Buffer, binder: bytes) -> None: + push_opaque(buf, 1, binder) + ===========changed ref 8=========== # module: aioquic.tls + def push_psk_identity(buf: Buffer, entry: PskIdentity) -> None: + push_opaque(buf, 2, entry[0]) + push_uint32(buf, entry[1]) + ===========changed ref 9=========== # module: aioquic.tls def push_alpn_protocol(buf: Buffer, protocol: str) -> None: - data = protocol.encode("ascii") - push_uint8(buf, len(data)) - push_bytes(buf, data) + push_opaque(buf, 1, protocol.encode("ascii")) ===========changed ref 10=========== # module: aioquic.tls + def push_opaque(buf: Buffer, capacity: int, value: bytes) -> None: + """ + Push an opaque value prefix by a length. + """ + with push_block(buf, capacity): + push_bytes(buf, value) + ===========changed ref 11=========== # module: aioquic.tls # KeyShareEntry KeyShareEntry = Tuple[Group, bytes] + # PRE SHARED KEY + + PskIdentity = Tuple[bytes, int] + ===========changed ref 12=========== # module: aioquic.tls def push_key_share(buf: Buffer, value: KeyShareEntry) -> None: push_group(buf, value[0]) - with push_block(buf, 2): + push_opaque(buf, 2, value[1]) - push_bytes(buf, value[1])
aioquic.tls/pull_server_hello
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<4>:<del> session_id_length = pull_uint8(buf) <8>:<add> session_id=pull_opaque(buf, 1), <del> session_id=pull_bytes(buf, session_id_length),
# module: aioquic.tls def pull_server_hello(buf: Buffer) -> ServerHello: <0> assert pull_uint8(buf) == HandshakeType.SERVER_HELLO <1> with pull_block(buf, 3): <2> assert pull_uint16(buf) == TLS_VERSION_1_2 <3> server_random = pull_bytes(buf, 32) <4> session_id_length = pull_uint8(buf) <5> <6> hello = ServerHello( <7> random=server_random, <8> session_id=pull_bytes(buf, session_id_length), <9> cipher_suite=pull_cipher_suite(buf), <10> compression_method=pull_compression_method(buf), <11> ) <12> <13> # extensions <14> def pull_extension(buf: Buffer) -> None: <15> extension_type = pull_uint16(buf) <16> extension_length = pull_uint16(buf) <17> if extension_type == ExtensionType.SUPPORTED_VERSIONS: <18> hello.supported_version = pull_uint16(buf) <19> elif extension_type == ExtensionType.KEY_SHARE: <20> hello.key_share = pull_key_share(buf) <21> else: <22> pull_bytes(buf, extension_length) <23> <24> pull_list(buf, 2, pull_extension) <25> <26> return hello <27>
===========unchanged ref 0=========== at: aioquic.buffer push_bytes(buf: Buffer, v: bytes) -> None push_uint8(buf: Buffer, v: int) -> None push_uint16(buf: Buffer, v: int) -> None at: aioquic.tls TLS_VERSION_1_2 = 0x0303 ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) push_cipher_suite = push_uint16 push_compression_method = push_uint8 push_group = push_uint16 push_key_exchange_mode = push_uint8 push_signature_algorithm = push_uint16 push_block(buf: Buffer, capacity: int) -> Generator push_list(buf: Buffer, capacity: int, func: Callable[[Buffer, T], None], values: Sequence[T]) -> None push_opaque(buf: Buffer, capacity: int, value: bytes) -> None push_extension(buf: Buffer, extension_type: int) -> Generator push_key_share(buf: Buffer, value: KeyShareEntry) -> None at: aioquic.tls.ClientHello random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None ===========changed ref 0=========== # module: aioquic.tls + def push_opaque(buf: Buffer, capacity: int, value: bytes) -> None: + """ + Push an opaque value prefix by a length. + """ + with push_block(buf, capacity): + push_bytes(buf, value) + ===========changed ref 1=========== # module: aioquic.tls def push_key_share(buf: Buffer, value: KeyShareEntry) -> None: push_group(buf, value[0]) - with push_block(buf, 2): + push_opaque(buf, 2, value[1]) - push_bytes(buf, value[1]) ===========changed ref 2=========== # module: aioquic.tls + @dataclass + class OfferedPsks: + identities: List[PskIdentity] + binders: List[bytes] + ===========changed ref 3=========== # module: aioquic.tls + def push_psk_binder(buf: Buffer, binder: bytes) -> None: + push_opaque(buf, 1, binder) + ===========changed ref 4=========== # module: aioquic.tls + def pull_psk_binder(buf: Buffer) -> bytes: + return pull_opaque(buf, 1) + ===========changed ref 5=========== # module: aioquic.tls + def push_psk_identity(buf: Buffer, entry: PskIdentity) -> None: + push_opaque(buf, 2, entry[0]) + push_uint32(buf, entry[1]) + ===========changed ref 6=========== # module: aioquic.tls + def pull_psk_identity(buf: Buffer) -> PskIdentity: + identity = pull_opaque(buf, 2) + obfuscated_ticket_age = pull_uint32(buf) + return (identity, obfuscated_ticket_age) + ===========changed ref 7=========== # module: aioquic.tls # ALPN def pull_alpn_protocol(buf: Buffer) -> str: - length = pull_uint8(buf) + return pull_opaque(buf, 1).decode("ascii") - return pull_bytes(buf, length).decode("ascii") ===========changed ref 8=========== # module: aioquic.tls def push_alpn_protocol(buf: Buffer, protocol: str) -> None: - data = protocol.encode("ascii") - push_uint8(buf, len(data)) - push_bytes(buf, data) + push_opaque(buf, 1, protocol.encode("ascii")) ===========changed ref 9=========== # module: aioquic.tls # KeyShareEntry KeyShareEntry = Tuple[Group, bytes] + # PRE SHARED KEY + + PskIdentity = Tuple[bytes, int] + ===========changed ref 10=========== # module: aioquic.tls + def pull_opaque(buf: Buffer, capacity: int) -> bytes: + """ + Pull an opaque value prefixed by a length. + """ + with pull_block(buf, capacity) as length: + return pull_bytes(buf, length) + ===========changed ref 11=========== # module: aioquic.tls def pull_key_share(buf: Buffer) -> KeyShareEntry: group = pull_group(buf) - data_length = pull_uint16(buf) - data = pull_bytes(buf, data_length) + data = pull_opaque(buf, 2) return (group, data) ===========changed ref 12=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None + pre_shared_key: Optional[OfferedPsks] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) ===========changed ref 13=========== # module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: push_uint8(buf, HandshakeType.CLIENT_HELLO) with push_block(buf, 3): push_uint16(buf, TLS_VERSION_1_2) push_bytes(buf, hello.random) - with push_block(buf, 1): + push_opaque(buf, 1, hello.session_id) - push_bytes(buf, hello.session_id) push_list(buf, 2, push_cipher_suite, hello.cipher_suites) push_list(buf, 1, push_compression_method, hello.compression_methods) # extensions with push_block(buf, 2): with push_extension(buf, ExtensionType.KEY_SHARE): push_list(buf, 2, push_key_share, hello.key_share) with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): push_list(buf, 1, push_uint16, hello.supported_versions) with push_extension(buf, ExtensionType.SIGNATURE_ALGORITHMS): push_list(buf, 2, push_signature_algorithm, hello.signature_algorithms) with push_extension(buf, ExtensionType.SUPPORTED_GROUPS): push_list(buf, 2, push_group, hello.supported_groups) with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): push_list(buf, 1, push_key_exchange_mode, hello.key_exchange_modes) if hello.server_name is not None: with push_extension(buf, ExtensionType.SERVER_NAME): with push_block(buf, 2): push_uint8(buf, 0) - with push_block(buf, 2): + push_opaque(buf, 2, hello.server_name.encode("ascii")) - push_bytes(buf, hello.server_name.encode("ascii")) if hello.al</s>
aioquic.tls/push_server_hello
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<5>:<del> with push_block(buf, 1): <6>:<add> push_opaque(buf, 1, hello.session_id) <del> push_bytes(buf, hello.session_id) <7>:<del>
# module: aioquic.tls def push_server_hello(buf: Buffer, hello: ServerHello) -> None: <0> push_uint8(buf, HandshakeType.SERVER_HELLO) <1> with push_block(buf, 3): <2> push_uint16(buf, TLS_VERSION_1_2) <3> push_bytes(buf, hello.random) <4> <5> with push_block(buf, 1): <6> push_bytes(buf, hello.session_id) <7> <8> push_cipher_suite(buf, hello.cipher_suite) <9> push_compression_method(buf, hello.compression_method) <10> <11> # extensions <12> with push_block(buf, 2): <13> if hello.supported_version is not None: <14> with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): <15> push_uint16(buf, hello.supported_version) <16> <17> if hello.key_share is not None: <18> with push_extension(buf, ExtensionType.KEY_SHARE): <19> push_key_share(buf, hello.key_share) <20>
===========unchanged ref 0=========== at: aioquic.buffer push_bytes(buf: Buffer, v: bytes) -> None at: aioquic.tls ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) push_list(buf: Buffer, capacity: int, func: Callable[[Buffer, T], None], values: Sequence[T]) -> None push_extension(buf: Buffer, extension_type: int) -> Generator push_alpn_protocol(buf: Buffer, protocol: str) -> None push_psk_identity(buf: Buffer, entry: PskIdentity) -> None push_psk_binder(buf: Buffer, binder: bytes) -> None at: aioquic.tls.ClientHello alpn_protocols: Optional[List[str]] = None pre_shared_key: Optional[OfferedPsks] = None other_extensions: List[Extension] = field(default_factory=list) at: aioquic.tls.OfferedPsks identities: List[PskIdentity] binders: List[bytes] at: aioquic.tls.ServerHello cipher_suite: CipherSuite compression_method: CompressionMethod key_share: Optional[KeyShareEntry] = None supported_version: Optional[int] = None at: dataclasses dataclass(*, init: bool=..., repr: bool=..., eq: bool=..., order: bool=..., unsafe_hash: bool=..., frozen: bool=...) -> Callable[[Type[_T]], Type[_T]] dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]] dataclass(_cls: Type[_T]) -> Type[_T] ===========changed ref 0=========== # module: aioquic.tls + def push_psk_binder(buf: Buffer, binder: bytes) -> None: + push_opaque(buf, 1, binder) + ===========changed ref 1=========== # module: aioquic.tls + def push_psk_identity(buf: Buffer, entry: PskIdentity) -> None: + push_opaque(buf, 2, entry[0]) + push_uint32(buf, entry[1]) + ===========changed ref 2=========== # module: aioquic.tls def push_alpn_protocol(buf: Buffer, protocol: str) -> None: - data = protocol.encode("ascii") - push_uint8(buf, len(data)) - push_bytes(buf, data) + push_opaque(buf, 1, protocol.encode("ascii")) ===========changed ref 3=========== # module: aioquic.tls + @dataclass + class OfferedPsks: + identities: List[PskIdentity] + binders: List[bytes] + ===========changed ref 4=========== # module: aioquic.tls + def pull_psk_binder(buf: Buffer) -> bytes: + return pull_opaque(buf, 1) + ===========changed ref 5=========== # module: aioquic.tls + def pull_psk_identity(buf: Buffer) -> PskIdentity: + identity = pull_opaque(buf, 2) + obfuscated_ticket_age = pull_uint32(buf) + return (identity, obfuscated_ticket_age) + ===========changed ref 6=========== # module: aioquic.tls # ALPN def pull_alpn_protocol(buf: Buffer) -> str: - length = pull_uint8(buf) + return pull_opaque(buf, 1).decode("ascii") - return pull_bytes(buf, length).decode("ascii") ===========changed ref 7=========== # module: aioquic.tls + def push_opaque(buf: Buffer, capacity: int, value: bytes) -> None: + """ + Push an opaque value prefix by a length. + """ + with push_block(buf, capacity): + push_bytes(buf, value) + ===========changed ref 8=========== # module: aioquic.tls # KeyShareEntry KeyShareEntry = Tuple[Group, bytes] + # PRE SHARED KEY + + PskIdentity = Tuple[bytes, int] + ===========changed ref 9=========== # module: aioquic.tls def push_key_share(buf: Buffer, value: KeyShareEntry) -> None: push_group(buf, value[0]) - with push_block(buf, 2): + push_opaque(buf, 2, value[1]) - push_bytes(buf, value[1]) ===========changed ref 10=========== # module: aioquic.tls + def pull_opaque(buf: Buffer, capacity: int) -> bytes: + """ + Pull an opaque value prefixed by a length. + """ + with pull_block(buf, capacity) as length: + return pull_bytes(buf, length) + ===========changed ref 11=========== # module: aioquic.tls def pull_key_share(buf: Buffer) -> KeyShareEntry: group = pull_group(buf) - data_length = pull_uint16(buf) - data = pull_bytes(buf, data_length) + data = pull_opaque(buf, 2) return (group, data) ===========changed ref 12=========== # module: aioquic.tls def pull_server_hello(buf: Buffer) -> ServerHello: assert pull_uint8(buf) == HandshakeType.SERVER_HELLO with pull_block(buf, 3): assert pull_uint16(buf) == TLS_VERSION_1_2 server_random = pull_bytes(buf, 32) - session_id_length = pull_uint8(buf) hello = ServerHello( random=server_random, + session_id=pull_opaque(buf, 1), - session_id=pull_bytes(buf, session_id_length), cipher_suite=pull_cipher_suite(buf), compression_method=pull_compression_method(buf), ) # extensions def pull_extension(buf: Buffer) -> None: extension_type = pull_uint16(buf) extension_length = pull_uint16(buf) if extension_type == ExtensionType.SUPPORTED_VERSIONS: hello.supported_version = pull_uint16(buf) elif extension_type == ExtensionType.KEY_SHARE: hello.key_share = pull_key_share(buf) else: pull_bytes(buf, extension_length) pull_list(buf, 2, pull_extension) return hello ===========changed ref 13=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None + pre_shared_key: Optional[OfferedPsks] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list)
aioquic.tls/pull_new_session_ticket
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<6>:<del> with pull_block(buf, 1) as length: <7>:<add> new_session_ticket.ticket_nonce = pull_opaque(buf, 1) <del> new_session_ticket.ticket_nonce = pull_bytes(buf, length) <8>:<del> with pull_block(buf, 2) as length: <9>:<add> new_session_ticket.ticket = pull_opaque(buf, 2) <del> new_session_ticket.ticket = pull_bytes(buf, length)
# module: aioquic.tls def pull_new_session_ticket(buf: Buffer) -> NewSessionTicket: <0> new_session_ticket = NewSessionTicket() <1> <2> assert pull_uint8(buf) == HandshakeType.NEW_SESSION_TICKET <3> with pull_block(buf, 3): <4> new_session_ticket.ticket_lifetime = pull_uint32(buf) <5> new_session_ticket.ticket_age_add = pull_uint32(buf) <6> with pull_block(buf, 1) as length: <7> new_session_ticket.ticket_nonce = pull_bytes(buf, length) <8> with pull_block(buf, 2) as length: <9> new_session_ticket.ticket = pull_bytes(buf, length) <10> new_session_ticket.extensions = pull_list(buf, 2, pull_raw_extension) <11> <12> return new_session_ticket <13>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) pull_bytes(buf: Buffer, length: int) -> bytes pull_uint16(buf: Buffer) -> int at: aioquic.tls TLS_VERSION_1_2 = 0x0303 pull_cipher_suite(buf: Buffer) -> CipherSuite pull_compression_method(buf: Buffer) -> CompressionMethod pull_opaque(buf: Buffer, capacity: int) -> bytes ServerHello(random: bytes, session_id: bytes, cipher_suite: CipherSuite, compression_method: CompressionMethod, key_share: Optional[KeyShareEntry]=None, supported_version: Optional[int]=None) ===========changed ref 0=========== # module: aioquic.tls + def pull_opaque(buf: Buffer, capacity: int) -> bytes: + """ + Pull an opaque value prefixed by a length. + """ + with pull_block(buf, capacity) as length: + return pull_bytes(buf, length) + ===========changed ref 1=========== # module: aioquic.tls + @dataclass + class OfferedPsks: + identities: List[PskIdentity] + binders: List[bytes] + ===========changed ref 2=========== # module: aioquic.tls + def push_psk_binder(buf: Buffer, binder: bytes) -> None: + push_opaque(buf, 1, binder) + ===========changed ref 3=========== # module: aioquic.tls + def pull_psk_binder(buf: Buffer) -> bytes: + return pull_opaque(buf, 1) + ===========changed ref 4=========== # module: aioquic.tls + def push_psk_identity(buf: Buffer, entry: PskIdentity) -> None: + push_opaque(buf, 2, entry[0]) + push_uint32(buf, entry[1]) + ===========changed ref 5=========== # module: aioquic.tls + def pull_psk_identity(buf: Buffer) -> PskIdentity: + identity = pull_opaque(buf, 2) + obfuscated_ticket_age = pull_uint32(buf) + return (identity, obfuscated_ticket_age) + ===========changed ref 6=========== # module: aioquic.tls # ALPN def pull_alpn_protocol(buf: Buffer) -> str: - length = pull_uint8(buf) + return pull_opaque(buf, 1).decode("ascii") - return pull_bytes(buf, length).decode("ascii") ===========changed ref 7=========== # module: aioquic.tls def push_server_hello(buf: Buffer, hello: ServerHello) -> None: push_uint8(buf, HandshakeType.SERVER_HELLO) with push_block(buf, 3): push_uint16(buf, TLS_VERSION_1_2) push_bytes(buf, hello.random) - with push_block(buf, 1): + push_opaque(buf, 1, hello.session_id) - push_bytes(buf, hello.session_id) - push_cipher_suite(buf, hello.cipher_suite) push_compression_method(buf, hello.compression_method) # extensions with push_block(buf, 2): if hello.supported_version is not None: with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): push_uint16(buf, hello.supported_version) if hello.key_share is not None: with push_extension(buf, ExtensionType.KEY_SHARE): push_key_share(buf, hello.key_share) ===========changed ref 8=========== # module: aioquic.tls def push_alpn_protocol(buf: Buffer, protocol: str) -> None: - data = protocol.encode("ascii") - push_uint8(buf, len(data)) - push_bytes(buf, data) + push_opaque(buf, 1, protocol.encode("ascii")) ===========changed ref 9=========== # module: aioquic.tls + def push_opaque(buf: Buffer, capacity: int, value: bytes) -> None: + """ + Push an opaque value prefix by a length. + """ + with push_block(buf, capacity): + push_bytes(buf, value) + ===========changed ref 10=========== # module: aioquic.tls # KeyShareEntry KeyShareEntry = Tuple[Group, bytes] + # PRE SHARED KEY + + PskIdentity = Tuple[bytes, int] + ===========changed ref 11=========== # module: aioquic.tls def push_key_share(buf: Buffer, value: KeyShareEntry) -> None: push_group(buf, value[0]) - with push_block(buf, 2): + push_opaque(buf, 2, value[1]) - push_bytes(buf, value[1]) ===========changed ref 12=========== # module: aioquic.tls def pull_key_share(buf: Buffer) -> KeyShareEntry: group = pull_group(buf) - data_length = pull_uint16(buf) - data = pull_bytes(buf, data_length) + data = pull_opaque(buf, 2) return (group, data) ===========changed ref 13=========== # module: aioquic.tls def pull_server_hello(buf: Buffer) -> ServerHello: assert pull_uint8(buf) == HandshakeType.SERVER_HELLO with pull_block(buf, 3): assert pull_uint16(buf) == TLS_VERSION_1_2 server_random = pull_bytes(buf, 32) - session_id_length = pull_uint8(buf) hello = ServerHello( random=server_random, + session_id=pull_opaque(buf, 1), - session_id=pull_bytes(buf, session_id_length), cipher_suite=pull_cipher_suite(buf), compression_method=pull_compression_method(buf), ) # extensions def pull_extension(buf: Buffer) -> None: extension_type = pull_uint16(buf) extension_length = pull_uint16(buf) if extension_type == ExtensionType.SUPPORTED_VERSIONS: hello.supported_version = pull_uint16(buf) elif extension_type == ExtensionType.KEY_SHARE: hello.key_share = pull_key_share(buf) else: pull_bytes(buf, extension_length) pull_list(buf, 2, pull_extension) return hello ===========changed ref 14=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None + pre_shared_key: Optional[OfferedPsks] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list)
aioquic.tls/push_new_session_ticket
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<4>:<del> with push_block(buf, 1): <5>:<add> push_opaque(buf, 1, new_session_ticket.ticket_nonce) <del> push_bytes(buf, new_session_ticket.ticket_nonce) <6>:<del> with push_block(buf, 2): <7>:<add> push_opaque(buf, 2, new_session_ticket.ticket) <del> push_bytes(buf, new_session_ticket.ticket)
# module: aioquic.tls def push_new_session_ticket(buf: Buffer, new_session_ticket: NewSessionTicket) -> None: <0> push_uint8(buf, HandshakeType.NEW_SESSION_TICKET) <1> with push_block(buf, 3): <2> push_uint32(buf, new_session_ticket.ticket_lifetime) <3> push_uint32(buf, new_session_ticket.ticket_age_add) <4> with push_block(buf, 1): <5> push_bytes(buf, new_session_ticket.ticket_nonce) <6> with push_block(buf, 2): <7> push_bytes(buf, new_session_ticket.ticket) <8> push_list(buf, 2, push_raw_extension, new_session_ticket.extensions) <9>
===========unchanged ref 0=========== at: aioquic.buffer pull_bytes(buf: Buffer, length: int) -> bytes at: aioquic.tls ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_list(buf: Buffer, capacity: int, func: Callable[[Buffer], T]) -> List[T] pull_key_share(buf: Buffer) -> KeyShareEntry at: aioquic.tls.ServerHello key_share: Optional[KeyShareEntry] = None at: aioquic.tls.pull_server_hello hello = ServerHello( random=server_random, session_id=pull_opaque(buf, 1), cipher_suite=pull_cipher_suite(buf), compression_method=pull_compression_method(buf), ) pull_extension(buf: Buffer) -> None ===========changed ref 0=========== # module: aioquic.tls def pull_key_share(buf: Buffer) -> KeyShareEntry: group = pull_group(buf) - data_length = pull_uint16(buf) - data = pull_bytes(buf, data_length) + data = pull_opaque(buf, 2) return (group, data) ===========changed ref 1=========== # module: aioquic.tls + @dataclass + class OfferedPsks: + identities: List[PskIdentity] + binders: List[bytes] + ===========changed ref 2=========== # module: aioquic.tls + def push_psk_binder(buf: Buffer, binder: bytes) -> None: + push_opaque(buf, 1, binder) + ===========changed ref 3=========== # module: aioquic.tls + def pull_psk_binder(buf: Buffer) -> bytes: + return pull_opaque(buf, 1) + ===========changed ref 4=========== # module: aioquic.tls + def push_psk_identity(buf: Buffer, entry: PskIdentity) -> None: + push_opaque(buf, 2, entry[0]) + push_uint32(buf, entry[1]) + ===========changed ref 5=========== # module: aioquic.tls def pull_new_session_ticket(buf: Buffer) -> NewSessionTicket: new_session_ticket = NewSessionTicket() assert pull_uint8(buf) == HandshakeType.NEW_SESSION_TICKET with pull_block(buf, 3): new_session_ticket.ticket_lifetime = pull_uint32(buf) new_session_ticket.ticket_age_add = pull_uint32(buf) - with pull_block(buf, 1) as length: + new_session_ticket.ticket_nonce = pull_opaque(buf, 1) - new_session_ticket.ticket_nonce = pull_bytes(buf, length) - with pull_block(buf, 2) as length: + new_session_ticket.ticket = pull_opaque(buf, 2) - new_session_ticket.ticket = pull_bytes(buf, length) new_session_ticket.extensions = pull_list(buf, 2, pull_raw_extension) return new_session_ticket ===========changed ref 6=========== # module: aioquic.tls + def pull_psk_identity(buf: Buffer) -> PskIdentity: + identity = pull_opaque(buf, 2) + obfuscated_ticket_age = pull_uint32(buf) + return (identity, obfuscated_ticket_age) + ===========changed ref 7=========== # module: aioquic.tls # ALPN def pull_alpn_protocol(buf: Buffer) -> str: - length = pull_uint8(buf) + return pull_opaque(buf, 1).decode("ascii") - return pull_bytes(buf, length).decode("ascii") ===========changed ref 8=========== # module: aioquic.tls def push_server_hello(buf: Buffer, hello: ServerHello) -> None: push_uint8(buf, HandshakeType.SERVER_HELLO) with push_block(buf, 3): push_uint16(buf, TLS_VERSION_1_2) push_bytes(buf, hello.random) - with push_block(buf, 1): + push_opaque(buf, 1, hello.session_id) - push_bytes(buf, hello.session_id) - push_cipher_suite(buf, hello.cipher_suite) push_compression_method(buf, hello.compression_method) # extensions with push_block(buf, 2): if hello.supported_version is not None: with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): push_uint16(buf, hello.supported_version) if hello.key_share is not None: with push_extension(buf, ExtensionType.KEY_SHARE): push_key_share(buf, hello.key_share) ===========changed ref 9=========== # module: aioquic.tls def push_alpn_protocol(buf: Buffer, protocol: str) -> None: - data = protocol.encode("ascii") - push_uint8(buf, len(data)) - push_bytes(buf, data) + push_opaque(buf, 1, protocol.encode("ascii")) ===========changed ref 10=========== # module: aioquic.tls + def push_opaque(buf: Buffer, capacity: int, value: bytes) -> None: + """ + Push an opaque value prefix by a length. + """ + with push_block(buf, capacity): + push_bytes(buf, value) + ===========changed ref 11=========== # module: aioquic.tls # KeyShareEntry KeyShareEntry = Tuple[Group, bytes] + # PRE SHARED KEY + + PskIdentity = Tuple[bytes, int] + ===========changed ref 12=========== # module: aioquic.tls def push_key_share(buf: Buffer, value: KeyShareEntry) -> None: push_group(buf, value[0]) - with push_block(buf, 2): + push_opaque(buf, 2, value[1]) - push_bytes(buf, value[1]) ===========changed ref 13=========== # module: aioquic.tls + def pull_opaque(buf: Buffer, capacity: int) -> bytes: + """ + Pull an opaque value prefixed by a length. + """ + with pull_block(buf, capacity) as length: + return pull_bytes(buf, length) + ===========changed ref 14=========== # module: aioquic.tls def pull_server_hello(buf: Buffer) -> ServerHello: assert pull_uint8(buf) == HandshakeType.SERVER_HELLO with pull_block(buf, 3): assert pull_uint16(buf) == TLS_VERSION_1_2 server_random = pull_bytes(buf, 32) - session_id_length = pull_uint8(buf) hello = ServerHello( random=server_random, + session_id=pull_opaque(buf, 1), - session_id=pull_bytes(buf, session_id_length), cipher_suite=pull_cipher_suite(buf), compression_method=pull_compression_method(buf), ) # extensions def pull_extension(buf: Buffer) -> None: extension_type = pull_uint16(buf) extension_length = pull_uint16(buf) if extension_type == ExtensionType.SUPPORTED_VERSIONS: hello.supported_version = pull_uint16(buf) elif extension_type == ExtensionType.KEY_SHARE: hello.key_share = pull_key_share(buf) else: pull_bytes(buf, extension_length) pull_list(buf, 2, pull_extension) return hello
aioquic.tls/pull_certificate
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<4>:<del> with pull_block(buf, 1) as length: <5>:<add> certificate.request_context = pull_opaque(buf, 1) <del> certificate.request_context = pull_bytes(buf, length) <8>:<del> with pull_block(buf, 3) as length: <9>:<add> data = pull_opaque(buf, 3) <del> data = pull_bytes(buf, length) <10>:<del> with pull_block(buf, 2) as length: <11>:<add> extensions = pull_opaque(buf, 2) <del> extensions = pull_bytes(buf, length)
# module: aioquic.tls def pull_certificate(buf: Buffer) -> Certificate: <0> certificate = Certificate() <1> <2> assert pull_uint8(buf) == HandshakeType.CERTIFICATE <3> with pull_block(buf, 3): <4> with pull_block(buf, 1) as length: <5> certificate.request_context = pull_bytes(buf, length) <6> <7> def pull_certificate_entry(buf: Buffer) -> CertificateEntry: <8> with pull_block(buf, 3) as length: <9> data = pull_bytes(buf, length) <10> with pull_block(buf, 2) as length: <11> extensions = pull_bytes(buf, length) <12> return (data, extensions) <13> <14> certificate.certificates = pull_list(buf, 3, pull_certificate_entry) <15> <16> return certificate <17>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) pull_uint8(buf: Buffer) -> int pull_uint16(buf: Buffer) -> int at: aioquic.tls HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) pull_block(buf: Buffer, capacity: int) -> Generator at: dataclasses field(*, default_factory: Callable[[], _T], init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> _T field(*, init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> Any field(*, default: _T, init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> _T dataclass(*, init: bool=..., repr: bool=..., eq: bool=..., order: bool=..., unsafe_hash: bool=..., frozen: bool=...) -> Callable[[Type[_T]], Type[_T]] dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]] dataclass(_cls: Type[_T]) -> Type[_T] at: typing Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.tls + @dataclass + class OfferedPsks: + identities: List[PskIdentity] + binders: List[bytes] + ===========changed ref 1=========== # module: aioquic.tls def push_new_session_ticket(buf: Buffer, new_session_ticket: NewSessionTicket) -> None: push_uint8(buf, HandshakeType.NEW_SESSION_TICKET) with push_block(buf, 3): push_uint32(buf, new_session_ticket.ticket_lifetime) push_uint32(buf, new_session_ticket.ticket_age_add) - with push_block(buf, 1): + push_opaque(buf, 1, new_session_ticket.ticket_nonce) - push_bytes(buf, new_session_ticket.ticket_nonce) - with push_block(buf, 2): + push_opaque(buf, 2, new_session_ticket.ticket) - push_bytes(buf, new_session_ticket.ticket) push_list(buf, 2, push_raw_extension, new_session_ticket.extensions) ===========changed ref 2=========== # module: aioquic.tls + def push_psk_binder(buf: Buffer, binder: bytes) -> None: + push_opaque(buf, 1, binder) + ===========changed ref 3=========== # module: aioquic.tls + def pull_psk_binder(buf: Buffer) -> bytes: + return pull_opaque(buf, 1) + ===========changed ref 4=========== # module: aioquic.tls + def push_psk_identity(buf: Buffer, entry: PskIdentity) -> None: + push_opaque(buf, 2, entry[0]) + push_uint32(buf, entry[1]) + ===========changed ref 5=========== # module: aioquic.tls def pull_new_session_ticket(buf: Buffer) -> NewSessionTicket: new_session_ticket = NewSessionTicket() assert pull_uint8(buf) == HandshakeType.NEW_SESSION_TICKET with pull_block(buf, 3): new_session_ticket.ticket_lifetime = pull_uint32(buf) new_session_ticket.ticket_age_add = pull_uint32(buf) - with pull_block(buf, 1) as length: + new_session_ticket.ticket_nonce = pull_opaque(buf, 1) - new_session_ticket.ticket_nonce = pull_bytes(buf, length) - with pull_block(buf, 2) as length: + new_session_ticket.ticket = pull_opaque(buf, 2) - new_session_ticket.ticket = pull_bytes(buf, length) new_session_ticket.extensions = pull_list(buf, 2, pull_raw_extension) return new_session_ticket ===========changed ref 6=========== # module: aioquic.tls + def pull_psk_identity(buf: Buffer) -> PskIdentity: + identity = pull_opaque(buf, 2) + obfuscated_ticket_age = pull_uint32(buf) + return (identity, obfuscated_ticket_age) + ===========changed ref 7=========== # module: aioquic.tls # ALPN def pull_alpn_protocol(buf: Buffer) -> str: - length = pull_uint8(buf) + return pull_opaque(buf, 1).decode("ascii") - return pull_bytes(buf, length).decode("ascii") ===========changed ref 8=========== # module: aioquic.tls def push_server_hello(buf: Buffer, hello: ServerHello) -> None: push_uint8(buf, HandshakeType.SERVER_HELLO) with push_block(buf, 3): push_uint16(buf, TLS_VERSION_1_2) push_bytes(buf, hello.random) - with push_block(buf, 1): + push_opaque(buf, 1, hello.session_id) - push_bytes(buf, hello.session_id) - push_cipher_suite(buf, hello.cipher_suite) push_compression_method(buf, hello.compression_method) # extensions with push_block(buf, 2): if hello.supported_version is not None: with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): push_uint16(buf, hello.supported_version) if hello.key_share is not None: with push_extension(buf, ExtensionType.KEY_SHARE): push_key_share(buf, hello.key_share) ===========changed ref 9=========== # module: aioquic.tls def push_alpn_protocol(buf: Buffer, protocol: str) -> None: - data = protocol.encode("ascii") - push_uint8(buf, len(data)) - push_bytes(buf, data) + push_opaque(buf, 1, protocol.encode("ascii")) ===========changed ref 10=========== # module: aioquic.tls + def push_opaque(buf: Buffer, capacity: int, value: bytes) -> None: + """ + Push an opaque value prefix by a length. + """ + with push_block(buf, capacity): + push_bytes(buf, value) + ===========changed ref 11=========== # module: aioquic.tls # KeyShareEntry KeyShareEntry = Tuple[Group, bytes] + # PRE SHARED KEY + + PskIdentity = Tuple[bytes, int] + ===========changed ref 12=========== # module: aioquic.tls def push_key_share(buf: Buffer, value: KeyShareEntry) -> None: push_group(buf, value[0]) - with push_block(buf, 2): + push_opaque(buf, 2, value[1]) - push_bytes(buf, value[1]) ===========changed ref 13=========== # module: aioquic.tls + def pull_opaque(buf: Buffer, capacity: int) -> bytes: + """ + Pull an opaque value prefixed by a length. + """ + with pull_block(buf, capacity) as length: + return pull_bytes(buf, length) + ===========changed ref 14=========== # module: aioquic.tls def pull_key_share(buf: Buffer) -> KeyShareEntry: group = pull_group(buf) - data_length = pull_uint16(buf) - data = pull_bytes(buf, data_length) + data = pull_opaque(buf, 2) return (group, data)
aioquic.tls/push_certificate
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<2>:<del> with push_block(buf, 1): <3>:<add> push_opaque(buf, 1, certificate.request_context) <del> push_bytes(buf, certificate.request_context) <6>:<del> with push_block(buf, 3): <7>:<add> push_opaque(buf, 3, entry[0]) <del> push_bytes(buf, entry[0]) <8>:<del> with push_block(buf, 2): <9>:<add> push_opaque(buf, 2, entry[1]) <del> push_bytes(buf, entry[1])
# module: aioquic.tls def push_certificate(buf: Buffer, certificate: Certificate) -> None: <0> push_uint8(buf, HandshakeType.CERTIFICATE) <1> with push_block(buf, 3): <2> with push_block(buf, 1): <3> push_bytes(buf, certificate.request_context) <4> <5> def push_certificate_entry(buf: Buffer, entry: CertificateEntry) -> None: <6> with push_block(buf, 3): <7> push_bytes(buf, entry[0]) <8> with push_block(buf, 2): <9> push_bytes(buf, entry[1]) <10> <11> push_list(buf, 3, push_certificate_entry, certificate.certificates) <12>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) pull_bytes(buf: Buffer, length: int) -> bytes push_uint8(buf: Buffer, v: int) -> None at: aioquic.tls HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) push_block(buf: Buffer, capacity: int) -> Generator pull_list(buf: Buffer, capacity: int, func: Callable[[Buffer], T]) -> List[T] EncryptedExtensions(alpn_protocol: Optional[str]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) at: aioquic.tls.EncryptedExtensions other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) at: aioquic.tls.pull_encrypted_extensions extensions = EncryptedExtensions() pull_extension(buf: Buffer) -> None ===========changed ref 0=========== # module: aioquic.tls def pull_certificate(buf: Buffer) -> Certificate: certificate = Certificate() assert pull_uint8(buf) == HandshakeType.CERTIFICATE with pull_block(buf, 3): - with pull_block(buf, 1) as length: + certificate.request_context = pull_opaque(buf, 1) - certificate.request_context = pull_bytes(buf, length) def pull_certificate_entry(buf: Buffer) -> CertificateEntry: - with pull_block(buf, 3) as length: + data = pull_opaque(buf, 3) - data = pull_bytes(buf, length) - with pull_block(buf, 2) as length: + extensions = pull_opaque(buf, 2) - extensions = pull_bytes(buf, length) return (data, extensions) certificate.certificates = pull_list(buf, 3, pull_certificate_entry) return certificate ===========changed ref 1=========== # module: aioquic.tls + @dataclass + class OfferedPsks: + identities: List[PskIdentity] + binders: List[bytes] + ===========changed ref 2=========== # module: aioquic.tls def push_new_session_ticket(buf: Buffer, new_session_ticket: NewSessionTicket) -> None: push_uint8(buf, HandshakeType.NEW_SESSION_TICKET) with push_block(buf, 3): push_uint32(buf, new_session_ticket.ticket_lifetime) push_uint32(buf, new_session_ticket.ticket_age_add) - with push_block(buf, 1): + push_opaque(buf, 1, new_session_ticket.ticket_nonce) - push_bytes(buf, new_session_ticket.ticket_nonce) - with push_block(buf, 2): + push_opaque(buf, 2, new_session_ticket.ticket) - push_bytes(buf, new_session_ticket.ticket) push_list(buf, 2, push_raw_extension, new_session_ticket.extensions) ===========changed ref 3=========== # module: aioquic.tls + def push_psk_binder(buf: Buffer, binder: bytes) -> None: + push_opaque(buf, 1, binder) + ===========changed ref 4=========== # module: aioquic.tls + def pull_psk_binder(buf: Buffer) -> bytes: + return pull_opaque(buf, 1) + ===========changed ref 5=========== # module: aioquic.tls + def push_psk_identity(buf: Buffer, entry: PskIdentity) -> None: + push_opaque(buf, 2, entry[0]) + push_uint32(buf, entry[1]) + ===========changed ref 6=========== # module: aioquic.tls def pull_new_session_ticket(buf: Buffer) -> NewSessionTicket: new_session_ticket = NewSessionTicket() assert pull_uint8(buf) == HandshakeType.NEW_SESSION_TICKET with pull_block(buf, 3): new_session_ticket.ticket_lifetime = pull_uint32(buf) new_session_ticket.ticket_age_add = pull_uint32(buf) - with pull_block(buf, 1) as length: + new_session_ticket.ticket_nonce = pull_opaque(buf, 1) - new_session_ticket.ticket_nonce = pull_bytes(buf, length) - with pull_block(buf, 2) as length: + new_session_ticket.ticket = pull_opaque(buf, 2) - new_session_ticket.ticket = pull_bytes(buf, length) new_session_ticket.extensions = pull_list(buf, 2, pull_raw_extension) return new_session_ticket ===========changed ref 7=========== # module: aioquic.tls + def pull_psk_identity(buf: Buffer) -> PskIdentity: + identity = pull_opaque(buf, 2) + obfuscated_ticket_age = pull_uint32(buf) + return (identity, obfuscated_ticket_age) + ===========changed ref 8=========== # module: aioquic.tls # ALPN def pull_alpn_protocol(buf: Buffer) -> str: - length = pull_uint8(buf) + return pull_opaque(buf, 1).decode("ascii") - return pull_bytes(buf, length).decode("ascii") ===========changed ref 9=========== # module: aioquic.tls def push_server_hello(buf: Buffer, hello: ServerHello) -> None: push_uint8(buf, HandshakeType.SERVER_HELLO) with push_block(buf, 3): push_uint16(buf, TLS_VERSION_1_2) push_bytes(buf, hello.random) - with push_block(buf, 1): + push_opaque(buf, 1, hello.session_id) - push_bytes(buf, hello.session_id) - push_cipher_suite(buf, hello.cipher_suite) push_compression_method(buf, hello.compression_method) # extensions with push_block(buf, 2): if hello.supported_version is not None: with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): push_uint16(buf, hello.supported_version) if hello.key_share is not None: with push_extension(buf, ExtensionType.KEY_SHARE): push_key_share(buf, hello.key_share) ===========changed ref 10=========== # module: aioquic.tls def push_alpn_protocol(buf: Buffer, protocol: str) -> None: - data = protocol.encode("ascii") - push_uint8(buf, len(data)) - push_bytes(buf, data) + push_opaque(buf, 1, protocol.encode("ascii")) ===========changed ref 11=========== # module: aioquic.tls + def push_opaque(buf: Buffer, capacity: int, value: bytes) -> None: + """ + Push an opaque value prefix by a length. + """ + with push_block(buf, capacity): + push_bytes(buf, value) + ===========changed ref 12=========== # module: aioquic.tls # KeyShareEntry KeyShareEntry = Tuple[Group, bytes] + # PRE SHARED KEY + + PskIdentity = Tuple[bytes, int] + ===========changed ref 13=========== # module: aioquic.tls def push_key_share(buf: Buffer, value: KeyShareEntry) -> None: push_group(buf, value[0]) - with push_block(buf, 2): + push_opaque(buf, 2, value[1]) - push_bytes(buf, value[1]) ===========changed ref 14=========== # module: aioquic.tls + def pull_opaque(buf: Buffer, capacity: int) -> bytes: + """ + Pull an opaque value prefixed by a length. + """ + with pull_block(buf, capacity) as length: + return pull_bytes(buf, length) +
aioquic.tls/pull_certificate_verify
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<3>:<del> with pull_block(buf, 2) as length: <4>:<add> signature = pull_opaque(buf, 2) <del> signature = pull_bytes(buf, length)
# module: aioquic.tls def pull_certificate_verify(buf: Buffer) -> CertificateVerify: <0> assert pull_uint8(buf) == HandshakeType.CERTIFICATE_VERIFY <1> with pull_block(buf, 3): <2> algorithm = pull_signature_algorithm(buf) <3> with pull_block(buf, 2) as length: <4> signature = pull_bytes(buf, length) <5> <6> return CertificateVerify(algorithm=algorithm, signature=signature) <7>
===========unchanged ref 0=========== at: aioquic.tls.Certificate certificates: List[CertificateEntry] = field(default_factory=list) at: dataclasses dataclass(*, init: bool=..., repr: bool=..., eq: bool=..., order: bool=..., unsafe_hash: bool=..., frozen: bool=...) -> Callable[[Type[_T]], Type[_T]] dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]] dataclass(_cls: Type[_T]) -> Type[_T] at: typing Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') ===========changed ref 0=========== # module: aioquic.tls def push_certificate(buf: Buffer, certificate: Certificate) -> None: push_uint8(buf, HandshakeType.CERTIFICATE) with push_block(buf, 3): - with push_block(buf, 1): + push_opaque(buf, 1, certificate.request_context) - push_bytes(buf, certificate.request_context) def push_certificate_entry(buf: Buffer, entry: CertificateEntry) -> None: - with push_block(buf, 3): + push_opaque(buf, 3, entry[0]) - push_bytes(buf, entry[0]) - with push_block(buf, 2): + push_opaque(buf, 2, entry[1]) - push_bytes(buf, entry[1]) push_list(buf, 3, push_certificate_entry, certificate.certificates) ===========changed ref 1=========== # module: aioquic.tls def pull_certificate(buf: Buffer) -> Certificate: certificate = Certificate() assert pull_uint8(buf) == HandshakeType.CERTIFICATE with pull_block(buf, 3): - with pull_block(buf, 1) as length: + certificate.request_context = pull_opaque(buf, 1) - certificate.request_context = pull_bytes(buf, length) def pull_certificate_entry(buf: Buffer) -> CertificateEntry: - with pull_block(buf, 3) as length: + data = pull_opaque(buf, 3) - data = pull_bytes(buf, length) - with pull_block(buf, 2) as length: + extensions = pull_opaque(buf, 2) - extensions = pull_bytes(buf, length) return (data, extensions) certificate.certificates = pull_list(buf, 3, pull_certificate_entry) return certificate ===========changed ref 2=========== # module: aioquic.tls + @dataclass + class OfferedPsks: + identities: List[PskIdentity] + binders: List[bytes] + ===========changed ref 3=========== # module: aioquic.tls def push_new_session_ticket(buf: Buffer, new_session_ticket: NewSessionTicket) -> None: push_uint8(buf, HandshakeType.NEW_SESSION_TICKET) with push_block(buf, 3): push_uint32(buf, new_session_ticket.ticket_lifetime) push_uint32(buf, new_session_ticket.ticket_age_add) - with push_block(buf, 1): + push_opaque(buf, 1, new_session_ticket.ticket_nonce) - push_bytes(buf, new_session_ticket.ticket_nonce) - with push_block(buf, 2): + push_opaque(buf, 2, new_session_ticket.ticket) - push_bytes(buf, new_session_ticket.ticket) push_list(buf, 2, push_raw_extension, new_session_ticket.extensions) ===========changed ref 4=========== # module: aioquic.tls + def push_psk_binder(buf: Buffer, binder: bytes) -> None: + push_opaque(buf, 1, binder) + ===========changed ref 5=========== # module: aioquic.tls + def pull_psk_binder(buf: Buffer) -> bytes: + return pull_opaque(buf, 1) + ===========changed ref 6=========== # module: aioquic.tls + def push_psk_identity(buf: Buffer, entry: PskIdentity) -> None: + push_opaque(buf, 2, entry[0]) + push_uint32(buf, entry[1]) + ===========changed ref 7=========== # module: aioquic.tls def pull_new_session_ticket(buf: Buffer) -> NewSessionTicket: new_session_ticket = NewSessionTicket() assert pull_uint8(buf) == HandshakeType.NEW_SESSION_TICKET with pull_block(buf, 3): new_session_ticket.ticket_lifetime = pull_uint32(buf) new_session_ticket.ticket_age_add = pull_uint32(buf) - with pull_block(buf, 1) as length: + new_session_ticket.ticket_nonce = pull_opaque(buf, 1) - new_session_ticket.ticket_nonce = pull_bytes(buf, length) - with pull_block(buf, 2) as length: + new_session_ticket.ticket = pull_opaque(buf, 2) - new_session_ticket.ticket = pull_bytes(buf, length) new_session_ticket.extensions = pull_list(buf, 2, pull_raw_extension) return new_session_ticket ===========changed ref 8=========== # module: aioquic.tls + def pull_psk_identity(buf: Buffer) -> PskIdentity: + identity = pull_opaque(buf, 2) + obfuscated_ticket_age = pull_uint32(buf) + return (identity, obfuscated_ticket_age) + ===========changed ref 9=========== # module: aioquic.tls # ALPN def pull_alpn_protocol(buf: Buffer) -> str: - length = pull_uint8(buf) + return pull_opaque(buf, 1).decode("ascii") - return pull_bytes(buf, length).decode("ascii") ===========changed ref 10=========== # module: aioquic.tls def push_server_hello(buf: Buffer, hello: ServerHello) -> None: push_uint8(buf, HandshakeType.SERVER_HELLO) with push_block(buf, 3): push_uint16(buf, TLS_VERSION_1_2) push_bytes(buf, hello.random) - with push_block(buf, 1): + push_opaque(buf, 1, hello.session_id) - push_bytes(buf, hello.session_id) - push_cipher_suite(buf, hello.cipher_suite) push_compression_method(buf, hello.compression_method) # extensions with push_block(buf, 2): if hello.supported_version is not None: with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): push_uint16(buf, hello.supported_version) if hello.key_share is not None: with push_extension(buf, ExtensionType.KEY_SHARE): push_key_share(buf, hello.key_share) ===========changed ref 11=========== # module: aioquic.tls def push_alpn_protocol(buf: Buffer, protocol: str) -> None: - data = protocol.encode("ascii") - push_uint8(buf, len(data)) - push_bytes(buf, data) + push_opaque(buf, 1, protocol.encode("ascii")) ===========changed ref 12=========== # module: aioquic.tls + def push_opaque(buf: Buffer, capacity: int, value: bytes) -> None: + """ + Push an opaque value prefix by a length. + """ + with push_block(buf, capacity): + push_bytes(buf, value) + ===========changed ref 13=========== # module: aioquic.tls # KeyShareEntry KeyShareEntry = Tuple[Group, bytes] + # PRE SHARED KEY + + PskIdentity = Tuple[bytes, int] +
aioquic.tls/push_certificate_verify
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<3>:<del> with push_block(buf, 2): <4>:<add> push_opaque(buf, 2, verify.signature) <del> push_bytes(buf, verify.signature)
# module: aioquic.tls def push_certificate_verify(buf: Buffer, verify: CertificateVerify) -> None: <0> push_uint8(buf, HandshakeType.CERTIFICATE_VERIFY) <1> with push_block(buf, 3): <2> push_signature_algorithm(buf, verify.algorithm) <3> with push_block(buf, 2): <4> push_bytes(buf, verify.signature) <5>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) pull_uint8(buf: Buffer) -> int at: aioquic.tls HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) pull_block(buf: Buffer, capacity: int) -> Generator Certificate(request_context: bytes=b"", certificates: List[CertificateEntry]=field(default_factory=list)) ===========changed ref 0=========== # module: aioquic.tls def pull_certificate_verify(buf: Buffer) -> CertificateVerify: assert pull_uint8(buf) == HandshakeType.CERTIFICATE_VERIFY with pull_block(buf, 3): algorithm = pull_signature_algorithm(buf) - with pull_block(buf, 2) as length: + signature = pull_opaque(buf, 2) - signature = pull_bytes(buf, length) return CertificateVerify(algorithm=algorithm, signature=signature) ===========changed ref 1=========== # module: aioquic.tls def push_certificate(buf: Buffer, certificate: Certificate) -> None: push_uint8(buf, HandshakeType.CERTIFICATE) with push_block(buf, 3): - with push_block(buf, 1): + push_opaque(buf, 1, certificate.request_context) - push_bytes(buf, certificate.request_context) def push_certificate_entry(buf: Buffer, entry: CertificateEntry) -> None: - with push_block(buf, 3): + push_opaque(buf, 3, entry[0]) - push_bytes(buf, entry[0]) - with push_block(buf, 2): + push_opaque(buf, 2, entry[1]) - push_bytes(buf, entry[1]) push_list(buf, 3, push_certificate_entry, certificate.certificates) ===========changed ref 2=========== # module: aioquic.tls def pull_certificate(buf: Buffer) -> Certificate: certificate = Certificate() assert pull_uint8(buf) == HandshakeType.CERTIFICATE with pull_block(buf, 3): - with pull_block(buf, 1) as length: + certificate.request_context = pull_opaque(buf, 1) - certificate.request_context = pull_bytes(buf, length) def pull_certificate_entry(buf: Buffer) -> CertificateEntry: - with pull_block(buf, 3) as length: + data = pull_opaque(buf, 3) - data = pull_bytes(buf, length) - with pull_block(buf, 2) as length: + extensions = pull_opaque(buf, 2) - extensions = pull_bytes(buf, length) return (data, extensions) certificate.certificates = pull_list(buf, 3, pull_certificate_entry) return certificate ===========changed ref 3=========== # module: aioquic.tls + @dataclass + class OfferedPsks: + identities: List[PskIdentity] + binders: List[bytes] + ===========changed ref 4=========== # module: aioquic.tls def push_new_session_ticket(buf: Buffer, new_session_ticket: NewSessionTicket) -> None: push_uint8(buf, HandshakeType.NEW_SESSION_TICKET) with push_block(buf, 3): push_uint32(buf, new_session_ticket.ticket_lifetime) push_uint32(buf, new_session_ticket.ticket_age_add) - with push_block(buf, 1): + push_opaque(buf, 1, new_session_ticket.ticket_nonce) - push_bytes(buf, new_session_ticket.ticket_nonce) - with push_block(buf, 2): + push_opaque(buf, 2, new_session_ticket.ticket) - push_bytes(buf, new_session_ticket.ticket) push_list(buf, 2, push_raw_extension, new_session_ticket.extensions) ===========changed ref 5=========== # module: aioquic.tls + def push_psk_binder(buf: Buffer, binder: bytes) -> None: + push_opaque(buf, 1, binder) + ===========changed ref 6=========== # module: aioquic.tls + def pull_psk_binder(buf: Buffer) -> bytes: + return pull_opaque(buf, 1) + ===========changed ref 7=========== # module: aioquic.tls + def push_psk_identity(buf: Buffer, entry: PskIdentity) -> None: + push_opaque(buf, 2, entry[0]) + push_uint32(buf, entry[1]) + ===========changed ref 8=========== # module: aioquic.tls def pull_new_session_ticket(buf: Buffer) -> NewSessionTicket: new_session_ticket = NewSessionTicket() assert pull_uint8(buf) == HandshakeType.NEW_SESSION_TICKET with pull_block(buf, 3): new_session_ticket.ticket_lifetime = pull_uint32(buf) new_session_ticket.ticket_age_add = pull_uint32(buf) - with pull_block(buf, 1) as length: + new_session_ticket.ticket_nonce = pull_opaque(buf, 1) - new_session_ticket.ticket_nonce = pull_bytes(buf, length) - with pull_block(buf, 2) as length: + new_session_ticket.ticket = pull_opaque(buf, 2) - new_session_ticket.ticket = pull_bytes(buf, length) new_session_ticket.extensions = pull_list(buf, 2, pull_raw_extension) return new_session_ticket ===========changed ref 9=========== # module: aioquic.tls + def pull_psk_identity(buf: Buffer) -> PskIdentity: + identity = pull_opaque(buf, 2) + obfuscated_ticket_age = pull_uint32(buf) + return (identity, obfuscated_ticket_age) + ===========changed ref 10=========== # module: aioquic.tls # ALPN def pull_alpn_protocol(buf: Buffer) -> str: - length = pull_uint8(buf) + return pull_opaque(buf, 1).decode("ascii") - return pull_bytes(buf, length).decode("ascii") ===========changed ref 11=========== # module: aioquic.tls def push_server_hello(buf: Buffer, hello: ServerHello) -> None: push_uint8(buf, HandshakeType.SERVER_HELLO) with push_block(buf, 3): push_uint16(buf, TLS_VERSION_1_2) push_bytes(buf, hello.random) - with push_block(buf, 1): + push_opaque(buf, 1, hello.session_id) - push_bytes(buf, hello.session_id) - push_cipher_suite(buf, hello.cipher_suite) push_compression_method(buf, hello.compression_method) # extensions with push_block(buf, 2): if hello.supported_version is not None: with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): push_uint16(buf, hello.supported_version) if hello.key_share is not None: with push_extension(buf, ExtensionType.KEY_SHARE): push_key_share(buf, hello.key_share) ===========changed ref 12=========== # module: aioquic.tls def push_alpn_protocol(buf: Buffer, protocol: str) -> None: - data = protocol.encode("ascii") - push_uint8(buf, len(data)) - push_bytes(buf, data) + push_opaque(buf, 1, protocol.encode("ascii"))
aioquic.tls/pull_finished
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<3>:<del> with pull_block(buf, 3) as length: <4>:<add> finished.verify_data = pull_opaque(buf, 3) <del> finished.verify_data = pull_bytes(buf, length)
# module: aioquic.tls def pull_finished(buf: Buffer) -> Finished: <0> finished = Finished() <1> <2> assert pull_uint8(buf) == HandshakeType.FINISHED <3> with pull_block(buf, 3) as length: <4> finished.verify_data = pull_bytes(buf, length) <5> <6> return finished <7>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) push_uint8(buf: Buffer, v: int) -> None at: aioquic.tls HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) push_block(buf: Buffer, capacity: int) -> Generator pull_list(buf: Buffer, capacity: int, func: Callable[[Buffer], T]) -> List[T] Certificate(request_context: bytes=b"", certificates: List[CertificateEntry]=field(default_factory=list)) at: aioquic.tls.Certificate certificates: List[CertificateEntry] = field(default_factory=list) at: aioquic.tls.pull_certificate certificate = Certificate() pull_certificate_entry(buf: Buffer) -> CertificateEntry ===========changed ref 0=========== # module: aioquic.tls def push_certificate_verify(buf: Buffer, verify: CertificateVerify) -> None: push_uint8(buf, HandshakeType.CERTIFICATE_VERIFY) with push_block(buf, 3): push_signature_algorithm(buf, verify.algorithm) - with push_block(buf, 2): + push_opaque(buf, 2, verify.signature) - push_bytes(buf, verify.signature) ===========changed ref 1=========== # module: aioquic.tls def pull_certificate_verify(buf: Buffer) -> CertificateVerify: assert pull_uint8(buf) == HandshakeType.CERTIFICATE_VERIFY with pull_block(buf, 3): algorithm = pull_signature_algorithm(buf) - with pull_block(buf, 2) as length: + signature = pull_opaque(buf, 2) - signature = pull_bytes(buf, length) return CertificateVerify(algorithm=algorithm, signature=signature) ===========changed ref 2=========== # module: aioquic.tls def push_certificate(buf: Buffer, certificate: Certificate) -> None: push_uint8(buf, HandshakeType.CERTIFICATE) with push_block(buf, 3): - with push_block(buf, 1): + push_opaque(buf, 1, certificate.request_context) - push_bytes(buf, certificate.request_context) def push_certificate_entry(buf: Buffer, entry: CertificateEntry) -> None: - with push_block(buf, 3): + push_opaque(buf, 3, entry[0]) - push_bytes(buf, entry[0]) - with push_block(buf, 2): + push_opaque(buf, 2, entry[1]) - push_bytes(buf, entry[1]) push_list(buf, 3, push_certificate_entry, certificate.certificates) ===========changed ref 3=========== # module: aioquic.tls def pull_certificate(buf: Buffer) -> Certificate: certificate = Certificate() assert pull_uint8(buf) == HandshakeType.CERTIFICATE with pull_block(buf, 3): - with pull_block(buf, 1) as length: + certificate.request_context = pull_opaque(buf, 1) - certificate.request_context = pull_bytes(buf, length) def pull_certificate_entry(buf: Buffer) -> CertificateEntry: - with pull_block(buf, 3) as length: + data = pull_opaque(buf, 3) - data = pull_bytes(buf, length) - with pull_block(buf, 2) as length: + extensions = pull_opaque(buf, 2) - extensions = pull_bytes(buf, length) return (data, extensions) certificate.certificates = pull_list(buf, 3, pull_certificate_entry) return certificate ===========changed ref 4=========== # module: aioquic.tls + @dataclass + class OfferedPsks: + identities: List[PskIdentity] + binders: List[bytes] + ===========changed ref 5=========== # module: aioquic.tls def push_new_session_ticket(buf: Buffer, new_session_ticket: NewSessionTicket) -> None: push_uint8(buf, HandshakeType.NEW_SESSION_TICKET) with push_block(buf, 3): push_uint32(buf, new_session_ticket.ticket_lifetime) push_uint32(buf, new_session_ticket.ticket_age_add) - with push_block(buf, 1): + push_opaque(buf, 1, new_session_ticket.ticket_nonce) - push_bytes(buf, new_session_ticket.ticket_nonce) - with push_block(buf, 2): + push_opaque(buf, 2, new_session_ticket.ticket) - push_bytes(buf, new_session_ticket.ticket) push_list(buf, 2, push_raw_extension, new_session_ticket.extensions) ===========changed ref 6=========== # module: aioquic.tls + def push_psk_binder(buf: Buffer, binder: bytes) -> None: + push_opaque(buf, 1, binder) + ===========changed ref 7=========== # module: aioquic.tls + def pull_psk_binder(buf: Buffer) -> bytes: + return pull_opaque(buf, 1) + ===========changed ref 8=========== # module: aioquic.tls + def push_psk_identity(buf: Buffer, entry: PskIdentity) -> None: + push_opaque(buf, 2, entry[0]) + push_uint32(buf, entry[1]) + ===========changed ref 9=========== # module: aioquic.tls def pull_new_session_ticket(buf: Buffer) -> NewSessionTicket: new_session_ticket = NewSessionTicket() assert pull_uint8(buf) == HandshakeType.NEW_SESSION_TICKET with pull_block(buf, 3): new_session_ticket.ticket_lifetime = pull_uint32(buf) new_session_ticket.ticket_age_add = pull_uint32(buf) - with pull_block(buf, 1) as length: + new_session_ticket.ticket_nonce = pull_opaque(buf, 1) - new_session_ticket.ticket_nonce = pull_bytes(buf, length) - with pull_block(buf, 2) as length: + new_session_ticket.ticket = pull_opaque(buf, 2) - new_session_ticket.ticket = pull_bytes(buf, length) new_session_ticket.extensions = pull_list(buf, 2, pull_raw_extension) return new_session_ticket ===========changed ref 10=========== # module: aioquic.tls + def pull_psk_identity(buf: Buffer) -> PskIdentity: + identity = pull_opaque(buf, 2) + obfuscated_ticket_age = pull_uint32(buf) + return (identity, obfuscated_ticket_age) + ===========changed ref 11=========== # module: aioquic.tls # ALPN def pull_alpn_protocol(buf: Buffer) -> str: - length = pull_uint8(buf) + return pull_opaque(buf, 1).decode("ascii") - return pull_bytes(buf, length).decode("ascii")
aioquic.tls/push_finished
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<1>:<del> with push_block(buf, 3): <2>:<add> push_opaque(buf, 3, finished.verify_data) <del> push_bytes(buf, finished.verify_data)
# module: aioquic.tls def push_finished(buf: Buffer, finished: Finished) -> None: <0> push_uint8(buf, HandshakeType.FINISHED) <1> with push_block(buf, 3): <2> push_bytes(buf, finished.verify_data) <3>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls push_opaque(buf: Buffer, capacity: int, value: bytes) -> None CertificateEntry = Tuple[bytes, bytes] ===========changed ref 0=========== # module: aioquic.tls + def push_opaque(buf: Buffer, capacity: int, value: bytes) -> None: + """ + Push an opaque value prefix by a length. + """ + with push_block(buf, capacity): + push_bytes(buf, value) + ===========changed ref 1=========== # module: aioquic.tls def pull_finished(buf: Buffer) -> Finished: finished = Finished() assert pull_uint8(buf) == HandshakeType.FINISHED - with pull_block(buf, 3) as length: + finished.verify_data = pull_opaque(buf, 3) - finished.verify_data = pull_bytes(buf, length) return finished ===========changed ref 2=========== # module: aioquic.tls def push_certificate_verify(buf: Buffer, verify: CertificateVerify) -> None: push_uint8(buf, HandshakeType.CERTIFICATE_VERIFY) with push_block(buf, 3): push_signature_algorithm(buf, verify.algorithm) - with push_block(buf, 2): + push_opaque(buf, 2, verify.signature) - push_bytes(buf, verify.signature) ===========changed ref 3=========== # module: aioquic.tls def pull_certificate_verify(buf: Buffer) -> CertificateVerify: assert pull_uint8(buf) == HandshakeType.CERTIFICATE_VERIFY with pull_block(buf, 3): algorithm = pull_signature_algorithm(buf) - with pull_block(buf, 2) as length: + signature = pull_opaque(buf, 2) - signature = pull_bytes(buf, length) return CertificateVerify(algorithm=algorithm, signature=signature) ===========changed ref 4=========== # module: aioquic.tls def push_certificate(buf: Buffer, certificate: Certificate) -> None: push_uint8(buf, HandshakeType.CERTIFICATE) with push_block(buf, 3): - with push_block(buf, 1): + push_opaque(buf, 1, certificate.request_context) - push_bytes(buf, certificate.request_context) def push_certificate_entry(buf: Buffer, entry: CertificateEntry) -> None: - with push_block(buf, 3): + push_opaque(buf, 3, entry[0]) - push_bytes(buf, entry[0]) - with push_block(buf, 2): + push_opaque(buf, 2, entry[1]) - push_bytes(buf, entry[1]) push_list(buf, 3, push_certificate_entry, certificate.certificates) ===========changed ref 5=========== # module: aioquic.tls def pull_certificate(buf: Buffer) -> Certificate: certificate = Certificate() assert pull_uint8(buf) == HandshakeType.CERTIFICATE with pull_block(buf, 3): - with pull_block(buf, 1) as length: + certificate.request_context = pull_opaque(buf, 1) - certificate.request_context = pull_bytes(buf, length) def pull_certificate_entry(buf: Buffer) -> CertificateEntry: - with pull_block(buf, 3) as length: + data = pull_opaque(buf, 3) - data = pull_bytes(buf, length) - with pull_block(buf, 2) as length: + extensions = pull_opaque(buf, 2) - extensions = pull_bytes(buf, length) return (data, extensions) certificate.certificates = pull_list(buf, 3, pull_certificate_entry) return certificate ===========changed ref 6=========== # module: aioquic.tls + @dataclass + class OfferedPsks: + identities: List[PskIdentity] + binders: List[bytes] + ===========changed ref 7=========== # module: aioquic.tls def push_new_session_ticket(buf: Buffer, new_session_ticket: NewSessionTicket) -> None: push_uint8(buf, HandshakeType.NEW_SESSION_TICKET) with push_block(buf, 3): push_uint32(buf, new_session_ticket.ticket_lifetime) push_uint32(buf, new_session_ticket.ticket_age_add) - with push_block(buf, 1): + push_opaque(buf, 1, new_session_ticket.ticket_nonce) - push_bytes(buf, new_session_ticket.ticket_nonce) - with push_block(buf, 2): + push_opaque(buf, 2, new_session_ticket.ticket) - push_bytes(buf, new_session_ticket.ticket) push_list(buf, 2, push_raw_extension, new_session_ticket.extensions) ===========changed ref 8=========== # module: aioquic.tls + def push_psk_binder(buf: Buffer, binder: bytes) -> None: + push_opaque(buf, 1, binder) + ===========changed ref 9=========== # module: aioquic.tls + def pull_psk_binder(buf: Buffer) -> bytes: + return pull_opaque(buf, 1) + ===========changed ref 10=========== # module: aioquic.tls + def push_psk_identity(buf: Buffer, entry: PskIdentity) -> None: + push_opaque(buf, 2, entry[0]) + push_uint32(buf, entry[1]) + ===========changed ref 11=========== # module: aioquic.tls def pull_new_session_ticket(buf: Buffer) -> NewSessionTicket: new_session_ticket = NewSessionTicket() assert pull_uint8(buf) == HandshakeType.NEW_SESSION_TICKET with pull_block(buf, 3): new_session_ticket.ticket_lifetime = pull_uint32(buf) new_session_ticket.ticket_age_add = pull_uint32(buf) - with pull_block(buf, 1) as length: + new_session_ticket.ticket_nonce = pull_opaque(buf, 1) - new_session_ticket.ticket_nonce = pull_bytes(buf, length) - with pull_block(buf, 2) as length: + new_session_ticket.ticket = pull_opaque(buf, 2) - new_session_ticket.ticket = pull_bytes(buf, length) new_session_ticket.extensions = pull_list(buf, 2, pull_raw_extension) return new_session_ticket ===========changed ref 12=========== # module: aioquic.tls + def pull_psk_identity(buf: Buffer) -> PskIdentity: + identity = pull_opaque(buf, 2) + obfuscated_ticket_age = pull_uint32(buf) + return (identity, obfuscated_ticket_age) + ===========changed ref 13=========== # module: aioquic.tls # ALPN def pull_alpn_protocol(buf: Buffer) -> str: - length = pull_uint8(buf) + return pull_opaque(buf, 1).decode("ascii") - return pull_bytes(buf, length).decode("ascii")
aioquic.tls/Context.__init__
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<10>:<add> self.session_ticket: Optional[SessionTicket] = None <13>:<add> self.new_session_ticket_cb: NewSessionTicketHandler = lambda t: None <del> self.session_ticket_cb: SessionTicketHandler = lambda t: None
# module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): <0> self.alpn_negotiated: Optional[str] = None <1> self.alpn_protocols: Optional[List[str]] = None <2> self.certificate: Optional[x509.Certificate] = None <3> self.certificate_private_key: Optional[ <4> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] <5> ] = None <6> self.handshake_extensions: List[Extension] = [] <7> self.is_client = is_client <8> self.key_schedule: Optional[KeySchedule] = None <9> self.received_extensions: List[Extension] = [] <10> self.server_name: Optional[str] = None <11> <12> # callbacks <13> self.session_ticket_cb: SessionTicketHandler = lambda t: None <14> self.update_traffic_key_cb: Callable[ <15> [Direction, Epoch, bytes], None <16> ] = lambda d, e, s: None <17> <18> self._cipher_suites = [ <19> CipherSuite.AES_256_GCM_SHA384, <20> CipherSuite.AES_128_GCM_SHA256, <21> CipherSuite.CHACHA20_POLY1305_SHA256, <22> ] <23> self._compression_methods = [CompressionMethod.NULL] <24> self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] <25> self._signature_algorithms = [ <26> SignatureAlgorithm.RSA_PSS_RSAE_SHA256, <27> SignatureAlgorithm.ECDSA_SECP256R1_SHA256, <28> SignatureAlgorithm.RSA_PKCS1_SHA256, <29> SignatureAlgorithm.RSA_PKCS1_SHA1, <30> ] <31> self._supported_groups = [Group.SECP256R1] <32> self._supported_versions = [TLS_VERSION_1_3</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.buffer.Buffer data_slice(start: int, end: int) -> bytes tell() -> int at: aioquic.tls T = TypeVar("T") Alert(*args: object) CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) SIGNATURE_ALGORITHMS = { SignatureAlgorithm.ECDSA_SECP256R1_SHA256: (None, hashes.SHA256), SignatureAlgorithm.ECDSA_SECP384R1_SHA384: (None, hashes.SHA384), SignatureAlgorithm.ECDSA_SECP521R1_SHA512: (None, hashes.SHA512), SignatureAlgorithm.RSA_PKCS1_SHA1: (padding.PKCS1v15, hashes.SHA1), SignatureAlgorithm.RSA_PKCS1_SHA256: (padding.PKCS1v15, hashes.SHA256), SignatureAlgorithm.RSA_PKCS1_SHA384: (padding.PKCS1v15, hashes.SHA384), SignatureAlgorithm.RSA_PKCS1_SHA512: (padding.PKCS1v15, hashes.SHA512), SignatureAlgorithm.RSA_PSS_RSAE_SHA256: (padding.PSS, hashes.SHA256), SignatureAlgorithm.RSA_PSS_RSAE_SHA384: (padding.PSS, hashes.SHA384), SignatureAlgorithm.RSA_PSS_RSAE_SHA512: (padding.PSS, hashes.SHA512), } ===========unchanged ref 1=========== at: aioquic.tls.KeySchedule update_hash(data: bytes) -> None at: aioquic.tls.KeyScheduleProxy update_hash(data: bytes) -> None at: contextlib contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., _GeneratorContextManager[_T]] at: dataclasses dataclass(*, init: bool=..., repr: bool=..., eq: bool=..., order: bool=..., unsafe_hash: bool=..., frozen: bool=...) -> Callable[[Type[_T]], Type[_T]] dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]] dataclass(_cls: Type[_T]) -> Type[_T] at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: datetime.timedelta __slots__ = '_days', '_seconds', '_microseconds', '_hashcode' total_seconds() -> float __radd__ = __add__ __rmul__ = __mul__ at: typing Callable = _CallableType(collections.abc.Callable, 2) Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') List = _alias(list, 1, inst=False, name='List') Generator = _alias(collections.abc.Generator, 3) ===========changed ref 0=========== # module: aioquic.tls - # callback types + NewSessionTicketHandler = Callable[[SessionTicket], None] - SessionTicketHandler = Callable[[NewSessionTicket], None] ===========changed ref 1=========== # module: aioquic.tls def push_finished(buf: Buffer, finished: Finished) -> None: push_uint8(buf, HandshakeType.FINISHED) - with push_block(buf, 3): + push_opaque(buf, 3, finished.verify_data) - push_bytes(buf, finished.verify_data) ===========changed ref 2=========== # module: aioquic.tls def pull_finished(buf: Buffer) -> Finished: finished = Finished() assert pull_uint8(buf) == HandshakeType.FINISHED - with pull_block(buf, 3) as length: + finished.verify_data = pull_opaque(buf, 3) - finished.verify_data = pull_bytes(buf, length) return finished ===========changed ref 3=========== # module: aioquic.tls def push_certificate_verify(buf: Buffer, verify: CertificateVerify) -> None: push_uint8(buf, HandshakeType.CERTIFICATE_VERIFY) with push_block(buf, 3): push_signature_algorithm(buf, verify.algorithm) - with push_block(buf, 2): + push_opaque(buf, 2, verify.signature) - push_bytes(buf, verify.signature) ===========changed ref 4=========== # module: aioquic.tls def pull_certificate_verify(buf: Buffer) -> CertificateVerify: assert pull_uint8(buf) == HandshakeType.CERTIFICATE_VERIFY with pull_block(buf, 3): algorithm = pull_signature_algorithm(buf) - with pull_block(buf, 2) as length: + signature = pull_opaque(buf, 2) - signature = pull_bytes(buf, length) return CertificateVerify(algorithm=algorithm, signature=signature) ===========changed ref 5=========== # module: aioquic.tls def push_certificate(buf: Buffer, certificate: Certificate) -> None: push_uint8(buf, HandshakeType.CERTIFICATE) with push_block(buf, 3): - with push_block(buf, 1): + push_opaque(buf, 1, certificate.request_context) - push_bytes(buf, certificate.request_context) def push_certificate_entry(buf: Buffer, entry: CertificateEntry) -> None: - with push_block(buf, 3): + push_opaque(buf, 3, entry[0]) - push_bytes(buf, entry[0]) - with push_block(buf, 2): + push_opaque(buf, 2, entry[1]) - push_bytes(buf, entry[1]) push_list(buf, 3, push_certificate_entry, certificate.certificates)
aioquic.tls/Context._client_send_hello
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<32>:<add> # PSK <add> if self.session_ticket: <add> tmp_schedule = KeySchedule(self.session_ticket.cipher_suite) <add> tmp_schedule.extract(self.session_ticket.resumption_secret) <add> binder_key = tmp_schedule.derive_secret(b"res binder") <add> binder_length = tmp_schedule.algorithm.digest_size <add> <add> # serialize hello without binder <add> tmp_buf = Buffer(capacity=1024) <add> hello.pre_shared_key = OfferedPsks( <add> identities=[ <add> (self.session_ticket.ticket, self.session_ticket.obfuscated_age) <add> ], <add> binders=[bytes(binder_length)], <add> ) <add> push_client_hello(tmp_buf, hello) <add> <add> # calculate binder <add> tmp_schedule.update_hash( <add>
# module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: <0> key_share: List[KeyShareEntry] = [] <1> supported_groups: List[Group] = [] <2> <3> if Group.SECP256R1 in self._supported_groups: <4> self._ec_private_key = ec.generate_private_key( <5> GROUP_TO_CURVE[Group.SECP256R1](), default_backend() <6> ) <7> key_share.append(encode_public_key(self._ec_private_key.public_key())) <8> supported_groups.append(Group.SECP256R1) <9> <10> if Group.X25519 in self._supported_groups: <11> self._x25519_private_key = x25519.X25519PrivateKey.generate() <12> key_share.append(encode_public_key(self._x25519_private_key.public_key())) <13> supported_groups.append(Group.X25519) <14> <15> assert len(key_share), "no key share entries" <16> <17> hello = ClientHello( <18> random=self.client_random, <19> session_id=self.session_id, <20> cipher_suites=self._cipher_suites, <21> compression_methods=self._compression_methods, <22> alpn_protocols=self.alpn_protocols, <23> key_exchange_modes=self._key_exchange_modes, <24> key_share=key_share, <25> server_name=self.server_name, <26> signature_algorithms=self._signature_algorithms, <27> supported_groups=supported_groups, <28> supported_versions=self._supported_versions, <29> other_extensions=self.handshake_extensions, <30> ) <31> <32> self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) <33> self._key_schedule_proxy.extract(None) <34> <35> with push_message(self._key_schedule_proxy, output_buf): <36> push</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: # offset: 1 self._set_state(State.CLIENT_EXPECT_SERVER_HELLO) ===========unchanged ref 0=========== at: aioquic.tls AlertUnexpectedMessage(*args: object) Epoch() State() HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) at: aioquic.tls.Context _client_handle_hello(input_buf: Buffer, output_buf: Buffer) -> None _client_handle_hello(self, input_buf: Buffer, output_buf: Buffer) -> None _client_handle_encrypted_extensions(input_buf: Buffer) -> None _client_handle_certificate(input_buf: Buffer) -> None _client_handle_certificate_verify(input_buf: Buffer) -> None _client_handle_finished(input_buf: Buffer, output_buf: Buffer) -> None _client_handle_new_session_ticket(input_buf: Buffer) -> None _server_handle_hello(input_buf: Buffer, initial_buf: Buffer, output_buf: Buffer) -> None at: aioquic.tls.Context.__init__ self.state = State.CLIENT_HANDSHAKE_START self.state = State.SERVER_EXPECT_CLIENT_HELLO at: aioquic.tls.Context._set_state self.state = state at: aioquic.tls.Context.handle_message message_type = self._receive_buffer[0] input_buf = Buffer(data=message) ===========changed ref 0=========== # module: aioquic.tls + # callback types + + + @dataclass + class SessionTicket: + @property + def obfuscated_age(self) -> int: + age = int((datetime.datetime.now() - self.not_valid_before).total_seconds()) + return (age + self.age_add) % (1 << 32) + ===========changed ref 1=========== # module: aioquic.tls + # callback types + + + @dataclass + class SessionTicket: + age_add: int + cipher_suite: CipherSuite + not_valid_after: datetime.datetime + not_valid_before: datetime.datetime + resumption_secret: bytes + server_name: str + ticket: bytes + ===========changed ref 2=========== # module: aioquic.tls - # callback types + NewSessionTicketHandler = Callable[[SessionTicket], None] - SessionTicketHandler = Callable[[NewSessionTicket], None] ===========changed ref 3=========== # module: aioquic.tls def push_finished(buf: Buffer, finished: Finished) -> None: push_uint8(buf, HandshakeType.FINISHED) - with push_block(buf, 3): + push_opaque(buf, 3, finished.verify_data) - push_bytes(buf, finished.verify_data) ===========changed ref 4=========== # module: aioquic.tls def pull_finished(buf: Buffer) -> Finished: finished = Finished() assert pull_uint8(buf) == HandshakeType.FINISHED - with pull_block(buf, 3) as length: + finished.verify_data = pull_opaque(buf, 3) - finished.verify_data = pull_bytes(buf, length) return finished ===========changed ref 5=========== # module: aioquic.tls def push_certificate_verify(buf: Buffer, verify: CertificateVerify) -> None: push_uint8(buf, HandshakeType.CERTIFICATE_VERIFY) with push_block(buf, 3): push_signature_algorithm(buf, verify.algorithm) - with push_block(buf, 2): + push_opaque(buf, 2, verify.signature) - push_bytes(buf, verify.signature) ===========changed ref 6=========== # module: aioquic.tls def pull_certificate_verify(buf: Buffer) -> CertificateVerify: assert pull_uint8(buf) == HandshakeType.CERTIFICATE_VERIFY with pull_block(buf, 3): algorithm = pull_signature_algorithm(buf) - with pull_block(buf, 2) as length: + signature = pull_opaque(buf, 2) - signature = pull_bytes(buf, length) return CertificateVerify(algorithm=algorithm, signature=signature) ===========changed ref 7=========== # module: aioquic.tls def push_certificate(buf: Buffer, certificate: Certificate) -> None: push_uint8(buf, HandshakeType.CERTIFICATE) with push_block(buf, 3): - with push_block(buf, 1): + push_opaque(buf, 1, certificate.request_context) - push_bytes(buf, certificate.request_context) def push_certificate_entry(buf: Buffer, entry: CertificateEntry) -> None: - with push_block(buf, 3): + push_opaque(buf, 3, entry[0]) - push_bytes(buf, entry[0]) - with push_block(buf, 2): + push_opaque(buf, 2, entry[1]) - push_bytes(buf, entry[1]) push_list(buf, 3, push_certificate_entry, certificate.certificates) ===========changed ref 8=========== # module: aioquic.tls def pull_certificate(buf: Buffer) -> Certificate: certificate = Certificate() assert pull_uint8(buf) == HandshakeType.CERTIFICATE with pull_block(buf, 3): - with pull_block(buf, 1) as length: + certificate.request_context = pull_opaque(buf, 1) - certificate.request_context = pull_bytes(buf, length) def pull_certificate_entry(buf: Buffer) -> CertificateEntry: - with pull_block(buf, 3) as length: + data = pull_opaque(buf, 3) - data = pull_bytes(buf, length) - with pull_block(buf, 2) as length: + extensions = pull_opaque(buf, 2) - extensions = pull_bytes(buf, length) return (data, extensions) certificate.certificates = pull_list(buf, 3, pull_certificate_entry) return certificate ===========changed ref 9=========== # module: aioquic.tls + @dataclass + class OfferedPsks: + identities: List[PskIdentity] + binders: List[bytes] + ===========changed ref 10=========== # module: aioquic.tls def push_new_session_ticket(buf: Buffer, new_session_ticket: NewSessionTicket) -> None: push_uint8(buf, HandshakeType.NEW_SESSION_TICKET) with push_block(buf, 3): push_uint32(buf, new_session_ticket.ticket_lifetime) push_uint32(buf, new_session_ticket.ticket_age_add) - with push_block(buf, 1): + push_opaque(buf, 1, new_session_ticket.ticket_nonce) - push_bytes(buf, new_session_ticket.ticket_nonce) - with push_block(buf, 2): + push_opaque(buf, 2, new_session_ticket.ticket) - push_bytes(buf, new_session_ticket.ticket) push_list(buf, 2, push_raw_extension, new_session_ticket.extensions) ===========changed ref 11=========== # module: aioquic.tls + def push_psk_binder(buf: Buffer, binder: bytes) -> None: + push_opaque(buf, 1, binder) + ===========changed ref 12=========== # module: aioquic.tls + def pull_psk_binder(buf: Buffer) -> bytes: + return pull_opaque(buf, 1) + ===========changed ref 13=========== # module: aioquic.tls + def push_psk_identity(buf: Buffer, entry: PskIdentity) -> None: + push_opaque(buf, 2, entry[0]) + push_uint32(buf, entry[1]) +
aioquic.tls/Context._client_handle_finished
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<16>:<add> with push_message(self.key_schedule, output_buf): <add> push_finished( <del> push_finished( <17>:<add> output_buf, <del> output_buf, <18>:<add> Finished( <add> verify_data=self.key_schedule.finished_verify_data(self._enc_key) <del> Finished(verify_data=self.key_schedule.finished_verify_data(self._enc_key)), <19>:<add> ), <add> ) <del> )
# module: aioquic.tls class Context: def _client_handle_finished(self, input_buf: Buffer, output_buf: Buffer) -> None: <0> finished = pull_finished(input_buf) <1> <2> # check verify data <3> expected_verify_data = self.key_schedule.finished_verify_data(self._dec_key) <4> assert finished.verify_data == expected_verify_data <5> self.key_schedule.update_hash(input_buf.data) <6> <7> # prepare traffic keys <8> assert self.key_schedule.generation == 2 <9> self.key_schedule.extract(None) <10> self._setup_traffic_protection( <11> Direction.DECRYPT, Epoch.ONE_RTT, b"s ap traffic" <12> ) <13> next_enc_key = self.key_schedule.derive_secret(b"c ap traffic") <14> <15> # send finished <16> push_finished( <17> output_buf, <18> Finished(verify_data=self.key_schedule.finished_verify_data(self._enc_key)), <19> ) <20> <21> # commit traffic key <22> self._enc_key = next_enc_key <23> self.update_traffic_key_cb(Direction.ENCRYPT, Epoch.ONE_RTT, self._enc_key) <24> <25> self._set_state(State.CLIENT_POST_HANDSHAKE) <26>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls State() push_client_hello(buf: Buffer, hello: ClientHello) -> None pull_server_hello(buf: Buffer) -> ServerHello KeyScheduleProxy(cipher_suites: List[CipherSuite]) decode_public_key(key_share: KeyShareEntry) -> Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey] push_message(key_schedule: Union[KeySchedule, KeyScheduleProxy], buf: Buffer) -> Generator at: aioquic.tls.ClientHello cipher_suites: List[CipherSuite] pre_shared_key: Optional[OfferedPsks] = None at: aioquic.tls.Context _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None at: aioquic.tls.Context._client_send_hello self._x25519_private_key = x25519.X25519PrivateKey.generate() ===========unchanged ref 1=========== hello = ClientHello( random=self.client_random, session_id=self.session_id, cipher_suites=self._cipher_suites, compression_methods=self._compression_methods, alpn_protocols=self.alpn_protocols, key_exchange_modes=self._key_exchange_modes, key_share=key_share, server_name=self.server_name, signature_algorithms=self._signature_algorithms, supported_groups=supported_groups, supported_versions=self._supported_versions, other_extensions=self.handshake_extensions, ) tmp_schedule = KeySchedule(self.session_ticket.cipher_suite) binder_key = tmp_schedule.derive_secret(b"res binder") at: aioquic.tls.Context._server_handle_hello self._x25519_private_key = x25519.X25519PrivateKey.generate() at: aioquic.tls.KeySchedule finished_verify_data(secret: bytes) -> bytes at: aioquic.tls.KeyScheduleProxy extract(key_material: Optional[bytes]=None) -> None at: aioquic.tls.OfferedPsks binders: List[bytes] at: aioquic.tls.ServerHello cipher_suite: CipherSuite compression_method: CompressionMethod key_share: Optional[KeyShareEntry] = None supported_version: Optional[int] = None ===========changed ref 0=========== # module: aioquic.tls def pull_server_hello(buf: Buffer) -> ServerHello: assert pull_uint8(buf) == HandshakeType.SERVER_HELLO with pull_block(buf, 3): assert pull_uint16(buf) == TLS_VERSION_1_2 server_random = pull_bytes(buf, 32) - session_id_length = pull_uint8(buf) hello = ServerHello( random=server_random, + session_id=pull_opaque(buf, 1), - session_id=pull_bytes(buf, session_id_length), cipher_suite=pull_cipher_suite(buf), compression_method=pull_compression_method(buf), ) # extensions def pull_extension(buf: Buffer) -> None: extension_type = pull_uint16(buf) extension_length = pull_uint16(buf) if extension_type == ExtensionType.SUPPORTED_VERSIONS: hello.supported_version = pull_uint16(buf) elif extension_type == ExtensionType.KEY_SHARE: hello.key_share = pull_key_share(buf) else: pull_bytes(buf, extension_length) pull_list(buf, 2, pull_extension) return hello ===========changed ref 1=========== # module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: push_uint8(buf, HandshakeType.CLIENT_HELLO) with push_block(buf, 3): push_uint16(buf, TLS_VERSION_1_2) push_bytes(buf, hello.random) - with push_block(buf, 1): + push_opaque(buf, 1, hello.session_id) - push_bytes(buf, hello.session_id) push_list(buf, 2, push_cipher_suite, hello.cipher_suites) push_list(buf, 1, push_compression_method, hello.compression_methods) # extensions with push_block(buf, 2): with push_extension(buf, ExtensionType.KEY_SHARE): push_list(buf, 2, push_key_share, hello.key_share) with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): push_list(buf, 1, push_uint16, hello.supported_versions) with push_extension(buf, ExtensionType.SIGNATURE_ALGORITHMS): push_list(buf, 2, push_signature_algorithm, hello.signature_algorithms) with push_extension(buf, ExtensionType.SUPPORTED_GROUPS): push_list(buf, 2, push_group, hello.supported_groups) with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): push_list(buf, 1, push_key_exchange_mode, hello.key_exchange_modes) if hello.server_name is not None: with push_extension(buf, ExtensionType.SERVER_NAME): with push_block(buf, 2): push_uint8(buf, 0) - with push_block(buf, 2): + push_opaque(buf, 2, hello.server_name.encode("ascii")) - push_bytes(buf, hello.server_name.encode("ascii")) if hello.al</s> ===========changed ref 2=========== # module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: # offset: 1 <s>ascii")) - push_bytes(buf, hello.server_name.encode("ascii")) if hello.alpn_protocols is not None: with push_extension(buf, ExtensionType.ALPN): push_list(buf, 2, push_alpn_protocol, hello.alpn_protocols) for extension_type, extension_value in hello.other_extensions: with push_extension(buf, extension_type): push_bytes(buf, extension_value) ===========changed ref 3=========== # module: aioquic.tls + # callback types + + + @dataclass + class SessionTicket: + @property + def obfuscated_age(self) -> int: + age = int((datetime.datetime.now() - self.not_valid_before).total_seconds()) + return (age + self.age_add) % (1 << 32) + ===========changed ref 4=========== # module: aioquic.tls + # callback types + + + @dataclass + class SessionTicket: + age_add: int + cipher_suite: CipherSuite + not_valid_after: datetime.datetime + not_valid_before: datetime.datetime + resumption_secret: bytes + server_name: str + ticket: bytes +
aioquic.tls/Context._client_handle_new_session_ticket
Modified
aiortc~aioquic
4e5d8225a1090a7c2c37135a456c0b3c6d0efd29
[tls] add code to support session ticket parsing / serialization
<0>:<add> new_session_ticket = pull_new_session_ticket(input_buf) <del> ticket = pull_new_session_ticket(input_buf) <1>:<del> self.session_ticket_cb(ticket)
# module: aioquic.tls class Context: def _client_handle_new_session_ticket(self, input_buf: Buffer) -> None: <0> ticket = pull_new_session_ticket(input_buf) <1> self.session_ticket_cb(ticket) <2>
===========unchanged ref 0=========== at: aioquic.tls.Context.__init__ self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None at: aioquic.tls.Context._client_handle_hello peer_public_key = decode_public_key(peer_hello.key_share) at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) at: aioquic.tls.Context._server_handle_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) ===========changed ref 0=========== # module: aioquic.tls + # callback types + + + @dataclass + class SessionTicket: + @property + def obfuscated_age(self) -> int: + age = int((datetime.datetime.now() - self.not_valid_before).total_seconds()) + return (age + self.age_add) % (1 << 32) + ===========changed ref 1=========== # module: aioquic.tls + # callback types + + + @dataclass + class SessionTicket: + age_add: int + cipher_suite: CipherSuite + not_valid_after: datetime.datetime + not_valid_before: datetime.datetime + resumption_secret: bytes + server_name: str + ticket: bytes + ===========changed ref 2=========== # module: aioquic.tls - # callback types + NewSessionTicketHandler = Callable[[SessionTicket], None] - SessionTicketHandler = Callable[[NewSessionTicket], None] ===========changed ref 3=========== # module: aioquic.tls class Context: def _client_handle_finished(self, input_buf: Buffer, output_buf: Buffer) -> None: finished = pull_finished(input_buf) # check verify data expected_verify_data = self.key_schedule.finished_verify_data(self._dec_key) assert finished.verify_data == expected_verify_data self.key_schedule.update_hash(input_buf.data) # prepare traffic keys assert self.key_schedule.generation == 2 self.key_schedule.extract(None) self._setup_traffic_protection( Direction.DECRYPT, Epoch.ONE_RTT, b"s ap traffic" ) next_enc_key = self.key_schedule.derive_secret(b"c ap traffic") # send finished + with push_message(self.key_schedule, output_buf): + push_finished( - push_finished( + output_buf, - output_buf, + Finished( + verify_data=self.key_schedule.finished_verify_data(self._enc_key) - Finished(verify_data=self.key_schedule.finished_verify_data(self._enc_key)), + ), + ) - ) # commit traffic key self._enc_key = next_enc_key self.update_traffic_key_cb(Direction.ENCRYPT, Epoch.ONE_RTT, self._enc_key) self._set_state(State.CLIENT_POST_HANDSHAKE) ===========changed ref 4=========== # module: aioquic.tls def push_finished(buf: Buffer, finished: Finished) -> None: push_uint8(buf, HandshakeType.FINISHED) - with push_block(buf, 3): + push_opaque(buf, 3, finished.verify_data) - push_bytes(buf, finished.verify_data) ===========changed ref 5=========== # module: aioquic.tls def pull_finished(buf: Buffer) -> Finished: finished = Finished() assert pull_uint8(buf) == HandshakeType.FINISHED - with pull_block(buf, 3) as length: + finished.verify_data = pull_opaque(buf, 3) - finished.verify_data = pull_bytes(buf, length) return finished ===========changed ref 6=========== # module: aioquic.tls def push_certificate_verify(buf: Buffer, verify: CertificateVerify) -> None: push_uint8(buf, HandshakeType.CERTIFICATE_VERIFY) with push_block(buf, 3): push_signature_algorithm(buf, verify.algorithm) - with push_block(buf, 2): + push_opaque(buf, 2, verify.signature) - push_bytes(buf, verify.signature) ===========changed ref 7=========== # module: aioquic.tls def pull_certificate_verify(buf: Buffer) -> CertificateVerify: assert pull_uint8(buf) == HandshakeType.CERTIFICATE_VERIFY with pull_block(buf, 3): algorithm = pull_signature_algorithm(buf) - with pull_block(buf, 2) as length: + signature = pull_opaque(buf, 2) - signature = pull_bytes(buf, length) return CertificateVerify(algorithm=algorithm, signature=signature) ===========changed ref 8=========== # module: aioquic.tls def push_certificate(buf: Buffer, certificate: Certificate) -> None: push_uint8(buf, HandshakeType.CERTIFICATE) with push_block(buf, 3): - with push_block(buf, 1): + push_opaque(buf, 1, certificate.request_context) - push_bytes(buf, certificate.request_context) def push_certificate_entry(buf: Buffer, entry: CertificateEntry) -> None: - with push_block(buf, 3): + push_opaque(buf, 3, entry[0]) - push_bytes(buf, entry[0]) - with push_block(buf, 2): + push_opaque(buf, 2, entry[1]) - push_bytes(buf, entry[1]) push_list(buf, 3, push_certificate_entry, certificate.certificates) ===========changed ref 9=========== # module: aioquic.tls def pull_certificate(buf: Buffer) -> Certificate: certificate = Certificate() assert pull_uint8(buf) == HandshakeType.CERTIFICATE with pull_block(buf, 3): - with pull_block(buf, 1) as length: + certificate.request_context = pull_opaque(buf, 1) - certificate.request_context = pull_bytes(buf, length) def pull_certificate_entry(buf: Buffer) -> CertificateEntry: - with pull_block(buf, 3) as length: + data = pull_opaque(buf, 3) - data = pull_bytes(buf, length) - with pull_block(buf, 2) as length: + extensions = pull_opaque(buf, 2) - extensions = pull_bytes(buf, length) return (data, extensions) certificate.certificates = pull_list(buf, 3, pull_certificate_entry) return certificate ===========changed ref 10=========== # module: aioquic.tls + @dataclass + class OfferedPsks: + identities: List[PskIdentity] + binders: List[bytes] + ===========changed ref 11=========== # module: aioquic.tls def push_new_session_ticket(buf: Buffer, new_session_ticket: NewSessionTicket) -> None: push_uint8(buf, HandshakeType.NEW_SESSION_TICKET) with push_block(buf, 3): push_uint32(buf, new_session_ticket.ticket_lifetime) push_uint32(buf, new_session_ticket.ticket_age_add) - with push_block(buf, 1): + push_opaque(buf, 1, new_session_ticket.ticket_nonce) - push_bytes(buf, new_session_ticket.ticket_nonce) - with push_block(buf, 2): + push_opaque(buf, 2, new_session_ticket.ticket) - push_bytes(buf, new_session_ticket.ticket) push_list(buf, 2, push_raw_extension, new_session_ticket.extensions)
aioquic.tls/pull_server_hello
Modified
aiortc~aioquic
16d7614749c47c563a33fdb717d8bfe1c000749a
[tls] parse/serialize ServerHello.pre_shared_key
<20>:<add> elif extension_type == ExtensionType.PRE_SHARED_KEY: <add> hello.pre_shared_key = pull_uint16(buf)
# module: aioquic.tls def pull_server_hello(buf: Buffer) -> ServerHello: <0> assert pull_uint8(buf) == HandshakeType.SERVER_HELLO <1> with pull_block(buf, 3): <2> assert pull_uint16(buf) == TLS_VERSION_1_2 <3> server_random = pull_bytes(buf, 32) <4> <5> hello = ServerHello( <6> random=server_random, <7> session_id=pull_opaque(buf, 1), <8> cipher_suite=pull_cipher_suite(buf), <9> compression_method=pull_compression_method(buf), <10> ) <11> <12> # extensions <13> def pull_extension(buf: Buffer) -> None: <14> extension_type = pull_uint16(buf) <15> extension_length = pull_uint16(buf) <16> if extension_type == ExtensionType.SUPPORTED_VERSIONS: <17> hello.supported_version = pull_uint16(buf) <18> elif extension_type == ExtensionType.KEY_SHARE: <19> hello.key_share = pull_key_share(buf) <20> else: <21> pull_bytes(buf, extension_length) <22> <23> pull_list(buf, 2, pull_extension) <24> <25> return hello <26>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) pull_bytes(buf: Buffer, length: int) -> bytes pull_uint8(buf: Buffer) -> int pull_uint16(buf: Buffer) -> int at: aioquic.tls TLS_VERSION_1_2 = 0x0303 ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) pull_cipher_suite(buf: Buffer) -> CipherSuite pull_compression_method(buf: Buffer) -> CompressionMethod pull_block(buf: Buffer, capacity: int) -> Generator pull_opaque(buf: Buffer, capacity: int) -> bytes pull_key_share(buf: Buffer) -> KeyShareEntry ServerHello(random: bytes, session_id: bytes, cipher_suite: CipherSuite, compression_method: CompressionMethod, key_share: Optional[KeyShareEntry]=None, pre_shared_key: Optional[int]=None, supported_version: Optional[int]=None) at: aioquic.tls.ServerHello random: bytes session_id: bytes cipher_suite: CipherSuite compression_method: CompressionMethod key_share: Optional[KeyShareEntry] = None pre_shared_key: Optional[int] = None supported_version: Optional[int] = None ===========changed ref 0=========== # module: aioquic.tls @dataclass class ServerHello: random: bytes session_id: bytes cipher_suite: CipherSuite compression_method: CompressionMethod # extensions key_share: Optional[KeyShareEntry] = None + pre_shared_key: Optional[int] = None supported_version: Optional[int] = None
tests.test_tls/TlsTest.test_pull_server_hello
Modified
aiortc~aioquic
16d7614749c47c563a33fdb717d8bfe1c000749a
[tls] parse/serialize ServerHello.pre_shared_key
<29>:<add> self.assertEqual(hello.pre_shared_key, None)
# module: tests.test_tls class TlsTest(TestCase): def test_pull_server_hello(self): <0> buf = Buffer(data=load("tls_server_hello.bin")) <1> hello = pull_server_hello(buf) <2> self.assertTrue(buf.eof()) <3> <4> self.assertEqual( <5> hello.random, <6> binascii.unhexlify( <7> "ada85271d19680c615ea7336519e3fdf6f1e26f3b1075ee1de96ffa8884e8280" <8> ), <9> ) <10> self.assertEqual( <11> hello.session_id, <12> binascii.unhexlify( <13> "9aee82a2d186c1cb32a329d9dcfe004a1a438ad0485a53c6bfcf55c132a23235" <14> ), <15> ) <16> self.assertEqual(hello.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384) <17> self.assertEqual(hello.compression_method, tls.CompressionMethod.NULL) <18> self.assertEqual( <19> hello.key_share, <20> ( <21> tls.Group.SECP256R1, <22> binascii.unhexlify( <23> "048b27d0282242d84b7fcc02a9c4f13eca0329e3c7029aa34a33794e6e7ba189" <24> "5cca1c503bf0378ac6937c354912116ff3251026bca1958d7f387316c83ae6cf" <25> "b2" <26> ), <27> ), <28> ) <29> self.assertEqual(hello.supported_version, tls.TLS_VERSION_1_3) <30>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.buffer.Buffer eof() -> bool at: aioquic.tls CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_server_hello(buf: Buffer) -> ServerHello at: aioquic.tls.ServerHello random: bytes session_id: bytes cipher_suite: CipherSuite compression_method: CompressionMethod key_share: Optional[KeyShareEntry] = None pre_shared_key: Optional[int] = None supported_version: Optional[int] = None at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.utils load(name) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.tls def pull_server_hello(buf: Buffer) -> ServerHello: assert pull_uint8(buf) == HandshakeType.SERVER_HELLO with pull_block(buf, 3): assert pull_uint16(buf) == TLS_VERSION_1_2 server_random = pull_bytes(buf, 32) hello = ServerHello( random=server_random, session_id=pull_opaque(buf, 1), cipher_suite=pull_cipher_suite(buf), compression_method=pull_compression_method(buf), ) # extensions def pull_extension(buf: Buffer) -> None: extension_type = pull_uint16(buf) extension_length = pull_uint16(buf) if extension_type == ExtensionType.SUPPORTED_VERSIONS: hello.supported_version = pull_uint16(buf) elif extension_type == ExtensionType.KEY_SHARE: hello.key_share = pull_key_share(buf) + elif extension_type == ExtensionType.PRE_SHARED_KEY: + hello.pre_shared_key = pull_uint16(buf) else: pull_bytes(buf, extension_length) pull_list(buf, 2, pull_extension) return hello ===========changed ref 1=========== # module: aioquic.tls @dataclass class ServerHello: random: bytes session_id: bytes cipher_suite: CipherSuite compression_method: CompressionMethod # extensions key_share: Optional[KeyShareEntry] = None + pre_shared_key: Optional[int] = None supported_version: Optional[int] = None
aioquic.tls/Context.__init__
Modified
aiortc~aioquic
c676681373134e5869677b58718e32956794de73
[tls] handle pre_shared_key in ServerHello
# module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): <0> self.alpn_negotiated: Optional[str] = None <1> self.alpn_protocols: Optional[List[str]] = None <2> self.certificate: Optional[x509.Certificate] = None <3> self.certificate_private_key: Optional[ <4> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] <5> ] = None <6> self.handshake_extensions: List[Extension] = [] <7> self.is_client = is_client <8> self.key_schedule: Optional[KeySchedule] = None <9> self.received_extensions: List[Extension] = [] <10> self.session_ticket: Optional[SessionTicket] = None <11> self.server_name: Optional[str] = None <12> <13> # callbacks <14> self.new_session_ticket_cb: NewSessionTicketHandler = lambda t: None <15> self.update_traffic_key_cb: Callable[ <16> [Direction, Epoch, bytes], None <17> ] = lambda d, e, s: None <18> <19> self._cipher_suites = [ <20> CipherSuite.AES_256_GCM_SHA384, <21> CipherSuite.AES_128_GCM_SHA256, <22> CipherSuite.CHACHA20_POLY1305_SHA256, <23> ] <24> self._compression_methods = [CompressionMethod.NULL] <25> self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] <26> self._signature_algorithms = [ <27> SignatureAlgorithm.RSA_PSS_RSAE_SHA256, <28> SignatureAlgorithm.ECDSA_SECP256R1_SHA256, <29> SignatureAlgorithm.RSA_PKCS1_SHA256, <30> SignatureAlgorithm.RSA_PKCS1_SHA1, <31> ] <32> self._supported_groups = [Group.SECP256R</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========unchanged ref 0=========== at: aioquic.tls TLS_VERSION_1_3 = 0x0304 Direction() Epoch() State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeyExchangeMode(x: Union[str, bytes, bytearray], base: int) KeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Extension = Tuple[int, bytes] KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes) NewSessionTicketHandler = Callable[[SessionTicket], None] at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol self.received_extensions = encrypted_extensions.other_extensions ===========unchanged ref 1=========== at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) self._key_schedule_psk = None at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) self.client_random = peer_hello.random self.session_id = peer_hello.session_id self.received_extensions = peer_hello.other_extensions self.key_schedule = KeySchedule(cipher_suite) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) at: aioquic.tls.Context._set_state self.state = state at: aioquic.tls.Context._setup_traffic_protection self._enc_key = key ===========unchanged ref 2=========== self._dec_key = key at: aioquic.tls.Context.handle_message self._receive_buffer += input_data self._receive_buffer = self._receive_buffer[message_length:] at: logging Logger(name: str, level: _Level=...) LoggerAdapter(logger: Logger, extra: Mapping[str, Any]) at: os urandom(size: int, /) -> bytes at: typing Callable = _CallableType(collections.abc.Callable, 2) List = _alias(list, 1, inst=False, name='List')
aioquic.tls/Context._client_send_hello
Modified
aiortc~aioquic
c676681373134e5869677b58718e32956794de73
[tls] handle pre_shared_key in ServerHello
<34>:<add> self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) <del> tmp_schedule = KeySchedule(self.session_ticket.cipher_suite) <35>:<add> self._key_schedule_psk.extract(self.session_ticket.resumption_secret) <del> tmp_schedule.extract(self.session_ticket.resumption_secret) <36>:<add> binder_key = self._key_schedule_psk.derive_secret(b"res binder") <del> binder_key
# module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: <0> key_share: List[KeyShareEntry] = [] <1> supported_groups: List[Group] = [] <2> <3> if Group.SECP256R1 in self._supported_groups: <4> self._ec_private_key = ec.generate_private_key( <5> GROUP_TO_CURVE[Group.SECP256R1](), default_backend() <6> ) <7> key_share.append(encode_public_key(self._ec_private_key.public_key())) <8> supported_groups.append(Group.SECP256R1) <9> <10> if Group.X25519 in self._supported_groups: <11> self._x25519_private_key = x25519.X25519PrivateKey.generate() <12> key_share.append(encode_public_key(self._x25519_private_key.public_key())) <13> supported_groups.append(Group.X25519) <14> <15> assert len(key_share), "no key share entries" <16> <17> hello = ClientHello( <18> random=self.client_random, <19> session_id=self.session_id, <20> cipher_suites=self._cipher_suites, <21> compression_methods=self._compression_methods, <22> alpn_protocols=self.alpn_protocols, <23> key_exchange_modes=self._key_exchange_modes, <24> key_share=key_share, <25> server_name=self.server_name, <26> signature_algorithms=self._signature_algorithms, <27> supported_groups=supported_groups, <28> supported_versions=self._supported_versions, <29> other_extensions=self.handshake_extensions, <30> ) <31> <32> # PSK <33> if self.session_ticket: <34> tmp_schedule = KeySchedule(self.session_ticket.cipher_suite) <35> tmp_schedule.extract(self.session_ticket.resumption_secret) <36> binder_key</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: # offset: 1 binder_length = tmp_schedule.algorithm.digest_size # serialize hello without binder tmp_buf = Buffer(capacity=1024) hello.pre_shared_key = OfferedPsks( identities=[ (self.session_ticket.ticket, self.session_ticket.obfuscated_age) ], binders=[bytes(binder_length)], ) push_client_hello(tmp_buf, hello) # calculate binder tmp_schedule.update_hash( tmp_buf.data_slice(0, tmp_buf.tell() - binder_length - 3) ) hello.pre_shared_key.binders[0] = tmp_schedule.finished_verify_data( binder_key ) self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) self._key_schedule_proxy.extract(None) with push_message(self._key_schedule_proxy, output_buf): push_client_hello(output_buf, hello) self._set_state(State.CLIENT_EXPECT_SERVER_HELLO) ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.buffer.Buffer data_slice(start: int, end: int) -> bytes tell() -> int at: aioquic.tls Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeyShareEntry = Tuple[Group, bytes] OfferedPsks(identities: List[PskIdentity], binders: List[bytes]) ClientHello(random: bytes, session_id: bytes, cipher_suites: List[CipherSuite], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, key_exchange_modes: Optional[List[KeyExchangeMode]]=None, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list)) push_client_hello(buf: Buffer, hello: ClientHello) -> None KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) GROUP_TO_CURVE = { Group.SECP256R1: ec.SECP256R1, Group.SECP384R1: ec.SECP384R1, Group.SECP521R1: ec.SECP521R1, } encode_public_key(public_key: Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey]) -> KeyShareEntry push_message(key_schedule: Union[KeySchedule, KeyScheduleProxy], buf: Buffer) -> Generator ===========unchanged ref 1=========== at: aioquic.tls.ClientHello random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] alpn_protocols: Optional[List[str]] = None key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) at: aioquic.tls.Context.__init__ self.alpn_protocols: Optional[List[str]] = None self.handshake_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_psk: Optional[KeySchedule] = None ===========unchanged ref 2=========== self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None self.client_random = None self.client_random = os.urandom(32) self.session_id = None self.session_id = os.urandom(32) at: aioquic.tls.Context._client_handle_hello self._key_schedule_psk = None at: aioquic.tls.Context._server_handle_hello self.client_random = peer_hello.random self.session_id = peer_hello.session_id self._x25519_private_key = x25519.X25519PrivateKey.generate() self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) at: aioquic.tls.KeySchedule finished_verify_data(secret: bytes) -> bytes derive_secret(label: bytes) -> bytes extract(key_material: Optional[bytes]=None) -> None update_hash(data: bytes) -> None at: aioquic.tls.KeySchedule.__init__ self.algorithm = cipher_suite_hash(cipher_suite) at: aioquic.tls.KeyScheduleProxy extract(key_material: Optional[bytes]=None) -> None at: aioquic.tls.OfferedPsks identities: List[PskIdentity] binders: List[bytes] at: aioquic.tls.SessionTicket age_add: int cipher_suite: CipherSuite not_valid_after: datetime.datetime not_valid_before: datetime.datetime resumption_secret: bytes server_name: str ticket: bytes ===========unchanged ref 3=========== at: typing List = _alias(list, 1, inst=False, name='List')
aioquic.tls/Context._client_handle_hello
Modified
aiortc~aioquic
c676681373134e5869677b58718e32956794de73
[tls] handle pre_shared_key in ServerHello
<5>:<add> <add> # select key schedule <add> if self._key_schedule_psk is not None and peer_hello.pre_shared_key is not None: <add> assert peer_hello.pre_shared_key == 0 <add> self.key_schedule = self._key_schedule_psk <add> else: <add> self._key_schedule_psk = None <add> self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) <23>:<del> self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite)
# module: aioquic.tls class Context: def _client_handle_hello(self, input_buf: Buffer, output_buf: Buffer) -> None: <0> peer_hello = pull_server_hello(input_buf) <1> <2> assert peer_hello.cipher_suite in self._cipher_suites <3> assert peer_hello.compression_method in self._compression_methods <4> assert peer_hello.supported_version in self._supported_versions <5> <6> # perform key exchange <7> peer_public_key = decode_public_key(peer_hello.key_share) <8> shared_key: Optional[bytes] = None <9> if ( <10> isinstance(peer_public_key, x25519.X25519PublicKey) <11> and self._x25519_private_key is not None <12> ): <13> shared_key = self._x25519_private_key.exchange(peer_public_key) <14> elif ( <15> isinstance(peer_public_key, ec.EllipticCurvePublicKey) <16> and self._ec_private_key is not None <17> and self._ec_private_key.public_key().curve.__class__ <18> == peer_public_key.curve.__class__ <19> ): <20> shared_key = self._ec_private_key.exchange(ec.ECDH(), peer_public_key) <21> assert shared_key is not None <22> <23> self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) <24> self.key_schedule.update_hash(input_buf.data) <25> self.key_schedule.extract(shared_key) <26> <27> self._setup_traffic_protection( <28> Direction.DECRYPT, Epoch.HANDSHAKE, b"s hs traffic" <29> ) <30> <31> self._set_state(State.CLIENT_EXPECT_ENCRYPTED_EXTENSIONS) <32>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls State() pull_server_hello(buf: Buffer) -> ServerHello decode_public_key(key_share: KeyShareEntry) -> Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey] at: aioquic.tls.Context _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self.key_schedule: Optional[KeySchedule] = None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) self._x25519_private_key = x25519.X25519PrivateKey.generate() ===========unchanged ref 1=========== self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) at: aioquic.tls.KeyScheduleProxy select(cipher_suite: CipherSuite) -> KeySchedule at: aioquic.tls.ServerHello random: bytes session_id: bytes cipher_suite: CipherSuite compression_method: CompressionMethod key_share: Optional[KeyShareEntry] = None pre_shared_key: Optional[int] = None supported_version: Optional[int] = None ===========changed ref 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.is_client = is_client self.key_schedule: Optional[KeySchedule] = None self.received_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None # callbacks self.new_session_ticket_cb: NewSessionTicketHandler = lambda t: None self.update_traffic_key_cb: Callable[ [Direction, Epoch, bytes], None ] = lambda d, e, s: None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] + self._key_schedule_psk: Optional</s> ===========changed ref 1=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 <s> self._supported_versions = [TLS_VERSION_1_3] + self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO
aioquic.tls/Context._client_handle_encrypted_extensions
Modified
aiortc~aioquic
c676681373134e5869677b58718e32956794de73
[tls] handle pre_shared_key in ServerHello
<9>:<add> if self._key_schedule_psk is not None: <add> self._set_state(State.CLIENT_EXPECT_FINISHED) <add> else: <add> self._set_state(State.CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE) <del> self._set_state(State.CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE)
# module: aioquic.tls class Context: def _client_handle_encrypted_extensions(self, input_buf: Buffer) -> None: <0> encrypted_extensions = pull_encrypted_extensions(input_buf) <1> self.alpn_negotiated = encrypted_extensions.alpn_protocol <2> self.received_extensions = encrypted_extensions.other_extensions <3> <4> self._setup_traffic_protection( <5> Direction.ENCRYPT, Epoch.HANDSHAKE, b"c hs traffic" <6> ) <7> self.key_schedule.update_hash(input_buf.data) <8> <9> self._set_state(State.CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE) <10>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls Direction() Epoch() State() pull_encrypted_extensions(buf: Buffer) -> EncryptedExtensions at: aioquic.tls.Context _setup_traffic_protection(direction: Direction, epoch: Epoch, label: bytes) -> None _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self.key_schedule: Optional[KeySchedule] = None at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) shared_key: Optional[bytes] = None shared_key = self._ec_private_key.exchange(ec.ECDH(), peer_public_key) shared_key = self._x25519_private_key.exchange(peer_public_key) at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) at: aioquic.tls.KeySchedule extract(key_material: Optional[bytes]=None) -> None update_hash(data: bytes) -> None ===========changed ref 0=========== # module: aioquic.tls class Context: def _client_handle_hello(self, input_buf: Buffer, output_buf: Buffer) -> None: peer_hello = pull_server_hello(input_buf) assert peer_hello.cipher_suite in self._cipher_suites assert peer_hello.compression_method in self._compression_methods assert peer_hello.supported_version in self._supported_versions + + # select key schedule + if self._key_schedule_psk is not None and peer_hello.pre_shared_key is not None: + assert peer_hello.pre_shared_key == 0 + self.key_schedule = self._key_schedule_psk + else: + self._key_schedule_psk = None + self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) # perform key exchange peer_public_key = decode_public_key(peer_hello.key_share) shared_key: Optional[bytes] = None if ( isinstance(peer_public_key, x25519.X25519PublicKey) and self._x25519_private_key is not None ): shared_key = self._x25519_private_key.exchange(peer_public_key) elif ( isinstance(peer_public_key, ec.EllipticCurvePublicKey) and self._ec_private_key is not None and self._ec_private_key.public_key().curve.__class__ == peer_public_key.curve.__class__ ): shared_key = self._ec_private_key.exchange(ec.ECDH(), peer_public_key) assert shared_key is not None - self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) self.key_schedule.update_hash(input_buf.data) self.key_schedule.extract(shared_key) self._setup_traffic_protection( Direction.DECRYPT, Epoch</s> ===========changed ref 1=========== # module: aioquic.tls class Context: def _client_handle_hello(self, input_buf: Buffer, output_buf: Buffer) -> None: # offset: 1 <s>_schedule.extract(shared_key) self._setup_traffic_protection( Direction.DECRYPT, Epoch.HANDSHAKE, b"s hs traffic" ) self._set_state(State.CLIENT_EXPECT_ENCRYPTED_EXTENSIONS) ===========changed ref 2=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.is_client = is_client self.key_schedule: Optional[KeySchedule] = None self.received_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None # callbacks self.new_session_ticket_cb: NewSessionTicketHandler = lambda t: None self.update_traffic_key_cb: Callable[ [Direction, Epoch, bytes], None ] = lambda d, e, s: None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] + self._key_schedule_psk: Optional</s> ===========changed ref 3=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 <s> self._supported_versions = [TLS_VERSION_1_3] + self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO
aioquic.tls/Context.__init__
Modified
aiortc~aioquic
45e8c0b4a86930f1682e8bae50f931217cf53329
[client] add support for session resumption
<14>:<add> self.new_session_ticket_cb: SessionTicketHandler = lambda t: None <del> self.new_session_ticket_cb: NewSessionTicketHandler = lambda t: None
# module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): <0> self.alpn_negotiated: Optional[str] = None <1> self.alpn_protocols: Optional[List[str]] = None <2> self.certificate: Optional[x509.Certificate] = None <3> self.certificate_private_key: Optional[ <4> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] <5> ] = None <6> self.handshake_extensions: List[Extension] = [] <7> self.is_client = is_client <8> self.key_schedule: Optional[KeySchedule] = None <9> self.received_extensions: List[Extension] = [] <10> self.session_ticket: Optional[SessionTicket] = None <11> self.server_name: Optional[str] = None <12> <13> # callbacks <14> self.new_session_ticket_cb: NewSessionTicketHandler = lambda t: None <15> self.update_traffic_key_cb: Callable[ <16> [Direction, Epoch, bytes], None <17> ] = lambda d, e, s: None <18> <19> self._cipher_suites = [ <20> CipherSuite.AES_256_GCM_SHA384, <21> CipherSuite.AES_128_GCM_SHA256, <22> CipherSuite.CHACHA20_POLY1305_SHA256, <23> ] <24> self._compression_methods = [CompressionMethod.NULL] <25> self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] <26> self._signature_algorithms = [ <27> SignatureAlgorithm.RSA_PSS_RSAE_SHA256, <28> SignatureAlgorithm.ECDSA_SECP256R1_SHA256, <29> SignatureAlgorithm.RSA_PKCS1_SHA256, <30> SignatureAlgorithm.RSA_PKCS1_SHA1, <31> ] <32> self._supported_groups = [Group.SECP256R</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========unchanged ref 0=========== at: aioquic.tls TLS_VERSION_1_3 = 0x0304 Direction() Epoch() State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeyExchangeMode(x: Union[str, bytes, bytearray], base: int) KeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Extension = Tuple[int, bytes] KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes) SessionTicketHandler = Callable[[SessionTicket], None] at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol self.received_extensions = encrypted_extensions.other_extensions ===========unchanged ref 1=========== at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) self._key_schedule_psk = None at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) self.client_random = peer_hello.random self.session_id = peer_hello.session_id self.received_extensions = peer_hello.other_extensions self.key_schedule = KeySchedule(cipher_suite) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) at: aioquic.tls.Context._set_state self.state = state at: aioquic.tls.Context._setup_traffic_protection self._enc_key = key ===========unchanged ref 2=========== self._dec_key = key at: aioquic.tls.Context.handle_message self._receive_buffer += input_data self._receive_buffer = self._receive_buffer[message_length:] at: logging Logger(name: str, level: _Level=...) LoggerAdapter(logger: Logger, extra: Mapping[str, Any]) at: os urandom(size: int, /) -> bytes at: typing Callable = _CallableType(collections.abc.Callable, 2) List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.tls + SessionTicketHandler = Callable[[SessionTicket], None] - NewSessionTicketHandler = Callable[[SessionTicket], None]
aioquic.connection/QuicConnection.__init__
Modified
aiortc~aioquic
45e8c0b4a86930f1682e8bae50f931217cf53329
[client] add support for session resumption
<s> private_key: Any = None, alpn_protocols: Optional[List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, + session_ticket: Optional[tls.SessionTicket] = None, + session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: <0> if is_client: <1> assert ( <2> original_connection_id is None <3> ), "Cannot set original_connection_id for a client" <4> else: <5> assert certificate is not None, "SSL certificate is required for a server" <6> assert private_key is not None, "SSL private key is required for a server" <7> <8> self.alpn_protocols = alpn_protocols <9> self.certificate = certificate <10> self.is_client = is_client <11> self.host_cid = os.urandom(8) <12> self.peer_cid = os.urandom(8) <13> self.peer_cid_set = False <14> self.peer_token = b"" <15> self.private_key = private_key <16> self.secrets_log_file = secrets_log_file <17> self.server_name = server_name <18> self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} <19> <20> # counters for debugging <21> self._stateless_retry_count = 0 <22> self._version_negotiation_count = 0 <23> <24> self._loop = asyncio.get_event_loop() <25> self.__close: Optional[Dict] = None <26> self.__connected = asyncio.Event() <27> self.__epoch = tls.Epoch.INITIAL <28> self._local_idle_timeout = 60000 # milliseconds <29> self._local_max_data = 1048576 <30> self._local_max_data_used = 0 <31> self._local_max_stream_data</s>
===========below chunk 0=========== <s>: Any = None, alpn_protocols: Optional[List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, + session_ticket: Optional[tls.SessionTicket] = None, + session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 1 self._local_max_stream_data_bidi_remote = 1048576 self._local_max_stream_data_uni = 1048576 self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} ) self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._ping_packet_number: Optional[int] = None self._ping_waiter: Optional[asyncio.Future[None]] = None self._remote_idle_timeout = 0 # milliseconds self._remote_max_data = 0 self._remote_max_data_used = 0 self._remote_max_stream_data_bidi_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._spin_bit = False self._spin_bit_peer = False self._spin_highest_pn = 0 self.__send_pending_task: Optional[asyncio.Handle] = None self.__state = QuicConnectionState.FIRSTFLIGHT self._transport: Optional[asyncio.DatagramTransport] = None self._version: Optional[int] =</s> ===========below chunk 1=========== <s>: Any = None, alpn_protocols: Optional[List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, + session_ticket: Optional[tls.SessionTicket] = None, + session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 2 <s>FLIGHT self._transport: Optional[asyncio.DatagramTransport] = None self._version: Optional[int] = None # callbacks if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None # frame handlers self.__frame_handlers = [ self._handle_padding_frame, self._handle_padding_frame, self._handle_ack_frame, self._handle_ack_frame, self._handle_reset_stream_frame, self._handle_stop_sending_frame, self._handle_crypto_frame, self._handle_new_token_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_max_data_frame, self._handle_max_stream_data_frame, self._handle_max_streams_bidi_frame, self._handle_max_streams_uni_frame, self._handle_data_blocked_frame, self._handle_stream_data_blocked_frame, self._handle_streams_blocked_frame</s> ===========below chunk 2=========== <s>: Any = None, alpn_protocols: Optional[List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, + session_ticket: Optional[tls.SessionTicket] = None, + session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 3 <s> self._handle_streams_blocked_frame, self._handle_new_connection_id_frame, self._handle_retire_connection_id_frame, self._handle_path_challenge_frame, self._handle_path_response_frame, self._handle_connection_close_frame, self._handle_connection_close_frame, ] ===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.connection logger = logging.getLogger("quic") QuicConnectionAdapter(logger: Logger, extra: Mapping[str, Any]) QuicConnectionState() QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None) QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] at: aioquic.connection.QuicConnection supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20] _handle_ack_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_crypto_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_data_blocked_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_max_data_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_max_stream_data_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_max_streams_bidi_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_max_streams_uni_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_new_token_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_padding_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_reset_stream_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None
aioquic.connection/QuicConnection._initialize
Modified
aiortc~aioquic
45e8c0b4a86930f1682e8bae50f931217cf53329
[client] add support for session resumption
<12>:<add> self.tls.session_ticket = self._session_ticket <add> self.tls.new_session_ticket_cb = self._session_ticket_handler
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _initialize(self, peer_cid: bytes) -> None: <0> # TLS <1> self.tls = tls.Context(is_client=self.is_client, logger=self._logger) <2> self.tls.alpn_protocols = self.alpn_protocols <3> self.tls.certificate = self.certificate <4> self.tls.certificate_private_key = self.private_key <5> self.tls.handshake_extensions = [ <6> ( <7> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, <8> self._serialize_transport_parameters(), <9> ) <10> ] <11> self.tls.server_name = self.server_name <12> self.tls.update_traffic_key_cb = self._update_traffic_key <13> <14> # packet spaces <15> self.send_ack = { <16> tls.Epoch.INITIAL: False, <17> tls.Epoch.HANDSHAKE: False, <18> tls.Epoch.ONE_RTT: False, <19> } <20> self.send_buffer = { <21> tls.Epoch.INITIAL: Buffer(capacity=4096), <22> tls.Epoch.HANDSHAKE: Buffer(capacity=4096), <23> tls.Epoch.ONE_RTT: Buffer(capacity=4096), <24> } <25> self.spaces = { <26> tls.Epoch.INITIAL: QuicPacketSpace(), <27> tls.Epoch.HANDSHAKE: QuicPacketSpace(), <28> tls.Epoch.ONE_RTT: QuicPacketSpace(), <29> } <30> self.streams[tls.Epoch.INITIAL] = QuicStream() <31> self.streams[tls.Epoch.HANDSHAKE] = QuicStream() <32> self.streams[tls.Epoch.ONE_RTT] = QuicStream() <33> <34> self.spaces[tls.Epoch.INITIAL].crypto.setup_initial( <35> cid=peer_cid, is_client=self.is_client <36> ) <37> <38> self.packet_number = 0</s>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.connection QuicPacketSpace() at: aioquic.connection.QuicConnection _serialize_transport_parameters() -> bytes _update_traffic_key(direction: tls.Direction, epoch: tls.Epoch, secret: bytes) -> None at: aioquic.connection.QuicConnection.__init__ self.alpn_protocols = alpn_protocols self.certificate = certificate self.is_client = is_client self.private_key = private_key self.server_name = server_name self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} ) self._session_ticket = session_ticket self._session_ticket_handler = lambda t: None self._session_ticket_handler = session_ticket_handler self._stream_handler = lambda r, w: None self._stream_handler = stream_handler at: aioquic.connection.QuicConnection._get_or_create_stream stream = self.streams[stream_id] = QuicStream( connection=self, stream_id=stream_id, max_stream_data_local=max_stream_data_local, max_stream_data_remote=max_stream_data_remote, ) stream = self.streams.get(stream_id, None) max_stream_data_local = self._local_max_stream_data_uni max_stream_data_local = self._local_max_stream_data_bidi_remote max_stream_data_remote = 0 max_stream_data_remote = self._remote_max_stream_data_bidi_local at: aioquic.stream.QuicStream.__init__ self.reader = asyncio.StreamReader() self.reader = None ===========unchanged ref 1=========== self.writer = None self.writer = asyncio.StreamWriter(self, None, self.reader, None) at: aioquic.tls Epoch() ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None) at: aioquic.tls.Context.__init__ self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None self.new_session_ticket_cb: NewSessionTicketHandler = lambda t: None self.update_traffic_key_cb: Callable[ [Direction, Epoch, bytes], None ] = lambda d, e, s: None ===========changed ref 0=========== # module: aioquic.tls + SessionTicketHandler = Callable[[SessionTicket], None] - NewSessionTicketHandler = Callable[[SessionTicket], None] ===========changed ref 1=========== <s> private_key: Any = None, alpn_protocols: Optional[List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, + session_ticket: Optional[tls.SessionTicket] = None, + session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: if is_client: assert ( original_connection_id is None ), "Cannot set original_connection_id for a client" else: assert certificate is not None, "SSL certificate is required for a server" assert private_key is not None, "SSL private key is required for a server" self.alpn_protocols = alpn_protocols self.certificate = certificate self.is_client = is_client self.host_cid = os.urandom(8) self.peer_cid = os.urandom(8) self.peer_cid_set = False self.peer_token = b"" self.private_key = private_key self.secrets_log_file = secrets_log_file self.server_name = server_name self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} # counters for debugging self._stateless_retry_count = 0 self._version_negotiation_count = 0 self._loop = asyncio.get_event_loop() self.__close: Optional[Dict] = None self.__connected = asyncio.Event() self.__epoch = tls.Epoch.INITIAL self._local_idle_timeout = 60000 # milliseconds self._local_max_data = 1048576 self._local_max_data_used = 0 self._local_max_stream_data_bidi_local = 1048576 self._local_max_stream_data_bidi_remote = 1048576 self</s> ===========changed ref 2=========== <s>: Any = None, alpn_protocols: Optional[List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, + session_ticket: Optional[tls.SessionTicket] = None, + session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 1 <s>i_local = 1048576 self._local_max_stream_data_bidi_remote = 1048576 self._local_max_stream_data_uni = 1048576 self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} ) self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._ping_packet_number: Optional[int] = None self._ping_waiter: Optional[asyncio.Future[None]] = None self._remote_idle_timeout = 0 # milliseconds self._remote_max_data = 0 self._remote_max_data_used = 0 self._remote_max_stream_data_bidi_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 + self._session_ticket = session_ticket self._spin_bit = False self._spin_bit_peer = False self._spin_highest_pn = 0 self.__send_pending_</s>
aioquic.client/connect
Modified
aiortc~aioquic
45e8c0b4a86930f1682e8bae50f931217cf53329
[client] add support for session resumption
<12>:<add> * ``session_ticket`` is a TLS session ticket which should be used for <add> resumption. <add> * ``session_ticket_handler`` is a callback which is invoked by the TLS <add> engine when a new session ticket is received.
<s>async def connect( host: str, port: int, *, alpn_protocols: Optional[List[str]] = None, protocol_version: Optional[int] = None, secrets_log_file: Optional[TextIO] = None, + session_ticket: Optional[SessionTicket] = None, + session_ticket_handler: Optional[SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> AsyncGenerator[QuicConnection, None]: <0> """ <1> Connect to a QUIC server at the given `host` and `port`. <2> <3> :meth:`connect()` returns an awaitable. Awaiting it yields a <4> :class:`~aioquic.QuicConnection` which can be used to create streams. <5> <6> :func:`connect` also accepts the following optional arguments: <7> <8> * ``alpn_protocols`` is a list of ALPN protocols to offer in the <9> ClientHello. <10> * ``secrets_log_file`` is a file-like object in which to log traffic <11> secrets. This is useful to analyze traffic captures with Wireshark. <12> * ``stream_handler`` is a callback which is invoked whenever a stream is <13> created. It must accept two arguments: a :class:`asyncio.StreamReader` <14> and a :class:`asyncio.StreamWriter`. <15> """ <16> loop = asyncio.get_event_loop() <17> <18> # if host is not an IP address, pass it to enable SNI <19> try: <20> ipaddress.ip_address(host) <21> server_name = None <22> except ValueError: <23> server_name = host <24> <25> # lookup remote address <26> infos = await loop.getaddrinfo(host, port, type=socket.SOCK_DGRAM) <27> addr = infos[0][4] <28> if len(addr) == 2: <29> addr = ("::ffff:" + addr[0], addr[1], 0, 0) <30> <31> # connect <32> _, protocol = await loop.create_datagram_endpoint(</s>
===========below chunk 0=========== <s> host: str, port: int, *, alpn_protocols: Optional[List[str]] = None, protocol_version: Optional[int] = None, secrets_log_file: Optional[TextIO] = None, + session_ticket: Optional[SessionTicket] = None, + session_ticket_handler: Optional[SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> AsyncGenerator[QuicConnection, None]: # offset: 1 alpn_protocols=alpn_protocols, is_client=True, secrets_log_file=secrets_log_file, server_name=server_name, stream_handler=stream_handler, ), local_addr=("::", 0), ) protocol = cast(QuicConnection, protocol) await protocol.connect(addr, protocol_version=protocol_version) try: yield protocol finally: protocol.close() ===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.connection QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] QuicConnection(*, is_client: bool=True, certificate: Any=None, private_key: Any=None, alpn_protocols: Optional[List[str]]=None, original_connection_id: Optional[bytes]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.tls SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes) SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.events get_event_loop() -> AbstractEventLoop at: asyncio.events.AbstractEventLoop getaddrinfo(host: Optional[str], port: Union[str, int, None], *, family: int=..., type: int=..., proto: int=..., flags: int=...) -> List[Tuple[AddressFamily, SocketKind, int, str, Union[Tuple[str, int], Tuple[str, int, int, int]]]] create_datagram_endpoint(protocol_factory: _ProtocolFactory, local_addr: Optional[Tuple[str, int]]=..., remote_addr: Optional[Tuple[str, int]]=..., *, family: int=..., proto: int=..., flags: int=..., reuse_address: Optional[bool]=..., reuse_port: Optional[bool]=..., allow_broadcast: Optional[bool]=..., sock: Optional[socket]=...) -> _TransProtPair at: contextlib asynccontextmanager(func: Callable[..., AsyncIterator[_T]]) -> Callable[..., AsyncContextManager[_T]] ===========unchanged ref 1=========== at: ipaddress ip_address(address: object) -> Any at: socket SOCK_DGRAM: SocketKind at: typing List = _alias(list, 1, inst=False, name='List') AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2) TextIO() ===========changed ref 0=========== # module: aioquic.tls + SessionTicketHandler = Callable[[SessionTicket], None] - NewSessionTicketHandler = Callable[[SessionTicket], None] ===========changed ref 1=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _initialize(self, peer_cid: bytes) -> None: # TLS self.tls = tls.Context(is_client=self.is_client, logger=self._logger) self.tls.alpn_protocols = self.alpn_protocols self.tls.certificate = self.certificate self.tls.certificate_private_key = self.private_key self.tls.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, self._serialize_transport_parameters(), ) ] self.tls.server_name = self.server_name + self.tls.session_ticket = self._session_ticket + self.tls.new_session_ticket_cb = self._session_ticket_handler self.tls.update_traffic_key_cb = self._update_traffic_key # packet spaces self.send_ack = { tls.Epoch.INITIAL: False, tls.Epoch.HANDSHAKE: False, tls.Epoch.ONE_RTT: False, } self.send_buffer = { tls.Epoch.INITIAL: Buffer(capacity=4096), tls.Epoch.HANDSHAKE: Buffer(capacity=4096), tls.Epoch.ONE_RTT: Buffer(capacity=4096), } self.spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self.streams[tls.Epoch.INITIAL] = QuicStream() self.streams[tls.Epoch.HANDSHAKE] = QuicStream() self.streams[tls.Epoch.ONE_RTT] = QuicStream() self.spaces[tls.Epoch.INITIAL].crypto.setup_initial( cid=peer_cid, is_client=self.is_client ) self.packet_number = 0 ===========changed ref 2=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.is_client = is_client self.key_schedule: Optional[KeySchedule] = None self.received_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None # callbacks + self.new_session_ticket_cb: SessionTicketHandler = lambda t: None - self.new_session_ticket_cb: NewSessionTicketHandler = lambda t: None self.update_traffic_key_cb: Callable[ [Direction, Epoch, bytes], None ] = lambda d, e, s: None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [</s>
aioquic.tls/Context.__init__
Modified
aiortc~aioquic
5c8733aaa017e4c0c79192f27630289b047c277f
[tls] make server create new session tickets
<14>:<add> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None <add> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None <del> self.new_session_ticket_cb: SessionTicketHandler = lambda t: None
# module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): <0> self.alpn_negotiated: Optional[str] = None <1> self.alpn_protocols: Optional[List[str]] = None <2> self.certificate: Optional[x509.Certificate] = None <3> self.certificate_private_key: Optional[ <4> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] <5> ] = None <6> self.handshake_extensions: List[Extension] = [] <7> self.is_client = is_client <8> self.key_schedule: Optional[KeySchedule] = None <9> self.received_extensions: List[Extension] = [] <10> self.session_ticket: Optional[SessionTicket] = None <11> self.server_name: Optional[str] = None <12> <13> # callbacks <14> self.new_session_ticket_cb: SessionTicketHandler = lambda t: None <15> self.update_traffic_key_cb: Callable[ <16> [Direction, Epoch, bytes], None <17> ] = lambda d, e, s: None <18> <19> self._cipher_suites = [ <20> CipherSuite.AES_256_GCM_SHA384, <21> CipherSuite.AES_128_GCM_SHA256, <22> CipherSuite.CHACHA20_POLY1305_SHA256, <23> ] <24> self._compression_methods = [CompressionMethod.NULL] <25> self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] <26> self._signature_algorithms = [ <27> SignatureAlgorithm.RSA_PSS_RSAE_SHA256, <28> SignatureAlgorithm.ECDSA_SECP256R1_SHA256, <29> SignatureAlgorithm.RSA_PKCS1_SHA256, <30> SignatureAlgorithm.RSA_PKCS1_SHA1, <31> ] <32> self._supported_groups = [Group.SECP256R1</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========unchanged ref 0=========== at: aioquic.tls TLS_VERSION_1_3 = 0x0304 Direction() Epoch() State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeyExchangeMode(x: Union[str, bytes, bytearray], base: int) KeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Extension = Tuple[int, bytes] KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes) SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol self.received_extensions = encrypted_extensions.other_extensions ===========unchanged ref 1=========== at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) self._key_schedule_psk = None at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) self.client_random = peer_hello.random self.session_id = peer_hello.session_id self.received_extensions = peer_hello.other_extensions self.key_schedule = KeySchedule(cipher_suite) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) at: aioquic.tls.Context._set_state self.state = state at: aioquic.tls.Context._setup_traffic_protection self._enc_key = key ===========unchanged ref 2=========== self._dec_key = key at: aioquic.tls.Context.handle_message self._receive_buffer += input_data self._receive_buffer = self._receive_buffer[message_length:] at: logging Logger(name: str, level: _Level=...) LoggerAdapter(logger: Logger, extra: Mapping[str, Any]) at: os urandom(size: int, /) -> bytes at: typing Callable = _CallableType(collections.abc.Callable, 2) List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.tls + SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None]
aioquic.tls/Context.handle_message
Modified
aiortc~aioquic
5c8733aaa017e4c0c79192f27630289b047c277f
[tls] make server create new session tickets
# module: aioquic.tls class Context: def handle_message( self, input_data: bytes, output_buf: Dict[Epoch, Buffer] ) -> None: <0> if self.state == State.CLIENT_HANDSHAKE_START: <1> self._client_send_hello(output_buf[Epoch.INITIAL]) <2> return <3> <4> self._receive_buffer += input_data <5> while len(self._receive_buffer) >= 4: <6> # determine message length <7> message_type = self._receive_buffer[0] <8> message_length = 0 <9> for b in self._receive_buffer[1:4]: <10> message_length = (message_length << 8) | b <11> message_length += 4 <12> <13> # check message is complete <14> if len(self._receive_buffer) < message_length: <15> break <16> message = self._receive_buffer[:message_length] <17> self._receive_buffer = self._receive_buffer[message_length:] <18> <19> input_buf = Buffer(data=message) <20> <21> # client states <22> <23> if self.state == State.CLIENT_EXPECT_SERVER_HELLO: <24> if message_type == HandshakeType.SERVER_HELLO: <25> self._client_handle_hello(input_buf, output_buf[Epoch.INITIAL]) <26> else: <27> raise AlertUnexpectedMessage <28> elif self.state == State.CLIENT_EXPECT_ENCRYPTED_EXTENSIONS: <29> if message_type == HandshakeType.ENCRYPTED_EXTENSIONS: <30> self._client_handle_encrypted_extensions(input_buf) <31> else: <32> raise AlertUnexpectedMessage <33> elif self.state == State.CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE: <34> if message_type == HandshakeType.CERTIFICATE: <35> self._client_handle_certificate(input_buf) <36> else: <37> # FIXME: handle certificate request <38> raise AlertUnexpectedMessage <39> elif self.state == State.CLIENT_EXPECT_CERTIFICATE</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def handle_message( self, input_data: bytes, output_buf: Dict[Epoch, Buffer] ) -> None: # offset: 1 if message_type == HandshakeType.CERTIFICATE_VERIFY: self._client_handle_certificate_verify(input_buf) else: raise AlertUnexpectedMessage elif self.state == State.CLIENT_EXPECT_FINISHED: if message_type == HandshakeType.FINISHED: self._client_handle_finished(input_buf, output_buf[Epoch.HANDSHAKE]) else: raise AlertUnexpectedMessage elif self.state == State.CLIENT_POST_HANDSHAKE: if message_type == HandshakeType.NEW_SESSION_TICKET: self._client_handle_new_session_ticket(input_buf) else: raise AlertUnexpectedMessage # server states elif self.state == State.SERVER_EXPECT_CLIENT_HELLO: if message_type == HandshakeType.CLIENT_HELLO: self._server_handle_hello( input_buf, output_buf[Epoch.INITIAL], output_buf[Epoch.HANDSHAKE], ) else: raise AlertUnexpectedMessage elif self.state == State.SERVER_EXPECT_FINISHED: if message_type == HandshakeType.FINISHED: self._server_handle_finished(input_buf) else: raise AlertUnexpectedMessage elif self.state == State.SERVER_POST_HANDSHAKE: raise AlertUnexpectedMessage # should not happen else: raise Exception("unhandled state") assert input_buf.eof() ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls AlertUnexpectedMessage(*args: object) Epoch() State() HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) at: aioquic.tls.Context _client_send_hello(output_buf: Buffer) -> None _client_handle_hello(input_buf: Buffer, output_buf: Buffer) -> None _client_handle_encrypted_extensions(input_buf: Buffer) -> None _client_handle_certificate(input_buf: Buffer) -> None _client_handle_certificate_verify(input_buf: Buffer) -> None _client_handle_finished(input_buf: Buffer, output_buf: Buffer) -> None _client_handle_new_session_ticket(input_buf: Buffer) -> None _server_handle_hello(input_buf: Buffer, initial_buf: Buffer, output_buf: Buffer) -> None _server_handle_finished(input_buf: Buffer, output_buf: Buffer) -> None at: aioquic.tls.Context.__init__ self._receive_buffer = b"" at: aioquic.tls.Context._set_state self.state = state at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: aioquic.tls + SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] ===========changed ref 1=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.is_client = is_client self.key_schedule: Optional[KeySchedule] = None self.received_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None # callbacks + self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None + self.new_session_ticket_cb: Optional[SessionTicketHandler] = None - self.new_session_ticket_cb: SessionTicketHandler = lambda t: None self.update_traffic_key_cb: Callable[ [Direction, Epoch, bytes], None ] = lambda d, e, s: None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_</s> ===========changed ref 2=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 <s>RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO
aioquic.tls/Context._client_handle_new_session_ticket
Modified
aiortc~aioquic
5c8733aaa017e4c0c79192f27630289b047c277f
[tls] make server create new session tickets
<2>:<del> # compute resumption secret <3>:<del> resumption_master_secret = self.key_schedule.derive_secret(b"res master") <4>:<del> resumption_secret = hkdf_expand_label( <5>:<del> algorithm=self.key_schedule.algorithm, <6>:<del> secret=resumption_master_secret, <7>:<del> label=b"resumption", <8>:<add> # notify application <add> if self.new_session_ticket_cb is not None: <add> ticket = self._build_session_ticket(new_session_ticket) <add> self.new_session_ticket_cb(ticket) <del> hash_value=new_session_ticket.ticket_nonce, <9>:<del> length=self.key_schedule.algorithm.digest_size, <10>:<del> ) <12>:<del> timestamp = datetime.datetime.now() <13>:<del> ticket = SessionTicket( <14>:<del> age_add=new_session_ticket.ticket_age_add, <15>:<del> cipher_suite=self.key_schedule.cipher_suite, <16>:<del> not_valid_after=timestamp <17>:<del> + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), <18>:<del> not_valid_before=timestamp, <19>:<del> resumption_secret=resumption_secret, <20>:<del> server_name=self.server_name, <21>:<del> ticket=new_session_ticket.ticket, <22>:<del> ) <23>:<del> self.new_session_ticket_cb(ticket) <24>:<del>
# module: aioquic.tls class Context: def _client_handle_new_session_ticket(self, input_buf: Buffer) -> None: <0> new_session_ticket = pull_new_session_ticket(input_buf) <1> <2> # compute resumption secret <3> resumption_master_secret = self.key_schedule.derive_secret(b"res master") <4> resumption_secret = hkdf_expand_label( <5> algorithm=self.key_schedule.algorithm, <6> secret=resumption_master_secret, <7> label=b"resumption", <8> hash_value=new_session_ticket.ticket_nonce, <9> length=self.key_schedule.algorithm.digest_size, <10> ) <11> <12> timestamp = datetime.datetime.now() <13> ticket = SessionTicket( <14> age_add=new_session_ticket.ticket_age_add, <15> cipher_suite=self.key_schedule.cipher_suite, <16> not_valid_after=timestamp <17> + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), <18> not_valid_before=timestamp, <19> resumption_secret=resumption_secret, <20> server_name=self.server_name, <21> ticket=new_session_ticket.ticket, <22> ) <23> self.new_session_ticket_cb(ticket) <24>
===========unchanged ref 0=========== at: aioquic.tls Direction() Epoch() State() Finished(verify_data: bytes=b"") push_finished(buf: Buffer, finished: Finished) -> None push_message(key_schedule: Union[KeySchedule, KeyScheduleProxy], buf: Buffer) -> Generator at: aioquic.tls.Context _setup_traffic_protection(direction: Direction, epoch: Epoch, label: bytes) -> None _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self.key_schedule: Optional[KeySchedule] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, bytes], None ] = lambda d, e, s: None self._enc_key: Optional[bytes] = None at: aioquic.tls.Context._client_handle_finished finished = pull_finished(input_buf) expected_verify_data = self.key_schedule.finished_verify_data(self._dec_key) at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) at: aioquic.tls.Context._setup_traffic_protection self._enc_key = key at: aioquic.tls.Finished verify_data: bytes = b"" at: aioquic.tls.KeySchedule finished_verify_data(secret: bytes) -> bytes derive_secret(label: bytes) -> bytes extract(key_material: Optional[bytes]=None) -> None update_hash(data: bytes) -> None at: aioquic.tls.KeySchedule.__init__ self.generation = 0 ===========unchanged ref 1=========== at: aioquic.tls.KeySchedule.extract self.generation += 1 ===========changed ref 0=========== # module: aioquic.tls + SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] ===========changed ref 1=========== # module: aioquic.tls class Context: + def _build_session_ticket( + self, new_session_ticket: NewSessionTicket + ) -> SessionTicket: + resumption_master_secret = self.key_schedule.derive_secret(b"res master") + resumption_secret = hkdf_expand_label( + algorithm=self.key_schedule.algorithm, + secret=resumption_master_secret, + label=b"resumption", + hash_value=new_session_ticket.ticket_nonce, + length=self.key_schedule.algorithm.digest_size, + ) + + timestamp = datetime.datetime.now() + return SessionTicket( + age_add=new_session_ticket.ticket_age_add, + cipher_suite=self.key_schedule.cipher_suite, + not_valid_after=timestamp + + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), + not_valid_before=timestamp, + resumption_secret=resumption_secret, + server_name=self.server_name, + ticket=new_session_ticket.ticket, + ) + ===========changed ref 2=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.is_client = is_client self.key_schedule: Optional[KeySchedule] = None self.received_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None # callbacks + self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None + self.new_session_ticket_cb: Optional[SessionTicketHandler] = None - self.new_session_ticket_cb: SessionTicketHandler = lambda t: None self.update_traffic_key_cb: Callable[ [Direction, Epoch, bytes], None ] = lambda d, e, s: None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_</s> ===========changed ref 3=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 <s>RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO
aioquic.connection/QuicConnection.__init__
Modified
aiortc~aioquic
5c8733aaa017e4c0c79192f27630289b047c277f
[tls] make server create new session tickets
<s>List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, session_ticket: Optional[tls.SessionTicket] = None, + session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: <0> if is_client: <1> assert ( <2> original_connection_id is None <3> ), "Cannot set original_connection_id for a client" <4> else: <5> assert certificate is not None, "SSL certificate is required for a server" <6> assert private_key is not None, "SSL private key is required for a server" <7> <8> self.alpn_protocols = alpn_protocols <9> self.certificate = certificate <10> self.is_client = is_client <11> self.host_cid = os.urandom(8) <12> self.peer_cid = os.urandom(8) <13> self.peer_cid_set = False <14> self.peer_token = b"" <15> self.private_key = private_key <16> self.secrets_log_file = secrets_log_file <17> self.server_name = server_name <18> self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} <19> <20> # counters for debugging <21> self._stateless_retry_count = 0 <22> self._version_negotiation_count = 0 <23> <24> self._loop = asyncio.get_event_loop() <25> self.__close: Optional[Dict] = None <26> self.__connected = asyncio.Event() <27> self.__epoch = tls.Epoch.INITIAL <28> self._local_idle_timeout = 60000 # milliseconds <29> self._local_max_data = 1048576 <30> self._local_max_data_used = 0 <31> self._local_max_stream_data</s>
===========below chunk 0=========== <s> None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, session_ticket: Optional[tls.SessionTicket] = None, + session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 1 self._local_max_stream_data_bidi_remote = 1048576 self._local_max_stream_data_uni = 1048576 self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} ) self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._ping_packet_number: Optional[int] = None self._ping_waiter: Optional[asyncio.Future[None]] = None self._remote_idle_timeout = 0 # milliseconds self._remote_max_data = 0 self._remote_max_data_used = 0 self._remote_max_stream_data_bidi_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._session_ticket = session_ticket self._spin_bit = False self._spin_bit_peer = False self._spin_highest_pn = 0 self.__send_pending_task: Optional[asyncio.Handle] = None self.__state = QuicConnectionState.FIRSTFLIGHT self._transport: Optional[asyncio.DatagramTransport] = None</s> ===========below chunk 1=========== <s> None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, session_ticket: Optional[tls.SessionTicket] = None, + session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 2 <s> self.__state = QuicConnectionState.FIRSTFLIGHT self._transport: Optional[asyncio.DatagramTransport] = None self._version: Optional[int] = None # callbacks if session_ticket_handler is not None: self._session_ticket_handler = session_ticket_handler else: self._session_ticket_handler = lambda t: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None # frame handlers self.__frame_handlers = [ self._handle_padding_frame, self._handle_padding_frame, self._handle_ack_frame, self._handle_ack_frame, self._handle_reset_stream_frame, self._handle_stop_sending_frame, self._handle_crypto_frame, self._handle_new_token_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_max_data_frame, self._handle_max_stream_data_frame, self._handle_max_streams_</s> ===========below chunk 2=========== <s> None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, session_ticket: Optional[tls.SessionTicket] = None, + session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 3 <s>_frame, self._handle_max_streams_uni_frame, self._handle_data_blocked_frame, self._handle_stream_data_blocked_frame, self._handle_streams_blocked_frame, self._handle_streams_blocked_frame, self._handle_new_connection_id_frame, self._handle_retire_connection_id_frame, self._handle_path_challenge_frame, self._handle_path_response_frame, self._handle_connection_close_frame, self._handle_connection_close_frame, ] ===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.connection logger = logging.getLogger("quic") QuicConnectionAdapter(logger: Logger, extra: Mapping[str, Any]) QuicConnectionState() QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None) QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] at: aioquic.connection.QuicConnection supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20] _handle_ack_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_connection_close_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_crypto_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_data_blocked_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_max_data_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_max_stream_data_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_max_streams_bidi_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_max_streams_uni_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_new_connection_id_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_new_token_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None
aioquic.connection/QuicConnection._initialize
Modified
aiortc~aioquic
5c8733aaa017e4c0c79192f27630289b047c277f
[tls] make server create new session tickets
<13>:<add> if self._session_ticket_fetcher is not None: <add> self.tls.get_session_ticket_cb = self._session_ticket_fetcher <add> if self._session_ticket_handler is not None: <add> self.tls.new_session_ticket_cb = self._session_ticket_handler <del> self.tls.new_session_ticket_cb = self._session_ticket_handler
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _initialize(self, peer_cid: bytes) -> None: <0> # TLS <1> self.tls = tls.Context(is_client=self.is_client, logger=self._logger) <2> self.tls.alpn_protocols = self.alpn_protocols <3> self.tls.certificate = self.certificate <4> self.tls.certificate_private_key = self.private_key <5> self.tls.handshake_extensions = [ <6> ( <7> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, <8> self._serialize_transport_parameters(), <9> ) <10> ] <11> self.tls.server_name = self.server_name <12> self.tls.session_ticket = self._session_ticket <13> self.tls.new_session_ticket_cb = self._session_ticket_handler <14> self.tls.update_traffic_key_cb = self._update_traffic_key <15> <16> # packet spaces <17> self.send_ack = { <18> tls.Epoch.INITIAL: False, <19> tls.Epoch.HANDSHAKE: False, <20> tls.Epoch.ONE_RTT: False, <21> } <22> self.send_buffer = { <23> tls.Epoch.INITIAL: Buffer(capacity=4096), <24> tls.Epoch.HANDSHAKE: Buffer(capacity=4096), <25> tls.Epoch.ONE_RTT: Buffer(capacity=4096), <26> } <27> self.spaces = { <28> tls.Epoch.INITIAL: QuicPacketSpace(), <29> tls.Epoch.HANDSHAKE: QuicPacketSpace(), <30> tls.Epoch.ONE_RTT: QuicPacketSpace(), <31> } <32> self.streams[tls.Epoch.INITIAL] = QuicStream() <33> self.streams[tls.Epoch.HANDSHAKE] = QuicStream() <34> self.streams[tls.Epoch.ONE_RTT] = QuicStream() <35> <36> self.spaces[tls.Epoch.INITIAL].crypto.</s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _initialize(self, peer_cid: bytes) -> None: # offset: 1 cid=peer_cid, is_client=self.is_client ) self.packet_number = 0 ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.connection QuicPacketSpace() at: aioquic.connection.QuicConnection _serialize_transport_parameters() -> bytes _update_traffic_key(direction: tls.Direction, epoch: tls.Epoch, secret: bytes) -> None at: aioquic.connection.QuicConnection.__init__ self.alpn_protocols = alpn_protocols self.certificate = certificate self.is_client = is_client self.private_key = private_key self.server_name = server_name self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} ) self._session_ticket = session_ticket self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler at: aioquic.connection.QuicPacketSpace.__init__ self.crypto = CryptoPair() at: aioquic.crypto.CryptoPair setup_initial(cid: bytes, is_client: bool) -> None at: aioquic.stream QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0) at: aioquic.tls Epoch() ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None) ===========unchanged ref 1=========== at: aioquic.tls.Context.__init__ self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None self.new_session_ticket_cb: SessionTicketHandler = lambda t: None self.update_traffic_key_cb: Callable[ [Direction, Epoch, bytes], None ] = lambda d, e, s: None ===========changed ref 0=========== # module: aioquic.tls + SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] ===========changed ref 1=========== # module: aioquic.tls class Context: + def _build_session_ticket( + self, new_session_ticket: NewSessionTicket + ) -> SessionTicket: + resumption_master_secret = self.key_schedule.derive_secret(b"res master") + resumption_secret = hkdf_expand_label( + algorithm=self.key_schedule.algorithm, + secret=resumption_master_secret, + label=b"resumption", + hash_value=new_session_ticket.ticket_nonce, + length=self.key_schedule.algorithm.digest_size, + ) + + timestamp = datetime.datetime.now() + return SessionTicket( + age_add=new_session_ticket.ticket_age_add, + cipher_suite=self.key_schedule.cipher_suite, + not_valid_after=timestamp + + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), + not_valid_before=timestamp, + resumption_secret=resumption_secret, + server_name=self.server_name, + ticket=new_session_ticket.ticket, + ) + ===========changed ref 2=========== # module: aioquic.tls class Context: def _client_handle_new_session_ticket(self, input_buf: Buffer) -> None: new_session_ticket = pull_new_session_ticket(input_buf) - # compute resumption secret - resumption_master_secret = self.key_schedule.derive_secret(b"res master") - resumption_secret = hkdf_expand_label( - algorithm=self.key_schedule.algorithm, - secret=resumption_master_secret, - label=b"resumption", + # notify application + if self.new_session_ticket_cb is not None: + ticket = self._build_session_ticket(new_session_ticket) + self.new_session_ticket_cb(ticket) - hash_value=new_session_ticket.ticket_nonce, - length=self.key_schedule.algorithm.digest_size, - ) - timestamp = datetime.datetime.now() - ticket = SessionTicket( - age_add=new_session_ticket.ticket_age_add, - cipher_suite=self.key_schedule.cipher_suite, - not_valid_after=timestamp - + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), - not_valid_before=timestamp, - resumption_secret=resumption_secret, - server_name=self.server_name, - ticket=new_session_ticket.ticket, - ) - self.new_session_ticket_cb(ticket) -
aioquic.connection/QuicConnection._write_application
Modified
aiortc~aioquic
5c8733aaa017e4c0c79192f27630289b047c277f
[tls] make server create new session tickets
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _write_application(self, network_path: QuicNetworkPath) -> Iterator[bytes]: <0> epoch = tls.Epoch.ONE_RTT <1> space = self.spaces[epoch] <2> if not space.crypto.send.is_valid(): <3> return <4> <5> buf = Buffer(capacity=PACKET_MAX_SIZE) <6> capacity = buf.capacity - space.crypto.aead_tag_size <7> <8> while True: <9> # write header <10> push_uint8( <11> buf, <12> PACKET_FIXED_BIT <13> | (self._spin_bit << 5) <14> | (space.crypto.key_phase << 2) <15> | (PACKET_NUMBER_SEND_SIZE - 1), <16> ) <17> push_bytes(buf, self.peer_cid) <18> push_uint16(buf, self.packet_number) <19> header_size = buf.tell() <20> <21> # ACK <22> if self.send_ack[epoch] and space.ack_queue: <23> push_uint_var(buf, QuicFrameType.ACK) <24> packet.push_ack_frame(buf, space.ack_queue, 0) <25> self.send_ack[epoch] = False <26> <27> # PATH CHALLENGE <28> if ( <29> self.__epoch == tls.Epoch.ONE_RTT <30> and not network_path.is_validated <31> and network_path.local_challenge is None <32> ): <33> self._logger.info( <34> "Network path %s sending challenge", network_path.addr <35> ) <36> network_path.local_challenge = os.urandom(8) <37> push_uint_var(buf, QuicFrameType.PATH_CHALLENGE) <38> push_bytes(buf, network_path.local_challenge) <39> <40> # PATH RESPONSE <41> if network_path.remote_challenge is not None: <42> push_uint_var(</s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _write_application(self, network_path: QuicNetworkPath) -> Iterator[bytes]: # offset: 1 push_bytes(buf, network_path.remote_challenge) network_path.remote_challenge = None # PING if self._ping_waiter is not None and self._ping_packet_number is None: self._ping_packet_number = self.packet_number self._logger.info("Sending PING in packet %d", self.packet_number) push_uint_var(buf, QuicFrameType.PING) # CLOSE if self.__close and self.__epoch == epoch: push_close(buf, **self.__close) self.__close = None # STREAM for stream_id, stream in self.streams.items(): if isinstance(stream_id, int): # the frame data size is constrained by our peer's MAX_DATA and # the space available in the current packet frame_overhead = ( 3 + quic_uint_length(stream_id) + ( quic_uint_length(stream._send_start) if stream._send_start else 0 ) ) frame = stream.get_frame( min( capacity - buf.tell() - frame_overhead, self._remote_max_data - self._remote_max_data_used, ) ) if frame is not None: flags = QuicStreamFlag.LEN if frame.offset: flags |= QuicStreamFlag.OFF if frame.fin: flags |= QuicStreamFlag.FIN push_uint_var(buf, QuicFrameType.STREAM_BASE | flags) with push_stream_frame(buf, stream_id, frame.offset): push_bytes(buf, frame.data) self._remote_max_data_used += len(frame.data) packet_size = buf.tell() if</s> ===========below chunk 1=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _write_application(self, network_path: QuicNetworkPath) -> Iterator[bytes]: # offset: 2 <s>._remote_max_data_used += len(frame.data) packet_size = buf.tell() if packet_size > header_size: # check whether we need padding padding_size = ( PACKET_NUMBER_MAX_SIZE - PACKET_NUMBER_SEND_SIZE + header_size - packet_size ) if padding_size > 0: push_bytes(buf, bytes(padding_size)) packet_size += padding_size # encrypt data = buf.data yield space.crypto.encrypt_packet( data[0:header_size], data[header_size:packet_size] ) self.packet_number += 1 buf.seek(0) else: break ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) push_bytes(buf: Buffer, v: bytes) -> None push_uint8(buf: Buffer, v: int) -> None push_uint16(buf: Buffer, v: int) -> None at: aioquic.buffer.Buffer tell() -> int at: aioquic.connection PACKET_MAX_SIZE = 1280 push_close(buf: Buffer, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None) at: aioquic.connection.QuicConnection.__init__ self.peer_cid = os.urandom(8) self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} self.__close: Optional[Dict] = None self.__epoch = tls.Epoch.INITIAL self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} ) self._ping_packet_number: Optional[int] = None self._ping_waiter: Optional[asyncio.Future[None]] = None self._remote_max_data = 0 self._remote_max_data_used = 0 self._spin_bit = False at: aioquic.connection.QuicConnection._handle_ack_frame self._ping_waiter = None self._ping_packet_number = None at: aioquic.connection.QuicConnection._handle_crypto_frame self.__epoch = tls.Epoch.ONE_RTT self.__epoch = tls.Epoch.HANDSHAKE ===========unchanged ref 1=========== at: aioquic.connection.QuicConnection._handle_max_data_frame self._remote_max_data = max_data at: aioquic.connection.QuicConnection._initialize self.tls = tls.Context(is_client=self.is_client, logger=self._logger) self.send_ack = { tls.Epoch.INITIAL: False, tls.Epoch.HANDSHAKE: False, tls.Epoch.ONE_RTT: False, } self.spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self.packet_number = 0 at: aioquic.connection.QuicConnection._update_traffic_key crypto = self.spaces[epoch].crypto at: aioquic.connection.QuicConnection._write_application self.packet_number += 1 at: aioquic.connection.QuicConnection._write_handshake self.__close = None self.packet_number += 1 at: aioquic.connection.QuicConnection.close self.__close = { "error_code": error_code, "frame_type": frame_type, "reason_phrase": reason_phrase, } at: aioquic.connection.QuicConnection.datagram_received self.peer_cid = header.source_cid self._spin_bit = self._spin_bit_peer self._spin_bit = not self._spin_bit_peer at: aioquic.connection.QuicConnection.ping self._ping_packet_number = None self._ping_waiter = self._loop.create_future() at: aioquic.connection.QuicNetworkPath addr: NetworkAddress bytes_received: int = 0 bytes_sent: int = 0 is_validated: bool = False local_challenge: Optional[bytes] = None
aioquic.server/QuicServer.__init__
Modified
aiortc~aioquic
5c8733aaa017e4c0c79192f27630289b047c277f
[tls] make server create new session tickets
<5>:<add> self._session_ticket_fetcher = session_ticket_fetcher <add> self._session_ticket_handler = session_ticket_handler
<s> private_key: Any, alpn_protocols: Optional[List[str]] = None, connection_handler: Optional[QuicConnectionHandler] = None, secrets_log_file: Optional[TextIO] = None, + session_ticket_fetcher: Optional[SessionTicketFetcher] = None, + session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: <0> self._alpn_protocols = alpn_protocols <1> self._certificate = certificate <2> self._connections: Dict[bytes, QuicConnection] = {} <3> self._private_key = private_key <4> self._secrets_log_file = secrets_log_file <5> self._transport: Optional[asyncio.DatagramTransport] = None <6> <7> if connection_handler is not None: <8> self._connection_handler = connection_handler <9> else: <10> self._connection_handler = lambda c: None <11> <12> self._stream_handler = stream_handler <13> <14> if stateless_retry: <15> self._retry_key = rsa.generate_private_key( <16> public_exponent=65537, key_size=1024, backend=default_backend() <17> ) <18> else: <19> self._retry_key = None <20>
===========unchanged ref 0=========== at: aioquic.connection QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] QuicConnection(*, is_client: bool=True, certificate: Any=None, private_key: Any=None, alpn_protocols: Optional[List[str]]=None, original_connection_id: Optional[bytes]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.server QuicConnectionHandler = Callable[[QuicConnection], None] at: aioquic.server.QuicServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: aioquic.tls SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.protocols DatagramProtocol() at: asyncio.transports DatagramTransport(extra: Optional[Mapping[Any, Any]]=...) at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict') TextIO() ===========changed ref 0=========== # module: aioquic.tls + SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] ===========changed ref 1=========== # module: aioquic.tls class Context: + def _build_session_ticket( + self, new_session_ticket: NewSessionTicket + ) -> SessionTicket: + resumption_master_secret = self.key_schedule.derive_secret(b"res master") + resumption_secret = hkdf_expand_label( + algorithm=self.key_schedule.algorithm, + secret=resumption_master_secret, + label=b"resumption", + hash_value=new_session_ticket.ticket_nonce, + length=self.key_schedule.algorithm.digest_size, + ) + + timestamp = datetime.datetime.now() + return SessionTicket( + age_add=new_session_ticket.ticket_age_add, + cipher_suite=self.key_schedule.cipher_suite, + not_valid_after=timestamp + + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), + not_valid_before=timestamp, + resumption_secret=resumption_secret, + server_name=self.server_name, + ticket=new_session_ticket.ticket, + ) + ===========changed ref 2=========== # module: aioquic.tls class Context: def _client_handle_new_session_ticket(self, input_buf: Buffer) -> None: new_session_ticket = pull_new_session_ticket(input_buf) - # compute resumption secret - resumption_master_secret = self.key_schedule.derive_secret(b"res master") - resumption_secret = hkdf_expand_label( - algorithm=self.key_schedule.algorithm, - secret=resumption_master_secret, - label=b"resumption", + # notify application + if self.new_session_ticket_cb is not None: + ticket = self._build_session_ticket(new_session_ticket) + self.new_session_ticket_cb(ticket) - hash_value=new_session_ticket.ticket_nonce, - length=self.key_schedule.algorithm.digest_size, - ) - timestamp = datetime.datetime.now() - ticket = SessionTicket( - age_add=new_session_ticket.ticket_age_add, - cipher_suite=self.key_schedule.cipher_suite, - not_valid_after=timestamp - + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), - not_valid_before=timestamp, - resumption_secret=resumption_secret, - server_name=self.server_name, - ticket=new_session_ticket.ticket, - ) - self.new_session_ticket_cb(ticket) - ===========changed ref 3=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _initialize(self, peer_cid: bytes) -> None: # TLS self.tls = tls.Context(is_client=self.is_client, logger=self._logger) self.tls.alpn_protocols = self.alpn_protocols self.tls.certificate = self.certificate self.tls.certificate_private_key = self.private_key self.tls.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, self._serialize_transport_parameters(), ) ] self.tls.server_name = self.server_name self.tls.session_ticket = self._session_ticket + if self._session_ticket_fetcher is not None: + self.tls.get_session_ticket_cb = self._session_ticket_fetcher + if self._session_ticket_handler is not None: + self.tls.new_session_ticket_cb = self._session_ticket_handler - self.tls.new_session_ticket_cb = self._session_ticket_handler self.tls.update_traffic_key_cb = self._update_traffic_key # packet spaces self.send_ack = { tls.Epoch.INITIAL: False, tls.Epoch.HANDSHAKE: False, tls.Epoch.ONE_RTT: False, } self.send_buffer = { tls.Epoch.INITIAL: Buffer(capacity=4096), tls.Epoch.HANDSHAKE: Buffer(capacity=4096), tls.Epoch.ONE_RTT: Buffer(capacity=4096), } self.spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self.streams[tls.Epoch.INITIAL] = QuicStream() self.streams[tls.Epoch.HANDSHAKE]</s> ===========changed ref 4=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _initialize(self, peer_cid: bytes) -> None: # offset: 1 <s> self.streams[tls.Epoch.INITIAL] = QuicStream() self.streams[tls.Epoch.HANDSHAKE] = QuicStream() self.streams[tls.Epoch.ONE_RTT] = QuicStream() self.spaces[tls.Epoch.INITIAL].crypto.setup_initial( cid=peer_cid, is_client=self.is_client ) self.packet_number = 0
aioquic.server/QuicServer.datagram_received
Modified
aiortc~aioquic
5c8733aaa017e4c0c79192f27630289b047c277f
[tls] make server create new session tickets
# module: aioquic.server class QuicServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: <0> data = cast(bytes, data) <1> buf = Buffer(data=data) <2> header = pull_quic_header(buf, host_cid_length=8) <3> <4> # version negotiation <5> if ( <6> header.version is not None <7> and header.version not in QuicConnection.supported_versions <8> ): <9> self._transport.sendto( <10> encode_quic_version_negotiation( <11> source_cid=header.destination_cid, <12> destination_cid=header.source_cid, <13> supported_versions=QuicConnection.supported_versions, <14> ), <15> addr, <16> ) <17> return <18> <19> connection = self._connections.get(header.destination_cid, None) <20> original_connection_id: Optional[bytes] = None <21> if connection is None and header.packet_type == PACKET_TYPE_INITIAL: <22> # stateless retry <23> if self._retry_key is not None: <24> if not header.token: <25> retry_message = encode_address(addr) + b"|" + header.destination_cid <26> retry_token = self._retry_key.public_key().encrypt( <27> retry_message, <28> padding.OAEP( <29> mgf=padding.MGF1(hashes.SHA256()), <30> algorithm=hashes.SHA256(), <31> label=None, <32> ), <33> ) <34> self._transport.sendto( <35> encode_quic_retry( <36> version=header.version, <37> source_cid=os.urandom(8), <38> destination_cid=header.source_cid, <39> original_destination_cid=header.destination_cid, <40> retry_token=retry_token, <41> ), <42> addr, <43> ) <44> return <45> else:</s>
===========below chunk 0=========== # module: aioquic.server class QuicServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 retry_message = self._retry_key.decrypt( header.token, padding.OAEP( mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None, ), ) encoded_addr, original_connection_id = retry_message.split( b"|", maxsplit=1 ) if encoded_addr != encode_address(addr): return except ValueError: return # create new connection connection = QuicConnection( alpn_protocols=self._alpn_protocols, certificate=self._certificate, is_client=False, original_connection_id=original_connection_id, private_key=self._private_key, secrets_log_file=self._secrets_log_file, stream_handler=self._stream_handler, ) connection.connection_made(self._transport) self._connections[connection.host_cid] = connection self._connection_handler(connection) if connection is not None: connection.datagram_received(data, addr) ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.connection NetworkAddress = Any QuicConnection(*, is_client: bool=True, certificate: Any=None, private_key: Any=None, alpn_protocols: Optional[List[str]]=None, original_connection_id: Optional[bytes]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.connection.QuicConnection supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20] at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 pull_quic_header(buf: Buffer, host_cid_length: Optional[int]=None) -> QuicHeader encode_quic_retry(version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes) -> bytes encode_quic_version_negotiation(source_cid: bytes, destination_cid: bytes, supported_versions: List[QuicProtocolVersion]) -> bytes at: aioquic.packet.QuicHeader version: Optional[int] packet_type: int destination_cid: bytes source_cid: bytes original_destination_cid: bytes = b"" token: bytes = b"" rest_length: int = 0 at: aioquic.server encode_address(addr: NetworkAddress) -> bytes at: aioquic.server.QuicServer.__init__ self._alpn_protocols = alpn_protocols self._certificate = certificate ===========unchanged ref 1=========== self._connections: Dict[bytes, QuicConnection] = {} self._private_key = private_key self._secrets_log_file = secrets_log_file self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None self._stream_handler = stream_handler at: asyncio.protocols.BaseProtocol __slots__ = () connection_made(self, transport: transports.BaseTransport) -> None at: asyncio.protocols.DatagramProtocol __slots__ = () datagram_received(self, data: bytes, addr: Tuple[str, int]) -> None at: asyncio.transports BaseTransport(extra: Optional[Mapping[Any, Any]]=...) DatagramTransport(extra: Optional[Mapping[Any, Any]]=...) at: asyncio.transports.DatagramTransport __slots__ = () sendto(data: Any, addr: Optional[_Address]=...) -> None at: os urandom(size: int, /) -> bytes at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any Text = str at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] ===========changed ref 0=========== <s> private_key: Any, alpn_protocols: Optional[List[str]] = None, connection_handler: Optional[QuicConnectionHandler] = None, secrets_log_file: Optional[TextIO] = None, + session_ticket_fetcher: Optional[SessionTicketFetcher] = None, + session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: self._alpn_protocols = alpn_protocols self._certificate = certificate self._connections: Dict[bytes, QuicConnection] = {} self._private_key = private_key self._secrets_log_file = secrets_log_file + self._session_ticket_fetcher = session_ticket_fetcher + self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None if connection_handler is not None: self._connection_handler = connection_handler else: self._connection_handler = lambda c: None self._stream_handler = stream_handler if stateless_retry: self._retry_key = rsa.generate_private_key( public_exponent=65537, key_size=1024, backend=default_backend() ) else: self._retry_key = None ===========changed ref 1=========== # module: aioquic.tls + SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] ===========changed ref 2=========== # module: aioquic.tls class Context: + def _build_session_ticket( + self, new_session_ticket: NewSessionTicket + ) -> SessionTicket: + resumption_master_secret = self.key_schedule.derive_secret(b"res master") + resumption_secret = hkdf_expand_label( + algorithm=self.key_schedule.algorithm, + secret=resumption_master_secret, + label=b"resumption", + hash_value=new_session_ticket.ticket_nonce, + length=self.key_schedule.algorithm.digest_size, + ) + + timestamp = datetime.datetime.now() + return SessionTicket( + age_add=new_session_ticket.ticket_age_add, + cipher_suite=self.key_schedule.cipher_suite, + not_valid_after=timestamp + + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), + not_valid_before=timestamp, + resumption_secret=resumption_secret, + server_name=self.server_name, + ticket=new_session_ticket.ticket, + ) +
aioquic.server/serve
Modified
aiortc~aioquic
5c8733aaa017e4c0c79192f27630289b047c277f
[tls] make server create new session tickets
<s>, certificate: Any, private_key: Any, alpn_protocols: Optional[List[str]] = None, connection_handler: QuicConnectionHandler = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, + session_ticket_fetcher: Optional[SessionTicketFetcher] = None, + session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, ) -> None: <0> """ <1> Start a QUIC server at the given `host` and `port`. <2> <3> :func:`serve` requires a TLS certificate and private key, which can be <4> specified using the following arguments: <5> <6> * ``certificate`` is the server's TLS certificate. <7> See :func:`cryptography.x509.load_pem_x509_certificate`. <8> * ``private_key`` is the server's private key. <9> See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. <10> <11> :func:`serve` also accepts the following optional arguments: <12> <13> * ``connection_handler`` is a callback which is invoked whenever a <14> connection is created. It must be a a function accepting a single <15> argument: a :class:`~aioquic.QuicConnection`. <16> * ``secrets_log_file`` is a file-like object in which to log traffic <17> secrets. This is useful to analyze traffic captures with Wireshark. <18> * ``stateless_retry`` specifies whether a stateless retry should be <19> performed prior to handling new connections. <20> * ``stream_handler`` is a callback which is invoked whenever a stream is <21> created. It must accept two arguments: a :class:`asyncio.StreamReader` <22> and a :class:`asyncio.StreamWriter`. <23> """ <24> <25> loop = asyncio.get_event_loop() <26> <27> _, protocol = await loop.create_datagram_endpoint( <28> lambda: QuicServer( <29> alpn_protocols=alpn</s>
===========below chunk 0=========== <s> Any, private_key: Any, alpn_protocols: Optional[List[str]] = None, connection_handler: QuicConnectionHandler = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, + session_ticket_fetcher: Optional[SessionTicketFetcher] = None, + session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, ) -> None: # offset: 1 certificate=certificate, connection_handler=connection_handler, private_key=private_key, secrets_log_file=secrets_log_file, stateless_retry=stateless_retry, stream_handler=stream_handler, ), local_addr=(host, port), ) ===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.connection QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] at: aioquic.connection.QuicConnection datagram_received(data: Union[bytes, Text], addr: NetworkAddress) -> None at: aioquic.connection.QuicConnection.__init__ self.host_cid = os.urandom(8) at: aioquic.server QuicConnectionHandler = Callable[[QuicConnection], None] QuicServer(*, certificate: Any, private_key: Any, alpn_protocols: Optional[List[str]]=None, connection_handler: Optional[QuicConnectionHandler]=None, secrets_log_file: Optional[TextIO]=None, session_ticket_fetcher: Optional[SessionTicketFetcher]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stateless_retry: bool=False, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.server.QuicServer.__init__ self._connections: Dict[bytes, QuicConnection] = {} self._connection_handler = connection_handler self._connection_handler = lambda c: None at: aioquic.server.QuicServer.datagram_received data = cast(bytes, data) connection = self._connections.get(header.destination_cid, None) connection = QuicConnection( alpn_protocols=self._alpn_protocols, certificate=self._certificate, is_client=False, original_connection_id=original_connection_id, private_key=self._private_key, secrets_log_file=self._secrets_log_file, session_ticket_fetcher=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler, stream_handler=self._stream_handler, ) at: aioquic.tls SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] ===========unchanged ref 1=========== SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.events get_event_loop() -> AbstractEventLoop at: asyncio.events.AbstractEventLoop create_datagram_endpoint(protocol_factory: _ProtocolFactory, local_addr: Optional[Tuple[str, int]]=..., remote_addr: Optional[Tuple[str, int]]=..., *, family: int=..., proto: int=..., flags: int=..., reuse_address: Optional[bool]=..., reuse_port: Optional[bool]=..., allow_broadcast: Optional[bool]=..., sock: Optional[socket]=...) -> _TransProtPair at: typing List = _alias(list, 1, inst=False, name='List') TextIO() ===========changed ref 0=========== <s> private_key: Any, alpn_protocols: Optional[List[str]] = None, connection_handler: Optional[QuicConnectionHandler] = None, secrets_log_file: Optional[TextIO] = None, + session_ticket_fetcher: Optional[SessionTicketFetcher] = None, + session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: self._alpn_protocols = alpn_protocols self._certificate = certificate self._connections: Dict[bytes, QuicConnection] = {} self._private_key = private_key self._secrets_log_file = secrets_log_file + self._session_ticket_fetcher = session_ticket_fetcher + self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None if connection_handler is not None: self._connection_handler = connection_handler else: self._connection_handler = lambda c: None self._stream_handler = stream_handler if stateless_retry: self._retry_key = rsa.generate_private_key( public_exponent=65537, key_size=1024, backend=default_backend() ) else: self._retry_key = None ===========changed ref 1=========== # module: aioquic.server class QuicServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: data = cast(bytes, data) buf = Buffer(data=data) header = pull_quic_header(buf, host_cid_length=8) # version negotiation if ( header.version is not None and header.version not in QuicConnection.supported_versions ): self._transport.sendto( encode_quic_version_negotiation( source_cid=header.destination_cid, destination_cid=header.source_cid, supported_versions=QuicConnection.supported_versions, ), addr, ) return connection = self._connections.get(header.destination_cid, None) original_connection_id: Optional[bytes] = None if connection is None and header.packet_type == PACKET_TYPE_INITIAL: # stateless retry if self._retry_key is not None: if not header.token: retry_message = encode_address(addr) + b"|" + header.destination_cid retry_token = self._retry_key.public_key().encrypt( retry_message, padding.OAEP( mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None, ), ) self._transport.sendto( encode_quic_retry( version=header.version, source_cid=os.urandom(8), destination_cid=header.source_cid, original_destination_cid=header.destination_cid, retry_token=retry_token, ), addr, ) return else: try: retry_message = self._retry_key.decrypt( header.token, padding.OAEP( mgf=padding.MGF1(hashes.SHA</s>
tests.test_tls/ContextTest.test_handshake
Modified
aiortc~aioquic
e1c14782f506e80431ece2778d70401bcac1bf10
[tls] rework handshake tests
<3>:<del> # send client hello <4>:<del> client_buf = create_buffers() <5>:<del> client.handle_message(b"", client_buf) <6>:<del> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <7>:<del> server_input = merge_buffers(client_buf) <8>:<del> self.assertEqual(len(server_input), 252) <9>:<del> reset_buffers(client_buf) <10>:<add> self._handshake(client, server, create_ticket=False) <11>:<del> # handle client hello <12>:<del> # send server hello, encrypted extensions, certificate, certificate verify, finished <13>:<del> server_buf = create_buffers() <14>:<del> server.handle_message(server_input, server_buf) <15>:<del> self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) <16>:<del> client_input = merge_buffers(server_buf) <17>:<del> self.assertEqual(len(client_input), 2227) <18>:<del> reset_buffers(server_buf) <19>:<add> # check ALPN matches <add> self.assertEqual(client.alpn_negotiated, None) <add> self.assertEqual(server.alpn_negotiated, None) <20>:<del> # handle server hello, encrypted extensions, certificate, certificate verify, finished <21>:<del> # send finished <22>:<del> client.handle_message(client_input, client_buf) <23>:<del> self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) <24>:<del> server_input = merge_buffers(client_buf) <25>:<del> self.assertEqual(len(server_input), 52) <26>:<del> reset_buffers(client_buf) <27>:<del> <28>:<del> # handle finished <29>:<del> server.handle_message(server_input, server_buf) <30>:<del> self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) <31>:<del> client_input = merge_buffers(server_buf) <32>:<del> self.assertEqual(len(client_input), 0) <33>:<del> <34>:<del> # check keys match <35>:<del> self.assertEqual(client._dec_key, server._enc_key) <36>:<del> self.assertEqual(client._enc_key, server._dec_key) <37>:<del> <38>:<del>
# module: tests.test_tls class ContextTest(TestCase): def test_handshake(self): <0> client = self.create_client() <1> server = self.create_server() <2> <3> # send client hello <4> client_buf = create_buffers() <5> client.handle_message(b"", client_buf) <6> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <7> server_input = merge_buffers(client_buf) <8> self.assertEqual(len(server_input), 252) <9> reset_buffers(client_buf) <10> <11> # handle client hello <12> # send server hello, encrypted extensions, certificate, certificate verify, finished <13> server_buf = create_buffers() <14> server.handle_message(server_input, server_buf) <15> self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) <16> client_input = merge_buffers(server_buf) <17> self.assertEqual(len(client_input), 2227) <18> reset_buffers(server_buf) <19> <20> # handle server hello, encrypted extensions, certificate, certificate verify, finished <21> # send finished <22> client.handle_message(client_input, client_buf) <23> self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) <24> server_input = merge_buffers(client_buf) <25> self.assertEqual(len(server_input), 52) <26> reset_buffers(client_buf) <27> <28> # handle finished <29> server.handle_message(server_input, server_buf) <30> self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) <31> client_input = merge_buffers(server_buf) <32> self.assertEqual(len(client_input), 0) <33> <34> # check keys match <35> self.assertEqual(client._dec_key, server._enc_key) <36> self.assertEqual(client._enc_key, server._dec_key) <37> <38> </s>
===========below chunk 0=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake(self): # offset: 1 new_session_ticket = binascii.unhexlify( "04000035000151809468b842000020441fc19f9eb6ea425b48989c800258495" "a2bc30cac3a55032a7c0822feb842eb0008002a0004ffffffff" ) client.handle_message(new_session_ticket, client_buf) server_input = merge_buffers(client_buf) self.assertEqual(len(server_input), 0) ===========unchanged ref 0=========== at: aioquic.tls State() at: aioquic.tls.Context handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None at: aioquic.tls.Context.__init__ self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.state = State.CLIENT_HANDSHAKE_START self.state = State.SERVER_EXPECT_CLIENT_HELLO at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key at: aioquic.tls.Context._set_state self.state = state at: aioquic.tls.Context._setup_traffic_protection self._enc_key = key self._dec_key = key at: tests.test_tls create_buffers() merge_buffers(buffers) reset_buffers(buffers) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertGreaterEqual(a: Any, b: Any, msg: Any=...) -> None assertLessEqual(a: Any, b: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_tls class ContextTest(TestCase): + def _handshake(self, client, server, create_ticket): + # send client hello + client_buf = create_buffers() + client.handle_message(b"", client_buf) + self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) + server_input = merge_buffers(client_buf) + self.assertGreaterEqual(len(server_input), 219) + self.assertLessEqual(len(server_input), 264) + reset_buffers(client_buf) + + # handle client hello + # send server hello, encrypted extensions, certificate, certificate verify, finished + server_buf = create_buffers() + server.handle_message(server_input, server_buf) + self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) + client_input = merge_buffers(server_buf) + self.assertGreaterEqual(len(client_input), 2194) + self.assertLessEqual(len(client_input), 2239) + reset_buffers(server_buf) + + # handle server hello, encrypted extensions, certificate, certificate verify, finished + # send finished + client.handle_message(client_input, client_buf) + self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) + server_input = merge_buffers(client_buf) + self.assertEqual(len(server_input), 52) + reset_buffers(client_buf) + + # handle finished + # send new_session_ticket + server.handle_message(server_input, server_buf) + self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) + client_input = merge_buffers(server_buf) + if create_ticket: + self.assertEqual(len(client_input), 81) + reset_buffers(server_buf) + </s> ===========changed ref 1=========== # module: tests.test_tls class ContextTest(TestCase): + def _handshake(self, client, server, create_ticket): # offset: 1 <s> + self.assertEqual(len(client_input), 81) + reset_buffers(server_buf) + + # handle new_session_ticket + client.handle_message(client_input, client_buf) + self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) + server_input = merge_buffers(client_buf) + self.assertEqual(len(server_input), 0) + else: + self.assertEqual(len(client_input), 0) + + # check keys match + self.assertEqual(client._dec_key, server._enc_key) + self.assertEqual(client._enc_key, server._dec_key) + + # check cipher suite + self.assertEqual( + client.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384 + ) + self.assertEqual( + server.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384 + ) +
tests.test_tls/ContextTest.test_handshake_with_alpn
Modified
aiortc~aioquic
e1c14782f506e80431ece2778d70401bcac1bf10
[tls] rework handshake tests
<2>:<add> <5>:<del> # send client hello <6>:<del> client_buf = create_buffers() <7>:<del> client.handle_message(b"", client_buf) <8>:<del> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <9>:<del> server_input = merge_buffers(client_buf) <10>:<del> self.assertEqual(len(server_input), 264) <11>:<del> reset_buffers(client_buf) <12>:<del> <13>:<del> # handle client hello <14>:<del> # send server hello, encrypted extensions, certificate, certificate verify, finished <15>:<del> server_buf = create_buffers() <16>:<del> server.handle_message(server_input, server_buf) <17>:<del> self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) <18>:<del> client_input = merge_buffers(server_buf) <19>:<del> self.assertEqual(len(client_input), 2239) <20>:<del> reset_buffers(server_buf) <21>:<del> <22>:<del> # handle server hello, encrypted extensions, certificate, certificate verify, finished <23>:<del> # send finished <24>:<del> client.handle_message(client_input, client_buf) <25>:<del> self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) <26>:<del> server_input = merge_buffers(client_buf) <27>:<del> self.assertEqual(len(server_input), 52) <28>:<del> reset_buffers(client_buf) <29>:<del> <30>:<del> # handle finished <31>:<del> server.handle_message(server_input, server_buf) <32>:<del> self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) <33>:<del> client_input = merge_buffers(server_buf) <34>:<del> self.assertEqual(len(client_input), 0) <35>:<del> <36>:<del> # check keys match <37>:<del> ((bad delete))
# module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_alpn(self): <0> client = self.create_client() <1> client.alpn_protocols = ["hq-20"] <2> server = self.create_server() <3> server.alpn_protocols = ["hq-20", "h3-20"] <4> <5> # send client hello <6> client_buf = create_buffers() <7> client.handle_message(b"", client_buf) <8> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <9> server_input = merge_buffers(client_buf) <10> self.assertEqual(len(server_input), 264) <11> reset_buffers(client_buf) <12> <13> # handle client hello <14> # send server hello, encrypted extensions, certificate, certificate verify, finished <15> server_buf = create_buffers() <16> server.handle_message(server_input, server_buf) <17> self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) <18> client_input = merge_buffers(server_buf) <19> self.assertEqual(len(client_input), 2239) <20> reset_buffers(server_buf) <21> <22> # handle server hello, encrypted extensions, certificate, certificate verify, finished <23> # send finished <24> client.handle_message(client_input, client_buf) <25> self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) <26> server_input = merge_buffers(client_buf) <27> self.assertEqual(len(server_input), 52) <28> reset_buffers(client_buf) <29> <30> # handle finished <31> server.handle_message(server_input, server_buf) <32> self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) <33> client_input = merge_buffers(server_buf) <34> self.assertEqual(len(client_input), 0) <35> <36> # check keys match <37> </s>
===========below chunk 0=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_alpn(self): # offset: 1 self.assertEqual(client._enc_key, server._dec_key) # check ALPN matches self.assertEqual(client.alpn_negotiated, "hq-20") self.assertEqual(server.alpn_negotiated, "hq-20") ===========unchanged ref 0=========== at: aioquic.tls State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: aioquic.tls.Context.__init__ self.alpn_negotiated: Optional[str] = None self.key_schedule: Optional[KeySchedule] = None at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) self.key_schedule = KeySchedule(cipher_suite) at: aioquic.tls.KeySchedule.__init__ self.cipher_suite = cipher_suite at: tests.test_tls create_buffers() merge_buffers(buffers) at: tests.test_tls.ContextTest create_client() create_server() _handshake(client, server, create_ticket) _handshake(self, client, server, create_ticket) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_tls class ContextTest(TestCase): + def _handshake(self, client, server, create_ticket): + # send client hello + client_buf = create_buffers() + client.handle_message(b"", client_buf) + self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) + server_input = merge_buffers(client_buf) + self.assertGreaterEqual(len(server_input), 219) + self.assertLessEqual(len(server_input), 264) + reset_buffers(client_buf) + + # handle client hello + # send server hello, encrypted extensions, certificate, certificate verify, finished + server_buf = create_buffers() + server.handle_message(server_input, server_buf) + self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) + client_input = merge_buffers(server_buf) + self.assertGreaterEqual(len(client_input), 2194) + self.assertLessEqual(len(client_input), 2239) + reset_buffers(server_buf) + + # handle server hello, encrypted extensions, certificate, certificate verify, finished + # send finished + client.handle_message(client_input, client_buf) + self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) + server_input = merge_buffers(client_buf) + self.assertEqual(len(server_input), 52) + reset_buffers(client_buf) + + # handle finished + # send new_session_ticket + server.handle_message(server_input, server_buf) + self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) + client_input = merge_buffers(server_buf) + if create_ticket: + self.assertEqual(len(client_input), 81) + reset_buffers(server_buf) + </s> ===========changed ref 1=========== # module: tests.test_tls class ContextTest(TestCase): + def _handshake(self, client, server, create_ticket): # offset: 1 <s> + self.assertEqual(len(client_input), 81) + reset_buffers(server_buf) + + # handle new_session_ticket + client.handle_message(client_input, client_buf) + self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) + server_input = merge_buffers(client_buf) + self.assertEqual(len(server_input), 0) + else: + self.assertEqual(len(client_input), 0) + + # check keys match + self.assertEqual(client._dec_key, server._enc_key) + self.assertEqual(client._enc_key, server._dec_key) + + # check cipher suite + self.assertEqual( + client.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384 + ) + self.assertEqual( + server.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384 + ) + ===========changed ref 2=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake(self): client = self.create_client() server = self.create_server() - # send client hello - client_buf = create_buffers() - client.handle_message(b"", client_buf) - self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) - server_input = merge_buffers(client_buf) - self.assertEqual(len(server_input), 252) - reset_buffers(client_buf) + self._handshake(client, server, create_ticket=False) - # handle client hello - # send server hello, encrypted extensions, certificate, certificate verify, finished - server_buf = create_buffers() - server.handle_message(server_input, server_buf) - self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) - client_input = merge_buffers(server_buf) - self.assertEqual(len(client_input), 2227) - reset_buffers(server_buf) + # check ALPN matches + self.assertEqual(client.alpn_negotiated, None) + self.assertEqual(server.alpn_negotiated, None) - # handle server hello, encrypted extensions, certificate, certificate verify, finished - # send finished - client.handle_message(client_input, client_buf) - self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) - server_input = merge_buffers(client_buf) - self.assertEqual(len(server_input), 52) - reset_buffers(client_buf) - - # handle finished - server.handle_message(server_input, server_buf) - self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) - client_input = merge_buffers(server_buf) - self.assertEqual(len(client</s>
tests.test_tls/ContextTest.test_handshake_with_rsa_pkcs1_sha256_signature
Modified
aiortc~aioquic
e1c14782f506e80431ece2778d70401bcac1bf10
[tls] rework handshake tests
<4>:<del> # send client hello <5>:<del> client_buf = create_buffers() <6>:<del> client.handle_message(b"", client_buf) <7>:<del> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <8>:<del> server_input = merge_buffers(client_buf) <9>:<del> self.assertEqual(len(server_input), 246) <10>:<del> reset_buffers(client_buf) <11>:<add> self._handshake(client, server, create_ticket=False) <12>:<del> # handle client hello <13>:<del> # send server hello, encrypted extensions, certificate, certificate verify, finished <14>:<del> server_buf = create_buffers() <15>:<del> server.handle_message(server_input, server_buf) <16>:<del> self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) <17>:<del> client_input = merge_buffers(server_buf) <18>:<del> self.assertEqual(len(client_input), 2227) <19>:<del> reset_buffers(server_buf) <20>:<del> <21>:<del> # handle server hello, encrypted extensions, certificate, certificate verify, finished <22>:<del> # send finished <23>:<del> client.handle_message(client_input, client_buf) <24>:<del> self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) <25>:<del> server_input = merge_buffers(client_buf) <26>:<del> self.assertEqual(len(server_input), 52) <27>:<del> reset_buffers(client_buf) <28>:<del> <29>:<del> # handle finished <30>:<del> server.handle_message(server_input, server_buf) <31>:<del> self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) <32>:<del> client_input = merge_buffers(server_buf) <33>:<del> self.assertEqual(len(client_input), 0) <34>:<del> <35>:<del> # check keys match <36>:<del> self.assertEqual(
# module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_rsa_pkcs1_sha256_signature(self): <0> client = self.create_client() <1> client._signature_algorithms = [tls.SignatureAlgorithm.RSA_PKCS1_SHA256] <2> server = self.create_server() <3> <4> # send client hello <5> client_buf = create_buffers() <6> client.handle_message(b"", client_buf) <7> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <8> server_input = merge_buffers(client_buf) <9> self.assertEqual(len(server_input), 246) <10> reset_buffers(client_buf) <11> <12> # handle client hello <13> # send server hello, encrypted extensions, certificate, certificate verify, finished <14> server_buf = create_buffers() <15> server.handle_message(server_input, server_buf) <16> self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) <17> client_input = merge_buffers(server_buf) <18> self.assertEqual(len(client_input), 2227) <19> reset_buffers(server_buf) <20> <21> # handle server hello, encrypted extensions, certificate, certificate verify, finished <22> # send finished <23> client.handle_message(client_input, client_buf) <24> self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) <25> server_input = merge_buffers(client_buf) <26> self.assertEqual(len(server_input), 52) <27> reset_buffers(client_buf) <28> <29> # handle finished <30> server.handle_message(server_input, server_buf) <31> self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) <32> client_input = merge_buffers(server_buf) <33> self.assertEqual(len(client_input), 0) <34> <35> # check keys match <36> self.assertEqual(</s>
===========below chunk 0=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_rsa_pkcs1_sha256_signature(self): # offset: 1 self.assertEqual(client._enc_key, server._dec_key) ===========unchanged ref 0=========== at: tests.test_tls.ContextTest create_client() create_server() _handshake(client, server, create_ticket) _handshake(self, client, server, create_ticket) at: tests.test_tls.ContextTest.test_handshake_with_x25519 client = self.create_client() server = self.create_server() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_tls class ContextTest(TestCase): + def _handshake(self, client, server, create_ticket): + # send client hello + client_buf = create_buffers() + client.handle_message(b"", client_buf) + self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) + server_input = merge_buffers(client_buf) + self.assertGreaterEqual(len(server_input), 219) + self.assertLessEqual(len(server_input), 264) + reset_buffers(client_buf) + + # handle client hello + # send server hello, encrypted extensions, certificate, certificate verify, finished + server_buf = create_buffers() + server.handle_message(server_input, server_buf) + self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) + client_input = merge_buffers(server_buf) + self.assertGreaterEqual(len(client_input), 2194) + self.assertLessEqual(len(client_input), 2239) + reset_buffers(server_buf) + + # handle server hello, encrypted extensions, certificate, certificate verify, finished + # send finished + client.handle_message(client_input, client_buf) + self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) + server_input = merge_buffers(client_buf) + self.assertEqual(len(server_input), 52) + reset_buffers(client_buf) + + # handle finished + # send new_session_ticket + server.handle_message(server_input, server_buf) + self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) + client_input = merge_buffers(server_buf) + if create_ticket: + self.assertEqual(len(client_input), 81) + reset_buffers(server_buf) + </s> ===========changed ref 1=========== # module: tests.test_tls class ContextTest(TestCase): + def _handshake(self, client, server, create_ticket): # offset: 1 <s> + self.assertEqual(len(client_input), 81) + reset_buffers(server_buf) + + # handle new_session_ticket + client.handle_message(client_input, client_buf) + self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) + server_input = merge_buffers(client_buf) + self.assertEqual(len(server_input), 0) + else: + self.assertEqual(len(client_input), 0) + + # check keys match + self.assertEqual(client._dec_key, server._enc_key) + self.assertEqual(client._enc_key, server._dec_key) + + # check cipher suite + self.assertEqual( + client.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384 + ) + self.assertEqual( + server.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384 + ) + ===========changed ref 2=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_alpn(self): client = self.create_client() client.alpn_protocols = ["hq-20"] + server = self.create_server() server.alpn_protocols = ["hq-20", "h3-20"] - # send client hello - client_buf = create_buffers() - client.handle_message(b"", client_buf) - self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) - server_input = merge_buffers(client_buf) - self.assertEqual(len(server_input), 264) - reset_buffers(client_buf) - - # handle client hello - # send server hello, encrypted extensions, certificate, certificate verify, finished - server_buf = create_buffers() - server.handle_message(server_input, server_buf) - self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) - client_input = merge_buffers(server_buf) - self.assertEqual(len(client_input), 2239) - reset_buffers(server_buf) - - # handle server hello, encrypted extensions, certificate, certificate verify, finished - # send finished - client.handle_message(client_input, client_buf) - self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) - server_input = merge_buffers(client_buf) - self.assertEqual(len(server_input), 52) - reset_buffers(client_buf) - - # handle finished - server.handle_message(server_input, server_buf) - self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) - client_input = merge_buffers(server_buf) - self.assertEqual(len(client_input), 0) - - # check keys match - self.</s> ===========changed ref 3=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_alpn(self): # offset: 1 <s> - self.assertEqual(len(client_input), 0) - - # check keys match - self.assertEqual(client._dec_key, server._enc_key) - self.assertEqual(client._enc_key, server._dec_key) + self._handshake(client, server, create_ticket=False) # check ALPN matches self.assertEqual(client.alpn_negotiated, "hq-20") self.assertEqual(server.alpn_negotiated, "hq-20")
tests.test_tls/ContextTest.test_handshake_with_x25519
Modified
aiortc~aioquic
e1c14782f506e80431ece2778d70401bcac1bf10
[tls] rework handshake tests
<4>:<del> # send client hello <5>:<del> client_buf = create_buffers() <6>:<del> client.handle_message(b"", client_buf) <7>:<del> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <8>:<del> server_input = merge_buffers(client_buf) <9>:<del> self.assertEqual(len(server_input), 219) <10>:<del> reset_buffers(client_buf) <11>:<add> self._handshake(client, server, create_ticket=False) <12>:<del> # handle client hello <13>:<del> # send server hello, encrypted extensions, certificate, certificate verify, finished <14>:<del> server_buf = create_buffers() <15>:<del> server.handle_message(server_input, server_buf) <16>:<del> self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) <17>:<del> client_input = merge_buffers(server_buf) <18>:<del> self.assertEqual(len(client_input), 2194) <19>:<del> reset_buffers(server_buf) <20>:<del> <21>:<del> # handle server hello, encrypted extensions, certificate, certificate verify, finished <22>:<del> # send finished <23>:<del> client.handle_message(client_input, client_buf) <24>:<del> self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) <25>:<del> server_input = merge_buffers(client_buf) <26>:<del> self.assertEqual(len(server_input), 52) <27>:<del> reset_buffers(client_buf) <28>:<del> <29>:<del> # handle finished <30>:<del> server.handle_message(server_input, server_buf) <31>:<del> self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) <32>:<del> client_input = merge_buffers(server_buf) <33>:<del> self.assertEqual(len(client_input), 0) <34>:<del> <35>:<del> # check keys match <36>:<del> self.assertEqual(client._dec_key, server._enc_key) <37>:<del> self
# module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_x25519(self): <0> client = self.create_client() <1> client._supported_groups = [tls.Group.X25519] <2> server = self.create_server() <3> <4> # send client hello <5> client_buf = create_buffers() <6> client.handle_message(b"", client_buf) <7> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <8> server_input = merge_buffers(client_buf) <9> self.assertEqual(len(server_input), 219) <10> reset_buffers(client_buf) <11> <12> # handle client hello <13> # send server hello, encrypted extensions, certificate, certificate verify, finished <14> server_buf = create_buffers() <15> server.handle_message(server_input, server_buf) <16> self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) <17> client_input = merge_buffers(server_buf) <18> self.assertEqual(len(client_input), 2194) <19> reset_buffers(server_buf) <20> <21> # handle server hello, encrypted extensions, certificate, certificate verify, finished <22> # send finished <23> client.handle_message(client_input, client_buf) <24> self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) <25> server_input = merge_buffers(client_buf) <26> self.assertEqual(len(server_input), 52) <27> reset_buffers(client_buf) <28> <29> # handle finished <30> server.handle_message(server_input, server_buf) <31> self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) <32> client_input = merge_buffers(server_buf) <33> self.assertEqual(len(client_input), 0) <34> <35> # check keys match <36> self.assertEqual(client._dec_key, server._enc_key) <37> self</s>
===========below chunk 0=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_x25519(self): # offset: 1 ===========unchanged ref 0=========== at: aioquic.tls State() at: tests.test_tls create_buffers() merge_buffers(buffers) reset_buffers(buffers) at: tests.test_tls.ContextTest.test_session_ticket server_get_ticket(label) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_rsa_pkcs1_sha256_signature(self): client = self.create_client() client._signature_algorithms = [tls.SignatureAlgorithm.RSA_PKCS1_SHA256] server = self.create_server() - # send client hello - client_buf = create_buffers() - client.handle_message(b"", client_buf) - self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) - server_input = merge_buffers(client_buf) - self.assertEqual(len(server_input), 246) - reset_buffers(client_buf) + self._handshake(client, server, create_ticket=False) - # handle client hello - # send server hello, encrypted extensions, certificate, certificate verify, finished - server_buf = create_buffers() - server.handle_message(server_input, server_buf) - self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) - client_input = merge_buffers(server_buf) - self.assertEqual(len(client_input), 2227) - reset_buffers(server_buf) - - # handle server hello, encrypted extensions, certificate, certificate verify, finished - # send finished - client.handle_message(client_input, client_buf) - self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) - server_input = merge_buffers(client_buf) - self.assertEqual(len(server_input), 52) - reset_buffers(client_buf) - - # handle finished - server.handle_message(server_input, server_buf) - self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) - client_input = merge_buffers(server_buf) - self.assertEqual(len(client_input), 0) - - </s> ===========changed ref 1=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_rsa_pkcs1_sha256_signature(self): # offset: 1 <s>input = merge_buffers(server_buf) - self.assertEqual(len(client_input), 0) - - # check keys match - self.assertEqual(client._dec_key, server._enc_key) - self.assertEqual(client._enc_key, server._dec_key) - ===========changed ref 2=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_alpn(self): client = self.create_client() client.alpn_protocols = ["hq-20"] + server = self.create_server() server.alpn_protocols = ["hq-20", "h3-20"] - # send client hello - client_buf = create_buffers() - client.handle_message(b"", client_buf) - self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) - server_input = merge_buffers(client_buf) - self.assertEqual(len(server_input), 264) - reset_buffers(client_buf) - - # handle client hello - # send server hello, encrypted extensions, certificate, certificate verify, finished - server_buf = create_buffers() - server.handle_message(server_input, server_buf) - self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) - client_input = merge_buffers(server_buf) - self.assertEqual(len(client_input), 2239) - reset_buffers(server_buf) - - # handle server hello, encrypted extensions, certificate, certificate verify, finished - # send finished - client.handle_message(client_input, client_buf) - self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) - server_input = merge_buffers(client_buf) - self.assertEqual(len(server_input), 52) - reset_buffers(client_buf) - - # handle finished - server.handle_message(server_input, server_buf) - self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) - client_input = merge_buffers(server_buf) - self.assertEqual(len(client_input), 0) - - # check keys match - self.</s> ===========changed ref 3=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_alpn(self): # offset: 1 <s> - self.assertEqual(len(client_input), 0) - - # check keys match - self.assertEqual(client._dec_key, server._enc_key) - self.assertEqual(client._enc_key, server._dec_key) + self._handshake(client, server, create_ticket=False) # check ALPN matches self.assertEqual(client.alpn_negotiated, "hq-20") self.assertEqual(server.alpn_negotiated, "hq-20") ===========changed ref 4=========== # module: tests.test_tls class ContextTest(TestCase): + def _handshake(self, client, server, create_ticket): + # send client hello + client_buf = create_buffers() + client.handle_message(b"", client_buf) + self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) + server_input = merge_buffers(client_buf) + self.assertGreaterEqual(len(server_input), 219) + self.assertLessEqual(len(server_input), 264) + reset_buffers(client_buf) + + # handle client hello + # send server hello, encrypted extensions, certificate, certificate verify, finished + server_buf = create_buffers() + server.handle_message(server_input, server_buf) + self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) + client_input = merge_buffers(server_buf) + self.assertGreaterEqual(len(client_input), 2194) + self.assertLessEqual(len(client_input), 2239) + reset_buffers(server_buf) + + # handle server hello, encrypted extensions, certificate, certificate verify, finished + # send finished + client.handle_message(client_input, client_buf) + self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) + server_input = merge_buffers(client_buf) + self.assertEqual(len(server_input), 52) + reset_buffers(client_buf) + + # handle finished + # send new_session_ticket + server.handle_message(server_input, server_buf) + self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) + client_input = merge_buffers(server_buf) + if create_ticket: + self.assertEqual(len(client_input), 81) + reset_buffers(server_buf) + </s>
tests.test_tls/ContextTest.test_session_ticket
Modified
aiortc~aioquic
e1c14782f506e80431ece2778d70401bcac1bf10
[tls] rework handshake tests
<20>:<del> server.get_session_ticket_cb = server_get_ticket <23>:<del> # send client hello <24>:<del> client_buf = create_buffers() <25>:<del> client.handle_message(b"", client_buf) <26>:<del> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <27>:<del> server_input = merge_buffers(client_buf) <28>:<del> self.assertEqual(len(server_input), 252) <29>:<del> reset_buffers(client_buf) <30>:<del> <31>:<del> # handle client hello <32>:<del> # send server hello, encrypted extensions, certificate, certificate verify, finished <33>:<del> server_buf = create_buffers() <34>:<del> server.handle_message(server_input, server_buf) <35>:<del> self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) <36>:<del> client_input = merge_buffers(server_buf) <37>:<del> self.assertEqual(len(client_input), 2227) <38>:<del> reset_buffers(server_buf) <39>:<del> <40>:<del> # handle server hello, encrypted extensions, certificate, certificate verify, finished <41>:<del> # send finished <42>:<del> client.handle_message(client_input, client_buf) <43>:<del> self.assertEqual(client.state, State
# module: tests.test_tls class ContextTest(TestCase): def test_session_ticket(self): <0> client_tickets = [] <1> server_tickets = [] <2> <3> def client_new_ticket(ticket): <4> client_tickets.append(ticket) <5> <6> def server_get_ticket(label): <7> for t in server_tickets: <8> if t.ticket == label: <9> return t <10> return None <11> <12> def server_new_ticket(ticket): <13> server_tickets.append(ticket) <14> <15> def first_handshake(): <16> client = self.create_client() <17> client.new_session_ticket_cb = client_new_ticket <18> <19> server = self.create_server() <20> server.get_session_ticket_cb = server_get_ticket <21> server.new_session_ticket_cb = server_new_ticket <22> <23> # send client hello <24> client_buf = create_buffers() <25> client.handle_message(b"", client_buf) <26> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <27> server_input = merge_buffers(client_buf) <28> self.assertEqual(len(server_input), 252) <29> reset_buffers(client_buf) <30> <31> # handle client hello <32> # send server hello, encrypted extensions, certificate, certificate verify, finished <33> server_buf = create_buffers() <34> server.handle_message(server_input, server_buf) <35> self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) <36> client_input = merge_buffers(server_buf) <37> self.assertEqual(len(client_input), 2227) <38> reset_buffers(server_buf) <39> <40> # handle server hello, encrypted extensions, certificate, certificate verify, finished <41> # send finished <42> client.handle_message(client_input, client_buf) <43> self.assertEqual(client.state, State</s>
===========below chunk 0=========== # module: tests.test_tls class ContextTest(TestCase): def test_session_ticket(self): # offset: 1 server_input = merge_buffers(client_buf) self.assertEqual(len(server_input), 52) reset_buffers(client_buf) # handle finished # send new_session_ticket server.handle_message(server_input, server_buf) self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) client_input = merge_buffers(server_buf) self.assertEqual(len(client_input), 81) reset_buffers(server_buf) # handle new_session_ticket client.handle_message(client_input, client_buf) self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) server_input = merge_buffers(client_buf) self.assertEqual(len(server_input), 0) # check keys match self.assertEqual(client._dec_key, server._enc_key) self.assertEqual(client._enc_key, server._dec_key) # check tickets match self.assertEqual(len(client_tickets), 1) self.assertEqual(len(server_tickets), 1) self.assertEqual(client_tickets[0].ticket, server_tickets[0].ticket) self.assertEqual( client_tickets[0].resumption_secret, server_tickets[0].resumption_secret ) def second_handshake(): client = self.create_client() client.new_session_ticket_cb = client_new_ticket client.session_ticket = client_tickets[0] server = self.create_server() server.get_session_ticket_cb = server_get_ticket server.new_session_ticket_cb = server_new_ticket # send client hello with pre_shared_key client_buf = create_buffers() client.handle_message(</s> ===========below chunk 1=========== # module: tests.test_tls class ContextTest(TestCase): def test_session_ticket(self): # offset: 2 <s> # send client hello with pre_shared_key client_buf = create_buffers() client.handle_message(b"", client_buf) self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) server_input = merge_buffers(client_buf) self.assertEqual(len(server_input), 379) reset_buffers(client_buf) # handle client hello # send server hello, encrypted extensions, finished server_buf = create_buffers() server.handle_message(server_input, server_buf) self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) client_input = merge_buffers(server_buf) self.assertEqual(len(client_input), 303) reset_buffers(server_buf) # handle server hello, encrypted extensions, certificate, certificate verify, finished # send finished client.handle_message(client_input, client_buf) self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) server_input = merge_buffers(client_buf) self.assertEqual(len(server_input), 52) reset_buffers(client_buf) # handle finished # send new_session_ticket server.handle_message(server_input, server_buf) self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) client_input = merge_buffers(server_buf) self.assertEqual(len(client_input), 81) reset_buffers(server_buf) # handle new_session_ticket client.handle_message(client_input, client_buf) self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) </s> ===========below chunk 2=========== # module: tests.test_tls class ContextTest(TestCase): def test_session_ticket(self): # offset: 3 <s>input = merge_buffers(client_buf) self.assertEqual(len(server_input), 0) # check keys match self.assertEqual(client._dec_key, server._enc_key) self.assertEqual(client._enc_key, server._dec_key) first_handshake() second_handshake() ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.buffer.Buffer eof() -> bool at: aioquic.tls TLS_VERSION_1_3 = 0x0304 TLS_VERSION_1_3_DRAFT_28 = 0x7F1C TLS_VERSION_1_3_DRAFT_27 = 0x7F1B TLS_VERSION_1_3_DRAFT_26 = 0x7F1A AlertHandshakeFailure(*args: object) State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeyExchangeMode(x: Union[str, bytes, bytearray], base: int) KeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_client_hello(buf: Buffer) -> ClientHello at: binascii unhexlify(hexstr: _Ascii, /) -> bytes ===========unchanged ref 1=========== at: tests.test_tls CLIENT_QUIC_TRANSPORT_PARAMETERS = binascii.unhexlify( b"ff0000110031000500048010000000060004801000000007000480100000000" b"4000481000000000100024258000800024064000a00010a" ) create_buffers() merge_buffers(buffers) reset_buffers(buffers) at: tests.test_tls.ContextTest create_client() create_server() at: tests.test_tls.ContextTest.test_session_ticket client_tickets = [] server_get_ticket(label) first_handshake() second_handshake() second_handshake_fail() at: tests.utils load(name) at: unittest.case TestCase(methodName: str=...) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None at: unittest.case._AssertRaisesContext.__exit__ self.exception = exc_value.with_traceback(None)
aioquic.tls/Context._client_handle_hello
Modified
aiortc~aioquic
842c3db0cebad36e839d063d3db4f9e3aa4f3da0
[tls] make client validate PSK strictly
<7>:<add> if peer_hello.pre_shared_key is not None: <add> if ( <add> self._key_schedule_psk is None <del> if self._key_schedule_psk is not None and peer_hello.pre_shared_key is not None: <8>:<add> or peer_hello.pre_shared_key != 0 <del> assert peer_hello.pre_shared_key == 0 <9>:<add> or peer_hello.cipher_suite != self._key_schedule_psk.cipher_suite <add> ): <add> raise AlertIllegalParameter <11>:<del> self._key_schedule_psk = None
# module: aioquic.tls class Context: def _client_handle_hello(self, input_buf: Buffer, output_buf: Buffer) -> None: <0> peer_hello = pull_server_hello(input_buf) <1> <2> assert peer_hello.cipher_suite in self._cipher_suites <3> assert peer_hello.compression_method in self._compression_methods <4> assert peer_hello.supported_version in self._supported_versions <5> <6> # select key schedule <7> if self._key_schedule_psk is not None and peer_hello.pre_shared_key is not None: <8> assert peer_hello.pre_shared_key == 0 <9> self.key_schedule = self._key_schedule_psk <10> else: <11> self._key_schedule_psk = None <12> self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) <13> <14> # perform key exchange <15> peer_public_key = decode_public_key(peer_hello.key_share) <16> shared_key: Optional[bytes] = None <17> if ( <18> isinstance(peer_public_key, x25519.X25519PublicKey) <19> and self._x25519_private_key is not None <20> ): <21> shared_key = self._x25519_private_key.exchange(peer_public_key) <22> elif ( <23> isinstance(peer_public_key, ec.EllipticCurvePublicKey) <24> and self._ec_private_key is not None <25> and self._ec_private_key.public_key().curve.__class__ <26> == peer_public_key.curve.__class__ <27> ): <28> shared_key = self._ec_private_key.exchange(ec.ECDH(), peer_public_key) <29> assert shared_key is not None <30> <31> self.key_schedule.update_hash(input_buf.data) <32> self.key_schedule.extract(shared_key) <33> <34> self._setup_traffic_protection( <35> Direction.DECRYPT, E</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def _client_handle_hello(self, input_buf: Buffer, output_buf: Buffer) -> None: # offset: 1 ) self._set_state(State.CLIENT_EXPECT_ENCRYPTED_EXTENSIONS) ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls AlertIllegalParameter(*args: object) State() push_client_hello(buf: Buffer, hello: ClientHello) -> None pull_server_hello(buf: Buffer) -> ServerHello decode_public_key(key_share: KeyShareEntry) -> Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey] at: aioquic.tls.Context _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self.key_schedule: Optional[KeySchedule] = None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() ===========unchanged ref 1=========== hello = ClientHello( random=self.client_random, session_id=self.session_id, cipher_suites=self._cipher_suites, compression_methods=self._compression_methods, alpn_protocols=self.alpn_protocols, key_exchange_modes=self._key_exchange_modes, key_share=key_share, server_name=self.server_name, signature_algorithms=self._signature_algorithms, supported_groups=supported_groups, supported_versions=self._supported_versions, other_extensions=self.handshake_extensions, ) self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) at: aioquic.tls.KeySchedule.__init__ self.cipher_suite = cipher_suite at: aioquic.tls.KeyScheduleProxy select(cipher_suite: CipherSuite) -> KeySchedule at: aioquic.tls.ServerHello random: bytes session_id: bytes cipher_suite: CipherSuite compression_method: CompressionMethod key_share: Optional[KeyShareEntry] = None pre_shared_key: Optional[int] = None supported_version: Optional[int] = None ===========changed ref 0=========== # module: aioquic.tls + class AlertIllegalParameter(Alert): + description = AlertDescription.illegal_parameter +
tests.test_tls/ContextTest.test_session_ticket
Modified
aiortc~aioquic
842c3db0cebad36e839d063d3db4f9e3aa4f3da0
[tls] make client validate PSK strictly
# module: tests.test_tls class ContextTest(TestCase): def test_session_ticket(self): <0> client_tickets = [] <1> server_tickets = [] <2> <3> def client_new_ticket(ticket): <4> client_tickets.append(ticket) <5> <6> def server_get_ticket(label): <7> for t in server_tickets: <8> if t.ticket == label: <9> return t <10> return None <11> <12> def server_new_ticket(ticket): <13> server_tickets.append(ticket) <14> <15> def first_handshake(): <16> client = self.create_client() <17> client.new_session_ticket_cb = client_new_ticket <18> <19> server = self.create_server() <20> server.new_session_ticket_cb = server_new_ticket <21> <22> self._handshake(client, server, create_ticket=True) <23> <24> # check tickets match <25> self.assertEqual(len(client_tickets), 1) <26> self.assertEqual(len(server_tickets), 1) <27> self.assertEqual(client_tickets[0].ticket, server_tickets[0].ticket) <28> self.assertEqual( <29> client_tickets[0].resumption_secret, server_tickets[0].resumption_secret <30> ) <31> <32> def second_handshake(): <33> client = self.create_client() <34> client.session_ticket = client_tickets[0] <35> <36> server = self.create_server() <37> server.get_session_ticket_cb = server_get_ticket <38> <39> # send client hello with pre_shared_key <40> client_buf = create_buffers() <41> client.handle_message(b"", client_buf) <42> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <43> server_input = merge_buffers(client_buf) <44> self.assertEqual(len(server_input), 379) </s>
===========below chunk 0=========== # module: tests.test_tls class ContextTest(TestCase): def test_session_ticket(self): # offset: 1 # handle client hello # send server hello, encrypted extensions, finished server_buf = create_buffers() server.handle_message(server_input, server_buf) self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) client_input = merge_buffers(server_buf) self.assertEqual(len(client_input), 303) reset_buffers(server_buf) # handle server hello, encrypted extensions, certificate, certificate verify, finished # send finished client.handle_message(client_input, client_buf) self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) server_input = merge_buffers(client_buf) self.assertEqual(len(server_input), 52) reset_buffers(client_buf) # handle finished # send new_session_ticket server.handle_message(server_input, server_buf) self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) client_input = merge_buffers(server_buf) self.assertEqual(len(client_input), 0) reset_buffers(server_buf) # check keys match self.assertEqual(client._dec_key, server._enc_key) self.assertEqual(client._enc_key, server._dec_key) def second_handshake_fail(): client = self.create_client() client.session_ticket = client_tickets[0] server = self.create_server() server.get_session_ticket_cb = server_get_ticket # send client hello with pre_shared_key client_buf = create_buffers() client.handle_message(b"", client_buf) self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) server_input = merge_buffers(client_buf</s> ===========below chunk 1=========== # module: tests.test_tls class ContextTest(TestCase): def test_session_ticket(self): # offset: 2 <s>client.state, State.CLIENT_EXPECT_SERVER_HELLO) server_input = merge_buffers(client_buf) self.assertEqual(len(server_input), 379) reset_buffers(client_buf) # tamper with binder server_input = server_input[:-4] + bytes(4) # handle client hello # send server hello, encrypted extensions, finished server_buf = create_buffers() with self.assertRaises(tls.AlertHandshakeFailure) as cm: server.handle_message(server_input, server_buf) self.assertEqual(str(cm.exception), "PSK validation failed") first_handshake() second_handshake() second_handshake_fail() ===========unchanged ref 0=========== at: aioquic.tls AlertHandshakeFailure(*args: object) State() at: aioquic.tls.Context handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None at: aioquic.tls.Context.__init__ self.session_ticket: Optional[SessionTicket] = None self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.state = State.CLIENT_HANDSHAKE_START self.state = State.SERVER_EXPECT_CLIENT_HELLO at: aioquic.tls.Context._set_state self.state = state at: tests.test_tls create_buffers() merge_buffers(buffers) reset_buffers(buffers) at: tests.test_tls.ContextTest create_client() create_server() _handshake(client, server, create_ticket) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None at: unittest.case._AssertRaisesContext.__exit__ self.exception = exc_value.with_traceback(None) ===========changed ref 0=========== # module: aioquic.tls + class AlertIllegalParameter(Alert): + description = AlertDescription.illegal_parameter + ===========changed ref 1=========== # module: aioquic.tls class Context: def _client_handle_hello(self, input_buf: Buffer, output_buf: Buffer) -> None: peer_hello = pull_server_hello(input_buf) assert peer_hello.cipher_suite in self._cipher_suites assert peer_hello.compression_method in self._compression_methods assert peer_hello.supported_version in self._supported_versions # select key schedule + if peer_hello.pre_shared_key is not None: + if ( + self._key_schedule_psk is None - if self._key_schedule_psk is not None and peer_hello.pre_shared_key is not None: + or peer_hello.pre_shared_key != 0 - assert peer_hello.pre_shared_key == 0 + or peer_hello.cipher_suite != self._key_schedule_psk.cipher_suite + ): + raise AlertIllegalParameter self.key_schedule = self._key_schedule_psk else: - self._key_schedule_psk = None self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) # perform key exchange peer_public_key = decode_public_key(peer_hello.key_share) shared_key: Optional[bytes] = None if ( isinstance(peer_public_key, x25519.X25519PublicKey) and self._x25519_private_key is not None ): shared_key = self._x25519_private_key.exchange(peer_public_key) elif ( isinstance(peer_public_key, ec.EllipticCurvePublicKey) and self._ec_private_key is not None and self._ec_private_key.public_key().curve.__class__ == peer_public_key.curve.__class__ ): shared_key = self._ec_private_key.exchange(ec.ECDH(), peer_public_key) assert shared_key is not None</s> ===========changed ref 2=========== # module: aioquic.tls class Context: def _client_handle_hello(self, input_buf: Buffer, output_buf: Buffer) -> None: # offset: 1 <s> self._ec_private_key.exchange(ec.ECDH(), peer_public_key) assert shared_key is not None self.key_schedule.update_hash(input_buf.data) self.key_schedule.extract(shared_key) self._setup_traffic_protection( Direction.DECRYPT, Epoch.HANDSHAKE, b"s hs traffic" ) self._set_state(State.CLIENT_EXPECT_ENCRYPTED_EXTENSIONS)
tests.test_high_level/run_server
Modified
aiortc~aioquic
b41523760ea7198d2ff021c0506dd3e76360ca88
[tests] add high-level test for session resumption
<5>:<del> stateless_retry=stateless_retry, <7>:<add> **kwargs
# module: tests.test_high_level + def run_server(**kwargs): - def run_server(stateless_retry): <0> await serve( <1> host="::", <2> port="4433", <3> certificate=SERVER_CERTIFICATE, <4> private_key=SERVER_PRIVATE_KEY, <5> stateless_retry=stateless_retry, <6> stream_handler=handle_stream, <7> ) <8>
===========unchanged ref 0=========== at: asyncio.tasks ensure_future(coro_or_future: _FutureT[_T], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T] ===========changed ref 0=========== # module: tests.test_high_level + class SessionTicketStore: + def pop(self, label): + return self.tickets.pop(label, None) + ===========changed ref 1=========== # module: tests.test_high_level + class SessionTicketStore: + def __init__(self): + self.tickets = {} + ===========changed ref 2=========== # module: tests.test_high_level + class SessionTicketStore: + def add(self, ticket): + self.tickets[ticket.ticket] = ticket +
aioquic.tls/pull_new_session_ticket
Modified
aiortc~aioquic
d22c8bc23b48cf585c1e9a805aa03c1e6b21ad06
[tls] explicitly parse NewSessionTicket.max_early_data_size
<8>:<add> <add> def pull_extension(buf: Buffer) -> None: <add> extension_type = pull_uint16(buf) <add> extension_length = pull_uint16(buf) <add> if extension_type == ExtensionType.EARLY_DATA: <add> new_session_ticket.max_early_data_size = pull_uint32(buf) <add> else: <add> pull_bytes(buf, extension_length) <add> <add> pull_list(buf, 2, pull_extension) <del> new_session_ticket.extensions = pull_list(buf, 2, pull_raw_extension)
# module: aioquic.tls def pull_new_session_ticket(buf: Buffer) -> NewSessionTicket: <0> new_session_ticket = NewSessionTicket() <1> <2> assert pull_uint8(buf) == HandshakeType.NEW_SESSION_TICKET <3> with pull_block(buf, 3): <4> new_session_ticket.ticket_lifetime = pull_uint32(buf) <5> new_session_ticket.ticket_age_add = pull_uint32(buf) <6> new_session_ticket.ticket_nonce = pull_opaque(buf, 1) <7> new_session_ticket.ticket = pull_opaque(buf, 2) <8> new_session_ticket.extensions = pull_list(buf, 2, pull_raw_extension) <9> <10> return new_session_ticket <11>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) pull_uint8(buf: Buffer) -> int pull_uint32(buf: Buffer) -> int at: aioquic.tls HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) pull_block(buf: Buffer, capacity: int) -> Generator pull_opaque(buf: Buffer, capacity: int) -> bytes NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b"", ticket: bytes=b"", max_early_data_size: Optional[int]=None) at: aioquic.tls.NewSessionTicket ticket_lifetime: int = 0 ticket_age_add: int = 0 ticket_nonce: bytes = b"" ticket: bytes = b"" max_early_data_size: Optional[int] = None ===========changed ref 0=========== # module: aioquic.tls @dataclass class NewSessionTicket: ticket_lifetime: int = 0 ticket_age_add: int = 0 ticket_nonce: bytes = b"" ticket: bytes = b"" - extensions: List[Extension] = field(default_factory=list)
aioquic.tls/push_new_session_ticket
Modified
aiortc~aioquic
d22c8bc23b48cf585c1e9a805aa03c1e6b21ad06
[tls] explicitly parse NewSessionTicket.max_early_data_size
<6>:<del> push_list(buf, 2, push_raw_extension, new_session_ticket.extensions)
# module: aioquic.tls def push_new_session_ticket(buf: Buffer, new_session_ticket: NewSessionTicket) -> None: <0> push_uint8(buf, HandshakeType.NEW_SESSION_TICKET) <1> with push_block(buf, 3): <2> push_uint32(buf, new_session_ticket.ticket_lifetime) <3> push_uint32(buf, new_session_ticket.ticket_age_add) <4> push_opaque(buf, 1, new_session_ticket.ticket_nonce) <5> push_opaque(buf, 2, new_session_ticket.ticket) <6> push_list(buf, 2, push_raw_extension, new_session_ticket.extensions) <7>
===========unchanged ref 0=========== at: aioquic.buffer pull_bytes(buf: Buffer, length: int) -> bytes pull_uint16(buf: Buffer) -> int pull_uint32(buf: Buffer) -> int at: aioquic.tls ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_list(buf: Buffer, capacity: int, func: Callable[[Buffer], T]) -> List[T] at: aioquic.tls.NewSessionTicket max_early_data_size: Optional[int] = None at: aioquic.tls.pull_new_session_ticket new_session_ticket = NewSessionTicket() pull_extension(buf: Buffer) -> None ===========changed ref 0=========== # module: aioquic.tls @dataclass class NewSessionTicket: ticket_lifetime: int = 0 ticket_age_add: int = 0 ticket_nonce: bytes = b"" ticket: bytes = b"" - extensions: List[Extension] = field(default_factory=list) ===========changed ref 1=========== # module: aioquic.tls def pull_new_session_ticket(buf: Buffer) -> NewSessionTicket: new_session_ticket = NewSessionTicket() assert pull_uint8(buf) == HandshakeType.NEW_SESSION_TICKET with pull_block(buf, 3): new_session_ticket.ticket_lifetime = pull_uint32(buf) new_session_ticket.ticket_age_add = pull_uint32(buf) new_session_ticket.ticket_nonce = pull_opaque(buf, 1) new_session_ticket.ticket = pull_opaque(buf, 2) + + def pull_extension(buf: Buffer) -> None: + extension_type = pull_uint16(buf) + extension_length = pull_uint16(buf) + if extension_type == ExtensionType.EARLY_DATA: + new_session_ticket.max_early_data_size = pull_uint32(buf) + else: + pull_bytes(buf, extension_length) + + pull_list(buf, 2, pull_extension) - new_session_ticket.extensions = pull_list(buf, 2, pull_raw_extension) return new_session_ticket
aioquic.tls/Context._build_session_ticket
Modified
aiortc~aioquic
d22c8bc23b48cf585c1e9a805aa03c1e6b21ad06
[tls] explicitly parse NewSessionTicket.max_early_data_size
<13>:<add> max_early_data_size=new_session_ticket.max_early_data_size,
# module: aioquic.tls class Context: def _build_session_ticket( self, new_session_ticket: NewSessionTicket ) -> SessionTicket: <0> resumption_master_secret = self.key_schedule.derive_secret(b"res master") <1> resumption_secret = hkdf_expand_label( <2> algorithm=self.key_schedule.algorithm, <3> secret=resumption_master_secret, <4> label=b"resumption", <5> hash_value=new_session_ticket.ticket_nonce, <6> length=self.key_schedule.algorithm.digest_size, <7> ) <8> <9> timestamp = datetime.datetime.now() <10> return SessionTicket( <11> age_add=new_session_ticket.ticket_age_add, <12> cipher_suite=self.key_schedule.cipher_suite, <13> not_valid_after=timestamp <14> + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), <15> not_valid_before=timestamp, <16> resumption_secret=resumption_secret, <17> server_name=self.server_name, <18> ticket=new_session_ticket.ticket, <19> ) <20>
===========unchanged ref 0=========== at: aioquic.buffer.Buffer eof() -> bool at: aioquic.tls AlertUnexpectedMessage(*args: object) Epoch() State() HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b"", ticket: bytes=b"", max_early_data_size: Optional[int]=None) at: aioquic.tls.Context _server_handle_finished(input_buf: Buffer, output_buf: Buffer) -> None at: aioquic.tls.Context.__init__ self.state = State.CLIENT_HANDSHAKE_START self.state = State.SERVER_EXPECT_CLIENT_HELLO at: aioquic.tls.Context._set_state self.state = state at: aioquic.tls.Context.handle_message message_type = self._receive_buffer[0] input_buf = Buffer(data=message) ===========changed ref 0=========== # module: aioquic.tls @dataclass class NewSessionTicket: ticket_lifetime: int = 0 ticket_age_add: int = 0 ticket_nonce: bytes = b"" ticket: bytes = b"" - extensions: List[Extension] = field(default_factory=list) ===========changed ref 1=========== # module: aioquic.tls # callback types @dataclass class SessionTicket: + """ + A TLS session ticket for session resumption. + """ + age_add: int cipher_suite: CipherSuite not_valid_after: datetime.datetime not_valid_before: datetime.datetime resumption_secret: bytes server_name: str ticket: bytes ===========changed ref 2=========== # module: aioquic.tls def push_new_session_ticket(buf: Buffer, new_session_ticket: NewSessionTicket) -> None: push_uint8(buf, HandshakeType.NEW_SESSION_TICKET) with push_block(buf, 3): push_uint32(buf, new_session_ticket.ticket_lifetime) push_uint32(buf, new_session_ticket.ticket_age_add) push_opaque(buf, 1, new_session_ticket.ticket_nonce) push_opaque(buf, 2, new_session_ticket.ticket) - push_list(buf, 2, push_raw_extension, new_session_ticket.extensions) ===========changed ref 3=========== # module: aioquic.tls def pull_new_session_ticket(buf: Buffer) -> NewSessionTicket: new_session_ticket = NewSessionTicket() assert pull_uint8(buf) == HandshakeType.NEW_SESSION_TICKET with pull_block(buf, 3): new_session_ticket.ticket_lifetime = pull_uint32(buf) new_session_ticket.ticket_age_add = pull_uint32(buf) new_session_ticket.ticket_nonce = pull_opaque(buf, 1) new_session_ticket.ticket = pull_opaque(buf, 2) + + def pull_extension(buf: Buffer) -> None: + extension_type = pull_uint16(buf) + extension_length = pull_uint16(buf) + if extension_type == ExtensionType.EARLY_DATA: + new_session_ticket.max_early_data_size = pull_uint32(buf) + else: + pull_bytes(buf, extension_length) + + pull_list(buf, 2, pull_extension) - new_session_ticket.extensions = pull_list(buf, 2, pull_raw_extension) return new_session_ticket
tests.test_tls/TlsTest.test_pull_new_session_ticket
Modified
aiortc~aioquic
d22c8bc23b48cf585c1e9a805aa03c1e6b21ad06
[tls] explicitly parse NewSessionTicket.max_early_data_size
<5>:<del> self.assertEqual(new_session_ticket.ticket_lifetime, 86400) <6>:<del> self.assertEqual(new_session_ticket.ticket_age_add, 3303452425) <7>:<del> self.assertEqual(new_session_ticket.ticket_nonce, b"") <9>:<add> new_session_ticket, <del> new_session_ticket.ticket, <10>:<add> NewSessionTicket( <add> ticket_lifetime=86400, <add> ticket_age_add=3303452425, <add> ticket_nonce=b"", <add> ticket=binascii.unhexlify( <del> binascii.unhexlify( <11>:<add> "dbe6f1a77a78c0426bfa607cd0d02b350247d90618704709596beda7e962cc81" <del> "dbe6f1a77a78c0426bfa607cd0d02b350247d90618704709596beda7e962cc81" <12>:<add> ), <add> max_early_data_size=4294967295, <14>:<del> self.assertEqual( <15>:<del> new_session_ticket.extensions, <16>:<del> [(tls.ExtensionType.EARLY_DATA, b"\xff\xff\xff\xff")], <17>:<del> )
# module: tests.test_tls class TlsTest(TestCase): def test_pull_new_session_ticket(self): <0> buf = Buffer(data=load("tls_new_session_ticket.bin")) <1> new_session_ticket = pull_new_session_ticket(buf) <2> self.assertIsNotNone(new_session_ticket) <3> self.assertTrue(buf.eof()) <4> <5> self.assertEqual(new_session_ticket.ticket_lifetime, 86400) <6> self.assertEqual(new_session_ticket.ticket_age_add, 3303452425) <7> self.assertEqual(new_session_ticket.ticket_nonce, b"") <8> self.assertEqual( <9> new_session_ticket.ticket, <10> binascii.unhexlify( <11> "dbe6f1a77a78c0426bfa607cd0d02b350247d90618704709596beda7e962cc81" <12> ), <13> ) <14> self.assertEqual( <15> new_session_ticket.extensions, <16> [(tls.ExtensionType.EARLY_DATA, b"\xff\xff\xff\xff")], <17> ) <18>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.buffer.Buffer eof() -> bool at: aioquic.tls NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b"", ticket: bytes=b"", max_early_data_size: Optional[int]=None) pull_new_session_ticket(buf: Buffer) -> NewSessionTicket at: aioquic.tls.NewSessionTicket ticket_lifetime: int = 0 ticket_age_add: int = 0 ticket_nonce: bytes = b"" ticket: bytes = b"" max_early_data_size: Optional[int] = None at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.utils load(name) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None assertIsNotNone(obj: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.tls @dataclass class NewSessionTicket: ticket_lifetime: int = 0 ticket_age_add: int = 0 ticket_nonce: bytes = b"" ticket: bytes = b"" - extensions: List[Extension] = field(default_factory=list) ===========changed ref 1=========== # module: aioquic.tls def pull_new_session_ticket(buf: Buffer) -> NewSessionTicket: new_session_ticket = NewSessionTicket() assert pull_uint8(buf) == HandshakeType.NEW_SESSION_TICKET with pull_block(buf, 3): new_session_ticket.ticket_lifetime = pull_uint32(buf) new_session_ticket.ticket_age_add = pull_uint32(buf) new_session_ticket.ticket_nonce = pull_opaque(buf, 1) new_session_ticket.ticket = pull_opaque(buf, 2) + + def pull_extension(buf: Buffer) -> None: + extension_type = pull_uint16(buf) + extension_length = pull_uint16(buf) + if extension_type == ExtensionType.EARLY_DATA: + new_session_ticket.max_early_data_size = pull_uint32(buf) + else: + pull_bytes(buf, extension_length) + + pull_list(buf, 2, pull_extension) - new_session_ticket.extensions = pull_list(buf, 2, pull_raw_extension) return new_session_ticket ===========changed ref 2=========== # module: aioquic.tls # callback types @dataclass class SessionTicket: + """ + A TLS session ticket for session resumption. + """ + age_add: int cipher_suite: CipherSuite not_valid_after: datetime.datetime not_valid_before: datetime.datetime resumption_secret: bytes server_name: str ticket: bytes ===========changed ref 3=========== # module: aioquic.tls def push_new_session_ticket(buf: Buffer, new_session_ticket: NewSessionTicket) -> None: push_uint8(buf, HandshakeType.NEW_SESSION_TICKET) with push_block(buf, 3): push_uint32(buf, new_session_ticket.ticket_lifetime) push_uint32(buf, new_session_ticket.ticket_age_add) push_opaque(buf, 1, new_session_ticket.ticket_nonce) push_opaque(buf, 2, new_session_ticket.ticket) - push_list(buf, 2, push_raw_extension, new_session_ticket.extensions) ===========changed ref 4=========== # module: aioquic.tls class Context: def _build_session_ticket( self, new_session_ticket: NewSessionTicket ) -> SessionTicket: resumption_master_secret = self.key_schedule.derive_secret(b"res master") resumption_secret = hkdf_expand_label( algorithm=self.key_schedule.algorithm, secret=resumption_master_secret, label=b"resumption", hash_value=new_session_ticket.ticket_nonce, length=self.key_schedule.algorithm.digest_size, ) timestamp = datetime.datetime.now() return SessionTicket( age_add=new_session_ticket.ticket_age_add, cipher_suite=self.key_schedule.cipher_suite, + max_early_data_size=new_session_ticket.max_early_data_size, not_valid_after=timestamp + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), not_valid_before=timestamp, resumption_secret=resumption_secret, server_name=self.server_name, ticket=new_session_ticket.ticket, )
aioquic.tls/pull_client_hello
Modified
aiortc~aioquic
594ffcc66ed15b41af4c19a6de82426f4ff3d59d
[tls] parse ClientHello.early_data
# module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: <0> assert pull_uint8(buf) == HandshakeType.CLIENT_HELLO <1> with pull_block(buf, 3): <2> assert pull_uint16(buf) == TLS_VERSION_1_2 <3> client_random = pull_bytes(buf, 32) <4> <5> hello = ClientHello( <6> random=client_random, <7> session_id=pull_opaque(buf, 1), <8> cipher_suites=pull_list(buf, 2, pull_cipher_suite), <9> compression_methods=pull_list(buf, 1, pull_compression_method), <10> ) <11> <12> # extensions <13> after_psk = False <14> <15> def pull_extension(buf: Buffer) -> None: <16> # pre_shared_key MUST be last <17> nonlocal after_psk <18> assert not after_psk <19> <20> extension_type = pull_uint16(buf) <21> extension_length = pull_uint16(buf) <22> if extension_type == ExtensionType.KEY_SHARE: <23> hello.key_share = pull_list(buf, 2, pull_key_share) <24> elif extension_type == ExtensionType.SUPPORTED_VERSIONS: <25> hello.supported_versions = pull_list(buf, 1, pull_uint16) <26> elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS: <27> hello.signature_algorithms = pull_list(buf, 2, pull_signature_algorithm) <28> elif extension_type == ExtensionType.SUPPORTED_GROUPS: <29> hello.supported_groups = pull_list(buf, 2, pull_group) <30> elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES: <31> hello.key_exchange_modes = pull_list(buf, 1, pull_key_exchange_mode) <32> elif extension_type == ExtensionType.SERVER_NAME: <33> with pull_block(buf, 2): <34> assert pull_uint8(buf) == 0 <35> hello</s>
===========below chunk 0=========== # module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: # offset: 1 elif extension_type == ExtensionType.ALPN: hello.alpn_protocols = pull_list(buf, 2, pull_alpn_protocol) elif extension_type == ExtensionType.PRE_SHARED_KEY: hello.pre_shared_key = OfferedPsks( identities=pull_list(buf, 2, pull_psk_identity), binders=pull_list(buf, 2, pull_psk_binder), ) after_psk = True else: hello.other_extensions.append( (extension_type, pull_bytes(buf, extension_length)) ) pull_list(buf, 2, pull_extension) return hello ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) pull_bytes(buf: Buffer, length: int) -> bytes pull_uint8(buf: Buffer) -> int pull_uint16(buf: Buffer) -> int at: aioquic.tls TLS_VERSION_1_2 = 0x0303 ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) pull_cipher_suite(buf: Buffer) -> CipherSuite pull_compression_method(buf: Buffer) -> CompressionMethod pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode pull_group(buf: Buffer) -> Group pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm pull_block(buf: Buffer, capacity: int) -> Generator pull_list(buf: Buffer, capacity: int, func: Callable[[Buffer], T]) -> List[T] pull_opaque(buf: Buffer, capacity: int) -> bytes pull_key_share(buf: Buffer) -> KeyShareEntry pull_alpn_protocol(buf: Buffer) -> str pull_psk_identity(buf: Buffer) -> PskIdentity pull_psk_binder(buf: Buffer) -> bytes OfferedPsks(identities: List[PskIdentity], binders: List[bytes]) ===========unchanged ref 1=========== ClientHello(random: bytes, session_id: bytes, cipher_suites: List[CipherSuite], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_exchange_modes: Optional[List[KeyExchangeMode]]=None, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list)) at: aioquic.tls.ClientHello random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] alpn_protocols: Optional[List[str]] = None early_data: bool = False key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) at: aioquic.tls.OfferedPsks identities: List[PskIdentity] binders: List[bytes] ===========changed ref 0=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None + early_data: bool = False key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list)
aioquic.tls/push_client_hello
Modified
aiortc~aioquic
594ffcc66ed15b41af4c19a6de82426f4ff3d59d
[tls] parse ClientHello.early_data
# module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: <0> push_uint8(buf, HandshakeType.CLIENT_HELLO) <1> with push_block(buf, 3): <2> push_uint16(buf, TLS_VERSION_1_2) <3> push_bytes(buf, hello.random) <4> push_opaque(buf, 1, hello.session_id) <5> push_list(buf, 2, push_cipher_suite, hello.cipher_suites) <6> push_list(buf, 1, push_compression_method, hello.compression_methods) <7> <8> # extensions <9> with push_block(buf, 2): <10> with push_extension(buf, ExtensionType.KEY_SHARE): <11> push_list(buf, 2, push_key_share, hello.key_share) <12> <13> with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): <14> push_list(buf, 1, push_uint16, hello.supported_versions) <15> <16> with push_extension(buf, ExtensionType.SIGNATURE_ALGORITHMS): <17> push_list(buf, 2, push_signature_algorithm, hello.signature_algorithms) <18> <19> with push_extension(buf, ExtensionType.SUPPORTED_GROUPS): <20> push_list(buf, 2, push_group, hello.supported_groups) <21> <22> with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): <23> push_list(buf, 1, push_key_exchange_mode, hello.key_exchange_modes) <24> <25> if hello.server_name is not None: <26> with push_extension(buf, ExtensionType.SERVER_NAME): <27> with push_block(buf, 2): <28> push_uint8(buf, 0) <29> push_opaque(buf, 2, hello.server_name.encode("ascii")) <30> <31> if hello.alpn_protocols is not None: <32> with push_extension(buf, ExtensionType.ALPN): <33> push_list</s>
===========below chunk 0=========== # module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: # offset: 1 for extension_type, extension_value in hello.other_extensions: with push_extension(buf, extension_type): push_bytes(buf, extension_value) # pre_shared_key MUST be last if hello.pre_shared_key is not None: with push_extension(buf, ExtensionType.PRE_SHARED_KEY): push_list( buf, 2, push_psk_identity, hello.pre_shared_key.identities ) push_list(buf, 2, push_psk_binder, hello.pre_shared_key.binders) ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) push_bytes(buf: Buffer, v: bytes) -> None push_uint8(buf: Buffer, v: int) -> None push_uint16(buf: Buffer, v: int) -> None at: aioquic.tls TLS_VERSION_1_2 = 0x0303 ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) push_cipher_suite = push_uint16 push_compression_method = push_uint8 push_group = push_uint16 push_key_exchange_mode = push_uint8 push_signature_algorithm = push_uint16 push_block(buf: Buffer, capacity: int) -> Generator push_list(buf: Buffer, capacity: int, func: Callable[[Buffer, T], None], values: Sequence[T]) -> None push_opaque(buf: Buffer, capacity: int, value: bytes) -> None push_extension(buf: Buffer, extension_type: int) -> Generator push_key_share(buf: Buffer, value: KeyShareEntry) -> None push_alpn_protocol(buf: Buffer, protocol: str) -> None ===========unchanged ref 1=========== ClientHello(random: bytes, session_id: bytes, cipher_suites: List[CipherSuite], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_exchange_modes: Optional[List[KeyExchangeMode]]=None, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list)) at: aioquic.tls.ClientHello random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] alpn_protocols: Optional[List[str]] = None early_data: bool = False key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) at: aioquic.tls.pull_client_hello hello = ClientHello( random=client_random, session_id=pull_opaque(buf, 1), cipher_suites=pull_list(buf, 2, pull_cipher_suite), compression_methods=pull_list(buf, 1, pull_compression_method), ) ===========changed ref 0=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None + early_data: bool = False key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) ===========changed ref 1=========== # module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: assert pull_uint8(buf) == HandshakeType.CLIENT_HELLO with pull_block(buf, 3): assert pull_uint16(buf) == TLS_VERSION_1_2 client_random = pull_bytes(buf, 32) hello = ClientHello( random=client_random, session_id=pull_opaque(buf, 1), cipher_suites=pull_list(buf, 2, pull_cipher_suite), compression_methods=pull_list(buf, 1, pull_compression_method), ) # extensions after_psk = False def pull_extension(buf: Buffer) -> None: # pre_shared_key MUST be last nonlocal after_psk assert not after_psk extension_type = pull_uint16(buf) extension_length = pull_uint16(buf) if extension_type == ExtensionType.KEY_SHARE: hello.key_share = pull_list(buf, 2, pull_key_share) elif extension_type == ExtensionType.SUPPORTED_VERSIONS: hello.supported_versions = pull_list(buf, 1, pull_uint16) elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS: hello.signature_algorithms = pull_list(buf, 2, pull_signature_algorithm) elif extension_type == ExtensionType.SUPPORTED_GROUPS: hello.supported_groups = pull_list(buf, 2, pull_group) elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES: hello.key_exchange_modes = pull_list(buf, 1, pull_key_exchange_mode) elif extension_type == ExtensionType.SERVER_NAME: with pull_block(buf, 2): assert pull_uint8(buf) == 0 hello.server_name = pull_opaque(buf, 2).decode("ascii") elif extension_type == ExtensionType.ALPN: hello.al</s>
tests.test_tls/TlsTest.test_pull_client_hello_with_alpn
Modified
aiortc~aioquic
594ffcc66ed15b41af4c19a6de82426f4ff3d59d
[tls] parse ClientHello.early_data
<24>:<add> self.assertEqual(hello.early_data, False)
# module: tests.test_tls class TlsTest(TestCase): def test_pull_client_hello_with_alpn(self): <0> buf = Buffer(data=load("tls_client_hello_with_alpn.bin")) <1> hello = pull_client_hello(buf) <2> self.assertTrue(buf.eof()) <3> <4> self.assertEqual( <5> hello.random, <6> binascii.unhexlify( <7> "ed575c6fbd599c4dfaabd003dca6e860ccdb0e1782c1af02e57bf27cb6479b76" <8> ), <9> ) <10> self.assertEqual(hello.session_id, b"") <11> self.assertEqual( <12> hello.cipher_suites, <13> [ <14> tls.CipherSuite.AES_128_GCM_SHA256, <15> tls.CipherSuite.AES_256_GCM_SHA384, <16> tls.CipherSuite.CHACHA20_POLY1305_SHA256, <17> tls.CipherSuite.EMPTY_RENEGOTIATION_INFO_SCSV, <18> ], <19> ) <20> self.assertEqual(hello.compression_methods, [tls.CompressionMethod.NULL]) <21> <22> # extensions <23> self.assertEqual(hello.alpn_protocols, ["h3-19"]) <24> self.assertEqual(hello.key_exchange_modes, [tls.KeyExchangeMode.PSK_DHE_KE]) <25> self.assertEqual( <26> hello.key_share, <27> [ <28> ( <29> tls.Group.SECP256R1, <30> binascii.unhexlify( <31> "048842315c437bb0ce2929c816fee4e942ec5cb6db6a6b9bf622680188ebb0d4" <32> "b652e69033f71686aa01cbc79155866e264c9f33f45aa16b0dfa10a222e3a66</s>
===========below chunk 0=========== # module: tests.test_tls class TlsTest(TestCase): def test_pull_client_hello_with_alpn(self): # offset: 1 "22" ), ) ], ) self.assertEqual(hello.server_name, "cloudflare-quic.com") self.assertEqual( hello.signature_algorithms, [ tls.SignatureAlgorithm.ECDSA_SECP256R1_SHA256, tls.SignatureAlgorithm.ECDSA_SECP384R1_SHA384, tls.SignatureAlgorithm.ECDSA_SECP521R1_SHA512, tls.SignatureAlgorithm.ED25519, tls.SignatureAlgorithm.ED448, tls.SignatureAlgorithm.RSA_PSS_PSS_SHA256, tls.SignatureAlgorithm.RSA_PSS_PSS_SHA384, tls.SignatureAlgorithm.RSA_PSS_PSS_SHA512, tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA256, tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA384, tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA512, tls.SignatureAlgorithm.RSA_PKCS1_SHA256, tls.SignatureAlgorithm.RSA_PKCS1_SHA384, tls.SignatureAlgorithm.RSA_PKCS1_SHA512, ], ) self.assertEqual( hello.supported_groups, [ tls.Group.SECP256R1, tls.Group.X25519, tls.Group.SECP384R1, tls.Group.SECP521R1, ], ) self.assertEqual(hello.supported_versions, [tls.TLS_VERSION_1_3]) # serialize buf = Buffer(1000) push_client_hello(buf, hello) self.assertEqual(len(buf.data), len(load("tls_client_hello_with_alpn.bin"))) ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.buffer.Buffer eof() -> bool at: aioquic.tls TLS_VERSION_1_3 = 0x0304 CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeyExchangeMode(x: Union[str, bytes, bytearray], base: int) KeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_client_hello(buf: Buffer) -> ClientHello push_client_hello(buf: Buffer, hello: ClientHello) -> None at: aioquic.tls.ClientHello random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] alpn_protocols: Optional[List[str]] = None early_data: bool = False key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None ===========unchanged ref 1=========== supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.utils load(name) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: push_uint8(buf, HandshakeType.CLIENT_HELLO) with push_block(buf, 3): push_uint16(buf, TLS_VERSION_1_2) push_bytes(buf, hello.random) push_opaque(buf, 1, hello.session_id) push_list(buf, 2, push_cipher_suite, hello.cipher_suites) push_list(buf, 1, push_compression_method, hello.compression_methods) # extensions with push_block(buf, 2): with push_extension(buf, ExtensionType.KEY_SHARE): push_list(buf, 2, push_key_share, hello.key_share) with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): push_list(buf, 1, push_uint16, hello.supported_versions) with push_extension(buf, ExtensionType.SIGNATURE_ALGORITHMS): push_list(buf, 2, push_signature_algorithm, hello.signature_algorithms) with push_extension(buf, ExtensionType.SUPPORTED_GROUPS): push_list(buf, 2, push_group, hello.supported_groups) with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): push_list(buf, 1, push_key_exchange_mode, hello.key_exchange_modes) if hello.server_name is not None: with push_extension(buf, ExtensionType.SERVER_NAME): with push_block(buf, 2): push_uint8(buf, 0) push_opaque(buf, 2, hello.server_name.encode("ascii")) if hello.alpn_protocols is not None: with push_extension(buf, ExtensionType.ALPN): push_list(buf, 2, push_alpn_protocol, hello.alpn_protocols) for extension_type, extension_value in hello.other</s> ===========changed ref 1=========== # module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: # offset: 1 <s>, push_alpn_protocol, hello.alpn_protocols) for extension_type, extension_value in hello.other_extensions: with push_extension(buf, extension_type): push_bytes(buf, extension_value) + if hello.early_data: + with push_extension(buf, ExtensionType.EARLY_DATA): + pass + # pre_shared_key MUST be last if hello.pre_shared_key is not None: with push_extension(buf, ExtensionType.PRE_SHARED_KEY): push_list( buf, 2, push_psk_identity, hello.pre_shared_key.identities ) push_list(buf, 2, push_psk_binder, hello.pre_shared_key.binders)
tests.test_tls/TlsTest.test_pull_client_hello_with_psk
Modified
aiortc~aioquic
594ffcc66ed15b41af4c19a6de82426f4ff3d59d
[tls] parse ClientHello.early_data
<3>:<add> self.assertEqual(hello.early_data, True)
# module: tests.test_tls class TlsTest(TestCase): def test_pull_client_hello_with_psk(self): <0> buf = Buffer(data=load("tls_client_hello_with_psk.bin")) <1> hello = pull_client_hello(buf) <2> <3> self.assertEqual( <4> hello.pre_shared_key, <5> tls.OfferedPsks( <6> identities=[ <7> ( <8> binascii.unhexlify( <9> "fab3dc7d79f35ea53e9adf21150e601591a750b80cde0cd167fef6e0cdbc032a" <10> "c4161fc5c5b66679de49524bd5624c50d71ba3e650780a4bfe402d6a06a00525" <11> "0b5dc52085233b69d0dd13924cc5c713a396784ecafc59f5ea73c1585d79621b" <12> "8a94e4f2291b17427d5185abf4a994fca74ee7a7f993a950c71003fc7cf8" <13> ), <14> 2067156378, <15> ) <16> ], <17> binders=[ <18> binascii.unhexlify( <19> "1788ad43fdff37cfc628f24b6ce7c8c76180705380da17da32811b5bae4e78" <20> "d7aaaf65a9b713872f2bb28818ca1a6b01" <21> ) <22> ], <23> ), <24> ) <25> <26> self.assertTrue(buf.eof()) <27> <28> # serialize <29> buf = Buffer(1000) <30> push_client_hello(buf, hello) <31> self.assertEqual(buf.data, load("tls_client_hello_with_psk.bin")) <32>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.buffer.Buffer eof() -> bool at: aioquic.tls OfferedPsks(identities: List[PskIdentity], binders: List[bytes]) pull_client_hello(buf: Buffer) -> ClientHello at: aioquic.tls.OfferedPsks identities: List[PskIdentity] binders: List[bytes] at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.utils load(name) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: assert pull_uint8(buf) == HandshakeType.CLIENT_HELLO with pull_block(buf, 3): assert pull_uint16(buf) == TLS_VERSION_1_2 client_random = pull_bytes(buf, 32) hello = ClientHello( random=client_random, session_id=pull_opaque(buf, 1), cipher_suites=pull_list(buf, 2, pull_cipher_suite), compression_methods=pull_list(buf, 1, pull_compression_method), ) # extensions after_psk = False def pull_extension(buf: Buffer) -> None: # pre_shared_key MUST be last nonlocal after_psk assert not after_psk extension_type = pull_uint16(buf) extension_length = pull_uint16(buf) if extension_type == ExtensionType.KEY_SHARE: hello.key_share = pull_list(buf, 2, pull_key_share) elif extension_type == ExtensionType.SUPPORTED_VERSIONS: hello.supported_versions = pull_list(buf, 1, pull_uint16) elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS: hello.signature_algorithms = pull_list(buf, 2, pull_signature_algorithm) elif extension_type == ExtensionType.SUPPORTED_GROUPS: hello.supported_groups = pull_list(buf, 2, pull_group) elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES: hello.key_exchange_modes = pull_list(buf, 1, pull_key_exchange_mode) elif extension_type == ExtensionType.SERVER_NAME: with pull_block(buf, 2): assert pull_uint8(buf) == 0 hello.server_name = pull_opaque(buf, 2).decode("ascii") elif extension_type == ExtensionType.ALPN: hello.al</s> ===========changed ref 1=========== # module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: # offset: 1 <s>_opaque(buf, 2).decode("ascii") elif extension_type == ExtensionType.ALPN: hello.alpn_protocols = pull_list(buf, 2, pull_alpn_protocol) + elif extension_type == ExtensionType.EARLY_DATA: + hello.early_data = True elif extension_type == ExtensionType.PRE_SHARED_KEY: hello.pre_shared_key = OfferedPsks( identities=pull_list(buf, 2, pull_psk_identity), binders=pull_list(buf, 2, pull_psk_binder), ) after_psk = True else: hello.other_extensions.append( (extension_type, pull_bytes(buf, extension_length)) ) pull_list(buf, 2, pull_extension) return hello ===========changed ref 2=========== # module: tests.test_tls class TlsTest(TestCase): def test_pull_client_hello_with_alpn(self): buf = Buffer(data=load("tls_client_hello_with_alpn.bin")) hello = pull_client_hello(buf) self.assertTrue(buf.eof()) self.assertEqual( hello.random, binascii.unhexlify( "ed575c6fbd599c4dfaabd003dca6e860ccdb0e1782c1af02e57bf27cb6479b76" ), ) self.assertEqual(hello.session_id, b"") self.assertEqual( hello.cipher_suites, [ tls.CipherSuite.AES_128_GCM_SHA256, tls.CipherSuite.AES_256_GCM_SHA384, tls.CipherSuite.CHACHA20_POLY1305_SHA256, tls.CipherSuite.EMPTY_RENEGOTIATION_INFO_SCSV, ], ) self.assertEqual(hello.compression_methods, [tls.CompressionMethod.NULL]) # extensions self.assertEqual(hello.alpn_protocols, ["h3-19"]) + self.assertEqual(hello.early_data, False) self.assertEqual(hello.key_exchange_modes, [tls.KeyExchangeMode.PSK_DHE_KE]) self.assertEqual( hello.key_share, [ ( tls.Group.SECP256R1, binascii.unhexlify( "048842315c437bb0ce2929c816fee4e942ec5cb6db6a6b9bf622680188ebb0d4" "b652e69033f71686aa01cbc79155866e264c9f33f45aa16b0dfa10a222e3a669" "22" ), ) </s> ===========changed ref 3=========== # module: tests.test_tls class TlsTest(TestCase): def test_pull_client_hello_with_alpn(self): # offset: 1 <s>45aa16b0dfa10a222e3a669" "22" ), ) ], ) self.assertEqual(hello.server_name, "cloudflare-quic.com") self.assertEqual( hello.signature_algorithms, [ tls.SignatureAlgorithm.ECDSA_SECP256R1_SHA256, tls.SignatureAlgorithm.ECDSA_SECP384R1_SHA384, tls.SignatureAlgorithm.ECDSA_SECP521R1_SHA512, tls.SignatureAlgorithm.ED25519, tls.SignatureAlgorithm.ED448, tls.SignatureAlgorithm.RSA_PSS_PSS_SHA256, tls.SignatureAlgorithm.RSA_PSS_PSS_SHA384, tls.SignatureAlgorithm.RSA_PSS_PSS_SHA512, tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA256, tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA384, tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA512, tls.SignatureAlgorithm.RSA_PKCS1_SHA256, tls.SignatureAlgorithm.RSA_PKCS1_SHA384, tls.SignatureAlgorithm.RSA_PKCS1_SHA512, ], ) self.assertEqual( hello.supported_groups, [ tls.Group.SECP256R1, tls.Group.X25519, tls.Group.SECP384R1, tls.Group.SECP521R1, ], ) self.assertEqual(hello.supported_versions, [tls.TLS_VERSION_1_3]) # serialize buf = Buffer(1000) push_client_hello(buf, hello)
aioquic.tls/Context._client_send_hello
Modified
aiortc~aioquic
e6661530bef266f5122bd771f0481042a09bdb2d
[tls] check ticket date
<33>:<add> if self.session_ticket and self.session_ticket.is_valid: <del> if self.session_ticket:
# module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: <0> key_share: List[KeyShareEntry] = [] <1> supported_groups: List[Group] = [] <2> <3> if Group.SECP256R1 in self._supported_groups: <4> self._ec_private_key = ec.generate_private_key( <5> GROUP_TO_CURVE[Group.SECP256R1](), default_backend() <6> ) <7> key_share.append(encode_public_key(self._ec_private_key.public_key())) <8> supported_groups.append(Group.SECP256R1) <9> <10> if Group.X25519 in self._supported_groups: <11> self._x25519_private_key = x25519.X25519PrivateKey.generate() <12> key_share.append(encode_public_key(self._x25519_private_key.public_key())) <13> supported_groups.append(Group.X25519) <14> <15> assert len(key_share), "no key share entries" <16> <17> hello = ClientHello( <18> random=self.client_random, <19> session_id=self.session_id, <20> cipher_suites=self._cipher_suites, <21> compression_methods=self._compression_methods, <22> alpn_protocols=self.alpn_protocols, <23> key_exchange_modes=self._key_exchange_modes, <24> key_share=key_share, <25> server_name=self.server_name, <26> signature_algorithms=self._signature_algorithms, <27> supported_groups=supported_groups, <28> supported_versions=self._supported_versions, <29> other_extensions=self.handshake_extensions, <30> ) <31> <32> # PSK <33> if self.session_ticket: <34> self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) <35> self._key_schedule_psk.extract(self.session_ticket.resum</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: # offset: 1 binder_key = self._key_schedule_psk.derive_secret(b"res binder") binder_length = self._key_schedule_psk.algorithm.digest_size # serialize hello without binder tmp_buf = Buffer(capacity=1024) hello.pre_shared_key = OfferedPsks( identities=[ (self.session_ticket.ticket, self.session_ticket.obfuscated_age) ], binders=[bytes(binder_length)], ) push_client_hello(tmp_buf, hello) # calculate binder hash_offset = tmp_buf.tell() - binder_length - 3 self._key_schedule_psk.update_hash(tmp_buf.data_slice(0, hash_offset)) binder = self._key_schedule_psk.finished_verify_data(binder_key) hello.pre_shared_key.binders[0] = binder self._key_schedule_psk.update_hash( tmp_buf.data_slice(hash_offset, hash_offset + 3) + binder ) self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) self._key_schedule_proxy.extract(None) with push_message(self._key_schedule_proxy, output_buf): push_client_hello(output_buf, hello) self._set_state(State.CLIENT_EXPECT_SERVER_HELLO) ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.buffer.Buffer data_slice(start: int, end: int) -> bytes tell() -> int at: aioquic.tls Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeyShareEntry = Tuple[Group, bytes] OfferedPsks(identities: List[PskIdentity], binders: List[bytes]) ClientHello(random: bytes, session_id: bytes, cipher_suites: List[CipherSuite], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_exchange_modes: Optional[List[KeyExchangeMode]]=None, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list)) push_client_hello(buf: Buffer, hello: ClientHello) -> None KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) GROUP_TO_CURVE = { Group.SECP256R1: ec.SECP256R1, Group.SECP384R1: ec.SECP384R1, Group.SECP521R1: ec.SECP521R1, } encode_public_key(public_key: Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey]) -> KeyShareEntry at: aioquic.tls.ClientHello random: bytes session_id: bytes ===========unchanged ref 1=========== cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] alpn_protocols: Optional[List[str]] = None early_data: bool = False key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) at: aioquic.tls.Context.__init__ self.alpn_protocols: Optional[List[str]] = None self.handshake_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None ===========unchanged ref 2=========== self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None self.client_random = None self.client_random = os.urandom(32) self.session_id = None self.session_id = os.urandom(32) at: aioquic.tls.Context._build_session_ticket resumption_secret = hkdf_expand_label( algorithm=self.key_schedule.algorithm, secret=resumption_master_secret, label=b"resumption", hash_value=new_session_ticket.ticket_nonce, length=self.key_schedule.algorithm.digest_size, ) at: aioquic.tls.Context._server_handle_hello self.client_random = peer_hello.random self.session_id = peer_hello.session_id self._x25519_private_key = x25519.X25519PrivateKey.generate() self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) at: aioquic.tls.KeySchedule finished_verify_data(secret: bytes) -> bytes derive_secret(label: bytes) -> bytes extract(key_material: Optional[bytes]=None) -> None update_hash(data: bytes) -> None at: aioquic.tls.KeySchedule.__init__ self.algorithm = cipher_suite_hash(cipher_suite) at: aioquic.tls.KeyScheduleProxy extract(key_material: Optional[bytes]=None) -> None at: aioquic.tls.NewSessionTicket ticket_lifetime: int = 0 ticket_age_add: int = 0 ticket_nonce: bytes = b"" ticket: bytes = b"" max_early_data_size: Optional[int] = None
aioquic.tls/Context.__init__
Modified
aiortc~aioquic
d8370455a94a872c0778a242e1e040c0f6d079a4
[tls] add a property to check whether session resumption was used
# module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): <0> self.alpn_negotiated: Optional[str] = None <1> self.alpn_protocols: Optional[List[str]] = None <2> self.certificate: Optional[x509.Certificate] = None <3> self.certificate_private_key: Optional[ <4> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] <5> ] = None <6> self.handshake_extensions: List[Extension] = [] <7> self.is_client = is_client <8> self.key_schedule: Optional[KeySchedule] = None <9> self.received_extensions: List[Extension] = [] <10> self.session_ticket: Optional[SessionTicket] = None <11> self.server_name: Optional[str] = None <12> <13> # callbacks <14> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None <15> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None <16> self.update_traffic_key_cb: Callable[ <17> [Direction, Epoch, bytes], None <18> ] = lambda d, e, s: None <19> <20> self._cipher_suites = [ <21> CipherSuite.AES_256_GCM_SHA384, <22> CipherSuite.AES_128_GCM_SHA256, <23> CipherSuite.CHACHA20_POLY1305_SHA256, <24> ] <25> self._compression_methods = [CompressionMethod.NULL] <26> self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] <27> self._signature_algorithms = [ <28> SignatureAlgorithm.RSA_PSS_RSAE_SHA256, <29> SignatureAlgorithm.ECDSA_SECP256R1_SHA256, <30> SignatureAlgorithm.RSA_PKCS1_SHA256, <31> SignatureAlgorithm.RSA_PKCS1_SHA1,</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========unchanged ref 0=========== at: aioquic.tls TLS_VERSION_1_3 = 0x0304 Direction() Epoch() State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeyExchangeMode(x: Union[str, bytes, bytearray], base: int) KeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Extension = Tuple[int, bytes] KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None) SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol ===========unchanged ref 1=========== self.received_extensions = encrypted_extensions.other_extensions at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) self._session_resumed = True at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) self.client_random = peer_hello.random self.session_id = peer_hello.session_id self.received_extensions = peer_hello.other_extensions self.key_schedule = KeySchedule(cipher_suite) self._session_resumed = True self._x25519_private_key = x25519.X25519PrivateKey.generate() self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) at: aioquic.tls.Context._set_state self.state = state ===========unchanged ref 2=========== at: aioquic.tls.Context._setup_traffic_protection self._enc_key = key self._dec_key = key at: aioquic.tls.Context.handle_message self._receive_buffer += input_data self._receive_buffer = self._receive_buffer[message_length:] at: logging Logger(name: str, level: _Level=...) LoggerAdapter(logger: Logger, extra: Mapping[str, Any]) at: os urandom(size: int, /) -> bytes at: typing Callable = _CallableType(collections.abc.Callable, 2) List = _alias(list, 1, inst=False, name='List')
aioquic.tls/Context._client_handle_hello
Modified
aiortc~aioquic
d8370455a94a872c0778a242e1e040c0f6d079a4
[tls] add a property to check whether session resumption was used
<15>:<add> self._session_resumed = True
# module: aioquic.tls class Context: def _client_handle_hello(self, input_buf: Buffer, output_buf: Buffer) -> None: <0> peer_hello = pull_server_hello(input_buf) <1> <2> assert peer_hello.cipher_suite in self._cipher_suites <3> assert peer_hello.compression_method in self._compression_methods <4> assert peer_hello.supported_version in self._supported_versions <5> <6> # select key schedule <7> if peer_hello.pre_shared_key is not None: <8> if ( <9> self._key_schedule_psk is None <10> or peer_hello.pre_shared_key != 0 <11> or peer_hello.cipher_suite != self._key_schedule_psk.cipher_suite <12> ): <13> raise AlertIllegalParameter <14> self.key_schedule = self._key_schedule_psk <15> else: <16> self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) <17> <18> # perform key exchange <19> peer_public_key = decode_public_key(peer_hello.key_share) <20> shared_key: Optional[bytes] = None <21> if ( <22> isinstance(peer_public_key, x25519.X25519PublicKey) <23> and self._x25519_private_key is not None <24> ): <25> shared_key = self._x25519_private_key.exchange(peer_public_key) <26> elif ( <27> isinstance(peer_public_key, ec.EllipticCurvePublicKey) <28> and self._ec_private_key is not None <29> and self._ec_private_key.public_key().curve.__class__ <30> == peer_public_key.curve.__class__ <31> ): <32> shared_key = self._ec_private_key.exchange(ec.ECDH(), peer_public_key) <33> assert shared_key is not None <34> <35> self.key_schedule.update_hash(input_buf.data) <36> self.key_schedule.</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def _client_handle_hello(self, input_buf: Buffer, output_buf: Buffer) -> None: # offset: 1 self._setup_traffic_protection( Direction.DECRYPT, Epoch.HANDSHAKE, b"s hs traffic" ) self._set_state(State.CLIENT_EXPECT_ENCRYPTED_EXTENSIONS) ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls AlertIllegalParameter(*args: object) State() push_client_hello(buf: Buffer, hello: ClientHello) -> None pull_server_hello(buf: Buffer) -> ServerHello KeyScheduleProxy(cipher_suites: List[CipherSuite]) decode_public_key(key_share: KeyShareEntry) -> Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey] push_message(key_schedule: Union[KeySchedule, KeyScheduleProxy], buf: Buffer) -> Generator at: aioquic.tls.ClientHello random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] alpn_protocols: Optional[List[str]] = None early_data: bool = False key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) at: aioquic.tls.Context _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self.key_schedule: Optional[KeySchedule] = None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] ===========unchanged ref 1=========== self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._session_resumed = False self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() hello = ClientHello( random=self.client_random, session_id=self.session_id, cipher_suites=self._cipher_suites, compression_methods=self._compression_methods, alpn_protocols=self.alpn_protocols, key_exchange_modes=self._key_exchange_modes, key_share=key_share, server_name=self.server_name, signature_algorithms=self._signature_algorithms, supported_groups=supported_groups, supported_versions=self._supported_versions, other_extensions=self.handshake_extensions, ) self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) self._session_resumed = True self._x25519_private_key = x25519.X25519PrivateKey.generate() self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) ===========unchanged ref 2=========== at: aioquic.tls.KeySchedule.__init__ self.cipher_suite = cipher_suite at: aioquic.tls.KeyScheduleProxy extract(key_material: Optional[bytes]=None) -> None select(cipher_suite: CipherSuite) -> KeySchedule at: aioquic.tls.ServerHello random: bytes session_id: bytes cipher_suite: CipherSuite compression_method: CompressionMethod key_share: Optional[KeyShareEntry] = None pre_shared_key: Optional[int] = None supported_version: Optional[int] = None ===========changed ref 0=========== # module: aioquic.tls class Context: + @property + def session_resumed(self) -> bool: + """ + Returns True if session resumption was successfully used. + """ + return self._session_resumed + ===========changed ref 1=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.is_client = is_client self.key_schedule: Optional[KeySchedule] = None self.received_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None # callbacks self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, bytes], None ] = lambda d, e, s: None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION</s>
tests.test_tls/ContextTest.test_session_ticket
Modified
aiortc~aioquic
d8370455a94a872c0778a242e1e040c0f6d079a4
[tls] add a property to check whether session resumption was used
<23>:<add> <add> # check session resumption was not used <add> self.assertFalse(client.session_resumed) <add> self.assertFalse(server.session_resumed)
# module: tests.test_tls class ContextTest(TestCase): def test_session_ticket(self): <0> client_tickets = [] <1> server_tickets = [] <2> <3> def client_new_ticket(ticket): <4> client_tickets.append(ticket) <5> <6> def server_get_ticket(label): <7> for t in server_tickets: <8> if t.ticket == label: <9> return t <10> return None <11> <12> def server_new_ticket(ticket): <13> server_tickets.append(ticket) <14> <15> def first_handshake(): <16> client = self.create_client() <17> client.new_session_ticket_cb = client_new_ticket <18> <19> server = self.create_server() <20> server.new_session_ticket_cb = server_new_ticket <21> <22> self._handshake(client, server, create_ticket=True) <23> <24> # check tickets match <25> self.assertEqual(len(client_tickets), 1) <26> self.assertEqual(len(server_tickets), 1) <27> self.assertEqual(client_tickets[0].ticket, server_tickets[0].ticket) <28> self.assertEqual( <29> client_tickets[0].resumption_secret, server_tickets[0].resumption_secret <30> ) <31> <32> def second_handshake(): <33> client = self.create_client() <34> client.session_ticket = client_tickets[0] <35> <36> server = self.create_server() <37> server.get_session_ticket_cb = server_get_ticket <38> <39> # send client hello with pre_shared_key <40> client_buf = create_buffers() <41> client.handle_message(b"", client_buf) <42> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <43> server_input = merge_buffers(client_buf) <44> self.assertEqual(len(server_input), 379) </s>
===========below chunk 0=========== # module: tests.test_tls class ContextTest(TestCase): def test_session_ticket(self): # offset: 1 # handle client hello # send server hello, encrypted extensions, finished server_buf = create_buffers() server.handle_message(server_input, server_buf) self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) client_input = merge_buffers(server_buf) self.assertEqual(len(client_input), 303) reset_buffers(server_buf) # handle server hello, encrypted extensions, certificate, certificate verify, finished # send finished client.handle_message(client_input, client_buf) self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) server_input = merge_buffers(client_buf) self.assertEqual(len(server_input), 52) reset_buffers(client_buf) # handle finished # send new_session_ticket server.handle_message(server_input, server_buf) self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) client_input = merge_buffers(server_buf) self.assertEqual(len(client_input), 0) reset_buffers(server_buf) # check keys match self.assertEqual(client._dec_key, server._enc_key) self.assertEqual(client._enc_key, server._dec_key) def second_handshake_bad_binder(): client = self.create_client() client.session_ticket = client_tickets[0] server = self.create_server() server.get_session_ticket_cb = server_get_ticket # send client hello with pre_shared_key client_buf = create_buffers() client.handle_message(b"", client_buf) self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) server_input = merge_buffers(</s> ===========below chunk 1=========== # module: tests.test_tls class ContextTest(TestCase): def test_session_ticket(self): # offset: 2 <s>assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) server_input = merge_buffers(client_buf) self.assertEqual(len(server_input), 379) reset_buffers(client_buf) # tamper with binder server_input = server_input[:-4] + bytes(4) # handle client hello # send server hello, encrypted extensions, finished server_buf = create_buffers() with self.assertRaises(tls.AlertHandshakeFailure) as cm: server.handle_message(server_input, server_buf) self.assertEqual(str(cm.exception), "PSK validation failed") def second_handshake_bad_pre_shared_key(): client = self.create_client() client.session_ticket = client_tickets[0] server = self.create_server() server.get_session_ticket_cb = server_get_ticket # send client hello with pre_shared_key client_buf = create_buffers() client.handle_message(b"", client_buf) self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) server_input = merge_buffers(client_buf) self.assertEqual(len(server_input), 379) reset_buffers(client_buf) # handle client hello # send server hello, encrypted extensions, finished server_buf = create_buffers() server.handle_message(server_input, server_buf) self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) # tamper with pre_share_key index buf = server_buf[tls.Epoch.INITIAL] buf._data[buf.tell()</s> ===========below chunk 2=========== # module: tests.test_tls class ContextTest(TestCase): def test_session_ticket(self): # offset: 3 <s>] = 1 client_input = merge_buffers(server_buf) self.assertEqual(len(client_input), 303) reset_buffers(server_buf) # handle server hello and bomb with self.assertRaises(tls.AlertIllegalParameter): client.handle_message(client_input, client_buf) first_handshake() second_handshake() second_handshake_bad_binder() second_handshake_bad_pre_shared_key() ===========unchanged ref 0=========== at: aioquic.buffer.Buffer tell() -> int at: aioquic.buffer.Buffer.__init__ self._data = bytearray(capacity) self._data = bytearray(data) at: aioquic.tls AlertHandshakeFailure(*args: object) Epoch() State() at: aioquic.tls.Context handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None at: aioquic.tls.Context.__init__ self.session_ticket: Optional[SessionTicket] = None self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.state = State.CLIENT_HANDSHAKE_START self.state = State.SERVER_EXPECT_CLIENT_HELLO at: aioquic.tls.Context._set_state self.state = state at: tests.test_tls create_buffers() merge_buffers(buffers) reset_buffers(buffers) at: tests.test_tls.ContextTest create_client() create_server() _handshake(client, server, create_ticket) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None assertFalse(expr: Any, msg: Any=...) -> None ===========unchanged ref 1=========== assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None at: unittest.case._AssertRaisesContext.__exit__ self.exception = exc_value.with_traceback(None) ===========changed ref 0=========== # module: aioquic.tls class Context: + @property + def session_resumed(self) -> bool: + """ + Returns True if session resumption was successfully used. + """ + return self._session_resumed +
examples.interop/test_session_resumption
Modified
aiortc~aioquic
d8370455a94a872c0778a242e1e040c0f6d079a4
[tls] add a property to check whether session resumption was used
<22>:<add> # check session was resumed <add> if connection.tls.session_resumed: <add> config.result |= Result.R <del> config.result |= Result.R
# module: examples.interop def test_session_resumption(config, **kwargs): <0> saved_ticket = None <1> <2> def session_ticket_handler(ticket): <3> nonlocal saved_ticket <4> saved_ticket = ticket <5> <6> # connect a first time, receive a ticket <7> async with aioquic.connect( <8> config.host, <9> config.port, <10> session_ticket_handler=session_ticket_handler, <11> **kwargs <12> ) as connection: <13> await connection.ping() <14> <15> # connect a second time, with the ticket <16> if saved_ticket is not None: <17> async with aioquic.connect( <18> config.host, config.port, session_ticket=saved_ticket, **kwargs <19> ) as connection: <20> await connection.ping() <21> <22> config.result |= Result.R <23>
===========unchanged ref 0=========== at: aioquic.client connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnection, None] at: aioquic.connection.QuicConnection supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20] ping() -> None ===========changed ref 0=========== # module: aioquic.tls class Context: + @property + def session_resumed(self) -> bool: + """ + Returns True if session resumption was successfully used. + """ + return self._session_resumed + ===========changed ref 1=========== # module: aioquic.tls class Context: def _client_handle_hello(self, input_buf: Buffer, output_buf: Buffer) -> None: peer_hello = pull_server_hello(input_buf) assert peer_hello.cipher_suite in self._cipher_suites assert peer_hello.compression_method in self._compression_methods assert peer_hello.supported_version in self._supported_versions # select key schedule if peer_hello.pre_shared_key is not None: if ( self._key_schedule_psk is None or peer_hello.pre_shared_key != 0 or peer_hello.cipher_suite != self._key_schedule_psk.cipher_suite ): raise AlertIllegalParameter self.key_schedule = self._key_schedule_psk + self._session_resumed = True else: self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) # perform key exchange peer_public_key = decode_public_key(peer_hello.key_share) shared_key: Optional[bytes] = None if ( isinstance(peer_public_key, x25519.X25519PublicKey) and self._x25519_private_key is not None ): shared_key = self._x25519_private_key.exchange(peer_public_key) elif ( isinstance(peer_public_key, ec.EllipticCurvePublicKey) and self._ec_private_key is not None and self._ec_private_key.public_key().curve.__class__ == peer_public_key.curve.__class__ ): shared_key = self._ec_private_key.exchange(ec.ECDH(), peer_public_key) assert shared_key is not None self.key_schedule.update_hash(input_buf.data) self.key_schedule.extract(shared_key) self._setup_traffic_protection( Direction.DECRYPT,</s> ===========changed ref 2=========== # module: aioquic.tls class Context: def _client_handle_hello(self, input_buf: Buffer, output_buf: Buffer) -> None: # offset: 1 <s>.key_schedule.extract(shared_key) self._setup_traffic_protection( Direction.DECRYPT, Epoch.HANDSHAKE, b"s hs traffic" ) self._set_state(State.CLIENT_EXPECT_ENCRYPTED_EXTENSIONS) ===========changed ref 3=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.is_client = is_client self.key_schedule: Optional[KeySchedule] = None self.received_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None # callbacks self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, bytes], None ] = lambda d, e, s: None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION</s> ===========changed ref 4=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 <s> ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" + self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO
aioquic.tls/Context.__init__
Modified
aiortc~aioquic
2d2383a3178e5cafb0728176caca784b1410e3bd
[tls] generate random ticket_age_add
<7>:<del> self.is_client = is_client <20>:<add> # supported parameters
# module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): <0> self.alpn_negotiated: Optional[str] = None <1> self.alpn_protocols: Optional[List[str]] = None <2> self.certificate: Optional[x509.Certificate] = None <3> self.certificate_private_key: Optional[ <4> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] <5> ] = None <6> self.handshake_extensions: List[Extension] = [] <7> self.is_client = is_client <8> self.key_schedule: Optional[KeySchedule] = None <9> self.received_extensions: List[Extension] = [] <10> self.session_ticket: Optional[SessionTicket] = None <11> self.server_name: Optional[str] = None <12> <13> # callbacks <14> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None <15> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None <16> self.update_traffic_key_cb: Callable[ <17> [Direction, Epoch, bytes], None <18> ] = lambda d, e, s: None <19> <20> self._cipher_suites = [ <21> CipherSuite.AES_256_GCM_SHA384, <22> CipherSuite.AES_128_GCM_SHA256, <23> CipherSuite.CHACHA20_POLY1305_SHA256, <24> ] <25> self._compression_methods = [CompressionMethod.NULL] <26> self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] <27> self._signature_algorithms = [ <28> SignatureAlgorithm.RSA_PSS_RSAE_SHA256, <29> SignatureAlgorithm.ECDSA_SECP256R1_SHA256, <30> SignatureAlgorithm.RSA_PKCS1_SHA256, <31> SignatureAlgorithm.RSA_PKCS1_SHA1,</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========unchanged ref 0=========== at: aioquic.tls TLS_VERSION_1_3 = 0x0304 Direction() Epoch() State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeyExchangeMode(x: Union[str, bytes, bytearray], base: int) KeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Extension = Tuple[int, bytes] KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None) SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol ===========unchanged ref 1=========== self.received_extensions = encrypted_extensions.other_extensions at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) self._session_resumed = True at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) self.client_random = peer_hello.random self.session_id = peer_hello.session_id self.received_extensions = peer_hello.other_extensions self.key_schedule = KeySchedule(cipher_suite) self._session_resumed = True self._x25519_private_key = x25519.X25519PrivateKey.generate() self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) at: aioquic.tls.Context._set_state self.state = state ===========unchanged ref 2=========== at: aioquic.tls.Context._setup_traffic_protection self._enc_key = key self._dec_key = key at: aioquic.tls.Context.handle_message self._receive_buffer += input_data self._receive_buffer = self._receive_buffer[message_length:] at: logging Logger(name: str, level: _Level=...) LoggerAdapter(logger: Logger, extra: Mapping[str, Any]) at: os urandom(size: int, /) -> bytes at: typing Callable = _CallableType(collections.abc.Callable, 2) List = _alias(list, 1, inst=False, name='List')
aioquic.tls/Context._server_handle_finished
Modified
aiortc~aioquic
2d2383a3178e5cafb0728176caca784b1410e3bd
[tls] generate random ticket_age_add
<19>:<add> ticket_age_add=struct.unpack("I", os.urandom(4))[0], <del> ticket_age_add=0,
# module: aioquic.tls class Context: def _server_handle_finished(self, input_buf: Buffer, output_buf: Buffer) -> None: <0> finished = pull_finished(input_buf) <1> <2> # check verify data <3> expected_verify_data = self.key_schedule.finished_verify_data(self._dec_key) <4> assert finished.verify_data == expected_verify_data <5> <6> # commit traffic key <7> self._dec_key = self._next_dec_key <8> self._next_dec_key = None <9> self.update_traffic_key_cb(Direction.DECRYPT, Epoch.ONE_RTT, self._dec_key) <10> <11> self.key_schedule.update_hash(input_buf.data) <12> <13> self._set_state(State.SERVER_POST_HANDSHAKE) <14> <15> # create a new session ticket <16> if self.new_session_ticket_cb is not None: <17> new_session_ticket = NewSessionTicket( <18> ticket_lifetime=86400, <19> ticket_age_add=0, <20> ticket_nonce=b"", <21> ticket=os.urandom(64), <22> ) <23> <24> # notify application <25> ticket = self._build_session_ticket(new_session_ticket) <26> self.new_session_ticket_cb(ticket) <27> <28> # send messsage <29> push_new_session_ticket(output_buf, new_session_ticket) <30>
===========unchanged ref 0=========== at: _struct unpack(format, buffer, /) at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls Direction() Epoch() State() NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b"", ticket: bytes=b"", max_early_data_size: Optional[int]=None) pull_finished(buf: Buffer) -> Finished at: aioquic.tls.Context _build_session_ticket(new_session_ticket: NewSessionTicket) -> SessionTicket _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self.key_schedule: Optional[KeySchedule] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, bytes], None ] = lambda d, e, s: None self._dec_key: Optional[bytes] = None at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) self._next_dec_key = self.key_schedule.derive_secret(b"c ap traffic") at: aioquic.tls.Context._setup_traffic_protection self._dec_key = key at: aioquic.tls.Finished verify_data: bytes = b"" at: aioquic.tls.KeySchedule finished_verify_data(secret: bytes) -> bytes update_hash(data: bytes) -> None ===========unchanged ref 1=========== at: aioquic.tls.NewSessionTicket ticket_lifetime: int = 0 ticket_age_add: int = 0 ticket_nonce: bytes = b"" ticket: bytes = b"" max_early_data_size: Optional[int] = None at: os urandom(size: int, /) -> bytes ===========changed ref 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] - self.is_client = is_client self.key_schedule: Optional[KeySchedule] = None self.received_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None # callbacks self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, bytes], None ] = lambda d, e, s: None + # supported parameters self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported</s> ===========changed ref 1=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 <s>1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] + # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO
aioquic.connection/QuicConnectionError.__str__
Modified
aiortc~aioquic
b25651bb95c31c0c5fe50ec23854826f30391016
[connection] validate frame types against epoch
<0>:<add> s = "Error: %d, reason: %s" % (self.error_code, self.reason_phrase) <del> return "Error: %d, reason: %s" % (self.error_code, self.reason_phrase) <1>:<add> if self.frame_type is not None: <add> s += ", frame_type: %s" % self.frame_type <add> return s
# module: aioquic.connection class QuicConnectionError(Exception): def __str__(self) -> str: <0> return "Error: %d, reason: %s" % (self.error_code, self.reason_phrase) <1>
===========changed ref 0=========== # module: aioquic.connection + def EPOCHS(shortcut: str) -> FrozenSet[tls.Epoch]: + return frozenset(EPOCH_SHORTCUTS[i] for i in shortcut) + ===========changed ref 1=========== # module: aioquic.connection logger = logging.getLogger("quic") + EPOCH_SHORTCUTS = { + "I": tls.Epoch.INITIAL, + "Z": tls.Epoch.ZERO_RTT, + "H": tls.Epoch.HANDSHAKE, + "O": tls.Epoch.ONE_RTT, + } PACKET_MAX_SIZE = 1280 SECRETS_LABELS = [ [ None, "QUIC_CLIENT_EARLY_TRAFFIC_SECRET", "QUIC_CLIENT_HANDSHAKE_TRAFFIC_SECRET", "QUIC_CLIENT_TRAFFIC_SECRET_0", ], [ None, None, "QUIC_SERVER_HANDSHAKE_TRAFFIC_SECRET", "QUIC_SERVER_TRAFFIC_SECRET_0", ], ] STREAM_FLAGS = 0x07 NetworkAddress = Any
aioquic.connection/QuicConnection.__init__
Modified
aiortc~aioquic
b25651bb95c31c0c5fe50ec23854826f30391016
[connection] validate frame types against epoch
<s>[List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, session_ticket: Optional[tls.SessionTicket] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: <0> if is_client: <1> assert ( <2> original_connection_id is None <3> ), "Cannot set original_connection_id for a client" <4> else: <5> assert certificate is not None, "SSL certificate is required for a server" <6> assert private_key is not None, "SSL private key is required for a server" <7> <8> self.alpn_protocols = alpn_protocols <9> self.certificate = certificate <10> self.is_client = is_client <11> self.host_cid = os.urandom(8) <12> self.peer_cid = os.urandom(8) <13> self.peer_cid_set = False <14> self.peer_token = b"" <15> self.private_key = private_key <16> self.secrets_log_file = secrets_log_file <17> self.server_name = server_name <18> self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} <19> <20> # counters for debugging <21> self._stateless_retry_count = 0 <22> self._version_negotiation_count = 0 <23> <24> self._loop = asyncio.get_event_loop() <25> self.__close: Optional[Dict] = None <26> self.__connected = asyncio.Event() <27> self.__epoch = tls.Epoch.INITIAL <28> self._local_idle_timeout = 60000 # milliseconds <29> self._local_max_data = 1048576 <30> self._local_max_data_used = 0 <31> self._local_max_stream_data</s>
===========below chunk 0=========== <s> = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, session_ticket: Optional[tls.SessionTicket] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 1 self._local_max_stream_data_bidi_remote = 1048576 self._local_max_stream_data_uni = 1048576 self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} ) self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._ping_packet_number: Optional[int] = None self._ping_waiter: Optional[asyncio.Future[None]] = None self._remote_idle_timeout = 0 # milliseconds self._remote_max_data = 0 self._remote_max_data_used = 0 self._remote_max_stream_data_bidi_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._session_ticket = session_ticket self._spin_bit = False self._spin_bit_peer = False self._spin_highest_pn = 0 self.__send_pending_task: Optional[asyncio.Handle] = None self.__state = QuicConnectionState.FIRSTFLIGHT self._transport: Optional[asyncio.DatagramTransport] = None</s> ===========below chunk 1=========== <s> = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, session_ticket: Optional[tls.SessionTicket] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 2 <s> self.__state = QuicConnectionState.FIRSTFLIGHT self._transport: Optional[asyncio.DatagramTransport] = None self._version: Optional[int] = None # callbacks self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None # frame handlers self.__frame_handlers = [ self._handle_padding_frame, self._handle_padding_frame, self._handle_ack_frame, self._handle_ack_frame, self._handle_reset_stream_frame, self._handle_stop_sending_frame, self._handle_crypto_frame, self._handle_new_token_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_stream_frame, self._handle_max_data_frame, self._handle_max_stream_data_frame, self._handle_max_streams_bidi_frame, self._handle_max_</s> ===========below chunk 2=========== <s> = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, session_ticket: Optional[tls.SessionTicket] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 3 <s>uni_frame, self._handle_data_blocked_frame, self._handle_stream_data_blocked_frame, self._handle_streams_blocked_frame, self._handle_streams_blocked_frame, self._handle_new_connection_id_frame, self._handle_retire_connection_id_frame, self._handle_path_challenge_frame, self._handle_path_response_frame, self._handle_connection_close_frame, self._handle_connection_close_frame, ] ===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.connection logger = logging.getLogger("quic") EPOCHS(shortcut: str) -> FrozenSet[tls.Epoch] QuicConnectionAdapter(logger: Logger, extra: Mapping[str, Any]) QuicConnectionState() QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None) at: aioquic.connection.QuicConnection _handle_ack_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_crypto_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_max_data_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_new_token_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_padding_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_reset_stream_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_stop_sending_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None _handle_stream_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None at: aioquic.connection.QuicConnection._handle_ack_frame self._ping_waiter = None self._ping_packet_number = None at: aioquic.connection.QuicConnection._handle_crypto_frame self.__epoch = tls.Epoch.ONE_RTT self.__epoch = tls.Epoch.HANDSHAKE
aioquic.connection/QuicConnection._payload_received
Modified
aiortc~aioquic
b25651bb95c31c0c5fe50ec23854826f30391016
[connection] validate frame types against epoch
<6>:<add> <add> # check frame type is known <add> try: <add> frame_handler, frame_epochs = self.__frame_handlers[frame_type] <add> except IndexError: <add> raise QuicConnectionError( <add> error_code=QuicErrorCode.PROTOCOL_VIOLATION, <add> frame_type=frame_type, <add> reason_phrase="Unknown frame type", <add> ) <add> <add> # check frame is allowed for the epoch <add> if context.epoch not in frame_epochs: <add> raise QuicConnectionError( <add> error_code=QuicErrorCode.PROTOCOL_VIOLATION, <add> frame_type=frame_type, <add> reason_phrase="Unexpected frame type", <add> ) <add> <add> # handle the frame <add> try: <add> frame_handler(context, frame_type, buf) <add> except BufferReadError: <add> raise QuicConnectionError( <add> error_code=QuicErrorCode.FRAME_ENCODING_ERROR, <add> frame_type=frame_type, <add> reason_phrase
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _payload_received( self, context: QuicReceiveContext, plain: bytes ) -> Tuple[bool, bool]: <0> buf = Buffer(data=plain) <1> <2> is_ack_only = True <3> is_probing = None <4> while not buf.eof(): <5> frame_type = pull_uint_var(buf) <6> if frame_type not in [ <7> QuicFrameType.ACK, <8> QuicFrameType.ACK_ECN, <9> QuicFrameType.PADDING, <10> ]: <11> is_ack_only = False <12> <13> if frame_type not in [ <14> QuicFrameType.PATH_CHALLENGE, <15> QuicFrameType.PATH_RESPONSE, <16> QuicFrameType.PADDING, <17> QuicFrameType.NEW_CONNECTION_ID, <18> ]: <19> is_probing = False <20> elif is_probing is None: <21> is_probing = True <22> <23> if frame_type < len(self.__frame_handlers): <24> try: <25> self.__frame_handlers[frame_type](context, frame_type, buf) <26> except BufferReadError: <27> raise QuicConnectionError( <28> error_code=QuicErrorCode.FRAME_ENCODING_ERROR, <29> frame_type=frame_type, <30> reason_phrase="Failed to parse frame", <31> ) <32> else: <33> raise QuicConnectionError( <34> error_code=QuicErrorCode.PROTOCOL_VIOLATION, <35> frame_type=frame_type, <36> reason_phrase="Unexpected frame type", <37> ) <38> <39> self._push_crypto_data() <40> <41> return is_ack_only, bool(is_probing) <42>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.buffer.Buffer eof() -> bool at: aioquic.connection QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) QuicReceiveContext(epoch: tls.Epoch, network_path: QuicNetworkPath) at: aioquic.connection.QuicConnection _assert_stream_can_receive(frame_type: int, stream_id: int) -> None _get_or_create_stream(frame_type: int, stream_id: int) -> QuicStream ===========unchanged ref 1=========== at: aioquic.connection.QuicConnection.__init__ self.__frame_handlers = [ (self._handle_padding_frame, EPOCHS("IZHO")), (self._handle_padding_frame, EPOCHS("ZO")), (self._handle_ack_frame, EPOCHS("IHO")), (self._handle_ack_frame, EPOCHS("IHO")), (self._handle_reset_stream_frame, EPOCHS("ZO")), (self._handle_stop_sending_frame, EPOCHS("ZO")), (self._handle_crypto_frame, EPOCHS("IHO")), (self._handle_new_token_frame, EPOCHS("O")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_max_data_frame, EPOCHS("ZO")), (self._handle_max_stream_data_frame, EPOCHS("ZO")), (self._handle_max_streams_bidi_frame, EPOCHS("ZO")), (self._handle_max_streams_uni_frame, EPOCHS("ZO")), (self._handle_data_blocked_frame, EPOCHS("ZO")), (self._handle_stream_data_blocked_frame, EPOCHS("ZO")), (self._handle_streams_blocked_frame, EPOCHS("ZO")), (self._handle_streams_blocked_frame, EPOCHS("ZO")),</s> ===========unchanged ref 2=========== at: aioquic.connection.QuicConnection._handle_stream_data_blocked_frame stream_id = pull_uint_var(buf) at: aioquic.connection.QuicReceiveContext epoch: tls.Epoch network_path: QuicNetworkPath at: aioquic.packet QuicErrorCode(x: Union[str, bytes, bytearray], base: int) QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_uint_var(buf: Buffer) -> int at: typing Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') ===========changed ref 0=========== # module: aioquic.connection + def EPOCHS(shortcut: str) -> FrozenSet[tls.Epoch]: + return frozenset(EPOCH_SHORTCUTS[i] for i in shortcut) + ===========changed ref 1=========== # module: aioquic.connection class QuicConnectionError(Exception): def __str__(self) -> str: + s = "Error: %d, reason: %s" % (self.error_code, self.reason_phrase) - return "Error: %d, reason: %s" % (self.error_code, self.reason_phrase) + if self.frame_type is not None: + s += ", frame_type: %s" % self.frame_type + return s ===========changed ref 2=========== # module: aioquic.connection logger = logging.getLogger("quic") + EPOCH_SHORTCUTS = { + "I": tls.Epoch.INITIAL, + "Z": tls.Epoch.ZERO_RTT, + "H": tls.Epoch.HANDSHAKE, + "O": tls.Epoch.ONE_RTT, + } PACKET_MAX_SIZE = 1280 SECRETS_LABELS = [ [ None, "QUIC_CLIENT_EARLY_TRAFFIC_SECRET", "QUIC_CLIENT_HANDSHAKE_TRAFFIC_SECRET", "QUIC_CLIENT_TRAFFIC_SECRET_0", ], [ None, None, "QUIC_SERVER_HANDSHAKE_TRAFFIC_SECRET", "QUIC_SERVER_TRAFFIC_SECRET_0", ], ] STREAM_FLAGS = 0x07 NetworkAddress = Any ===========changed ref 3=========== <s>[List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, session_ticket: Optional[tls.SessionTicket] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: if is_client: assert ( original_connection_id is None ), "Cannot set original_connection_id for a client" else: assert certificate is not None, "SSL certificate is required for a server" assert private_key is not None, "SSL private key is required for a server" self.alpn_protocols = alpn_protocols self.certificate = certificate self.is_client = is_client self.host_cid = os.urandom(8) self.peer_cid = os.urandom(8) self.peer_cid_set = False self.peer_token = b"" self.private_key = private_key self.secrets_log_file = secrets_log_file self.server_name = server_name self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} # counters for debugging self._stateless_retry_count = 0 self._version_negotiation_count = 0 self._loop = asyncio.get_event_loop() self.__close: Optional[Dict] = None self.__connected = asyncio.Event() self.__epoch = tls.Epoch.INITIAL self._local_idle_timeout = 60000 # milliseconds self._local_max_data = 1048576 self._local_max_data_used = 0 self._local_max_stream_data_bidi_local = 1048576 self._local_max_stream_data_bidi_remote = 1048576 self</s>
tests.test_connection/client_receive_context
Modified
aiortc~aioquic
b25651bb95c31c0c5fe50ec23854826f30391016
[connection] validate frame types against epoch
<0>:<del> return QuicReceiveContext( <1>:<del> epoch=tls.Epoch.ONE_RTT, network_path=client._network_paths[0] <2>:<del> ) <3>:<add> return QuicReceiveContext(epoch=epoch, network_path=client._network_paths[0])
# module: tests.test_connection + def client_receive_context(client, epoch=tls.Epoch.ONE_RTT): - def client_receive_context(client): <0> return QuicReceiveContext( <1> epoch=tls.Epoch.ONE_RTT, network_path=client._network_paths[0] <2> ) <3>
===========unchanged ref 0=========== at: aioquic.connection QuicReceiveContext(epoch: tls.Epoch, network_path: QuicNetworkPath) at: aioquic.connection.QuicConnection.__init__ self._network_paths: List[QuicNetworkPath] = [] at: aioquic.connection.QuicConnection.connect self._network_paths = [QuicNetworkPath(addr, is_validated=True)] at: aioquic.connection.QuicConnection.datagram_received self._network_paths = [network_path] at: aioquic.connection.QuicReceiveContext epoch: tls.Epoch network_path: QuicNetworkPath at: aioquic.tls Epoch() ===========changed ref 0=========== # module: aioquic.connection + def EPOCHS(shortcut: str) -> FrozenSet[tls.Epoch]: + return frozenset(EPOCH_SHORTCUTS[i] for i in shortcut) + ===========changed ref 1=========== # module: aioquic.connection class QuicConnectionError(Exception): def __str__(self) -> str: + s = "Error: %d, reason: %s" % (self.error_code, self.reason_phrase) - return "Error: %d, reason: %s" % (self.error_code, self.reason_phrase) + if self.frame_type is not None: + s += ", frame_type: %s" % self.frame_type + return s ===========changed ref 2=========== # module: aioquic.connection logger = logging.getLogger("quic") + EPOCH_SHORTCUTS = { + "I": tls.Epoch.INITIAL, + "Z": tls.Epoch.ZERO_RTT, + "H": tls.Epoch.HANDSHAKE, + "O": tls.Epoch.ONE_RTT, + } PACKET_MAX_SIZE = 1280 SECRETS_LABELS = [ [ None, "QUIC_CLIENT_EARLY_TRAFFIC_SECRET", "QUIC_CLIENT_HANDSHAKE_TRAFFIC_SECRET", "QUIC_CLIENT_TRAFFIC_SECRET_0", ], [ None, None, "QUIC_SERVER_HANDSHAKE_TRAFFIC_SECRET", "QUIC_SERVER_TRAFFIC_SECRET_0", ], ] STREAM_FLAGS = 0x07 NetworkAddress = Any ===========changed ref 3=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _payload_received( self, context: QuicReceiveContext, plain: bytes ) -> Tuple[bool, bool]: buf = Buffer(data=plain) is_ack_only = True is_probing = None while not buf.eof(): frame_type = pull_uint_var(buf) + + # check frame type is known + try: + frame_handler, frame_epochs = self.__frame_handlers[frame_type] + except IndexError: + raise QuicConnectionError( + error_code=QuicErrorCode.PROTOCOL_VIOLATION, + frame_type=frame_type, + reason_phrase="Unknown frame type", + ) + + # check frame is allowed for the epoch + if context.epoch not in frame_epochs: + raise QuicConnectionError( + error_code=QuicErrorCode.PROTOCOL_VIOLATION, + frame_type=frame_type, + reason_phrase="Unexpected frame type", + ) + + # handle the frame + try: + frame_handler(context, frame_type, buf) + except BufferReadError: + raise QuicConnectionError( + error_code=QuicErrorCode.FRAME_ENCODING_ERROR, + frame_type=frame_type, + reason_phrase="Failed to parse frame", + ) + + # update ACK only / probing flags if frame_type not in [ QuicFrameType.ACK, QuicFrameType.ACK_ECN, QuicFrameType.PADDING, ]: is_ack_only = False if frame_type not in [ QuicFrameType.PATH_CHALLENGE, QuicFrameType.PATH_RESPONSE, QuicFrameType.PADDING, QuicFrameType.NEW_CONNECTION_ID, ]: is_probing = False elif is_probing is None: </s> ===========changed ref 4=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _payload_received( self, context: QuicReceiveContext, plain: bytes ) -> Tuple[bool, bool]: # offset: 1 <s>NEW_CONNECTION_ID, ]: is_probing = False elif is_probing is None: is_probing = True - if frame_type < len(self.__frame_handlers): - try: - self.__frame_handlers[frame_type](context, frame_type, buf) - except BufferReadError: - raise QuicConnectionError( - error_code=QuicErrorCode.FRAME_ENCODING_ERROR, - frame_type=frame_type, - reason_phrase="Failed to parse frame", - ) - else: - raise QuicConnectionError( - error_code=QuicErrorCode.PROTOCOL_VIOLATION, - frame_type=frame_type, - reason_phrase="Unexpected frame type", - ) - self._push_crypto_data() return is_ack_only, bool(is_probing) ===========changed ref 5=========== <s>[List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, session_ticket: Optional[tls.SessionTicket] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: if is_client: assert ( original_connection_id is None ), "Cannot set original_connection_id for a client" else: assert certificate is not None, "SSL certificate is required for a server" assert private_key is not None, "SSL private key is required for a server" self.alpn_protocols = alpn_protocols self.certificate = certificate self.is_client = is_client self.host_cid = os.urandom(8) self.peer_cid = os.urandom(8) self.peer_cid_set = False self.peer_token = b"" self.private_key = private_key self.secrets_log_file = secrets_log_file self.server_name = server_name self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} # counters for debugging self._stateless_retry_count = 0 self._version_negotiation_count = 0 self._loop = asyncio.get_event_loop() self.__close: Optional[Dict] = None self.__connected = asyncio.Event() self.__epoch = tls.Epoch.INITIAL self._local_idle_timeout = 60000 # milliseconds self._local_max_data = 1048576 self._local_max_data_used = 0 self._local_max_stream_data_bidi_local = 1048576 self._local_max_stream_data_bidi_remote = 1048576 self</s>
tests.test_connection/QuicConnectionTest.test_handle_unknown_frame
Modified
aiortc~aioquic
b25651bb95c31c0c5fe50ec23854826f30391016
[connection] validate frame types against epoch
<16>:<add> self.assertEqual(cm.exception.reason_phrase, "Unknown frame type") <del> self.assertEqual(cm.exception.reason_phrase, "Unexpected frame type")
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_unknown_frame(self): <0> client = QuicConnection(is_client=True) <1> <2> server = QuicConnection( <3> is_client=False, <4> certificate=SERVER_CERTIFICATE, <5> private_key=SERVER_PRIVATE_KEY, <6> ) <7> <8> # perform handshake <9> client_transport, server_transport = create_transport(client, server) <10> <11> # client receives unknown frame <12> with self.assertRaises(QuicConnectionError) as cm: <13> client._payload_received(client_receive_context(client), b"\x1e") <14> self.assertEqual(cm.exception.error_code, QuicErrorCode.PROTOCOL_VIOLATION) <15> self.assertEqual(cm.exception.frame_type, 0x1E) <16> self.assertEqual(cm.exception.reason_phrase, "Unexpected frame type") <17>
===========unchanged ref 0=========== at: aioquic.connection QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) QuicConnection(*, is_client: bool=True, certificate: Any=None, private_key: Any=None, alpn_protocols: Optional[List[str]]=None, original_connection_id: Optional[bytes]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.connection.QuicConnection supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20] _payload_received(context: QuicReceiveContext, plain: bytes) -> Tuple[bool, bool] at: aioquic.packet QuicErrorCode(x: Union[str, bytes, bytearray], base: int) QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: tests.test_connection client_receive_context(client, epoch=tls.Epoch.ONE_RTT) create_transport(client, server) at: tests.test_connection.QuicConnectionTest.test_handle_unknown_frame client = QuicConnection(is_client=True) at: tests.utils SERVER_CERTIFICATE = x509.load_pem_x509_certificate( load("ssl_cert.pem"), backend=default_backend() ) SERVER_PRIVATE_KEY = serialization.load_pem_private_key( load("ssl_key.pem"), password=None, backend=default_backend() ) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str ===========unchanged ref 1=========== _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None at: unittest.case._AssertRaisesContext.__exit__ self.exception = exc_value.with_traceback(None) ===========changed ref 0=========== # module: tests.test_connection + def client_receive_context(client, epoch=tls.Epoch.ONE_RTT): - def client_receive_context(client): - return QuicReceiveContext( - epoch=tls.Epoch.ONE_RTT, network_path=client._network_paths[0] - ) + return QuicReceiveContext(epoch=epoch, network_path=client._network_paths[0]) ===========changed ref 1=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _payload_received( self, context: QuicReceiveContext, plain: bytes ) -> Tuple[bool, bool]: buf = Buffer(data=plain) is_ack_only = True is_probing = None while not buf.eof(): frame_type = pull_uint_var(buf) + + # check frame type is known + try: + frame_handler, frame_epochs = self.__frame_handlers[frame_type] + except IndexError: + raise QuicConnectionError( + error_code=QuicErrorCode.PROTOCOL_VIOLATION, + frame_type=frame_type, + reason_phrase="Unknown frame type", + ) + + # check frame is allowed for the epoch + if context.epoch not in frame_epochs: + raise QuicConnectionError( + error_code=QuicErrorCode.PROTOCOL_VIOLATION, + frame_type=frame_type, + reason_phrase="Unexpected frame type", + ) + + # handle the frame + try: + frame_handler(context, frame_type, buf) + except BufferReadError: + raise QuicConnectionError( + error_code=QuicErrorCode.FRAME_ENCODING_ERROR, + frame_type=frame_type, + reason_phrase="Failed to parse frame", + ) + + # update ACK only / probing flags if frame_type not in [ QuicFrameType.ACK, QuicFrameType.ACK_ECN, QuicFrameType.PADDING, ]: is_ack_only = False if frame_type not in [ QuicFrameType.PATH_CHALLENGE, QuicFrameType.PATH_RESPONSE, QuicFrameType.PADDING, QuicFrameType.NEW_CONNECTION_ID, ]: is_probing = False elif is_probing is None: </s> ===========changed ref 2=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _payload_received( self, context: QuicReceiveContext, plain: bytes ) -> Tuple[bool, bool]: # offset: 1 <s>NEW_CONNECTION_ID, ]: is_probing = False elif is_probing is None: is_probing = True - if frame_type < len(self.__frame_handlers): - try: - self.__frame_handlers[frame_type](context, frame_type, buf) - except BufferReadError: - raise QuicConnectionError( - error_code=QuicErrorCode.FRAME_ENCODING_ERROR, - frame_type=frame_type, - reason_phrase="Failed to parse frame", - ) - else: - raise QuicConnectionError( - error_code=QuicErrorCode.PROTOCOL_VIOLATION, - frame_type=frame_type, - reason_phrase="Unexpected frame type", - ) - self._push_crypto_data() return is_ack_only, bool(is_probing) ===========changed ref 3=========== # module: aioquic.connection + def EPOCHS(shortcut: str) -> FrozenSet[tls.Epoch]: + return frozenset(EPOCH_SHORTCUTS[i] for i in shortcut) + ===========changed ref 4=========== # module: aioquic.connection class QuicConnectionError(Exception): def __str__(self) -> str: + s = "Error: %d, reason: %s" % (self.error_code, self.reason_phrase) - return "Error: %d, reason: %s" % (self.error_code, self.reason_phrase) + if self.frame_type is not None: + s += ", frame_type: %s" % self.frame_type + return s ===========changed ref 5=========== # module: aioquic.connection logger = logging.getLogger("quic") + EPOCH_SHORTCUTS = { + "I": tls.Epoch.INITIAL, + "Z": tls.Epoch.ZERO_RTT, + "H": tls.Epoch.HANDSHAKE, + "O": tls.Epoch.ONE_RTT, + } PACKET_MAX_SIZE = 1280 SECRETS_LABELS = [ [ None, "QUIC_CLIENT_EARLY_TRAFFIC_SECRET", "QUIC_CLIENT_HANDSHAKE_TRAFFIC_SECRET", "QUIC_CLIENT_TRAFFIC_SECRET_0", ], [ None, None, "QUIC_SERVER_HANDSHAKE_TRAFFIC_SECRET", "QUIC_SERVER_TRAFFIC_SECRET_0", ], ] STREAM_FLAGS = 0x07 NetworkAddress = Any
aioquic.connection/QuicPacketSpace.__init__
Modified
aiortc~aioquic
dd6122cf531739c2c9f0885e990dc0ad008ce4f2
[connection] move crypto out of QuicPacketSpace
<1>:<add> self.ack_required = False <del> self.crypto = CryptoPair()
# module: aioquic.connection class QuicPacketSpace: def __init__(self) -> None: <0> self.ack_queue = RangeSet() <1> self.crypto = CryptoPair() <2>
===========unchanged ref 0=========== at: aioquic.rangeset RangeSet(ranges: Iterable[range]=[])
aioquic.connection/QuicConnection.request_key_update
Modified
aiortc~aioquic
dd6122cf531739c2c9f0885e990dc0ad008ce4f2
[connection] move crypto out of QuicPacketSpace
<4>:<add> self.cryptos[tls.Epoch.ONE_RTT].update_key() <del> self.spaces[tls.Epoch.ONE_RTT].crypto.update_key()
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def request_key_update(self) -> None: <0> """ <1> Request an update of the encryption keys. <2> """ <3> if self.__epoch == tls.Epoch.ONE_RTT: <4> self.spaces[tls.Epoch.ONE_RTT].crypto.update_key() <5>
===========unchanged ref 0=========== at: aioquic.connection.QuicConnection supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20] at: aioquic.connection.QuicConnection.__init__ self.__epoch = tls.Epoch.INITIAL at: aioquic.connection.QuicConnection._handle_crypto_frame self.__epoch = tls.Epoch.ONE_RTT self.__epoch = tls.Epoch.HANDSHAKE at: aioquic.connection.QuicConnection._initialize self.cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } at: aioquic.crypto.CryptoPair update_key() -> None at: aioquic.tls Epoch() ===========changed ref 0=========== # module: aioquic.connection class QuicPacketSpace: def __init__(self) -> None: self.ack_queue = RangeSet() + self.ack_required = False - self.crypto = CryptoPair()
aioquic.connection/QuicConnection.datagram_received
Modified
aiortc~aioquic
dd6122cf531739c2c9f0885e990dc0ad008ce4f2
[connection] move crypto out of QuicPacketSpace
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: <0> """ <1> Handle an incoming datagram. <2> """ <3> # stop handling packets when closing <4> if self.__state in [QuicConnectionState.CLOSING, QuicConnectionState.DRAINING]: <5> return <6> <7> data = cast(bytes, data) <8> buf = Buffer(data=data) <9> while not buf.eof(): <10> start_off = buf.tell() <11> header = pull_quic_header(buf, host_cid_length=len(self.host_cid)) <12> <13> # check destination CID matches <14> if self.is_client and header.destination_cid != self.host_cid: <15> return <16> <17> # check protocol version <18> if self.is_client and header.version == QuicProtocolVersion.NEGOTIATION: <19> # version negotiation <20> versions = [] <21> while not buf.eof(): <22> versions.append(pull_uint32(buf)) <23> common = set(self.supported_versions).intersection(versions) <24> if not common: <25> self._logger.error("Could not find a common protocol version") <26> return <27> self._version = QuicProtocolVersion(max(common)) <28> self._version_negotiation_count += 1 <29> self._logger.info("Retrying with %s", self._version) <30> self._connect() <31> return <32> elif ( <33> header.version is not None <34> and header.version not in self.supported_versions <35> ): <36> # unsupported version <37> return <38> <39> if self.is_client and header.packet_type == PACKET_TYPE_RETRY: <40> # stateless retry <41> if ( <42> header.destination_cid == self.host_cid <43> and header.original_destination_cid == self.peer_cid <44> and not self._stateless_retry_count </s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 self._original_connection_id = self.peer_cid self.peer_cid = header.source_cid self.peer_token = header.token self._stateless_retry_count += 1 self._logger.info("Performing stateless retry") self._connect() return network_path = self._find_network_path(addr) # server initialization if not self.is_client and self.__state == QuicConnectionState.FIRSTFLIGHT: assert ( header.packet_type == PACKET_TYPE_INITIAL ), "first packet must be INITIAL" self._network_paths = [network_path] self._version = QuicProtocolVersion(header.version) self._initialize(header.destination_cid) # decrypt packet encrypted_off = buf.tell() - start_off end_off = buf.tell() + header.rest_length pull_bytes(buf, header.rest_length) epoch = get_epoch(header.packet_type) space = self.spaces[epoch] if not space.crypto.recv.is_valid(): return try: plain_header, plain_payload, packet_number = space.crypto.decrypt_packet( data[start_off:end_off], encrypted_off ) except CryptoError as exc: self._logger.warning(exc) return # discard initial keys if not self.is_client and epoch == tls.Epoch.HANDSHAKE: self.spaces[tls.Epoch.INITIAL].crypto.teardown() # update state if not self.peer_cid_set: self.peer_cid = header.source_cid self.peer_cid_set = True if self.__state == QuicConnectionState.FIRSTFLIGHT: self._set_state(Qu</s> ===========below chunk 1=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 2 <s>_set = True if self.__state == QuicConnectionState.FIRSTFLIGHT: self._set_state(QuicConnectionState.CONNECTED) # update spin bit if ( not is_long_header(plain_header[0]) and packet_number > self._spin_highest_pn ): self._spin_bit_peer = get_spin_bit(plain_header[0]) if self.is_client: self._spin_bit = not self._spin_bit_peer else: self._spin_bit = self._spin_bit_peer self._spin_highest_pn = packet_number # handle payload context = QuicReceiveContext(epoch=epoch, network_path=network_path) try: is_ack_only, is_probing = self._payload_received(context, plain_payload) except QuicConnectionError as exc: self._logger.warning(exc) self.close( error_code=exc.error_code, frame_type=exc.frame_type, reason_phrase=exc.reason_phrase, ) return # update network path if not network_path.is_validated and epoch == tls.Epoch.HANDSHAKE: self._logger.info( "Network path %s validated by handshake", network_path.addr ) network_path.is_validated = True network_path.bytes_received += buf.tell() - start_off if network_path not in self._network_paths: self._network_paths.append(network_path) idx = self._network_paths.index(network_path) if idx and not is_prob</s> ===========below chunk 2=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 3 <s> self._logger.info("Network path %s promoted", network_path.addr) self._network_paths.pop(idx) self._network_paths.insert(0, network_path) # record packet as received space.ack_queue.add(packet_number) if not is_ack_only: self.send_ack[epoch] = True self._send_pending() ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) pull_bytes(buf: Buffer, length: int) -> bytes pull_uint32(buf: Buffer) -> int at: aioquic.buffer.Buffer eof() -> bool tell() -> int at: aioquic.connection NetworkAddress = Any get_epoch(packet_type: int) -> tls.Epoch QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) QuicConnectionState() QuicReceiveContext(epoch: tls.Epoch, network_path: QuicNetworkPath) at: aioquic.connection.QuicConnection supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20] close(error_code: int=QuicErrorCode.NO_ERROR, frame_type: Optional[int]=None, reason_phrase: str="") -> None _connect() -> None _find_network_path(addr: NetworkAddress) -> QuicNetworkPath _initialize(self, peer_cid: bytes) -> None _initialize(peer_cid: bytes) -> None _payload_received(context: QuicReceiveContext, plain: bytes) -> Tuple[bool, bool] _set_state(state: QuicConnectionState) -> None at: aioquic.connection.QuicConnection.__init__ self.is_client = is_client self.host_cid = os.urandom(8) self.peer_cid = os.urandom(8) self.peer_cid_set = False self.peer_token = b"" self._stateless_retry_count = 0 self._version_negotiation_count = 0 self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} )
aioquic.connection/QuicConnection._initialize
Modified
aiortc~aioquic
dd6122cf531739c2c9f0885e990dc0ad008ce4f2
[connection] move crypto out of QuicPacketSpace
<20>:<add> self.cryptos = { <del> self.send_ack = { <21>:<add> tls.Epoch.INITIAL: CryptoPair(), <del> tls.Epoch.INITIAL: False, <22>:<add> tls.Epoch.HANDSHAKE: CryptoPair(), <del> tls.Epoch.HANDSHAKE: False, <23>:<add> tls.Epoch.ONE_RTT: CryptoPair(), <del> tls.Epoch.ONE_RTT: False,
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _initialize(self, peer_cid: bytes) -> None: <0> # TLS <1> self.tls = tls.Context(is_client=self.is_client, logger=self._logger) <2> self.tls.alpn_protocols = self.alpn_protocols <3> self.tls.certificate = self.certificate <4> self.tls.certificate_private_key = self.private_key <5> self.tls.handshake_extensions = [ <6> ( <7> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, <8> self._serialize_transport_parameters(), <9> ) <10> ] <11> self.tls.server_name = self.server_name <12> self.tls.session_ticket = self._session_ticket <13> if self._session_ticket_fetcher is not None: <14> self.tls.get_session_ticket_cb = self._session_ticket_fetcher <15> if self._session_ticket_handler is not None: <16> self.tls.new_session_ticket_cb = self._session_ticket_handler <17> self.tls.update_traffic_key_cb = self._update_traffic_key <18> <19> # packet spaces <20> self.send_ack = { <21> tls.Epoch.INITIAL: False, <22> tls.Epoch.HANDSHAKE: False, <23> tls.Epoch.ONE_RTT: False, <24> } <25> self.send_buffer = { <26> tls.Epoch.INITIAL: Buffer(capacity=4096), <27> tls.Epoch.HANDSHAKE: Buffer(capacity=4096), <28> tls.Epoch.ONE_RTT: Buffer(capacity=4096), <29> } <30> self.spaces = { <31> tls.Epoch.INITIAL: QuicPacketSpace(), <32> tls.Epoch.HANDSHAKE: QuicPacketSpace(), <33> tls.Epoch.ONE_RTT: QuicPacketSpace(), <34> } <35> self.streams[tls.Epoch.INITIAL] = QuicStream() <36> self</s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _initialize(self, peer_cid: bytes) -> None: # offset: 1 self.streams[tls.Epoch.ONE_RTT] = QuicStream() self.spaces[tls.Epoch.INITIAL].crypto.setup_initial( cid=peer_cid, is_client=self.is_client ) self.packet_number = 0 ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.connection QuicPacketSpace() at: aioquic.connection.QuicConnection _serialize_transport_parameters() -> bytes _update_traffic_key(direction: tls.Direction, epoch: tls.Epoch, secret: bytes) -> None _update_traffic_key(self, direction: tls.Direction, epoch: tls.Epoch, secret: bytes) -> None at: aioquic.connection.QuicConnection.__init__ self.alpn_protocols = alpn_protocols self.certificate = certificate self.is_client = is_client self.private_key = private_key self.server_name = server_name self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} ) self._session_ticket = session_ticket self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler at: aioquic.crypto CryptoPair() at: aioquic.crypto.CryptoPair setup_initial(cid: bytes, is_client: bool) -> None at: aioquic.stream QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0) at: aioquic.tls Epoch() ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None) ===========unchanged ref 1=========== at: aioquic.tls.Context.__init__ self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, bytes], None ] = lambda d, e, s: None ===========changed ref 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def request_key_update(self) -> None: """ Request an update of the encryption keys. """ if self.__epoch == tls.Epoch.ONE_RTT: + self.cryptos[tls.Epoch.ONE_RTT].update_key() - self.spaces[tls.Epoch.ONE_RTT].crypto.update_key() ===========changed ref 1=========== # module: aioquic.connection class QuicPacketSpace: def __init__(self) -> None: self.ack_queue = RangeSet() + self.ack_required = False - self.crypto = CryptoPair() ===========changed ref 2=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: """ Handle an incoming datagram. """ # stop handling packets when closing if self.__state in [QuicConnectionState.CLOSING, QuicConnectionState.DRAINING]: return data = cast(bytes, data) buf = Buffer(data=data) while not buf.eof(): start_off = buf.tell() header = pull_quic_header(buf, host_cid_length=len(self.host_cid)) # check destination CID matches if self.is_client and header.destination_cid != self.host_cid: return # check protocol version if self.is_client and header.version == QuicProtocolVersion.NEGOTIATION: # version negotiation versions = [] while not buf.eof(): versions.append(pull_uint32(buf)) common = set(self.supported_versions).intersection(versions) if not common: self._logger.error("Could not find a common protocol version") return self._version = QuicProtocolVersion(max(common)) self._version_negotiation_count += 1 self._logger.info("Retrying with %s", self._version) self._connect() return elif ( header.version is not None and header.version not in self.supported_versions ): # unsupported version return if self.is_client and header.packet_type == PACKET_TYPE_RETRY: # stateless retry if ( header.destination_cid == self.host_cid and header.original_destination_cid == self.peer_cid and not self._stateless_retry_count ): self._original_connection_id = self.peer_cid self.peer_cid = header.source_cid self.peer_token = header.token self</s> ===========changed ref 3=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 <s>peer_cid self.peer_cid = header.source_cid self.peer_token = header.token self._stateless_retry_count += 1 self._logger.info("Performing stateless retry") self._connect() return network_path = self._find_network_path(addr) # server initialization if not self.is_client and self.__state == QuicConnectionState.FIRSTFLIGHT: assert ( header.packet_type == PACKET_TYPE_INITIAL ), "first packet must be INITIAL" self._network_paths = [network_path] self._version = QuicProtocolVersion(header.version) self._initialize(header.destination_cid) # decrypt packet encrypted_off = buf.tell() - start_off end_off = buf.tell() + header.rest_length pull_bytes(buf, header.rest_length) epoch = get_epoch(header.packet_type) + crypto = self.cryptos[epoch] space = self.spaces[epoch] + if not crypto.recv.is_valid(): - if not space.crypto.recv.is_valid(): return try: + plain_header, plain_payload, packet_number = crypto.decrypt_packet( - plain_header, plain_payload, packet_number = space.crypto.decrypt_packet( data[start_off:end_off], encrypted_off ) except CryptoError as exc: self._logger.warning(exc) return # discard initial keys if not self.is_client and epoch == tls.Epoch.HANDSHAKE: + self.cryptos[tls.Epoch.INITIAL].te</s>
aioquic.connection/QuicConnection._update_traffic_key
Modified
aiortc~aioquic
dd6122cf531739c2c9f0885e990dc0ad008ce4f2
[connection] move crypto out of QuicPacketSpace
<12>:<add> crypto = self.cryptos[epoch] <del> crypto = self.spaces[epoch].crypto
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _update_traffic_key( self, direction: tls.Direction, epoch: tls.Epoch, secret: bytes ) -> None: <0> """ <1> Callback which is invoked by the TLS engine when new traffic keys are <2> available. <3> """ <4> if self.secrets_log_file is not None: <5> label_row = self.is_client == (direction == tls.Direction.DECRYPT) <6> label = SECRETS_LABELS[label_row][epoch.value] <7> self.secrets_log_file.write( <8> "%s %s %s\n" % (label, self.tls.client_random.hex(), secret.hex()) <9> ) <10> self.secrets_log_file.flush() <11> <12> crypto = self.spaces[epoch].crypto <13> if direction == tls.Direction.ENCRYPT: <14> crypto.send.setup(self.tls.key_schedule.cipher_suite, secret) <15> else: <16> crypto.recv.setup(self.tls.key_schedule.cipher_suite, secret) <17>
===========unchanged ref 0=========== at: aioquic.connection SECRETS_LABELS = [ [ None, "QUIC_CLIENT_EARLY_TRAFFIC_SECRET", "QUIC_CLIENT_HANDSHAKE_TRAFFIC_SECRET", "QUIC_CLIENT_TRAFFIC_SECRET_0", ], [ None, None, "QUIC_SERVER_HANDSHAKE_TRAFFIC_SECRET", "QUIC_SERVER_TRAFFIC_SECRET_0", ], ] at: aioquic.connection.QuicConnection.__init__ self.is_client = is_client self.secrets_log_file = secrets_log_file at: aioquic.connection.QuicConnection._initialize self.tls = tls.Context(is_client=self.is_client, logger=self._logger) self.cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } at: aioquic.crypto.CryptoContext setup(cipher_suite: CipherSuite, secret: bytes) -> None at: aioquic.crypto.CryptoPair.__init__ self.send = CryptoContext() at: aioquic.tls Direction() Epoch() at: aioquic.tls.Context.__init__ self.key_schedule: Optional[KeySchedule] = None self.client_random = None self.client_random = os.urandom(32) at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) at: aioquic.tls.Context._server_handle_hello self.client_random = peer_hello.random self.key_schedule = KeySchedule(cipher_suite) ===========unchanged ref 1=========== at: aioquic.tls.KeySchedule.__init__ self.cipher_suite = cipher_suite at: enum.Enum name: str value: Any _name_: str _value_: Any _member_names_: List[str] # undocumented _member_map_: Dict[str, Enum] # undocumented _value2member_map_: Dict[int, Enum] # undocumented _ignore_: Union[str, List[str]] _order_: str __order__: str at: typing.IO __slots__ = () flush() -> None write(s: AnyStr) -> int ===========changed ref 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def request_key_update(self) -> None: """ Request an update of the encryption keys. """ if self.__epoch == tls.Epoch.ONE_RTT: + self.cryptos[tls.Epoch.ONE_RTT].update_key() - self.spaces[tls.Epoch.ONE_RTT].crypto.update_key() ===========changed ref 1=========== # module: aioquic.connection class QuicPacketSpace: def __init__(self) -> None: self.ack_queue = RangeSet() + self.ack_required = False - self.crypto = CryptoPair() ===========changed ref 2=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _initialize(self, peer_cid: bytes) -> None: # TLS self.tls = tls.Context(is_client=self.is_client, logger=self._logger) self.tls.alpn_protocols = self.alpn_protocols self.tls.certificate = self.certificate self.tls.certificate_private_key = self.private_key self.tls.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, self._serialize_transport_parameters(), ) ] self.tls.server_name = self.server_name self.tls.session_ticket = self._session_ticket if self._session_ticket_fetcher is not None: self.tls.get_session_ticket_cb = self._session_ticket_fetcher if self._session_ticket_handler is not None: self.tls.new_session_ticket_cb = self._session_ticket_handler self.tls.update_traffic_key_cb = self._update_traffic_key # packet spaces + self.cryptos = { - self.send_ack = { + tls.Epoch.INITIAL: CryptoPair(), - tls.Epoch.INITIAL: False, + tls.Epoch.HANDSHAKE: CryptoPair(), - tls.Epoch.HANDSHAKE: False, + tls.Epoch.ONE_RTT: CryptoPair(), - tls.Epoch.ONE_RTT: False, } self.send_buffer = { tls.Epoch.INITIAL: Buffer(capacity=4096), tls.Epoch.HANDSHAKE: Buffer(capacity=4096), tls.Epoch.ONE_RTT: Buffer(capacity=4096), } self.spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self</s> ===========changed ref 3=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _initialize(self, peer_cid: bytes) -> None: # offset: 1 <s>SHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self.streams[tls.Epoch.INITIAL] = QuicStream() self.streams[tls.Epoch.HANDSHAKE] = QuicStream() self.streams[tls.Epoch.ONE_RTT] = QuicStream() + self.cryptos[tls.Epoch.INITIAL].setup_initial( - self.spaces[tls.Epoch.INITIAL].crypto.setup_initial( cid=peer_cid, is_client=self.is_client ) self.packet_number = 0
aioquic.connection/QuicConnection._write_application
Modified
aiortc~aioquic
dd6122cf531739c2c9f0885e990dc0ad008ce4f2
[connection] move crypto out of QuicPacketSpace
<1>:<add> crypto = self.cryptos[epoch] <2>:<add> if not crypto.send.is_valid(): <del> if not space.crypto.send.is_valid(): <6>:<add> capacity = buf.capacity - crypto.aead_tag_size <del> capacity = buf.capacity - space.crypto.aead_tag_size <14>:<add> | (crypto.key_phase << 2) <del> | (space.crypto.key_phase << 2) <22>:<add> if space.ack_required and space.ack_queue: <del> if self.send_ack[epoch] and space.ack_queue: <25>:<add> space.ack_required = False <del> self.send_ack[epoch] = False
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _write_application(self, network_path: QuicNetworkPath) -> Iterator[bytes]: <0> epoch = tls.Epoch.ONE_RTT <1> space = self.spaces[epoch] <2> if not space.crypto.send.is_valid(): <3> return <4> <5> buf = Buffer(capacity=PACKET_MAX_SIZE) <6> capacity = buf.capacity - space.crypto.aead_tag_size <7> <8> while True: <9> # write header <10> push_uint8( <11> buf, <12> PACKET_FIXED_BIT <13> | (self._spin_bit << 5) <14> | (space.crypto.key_phase << 2) <15> | (PACKET_NUMBER_SEND_SIZE - 1), <16> ) <17> push_bytes(buf, self.peer_cid) <18> push_uint16(buf, self.packet_number) <19> header_size = buf.tell() <20> <21> # ACK <22> if self.send_ack[epoch] and space.ack_queue: <23> push_uint_var(buf, QuicFrameType.ACK) <24> packet.push_ack_frame(buf, space.ack_queue, 0) <25> self.send_ack[epoch] = False <26> <27> # PATH CHALLENGE <28> if ( <29> self.__epoch == tls.Epoch.ONE_RTT <30> and not network_path.is_validated <31> and network_path.local_challenge is None <32> ): <33> self._logger.info( <34> "Network path %s sending challenge", network_path.addr <35> ) <36> network_path.local_challenge = os.urandom(8) <37> push_uint_var(buf, QuicFrameType.PATH_CHALLENGE) <38> push_bytes(buf, network_path.local_challenge) <39> <40> # PATH RESPONSE <41> if network_path.remote_challenge is not None: <42> push_uint_var(</s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _write_application(self, network_path: QuicNetworkPath) -> Iterator[bytes]: # offset: 1 push_bytes(buf, network_path.remote_challenge) network_path.remote_challenge = None # PING if self._ping_waiter is not None and self._ping_packet_number is None: self._ping_packet_number = self.packet_number self._logger.info("Sending PING in packet %d", self.packet_number) push_uint_var(buf, QuicFrameType.PING) # CLOSE if self.__close and self.__epoch == epoch: push_close(buf, **self.__close) self.__close = None for stream_id, stream in self.streams.items(): # CRYPTO if stream_id == tls.Epoch.ONE_RTT: stream = self.streams[epoch] frame_overhead = 3 + quic_uint_length(stream._send_start) frame = stream.get_frame(capacity - buf.tell() - frame_overhead) if frame is not None: push_uint_var(buf, QuicFrameType.CRYPTO) with packet.push_crypto_frame(buf, frame.offset): push_bytes(buf, frame.data) # STREAM elif isinstance(stream_id, int): # the frame data size is constrained by our peer's MAX_DATA and # the space available in the current packet frame_overhead = ( 3 + quic_uint_length(stream_id) + ( quic_uint_length(stream._send_start) if stream._send_start else 0 ) ) frame = stream.get_frame( min( capacity - buf.tell() - frame_overhead, self._remote_max_data - self._remote_max_data_used, ) ) if frame is</s> ===========below chunk 1=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _write_application(self, network_path: QuicNetworkPath) -> Iterator[bytes]: # offset: 2 <s> self._remote_max_data - self._remote_max_data_used, ) ) if frame is not None: flags = QuicStreamFlag.LEN if frame.offset: flags |= QuicStreamFlag.OFF if frame.fin: flags |= QuicStreamFlag.FIN push_uint_var(buf, QuicFrameType.STREAM_BASE | flags) with push_stream_frame(buf, stream_id, frame.offset): push_bytes(buf, frame.data) self._remote_max_data_used += len(frame.data) packet_size = buf.tell() if packet_size > header_size: # check whether we need padding padding_size = ( PACKET_NUMBER_MAX_SIZE - PACKET_NUMBER_SEND_SIZE + header_size - packet_size ) if padding_size > 0: push_bytes(buf, bytes(padding_size)) packet_size += padding_size # encrypt data = buf.data yield space.crypto.encrypt_packet( data[0:header_size], data[header_size:packet_size] ) self.packet_number += 1 buf.seek(0) else: break ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) push_bytes(buf: Buffer, v: bytes) -> None push_uint8(buf: Buffer, v: int) -> None push_uint16(buf: Buffer, v: int) -> None at: aioquic.buffer.Buffer seek(pos: int) -> None tell() -> int at: aioquic.connection PACKET_MAX_SIZE = 1280 push_close(buf: Buffer, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None) at: aioquic.connection.QuicConnection.__init__ self.peer_cid = os.urandom(8) self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} self.__close: Optional[Dict] = None self.__epoch = tls.Epoch.INITIAL self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} ) self._ping_packet_number: Optional[int] = None self._ping_waiter: Optional[asyncio.Future[None]] = None self._remote_max_data = 0 self._remote_max_data_used = 0 self._spin_bit = False at: aioquic.connection.QuicConnection._handle_ack_frame self._ping_waiter = None self._ping_packet_number = None at: aioquic.connection.QuicConnection._handle_crypto_frame self.__epoch = tls.Epoch.ONE_RTT self.__epoch = tls.Epoch.HANDSHAKE ===========unchanged ref 1=========== at: aioquic.connection.QuicConnection._handle_max_data_frame self._remote_max_data = max_data at: aioquic.connection.QuicConnection._initialize self.cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } self.spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self.packet_number = 0 at: aioquic.connection.QuicConnection._write_handshake self.__close = None self.packet_number += 1 at: aioquic.connection.QuicConnection.close self.__close = { "error_code": error_code, "frame_type": frame_type, "reason_phrase": reason_phrase, } at: aioquic.connection.QuicConnection.datagram_received self.peer_cid = header.source_cid self._spin_bit = self._spin_bit_peer self._spin_bit = not self._spin_bit_peer at: aioquic.connection.QuicConnection.ping self._ping_packet_number = None self._ping_waiter = self._loop.create_future() at: aioquic.connection.QuicNetworkPath addr: NetworkAddress is_validated: bool = False local_challenge: Optional[bytes] = None remote_challenge: Optional[bytes] = None at: aioquic.connection.QuicPacketSpace.__init__ self.ack_required = False at: aioquic.crypto.CryptoContext is_valid() -> bool at: aioquic.crypto.CryptoPair.__init__ self.aead_tag_size = 16 self.send = CryptoContext()
aioquic.connection/QuicConnection._write_handshake
Modified
aiortc~aioquic
dd6122cf531739c2c9f0885e990dc0ad008ce4f2
[connection] move crypto out of QuicPacketSpace
<0>:<add> crypto = self.cryptos[epoch] <1>:<add> if not crypto.send.is_valid(): <del> if not space.crypto.send.is_valid(): <5>:<add> capacity = buf.capacity - crypto.aead_tag_size <del> capacity = buf.capacity - space.crypto.aead_tag_size <27>:<add> if space.ack_required and space.ack_queue: <del> if self.send_ack[epoch] and space.ack_queue: <30>:<add> space.ack_required = False <del> self.send_ack[epoch] = False
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _write_handshake(self, epoch: tls.Epoch) -> Iterator[bytes]: <0> space = self.spaces[epoch] <1> if not space.crypto.send.is_valid(): <2> return <3> <4> buf = Buffer(capacity=PACKET_MAX_SIZE) <5> capacity = buf.capacity - space.crypto.aead_tag_size <6> <7> while True: <8> if epoch == tls.Epoch.INITIAL: <9> packet_type = PACKET_TYPE_INITIAL <10> else: <11> packet_type = PACKET_TYPE_HANDSHAKE <12> <13> # write header <14> push_quic_header( <15> buf, <16> QuicHeader( <17> version=self._version, <18> packet_type=packet_type | (PACKET_NUMBER_SEND_SIZE - 1), <19> destination_cid=self.peer_cid, <20> source_cid=self.host_cid, <21> token=self.peer_token, <22> ), <23> ) <24> header_size = buf.tell() <25> <26> # ACK <27> if self.send_ack[epoch] and space.ack_queue: <28> push_uint_var(buf, QuicFrameType.ACK) <29> packet.push_ack_frame(buf, space.ack_queue, 0) <30> self.send_ack[epoch] = False <31> <32> # CLOSE <33> if self.__close and self.__epoch == epoch: <34> push_close(buf, **self.__close) <35> self.__close = None <36> <37> # CRYPTO <38> stream = self.streams[epoch] <39> frame_overhead = 3 + quic_uint_length(stream._send_start) <40> frame = stream.get_frame(capacity - buf.tell() - frame_overhead) <41> if frame is not None: <42> push_uint_var(buf, QuicFrameType.CRYPTO) <43> with packet.push_crypto_frame(buf</s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _write_handshake(self, epoch: tls.Epoch) -> Iterator[bytes]: # offset: 1 push_bytes(buf, frame.data) # PADDING if epoch == tls.Epoch.INITIAL and self.is_client: push_bytes(buf, bytes(capacity - buf.tell())) packet_size = buf.tell() if packet_size > header_size: # finalize length buf.seek(header_size - PACKET_NUMBER_SEND_SIZE - 2) length = packet_size - header_size + 2 + space.crypto.aead_tag_size push_uint16(buf, length | 0x4000) push_uint16(buf, self.packet_number) buf.seek(packet_size) # encrypt data = buf.data yield space.crypto.encrypt_packet( data[0:header_size], data[header_size:packet_size] ) self.packet_number += 1 buf.seek(0) # discard initial keys if self.is_client and epoch == tls.Epoch.HANDSHAKE: self.spaces[tls.Epoch.INITIAL].crypto.teardown() else: break ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) push_bytes(buf: Buffer, v: bytes) -> None push_uint16(buf: Buffer, v: int) -> None at: aioquic.buffer.Buffer seek(pos: int) -> None tell() -> int at: aioquic.connection PACKET_MAX_SIZE = 1280 push_close(buf: Buffer, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None at: aioquic.connection.QuicConnection.__init__ self.is_client = is_client self.host_cid = os.urandom(8) self.peer_cid = os.urandom(8) self.peer_token = b"" self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} self.__close: Optional[Dict] = None self.__epoch = tls.Epoch.INITIAL self._version: Optional[int] = None at: aioquic.connection.QuicConnection._handle_crypto_frame self.__epoch = tls.Epoch.ONE_RTT self.__epoch = tls.Epoch.HANDSHAKE at: aioquic.connection.QuicConnection._initialize self.cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } self.spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self.packet_number = 0 at: aioquic.connection.QuicConnection._write_application self.__close = None self.packet_number += 1 ===========unchanged ref 1=========== at: aioquic.connection.QuicConnection.close self.__close = { "error_code": error_code, "frame_type": frame_type, "reason_phrase": reason_phrase, } at: aioquic.connection.QuicConnection.connect self._version = max(self.supported_versions) self._version = protocol_version at: aioquic.connection.QuicConnection.datagram_received self._version = QuicProtocolVersion(header.version) self._version = QuicProtocolVersion(max(common)) self.peer_cid = header.source_cid self.peer_token = header.token at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20 PACKET_NUMBER_SEND_SIZE = 2 QuicHeader(version: Optional[int], packet_type: int, destination_cid: bytes, source_cid: bytes, original_destination_cid: bytes=b"", token: bytes=b"", rest_length: int=0) quic_uint_length(value: int) -> int push_uint_var(buf: Buffer, value: int) -> None push_quic_header(buf: Buffer, header: QuicHeader) -> None QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) push_ack_frame(buf: Buffer, rangeset: RangeSet, delay: int) -> None push_crypto_frame(buf: Buffer, offset: int=0) -> Generator at: aioquic.stream.QuicStream get_frame(size: int) -> Optional[QuicStreamFrame] at: aioquic.stream.QuicStream.__init__ self._send_start = 0 ===========unchanged ref 2=========== at: aioquic.stream.QuicStream.get_frame self._send_start += size at: aioquic.tls Epoch() at: typing Iterator = _alias(collections.abc.Iterator, 1) ===========changed ref 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _update_traffic_key( self, direction: tls.Direction, epoch: tls.Epoch, secret: bytes ) -> None: """ Callback which is invoked by the TLS engine when new traffic keys are available. """ if self.secrets_log_file is not None: label_row = self.is_client == (direction == tls.Direction.DECRYPT) label = SECRETS_LABELS[label_row][epoch.value] self.secrets_log_file.write( "%s %s %s\n" % (label, self.tls.client_random.hex(), secret.hex()) ) self.secrets_log_file.flush() + crypto = self.cryptos[epoch] - crypto = self.spaces[epoch].crypto if direction == tls.Direction.ENCRYPT: crypto.send.setup(self.tls.key_schedule.cipher_suite, secret) else: crypto.recv.setup(self.tls.key_schedule.cipher_suite, secret) ===========changed ref 1=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def request_key_update(self) -> None: """ Request an update of the encryption keys. """ if self.__epoch == tls.Epoch.ONE_RTT: + self.cryptos[tls.Epoch.ONE_RTT].update_key() - self.spaces[tls.Epoch.ONE_RTT].crypto.update_key() ===========changed ref 2=========== # module: aioquic.connection class QuicPacketSpace: def __init__(self) -> None: self.ack_queue = RangeSet() + self.ack_required = False - self.crypto = CryptoPair()
tests.test_connection/QuicConnectionTest.test_decryption_error
Modified
aiortc~aioquic
dd6122cf531739c2c9f0885e990dc0ad008ce4f2
[connection] move crypto out of QuicPacketSpace
<14>:<add> server.cryptos[tls.Epoch.ONE_RTT].send.setup( <del> server.spaces[tls.Epoch.ONE_RTT].crypto.send.setup(
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_decryption_error(self): <0> client = QuicConnection(is_client=True) <1> <2> server = QuicConnection( <3> is_client=False, <4> certificate=SERVER_CERTIFICATE, <5> private_key=SERVER_PRIVATE_KEY, <6> ) <7> <8> # perform handshake <9> client_transport, server_transport = create_transport(client, server) <10> self.assertEqual(client_transport.sent, 4) <11> self.assertEqual(server_transport.sent, 4) <12> <13> # mess with encryption key <14> server.spaces[tls.Epoch.ONE_RTT].crypto.send.setup( <15> tls.CipherSuite.AES_128_GCM_SHA256, bytes(48) <16> ) <17> <18> # close <19> server.close(error_code=QuicErrorCode.NO_ERROR) <20> self.assertEqual(client_transport.sent, 4) <21> self.assertEqual(server_transport.sent, 5) <22>
===========unchanged ref 0=========== at: aioquic.connection QuicConnection(*, is_client: bool=True, certificate: Any=None, private_key: Any=None, alpn_protocols: Optional[List[str]]=None, original_connection_id: Optional[bytes]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.connection.QuicConnection supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20] close(error_code: int=QuicErrorCode.NO_ERROR, frame_type: Optional[int]=None, reason_phrase: str="") -> None at: aioquic.connection.QuicConnection._initialize self.cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } at: aioquic.crypto.CryptoContext setup(cipher_suite: CipherSuite, secret: bytes) -> None at: aioquic.crypto.CryptoPair.__init__ self.send = CryptoContext() at: aioquic.packet QuicErrorCode(x: Union[str, bytes, bytearray], base: int) QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: aioquic.tls Epoch() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: tests.test_connection create_transport(client, server) at: tests.test_connection.FakeTransport.sendto self.sent += 1 ===========unchanged ref 1=========== at: tests.utils SERVER_CERTIFICATE = x509.load_pem_x509_certificate( load("ssl_cert.pem"), backend=default_backend() ) SERVER_PRIVATE_KEY = serialization.load_pem_private_key( load("ssl_key.pem"), password=None, backend=default_backend() ) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.connection class QuicPacketSpace: def __init__(self) -> None: self.ack_queue = RangeSet() + self.ack_required = False - self.crypto = CryptoPair() ===========changed ref 1=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def request_key_update(self) -> None: """ Request an update of the encryption keys. """ if self.__epoch == tls.Epoch.ONE_RTT: + self.cryptos[tls.Epoch.ONE_RTT].update_key() - self.spaces[tls.Epoch.ONE_RTT].crypto.update_key() ===========changed ref 2=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _update_traffic_key( self, direction: tls.Direction, epoch: tls.Epoch, secret: bytes ) -> None: """ Callback which is invoked by the TLS engine when new traffic keys are available. """ if self.secrets_log_file is not None: label_row = self.is_client == (direction == tls.Direction.DECRYPT) label = SECRETS_LABELS[label_row][epoch.value] self.secrets_log_file.write( "%s %s %s\n" % (label, self.tls.client_random.hex(), secret.hex()) ) self.secrets_log_file.flush() + crypto = self.cryptos[epoch] - crypto = self.spaces[epoch].crypto if direction == tls.Direction.ENCRYPT: crypto.send.setup(self.tls.key_schedule.cipher_suite, secret) else: crypto.recv.setup(self.tls.key_schedule.cipher_suite, secret) ===========changed ref 3=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _initialize(self, peer_cid: bytes) -> None: # TLS self.tls = tls.Context(is_client=self.is_client, logger=self._logger) self.tls.alpn_protocols = self.alpn_protocols self.tls.certificate = self.certificate self.tls.certificate_private_key = self.private_key self.tls.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, self._serialize_transport_parameters(), ) ] self.tls.server_name = self.server_name self.tls.session_ticket = self._session_ticket if self._session_ticket_fetcher is not None: self.tls.get_session_ticket_cb = self._session_ticket_fetcher if self._session_ticket_handler is not None: self.tls.new_session_ticket_cb = self._session_ticket_handler self.tls.update_traffic_key_cb = self._update_traffic_key # packet spaces + self.cryptos = { - self.send_ack = { + tls.Epoch.INITIAL: CryptoPair(), - tls.Epoch.INITIAL: False, + tls.Epoch.HANDSHAKE: CryptoPair(), - tls.Epoch.HANDSHAKE: False, + tls.Epoch.ONE_RTT: CryptoPair(), - tls.Epoch.ONE_RTT: False, } self.send_buffer = { tls.Epoch.INITIAL: Buffer(capacity=4096), tls.Epoch.HANDSHAKE: Buffer(capacity=4096), tls.Epoch.ONE_RTT: Buffer(capacity=4096), } self.spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self</s> ===========changed ref 4=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _initialize(self, peer_cid: bytes) -> None: # offset: 1 <s>SHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self.streams[tls.Epoch.INITIAL] = QuicStream() self.streams[tls.Epoch.HANDSHAKE] = QuicStream() self.streams[tls.Epoch.ONE_RTT] = QuicStream() + self.cryptos[tls.Epoch.INITIAL].setup_initial( - self.spaces[tls.Epoch.INITIAL].crypto.setup_initial( cid=peer_cid, is_client=self.is_client ) self.packet_number = 0
aioquic.connection/get_epoch
Modified
aiortc~aioquic
428adcf6391b350ddb03ac4f32c38c30b3071b37
[connection] ensure 0-RTT uses correct crypto
<2>:<add> elif packet_type == PACKET_TYPE_ZERO_RTT: <add> return tls.Epoch.ZERO_RTT
# module: aioquic.connection def get_epoch(packet_type: int) -> tls.Epoch: <0> if packet_type == PACKET_TYPE_INITIAL: <1> return tls.Epoch.INITIAL <2> elif packet_type == PACKET_TYPE_HANDSHAKE: <3> return tls.Epoch.HANDSHAKE <4> else: <5> return tls.Epoch.ONE_RTT <6>
===========unchanged ref 0=========== at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 PACKET_TYPE_ZERO_RTT = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x10 PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20 at: aioquic.tls Epoch() ===========changed ref 0=========== # module: aioquic.packet PACKET_LONG_HEADER = 0x80 PACKET_FIXED_BIT = 0x40 PACKET_SPIN_BIT = 0x20 PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 + PACKET_TYPE_ZERO_RTT = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x10 - PACKET_TYPE_0RTT = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x10 PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20 PACKET_TYPE_RETRY = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x30 PACKET_TYPE_MASK = 0xF0 PACKET_NUMBER_MAX_SIZE = 4 PACKET_NUMBER_SEND_SIZE = 2 UINT_VAR_FORMATS = [ (pull_uint8, push_uint8, 0x3F), (pull_uint16, push_uint16, 0x3FFF), (pull_uint32, push_uint32, 0x3FFFFFFF), (pull_uint64, push_uint64, 0x3FFFFFFFFFFFFFFF), ]
aioquic.connection/QuicConnection.datagram_received
Modified
aiortc~aioquic
428adcf6391b350ddb03ac4f32c38c30b3071b37
[connection] ensure 0-RTT uses correct crypto
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: <0> """ <1> Handle an incoming datagram. <2> """ <3> # stop handling packets when closing <4> if self.__state in [QuicConnectionState.CLOSING, QuicConnectionState.DRAINING]: <5> return <6> <7> data = cast(bytes, data) <8> buf = Buffer(data=data) <9> while not buf.eof(): <10> start_off = buf.tell() <11> header = pull_quic_header(buf, host_cid_length=len(self.host_cid)) <12> <13> # check destination CID matches <14> if self.is_client and header.destination_cid != self.host_cid: <15> return <16> <17> # check protocol version <18> if self.is_client and header.version == QuicProtocolVersion.NEGOTIATION: <19> # version negotiation <20> versions = [] <21> while not buf.eof(): <22> versions.append(pull_uint32(buf)) <23> common = set(self.supported_versions).intersection(versions) <24> if not common: <25> self._logger.error("Could not find a common protocol version") <26> return <27> self._version = QuicProtocolVersion(max(common)) <28> self._version_negotiation_count += 1 <29> self._logger.info("Retrying with %s", self._version) <30> self._connect() <31> return <32> elif ( <33> header.version is not None <34> and header.version not in self.supported_versions <35> ): <36> # unsupported version <37> return <38> <39> if self.is_client and header.packet_type == PACKET_TYPE_RETRY: <40> # stateless retry <41> if ( <42> header.destination_cid == self.host_cid <43> and header.original_destination_cid == self.peer_cid <44> and not self._stateless_retry_count </s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 self._original_connection_id = self.peer_cid self.peer_cid = header.source_cid self.peer_token = header.token self._stateless_retry_count += 1 self._logger.info("Performing stateless retry") self._connect() return network_path = self._find_network_path(addr) # server initialization if not self.is_client and self.__state == QuicConnectionState.FIRSTFLIGHT: assert ( header.packet_type == PACKET_TYPE_INITIAL ), "first packet must be INITIAL" self._network_paths = [network_path] self._version = QuicProtocolVersion(header.version) self._initialize(header.destination_cid) # decrypt packet encrypted_off = buf.tell() - start_off end_off = buf.tell() + header.rest_length pull_bytes(buf, header.rest_length) epoch = get_epoch(header.packet_type) crypto = self.cryptos[epoch] space = self.spaces[epoch] if not crypto.recv.is_valid(): return try: plain_header, plain_payload, packet_number = crypto.decrypt_packet( data[start_off:end_off], encrypted_off ) except CryptoError as exc: self._logger.warning(exc) return # discard initial keys if not self.is_client and epoch == tls.Epoch.HANDSHAKE: self.cryptos[tls.Epoch.INITIAL].teardown() # update state if not self.peer_cid_set: self.peer_cid = header.source_cid self.peer_cid_set = True if self.__state == QuicConnectionState.FIRSTFLIGHT: self</s> ===========below chunk 1=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 2 <s> self.peer_cid_set = True if self.__state == QuicConnectionState.FIRSTFLIGHT: self._set_state(QuicConnectionState.CONNECTED) # update spin bit if ( not is_long_header(plain_header[0]) and packet_number > self._spin_highest_pn ): self._spin_bit_peer = get_spin_bit(plain_header[0]) if self.is_client: self._spin_bit = not self._spin_bit_peer else: self._spin_bit = self._spin_bit_peer self._spin_highest_pn = packet_number # handle payload context = QuicReceiveContext(epoch=epoch, network_path=network_path) try: is_ack_only, is_probing = self._payload_received(context, plain_payload) except QuicConnectionError as exc: self._logger.warning(exc) self.close( error_code=exc.error_code, frame_type=exc.frame_type, reason_phrase=exc.reason_phrase, ) return # update network path if not network_path.is_validated and epoch == tls.Epoch.HANDSHAKE: self._logger.info( "Network path %s validated by handshake", network_path.addr ) network_path.is_validated = True network_path.bytes_received += buf.tell() - start_off if network_path not in self._network_paths: self._network_paths.append(network_path) idx = self._network_paths.index(network_path) if</s> ===========below chunk 2=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 3 <s> not is_probing: self._logger.info("Network path %s promoted", network_path.addr) self._network_paths.pop(idx) self._network_paths.insert(0, network_path) # record packet as received space.ack_queue.add(packet_number) if not is_ack_only: space.ack_required = True self._send_pending() ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) pull_bytes(buf: Buffer, length: int) -> bytes pull_uint32(buf: Buffer) -> int at: aioquic.buffer.Buffer eof() -> bool tell() -> int at: aioquic.connection NetworkAddress = Any get_epoch(packet_type: int) -> tls.Epoch QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) QuicConnectionState() QuicReceiveContext(epoch: tls.Epoch, network_path: QuicNetworkPath) at: aioquic.connection.QuicConnection supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20] close(error_code: int=QuicErrorCode.NO_ERROR, frame_type: Optional[int]=None, reason_phrase: str="") -> None _connect() -> None _find_network_path(addr: NetworkAddress) -> QuicNetworkPath _initialize(self, peer_cid: bytes) -> None _initialize(peer_cid: bytes) -> None _payload_received(context: QuicReceiveContext, plain: bytes) -> Tuple[bool, bool] _set_state(state: QuicConnectionState) -> None at: aioquic.connection.QuicConnection.__init__ self.is_client = is_client self.host_cid = os.urandom(8) self.peer_cid = os.urandom(8) self.peer_cid_set = False self.peer_token = b"" self._stateless_retry_count = 0 self._version_negotiation_count = 0 self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} )
aioquic.connection/QuicConnection._initialize
Modified
aiortc~aioquic
428adcf6391b350ddb03ac4f32c38c30b3071b37
[connection] ensure 0-RTT uses correct crypto
<22>:<add> tls.Epoch.ZERO_RTT: CryptoPair(),
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _initialize(self, peer_cid: bytes) -> None: <0> # TLS <1> self.tls = tls.Context(is_client=self.is_client, logger=self._logger) <2> self.tls.alpn_protocols = self.alpn_protocols <3> self.tls.certificate = self.certificate <4> self.tls.certificate_private_key = self.private_key <5> self.tls.handshake_extensions = [ <6> ( <7> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, <8> self._serialize_transport_parameters(), <9> ) <10> ] <11> self.tls.server_name = self.server_name <12> self.tls.session_ticket = self._session_ticket <13> if self._session_ticket_fetcher is not None: <14> self.tls.get_session_ticket_cb = self._session_ticket_fetcher <15> if self._session_ticket_handler is not None: <16> self.tls.new_session_ticket_cb = self._session_ticket_handler <17> self.tls.update_traffic_key_cb = self._update_traffic_key <18> <19> # packet spaces <20> self.cryptos = { <21> tls.Epoch.INITIAL: CryptoPair(), <22> tls.Epoch.HANDSHAKE: CryptoPair(), <23> tls.Epoch.ONE_RTT: CryptoPair(), <24> } <25> self.send_buffer = { <26> tls.Epoch.INITIAL: Buffer(capacity=4096), <27> tls.Epoch.HANDSHAKE: Buffer(capacity=4096), <28> tls.Epoch.ONE_RTT: Buffer(capacity=4096), <29> } <30> self.spaces = { <31> tls.Epoch.INITIAL: QuicPacketSpace(), <32> tls.Epoch.HANDSHAKE: QuicPacketSpace(), <33> tls.Epoch.ONE_RTT: QuicPacketSpace(), <34> } <35> self.streams[tls.Epoch.INITIAL] = QuicStream() <36> </s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _initialize(self, peer_cid: bytes) -> None: # offset: 1 self.streams[tls.Epoch.ONE_RTT] = QuicStream() self.cryptos[tls.Epoch.INITIAL].setup_initial( cid=peer_cid, is_client=self.is_client ) self.packet_number = 0 ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.connection QuicPacketSpace() at: aioquic.connection.QuicConnection _serialize_transport_parameters() -> bytes _update_traffic_key(direction: tls.Direction, epoch: tls.Epoch, secret: bytes) -> None at: aioquic.connection.QuicConnection.__init__ self.alpn_protocols = alpn_protocols self.certificate = certificate self.is_client = is_client self.private_key = private_key self.server_name = server_name self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} ) self._session_ticket = session_ticket self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._stream_handler = lambda r, w: None self._stream_handler = stream_handler at: aioquic.connection.QuicConnection._get_or_create_stream stream = self.streams[stream_id] = QuicStream( connection=self, stream_id=stream_id, max_stream_data_local=max_stream_data_local, max_stream_data_remote=max_stream_data_remote, ) stream = self.streams.get(stream_id, None) max_stream_data_local = self._local_max_stream_data_uni max_stream_data_local = self._local_max_stream_data_bidi_remote max_stream_data_remote = 0 max_stream_data_remote = self._remote_max_stream_data_bidi_local ===========unchanged ref 1=========== at: aioquic.crypto CryptoPair() at: aioquic.stream QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0) at: aioquic.stream.QuicStream.__init__ self.reader = asyncio.StreamReader() self.reader = None self.writer = None self.writer = asyncio.StreamWriter(self, None, self.reader, None) at: aioquic.tls Epoch() ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None) at: aioquic.tls.Context.__init__ self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, bytes], None ] = lambda d, e, s: None ===========changed ref 0=========== # module: aioquic.connection def get_epoch(packet_type: int) -> tls.Epoch: if packet_type == PACKET_TYPE_INITIAL: return tls.Epoch.INITIAL + elif packet_type == PACKET_TYPE_ZERO_RTT: + return tls.Epoch.ZERO_RTT elif packet_type == PACKET_TYPE_HANDSHAKE: return tls.Epoch.HANDSHAKE else: return tls.Epoch.ONE_RTT ===========changed ref 1=========== # module: aioquic.packet PACKET_LONG_HEADER = 0x80 PACKET_FIXED_BIT = 0x40 PACKET_SPIN_BIT = 0x20 PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 + PACKET_TYPE_ZERO_RTT = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x10 - PACKET_TYPE_0RTT = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x10 PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20 PACKET_TYPE_RETRY = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x30 PACKET_TYPE_MASK = 0xF0 PACKET_NUMBER_MAX_SIZE = 4 PACKET_NUMBER_SEND_SIZE = 2 UINT_VAR_FORMATS = [ (pull_uint8, push_uint8, 0x3F), (pull_uint16, push_uint16, 0x3FFF), (pull_uint32, push_uint32, 0x3FFFFFFF), (pull_uint64, push_uint64, 0x3FFFFFFFFFFFFFFF), ] ===========changed ref 2=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: """ Handle an incoming datagram. """ # stop handling packets when closing if self.__state in [QuicConnectionState.CLOSING, QuicConnectionState.DRAINING]: return data = cast(bytes, data) buf = Buffer(data=data) while not buf.eof(): start_off = buf.tell() header = pull_quic_header(buf, host_cid_length=len(self.host_cid)) # check destination CID matches if self.is_client and header.destination_cid != self.host_cid: return # check protocol version if self.is_client and header.version == QuicProtocolVersion.NEGOTIATION: # version negotiation versions = [] while not buf.eof(): versions.append(pull_uint32(buf)) common = set(self.supported_versions).intersection(versions) if not common: self._logger.error("Could not find a common protocol version") return self._version = QuicProtocolVersion(max(common)) self._version_negotiation_count += 1 self._logger.info("Retrying with %s", self._version) self._connect() return elif ( header.version is not None and header.version not in self.supported_versions ): # unsupported version return if self.is_client and header.packet_type == PACKET_TYPE_RETRY: # stateless retry if ( header.destination_cid == self.host_cid and header.original_destination_cid == self.peer_cid and not self._stateless_retry_count ): self._original_connection_id = self.peer_cid self.peer_cid = header.source_cid self.peer_token = header.token self</s>
aioquic.tls/pull_encrypted_extensions
Modified
aiortc~aioquic
3587e98245e61472c74576bfb09e41c5e11aa832
[tls] parse and serialize EncryptedExtensions.early_data
<10>:<add> elif extension_type == ExtensionType.EARLY_DATA: <add> extensions.early_data = True
# module: aioquic.tls def pull_encrypted_extensions(buf: Buffer) -> EncryptedExtensions: <0> extensions = EncryptedExtensions() <1> <2> assert pull_uint8(buf) == HandshakeType.ENCRYPTED_EXTENSIONS <3> with pull_block(buf, 3): <4> <5> def pull_extension(buf: Buffer) -> None: <6> extension_type = pull_uint16(buf) <7> extension_length = pull_uint16(buf) <8> if extension_type == ExtensionType.ALPN: <9> extensions.alpn_protocol = pull_list(buf, 2, pull_alpn_protocol)[0] <10> else: <11> extensions.other_extensions.append( <12> (extension_type, pull_bytes(buf, extension_length)) <13> ) <14> <15> pull_list(buf, 2, pull_extension) <16> <17> return extensions <18>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) pull_bytes(buf: Buffer, length: int) -> bytes pull_uint8(buf: Buffer) -> int pull_uint16(buf: Buffer) -> int at: aioquic.tls ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) pull_block(buf: Buffer, capacity: int) -> Generator pull_list(buf: Buffer, capacity: int, func: Callable[[Buffer], T]) -> List[T] pull_alpn_protocol(buf: Buffer) -> str EncryptedExtensions(alpn_protocol: Optional[str]=None, early_data: Optional[bool]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) at: aioquic.tls.EncryptedExtensions alpn_protocol: Optional[str] = None early_data: Optional[bool] = None other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) ===========changed ref 0=========== # module: aioquic.tls @dataclass class EncryptedExtensions: alpn_protocol: Optional[str] = None + early_data: Optional[bool] = None other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)
aioquic.tls/push_encrypted_extensions
Modified
aiortc~aioquic
3587e98245e61472c74576bfb09e41c5e11aa832
[tls] parse and serialize EncryptedExtensions.early_data
<7>:<add> if extensions.early_data: <add> with push_extension(buf, ExtensionType.EARLY_DATA): <add> pass <add>
# module: aioquic.tls def push_encrypted_extensions(buf: Buffer, extensions: EncryptedExtensions) -> None: <0> push_uint8(buf, HandshakeType.ENCRYPTED_EXTENSIONS) <1> with push_block(buf, 3): <2> with push_block(buf, 2): <3> if extensions.alpn_protocol is not None: <4> with push_extension(buf, ExtensionType.ALPN): <5> push_list(buf, 2, push_alpn_protocol, [extensions.alpn_protocol]) <6> <7> for extension_type, extension_value in extensions.other_extensions: <8> with push_extension(buf, extension_type): <9> push_bytes(buf, extension_value) <10>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) push_uint8(buf: Buffer, v: int) -> None at: aioquic.tls ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) push_block(buf: Buffer, capacity: int) -> Generator push_list(buf: Buffer, capacity: int, func: Callable[[Buffer, T], None], values: Sequence[T]) -> None push_extension(buf: Buffer, extension_type: int) -> Generator push_alpn_protocol(buf: Buffer, protocol: str) -> None EncryptedExtensions(alpn_protocol: Optional[str]=None, early_data: Optional[bool]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) at: aioquic.tls.EncryptedExtensions alpn_protocol: Optional[str] = None at: aioquic.tls.pull_encrypted_extensions extensions = EncryptedExtensions() ===========changed ref 0=========== # module: aioquic.tls @dataclass class EncryptedExtensions: alpn_protocol: Optional[str] = None + early_data: Optional[bool] = None other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) ===========changed ref 1=========== # module: aioquic.tls def pull_encrypted_extensions(buf: Buffer) -> EncryptedExtensions: extensions = EncryptedExtensions() assert pull_uint8(buf) == HandshakeType.ENCRYPTED_EXTENSIONS with pull_block(buf, 3): def pull_extension(buf: Buffer) -> None: extension_type = pull_uint16(buf) extension_length = pull_uint16(buf) if extension_type == ExtensionType.ALPN: extensions.alpn_protocol = pull_list(buf, 2, pull_alpn_protocol)[0] + elif extension_type == ExtensionType.EARLY_DATA: + extensions.early_data = True else: extensions.other_extensions.append( (extension_type, pull_bytes(buf, extension_length)) ) pull_list(buf, 2, pull_extension) return extensions
aioquic.tls/Context.__init__
Modified
aiortc~aioquic
2b34d727cd73867ea5220ca97f75c7f8923c6c09
[tls] add early data key generation
<8>:<add> self.received_extensions: Optional[List[Extension]] = None <del> self.received_extensions: List[Extension] = []
# module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): <0> self.alpn_negotiated: Optional[str] = None <1> self.alpn_protocols: Optional[List[str]] = None <2> self.certificate: Optional[x509.Certificate] = None <3> self.certificate_private_key: Optional[ <4> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] <5> ] = None <6> self.handshake_extensions: List[Extension] = [] <7> self.key_schedule: Optional[KeySchedule] = None <8> self.received_extensions: List[Extension] = [] <9> self.session_ticket: Optional[SessionTicket] = None <10> self.server_name: Optional[str] = None <11> <12> # callbacks <13> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None <14> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None <15> self.update_traffic_key_cb: Callable[ <16> [Direction, Epoch, bytes], None <17> ] = lambda d, e, s: None <18> <19> # supported parameters <20> self._cipher_suites = [ <21> CipherSuite.AES_256_GCM_SHA384, <22> CipherSuite.AES_128_GCM_SHA256, <23> CipherSuite.CHACHA20_POLY1305_SHA256, <24> ] <25> self._compression_methods = [CompressionMethod.NULL] <26> self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] <27> self._signature_algorithms = [ <28> SignatureAlgorithm.RSA_PSS_RSAE_SHA256, <29> SignatureAlgorithm.ECDSA_SECP256R1_SHA256, <30> SignatureAlgorithm.RSA_PKCS1_SHA256, <31> SignatureAlgorithm.RSA_PKCS1_SHA1, <32> ] <33> </s>
===========below chunk 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========unchanged ref 0=========== at: aioquic.tls TLS_VERSION_1_3 = 0x0304 Direction() Epoch() State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeyExchangeMode(x: Union[str, bytes, bytearray], base: int) KeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Extension = Tuple[int, bytes] KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None) SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol ===========unchanged ref 1=========== self.received_extensions = encrypted_extensions.other_extensions at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) self._session_resumed = True at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) self.client_random = peer_hello.random self.session_id = peer_hello.session_id self.received_extensions = peer_hello.other_extensions self.key_schedule = KeySchedule(cipher_suite) self._session_resumed = True self._x25519_private_key = x25519.X25519PrivateKey.generate() self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) at: aioquic.tls.Context._set_state self.state = state ===========unchanged ref 2=========== at: aioquic.tls.Context._setup_traffic_protection self._enc_key = key self._dec_key = key at: aioquic.tls.Context.handle_message self._receive_buffer += input_data self._receive_buffer = self._receive_buffer[message_length:] at: logging Logger(name: str, level: _Level=...) LoggerAdapter(logger: Logger, extra: Mapping[str, Any]) at: os urandom(size: int, /) -> bytes at: typing Callable = _CallableType(collections.abc.Callable, 2) List = _alias(list, 1, inst=False, name='List')
aioquic.tls/Context._client_send_hello
Modified
aiortc~aioquic
2b34d727cd73867ea5220ca97f75c7f8923c6c09
[tls] add early data key generation
# module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: <0> key_share: List[KeyShareEntry] = [] <1> supported_groups: List[Group] = [] <2> <3> if Group.SECP256R1 in self._supported_groups: <4> self._ec_private_key = ec.generate_private_key( <5> GROUP_TO_CURVE[Group.SECP256R1](), default_backend() <6> ) <7> key_share.append(encode_public_key(self._ec_private_key.public_key())) <8> supported_groups.append(Group.SECP256R1) <9> <10> if Group.X25519 in self._supported_groups: <11> self._x25519_private_key = x25519.X25519PrivateKey.generate() <12> key_share.append(encode_public_key(self._x25519_private_key.public_key())) <13> supported_groups.append(Group.X25519) <14> <15> assert len(key_share), "no key share entries" <16> <17> hello = ClientHello( <18> random=self.client_random, <19> session_id=self.session_id, <20> cipher_suites=self._cipher_suites, <21> compression_methods=self._compression_methods, <22> alpn_protocols=self.alpn_protocols, <23> key_exchange_modes=self._key_exchange_modes, <24> key_share=key_share, <25> server_name=self.server_name, <26> signature_algorithms=self._signature_algorithms, <27> supported_groups=supported_groups, <28> supported_versions=self._supported_versions, <29> other_extensions=self.handshake_extensions, <30> ) <31> <32> # PSK <33> if self.session_ticket and self.session_ticket.is_valid: <34> self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) <35> self._key_schedule_psk.</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: # offset: 1 binder_key = self._key_schedule_psk.derive_secret(b"res binder") binder_length = self._key_schedule_psk.algorithm.digest_size # serialize hello without binder tmp_buf = Buffer(capacity=1024) hello.pre_shared_key = OfferedPsks( identities=[ (self.session_ticket.ticket, self.session_ticket.obfuscated_age) ], binders=[bytes(binder_length)], ) push_client_hello(tmp_buf, hello) # calculate binder hash_offset = tmp_buf.tell() - binder_length - 3 self._key_schedule_psk.update_hash(tmp_buf.data_slice(0, hash_offset)) binder = self._key_schedule_psk.finished_verify_data(binder_key) hello.pre_shared_key.binders[0] = binder self._key_schedule_psk.update_hash( tmp_buf.data_slice(hash_offset, hash_offset + 3) + binder ) self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) self._key_schedule_proxy.extract(None) with push_message(self._key_schedule_proxy, output_buf): push_client_hello(output_buf, hello) self._set_state(State.CLIENT_EXPECT_SERVER_HELLO) ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.buffer.Buffer data_slice(start: int, end: int) -> bytes tell() -> int at: aioquic.tls Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeyShareEntry = Tuple[Group, bytes] OfferedPsks(identities: List[PskIdentity], binders: List[bytes]) ClientHello(random: bytes, session_id: bytes, cipher_suites: List[CipherSuite], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_exchange_modes: Optional[List[KeyExchangeMode]]=None, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list)) push_client_hello(buf: Buffer, hello: ClientHello) -> None KeySchedule(cipher_suite: CipherSuite) GROUP_TO_CURVE = { Group.SECP256R1: ec.SECP256R1, Group.SECP384R1: ec.SECP384R1, Group.SECP521R1: ec.SECP521R1, } encode_public_key(public_key: Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey]) -> KeyShareEntry at: aioquic.tls.ClientHello random: bytes session_id: bytes cipher_suites: List[CipherSuite] ===========unchanged ref 1=========== compression_methods: List[CompressionMethod] alpn_protocols: Optional[List[str]] = None early_data: bool = False key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) at: aioquic.tls.Context.__init__ self.alpn_protocols: Optional[List[str]] = None self.handshake_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_psk: Optional[KeySchedule] = None self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None ===========unchanged ref 2=========== self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None self.client_random = None self.client_random = os.urandom(32) self.session_id = None self.session_id = os.urandom(32) at: aioquic.tls.Context._server_handle_hello self.client_random = peer_hello.random self.session_id = peer_hello.session_id self._x25519_private_key = x25519.X25519PrivateKey.generate() self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) at: aioquic.tls.KeySchedule finished_verify_data(secret: bytes) -> bytes derive_secret(label: bytes) -> bytes extract(key_material: Optional[bytes]=None) -> None update_hash(data: bytes) -> None at: aioquic.tls.KeySchedule.__init__ self.algorithm = cipher_suite_hash(cipher_suite) at: aioquic.tls.OfferedPsks identities: List[PskIdentity] binders: List[bytes] at: aioquic.tls.SessionTicket age_add: int cipher_suite: CipherSuite not_valid_after: datetime.datetime not_valid_before: datetime.datetime resumption_secret: bytes server_name: str ticket: bytes max_early_data_size: Optional[int] = None at: typing List = _alias(list, 1, inst=False, name='List')
aioquic.connection/QuicConnection.__init__
Modified
aiortc~aioquic
2b34d727cd73867ea5220ca97f75c7f8923c6c09
[tls] add early data key generation
<s>[List[str]] = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, session_ticket: Optional[tls.SessionTicket] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: <0> if is_client: <1> assert ( <2> original_connection_id is None <3> ), "Cannot set original_connection_id for a client" <4> else: <5> assert certificate is not None, "SSL certificate is required for a server" <6> assert private_key is not None, "SSL private key is required for a server" <7> <8> self.alpn_protocols = alpn_protocols <9> self.certificate = certificate <10> self.is_client = is_client <11> self.host_cid = os.urandom(8) <12> self.peer_cid = os.urandom(8) <13> self.peer_cid_set = False <14> self.peer_token = b"" <15> self.private_key = private_key <16> self.secrets_log_file = secrets_log_file <17> self.server_name = server_name <18> self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} <19> <20> # counters for debugging <21> self._stateless_retry_count = 0 <22> self._version_negotiation_count = 0 <23> <24> self._loop = asyncio.get_event_loop() <25> self.__close: Optional[Dict] = None <26> self.__connected = asyncio.Event() <27> self.__epoch = tls.Epoch.INITIAL <28> self._local_idle_timeout = 60000 # milliseconds <29> self._local_max_data = 1048576 <30> self._local_max_data_used = 0 <31> self._local_max_stream_data</s>
===========below chunk 0=========== <s> = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, session_ticket: Optional[tls.SessionTicket] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 1 self._local_max_stream_data_bidi_remote = 1048576 self._local_max_stream_data_uni = 1048576 self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} ) self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._ping_packet_number: Optional[int] = None self._ping_waiter: Optional[asyncio.Future[None]] = None self._remote_idle_timeout = 0 # milliseconds self._remote_max_data = 0 self._remote_max_data_used = 0 self._remote_max_stream_data_bidi_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._session_ticket = session_ticket self._spin_bit = False self._spin_bit_peer = False self._spin_highest_pn = 0 self.__send_pending_task: Optional[asyncio.Handle] = None self.__state = QuicConnectionState.FIRSTFLIGHT self._transport: Optional[asyncio.DatagramTransport] = None</s> ===========below chunk 1=========== <s> = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, session_ticket: Optional[tls.SessionTicket] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 2 <s> self.__state = QuicConnectionState.FIRSTFLIGHT self._transport: Optional[asyncio.DatagramTransport] = None self._version: Optional[int] = None # callbacks self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None # frame handlers self.__frame_handlers = [ (self._handle_padding_frame, EPOCHS("IZHO")), (self._handle_padding_frame, EPOCHS("ZO")), (self._handle_ack_frame, EPOCHS("IHO")), (self._handle_ack_frame, EPOCHS("IHO")), (self._handle_reset_stream_frame, EPOCHS("ZO")), (self._handle_stop_sending_frame, EPOCHS("ZO")), (self._handle_crypto_frame, EPOCHS("IHO")), (self._handle_new_token_frame, EPOCHS("O")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), </s> ===========below chunk 2=========== <s> = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, session_ticket: Optional[tls.SessionTicket] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 3 <s>self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_max_data_frame, EPOCHS("ZO")), (self._handle_max_stream_data_frame, EPOCHS("ZO")), (self._handle_max_streams_bidi_frame, EPOCHS("ZO")), (self._handle_max_streams_uni_frame, EPOCHS("ZO")), (self._handle_data_blocked_frame, EPOCHS("ZO")), (self._handle_stream_data_blocked_frame, EPOCHS("ZO")), (self._handle_streams_blocked_frame, EPOCHS("ZO")), (self._handle_streams_blocked_frame, EPOCHS("ZO")), (self._handle_new_connection_id_frame, EPOCHS("ZO")), (self._handle_retire_connection_id_frame, EPOCHS("O")), (self._handle_path_challenge_frame, EPOCHS("ZO")), (self._handle_path_response_frame,</s> ===========below chunk 3=========== <s> = None, original_connection_id: Optional[bytes] = None, secrets_log_file: TextIO = None, server_name: Optional[str] = None, session_ticket: Optional[tls.SessionTicket] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: # offset: 4 <s>S("O")), (self._handle_connection_close_frame, EPOCHS("IZHO")), (self._handle_connection_close_frame, EPOCHS("ZO")), ]
aioquic.connection/QuicConnection.datagram_received
Modified
aiortc~aioquic
2b34d727cd73867ea5220ca97f75c7f8923c6c09
[tls] add early data key generation
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: <0> """ <1> Handle an incoming datagram. <2> """ <3> # stop handling packets when closing <4> if self.__state in [QuicConnectionState.CLOSING, QuicConnectionState.DRAINING]: <5> return <6> <7> data = cast(bytes, data) <8> buf = Buffer(data=data) <9> while not buf.eof(): <10> start_off = buf.tell() <11> header = pull_quic_header(buf, host_cid_length=len(self.host_cid)) <12> <13> # check destination CID matches <14> if self.is_client and header.destination_cid != self.host_cid: <15> return <16> <17> # check protocol version <18> if self.is_client and header.version == QuicProtocolVersion.NEGOTIATION: <19> # version negotiation <20> versions = [] <21> while not buf.eof(): <22> versions.append(pull_uint32(buf)) <23> common = set(self.supported_versions).intersection(versions) <24> if not common: <25> self._logger.error("Could not find a common protocol version") <26> return <27> self._version = QuicProtocolVersion(max(common)) <28> self._version_negotiation_count += 1 <29> self._logger.info("Retrying with %s", self._version) <30> self._connect() <31> return <32> elif ( <33> header.version is not None <34> and header.version not in self.supported_versions <35> ): <36> # unsupported version <37> return <38> <39> if self.is_client and header.packet_type == PACKET_TYPE_RETRY: <40> # stateless retry <41> if ( <42> header.destination_cid == self.host_cid <43> and header.original_destination_cid == self.peer_cid <44> and not self._stateless_retry_count </s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 self._original_connection_id = self.peer_cid self.peer_cid = header.source_cid self.peer_token = header.token self._stateless_retry_count += 1 self._logger.info("Performing stateless retry") self._connect() return network_path = self._find_network_path(addr) # server initialization if not self.is_client and self.__state == QuicConnectionState.FIRSTFLIGHT: assert ( header.packet_type == PACKET_TYPE_INITIAL ), "first packet must be INITIAL" self._network_paths = [network_path] self._version = QuicProtocolVersion(header.version) self._initialize(header.destination_cid) # decrypt packet encrypted_off = buf.tell() - start_off end_off = buf.tell() + header.rest_length pull_bytes(buf, header.rest_length) epoch = get_epoch(header.packet_type) crypto = self.cryptos[epoch] if not crypto.recv.is_valid(): return try: plain_header, plain_payload, packet_number = crypto.decrypt_packet( data[start_off:end_off], encrypted_off ) except CryptoError as exc: self._logger.warning(exc) return # discard initial keys if not self.is_client and epoch == tls.Epoch.HANDSHAKE: self.cryptos[tls.Epoch.INITIAL].teardown() # update state if not self.peer_cid_set: self.peer_cid = header.source_cid self.peer_cid_set = True if self.__state == QuicConnectionState.FIRSTFLIGHT: self._set_state(QuicConnectionState.</s> ===========below chunk 1=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 2 <s> if self.__state == QuicConnectionState.FIRSTFLIGHT: self._set_state(QuicConnectionState.CONNECTED) # update spin bit if ( not is_long_header(plain_header[0]) and packet_number > self._spin_highest_pn ): self._spin_bit_peer = get_spin_bit(plain_header[0]) if self.is_client: self._spin_bit = not self._spin_bit_peer else: self._spin_bit = self._spin_bit_peer self._spin_highest_pn = packet_number # handle payload context = QuicReceiveContext(epoch=epoch, network_path=network_path) try: is_ack_only, is_probing = self._payload_received(context, plain_payload) except QuicConnectionError as exc: self._logger.warning(exc) self.close( error_code=exc.error_code, frame_type=exc.frame_type, reason_phrase=exc.reason_phrase, ) return # update network path if not network_path.is_validated and epoch == tls.Epoch.HANDSHAKE: self._logger.info( "Network path %s validated by handshake", network_path.addr ) network_path.is_validated = True network_path.bytes_received += buf.tell() - start_off if network_path not in self._network_paths: self._network_paths.append(network_path) idx = self._network_paths.index(network_path) if idx and not is_probing: </s> ===========below chunk 2=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 3 <s>logger.info("Network path %s promoted", network_path.addr) self._network_paths.pop(idx) self._network_paths.insert(0, network_path) # record packet as received if epoch == tls.Epoch.ZERO_RTT: space = self.spaces[tls.Epoch.ONE_RTT] else: space = self.spaces[epoch] space.ack_queue.add(packet_number) if not is_ack_only: space.ack_required = True self._send_pending() ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) pull_bytes(buf: Buffer, length: int) -> bytes pull_uint32(buf: Buffer) -> int at: aioquic.buffer.Buffer eof() -> bool tell() -> int at: aioquic.connection NetworkAddress = Any get_epoch(packet_type: int) -> tls.Epoch QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) QuicConnectionState() QuicReceiveContext(epoch: tls.Epoch, network_path: QuicNetworkPath) at: aioquic.connection.QuicConnection supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20] close(error_code: int=QuicErrorCode.NO_ERROR, frame_type: Optional[int]=None, reason_phrase: str="") -> None _connect() -> None _find_network_path(addr: NetworkAddress) -> QuicNetworkPath _initialize(peer_cid: bytes) -> None _payload_received(context: QuicReceiveContext, plain: bytes) -> Tuple[bool, bool] _payload_received(self, context: QuicReceiveContext, plain: bytes) -> Tuple[bool, bool] _set_state(state: QuicConnectionState) -> None at: aioquic.connection.QuicConnection.__init__ self.is_client = is_client self.host_cid = os.urandom(8) self.peer_cid = os.urandom(8) self.peer_cid_set = False self.peer_token = b"" self._stateless_retry_count = 0 self._version_negotiation_count = 0 self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} )
aioquic.connection/QuicConnection._handle_crypto_frame
Modified
aiortc~aioquic
2b34d727cd73867ea5220ca97f75c7f8923c6c09
[tls] add early data key generation
<17>:<add> # parse transport parameters <add> if ( <add> not self._parameters_received <add> and self.tls.received_extensions is not None <add> ): <add> for ext_type, ext_data in self.tls.received_extensions: <add> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: <add> self._parse_transport_parameters(ext_data) <add> break <add> self._parameters_received = True <add> <22>:<del> # parse transport parameters <23>:<del> for ext_type, ext_data in self.tls.received_extensions: <24>:<del> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: <25>:<del> self._parse_transport_parameters(ext_data) <26>:<del> break <28>:<del>
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a CRYPTO frame. <2> """ <3> stream = self.streams[context.epoch] <4> stream.add_frame(packet.pull_crypto_frame(buf)) <5> data = stream.pull_data() <6> if data: <7> # pass data to TLS layer <8> try: <9> self.tls.handle_message(data, self.send_buffer) <10> except tls.Alert as exc: <11> raise QuicConnectionError( <12> error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description), <13> frame_type=QuicFrameType.CRYPTO, <14> reason_phrase=str(exc), <15> ) <16> <17> # update current epoch <18> if self.__epoch == tls.Epoch.HANDSHAKE and self.tls.state in [ <19> tls.State.CLIENT_POST_HANDSHAKE, <20> tls.State.SERVER_POST_HANDSHAKE, <21> ]: <22> # parse transport parameters <23> for ext_type, ext_data in self.tls.received_extensions: <24> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: <25> self._parse_transport_parameters(ext_data) <26> break <27> self.__epoch = tls.Epoch.ONE_RTT <28> <29> # wakeup waiter <30> if not self.__connected.is_set(): <31> self.__connected.set() <32> elif self.__epoch == tls.Epoch.INITIAL: <33> self.__epoch = tls.Epoch.HANDSHAKE <34>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.connection QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) QuicReceiveContext(epoch: tls.Epoch, network_path: QuicNetworkPath) at: aioquic.connection.QuicConnection _parse_transport_parameters(data: bytes) -> None at: aioquic.connection.QuicConnection.__init__ self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {} self.__epoch = tls.Epoch.INITIAL self._parameters_received = False at: aioquic.connection.QuicConnection._handle_crypto_frame self.__epoch = tls.Epoch.ONE_RTT self.__epoch = tls.Epoch.HANDSHAKE at: aioquic.connection.QuicConnection._initialize self.tls = tls.Context(is_client=self.is_client, logger=self._logger) self.send_buffer = { tls.Epoch.INITIAL: Buffer(capacity=4096), tls.Epoch.HANDSHAKE: Buffer(capacity=4096), tls.Epoch.ONE_RTT: Buffer(capacity=4096), } at: aioquic.connection.QuicReceiveContext epoch: tls.Epoch at: aioquic.packet QuicErrorCode(x: Union[str, bytes, bytearray], base: int) QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) pull_crypto_frame(buf: Buffer) -> QuicStreamFrame at: aioquic.stream.QuicStream add_frame(frame: QuicStreamFrame) -> None pull_data() -> bytes ===========unchanged ref 1=========== at: aioquic.tls Alert(*args: object) Epoch() State() ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: aioquic.tls.Alert description: AlertDescription at: aioquic.tls.Context handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None at: aioquic.tls.Context.__init__ self.received_extensions: List[Extension] = [] self.state = State.CLIENT_HANDSHAKE_START self.state = State.SERVER_EXPECT_CLIENT_HELLO at: aioquic.tls.Context._client_handle_encrypted_extensions self.received_extensions = encrypted_extensions.other_extensions at: aioquic.tls.Context._server_handle_hello self.received_extensions = peer_hello.other_extensions at: aioquic.tls.Context._set_state self.state = state ===========changed ref 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: """ Handle an incoming datagram. """ # stop handling packets when closing if self.__state in [QuicConnectionState.CLOSING, QuicConnectionState.DRAINING]: return data = cast(bytes, data) buf = Buffer(data=data) while not buf.eof(): start_off = buf.tell() header = pull_quic_header(buf, host_cid_length=len(self.host_cid)) # check destination CID matches if self.is_client and header.destination_cid != self.host_cid: return # check protocol version if self.is_client and header.version == QuicProtocolVersion.NEGOTIATION: # version negotiation versions = [] while not buf.eof(): versions.append(pull_uint32(buf)) common = set(self.supported_versions).intersection(versions) if not common: self._logger.error("Could not find a common protocol version") return self._version = QuicProtocolVersion(max(common)) self._version_negotiation_count += 1 self._logger.info("Retrying with %s", self._version) self._connect() return elif ( header.version is not None and header.version not in self.supported_versions ): # unsupported version return if self.is_client and header.packet_type == PACKET_TYPE_RETRY: # stateless retry if ( header.destination_cid == self.host_cid and header.original_destination_cid == self.peer_cid and not self._stateless_retry_count ): self._original_connection_id = self.peer_cid self.peer_cid = header.source_cid self.peer_token = header.token self</s> ===========changed ref 1=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 <s>peer_cid self.peer_cid = header.source_cid self.peer_token = header.token self._stateless_retry_count += 1 self._logger.info("Performing stateless retry") self._connect() return network_path = self._find_network_path(addr) # server initialization if not self.is_client and self.__state == QuicConnectionState.FIRSTFLIGHT: assert ( header.packet_type == PACKET_TYPE_INITIAL ), "first packet must be INITIAL" self._network_paths = [network_path] self._version = QuicProtocolVersion(header.version) self._initialize(header.destination_cid) # decrypt packet encrypted_off = buf.tell() - start_off end_off = buf.tell() + header.rest_length pull_bytes(buf, header.rest_length) epoch = get_epoch(header.packet_type) crypto = self.cryptos[epoch] if not crypto.recv.is_valid(): return try: plain_header, plain_payload, packet_number = crypto.decrypt_packet( data[start_off:end_off], encrypted_off ) except CryptoError as exc: self._logger.warning(exc) return # discard initial keys if not self.is_client and epoch == tls.Epoch.HANDSHAKE: self.cryptos[tls.Epoch.INITIAL].teardown() # update state if not self.peer_cid_set: self.peer_cid = header.source_cid self.peer_cid_set = True if self.__state ==</s>
aioquic.connection/QuicConnection._payload_received
Modified
aiortc~aioquic
2b34d727cd73867ea5220ca97f75c7f8923c6c09
[tls] add early data key generation
<0>:<add> """ <add> Handle a QUIC packet payload. <add> """ <26>:<del> try: <27>:<del> frame_handler(context, frame_type, buf) <28>:<del> except BufferReadError: <29>:<del> raise QuicConnectionError( <30>:<del> error_code=QuicErrorCode.FRAME_ENCODING_ERROR, <31>:<del> frame_type=frame_type, <32>:<del> reason_phrase="Failed to parse frame", <33>:<add> if frame_type != QuicFrameType.PADDING: <add> self._logger.debug( <add> "[%s] handling frame type %s", context.epoch, frame_type <34>:<add> try: <add> frame_handler(context, frame_type, buf) <add> except BufferReadError: <add> raise QuicConnectionError( <add> error_code=QuicErrorCode.FRAME_ENCODING_ERROR, <add> frame_type=frame_type, <add> reason_phrase="Failed to parse frame", <add> )
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _payload_received( self, context: QuicReceiveContext, plain: bytes ) -> Tuple[bool, bool]: <0> buf = Buffer(data=plain) <1> <2> is_ack_only = True <3> is_probing = None <4> while not buf.eof(): <5> frame_type = pull_uint_var(buf) <6> <7> # check frame type is known <8> try: <9> frame_handler, frame_epochs = self.__frame_handlers[frame_type] <10> except IndexError: <11> raise QuicConnectionError( <12> error_code=QuicErrorCode.PROTOCOL_VIOLATION, <13> frame_type=frame_type, <14> reason_phrase="Unknown frame type", <15> ) <16> <17> # check frame is allowed for the epoch <18> if context.epoch not in frame_epochs: <19> raise QuicConnectionError( <20> error_code=QuicErrorCode.PROTOCOL_VIOLATION, <21> frame_type=frame_type, <22> reason_phrase="Unexpected frame type", <23> ) <24> <25> # handle the frame <26> try: <27> frame_handler(context, frame_type, buf) <28> except BufferReadError: <29> raise QuicConnectionError( <30> error_code=QuicErrorCode.FRAME_ENCODING_ERROR, <31> frame_type=frame_type, <32> reason_phrase="Failed to parse frame", <33> ) <34> <35> # update ACK only / probing flags <36> if frame_type not in [ <37> QuicFrameType.ACK, <38> QuicFrameType.ACK_ECN, <39> QuicFrameType.PADDING, <40> ]: <41> is_ack_only = False <42> <43> if frame_type not in [ <44> QuicFrameType.PATH_CHALLENGE, <45> QuicFrameType.PATH_RESPONSE, <46> QuicFrameType.PADDING, <47> QuicFrameType.NEW_CONNECTION_ID, <48> ]: </s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _payload_received( self, context: QuicReceiveContext, plain: bytes ) -> Tuple[bool, bool]: # offset: 1 elif is_probing is None: is_probing = True self._push_crypto_data() return is_ack_only, bool(is_probing) ===========unchanged ref 0=========== at: aioquic.buffer BufferReadError(*args: object) Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.buffer.Buffer eof() -> bool at: aioquic.connection QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) QuicReceiveContext(epoch: tls.Epoch, network_path: QuicNetworkPath) at: aioquic.connection.QuicConnection.__init__ self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} ) ===========unchanged ref 1=========== self.__frame_handlers = [ (self._handle_padding_frame, EPOCHS("IZHO")), (self._handle_padding_frame, EPOCHS("ZO")), (self._handle_ack_frame, EPOCHS("IHO")), (self._handle_ack_frame, EPOCHS("IHO")), (self._handle_reset_stream_frame, EPOCHS("ZO")), (self._handle_stop_sending_frame, EPOCHS("ZO")), (self._handle_crypto_frame, EPOCHS("IHO")), (self._handle_new_token_frame, EPOCHS("O")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_max_data_frame, EPOCHS("ZO")), (self._handle_max_stream_data_frame, EPOCHS("ZO")), (self._handle_max_streams_bidi_frame, EPOCHS("ZO")), (self._handle_max_streams_uni_frame, EPOCHS("ZO")), (self._handle_data_blocked_frame, EPOCHS("ZO")), (self._handle_stream_data_blocked_frame, EPOCHS("ZO")), (self._handle_streams_blocked_frame, EPOCHS("ZO")), (self._handle_streams_blocked_frame, EPOCHS("ZO")), (self._handle_new_connection_id_frame,</s> ===========unchanged ref 2=========== at: aioquic.connection.QuicReceiveContext epoch: tls.Epoch at: aioquic.packet QuicErrorCode(x: Union[str, bytes, bytearray], base: int) QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_uint_var(buf: Buffer) -> int QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: logging.LoggerAdapter debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None at: typing Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') ===========changed ref 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a CRYPTO frame. """ stream = self.streams[context.epoch] stream.add_frame(packet.pull_crypto_frame(buf)) data = stream.pull_data() if data: # pass data to TLS layer try: self.tls.handle_message(data, self.send_buffer) except tls.Alert as exc: raise QuicConnectionError( error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description), frame_type=QuicFrameType.CRYPTO, reason_phrase=str(exc), ) + # parse transport parameters + if ( + not self._parameters_received + and self.tls.received_extensions is not None + ): + for ext_type, ext_data in self.tls.received_extensions: + if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: + self._parse_transport_parameters(ext_data) + break + self._parameters_received = True + # update current epoch if self.__epoch == tls.Epoch.HANDSHAKE and self.tls.state in [ tls.State.CLIENT_POST_HANDSHAKE, tls.State.SERVER_POST_HANDSHAKE, ]: - # parse transport parameters - for ext_type, ext_data in self.tls.received_extensions: - if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: - self._parse_transport_parameters(ext_data) - break self.__epoch = tls.Epoch.ONE_RTT - # wakeup waiter if not self.__connected.is_set(): self.__connected.set() elif self.__epoch == tls.Epoch.INITIAL: self.__epoch =</s> ===========changed ref 1=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: # offset: 1 <s>_set(): self.__connected.set() elif self.__epoch == tls.Epoch.INITIAL: self.__epoch = tls.Epoch.HANDSHAKE
aioquic.tls/Context.__init__
Modified
aiortc~aioquic
5ce021bf7d21195e8398b6b4146b0e25759be3fb
[tls] pass cipher suite to app
<16>:<add> [Direction, Epoch, CipherSuite, bytes], None <del> [Direction, Epoch, bytes], None <17>:<add> ] = lambda d, e, c, s: None <del> ] = lambda d, e, s: None
# module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): <0> self.alpn_negotiated: Optional[str] = None <1> self.alpn_protocols: Optional[List[str]] = None <2> self.certificate: Optional[x509.Certificate] = None <3> self.certificate_private_key: Optional[ <4> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] <5> ] = None <6> self.handshake_extensions: List[Extension] = [] <7> self.key_schedule: Optional[KeySchedule] = None <8> self.received_extensions: Optional[List[Extension]] = None <9> self.session_ticket: Optional[SessionTicket] = None <10> self.server_name: Optional[str] = None <11> <12> # callbacks <13> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None <14> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None <15> self.update_traffic_key_cb: Callable[ <16> [Direction, Epoch, bytes], None <17> ] = lambda d, e, s: None <18> <19> # supported parameters <20> self._cipher_suites = [ <21> CipherSuite.AES_256_GCM_SHA384, <22> CipherSuite.AES_128_GCM_SHA256, <23> CipherSuite.CHACHA20_POLY1305_SHA256, <24> ] <25> self._compression_methods = [CompressionMethod.NULL] <26> self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] <27> self._signature_algorithms = [ <28> SignatureAlgorithm.RSA_PSS_RSAE_SHA256, <29> SignatureAlgorithm.ECDSA_SECP256R1_SHA256, <30> SignatureAlgorithm.RSA_PKCS1_SHA256, <31> SignatureAlgorithm.RSA_PKCS1_SHA1, <32> ]</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========unchanged ref 0=========== at: aioquic.tls TLS_VERSION_1_3 = 0x0304 Direction() Epoch() State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeyExchangeMode(x: Union[str, bytes, bytearray], base: int) KeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Extension = Tuple[int, bytes] KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None) SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol ===========unchanged ref 1=========== self.received_extensions = encrypted_extensions.other_extensions at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) self._session_resumed = True at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) self.client_random = peer_hello.random self.session_id = peer_hello.session_id self.received_extensions = peer_hello.other_extensions self.key_schedule = KeySchedule(cipher_suite) self._session_resumed = True self._x25519_private_key = x25519.X25519PrivateKey.generate() self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) at: aioquic.tls.Context._set_state self.state = state ===========unchanged ref 2=========== at: aioquic.tls.Context._setup_traffic_protection self._enc_key = key self._dec_key = key at: aioquic.tls.Context.handle_message self._receive_buffer += input_data self._receive_buffer = self._receive_buffer[message_length:] at: logging Logger(name: str, level: _Level=...) LoggerAdapter(logger: Logger, extra: Mapping[str, Any]) at: os urandom(size: int, /) -> bytes at: typing Callable = _CallableType(collections.abc.Callable, 2) List = _alias(list, 1, inst=False, name='List')
aioquic.tls/Context._client_send_hello
Modified
aiortc~aioquic
5ce021bf7d21195e8398b6b4146b0e25759be3fb
[tls] pass cipher suite to app
# module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: <0> key_share: List[KeyShareEntry] = [] <1> supported_groups: List[Group] = [] <2> <3> if Group.SECP256R1 in self._supported_groups: <4> self._ec_private_key = ec.generate_private_key( <5> GROUP_TO_CURVE[Group.SECP256R1](), default_backend() <6> ) <7> key_share.append(encode_public_key(self._ec_private_key.public_key())) <8> supported_groups.append(Group.SECP256R1) <9> <10> if Group.X25519 in self._supported_groups: <11> self._x25519_private_key = x25519.X25519PrivateKey.generate() <12> key_share.append(encode_public_key(self._x25519_private_key.public_key())) <13> supported_groups.append(Group.X25519) <14> <15> assert len(key_share), "no key share entries" <16> <17> hello = ClientHello( <18> random=self.client_random, <19> session_id=self.session_id, <20> cipher_suites=self._cipher_suites, <21> compression_methods=self._compression_methods, <22> alpn_protocols=self.alpn_protocols, <23> key_exchange_modes=self._key_exchange_modes, <24> key_share=key_share, <25> server_name=self.server_name, <26> signature_algorithms=self._signature_algorithms, <27> supported_groups=supported_groups, <28> supported_versions=self._supported_versions, <29> other_extensions=self.handshake_extensions, <30> ) <31> <32> # PSK <33> if self.session_ticket and self.session_ticket.is_valid: <34> self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) <35> self._key_schedule_psk.</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: # offset: 1 binder_key = self._key_schedule_psk.derive_secret(b"res binder") binder_length = self._key_schedule_psk.algorithm.digest_size # update hello if self.session_ticket.max_early_data_size is not None: hello.early_data = True hello.pre_shared_key = OfferedPsks( identities=[ (self.session_ticket.ticket, self.session_ticket.obfuscated_age) ], binders=[bytes(binder_length)], ) # serialize hello without binder tmp_buf = Buffer(capacity=1024) push_client_hello(tmp_buf, hello) # calculate binder hash_offset = tmp_buf.tell() - binder_length - 3 self._key_schedule_psk.update_hash(tmp_buf.data_slice(0, hash_offset)) binder = self._key_schedule_psk.finished_verify_data(binder_key) hello.pre_shared_key.binders[0] = binder self._key_schedule_psk.update_hash( tmp_buf.data_slice(hash_offset, hash_offset + 3) + binder ) # calculate early data key if hello.early_data: early_key = self._key_schedule_psk.derive_secret(b"c e traffic") self.update_traffic_key_cb(Direction.ENCRYPT, Epoch.ZERO_RTT, early_key) self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) self._key_schedule_proxy.extract(None) with push_message(self._key_schedule_proxy, output_buf): push_client_hello(output_buf, hello) self._set_state(State.CLIENT_EXPE</s> ===========below chunk 1=========== # module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: # offset: 2 <s>): push_client_hello(output_buf, hello) self._set_state(State.CLIENT_EXPECT_SERVER_HELLO) ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.buffer.Buffer data_slice(start: int, end: int) -> bytes tell() -> int at: aioquic.tls Direction() Epoch() Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeyShareEntry = Tuple[Group, bytes] OfferedPsks(identities: List[PskIdentity], binders: List[bytes]) ClientHello(random: bytes, session_id: bytes, cipher_suites: List[CipherSuite], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_exchange_modes: Optional[List[KeyExchangeMode]]=None, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list)) push_client_hello(buf: Buffer, hello: ClientHello) -> None KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) GROUP_TO_CURVE = { Group.SECP256R1: ec.SECP256R1, Group.SECP384R1: ec.SECP384R1, Group.SECP521R1: ec.SECP521R1, } encode_public_key(public_key: Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey]) -> KeyShareEntry at: aioquic.tls.ClientHello random: bytes ===========unchanged ref 1=========== session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] alpn_protocols: Optional[List[str]] = None early_data: bool = False key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) at: aioquic.tls.Context.__init__ self.alpn_protocols: Optional[List[str]] = None self.handshake_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1]
aioquic.tls/Context._client_handle_finished
Modified
aiortc~aioquic
5ce021bf7d21195e8398b6b4146b0e25759be3fb
[tls] pass cipher suite to app
<26>:<add> self.update_traffic_key_cb( <add> Direction.ENCRYPT, <add> Epoch.ONE_RTT, <add> self.key_schedule.cipher_suite, <add> self._enc_key, <add> ) <del> self.update_traffic_key_cb(Direction.ENCRYPT, Epoch.ONE_RTT, self._enc_key)
# module: aioquic.tls class Context: def _client_handle_finished(self, input_buf: Buffer, output_buf: Buffer) -> None: <0> finished = pull_finished(input_buf) <1> <2> # check verify data <3> expected_verify_data = self.key_schedule.finished_verify_data(self._dec_key) <4> assert finished.verify_data == expected_verify_data <5> self.key_schedule.update_hash(input_buf.data) <6> <7> # prepare traffic keys <8> assert self.key_schedule.generation == 2 <9> self.key_schedule.extract(None) <10> self._setup_traffic_protection( <11> Direction.DECRYPT, Epoch.ONE_RTT, b"s ap traffic" <12> ) <13> next_enc_key = self.key_schedule.derive_secret(b"c ap traffic") <14> <15> # send finished <16> with push_message(self.key_schedule, output_buf): <17> push_finished( <18> output_buf, <19> Finished( <20> verify_data=self.key_schedule.finished_verify_data(self._enc_key) <21> ), <22> ) <23> <24> # commit traffic key <25> self._enc_key = next_enc_key <26> self.update_traffic_key_cb(Direction.ENCRYPT, Epoch.ONE_RTT, self._enc_key) <27> <28> self._set_state(State.CLIENT_POST_HANDSHAKE) <29>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls Direction() Epoch() State() Finished(verify_data: bytes=b"") pull_finished(buf: Buffer) -> Finished push_finished(buf: Buffer, finished: Finished) -> None push_message(key_schedule: Union[KeySchedule, KeyScheduleProxy], buf: Buffer) -> Generator at: aioquic.tls.Context _setup_traffic_protection(direction: Direction, epoch: Epoch, label: bytes) -> None _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self.key_schedule: Optional[KeySchedule] = None self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) at: aioquic.tls.Context._setup_traffic_protection self._enc_key = key self._dec_key = key at: aioquic.tls.Finished verify_data: bytes = b"" at: aioquic.tls.KeySchedule finished_verify_data(secret: bytes) -> bytes derive_secret(label: bytes) -> bytes extract(key_material: Optional[bytes]=None) -> None ===========unchanged ref 1=========== update_hash(data: bytes) -> None at: aioquic.tls.KeySchedule.__init__ self.generation = 0 at: aioquic.tls.KeySchedule.extract self.generation += 1 ===========changed ref 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.key_schedule: Optional[KeySchedule] = None self.received_extensions: Optional[List[Extension]] = None self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None # callbacks self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ + [Direction, Epoch, CipherSuite, bytes], None - [Direction, Epoch, bytes], None + ] = lambda d, e, c, s: None - ] = lambda d, e, s: None # supported parameters self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] </s> ===========changed ref 1=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 <s> SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========changed ref 2=========== # module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: key_share: List[KeyShareEntry] = [] supported_groups: List[Group] = [] if Group.SECP256R1 in self._supported_groups: self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) key_share.append(encode_public_key(self._ec_private_key.public_key())) supported_groups.append(Group.SECP256R1) if Group.X25519 in self._supported_groups: self._x25519_private_key = x25519.X25519PrivateKey.generate() key_share.append(encode_public_key(self._x25519_private_key.public_key())) supported_groups.append(Group.X25519) assert len(key_share), "no key share entries" hello = ClientHello( random=self.client_random, session_id=self.session_id, cipher_suites=self._cipher_suites, compression_methods=self._compression_methods, alpn_protocols=self.alpn_protocols, key_exchange_modes=self._key_exchange_modes, key_share=key_share, server_name=self.server_name, signature_algorithms=self._signature_algorithms, supported_groups=supported_groups, supported_versions=self._supported_versions, other_extensions=self.handshake_extensions, ) # PSK if self.session_ticket and self.session_ticket.is_valid: self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_psk.extract(self.session_ticket.resumption_secret) binder_key = self._key_schedule_psk.derive_secret(b"</s>
aioquic.tls/Context._server_handle_finished
Modified
aiortc~aioquic
5ce021bf7d21195e8398b6b4146b0e25759be3fb
[tls] pass cipher suite to app
<9>:<add> self.update_traffic_key_cb( <add> Direction.DECRYPT, <add> Epoch.ONE_RTT, <add> self.key_schedule.cipher_suite, <add> self._dec_key, <add> ) <del> self.update_traffic_key_cb(Direction.DECRYPT, Epoch.ONE_RTT, self._dec_key)
# module: aioquic.tls class Context: def _server_handle_finished(self, input_buf: Buffer, output_buf: Buffer) -> None: <0> finished = pull_finished(input_buf) <1> <2> # check verify data <3> expected_verify_data = self.key_schedule.finished_verify_data(self._dec_key) <4> assert finished.verify_data == expected_verify_data <5> <6> # commit traffic key <7> self._dec_key = self._next_dec_key <8> self._next_dec_key = None <9> self.update_traffic_key_cb(Direction.DECRYPT, Epoch.ONE_RTT, self._dec_key) <10> <11> self.key_schedule.update_hash(input_buf.data) <12> <13> self._set_state(State.SERVER_POST_HANDSHAKE) <14> <15> # create a new session ticket <16> if self.new_session_ticket_cb is not None: <17> new_session_ticket = NewSessionTicket( <18> ticket_lifetime=86400, <19> ticket_age_add=struct.unpack("I", os.urandom(4))[0], <20> ticket_nonce=b"", <21> ticket=os.urandom(64), <22> ) <23> <24> # notify application <25> ticket = self._build_session_ticket(new_session_ticket) <26> self.new_session_ticket_cb(ticket) <27> <28> # send messsage <29> push_new_session_ticket(output_buf, new_session_ticket) <30>
===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls Direction() Epoch() State() pull_finished(buf: Buffer) -> Finished at: aioquic.tls.Context _setup_traffic_protection(direction: Direction, epoch: Epoch, label: bytes) -> None _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self.key_schedule: Optional[KeySchedule] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None self._dec_key: Optional[bytes] = None at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) at: aioquic.tls.Context._setup_traffic_protection self._dec_key = key at: aioquic.tls.Finished verify_data: bytes = b"" at: aioquic.tls.KeySchedule finished_verify_data(secret: bytes) -> bytes derive_secret(label: bytes) -> bytes extract(key_material: Optional[bytes]=None) -> None update_hash(data: bytes) -> None at: aioquic.tls.KeySchedule.__init__ self.cipher_suite = cipher_suite self.generation = 0 at: aioquic.tls.KeySchedule.extract self.generation += 1 ===========changed ref 0=========== # module: aioquic.tls class Context: def _client_handle_finished(self, input_buf: Buffer, output_buf: Buffer) -> None: finished = pull_finished(input_buf) # check verify data expected_verify_data = self.key_schedule.finished_verify_data(self._dec_key) assert finished.verify_data == expected_verify_data self.key_schedule.update_hash(input_buf.data) # prepare traffic keys assert self.key_schedule.generation == 2 self.key_schedule.extract(None) self._setup_traffic_protection( Direction.DECRYPT, Epoch.ONE_RTT, b"s ap traffic" ) next_enc_key = self.key_schedule.derive_secret(b"c ap traffic") # send finished with push_message(self.key_schedule, output_buf): push_finished( output_buf, Finished( verify_data=self.key_schedule.finished_verify_data(self._enc_key) ), ) # commit traffic key self._enc_key = next_enc_key + self.update_traffic_key_cb( + Direction.ENCRYPT, + Epoch.ONE_RTT, + self.key_schedule.cipher_suite, + self._enc_key, + ) - self.update_traffic_key_cb(Direction.ENCRYPT, Epoch.ONE_RTT, self._enc_key) self._set_state(State.CLIENT_POST_HANDSHAKE) ===========changed ref 1=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.key_schedule: Optional[KeySchedule] = None self.received_extensions: Optional[List[Extension]] = None self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None # callbacks self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ + [Direction, Epoch, CipherSuite, bytes], None - [Direction, Epoch, bytes], None + ] = lambda d, e, c, s: None - ] = lambda d, e, s: None # supported parameters self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] </s> ===========changed ref 2=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 <s> SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO
aioquic.tls/Context._setup_traffic_protection
Modified
aiortc~aioquic
5ce021bf7d21195e8398b6b4146b0e25759be3fb
[tls] pass cipher suite to app
<7>:<add> self.update_traffic_key_cb( <del> self.update_traffic_key_cb(direction, epoch, key) <8>:<add> direction, epoch, self.key_schedule.cipher_suite, key <add> )
# module: aioquic.tls class Context: def _setup_traffic_protection( self, direction: Direction, epoch: Epoch, label: bytes ) -> None: <0> key = self.key_schedule.derive_secret(label) <1> <2> if direction == Direction.ENCRYPT: <3> self._enc_key = key <4> else: <5> self._dec_key = key <6> <7> self.update_traffic_key_cb(direction, epoch, key) <8>
===========unchanged ref 0=========== at: _struct unpack(format, buffer, /) at: aioquic.tls State() NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b"", ticket: bytes=b"", max_early_data_size: Optional[int]=None) at: aioquic.tls.Context _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self.new_session_ticket_cb: Optional[SessionTicketHandler] = None at: aioquic.tls.NewSessionTicket ticket_lifetime: int = 0 ticket_age_add: int = 0 ticket_nonce: bytes = b"" ticket: bytes = b"" max_early_data_size: Optional[int] = None at: os urandom(size: int, /) -> bytes ===========changed ref 0=========== # module: aioquic.tls class Context: def _server_handle_finished(self, input_buf: Buffer, output_buf: Buffer) -> None: finished = pull_finished(input_buf) # check verify data expected_verify_data = self.key_schedule.finished_verify_data(self._dec_key) assert finished.verify_data == expected_verify_data # commit traffic key self._dec_key = self._next_dec_key self._next_dec_key = None + self.update_traffic_key_cb( + Direction.DECRYPT, + Epoch.ONE_RTT, + self.key_schedule.cipher_suite, + self._dec_key, + ) - self.update_traffic_key_cb(Direction.DECRYPT, Epoch.ONE_RTT, self._dec_key) self.key_schedule.update_hash(input_buf.data) self._set_state(State.SERVER_POST_HANDSHAKE) # create a new session ticket if self.new_session_ticket_cb is not None: new_session_ticket = NewSessionTicket( ticket_lifetime=86400, ticket_age_add=struct.unpack("I", os.urandom(4))[0], ticket_nonce=b"", ticket=os.urandom(64), ) # notify application ticket = self._build_session_ticket(new_session_ticket) self.new_session_ticket_cb(ticket) # send messsage push_new_session_ticket(output_buf, new_session_ticket) ===========changed ref 1=========== # module: aioquic.tls class Context: def _client_handle_finished(self, input_buf: Buffer, output_buf: Buffer) -> None: finished = pull_finished(input_buf) # check verify data expected_verify_data = self.key_schedule.finished_verify_data(self._dec_key) assert finished.verify_data == expected_verify_data self.key_schedule.update_hash(input_buf.data) # prepare traffic keys assert self.key_schedule.generation == 2 self.key_schedule.extract(None) self._setup_traffic_protection( Direction.DECRYPT, Epoch.ONE_RTT, b"s ap traffic" ) next_enc_key = self.key_schedule.derive_secret(b"c ap traffic") # send finished with push_message(self.key_schedule, output_buf): push_finished( output_buf, Finished( verify_data=self.key_schedule.finished_verify_data(self._enc_key) ), ) # commit traffic key self._enc_key = next_enc_key + self.update_traffic_key_cb( + Direction.ENCRYPT, + Epoch.ONE_RTT, + self.key_schedule.cipher_suite, + self._enc_key, + ) - self.update_traffic_key_cb(Direction.ENCRYPT, Epoch.ONE_RTT, self._enc_key) self._set_state(State.CLIENT_POST_HANDSHAKE) ===========changed ref 2=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.key_schedule: Optional[KeySchedule] = None self.received_extensions: Optional[List[Extension]] = None self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None # callbacks self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ + [Direction, Epoch, CipherSuite, bytes], None - [Direction, Epoch, bytes], None + ] = lambda d, e, c, s: None - ] = lambda d, e, s: None # supported parameters self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] </s> ===========changed ref 3=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 <s> SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO
aioquic.connection/QuicConnection._update_traffic_key
Modified
aiortc~aioquic
5ce021bf7d21195e8398b6b4146b0e25759be3fb
[tls] pass cipher suite to app
<14>:<add> crypto.send.setup(cipher_suite, secret) <del> crypto.send.setup(self.tls.key_schedule.cipher_suite, secret) <16>:<add> crypto.recv.setup(cipher_suite, secret) <del> crypto.recv.setup(self.tls.key_schedule.cipher_suite, secret)
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def _update_traffic_key( + self, + direction: tls.Direction, + epoch: tls.Epoch, + cipher_suite: tls.CipherSuite, + secret: bytes, - self, direction: tls.Direction, epoch: tls.Epoch, secret: bytes ) -> None: <0> """ <1> Callback which is invoked by the TLS engine when new traffic keys are <2> available. <3> """ <4> if self.secrets_log_file is not None: <5> label_row = self.is_client == (direction == tls.Direction.DECRYPT) <6> label = SECRETS_LABELS[label_row][epoch.value] <7> self.secrets_log_file.write( <8> "%s %s %s\n" % (label, self.tls.client_random.hex(), secret.hex()) <9> ) <10> self.secrets_log_file.flush() <11> <12> crypto = self.cryptos[epoch] <13> if direction == tls.Direction.ENCRYPT: <14> crypto.send.setup(self.tls.key_schedule.cipher_suite, secret) <15> else: <16> crypto.recv.setup(self.tls.key_schedule.cipher_suite, secret) <17>
===========unchanged ref 0=========== at: aioquic.connection SECRETS_LABELS = [ [ None, "QUIC_CLIENT_EARLY_TRAFFIC_SECRET", "QUIC_CLIENT_HANDSHAKE_TRAFFIC_SECRET", "QUIC_CLIENT_TRAFFIC_SECRET_0", ], [ None, None, "QUIC_SERVER_HANDSHAKE_TRAFFIC_SECRET", "QUIC_SERVER_TRAFFIC_SECRET_0", ], ] at: aioquic.connection.QuicConnection supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20] at: aioquic.connection.QuicConnection.__init__ self.is_client = is_client self.secrets_log_file = secrets_log_file at: aioquic.connection.QuicConnection._initialize self.tls = tls.Context(is_client=self.is_client, logger=self._logger) self.cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.ZERO_RTT: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } at: aioquic.tls Direction() Epoch() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: aioquic.tls.Context.__init__ self.client_random = None self.client_random = os.urandom(32) at: aioquic.tls.Context._server_handle_hello self.client_random = peer_hello.random at: enum.Enum name: str value: Any _name_: str _value_: Any _member_names_: List[str] # undocumented ===========unchanged ref 1=========== _member_map_: Dict[str, Enum] # undocumented _value2member_map_: Dict[int, Enum] # undocumented _ignore_: Union[str, List[str]] _order_: str __order__: str at: typing.IO __slots__ = () flush() -> None write(s: AnyStr) -> int ===========changed ref 0=========== # module: aioquic.tls class Context: def _setup_traffic_protection( self, direction: Direction, epoch: Epoch, label: bytes ) -> None: key = self.key_schedule.derive_secret(label) if direction == Direction.ENCRYPT: self._enc_key = key else: self._dec_key = key + self.update_traffic_key_cb( - self.update_traffic_key_cb(direction, epoch, key) + direction, epoch, self.key_schedule.cipher_suite, key + ) ===========changed ref 1=========== # module: aioquic.tls class Context: def _client_handle_finished(self, input_buf: Buffer, output_buf: Buffer) -> None: finished = pull_finished(input_buf) # check verify data expected_verify_data = self.key_schedule.finished_verify_data(self._dec_key) assert finished.verify_data == expected_verify_data self.key_schedule.update_hash(input_buf.data) # prepare traffic keys assert self.key_schedule.generation == 2 self.key_schedule.extract(None) self._setup_traffic_protection( Direction.DECRYPT, Epoch.ONE_RTT, b"s ap traffic" ) next_enc_key = self.key_schedule.derive_secret(b"c ap traffic") # send finished with push_message(self.key_schedule, output_buf): push_finished( output_buf, Finished( verify_data=self.key_schedule.finished_verify_data(self._enc_key) ), ) # commit traffic key self._enc_key = next_enc_key + self.update_traffic_key_cb( + Direction.ENCRYPT, + Epoch.ONE_RTT, + self.key_schedule.cipher_suite, + self._enc_key, + ) - self.update_traffic_key_cb(Direction.ENCRYPT, Epoch.ONE_RTT, self._enc_key) self._set_state(State.CLIENT_POST_HANDSHAKE) ===========changed ref 2=========== # module: aioquic.tls class Context: def _server_handle_finished(self, input_buf: Buffer, output_buf: Buffer) -> None: finished = pull_finished(input_buf) # check verify data expected_verify_data = self.key_schedule.finished_verify_data(self._dec_key) assert finished.verify_data == expected_verify_data # commit traffic key self._dec_key = self._next_dec_key self._next_dec_key = None + self.update_traffic_key_cb( + Direction.DECRYPT, + Epoch.ONE_RTT, + self.key_schedule.cipher_suite, + self._dec_key, + ) - self.update_traffic_key_cb(Direction.DECRYPT, Epoch.ONE_RTT, self._dec_key) self.key_schedule.update_hash(input_buf.data) self._set_state(State.SERVER_POST_HANDSHAKE) # create a new session ticket if self.new_session_ticket_cb is not None: new_session_ticket = NewSessionTicket( ticket_lifetime=86400, ticket_age_add=struct.unpack("I", os.urandom(4))[0], ticket_nonce=b"", ticket=os.urandom(64), ) # notify application ticket = self._build_session_ticket(new_session_ticket) self.new_session_ticket_cb(ticket) # send messsage push_new_session_ticket(output_buf, new_session_ticket)
aioquic.connection/QuicConnection.datagram_received
Modified
aiortc~aioquic
50a89ca0e2b88fbf8a722dbeae98d4d39f393e25
[connection] if a packet cannot be decrypted, just skip it
# module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: <0> """ <1> Handle an incoming datagram. <2> """ <3> # stop handling packets when closing <4> if self.__state in [QuicConnectionState.CLOSING, QuicConnectionState.DRAINING]: <5> return <6> <7> data = cast(bytes, data) <8> buf = Buffer(data=data) <9> while not buf.eof(): <10> start_off = buf.tell() <11> header = pull_quic_header(buf, host_cid_length=len(self.host_cid)) <12> <13> # check destination CID matches <14> if self.is_client and header.destination_cid != self.host_cid: <15> return <16> <17> # check protocol version <18> if self.is_client and header.version == QuicProtocolVersion.NEGOTIATION: <19> # version negotiation <20> versions = [] <21> while not buf.eof(): <22> versions.append(pull_uint32(buf)) <23> common = set(self.supported_versions).intersection(versions) <24> if not common: <25> self._logger.error("Could not find a common protocol version") <26> return <27> self._version = QuicProtocolVersion(max(common)) <28> self._version_negotiation_count += 1 <29> self._logger.info("Retrying with %s", self._version) <30> self._connect() <31> return <32> elif ( <33> header.version is not None <34> and header.version not in self.supported_versions <35> ): <36> # unsupported version <37> return <38> <39> if self.is_client and header.packet_type == PACKET_TYPE_RETRY: <40> # stateless retry <41> if ( <42> header.destination_cid == self.host_cid <43> and header.original_destination_cid == self.peer_cid <44> and not self._stateless_retry_count </s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 self._original_connection_id = self.peer_cid self.peer_cid = header.source_cid self.peer_token = header.token self._stateless_retry_count += 1 self._logger.info("Performing stateless retry") self._connect() return network_path = self._find_network_path(addr) # server initialization if not self.is_client and self.__state == QuicConnectionState.FIRSTFLIGHT: assert ( header.packet_type == PACKET_TYPE_INITIAL ), "first packet must be INITIAL" self._network_paths = [network_path] self._version = QuicProtocolVersion(header.version) self._initialize(header.destination_cid) # decrypt packet encrypted_off = buf.tell() - start_off end_off = buf.tell() + header.rest_length pull_bytes(buf, header.rest_length) epoch = get_epoch(header.packet_type) crypto = self.cryptos[epoch] if not crypto.recv.is_valid(): return try: plain_header, plain_payload, packet_number = crypto.decrypt_packet( data[start_off:end_off], encrypted_off ) except CryptoError as exc: self._logger.warning(exc) return # discard initial keys if not self.is_client and epoch == tls.Epoch.HANDSHAKE: self.cryptos[tls.Epoch.INITIAL].teardown() # update state if not self.peer_cid_set: self.peer_cid = header.source_cid self.peer_cid_set = True if self.__state == QuicConnectionState.FIRSTFLIGHT: self._set_state(QuicConnectionState.</s> ===========below chunk 1=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 2 <s> if self.__state == QuicConnectionState.FIRSTFLIGHT: self._set_state(QuicConnectionState.CONNECTED) # update spin bit if ( not is_long_header(plain_header[0]) and packet_number > self._spin_highest_pn ): self._spin_bit_peer = get_spin_bit(plain_header[0]) if self.is_client: self._spin_bit = not self._spin_bit_peer else: self._spin_bit = self._spin_bit_peer self._spin_highest_pn = packet_number # handle payload context = QuicReceiveContext(epoch=epoch, network_path=network_path) self._logger.debug("[%s] handling packet %d", context.epoch, packet_number) try: is_ack_only, is_probing = self._payload_received(context, plain_payload) except QuicConnectionError as exc: self._logger.warning(exc) self.close( error_code=exc.error_code, frame_type=exc.frame_type, reason_phrase=exc.reason_phrase, ) return # update network path if not network_path.is_validated and epoch == tls.Epoch.HANDSHAKE: self._logger.info( "Network path %s validated by handshake", network_path.addr ) network_path.is_validated = True network_path.bytes_received += buf.tell() - start_off if network_path not in self._network_paths: self._network_paths.append(network_path) idx = self</s> ===========below chunk 2=========== # module: aioquic.connection class QuicConnection(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 3 <s>_paths.index(network_path) if idx and not is_probing: self._logger.info("Network path %s promoted", network_path.addr) self._network_paths.pop(idx) self._network_paths.insert(0, network_path) # record packet as received if epoch == tls.Epoch.ZERO_RTT: space = self.spaces[tls.Epoch.ONE_RTT] else: space = self.spaces[epoch] space.ack_queue.add(packet_number) if not is_ack_only: space.ack_required = True self._send_pending() ===========unchanged ref 0=========== at: aioquic.buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) pull_bytes(buf: Buffer, length: int) -> bytes pull_uint32(buf: Buffer) -> int at: aioquic.buffer.Buffer eof() -> bool tell() -> int at: aioquic.connection NetworkAddress = Any get_epoch(packet_type: int) -> tls.Epoch QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) QuicConnectionState() QuicReceiveContext(epoch: tls.Epoch, network_path: QuicNetworkPath) at: aioquic.connection.QuicConnection supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20] close(error_code: int=QuicErrorCode.NO_ERROR, frame_type: Optional[int]=None, reason_phrase: str="") -> None _connect() -> None _find_network_path(addr: NetworkAddress) -> QuicNetworkPath _initialize(peer_cid: bytes) -> None _payload_received(context: QuicReceiveContext, plain: bytes) -> Tuple[bool, bool] _set_state(state: QuicConnectionState) -> None at: aioquic.connection.QuicConnection.__init__ self.is_client = is_client self.host_cid = os.urandom(8) self.peer_cid = os.urandom(8) self.peer_cid_set = False self.peer_token = b"" self._stateless_retry_count = 0 self._version_negotiation_count = 0 self._logger = QuicConnectionAdapter( logger, {"host_cid": binascii.hexlify(self.host_cid).decode("ascii")} ) self._network_paths: List[QuicNetworkPath] = []