3 utl = require "luci.util"
4 sys = require "luci.sys"
5 ipc = require "luci.ip"
9 local uci = require "luci.model.uci".cursor_state()
10 local fs = require "nixio.fs"
11 local ip = require "luci.ip"
15 local has_ipv6 = fs.access("/proc/net/ipv6_route") and fs.access("/usr/sbin/ip6tables")
18 -- executes a cmd and gets its output
20 local ret = sys.exec(cmd)
22 if ret and ret ~= "" then
26 local ret = sys.exec(cmd .. " &> /dev/null")
31 -- just calls a command
40 call("lock /var/run/luci_splash.lock")
44 call("lock -u /var/run/luci_splash.lock")
48 local o3, o4 = ip:match("[0-9]+%.[0-9]+%.([0-9]+)%.([0-9]+)")
50 return string.format("%02X%s", tonumber(o3), "") .. string.format("%02X%s", tonumber(o4), "")
56 function update_stats(leased, whitelisted, whitelisttotal, blacklisted, blacklisttotal)
57 local leases = uci:get_all("luci_splash_leases", "stats")
58 uci:delete("luci_splash_leases", "stats")
59 uci:section("luci_splash_leases", "stats", "stats", {
60 leases = leased or (leases and leases.leases) or 0,
61 whitelisttotal = whitelisttotal or (leased and leases.whitelisttotal) or 0,
62 whitelistonline = whitelisted or (leases and leases.whitelistonline) or 0,
63 blacklisttotal = blacklisttotal or (leases and leases.blacklisttotal) or 0,
64 blacklistonline = blacklisted or (leases and leases.blacklistonline) or 0,
66 uci:save("luci_splash_leases")
70 function get_device_for_ip(ipaddr)
72 uci:foreach("network", "interface", function(s)
73 if s.ipaddr and s.netmask then
74 local network = ip.IPv4(s.ipaddr, s.netmask)
75 if network:contains(ip.IPv4(ipaddr)) then
76 -- this should be rewritten to luci functions if possible
77 dev = utl.trim(sys.exec(". /lib/functions/network.sh; network_get_device IFNAME '" .. s['.name'] .. "'; echo $IFNAME"))
84 function get_physdev(interface)
86 dev = utl.trim(sys.exec(". /lib/functions/network.sh; network_get_device IFNAME '" .. interface .. "'; echo $IFNAME"))
92 function get_filter_handle(parent, direction, device, mac)
93 local input = utl.split(sys.exec('/usr/sbin/tc filter show dev ' .. device .. ' parent ' .. parent) or {})
96 for k, v in pairs(input) do
97 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')
99 local mac, mac1, mac2, mac3, mac4, mac5, mac6
100 if direction == 'src' then
101 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')
102 mac5, mac6 = input[k+2]:match('match ([%a%d][%a%d])([%a%d][%a%d])0000/ffff0000')
104 mac1, mac2 = input[k+1]:match('match 0000([%a%d][%a%d])([%a%d][%a%d])/0000ffff')
105 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')
107 if mac1 and mac2 and mac3 and mac4 and mac5 and mac6 then
108 mac = "%s:%s:%s:%s:%s:%s" % { mac1, mac2, mac3, mac4, mac5, mac6 }
119 function macvalid(mac)
120 if mac and mac:match(
121 "^[a-fA-F0-9][a-fA-F0-9]:[a-fA-F0-9][a-fA-F0-9]:" ..
122 "[a-fA-F0-9][a-fA-F0-9]:[a-fA-F0-9][a-fA-F0-9]:" ..
123 "[a-fA-F0-9][a-fA-F0-9]:[a-fA-F0-9][a-fA-F0-9]$"
131 function ipvalid(ipaddr)
133 return ip.IPv4(ipaddr) and true or false
139 function mac_to_ip(mac)
140 ipc.neighbors({ family = 4 }, function(n)
141 if n.mac == mac and n.dest then
142 return n.dest:string()
147 function mac_to_dev(mac)
148 ipc.neighbors({ family = 4 }, function(n)
149 if n.mac == mac and n.dev then
155 function ip_to_mac(ip)
156 ipc.neighbors({ family = 4 }, function(n)
157 if n.mac and n.dest and n.dest:equal(ip) then
164 local cmd = table.remove(argv, 1)
167 limit_up = (tonumber(uci:get("luci_splash", "general", "limit_up")) or 0) * 8
168 limit_down = (tonumber(uci:get("luci_splash", "general", "limit_down")) or 0) * 8
170 if ( cmd == "lease" or cmd == "add-rules" or cmd == "remove" or
171 cmd == "whitelist" or cmd == "blacklist" or cmd == "status" ) and #argv > 0
173 if not (macvalid(arg) or ipvalid(arg)) then
174 print("Invalid argument. The second argument must " ..
175 "be a valid IPv4 or Mac Address.")
181 local leased_macs = get_known_macs("lease")
182 local blacklist_macs = get_known_macs("blacklist")
183 local whitelist_macs = get_known_macs("whitelist")
185 for i, adr in ipairs(argv) do
187 if adr:find(":") then
193 if mac and cmd == "add-rules" then
194 if leased_macs[mac] then
196 elseif blacklist_macs[mac] then
197 add_blacklist_rule(mac)
198 elseif whitelist_macs[mac] then
199 add_whitelist_rule(mac)
201 elseif mac and cmd == "status" then
202 print(leased_macs[mac] and "lease"
203 or whitelist_macs[mac] and "whitelist"
204 or blacklist_macs[mac] and "blacklist"
206 elseif mac and ( cmd == "whitelist" or cmd == "blacklist" or cmd == "lease" ) then
207 if cmd ~= "lease" and leased_macs[mac] then
208 print("Removing %s from leases" % mac)
210 leased_macs[mac] = nil
213 if cmd ~= "whitelist" and whitelist_macs[mac] then
214 if cmd == "lease" then
215 print('%s is whitelisted. Remove it before you can lease it.' % mac)
217 print("Removing %s from whitelist" % mac)
218 remove_whitelist(mac)
219 whitelist_macs[mac] = nil
223 if cmd == "whitelist" and leased_macs[mac] then
224 print("Removing %s from leases" % mac)
226 leased_macs[mac] = nil
229 if cmd ~= "blacklist" and blacklist_macs[mac] then
230 print("Removing %s from blacklist" % mac)
231 remove_blacklist(mac)
232 blacklist_macs[mac] = nil
235 if cmd == "lease" and not leased_macs[mac] then
236 if not whitelist_macs[mac] then
237 print("Adding %s to leases" % mac)
239 leased_macs[mac] = true
241 elseif cmd == "whitelist" and not whitelist_macs[mac] then
242 print("Adding %s to whitelist" % mac)
244 whitelist_macs[mac] = true
245 elseif cmd == "blacklist" and not blacklist_macs[mac] then
246 print("Adding %s to blacklist" % mac)
248 blacklist_macs[mac] = true
250 print("The mac %s is already %sed" %{ mac, cmd })
252 elseif mac and cmd == "remove" then
253 if leased_macs[mac] then
254 print("Removing %s from leases" % mac)
256 leased_macs[mac] = nil
257 elseif whitelist_macs[mac] then
258 print("Removing %s from whitelist" % mac)
259 remove_whitelist(mac)
260 whitelist_macs[mac] = nil
261 elseif blacklist_macs[mac] then
262 print("Removing %s from blacklist" % mac)
263 remove_blacklist(mac)
264 blacklist_macs[mac] = nil
266 print("The mac %s is not known" % mac)
270 print("Can not find mac for ip %s" % argv[i])
275 elseif cmd == "sync" then
278 elseif cmd == "list" then
283 print("\n luci-splash list\n List connected, black- and whitelisted clients")
284 print("\n luci-splash sync\n Synchronize firewall rules and clear expired leases")
285 print("\n luci-splash lease <MAC-or-IP>\n Create a lease for the given address")
286 print("\n luci-splash blacklist <MAC-or-IP>\n Add given address to blacklist")
287 print("\n luci-splash whitelist <MAC-or-IP>\n Add given address to whitelist")
288 print("\n luci-splash remove <MAC-or-IP>\n Remove given address from the lease-, black- or whitelist")
295 -- Get a list of known mac addresses
296 function get_known_macs(list)
297 local leased_macs = { }
299 if not list or list == "lease" then
300 uci:foreach("luci_splash_leases", "lease", function(s)
302 leased_macs[s.mac:lower()] = true
307 if not list or list == "whitelist" then
308 uci:foreach("luci_splash", "whitelist", function(s)
310 leased_macs[s.mac:lower()] = true
315 if not list or list == "blacklist" then
316 uci:foreach("luci_splash", "blacklist", function(s)
318 leased_macs[s.mac:lower()] = true
326 -- Helper to delete iptables rules
327 function ipt_delete_all(args, comp, off)
329 for i, r in ipairs(ipt:find(args)) do
330 if comp == nil or comp(r) then
331 off[r.table] = off[r.table] or { }
332 off[r.table][r.chain] = off[r.table][r.chain] or 0
334 exec("iptables -t %q -D %q %d 2>/dev/null"
335 %{ r.table, r.chain, r.index - off[r.table][r.chain] })
337 off[r.table][r.chain] = off[r.table][r.chain] + 1
342 function ipt6_delete_all(args, comp, off)
344 for i, r in ipairs(ipt:find(args)) do
345 if comp == nil or comp(r) then
346 off[r.table] = off[r.table] or { }
347 off[r.table][r.chain] = off[r.table][r.chain] or 0
349 exec("ip6tables -t %q -D %q %d 2>/dev/null"
350 %{ r.table, r.chain, r.index - off[r.table][r.chain] })
352 off[r.table][r.chain] = off[r.table][r.chain] + 1
358 -- Convert mac to uci-compatible section name
359 function convert_mac_to_secname(mac)
360 return string.gsub(mac, ":", "")
363 -- Add a lease to state and invoke add_rule
364 function add_lease(mac, no_uci)
367 -- Get current ip address
368 local ipaddr = mac_to_ip(mac)
370 -- Add lease if there is an ip addr
372 local device = get_device_for_ip(ipaddr)
374 local leased = uci:get("luci_splash_leases", "stats", "leases")
375 if type(tonumber(leased)) == "number" then
376 update_stats(leased + 1, nil, nil, nil, nil)
379 uci:section("luci_splash_leases", "lease", convert_mac_to_secname(mac), {
384 limit_down = limit_down,
387 uci:save("luci_splash_leases")
389 add_lease_rule(mac, ipaddr, device)
391 print("Found no active IP for %s, lease not added" % mac)
396 -- Remove a lease from state and invoke remove_rule
397 function remove_lease(mac)
400 uci:delete_all("luci_splash_leases", "lease",
402 if s.mac:lower() == mac then
404 local leased = uci:get("luci_splash_leases", "stats", "leases")
405 if type(tonumber(leased)) == "number" and tonumber(leased) > 0 then
406 update_stats(leased - 1, nil, nil, nil, nil)
408 remove_lease_rule(mac, s.ipaddr, s.device, tonumber(s.limit_up), tonumber(s.limit_down))
414 uci:save("luci_splash_leases")
418 -- Add a whitelist entry
419 function add_whitelist(mac)
420 uci:section("luci_splash", "whitelist", convert_mac_to_secname(mac), { mac = mac })
421 uci:save("luci_splash")
422 uci:commit("luci_splash")
423 add_whitelist_rule(mac)
427 -- Add a blacklist entry
428 function add_blacklist(mac)
429 uci:section("luci_splash", "blacklist", convert_mac_to_secname(mac), { mac = mac })
430 uci:save("luci_splash")
431 uci:commit("luci_splash")
432 add_blacklist_rule(mac)
436 -- Remove a whitelist entry
437 function remove_whitelist(mac)
439 uci:delete_all("luci_splash", "whitelist",
440 function(s) return not s.mac or s.mac:lower() == mac end)
441 uci:save("luci_splash")
442 uci:commit("luci_splash")
443 remove_lease_rule(mac)
444 remove_whitelist_tc(mac)
447 function remove_whitelist_tc(mac)
448 uci:foreach("luci_splash", "iface", function(s)
449 local device = get_physdev(s['.name'])
450 if device and device ~= "" then
452 print("Removing whitelist filters for %s interface %s." % {mac, device})
454 local handle = get_filter_handle('ffff:', 'src', device, mac)
456 exec('tc filter del dev "%s" parent ffff: protocol ip prio 1 handle %s u32' % { device, handle })
458 print('Warning! Could not get a handle for %s parent :ffff on interface %s' % { mac, device })
460 local handle = get_filter_handle('1:', 'dest', device, mac)
462 exec('tc filter del dev "%s" parent 1:0 protocol ip prio 1 handle %s u32' % { device, handle })
464 print('Warning! Could not get a handle for %s parent 1:0 on interface %s' % { mac, device })
470 -- Remove a blacklist entry
471 function remove_blacklist(mac)
473 uci:delete_all("luci_splash", "blacklist",
474 function(s) return not s.mac or s.mac:lower() == mac end)
475 uci:save("luci_splash")
476 uci:commit("luci_splash")
477 remove_lease_rule(mac)
481 -- Add an iptables rule
482 function add_lease_rule(mac, ipaddr, device)
488 exec("iptables -t mangle -I luci_splash_mark_out -m mac --mac-source %q -j RETURN" % mac)
490 -- Mark incoming packets to a splashed host
491 -- for ipv4 - by iptables and destination
492 if id and device then
493 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()})
496 --for ipv6: need to use the mac here
499 exec("ip6tables -t mangle -I luci_splash_mark_out -m mac --mac-source %q -j MARK --set-mark 79" % mac)
500 if id and device and tonumber(limit_down) then
501 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})
506 if device and tonumber(limit_up) > 0 then
507 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})
510 if id and device and tonumber(limit_down) > 0 then
511 exec("tc class add dev %s parent 1: classid 1:0x%s htb rate %skbit" % { device, id, limit_down })
512 exec("tc qdisc add dev %s parent 1:%s sfq perturb 10" % { device, id })
515 exec("iptables -t filter -I luci_splash_filter -m mac --mac-source %q -j RETURN" % mac)
516 exec("iptables -t nat -I luci_splash_leases -m mac --mac-source %q -j RETURN" % mac)
518 exec("ip6tables -t filter -I luci_splash_filter -m mac --mac-source %q -j RETURN" % mac)
523 -- Remove lease, black- or whitelist rules
524 function remove_lease_rule(mac, ipaddr, device, limit_up, limit_down)
532 ipt_delete_all({table="mangle", chain="luci_splash_mark_in", options={"/*", mac:upper()}})
533 ipt_delete_all({table="mangle", chain="luci_splash_mark_out", options={"MAC", mac:upper()}})
534 ipt_delete_all({table="filter", chain="luci_splash_filter", options={"MAC", mac:upper()}})
535 ipt_delete_all({table="nat", chain="luci_splash_leases", options={"MAC", mac:upper()}})
537 ipt6_delete_all({table="mangle", chain="luci_splash_mark_out", options={"MAC", mac:upper()}})
538 ipt6_delete_all({table="filter", chain="luci_splash_filter", options={"MAC", mac:upper()}})
541 if device and tonumber(limit_up) > 0 then
542 local handle = get_filter_handle('ffff:', 'src', device, mac)
544 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})
546 print('Warning! Could not get a handle for %s parent :ffff on interface %s' % { mac, device })
549 -- remove clients class
550 if device and id then
551 exec('tc class del dev "%s" classid 1:%s' % {device, id})
552 exec('tc filter del dev "%s" parent 1:0 prio 1' % device) -- ipv6 rule
553 --exec('tc qdisc del dev "%s" parent 1:%s sfq perturb 10' % { device, id })
558 -- Add whitelist rules
559 function add_whitelist_rule(mac)
560 exec("iptables -t filter -I luci_splash_filter -m mac --mac-source %q -j RETURN" % mac)
561 exec("iptables -t nat -I luci_splash_leases -m mac --mac-source %q -j RETURN" % mac)
563 exec("ip6tables -t filter -I luci_splash_filter -m mac --mac-source %q -j RETURN" % mac)
565 uci:foreach("luci_splash", "iface", function(s)
566 local device = get_physdev(s['.name'])
567 if device and device ~= "" then
568 exec('tc filter add dev "%s" parent ffff: protocol ip prio 1 u32 match ether src %s police pass' % { device, mac })
569 exec('tc filter add dev "%s" parent 1:0 protocol ip prio 1 u32 match ether dst %s classid 1:1' % { device, mac })
575 -- Add blacklist rules
576 function add_blacklist_rule(mac)
577 exec("iptables -t filter -I luci_splash_filter -m mac --mac-source %q -j DROP" % mac)
579 exec("ip6tables -t filter -I luci_splash_filter -m mac --mac-source %q -j DROP" % mac)
584 -- Synchronise leases, remove abandoned rules
588 local time = os.time()
590 -- Current leases in state files
591 local leases = uci:get_all("luci_splash_leases")
593 -- Convert leasetime to seconds
594 local leasetime = tonumber(uci:get("luci_splash", "general", "leasetime")) * 3600
597 uci:load("luci_splash_leases")
598 uci:revert("luci_splash_leases")
601 local blackwhitelist = uci:get_all("luci_splash")
602 local whitelist_total = 0
603 local whitelist_online = 0
604 local blacklist_total = 0
605 local blacklist_online = 0
607 local leases_online = 0
610 for k, v in pairs(leases) do
611 if v[".type"] == "lease" then
612 if os.difftime(time, tonumber(v.start)) > leasetime then
614 remove_lease_rule(v.mac, v.ipaddr, v.device, tonumber(v.limit_up), tonumber(v.limit_down))
616 leasecount = leasecount + 1
618 -- only count leases_online for connected clients
619 if mac_to_ip(v.mac) then
620 leases_online = leases_online + 1
624 uci:section("luci_splash_leases", "lease", convert_mac_to_secname(v.mac), {
629 limit_down = limit_down,
636 -- Whitelist, Blacklist
637 for _, s in utl.spairs(blackwhitelist,
638 function(a,b) return blackwhitelist[a][".type"] > blackwhitelist[b][".type"] end
640 if (s[".type"] == "whitelist") then
641 whitelist_total = whitelist_total + 1
643 local mac = s.mac:lower()
644 if mac_to_ip(mac) then
645 whitelist_online = whitelist_online + 1
649 if (s[".type"] == "blacklist") then
650 blacklist_total = blacklist_total + 1
652 local mac = s.mac:lower()
653 if mac_to_ip(mac) then
654 blacklist_online = blacklist_online + 1
661 -- include a new field "leases_online" in stats to differ between active clients and leases:
662 -- update_stats(leasecount, leases_online, whitelist_online, whitelist_total, blacklist_online, blacklist_total) later:
663 update_stats(leases_online, whitelist_online, whitelist_total, blacklist_online, blacklist_total)
665 uci:save("luci_splash_leases")
667 -- Get the mac addresses of current leases
668 local macs = get_known_macs()
672 ipt_delete_all({table="filter", chain="luci_splash_filter", options={"MAC"}},
673 function(r) return not macs[r.options[2]:lower()] end)
674 ipt_delete_all({table="nat", chain="luci_splash_leases", options={"MAC"}},
675 function(r) return not macs[r.options[2]:lower()] end)
676 ipt_delete_all({table="mangle", chain="luci_splash_mark_out", options={"MAC", "MARK", "set"}},
677 function(r) return not macs[r.options[2]:lower()] end)
678 ipt_delete_all({table="mangle", chain="luci_splash_mark_in", options={"/*", "MARK", "set"}},
679 function(r) return not macs[r.options[2]:lower()] end)
683 ipt6_delete_all({table="filter", chain="luci_splash_filter", options={"MAC"}},
684 function(r) return not macs[r.options[2]:lower()] end)
685 ipt6_delete_all({table="mangle", chain="luci_splash_mark_out", options={"MAC", "MARK", "set"}},
686 function(r) return not macs[r.options[2]:lower()] end)
694 -- Find traffic usage
695 local function traffic(lease)
697 local traffic_out = 0
699 local rin = ipt:find({table="mangle", chain="luci_splash_mark_in", destination=lease.ipaddr})
700 local rout = ipt:find({table="mangle", chain="luci_splash_mark_out", options={"MAC", lease.mac:upper()}})
702 if rin and #rin > 0 then traffic_in = math.floor( rin[1].bytes / 1024) end
703 if rout and #rout > 0 then traffic_out = math.floor(rout[1].bytes / 1024) end
705 return traffic_in, traffic_out
709 local leases = uci:get_all("luci_splash_leases")
710 local blackwhitelist = uci:get_all("luci_splash")
713 "%-17s %-15s %-9s %-4s %-7s %20s",
714 "MAC", "IP", "State", "Dur.", "Intf.", "Traffic down/up"
718 for _, s in pairs(leases) do
719 if s[".type"] == "lease" and s.mac then
720 local ti, to = traffic(s)
721 local mac = s.mac:lower()
723 "%-17s %-15s %-9s %3dm %-7s %7dKB %7dKB",
724 mac, s.ipaddr, "leased",
725 math.floor(( os.time() - tonumber(s.start) ) / 60),
726 mac_to_dev(mac) or "?", ti, to
731 -- Whitelist, Blacklist
732 for _, s in utl.spairs(blackwhitelist,
733 function(a,b) return blackwhitelist[a][".type"] > blackwhitelist[b][".type"] end
735 if (s[".type"] == "whitelist" or s[".type"] == "blacklist") and s.mac then
736 local mac = s.mac:lower()
738 "%-17s %-15s %-9s %4s %-7s %9s %9s",
739 mac, mac_to_ip(mac) or "?", s[".type"],
740 "- ", mac_to_dev(mac) or "?", "-", "-"