In my ASP.NET(3.5) project, I am using inbuilt TableAdapters/Dataset for all Data Access. Does it provide the same security as SQLDataSource does from SQL injection? I am using parameters as follows.
Dim myDAL As New ABCTableAdapters.XYZTableAdapter
Label1.Text = myDAL.getDatafromDB(myParameter)
Update 1:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim myParameter As String = getSafeURL(Request.QueryString("MS_Code")) 'getsafeurl encodes querystring using HttpUtility.UrlEncode
Dim myDAL As New ABCTableAdapters.XYZTableAdapter
Label1.Text = myDAL.getDatafromDB(myParameter)
End Sub
getDatafromDB corresponds to following query present in app_code/DAL.xsd
SELECT something FROM sometable where fieldname = #parameter
Update 2:
If I 'View Code' of XSD I am able to see following
<SelectCommand>
<DbCommand CommandType="Text" ModifiedByUser="true">
<CommandText>SELECT pageContent FROM [content] where name = #name</CommandText>
<Parameters>
<Parameter AllowDbNull="true" AutogeneratedName="name" ColumnName="name" DataSourceName="iseac.dbo.[content]" DataTypeServer="nchar(100)" DbType="String" Direction="Input" ParameterName="#name" Precision="0" ProviderType="NChar" Scale="0" Size="100" SourceColumn="name" SourceColumnNullMapping="false" SourceVersion="Current" />
</Parameters>
</DbCommand>
</SelectCommand>
It depends.
You could get SQL injection if you badly use tableAdapters.
The main thing is to use SqlParameters for all data that is gathered from users.
Can you show some of your data access code ?
Look up here How To: Protect From SQL Injection in ASP.NET
using System.Data;
using System.Data.SqlClient;
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet userDataset = new DataSet();
SqlDataAdapter myDataAdapter = new SqlDataAdapter(
"SELECT au_lname, au_fname FROM Authors WHERE au_id = #au_id",
connection);
myCommand.SelectCommand.Parameters.Add("#au_id", SqlDbType.VarChar, 11);
myCommand.SelectCommand.Parameters["#au_id"].Value = SSN.Text;
myDataAdapter.Fill(userDataset);
}
The important part here is that user entered data (what comes in from web request) is passed to DB inside database parameters like #au_id. In that case you are protected from SQL injection.
BAD WAY would be this (DON'T USE THIS):
myCommandText = string.Format(
"SELECT au_lname, au_fname
FROM Authors WHERE au_id = {0}", SSN.Text)
This way user can manipulate what is send to DB and if your connection to DB has enough privileges it can drop tables or database. Or it can silently modify your data and that is even worse.
So, always use database parameters.
Additionally if you do you gain in performance, because DB will cache execution plan and if you later execute same SQL with only different values for parameters, DB already have execution plan and it doesn't need to parse sql again.
Related
I have to migrate some Classic ASP pages to .NET. I've got the problem with ADODB connection that has been used in ASP App. Here is the code of old db.asp
<%
Option Explicit
' Declare variables...
Dim cnn ' ADO connection
Dim rst ' ADO recordset
Dim strTitle 'Title for each page
Sub OpenDatabase()
' Create an ADO Connection.
Set cnn = Server.CreateObject("ADODB.Connection")
' We're using SQL Server connection string
cnn.Open Session("SQLConnectString")
cnn.CommandTimeout = 0
Server.ScriptTimeout = 3000
' Create an ADO Recordset object
Set rst = Server.CreateObject("ADODB.Recordset")
End Sub
Sub RunSQL(strSQL)
'Open a recordset from the strSQL.
rst.Open strSQL, cnn
End Sub
Sub CloseDatabase()
rst.Close
Set rst = Nothing
cnn.Close
Set cnn = Nothing
End Sub
%>
I want to use this code on every page for connection to DB. know that I have to remove Option Explicit from my code and add header as <%# Page Language="VB" %> I've copied this code to the new aspx page and now I'm getting errors:
1) VS ask me to put End Sub before Sub OpenDatabase(), but there is no Open Sub that need to be closed.
2) VS don't see those variables cnn, rst, strTitle
3) Now I'm storing ConnectionString in Web.config, so I've replaced open with the following code:
cnn.Open(System.Configuration.ConfigurationManager.ConnectionStrings("SQLConnectString").ConnectionString)
What else should I change to fix it? Any advise=) Thanks
You do not use ADODB in DotNet. Technically, you can, but that's not the way to do.
You use ADO.Net, IDataReaders, DataSets (loose or strongly-typed, I prefer strongly-typed).
ASP.NET is not ASP.
Don't feel bad, I was trying the same thing you are (albeit, back in 2002).
Until someone told me differently.
Here is a tutorial...probably at the right level for where you are now.
http://www.aspsnippets.com/Articles/Difference-between-ExecuteReader-ExecuteScalar-and-ExecuteNonQuery.aspx
Rule #1 in NET: connection string better be in web.config or other config files. Or in some cases in OS registry.
Using connection string defined in each and every page in NET is bad practice from security, maintenance and lot of other reasons and on top of that it show low qualification of a programmer who build it.
Rule #2. You can use inline SQL statement but for the same reason as in rule #1 it is a bad idea. Use parametrized stored procedures unless you do not have any like while working with access or Excel or plain text files as data storage.
So in your web.config you should have following entry:
<connectionStrings>
<add name="DBCS"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|ProjectDatabases.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
then in your code you call
Public void main()
{
String CONN
String SQLString
CONN = String.Format(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString, rootPath);
SQLString=/// your stored procedure and parameters if any
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd = new SqlCommand(SQLString), CONN);
CONN.Open();
SqlDataReader reader = cmd.ExecuteReader();
/// do what ever you need to work with your data like build a string, html document etc
closeConn();
}
public void closeConn()
{
if (reader != null)
{
reader.Close();
}
if (CONN!= null)
{
CONN.Close();
}
}
You do not need Option Explicit for simple reason: C# will not allow you to use any undeclared variable
I am a complete beginner at ASP.net(and this forum) i am using Visual studio 2013 and have created created another table in the created database using the package manager console.
How do i go about placing the information into this new table? (I am looking to store firstname and last name in a separate table)
The create account button is below:
Protected Sub CreateUser_Click(sender As Object, e As EventArgs)
Dim userName As String = UserNameCtrl.Text
Dim Firstnane As String = firstnamectrl.Text
Dim manager = New UserManager
Dim User = New ApplicationUser() With {.UserName = userName}
Dim result = manager.Create(User, Password.Text)
If result.Succeeded Then
IdentityHelper.SignIn(manager, User, isPersistent:=False)
IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
Else
ErrorMessage.Text = result.Errors.FirstOrDefault()
End If
End Sub
Any pointers in the right direction, hints or suggested reading would be very helpful.
If I understand correctly, this link may be of some help:
http://www.codeguru.com/vb/gen/vb_database/adonet/article.php/c15033/A-Basic-VBNET-ADONET-Tutorial-Adding-Deleting-and-Updating.htm
It is for a windows form application, but it should translate pretty well if you're using web forms. Basically, you just want to make a connection to the database during the button click event (the simplest way I know of to make this connection is using ADO.NET), and pass the values of the first and last name in a SQL query to the sql server.
You would be building the sql query as a string, and concatenating your vb variables into that string. Something like; "Insert into table xxx(firstname, LastName) values " & Firstname & ", " & Lastname...
I'm a new in the world of coding,
I built a large web site with several textboxes, so now i figure out that I've been using a dangerous method of inserting data in the SQL server by some thing like this:
execSQL("insert into Dossier(ID_Dossier,Nom_Giac) values(" & id_dossier.text & "," Nom_gaic.text & "')")
Public Function execSQL(ByVal req As String, Optional ByVal type As String = "r")
cmd = New SqlCommand
cmd.CommandText = req
cmd.Connection = con
openCon()
If type = "r" Then
Return cmd.ExecuteReader(CommandBehavior.CloseConnection)
Else
Return cmd.ExecuteNonQuery
End If
closeCon()
End Function
I just want to know if there is any quick way to solve this problem in my entire web site.
I applaud the fact that you want to remove any possibilities of SQL injection from your site.
That said, there's no quick, magical "find-and-replace-my-vulnerable-code" function; you need to go into your system and update any calls like that with parameterized queries.
Parameterized queries are required to prevent SQL injection. Here's an example, taken from this question: How do I create a parameterized SQL query? Why Should I?
Public Function GetBarFooByBaz(ByVal Baz As String) As String
Dim sql As String = "SELECT foo FROM bar WHERE baz= #Baz"
Using cn As New SqlConnection("Your connection string here"), _
cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("#Baz", SqlDbTypes.VarChar, 50).Value = Baz
Return cmd.ExecuteScalar().ToString()
End Using
End Function
Using LINQ to SQL can help prevent SQL Injection attacks by parameterizing for you:
LINQ to SQL passes all data to the database via SQL parameters. So, although the SQL query is composed dynamically, the values are substitued server side through parameters safeguarding against the most common cause of SQL injection attacks.
Read more about it here.
We would like to update data in a SQL Server 2012 database with a value obtained from
changing a value on an ASP.Net DetailsView. I Would would like to update the database using
a strongly typed DataSet called DataSetParentsDetails
a TableAdapter called ParentsDetailsTableAdapter
a DataTable called ParentsDetails.
These were created with the DataSet Designer.
This is the code from the code-behind file used to figure out the amount we want to update into the database:
Protected Sub DetailsViewDetails_ItemCommand(sender As Object, e As System.Web.UI.WebControls.DetailsViewCommandEventArgs)
Dim dcmAmountToAdjust As Decimal
Dim StrSqlStatement As String
Select Case e.CommandName
Case "Add"
Case "Edit"
dcmOriginalRegistrationFee = GetValueFromLabelRegistrationFee()
Case "Delete"
Case "Update"
dcmNewRegistrationFee = GetValueFromTextBoxRegistrationFee()
dcmAmountToAdjust = dcmNewRegistrationFee - dcmOriginalRegistrationFee
' Update the tuition balance in the parent's data.
'-------------------------------------------------
StrSqlStatement =
"Update Students " & _
"Set RegistrationCode = RegistrationCode + #AmountToAdjust " & _
"Where StudentID = #ID"
' Code to update the database goes here.
'---------------------------------------
End Select
End Sub
I'm sure that this was asked many times before but I can't find a good example on how to use the query in: StrSqlStatement to update the database through the strongly typed DataSet.
First off you need a connection string, it's good practise to store your connection strings in the web.config file:
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=putYourServerAndInstanceNameHere;Initial Catalog=putYourDatabaseNameHere;User ID=putYourSqlUsernameHere;Password=password" providerName="System.Data.SqlClient" />
</connectionStrings>
This is a direct child of the root <configuration> element. For more information about connection strings, visit http://www.connectionstrings.com.
Then you'll need some imports in your code-behind, and you'll need to add them as references to your project if you haven't already got them in there:
Import System.Data
Import System.Data.SqlClient
Then we connect to the database and run our command, we use parameters because they're more secure.
'build the connection object using the string from the web.config file
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)
'build the command object specifying the command text and the connection to use, conn
Using cmd As New SqlCommand("UPDATE Students SET RegistrationCode = RegistrationCode + #AmountToAdjust WHERE StudentID = #ID", conn)
'add the parameters needed by the command
cmd.Parameters.AddWithValue("#AmountToAdjust", amountToAdjust)
cmd.Parameters.AddWithValue("#ID", studentID)
'try to open the connection and execute the statement
Try
conn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
'handle the exception here
End Try
End Using
End Using
Note that there is no need to use conn.Close() here as the Using statement will take care of that for you (SqlConnection's Dispose method closes the connection if it is still open).
Okay this question could either be very broad or very specific because I am not sure if I am going about this in a fundamentally wrong way or if I am close to correct.
First an overview: What I am trying to do it create a server application for all of the clients in my organization to connect to. I think the best way to do this is to use a web service. Please correct me if I am wrong!
Anyway, if I use a web service I need the web service(server) to connect to the database. In MS Visual studio when you add a web service project the data menu disappears and you can't add a data source to the project. There may be a workaround for this by hand coding this, but I am not sure how to do it. This is my first time working with a web service and ASP.NET so I am a real noob in this area.
Any help would be greatly appreciated!!!
Add your database connection string to the <connectionStrings/> section of the web service web.config file. Check this web site for a list of the most common database connection strings: Connectionstrings.com
You would use standard ADO.Net commands and SQL statements, rather than using the dataset designer. Example (IN VB)
<WebMethod()> _
Public Function DoesOpenCallExist(ByVal CustID As String, ByVal CallType As String, ByVal SubCallType As String) As Boolean
Dim returnvalue As Boolean = False
' first, entry validation
' snip - code deleted
Dim conn As New System.Data.SqlClient.SqlConnection
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("HEATConnectionString").ConnectionString
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = conn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "sp_GetCallCount"
cmd.Parameters.AddWithValue("#CustID", CustID)
' Etc...
Try
conn.Open()
returnvalue = cmd.ExecuteScalar() > 0
Catch ex As Exception
Throw New Exception(ex.ToString())
Finally
conn.Close()
End Try
Return returnvalue
End Function
*This should be done
web.config file*
here the datsource is the servername,initial catlog is the databasename and the userid ur sql userid and the password is as same.
And then in the class we want to get connect with the database......
****class.cs****
public class connect
{
public static SqlConnection con()
{
String con= ConfigurationManager.AppSettings["connections"].ToString();
SqlConnection cn = new SqlConnection(con);
cn.Open();
return cn;
}
}
here the connection is the keyname......
ok i think its sufficient............