Search in sources :

Example 21 with KuraException

use of org.eclipse.kura.KuraException in project kura by eclipse.

the class IptablesConfig method save.

/*
     * Saves (using iptables-save) the current iptables config into /etc/sysconfig/iptables
     */
public static void save() throws KuraException {
    SafeProcess proc = null;
    BufferedReader br = null;
    PrintWriter out = null;
    try {
        int status = -1;
        proc = ProcessUtil.exec("iptables-save");
        status = proc.waitFor();
        if (status != 0) {
            s_logger.error("save() :: failed - {}", LinuxProcessUtil.getInputStreamAsString(proc.getErrorStream()));
            throw new KuraException(KuraErrorCode.INTERNAL_ERROR, "Failed to execute the iptable-save command");
        }
        String line = null;
        br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        out = new PrintWriter(FIREWALL_CONFIG_FILE_NAME);
        while ((line = br.readLine()) != null) {
            out.println(line);
        }
        s_logger.debug("iptablesSave() :: completed!, status={}", status);
    } catch (Exception e) {
        throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e);
    } finally {
        if (out != null) {
            out.flush();
            out.close();
        }
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                s_logger.error("iptablesSave() :: failed to close BufferedReader - {}", e);
            }
        }
        if (proc != null) {
            ProcessUtil.destroy(proc);
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) KuraException(org.eclipse.kura.KuraException) SafeProcess(org.eclipse.kura.core.util.SafeProcess) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) IOException(java.io.IOException) KuraException(org.eclipse.kura.KuraException) PrintWriter(java.io.PrintWriter)

Example 22 with KuraException

use of org.eclipse.kura.KuraException in project kura by eclipse.

the class IptablesConfig method restore.

/*
     * Populates the m_localRules, m_portForwardRules, m_natRules, and m_autoNatRules by parsing
     * the iptables configuration file.
     */
public void restore() throws KuraException {
    BufferedReader br = null;
    try {
        List<NatPreroutingChainRule> natPreroutingChain = new ArrayList<NatPreroutingChainRule>();
        List<NatPostroutingChainRule> natPostroutingChain = new ArrayList<NatPostroutingChainRule>();
        List<FilterForwardChainRule> filterForwardChain = new ArrayList<FilterForwardChainRule>();
        br = new BufferedReader(new FileReader(FIREWALL_CONFIG_FILE_NAME));
        String line = null;
        boolean readingNatTable = false;
        boolean readingFilterTable = false;
        lineloop: while ((line = br.readLine()) != null) {
            line = line.trim();
            // skip any predefined lines or comment lines
            if (line.equals("")) {
                continue;
            }
            if (line.startsWith("#") || line.startsWith(":")) {
                continue;
            }
            if (line.equals("*nat")) {
                readingNatTable = true;
            } else if (line.equals("*filter")) {
                readingFilterTable = true;
            } else if (line.equals("COMMIT")) {
                if (readingNatTable) {
                    readingNatTable = false;
                }
                if (readingFilterTable) {
                    readingFilterTable = false;
                }
            } else if (readingNatTable && line.startsWith("-A PREROUTING")) {
                natPreroutingChain.add(new NatPreroutingChainRule(line));
            } else if (readingNatTable && line.startsWith("-A POSTROUTING")) {
                natPostroutingChain.add(new NatPostroutingChainRule(line));
            } else if (readingFilterTable && line.startsWith("-A FORWARD")) {
                filterForwardChain.add(new FilterForwardChainRule(line));
            } else if (readingFilterTable && line.startsWith("-A INPUT")) {
                if (ALLOW_ALL_TRAFFIC_TO_LOOPBACK.equals(line)) {
                    continue;
                }
                if (ALLOW_ONLY_INCOMING_TO_OUTGOING.equals(line)) {
                    continue;
                }
                for (String allowIcmp : ALLOW_ICMP) {
                    if (allowIcmp.equals(line)) {
                        this.m_allowIcmp = true;
                        continue lineloop;
                    }
                }
                for (String allowIcmp : DO_NOT_ALLOW_ICMP) {
                    if (allowIcmp.equals(line)) {
                        this.m_allowIcmp = false;
                        continue lineloop;
                    }
                }
                try {
                    LocalRule localRule = new LocalRule(line);
                    s_logger.debug("parseFirewallConfigurationFile() :: Adding local rule: {}", localRule);
                    this.m_localRules.add(localRule);
                } catch (KuraException e) {
                    s_logger.error("Failed to parse Local Rule: {} - {}", line, e);
                }
            }
        }
        // ! done parsing !
        for (NatPreroutingChainRule natPreroutingChainRule : natPreroutingChain) {
            // found port forwarding rule ...
            String inboundIfaceName = natPreroutingChainRule.getInputInterface();
            String outboundIfaceName = null;
            String protocol = natPreroutingChainRule.getProtocol();
            int inPort = natPreroutingChainRule.getExternalPort();
            int outPort = natPreroutingChainRule.getInternalPort();
            boolean masquerade = false;
            String sport = null;
            if (natPreroutingChainRule.getSrcPortFirst() > 0 && natPreroutingChainRule.getSrcPortFirst() <= natPreroutingChainRule.getSrcPortLast()) {
                StringBuilder sbSport = new StringBuilder().append(natPreroutingChainRule.getSrcPortFirst()).append(':').append(natPreroutingChainRule.getSrcPortLast());
                sport = sbSport.toString();
            }
            String permittedMac = natPreroutingChainRule.getPermittedMacAddress();
            String permittedNetwork = natPreroutingChainRule.getPermittedNetwork();
            int permittedNetworkMask = natPreroutingChainRule.getPermittedNetworkMask();
            String address = natPreroutingChainRule.getDstIpAddress();
            for (NatPostroutingChainRule natPostroutingChainRule : natPostroutingChain) {
                if (natPreroutingChainRule.getDstIpAddress().equals(natPostroutingChainRule.getDstNetwork())) {
                    outboundIfaceName = natPostroutingChainRule.getDstInterface();
                    if (natPostroutingChainRule.isMasquerade()) {
                        masquerade = true;
                    }
                }
            }
            if (permittedNetwork == null) {
                permittedNetwork = "0.0.0.0";
            }
            PortForwardRule portForwardRule = new PortForwardRule(inboundIfaceName, outboundIfaceName, address, protocol, inPort, outPort, masquerade, permittedNetwork, permittedNetworkMask, permittedMac, sport);
            s_logger.debug("Adding port forward rule: {}", portForwardRule);
            this.m_portForwardRules.add(portForwardRule);
        }
        for (NatPostroutingChainRule natPostroutingChainRule : natPostroutingChain) {
            String destinationInterface = natPostroutingChainRule.getDstInterface();
            boolean masquerade = natPostroutingChainRule.isMasquerade();
            String protocol = natPostroutingChainRule.getProtocol();
            if (protocol != null) {
                // found NAT rule, ... maybe
                boolean isNATrule = false;
                String source = natPostroutingChainRule.getSrcNetwork();
                String destination = natPostroutingChainRule.getDstNetwork();
                if (destination != null) {
                    StringBuilder sbDestination = new StringBuilder().append(destination).append('/').append(natPostroutingChainRule.getDstMask());
                    destination = sbDestination.toString();
                } else {
                    isNATrule = true;
                }
                if (source != null) {
                    StringBuilder sbSource = new StringBuilder().append(source).append('/').append(natPostroutingChainRule.getSrcMask());
                    source = sbSource.toString();
                }
                if (!isNATrule) {
                    boolean matchFound = false;
                    for (NatPreroutingChainRule natPreroutingChainRule : natPreroutingChain) {
                        if (natPreroutingChainRule.getDstIpAddress().equals(natPostroutingChainRule.getDstNetwork())) {
                            matchFound = true;
                            break;
                        }
                    }
                    if (!matchFound) {
                        isNATrule = true;
                    }
                }
                if (isNATrule) {
                    // match FORWARD rule to find out source interface ...
                    for (FilterForwardChainRule filterForwardChainRule : filterForwardChain) {
                        if (natPostroutingChainRule.isMatchingForwardChainRule(filterForwardChainRule)) {
                            String sourceInterface = filterForwardChainRule.getInputInterface();
                            s_logger.debug("parseFirewallConfigurationFile() :: Parsed NAT rule with" + "   sourceInterface: " + sourceInterface + "   destinationInterface: " + destinationInterface + "   masquerade: " + masquerade + "	protocol: " + protocol + "	source network/host: " + source + "	destination network/host " + destination);
                            NATRule natRule = new NATRule(sourceInterface, destinationInterface, protocol, source, destination, masquerade);
                            s_logger.debug("parseFirewallConfigurationFile() :: Adding NAT rule {}", natRule);
                            this.m_natRules.add(natRule);
                        }
                    }
                }
            } else {
                // match FORWARD rule to find out source interface ...
                for (FilterForwardChainRule filterForwardChainRule : filterForwardChain) {
                    if (natPostroutingChainRule.isMatchingForwardChainRule(filterForwardChainRule)) {
                        String sourceInterface = filterForwardChainRule.getInputInterface();
                        s_logger.debug("parseFirewallConfigurationFile() :: Parsed auto NAT rule with" + "   sourceInterface: " + sourceInterface + "   destinationInterface: " + destinationInterface + "   masquerade: " + masquerade);
                        NATRule natRule = new NATRule(sourceInterface, destinationInterface, masquerade);
                        s_logger.debug("parseFirewallConfigurationFile() :: Adding auto NAT rule {}", natRule);
                        this.m_autoNatRules.add(natRule);
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e);
    } finally {
        // close
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e);
            }
            br = null;
        }
    }
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) IOException(java.io.IOException) KuraException(org.eclipse.kura.KuraException) KuraException(org.eclipse.kura.KuraException) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader)

Example 23 with KuraException

use of org.eclipse.kura.KuraException in project kura by eclipse.

the class IptablesConfig method clearAllChains.

/*
     * Clears all chains
     */
public static void clearAllChains() throws KuraException {
    FileOutputStream fos = null;
    PrintWriter writer = null;
    try {
        fos = new FileOutputStream(FIREWALL_TMP_CONFIG_FILE_NAME);
        writer = new PrintWriter(fos);
        writer.println("*nat");
        writer.println("COMMIT");
        writer.println("*filter");
        writer.println("COMMIT");
    } catch (Exception e) {
        s_logger.error("clear() :: failed to clear all chains - {}", e);
        throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e);
    } finally {
        if (writer != null) {
            writer.flush();
            writer.close();
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                s_logger.error("clear() :: failed to close FileOutputStream - {}", e);
            }
        }
    }
    File configFile = new File(FIREWALL_TMP_CONFIG_FILE_NAME);
    if (configFile.exists()) {
        restore(FIREWALL_TMP_CONFIG_FILE_NAME);
    }
}
Also used : KuraException(org.eclipse.kura.KuraException) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) File(java.io.File) IOException(java.io.IOException) KuraException(org.eclipse.kura.KuraException) PrintWriter(java.io.PrintWriter)

Example 24 with KuraException

use of org.eclipse.kura.KuraException in project kura by eclipse.

the class LinuxFirewall method addLocalRules.

public void addLocalRules(List<LocalRule> newLocalRules) throws KuraException {
    try {
        boolean doUpdate = false;
        for (LocalRule newLocalRule : newLocalRules) {
            // make sure it is not already present
            boolean addRule = true;
            for (LocalRule localRule : this.m_localRules) {
                if (newLocalRule.equals(localRule)) {
                    addRule = false;
                    break;
                }
            }
            if (addRule) {
                s_logger.info("Adding local rule to firewall configuration: {}", newLocalRule.toString());
                this.m_localRules.add(newLocalRule);
                doUpdate = true;
            } else {
                s_logger.warn("Not adding local rule that is already present: {}", newLocalRule.toString());
            }
        }
        if (doUpdate) {
            update();
        }
    } catch (Exception e) {
        throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e);
    }
}
Also used : KuraException(org.eclipse.kura.KuraException) IOException(java.io.IOException) KuraException(org.eclipse.kura.KuraException)

Example 25 with KuraException

use of org.eclipse.kura.KuraException in project kura by eclipse.

the class LinuxFirewall method addLocalRule.

public void addLocalRule(int port, String protocol, String permittedNetwork, String permittedNetworkPrefix, String permittedInterfaceName, String unpermittedInterfaceName, String permittedMAC, String sourcePortRange) throws KuraException {
    try {
        LocalRule newLocalRule = null;
        if (permittedNetwork != null && permittedNetworkPrefix != null) {
            s_logger.debug("permittedNetwork: {}", permittedNetwork);
            s_logger.debug("permittedNetworkPrefix: {}", permittedNetworkPrefix);
            newLocalRule = new LocalRule(port, protocol, new NetworkPair<IP4Address>((IP4Address) IPAddress.parseHostAddress(permittedNetwork), Short.parseShort(permittedNetworkPrefix)), permittedInterfaceName, unpermittedInterfaceName, permittedMAC, sourcePortRange);
        } else {
            newLocalRule = new LocalRule(port, protocol, new NetworkPair<IP4Address>((IP4Address) IPAddress.parseHostAddress("0.0.0.0"), (short) 0), permittedInterfaceName, permittedInterfaceName, permittedMAC, sourcePortRange);
        }
        ArrayList<LocalRule> localRules = new ArrayList<LocalRule>();
        localRules.add(newLocalRule);
        addLocalRules(localRules);
    } catch (Exception e) {
        throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e);
    }
}
Also used : NetworkPair(org.eclipse.kura.net.NetworkPair) KuraException(org.eclipse.kura.KuraException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) KuraException(org.eclipse.kura.KuraException)

Aggregations

KuraException (org.eclipse.kura.KuraException)315 IOException (java.io.IOException)191 CommConnection (org.eclipse.kura.comm.CommConnection)54 SafeProcess (org.eclipse.kura.core.util.SafeProcess)49 ArrayList (java.util.ArrayList)46 File (java.io.File)44 BufferedReader (java.io.BufferedReader)42 InputStreamReader (java.io.InputStreamReader)30 UnknownHostException (java.net.UnknownHostException)30 FileNotFoundException (java.io.FileNotFoundException)25 NetConfig (org.eclipse.kura.net.NetConfig)23 NetInterfaceAddressConfig (org.eclipse.kura.net.NetInterfaceAddressConfig)20 SupportedUsbModemInfo (org.eclipse.kura.linux.net.modem.SupportedUsbModemInfo)19 UsbModemDevice (org.eclipse.kura.usb.UsbModemDevice)19 Properties (java.util.Properties)18 NetConfigIP4 (org.eclipse.kura.net.NetConfigIP4)17 GwtKuraException (org.eclipse.kura.web.shared.GwtKuraException)17 StringTokenizer (java.util.StringTokenizer)16 FileOutputStream (java.io.FileOutputStream)15 IP4Address (org.eclipse.kura.net.IP4Address)15