codeql icon indicating copy to clipboard operation
codeql copied to clipboard

CodeQL Csharp query help

Open sunhere opened this issue 1 year ago • 3 comments
trafficstars

I am new to CodeQL. Here is the scenario I have.

I am trying to retrieve the parameters of all public methods in a controller class. if the parameter type is not primitive then it should get the result as is, however if the param is ref type, then it has to get all the fields of the ref type. I was able to get all the parameters, however not able to retrieve the fields of the ref type. I have been trying with a recursive function, not successful. can someone please help me with the query. below is the query:

 import csharp

 class Controller extends Class {
   Controller() {
     this.getName().matches("%VaultController")
   }
 }

 from Controller c, Method m, Parameter p
 where 
   m.getDeclaringType() = c and 
   m.hasModifier("public") and 
   p.getCallable() = m 
   select c.getName(), m.getName(), p.getType().getName()

sunhere avatar Oct 09 '24 20:10 sunhere

👋 @sunhere

You might want to look at Type.qll, and in particular at ValueOrRefType.

  • You can use exists(RefType t | t = p.getType() and ...) or p.getType().(RefType) to cover the reference type case, and not p.getType() instanceof RefType to cover the rest of cases
  • If you just need the direct (non-inherited) fields of such a type, you can use t.getAField()
  • if you also need inherited fields, you can go for exists(Field f | t.hasMember(f) and ...)

Let us know if you need any more pointers 🤗

redsun82 avatar Oct 10 '24 07:10 redsun82

Hi, Thank you for the response. the below code only gets me string types and not any object type. could you tell me where is the issue? Thanks

import csharp
class Controller extends Class {
  Controller() {
    this.getName().matches("%VaultController")
  }
}

from Controller c, Method m, Parameter p, Field f//string fieldName
where
m.getDeclaringType() = c and
m.hasModifier("public") and
p = m.getAParameter() and
f = p.getType().(RefType).getAField() 
select c.getName(), m.getName(), p.getType().getName() + " " + p.getName(), " field: " + f.getType().getName() + " " + f.getName()

sunhere avatar Oct 10 '24 19:10 sunhere

Hi @sunhere, could you provide some snippets of the C# code exhibiting your issue? I tested the query locally and it seems to do what's expected, but the actual code might be important.

redsun82 avatar Oct 11 '24 07:10 redsun82

This issue is stale because it has been open 14 days with no activity. Comment or remove the Stale label in order to avoid having this issue closed in 7 days.

github-actions[bot] avatar Oct 26 '24 01:10 github-actions[bot]

This issue was closed because it has been inactive for 7 days.

github-actions[bot] avatar Nov 02 '24 01:11 github-actions[bot]