Whitelist a script for Internet Access - linux

We've a windows server and a linux server. There is no internet on both servers. Now, we need to deploy a python script on these servers which will make an http get request to an outside network url. So, I would need internet for that. But we can't enable internet for all applications. Is there a way we can enable internet only for this particular script?

I don't know well Linux platform, but you could allow the program to make outgoing requests with the command line, from python like so:
import sys
import os
def allow_outbound_connections(program_path):
"""
Allow program outbound connections.
"""
if "win" in sys.platform:
command = f'netsh advfirewall firewall add rule name="{program_path}" '\
'dir=out action=block program= "{os.path.basename(program_path}"'\
' enable=yes profile=any'
if "linux" in sys.platform:
# *Add a similar command in Linux*
with os.popen(command) as stream:
return stream.read()
def main():
# First allow this program to make outbound connections.
output = allow_outbound_connections(__file__)
# (Eventually you could handle the output)
# Now make request to an outside network url.

Related

Cannot create firewall or ACL in Python 3.11 on linux

I have to create simple python firewall or at least extended access control list like on Cisco program running on kali linux with newest python version.
I already have python sniffer using socket and struck and that works. Now i just need the program to decide when forward a packet if it follows some rules like source IP address or source port. In my sniffer i already extracted the ethernet, IP, TCP, UDP headers so i am able to make the decision for ACL based on it's fields successfully. Now i just need the program to drop and not forward it when decided.
I tried netfilterqueue, iptables, netfilter libraries but that doesn't seem to be working with python 3.11 and i'm worried that downgrade will disrupt my currently working sniffer. So is there a way to code a firewall or ACL with python 3.11 or 3.10 ?
This is a part of code i use to capture packet for deep inspection but then i have to extend it with firewall rules for forwarding decisions. Is there a chance to do it using socket. The if statement is an example of what i'm trying to achieve and that's force the program to drop the packet.
import socket
import struct
forbidden_ip = 192.168.1.5
interface = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0800)) # Linux
while True:
packet = interface.recvfrom(65565)
ip_header = struct.unpack("!BBHHHBBH4s4s", (packet[0][14:34]))
srcip = socket.inet_ntoa(ip_header[8])
dstip = socket.inet_ntoa(ip_header[9])
if srcip == forbidden_ip:
# now i need to drop the packet. iptables and netfilterqueue does not work for python 3.10 and 11
else:
continue

traffic forwarding with scapy between two interfaces

Hello I want to forward traffic between two interfaces to manipulate the packages between them (mitm). Here is my code:
from scapy.all import *
interfaces = {
"plc": "ens19",
"io": "ens20"
}
def pkt_PLC(pkt):
return True
def pkt_IO(pkt):
return True
def bridge():
bridge_and_sniff(interfaces["plc"], interfaces["io"],
xfrm12=pkt_PLC, xfrm21=pkt_io,
count=0, store=0)
if __name__ == "__main__":
conf.sniff_promisc=True
bridge()
The script is working and forwarding the traffic. My Problem is know that through the two interfaces is running are large amount of packages and the connection is not allowed to stop. My Problem is know that when i am looking at wireshark i can see that the connection is at points cut because not all the traffic is forwarded ,and so the application from which i am getting the traffic is stopped, after the short stop the traffic is again re transmitted. The process with stoping and res transmitting is repeated all the time. Ifthink
The setup is an industrial control station which is communicating with provinet. The component which i am siting between is the plc and and the rest of the system. When the system is starting it builds a connection with the rest of its components over profinet and continuously sends after that packages with profinet. Now if the communication is cut one needs to reset the error messages that the system can run again. Per second are about 3000 packages transmited.

How to redirect commands to a raspberry from an android App?

I have a trial version of a VPS, I want to use this as a server to send commands from a smartphone to the raspberry.
I am using http to send requests to the VPS but how can I redirect the commands received from the smartphone to the raspberry?
You can code a client-side script in Python which reads the response from the VPS each 2 seconds (or other time) and execute the command you want. E.g.
client-side script (read.py)
#client example
import socket, time
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('theVPSip', 80)) # port 80 by default
TIME = 2 # amount of time to wait. Do not saturate VPS server
while 1:
time.sleep(TIME)
data = client_socket.recv(512)
print "RECIEVED:" , data
import subprocess
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output = process.communicate()[0]
server-side script
Depending on what language you code, you will use a different syntax (of course). But I'll tell you what you have to do:
Register the Raspberry IP into a variable (only first time, experimenting, then let it fixed)
Register to-be-sent commands in a database
Check if the request comes from the RPi or from the phone.
RPi-> send command to execute as a return in plain text
Phone-> register data (taken from POST/GET request) into database
I suppose you could communicate with the raspberry using other model, but you would need to have a bigger control to the server and be able to run scripts of the kind of a socket connection (e.g. using Python/Java)

Establish IPSEC Tunnel between two Ubuntu 12.04 PCs over LAN

I have two ubuntu 12.04 32 Bit PCs between which I want IPSec Tunnel to be setup. I have setup ipsec in both systems and ipsec verify runs fine on both. Since I have no prior experience of openswan, I am finding it hard to set config files.
Here is the snippet of ipsec.config
config setup
# Do not set debug options to debug configuration issues!
# plutodebug / klipsdebug = "all", "none" or a combation from below:
# "raw crypt parsing emitting control klips pfkey natt x509 dpd private"
# eg:
# plutodebug="control parsing"
# Again: only enable plutodebug or klipsdebug when asked by a developer
#
# enable to get logs per-peer
# plutoopts="--perpeerlog"
#
# Enable core dumps (might require system changes, like ulimit -C)
# This is required for abrtd to work properly
# Note: incorrect SElinux policies might prevent pluto writing the core
dumpdir=/var/run/pluto/
#
# NAT-TRAVERSAL support, see README.NAT-Traversal
nat_traversal=yes
# exclude networks used on server side by adding %v4:!a.b.c.0/24
# It seems that T-Mobile in the US and Rogers/Fido in Canada are
# using 25/8 as "private" address space on their 3G network.
# This range has not been announced via BGP (at least upto 2010-12-21)
virtual_private=%v4:10.0.0.0/8,%v4:192.168.0.0/16,%v4:172.16.0.0/12,%v4:25.0.0.0/8,%v6:fd00::/8,%v6:fe80::/10
# OE is now off by default. Uncomment and change to on, to enable.
oe=off
# which IPsec stack to use. auto will try netkey, then klips then mast
protostack=netkey
# Use this to log to a file, or disable logging on embedded systems (like openwrt)
#plutostderrlog=/dev/null
# Add connections here
# sample VPN connection
# for more examples, see /etc/ipsec.d/examples/
conn linux-to-linux
# # Left security gateway, subnet behind it, nexthop toward right.
left=192.168.58.17
# leftsubnet=172.16.0.0/24
# leftnexthop=10.22.33.44
# # Right security gateway, subnet behind it, nexthop toward left.
right=192.168.58.32
# rightsubnet=192.168.0.0/24
# rightnexthop=10.101.102.103
# # To authorize this connection, but not actually start it,
# # at startup, uncomment this.
auto=start
Queries:
Now based on the given topology (see image) of my network, is the above config correct for both the PCs.
Is it have to be same for both left and right PCs.
After it is setup how do I confirm that secure tunnel is working, what is the best tool to check the algos being used and packet's content.
Inside LAN the secure ipsec tunnel is called host-to-host tunnel and the site-to-site connection refers to when VPN kicks in, right?
Quse 1)Now based on the given topology (see image) of my network, is the above config correct for both the PCs.
Ans) You have to provide ipsec.secrets file and the method of authentication like PSK/RSA
Ques 2)Is it have to be same for both left and right PCs.
Ans) Left and right should be interchanged.
Quse 3)After it is setup how do I confirm that secure tunnel is working, what is the best tool to check the algos being used and packet's content.
Ans) try to ping any system on central site.
Ques 4)Inside LAN the secure ipsec tunnel is called host-to-host tunnel and the site-to-site connection refers to when VPN kicks in, right?
Ans) No, host-to host ans site-to-site are two different VPN configuration depending upon network topology

Router blocking response from external networks

I'm working on a company network right now, and I've come across a problem where my scripts cannot connect to external networks. I'm just wondering if anyone knows common practices in network security that may cause this?
Ex. I can visit www.example.com on firefox, but my python script will get a timeout error if it tries to connect.
These scripts work perfectly fine on another network or if I change the URL to something on the local network.
import urllib.request
f = urllib.request.urlopen('http://www.python.org/')
print(f.read(300))
ANSWER: the browser uses the network's proxy. Scripts also have to use that proxy to run
import urllib.request
proxy = urllib.request.ProxyHandler({'http': '127.0.0.1'})
opener = urllib.request.build_opener(proxy)
urllib.request.install_opener(opener)
req = urllib.request.urlopen('http://www.google.com')
print(req.read())
It is very likely that your browser is configured to use a proxy. If that is true, then you will need to augment your python script with ProxyHandler (see Proxy with urllib2)

Resources