I have a very low security environment (sensor data on a LAN) that I am trying to add just a little bit of security on.
I am pretty sure this error is asking for proper DNS which is not available. Certs are self-signed with basically junk added to the FQDN.
I get the following error:
$ python3 twistedClientsocketSSL.001.py
Error during info_callback
Traceback (most recent call last):
File "/home/.local/lib/python3.5/site-packages/twisted/protocols/tls.py", line 315, in dataReceived
self._checkHandshakeStatus()
File "/home/.local/lib/python3.5/site-packages/twisted/protocols/tls.py", line 235, in _checkHandshakeStatus
self._tlsConnection.do_handshake()
File "/home/.local/lib/python3.5/site-packages/OpenSSL/SSL.py", line 1906, in do_handshake
result = _lib.SSL_do_handshake(self._ssl)
File "/home/.local/lib/python3.5/site-packages/OpenSSL/SSL.py", line 1288, in wrapper
callback(Connection._reverse_mapping[ssl], where, return_code)
--- <exception caught here> ---
File "/home/.local/lib/python3.5/site-packages/twisted/internet/_sslverify.py", line 1103, in infoCallback
return wrapped(connection, where, ret)
File "/home/.local/lib/python3.5/site-packages/twisted/internet/_sslverify.py", line 1216, in _identityVerifyingInfoCallback
verifyHostname(connection, self._hostnameASCII)
File "/home/.local/lib/python3.5/site-packages/service_identity/pyopenssl.py", line 48, in verify_hostname
obligatory_ids=[DNS_ID(hostname)],
File "/home/.local/lib/python3.5/site-packages/service_identity/_common.py", line 245, in __init__
raise ValueError("Invalid DNS-ID.")
builtins.ValueError: Invalid DNS-ID.
main function encountered error
Traceback (most recent call last):
--- <exception caught here> ---
File "twistedClientsocketSSL.001.py", line 18, in custom_trust
response = yield treqish.get('https://192.168.1.7:1079')
twisted.web._newclient.ResponseNeverReceived: [<twisted.python.failure.Failure builtins.ValueError: Invalid DNS-ID.>]
client code:
import treq
from twisted.internet import defer, ssl, task
from twisted.web import client
#task.react
#defer.inlineCallbacks
def custom_trust(_reactor):
# get root cert from pem file
with open('keys/server.crt') as cert_file:
trust_root = yield ssl.Certificate.loadPEM(cert_file.read())
# ready made browser-like policy
policy = client.BrowserLikePolicyForHTTPS(trustRoot=trust_root)
agent = client.Agent(_reactor, policy)
treqish = treq.client.HTTPClient(agent)
response = yield treqish.get('https://192.168.1.7:1079')
content = yield response.content()
print(content)
corresponding server code:
$ cat twistedServersocketSSL.002.py
import sys
from twisted.internet import endpoints, reactor, ssl
from twisted.web import server, resource
from twisted.python import log
from twisted.python.modules import getModule
class Example(resource.Resource):
isLeaf = True
def render_GET(self, request):
return u'Hello World'.encode('ascii')
# create SSL server from string
https_server = endpoints.serverFromString(
reactor,
'ssl:1079:interface=192.168.1.7:certKey=keys/server.crt:privateKey=keys/server_no_pass.key')
# start server
site = server.Site(Example())
https_server.listen(site)
log.startLogging(sys.stdout)
reactor.run()
How do I dumb down SSL DNS verification so I can get around this error or a decent low security solution thats light weight that gets plain text off a network socket connection?
Related
I'm creating a telnet server using telnetsrv and green. I'm using python3. Modified the green.py from from telnetsrvlib import TelnetHandlerBase, command to from .telnetsrvlib import TelnetHandlerBase, command and SocketServer to socketserver for python3 compatibility. I'm facing the following errors while connecting to the servers.
[+] Welcome to Telnet server
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 906, in gevent._gevent_cgreenlet.Greenlet.run
File "/usr/local/lib/python3.8/dist-packages/gevent/baseserver.py", line 34, in _handle_and_close_when_done
return handle(*args_tuple)
File "/usr/local/lib/python3.8/dist-packages/telnetsrv/telnetsrvlib.py", line 495, in streamserver_handle
cls(request, address, server)
File "/usr/local/lib/python3.8/dist-packages/telnetsrv/green.py", line 14, in __init__
TelnetHandlerBase.__init__(self, request, client_address, server)
File "/usr/local/lib/python3.8/dist-packages/telnetsrv/telnetsrvlib.py", line 482, in __init__
SocketServer.BaseRequestHandler.__init__(self, request, client_address, server)
File "/usr/lib/python3.8/socketserver.py", line 748, in __init__
self.setup()
File "/usr/local/lib/python3.8/dist-packages/telnetsrv/green.py", line 18, in setup
TelnetHandlerBase.setup(self)
File "/usr/local/lib/python3.8/dist-packages/telnetsrv/telnetsrvlib.py", line 519, in setup
self.sock = self.request._sock
AttributeError: 'Telnet_handler' object has no attribute 'request'
2022-08-13T15:21:34Z <Greenlet at 0x7f8902e428c0: _handle_and_close_when_done(<bound method TelnetHandlerBase.streamserver_handl, <bound method StreamServer.do_close of <StreamServ, (<gevent._socket3.socket [closed] at 0x7f8902a181c)> failed with AttributeError```
*This is my code*
```#!/usr/bin/python3
import gevent, gevent.server
from telnetsrv.green import TelnetHandler, command
class Telnet_handler(TelnetHandler):
WELCOME = "Welcome to my server."
print(WELCOME)
server = gevent.server.StreamServer(("", 8023),Telnet_handler.streamserver_handle)
try:
print("[+] Welcome to Telnet server")
server.serve_forever()
except KeyboardInterrupt:
print("[-] Connection Failed \n Exiting Telnet Server ")```
[1]: https://i.stack.imgur.com/GuyNX.png
I am trying to configure AsyncHTTPClient with auth proxy to access https websites. Is it possible to do with authenticated proxy?
from tornado import httpclient, ioloop
config = {
'proxy_host': proxy_host,
'proxy_port': proxy_post,
"proxy_username": proxy_username,
"proxy_password": proxy_password
}
httpclient.AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
def handle_request(response):
if response.error:
print("Error:", response.error)
else:
print(response.body)
ioloop.IOLoop.instance().stop()
http_client = httpclient.AsyncHTTPClient()
http_client.fetch("https://twitter.com/",
handle_request, **config)
ioloop.IOLoop.instance().start()
I get these errors after running the code above
Traceback (most recent call last):
File "C:\Users\Adam\Anaconda3\envs\sizeer\lib\site-packages\tornado\curl_httpclient.py", line 130, in _handle_socket
self.io_loop.add_handler(fd, self._handle_events, ioloop_event)
File "C:\Users\Adam\Anaconda3\envs\sizeer\lib\site-packages\tornado\platform\asyncio.py", line 103, in add_handler
self.asyncio_loop.add_writer(fd, self._handle_events, fd, IOLoop.WRITE)
File "C:\Users\Adam\Anaconda3\envs\sizeer\lib\asyncio\events.py", line 507, in add_writer
raise NotImplementedError
NotImplementedError
Traceback (most recent call last):
File "C:\Users\Adam\Anaconda3\envs\sizeer\lib\site-packages\tornado\curl_httpclient.py", line 130, in _handle_socket
self.io_loop.add_handler(fd, self._handle_events, ioloop_event)
File "C:\Users\Adam\Anaconda3\envs\sizeer\lib\site-packages\tornado\platform\asyncio.py", line 97, in add_handler
raise ValueError("fd %s added twice" % fd)
ValueError: fd 700 added twice
ERROR:asyncio:Future exception was never retrieved
future: <Future finished exception=HTTP 599: SSL certificate problem: unable to get local issuer certificate>
tornado.curl_httpclient.CurlError: HTTP 599: SSL certificate problem: unable to get local issuer certificate
Process finished with exit code -1
I'm not sure if this is the only problem here, but the NotImplementedError is because Python 3.8 on Windows uses a different event loop implementation that is incompatible with Tornado. You need to add asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) to the beginning of your main file/function.
I suspect you may also need to use the ca_certs argument to tell libcurl where to find the trusted root certificates for your proxy.
I am trying out pyro4 connection between my PC and Raspberry Pi 4.
Code on my PC is:
# saved as server.py
import Pyro4, Pyro4.naming
import socket, threading
# Define an object that will be accessible over the network.
# This is where all your code should go...
#Pyro4.expose
class MessageServer(object):
def show_message(self, msg):
print("Message received: {}".format(msg))
# Start a Pyro nameserver and daemon (server process) that are accessible
# over the network. This has security risks; see
# https://pyro4.readthedocs.io/en/stable/security.html
hostname = socket.gethostname()
ns_thread = threading.Thread(
target=Pyro4.naming.startNSloop, kwargs={'host': hostname}
)
ns_thread.daemon = True # automatically exit when main program finishes
ns_thread.start()
main_daemon = Pyro4.Daemon(host=hostname)
# find the name server
ns = Pyro4.locateNS()
# register the message server as a Pyro object
main_daemon_uri = main_daemon.register(MessageServer)
# register a name for the object in the name server
ns.register("example.message", main_daemon_uri)
# start the event loop of the main_daemon to wait for calls
print("Message server ready.")
main_daemon.requestLoop()
And code on my Raspberry is:
import Pyro4
import sys
print("Message:")
msg=sys.stdin.readline().strip()
message_server = Pyro4.Proxy("PYRONAME:192.168.1.5")
message_server.show_message(msg)
Code on my PC doesn t show any errors, but when I try to send a message from raspberry i get this:
What s your message?
test
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/socketutil.py", line 102, in getIpAddress
return getaddr(config.PREFER_IP_VERSION) if ipVersion is None else getaddr(ipVersion)
File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/socketutil.py", line 94, in getaddr
ip = socket.getaddrinfo(hostname or socket.gethostname(), 80, family, socket.SOCK_STREAM, socket.SOL_TCP)[0][4][0]
File "/usr/lib/python3.7/socket.py", line 748, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 515, in connect_and_handshake
sslContext=sslContext)
File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/socketutil.py", line 266, in createSocket
if getIpVersion(connect[0]) == 4:
File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/socketutil.py", line 68, in getIpVersion
address = getIpAddress(hostnameOrAddress)
File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/socketutil.py", line 106, in getIpAddress
return getaddr(0)
File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/socketutil.py", line 94, in getaddr
ip = socket.getaddrinfo(hostname or socket.gethostname(), 80, family, socket.SOCK_STREAM, socket.SOL_TCP)[0][4][0]
File "/usr/lib/python3.7/socket.py", line 748, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/pi/Desktop/client.py", line 10, in <module>
message_server.show_message(msg)
File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 275, in __getattr__
self._pyroGetMetadata()
File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 615, in _pyroGetMetadata
self.__pyroCreateConnection()
File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 588, in __pyroCreateConnection
uri = _resolve(self._pyroUri, self._pyroHmacKey)
File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 1915, in _resolve
return nameserver.lookup(uri.object)
File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 275, in __getattr__
self._pyroGetMetadata()
File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 615, in _pyroGetMetadata
self.__pyroCreateConnection()
File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 596, in __pyroCreateConnection
connect_and_handshake(conn)
File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 549, in connect_and_handshake
raise ce
Pyro4.errors.CommunicationError: cannot connect to ('JAKOB-PC', 9090): [Errno -2] Name or service not known
My PC has its firewall disabled, so there shouldn t be any problem with that. My local ip is 192.168.1.5.
I am using a headless Raspberry and write code on it with puTTY and VNC.
I have googled this error but couldn t find any answers. Any help would be appreciated.
I did this
#
# Server.py
#
from __future__ import print_function
import Pyro4
#Pyro4.expose
#Pyro4.behavior(instance_mode="single")
class Messenger(object):
# This is a constructor
def __init__(self):
pass
# This method will be called on the server
def send_message(self, name, message):
print("[{0}] {1}".format(name, message))
def main():
Pyro4.Daemon.serveSimple(
{
Messenger: "example.messenger"
},
ns=True)
if __name__ == "__main__":
main()
#
# Client.py
#
# This is the code that visits the warehouse.
import sys
import Pyro4
import Pyro4.util
sys.excepthook = Pyro4.util.excepthook
messenger = Pyro4.Proxy("PYRONAME:example.messenger#192.168.1.5")
messenger.send_message("Tim", "Hello!")
Then ran
python -m Pyro4.naming -n 192.168.1.5
python Server.py
python Client.py
In short I couldn't solve the problem with Pyro and (almost) no one helped so I decided to use 'websockets' instead.
You can read the documentation here but I'll explain it here anyway.
First of all you need two devices with network connection. You also have to run python 3.6.1 on both of them. After that you also need to install websockets if you don't have them already with pip install websockets or as I had to do it with pip3 install websockets.
Code below runs on the server and handles messages you send to it from client. Function 'hello' is a simple example of processing request and sending back a response. 'request' is the data server receives, that data must be bytes, string on iterable. Response is made by converting request to integer, squaring it and converting it back to string. This response is then sent back to client.
'start_server' defines the server, function that will define its behavior(hello), ip address on witch the server is running on(192.168.1.117) and port on witch it will receive requests(8765).
!/usr/bin/env python
import asyncio
import websockets
print("Running...")
async def hello(websocket, path):
request = await websocket.recv()
print("Request: " + request)
response = str(int(request)*int(request))
await websocket.send(response)
print("Response:" + response)
start_server = websockets.serve(hello, "192.168.1.117", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Next bit is code on the client. 'uri' is ip and port of the server. Function 'tellServ' asks you to input some data('tell' variable) and sends it to the server. After that it waits for reply and once it gets it it prints it out. In this case if I would input number "6" server would reply with "36". Function loop is in a while loop so I can send multiple numbers without having to restart the script.
#!/usr/bin/env python
import asyncio
import websockets
uri = "ws://192.168.1.117:8765"
async def tellServ():
async with websockets.connect(uri) as websocket:
tell = input("Podatek ki ga posles: ")
await websocket.send(tell)
reply = await websocket.recv()
print("Odgovor:")
print(reply)
while 1:
asyncio.get_event_loop().run_until_complete(tellServ())
I am trying to connect to JMS queue by spring-python. I take example of receiver from official spring python site
enter code herefrom springpython.jms.core import JmsTemplate
from springpython.jms.factory import WebSphereMQConnectionFactory
qm_name = "my_qmname"
channel = "my_channel"
host = 'my_host'
listener_port = 'my_port'
queue1 = "MY_QUEUE"
# The connection factory we're going to use.
factory = WebSphereMQConnectionFactory(qm_name, channel, host, listener_port)
# Every JmsTemplate uses a connection factory for actually communicating with a JMS provider.
jms_template = JmsTemplate(factory)
# Get a message off the queue. The call to receive will by default time out
# after 1000ms and raise springpython.jms.NoMessageAvailableException then.
jms_template.receive(queue1)
# We're not using an IoC so we need to shut down the connection factory ourselves.
factory.destroy()
And i get next error:
Traceback (most recent call last):
File "E:/Repos/provisioning/test.py", line 30, in <module>
jms_template.receive('MY_QUEUE')
File "c:\Python27\Lib\site-packages\springpython\jms\core.py", line 108, in receive
return self.factory.receive(dest, timeout)
File "c:\Python27\Lib\site-packages\springpython\jms\factory.py", line 327, in receive
self._connect()
File "c:\Python27\Lib\site-packages\springpython\util.py", line 45, in lockedfunc
return f(*args, **kwargs)
File "c:\Python27\Lib\site-packages\springpython\jms\factory.py", line 211, in _connect
raise exc
springpython.jms.WebSphereMQJMSException: MQSCO wrong size. Given: 540, expected 560
As i found MQSCO is something related to SSL, how can i fix the problem?
Thank you
So my twisted mail receiver is working nicely. Right up until we try to handle a case where the config is fubarred, and a mismatched cert/key is passed to the certificate options object for the factory.
I have a module, custom_esmtp.py, which includes an overload of ext_STARTLS(self,rest) which I have modified as follows, to include a try/except:
elif self.ctx and self.canStartTLS:
try:
self.sendCode(220, 'Begin TLS negotiation now')
self.transport.startTLS(self.ctx)
self.startedTLS = True
except:
log.err()
self.sendCode(550, "Internal server error")
return
When I run the code, having passed a cert and key that do not match, I get the following call stack:
Unhandled Error
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/twisted/internet/tcp.py", line 220, in _dataReceived
rval = self.protocol.dataReceived(data)
File "/usr/local/lib/python2.7/site-packages/twisted/protocols/basic.py", line 454, in dataReceived
self.lineReceived(line)
File "/usr/local/lib/python2.7/site-packages/twisted/mail/smtp.py", line 568, in lineReceived
return getattr(self, 'state_' + self.mode)(line)
File "/usr/local/lib/python2.7/site-packages/twisted/mail/smtp.py", line 582, in state_COMMAND
method('')
--- <exception caught here> ---
File "custom_esmtp.py", line 286, in ext_STARTTLS
self.transport.startTLS(self.ctx)
File "/usr/local/lib/python2.7/site-packages/twisted/internet/_newtls.py", line 179, in startTLS
startTLS(self, ctx, normal, FileDescriptor)
File "/usr/local/lib/python2.7/site-packages/twisted/internet/_newtls.py", line 139, in startTLS
tlsFactory = TLSMemoryBIOFactory(contextFactory, client, None)
File "/usr/local/lib/python2.7/site-packages/twisted/protocols/tls.py", line 769, in __init__
contextFactory = _ContextFactoryToConnectionFactory(contextFactory)
File "/usr/local/lib/python2.7/site-packages/twisted/protocols/tls.py", line 648, in __init__
oldStyleContextFactory.getContext()
File "/usr/local/lib/python2.7/site-packages/twisted/internet/_sslverify.py", line 1429, in getContext
self._context = self._makeContext()
File "/usr/local/lib/python2.7/site-packages/twisted/internet/_sslverify.py", line 1439, in _makeContext
ctx.use_privatekey(self.privateKey)
OpenSSL.SSL.Error: [('x509 certificate routines', 'X509_check_private_key', 'key values mismatch')]
Line 286 of custom_esmtp.py is the self.transport.startTLS(self.ctx). I've looked through all the twisted modules listed in the stack, at the quoted lines, and there are no other try/except blocks.... So my understanding is that the error should be passed back up the stack, unhandled, until it reaches my handler in custom_esmtp.py? So why is it not getting handled - especially since the only except I have is a "catch all"?
Thanks in advance!
If you want this error to be caught, you can do:
from OpenSSL import SSL
# ...
try:
# ...
except SSL.Error:
# ...
Perhaps the syntax changes a bit. I can't check because I don't use this precise package, but the idea is that you have to declare the import path of the exceptions you want to catch.