firewall: fix generation of outgoing rules on webserver
[hcoop/domtool2.git] / src / plugins / firewall.sml
index e6f92b2..1131f20 100644 (file)
@@ -1,6 +1,6 @@
 (* HCoop Domtool (http://hcoop.sourceforge.net/)
  * Copyright (c) 2006-2007, Adam Chlipala
- * Copyright (c) 2011,2012,2013,2014 Clinton Ebadi
+ * Copyright (c) 2011,2012,2013,2014,2018 Clinton Ebadi
  *
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU General Public License
@@ -24,7 +24,7 @@
 structure Firewall :> FIREWALL = struct
 
 datatype user = User of string
-                   
+
 datatype fwnode = FirewallNode of string
 
 datatype fwrule = Client of int list * string list
@@ -34,6 +34,9 @@ datatype fwrule = Client of int list * string list
 
 type firewall_rules = (user * fwnode * fwrule) list
 
+datatype fwip = FwIPv4
+             | FwIPv6
+
 structure StringMap = DataStructures.StringMap
 
 fun parseRules () =
@@ -85,32 +88,59 @@ fun query (node, uname) =
            (List.filter (fn (User u, FirewallNode n, _) => u = uname andalso n = node) rules)
     end
 
+fun dnsExists dnsRR dnsRecord =
+    let
+       val dnsRR_string = case dnsRR of
+                              FwIPv6 => "AAAA"
+                            | FwIPv4 => "A"
+    in
+       (* timeout chosen arbitrarilty, shorter is better if it's reliable *)
+       (* dig outputs true even if the lookup fails, but no output in short mode should work *)
+       case Slave.runOutput (Config.Firewall.dig, ["+short", "+timeout=3", "-t", dnsRR_string, dnsRecord]) of
+           (_, SOME s) => (case Domain.validDomain (substring (s, 0, size s - 2)) of (* delete trailing . from cname *)
+                               true => dnsExists dnsRR s (* dig will return CNAME, must recurse *)
+                             | false => true) (* maybe also double check ip? use size s - 1 if so! *)
+
+         | (_, NONE) => false
+    end
+
+fun fermVariable x = String.isPrefix "$" x
+fun filterHosts (hosts, ipv6) =
+    List.filter (fn host => fermVariable host
+                           orelse (case ipv6 of FwIPv6 => Domain.validIpv6 host
+                                              | FwIPv4 =>  Domain.validIp host)
+                           orelse dnsExists ipv6 host)
+               hosts
+
+
 fun formatPorts ports = "(" ^ String.concatWith " " (map Int.toString ports) ^ ")"
-fun formatHosts hosts = "(" ^ String.concatWith " " hosts ^ ")"
+fun formatHosts (hosts, ipv6) = "(" ^ String.concatWith " " (filterHosts (hosts, ipv6)) ^ ")"
 
-fun formatOutputRule (Client (ports, hosts)) = "dport " ^ formatPorts ports ^ (case hosts of 
+fun formatOutputRule (Client (ports, hosts), ipv6) = "dport " ^ formatPorts ports ^ (case hosts of
                                                                                 [] => ""
-                                                                              | _ => " daddr " ^ formatHosts hosts) ^ " ACCEPT;"
+                                                                              | _ => " daddr " ^ formatHosts (hosts, ipv6)) ^ " ACCEPT;"
   | formatOutputRule _ = ""
 
-fun formatInputRule (Server (ports, hosts)) = "dport " ^ formatPorts ports ^ (case hosts of 
+fun formatInputRule (Server (ports, hosts), ipv6) = "dport " ^ formatPorts ports ^ (case hosts of
                                                                                  [] => ""
-                                                                               | _ => " saddr " ^ formatHosts hosts) ^ " ACCEPT;"
+                                                                               | _ => " saddr " ^ formatHosts (hosts, ipv6)) ^ " ACCEPT;"
   | formatInputRule _ = ""
 
 type ferm_lines = { input_rules : (string list) DataStructures.StringMap.map,
-                   output_rules : (string list) DataStructures.StringMap.map } 
+                   output_rules : (string list) DataStructures.StringMap.map }
 
-fun generateNodeFermRules rules  = 
+fun generateNodeFermRules rules  =
     let
        fun filter_node_rules rules =
-           List.filter (fn (uname, FirewallNode node, rule) => node = Slave.hostname () orelse case rule of 
+           List.filter (fn (uname, FirewallNode node, rule) => node = Slave.hostname () orelse case rule of
                                                                                                    ProxiedServer _ => List.exists (fn (h,_) => h = Slave.hostname ()) Config.Apache.webNodes_all
                                                                                     | _ => false)
                        rules
 
        val inputLines = ref StringMap.empty
        val outputLines = ref StringMap.empty
+       val inputLines_v6 = ref StringMap.empty
+       val outputLines_v6 = ref StringMap.empty
 
        fun confLine r (User uname, line) =
            let
@@ -122,26 +152,36 @@ fun generateNodeFermRules rules  =
                r := StringMap.insert (!r, uname, line :: lines)
            end
 
-       fun confLine_in (uname, rule) = confLine inputLines (uname, formatInputRule rule)
-       fun confLine_out (uname, rule) = confLine outputLines (uname, formatOutputRule rule)
+       fun confLine_in (uname, rule) = confLine inputLines (uname, formatInputRule (rule, FwIPv4))
+       fun confLine_out (uname, rule) = confLine outputLines (uname, formatOutputRule (rule, FwIPv4))
+       fun confLine_in_v6 (uname, rule) = confLine inputLines_v6 (uname, formatInputRule (rule, FwIPv6))
+       fun confLine_out_v6 (uname, rule) = confLine outputLines_v6 (uname, formatOutputRule (rule, FwIPv6))
 
        fun insertConfLine (uname, ruleNode, rule) =
-           case rule of 
-               Client (ports, hosts) => confLine_out (uname, rule)
-             | Server (ports, hosts) => confLine_in (uname, rule)
-             | LocalServer ports => (insertConfLine (uname, ruleNode, Client (ports, ["127.0.0.1/8"]));
-                                     insertConfLine (uname, ruleNode, Server (ports, ["127.0.0.1/8"])))
-             | ProxiedServer ports => if (fn FirewallNode r => r) ruleNode = Slave.hostname () then
-                                          (insertConfLine (uname, ruleNode, Server (ports, ["$WEBNODES"]));
-                                           insertConfLine (uname, ruleNode, Client (ports, [(fn FirewallNode r => r) ruleNode])))
-                                      else (* we are a web server *)
-                                          (insertConfLine (uname, ruleNode, Client (ports, [(fn FirewallNode r => r) ruleNode]));
-                                           insertConfLine (User "www-data", ruleNode, Client (ports, [(fn FirewallNode r => r) ruleNode])))
+           let
+               val fwnode_domain = fn FirewallNode node => node ^ "." ^ Config.defaultDomain
+           in
+               case rule of
+                   Client (ports, hosts) => (confLine_out (uname, rule); confLine_out_v6 (uname, rule))
+                 | Server (ports, hosts) => (confLine_in (uname, rule); confLine_in_v6 (uname, rule))
+                 | LocalServer ports => (insertConfLine (uname, ruleNode, Client (ports, ["127.0.0.1/8"]));
+                                         insertConfLine (uname, ruleNode, Server (ports, ["127.0.0.1/8"]));
+                                         insertConfLine (uname, ruleNode, Client (ports, [":::1"]));
+                                         insertConfLine (uname, ruleNode, Server (ports, [":::1"])))
+                 | ProxiedServer ports => if (fn FirewallNode r => r) ruleNode = Slave.hostname () then
+                                              (insertConfLine (uname, ruleNode, Server (ports, ["$WEBNODES"]));
+                                               insertConfLine (uname, ruleNode, Client (ports, [fwnode_domain ruleNode])))
+                                          else (* we are a web server *)
+                                              (insertConfLine (uname, ruleNode, Client (ports, [fwnode_domain ruleNode]));
+                                               insertConfLine (User "www-data", ruleNode, Client (ports, [fwnode_domain ruleNode])))
+           end
 
        val _ = map insertConfLine (filter_node_rules rules)
     in
        { input_rules = !inputLines,
-         output_rules = !outputLines }
+         output_rules = !outputLines,
+          input6_rules = !inputLines_v6,
+         output6_rules = !outputLines_v6 }
 
 
     end
@@ -153,55 +193,60 @@ fun generateFirewallConfig rules =
     let
        val users_tcp_out_conf = TextIO.openOut (Config.Firewall.firewallDir ^ "/users_tcp_out.conf")
        val users_tcp_in_conf = TextIO.openOut (Config.Firewall.firewallDir ^ "/users_tcp_in.conf")
-       val user_chains_conf = TextIO.openOut (Config.Firewall.firewallDir ^ "/user_chains.conf")
+
+       val users_tcp6_out_conf = TextIO.openOut (Config.Firewall.firewallDir ^ "/users_tcp6_out.conf")
+       val users_tcp6_in_conf = TextIO.openOut (Config.Firewall.firewallDir ^ "/users_tcp6_in.conf")
 
        val nodeFermRules = generateNodeFermRules rules
-               
-       fun write_tcp_in_conf_preamble outf = 
-           TextIO.output (outf, String.concat ["@def $WEBNODES = (",
-                                               (String.concatWith " " (List.map (fn (_, ip) => ip) 
+
+       fun write_tcp_in_conf_preamble outf =
+           (* no ipv6 support yet, but use @ipfilter() in ferm to prepare *)
+           TextIO.output (outf, String.concat ["@def $WEBNODES = @ipfilter((",
+                                               (String.concatWith " " (List.map (fn (_, ip) => ip)
                                                                                 (List.filter (fn (node, _) => List.exists (fn (n) => n = node) (List.map (fn (node, _) => node) (Config.Apache.webNodes_all @ Config.Apache.webNodes_admin)))
                                                                                              Config.nodeIps))),
-                                               ");\n\n"])
+                                               "));\n\n"])
 
-       fun writeUserInRules (uname, lines) = 
+       fun writeUserInRules tcp_inf (uname, lines) =
            (* We can't match the user when listening; SELinux or
               similar would let us manage this with better
               granularity.*)
            let
                val _ = SysWord.toInt (Posix.ProcEnv.uidToWord (Posix.SysDB.Passwd.uid (Posix.SysDB.getpwnam uname)))
            in
-               TextIO.output (users_tcp_in_conf, "proto tcp {\n");
-               TextIO.output (users_tcp_in_conf, concat lines);
-               TextIO.output (users_tcp_in_conf, "\n}\n\n")
-           end handle OS.SysErr _ => print "Invalid user in firewall config, skipping.\n" (* no sense in opening ports for bad users *)                
+               TextIO.output (tcp_inf, "proto tcp mod comment comment \"user:" ^ uname ^ "\" {\n");
+               TextIO.output (tcp_inf, concat lines);
+               TextIO.output (tcp_inf, "\n}\n\n")
+           end handle OS.SysErr _ => print "Invalid user in firewall config, skipping.\n" (* no sense in opening ports for bad users *)
 
-       fun writeUserOutRules (uname, lines) =
+       fun writeUserOutRules tcp_outf (uname, lines) =
            let
                val uid = SysWord.toInt (Posix.ProcEnv.uidToWord (Posix.SysDB.Passwd.uid (Posix.SysDB.getpwnam uname)))
            in
-               TextIO.output (users_tcp_out_conf, "mod owner uid-owner " ^ (Int.toString uid)
-                                                  ^ " { jump user_" ^ uname ^ "_tcp_out"
-                                                  ^ "; DROP; }\n");
-
-               TextIO.output (user_chains_conf, "chain user_" ^ uname ^ "_tcp_out"
-                                                ^ " proto tcp {\n");
-               TextIO.output (user_chains_conf, concat lines);
-               TextIO.output (user_chains_conf, "\n}\n\n")
+               TextIO.output (tcp_outf, "mod owner uid-owner " ^ (Int.toString uid) ^ " mod comment comment \"user:" ^ uname ^ "\" proto tcp {\n");
+               TextIO.output (tcp_outf, concat lines);
+               TextIO.output (tcp_outf, "\nDROP;\n}\n\n")
            end handle OS.SysErr _ => print "Invalid user in firewall config, skipping.\n"
-           
+
     in
        write_tcp_in_conf_preamble (users_tcp_in_conf);
-       StringMap.appi (writeUserOutRules) (#output_rules nodeFermRules);
-       StringMap.appi (writeUserInRules) (#input_rules nodeFermRules);
+       StringMap.appi (writeUserOutRules users_tcp_out_conf) (#output_rules nodeFermRules);
+       StringMap.appi (writeUserInRules users_tcp_in_conf) (#input_rules nodeFermRules);
+
+       write_tcp_in_conf_preamble (users_tcp6_in_conf);
+       StringMap.appi (writeUserOutRules users_tcp6_out_conf) (#output6_rules nodeFermRules);
+       StringMap.appi (writeUserInRules users_tcp6_in_conf) (#input6_rules nodeFermRules);
 
-       TextIO.closeOut user_chains_conf;
        TextIO.closeOut users_tcp_out_conf;
        TextIO.closeOut users_tcp_in_conf;
 
+       TextIO.closeOut users_tcp6_out_conf;
+       TextIO.closeOut users_tcp6_in_conf;
+
        true
     end
 
-fun publishConfig _ = 
+
+fun publishConfig _ =
     Slave.shell [Config.Firewall.reload]
 end