Generate new nonce for the I2P connections and improve nonce handling:

- make tuple (host, port) a key for shared.nonce_pool
    to differentiate incoming tor connections,
  - reserve 127.0.0.1, 8448 for self,
  - convert nonce to string for logging.
This commit is contained in:
Lee Miller 2024-01-24 00:20:41 +02:00
parent d4cf657efd
commit 6c545087dc
Signed by: lee.miller
GPG Key ID: 4F97A5EA88F4AB63
2 changed files with 18 additions and 8 deletions

View File

@ -4,6 +4,7 @@ import base64
import errno
import logging
import math
import os
import random
import select
import socket
@ -80,7 +81,8 @@ class ConnectionBase(threading.Thread):
if self.network == 'ip':
self.send_queue.put(message.Version(self.host, self.port))
else:
self.send_queue.put(message.Version('127.0.0.1', 7656))
self.send_queue.put(message.Version(
'127.0.0.1', 7656, nonce=self._get_nonce()))
while True:
if (
self.on_connection_fully_established_scheduled
@ -149,6 +151,14 @@ class ConnectionBase(threading.Thread):
break
time.sleep(0.2)
def _get_nonce(self):
nonce = shared.nonce_pool.get(('127.0.0.1', 8448))
if nonce is None:
nonce = os.urandom(8)
shared.nonce_pool[('127.0.0.1', 8448)] = nonce
return nonce
def _connect(self):
peer_str = '{0.host_print}:{0.port}'.format(self)
logging.debug('Connecting to %s', peer_str)
@ -377,6 +387,7 @@ class ConnectionBase(threading.Thread):
if shared.stream not in version.streams:
raise ValueError('message not for stream %i' % shared.stream)
logging.debug('%s:%s -> %s', self.host_print, self.port, version)
nonce_print = base64.b16encode(version.nonce).decode()
if (
version.protocol_version != shared.protocol_version
or version.nonce == shared.nonce
@ -384,16 +395,14 @@ class ConnectionBase(threading.Thread):
):
logging.warning(
'Disconnecting v%s node %s with nonce %s',
version.protocol_version, self.host_print,
base64.b16encode(version.nonce))
version.protocol_version, self.host_print, nonce_print)
self.status = 'disconnecting'
self.send_queue.put(None)
else:
shared.nonce_pool[self.host] = version.nonce
shared.nonce_pool[(self.host, self.port)] = version.nonce
logging.info(
'%s:%s claims to be %s (%s)',
self.host_print, self.port, version.user_agent,
base64.b16encode(version.nonce))
self.host_print, self.port, version.user_agent, nonce_print)
self.send_queue.put(message.Message(b'verack', b''))
self.verack_sent = True
self.remote_version = version
@ -412,7 +421,8 @@ class ConnectionBase(threading.Thread):
if self.network == 'ip':
self.send_queue.put(message.Version(self.host, self.port))
else:
self.send_queue.put(message.Version('127.0.0.1', 7656))
self.send_queue.put(message.Version(
'127.0.0.1', 7656, nonce=self._get_nonce()))
def _process_msg_addr(self, m):
addr = message.Addr.from_message(m)

View File

@ -107,7 +107,7 @@ class Manager(threading.Thread):
with shared.connections_lock:
shared.connections.remove(c)
try:
del shared.nonce_pool[c.host]
del shared.nonce_pool[(c.host, c.port)]
except KeyError:
pass
else: