CodeQL queries 1.24

Skip to end of metadata
Go to start of metadata

Name: Insecure SQL connection

Description: Using an SQL Server connection without enforcing encryption is a security vulnerability.

ID: cs/insecure-sql-connection

Kind: path-problem

Severity: error

Query: InsecureSQLConnection.ql
/**
 * @name Insecure SQL connection
 * @description Using an SQL Server connection without enforcing encryption is a security vulnerability.
 * @kind path-problem
 * @id cs/insecure-sql-connection
 * @problem.severity error
 * @tags security
 *       external/cwe/cwe-327
 */

/*
 * consider: @precision high
 */

import csharp
import DataFlow::PathGraph

/**
 * A `DataFlow::Configuration` for tracking `Strings passed to SqlConnectionStringBuilder` instances.
 */
class TaintTrackingConfiguration extends TaintTracking::Configuration {
  TaintTrackingConfiguration() { this = "TaintTrackingConfiguration" }

  override predicate isSource(DataFlow::Node source) {
    exists(string s | s = source.asExpr().(StringLiteral).getValue().toLowerCase() |
      s.matches("%encrypt=false%")
      or
      not s.matches("%encrypt=%")
    )
  }

  override predicate isSink(DataFlow::Node sink) {
    exists(ObjectCreation oc |
      oc.getRuntimeArgument(0) = sink.asExpr() and
      (
        oc.getType().getName() = "SqlConnectionStringBuilder"
        or
        oc.getType().getName() = "SqlConnection"
      )
    )
  }
}

from TaintTrackingConfiguration c, DataFlow::PathNode source, DataFlow::PathNode sink
where c.hasFlowPath(source, sink)
select sink.getNode(), source, sink, "$@ flows to here and does not specify `Encrypt=True`.",
  source.getNode(), "Connection string"

SQL Server connections where the client is not enforcing the encryption in transit are susceptible to multiple attacks, including a man-in-the-middle, that would potentially compromise the user credentials and/or the TDS session.

Recommendation

Ensure that the client code enforces the Encrypt option by setting it to true in the connection string.

Example

The following example shows a SQL connection string that is not explicitly enabling the Encrypt setting to force encryption.

using System.Data.SqlClient;

// BAD, Encrypt not specified
string connectString =
    "Server=1.2.3.4;Database=Anything;Integrated Security=true;";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);
var conn = new SqlConnection(builder.ConnectionString);

The following example shows a SQL connection string that is explicitly enabling the Encrypt setting to force encryption in transit.

using System.Data.SqlClient;

string connectString =
    "Server=1.2.3.4;Database=Anything;Integrated Security=true;;Encrypt=true;";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);
var conn = new SqlConnection(builder.ConnectionString);

References