| description | Guidance for developing CodeQL queries targeting Go code |
|---|
This prompt provides guidance for developing CodeQL queries targeting Go code. For common query development patterns and best practices, see query_development.prompt.md.
- Import
gofor Go AST nodes and predicates - Common imports:
Stmt,Expr,Function,Type,Package,File - Use
DataFlowandTaintTrackingfor tracking data flow through Go programs - Import
semmle.go.securityfor security-related predicates
- Start syntactic (AST) for structure; switch to data flow graph (DFG) for semantic flow
- Use
hasQualifiedNamefor stable matching of stdlib/framework APIs - Prefer library predicates over string parsing; rely on classes and accessors
- Keep queries specific and cheap first; generalize after validation
- File Structure:
GoFilefor file nodes - Functions:
FuncDeclfor function declarations,MethodDeclfor methods,FuncLitfor function literals - Types:
StructTypeExpr,ArrayTypeExpr,StarExpr(pointers),FuncTypeExpr - Statements:
IfStmt,ForStmt,SwitchStmt,BlockStmt,ReturnStmt,DefineStmt,AssignStmt,DeferStmt,RangeStmt,IncStmt - Expressions:
CallExpr,SelectorExpr,IndexExpr,AddressExpr,EqlExpr,LssExpr,GtrExpr,MulExpr,NeqExpr - Literals:
StringLit,IntLit,StructLit,SliceLit - Declarations:
ImportDecl,TypeDecl,FieldDecl,ParameterDecl,ReceiverDecl,ResultVariableDecl - Identifiers:
Identwith roles likeFunctionName,VariableName,TypeName,PackageName,ConstantName
- Use
getType()to get the type of an expression - Check interface satisfaction with
implements() - Navigate pointer types with
getBaseType() - Check for built-in types:
isString(),isNumeric(), etc.
- Function calls:
call.getTarget().hasName("functionName")wherecallis aCallExpr - Method calls: Use
SelectorExprfor method access, thenCallExprfor invocation - Package imports: Navigate
ImportDeclandImportSpecfor import analysis - Struct operations:
StructLitfor literals,FieldDeclfor field declarations - Array/slice operations:
SliceLit,ArrayTypeExpr,IndexExprfor array access - Assignment operations:
AssignStmtandDefineStmtfor variable assignments - Control flow:
IfStmt,ForStmt,RangeStmtfor iteration patterns - Defer statements:
DeferStmtfor cleanup patterns - Error handling: Look for patterns with
if err != nilusing comparison expressions
- Use
DataFlow::Nodefor nodes in the data flow graph TaintTracking::Configurationfor taint analysis- Track through function calls with
allowImplicitRead() - Handle Go-specific flow: channels, goroutines, interfaces
- Consider pointer aliasing and escape analysis
- Command injection:
os/exec.Command(),os/exec.CommandContext() - SQL injection: Database query methods with user input
- Path traversal:
os.Open(),ioutil.ReadFile()with unsanitized paths - Unsafe reflection:
reflectpackage misuse - Goroutine leaks: Unbounded goroutine creation
- Race conditions: Shared memory access without synchronization
- Improper error handling: Ignored errors, information leakage
- Unsafe pointer operations:
unsafepackage usage - Cryptographic issues: Weak random number generation, deprecated crypto
- Error handling: Check for proper error checking patterns
- Context usage: Verify context propagation in concurrent code
- Resource cleanup: Ensure proper use of
deferstatements - Type assertions: Check for unsafe type assertions without ok checks
- Nil pointer dereference: Check for nil checks before dereference
- Slice bounds: Check for slice out-of-bounds access
- Channel operations: Deadlocks, channel leaks, nil channel operations
- Interface{} usage: Type safety with empty interfaces
- Go Module Setup: Test databases require a
go.modfile in the test directory for proper extraction - QLT Limitations: The QLT scaffolding tool doesn't support Go; create directory structure manually
- Test File Structure: Follow pattern:
test/{QueryName}/{QueryName}.go,{QueryName}.expected,{QueryName}.qlref - qlref Paths: Use simple paths like
QueryName/QueryName.qlin .qlref files, not relative paths with.. - Search Paths: Include
--search-path=path/to/srcwhen running tests to resolve query references - Expected Results: Include full location info:
| file.go:line:col:line:col | element | message |
- HTTP handlers:
http.HandlerFunc,http.Handlerinterface - JSON operations:
json.Marshal(),json.Unmarshal() - File operations:
ospackage,io/ioutilpatterns - String operations:
stringspackage functions - Time operations:
timepackage, duration handling - Crypto operations:
crypto/*package usage
- Go AST Classes - Comprehensive AST navigation guide
- Go Security Query Guide - Security patterns and vulnerability detection
- Go Data Flow Analysis - Local and global data flow tracking
- Go Library Modeling - Customizing library models with YAML
- Go Basic Query Examples - Practical query examples and patterns
- qlt query generate new-query - Generate scaffolding for a new CodeQL query with packs and tests
- codeql query format
- codeql query compile
- codeql query run
- codeql test run