Port scan fails when firewall is enabled - python

I have windows client system environment , when i do port scan with below command i do not get response if firewall is turned on.
Q1. i would like to know if any method i can get response whenever if firewall turned on or not?
Q2. Any port is always open in a windows system so that i can get response.
Note: Disable Firewall option is not suitable for me as when ever i do change computer domain settings firewall turned on by default for domain Networks in firewall
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ClientIP = '10.xxx.xxx.xxx'
def portscanner(port):
try:
s.connect((ClientIP,port))
return True
except:
return False
for x in range(8000,8003):
if portscanner(x):
print("Port is open",x)
else:
print("port is closed",x)

When the port is blocked by a firewall, you can't detect the failure until a timeout. You can set a short timeout.
s.settimeout(1);
This will only wait 1 second before giving up.

Related

Server connectivity validation through python codes

I have a MySQL server hosted at a particular IP and port. Now, I need to validate this connectivity whether the server is up or down. Also this server uses a self-signed SSL certificate.
Does anyone have any reference python snippet that would comply this connectivity validation along with SSL certificate verification?
Trye the same thing you'd do from a command line. E.g. when you ``telnetserver port, then you get "connection refused" if a server is not listening on the given port, or a timeout if server:port is behind a firewall, or "No route to host" etc. For a successful connection you get something.
Self signed certs can't be validate, AFAIK, and this will work for ssl connections too.
import telnetlib
server_ip = '192.168.2.1'
server_port = 80
timeout = 5
conn_ok = False
try:
tn = telnetlib.Telnet(server_ip, server_port, timeout)
conn_ok = True
except Exception as e:
print(e)
tn.close()

Sending Emails through Django - WinError 10060 A connection attempt failed and GetAddrInfo Error

I've been running an instance of Django on Windows R2 2012 for over a year and I've come to a road block. Yesterday something happened, I don't know what it could be. The same two errors keep popping up at different times though when trying to send an email:
[WinError 10060] A connection attempt failed because the connected
party did not properly respond after a period of time, or established
connection failed because connected host has failed to respond
and
socket.gaierror: [Errno 11001] getaddrinfo failed
Users are able to connect to the IP address of the server and the port Django is running on 192.168.1.5:8000, but they cannot send emails anymore. Though a percentage do go through as described here, but very few.
Things I've tried
1) This solution
import socket
socket.getaddrinfo('localhost', 8000)
Since I'm doing python manage.py runserver 192.168.1.5:8000, I added that IP and nothing.
2) I went into the Firewall settings and made sure that the ports were all good. The SMTP one that is declared in the setting.py file in my Django project and 25. All of them, inbound and out.
3) I tried sending things on my local machine and it does work. I used other programs that do not use Django to send emails and they do process on all other machines except the Server. So I know it's not my email server.
4) I changed the email config to use my Gmail account and it does process on all other machines except for the server. So it has to be the environment.
5) Editing http_proxy environment variables
The problem, in my case, was that some install at some point defined
an
environment variable http_proxy on my machine when I had no proxy.
Removing the http_proxy environment variable fixed the problem.
As described here
and in my Django project in the wsgi.y file:
os.environ['http_proxy'] = "http://192.168.1.5:8080"
os.environ['https_proxy'] = "http://192.168.1.5:8080"
6) Given this answer here (can someone please explain how I would do it to a django email function), I've also tried this method of wrapping it from solutions here
import smtplib
import socks
#socks.setdefaultproxy(TYPE, ADDR, PORT)
socks.setdefaultproxy(socks.SOCKS5, '192.168.1.5', 8080)
socks.wrapmodule(smtplib)
smtpserver = 'smtp.live.com'
AUTHREQUIRED = 1
smtpuser = 'example#hotmail.fr'
smtppass = 'mypassword'
RECIPIENTS = 'mailto#gmail.com'
SENDER = 'example#hotmail.fr'
mssg = "test message"
s = mssg
server = smtplib.SMTP(smtpserver,587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(smtpuser,smtppass)
server.set_debuglevel(1)
server.sendmail(SENDER, [RECIPIENTS], s)
server.quit()
Though I wouldn't like to use such a method as I'd prefer using Django's built in email service.
Since you have not changed the code and errors you shared shows that it's a network related problem.
It's most probably a DNS issue. In your settings.py you have specified the EMAIL_HOST, which is i believe a hostname. You need to check you server's DNS server.
You are mentioning about checking your firewall settings but what you are doing wrong is not checking the actual connection.
To address the problem you can use couple of command line utilities like telnet or nslookup. You can check if you can resolve a hostname:
nslookup smptp.mail_host.com
This command will fail most probably.
I would like to point what you did wrong in your steps:
1) You have tried to get your services getaddrinfo in which you needed to put your smtp servers hostname, which would result with the same error. Sockets are the very primitive part of the connection on the application layer, you don't really need to dig in to that.
2) Checking firewall settings is OK.
3) This is a good step which shows that there is a problem with your servers network connection.
4) That is another evidence :)
5) You have got it wrong, if you have a proxy server on your network to connect external networks, than you use this settings. But you have configured it wrong. You should not set your projects url as proxy server.
6) This is another deep level coding. You should not use such low level script, which will cause you numerious problems, which would have been handled in high level modules.
I focused my answer on the strange fact that you can get around the problem using a SOCKS5 proxy. (I believe you. There was no time to ask you for details.) You verified that your example solution by SOCKS5 works for you. Django uses the same smtplib and you can easily wrap it the same way by this code added to wsgi.py.
import smtplib
import socks # it is the package SocksiPy or PySocks
socks.setdefaultproxy(socks.SOCKS5, '192.168.1.5', 8080)
socks.wrapmodule(smtplib)
Http(s) proxy (paragraph 5)) is not related because it does not affect SMTP and other protocols except http(s) because "SOCKS operates at a lower level than HTTP proxying".

Asterisk AMI no longer allows connection

I have been connecting my Python script to Asterisk AMI and things have been fine but suddenly it just stopped receiving connections I suppose. My manager.conf looks like this
[general]
enabled = yes
port = 5038
bindaddr = 0.0.0.0
displayconnects = yes
[myusername]
secret = mysecret
deny=0.0.0.0/0.0.0.0
permit=111.222.333.444/255.255.255.0
read = all
write = all
Suddenly it just stopped working. I tried to connect to the address 111.222.333.444 with the port 5038 on Telnet using Putty but the connection was refused. Please what might go wrong suddenly?
Try:
asterisk*CLI> manager show status
to verify for the interface.
Also you can do it from Linux, it's a standard TCP socket:
netstat -lna | grep 5038
netstat -lnap | grep asterisk
Try these:
Action: Login
Username: username
Secret: password
Hit two enters then.
Try to paste it from clipboard instead of typing. It may time out otherwise.
I'm reading that you have tried PuTTY I guess from a remote machine and you got "connection refused". Butt using telnet on the local machine Works for you, so it must be a firewall problem (iptables?).

Unable to change DNS resolver to localhost

I configured my windows machine's DNS server to 127.0.0.1 and on localhost I created a basic python server:
from socket import *
serverPort = 53
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('127.0.0.1', serverPort))
print "The server is ready to receive on port: {}".format(serverPort)
while 1:
try:
message, clientAddress = serverSocket.recvfrom(512)
except:
continue
print clientAddress, message
modifiedMessage = "127.0.0.1"
serverSocket.sendto(modifiedMessage, clientAddress)
PS :I know that DNS is a binary protocol and sending ASCII text won't do any good, but I am not trying to make a resolver, I am trying to see with transperancy that how the former works.
When I srarted the server, I am greated with the following output:
(('127.0.0.1', 53945), '.\x9c\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01')
(('127.0.0.1', 53945), '.\x9c\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01')
(('127.0.0.1', 53945), '.\x9c\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01')
(('127.0.0.1', 61362), '\xefc\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01')
(('127.0.0.1', 50065), '\xb5\xfc\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x06google\x03com\x00\x00\x01\x00\x01')
(('127.0.0.1', 61362), '\xefc\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01')
(('127.0.0.1', 61362), '\xefc\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01')
(('127.0.0.1', 52718), '\xc7\x15\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x05tiles\x08services\x07mozilla\x03com\x00\x00\x01\x00\x01')
But unlike as I enticipated, I am still able to open websites. And Wireshark told me that I am making connection to 8.8.8.8(IDK how?).
I tried flushing the DNS cashe from my machine, nada.
What am I missing?
PPS: If I remove the try/catch clause I get this error(a few seconds after the execution of the program):
error: [Errno 10054] An existing connection was forcibly closed by the remote host
You probably have configured Googles 8.8.8.8 as a fallback DNS server.
And since you are destroying the DNS answers, whoever is receiving these broken answers is falling back to the secondary server. The whole path of DNS queries on a typical UN*X machine is quite complicated and the whole system is usually quite robust.

How to ssh over HTTP proxy in Python Paramiko?

I am adapting a Python script to be OS independent and run on Windows. I have changed its ssh system calls to calls to paramiko functions. I am stuck with the issue of http proxy authentication. In Unix (actually Cygwin) environment I would use ~/.ssh/config
Host *
ProxyCommand corkscrew http-proxy.example.com 8080 %h %p
Is there a way to obtain the same using paramiko (or the Python ssh module) either using or not using corkscrew? This post seems to suggest that, but I don't know how.
Note: I am behind a firewall that allows me to use only port 80. I need to control Amazon ec2 instances so I configured the sshd server on those machines to listen to port 80. Everything is working fine in my cygwin+corkscrew prototype, but I would like to have a Python script that works without Cygwin.
You can use any pre-established session to paramiko via the sock parameter in SSHClient.connect(hostname,username,password,...,sock).
Below is a code-snippet that tunnels SSH via HTTP-Proxy-Tunnel (HTTP-CONNECT). At first the connection to the proxy is established and the proxy is instructed to connect to localhost:22. The result is a TCP tunnel over the established session that is usually used to tunnel SSL but can be used for any tcp based protocol.
This scenario works with a default installation of tinyproxy with Allow <yourIP> and ConnectPort 22 being set in /etc/tinyproxy.conf. The proxy and the sshd are running on the same host in my example but all you need is any proxy that allows you to CONNECT to your ssh port. Usually this is restricted to port 443 (hint: if you make your sshd listen on 443 this will work with most of the public proxies even thought I do not recommend to do this for interop and security reasons). If this ultimately allows you to bypass your firewall depends on what kind of firewall is employed. If there's no DPI/SSL-Interception features involved, you should be fine. If there's SSL-Interception involved you could still try to tunnel it via ssl or as part of HTTP payload :)
import paramiko
import socket
import logging
logging.basicConfig(loglevel=logging.DEBUG)
LOG = logging.getLogger("xxx")
def http_proxy_tunnel_connect(proxy, target,timeout=None):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
sock.connect(proxy)
LOG.debug("connected")
cmd_connect = "CONNECT %s:%d HTTP/1.1\r\n\r\n"%target
LOG.debug("--> %s"%repr(cmd_connect))
sock.sendall(cmd_connect)
response = []
sock.settimeout(2) # quick hack - replace this with something better performing.
try:
# in worst case this loop will take 2 seconds if not response was received (sock.timeout)
while True:
chunk = sock.recv(1024)
if not chunk: # if something goes wrong
break
response.append(chunk)
if "\r\n\r\n" in chunk: # we do not want to read too far ;)
break
except socket.error, se:
if "timed out" not in se:
response=[se]
response = ''.join(response)
LOG.debug("<-- %s"%repr(response))
if not "200 connection established" in response.lower():
raise Exception("Unable to establish HTTP-Tunnel: %s"%repr(response))
return sock
if __name__=="__main__":
LOG.setLevel(logging.DEBUG)
LOG.debug("--start--")
sock = http_proxy_tunnel_connect(proxy=("192.168.139.128",8888),
target=("192.168.139.128",22),
timeout=50)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname="192.168.139.128",sock=sock, username="xxxx", password="xxxxx")
print "#> whoami \n%s"% ssh.exec_command("whoami")[1].read()
output:
DEBUG:xxx:--start--
DEBUG:xxx:connected
DEBUG:xxx:--> 'CONNECT 192.168.139.128:22 HTTP/1.1\r\n\r\n'
DEBUG:xxx:<-- 'HTTP/1.0 200 Connection established\r\nProxy-agent: tinyproxy/1.8.3\r\n\r\n'
#> whoami
root
here are some other resources on how to tunnel through proxies. Just do whatever is needed to establish your tunnel and pass the socket to SSHClient.connect(...,sock)
There's paraproxy, which implements proxy support for Paramiko.
The post you linked to suggets that Paramiko can operate over an arbitrary socket, but that doesn't appear to be the case. In fact, paraproxy works by completing replacing specific methods inside paramiko, since the existing code simply calls socket.socket() to obtain a socket and does not offer any way of hooking in a proxy.

Categories

Resources