challenges/newbiecontest/prog/crypto/crypto.lua

136 lines
3.4 KiB
Lua
Executable file

#!/usr/bin/env lua
-- require ---------------------------------------------------------------------
local luasql = require "luasql.sqlite3" -- sqlite module
local http = require "socket.http" -- http module
local ltn12 = require("ltn12") -- ltn12 module used to convert a sink to a table
-- functions -------------------------------------------------------------------
-- Extract info about the cookie used for newbiecontest connection
function extract_cookie(db)
-- cookie value
cursor = db:execute("SELECT value FROM moz_cookies WHERE host LIKE\
'%newbiecontest.org%' AND name LIKE '%SMFCookie%'")
cookie_value = cursor:fetch(row)
cursor:close()
-- cookie name
cursor = db:execute("SELECT name FROM moz_cookies WHERE host LIKE\
'%newbiecontest.org%' AND name LIKE '%SMFCookie%'")
cookie_name = cursor:fetch(row)
cursor:close()
return cookie_value, cookie_name
end
-- Extract message from http request
function extract_message(cookie_name, cookie_value, url)
-- create the table
local t = {}
-- add the SMF cookie to the header
local headers = {
["Cookie"] = cookie_name .. "=" .. cookie_value
}
-- request
r = http.request{url = url,
headers = headers,
sink = ltn12.sink.table(t) -- information goes to the table t
}
-- convert the answer to string
string_r = table.concat(t)
-- extract message and key
message = string.match(string_r, '\'([a-z]+)\'')
key = string.match(string_r, '\'([0-9]+)\'')
return message, key
end
-- decrypt
function decrypt(message, key)
i = 0
char_code = 0
-- create the local table containing the solution
local r = {}
-- for each byte of the message
for i = 1, string.len(message), i + 1 do
-- extract the char code
char_code = string.byte(message, i)
-- if it goes behind the "a" move to "z"
if (char_code - key < string.byte("a"))
then
-- here goes the barbary...
r[i] = string.char((string.byte("z")) - (key - (char_code -
string.byte("a") - 1)))
-- if it's not, just do it
else
r[i] = string.char(char_code - key)
end
end
return table.concat(r)
end
-- Give the response back to the server
function send_response(r, url)
-- crate the table
local t = {}
-- concatenate the url
url = url .. "?solution=" .. r
-- add the SMF cookie to the header
local headers = {
["Cookie"] = cookie_name .. "=" .. cookie_value
}
-- send the reply
r = http.request{url = url,
headers = headers,
sink = ltn12.sink.table(t)
}
return table.concat(t) -- return the token
end
-- main -----------------------------------------------------------------------
if table.maxn(arg) < 3
then
print("Get. The. Fuck. Out")
print("[i] Usage : ./crypto.lua file_db url_1 url_2")
os.exit()
end
-- sqlite connection
env = luasql.sqlite3()
conn = env:connect(arg[1])
cookie_value, cookie_name = extract_cookie(conn)
message, key = extract_message(cookie_name, cookie_value, arg[2])
r = decrypt(message, key)
token = send_response(r, arg[3])
print(token)
-- sqlite close
env:close()
conn:close()
print("Done.")