| 926 | |
| 927 | |
| 928 | class TLSUpgradeProto(asyncio.Protocol): |
| 929 | def __init__( |
| 930 | self, |
| 931 | loop: asyncio.AbstractEventLoop, |
| 932 | host: str, |
| 933 | port: int, |
| 934 | ssl_context: ssl_module.SSLContext, |
| 935 | ssl_is_advisory: bool, |
| 936 | ) -> None: |
| 937 | self.on_data = _create_future(loop) |
| 938 | self.host = host |
| 939 | self.port = port |
| 940 | self.ssl_context = ssl_context |
| 941 | self.ssl_is_advisory = ssl_is_advisory |
| 942 | |
| 943 | def data_received(self, data: bytes) -> None: |
| 944 | if self.on_data.done(): |
| 945 | return |
| 946 | if data == b'S': |
| 947 | self.on_data.set_result(True) |
| 948 | elif (self.ssl_is_advisory and |
| 949 | self.ssl_context.verify_mode == ssl_module.CERT_NONE and |
| 950 | data == b'N'): |
| 951 | # ssl_is_advisory will imply that ssl.verify_mode == CERT_NONE, |
| 952 | # since the only way to get ssl_is_advisory is from |
| 953 | # sslmode=prefer. But be extra sure to disallow insecure |
| 954 | # connections when the ssl context asks for real security. |
| 955 | self.on_data.set_result(False) |
| 956 | elif data.startswith(b'E'): |
| 957 | # Never trust or expose pre-TLS ErrorResponse fields |
| 958 | # (including SQLSTATE). See CVE-2024-10977. |
| 959 | self.on_data.set_exception(ConnectionError( |
| 960 | f'PostgreSQL server at "{self.host}:{self.port}": ' |
| 961 | 'server sent an error response during SSL exchange; ' |
| 962 | 'check the server logs for details')) |
| 963 | else: |
| 964 | self.on_data.set_exception( |
| 965 | ConnectionError( |
| 966 | 'PostgreSQL server at "{host}:{port}" ' |
| 967 | 'rejected SSL upgrade'.format( |
| 968 | host=self.host, port=self.port))) |
| 969 | |
| 970 | def connection_lost(self, exc: typing.Optional[Exception]) -> None: |
| 971 | if not self.on_data.done(): |
| 972 | if exc is None: |
| 973 | exc = ConnectionError('unexpected connection_lost() call') |
| 974 | self.on_data.set_exception(exc) |
| 975 | |
| 976 | |
| 977 | _ProctolFactoryR = typing.TypeVar( |
no outgoing calls
no test coverage detected