id = "TIME"

description = "Connects to the TIME service (RFC 868, not NTP) and on success prints the date and time."

author = "Dirk Loss <http://www.dirk-loss.de>"

license = "Same as Nmap--See http://nmap.org/book/man-legal.html"

categories = {"demo"}

require "shortport"
require "comm"
require "stdnse"

unpack_uint32 = function(str)
    -- Convert given 4 character string into a big-endian 32bit integer 
    if string.len(str) ~= 4 then
        valid = false
        result = "Argument must be a 4 character string."
    else
        valid = true
        a = string.byte(string.sub(str,1,1))
        b = string.byte(string.sub(str,2,2))
        c = string.byte(string.sub(str,3,3))
        d = string.byte(string.sub(str,4,4))
        result = a*256*256*256 + b*256*256 + c*256 + d
    end
    return valid, result
end

-- Seconds between Unix epoch (1970-01-01) and NTP epoch (1900-01-01)
EPOCH1900_DIFF = 2208988800

portrule = shortport.port_or_service(37, "time", "udp")

action = function(host, port)
    local status, result = comm.exchange(host, port, '\n',
                                        {bytes=4, proto="udp", timeout=1000})
    if status then
        local valid, seconds = unpack_uint32(result)
        if valid then
            return os.date("%c", seconds - EPOCH1900_DIFF)
        end
    end
end
