Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d05109d

Browse files
committed
C#: Update queries in Bad Practices/Implementation Hiding
1 parent 3c0f04a commit d05109d

41 files changed

Lines changed: 590 additions & 337 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

change-notes/1.18/analysis-csharp.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
| **Query** | **Tags** | **Purpose** |
1717
|-----------------------------|-----------|--------------------------------------------------------------------|
18+
| [Exposing internal representation (cs/expose-implementation)] | Different results | The query has been rewritten, based on the equivalent Java query. |
1819
| Local scope variable shadows member (cs/local-shadows-member) | maintainability, readability | Replaces the existing queries [Local variable shadows class member (cs/local-shadows-class-member)](https://help.semmle.com/wiki/display/CSHARP/Local+variable+shadows+class+member), [Local variable shadows struct member (cs/local-shadows-struct-member)](https://help.semmle.com/wiki/display/CSHARP/Local+variable+shadows+struct+member), [Parameter shadows class member (cs/parameter-shadows-class-member)](https://help.semmle.com/wiki/display/CSHARP/Parameter+shadows+class+member), and [Parameter shadows struct member (cs/parameter-shadows-struct-member)](https://help.semmle.com/wiki/display/CSHARP/Parameter+shadows+struct+member). |
1920

2021
## Changes to existing queries

csharp/ql/src/Bad Practices/Implementation Hiding/AbstractToConcreteCollection.cs

Lines changed: 0 additions & 10 deletions
This file was deleted.

csharp/ql/src/Bad Practices/Implementation Hiding/AbstractToConcreteCollection.qhelp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ more difficult to change which implementation you are using at a later date.</p>
1212

1313
</recommendation>
1414
<example>
15-
<p>The example shows casting from an ICollection to a List. This should be avoided where possible.</p>
16-
<sample src="AbstractToConcreteCollection.cs" />
15+
<p>The example shows casting from an <code>IEnumerable&lt;string&gt;</code> to a <code>List&lt;string&gt;</code>. This should be avoided where possible.</p>
16+
<sample src="AbstractToConcreteCollectionBad.cs" />
1717

1818
</example>
1919
<references>
Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
/**
22
* @name Cast from abstract to concrete collection
3-
* @description Finds casts from an abstract collection to a concrete implementation
4-
* type. This makes the code brittle; it is best to program against the
5-
* abstract collection interfaces only.
3+
* @description A cast from an abstract collection to a concrete implementation type
4+
* makes the code brittle; it is best to program against the abstract
5+
* collection interface only.
66
* @kind problem
77
* @problem.severity warning
88
* @precision medium
@@ -13,20 +13,25 @@
1313
* external/cwe/cwe-485
1414
*/
1515
import csharp
16+
import semmle.code.csharp.frameworks.system.Collections
17+
import semmle.code.csharp.frameworks.system.collections.Generic
1618

17-
/** A sub-interface of Collection */
19+
/** A collection interface. */
1820
class CollectionInterface extends Interface {
1921
CollectionInterface() {
20-
exists(string name |
21-
this.getSourceDeclaration().getABaseType*().getName() = name and
22-
( name.matches("ICollection<%>")
23-
or name="ICollection")
22+
exists(Interface i |
23+
i = this.getABaseInterface*() |
24+
i instanceof SystemCollectionsICollectionInterface or
25+
i.getSourceDeclaration() instanceof SystemCollectionsGenericICollectionInterface or
26+
i instanceof SystemCollectionsIEnumerableInterface or
27+
i.getSourceDeclaration() instanceof SystemCollectionsGenericIEnumerableTInterface
2428
)
2529
}
2630
}
2731

2832
from CastExpr e, Class c, CollectionInterface i
29-
where e.getType() = c and
30-
e.getExpr().getType().(RefType).getSourceDeclaration() = i
31-
select e, "Questionable cast from abstract " + i.getName()
32-
+ " to concrete implementation " + c.getName() + "."
33+
where e.getType() = c
34+
and e.getExpr().getType() = i
35+
and c.isImplicitlyConvertibleTo(i)
36+
select e, "Questionable cast from abstract '" + i.getName()
37+
+ "' to concrete implementation '" + c.getName() + "'."
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
using System.Collections.Generic;
2+
3+
class Bad
4+
{
5+
public static void Main(string[] args)
6+
{
7+
var names = GetNames();
8+
var list = (List<string>) names;
9+
list.Add("Eve");
10+
}
11+
12+
static IEnumerable<string> GetNames()
13+
{
14+
var ret = new List<string>()
15+
{
16+
"Alice",
17+
"Bob"
18+
};
19+
return ret;
20+
}
21+
}

csharp/ql/src/Bad Practices/Implementation Hiding/ExposeRepresentation.cs

Lines changed: 0 additions & 27 deletions
This file was deleted.

csharp/ql/src/Bad Practices/Implementation Hiding/ExposeRepresentation.qhelp

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,25 +19,25 @@ fields will not be affected.</p>
1919
</recommendation>
2020
<example>
2121
<p>This example clearly demonstrates the problem with passing references to mutable objects outside a class. In this case
22-
it was possible to modify the values in the array despite the Range class not offering any method to do so.</p>
23-
<sample src="ExposeRepresentation.cs" />
22+
it was possible to modify the values in the array despite the <code>Range</code> class not offering any method to do so.</p>
23+
<sample src="ExposeRepresentationBad.cs" />
2424

2525
</example>
26-
<section title="Fixing With an Immutable Object">
26+
<section title="Fixing with an immutable object">
2727
<p>Here the example has been modified to prevent changes to the private field by using a <code>ReadOnlyCollection</code>
2828
object.</p>
29-
<sample src="ExposeRepresentationFix1.cs" />
29+
<sample src="ExposeRepresentationGood1.cs" />
3030

3131
</section>
32-
<section title="Fixing With Defensive Copying">
32+
<section title="Fixing with defensive copying">
3333
<p>This is an example of the same class but this time it returns a defensive copy of the private field. There is also
3434
a short program showing what happens when an attempt is made to modify the data held by the field.</p>
35-
<sample src="ExposeRepresentationFix2.cs" />
35+
<sample src="ExposeRepresentationGood2.cs" />
3636

3737
</section>
3838
<references>
3939

40-
<li>MSDN, C# Programming Guide, <a href="http://msdn.microsoft.com/en-us/library/vstudio/2z4khca9.aspx">Arrays as Objects</a>.</li>
40+
<li>MSDN, C# Programming Guide, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/arrays-as-objects">Arrays as Objects</a>.</li>
4141
<li>MSDN, <a href="http://msdn.microsoft.com/en-us/library/ms132474.aspx">ReadOnlyCollection&lt;T&gt;</a>.</li>
4242

4343
</references>
Lines changed: 73 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,82 @@
11
/**
2-
* @name Exposes internal representation
3-
* @description Finds code that may expose an object's internal representation by
4-
* incorporating reference to mutable object.
2+
* @name Exposing internal representation
3+
* @description An object that accidentally exposes its internal representation may allow the
4+
* object's fields to be modified in ways that the object is not prepared to handle.
55
* @kind problem
66
* @problem.severity recommendation
7-
* @precision medium
7+
* @precision high
88
* @id cs/expose-implementation
99
* @tags reliability
1010
* external/cwe/cwe-485
1111
*/
1212
import csharp
13+
import semmle.code.csharp.commons.Collections
14+
import DataFlow
1315

14-
/* This code stores a reference to an externally mutable object into the internal
15-
representation of the object.
16-
If instances are accessed by untrusted code, and unchecked changes to the mutable
17-
object would compromise security or other important properties,
18-
you will need to do something different. Storing a copy of the object is better
19-
approach in many situations.
20-
21-
In this analysis an object is considered mutable if it is an array, a
22-
java.util.Hashtable, or a java.util.Date.
23-
The analysis detects stores to fields of these types where the value is given as a
24-
parameter. */
25-
26-
from Assignment a, Field f, VariableAccess va, RefType t
27-
where a.getLValue() = va and
28-
va.getTarget() = f and
29-
f.getType().(RefType).getSourceDeclaration() = t and
30-
( (va.(MemberAccess).hasQualifier() and
31-
va.(MemberAccess).getQualifier() instanceof ThisAccess)
32-
or not va.(MemberAccess).hasQualifier()) and
33-
a.getRValue().(VariableAccess).getTarget() instanceof Parameter and
34-
( t instanceof ArrayType
35-
//Add mutable types here as necessary. Kept the java types as a reference
36-
/*or t.hasQualifiedName("java.util", "Hashtable")
37-
or t.hasQualifiedName("java.util", "Date")*/)
38-
select a,
39-
"May expose internal representation by storing an externally mutable object in "
40-
+ f.getName() + "."
16+
predicate storesCollection(Callable c, Parameter p, Field f) {
17+
f.getDeclaringType() = c.getDeclaringType().getABaseType*().getSourceDeclaration() and
18+
f.getType() instanceof CollectionType and
19+
p = c.getAParameter() and
20+
f.getAnAssignedValue() = p.getAnAccess() and
21+
not c.(Modifiable).isStatic()
22+
}
23+
24+
predicate returnsCollection(Callable c, Field f) {
25+
f.getDeclaringType() = c.getDeclaringType().getABaseType*().getSourceDeclaration() and
26+
f.getType() instanceof CollectionType and
27+
c.canReturn(f.getAnAccess()) and
28+
not c.(Modifiable).isStatic()
29+
}
30+
31+
predicate mayWriteToCollection(Expr modified) {
32+
modified instanceof CollectionModificationAccess
33+
or
34+
exists(Expr mid |
35+
mayWriteToCollection(mid) |
36+
localFlow(exprNode(modified), exprNode(mid))
37+
)
38+
or
39+
exists(MethodCall mid, Callable c |
40+
mayWriteToCollection(mid) |
41+
mid.getTarget() = c and
42+
c.canReturn(modified)
43+
)
44+
}
45+
46+
predicate modificationAfter(Expr before, Expr after) {
47+
mayWriteToCollection(after) and
48+
localFlowStep+(exprNode(before), exprNode(after))
49+
}
50+
51+
VariableAccess varPassedInto(Callable c, Parameter p) {
52+
exists(Call call |
53+
call.getTarget() = c |
54+
call.getArgumentForParameter(p) = result
55+
)
56+
}
57+
58+
predicate exposesByReturn(Callable c, Field f, Expr why, string whyText) {
59+
returnsCollection(c, f) and
60+
exists(MethodCall ma |
61+
ma.getTarget() = c |
62+
mayWriteToCollection(ma) and
63+
why = ma and
64+
whyText = "after this call to " + c.getName()
65+
)
66+
}
67+
68+
predicate exposesByStore(Callable c, Field f, Expr why, string whyText) {
69+
exists(VariableAccess v, Parameter p |
70+
storesCollection(c, p, f) and
71+
v = varPassedInto(c, p) and
72+
modificationAfter(v, why) and
73+
whyText = "through the variable " + v.getTarget().getName()
74+
)
75+
}
76+
77+
from Callable c, Field f, Expr why, string whyText
78+
where exposesByReturn(c, f, why, whyText) or
79+
exposesByStore(c, f, why, whyText)
80+
select c, "'" + c.getName() + "' exposes the internal representation stored in field '" + f.getName() +
81+
"'. The value may be modified $@.",
82+
why.getLocation(), whyText
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
using System;
2+
3+
class Bad
4+
{
5+
class Range
6+
{
7+
private int[] rarray = new int[2];
8+
9+
public Range(int min, int max)
10+
{
11+
if (min <= max)
12+
{
13+
rarray[0] = min;
14+
rarray[1] = max;
15+
}
16+
}
17+
18+
public int[] Get() => rarray;
19+
}
20+
21+
public static void Main(string[] args)
22+
{
23+
var r = new Range(1, 10);
24+
var r_range = r.Get();
25+
r_range[0] = 500;
26+
Console.WriteLine("Min: " + r.Get()[0] + " Max: " + r.Get()[1]);
27+
// prints "Min: 500 Max: 10"
28+
}
29+
}

csharp/ql/src/Bad Practices/Implementation Hiding/ExposeRepresentationFix1.cs

Lines changed: 0 additions & 20 deletions
This file was deleted.

0 commit comments

Comments
 (0)