CodeQL queries 1.25
Skip to end of metadata
Go to start of metadata

Name: Deserialized delegate

Description: Deserializing a delegate allows for remote code execution when an attacker can control the serialized data.

ID: cs/deserialized-delegate

Kind: problem

Severity: warning

Precision: high

Query: DeserializedDelegate.ql
/**
 * @name Deserialized delegate
 * @description Deserializing a delegate allows for remote code execution when an
 *              attacker can control the serialized data.
 * @kind problem
 * @id cs/deserialized-delegate
 * @problem.severity warning
 * @precision high
 * @tags security
 *       external/cwe/cwe-502
 */

import csharp
import semmle.code.csharp.frameworks.system.linq.Expressions
import semmle.code.csharp.serialization.Deserializers

from Call deserialization, Cast cast
where
  deserialization.getTarget() instanceof UnsafeDeserializer and
  cast.getExpr() = deserialization and
  cast.getTargetType() instanceof SystemLinqExpressions::DelegateExtType
select deserialization, "Deserialization of delegate type."

Deserializing a delegate object may result in remote code execution, when an attacker can control the serialized data.

Recommendation

Avoid deserializing delegate objects, if possible, or make sure that the serialized data cannot be controlled by an attacker.

Example

In this example, a file stream is deserialized to a Func<int> object, using a BinaryFormatter. The file stream is a parameter of a public method, so depending on the calls to InvokeSerialized, this may or may not pose a security problem.

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

class Bad
{
    public static int InvokeSerialized(FileStream fs)
    {
        var formatter = new BinaryFormatter();
        // BAD
        var f = (Func<int>)formatter.Deserialize(fs);
        return f();
    }
}

References