# The KMyFirewall Handbook

## Introduction

### About

&kmyfirewall; attempts to make it easier to setup firewalls for your computer network without limitating your configuration options. If you don't have the time and/or the interest to spend hours in front of your operating system manual just to setup a simple firewall that keeps the "bad" people out, &kmyfirewall; will help you to configure your computer within a few clicks.

It will be the right tool if you like to have a so called "Personal Firewall" running on your worstation but it will also help you to setup complex rulesets for your network routers. Each of it's two different Graphical ruleset editors try to provide the right tool for each group of users.

Entire rule sets can be saved, so you only have to configure your rule set one time and then you can use it on several computers giving each of them a similar configuration (p.e. school networks, office, university etc.).

### Note

Programs can't do any magic so you still will have to know what your firewall should do to setup your rule set.

KMyFirewall tries to provide well designed default settings so that there should not be much to do anymore to provide a secure setup. But there is no way &kmyfirewall; can prevent you from openeing security holes in your setup! Please allways test rulesets you created before you use them for a production system.

### Features

#### Main Features

1. Easy setup of a small but efficient "Personal Firewall".

2. Nice overview of the configuration.

3. Import/Export of rule sets to ease the setup of large networks.

4. Easy-to-use GUI interface for most common setups.

5. An advanced interface for complex rule sets as needed by routers

6. Preconfigured rulesets for most common setups.

7. Integrated Install scripts for automatic execution during booting.

8. Plugin framowork that allows easy and fast development of new features.

9. Plugin framowork that allows easy and fast development of new features.

#### Generic Interface

1. Zone/Host based rule creation.

2. No portnumbers need to be known.

3. NAT and simple network router support.

4. Support for special hosts e.g. trusted banned etc.

5. Rule inheritance can be enabled/disabled for nested notwork zones.

6. Operating system and backend independet. (Currently only Linux is supported but OpenBSD should follow soon)

#### IPTables Interface

1. XML based iptables command generation engine that allows to be extended by plugins providing a description about the new option.

2. State full packet filtering.

3. IP, MAC, Protocol, ROS and Interface based filtering

4. Limiting packet matches (avoids DoS attacks)

5. Logging of dropped packets

6. View running IP Tables configuration

7. NAT (SNAT, DNAT) configuration (Masquerading)

8. User defined Chains

9. MANGLE configuration

10. Undo/Redo

## Just a bit of Theory

### What can a firewall do?

As firewalling is a really complex topic I'd like to give you a briefly introduction about what firewalls are and how IPTables firewalls work.

When you think of a firewall most people would say firewalls just restrict the network traffic, but a modern firewall has more to do that just restricting the traffic which is of course it's main task.

You can filter by having a look at the packet headers that store information about where the packet comes from, which protocol is used etc.

The filtering possibilities provided by the IPTables are very powerful so it's even possible to only let packets in that are know to belong to a connection you have made. This technology is called Connection Tracking or Statefull Packet Filtering.

The second important feature a firewall has to provide is the possibility to log the network traffic. This is a much more important part of it as you may think, because logfiles are give you a good view about the activities in your network like who did what and when.

Logs are also really important when the firewall got cracked and you want to know how. In that you would have a much harder life if you didn't activeted the logging functions so that you can see what has happend and how the configuration be improved.

Most people think about firewalls just being used to block traffic from the Internet to your host, but you may also configure your firewall to restrict the Internet access. Par example you may block some well known porn sites on your Children's PC or you just want to allow e-mail and Web browsing in your office but you don't want your employees to be able to download files via FTP.

All the things described are really easy to implement with the IPTables once you have understood how they work. Please read carefully through the next few chapters to learn how to efficiently use this Program to settup an firewall for your PC/Network.

### A Note about Security in general

A firewall can actually not guarantee 100% of security just because there may be bugs in the underlying software or the configuration or even a hardware problem can be the open door for the bad guys.

It is also a common mistake to believe that a firewall is enough to provide security. If you want to have a really high level of security you will need a whole Security Concept which defined the basic rules for the network environment. This includes the used software, installing security updates to the running software, a good documentation about how the security level is enforced in your network etc.

Here is an example what I mean by that.

Imagine you are running a public web server. To make it possible for the World to reach you you have to open the TCP port 80 for incoming connections. By opening this port your computer is reachable through the Internet. You as the admin implemented a really bomb save firewall configuration and you feel save because your firewall protects you. But certainly a securityhole in the webserver application is found and made public in the Internet. If you didn't installed the security update because you forgot or it isn't available yet a hacker may be able to use this securityhole (in the webserver not the firewall) to get access to your network. In this case the firewall can't do anything against it because you allowed people to connect to your server.

I hope that this example makes it a little bit clearer what is meant when talking about a security concept. To prevent these cases there are some basic rules to follow.

1. Install updates to the software you are running.

2. Try to have a look at some security based websites to stay informed about whats going on out there.

3. Think about creating a security concept for your network.

4. Never ever trust your configuration blindly!

5. Watch your logfiles for strange activities.

6. Keep an eye on the legal users in your network, a lot of networks have been hacked because of users that didn't follow the security concept and installed disallowed software, connect to the internet via modem or WLAN so that your firewall is simply can't see those connections, or the installed software was a virus or hidden backdoor to the system.

7. Read books and all kind of documentation about this topic you can find.

8. Always remember there is no save host. Except it's offline...

### IPTables basics

An IPTables based firewall is made of three different basic objects.

1. Rules

2. Chains

3. Tables

Please read through the next three chapters to get a short description about those objects. Note that this is just a briefly introduction to the IPTables. For more detailed documentation have a look at the IPTables Manpage or www.iptables.org.

#### Rules

The lowest level objects are the rules that are performing the packetfiltering or manipulation. A rule is made of several parts.

1. The Table to which this rule should be added. If no table is defined the rule will be added to the filter table.

2. The Chain to which this rule should be added p.e INPUT or FORWARD

3. The filtering or manipulation instructions.

4. The target of the rule. This target decides what should be done with the packet if it matches the rule. The most Important targets are DROP, which drops the packet without any further action, ACCEPT, which will let the packet pass the firewall and the data is sent to the receiver and LOG that simply writes some information (src. IP, ports etc.) about the packet that matches to the Syslog.

#### Chains

Those rules are organized in chains which are simple ordered list of rules. There are some built-in chains that are always available for the user like the INPUT or the OUTPUT chain in the filter table. Built-in chains do also have a so called Default Target which decides what to do with a packet that didn't match any of the rules defined in that chain.

For large configurations it's often required to settup rules for packets that are common in some pieces of their attributes. When you setup a firewall that also provides routing functionality you may want to have different kind of rules for packets coming from the internal network than for packets coming from the evil Internet.

To make it more easy to manage such configurations you have the possibility to create your own chains. Those user defined chains don't have a Default Target.

User defined chains must be fed by rules that have the name of the user defined chain as their target. When a packet passes the whole user defined chain without matching any of its rules the packet will be sent back to the chain that fed this chain just right after the rule that sent the packet to the user defined chain.

The packets will be compared to the rules in the order as they are defined in the chain. This means that the packet will no longer be tested if a rule before matched. So please pay attention to the order of the rules as a wrong ruleorder may end up in an very hard to find bug in the configuration.

#### Tables

Because of the lots of possibilities that IPTables rules give you to filter and/or mainpulate the packets that are checked the chains themselves are organized in so called tables. Each table has it's own set of built-in chains that are available for direct use.

There are three tables available filter, nat and mangle.

1. The filter table that is used for packet filtering as we all think about when we are talking about firewalls

2. The nat table is made for all kind of Network Address Translation which is a technology used to change the source and destination attributes of the packet. The well known IP Masquerading is the most common way to use this feature.

3. The mangle table is designed to hold chains and rules that change other attributes of the packets or sending them into the userspace to be processed by any other application. If you are not thinking about really complicated things you shouldn't need to use this table.

## IPTables usage

Here is a short reference for the iptables commandline program. I'll try to explain most of the important options the iptables command allows. For more details please have a look at man iptables

Some (quiet a lot) of the descriptions are copy and paste from the iptables manpage, because the manpage is really good and I just added my own explanations where I thought this should be clearer. I'd like to say thanks to the iptables developers for this fabulous manpage.

### Selecting the Table

Each rule you like to add to your firewall needs to be inserted or appended into an existing chain in one of the three tables filter, nat or mangle. Which of the tables are available depends on the configuration of your kernel.

Lets have a look at the following iptables commandline:

`iptables -t filter -A INPUT --source 192.168.0.1 -j DROP`

As you can see the command has several parts to set the behavior of the rule. Lets start with `iptables -t <tablename> ...` The option -t tells iptables to add the rule to a chain in the table <tablename>. If no -t option is defined the rule will be inserted into the filter table which is the default.

### Append, Insert and Delete

`iptables -t filter -A INPUT ...`

The option -A INPUT tells the program to add the rule at the end of the INPUT chain. There are also the options -I chain [rulenum] for inserting a rule, -R chain [rulenum] for replacing a rule and -D chain rulenum for deleting a rule from a chain.

&kapp; only uses the -A option in the generated script.

### Defining Options

For filtering and manipulation of packets you need to define which properties a packet must have to be filtered/manipulated. This is done by passing one or more option names p.e. --source and the value that should match 192.168.0.1 in that case.

IPTables define quiet a lot of different options you can check for. Some of them are directly implemented in the iptables program like the --source option but there are also some more complex options that need to load the needed modules into the kernel to be available. Those options are defined like `... --match state --state RELATED,ESTABLISHED ...` The --match state options lets the program look for an available option called state which is in this case the connection tracking module.

The availability of those extended options depends on the configuration of your kernel and the available modules that can be loaded or are directly compiled into the kernel.

For a more detailed description of the options that can be used from within this program have a look at the chapter Packet Filtering and Altering.

### Targets

`... -j LOG --log-prefix "KMF: "`

The Target of a rule defines what to do if a packet matches the rule. The target is defined by the `-j <target> [target-options]` option at the end of the filtering/manipulation options at the end of the rule. There are two different types of targets terminating and non-terminating. If a target is terminating the packet will not be passed to rules after the matching one.

A good example for a terminating target is `... -j DROP`. The DROP target that tell the kernel to drop (delete) the matching packet which means that it will not reach it's destination. And it's quiet logical that you don't want to check the packet against the other (later in the chain) defined rule as you already know what to do with it.

For a non-terminating target have a look at the code snip above. The here used LOG target lets the kernel log the packets matching this rule to the syslog. It wouldn't be very useful if the packets would stop here therefore the packets continue the way through the kernel.

## Filtering and Manipulation of Packets

Packet filtering and altering is the main task iptables have to perform and they are really good in it. But a highly configurable and flexible packetfilter is nothing trivial so please read this carefully before you start you experiments.

This chapter will show you how the different filter modules of the iptables are used in detail. It may look shocking but it's not that hard to understand and once you've got it, it' really easy to settup highly complex rulesets for big network routers or simple personal firewalls. Some of these advanced filtering options (connection tracking, mac) need extra modules to be either loaded as module or directly compiled into the kernel. Have a look at the Kernel Compiling HOWTO for details about building a custom kernel.

### Source and destination IP

`iptables -A INPUT --source 12.168.120.15 -j ACCEPT`

Source specification. Address can be either a network name, a hostname (please note that specifying any name to be resolved with a remote query such as DNS is a really bad idea), a network IP address (with /mask), or a plain IP address. The mask can be either a network mask or a plain number, specifying the number of 1's at the left side of the network mask. Thus, a mask of 24 is equivalent to `255.255.255.`. A `!` argument before the address specification inverts the sense of the address. The flag `--src` is an alias for this option.

`iptables -A INPUT --destination ! 32.112.0.31/24 -j ACCEPT`

Destination specification is similar in usage to the source option.

### Checking for the protocol

`iptables -A INPUT --protocol tcp -j ACCEPT`

`iptables -A INPUT --protocol ! udp -j LOG`

The protocol of the rule or of the packet to check. The specified protocol can be one of `tcp`, `udp`, `icmp`, or all, or it can be a numeric value, representing one of these protocols or a different one. A protocol name from /etc/protocols is also allowed. A `!` argument before the protocol inverts the test. The number zero is equivalent to all. Protocol all will match with all protocols and is taken as default when this option is omitted.

#### TCP specific options

TCP specific are all filter options that have a deeper look into the TCP header of the packet. This includes checking for source-, destination port, real tcp connection tracking, tcp flags etc.

##### TCP Source and destination ports

`iptables -A INPUT --protocol tcp --source-port 22:12 -j LOG`

`iptables -A POSTROUTING --protocol tcp --destination-port ! 21232 -j DROP`

Source/Destination port or port range specification. This can either be a service name or a port number. An inclusive range can also be specified, using the format `port:port`. If the first port is omitted, "0" is assumed; if the last is omitted, `65535` is assumed. If the second port greater then the first they will be swapped. The flag `--sport` is a convenient alias for this option.

##### TCP Flags

`iptables -A INPUT --protocol tcp --tcp-flags ! SYN,ACK,FIN SYN,ACK -j LOG`

Match when the TCP flags are as specified. The first argument is the flags which we should examine, written as a comma-separated list, and the second argument is a comma-separated list of flags which must be set. Flags are: `SYN ACK FIN RST URG PSH ALL NONE` . Hence the command:

`iptables -A FORWARD -p tcp --tcp-option SYN,ACK,FIN,RST SYN -j ACCEPT` will only match packets with the SYN flag set, and the ACK, FIN and RST flags unset.

##### TCP Options

`iptables -A INPUT --protocol tcp --tcp-option 0 -j LOG`

Match if the numeric TCP option is set in the tcp header. A `!` may be used to invert the match option.

#### UDP specific options

UDP is the second big protocol in the internet. The main difference to TCP is that it does not provide a stateful connection to the peer host. In other words UDP packets are anonymous and easy to fake. On the other hand is it extremely fast (no overhead of establishing connections) and therefore it's used by lots of protocols. Most important UDP protocols are `DNS` (hostname <---> ip address ) and `NFS` (Standard *NIX filesharing protocol).

##### UDP Source and destination ports

`iptables -A INPUT --protocol udp --source-port 22:12 -j LOG`

`iptables -A POSTROUTING --protocol udp --destination-port ! 21232 -j DROP`

Source/Destination port or port range specification. This can either be a service name or a port number. An inclusive range can also be specified, using the format `port:port`. If the first port is omitted, "0" is assumed; if the last is omitted, `65535` is assumed. If the second port greater then the first they will be swapped. The flag `--sport` is a convenient alias for this option.

#### ICMP

The Internet Control Message Protocol (ICMP) is the control and message protocol for the underlying IP protocol. Often needed messages and commands are defined in this protocol like host-unreachable when an ip address was not found,echo-request the normal ping and source-quench tells the receiver to slow down the traffic -> !!!Denial of Service!!!,

##### ICMP type

`iptables -A INPUT --protocol icmp --icmp-type echo-request -j LOG`

This allows specification of the ICMP type, which can be a numeric ICMP type, or one of the ICMP type names shown by the command: `iptables -p icmp -h` .

#### Multiport Match Extension

The Multiport match extension allows you to define a comma-separated list of up to 15 ports in an TCP or UDP specific rule. This is mostly useful to save some typing by specifying mor that one port per rule.

##### Source Ports

`iptables -A INPUT --protocol tcp --match multiport --source-ports 22,21,20,80 -j LOG`

This rule will match all tcp packets that have a source port contained in the given port list.

##### Destination Ports

`iptables -A INPUT --protocol udp --match multiport --destination-ports 20,80,10 -j LOG`

This rule will match all udp packets that have a destination port contained in the given port list.

#####

`iptables -A INPUT --protocol tcp --match multiport --ports 20,50,1660 -j LOG`

Match if the both the source and destination ports are equal to each other and to one of the given ports.

### Incoming and Outgoing Interface

`iptables -A INPUT --in-interface eth0 -j LOG`

Name of an interface via which a packet is going to be received (only for packets entering the `INPUT`, `FORWARD` and `PREROUTING` chains). When the "!" argument is used before the interface name, the sense is inverted. If the interface name ends in a "+", then any interface which begins with this name will match. If this option is omitted, any interface name will match.

`iptables -A OUTPUT --out-interface ! ippp1 -j DROP`

Name of an interface via which a packet is going to be sent (for packets entering the `FORWARD`, `OUTPUT` and `POSTROUTING` chains). When the "!" argument is used before the interface name, the sense is inverted. If the interface name ends in a "+", then any interface which begins with this name will match. If this option is omitted, any interface name will match.

### Source MAC

`iptables -A INPUT --match mac --mac-source 12:E4:86:FA:5C:54 -j ACCEPT`

Match source MAC address. It must be of the form XX:XX:XX:XX:XX:XX. Note that this only makes sense for packets coming from an Ethernet device and entering the `PREROUTING`, `FORWARD` or `INPUT` chains.

This options is very useful for protection against man-in-the-middle attacks, because it is possible to combine it with the `--source` option and so protection against arp-spoofing may be provided.

### Limit matches

This module matches at a limited rate using a token bucket filter. A rule using this extension will match until this limit is reached (unless the `!' flag is used). It can be used in combination with the `LOG` target to give limited logging, for example.

`iptables -A INPUT --match limit --limit 10/second --limit-burst 5 -j ACCEPT`

`iptables -A INPUT --match limit --limit 2/hour --limit-burst 10 -j LOG`

### Statefull Packet Filtering

`iptables -A INPUT --match state --state RELATED,ESTABLISHED -j ACCEPT`

Where state is a comma separated list of the connection states to match. Possible states are `INVALID` meaning that the packet is associated with no known connection, `ESTABLISHED` meaning that the packet is associated with a connection which has seen packets in both directions, `NEW` meaning that the packet has started a new connection, or otherwise associated with a connection which has not seen packets in both directions, and `RELATED` meaning that the packet is starting a new connection, but is associated with an existing connection, such as an FTP data transfer, or an ICMP error.

### TOS - Type of Service

This module matches the 8 bits of Type of Service field in the IP header (ie. including the precedence bits).

`iptables -A INPUT --match tos --tos Minimize-Delay -j ACCEPT`

The argument is either a standard name, or a numeric value to match. Run `iptables -m tos -h` to see the list of allowed names).

## Using &kapp;

### Overview - GUI Interfaces

&kapp; ships with two different GUI interfaces.

#### Generic Interface

The Generic Interface is an abstract view on what kind of netwok traffic may or may not pass yout computer. The rules are generated by a compiler plugin so that it is possible to generate scripts for other plattforms p.e. OpenBSD/pf then GNU/Linux/iptables (well currently just the iptables compiler is implemented. Let me know if you are interrested in implementing that :)).

#### IPTables Interface

The IPTables interfaces tries to represent a 1-1 look at the iptables rule set your configuration will create. Therefore it is ment to be used by experienced system administrators in order to setup very fine graduaded rulesets. Becaus of the tight relation this GUI has to the netfilter/iptables framework it can only be used on GNU/Linux workstations as the document can not be compiled into any other rule description language.

### Getting Started

The easiest way to start is to create a new Document Ctrl n and use the Wizard to setup the basic rules for your new firewall. For a simple Personal Firewall the default configuration should be quiet usable as it is designed to let everything out of your Box (Table: Filter, Chain: OUTPUT, Target: ACCEPT) and only lets packets is that are related with connections you established.

This configuration is a good starting point for your firewall if you don't need any kind of routing or packet mangling because it deactivates the routing functionality in your kernel and only the filter table is used.

The Wizard can not be used to change an existing configuration it's simply made for setting up a basic ruleset that can be changed by using the Rule Editor and the Chain Editor.

For more complex rulesets as needed by routes or firewalls that protect a whole network, you need to use the Advanced Interface to setup the firewall. The document generated by the Advanced Interface is an empty ruleset! In other words there are no rules defined to filter any kind of packets.

## Developer's Guide to &kapp;

As you can see this thing gets quiet big so every kind of help (coding,docs,translations) is very welcome. Please don't hesitate to contact me chubinger@gmail.com if you have some ideas, patches, wishes or whatever.

### &kapp; Plugin framework

&kapp; extensively uses KDE's KParts/XMLGUI technology to provide an easy to and robust plugin infrastructure. Allmost every function is performed by dynamicaly loaded plugins in order to make it easy manage the code and write extentions. Especially the IPTables interface uses plugins to embeed the different iptables rule options edit dialogs.

### Rule- option/targetoptin Plugins (IPTables interface only)

As the iptables command utility is really fast developing and every few week new options are added, all ruleoption handling is outsourced to small easy to write plugins.

The underlieing document format is designed flexible enougth to allow the implementaiton of any command option iptables knows (or will know, if i didn't forget anything).

The rule creation engine can be extend by registering new option/targetoption types defined in small XML files that are parsed at startup. And the editor GUI can embeed the edit widgets needed to configure the ruleoption.

#### Parts of an Ruleoption/targetoption Plugin

- A XML file named p.e. kmfruleoption_mac_option.xml

- A desktop file p.e. kmfruleoptionedit_mac.desktop that registeres the plugin within the KDE services framework.

- An KParts Plugin component/class that derives form either KMFRuleOptionEditInterface or KMFRuleTargetOptionEditInterface named p.e. KMFRuleOptionEditMAC

- A Class deriving from TQWidget that may be loaded into the editor view when editing that option.

  Most likely you'll use QTDesigner to design the GUI. If you do this you need to inherit from the generated class.

#### XML File describing the rule option

The xml file gets loaded during application startup and registers the specified rule option in the engine. Have a look at some of the other XML files installed in $KDE-PREFIX/share/apps/kmyfirewall/ruleoptions for some more example of how to define the needed options.

    <!DOCTYPE kmyfirewall-kmfruleoptiondefinition>
    <ruleoptiondefinitionset>
    <ruleoptiondefinition name="mac_opt"  guiName="MAC Address">
      <option guiName="" command="--match mac" />
      <option guiName="MAC:" command="--mac-source" />
    </ruleoptiondefinition>
    </ruleoptiondefinitionset>

#### The .desktop file

This file is installed into the services directory and makes the plugin available for the KDE plugin framework

The important thing here is that you set Type=Service and the right SeviceType. The application only searches for plugins with SeviceType=KMyFirewall/RuleOptionEdit or SeviceType=KMyFirewall/RuleTargetOptionEdit.

The line X-TDE-Library=libkmfruleoptionedit_mac lets the KDE plugin framework know which library defines the functionality.

    [Desktop Entry]
    Encoding=UTF-8
    Type=Service
    Name=KMyFirewall MAC option edit
    Name[da]=KMyFirewall MAC redigeringstilvalg
    Comment=Plugin for edition MAC address based iptables rule options
    Comment[da]=Plugin ril at redigere MAC adressebaserede regeltilvalg for iptables
    X-TDE-Library=libkmfruleoptionedit_mac
    ServiceTypes=KMyFirewall/RuleOptionEdit

#### The Makefile.am

Make shure that you add the option -module $(KDE_PLUGIN) to the <library_name>_LDFLAGS. Otherwise the plugin can not be loaded at runtime.

    INCLUDES = -I../kmfwidgets -I../../ipteditor -I$(srcdir)/../interfaces $(all_includes)
    METASOURCES = AUTO
    kde_module_LTLIBRARIES =  libkmfruleoptionedit_mac.la

    libkmfruleoptionedit_mac_la_LDFLAGS = -module $(KDE_PLUGIN) $(all_libraries)
    libkmfruleoptionedit_mac_la_LIBADD = ../../core/libkmfcore.la ../../interfaces/libkmfinterfaces.la $(LIB_TDEPARTS)
    noinst_HEADERS =  kmfruleoptioneditmac.h kmfruleeditmac.h

    libkmfruleoptionedit_mac_la_SOURCES = kmfruleoptioneditmac.cpp kmfruleeditmac.cpp  kmyfirewallruleeditormac.ui

    partdesktopdir = $(kde_servicesdir)
    partdesktop_DATA = kmfruleoptionedit_mac.desktop

    install-data-local:
    	$(mkinstalldirs) $(DESTDIR)$(kde_datadir)/kmyfirewall/ruleoptions/
    	$(INSTALL_DATA)  $(srcdir)/kmfruleoption_mac_option.xml $(DESTDIR)$(kde_datadir)/kmyfirewall/ruleoptions/kmfruleoption_mac_option.xml

    uninstall-local:
    	-rm -f $(DESTDIR)$(kde_datadir)/kmyfirewall/ruleoptions/kmfruleoption_mac_option.xml

#### KParts Plugin component/class

This class defines the plugin that will be loaded at application startup.

kmfruleoptioneditmac.h

    /***************************************************************************
        Copyright (C) 2004 Christian Hubinger
     ***************************************************************************/

    /***************************************************************************
     *                                                                         *
     *   This program is free software; you can redistribute it and/or modify  *
     *   it under the terms of the GNU General Public License as published by  *
     *   the Free Software Foundation; either version 2 of the License, or     *
     *   (at your option) any later version.                                   *
     *                                                                         *
     ***************************************************************************/
    // Author: Christian Hubinger <chubinger@gmail.com>, (C) 2004
    #ifndef KMFRULEOPTIONEDITMAC_H
    #define KMFRULEOPTIONEDITMAC_H

    #include "../../interfaces/kmfruleoptioneditinterface.h"

    // KDE includes
    #include <tdeparts/part.h>
    #include <tdeparts/plugin.h>
    #include <tdeparts/factory.h>
    #include <kxmlgui.h>

    #include <qstring.h>
    #include <qptrlist.h>

    class IPTRule;
    class KMFRuleEditMac;
    /**
    @author Christian Hubinger
    */
    class KMFRuleOptionEditMAC : public KMFRuleOptionEditInterface {
    	TQ_OBJECT
    public:
    	KMFRuleOptionEditMAC(TQObject *parent = 0, const char *name = 0);

    	~KMFRuleOptionEditMAC();
    	void loadRule( IPTRule* rule );
    	TQWidget* editWidget();
    	const TQString& optionEditName() const;
    	const TQString& description() const;

    private slots:
    	void slotAddRuleOption(TQString*, QPtrList< TQString >* );
    	void slotAddTargetOption(TQString*, QPtrList< TQString >* );
    	void slotShowOverview();

    private:
    	KMFRuleEditMac *m_edit;
    	IPTRule *m_rule;

    };

    class TDEInstance;

    class KMFRuleOptionEditMACFactory : public KLibFactory {
    	TQ_OBJECT
    public:
    	KMFRuleOptionEditMACFactory( TQObject *parent = 0, const char *name = 0 );
    	virtual ~KMFRuleOptionEditMACFactory() {
    	};
    	virtual TQObject* createObject( TQObject* parent = 0, const char* pname = 0,
    	                               const char* name = "TQObject",
    	                               const QStringList &args = QStringList() );

    };

kmfruleoptioneditmac.cpp

    /***************************************************************************
     *                                                                         *
     *   This program is free software; you can redistribute it and/or modify  *
     *   it under the terms of the GNU General Public License as published by  *
     *   the Free Software Foundation; either version 2 of the License, or     *
     *   (at your option) any later version.                                   *
     *                                                                         *
     ***************************************************************************/
    #include "kmfruleoptioneditmac.h"

    // TQt includes
    #include <qstring.h>

    // KDE includes
    #include <kdebug.h>
    #include <tdelocale.h>

    // Project includes
    #include "../../core/iptrule.h"
    #include "../../interfaces/kmfruleeditinterface.h"
    #include "kmfruleeditmac.h"

    // Constructor get out plugin into a valid state
    KMFRuleOptionEditMAC::KMFRuleOptionEditMAC(TQObject *parent, const char *name)
    		: KMFRuleOptionEditInterface(parent, name) {

    	// Initialise the editor class
    	m_edit = new KMFRuleEditMac( 0 , "Edit", 0 );
    	// hide it for now
    	m_edit->hide();

    	// Connect the Signals for the editor class to our slots passing them to the app
    	connect( m_edit,TQ_SIGNAL(sigAddRuleOpt(TQString*, QPtrList< TQString >* ) ),
    		this,TQ_SLOT( slotAddRuleOption(TQString*, QPtrList< TQString >* ) ) );
    	//
    	//connect( m_edit,TQ_SIGNAL(sigAddTargetOpt(TQString*, QPtrList< TQString >* ) ),
    	//	this,TQ_SLOT( slotAddTargetOption(TQString*, QPtrList< TQString >* ) ) );
    	connect( m_edit,TQ_SIGNAL(sigHideMe() ),
    		this,TQ_SLOT( slotShowOverview() ) );
    }

    KMFRuleOptionEditMAC::~KMFRuleOptionEditMAC() {}

    // Slot to pass the Signals to the app
    void KMFRuleOptionEditMAC::slotAddRuleOption(TQString* name, QPtrList< TQString >* values ) {
    	if ( KMFRuleEditInterface* ruleedit = dynamic_cast<KMFRuleEditInterface*> ( parent() ) ) {
    		ruleedit->addRuleOption( name, values );
    	} else {
    		kdDebug() << "KMFRuleOptionEditMAC::slotAddRuleOption(): parent() not of type KMFRuleEditInterface" << endl;
    	}
    }
    void KMFRuleOptionEditMAC::slotAddTargetOption(TQString* name, QPtrList< TQString >* values ) {
    	if ( KMFRuleEditInterface* ruleedit = dynamic_cast<KMFRuleEditInterface*> ( parent() ) ) {
    		ruleedit->addRuleTargetOption( name, values );
    	} else {
    		kdDebug() << "KMFRuleOptionEditMAC::slotAddTargetOption(): parent() not of type KMFRuleEditInterface" << endl;
    	}
    }

    // Make the editor hide the plugin widget
    void KMFRuleOptionEditMAC::slotShowOverview() {
    	if ( KMFRuleEditInterface* ruleedit = dynamic_cast<KMFRuleEditInterface*> ( parent() ) ) {
    		ruleedit->showOverview();
    	} else {
    		kdDebug() << "KMFRuleOptionEditMAC::slotShowOverview(): parent() not of type KMFRuleEditInterface" << endl;
    	}
    }

    // Get info for GUI about the plugin
    const TQString& KMFRuleOptionEditMAC::optionEditName() const {
    	return *( new TQString( i18n("MAC Option") ) );
    }
    const TQString& KMFRuleOptionEditMAC::description() const {
    	return *( new TQString( i18n("This plugin manages the MAC address based options of iptables.") ) );
    }

    // We must implement this as it is called from the underliening rule editor
    void KMFRuleOptionEditMAC::loadRule( IPTRule* rule ) {
    	if ( !rule ) {
    		kdDebug() << "KMFRuleOptionEditMAC::loadRule( IPTRule* rule ) - rule == 0" <<endl;
    		return;
    	}
    	m_edit->loadRule( rule );
    	m_rule = rule;
    }

    // return a pointer to our editor widget
    TQWidget* KMFRuleOptionEditMAC::editWidget() {
    	if ( ! m_edit ) {
    		kdDebug() << "KMFRuleOptionEditMAC::editWidget() - m_edit == 0" << endl;
    		return 0;
    	}
    	return m_edit;
    }

    // It's usually safe to leave the factory code alone.. with the
    // notable exception of the TDEAboutData data
    #include <tdeaboutdata.h>
    #include <tdelocale.h>

    // TDEInstance* KMFRuleOptionEditMACFactory::s_instance = 0L;
    // TDEAboutData* KMFRuleOptionEditMACFactory::s_about = 0L;

    KMFRuleOptionEditMACFactory::KMFRuleOptionEditMACFactory( TQObject* parent, const char* name )
    		: KLibFactory( parent, name ) {
    }

    TQObject* KMFRuleOptionEditMACFactory::createObject( TQObject* parent, const char* name,
            const char*, const QStringList & ) {
    	TQObject * obj = new KMFRuleOptionEditMAC( parent, name );
    	emit objectCreated( obj );
    	return obj;
    }

    extern "C" {
    	TDE_EXPORT void* init_libkmfruleoptionedit_mac() {
    		return new KMFRuleOptionEditMACFactory;
    	}
    }
    #include "kmfruleoptioneditmac.moc"

#### The editor widget class

This class defines a widget that can configure the specific rule option.

kmfruleeditmac.h

    /***************************************************************************
     *                                                                         *
     *   This program is free software; you can redistribute it and/or modify  *
     *   it under the terms of the GNU General Public License as published by  *
     *   the Free Software Foundation; either version 2 of the License, or     *
     *   (at your option) any later version.                                   *
     *                                                                         *
     ***************************************************************************/
    /*
    Author: Christian Hubinger <chubinger@gmail.com>, (C) 2001-2004
    */

    #ifndef KMFRULEEDITMAC_H
    #define KMFRULEEDITMAC_H

    #include "kmyfirewallruleeditormac.h"

    #include <qvariant.h>
    #include <qdialog.h>
    #include <qptrlist.h>

    class IPTRule;
    class KMFErrorHandler;
    class KMFCheckInput;
    class KMFError;

    class KMFRuleEditMac : public KMyFirewallRuleEditorMac {
    	TQ_OBJECT

    public:
    	KMFRuleEditMac( TQWidget* parent = 0, const char* name = 0, WFlags fl = 0 );
    	~KMFRuleEditMac();

    	void loadRule( IPTRule* );

    public slots:
    	void accept();
    	void slotHelp();
    	void reject();

    protected:
    	bool event( QEvent* );

    private:
    	KMFCheckInput *m_check_input;
    	KMFErrorHandler *m_err_handler;
    	KMFError *m_err;
    	IPTRule* m_rule;

    signals:
    	void sigAddRuleOpt( TQString*, QPtrList<TQString>* );
    	void sigHideMe();
    };

    #endif // KMFRULEEDITMAC_H

kmfruleeditmac.cpp

    /***************************************************************************
     *                                                                         *
     *   This program is free software; you can redistribute it and/or modify  *
     *   it under the terms of the GNU General Public License as published by  *
     *   the Free Software Foundation; either version 2 of the License, or     *
     *   (at your option) any later version.                                   *
     *                                                                         *
     ***************************************************************************/
    /*
    Author: Christian Hubinger <chubinger@gmail.com>, (C) 2001-2004
    */

    #include "kmfruleeditmac.h"

    #include <qcheckbox.h>
    #include <qframe.h>
    #include <qlabel.h>
    #include <qlineedit.h>
    #include <qpushbutton.h>
    #include <qlayout.h>
    #include <qvariant.h>
    #include <qtooltip.h>
    #include <qwhatsthis.h>

    #include <kdebug.h>
    #include <tdemessagebox.h>
    #include <tdelocale.h>
    #include <tdeapplication.h>

    // project includes
    #include "../../core/iptrule.h"
    #include "../../core/iptchain.h"
    #include "../../core/iptable.h"
    #include "../../core/kmfdoc.h"
    #include "../../core/kmfiptdoc.h"
    #include "../../core/kmfcheckinput.h"
    #include "../../core/kmferror.h"
    #include "../../core/kmferrorhandler.h"

    /*
     *  Constructs a KMFRuleEditMac which is a child of 'parent', with the
     *  name 'name' and widget flags set to 'f'
     *
     *  The dialog will by default be modeless, unless you set 'modal' to
     *  true to construct a modal dialog.
     */
    KMFRuleEditMac::KMFRuleEditMac( TQWidget* parent, const char* name, WFlags fl )
    		: KMyFirewallRuleEditorMac( parent, name, fl ) {
    	m_err_handler = new KMFErrorHandler( "KMFRuleEditMac" );
    	m_check_input = new KMFCheckInput();
    	m_err = new KMFError();

    }

    /*
     *  Destroys the object and frees any allocated resources
     */
    KMFRuleEditMac::~KMFRuleEditMac() {
    	// no need to delete child widgets, TQt does it all for us
    }

    /*
     *  Main event handler. Reimplemented to handle application
     *  font changes
     */
    bool KMFRuleEditMac::event( QEvent* ev ) {
    	bool ret = TQWidget::event( ev );
    	if ( ev->type() == QEvent::ApplicationFontChange ) {}
    	return ret;
    }

    void KMFRuleEditMac::loadRule( IPTRule * rule ) {
    	kdDebug() << "void KMFRuleEditMac::loadRule( IPTRule * rule )" << endl,
    	c_src_mac->setChecked( false );
    	c_inv_src_mac->setChecked( false );
    	t_src_mac1 ->clear();
    	t_src_mac2 ->clear();
    	t_src_mac3 ->clear();
    	t_src_mac4 ->clear();
    	t_src_mac5 ->clear();
    	t_src_mac6 ->clear();
    	m_rule = rule;
    	TQString line = "";

    	IPTRuleOption* opt = 0;
    	opt = m_rule->getOptionForName("mac_opt");
    	if ( opt ) {
    		QStringList args = opt->getValues();
    		TQString src, dest;
    		line = *args.at(1);
    		if ( line.isEmpty() || line == "UNDEFINED"  )
    			return;
    		if ( line.startsWith( "! " ) ) {
    			line = line.right( line.length() - 2 );
    			c_inv_src_mac->setChecked( true );
    		}
    		int num = 1;
    		TQString part = "";
    		c_src_mac->setChecked( true );
    		while ( !line.isEmpty() ) {
    			int pos = -1;
    			pos = line.find( ":" );
    			if ( pos < 0 ) {
    				part = line;
    				line = "";
    			} else {
    				part = line.left( pos );
    				line = line.right( line.length() - ( pos + 1 ) );
    			}
    			switch ( num ) {
    				case 1:
    					t_src_mac1 -> setText( part );
    					break;
    				case 2:
    					t_src_mac2 -> setText( part );
    					break;
    				case 3:
    					t_src_mac3 -> setText( part );
    					break;
    				case 4:
    					t_src_mac4 -> setText( part );
    					break;
    				case 5:
    					t_src_mac5 -> setText( part );
    					break;
    				case 6:
    					t_src_mac6 -> setText( part );
    					break;
    			}
    			num++;
    		}
    	}
    }

    void KMFRuleEditMac::accept() {
    	kdDebug() << "KMFRuleEditMac::accept()" << endl;
    	m_rule->chain()->table()->kmfDoc()->startTransaction();
    	m_rule->saveState();
    	TQString tok1 = t_src_mac1->text().upper();
    	TQString tok2 = t_src_mac2->text().upper();
    	TQString tok3 = t_src_mac3->text().upper();
    	TQString tok4 = t_src_mac4->text().upper();
    	TQString tok5 = t_src_mac5->text().upper();
    	TQString tok6 = t_src_mac6->text().upper();

    	if ( c_src_mac->isChecked() && ( tok1.isEmpty() || tok2.isEmpty() || tok3.isEmpty() || tok4.isEmpty() || tok5.isEmpty() || tok6.isEmpty() ) ) {
    		const TQString & msg = i18n( "One ore more of the fields are empty. Please fill out all fields to define a valid MAC address." );
    		KMessageBox::error( this, msg );
    		m_rule->chain()->table()->kmfDoc()->endTransaction();
    		return ;
    	}

    	TQString mac = "";

    	if ( c_src_mac->isChecked() ) {
    		mac = tok1 + ":" + tok2 + ":" + tok3 + ":" + tok4 + ":" + tok5 + ":" + tok6;
    		m_check_input->checkInput( mac, "MAC", m_err );
    		if ( ! m_err_handler->showError( m_err ) ) {
    			m_rule->chain()->table()->kmfDoc()->endTransaction();
    			return ;
    		}
    	}

    	QPtrList<TQString>* values = new QPtrList<TQString>;
    	TQString* op = new TQString( "mac_opt" );
    	if ( c_src_mac->isChecked() && !mac.isEmpty() ) {
    		kdDebug() << "Add new mac option" << endl;
    		TQString* src_mac = new TQString( mac );
    		if ( c_inv_src_mac->isChecked() ) {
    			src_mac->prepend( "! " );
    		}
    		values->append( new TQString( "bool:on" ) );
    		values->append( src_mac );
    	}
    	emit sigAddRuleOpt( op, values );
    	m_rule->chain()->table()->kmfDoc()->endTransaction();
    	emit sigHideMe();
    }

    void KMFRuleEditMac::slotHelp() {
    	kdDebug() << "void KMFRuleEditMac::slotHelp()" << endl;
    	kapp->invokeHelp( "src_mac" );
    }
    void KMFRuleEditMac::reject() {
    	kdDebug() << "void KMFRuleEditMac::reject()" << endl;
    	emit sigHideMe();
    }
    #include "kmfruleeditmac.moc"

## Credits and License

Program and Documentation copyright 2002 Christian Hubinger chubinger@gmail.com

&underFDL; &underGPL;

## Installation

### How to obtain KMyFirewall

&kmyfirewall; has it's on homepage at http://kmyfirewall.sourceforge.net. You may find a downloadlink and some more information about it there.

### Requirements

To run KMyFirewall you need to have at least KDE3 and iptables installed. So you can only use KMyFirewall on Linux systems.

- iptables >= 1.2.x

- linux >= 2.4.x (versions > 2.4.17 are recommended)

- KDE >= 3.x

&kmyfirewall; itself can be found on The &kmyfirewall; home page.

There you'll also find a list of important changes and know bugs.

### Compilation and Installation

In order to compile and install &kmyfirewall; on your system, type the following in the base directory of the extracted tarball:

    %./configure --prefix=/kde-install-path/ --with-tqt-dir=/tqt-install-path/
    %make
    %(as root) make install

Since &kmyfirewall; uses autoconf and automake you should not have trouble compiling it. Should you run into problems please report them to the author.

&documentation.index;