From 44d7dbc5175a0e07823f4c0d595a6a199ec04d0a Mon Sep 17 00:00:00 2001 From: nnposter Date: Sun, 1 Mar 2020 03:50:42 +0000 Subject: [PATCH] Streamline Luhn checksum code Removes various floating-point hazards. Fixes #1931, closes #1932 --- CHANGELOG | 3 +++ scripts/http-grep.nse | 29 +++++++++++------------------ 2 files changed, 14 insertions(+), 18 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index f6db28632..b7506b758 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -42,6 +42,9 @@ o [Windows] Add support for the new loopback behavior in Npcap 0.9983. This Adapter to be installed, which was a source of problems for some users. [Daniel Miller] +o [NSE][GH#1931][GH#1932] Script http-grep was not correctly calculating Luhn + checksum [Colleen Li, nnposter] + o [NSE][GH#1838] Scripts dhcp-discover and broadcast-dhcp-discover now support new argument "mac" to force a specific client MAC address [nnposter] diff --git a/scripts/http-grep.nse b/scripts/http-grep.nse index 4df4f9143..75785df38 100644 --- a/scripts/http-grep.nse +++ b/scripts/http-grep.nse @@ -145,26 +145,19 @@ local function ip(matched_ip) return true end --- from rosettacode. A function to validate credit card numbers. +-- A function to validate credit card numbers. local function luhn(matched_ccno) - matched_ccno = matched_ccno:gsub("-", "") - matched_ccno = matched_ccno:gsub(" ", "") - local n = string.reverse(matched_ccno) - local s1 = 0 - for i=1, n:len(), 2 do - s1 = s1 + tonumber(n:sub(i,i)) + local ccno = matched_ccno:gsub("%D", ""):reverse() + local sum = 0 + for i = 1, #ccno do + local d = tonumber(ccno:sub(i,i)) + if i % 2 == 0 then + local dd = 2 * d + d = dd // 10 + dd % 10 + end + sum = sum + d end - local s2 = 0 - for i=2, n:len(), 2 do - local doubled = n:sub(i,i)*2 - doubled = string.gsub(doubled,'(%d)(%d)',function(a,b)return a+b end) - s2 = s2+doubled - end - local total = s1 + s2 - if total%10 == 0 then - return true - end - return false + return sum % 10 == 0 end -- A function to validate ssn numbers.