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

15
eris.py
View File

@ -43,14 +43,14 @@ class ElasticIndexer:
'request_timeout': args.timeout,
'max_retries': args.retries,
'retry_on_timeout': True,
'sniff_on_start': True, # Is this problematic?
'sniff_on_start': False, # Problems when True....
'sniff_on_node_failure': True,
'min_delay_between_sniffing': 60 # Add config option for this?
}
if args.api_key:
self.es_config['api_key'] = (args.api_key, '') # Verify this is correct
else:
#if args.api_key:
# self.es_config['api_key'] = (args.api_key, '') # Verify this is correct
#else:
self.es_config['basic_auth'] = (args.user, args.password)
@ -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)
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:
#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('--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('--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')
# Elasticsearch indexing arguments
@ -207,6 +207,9 @@ async def main():
elif args.zone:
from ingestors import ingest_zone as ingestor
if not isinstance(ingestor, object):
raise ValueError('No ingestor selected')
health = await edx.get_cluster_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)
if line == '~eof':
return last
yield last
break
# Skip empty lines
if not line:
@ -67,17 +68,14 @@ async def process_data(file_path: str):
# Do not index other records
if record_type != 'PTR':
logging.warning(f'Invalid record type: {record_type}: {line}')
continue
# Do not index PTR records that do not have a record
if not record:
logging.warning(f'Empty PTR record: {line}')
continue
# Let's not index the PTR record if it's the same as the in-addr.arpa domain
if record == name:
logging.warning(f'PTR record is the same as the in-addr.arpa domain: {line}')
continue
# 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
if last:
if ip == last['_id']:
last_record = last['_doc']['record']
last_record = last['doc']['record']
if isinstance(last_record, list):
if record not in last_record:
last['_doc']['record'].append(record)
last['doc']['record'].append(record)
else:
logging.warning(f'Duplicate PTR record: {line}')
else:
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
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
last = {
'_op_type' : 'update',
'_id' : ip,
'_index' : default_index,
'_doc' : {
'doc' : {
'ip' : ip,
'record' : record,
'seen' : time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
@ -138,9 +136,10 @@ if __name__ == '__main__':
'''
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
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...
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
async def init_elasticsearch_async(*args, **kwargs):
async def init_elasticsearch(*args, **kwargs):
'''
Initialize the Async Elasticsearch client with the sniff patch.
:param args: Async Elasticsearch positional 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)
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
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()
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():
try:
meta, node_infos = await transport.perform_request(
@ -79,9 +79,13 @@ def _override_async_sniff_callback(basic_auth):
port = int(port_str)
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:
continue
@ -93,4 +97,4 @@ def _override_async_sniff_callback(basic_auth):
return []
return modified_async_sniff_callback
return modified_sniff_callback