Showing posts with label sql server. Show all posts
Showing posts with label sql server. Show all posts

Wednesday, 6 January 2021

Steps to resolve VAPT Issues

  
1. Error: Web Parameter Tampering
Resolution:  
Add attribute "enableViewStateMac="false"" inside <pages> tag.
Eg:
<system.web>
    <pages enableViewStateMac="false"/>
</system.web>
 
 
2.  Error: Authentication Bypass Using default credentials
Resolution:
Add "<httpCookies requireSSL="true" />" inside <system.web> tag
Eg:
  <system.web>
     <httpCookies requireSSL="true" />
  </system.web>
 
 
3.  Error: Communication in cleartext
Resolution:  
Implement authorization and authentication in application
Eg:
  <authorization>
      <deny verbs="OPTIONS" users="?"/>
</authorization>
 
  <authentication mode="Forms">
      <forms loginUrl="Login2.aspx" defaultUrl="RedirectionPage.aspx">
      </forms>
</authentication>
 
 
4.  Error: Session Fixation
Resolution:
Add below source code on logout click
     Session.Clear();
     Session.Abandon();
     Session.RemoveAll();
 
     if (Request.Cookies["ASP.NET_SessionId"] != null)
     {
      Response.Cookies["ASP.NET_SessionId"].Value = string.Empty;
         Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-20);
     }
 
     if (Request.Cookies["AuthToken"] != null)
     {
      Response.Cookies["AuthToken"].Value = string.Empty;
         Response.Cookies["AuthToken"].Expires = DateTime.Now.AddMonths(-20);
     }
 
 
5.  Error: Cleartext submission of Password
  Resolution: Implement password encryption while sending to database
Eg of function:
public static string Encrypt(string clearText)
    {
        string EncryptionKey = "TEST123";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
}
 
 
6.  Error: Unencrypted __VIEWSTATE parameter
Resolution: Add attribute “viewStateEncryptionMode="Always"" inside <pages> tag.
Eg:
<system.web>
    <pages viewStateEncryptionMode="Always"/>
</system.web>
 
 
7.  Error: Server version disclosure
Resolution: Add “<httpRuntime enableVersionHeader="false" /> “ inside <system.web> tag.
Eg:
<system.web>
    <httpRuntime enableVersionHeader="false" />
</system.web>
 
 
8.  Error: Cookie Without HTTP Only Flag Set
Resolution:
Add "<httpCookies requireSSL="true" />" inside <system.web> tag
Eg:
  <system.web>
     <httpCookies requireSSL="true" />
  </system.web>
 
 
9.  Error: ASP.NET padding oracle vulnerability
Resolution:
Add attribute "redirectMode="ResponseRewrite"" inside <customErrors> tag
Eg:
<customErrors redirectMode="ResponseRewrite"  
defaultRedirect="customerror.htm" mode="On" />
 
 
10.  Error: Clickjacking
 Resolution:
 Add below code in Global.asax file
     void Application_BeginRequest(object sender, EventArgs e)
      {
         HttpContext.Current.Response.AddHeader("x-frame-options", "DENY");
 }
 
 
11.  Error: options method is enabled
 Resolution:
 Add below tag in "<system.webServer>" tag
    <security>
      <requestFiltering>
         <verbs allowUnlisted="true">
           <add verb="OPTIONS" allowed="false" />
         </verbs>
     </requestFiltering>
 </security>
 

SQL Server code review

SQL Stored Procedure Code Review Checklist

 

1. Stored Procedure body should be enclosed in BEGIN…END. Every Stored Procedure committed on source control should be “DROP and CREATE” and not the “ALTER”.

Eg:

IF EXISTS(SELECT 1 FROM sys.procedures WHERE name = 'USPGetPurchase')

BEGIN

DROP PROCEDURE USPGetPurchase

END

GO

CREATE PROCEDURE USPGetPurchase

 2. Stored Procedure parameters should be enclosed in parenthesis, each parameter listed on new line. Check validity of parameter data types.

 3. User-Defined Stored Procedure naming conventions to be followed as mentioned below, No Special characters to be included in the name of Stored Procedure.

Eg: USPGetPurchase

 4. Schema qualify (i.e. dbo.ClientDetails) all object references.

 5. Stored Procedure should have description and sample call(s) listed near the top.

 6. Always specify explicit column list, not a SELECT *

 7. Stored Procedure should have Error Log, Execute Statement Log and Output XML.

 8. All SQL Keywords should be in Uppercase.

 9. Is there a CASE statement without the ELSE clause? Always specify a default option even if you believe that it is impossible for that condition to happen.

 10. Use (N)VARCHAR(max) only when it is really necessary. Similar, columns/variables of short length should have a fixed size (CHAR, not VARCHAR(1), VARCHAR(2)). Also, check usage of Unicode (VARCHAR) data type, for example, usrs.uid is char(10), not a NCHAR(10), nor VARCHAR(10).

 11. Stored Procedure should do one thing and do it well. If the Stored Procedure returns multiple datasets – consider splitting into multiple Stored Procedures.

 12. Verify usage of temp tables vs. table variables (if you expect more than 200 rows to be temporarily stored – use local temp table; less than 200 – consider table variable).

 13. Stored Procedureshould not use global ## temp tables. Application procs should not be creating new “permanent” tables as an attempt to introduce “data backup/failure recovery point”.

 14. Verify usage of temp table columns – i.e. if you defining/populating columns that are not subsequently used – remove them. For example, if you define “client_id, client_name, client_number” columns, but later retrieve client_name and client_number from base tables (not temp one), then they should not be created as part of temp table.

15. Verify temp table columns data types – they should match the data type of base tables you’re populating them from. For example, if “client_name” is defined as NVARCHAR(500) in cm_client, then temp table should have it defined same way (not as VARCHAR(1000), NVARCHAR(1000), NVARCHAR(255), etc).

16. Verify temp table columns of “VARCHAR/NVARCHAR” data type – they should be created with “collate database_default” modifier to avoid errors if joins are performed on them in case-sensitive databases.

 17. Watch for data being implicitly converted between types. Implicit conversions can have unexpected results, such as truncating data or reducing performance.

 18. Is there GROUP BY <number> clause? It is deprecated, use proper GROUP BY <column> instead.

 19. Checks for record existence should be coded using IF EXISTS (…), not IF SELECT COUNT(*)>0…

 20. Verify usage of IN (…) or NOT IN (…), consider replacing with straight JOIN and/or IF EXISTS.

 21. Avoid using correlated sub-queries as part of SELECT, re-write using JOIN or CROSS APPLY. If you’re accessing same table more than once in a sub-query consider replacement with CTE instead.

 22. Consider using BEGIN TRY … END TRY … BEGIN CATCH … END CATCH for error handling; usage of

IF @@ERROR is discouraged, usage of GOTO is forbidden.

 23. Avoid using LOWER or UPPER built-in functions when trying to achieve case-insensitive compare;

 24. Verify handling of NULL values in nullable columns (or those brought in by LEFT JOIN), use ISNULL/COALESCE to ensure proper calculations or concatenation of the results. Use COALESCE() instead of ISNULL(), its faster & fail proof. Don’t use ISNUMERIC(), use TRY_PARSE() instead.

 25. Check for usage of @@IDENTITY, most likely it should be replaced with SCOPE_IDENTITY. Moreover, the OUTPUT clause is a better and safer way of capturing identity values. Don’t introduce your own “identity management” via MAX()+1.

 26. Verify usage of UNION vs. UNION ALL; if you’re bringing different record types that are already unique, use UNION ALL

 27. Verify usage of DISTINCT – are duplicate rows coming as a result of missing JOIN predicate or data quality issue?

28. Be careful with XML processing in SQL – check OPENXML vs. XML XQuery for the amount of data you’re considering to process.

 29. Verify target column list is used in INSERT statements. Be wary about INSERT…EXEC pattern to obtain data by calling another proc.

 30. Define NULL acceptance in the procedure and code accordingly.

31. If any dynamic SQL is used make sure it executes through only SP_EXECUTESQL only.

 32. Apply encryption procedures while dealing with sensitive information (Ex: Credit Card numbers, pass codes etc.).

 33. Verify and Drop the temp table at the beginning and end of the Stored Procedure.

 34. Try to use TRUNCATE instead of DELETE whenever is possible.

 35. Use CTEs instead of Sub-Queries for better code manageability and readability.

 36. Handle Divide-by-zero errors the columns/variables occurring in denominator.

 37. Always use SET NOCOUNT ON statement in the beginning of the Stored Procedure and SET NOCOUNT ON at the end of the Stored Procedure.

 38. With WHERE clause put OR conditions within brackets, otherwise they will conflict with other AND conditions and may behave differently.

 39. Always prefer using WITH (NOLOCK) for SELECT statement.

 40. Index should be created on all foreign keys.

 41. Expensive operators such as NOT LIKE should be avoided.

 42. No tables should have Insert, Update, Delete permissions.

Friday, 22 May 2020

CSharp Webconfig Interview Questions


CSharp Webconfig Interview Questions and Answers


1). What is web.config file in asp.net?
Web.config is the configurationsettings of an ASP.NET web application. The file is an xml document that defines configuration information regarding the web application.This file stores the information about how the web application will act. 

2). Does web.config file case-sensitive?
Yes.

3). Web.config file is stored in which form?
Web.config files are stored in XML format.

4). Can one directory contain multiple web.config files?
No. One directory can contain only one file.

5). Can you tell the location of the root web.config file from which all web.config file inherit ?
All the Web.config files inherit the root Web.config file available at the following location: Systemroot\Microsoft.NET\Framework\VersionNumber\CONFIG\Web.config


6). What is the root tag of web.config file?
<configuration> tag is the root element of the Web.config file under which it has all the remaining sub elements.

7). What is the use of customErrors tag in web.config file ?
CustomErrors tag provides information about custom error messages for an  application. The customErrors element can be defined at any level in the application file hierarchy.

<customErrors defaultRedirect ="ErrorPage.aspx" mode ="Off">
   <error statusCode ="401" redirect ="UnauthorizedPage.aspx"/>
</customErrors>

The customErrors section consists of defaultRedirect and mode attributes which specify the default redirect page and the on/off mode respectively.
Error status code:

  • 400 Bad Request
  • 401 Unauthorized
  • 404 Not Found
  • 408 Request Timeout

8). Can you describe the funcnalitity of <httpHandlers> tab in web.config?
HttpHandler is a code that executes when an http request for a specific resource is made to the server. For example, request an .aspx page the ASP.NET page handler is executed, similarly if an .asmx file is requested, the ASP.NET service handler is executed. An HTTP Handler is a component that handles the ASP.NET requests at a lower level than ASP.NET is capable of handling.

9). What is authentication tag/section in web.config?
ASP.NET implements additional authentication schemes using authentication providers, which are separate from and apply only after the IIS authentication schemes. ASP.NET supports the following authentication providers:

  • Windows (default)
  • Forms
  • Passport
  • None
To enable an authentication provider for an ASP.NET application, use the authentication element in either machine.config or Web.config as follows:

<system.web>
   <!-- mode=[Windows|Forms|Passport|None] -->
   <authentication mode="Windows" />
</system.web>


10). For which purpose you use <appSettings> tag?
AppSettings tag helps us to store the application settings information like connection strings, file paths, URLs, port numbers, custom key value pairs, etc.

<appSettings>
    <add key="ConnectionString" value="Data Srouce=....."/>
</appSettings>


11). What is the use of connectionStrings tag?
<ConnectionStrings> is the most common section of web.config file which allows you to store multiple connection strings that are used in the application.

<connectionStrings>
    <add name ="ConnectionString" connectionString ="Initial Catalog = dotnet;
        Data Source =localhost; Integrated Security = true"/>
</connectionStrings>


You can find more blogs on our website: Trigya Technologies

Steps to resolve VAPT Issues

    1. Error: Web Parameter Tampering Resolution:   Add attribute " enableViewStateMac = " false " " inside  <pages...