Tuesday, 31 July 2018

List all stored procedures with particular Text to Find.

There comes a scenario when you want to list all stored procedures with particular Text.


Here is the Script to List all the Objects which contains that text(even in comments) in that Particular Database:


SELECT DISTINCT
       o.name AS Object_Name,
       o.type_desc,o.create_date,o.modify_date
  FROM sys.sql_modules m
       INNER JOIN
       sys.objects o
         ON m.object_id = o.object_id
 WHERE m.definition Like '%coalesce%'


Here is the Script to List all the Objects which contains that text(even in comments) in all Database:


EXEC sp_msforeachdb  'USE [?];  SELECT DISTINCT
       o.name AS Object_Name,"?" as DBName,
       o.type_desc,o.create_date,o.modify_date
  FROM sys.sql_modules m
       INNER JOIN
       sys.objects o
         ON m.object_id = o.object_id
 WHERE m.definition Like ''%coalesce%'';'

Note: Here We had used System Stored Procedure sp_msforeachdb 


Happy Coding !!!

Saturday, 28 July 2018

Create Random Number By RNGCryptoServiceProvider

RNGCryptoServiceProvider generates high-quality random numbers. With it, we use an RNG (random number generator) that is as random as possible. This helps in applications where random numbers must be completely random.It is present in System.Security.Cryptography.

Caution:
RNGCryptoServiceProvider has a cost: it reduces performance over the Random type.

Time for one random int from RNGCryptoServiceProvider: 2796.19 ns 
Time for one random int from Random: 9.30 ns


How to use?

private string CreateSalt(int size) //Generate the salt via Randon Number Genertor cryptography
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] buff = new byte[size];
            rng.GetBytes(buff);
            return Convert.ToBase64String(buff);
        }




Thursday, 26 July 2018

Ranges in C# 8.0


Ranges

This feature is about delivering two new operators (Index operator ‘^’ and range operator ‘..’) that allow constructing System.Index and System.Range objects and using them to index or slice collections at runtime. The new operators are syntactic sugar and making your code more clean and readable. The code for the operator index ^ is implemented in System.Index and for the range ‘..’ in System.Range.

System.Index
Excellent way toindex a collection from the ending.

Example
var lastItem = array[^1]; this code equivalent to: var lastItem = array[collection.Count-1];
System.Range

Ranges way to access "ranges" or "slices" of collections. This will help you to avoid LINQ and making your code compact and more readable. You can compare this feature with Ranges in F#.


New style
Old style
var thirdItem = array [2]; 
// Code behind: array [2]
var thirdItem = array [2]; 
var lastItem = array [^1];
// Code Behind: [^1] = new Index(1, true); true = bool fromEnd 
var lastItem = array [array.Count -1];
var lastItem = array.Last; // LINQ
var subCollection = array[2..^5]; // Output: 2, 3, 4, 5
// Code Behind: Range.Create(2, new Index(5, true)); as you see here we have used the both operators! Range and Index. The Range is for the operator … and the index is for the operator ^. Means skip until the index 2 from the begin and ^5 means ignore the first 5 elements from behind.
var subCollection = array.ToList().GetRange(2, 4);
or with LINQ
var subCollection = array.Skip(2).Take(4);


Examples

Consider the following array:

var array = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Now we cut a slice view from this array as below:

var slice= array[2..5];


Value: 2 3 4

We can access the slice values with the following indexes:


Index 0 1 2

Note: the start index is inclusive (included to the slice), and the end index is exclusive (excluded from the slice).var slice1 = array [4..^2]; // Range.Create(4, new Index(2, true))

and the slice1 will be of type Span<int>. [4..^2] Skip from the begin until the index 4 and skip 2 from the ending.Output: 4, 5, 6, 7, 8 var slice2 = array [..^3]; // Range.ToEnd(new Index(3, true)) Output: 0, 1, 2, 3, 4, 5, 6, 7 var slice3 = array [2..]; // Range.FromStart(2) Output: 2, 3, 4, 5, 6, 7, 8,9, 10 var slice4 = array[..]; // array[Range.All] Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10


Bounded Ranges

In the bounded ranges, the lower bound (start index) and the upper bound(end index) are known or predefined.array[start..end] // Get items from start-1 until end-1 array[start..end:step] // Get items from start-1 until end-1 by step


The above Range syntax (step at end) is inspiredfrom Python. Python supports the following syntax(lower:upper:step), with :stepbeing optional and :1 by default, but there are some wishes in the community to use the F# syntax (lower..step..upper).

Range syntax in F#.


array { 5 .. 2 .. 20 } // where 2 = step [start .. step .. end]

Output:


5 7 9 11 13 15 17 19
Example for the bounded rangesvar array = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; var subarray = array[3..5]; // The selected items: 3, 4


The code above is equal to array.ToList().GetRange(3, 2);.If you compare array.ToList().GetRange(3, 2); with array[3..5] you can see that the new style is cleanerand more human readable.

There is a feature request to use the Range in the “if” statement or with the pattern matching as described below:

With “in” operatorvar anyChar = 'b'; if (anyChar in 'a'..'z') { Console.WriteLine($"The letter {anyChar} in range!"); } Output: The letter b in range!

Range Pattern is one of the new proposed pattern matching which can be used to produce simple range checks. Range Pattern will allow you to use the range operator ‘..’ in the select case" statement (switch).switch (anyChar) { case in 'a'..'z' => Console.WriteLine($“The letter {anyChar} in range!”), case in '!'..'+' => Console.WriteLine($“Something else!”), } Output: The letter b in range!

It is worth to mention that not everyone happy by using the “in” operator in Ranges. The community is divided between using “in” or “is”;


Unbounded Ranges


When the lower bound is omitted, it's interpreted to be zeroor the upper bound is omitted, it's interpreted to be the length of the receiving collection.
Examplesarray[start..] // Get items start-1 with the rest of the array array[..end] // Get items from the beginning until end-1 array[..] // A Get the whole array

Positive Boundsvar fiveToEnd = 5..; // Equivalent to Range.From(5) i.e. missing upper bound var startToTen = ..1; // Equivalent to Range.ToEnd(1). Missing lower bound. Result: 0, 1 var everything = ..; // Equivalent to Range.All. Missing upper and lower bound. Result: 0..Int.Max var everything = [5..11]; // Equivalent to Range.Create(5, 11) var collection = new [] { 'a', 'b', 'c' }; collection[2..]; // Result chars: c collection[..2]; // Result chars: a, b collection[..]; // Result chars: a, b, c


Wednesday, 11 July 2018

SQL Server : Script to find out all tables in our database which do not have primary key

Primary Key is the most important aspect in designing our Database or Table. One should always use one in each and every user-defined Table in our Databases. If in case you do not need one, you should define an auto-incremented column as 'SerialNumber' or 'RowNumber'. It is a good practice. But the Question arouses how will I see in Database which Tables do not have Primary Key.to solve this Problem, Here is the Script :



Happy Coding !!!

Tuesday, 10 July 2018

SQL Server : Shrink Multiple Database Logs at once

Here is the script to shrink multiple Database at once. Here Cursor is used for iterating to all Databases. You can also use sp_MSforeachdb


Happy Coding !!!

Monday, 9 July 2018

Bindings in WCF

Bindings will tell how the client will communicate with the outer world. It tells which protocols will your WCF use. It is used as per client need. It supports different types of encodings

A binding has several characteristics:
Transport: Defines the base protocol to be used like HTTP, Named Pipes, MSMQ and TCP.
Encoding(Optional): Three types of encodings are available  - Text, Binary or Message Transmission Optimization Mechanism(MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments and Large messages(greater than 64k).
Protocol(Optional): Defines Information to be used in the Binding such as Security, Transaction or Reliable Message Capability.

The following Table List some of the Important Bindings used by WCF Binding:


Binding Description
BasicHttpBinding Basic Web Service Communication. No Security by Default
WSHttpBinding Web Services with -* support. Support Transactions
WSDualHttpBinding Web Services with Duplex Contract and Transaction Support
WSFederationHttpBinding Web Services with Federated Security. Supports Transactions
MsmqIntegrationBinding Communication with MSMQ Applications. Supports Transactions
NetMsmqBinding Communication Between WCF Binding by using Queueing. Supports Transactions.
NetNamedPipeBinding Communnication between WCF Applications on same Computer. Supports Duplex Contracts and Transactions.
NetPeerTcpBinding Communications Between Computers across peer to peer services. Supports Duplicate Contracts
NetTcpBinding Communication between WCF Applications across Computers. Supports Duplex Contracts and transactions

Difference Between WCF and Web Service

When an Interviewer comes on Topic WCF with you, it is much obvious his First Question would be What is WCF? Why we use WCF over Web Service? What are the differences between two?

WCF (Windows Communication Foundation) is a programming platform for building, configuring and deploying network - distributed services. Interoperability is the Fundamental Characteristics of WCF. It is a combined feature of Web Services, .NET Remoting, MSMQ and COM+.

Difference Between WCF and Web Service


FEATURES WEB SERVICE WCF
Hosting It can be hosted in IIS It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming [WebService] attribute has to be added to the class [ServiceContraact] attribute has to be added to the class
Model [WebMethod] attribute represents the method exposed to the client [OperationContract] attribute represents the method exposed to the client
Operation One-way, Request-Response are the different operations supported in web service One-Way, Request-Response, Duplex are a different type of operations supported in WCF
XML System.Xml.serialization namespace is used for serialization System.Runtime.Serialization namespace is used for serialization
Encoding XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom XML 1.0, MTOM, Binary, Custom
Transports Can be accessed through HTTP, TCP, Custom Can be accessed through HTTP, TCP, Named pipes, MSMQ, P2P, Custom
Protocols Security Security, Reliable messaging, Transactions


Happy Coding !!!

OWASP Top 10 Vulnerabilities For Application Security

While Developing Applications, Security and Best Practices are revolving around Developers Mind. What to Do ? or What they should avoid? Which pattern to follow?, How to make Application Security-proof. As there are numerous hundreds of Vulnerabilities. OWASP has issued These TOP 10 Vulnerabilities in 2013 as the Most Common Security Potholes developers fall onto.

Have a look..

OWASP Top 10
OWASP Top 10 – 2013 (New)
·         A1 – Injection- Injection flaws, such as SQL, OS, and LDAP injection occur when untrusted data is sent to an interpreter as part of a command or query. The attacker’s hostile data can trick the interpreter into executing unintended commands or accessing data without proper authorization.
·      A2 – Broken Authentication and Session Management- Application functions related to authentication and session management are often not implemented correctly, allowing attackers to compromise passwords, keys, or session tokens, or to exploit other implementation flaws to assume other users’ identities.
·      A3 – Cross-Site Scripting (XSS)- XSS flaws occur whenever an application takes untrusted data and sends it to a web browser without proper validation or escaping. XSS allows attackers to execute scripts in the victim’s browser which can hijack user sessions, deface web sites, or redirect the user to malicious sites.
·      A4 – Insecure Direct Object References- A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, or database key. Without an access control check or other protection, attackers can manipulate these references to access unauthorized data.
·      A5 – Security Misconfiguration- Good security requires having a secure configuration defined and deployed for the application, frameworks, application server, web server, database server, and platform. Secure settings should be defined, implemented, and maintained, as defaults are often insecure. Additionally, software should be kept up to date.
·      A6 – Sensitive Data Exposure- Many web applications do not properly protect sensitive data, such as credit cards, tax IDs, and authentication credentials. Attackers may steal or modify such weakly protected data to conduct credit card fraud, identity theft, or other crimes. Sensitive data deserves extra protection such as encryption at rest or in transit, as well as special precautions when exchanged with the browser.
·       A7 – Missing Function Level Access Control-Most web applications verify function level access rights before making that functionality visible in the UI. However, applications need to perform the same access control checks on the server when each function is accessed. If requests are not verified, attackers will be able to forge requests in order to access functionality without proper authorization.
·       A8 – Cross-Site Request Forgery (CSRF)- A CSRF attack forces a logged-on victim’s browser to send a forged HTTP  request, including the victim’s session cookie and any other automatically included authentication information, to a vulnerable web application. This allows the attacker to force the victim’s browser to generate requests the vulnerable application thinks are legitimate requests from the victim.
·       A9 – Using Known Vulnerable Components- Components, such as libraries, frameworks, and other software modules, almost always run with full privileges. If a vulnerable component is exploited, such an attack can facilitate serious data loss or server takeover. Applications using components with known vulnerabilities may undermine application defenses and enable a range of possible attacks and impacts.
·       A10 – Unvalidated Redirects and Forwards-Web applications frequently redirect and forward users to other pages and websites, and use untrusted data to determine the destination pages. Without proper validation, attackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages.




A1 Injection

Example Attack Scenarios Scenario #1: The application uses untrusted data in the construction of the following vulnerable SQL call:
String query = "SELECT * FROM accounts WHERE userID='" + id.Text + "'";
In this case, the attacker modifies the ‘id’ parameter value in her browser to send: ' or '1'='1. For example: http://example.com/app/accountView?id=' or '1'='1
Thus Query becomes SELECT * FROM accounts WHERE userID= or 1=1, which would be always True.
Prevent Injection
Primary Defenses:
·Option #1: Use of Prepared Statements (Parameterized Queries)-

                         SqlCommand command = new SqlCommand(commandText, connection);
                         command.Parameters.Add("@ID", SqlDbType.Int);
                         command.Parameters["@ID"].Value = customerID;


·Option #2: Use of Stored Procedures
Option #3: Escaping all User Supplied Input
Additional Defenses:
· Also Enforce: Least Privilege

· Also Perform: White List Input Validation

A2 – Broken Authentication and Session Management


Authentication and session management includes all aspects of handling user authentication and managing active sessions. Authentication is a critical aspect of this process, but even solid authentication mechanisms can be undermined by flawed credential management functions, including password change, forgot my password, remember my password, account update, and other related functions. Because “walk by” attacks is likely for many web applications, all account management functions should require reauthentication even if the user has a valid session id.

User authentication on the web typically involves the use of a userid and password. Stronger methods of authentication are commercially available such as software and hardware-based cryptographic tokens or biometrics, but such mechanisms cost prohibitive for most web applications. A wide array of account and session management flaws can result in the compromise of user or system administration accounts. Development teams frequently underestimate the complexity of designing an authentication and session management scheme that adequately protects credentials in all aspects of the site. Web applications must establish sessions to keep track of the stream of requests from each user. HTTP does not provide this capability, so web applications must create it themselves. Frequently, the web application environment provides a session capability, but many developers prefer to create their own session tokens. In either case, if the session tokens are not properly protected, an attacker can hijack an active session and assume the identity of a user. Creating a scheme to create strong session tokens and protect them throughout their lifecycle has proven elusive for many developers. Unless all authentication credentials and session identifiers are protected with SSL at all times and protected against disclosure from other flaws, such as cross-site scripting, an attacker can hijack a user’s session and assume their identity.

Am I Vulnerable To 'Broken Authentication and Session Management'?

Are session management assets like user credentials and session IDs properly protected? You may be vulnerable if:

1. User authentication credentials aren’t protected when stored using hashing or encryption.

2. Credentials can be guessed or overwritten through weak account management functions (e.g., account creation, change password, recover password, weak session IDs).

3. Session IDs are exposed in the URL (e.g., URL rewriting).

4. Session IDs are vulnerable to session fixation attacks.

5. Session IDs don’t timeout, or user sessions or authentication tokens, particularly single sign-on (SSO) tokens, aren’t properly invalidated during logout.

6. Session IDs aren’t rotated after successful login.

7. Passwords, session IDs, and other credentials are sent over unencrypted connections

A3 – Cross-Site Scripting (XSS)-


Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted web sites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.

An attacker can use XSS to send a malicious script to an unsuspecting user. The end user’s browser has no way to know that the script should not be trusted, and will execute the script. Because it thinks the script came from a trusted source, the malicious script can access any cookies, session tokens, or other sensitive information retained by the browser and used with that site. These scripts can even rewrite the content of the HTML page. For more details on the different types of XSS flaws, see:
Types of Cross-Site Scripting

There are two different types of XSS flaws: 1) Stored and 2)Reflected, and each of these can occur on the a) Server or b) on theClient.

Am I Vulnerable To 'Cross-Site Scripting (XSS)'?

You are vulnerable if you do not ensure that all user supplied input is properly escaped, or you do not verify it to be safe via server-side input validation, before including that input in the output page. Without proper output escaping or validation, such input will be treated as active content in the browser. If Ajax is being used to dynamically update the page, are you using safe JavaScript APIs? For unsafe JavaScript APIs, encoding or validation must also be used.

Automated tools can find some XSS problems automatically. However, each application builds output pages differently and uses different browser side interpreters such as JavaScript, ActiveX, Flash, and Silverlight, making automated detection difficult. Therefore, complete coverage requires a combination of manual code review and penetration testing, in addition to automated approaches.

How Do I Prevent 'Cross-Site Scripting (XSS)'?

Preventing XSS requires separation of untrusted data from active browser content.

1. The preferred option is to properly escape all untrusted data based on the HTML context (body, attribute, JavaScript, CSS, or URL) that the data will be placed into.

2. Positive or “whitelist” server-side input validation is also recommended as it helps protect against XSS, but is not a complete defense as many applications require special characters in their input. Such validation should, as much as possible, validate the length, characters, format, and business rules on that data before accepting the input.

3. For rich content, consider auto-sanitization libraries like OWASP’s AntiSamy or the Java HTML Sanitizer Project.

4. Consider Content Security Policy (CSP) to defend against XSS across your entire site.



A4 – Insecure Direct Object References


A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, database record, or key, as a URL or form parameter. An attacker can manipulate direct object references to access other objects without authorization, unless an access control check is in place.

For example, in Internet Banking applications, it is common to use the account number as the primary key. Therefore, it is tempting to use the account number directly in the web interface. Even if the developers have used parameterized SQL queries to prevent SQL injection, if there is no extra check that the user is the account holder and authorized to see the account, an attacker tampering with the account number parameter can see or change all accounts.

Am I Vulnerable To 'Insecure Direct Object References'?

The best way to find out if an application is vulnerable to insecure direct object references is to verify that all object references have appropriate defenses. To achieve this, consider:

1. For direct references to restricted resources, does the application fail to verify the user is authorized to access the exact resource they have requested?

2. If the reference is an indirect reference, does the mapping to the direct reference fail to limit the values to those authorized for the current user?

Code review of the application can quickly verify whether either approach is implemented safely. Testing is also effective for identifying direct object references and whether they are safe. Automated tools typically do not look for such flaws because they cannot recognize what requires protection or what is safe or unsafe.

How Do I Prevent 'Insecure Direct Object References'?

Preventing insecure direct object references requires selecting an approach for protecting each user accessible object (e.g., object number, filename):

1. Use per user or session indirect object references. This prevents attackers from directly targeting unauthorized resources. For example, instead of using the resource’s database key, a drop-down list of six resources authorized for the current user could use the numbers 1 to 6 to indicate which value the user selected. The application has to map the per-user indirect reference back to the actual database key on the server. OWASP’s ESAPI includes both sequential and random access reference maps that developers can use to eliminate direct object references.

2. Check access. Each use of a direct object reference from an untrusted source must include an access control check to ensure the user is authorized for the requested object.


A5  - Security Misconfiguration 


Security misconfiguration can happen at any level of an application stack, including the platform, web server, application server, database, framework, and custom code. Developers and system administrators need to work together to ensure that the entire stack is configured properly. Automated scanners are useful for detecting missing patches, misconfigurations, use of default accounts, unnecessary services, etc.

Am I Vulnerable To 'Security Misconfiguration'?

Is your application missing the proper security hardening across any part of the application stack? Including:

1. Is any of your software out of date? This includes the OS, Web/App Server, DBMS, applications, and all code libraries (see new A9).

2. Are any unnecessary features enabled or installed (e.g., ports, services, pages, accounts, privileges)?

3. Are default accounts and their passwords still enabled and unchanged?

4. Does your error handling reveal stack traces or other overly informative error messages to users?

5. Are the security settings in your development frameworks (e.g., Struts, Spring, ASP.NET) and libraries not set to secure values?

Without a concerted, repeatable application security configuration process, systems are at a higher risk.

How Do I Prevent 'Security Misconfiguration'?

The primary recommendations are to establish all of the following:

1. A repeatable hardening process that makes it fast and easy to deploy another environment that is properly locked down. Development, QA, and production environments should all be configured identically (with different passwords used in each environment). This process should be automated to minimize the effort required to set up a new secure environment.

2. A process for keeping abreast of and deploying all new software updates and patches in a timely manner to each deployed environment. This needs to include all code libraries as well (see new A9).

3. A strong application architecture that provides effective, the secure separation between components.

4. Consider running scans and doing audits periodically to help detect future misconfigurations or missing patches.

A6  - Sensitive Data Exposure


Attackers typically don’t break crypto directly. They break something else, such as steal keys, do man-in-the-middle attacks, or steal clear text data off the server, while in transit, or from the user’s browser. The most common flaw is simply not encrypting sensitive data. When crypto is employed, weak key generation and management, and weak algorithm usage are common, particularly weak password hashing techniques. Browser weaknesses are very common and easy to detect, but hard to exploit on a large scale. External attackers have difficulty detecting server-side flaws due to limited access and they are also usually hard to exploit.

Am I Vulnerable To 'Sensitive Data Exposure'?

The first thing you have to determine is which data is sensitive enough to require extra protection. For example, passwords, credit card numbers, health records, and personal information should be protected. For all such data:

1. Is any of this data stored in clear text long term, including backups of this data?

2. Is any of this data transmitted in clear text, internally or externally? Internet traffic is especially dangerous.

3. Are any old/weak cryptographic algorithms used?

4. Are weak crypto keys generated, or is proper key management or rotation missing?

5. Are any browser security directives or headers missing when sensitive data is provided by / sent to the browser?

How Do I Prevent 'Sensitive Data Exposure'?

The full perils of unsafe cryptography, SSL usage, and data protection are well beyond the scope of the Top 10. That said, for all sensitive data, do all of the following, at a minimum:

1. Considering the threats you plan to protect this data from (e.g., insider attack, external user), make sure you encrypt all sensitive data at rest and in transit in a manner that defends against these threats.

2. Don’t store sensitive data unnecessarily. Discard it as soon as possible. Data you don’t have can’t be stolen.

3. Ensure strong standard algorithms and strong keys are used, and proper key management is in place.

4. Ensure passwords are stored with an algorithm specifically designed for password protection, such as bcrypt, PBKDF2, or scrypt.

5. Disable autocomplete on forms collecting sensitive data and disable caching for pages that contain sensitive data.


A7  - Missing Function Level Access Control


Most web applications verify function level access rights before making that functionality visible in the UI. However, applications need to perform the same access control checks on the server when each function is accessed. If requests are not verified, attackers will be able to forge requests in order to access functionality without proper authorization.

Am I Vulnerable To 'Missing Function Level Access Control'?

The best way to find out if an application has failed to properly restrict function level access is to verify every application function:

1. Does the UI show navigation to unauthorized functions?

2. Are server side authentication or authorization checks missing?

3. Are server side checks done that solely rely on information provided by the attacker?

Using a proxy, browse your application with a privileged role. Then revisit restricted pages using a less privileged role. If the server responses are alike, you're probably vulnerable. Some testing proxies directly support this type of analysis.

You can also check the access control implementation in the code. Try following a single privileged request through the code and verifying the authorization pattern. Then search the codebase to find where that pattern is not being followed.

Automated tools are unlikely to find these problems.

How Do I Prevent 'Missing Function Level Access Control'?

Your application should have a consistent and easy to analyze authorization module that is invoked from all of your business functions. Frequently, such protection is provided by one or more components external to the application code.

1. Think about the process for managing entitlements and ensure you can update and audit easily. Don’t hard code.

2. The enforcement mechanism(s) should deny all access by default, requiring explicit grants to specific roles for access to every function.

3. If the function is involved in a workflow, check to make sure the conditions are in the proper state to allow access.

NOTE: Most web applications don’t display links and buttons to unauthorized functions, but this “presentation layer access control” doesn’t actually provide protection. You must also implement checks in the controller or business logic.


A8  - Cross-Site Request Forgery (CSRF)


A CSRF attack forces a logged-on victim’s browser to send a forged HTTP  request, including the victim’s session cookie and any other automatically included authentication information, to a vulnerable web application. This allows the attacker to force the victim’s browser to generate requests the vulnerable application thinks are legitimate requests from the victim.

Am I Vulnerable To 'Cross-Site Request Forgery (CSRF)'?

To check whether an application is vulnerable, see if any links and forms lack an unpredictable CSRF token. Without such a token, attackers can forge malicious requests. An alternate defense is to require the user to prove they intended to submit the request, either through reauthentication, or some other proof they are a real user (e.g., a CAPTCHA).

Focus on the links and forms that invoke state-changing functions, since those are the most important CSRF targets.

You should check multistep transactions, as they are not inherently immune. Attackers can easily forge a series of requests by using multiple tags or possibly JavaScript.

Note that session cookies, source IP addresses, and other information automatically sent by the browser don’t provide any defense against CSRF since this information is also included in forged requests.

How Do I Prevent 'Cross-Site Request Forgery (CSRF)'?

Preventing CSRF usually requires the inclusion of an unpredictable token in each HTTP request. Such tokens should, at a minimum, be unique per user session.

1. The preferred option is to include the unique token in a hidden field. This causes the value to be sent in the body of the HTTP request, avoiding its inclusion in the URL, which is more prone to exposure.

2. The unique token can also be included in the URL itself, or a URL parameter. However, such placement runs a greater risk that the URL will be exposed to an attacker, thus compromising the secret token.
OWASP’s CSRF Guard can automatically include such tokens in Java EE, .NET, or PHP apps. OWASP’s ESAPI includes methods developers can use to prevent CSRF vulnerabilities.


3. Requiring the user to reauthenticate, or prove they are a user (e.g., via a CAPTCHA) can also protect against CSRF.

A9 - Using Components with Known Vulnerabilities


Components, such as libraries, frameworks, and other software modules, almost always run with full privileges. If a vulnerable component is exploited, such an attack can facilitate serious data loss or server takeover. Applications using components with known vulnerabilities may undermine application defenses and enable a range of possible attacks and impacts.

Am I Vulnerable To 'Using Components with Known Vulnerabilities'?

In theory, it ought to be easy to figure out if you are currently using any vulnerable components or libraries. Unfortunately, vulnerability reports for commercial or open source software do not always specify exactly which versions of a component are vulnerable in a standard, searchable way. Further, not all libraries use an understandable version numbering system. Worst of all, not all vulnerabilities are reported to a central clearinghouse that is easy to search, although sites like CVE and NVD are becoming easier to search.

Determining if you are vulnerable requires searching these databases, as well as keeping abreast of project mailing lists and announcements for anything that might be a vulnerability. If one of your components does have a vulnerability, you should carefully evaluate whether you are actually vulnerable by checking to see if your code uses the part of the component with the vulnerability and whether the flaw could result in an impact you care about.

How Do I Prevent 'Using Components with Known Vulnerabilities'?

One option is not to use components that you didn’t write. But that’s not very realistic.

Most component projects do not create vulnerability patches for old versions. Instead, most simply fix the problem in the next version. So upgrading to these new versions is critical. Software projects should have a process in place to:

1. Identify all components and the versions you are using, including all dependencies. (e.g., theversions plugin).

2. Monitor the security of these components in public databases, project mailing lists, and security mailing lists, and keep them up to date.

3. Establish security policies governing component use, such as requiring certain software development practices, passing security tests, and acceptable licenses.

4. Where appropriate, consider adding security wrappers around components to disable unused functionality and/ or secure weak or vulnerable aspects of the component.

A10-Unvalidated Redirects and Forwards

Web applications frequently redirect and forward users to other pages and websites, and use untrusted data to determine the destination pages. Without proper validation, attackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages.

Am I Vulnerable To 'Unvalidated Redirects and Forwards'?

The best way to find out if an application has any unvalidated redirects or forwards is to:

1. Review the code for all uses of redirect or forward (called a transfer in .NET). For each use, identify if the target URL is included in any parameter values. If so, if the target URL isn’t validated against a whitelist, you are vulnerable.

2. Also, spider the site to see if it generates any redirects (HTTP response codes 300-307, typically 302). Look at the parameters supplied prior to the redirect to see if they appear to be a target URL or a piece of such a URL. If so, change the URL target and observe whether the site redirects to the new target.

3. If code is unavailable, check all parameters to see if they look like part of a redirect or forward URL destination and test those that do.

How Do I Prevent 'Unvalidated Redirects and Forwards'?

Safe use of redirects and forwards can be done in a number of ways:

1. Simply avoid using redirects and forwards.

2. If used, don’t involve user parameters in calculating the destination. This can usually be done.

3. If destination parameters can’t be avoided, ensure that the supplied value is valid, and authorized for the user.
It is recommended that any such destination parameters be a mapping value, rather than the actual URL or portion of the URL, and that server side code translate this mapping to the target URL.
Applications can use ESAPI to override the sendRedirect() method to make sure all redirect destinations are safe.

Avoiding such flaws is extremely important as they are a favorite target of phishers trying to gain the user’s trust.


Be Safe and Keep your Application Safer. Happy Coding !!!




Sunday, 8 July 2018

SQL Server : sp_MSforeachdb : Execute Query in all Databases

Hello Everyone !!!



There are times when you need to run a SQL command against each database on one of my SQL Server instances. There is a handy stored procedure that allows you to do this without needing to set up a cursor against your sysdatabases table in the master database: sp_MSforeachdb.


Syntax:
EXEC sp_MSforeachdb
'Your Command Goes Here'

EXEC sp_msforeachdb 'USE [?]; INSERT INTO #ListOfSPs Select ''?'', Object_Id, Name FROM sys.procedures'


"?" Placeholder:

You'll see the use of the question mark as a placeholder for the database/database name. To reference the database name as a string to be returned in a query, embed it between a double set of single quotation marks. To treat it as a reference to the database object simply use it by itself. It is necessary to set the database for the query to run against, by using the USE ? statement, otherwise the code will execute in the context of the current database, for each database in your SQL instance. If you have 5 databases hosted in the current instance and you were to run the stored procedure code above while in the context of DBx it would execute the T-SQL text of the command 5 times in DB.

sp_MSforeachdb is extremely useful for pulling together metadata about your various SQL databases. We should use it quite frequently for reporting on such important metrics as database file sizes, amount of free space, and backup status.

Happy Coding !!!

SQL Server : To List all Store Procedures in all Databases

Hello Everyone, In this blog, I am telling you to List all Stored Procedures in all Databases (including master, msdb). There may be a situation arise when you are new to some project and there are multiple databases and you have to find a single store procedure. There are many ways but I feel this one is Optimum.

Here is the Script:


Happy Coding !!!

ASP.NET ERROR : System.ServiceModel.CommunicationObjectFaultedException: 'The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.'

This Error happens because a .NET exception has occurred at WCF service server side. Due to this error Communication Object (or Proxy Class)  has been disturbed results in the communication break-down between WCF Service and Client and hence, came to a faulted state.


Things You can do in order to cope with this:

Handle the Exception(Use Try- Catch / Throw an Exception): Don't Catch the Dot Net Exception (there is a reason why you should not use Dot Net Exception: As you are using WCF, whose one of the motto is Interoperability. By using .NET Exception you are sacrificing that).
Use FaultException Instead !!!

If you want to recreate the Communication channel between WCF Service and Client, you just need to instantiate the Proxy Class.

You can check whether the communication is in faulted state or not by :

if(client.InnerChannel.State != System.ServiceModel.CommunicationState.Faulted)
{
   // call service - everything's fine
}
else
{
   // channel faulted - re-create your client and then try again
}

Happy Coding !!! 

ASP.NET ERROR : System.ServiceModel.EndpointNotFoundException: 'There was no endpoint listening at http://localhost:8080/CalculatorService that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.'

For more Details for this Exception, First see the InnerException Details of this Exception, it may be changed for your case. Generally, this Exception occurs because of "The remote server returned an error: (404) Not Found".


There's no endpoint listening: Service is not Running at described Address (in my case, it is http://localhost:8080/ .Be sure Service is up and you can visit the SOAP Document with the URL.

If it is not in Localhost It might be possible that the server is down, you can check if the service is running by visiting the service address with a browser.




ASP.NET Error : System.ServiceModel.AddressAccessDeniedException : 'HTTP could not register URL http://+:8080/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).'

If you are new in WCF, there may be a chance you will be Happily engaged with this error.

As the name says it is an AccessDeniedException, Bottleneck exists in AccessPermission. InnerException property of Exception also says that Access is denied.

There is a Little Trick For this.. 

"You just had to start Your Visual Studio as an Administrator"

Happy Coding !!! 

Tuesday, 3 July 2018

Allocated and Unallocated space on database in SQL Server

We as Developers and DBA's generally need to know the Allocated and Unallocated Space On Database for Future Planning and Troubleshooting the Bottlenecks.

Here is the Script to know the Allocated and Unallocated space on the database in SQL Server :


Enjoy !!!

Find all Columns information(metadata) of a Database in SQL Server

Sometimes we need to List the Metadata Structure of our Database / Tables in SQL Server. It may prove to be a cumbersome task if we will do it manually.

Here is the Script :
Enjoy !!!

Monday, 2 July 2018

Numerous Regular Expressions Stating Password Policy


Here I am Listing some very handy Regular Expressions used for making  Password Policy in Login or sign up form using .NET RegularExpressionValidator. You can also use this in code-behind file as per your convenience.

Here is very good site for making and testing Regular Expression: https://regexr.com/. Check it out !!

SQL Audits

1. sys.server_audits What it is: Lists all server-level audit objects . An audit is the top-level object that defines: Where to wri...