Classic Asp Generate and Validate Anti Forgery Token - html

I have been stuck in this topic for a long time and I hope someone can help me.
I have an application written in asp classic. I must implement an antiforgery token in the form where I go to validate the data.
My page is composed like this
<% Dim token
token = GetGUID()
Session("token")=token
%>
<html>
<head>
</head>
<boby>
...
...
<form method="post" action="../includes/CENT_FUNCTIONS.ASP">
<input type="hidden" value="<%=Session("token")%> name="token">
</form>
</body>
</html>
As you can see at the top in the asp code when opening the page I generate a GUID that I am going to save in a session variable.
I generate the GUID with this vbs function
FUNCTION GetGUID()
GetGUID = CreateObject("Scriptlet.TypeLib").GUID
END FUNCTION
So I'm going to save the session variable in a hidden field of the form. The action of the form goes to call another asp file where I will go to collect the form data to call a store procedure in the sql database.
The file is written like this
<%
IF Request("token") = Session("token") THEN
ID_CENT=Request.QueryString("ID_CENT")
IDAZIENDA_CENT=Request("IDAZIENDA_CENT")
ELSE
Response.Redirect "../notallowed.asp"
END IF
set command = Server.CreateObject("ADODB.Command")
command.ActiveConnection = conn
command.CommandText = "CAR_CENTRALINI_FUNZIONI"
command.CommandType = adCmdStoredProc
set objParameter = command.CreateParameter ("#ID_CENT", adInteger, adParamInput,,ID_CENT)
command.Parameters.Append objParameter
set objParameter = command.CreateParameter ("#IDAZIENDA_CENT", adInteger, adParamInput,,IDAZIENDA_CENT)
command.Parameters.Append objParameter
command.Execute , , adExecuteNoRecords
Set command=Nothing
Set objParameter=Nothing
Response.Redirect "../Fonia/UT_Fonia_CENTRALINI.asp"
%>
So before collecting the form data I go to check if the token arrived is the same as the one stored in the session variable.
But this comparison that I make in the IF condition always returns false.
Is this way I am using to generate and validate the anti forgery token correct? What am I doing wrong?
Thanks for any replies

Related

How to read json respone field value in classic asp

Please help me to read json response filed value in classic asp.
For example:
I am getting below response in classic asp. I require deliveryNo and content value. Please help on this:
{"labels":[{"shipmentID":"a2f3vh3","deliveryNo":"1234","content":"test","invoice":null,"responseStatus":{"code":200,"message":"SUCCESS","messageDetails":"All shipments processed and label/invoice generated successfully","logMsg":[]}}],"responseStatus":{"code":200,"message":"SUCCESS","messageDetails":"All shipments processed successfully","logMsg":[]}}
At the risk of annoying people by answering something that has been answered already lots of times, I use a solution which used to be available via http://www.aspjson.com/, but the site seems to be down now.
I still use the code though - it's here http://pastebin.com/qvn2UxXV
This is a very simple example of how to use it with your data, to get at deliveryNo and Content:
<!--#INCLUDE file="aspJSON.asp" -->
<%
Set oJSON = New aspJSON
jsonstring = "{""labels"":[{""shipmentID"":""a2f3vh3"",""deliveryNo"":""1234"",""content"":""test"",""invoice"":null,""responseStatus"":{""code"":200,""message"":""SUCCESS"",""messageDetails"":""All shipments processed and label/invoice generated successfully"",""logMsg"":[]}}],""responseStatus"":{""code"":200,""message"":""SUCCESS"",""messageDetails"":""All shipments processed successfully"",""logMsg"":[]}}"
Set oJSON = New aspJSON
oJSON.loadJSON(jsonstring)
For Each result In oJSON.data("labels")
Set this = oJSON.data("labels").item(data)
var_deliveryNo = this.item("deliveryNo")
var_content = this.item("content")
response.write "deliveryNo: " & var_deliveryNo & "<br />"
response.write "content: " & var_content & "<br />"
Next
%>
You could use ASPJSON
aspjson is JSON serializer for VBScript based ASP server technology.

HTML form with dropdown forms, sending it to database

I'm tying to make a html form with a dropbox where you can choose a few options. However when I want to send this to the databse, something goes wrong. Namely that it doesn't send the variable in the name but uses the option as variable.
<select name="name">
<option value="op1">op1</option>
<option value="op2">op2</option>
<option value="op3">op3</option>
<option value="op4">op4</option>
</select>
So when submitting this, it doesn't send var name with value opX but just opX.
While in a normal form box this seems to work:
<input name="email" type="text" value="" size="79"><br>
This sends var email with value = stuff that I typed in.
I am accessing with:
$name = $_POST["name"];
How do I fix this?
You'll probably be accessing your HTML form from some server-side language like PHP or Java.
Here's a PHP example:
$varName = $_POST['name']; // Would equal op1, op2, op3 or op4
create a hidden type and add it under the </select> but within the same form.like <input type=""hidden" name"submit" value="submit">....then check whether its set or not..like in php
if(isset($_GET/POST[submit])
{
//access your form data here..like:
$x=$_GET/POST[name]
}
this is how you can be assured about whether data is set or not
If you want to save data coming from html form, you must use server-side language. ASP,ASP.NET,PHP etc. are server-side programming language.
If you will use PHP or ASP, you should use MySql as a database. If you will use ASP.NET ,you should use MSSQL as a database. If you will use ASP , you should use MS Access Database.
Example for ASP:
<%
variable = Request.Form("name")
variable2 = Request.Form("email")
Set conn=CreateObject("ADODB.Connection")
dbpath="Data Source=" & Server.MapPath("db\yourdb.mdb")& ";Provider=Microsoft.Jet.OLEDB.4.0;"
Conn.Open dbpath
sql = "INSERT INTO yourtable_name (your_field1,yur_field2) VALUES (' "&variable&" ',' "&variable2&" ')"
Conn.execute sql
%>

How to update web page by sending POST request with parameter to it AND get the last retrieved paramter value by sending GET request to it

I need to write a simple web page that can be update by POST of a parameter:
Sending POST request to the page with a parameter - will update the web page constantly.
Sending GET request to the page will return the last retrieved value of the parameter
For example (Probably each request is a different session):
POST /mypage.asp?param1=Hello
GET /mypage.asp >> Response: Hello
POST /mypage.asp?param1=Changed
GET /mypage.asp >> Response: Changed
Use $_SESSION
session_start();
if($_SERVER['REQUEST_METHOD'] == "POST")
$_SESSION['last_val'] = $_POST['some_val'];
}
if($_SERVER['REQUEST_METHOD'] == "GET")
echo $_SESSION['last_val'];
}
Learn more about SESSION
Evan's answer is correct conceptually, but I think he doesn't address the different sessions and didn't use "classic ASP" (vbscript or jscript).
To persist a value between sessions and requests, you need some form of storage. Probably the simplest option is an Application variable (which I show below). Other options are "thread-safe" storage, like the widely available CAPROCK DICTIONARY, or a database.
The code:
<%# Language="VBScript" %>
<%
If Request.ServerVariables("REQUEST_METHOD")= "POST" Then
Application.Lock
Application("StoredValue") = Request.Form("param1")
Application.Unlock
Else
Application.Lock
Response.Write Application("StoredValue")
Application.Unlock
End If
%>
<%
dim fileSystemObject,Text_File,Text_File_Content,NewValue
NewValue=Request.QueryString("MyParam")
set fileSystemObject=Server.CreateObject("Scripting.FileSystemObject")
If NewValue <> "" Then
set Text_File=fileSystemObject.CreateTextFile("C:\MyPath\myTextFile.txt")
Text_File.write(NewValue)
Text_File.close
End If
if fileSystemObject.FileExists("C:\MyPath\myTextFile.txt")=true then
set Text_File=fileSystemObject.OpenTextFile("C:\MyPath\myTextFile.txt",1,false)
Text_File_Content=Text_File.ReadAll
Text_File.close
else
set Text_File=fileSystemObject.CreateTextFile("C:\MyPath\myTextFile.txt")
Text_File.write("Please send GET request to this page with paramter MyParam!")
Text_File.close
set Text_File=fileSystemObject.OpenTextFile("C:\MyPath\myTextFile.txt",1,false)
Text_File_Content=Text_File.ReadAll
Text_File.close
end if
Response.Write(Text_File_Content)
%>

Accessing a request's body using classic ASP?

How do I access what has been posted by a client to my classic ASP server?
I know that there is the Request.Forms variable, but the client's request was not made using a Form.
The client request's body is just a string made using a standard POST statement.
Thanks
You need to read request bytes if content type of request sent by client is not form data. In this case, request is not a form-data that is accessible through name-value pairs so you cannot use Request.Form collection. I suggest investigate the BinaryRead method.
Reading posted data and convert into string :
If Request.TotalBytes > 0 Then
Dim lngBytesCount
lngBytesCount = Request.TotalBytes
Response.Write BytesToStr(Request.BinaryRead(lngBytesCount))
End If
Function BytesToStr(bytes)
Dim Stream
Set Stream = Server.CreateObject("Adodb.Stream")
Stream.Type = 1 'adTypeBinary
Stream.Open
Stream.Write bytes
Stream.Position = 0
Stream.Type = 2 'adTypeText
Stream.Charset = "iso-8859-1"
BytesToStr = Stream.ReadText
Stream.Close
Set Stream = Nothing
End Function
Hope it helps.
Update #1:
With using JScript
if(Request.TotalBytes > 0){
var lngBytesCount = Request.TotalBytes
Response.Write(BytesToStr(Request.BinaryRead(lngBytesCount)))
}
function BytesToStr(bytes){
var stream = Server.CreateObject("Adodb.Stream")
stream.type = 1
stream.open
stream.write(bytes)
stream.position = 0
stream.type = 2
stream.charset = "iso-8859-1"
var sOut = stream.readtext()
stream.close
return sOut
}
To get the JSON string value just use CStr(Request.Form)
Works a treat.
In Classic ASP, Request.Form is the collection used for any data sent via POST.
For the sake of completeness, I'll add that Request.QueryString is the collection used for any data sent via GET/the Query String.
I would guess based on the above that even though the client is not a web browser, the Request.Form collection should be populated.
note: all of this is assuming the data being sent is textual in nature, and that there are no binary uploads (e.g. pictures or files) being sent. Update your question body if this is an incorrect assumption.
To test, write out the raw form data and see what you have - something along the lines of:
Response.Write(Request.Form)
Which with a regular web page will output something like
field=value&field2=value2
If you get something along those lines, you could then use that as a reference for a proper index.
If you do not get something like that, update your question with what you tried and what you got.

classic asp password validation sql

If i had a login page that got user input for username and password, how would i post that information to another page that is gonna be used to store subs and procedures so other pages will include that page so I can minimise the amount of times i type up a connection string.
So I have login.asp which i want to post login credentials to include.asp which will never be opened by if users login details are correct it would then be directed to table.asp. If incorrect it should show an error message in the login.asp page.
I've provided the code for include.asp file which will never be seen by a user below
Dim objCon, SQL, objRS
'Connect to Database
sub connect()
Set objCon = CreateObject("ADODB.Connection")
Set objRS = CreateObject("ADODB.Recordset")
objCon.Open "Provider=SQLOLEDB.1;Password=xxxx;Persist Security Info=True;User ID=xxxx;Initial Catalog=Customer;Data Source=xxxx"
SQL = "SELECT * FROM Customer"
objRS.open SQL, objCon
end sub
sub connectionClose()
objRS.close
objCon.close
end sub
let me post with code tag so it helps.
so u got login.asp,validateLogin.asp, table.asp ( they all got include.asp)
Login.asp post the credentials to validatelogin.asp
once in validatelogin.asp
dim username : username = request.form("username")
dim password: password = request.form("password")
'here for security purpose u will want to replace all the single quote in username and password with 2x single quote (you do that to avoid SQL injection form bots / hackers
username = replace(username ,"'","''")
password = replace(password,"'","''")
sqlValidateUser = "SELECT top 1 * FROM Customer where username='"&&"' and password = ''"
set rsValidateUser = objCon.execute(sqlValidateUser)
if not rsValidateUser.eof then
session("authentified") = "1"
response.redirect("table.asp")
response.end()
else
response.redirect("YOUR_ERROR_PAGE.asp")
response.end()
end if
rsValidateUser.close
then in your include.asp u will want something like :
'Validating if your NOT on login.asp or loginvalidate.asp ... if not Check if your logged in ... if not redirect to error page or login form
if not instr(lcase(request.servervariable("url")),"login.asp") > 0 and not instr(lcase(request.servervariable("url")),"validatelogin.asp") > 0 then
if session("authentified") = "1" then
response.redirect("your_Error_page.asp")
end if
end if
not 100% sure about the include.asp code i did not validate any of it but it should look like that
Under your root folder create an \includes folder.
Within \includes add a "functions.asp" page and put your common data access functions in that page. Include NO HTML - just server side script.
In your authentication page, add #include directives that point to your includes folder: example:
<!-- #include file = "../includes/functions.asp" -->
Then from your auth page you call any functions defined in functions.asp.