snstac / pytak

PyTAK is a Python package for rapid TAK integration.
https://pytak.readthedocs.io/en/stable/
Apache License 2.0
156 stars 42 forks source link

Issues connecting to TAK Server using TLS #70

Closed jeremymcgee73 closed 4 months ago

jeremymcgee73 commented 4 months ago

Hello, I'm having an issue trying to connect to my TAK server over TLS. I am able to connect to this TAK server from android phones, and with wintak. It seems like its not using the correct cert with the trust store. But, I have tried about a million different combinations. My truststore.pem does have the complete chain from the TAK server. I have also tried switching to a datapackage, but that does not seem to set the COT_URL correctly.

I've also tried not setting a Trust Store cert, and ignoring the cert warnings like this:

        "PYTAK_TLS_DONT_CHECK_HOSTNAME": 1,
        "PYTAK_TLS_DONT_VERIFY": 1,

I was hoping to get some ideas on what to try next.

Thanks so much!

Similar error with TAK server: https://mytecknet.com/tak-certificate-error-peer-not-verified/

Example code I'm using:

#!/usr/bin/env python3

import asyncio
import xml.etree.ElementTree as ET
import pytak
import cryptography

from configparser import ConfigParser

def gen_cot():
    """Generate CoT Event."""
    root = ET.Element("event")
    root.set("version", "2.0")
    root.set("type", "a-h-A-M-A")  # insert your type of marker
    root.set("uid", "name_your_marker")
    root.set("how", "m-g")
    root.set("time", pytak.cot_time())
    root.set("start", pytak.cot_time())
    root.set(
        "stale", pytak.cot_time(60)
    )  # time difference in seconds from 'start' when stale initiates

    pt_attr = {
        "lat": "40.781789",  # set your lat (this loc points to Central Park NY)
        "lon": "-73.968698",  # set your long (this loc points to Central Park NY)
        "hae": "0",
        "ce": "10",
        "le": "10",
    }

    ET.SubElement(root, "point", attrib=pt_attr)

    return ET.tostring(root)

class MySender(pytak.QueueWorker):
    """
    Defines how you process or generate your Cursor-On-Target Events.
    From there it adds the COT Events to a queue for TX to a COT_URL.
    """

    async def handle_data(self, data):
        """Handle pre-CoT data, serialize to CoT Event, then puts on queue."""
        event = data
        await self.put_queue(event)

    async def run(self, number_of_iterations=-1):
        """Run the loop for processing or generating pre-CoT data."""
        while 1:
            data = gen_cot()
            self._logger.info("Sending:\n%s\n", data.decode())
            await self.handle_data(data)
            await asyncio.sleep(5)

class MyReceiver(pytak.QueueWorker):
    """Defines how you will handle events from RX Queue."""

    async def handle_data(self, data):
        """Handle data from the receive queue."""
        self._logger.info("Received:\n%s\n", data.decode())

    async def run(self):  # pylint: disable=arguments-differ
        """Read from the receive queue, put data onto handler."""
        while 1:
            data = (
                await self.queue.get()
            )  # this is how we get the received CoT from rx_queue
            await self.handle_data(data)

async def main():
    """Main definition of your program, sets config params and
    adds your serializer to the asyncio task list.
    """
    config = ConfigParser()
    config["mycottool"] = {
        "COT_URL": "tls://192.168.1.1:8089", 
         "PYTAK_TLS_CLIENT_CAFILE": "truststore.pem",
        "DEBUG": 1,
        "PYTAK_TLS_CLIENT_CERT": "user.p12",
        "PYTAK_TLS_CLIENT_PASSWORD": "PASSWORD",
        }
    config = config["mycottool"]

    # Initializes worker queues and tasks.
    clitool = pytak.CLITool(config)
    await clitool.setup()

    # Add your serializer to the asyncio task list.
    clitool.add_tasks(
        set([MySender(clitool.tx_queue, config), MyReceiver(clitool.rx_queue, config)])
    )

    # Start all tasks.
    await clitool.run()

if __name__ == "__main__":
    asyncio.run(main())

Python Error:

  Traceback (most recent call last):
  File "/workspaces/tak/main.py", line 110, in <module>
    asyncio.run(main())
  File "/usr/local/lib/python3.11/asyncio/runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/asyncio/runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "/workspaces/tak/main.py", line 98, in main
    await clitool.setup()
  File "/home/vscode/.local/lib/python3.11/site-packages/pytak/classes.py", line 366, in setup
    reader, writer = await pytak.protocol_factory(self.config)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vscode/.local/lib/python3.11/site-packages/pytak/client_functions.py", line 280, in protocol_factory
    reader, writer = await asyncio.open_connection(host, port, ssl=ssl_ctx)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/asyncio/streams.py", line 48, in open_connection
    transport, _ = await loop.create_connection(
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/asyncio/base_events.py", line 1112, in create_connection
    transport, protocol = await self._create_connection_transport(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/asyncio/base_events.py", line 1145, in _create_connection_transport
    await waiter
ConnectionAbortedError: SSL handshake is taking longer than 60.0 seconds: aborting the connection

Error on TAK Server:

takserver-messaging.log:2024-05-16-19:05:54.696 [epollEventLoopGroup-4-7] ERROR c.b.m.n.n.h.NioNettyHandlerBase - NioNettyServerHandler error. Cause: io.netty.handler.ssl.NotSslRecordException: not an SSL/TLS record. Additional info: Remote address: 192.168.10.1; Remote port: 61050; Local port: 8089; Certificate error: peer not verified; 
jeremymcgee73 commented 4 months ago

Also, I am using 6.4.0 of pytak, and 3.11.4 is my version of python.

jeremymcgee73 commented 4 months ago

It was a network issue, disregard :-)