Many bugs fixed in sniffer and async model.

This commit is contained in:
Dionysus 2024-03-08 12:13:57 -05:00
parent d34aa105f1
commit 6c4ae3e988
Signed by: acidvegas
GPG Key ID: EF4B922DB85DC9DE
3 changed files with 52 additions and 46 deletions

17
eris.py
View File

@ -43,15 +43,15 @@ class ElasticIndexer:
'request_timeout': args.timeout, 'request_timeout': args.timeout,
'max_retries': args.retries, 'max_retries': args.retries,
'retry_on_timeout': True, 'retry_on_timeout': True,
'sniff_on_start': True, # Is this problematic? 'sniff_on_start': False, # Problems when True....
'sniff_on_node_failure': True, 'sniff_on_node_failure': True,
'min_delay_between_sniffing': 60 # Add config option for this? 'min_delay_between_sniffing': 60 # Add config option for this?
} }
if args.api_key: #if args.api_key:
self.es_config['api_key'] = (args.api_key, '') # Verify this is correct # self.es_config['api_key'] = (args.api_key, '') # Verify this is correct
else: #else:
self.es_config['basic_auth'] = (args.user, args.password) self.es_config['basic_auth'] = (args.user, args.password)
async def initialize(self): async def initialize(self):
@ -59,7 +59,7 @@ class ElasticIndexer:
# Patching the Elasticsearch client to fix a bug with sniffing (https://github.com/elastic/elasticsearch-py/issues/2005#issuecomment-1645641960) # Patching the Elasticsearch client to fix a bug with sniffing (https://github.com/elastic/elasticsearch-py/issues/2005#issuecomment-1645641960)
import sniff_patch import sniff_patch
self.es = sniff_patch.init_elasticsearch(**self.es_config) self.es = await sniff_patch.init_elasticsearch(**self.es_config)
# Remove the above and uncomment the below if the bug is fixed in the Elasticsearch client: # Remove the above and uncomment the below if the bug is fixed in the Elasticsearch client:
#self.es = AsyncElasticsearch(**es_config) #self.es = AsyncElasticsearch(**es_config)
@ -161,7 +161,7 @@ async def main():
parser.add_argument('--port', type=int, default=9200, help='Elasticsearch port') parser.add_argument('--port', type=int, default=9200, help='Elasticsearch port')
parser.add_argument('--user', default='elastic', help='Elasticsearch username') parser.add_argument('--user', default='elastic', help='Elasticsearch username')
parser.add_argument('--password', default=os.getenv('ES_PASSWORD'), help='Elasticsearch password (if not provided, check environment variable ES_PASSWORD)') parser.add_argument('--password', default=os.getenv('ES_PASSWORD'), help='Elasticsearch password (if not provided, check environment variable ES_PASSWORD)')
parser.add_argument('--api-key', default=os.getenv('ES_APIKEY'), help='Elasticsearch API Key for authentication (if not provided, check environment variable ES_APIKEY)') #parser.add_argument('--api-key', default=os.getenv('ES_APIKEY'), help='Elasticsearch API Key for authentication (if not provided, check environment variable ES_APIKEY)')
parser.add_argument('--self-signed', action='store_false', help='Elasticsearch is using self-signed certificates') parser.add_argument('--self-signed', action='store_false', help='Elasticsearch is using self-signed certificates')
# Elasticsearch indexing arguments # Elasticsearch indexing arguments
@ -207,6 +207,9 @@ async def main():
elif args.zone: elif args.zone:
from ingestors import ingest_zone as ingestor from ingestors import ingest_zone as ingestor
if not isinstance(ingestor, object):
raise ValueError('No ingestor selected')
health = await edx.get_cluster_health() health = await edx.get_cluster_health()
print(health) print(health)

View File

@ -48,7 +48,8 @@ async def process_data(file_path: str):
# Sentinel value to indicate the end of a process (for closing out a FIFO stream) # Sentinel value to indicate the end of a process (for closing out a FIFO stream)
if line == '~eof': if line == '~eof':
return last yield last
break
# Skip empty lines # Skip empty lines
if not line: if not line:
@ -67,17 +68,14 @@ async def process_data(file_path: str):
# Do not index other records # Do not index other records
if record_type != 'PTR': if record_type != 'PTR':
logging.warning(f'Invalid record type: {record_type}: {line}')
continue continue
# Do not index PTR records that do not have a record # Do not index PTR records that do not have a record
if not record: if not record:
logging.warning(f'Empty PTR record: {line}')
continue continue
# Let's not index the PTR record if it's the same as the in-addr.arpa domain # Let's not index the PTR record if it's the same as the in-addr.arpa domain
if record == name: if record == name:
logging.warning(f'PTR record is the same as the in-addr.arpa domain: {line}')
continue continue
# Get the IP address from the in-addr.arpa domain # Get the IP address from the in-addr.arpa domain
@ -86,25 +84,25 @@ async def process_data(file_path: str):
# Check if we are still processing the same IP address # Check if we are still processing the same IP address
if last: if last:
if ip == last['_id']: if ip == last['_id']:
last_record = last['_doc']['record'] last_record = last['doc']['record']
if isinstance(last_record, list): if isinstance(last_record, list):
if record not in last_record: if record not in last_record:
last['_doc']['record'].append(record) last['doc']['record'].append(record)
else: else:
logging.warning(f'Duplicate PTR record: {line}') logging.warning(f'Duplicate PTR record: {line}')
else: else:
if record != last_record: if record != last_record:
last['_doc']['record'] = [last_record, record] # IP addresses with more than one PTR record will turn into a list last['doc']['record'] = [last_record, record] # IP addresses with more than one PTR record will turn into a list
continue continue
else: else:
yield last yield last # Return the last document and start a new one
# Cache the this document in-case we have more for the same IP address # Cache the this document in-case we have more for the same IP address
last = { last = {
'_op_type' : 'update', '_op_type' : 'update',
'_id' : ip, '_id' : ip,
'_index' : default_index, '_index' : default_index,
'_doc' : { 'doc' : {
'ip' : ip, 'ip' : ip,
'record' : record, 'record' : record,
'seen' : time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()) 'seen' : time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
@ -138,9 +136,10 @@ if __name__ == '__main__':
''' '''
Deployment: Deployment:
sudo apt-get install build-essential gcc make
git clone --depth 1 https://github.com/blechschmidt/massdns.git $HOME/massdns && cd $HOME/massdns && make git clone --depth 1 https://github.com/blechschmidt/massdns.git $HOME/massdns && cd $HOME/massdns && make
curl -s https://public-dns.info/nameservers.txt | grep -v ':' > $HOME/massdns/nameservers.txt curl -s https://public-dns.info/nameservers.txt | grep -v ':' > $HOME/massdns/nameservers.txt
pythons ./scripts/ptr.py | ./bin/massdns -r $HOME/massdns/nameservers.txt -t PTR --filter NOERROR-s 1000 -o S -w $HOME/massdns/fifo.json python3 ./scripts/ptr.py | ./bin/massdns -r $HOME/massdns/nameservers.txt -t PTR --filter NOERROR-s 500 -o S -w $HOME/massdns/fifo.json
or... or...
while true; do python ./scripts/ptr.py | ./bin/massdns -r $HOME/massdns/nameservers.txt -t PTR --filter NOERROR -s 1000 -o S -w $HOME/massdns/fifo.json; done while true; do python ./scripts/ptr.py | ./bin/massdns -r $HOME/massdns/nameservers.txt -t PTR --filter NOERROR -s 1000 -o S -w $HOME/massdns/fifo.json; done

View File

@ -16,19 +16,19 @@ import elasticsearch._async.client as async_client
from elasticsearch.exceptions import SerializationError, ConnectionError from elasticsearch.exceptions import SerializationError, ConnectionError
async def init_elasticsearch_async(*args, **kwargs): async def init_elasticsearch(*args, **kwargs):
''' '''
Initialize the Async Elasticsearch client with the sniff patch. Initialize the Async Elasticsearch client with the sniff patch.
:param args: Async Elasticsearch positional arguments. :param args: Async Elasticsearch positional arguments.
:param kwargs: Async Elasticsearch keyword arguments. :param kwargs: Async Elasticsearch keyword arguments.
''' '''
async_client.default_sniff_callback = _override_async_sniff_callback(kwargs['basic_auth']) async_client.default_sniff_callback = _override_sniff_callback(kwargs['basic_auth'])
return async_client.AsyncElasticsearch(*args, **kwargs) return async_client.AsyncElasticsearch(*args, **kwargs)
def _override_async_sniff_callback(basic_auth): def _override_sniff_callback(basic_auth):
''' '''
Taken from https://github.com/elastic/elasticsearch-py/blob/8.8/elasticsearch/_sync/client/_base.py#L166 Taken from https://github.com/elastic/elasticsearch-py/blob/8.8/elasticsearch/_sync/client/_base.py#L166
Completely unmodified except for adding the auth header to the elastic request. Completely unmodified except for adding the auth header to the elastic request.
@ -40,7 +40,7 @@ def _override_async_sniff_callback(basic_auth):
auth_str = base64.b64encode(':'.join(basic_auth).encode()).decode() auth_str = base64.b64encode(':'.join(basic_auth).encode()).decode()
sniffed_node_callback = async_client._base._default_sniffed_node_callback sniffed_node_callback = async_client._base._default_sniffed_node_callback
async def modified_async_sniff_callback(transport, sniff_options): async def modified_sniff_callback(transport, sniff_options):
for _ in transport.node_pool.all(): for _ in transport.node_pool.all():
try: try:
meta, node_infos = await transport.perform_request( meta, node_infos = await transport.perform_request(
@ -48,7 +48,7 @@ def _override_async_sniff_callback(basic_auth):
'/_nodes/_all/http', '/_nodes/_all/http',
headers={ headers={
'accept': 'application/vnd.elasticsearch+json; compatible-with=8', 'accept': 'application/vnd.elasticsearch+json; compatible-with=8',
'authorization': f'Basic {auth_str}' # This auth header is missing in 8.x releases of the client, and causes 401s 'authorization': f'Basic {auth_str}' # This auth header is missing in 8.x releases of the client, and causes 401s
}, },
request_timeout=( request_timeout=(
sniff_options.sniff_timeout sniff_options.sniff_timeout
@ -79,9 +79,13 @@ def _override_async_sniff_callback(basic_auth):
port = int(port_str) port = int(port_str)
assert sniffed_node_callback is not None assert sniffed_node_callback is not None
sniffed_node = await sniffed_node_callback(
node_info, meta.node.replace(host=host, port=port) # Pay not mind to this, it's just a workaround for my own setup.
) #host = elastic.domain.com
#port = int(str(port).replace('', ''))
sniffed_node = sniffed_node_callback(node_info, meta.node.replace(host=host, port=port))
if sniffed_node is None: if sniffed_node is None:
continue continue
@ -93,4 +97,4 @@ def _override_async_sniff_callback(basic_auth):
return [] return []
return modified_async_sniff_callback return modified_sniff_callback