diff --git a/labs/os2/495px-VPN_overview-en.svg.png b/labs/os2/495px-VPN_overview-en.svg.png new file mode 100644 index 0000000..2e625d4 Binary files /dev/null and b/labs/os2/495px-VPN_overview-en.svg.png differ diff --git a/labs/os2/Iptables.adoc b/labs/os2/Iptables.adoc new file mode 100644 index 0000000..5828aeb --- /dev/null +++ b/labs/os2/Iptables.adoc @@ -0,0 +1,536 @@ += Iptables ! +Apostolos rootApostolos@swarmlab.io +// Metadata: +:description: iptables +:keywords: sec, tcpdump +:data-uri: +:toc: right +:toc-title: Table of Contents +:toclevels: 4 +:source-highlighter: highlight +:icons: font +:sectnums: + +include::header.adoc[] + + +{empty} + + + + + + +== iptables + + +**iptables** is a command line utility for configuring Linux kernel **firewall** implemented within the https://en.wikipedia.org/wiki/Netfilter[Netfilter] project. The term ''iptables'' is also commonly used to refer to this kernel-level firewall. It can be configured directly with iptables, or by using one of the many + +https://en.wikipedia.org/wiki/Iptables[More: wikipedia] + +- Console tools + +and + +- Graphical front-ends. + +**iptables** is used for https://en.wikipedia.org/wiki/IPv4[IPv4] and ''ip6tables'' is used for ihttps://en.wikipedia.org/wiki/IPv6[IPv6]. Both ''iptables'' and ''ip6tables'' have the same syntax, but some options are specific to either IPv4 or IPv6. + + +=== Installation + +The Swarmlab.io kernel is compiled with iptables support. + + +=== Front-ends + +==== Console + +- Shorewall, High-level tool for configuring Netfilter. + +You describe your firewall/gateway requirements using entries in a set of configuration files. + +http://www.shorewall.net/[shorewall] + +- Arno's Secure firewall for both single and multi-homed machines. + +Very easy to configure, handy to manage and highly customizable. Supports: NAT and SNAT, port forwarding, ADSL ethernet modems with both static and dynamically assigned IPs, MAC address filtering, stealth port scan detection, DMZ and DMZ-2-LAN forwarding, protection against SYN/ICMP flooding, extensive user definable logging with rate limiting to prevent log flooding, all IP protocols and VPNs such as IPsec, plugin support to add extra features.| + +http://rocky.eld.leidenuniv.nl/[arno-iptables-firewall] + +- FireHOL Language to express firewalling rules, not just a script that produces some kind of a firewall. It makes building even sophisticated firewalls easy - the way you want it. + +http://firehol.sourceforge.net + +- firewalld (firewall-cmd) Daemon and console interface for configuring network and firewall zones as well as setting up and configuring firewall rules. + +https://firewalld.org[firewalld] + +==== Graphical + +- Firewall Builder + +firewall configuration and management tool that supports iptables (netfilter), ipfilter, pf, ipfw, Cisco PIX (FWSM, ASA) and Cisco routers extended access lists. The program runs on Linux, FreeBSD, OpenBSD, Windows and macOS and can manage both local and remote firewalls. + +http://fwbuilder.sourceforge.net[fwbuilder] + +- firewalld + +(firewall-config) Daemon and graphical interface for configuring network and firewall zones as well as setting up and configuring firewall rules. + +https://firewalld.org[firewalld] + +- FireStarter + +High-level GUI Iptables firewall for Linux systems + +http://www.fs-security.com[firestarter] + +== Basic concepts + +iptables is used to inspect, modify, forward, redirect, and/or drop IP packets. + +- The code for filtering IP packets is already built into the kernel and is organized into a collection of **tables**, each with a specific purpose. +- The tables are made up of a set of predefined **chains**, and the chains contain **rules** which are traversed in order. +- Each rule consists of a predicate of potential matches and a corresponding action (called a **target**) which is executed if the predicate is true; i.e. the conditions are matched. +- If the IP packet reaches the end of a built-in chain, including an empty chain, then the chain's **policy** target determines the final destination of the IP packet. + +iptables is the user utility which allows you to work with these chains/rules. + + +.Understanding how iptables works +[NOTE] +==== +The key to understanding how iptables works is http://docs.swarmlab.io/lab/sec/tables_traverse.jpg[this chart]. + +The lowercase word on top is the **table** and the upper case word below is the **chain**. + +- Every IP packet that comes in **on any network interface** passes through this flow chart from top to bottom. + + +**All interfaces are handled the same way; it's up to you to define rules that treat them differently.** + +Some packets + +- are intended for local processes, hence come in from the top of the chart and stop at **Local Proces**, + +- while other packets are generated by local processes; hence start at **Local Process** and proceed downward through the flowchart. + +A detailed explanation http://docs.swarmlab.io/lab/sec/ex-3a_iptables-flow-chart.adoc.html[here]. +==== + +In the vast majority of use cases you won't need to use the **raw**, **mangle**, or **security** tables at all. + +Consequently, the following chart depicts a simplified network packet flow through **iptables**: + +[source,bash] +---- + + XXXXXXXXXXXXXXXXXX + XXX Network XXX + XXXXXXXXXXXXXXXXXX + + + | + v + +-------------+ +------------------+ + |table: filter| <---+ | table: nat | + |chain: INPUT | | | chain: PREROUTING| + +-----+-------+ | +--------+---------+ + | | | + v | v + [local process] | **************** +--------------+ + | +---------+ Routing decision +------> |table: filter | + v **************** |chain: FORWARD| +**************** +------+-------+ +Routing decision | +**************** | + | | + v **************** | ++-------------+ +------> Routing decision <---------------+ +|table: nat | | **************** +|chain: OUTPUT| | + ++-----+-------+ | | + | | v + v | +-------------------+ ++--------------+ | | table: nat | +|table: filter | +----+ | chain: POSTROUTING| +|chain: OUTPUT | +--------+----------+ ++--------------+ | + v + XXXXXXXXXXXXXXXXXX + XXX Network XXX + XXXXXXXXXXXXXXXXXX +---- + +=== Table + +iptables contains five tables: + +.Chains +[NOTE] +==== +Tables consist of **chains**, which are lists of rules which are followed in order. +==== + +==== Filter + +This is the default table. + +.Its built-in chains are: +[source,bash] +---- + Input: packets going to local sockets + Forward: packets routed through the server + Output: locally generated packets +---- + +==== Nat + +When a packet creates a new connection, this table is used. + + +.Its built-in chains are: +[source,bash] +---- + Prerouting: designating packets when they come in + Output: locally generated packets before routing takes place + Postrouting: altering packets on the way out +---- + +==== Mangle + +Used for special altering of packets. + +.Its built-in chains are: +[source,bash] +---- + Prerouting: incoming packets + Postrouting: outgoing packets + Output: locally generated packets that are being altered + Input: packets coming directly into the server + Forward: packets being routed through the server +---- + +==== Raw + +Primarily used for configuring exemptions from connection tracking. + +.Its built-in chains are: +[source,bash] +---- + Prerouting: packets that arrive by the network interface + Output: processes that are locally generated +---- + +==== Security + +Used for Mandatory Access Control (MAC) rules. After the filter table, the security table is accessed next. + +.Its built-in chains are: +[source,bash] +---- + Input: packets entering the server + Output: locally generated packets + Forward: packets passing through the server +---- + + + +[NOTE] +==== +In most common use cases you will only use two of these: **filter** and **nat**. +==== + + +=== Rules + +Packet filtering is based on **rules**, which are specified by multiple **matches** (conditions the packet must satisfy so that the rule can be applied), and one **target** (action taken when the packet matches all conditions). + +The typical things a rule might match on are + +- what interface the packet came in on (e.g eth0 or eth1), +- what type of packet it is (ICMP, TCP, or UDP), +- or the destination port of the packet. + +Targets are specified using the **-j** or **--jump** option. + +Targets can be either +- user-defined chains (i.e. if these conditions are matched, jump to the following user-defined chain and continue processing there), one of the special built-in targets, +- or a target extension. + +[NOTE] +==== +- Built-in targets are **ACCEPT**, **DROP**, **QUEUE** and **RETURN** +- target extensions are, for example, **REJECT** and **LOG**. +==== + +- If the target is a built-in target, the fate of the packet is decided immediately and processing of the packet in current table is stopped. + +- If the target is a user-defined chain and the fate of the packet is not decided by this second chain, it will be filtered against the remaining rules of the original chain. + +Target extensions can be either **terminating** (as built-in targets) or **non-terminating** (as user-defined chains) + +=== Traversing Chains + +A network packet received on any interface traverses the traffic control chains of tables in the order shown in the http://docs.swarmlab.io/lab/sec/tables_traverse.jpg[this chart] + +- The first routing decision involves deciding if the final destination of the packet is the local machine (in which case the packet traverses through the **INPUT chains** + +- or elsewhere (in which case the packet traverses through the **FORWARD chains**. + +- Subsequent routing decisions involve deciding what interface to assign to an outgoing packet. + +At each chain in the path, every rule in that chain is evaluated in order and whenever a rule matches, the corresponding target/jump action is executed. + +The 3 most commonly used targets are **ACCEPT**, **DROP**, and **jump** to a user-defined chain. + +[NOTE] +==== +While built-in chains can have default policies, user-defined chains can not. +==== + +- If every rule in a chain that you jumped fails to provide a complete match, the packet is dropped back into the calling chain as illustrated +http://docs.swarmlab.io/lab/sec/images/table_subtraverse.jpg[here]. + +- If at any time a complete match is achieved for a rule with a **DROP** target, the packet is dropped and no further processing is done. +- If a packet is **ACCEPT**ed within a chain, it will be **ACCEPT**ed in all superset chains also and it will not traverse any of the superset chains any further. + +However, be aware that the packet will continue to traverse all other chains in other tables in the normal fashion. + + + +== Usage + +=== Showing the current rules + +[source,bash] +---- +# iptables -nvL + +Chain INPUT (policy ACCEPT 0 packets, 0 bytes) + pkts bytes target prot opt in out source destination + +Chain FORWARD (policy ACCEPT 0 packets, 0 bytes) + pkts bytes target prot opt in out source destination + +Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes) + pkts bytes target prot opt in out source destination +---- + +If the output looks like the above, then there are no rules (i.e. nothing is blocked) in the default filter table + + +=== Resetting rules + +You can flush and reset iptables to default using these commands: + +[source,bash] +---- +# iptables -F +# iptables -X +# iptables -t nat -F +# iptables -t nat -X +# iptables -t mangle -F +# iptables -t mangle -X +# iptables -t raw -F +# iptables -t raw -X +# iptables -t security -F +# iptables -t security -X +# iptables -P INPUT ACCEPT +# iptables -P FORWARD ACCEPT +# iptables -P OUTPUT ACCEPT +---- + +The -F command with no arguments flushes all the chains in its current table. Similarly, -X deletes all empty non-default chains in a table. + +Individual chains may be flushed or deleted by following -F and -X with a [chain] argument. + +=== Editing rules + +Rules can be edited by + +- appending -A a rule to a chain, + +- inserting -I it at a specific position on the chain, + +- replacing -R an existing rule, + +- or deleting -D it. + +The first three commands are exemplified in the following. + +First of all, our computer is not a router (unless, of course, it is a router). We want to change the default policy on the FORWARD chain from ACCEPT to DROP. + +[source,bash] +---- +# iptables -P FORWARD DROP +---- + + + +=== Examples + +[NOTE] +==== +We are going to use Shorewall as an iptables configuration tool. + +See Appendix. +==== + +Here are some examples of "raw" iptables command lines. + + +==== Block Traffic by PortPermalink + +You may use a port to block all traffic coming in on a specific interface. + +For example: + +[source,bash] +---- +iptables -A INPUT -j DROP -p tcp --destination-port 110 -i eth0 +---- + +Let’s examine what each part of this command does: + +- **-A** will add or append the rule to the end of the chain. + + **INPUT** will add the rule to the table. + + **DROP** means the packets are discarded. + +- **-p tcp** means the rule will only drop TCP packets. + +- **--destination-port 110** filters packets targeted to port 110. + +- **-i eth0** means this rule will impact only packets arriving on the eth0 interface. + + +==== Drop Traffic + +In order to drop all incoming traffic from a specific IP address, use the iptables command with the following options: + +[source,bash] +---- +iptables -I INPUT -s 198.51.100.0 -j DROP +---- + +To remove these rules, use the **--delete** or **-D** option: + +[source,bash] +---- +iptables --delete INPUT -s 198.51.100.0 -j DROP +iptables -D INPUT -s 198.51.100.0 -j DROP +---- + + +==== Block or Allow Traffic by Port Number + +One way to create a firewall is to block all traffic to the system and then allow traffic on certain ports. + +Below is a sample sequence of commands to illustrate the process: + +[source,bash] +---- +iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT +iptables -A INPUT -i lo -m comment --comment "Allow loopback connections" -j ACCEPT +iptables -A INPUT -p icmp -m comment --comment "Allow Ping to work as expected" -j ACCEPT +iptables -A INPUT -p tcp -m multiport --destination-ports 22,25,53,80,443,465,5222,5269,5280,8999:9003 -j ACCEPT +iptables -A INPUT -p udp -m multiport --destination-ports 53 -j ACCEPT +iptables -P INPUT DROP +iptables -P FORWARD DROP +---- + +Let’s break down the example above. + +The **first two** commands add or append rules to the **INPUT chain** in order to allow access on specific ports. + +The **-p tcp** and **-p udp** options specify either **UDP** or **TCP** packet types. + +The **-m** multiport function matches packets on the basis of their source or destination ports, and can accept the specification of up to 15 ports. + +Multiport also accepts **ranges such as 8999:9003** which counts as 2 of the 15 possible ports, but matches ports 8999, 9000, 9001, 9002, and 9003. + +The next command **allows all incoming** and **outgoing packets** that are associated with existing connections so that they will not be inadvertently blocked by the firewall. + +The final two commands use the **-P** option to describe the **default policy** for these chains. As a result, all packets processed by **INPUT** and **FORWARD** will be dropped by default. + +[NOTE] +==== +Note that the rules described above only control incoming packets, and do not limit outgoing connections. +==== + +=== More Examples + +[source,bash] +---- +# Allow all loopback (lo0) traffic and reject traffic +# to localhost that does not originate from lo0. +-A INPUT -i lo -j ACCEPT +-A INPUT ! -i lo -s 127.0.0.0/8 -j REJECT + +# Allow ping. +-A INPUT -p icmp -m state --state NEW --icmp-type 8 -j ACCEPT + +# Allow SSH connections. +-A INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT + +# Allow HTTP and HTTPS connections from anywhere +# (the normal ports for web servers). +-A INPUT -p tcp --dport 80 -m state --state NEW -j ACCEPT +-A INPUT -p tcp --dport 443 -m state --state NEW -j ACCEPT + +# Allow inbound traffic from established connections. +# This includes ICMP error returns. +-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT + +# Log what was incoming but denied (optional but useful). +-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables_INPUT_denied: " --log-level 7 + +# Reject all other inbound. +-A INPUT -j REJECT + +# Log any traffic that was sent to you +# for forwarding (optional but useful). +-A FORWARD -m limit --limit 5/min -j LOG --log-prefix "iptables_FORWARD_denied: " --log-level 7 + +# Reject all traffic forwarding. +-A FORWARD -j REJECT +---- + + +[appendix] +== How to use iptables + + + +Shorewall is not the easiest to use of the available iptables configuration tools but I believe that it is the most flexible and powerful. + +It can handle complex and fast changing network environments. + +It needs multiple configuration files, even for simple setups. + +Suitable for powerusers! - Most likely there are a lot of these among our Students :-) + +Shorewall is very popular! + + + + + +https://wiki.archlinux.org[Origin] + + + + + + +:hardbreaks: + +{empty} + +{empty} + +{empty} + +:!hardbreaks: + +''' + diff --git a/labs/os2/LICENSE b/labs/os2/LICENSE new file mode 100644 index 0000000..82b5650 --- /dev/null +++ b/labs/os2/LICENSE @@ -0,0 +1,614 @@ +GNU AFFERO GENERAL PUBLIC LICENSE + +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +Preamble + +The GNU Affero General Public License is a free, copyleft license for software +and other kinds of works, specifically designed to ensure cooperation with +the community in the case of network server software. + +The licenses for most software and other practical works are designed to take +away your freedom to share and change the works. By contrast, our General +Public Licenses are intended to guarantee your freedom to share and change +all versions of a program--to make sure it remains free software for all its +users. + +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 them 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. + +Developers that use our General Public Licenses protect your rights with two +steps: (1) assert copyright on the software, and (2) offer you this License +which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made +in alternate versions of the program, if they receive widespread use, become +available for other developers to incorporate. Many developers of free software +are heartened and encouraged by the resulting cooperation. However, in the +case of software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and letting +the public access it on a server without ever releasing its source code to +the public. + +The GNU Affero General Public License is designed specifically to ensure that, +in such cases, the modified source code becomes available to the community. +It requires the operator of a network server to provide the source code of +the modified version running there to the users of that server. Therefore, +public use of a modified version, on a publicly accessible server, gives the +public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by +Affero, was designed to accomplish similar goals. This is a different license, +not a version of the Affero GPL, but Affero has released a new version of +the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification +follow. + +TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, +such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. +Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals +or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in +a fashion requiring copyright permission, other than the making of an exact +copy. The resulting work is called a "modified version" of the earlier work +or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the +Program. + +To "propagate" a work means to do anything with it that, without permission, +would make you directly or secondarily liable for infringement under applicable +copyright law, except executing it on a computer or modifying a private copy. +Propagation includes copying, distribution (with or without modification), +making available to the public, and in some countries other activities as +well. + +To "convey" a work means any kind of propagation that enables other parties +to make or receive copies. Mere interaction with a user through a computer +network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the +extent that it includes a convenient and prominently visible feature that +(1) displays an appropriate copyright notice, and (2) tells the user that +there is no warranty for the work (except to the extent that warranties are +provided), that licensees may convey the work under this License, and how +to view a copy of this License. If the interface presents a list of user commands +or options, such as a menu, a prominent item in the list meets this criterion. + + 1. Source Code. + +The "source code" for a work means the preferred form of the work for making +modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard +defined by a recognized standards body, or, in the case of interfaces specified +for a particular programming language, one that is widely used among developers +working in that language. + +The "System Libraries" of an executable work include anything, other than +the work as a whole, that (a) is included in the normal form of packaging +a Major Component, but which is not part of that Major Component, and (b) +serves only to enable use of the work with that Major Component, or to implement +a Standard Interface for which an implementation is available to the public +in source code form. A "Major Component", in this context, means a major essential +component (kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to produce +the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source +code needed to generate, install, and (for an executable work) run the object +code and to modify the work, including scripts to control those activities. +However, it does not include the work's System Libraries, or general-purpose +tools or generally available free programs which are used unmodified in performing +those activities but which are not part of the work. For example, Corresponding +Source includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically linked +subprograms that the work is specifically designed to require, such as by +intimate data communication or control flow between those + + subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate +automatically from other parts of the Corresponding Source. + + The Corresponding Source for a work in source code form is that same work. + + 2. Basic Permissions. + +All rights granted under this License are granted for the term of copyright +on the Program, and are irrevocable provided the stated conditions are met. +This License explicitly affirms your unlimited permission to run the unmodified +Program. The output from running a covered work is covered by this License +only if the output, given its content, constitutes a covered work. This License +acknowledges your rights of fair use or other equivalent, as provided by copyright +law. + +You may make, run and propagate covered works that you do not convey, without +conditions so long as your license otherwise remains in force. You may convey +covered works to others for the sole purpose of having them make modifications +exclusively for you, or provide you with facilities for running those works, +provided that you comply with the terms of this License in conveying all material +for which you do not control copyright. Those thus making or running the covered +works for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of your copyrighted +material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions +stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological measure +under any applicable law fulfilling obligations under article 11 of the WIPO +copyright treaty adopted on 20 December 1996, or similar laws prohibiting +or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention +of technological measures to the extent such circumvention is effected by +exercising rights under this License with respect to the covered work, and +you disclaim any intention to limit operation or modification of the work +as a means of enforcing, against the work's users, your or third parties' +legal rights to forbid circumvention of technological measures. + + 4. Conveying Verbatim Copies. + +You may convey 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; keep intact all notices stating +that this License and any non-permissive terms added in accord with section +7 apply to the code; keep intact all notices of the absence of any warranty; +and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you +may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to produce +it from the Program, in the form of source code under the terms of section +4, provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified it, and +giving a relevant date. + +b) The work must carry prominent notices stating that it is released under +this License and any conditions added under section 7. This requirement modifies +the requirement in section 4 to "keep intact all notices". + +c) You must license the entire work, as a whole, under this License to anyone +who comes into possession of a copy. This License will therefore apply, along +with any applicable section 7 additional terms, to the whole of the work, +and all its parts, regardless of how they are packaged. This License gives +no permission to license the work in any other way, but it does not invalidate +such permission if you have separately received it. + +d) If the work has interactive user interfaces, each must display Appropriate +Legal Notices; however, if the Program has interactive interfaces that do +not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, +which are not by their nature extensions of the covered work, and which are +not combined with it such as to form a larger program, in or on a volume of +a storage or distribution medium, is called an "aggregate" if the compilation +and its resulting copyright are not used to limit the access or legal rights +of the compilation's users beyond what the individual works permit. Inclusion +of a covered work in an aggregate does not cause this License to apply to +the other parts of the aggregate. + + 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of sections +4 and 5, provided that you also convey the machine-readable Corresponding +Source under the terms of this License, in one of these ways: + +a) Convey the object code in, or embodied in, a physical product (including +a physical distribution medium), accompanied by the Corresponding Source fixed +on a durable physical medium customarily used for software interchange. + +b) Convey the object code in, or embodied in, a physical product (including +a physical distribution medium), accompanied by a written offer, valid for +at least three years and valid for as long as you offer spare parts or customer +support for that product model, to give anyone who possesses the object code +either (1) a copy of the Corresponding Source for all the software in the +product that is covered by this License, on a durable physical medium customarily +used for software interchange, for a price no more than your reasonable cost +of physically performing this conveying of source, or (2) access to copy the +Corresponding Source from a network server at no charge. + +c) Convey individual copies of the object code with a copy of the written +offer to provide the Corresponding Source. This alternative is allowed only +occasionally and noncommercially, and only if you received the object code +with such an offer, in accord with subsection 6b. + +d) Convey the object code by offering access from a designated place (gratis +or for a charge), and offer equivalent access to the Corresponding Source +in the same way through the same place at no further charge. You need not +require recipients to copy the Corresponding Source along with the object +code. If the place to copy the object code is a network server, the Corresponding +Source may be on a different server (operated by you or a third party) that +supports equivalent copying facilities, provided you maintain clear directions +next to the object code saying where to find the Corresponding Source. Regardless +of what server hosts the Corresponding Source, you remain obligated to ensure +that it is available for as long as needed to satisfy these requirements. + +e) Convey the object code using peer-to-peer transmission, provided you inform +other peers where the object code and Corresponding Source of the work are +being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from +the Corresponding Source as a System Library, need not be included in conveying +the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible +personal property which is normally used for personal, family, or household +purposes, or (2) anything designed or sold for incorporation into a dwelling. +In determining whether a product is a consumer product, doubtful cases shall +be resolved in favor of coverage. For a particular product received by a particular +user, "normally used" refers to a typical or common use of that class of product, +regardless of the status of the particular user or of the way in which the +particular user actually uses, or expects or is expected to use, the product. +A product is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent the +only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, +authorization keys, or other information required to install and execute modified +versions of a covered work in that User Product from a modified version of +its Corresponding Source. The information must suffice to ensure that the +continued functioning of the modified object code is in no case prevented +or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically +for use in, a User Product, and the conveying occurs as part of a transaction +in which the right of possession and use of the User Product is transferred +to the recipient in perpetuity or for a fixed term (regardless of how the +transaction is characterized), the Corresponding Source conveyed under this +section must be accompanied by the Installation Information. But this requirement +does not apply if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has been installed +in ROM). + +The requirement to provide Installation Information does not include a requirement +to continue to provide support service, warranty, or updates for a work that +has been modified or installed by the recipient, or for the User Product in +which it has been modified or installed. Access to a network may be denied +when the modification itself materially and adversely affects the operation +of the network or violates the rules and protocols for communication across +the network. + +Corresponding Source conveyed, and Installation Information provided, in accord +with this section must be in a format that is publicly documented (and with +an implementation available to the public in source code form), and must require +no special password or key for unpacking, reading or copying. + + 7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this License +by making exceptions from one or more of its conditions. Additional permissions +that are applicable to the entire Program shall be treated as though they +were included in this License, to the extent that they are valid under applicable +law. If additional permissions apply only to part of the Program, that part +may be used separately under those permissions, but the entire Program remains +governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any +additional permissions from that copy, or from any part of it. (Additional +permissions may be written to require their own removal in certain cases when +you modify the work.) You may place additional permissions on material, added +by you to a covered work, for which you have or can give appropriate copyright +permission. + +Notwithstanding any other provision of this License, for material you add +to a covered work, you may (if authorized by the copyright holders of that +material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of +sections 15 and 16 of this License; or + +b) Requiring preservation of specified reasonable legal notices or author +attributions in that material or in the Appropriate Legal Notices displayed +by works containing it; or + +c) Prohibiting misrepresentation of the origin of that material, or requiring +that modified versions of such material be marked in reasonable ways as different +from the original version; or + +d) Limiting the use for publicity purposes of names of licensors or authors +of the material; or + +e) Declining to grant rights under trademark law for use of some trade names, +trademarks, or service marks; or + +f) Requiring indemnification of licensors and authors of that material by +anyone who conveys the material (or modified versions of it) with contractual +assumptions of liability to the recipient, for any liability that these contractual +assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered "further restrictions" +within the meaning of section 10. If the Program as you received it, or any +part of it, contains a notice stating that it is governed by this License +along with a term that is a further restriction, you may remove that term. +If a license document contains a further restriction but permits relicensing +or conveying under this License, you may add to a covered work material governed +by the terms of that license document, provided that the further restriction +does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, +in the relevant source files, a statement of the additional terms that apply +to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form +of a separately written license, or stated as exceptions; the above requirements +apply either way. + + 8. Termination. + +You may not propagate or modify a covered work except as expressly provided +under this License. Any attempt otherwise to propagate or modify it is void, +and will automatically terminate your rights under this License (including +any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from +a particular copyright holder is reinstated (a) provisionally, unless and +until the copyright holder explicitly and finally terminates your license, +and (b) permanently, if the copyright holder fails to notify you of the violation +by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently +if the copyright holder notifies you of the violation by some reasonable means, +this is the first time you have received notice of violation of this License +(for any work) from that copyright holder, and you cure the violation prior +to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses +of parties who have received copies or rights from you under this License. +If your rights have been terminated and not permanently reinstated, you do +not qualify to receive new licenses for the same material under section 10. + + 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy +of the Program. Ancillary propagation of a covered work occurring solely as +a consequence of using peer-to-peer transmission to receive a copy likewise +does not require acceptance. However, nothing other than this License grants +you permission to propagate or modify any covered work. These actions infringe +copyright if you do not accept this License. Therefore, by modifying or propagating +a covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives +a license from the original licensors, to run, modify and propagate that work, +subject to this License. You are not responsible for enforcing compliance +by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, +or substantially all assets of one, or subdividing an organization, or merging +organizations. If propagation of a covered work results from an entity transaction, +each party to that transaction who receives a copy of the work also receives +whatever licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the Corresponding +Source of the work from the predecessor in interest, if the predecessor has +it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights +granted or affirmed under this License. For example, you may not impose a +license fee, royalty, or other charge for exercise of rights granted under +this License, and you may not initiate litigation (including a cross-claim +or counterclaim in a lawsuit) alleging that any patent claim is infringed +by making, using, selling, offering for sale, or importing the Program or +any portion of it. + + 11. Patents. + +A "contributor" is a copyright holder who authorizes use under this License +of the Program or a work on which the Program is based. The work thus licensed +is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled +by the contributor, whether already acquired or hereafter acquired, that would +be infringed by some manner, permitted by this License, of making, using, +or selling its contributor version, but do not include claims that would be +infringed only as a consequence of further modification of the contributor +version. For purposes of this definition, "control" includes the right to +grant patent sublicenses in a manner consistent with the requirements of this +License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent +license under the contributor's essential patent claims, to make, use, sell, +offer for sale, import and otherwise run, modify and propagate the contents +of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement +or commitment, however denominated, not to enforce a patent (such as an express +permission to practice a patent or covenant not to s ue for patent infringement). +To "grant" such a patent license to a party means to make such an agreement +or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the +Corresponding Source of the work is not available for anyone to copy, free +of charge and under the terms of this License, through a publicly available +network server or other readily accessible means, then you must either (1) +cause the Corresponding Source to be so available, or (2) arrange to deprive +yourself of the benefit of the patent license for this particular work, or +(3) arrange, in a manner consistent with the requirements of this License, +to extend the patent + +license to downstream recipients. "Knowingly relying" means you have actual +knowledge that, but for the patent license, your conveying the covered work +in a country, or your recipient's use of the covered work in a country, would +infringe one or more identifiable patents in that country that you have reason +to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, +you convey, or propagate by procuring conveyance of, a covered work, and grant +a patent license to some of the parties receiving the covered work authorizing +them to use, propagate, modify or convey a specific copy of the covered work, +then the patent license you grant is automatically extended to all recipients +of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope +of its coverage, prohibits the exercise of, or is conditioned on the non-exercise +of one or more of the rights that are specifically granted under this License. +You may not convey a covered work if you are a party to an arrangement with +a third party that is in the business of distributing software, under which +you make payment to the third party based on the extent of your activity of +conveying the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by you +(or copies made from those copies), or (b) primarily for and in connection +with specific products or compilations that contain the covered work, unless +you entered into that arrangement, or that patent license was granted, prior +to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied +license or other defenses to infringement that may otherwise be available +to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + +If 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 convey a covered work so as +to satisfy simultaneously your obligations under this License and any other +pertinent obligations, then as a consequence you may + +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey the +Program, the only way you could satisfy both those terms and this License +would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, +your modified version must prominently offer all users interacting with it +remotely through a computer network (if your version supports such interaction) +an opportunity to receive the Corresponding Source of your version by providing +access to the Corresponding Source from a network server at no charge, through +some standard or customary means of facilitating copying of software. This +Corresponding Source shall include the Corresponding Source for any work covered +by version 3 of the GNU General Public License that is incorporated pursuant +to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to +link or combine any covered work with a work licensed under version 3 of the +GNU General Public License into a single combined work, and to convey the +resulting work. The terms of this License will continue to apply to the part +which is the covered work, but the work with which it is combined will remain +governed by version 3 of the GNU General Public License. + + 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the +GNU Affero 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 +that a certain numbered version of the GNU Affero General Public License "or +any later version" applies to it, you have the option of following the terms +and conditions either of that numbered version or of any later version published +by the Free Software Foundation. If the Program does not specify a version +number of the GNU Affero General Public License, you may choose any version +ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of +the GNU Affero General Public License can be used, that proxy's public statement +of acceptance of a version permanently authorizes you to choose that version +for the Program. + +Later license versions may give you additional or different permissions. However, +no additional obligations are imposed on any author or copyright holder as +a result of your choosing to follow a later version. + + 15. Disclaimer of Warranty. + +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. + + 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL +ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 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. + + 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot +be given local legal effect according to their terms, reviewing courts shall +apply local law that most closely approximates an absolute waiver of all civil +liability in connection with the Program, unless a warranty or assumption +of liability accompanies a copy of the Program in return for a fee. END OF +TERMS AND CONDITIONS + +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 state 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) + +This program is free software: you can redistribute it and/or modify it under +the terms of the GNU Affero General Public License as published by the Free +Software Foundation, either version 3 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 Affero General Public License for more +details. + +You should have received a copy of the GNU Affero General Public License along +with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, +you should also make sure that it provides a way for users to get its source. +For example, if your program is a web application, its interface could display +a "Source" link that leads users to an archive of the code. There are many +ways you could offer source, and different solutions will be better for different +programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. For +more information on this, and how to apply and follow the GNU AGPL, see . diff --git a/labs/os2/README.md b/labs/os2/README.md new file mode 100644 index 0000000..15dc6b3 --- /dev/null +++ b/labs/os2/README.md @@ -0,0 +1,3 @@ +# sec + +Σκοπός του εργαστηρίου είναι η εμβάθυνση των θεωρητικών και πρακτικών γνώσεων που ήδη έχει ο φοιτητής σε δίκτυα υπολογιστών και στην περιοχή της ασφάλειας υπολογιστών, ώστε να καλύψει το πλαίσιο γνώσεων της επιστημονικής περιοχής “Ασφάλειας Δικτύων και Επικοινωνιών”. diff --git a/labs/os2/basics.png b/labs/os2/basics.png new file mode 100644 index 0000000..620ec31 Binary files /dev/null and b/labs/os2/basics.png differ diff --git a/labs/os2/dmz1.png b/labs/os2/dmz1.png new file mode 100644 index 0000000..67b412d Binary files /dev/null and b/labs/os2/dmz1.png differ diff --git a/labs/os2/ex-3a_iptables-flow-chart.adoc b/labs/os2/ex-3a_iptables-flow-chart.adoc new file mode 100644 index 0000000..276275a --- /dev/null +++ b/labs/os2/ex-3a_iptables-flow-chart.adoc @@ -0,0 +1,104 @@ += Iptables - Traversing of tables and chains! +Apostolos rootApostolos@swarmlab.io +// Metadata: +:description: Intro and Install +:keywords: sec, tcpdump +:data-uri: +:toc: right +:toc-title: Table of Contents +:toclevels: 4 +:source-highlighter: highlight +:icons: font +:sectnums: + + + +{empty} + + + + +== General + +When a packet first enters the firewall, it hits the hardware and then gets passed on to the proper device driver in the kernel. + +Then the packet starts to go through a series of steps in the kernel, before it is either sent to the correct application (locally), or forwarded to another host - or whatever happens to it. + + +== Destination local host (our own machine) + +.Destination local host +|=== +|Step| Table| Chain| Comment +|1| | | On the wire (e.g., Internet) +|2| | | Comes in on the interface (e.g., eth0) +|3| raw| PREROUTING| This chain is used to handle packets before the connection tracking takes place. It can be used to set a specific connection not to be handled by the connection tracking code for example. +|4| | | This is when the connection tracking code takes place +|5| mangle| PREROUTING| This chain is normally used for mangling packets, i.e., changing TOS and so on. +|6| nat| PREROUTING| This chain is used for DNAT mainly. Avoid filtering in this chain since it will be bypassed in certain cases. +|7| | | Routing decision, i.e., is the packet destined for our local host or to be forwarded and where. +|8| mangle| INPUT| At this point, the mangle INPUT chain is hit. We use this chain to mangle packets, after they have been routed, but before they are actually sent to the process on the machine. +|9| filter| INPUT| This is where we do filtering for all incoming traffic destined for our local host. Note that all incoming packets destined for this host pass through this chain, no matter what interface or in which direction they came from. +|10| | | Local process or application (i.e., server or client program). +|=== + + +== Source local host (our own machine) + +.Source local host +|=== +|Step| Table| Chain| Comment +|1| | | Local process/application (i.e., server/client program) +|2| | | Routing decision. What source address to use, what outgoing interface to use, and other necessary information that needs to be gathered. +|3| raw| OUTPUT| This is where you do work before the connection tracking has taken place for locally generated packets. You can mark connections so that they will not be tracked for example. +|4| | | This is where the connection tracking takes place for locally generated packets, for example state changes et cetera. +|5| mangle| OUTPUT| This is where we mangle packets, it is suggested that you do not filter in this chain since it can have side effects. +|6| nat| OUTPUT| This chain can be used to NAT outgoing packets from the firewall itself. +|7| | | Routing decision, since the previous mangle and nat changes may have changed how the packet should be routed. +|8| filter| OUTPUT| This is where we filter packets going out from the local host. +|9| mangle| POSTROUTING| The POSTROUTING chain in the mangle table is mainly used when we want to do mangling on packets before they leave our host, but after the actual routing decisions. This chain will be hit by both packets just traversing the firewall, as well as packets created by the firewall itself. +|10| nat| POSTROUTING| This is where we do SNAT as described earlier. It is suggested that you don't do filtering here since it can have side effects, and certain packets might slip through even though you set a default policy of DROP. +|11| | | Goes out on some interface (e.g., eth0) +|12| | | On the wire (e.g., Internet) +|=== + + + +== Forwarded packets + +In this example, we're assuming that the packet is destined for another host on another network. The packet goes through the different steps in the following fashion: + +.Forwarded packets +|=== +|Step| Table| Chain| Comment +|1| | | On the wire (i.e., Internet) +|2| | | Comes in on the interface (i.e., eth0) +|3| raw| PREROUTING| Here you can set a connection to not be handled by the connection tracking system. +|4| | | This is where the non-locally generated connection tracking takes place. +|5| mangle| PREROUTING| This chain is normally used for mangling packets, i.e., changing TOS and so on. +|6| nat| PREROUTING| This chain is used for DNAT mainly. SNAT is done further on. Avoid filtering in this chain since it will be bypassed in certain cases. +|7| | | Routing decision, i.e., is the packet destined for our local host or to be forwarded and where. +|8| mangle| FORWARD| The packet is then sent on to the FORWARD chain of the mangle table. This can be used for very specific needs, where we want to mangle the packets after the initial routing decision, but before the last routing decision made just before the packet is sent out. +|9| filter| FORWARD| The packet gets routed onto the FORWARD chain. Only forwarded packets go through here, and here we do all the filtering. Note that all traffic that's forwarded goes through here (not only in one direction), so you need to think about it when writing your rule-set. +|10| mangle| POSTROUTING| This chain is used for specific types of packet mangling that we wish to take place after all kinds of routing decisions have been done, but still on this machine. +|11| nat| POSTROUTING| This chain should first and foremost be used for SNAT. Avoid doing filtering here, since certain packets might pass this chain without ever hitting it. This is also where Masquerading is done. +|12| | | Goes out on the outgoing interface (i.e., eth1). +|13| | | Out on the wire again (i.e., LAN). +|=== + + + + + + + + + +:hardbreaks: + +{empty} + +{empty} + +{empty} + +:!hardbreaks: + +''' diff --git a/labs/os2/ex-4_iptables.adoc b/labs/os2/ex-4_iptables.adoc new file mode 100644 index 0000000..8c2eaa3 --- /dev/null +++ b/labs/os2/ex-4_iptables.adoc @@ -0,0 +1,311 @@ += Iptables with shorewall! +Apostolos rootApostolos@swarmlab.io +// Metadata: +:description: Intro and Install +:keywords: sec, tcpdump +:data-uri: +:toc: right +:toc-title: Table of Contents +:toclevels: 4 +:source-highlighter: highlight +:icons: font +:sectnums: + + + +{empty} + + + +[[cheat-Docker]] +== Install swarmlab-sec (Home PC) + +HowTo: See http://docs.swarmlab.io/lab/sec/sec.adoc.html + + +.NOTE +[NOTE] +==== +Assuming you're already logged in +==== + + + +== shorewall + + +**Shorewall** is an open source firewall tool for Linux that builds upon the Netfilter (iptables/ipchains) system built into the Linux kernel, making it easier to manage more complex configuration schemes by providing a higher level of abstraction for describing rules using text files. + +https://en.wikipedia.org/wiki/Shorewall[More: wikipedia] + + +.NOTE +[NOTE] +==== +Our docker instances have only one nic + +to add more nic's: + +.create netowrk frist +[source,bash] +---- +docker network create --driver=bridge --subnet=192.168.0.0/16 net1 +docker network create --driver=bridge --subnet=192.168.0.0/16 net2 +docker network create --driver=bridge --subnet=192.168.0.0/16 net3 +---- + +then connect network to container + +.connect network created to container +[source,bash] +---- +docker network connect net1 master +docker network connect net1 worker1 +docker network connect net2 master +docker network connect net2 worker2 +---- + +now let's look at the following image + + +==== + + +=== Installation + +Shorewall is already installed on swarmlab-sec. + + +== Basic Two-Interface Firewall + + +image::basics.png[Basic Two-Interface Firewall] + + + +.connect to master first +[NOTE] +==== + +Assuming you're already logged in master! + +master is now our Firewall/Router + +swarmlab-sec login +==== + + +== Shorewall Concepts + +The configuration files for Shorewall are contained in the directory /etc/shorewall + +=== zones — Shorewall zone declaration file + +The /etc/shorewall/zones file declares your network zones. You specify the hosts in each zone through entries in /etc/shorewall/interfaces + + +./etc/shorewall/zones +[source,bash] +---- +#ZONE TYPE OPTIONS IN_OPTIONS OUT_OPTIONS +fw firewall +net ipv4 +loc ipv4 +---- + +=== interfaces — Shorewall interfaces file + +The interfaces file serves to define the firewall's network interfaces to Shorewall. + +./etc/shorewall/interfaces +[source,bash] +---- +#ZONE INTERFACE BROADCAST OPTIONS +net eth0 dhcp,routefilter +loc eth1 detect +---- + + +=== policy — Shorewall policy file + +This file defines the high-level policy for connections between zone + + +./etc/shorewall/policy +[source,bash] +---- +#SOURCE DEST POLICY LOGLEVEL LIMIT +loc net ACCEPT +net all DROP info +all all REJECT info +---- + + +=== rules — Shorewall rules file + +Entries in this file govern connection establishment by defining exceptions to the policies + + +./etc/shorewall/rules +[source,bash] +---- +#ACTION SOURCE DEST PROTO DPORT +ACCEPT $FW net udp 53 +ACCEPT net $FW udp 53 +ACCEPT $FW net tcp 80 +ACCEPT net $FW tcp 80 +---- + + +=== Compile then Execute + +Shorewall uses a "compile" then "execute" approach. The Shorewall configuration compiler reads the configuration files and generates a shell script. Errors in the compilation step cause the script to be discarded and the command to be aborted. If the compilation step doesn't find any errors then the shell script is executed. + + + +./sbin/shorewall +[source,bash] +---- +/sbin/shorewall start +/sbin/shorewall stop +/sbin/shorewall clear +---- + + + +.NOTE +[NOTE] +==== +The 'compiled' scripts are placed by default in the directory /var/lib/shorewall and are named to correspond to the command being executed. For example, the command /sbin/shorewall start will generate a script named /var/lib/shorewall/.start and, if the compilation is error free, that script will then be executed. If the script executes successfully, it then copies itself to /var/lib/shorewall/firewall. When an /sbin/shorewall stop or /sbin/shorewall clear command is subsequently executed, /var/lib/shorewall/firewall is run to perform the requested operation. + +The AUTOMAKE option in /etc/shorewall/shorewall.conf may be set to automatically generate a new script when one of the configuration files is changed. When no file has changed since the last compilation, the /sbin/shorewall start, /sbin/shorewall reload and /sbin/shorewall restart commands will simply execute the current /var/lib/shorewall/firewall script. +==== + + + +== Three-Interface Firewall + + +image::dmz1.png[Three-Interface Firewall] + +=== zones + +./etc/shorewall/zones +[source,bash] +---- +#ZONE TYPE OPTIONS IN_OPTIONS OUT_OPTIONS +fw firewall +net ipv4 +loc ipv4 +dmz ipv4 #new line +---- + +=== interfaces + +./etc/shorewall/interfaces +[source,bash] +---- +#ZONE INTERFACE BROADCAST OPTIONS +net eth0 dhcp,routefilter +loc eth1 detect +dmz eth2 detect #new line +---- + + +=== policy + +./etc/shorewall/policy +[source,bash] +---- +#SOURCE DEST POLICY LOGLEVEL LIMIT +loc net ACCEPT +dmz net DROP #new line +net all DROP info +all all REJECT info +---- + + +=== rules + +./etc/shorewall/rules +[source,bash] +---- +#ACTION SOURCE DEST PROTO DPORT +ACCEPT $FW net udp 53 +ACCEPT net $FW udp 53 +ACCEPT $FW net tcp 80 +ACCEPT net $FW tcp 80 +#New lines +ACCEPT $FW dmz udp 53 +ACCEPT dmz $FW udp 53 +ACCEPT $FW dmz tcp 80 +ACCEPT dmz $FW tcp 80 + +ACCEPT loc dmz tcp 80 # Add your rules for the zones you have defined. +ACCEPT dmz loc tcp 80 # +ACCEPT loc net tcp 80 # This here is an example +ACCEPT net loc tcp 80 # for communication +ACCEPT dmz net tcp 80 # over port 80 +ACCEPT net dmz tcp 80 # aka the web +---- + + + +=== masq - Shorewall Masquerade/SNAT definition file + +/etc/shorewall/masq - directs the firewall where to use many-to-one (dynamic) Network Address Translation (a.k.a. Masquerading) and Source Network Address Translation (SNAT). + + +./etc/shorewall/masq +[source,bash] +---- +#INTERFACE SOURCE ADDRESS PROTO DPORT +eth0 eth1 +eth0 eth2 +---- + +=== snat — Shorewall SNAT/Masquerade definition file + +This file is used to define dynamic NAT (Masquerading) and to define Source NAT (SNAT). It superseded shorewall-masq(5) in Shorewall 5.0.14. + + +./etc/shorewall/masq +[source,bash] +---- +#ACTION SOURCE DEST +MASQUERADE 192.168.0.0/24 eth0 +MASQUERADE 192.168.1.0/24 eth0 +---- + +- You have a simple masquerading setup where eth0 connects to internet and eth1 connects to your local network with subnet 192.168.0.0/24. +- You add a router to your local network to connect subnet 192.168.1.0/24 which you also want to masquerade. You then add a second entry for eth0 to this file + + +[NOTE] +==== +Beginning with that release, the Shorewall compiler will automatically convert existing masq files to the equivalent snat file, and rename the masq file to masq.bak. +==== + + +=== Compile and Execute + + +./sbin/shorewall +[source,bash] +---- +/sbin/shorewall start +/sbin/shorewall stop +/sbin/shorewall clear +---- + + + +:hardbreaks: + +{empty} + +{empty} + +{empty} + +:!hardbreaks: + +''' + diff --git a/labs/os2/ex-5_iptables.adoc b/labs/os2/ex-5_iptables.adoc new file mode 100644 index 0000000..9723014 --- /dev/null +++ b/labs/os2/ex-5_iptables.adoc @@ -0,0 +1,277 @@ += VPN! +Apostolos rootApostolos@swarmlab.io +// Metadata: +:description: Intro and Install +:keywords: sec, tcpdump +:data-uri: +:toc: right +:toc-title: Πίνακας περιεχομένων +:toclevels: 4 +:source-highlighter: highlight +:icons: font +:sectnums: + +include::header.adoc[] + + +{empty} + + + +[[cheat-Docker]] +== Install swarmlab-sec (Home PC) + +HowTo: See http://docs.swarmlab.io/lab/sec/sec.adoc.html + + +.NOTE +[NOTE] +==== +Assuming you're already logged in +==== + + + +== VPN + +A ***virtual private network (VPN)*** extends a private network across a public network, and enables users to send and receive data across shared or public networks as if their computing devices were directly connected to the private network. Applications running on a computing device, e.g., a laptop, desktop, smartphone, across a VPN may therefore benefit from the functionality, security, and management of the private network. Encryption is a common, though not an inherent, part of a VPN connection + +https://en.wikipedia.org/wiki/Virtual_private_network[More: wikipedia] + +image::495px-VPN_overview-en.svg.png[VPN connectivity overview] + +.NOTE +[NOTE] +==== +**OpenVPN** is an open-source software that implements virtual private network (VPN) techniques to create secure point-to-point or site-to-site connections in routed or bridged configurations and remote access facilities. It uses a custom security protocol that utilizes SSL/TLS for key exchange. It is capable of traversing network address translators (NATs) and firewalls. It was written by James Yonan and is published under the GNU General Public License (GPL). + +https://en.wikipedia.org/wiki/OpenVPN[More: wikipedia] +==== + + +== Create VPN + + +.create-vpn.sh +[source,bash] +---- +#!/bin/bash +IP=192.168.89.5 # Server IP +P=1194 # Server Port +OVPN_SERVER='10.80.0.0/16' # VPN Network +vpn_data=/var/lib/swarmlab/openvpn/openvpn-services/ # Dir to save data ** this must exist ** +NAME=swarmlab-vpn-services # name of docker service +DOCKERnetwork=swarmlab-vpn-services-network # docker network +docker=registry.vlabs.uniwa.gr:5080/myownvpn # docker image + +docker stop $NAME #stop container +sleep 3 +docker container rm $NAME #rm container + +# rm config files +sudo rm -f $vpn_data/openvpn.conf.*.bak +sudo rm -f $vpn_data/openvpn.conf +sudo rm -f $vpn_data/ovpn_env.sh.*.bak +sudo rm -f $vpn_data/ovpn_env.sh + +# create network +sleep 2 +docker network create --attachable=true --driver=bridge --subnet=172.50.0.0/16 --gateway=172.50.0.1 $DOCKERnetwork + +read -d '' MULTILINE_EXTRA_SERVER_CONF << EOF +duplicate-cn +max-clients 35000 +topology subnet +EOF + +#run container +sleep 3 +docker run --net=none -it -v $vpn_data:/etc/openvpn --rm $docker ovpn_genconfig -u udp://$IP:1194 \ +-N -d -c -p "route 172.50.20.0 255.255.255.0" -e "topology subnet" -s $OVPN_SERVER + + +# create pki +sleep 3 +echo "new pki is disabled" +docker run --net=none -v $vpn_data:/etc/openvpn --rm -it $docker ovpn_initpki + +#sleep 3 +#docker run --net=none -v $vpn_data:/etc/openvpn --rm $docker ovpn_copy_server_files + +#create vpn +sleep 3 +docker run --detach --name $NAME -v $vpn_data:/etc/openvpn --net=$DOCKERnetwork --ip=172.50.0.2 -p $P:1194/udp --cap-add=NET_ADMIN $docker + +sleep 5 +sudo sysctl -w net.ipv4.ip_forward=1 + +#show created +docker ps +---- + + +== Create user + +.config +[source,bash] +---- +#!/bin/bash +IP=83.212.114.14 +P=5194 +vpn_data=/var/lib/swarmlab/openvpn/openvpn-services/ +NAME=swarmlab-vpn-services +DOCKERnetwork=swarmlab-vpn-services-network +docker=registry.vlabs.uniwa.gr:5080/myownvpn +PATHNAME=/var/lib/swarmlab/openvpn/etc/vpn-data_user_config +vpn_data_user_config=$PATHNAME + +vpn_data=/var/lib/swarmlab/openvpn/openvpn-services/ +vpn_data_user_config=/var/lib/swarmlab/openvpn/etc/vpn-data_user_config +NAME=swarmlab-vpn-services + +MANAGER=/var/lib/swarmlab/openvpn/etc/managers +WORKER=/var/lib/swarmlab/openvpn/etc/workers +MANAGERkeys=/var/lib/swarmlab/openvpn/etc/managers_keys + +---- + + + +.create-user.sh +[source,bash] +---- +#!/bin/bash + +. ./config + +sudo mkdir -p $vpn_data +sudo mkdir -p $vpn_data_user_config +sudo mkdir -p $MANAGERkeys + +docker=registry.vlabs.uniwa.gr:5080/myownvpn +echo $vpnip +echo $# + +docker=registry.vlabs.uniwa.gr:5080/myownvpn +echo $vpnip +echo $# + +if [ $# -eq 1 ]; then + CLIENTNAME=$1 + U=$CLIENTNAME + mkdir users + docker run -v $vpn_data:/etc/openvpn --rm -it $docker easyrsa build-client-full $CLIENTNAME nopass + sleep 3 + docker run -v $vpn_data:/etc/openvpn --log-driver=none --rm $docker ovpn_getclient $CLIENTNAME > users/$CLIENTNAME.ovpn + + file="users/$CLIENTNAME.ovpn" + + ps='remote ' + pi="remote $IP $P udp" + grep -q "^$ps" $file && sed -i "s/^$ps.*/$pi/" $file || sed -i "5a $pi" $file + + ps='comp-lzo' + pi='comp-lzo no' + grep -q "^$ps" $file && sed -i "s/^$ps.*/$pi/" $file || sed -i "6a $pi" $file + + ps='resolv-retry' + pi='resolv-retry infinite' + grep -q "^$ps" $file && sed -i "s/^$ps.*/$pi/" $file || sed -i "7a $pi" $file + ps='persist-key' + pi='persist-key' + grep -q "^$ps" $file && sed -i "s/^$ps.*/$pi/" $file || sed -i "8a $pi" $file + + ps='persist-tun' + pi='persist-tun' + grep -q "^$ps" $file && sed -i "s/^$ps.*/$pi/" $file || sed -i "9a $pi" $file + + ps='keepalive' + pi='keepalive 15 60' + grep -q "^$ps" $file && sed -i "s/^$ps.*/$pi/" $file || sed -i "10a $pi" $file + + + +else + echo "no clientname" +fi +---- + + +== rm vpn user + +.rm-user.sh +[source,bash] +---- +#!/bin/bash +. ./config + +CLIENTNAME=$1 +U=$CLIENTNAME + +if [ $# -eq 1 ]; then + sudo rm -f $vpn_data/pki/reqs/$CLIENTNAME.req + sudo rm -f $vpn_data/pki/private/$CLIENTNAME.key + sudo rm -f $vpn_data/pki/issued/$CLIENTNAME.crt + sudo rm -f $vpn_data/server/ccd/$CLIENTNAME + sudo rm -f $vpn_data/ccd/$CLIENTNAME + pem=$(sudo grep "CN=$U$" $vpn_data/pki/index.txt | cut -f4) + #/var/lab/gswarm/vpn-data/pki/certs_by_serial/BACA61827E65D0E5F695245519410952.pem + sudo rm -f $vpn_data/pki/certs_by_serial/$pem.pem + sudo sed -i "/CN=$U$/d" $vpn_data/pki/index.txt + echo $pem + docker run -v $vpn_data:/etc/openvpn --log-driver=none --rm -it $docker ovpn_revokeclient $CLIENTNAME remove + + + sudo rm -f $vpn_data_user_config/$CLIENTNAME.ovpn + sudo rm -f $vpn_data_user_config1/$CLIENTNAME.ovpn +else + echo "no client" +fi + +---- + +== show all vpn users + +.show-user.sh +[source,bash] +---- +. ./config + +docker exec -it $NAME ovpn_listclients +---- + +== show all connected vpn users + +.show-conn-user.sh +[source,bash] +---- +. ./config + +docker exec -it $NAME cat /tmp/openvpn-status.log +---- + + + + + +:hardbreaks: + +{empty} + +{empty} + +{empty} + +:!hardbreaks: + +''' + +.Reminder +[NOTE] +==== +:hardbreaks: +Caminante, no hay camino, +se hace camino al andar. + +Wanderer, there is no path, +the path is made by walking. + +*Antonio Machado* Campos de Castilla +==== diff --git a/labs/os2/header.adoc b/labs/os2/header.adoc new file mode 100644 index 0000000..6caffd1 --- /dev/null +++ b/labs/os2/header.adoc @@ -0,0 +1,5 @@ +[options="header"] +|======================= +|http://docs.swarmlab.io[Home] icon:home[link="http://docs.swarmlab.io", window="_self"]|http://docs.swarmlab.io/Howtos[HowTos] icon:wpbeginner[link="http://docs.swarmlab.io/Howtos", window="_self"]|http://docs.swarmlab.io/lab[Labs] icon:mixcloud[link="http://docs.swarmlab.io/lab", window="_self"] +|======================= +[.right.text-center] diff --git a/labs/os2/index.adoc b/labs/os2/index.adoc new file mode 100644 index 0000000..d02b098 --- /dev/null +++ b/labs/os2/index.adoc @@ -0,0 +1,40 @@ += Practical Exercises! +Apostolos rootApostolos@swarmlab.io +// Metadata: +:description: Intro and Install +:keywords: sec, tcpdump +:data-uri: +:toc: right +:toc-title: Table of Contents +:toclevels: 4 +:source-highlighter: highlight +:icons: font +:sectnums: + + + +{empty} + + +== Network_Analysis + +.Network analysis! +**** +*tcpdump* is a common packet analyzer that runs under the command line. It allows the user to display TCP/IP and other packets being transmitted or received over a network to which the computer is attached. Distributed under the BSD license, tcpdump is free software. + +http://docs.swarmlab.io/labs/os2/network-analysis.adoc.html[Network analysis^] +**** + + + + + +:hardbreaks: + +{empty} + +{empty} + +{empty} + +:!hardbreaks: + +''' + diff --git a/labs/os2/network-analysis.adoc b/labs/os2/network-analysis.adoc new file mode 100644 index 0000000..56fb395 --- /dev/null +++ b/labs/os2/network-analysis.adoc @@ -0,0 +1,272 @@ += Network analysis ! +Apostolos rootApostolos@swarmlab.io +// Metadata: +:description: network analysis +:keywords: sec, tcpdump +:data-uri: +:toc: right +:toc-title: Table of Contents +:toclevels: 4 +:source-highlighter: highlight +:icons: font +:sectnums: + + + +{empty} + + + + + +**tcpdump** is a common packet analyzer that runs under the command line. It allows the user to display TCP/IP and other packets being transmitted or received over a network to which the computer is attached. Distributed under the BSD license, tcpdump is free software. + +https://en.wikipedia.org/wiki/Tcpdump[More: wikipedia] + +== Basic + +=== Everything on an interface + +Just see what’s going on, by looking at what’s hitting your interface. + +[source,bash] +---- +tcpdump -i eth0 +---- + +=== Find Traffic by IP + +One of the most common queries, using host, you can see traffic that’s going to or from 1.1.1.1. + +[source,bash] +---- +tcpdump host 1.1.1.1 +---- + + +=== Filtering by Source and/or Destination + +If you only want to see traffic in one direction or the other, you can use src and dst. + +[source,bash] +---- +tcpdump src 1.1.1.1 +tcpdump dst 1.0.0.1 +---- + +=== Finding Packets by Network + +To find packets going to or from a particular network or subnet, use the net option. + +[source,bash] +---- +tcpdump net 1.2.3.0/24 +---- + + +=== Show Traffic Related to a Specific Port + +You can find specific port traffic by using the port option followed by the port number. + +[source,bash] +---- +tcpdump port 3389 +tcpdump src port 1025 +---- + +=== Show Traffic of One Protocol + +If you’re looking for one particular kind of traffic, you can use tcp, udp, icmp, and many others as well. + +[source,bash] +---- +tcpdump icmp +---- + +=== Reading / Writing Captures to a File (pcap) + +It’s often useful to save packet captures into a file for analysis in the future. These files are known as PCAP (PEE-cap) files, and they can be processed by hundreds of different applications, including network analyzers, intrusion detection systems, and of course by tcpdump itself. Here we’re writing to a file called capture_file using the -w switch. + + +[source,bash] +---- +tcpdump port 80 -w capture_file +---- + + +== Advanced + + +Now that we’ve seen what we can do with the basics through some examples, let’s look at some more advanced stuff. + +.More options +[source,bash] +---- + -X : Show the packet’s contents in both hex and ASCII. + -XX : Same as -X, but also shows the ethernet header. + -D : Show the list of available interfaces + -l : Line-readable output (for viewing as you save, or sending to other commands) + -q : Be less verbose (more quiet) with your output. + -t : Give human-readable timestamp output. + -tttt : Give maximally human-readable timestamp output. + -i eth0 : Listen on the eth0 interface. + -vv : Verbose output (more v’s gives more output). + -c : Only get x number of packets and then stop. + -s : Define the snaplength (size) of the capture in bytes. Use -s0 to get everything, unless you are intentionally capturing less. + -S : Print absolute sequence numbers. + -e : Get the ethernet header as well. + -q : Show less protocol information. + -E : Decrypt IPSEC traffic by providing an encryption key. +---- + + +[NOTE] +==== +It’s All About the Combinations + +Being able to do these various things individually is powerful, but the real magic of tcpdump comes from the ability to combine options in creative ways in order to isolate exactly what you’re looking for. There are three ways to do combinations, and if you’ve studied programming at all they’ll be pretty familiar to you. + +- AND + + and or && + +- OR + + or or || + +- EXCEPT + + not or ! +==== + + +=== From specific IP and destined for a specific Port + +Let’s find all traffic from 10.5.2.3 going to any host on port 3389. + +[source,bash] +---- +tcpdump -nnvvS src 10.5.2.3 and dst port 3389 +---- + + +=== From One Network to Another + +Let’s look for all traffic coming from 192.168.x.x and going to the 10.x or 172.16.x.x networks, and we’re showing hex output with no hostname resolution and one level of extra verbosity. + +[source,bash] +---- +tcpdump -nvX src net 192.168.0.0/16 and dst net 10.0.0.0/8 or 172.16.0.0/16 +---- + + +=== Isolate TCP Flags + +You can also use filters to isolate packets with specific TCP flags set. + +==== Isolate TCP RST flags. + +The filters below find these various packets because tcp[13] looks at offset 13 in the TCP header, the number represents the location within the byte, and the !=0 means that the flag in question is set to 1, i.e. it’s on. + +[source,bash] +---- +tcpdump 'tcp[13] & 4!=0' +tcpdump 'tcp[tcpflags] == tcp-rst' +---- + +==== Isolate TCP SYN flags. + +[source,bash] +---- +tcpdump 'tcp[13] & 2!=0' +tcpdump 'tcp[tcpflags] == tcp-syn' +---- + +==== Isolate packets that have both the SYN and ACK flags set. + +[source,bash] +---- +tcpdump 'tcp[13]=18' +---- + +[NOTE] +==== +Only the PSH, RST, SYN, and FIN flags are displayed in tcpdump‘s flag field output. URGs and ACKs are displayed, but they are shown elsewhere in the output rather than in the flags field. +==== + +==== Isolate TCP URG flags. + +[source,bash] +---- +tcpdump 'tcp[13] & 32!=0' +tcpdump 'tcp[tcpflags] == tcp-urg' +---- + +==== Isolate TCP ACK flags. + +[source,bash] +---- +tcpdump 'tcp[13] & 16!=0' +tcpdump 'tcp[tcpflags] == tcp-ack' +---- + +==== Isolate TCP PSH flags. + +[source,bash] +---- +tcpdump 'tcp[13] & 8!=0' +tcpdump 'tcp[tcpflags] == tcp-psh' +---- + +==== Isolate TCP FIN flags. + +[source,bash] +---- +tcpdump 'tcp[13] & 1!=0' +tcpdump 'tcp[tcpflags] == tcp-fin' +---- + + +=== Find Traffic With Evil Bit + +There’s a bit in the IP header that never gets set by legitimate applications, which we call the “Evil Bit”. Here’s a fun filter to find packets where it’s been toggled. + +[source,bash] +---- +tcpdump 'ip[6] & 128 != 0' +---- + +=== Summary + +Here are the takeaways. + +[NOTE] +==== +- **tcpdump** is a valuable tool for anyone looking to get into networking or **information security**. +- The raw way it interfaces with traffic, combined with the precision it offers in inspecting packets make **it the best possible tool** for learning TCP/IP. +- Protocol Analyzers like **Wireshark** are great, but if you want to truly master **packet-fu**, you must become one with tcpdump +==== + + +[appendix] +== How to use tcpdump + + +This exercise will show you how to isolate traffic in various ways—from IP, to port, to protocol, to application-layer traffic—to make sure you find exactly what you need as quickly as possible. + +https://danielmiessler.com/study/tcpdump[Origin] + + + + + + +:hardbreaks: + +{empty} + +{empty} + +{empty} + +:!hardbreaks: + +''' + diff --git a/labs/os2/scan-and-network-statistics.adoc b/labs/os2/scan-and-network-statistics.adoc new file mode 100644 index 0000000..be7194c --- /dev/null +++ b/labs/os2/scan-and-network-statistics.adoc @@ -0,0 +1,350 @@ += Scan and network statistics ! +Apostolos rootApostolos@swarmlab.io +// Metadata: +:description: os +:keywords: scan network statistics +:data-uri: +:toc: right +:toc-title: Table of Contents +:toclevels: 4 +:source-highlighter: highlight +:icons: font +:sectnums: + + + +{empty} + + + + +== Find IP + +[source,bash] +---- +# ifconfig + +eth0: flags=4163 mtu 1500 + inet 172.21.0.2 netmask 255.255.0.0 broadcast 172.21.255.255 + ether 02:42:ac:15:00:02 txqueuelen 0 (Ethernet) + RX packets 61 bytes 9309 (9.3 KB) + RX errors 0 dropped 0 overruns 0 frame 0 + TX packets 0 bytes 0 (0.0 B) + TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 + +lo: flags=73 mtu 65536 + inet 127.0.0.1 netmask 255.0.0.0 + loop txqueuelen 1000 (Local Loopback) + RX packets 248 bytes 14260 (14.2 KB) + RX errors 0 dropped 0 overruns 0 frame 0 + TX packets 248 bytes 14260 (14.2 KB) + TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 +---- + +TIP: inet ***172.21.0.2*** netmask 255.255.0.0 broadcast 172.21.255.255 + +== Find live hosts + +[source,bash] +---- +nmap -sP 172.21.0.* + +Nmap scan report for 172.21.0.1 (172.21.0.1) +Host is up (0.00028s latency). +MAC Address: 02:42:56:48:D0:61 (Unknown) +Nmap scan report for testnetwork2_worker_1.testnetwork2_net (172.21.0.3) +Host is up (0.00015s latency). +MAC Address: 02:42:AC:15:00:03 (Unknown) +Nmap scan report for testnetwork2_worker_3.testnetwork2_net (172.21.0.4) +Host is up (0.00018s latency). +MAC Address: 02:42:AC:15:00:04 (Unknown) +Nmap scan report for testnetwork2_worker_4.testnetwork2_net (172.21.0.5) +Host is up (0.00015s latency). +MAC Address: 02:42:AC:15:00:05 (Unknown) +Nmap scan report for testnetwork2_worker_2.testnetwork2_net (172.21.0.6) +Host is up (0.00017s latency). +MAC Address: 02:42:AC:15:00:06 (Unknown) +Nmap scan report for 9110d42e466b (172.21.0.2) + + +nmap -sP 172.21.0.* | grep Nmap | cut -d' ' -f5-6 + +172.21.0.1 (172.21.0.1) +testnetwork2_worker_1.testnetwork2_net (172.21.0.3) +testnetwork2_worker_3.testnetwork2_net (172.21.0.4) +testnetwork2_worker_4.testnetwork2_net (172.21.0.5) +testnetwork2_worker_2.testnetwork2_net (172.21.0.6) +9110d42e466b (172.21.0.2) + +---- + +.What is Nmap? +[NOTE] +==== +Nmap, short for Network Mapper, is a free, open-source tool for vulnerability scanning and network discovery. Network administrators use Nmap to identify what devices are running on their systems, discovering hosts that are available and the services they offer, finding open ports and detecting security risks. + +See https://en.wikipedia.org/wiki/Nmap +==== + + + +== Scan Ports + +=== Scan a Single Port, All Ports, or Series + +[source,bash] +---- +Nmap commands can be used to scan a single port or a series of ports: +---- + +=== Scan port 80 on the target system: + +[source,bash] +---- +nmap –p 80 172.21.0.3 +---- + +=== Scan ports 1 through 200 on the target system: + +[source,bash] +---- +nmap –p 1-200 172.21.0.3 +---- + +=== Scan (Fast) the most common ports: + +[source,bash] +---- +nmap –F 172.21.0.3 +---- + +=== To scan all ports (1 – 65535): + +[source,bash] +---- +nmap –p– 172.21.0.3 +---- + + + +=== Scan All TCP UDP Ports + +Scan all UDP and TCP ports in a single command. We will use -sU for UDP and sT for TCP protocol. +[source,bash] +---- +nmap -sU -sT -p0-65535 IP +---- + + +.What Are Ports? +[NOTE] +==== + +On modern operating systems, ports are numbered addresses for network traffic. Different kinds of services use different ports by default. + +For example, normal web traffic uses Port 80, while POP3 email uses Port 110. One of the ways that a firewall works is by allowing or restricting traffic over a particular port. + +Because the ports into your computer can cause a security risk, it’s critical to know which ports are open and which are blocked. + +==== + +== netstat + +=== Listing (Almost all) + +[source,bash] +---- +netstat -antlupe +---- + +=== Listing TCP Ports connections + +[source,bash] +---- +netstat -at +---- + +.Netstat +[NOTE] +==== +Netstat command displays various network related information such as network connections, routing tables, interface statistics, masquerade connections, multicast memberships etc., +==== + + +=== Listing UDP Ports connections + +[source,bash] +---- +netstat -au +---- + + +=== Listing all LISTENING Connections + +[source,bash] +---- +netstat -l +---- + + +=== Listing all TCP Listening Ports + +[source,bash] +---- +netstat -lt +---- + +=== Listing all UDP Listening Ports + +[source,bash] +---- +netstat -lu +---- + + +=== Listing all UNIX Listening Ports + +[source,bash] +---- +netstat -lx +---- + + +=== Showing Statistics by Protocol + +[source,bash] +---- +netstat -s +---- + +=== Showing Statistics by TCP Protocol + +[source,bash] +---- +netstat -st +---- + +=== Showing Statistics by UDP Protocol + +[source,bash] +---- +netstat -su +---- + +=== Displaying Service name with PID + +[source,bash] +---- +netstat -tp +---- + + +=== Displaying Promiscuous Mode + +Displaying Promiscuous mode with -ac switch, netstat print the selected information or refresh screen every five second. Default screen refresh in every second. + + +[source,bash] +---- + netstat -ac 5 | grep tcp +---- + +=== Setting Promiscuous Mode + +[source,bash] +---- + ifconfig eth0 promisc + +OR + +ip link set eth0 promisc on +---- + +=== Remove Promiscuous Mode + +[source,bash] +---- + ifconfig eth0 –promisc +---- + + +.Promiscuous Mode +[NOTE] +==== +Promiscuous mode is a mode for a wired network interface controller (NIC) or wireless network interface controller (WNIC) that causes the controller to pass all traffic it receives to the central processing unit (CPU) rather than passing only the frames that the controller is specifically programmed to receive. + +When a capable NIC is placed in Promiscuous Mode, it allows the NIC to intercept and read each arriving network packet in its entirety. + +If the NIC is not in Promiscuous Mode, it will only receive packets that are specifically addressed to the NIC. Promiscuous Mode must be supported by the NIC and by the operating system and any associated driver. Not all NICs support Promiscuous Mode, however it is pretty easy to determine if you have a NIC and OS capable of Promiscuous Mode. +==== + + +=== check if promiscuous mode is enabled on network interface + +[source,bash] +---- + +netstat -i + +Iface MTU RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg +eth0 1500 8352 0 0 0 12677 0 0 0 BMRU +lo 65536 14656 0 0 0 14656 0 0 0 LRU + +ifconfig eth0 promisc + +netstat -i + +Iface MTU RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg +eth0 1500 8352 0 0 0 12677 0 0 0 BMPRU +lo 65536 14696 0 0 0 14696 0 0 0 LRU + +ifconfig eth0 -promisc + +netstat -i + +Iface MTU RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg +eth0 1500 8353 0 0 0 12677 0 0 0 BMRU +lo 65536 15232 0 0 0 15232 0 0 0 LRU + + +---- + +.Promiscuous Mode +[NOTE] +==== +Look under the last column “Flg” for value “P”. If it’s there, it means promiscuous mode is enabled for that network interface + +B flag is for broadcast + +M flag is for multicast + +P flag is for promisc mode + +R is for running + +U is for up + + +==== + + + + +[appendix] +== How to use Nmap + +While the basis of Nmap's functionality is port scanning, it allows for a variety of related capabilities including: + +- Network mapping: Nmap can identify the devices on a network (also called host discovery), including servers, routers and switches, and how they're physically connected. +- OS detection: Nmap can detect the operating systems running on network devices (also called OS fingerprinting), providing the vendor name, the underlying operating system, the version of the software and even an estimate of devices' uptime. +- Service discovery: Nmap can not only identify hosts on the network, but whether they're acting as mail, web or name servers, and the particular applications and versions of the related software they're running. +- Security auditing: Figuring out what versions of operating systems and applications are running on network hosts lets network managers determine their vulnerability to specific flaws. If a network admin receives an alert about a vulnerability in a particular version of an application, for example, she can scan her network to identify whether that software version is running on the network and take steps to patch or update the relevant hosts. Scripts can also automate tasks such as detecting specific vulnerabilities. + + + + + + + + +:hardbreaks: + +{empty} + +{empty} + +{empty} + +:!hardbreaks: + +''' diff --git a/labs/os2/sec.adoc b/labs/os2/sec.adoc new file mode 100644 index 0000000..aa30d08 --- /dev/null +++ b/labs/os2/sec.adoc @@ -0,0 +1,157 @@ += Ασφάλεια Δικτύων και Επικοινωνιών ! +Apostolos rootApostolos@swarmlab.io +// Metadata: +:description: Intro and Install +:keywords: sec, iptables +:data-uri: +:toc: right +:toc-title: Πίνακας περιεχομένων +:toclevels: 4 +:icons: font +:source-highlighter: highlight +:sectnums: + + +include::header.adoc[] + + + + +{empty} + + + +[[cheat-Docker]] +== Install swarmlab-sec (Home PC) + +- Install docker + +http://docs.swarmlab.io/Howtos/docker/install.adoc.html[^] + +- Clone repo https://git.swarmlab.io:3000/swarmlab/swarmlab-sec + +HowTo: See http://docs.swarmlab.io/Howtos/git/use-git.adoc.html + +.INSTALL +[NOTE] +==== +See INSTALL.md for Installation Instruction +==== + +.lab +[NOTE] +==== +In Lab's everything is ready! +Goto "create" +==== + +[[cheat-swarmlab-sec]] +== Usage (swarmlab-sec) + + +- Open a console + +- Create a directory + +``` +cd dir +swarmlab-sec + +create create project (swarmlab-sec create) +up start swarmlab-sec (swarmlab-sec up size=10) +scale resize swarmlab-sec (swarmlab-sec scale size=30) +reload rebuild image (swarmlab-sec reload size=15) +login login swarmlab-sec (swarmlab-sec login) +exec execute command (swarmlab-sec exec [SHELL COMMAND]) +down stop swarmlab-sec (swarmlab-sec down) +clean clean project (swarmlab-sec clean) +list show instances (swarmlab-sec swarmlab-sec list) +help show help (swarmlab-sec help) +``` + +[NOTE] +==== +Using the tab key to automatically complete unambiguous commands and paths in Bash +==== + + +[[cheat-swarmlab-create]] +== Create swarmlab project + +``` +mkdir myproject +cd myproject +swarmlab-sec create +``` +.Relevant files: +``` +Project +├── Dockerfile # Image specification +├── project # Sample program source code +│ └── hello_world.c +├── ssh # keys for accessing +│ ├── id_rsa # (could generate your own) +│ └── id_rsa.pub +├── docker-compose.yml # Container orchestration +``` + +[[cheat-swarmlab-up]] +== Spin up the swarmlab cluster + +``` +cd myproject +swarmlab-sec up size=5 +``` + + +.We built a high-performing, scalable infrastructure +image:./swarmlab-network.png[alt="Swarmlab"] + + + +[[cheat-swarmlab-up1]] +== Login to the swarmlab cluster + +``` +cd myproject +swarmlab-sec login +``` + + +[[cheat-swarmlab-scale]] +== Scale cluster in real-time + +As the cluster running, without having to close the session, open a different terminal and go back to the project directory. + +``` +cd myproject +swarmlab-sec scale size=10 +``` + +[[cheat-swarmlab-down]] +== shutdown swarmlab-sec cluster + + +``` +cd myproject +swarmlab-sec down +``` + +:hardbreaks: + +{empty} + +{empty} + +{empty} + +:!hardbreaks: + +''' + +.Reminder +[NOTE] +==== +:hardbreaks: +Caminante, no hay camino, +se hace camino al andar. + +Wanderer, there is no path, +the path is made by walking. + +*Antonio Machado* Campos de Castilla +==== diff --git a/labs/os2/ssh-tunneling-1366x416-WPhEwBvP.png b/labs/os2/ssh-tunneling-1366x416-WPhEwBvP.png new file mode 100644 index 0000000..3b3e135 Binary files /dev/null and b/labs/os2/ssh-tunneling-1366x416-WPhEwBvP.png differ diff --git a/labs/os2/ssh-tunneling.adoc b/labs/os2/ssh-tunneling.adoc new file mode 100644 index 0000000..48a8160 --- /dev/null +++ b/labs/os2/ssh-tunneling.adoc @@ -0,0 +1,245 @@ += SSH Tunneling! +Apostolos rootApostolos@swarmlab.io +// Metadata: +:description: Intro and Install +:keywords: sec, tcpdump +:data-uri: +:toc: right +:toc-title: Table of Contents +:toclevels: 4 +:source-highlighter: highlight +:icons: font +:sectnums: + + + +{empty} + + + + + + +== SSH Tunneling + +***SSH Tunneling***, is the ability to use ssh to create a bi-directional encrypted network connection between machines over which data can be exchanged, typically TCP/IP. + + +image::ssh-tunneling-1366x416-WPhEwBvP.png[SSH tunneling] + +.NOTE +[NOTE] +==== +SSH is a standard for secure remote logins and file transfers over untrusted networks. It also provides a way to secure the data traffic of any given application using port forwarding, basically tunneling any TCP/IP port over SSH. This means that the application data traffic is directed to flow inside an encrypted SSH connection so that it cannot be eavesdropped or intercepted while it is in transit. SSH tunneling enables adding network security to legacy applications that do not natively support encryption. +==== + + +== Local Port Forwarding + + +.local port forwarding +[source,bash] +---- +ssh -nNT -L 8000:localhost:3306 user@192.168.89.5 +---- + +The above command sets up an ssh tunnel between your machine and the server, and forwards all traffic from localhost:3306 to localhost:8000 (on your machine). + +So now you could connect to MySQL running on your server via localhost on port 8000 on your machine. + + +== Remote Port Forwarding + +.remote port forwarding +[source,bash] +---- +ssh -nNT -R 4000:localhost:3000 user@192.168.89.5 +---- + +The above command sets up an ssh tunnel between your machine and the server, and forwards all traffic from localhost:3000 (on your machine) to localhost:4000 (in the context of the server). + +So now you can connect to the locally running service on port 3000 on the server on port 4000 + + +== SSH Command + + +Practically every Linux system includes the ssh command. This command is used to start the SSH client program that enables secure connection to the SSH server on a remote machine. The ssh command is used from logging into the remote machine, transferring files between the two machines, and for executing commands on the remote machine. + + +=== Connect to server + +.connect +[source,bash] +---- +ssh user@192.168.89.5 + +The authenticity of host '192.168.89.5' cannot be established. +DSA key fingerprint is 04:48:30:31:b0:f3:5a:9b:01:9d:b3:a7:38:e2:b1:0c. +Are you sure you want to continue connecting (yes/no)? +---- + +Type yes to continue. This will add the server to your list of known hosts (~/.ssh/known_hosts) as seen in the following message: + +[source,bash] +---- +Warning: Permanently added '192.168.89.5' (DSA) to the list of known hosts. +---- + +Each server has a host key, and the above question related to verifying and saving the host key, so that next time you connect to the server, it can verify that it actually is the same server. + + +=== Executing remote commands on the server + +[source,bash] +---- +ssh user@192.168.89.5 /bin/bash -c "ls -al" +---- + + +== sshd_config - SSH Server Configuration + +The OpenSSH server reads a configuration file when it is started. Usually this file is /etc/ssh/sshd_config, but the location can be changed using the -f command line option when starting sshd. + +=== Cryptographic policy + +- Symmetric algorithms for encrypting the bulk of transferred data are configured using the Ciphers option. A good value is aes128-ctr,aes192-ctr,aes256-ctr. + +- Host key algorithms are selected by the HostKeyAlgorithms option. A good value is ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-rsa,ssh-dss. + +- Key exchange algorithms are selected by the KexAlgorithms option. recommend ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha256. + +[NOTE] +==== +not recommend allowing diffie-hellman-group1-sha1, unless needed for compatibility. It uses a 768 bit prime number, which is too small by today's standards and may be breakable by intelligence agencies in real time. Using it could expose connections to man-in-the-middle attacks when faced with such adversaries. +==== + +=== Verbose logging + +It is strongly recommended that LogLevel be set to VERBOSE. This way, the key fingerprint for any SSH key used for login is logged. This information is important for SSH key management, especially in legacy environments. + +[source,bash] +---- +LogLevel VERBOSE +---- + +=== Root login + +root access should generally go through a privileged access management system + +To disable passwords for root, but still allow key-based access without forced command, use: + +[source,bash] +---- +PermitRootLogin prohibit-password +---- + +To disable passwords and only allow key-based access with a forced command, use: + +[source,bash] +---- +PermitRootLogin forced-commands-only +---- + + +=== Port forwarding + +Generally prevent port forwarding on servers, unless expressly needed for tunneling legacy applications. +There is substantial risk that users will use SSH tunneling to open backdoors into the organization through the firewall to get access to work machines from home. + + +=== Generate a key pair + + +[source,bash] +---- +ssh-keygen +---- + +Output: + +[source,bash] +---- +Generating public/private rsa key pair. +Enter file in which to save the key (/home/user/.ssh/id_rsa): +Created directory '/home/user/.ssh'. +Enter passphrase (empty for no passphrase): +Enter same passphrase again: +Your identification has been saved in /home/user/.ssh/id_rsa. +Your public key has been saved in /home/user/.ssh/id_rsa.pub. +The key fingerprint is: +8c:2a:ed:82:98:6d:12:0a:3a:ba:b2:1c:c0:25:be:5b +---- + + +=== Install your public key + +[source,bash] +---- +sh-copy-id -i ~/.ssh/id_rsa.pub UserName@RemoteServer +---- + +Output: + +[source,bash] +---- +UserName@RemoteServer's password: ******** +---- + +Now try logging into the machine, with "ssh 'username@remoteserver'", and check in: + +[source,bash] +---- +~/.ssh/authorized_keys +---- + + +== run graphics applications remotely + +X11 forwarding needs to be enabled on both the client side and the server side. + +- On the client side, the -X (capital X) option to ssh enables X11 forwarding + +- On the server side, X11Forwarding yes must specified in /etc/ssh/sshd_config. + +- The xauth program must be installed on the server side. + + +[source,bash] +---- +ssh -X user@192.168.89.5 gimp +---- + +== Copy Files and Directories Between Two Systems + +=== Copy a file from a local to a remote system + + +To copy a file from a local to a remote system run the following command: + +[source,bash] +---- +scp file.txt user@192.168.89.5:/remote/directory +---- + +=== Copy a Remote File to a Local System using the scp ommand + + +To copy a file named file.txt from a remote server with IP 192.168.89.5 run the following command: + +[source,bash] +---- +scp user@192.168.89.5:/remote/file.txt /local/directory +---- + + + +:hardbreaks: + +{empty} + +{empty} + +{empty} + +:!hardbreaks: + +''' + diff --git a/labs/os2/swarmlab-network.png b/labs/os2/swarmlab-network.png new file mode 100644 index 0000000..7691a11 Binary files /dev/null and b/labs/os2/swarmlab-network.png differ diff --git a/labs/os2/table_subtraverse.jpg b/labs/os2/table_subtraverse.jpg new file mode 100644 index 0000000..5b96370 Binary files /dev/null and b/labs/os2/table_subtraverse.jpg differ diff --git a/labs/os2/tables_traverse.jpg b/labs/os2/tables_traverse.jpg new file mode 100644 index 0000000..782a703 Binary files /dev/null and b/labs/os2/tables_traverse.jpg differ