In my PowerShell script I SSL connect to windows server with the following code:
#SSL connecting to server
add-type #"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"#
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
How do I do it with Python script (without request me for a Certificate path)?
import socket
import ssl
# SET VARIABLES
packet, reply = "<packet>SOME_DATA</packet>", ""
HOST, PORT = 'XX.XX.XX.XX', 4434
# CREATE SOCKET
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
# WRAP SOCKET
wrappedSocket = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_TLSv1, ciphers="ADH-AES256-SHA")
# CONNECT AND PRINT REPLY
wrappedSocket.connect((HOST, PORT))
wrappedSocket.send(packet)
print wrappedSocket.recv(1280)
# CLOSE SOCKET CONNECTION
wrappedSocket.close()
Related
I have a python socket server that receives a string from an Android app and should return the same string in uppercase. The app can send the string and I receive it in the server but how could I receive the returned string in the Android studio?
Here is my python code:
import socket
HOST = "127.0.0.1" # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
print(data)
if not data:
break
conn.sendall(data.upper())
Here is my sending message function
Socket s;
PrintWriter pw;
#Override
protected Void doInBackground(String... voids) {
String message = voids[0];
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
try {
s = new Socket("10.0.2.2", Integer.parseInt("65432"));
//sending data
pw = new PrintWriter(s.getOutputStream());
pw.write(message);
pw.flush();
pw.close();
//////////
//receiving data
s.close();
} catch (IOException e) {
e.printStackTrace();
}
I have a program in python named server.py and I want to send multiple messages to client.cs using a socket, and use them while python program is still running.
I tried before in py (server) to py (client) and it works, but when I try py (server) to C# (client) I get multiple exceptions.
This is server.py:
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 7634
s.bind((host, port))
s.listen(1)
con, addr = s.accept()
print("Connected with: ", addr)
message = 1800
while message <= 2000:
con.send(str(message).encode())
message += 1
time.sleep(0.1)
Client.py:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 7634
s.connect((host, port))
message = 1800
while message <= 2000:
message = int(s_messg.decode())
print(message, "\n")
As I said before this works fine
Sending 1800 and instantly receiving 1800
Sending 1801 and instantly receiving 1801
...
Sending 2000 and instantly receiving 2000
I saw C# client code from Microsoft doc, but as I said before I get multiple exceptions:
SocketException: System.Net.Internals.SocketExceptionFactory+ExtendedSocketException
It says that the connection could not be established.
try
{
server = "127.0.0.1";
Int32 port = 7634;
TcpClient client = new TcpClient(server, port);
NetworkStream stream = client.GetStream();
Byte []data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
So i am trying to connect with the server side that i wrote in python(noob) with i simple Almofire network call.
The python code is this:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234))
s.listen(5)
while True:
# now our endpoint knows about the OTHER endpoint.
clientsocket, address = s.accept()
print(f"Connection from {address} has been established.")
and the swift is this:
func preformCall( success: #escaping () -> Void, failure: #escaping () -> Void) {
let url = "http://{my ip}:1234/"
Alamofire.request(url, method: .get).responseJSON { (response) in
if response.result.isFailure {
failure()
}
if let data = response.data {
let response = Response.init(data: data)
}
}
}
My ip - ip from network preferences (mac)
also i am connected to the same wifi.
If i take the same address to a browser i get this in the server side(terminal):
Connection from ('127.0.0.1', 52084) has been established.
Same when I connect to there sever with a simulator device it succeeded(url is - 127.0.0.1:1234), but when I try connecting from a real device it fails and I get this error :Code=-1004 "Could not connect to the server."
How can I test a connection from a real device and a localhost server?
So the answer was to listen to this address :0.0.0.0
s.bind(("0.0.0.0", 1234))
0.0. 0.0 means all IPv4 addresses on the local machine
It seems as if your are lunching rest request instead of connecting to the server via sockets. i dont think alamoFire is build to handle sockets. Try this.
https://github.com/daltoniam/Starscream
I am trying to connect my android app (client) to my PC (python server). They are both on the same network. I can ping my android phone from my PC and PC from phone. But when I try to connect them using sockets android app gets stuck at connecting and after a while throws a timeout exception.
Here is the code of Android Client class:
public class Client extends AsyncTask<Void, Void, Void> {
private String mCommand;
private String mHostIP;
public Client(String mCommand, String mHostIP) {
this.mCommand = mCommand;
this.mHostIP = mHostIP;
}
#Override
protected Void doInBackground(Void... voids) {
try {
InetAddress serverAddr = InetAddress.getByName(mHostIP);
Socket soc = new Socket(serverAddr,9999);
OutputStream toServer = soc.getOutputStream();
PrintWriter output = new PrintWriter(toServer);
output.println(mCommand);
DataOutputStream out = new DataOutputStream(toServer);
out.writeBytes(mCommand);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
It gets stuck at new Socket and throws exception after a while.
Here is the code for Python server:
import socket
import os
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
print('My IP: '+IPAddr)
port = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("socket successfully created")
server_address = ('192.168.10.4', 9999)
s.bind(server_address)
s.listen(1)
print ("socket is listening")
while True:
try:
c, addr = s.accept()
print ('Got connection from', addr)
type = c.recv(1024).decode('utf-8')
print(type)
finally:
print('Could not connect')
c.close()
break
Have a close look at your firewall.
I am trying to setup a Python TCP client-server session, but the client side is throwing this error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)
I am using a freshly generated LetsEncrypt certificate. I've stored the fullchain.pem (public certificate) on my computer which I'm running the client from, and yet it can't verify the authenticity. I am sure that fullchain.pem is the public key and privkey.pem is the private key, so I don't see why this isn't working. I've also tried using cert.pem for public too, which does not work either. Is anyone able to provide some insight on as to why the verification fails? Below is the client and server programs.
Client:
import sys
import socket
import os
import ssl
from backports.ssl_match_hostname import match_hostname, CertificateError
def connect(hostname, port, message):
"""
Connects to the hostname on the specified port and sends a message
:param hostname:
:param port:
:param message:
:return:
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # create a TCP socket
try:
s.connect((hostname, port)) # establish a TCP connection to the host
#ca_certs_path = os.path.join(os.path.dirname(sys.argv[0]), 'fullchain.pem')
ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)
#sslsock = ctx.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23, cert_reqs=ssl.CERT_REQUIRED, ca_certs=ca_certs_path)
sslsock = ctx.wrap_socket(s, server_hostname='encryptio.tk')
# Check if the server really matches the hostname to which we are trying to connect
match_hostname(sslsock.getpeercert(), hostname)
sslsock.send(message.encode('utf-8')) # send the message
except Exception as e:
sys.exit('[-]' + str(e))
def main():
connect('encryptio.tk', 12000, 'Client says hello') # replace '' with the hostname, 12000 as the port, and 'Hello' as the message
if __name__ == '__main__':
main()
Server:
import sys
import socket
import ssl
from backports.ssl_match_hostname import match_hostname, CertificateError
# Servers do not care whether clients connect with certificates
def listen(port):
"""
Listens on the specified port and accepts incoming connections
:param port:
:return:
"""
# server_socket - welcoming socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('', port)) # establish welcoming socket
ca_certs_path = '/etc/letsencrypt/live/encryptio.tk/fullchain.pem'
priv_certs_path = '/etc/letsencrypt/live/encryptio.tk/privkey.pem'
# listen for TCP connection requests.
server_socket.listen(1) # parameter specifies the maximum number of queued connections (at least 1)
ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ctx.load_cert_chain(certfile=ca_certs_path, keyfile=priv_certs_path)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print('[*] The server is ready to receive')
while 1:
try:
# When a client knocks on this door, the program invokes the accept() method for
# server_socket, which creates a new socket in the server, called connec-
# tion_ocket, dedicated to this particular client. The client and server then complete
# the handshaking, creating a TCP connection between the client’s client_socket
# and the server’s connection_socket
#connection_socket, addr = server_socket.accept()
#sslsock = ssl.wrap_socket(server_socket, ssl_version=ssl.PROTOCOL_SSLv23, cert_reqs=ssl.CERT_REQUIRED, server_side=True, certfile=ca_certs_path, keyfile=priv_certs_path)
connection_socket, addr = server_socket.accept()
sslsock = ctx.wrap_socket(connection_socket, server_side=True)
data = sslsock.read()
#message = connection_socket.recv(1500)
print('[+] From' + str(addr) + ': ' +
data.decode('utf-8'))
except Exception as e:
sys.exit('[-] ' + str(e))
#connection_socket.close()
sslsock.shutdown(socket.SHUT_RDWR)
sslsock.close()
def main():
listen(12000)
if __name__ == '__main__':
main()
EDIT:
I tried setting the CA in the client side program to a root certificate, and now I get this error:
[X509] PEM lib (_ssl.c:3053)
In your client you have this:
ca_certs_path = os.path.join(os.path.dirname(sys.argv[0]), 'fullchain.pem')
sslsock = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23,
cert_reqs=ssl.CERT_REQUIRED, ca_certs=ca_certs_path)
The default for ca_certs is None in ssl.wrap_socket which means that you have to provide a useful path if you use the non-default ssl.CERT_REQUIRED. Only, the path you provide seems to be the certificate chain you use in your server, i.e. server certificate and chain certificates but not the root certificate. Instead the ca_certs on the client side should only contain the root certificates, since this is the trust anchor which is used to build the trust chain using the certificates sent by the server (i.e. server certificate and chain).
Instead of using your own CA store you might also use the system wide store. With current versions of Python you can simply use the following code which creates a SSL context using the default CA store and with certificate and hostname validation enabled and then upgrades the socket to SSL and checks the certificate properly:
s.connect((hostname, port))
ctx = ssl.create_default_context()
sslsock = ctx.wrap_socket(s, server_hostname='example.com')