Anonymize the programs from your terminal with-torify - tor

By using this tutorial Torify app terminal
I find this error
*WARNING torsocks[5359]: [connect] Connection to a local address are denied since it might
be a TCP DNS query to a local DNS server. Rejecting it for safety reasons. (in tsocks_connect() at connect "
.c:186)*
knows how to patch this?
Ubuntu server 16.04
My command: sudo torify python3 torPython.py
My code here:
from urllib.request import urlopen
from stem import Signal
from stem.control import Controller
with Controller.from_port(port = 9051) as controller:
controller.authenticate(password='dummy123456admin')
print("Success!")
controller.signal(Signal.NEWNYM)
print("New Tor connection processed")
print(urlopen('http://icanhazip.com').read())

Related

Python3 requests not passing proxy authentication on Ubuntu server

The code is as follows:
import requests
proxy = 'username:password#ip:9999'
print(requests.get('https://api.ipify.org/', proxies={'http': f'http://{proxy}', 'https': f'http://{proxy}'}).text)
(username, password and ip have been omitted)
OS = Ubuntu 20.04.5 LTS
Python version = 3.8.10
Requests version = 2.28.1
When ran on said server Proxy-Authorization is not passed in the connection headers. However when running the exact same script on my Windows device it is passed.
Before opening an issue on GitHub, I wanted to see if anyone knows why this may be?

Requests library does not perform HTTP requests inside mitmproxy

I installed mitmproxy by using pip (pip(3) install mitmproxy). I created a script that performs HTTP requests - I use https://requests.readthedocs.io/en/master/ obviously - on a specific trigger (e.g. an image or file went through the reverse proxy).
Versions: Python 3.9.1 for Windows 10 64 bits, pip version 20.2.3, and mitmproxy 6.0.2.
#staticmethod
def _file_exists(file_name: str) -> bool:
request_path = "https://<url>/{}".format(file_name)
req = requests.get(request_path) # import requests
return True if req.status_code == 200 else False
This blocks forever if I use the command mitmdump -s script.py. Adding a timeout will result in a TCP timeout exception - for HTTP and TLS.
I tried the following:
Re-installing the SSL certificate of mitmproxy
Using a clean Windows installation
I tried to connect to an IP address
I tried to connect without HTTPS
I'm stuck. Any ideas?

Run 2 Python3 `http.server` on the same machine, different ports

Situation: Need 2 ad-hoc Python3 http.server instances on the same computer.
Problem: The first server was started successfully on the command line
python3 -m http.server 8888
The second server was attempted with the following script:
import http.server
import socketserver as ss
os.chdir("/path/to/working/directory")
Handler = http.server.SimpleHTTPRequestHandler
with ss.TCPServer(("", 8000), Handler) as httpd:
try:
httpd.serve_forever()
except PermissionError:
print("Permission denied.")
The second server terminated with OSError: [Errno 98] Address already in use.
Question: How can I run two Python3 http.server on the same machine (listening on 0.0.0.0)?
Additional Information 1: I have checked, and there are no other services holding onto port 8888 (server 1's port), and 8000 (server 2's port).
Additional Information 2: I am not sure why, but if I reverse the two ports, both servers run as intended (i.e. server 1 runs on port 8000; server 2 runs on 8888). Any ideas why?

Websocket Autobahn Python client: how to connect to server using server and client certificates?

A websocket client (using Autobahn/Python and Twisted) needs to connect to a websocket server: the client needs to present its client certificate to the server and the client needs to check the server's certificate. These certificates have been created, for instance, during setup of a Kubernetes minikube installation. In particular:
server certificate ~/.minikube/ca.crt (in X509 format from what I understand).
client certificate ~/.minikube/client.crt with key ~/.minikube/client.key.
I've checked that I can successfully use these certificates+key to issue Kubernetes remote API calls using curl.
From Autobahn's echo_tls/client.py example I understand that I may need to use a ssl.ClientContextFactory(). ssl here refers to the pyopenssl package that twisted automatically imports.
However, I cannot figure out how to pass the certificates to the factory?
How do I tell the websocket factor to present the client certificate to the server?
How do I tell the websocket to check the server's certificate in order to detect MITM attacks?
After some trial and error I've now arrived at this solution below. To help others I'll not only show code, but also a reference setup to test drive the example code.
First, install minikube, then start a minikube instance; I've tested with minikube 1.0.0, which then runs Kubernetes 1.14 which was current at the time of this writing. Then start a simple websocket server that just shows what is sent to it and will sent back any input you made to the connected websocket client.
minikube start
kubectl run wsserver --generator=run-pod/v1 --rm -i --tty \
--image ubuntu:disco -- bash -c "\
apt-get update && apt-get install -y wget && \
wget https://github.com/vi/websocat/releases/download/v1.4.0/websocat_1.4.0_ssl1.1_amd64.deb && \
dpkg -i webso*.deb && \
websocat -vv -s 0.0.0.0:8000"
Next comes the Python code. It attempts to connect to the wsserver we've just started via Kubernetes' remote API from the minikube, using the remote API as its reverse proxy. The minikube setup usually uses mutual SSL/TLS authentication of client and server, so this is a "hard" test here. Please note that there are also other methods, such as server certificate and bearer token (instead of a client certificate).
import kubernetes.client.configuration
from urllib.parse import urlparse
from twisted.internet import reactor
from twisted.internet import ssl
from twisted.python import log
from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS
import sys
if __name__ == '__main__':
log.startLogging(sys.stdout)
class EchoClientProto(WebSocketClientProtocol):
def onOpen(self):
print('onOpen')
self.sendMessage('testing...\n'.encode('utf8'))
def onMessage(self, payload, isBinary):
print('onMessage')
if not isBinary:
print('message %s' % payload.decode('utf8'))
def onClose(self, wasClean, code, reason):
print('onClose', wasClean, code, reason)
print('stopping reactor...')
reactor.stop()
# Select the Kubernetes cluster context of the minikube instance,
# and see what client and server certificates need to be used in
# order to talk to the minikube's remote API instance...
kubernetes.config.load_kube_config(context='minikube')
ccfg = kubernetes.client.configuration.Configuration._default
print('Kubernetes API server CA certificate at %s' % ccfg.ssl_ca_cert)
with open(ccfg.ssl_ca_cert) as ca_cert:
trust_root = ssl.Certificate.loadPEM(ca_cert.read())
print('Kubernetes client key at %s' % ccfg.key_file)
print('Kubernetes client certificate at %s' % ccfg.cert_file)
with open(ccfg.key_file) as cl_key:
with open(ccfg.cert_file) as cl_cert:
client_cert = ssl.PrivateCertificate.loadPEM(cl_key.read() + cl_cert.read())
# Now for the real meat: construct the secure websocket URL that connects
# us with the example wsserver inside the minikube cluster, via the
# remote API proxy verb.
ws_url = 'wss://%s/api/v1/namespaces/default/pods/wsserver:8000/proxy/test' % urlparse(ccfg.host).netloc
print('will contact: %s' % ws_url)
factory = WebSocketClientFactory(ws_url)
factory.protocol = EchoClientProto
# We need to attach the client and server certificates to our websocket
# factory so it can successfully connect to the remote API.
context = ssl.optionsForClientTLS(
trust_root.getSubject().commonName.decode('utf8'),
trustRoot=trust_root,
clientCertificate=client_cert
)
connectWS(factory, context)
print('starting reactor...')
reactor.run()
print('reactor stopped.')
The tricky part here when attaching the client and server certificates using optionsForClientTLS is that Twisted/SSL expects to be told the server's name we're going to talk to. This is also needed to inform virtual servers which one of their multiple server certificates they need to present -- before there will be any HTTP headers!
Unfortunately, this is now ugly territory -- and I would be glad to get feedback here! Simply using urlparse(ccfg.host).hostname works on some minikube instances, but not on others. I haven't yet figured out why seemingly similar instances behave differently.
My current workaround here is to simply use the CN (common name) of the subject from the server's certificate. Maybe a more robust way might be to only resort to such tactics when the URL for the remote API server uses an IP address literal and not a DNS name (or at least a label).
Alas, run the Python 3 code above python3 wssex.py. If the script correctly connects, then you should see a log message similar to 2019-05-03 12:34:56+9600 [-] {"peer": "tcp4:192.168.99.100:8443", "headers": {"sec-websocket-accept": ...
Additionally, the websocket server that you've started before should show log messages such as [INFO websocat::net_peer] Incoming TCP connection from Some(V4(172.17.0.1:35222)), and some more.
This then is proof that the client script has successfully connected to minikube's remote API via a secure websocket, passing authentication and access control, and is now connected to the (insecure) websocket demo server inside minikube.

Telnet [Unable to connect to remote host: Connection refused]

I was trying to create a telnet connection between Ubuntu and Guest OS (Kali). But the problem "Unable to connect to remote host: Connection refused" occurs in both Ubuntu terminal and Guest OS (Kali) Terminal. I configured Guest OS's ip settings as follows and I can send ping packets perfectly from both side.
According to ping packets sent and received, it seems there is no problem about connection line between these two system. But when I try to enter
In Ubuntu:
telnet ipAddressOfGuestOS
or
In Guest OS:
telnet ipAddressOfUbuntu
the terminal returns "Unable to connect to remote host: Connection refused" error. How can I handle this problem?
0.Configure Guest OS via Virtualbox as follows.
VirtualBox Manager > Settings > Network
Attached to: Bridged Adapter
Name : eth0
Advanced:
Promiscuous Mode: Allow All
1.Install telnet use this command in main OS terminal:
sudo apt-get install xinetd telnetd
2.Edit /etc/inetd.conf in main OS using your favourite file editor with root permission,add this line:
telnet stream tcp nowait telnetd /usr/sbin/tcpd /usr/sbin/in.telnetd
3.Edit /etc/xinetd.conf in main OS,make its content look like following:
Simple configuration file for xinetd
#
# Some defaults, and include /etc/xinetd.d/
defaults
{
# Please note that you need a log_type line to be able to use log_on_success
# and log_on_failure. The default is the following :
# log_type = SYSLOG daemon info
instances = 60
log_type = SYSLOG authpriv
log_on_success = HOST PID
log_on_failure = HOST
cps = 25 30
}
4.Use this command to start telnet server in main OS:
sudo /etc/init.d/xinetd restart
That was all. By the way, this configuration will affect just main OS which you use instead of Guest OS. That is, you can create a telnet connection just from Guest OS's terminal to main OS, not from main OS to Guest OS. Because, telnet server is in main OS. To be able to do two way telnet communication, you should repeat the steps above in Guest OS's terminal.
Resource : http://ubuntuguide.net/install-and-enable-telnet-server-in-ubuntu-linux
Attention: if you flush iptables (when run: iptables -F) it can just close your ssh connection, so you will not be able to connect to your server again
Check iptable rules.
iptables -L
Flush iptables
iptables -F
Try telnet again
first we need to see ubuntu system log with this command
sudo gedit /var/log/syslog
and if you will see this error "execv( /usr/sbin/tcpd ) failed: No such file or directory" then run this command
sudo apt-get install tcpd
it will solve your problem (if not then you need to search your system error on google)
Check telnet service is running
psgrep xinetd

Resources