3 utl = require "luci.util"
4 sys = require "luci.sys"
6 require("luci.model.uci")
7 require("luci.sys.iptparser")
10 local uci = luci.model.uci.cursor_state()
11 local ipt = luci.sys.iptparser.IptParser()
13 local fs = require "luci.fs"
14 local ip = require "luci.ip"
18 local has_ipv6 = fs.access("/proc/net/ipv6_route") and fs.access("/usr/sbin/ip6tables")
21 -- executes a cmd and gets its output
23 local ret = sys.exec(cmd)
25 if ret and ret ~= "" then
29 local ret = sys.exec(cmd .. " &> /dev/null")
34 -- just calls a command
43 call("lock /var/run/luci_splash.lock")
47 call("lock -u /var/run/luci_splash.lock")
51 local o3, o4 = ip:match("[0-9]+%.[0-9]+%.([0-9]+)%.([0-9]+)")
53 return string.format("%02X%s", tonumber(o3), "") .. string.format("%02X%s", tonumber(o4), "")
59 function update_stats(leased, whitelisted, whitelisttotal, blacklisted, blacklisttotal)
60 local leases = uci:get_all("luci_splash_leases", "stats")
61 uci:delete("luci_splash_leases", "stats")
62 uci:section("luci_splash_leases", "stats", "stats", {
63 leases = leased or (leases and leases.leases) or 0,
64 whitelisttotal = whitelisttotal or (leased and leases.whitelisttotal) or 0,
65 whitelistonline = whitelisted or (leases and leases.whitelistonline) or 0,
66 blacklisttotal = blacklisttotal or (leases and leases.blacklisttotal) or 0,
67 blacklistonline = blacklisted or (leases and leases.blacklistonline) or 0,
69 uci:save("luci_splash_leases")
73 function get_device_for_ip(ipaddr)
75 uci:foreach("network", "interface", function(s)
76 if s.ipaddr and s.netmask then
77 local network = ip.IPv4(s.ipaddr, s.netmask)
78 if network:contains(ip.IPv4(ipaddr)) then
79 -- this should be rewritten to luci functions if possible
80 dev = utl.trim(sys.exec(". /lib/functions/network.sh; network_get_device IFNAME '" .. s['.name'] .. "'; echo $IFNAME"))
87 function get_physdev(interface)
89 dev = utl.trim(sys.exec(". /lib/functions/network.sh; network_get_device IFNAME '" .. interface .. "'; echo $IFNAME"))
95 function get_filter_handle(parent, direction, device, mac)
96 local input = utl.split(sys.exec('/usr/sbin/tc filter show dev ' .. device .. ' parent ' .. parent) or {})
99 for k, v in pairs(input) do
100 handle = v:match('filter protocol ip pref %d+ u32 fh (%d*:%d*:%d*) order') or v:match('filter protocol all pref %d+ u32 fh (%d*:%d*:%d*) order')
102 local mac, mac1, mac2, mac3, mac4, mac5, mac6
103 if direction == 'src' then
104 mac1, mac2, mac3, mac4 = input[k+1]:match('match ([%a%d][%a%d])([%a%d][%a%d])([%a%d][%a%d])([%a%d][%a%d])/ffffffff')
105 mac5, mac6 = input[k+2]:match('match ([%a%d][%a%d])([%a%d][%a%d])0000/ffff0000')
107 mac1, mac2 = input[k+1]:match('match 0000([%a%d][%a%d])([%a%d][%a%d])/0000ffff')
108 mac3, mac4, mac5, mac6 = input[k+2]:match('match ([%a%d][%a%d])([%a%d][%a%d])([%a%d][%a%d])([%a%d][%a%d])/ffffffff')
110 if mac1 and mac2 and mac3 and mac4 and mac5 and mac6 then
111 mac = "%s:%s:%s:%s:%s:%s" % { mac1, mac2, mac3, mac4, mac5, mac6 }
122 function macvalid(mac)
123 if mac and mac:match(
124 "^[a-fA-F0-9][a-fA-F0-9]:[a-fA-F0-9][a-fA-F0-9]:" ..
125 "[a-fA-F0-9][a-fA-F0-9]:[a-fA-F0-9][a-fA-F0-9]:" ..
126 "[a-fA-F0-9][a-fA-F0-9]:[a-fA-F0-9][a-fA-F0-9]$"
134 function ipvalid(ipaddr)
136 return ip.IPv4(ipaddr) and true or false
143 local cmd = table.remove(argv, 1)
146 limit_up = (tonumber(uci:get("luci_splash", "general", "limit_up")) or 0) * 8
147 limit_down = (tonumber(uci:get("luci_splash", "general", "limit_down")) or 0) * 8
149 if ( cmd == "lease" or cmd == "add-rules" or cmd == "remove" or
150 cmd == "whitelist" or cmd == "blacklist" or cmd == "status" ) and #argv > 0
152 if not (macvalid(arg) or ipvalid(arg)) then
153 print("Invalid argument. The second argument must " ..
154 "be a valid IPv4 or Mac Address.")
160 local arp_cache = net.arptable()
161 local leased_macs = get_known_macs("lease")
162 local blacklist_macs = get_known_macs("blacklist")
163 local whitelist_macs = get_known_macs("whitelist")
165 for i, adr in ipairs(argv) do
167 if adr:find(":") then
170 for _, e in ipairs(arp_cache) do
171 if e["IP address"] == adr then
172 mac = e["HW address"]:lower()
178 if mac and cmd == "add-rules" then
179 if leased_macs[mac] then
180 add_lease(mac, arp_cache, true)
181 elseif blacklist_macs[mac] then
182 add_blacklist_rule(mac)
183 elseif whitelist_macs[mac] then
184 add_whitelist_rule(mac)
186 elseif mac and cmd == "status" then
187 print(leased_macs[mac] and "lease"
188 or whitelist_macs[mac] and "whitelist"
189 or blacklist_macs[mac] and "blacklist"
191 elseif mac and ( cmd == "whitelist" or cmd == "blacklist" or cmd == "lease" ) then
192 if cmd ~= "lease" and leased_macs[mac] then
193 print("Removing %s from leases" % mac)
195 leased_macs[mac] = nil
198 if cmd ~= "whitelist" and whitelist_macs[mac] then
199 if cmd == "lease" then
200 print('%s is whitelisted. Remove it before you can lease it.' % mac)
202 print("Removing %s from whitelist" % mac)
203 remove_whitelist(mac)
204 whitelist_macs[mac] = nil
208 if cmd == "whitelist" and leased_macs[mac] then
209 print("Removing %s from leases" % mac)
211 leased_macs[mac] = nil
214 if cmd ~= "blacklist" and blacklist_macs[mac] then
215 print("Removing %s from blacklist" % mac)
216 remove_blacklist(mac)
217 blacklist_macs[mac] = nil
220 if cmd == "lease" and not leased_macs[mac] then
221 if not whitelist_macs[mac] then
222 print("Adding %s to leases" % mac)
224 leased_macs[mac] = true
226 elseif cmd == "whitelist" and not whitelist_macs[mac] then
227 print("Adding %s to whitelist" % mac)
229 whitelist_macs[mac] = true
230 elseif cmd == "blacklist" and not blacklist_macs[mac] then
231 print("Adding %s to blacklist" % mac)
233 blacklist_macs[mac] = true
235 print("The mac %s is already %sed" %{ mac, cmd })
237 elseif mac and cmd == "remove" then
238 if leased_macs[mac] then
239 print("Removing %s from leases" % mac)
241 leased_macs[mac] = nil
242 elseif whitelist_macs[mac] then
243 print("Removing %s from whitelist" % mac)
244 remove_whitelist(mac)
245 whitelist_macs[mac] = nil
246 elseif blacklist_macs[mac] then
247 print("Removing %s from blacklist" % mac)
248 remove_blacklist(mac)
249 blacklist_macs[mac] = nil
251 print("The mac %s is not known" % mac)
255 print("Can not find mac for ip %s" % argv[i])
260 elseif cmd == "sync" then
263 elseif cmd == "list" then
268 print("\n luci-splash list\n List connected, black- and whitelisted clients")
269 print("\n luci-splash sync\n Synchronize firewall rules and clear expired leases")
270 print("\n luci-splash lease <MAC-or-IP>\n Create a lease for the given address")
271 print("\n luci-splash blacklist <MAC-or-IP>\n Add given address to blacklist")
272 print("\n luci-splash whitelist <MAC-or-IP>\n Add given address to whitelist")
273 print("\n luci-splash remove <MAC-or-IP>\n Remove given address from the lease-, black- or whitelist")
280 -- Get current arp cache
281 function get_arpcache()
283 for _, entry in ipairs(net.arptable()) do
284 arpcache[entry["HW address"]:lower()] = { entry["Device"]:lower(), entry["IP address"]:lower() }
289 -- Get a list of known mac addresses
290 function get_known_macs(list)
291 local leased_macs = { }
293 if not list or list == "lease" then
295 uci:foreach("luci_splash_leases", "lease",
296 function(s) leased_macs[s.mac:lower()] = true end)
299 if not list or list == "whitelist" then
300 uci:foreach("luci_splash", "whitelist",
301 function(s) leased_macs[s.mac:lower()] = true end)
304 if not list or list == "blacklist" then
305 uci:foreach("luci_splash", "blacklist",
306 function(s) leased_macs[s.mac:lower()] = true end)
313 -- Helper to delete iptables rules
314 function ipt_delete_all(args, comp, off)
316 for i, r in ipairs(ipt:find(args)) do
317 if comp == nil or comp(r) then
318 off[r.table] = off[r.table] or { }
319 off[r.table][r.chain] = off[r.table][r.chain] or 0
321 exec("iptables -t %q -D %q %d 2>/dev/null"
322 %{ r.table, r.chain, r.index - off[r.table][r.chain] })
324 off[r.table][r.chain] = off[r.table][r.chain] + 1
329 function ipt6_delete_all(args, comp, off)
331 for i, r in ipairs(ipt:find(args)) do
332 if comp == nil or comp(r) then
333 off[r.table] = off[r.table] or { }
334 off[r.table][r.chain] = off[r.table][r.chain] or 0
336 exec("ip6tables -t %q -D %q %d 2>/dev/null"
337 %{ r.table, r.chain, r.index - off[r.table][r.chain] })
339 off[r.table][r.chain] = off[r.table][r.chain] + 1
345 -- Convert mac to uci-compatible section name
346 function convert_mac_to_secname(mac)
347 return string.gsub(mac, ":", "")
350 -- Add a lease to state and invoke add_rule
351 function add_lease(mac, arp, no_uci)
354 -- Get current ip address
356 for _, entry in ipairs(arp or net.arptable()) do
357 if entry["HW address"]:lower() == mac then
358 ipaddr = entry["IP address"]
363 -- Add lease if there is an ip addr
365 local device = get_device_for_ip(ipaddr)
367 local leased = uci:get("luci_splash_leases", "stats", "leases")
368 if type(tonumber(leased)) == "number" then
369 update_stats(leased + 1, nil, nil, nil, nil)
372 uci:section("luci_splash_leases", "lease", convert_mac_to_secname(mac), {
377 limit_down = limit_down,
380 uci:save("luci_splash_leases")
382 add_lease_rule(mac, ipaddr, device)
384 print("Found no active IP for %s, lease not added" % mac)
389 -- Remove a lease from state and invoke remove_rule
390 function remove_lease(mac)
393 uci:delete_all("luci_splash_leases", "lease",
395 if s.mac:lower() == mac then
397 local leased = uci:get("luci_splash_leases", "stats", "leases")
398 if type(tonumber(leased)) == "number" and tonumber(leased) > 0 then
399 update_stats(leased - 1, nil, nil, nil, nil)
401 remove_lease_rule(mac, s.ipaddr, s.device, tonumber(s.limit_up), tonumber(s.limit_down))
407 uci:save("luci_splash_leases")
411 -- Add a whitelist entry
412 function add_whitelist(mac)
413 uci:section("luci_splash", "whitelist", convert_mac_to_secname(mac), { mac = mac })
414 uci:save("luci_splash")
415 uci:commit("luci_splash")
416 add_whitelist_rule(mac)
420 -- Add a blacklist entry
421 function add_blacklist(mac)
422 uci:section("luci_splash", "blacklist", convert_mac_to_secname(mac), { mac = mac })
423 uci:save("luci_splash")
424 uci:commit("luci_splash")
425 add_blacklist_rule(mac)
429 -- Remove a whitelist entry
430 function remove_whitelist(mac)
432 uci:delete_all("luci_splash", "whitelist",
433 function(s) return not s.mac or s.mac:lower() == mac end)
434 uci:save("luci_splash")
435 uci:commit("luci_splash")
436 remove_lease_rule(mac)
437 remove_whitelist_tc(mac)
440 function remove_whitelist_tc(mac)
441 uci:foreach("luci_splash", "iface", function(s)
442 local device = get_physdev(s['.name'])
443 if device and device ~= "" then
445 print("Removing whitelist filters for %s interface %s." % {mac, device})
447 local handle = get_filter_handle('ffff:', 'src', device, mac)
449 exec('tc filter del dev "%s" parent ffff: protocol ip prio 1 handle %s u32' % { device, handle })
451 print('Warning! Could not get a handle for %s parent :ffff on interface %s' % { mac, device })
453 local handle = get_filter_handle('1:', 'dest', device, mac)
455 exec('tc filter del dev "%s" parent 1:0 protocol ip prio 1 handle %s u32' % { device, handle })
457 print('Warning! Could not get a handle for %s parent 1:0 on interface %s' % { mac, device })
463 -- Remove a blacklist entry
464 function remove_blacklist(mac)
466 uci:delete_all("luci_splash", "blacklist",
467 function(s) return not s.mac or s.mac:lower() == mac end)
468 uci:save("luci_splash")
469 uci:commit("luci_splash")
470 remove_lease_rule(mac)
474 -- Add an iptables rule
475 function add_lease_rule(mac, ipaddr, device)
481 exec("iptables -t mangle -I luci_splash_mark_out -m mac --mac-source %q -j RETURN" % mac)
483 -- Mark incoming packets to a splashed host
484 -- for ipv4 - by iptables and destination
485 if id and device then
486 exec("iptables -t mangle -I luci_splash_mark_in -d %q -j MARK --set-mark 0x1%s -m comment --comment %s" % {ipaddr, id, mac:upper()})
489 --for ipv6: need to use the mac here
492 exec("ip6tables -t mangle -I luci_splash_mark_out -m mac --mac-source %q -j MARK --set-mark 79" % mac)
493 if id and device and tonumber(limit_down) then
494 exec("tc filter add dev %s parent 1:0 protocol ipv6 prio 1 u32 match ether dst %s classid 1:%s" % {device, mac:lower(), id})
499 if device and tonumber(limit_up) > 0 then
500 exec('tc filter add dev "%s" parent ffff: protocol all prio 2 u32 match ether src %s police rate %skbit mtu 6k burst 6k drop' % {device, mac, limit_up})
503 if id and device and tonumber(limit_down) > 0 then
504 exec("tc class add dev %s parent 1: classid 1:0x%s htb rate %skbit" % { device, id, limit_down })
505 exec("tc qdisc add dev %s parent 1:%s sfq perturb 10" % { device, id })
508 exec("iptables -t filter -I luci_splash_filter -m mac --mac-source %q -j RETURN" % mac)
509 exec("iptables -t nat -I luci_splash_leases -m mac --mac-source %q -j RETURN" % mac)
511 exec("ip6tables -t filter -I luci_splash_filter -m mac --mac-source %q -j RETURN" % mac)
516 -- Remove lease, black- or whitelist rules
517 function remove_lease_rule(mac, ipaddr, device, limit_up, limit_down)
525 ipt_delete_all({table="mangle", chain="luci_splash_mark_in", options={"/*", mac:upper()}})
526 ipt_delete_all({table="mangle", chain="luci_splash_mark_out", options={"MAC", mac:upper()}})
527 ipt_delete_all({table="filter", chain="luci_splash_filter", options={"MAC", mac:upper()}})
528 ipt_delete_all({table="nat", chain="luci_splash_leases", options={"MAC", mac:upper()}})
530 ipt6_delete_all({table="mangle", chain="luci_splash_mark_out", options={"MAC", mac:upper()}})
531 ipt6_delete_all({table="filter", chain="luci_splash_filter", options={"MAC", mac:upper()}})
534 if device and tonumber(limit_up) > 0 then
535 local handle = get_filter_handle('ffff:', 'src', device, mac)
537 exec('tc filter del dev "%s" parent ffff: protocol all prio 2 handle %s u32 police rate %skbit mtu 6k burst 6k drop' % {device, handle, limit_up})
539 print('Warning! Could not get a handle for %s parent :ffff on interface %s' % { mac, device })
542 -- remove clients class
543 if device and id then
544 exec('tc class del dev "%s" classid 1:%s' % {device, id})
545 exec('tc filter del dev "%s" parent 1:0 prio 1' % device) -- ipv6 rule
546 --exec('tc qdisc del dev "%s" parent 1:%s sfq perturb 10' % { device, id })
551 -- Add whitelist rules
552 function add_whitelist_rule(mac)
553 exec("iptables -t filter -I luci_splash_filter -m mac --mac-source %q -j RETURN" % mac)
554 exec("iptables -t nat -I luci_splash_leases -m mac --mac-source %q -j RETURN" % mac)
556 exec("ip6tables -t filter -I luci_splash_filter -m mac --mac-source %q -j RETURN" % mac)
558 uci:foreach("luci_splash", "iface", function(s)
559 local device = get_physdev(s['.name'])
560 if device and device ~= "" then
561 exec('tc filter add dev "%s" parent ffff: protocol ip prio 1 u32 match ether src %s police pass' % { device, mac })
562 exec('tc filter add dev "%s" parent 1:0 protocol ip prio 1 u32 match ether dst %s classid 1:1' % { device, mac })
568 -- Add blacklist rules
569 function add_blacklist_rule(mac)
570 exec("iptables -t filter -I luci_splash_filter -m mac --mac-source %q -j DROP" % mac)
572 exec("ip6tables -t filter -I luci_splash_filter -m mac --mac-source %q -j DROP" % mac)
577 -- Synchronise leases, remove abandoned rules
581 local time = os.time()
583 -- Current leases in state files
584 local leases = uci:get_all("luci_splash_leases")
586 -- Convert leasetime to seconds
587 local leasetime = tonumber(uci:get("luci_splash", "general", "leasetime")) * 3600
590 uci:load("luci_splash_leases")
591 uci:revert("luci_splash_leases")
594 local arpcache = get_arpcache()
596 local blackwhitelist = uci:get_all("luci_splash")
597 local whitelist_total = 0
598 local whitelist_online = 0
599 local blacklist_total = 0
600 local blacklist_online = 0
602 local leases_online = 0
605 for k, v in pairs(leases) do
606 if v[".type"] == "lease" then
607 if os.difftime(time, tonumber(v.start)) > leasetime then
609 remove_lease_rule(v.mac, v.ipaddr, v.device, tonumber(v.limit_up), tonumber(v.limit_down))
611 leasecount = leasecount + 1
613 -- only count leases_online for connected clients
614 if arpcache[v.mac] then
615 leases_online = leases_online + 1
619 uci:section("luci_splash_leases", "lease", convert_mac_to_secname(v.mac), {
624 limit_down = limit_down,
631 -- Whitelist, Blacklist
632 for _, s in utl.spairs(blackwhitelist,
633 function(a,b) return blackwhitelist[a][".type"] > blackwhitelist[b][".type"] end
635 if (s[".type"] == "whitelist") then
636 whitelist_total = whitelist_total + 1
638 local mac = s.mac:lower()
639 if arpcache[mac] then
640 whitelist_online = whitelist_online + 1
644 if (s[".type"] == "blacklist") then
645 blacklist_total = blacklist_total + 1
647 local mac = s.mac:lower()
648 if arpcache[mac] then
649 blacklist_online = blacklist_online + 1
656 -- include a new field "leases_online" in stats to differ between active clients and leases:
657 -- update_stats(leasecount, leases_online, whitelist_online, whitelist_total, blacklist_online, blacklist_total) later:
658 update_stats(leases_online, whitelist_online, whitelist_total, blacklist_online, blacklist_total)
660 uci:save("luci_splash_leases")
662 -- Get the mac addresses of current leases
663 local macs = get_known_macs()
667 ipt_delete_all({table="filter", chain="luci_splash_filter", options={"MAC"}},
668 function(r) return not macs[r.options[2]:lower()] end)
669 ipt_delete_all({table="nat", chain="luci_splash_leases", options={"MAC"}},
670 function(r) return not macs[r.options[2]:lower()] end)
671 ipt_delete_all({table="mangle", chain="luci_splash_mark_out", options={"MAC", "MARK", "set"}},
672 function(r) return not macs[r.options[2]:lower()] end)
673 ipt_delete_all({table="mangle", chain="luci_splash_mark_in", options={"/*", "MARK", "set"}},
674 function(r) return not macs[r.options[2]:lower()] end)
678 ipt6_delete_all({table="filter", chain="luci_splash_filter", options={"MAC"}},
679 function(r) return not macs[r.options[2]:lower()] end)
680 ipt6_delete_all({table="mangle", chain="luci_splash_mark_out", options={"MAC", "MARK", "set"}},
681 function(r) return not macs[r.options[2]:lower()] end)
689 local arpcache = get_arpcache()
690 -- Find traffic usage
691 local function traffic(lease)
693 local traffic_out = 0
695 local rin = ipt:find({table="mangle", chain="luci_splash_mark_in", destination=lease.ipaddr})
696 local rout = ipt:find({table="mangle", chain="luci_splash_mark_out", options={"MAC", lease.mac:upper()}})
698 if rin and #rin > 0 then traffic_in = math.floor( rin[1].bytes / 1024) end
699 if rout and #rout > 0 then traffic_out = math.floor(rout[1].bytes / 1024) end
701 return traffic_in, traffic_out
705 local leases = uci:get_all("luci_splash_leases")
706 local blackwhitelist = uci:get_all("luci_splash")
709 "%-17s %-15s %-9s %-4s %-7s %20s",
710 "MAC", "IP", "State", "Dur.", "Intf.", "Traffic down/up"
714 for _, s in pairs(leases) do
715 if s[".type"] == "lease" and s.mac then
716 local ti, to = traffic(s)
717 local mac = s.mac:lower()
718 local arp = arpcache[mac]
720 "%-17s %-15s %-9s %3dm %-7s %7dKB %7dKB",
721 mac, s.ipaddr, "leased",
722 math.floor(( os.time() - tonumber(s.start) ) / 60),
723 arp and arp[1] or "?", ti, to
728 -- Whitelist, Blacklist
729 for _, s in utl.spairs(blackwhitelist,
730 function(a,b) return blackwhitelist[a][".type"] > blackwhitelist[b][".type"] end
732 if (s[".type"] == "whitelist" or s[".type"] == "blacklist") and s.mac then
733 local mac = s.mac:lower()
734 local arp = arpcache[mac]
736 "%-17s %-15s %-9s %4s %-7s %9s %9s",
737 mac, arp and arp[2] or "?", s[".type"],
738 "- ", arp and arp[1] or "?", "-", "-"