pax_global_header00006660000000000000000000000064136100700030014500gustar00rootroot0000000000000052 comment=1676cabc85297c0160af4d0ad0bdfc671f545c97 vdens-0.2/000077500000000000000000000000001361007000300124605ustar00rootroot00000000000000vdens-0.2/CMakeLists.txt000066400000000000000000000021401361007000300152150ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.1) project("vdens" DESCRIPTION "create user namespaces connected to vde networks" HOMEPAGE_URL "https://github.com/rd235/vdens" VERSION 0.1 LANGUAGES C) include(GNUInstallDirs) include(CheckIncludeFile) set(CMAKE_REQUIRED_QUIET TRUE) set(LIBS_REQUIRED vdeplug cap execs) set(HEADERS_REQUIRED libvdeplug.h sys/capability.h execs.h) foreach(THISLIB IN LISTS LIBS_REQUIRED) find_library(LIB${THISLIB}_OK ${THISLIB}) if(NOT LIB${THISLIB}_OK) message(FATAL_ERROR "library lib${THISLIB} not found") endif() endforeach(THISLIB) foreach(HEADER IN LISTS HEADERS_REQUIRED) check_include_file(${HEADER} ${HEADER}_OK) if(NOT ${HEADER}_OK) message(FATAL_ERROR "header file ${HEADER} not found") endif() endforeach(HEADER) add_definitions(-D_GNU_SOURCE) include_directories(${CMAKE_CURRENT_SOURCE_DIR}) add_executable(vdens vdens.c) target_link_libraries(vdens -lcap -lexecs -lvdeplug) install(TARGETS vdens DESTINATION ${CMAKE_INSTALL_BINDIR}) file(GLOB MAN1_PAGES ${CMAKE_CURRENT_SOURCE_DIR}/*.1) install(FILES ${MAN1_PAGES} DESTINATION ${CMAKE_INSTALL_MANDIR}/man1) vdens-0.2/COPYING000066400000000000000000000431231361007000300135160ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19yy name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. vdens-0.2/README.md000066400000000000000000000101311361007000300137330ustar00rootroot00000000000000# vdens Create User Namespaces connected to VDE networks. vdens requires [vdeplug4](https://github.com/rd235/vdeplug4) (or [vde2](https://github.com/virtualsquare/vde-2) deprecated) ## Install vdens Vdens uses cmake so a standard installation procedure is the following: ``` $ mkdir build $ cd build $ cmake .. $ make $ sudo make install ``` vdens requires user namespace to be included and enabled in the kernel of the hosting system. Kernel config file must include the following option. ``` CONFIG_USER_NS=y ``` Debian users should enable user namespaces using the following command: ``` $ sudo echo 1 > /proc/sys/kernel/unprivileged_userns_clone ``` ## Tutorial Vdens can be used without any parameter: ``` $ vdens $ # ip addr 1: lo: mtu 65536 qdisc noop state DOWN group default qlen 1 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 ``` In this way vdens creates a new network namespace providing only the loopback interface. The new network namespace is created inside a user namespace so the user can be safely granted all the capability nedded to autonomously manage their own network. The caprint command (provided by the [cado](https://github.com/rd235/cado) command suite) can reveal the capabilities granted to the user inside a vdens namespace. ``` $ caprint cap_net_bind_service cap_net_broadcast cap_net_admin cap_net_raw ``` Thus, for example, it is possible to create a tap interface connected to a vde\_switch (using *vdeplug4*) ``` $ vde_plug -d vde:// tap://vde0 $ ip addr 1: lo: mtu 65536 qdisc noop state DOWN group default qlen 1 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 2: vde0: mtu 1500 qdisc noop state DOWN group default qlen 1000 link/ether 96:b4:71:c9:f6:f7 brd ff:ff:ff:ff:ff:ff ``` using *vde2* the first command is: ``` $ vde_plug2tap tap0 & ``` If required, the command cadrop (also provided by the [cado](https://github.com/rd235/cado) command suite). permits to drop some or all the capabilities after the network configuration phase, to provide higher security, Vde\_plug services based on TCP-IP networking (like slirp, vxvde, vxvdex, vxlan, udp, etc.) would not work if activated from inside the vdens namespace (the namespace providing access to the real networking interfaces is not accessible from within the vdens). Vdens can define a virtual interface during the activation of the namespace. The virtual network interface is usually named vde0 unless elseway defined by the -i option (see the man page). It is a virtual interface in the user private namespace, but the libvdeplug library (and its plugins) use the networking services available outside the private namespace. Note: the following example is for *vdeplug4* ``` $ vdens vxvde:// $ ip addr 1: lo: mtu 65536 qdisc noop state DOWN group default qlen 1 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 2: vde0: mtu 1500 qdisc noop state DOWN group default qlen 1000 link/ether ce:e6:4c:88:44:49 brd ff:ff:ff:ff:ff:ff ``` It is possible to run several instances of the command here above on several hosts of a LAN (multicast domain) to create a network of namespaces. All vdens namespaces connected to the same vxvde multicast address and vni (see libvdeplug\_vxvde(1) man page) will create a vlan of namespaces. In order to run a specific command in a vdens (instead of starting a shell session) just add the command and its arguments at the end of the vdens command line. ``` $ vdens vxvde:// xterm ``` It is also possible to create vde namespaces connected to several networks using the flag `-m` or `--multi`: vdeplug4: ``` $ vdens -m vde:// vxvde:// $ # ip addr 1: lo: mtu 65536 qdisc noop state DOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 2: vde0: mtu 1500 qdisc noop state DOWN group default qlen 1000 link/ether 6e:03:cd:c1:84:83 brd ff:ff:ff:ff:ff:ff 3: vde1: mtu 1500 qdisc noop state DOWN group default qlen 1000 link/ether 3e:39:0e:4e:52:c5 brd ff:ff:ff:ff:ff:ff ``` vde2: ``` $ vdens -m /var/run/sw1 /var/run/sw2 ``` vdens-0.2/vdens.1000066400000000000000000000066621361007000300136730ustar00rootroot00000000000000.TH VDENS 1 "November 26, 2016" "VirtualSquare Labs" .SH NAME vdens \- create a user namespace connected to a vde network .SH SYNOPSIS .B vdens [ options ] [ .I vde_network [ .I command [ .I args ] ] ] .B vdens .B -m [ options ] .I vde_network [ .I vde_network ... ] [ .B -- .I command [ .I args ] ] .B vdens .B --multi [ options ] .I vde_network [ .I vde_network ... ] [ .B -- .I command [ .I args ] ] .SH DESCRIPTION vdens creates a user namespace with a private network namespace. Vdens launches the command indicated as a parameter ($SHELL if omitted) in a private network namespace. If the vde_network parameter is present (and it does not match one of the strings "-" or "no") the virtual private network namespace will have a virtual interface connected to the specified vde network. Vdens grants the capabilities CAP_NET_BIND_SERVICE, CAP_NET_BROADCAST, CAP_NET_ADMIN and CAP_NET_RAW to the command to permit the configuration of the virtual interface. The scope of these capabilities is limited to the user namespace created by vdens. Once the network has been configured, the capabilities can be dropped (e.g. using csdrop(1)) in order to increase the security (obeying to the principle of least privilege). .SH OPTIONS OPTIONS .I vdens accepts the following options. .TP \fB\-m .TQ \fB\-\-multi connect the vde namespace to one or more vde networks. A virtual interface is defined for each \fIvde_network\fR: \fBvde0\fR is connected to the first \fIvde_network\fR, \fBvde1\fR is connected to the second and so on. (It is possible to use a different prefix for the interface names instead of "vde", see -i or --iface below). .TP \fB\-i \fI interface_prefix .TQ \fB\-\-iface \fI interface_prefix define the prefix of the interface name. For example use \fB--iface eth\fR to name the interfaces "eth0", "eth1", etc. (the default value is "vde") .TP \fB\-R \fI ip_addr(s) .TQ \fB\-\-resolvaddr \fI ip_addr(s) define the address (or addresses) of the domain name servers for the namespace. (multiple IPv4 or IPv6 addresses can be separated by commas, e.g. "-R 9.9.9.9,9.9.8.8") .TP \fB\-r \fI pathname .TQ \fB\-\-resolvconf \fI pathname define the pathname of the file which will appear as /etc/config.sys in the user namespace. (it is ignored if used together with \fB\-R\fR or \fB\-\-resolvaddr\fR) .TP \fB\-s .TQ \fB\-\-sysadm grant also CAP_SYS_ADMIN in the namespace so that it is possible to bind mount files and directories. .TP \fB\-c .TQ \fB\-\-clone Use clone(2) to create the private network namespace. Vdens needs one more thread to manage the vde communication. .TP \fB\-u .TQ \fB\-\-unshare Use unshare(2) to create the private network namespace. It may not work if the vde plugin in use is multithreaded (e.g. slirp). If neither -c/--clone nor -u/--unshare is set, vdens tries unshare first and then it uses clone if unshare fails. (If both are set vdens uses clone). .SH ENVIRONMENT VARIABLES .TP \fBVDE_RESOLVCONF define the default value for the \fB\-\-resolvconf \fR option .TP \fBVDE_RESOLVADDR define the default value for the \fB\-\-resolvaddr \fR option .SH NOTES Use of user namespaces requires a kernel that is configured with the CONFIG_USER_NS option. In some distributions (e.g. Debian) user namespaces must be enabled by writing 1 to /proc/sys/kernel/unprivileged_userns_clone. .SH SEE ALSO \fBvde_plug\fR(1), \fBcadrop\fR(1), \fBcado\fR(1), \fBcapabilities\fR(7) .SH AUTHORS Renzo Davoli , Davide Berardi . vdens-0.2/vdens.c000066400000000000000000000337741361007000300137610ustar00rootroot00000000000000/* * vdens: Create a user namespace connected to a VDE network * Copyright (C) 2016 Renzo Davoli, Davide Berardi University of Bologna * Credit: inspired by the example code included in the * user_namespaces(7) man page * * Vdens is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; If not, see . * */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define UNUSED(...) (void)(__VA_ARGS__) /* workaround for legacy vde2 libvdeplug.h compatibility */ #ifndef VDE_ETHBUFSIZE #define VDE_ETHBUFSIZE (9216 + 14 + 4) #endif #define DEFAULT_IF_NAME "vde" #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); } while(0) #define CONNTYPE_UNDEF 0 #define CONNTYPE_NONE 1 #define CONNTYPE_VDE 2 #define CONNTYPE_VDESTREAM 3 #define CONNTYPE_MULTIVDE 4 int conntype = CONNTYPE_UNDEF; union { VDECONN *vdeconn; VDECONN **vdemulticonn; int streamfd[2]; } conn; char *resolvaddr; char *resolvconf; char *if_name = DEFAULT_IF_NAME; char **cmdargv; int sysadm_flag; void vdens_core(void); static void usage_exit(char *pname) { fprintf(stderr, "Usage: %s OPTIONS [vde_net [cmd [arg...]]]\n" " %s -m OPTIONS vde_net [vde_net ...] [-- cmd [arg...]]\n" "OPTIONS:\n" " -h | --help print this short usage message\n" " -m | --multi connect two or more vde networks\n" " -i | --iface interface_prefix\n" " define the interface name prefix, the default value is \"vde\"\n" " e.g. use \"-i eth\" to name the virtual interfaces eth0, eth1, ...\n" " -r | --resolvconf file\n" " define the /etc/resolv.conf file, e.g. -r /tmp/resolv.conf\n" " -R | --resolvaddr string\n" " define the address of the DNS servers, e.g. -R 80.80.80.80\n" " -s | --sysadm enable the cap_sys_admin ambient capability\n" " -c | --clone use clone instead of unshare:\n" " %s uses one more process\n" " (default bevavior: try unshare and use clone if unshare fails)\n" " -u | --unshare use unshare instead of clone:\n" " %s saves 1 process (for non-multithreaded vde plugins only)\n" " no virtual interface if vde_net omitted or \"no\"\n" " it runs $SHELL if cmd omitted\n\n", pname, pname, pname, pname); exit(EXIT_FAILURE); } static void uid_gid_map(pid_t pid) { char map_file[PATH_MAX]; FILE *f; uid_t euid = geteuid(); gid_t egid = getegid(); snprintf(map_file, PATH_MAX, "/proc/%d/uid_map", pid); f = fopen(map_file, "w"); if (f) { fprintf(f,"%d %d 1\n",euid,euid); fclose(f); } snprintf(map_file, PATH_MAX, "/proc/%d/setgroups", pid); f = fopen(map_file, "w"); if (f) { fprintf(f,"deny\n"); fclose(f); } snprintf(map_file, PATH_MAX, "/proc/%d/gid_map", pid); f = fopen(map_file, "w"); if (f) { fprintf(f,"%d %d 1\n",egid,egid); fclose(f); } } static void setambientcaps(cap_value_t *caplist) { cap_t caps=cap_get_proc(); cap_value_t *cap; for (cap = caplist; *cap >= 0; cap++) cap_set_flag(caps, CAP_INHERITABLE, 1, cap, CAP_SET); cap_set_proc(caps); cap_free(caps); for (cap = caplist; *cap >= 0; cap++) prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, *cap, 0, 0); } static cap_value_t vdecaps[] = {CAP_SYS_ADMIN, CAP_NET_ADMIN, CAP_NET_RAW, CAP_NET_BIND_SERVICE, CAP_NET_BROADCAST, -1}; static void setvdenscap(int sysadm) { setambientcaps(vdecaps + (sysadm ? 0 : 1)); /* skip CAP_SYS_ADMIN if sysadm is not set */ } static int unsharenet(int sysadm, int clonens) { int pipe_fd[2]; pid_t child_pid; int unshare_rv; ssize_t rwlen; UNUSED(sysadm); if (pipe2(pipe_fd, O_CLOEXEC) == -1) errExit("pipe"); switch (child_pid = fork()) { case 0: close(pipe_fd[1]); rwlen = read(pipe_fd[0], &unshare_rv, sizeof(unshare_rv)); if (rwlen == sizeof(unshare_rv) && unshare_rv == 0) uid_gid_map(getppid()); exit(0); default: close(pipe_fd[0]); unshare_rv = unshare(CLONE_NEWUSER | CLONE_NEWNET | ((clonens) ? CLONE_NEWNS : 0)); rwlen = write(pipe_fd[1], &unshare_rv, sizeof(unshare_rv)); if (rwlen != sizeof(unshare_rv)) errExit("unsharenet write"); close(pipe_fd[1]); if (waitpid(child_pid, NULL, 0) == -1) /* Wait for child */ errExit("unshare waitpid"); break; case -1: errExit("unshare fork"); } return unshare_rv; } #define STACK_SIZE (64 * 1024) static int childFunc(void *arg) { int *pipe_fd = arg; char buf[1]; /* Wait until the parent has updated the UID and GID mappings. */ if (read(pipe_fd[0], buf, 1) != 0) errExit("Failure in child: read from pipe returned != 0"); close(pipe_fd[0]); vdens_core(); return 0; } static void clonenet(int sysadm, int clonens) { char child_stack[STACK_SIZE]; int pipe_fd[2]; pid_t child_pid; UNUSED(sysadm); if (pipe2(pipe_fd, O_CLOEXEC) == -1) errExit("pipe"); #ifdef __ia64__ child_pid = __clone2(childFunc, child_stack, STACK_SIZE, CLONE_VM | CLONE_FILES | CLONE_NEWUSER | CLONE_NEWNET | SIGCHLD | ((clonens) ? CLONE_NEWNS : 0), pipe_fd); #else child_pid = clone(childFunc, child_stack + STACK_SIZE, CLONE_VM | CLONE_FILES | CLONE_NEWUSER | CLONE_NEWNET | SIGCHLD | ((clonens) ? CLONE_NEWNS : 0), pipe_fd); #endif if (child_pid == -1) errExit("clone"); /* Parent falls through to here */ uid_gid_map(child_pid); /* Close the write end of the pipe, to signal to the child that we have updated the UID and GID maps */ close(pipe_fd[1]); if (waitpid(child_pid, NULL, 0) == -1) /* Wait for child */ errExit("waitpid"); exit(EXIT_SUCCESS); } static int open_tap(char *name, int n) { struct ifreq ifr; int fd=-1; if((fd = open("/dev/net/tun", O_RDWR | O_CLOEXEC)) < 0) return -1; memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = IFF_TAP | IFF_NO_PI; snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", name, n); if(ioctl(fd, TUNSETIFF, (void *) &ifr) < 0) { close(fd); return -1; } return fd; } static void plug2tap(VDECONN **conn, int *tapfd, int nnets) { int n, i; char buf[VDE_ETHBUFSIZE]; int npfd = 2 * nnets + 1; struct pollfd pfd[npfd]; sigset_t chldmask; sigemptyset(&chldmask); sigaddset(&chldmask, SIGCHLD); pfd[2 * nnets].fd = signalfd(-1, &chldmask, SFD_CLOEXEC); pfd[2 * nnets].events = POLLIN; for (i = 0; i < nnets; i++) { pfd[i].fd = vde_datafd(conn[i]); pfd[nnets + i].fd = tapfd[i]; pfd[i].events = pfd[nnets + i].events = POLLIN; } while (ppoll(pfd, npfd, NULL, &chldmask) >= 0) { for (i = 0; i < nnets; i++) { if (pfd[i].revents & POLLIN) { n = vde_recv(conn[i], buf, VDE_ETHBUFSIZE, 0); if (n == 0) goto terminate; n = write(tapfd[i], buf, n); } if (pfd[nnets + i].revents & POLLIN) { n = read(tapfd[i], buf, VDE_ETHBUFSIZE); if (n == 0) goto terminate; vde_send(conn[i], buf, n, 0); } } if (pfd[2 * nnets].revents & POLLIN) { break; } } terminate: for (i = 0; i < nnets; i++) { vde_close(conn[i]); close(tapfd[i]); } } static ssize_t stream2tap_read(void *opaque, void *buf, size_t count) { int *tapfd = opaque; return write(*tapfd, buf, count); } static void stream2tap(int streamfd[2], int tapfd) { int n; unsigned char buf[VDE_ETHBUFSIZE]; struct pollfd pfd[] = {{tapfd, POLLIN, 0}, {streamfd[0], POLLIN, 0}, {-1, POLLIN, 0}}; sigset_t chldmask; sigemptyset(&chldmask); sigaddset(&chldmask, SIGCHLD); int sfd = signalfd(-1, &chldmask, SFD_CLOEXEC); VDESTREAM *vdestream = vdestream_open(&tapfd, streamfd[1], stream2tap_read, NULL); pfd[2].fd = sfd; while (ppoll(pfd, 3, NULL, &chldmask) >= 0) { if (pfd[0].revents & POLLIN) { n = read(tapfd, buf, VDE_ETHBUFSIZE); if (n == 0) break; vdestream_send(vdestream, buf, n); } if (pfd[1].revents & POLLIN) { n = read(streamfd[0], buf, VDE_ETHBUFSIZE); if (n == 0) break; vdestream_recv(vdestream, buf, n); } if (pfd[2].revents & POLLIN) { break; } } } int mountaddr(const char *addr) { char tmpname[] = "/tmp/vdensmountXXXXXX"; int fd = mkstemp(tmpname); int retval; const char *tagbegin, *tagend; if (fd < 0) return -1; fchmod(fd, 0600); for (tagbegin = addr; *tagbegin != 0; tagbegin = tagend) { char *line = ""; size_t len; int linelen; for (tagend = tagbegin; *tagend != 0 && *tagend != ','; tagend++) ; len = tagend-tagbegin; while (*tagend == ',') tagend++; linelen = asprintf(&line, "nameserver %*.*s\n", (int) len, (int) len, tagbegin); if (write(fd, line, linelen) < 0) errExit("resolvconf create mountaddr"); free(line); } fchmod(fd, 0400); close(fd); retval = mount(tmpname, "/etc/resolv.conf", "", MS_BIND, NULL); unlink(tmpname); return retval; } void vdens_core(void) { pid_t child_pid; setvdenscap(sysadm_flag); if (resolvaddr) { if (mountaddr(resolvaddr) < 0) errExit("resolvaddr mount"); } else if (resolvconf && mount(resolvconf, "/etc/resolv.conf", "", MS_BIND, NULL) < 0) errExit("resolvconf mount"); switch (conntype) { case CONNTYPE_NONE: execvp(cmdargv[0], cmdargv); errExit("execvp"); break; case CONNTYPE_VDE: { int tapfd; if ((tapfd = open_tap(if_name, 0)) < 0) errExit("tap"); switch (child_pid = fork()) { case 0: execvp(cmdargv[0], cmdargv); errExit("execvp"); break; default: plug2tap(&conn.vdeconn, &tapfd, 1); exit(EXIT_SUCCESS); case -1: errExit("cmd fork"); break; } } break; case CONNTYPE_MULTIVDE: { int nnets, i; for (nnets = 0; conn.vdemulticonn[nnets] != NULL; nnets++) ; int tapfd[nnets]; for (i = 0; i < nnets; i++) tapfd[i] = open_tap(if_name, i); switch (child_pid = fork()) { case 0: execvp(cmdargv[0], cmdargv); errExit("execvp"); break; default: plug2tap(conn.vdemulticonn, tapfd, nnets); exit(EXIT_SUCCESS); case -1: errExit("cmd fork"); break; } } break; case CONNTYPE_VDESTREAM: { int tapfd; if ((tapfd = open_tap(if_name, 0)) < 0) errExit("tap"); switch (child_pid = fork()) { case 0: execvp(cmdargv[0], cmdargv); errExit("execvp"); break; default: stream2tap(conn.streamfd, tapfd); exit(EXIT_SUCCESS); case -1: errExit("cmd fork"); break; } break; } default: errExit("unknown conn type"); } exit(EXIT_SUCCESS); } int argv1_nonet(char *s) { if (s == NULL) return 1; if (strcmp(s,"") == 0) return 1; if (strcmp(s,"-") == 0) return 1; if (strcmp(s,"no") == 0) return 1; return 0; } int main(int argc, char *argv[]) { char *argvsh[] = {getenv("SHELL"),NULL}; char *vdenet = NULL; static char *short_options = "+i:hsucmr:R:"; static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"multi", no_argument, 0, 'm'}, {"iface", required_argument, 0, 'i'}, {"sysadm", no_argument, 0, 's'}, {"unshare", no_argument, 0, 'u'}, {"clone", no_argument, 0, 'c'}, {"resolvconf", required_argument, 0, 'r'}, {"resolvaddr", required_argument, 0, 'R'}, {0, 0, 0, 0}}; char *progname = basename(argv[0]); int unshare_flag = 0; int clone_flag = 0; int clonens_flag; resolvconf = getenv("VDE_RESOLVCONF"); resolvaddr = getenv("VDE_RESOLVADDR"); while (1) { int c; if ((c = getopt_long(argc, argv, short_options, long_options, NULL)) == -1) break; switch (c) { case 'i': if_name = optarg; break; case 'r': resolvconf = optarg; break; case 'R': resolvaddr = optarg; break; case 's': sysadm_flag = 1; break; case 'u': unshare_flag = 1; break; case 'c': clone_flag = 1; break; case 'm': conntype = CONNTYPE_MULTIVDE; break; case '?': case 'h': default: usage_exit(progname); } } argc -= optind; argv += optind; if (conntype == CONNTYPE_MULTIVDE && argc >= 1) { int nnets; int i; cmdargv = argv + 1; while (*cmdargv != 0 && strcmp(*cmdargv, "--") != 0) cmdargv++; nnets = cmdargv - argv; if (*cmdargv != 0) cmdargv++; if (*cmdargv == 0) cmdargv = argvsh; conn.vdemulticonn = malloc(nnets * sizeof(VDECONN *)); if (conn.vdemulticonn == NULL) errExit("alloc VDE conn array"); for (i = 0; i < nnets; i++) { if ((conn.vdemulticonn[i] = vde_open(argv[i], "vdens", NULL)) == NULL) errExit(argv[i]); } conn.vdemulticonn[i] = NULL; } else { switch (argc) { case 0: cmdargv = argvsh; break; case 1: cmdargv = argvsh; vdenet = argv[0]; break; default: cmdargv = argv + 1; vdenet = argv[0]; break; } if (cmdargv[0] == NULL) { fprintf(stderr, "Error: $SHELL env variable not set\n"); exit(EXIT_FAILURE); } if (vdenet == NULL || argv1_nonet(vdenet)) conntype = CONNTYPE_NONE; else if (*vdenet == '=') { conntype = CONNTYPE_VDESTREAM; if (coprocsp(vdenet+1, conn.streamfd) < 0) errExit("stream cmd"); } else { conntype = CONNTYPE_VDE; if ((conn.vdeconn = vde_open(vdenet, "vdens", NULL)) == NULL) errExit("vdeplug"); } } clonens_flag = sysadm_flag | (resolvconf != NULL) | (resolvaddr != NULL); if (clone_flag) clonenet(sysadm_flag, clonens_flag); else { if (unsharenet(sysadm_flag, clonens_flag) == 0) vdens_core(); else { if (unshare_flag) errExit("unshare"); else clonenet(sysadm_flag, clonens_flag); } } }