Git Product home page Git Product logo

pytun's Introduction

Linux TUN/TAP wrapper for Python

pytun is a Python module which let you create TUN/TAP device very easily.

License: MIT (see LICENSE)

Installation and Dependencies

Install pytun with pip install python-pytun or download this archive, decompress it and execute python setup.py install. As pytun is a C module you will need a compiler (e.g GCC) and the Python development headers installed on your system (e.g on Debian-like distribution check that build-essential and python-dev are present). There are no dependencies other than the Python Standard Library.

Documentation

NOTE: On most distributions you will need to be root to create TUN/TAP devices.

To create a TUN device:

from pytun import TunTapDevice

tun = TunTapDevice()

To create a TAP device:

from pytun import TunTapDevice, IFF_TAP

tap = TunTapDevice(flags=IFF_TAP)

To create a TUN/TAP device with a custom name use the name keyword:

tun = TunTapDevice(name='mytun')

You can get/set some parameters of the device directly:

print tun.name
tun.addr = '10.8.0.1'
tun.dstaddr = '10.8.0.2'
tun.netmask = '255.255.255.0'
tun.mtu = 1500

If the device is a TAP you can also get/set its MAC address:

tap.hwaddr = '\x00\x11\x22\x33\x44\x55'
print tap.hwaddr

To make the device persistent:

tun.persist(True)

To bring up the device:

tun.up()

To bring down the device:

tun.down()

To enable/disable the queue associated with the device (works only if it has been created with IFF_MULTI_QUEUE):

tun.mq_attach() # enable the queue
tun.mq_attach(False) # disable the queue

To read/write to the device, use the methods read(size) and write(buf):

buf = tun.read(tun.mtu)
tun.write(buf)

To close the device:

tun.close()

You can also use TunTapDevice objects with all functions that expect a fileno() method (e.g select())

pytun's People

Contributors

ben9923 avatar cofob avatar davidcampelo avatar montag451 avatar ogasser avatar talkain avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pytun's Issues

when create a tap device and set it, ping this machine failed

Hello, when i create a tap device and config it's. But why can't ping this machine.
`tap = TunTapDevice(name="my_tap_0", flags=IFF_TAP)
tap.addr = '10.10.10.117'
tap.dstaddr = '10.10.10.10'
tap.netmask = '255.255.255.0'
tap.mtu = 1500

#tap.persist(True)
tap.up()

while True:
packet = tap.read(1024)
print(packet)`

image

why ping 10.10.10.10 failed, please.

pytun.Error: [Errno 2] No such file or directory

I tried this on Ubuntu for Windows, but I got following weird error:

>>> from pytun import TunTapDevice, IFF_TAP
>>>
>>> tap = TunTapDevice(flags=IFF_TAP)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
pytun.Error: [Errno 2] No such file or directory
>>> tun = TunTapDevice()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
pytun.Error: [Errno 2] No such file or directory
>>> TunTapDevice

Am I missed something?

ImportError: cannot import name TunTapDevice

[root@centos python-pytun-2.1]# python -V
Python 2.6.6

[root@centos python-pytun-2.1]# python setup.py install
running install
running build
running build_ext
building 'pytun' extension
creating build
creating build/temp.linux-x86_64-2.6
gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/include/python2.6 -c pytun.c -o build/temp.linux-x86_64-2.6/pytun.o
creating build/lib.linux-x86_64-2.6
gcc -pthread -shared build/temp.linux-x86_64-2.6/pytun.o -L/usr/lib64 -lpython2.6 -o build/lib.linux-x86_64-2.6/pytun.so
running install_lib
copying build/lib.linux-x86_64-2.6/pytun.so -> /usr/lib64/python2.6/site-packages
running install_egg_info
Writing /usr/lib64/python2.6/site-packages/python_pytun-2.1-py2.6.egg-info

[root@centos python-pytun-2.1]# cat mytest.py
from pytun import TunTapDevice
tun = TunTapDevice()

[root@centos python-pytun-2.1]# python mytest.py
Traceback (most recent call last):
File "mytest.py", line 1, in
from pytun import TunTapDevice
File "/root/Desktop/python-pytun-2.1/mytest.py", line 1, in
from pytun import TunTapDevice
ImportError: cannot import name TunTapDevice

How can i run tun test?

I need to automatically run test_tun.py in my project's unittests,

so how can i run the test_tun.py?

Installing on Windows

I have error while install using pip.

c:\py3\include\pyconfig.h(222): fatal error C1083: Cannot open include file: 'basetsd.h': No such file or directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2

    ----------------------------------------
Command "c:\py3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Ramiil\\AppData\\Local\\Temp\\pip-build-7l07d56t\\python-pytun\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Ramiil\AppData\Local\Temp\pip-83dn8uqm-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\Ramiil\AppData\Local\Temp\pip-build-7l07d56t\python-pytun\

I think I have solution, but I haven't tested it yet.

Solution:
Download(http://www.microsoft.com/en-us/download/details.aspx?id=3138) and install Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 SP1. You will need only:
Developer Tools > Windows Headers and Libraries <-- this gives you basetsd.h
Developer Tools > Visual C++ Compilers <-- this gives you the 64-bit compilers

From here - https://stackoverflow.com/questions/23691564/running-cython-in-windows-x64-fatal-error-c1083-cannot-open-include-file-ba

Error writing bytes

I guess this is more of a question. I created a persistent tun device with e.g.

ip tuntap add dev tun0 mode tun user tera
ip address add dev tun0 10.20.0.1/24
ip link set dev tun0 up

a simple program:

import pytun

tun = pytun.TunTapDevice('tun0')
buf = b'foo'
tun.write(buf)

when trying to write bytes, most of the time I get the following error

pytun.Error: [Errno 22] Invalid argument

What's the issue here? How are you supposed to write raw bytes? (Disregarding where they come from, for now)

Closing device does not unblock the read call

What is the recommended way to tear down the process when the thread is locked waiting for buf = tun.read(tun.mtu)?

I was hoping that closing the device using tun.close() from another thread would make the read return an empty buffer, therefore allowing to join the reception thread, but that does not seem to be the case.

Is using select the way to go here?

Any idea?

Thanks!

Noob question maybe,

Say I have pytun running locally at 1.2.3.4 (with a TAP ip of 10.0.0.1) and remotely at 4.5.6.7 (with TAP ip being 10.0.0.2), how do I get them to talk to each other over the internet? Of course, poke through NAT, but I can't seem to figure out how to tell one to talk to the other?

By the way, thank you very much for this library! I'm going to be using it in my own project, OTPTunnel. (The repo is currently empty as I don't have a working prototype yet.) It is to be an implementation of streaming One Time Pad encryption over a TAP or TUN interface (thanks to your project) using a truly random number (obtained with special hardware) as a sort of symmetric key. The idea is to make passive listening not just really, really hard to do, but mathematically impossible while at the same time making OTP less of a pain to deal with (of course, it will always be sort of inconvenient due to the key distribution problem). Eventually, I plan to evolve the project into a full suite of OTP-related tools.

PS. I accidentally clicked the 'fork' button but don't intend to modify the project. Just haven't figured out how to un-fork it yet.

Segfaults/glib corruptions because of tp_dealloc

Hello. It's not safe to use Py_BEGIN_ALLOW_THREADS in tp_dealloc because of this issue
http://bugs.python.org/issue17263
Just wanted to post for someone else wandering about strange segfaults in their programs.

I don't know right now how to avoid this problem, since we can't just remove Py_BEGIN_ALLOW_THREADS from there. Probably, just advice people to close their tun objects before the interpreter starts to shutdown

Upd: hmm, sorry, it seems that it's not related to your code at all, I just should not use daemon threads and correct issue is http://bugs.python.org/issue1856

PyPy Support

PyPy is a python implemention for python, which implemented JIT that can largely speed up the execution.

After I installed python-pytun for pypy and trying to use it, I got a import error

pypy -m pip install python-pytun
xxx-VirtualBox# pypy
Python 2.7.10 (5.3.1+dfsg-1~ppa1~ubuntu16.04, Jun 19 2016, 15:11:31)
[PyPy 5.3.1 with GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>> import pytun
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named pytun

Note: A file named pytun.pypy-41.so in dist-pakcages directory

Build fails on windows

Building on windows fails because 'unistd.h' was not found.

Setup details:
Windows 10 Pro
MSVC v143 (v14.31-17.1) (Visual Studio 2022)

pip error message:

Defaulting to user installation because normal site-packages is not writeable
Collecting python-pytun
  Using cached python-pytun-2.4.1.tar.gz (8.5 kB)
  Preparing metadata (setup.py) ... done
Building wheels for collected packages: python-pytun
  Building wheel for python-pytun (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [11 lines of output]
      running bdist_wheel
      running build
      running build_ext
      building 'pytun' extension
      creating build
      creating build\temp.win-amd64-3.10
      creating build\temp.win-amd64-3.10\Release
      C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Program Files\Python310\include -IC:\Program Files\Python310\Include -IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\include -IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.17763.0\\shared -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.17763.0\\um -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.17763.0\\winrt -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.17763.0\\cppwinrt /Tcpytun.c /Fobuild\temp.win-amd64-3.10\Release\pytun.obj
      pytun.c
      pytun.c(4): fatal error C1083: Cannot open include file: 'unistd.h': No such file or directory
      error: command 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.31.31103\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for python-pytun
  Running setup.py clean for python-pytun
Failed to build python-pytun
Installing collected packages: python-pytun
  Running setup.py install for python-pytun ... error
  error: subprocess-exited-with-error

  × Running setup.py install for python-pytun did not run successfully.
  │ exit code: 1
  ╰─> [11 lines of output]
      running install
      running build
      running build_ext
      building 'pytun' extension
      creating build
      creating build\temp.win-amd64-3.10
      creating build\temp.win-amd64-3.10\Release
      C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Program Files\Python310\include -IC:\Program Files\Python310\Include -IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\include -IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.17763.0\\shared -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.17763.0\\um -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.17763.0\\winrt -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.17763.0\\cppwinrt /Tcpytun.c /Fobuild\temp.win-amd64-3.10\Release\pytun.obj
      pytun.c
      pytun.c(4): fatal error C1083: Cannot open include file: 'unistd.h': No such file or directory
      error: command 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.31.31103\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
      [end of output]

IPv6 support

The current release does not support IPv6 TUN interfaces.
I'd be happy to help/create this support, but could use some direction as to naming convention for parameters, etc...

macOS Support

Hi!

I'm willing to add the library partial support for macOS.
Many of the features will just returned NotImplementedError, but the most crucial should work just fine.
Will you be willing to merge this PR once I open it?

Can I assign the created tap interface to a virt-machine?

my usecase is:

  1. create a tap device with a specified name.
  2. the process that creates the tap device exits.
  3. let a qemu-kvm virt-machine use the created tap device.
  4. delete this tap device after the virt-machine quits.

The read/write operation is carried out by virt-machine, not the tap device creator.

In my test, the tap interface is deleted when calling close(), the tap interface is also deleted when the process who creates the tap interface exits. So there would be problem in step 2.

I'm can create the tap device with command provided by package openvpn or user-module-linux, but they both have some undesirable limitations.

Do you think I can implement my usecase with pytun?

Ability to create a TAP interface with it's file descriptor closed

Hey there!

I've been trying to use pytun to create TAP interfaces for qemu to use with bridged networking. My problem is that when I create a new TAP device using this lib, it's file descriptor is open (line 118 opens it), so qemu can not access to it.

Here is an example code:

import subprocess
import pytun

tap = pytun.TunTapDevice(flags=pytun.IFF_TAP) # Create a tap device

qemu = subprocess.Popen(['qemu-system-i386', '-drive', 'format=raw,file=/media/data/alpine.qcow', '-boot', 'd', '-m', '192', '-localtime', '-net', 'nic,macaddr=52:54:be:36:42:a9', '-net', "tap,ifname={}".format(tap.name), '-nographic']) # start qemu using the TAP device we just created

qemu.wait()


tap.down()
tap.close()

Running the code above produces the following error:

qemu-system-i386: -net tap,ifname=tap5: could not configure /dev/net/tun (tap5): Device or resource busy

However, if I close the file handle before, like this:

import subprocess
import pytun

tap = pytun.TunTapDevice(flags=pytun.IFF_TAP) # Create a tap device

tap.close()

qemu = subprocess.Popen(['qemu-system-i386', '-drive', 'format=raw,file=/media/data/alpine.qcow', '-boot', 'd', '-m', '192', '-localtime', '-net', 'nic,macaddr=52:54:be:36:42:a9', '-net', "tap,ifname={}".format(tap.name), '-nographic']) # start qemu using the TAP device we just created

qemu.wait()


tap.down() # <- This fails btw
tap.close()

Or like this:

import subprocess
import pytun
import os

tap = pytun.TunTapDevice(flags=pytun.IFF_TAP) # Create a tap device

os.close(tap.fileno())

qemu = subprocess.Popen(['qemu-system-i386', '-drive', 'format=raw,file=/media/data/alpine.qcow', '-boot', 'd', '-m', '192', '-localtime', '-net', 'nic,macaddr=52:54:be:36:42:a9', '-net', "tap,ifname={}".format(tap.name), '-nographic']) # start qemu using the TAP device we just created

qemu.wait()


tap.down() # <- this fails with "pytun.Error: [Errno 19] No such device" guess it needs to be re-opened or something
tap.close()

Qemu starts up (AND WORKS) just fine.

But I feel like this is a kind of hacky solution... it would be nice, if the lib provided some way to create TAP interface objects with their file handle closed, so other applications can use it, as if they were created using the ip tuntap add mode tap command.

Can I create a tun under non-root user?

When I create a tun in non-root I got a "Operation not permitted" error, can it be run under non-root user?

>>> from pytun import TunTapDevice as ttd
>>> a = ttd()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
pytun.Error: [Errno 1] Operation not permitted

outdated doc

Hi,

The doc you have might be outdated, the TunTap examples cannot be found if I install pytun via pip:

from pytun import TunTapDevice
Traceback (most recent call last):
File "", line 1, in
ImportError: cannot import name TunTapDevice

In [2]: pytun.
pytun.TUN_KO_PATH pytun.TunTunnel pytun.fcntl pytun.logger pytun.open pytun.struct
pytun.TapTunnel pytun.Tunnel pytun.functools pytun.logging pytun.os pytun.tunnel

Provide Python 3.10/3.11 wheels (+musllinux)

Hey :)

It would be cool to have wheels for Python 3.10 that's around for a while, and 3.11 while we're at it (It's now ABI stable).
It would also be really nice to have musllinux wheels, which seem to be provided by almost every (maintained) package now.

I'm planning on adding a CI script in a PR to build all of those, to make it super easy to do so.
There's no need for a new release, just uploading the 'diff' to PyPI, as apparently the latest release matches master.

Thanks for your work!

Something wrong with fragmentation

I saw an issue with my own script, but then reproduced it using the script in test/test_tap.py.

I set up a tunnel between two machines with mtu of 1500, and it appears to work, but if I ping with a payload above a certain size (1458) it fails. You can use ping -c 1 -s 1459 <ip> to test. Also, if I ssh to the host over the tunnel, I can log in okay, but if I do a ls -l in a large directory (like /etc) it will hang because the packets get above that threshold.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.