Last active
September 20, 2016 23:24
-
-
Save lfittl/8df549c0adeaa16ee0f201def841be74 to your computer and use it in GitHub Desktop.
Using pg_query fingerprinting to prevent SQL injections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#my_orm_method("1") | |
1 | |
#my_orm_method("'abc'") | |
abc | |
#my_orm_method("1 UNION SELECT * FROM passwords") | |
test.rb:8:in `exec_with_fingerprint': Invalid fingerprint, rejecting (RuntimeError) | |
from test.rb:16:in `my_orm_method' | |
from test.rb:23:in `<main>' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'pg' | |
require 'pg_query' | |
conn = PG::Connection.new(hostaddr: '192.168.99.100', user: 'postgres') | |
def exec_with_fingerprint(conn, query, fingerprint, &block) | |
if PgQuery.fingerprint(query) != fingerprint | |
fail 'Invalid fingerprint, rejecting' | |
else | |
conn.exec(query, &block) | |
end | |
end | |
def my_orm_method(conn, input_value) | |
puts "#my_orm_method(#{input_value.inspect})" | |
# 018e1acac181c6d28f4a923392cf1c4eda49ee4cd2 is the fingerprint for "SELECT 1" | |
exec_with_fingerprint(conn, "SELECT " + input_value, "018e1acac181c6d28f4a923392cf1c4eda49ee4cd2") do |res| | |
res.getvalue(0, 0) | |
end | |
end | |
puts my_orm_method(conn, '1') | |
puts my_orm_method(conn, "'abc'") | |
puts my_orm_method(conn, '1 UNION SELECT * FROM passwords') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment