### Start Joern Server Source: https://docs.joern.io/server Spawns the Joern server. This is the most basic way to start the server. ```bash joern --server ``` -------------------------------- ### Install and Test Sample Plugin Source: https://docs.joern.io/extensions Steps to clone, install, and test the sample Joern plugin, including setting up a local Joern instance. ```bash git clone https://github.com/joernio/sample-plugin.git cd sample-plugin ./install.sh ``` ```bash ./joern ``` ```bash run ``` -------------------------------- ### Install Joern CLI using pre-built binaries Source: https://docs.joern.io/installation Download and run the interactive installer script to set up the Joern CLI. This is the recommended method for most users. ```shell mkdir joern && cd joern # optional curl -L "https://github.com/joernio/joern/releases/latest/download/joern-install.sh" -o joern-install.sh chmod u+x joern-install.sh ./joern-install.sh --interactive ``` -------------------------------- ### Example JVM configuration for 30GB RAM Source: https://docs.joern.io/installation An example of setting the maximum JVM heap memory to 30 gigabytes. ```shell ./joern -J-Xmx30G ``` -------------------------------- ### Verify Joern CLI installation Source: https://docs.joern.io/installation Execute the Joern CLI to confirm that the installation was successful and the program is running. ```shell cd /joern/joern-cli ./joern ``` -------------------------------- ### Start Joern with JVM Heap Size Source: https://docs.joern.io/traversal-basics Start the Joern shell with a specified JVM heap size, recommended to be 4GB for larger projects. ```bash $ JAVA_OPTS='-Xmx4g' joern ``` -------------------------------- ### List Installed Joern Plugins Source: https://docs.joern.io/extensions Use this command to view all plugins currently installed in your Joern environment. ```bash joern --plugins ``` -------------------------------- ### Install coreutils for macOS build Source: https://docs.joern.io/installation Install the coreutils package using Homebrew, which is a prerequisite for building Joern from source on macOS. ```shell brew install coreutils ``` -------------------------------- ### Joern Script Example Source: https://docs.joern.io/interpreter Example of a Joern script defining a main function to import a CPG and export method names to a file. ```scala @main def exec(cpgFile: String, outFile: String) = { importCpg(cpgFile) cpg.method.name #> outFile } ``` -------------------------------- ### Build Joern CLI from source Source: https://docs.joern.io/installation Clone the Joern repository and use sbt to build the CLI. This method requires sbt to be installed. ```shell git clone https://github.com/joernio/joern.git cd joern sbt stage ``` -------------------------------- ### Start Joern Server with Basic Authentication Source: https://docs.joern.io/server Spawns the Joern server with basic HTTP authentication enabled. Replace 'username' and 'password' with your credentials. ```bash joern --server --server-auth-username username --server-auth-password password ``` -------------------------------- ### Add a New Joern Plugin Source: https://docs.joern.io/extensions Install a new plugin by providing the path to its zip file. ```bash joern --add-plugin ``` -------------------------------- ### Example: javasrc2cpg show-env argument Source: https://docs.joern.io/frontends/java Prints environment information used by javasrc2cpg and exits Joern. ```bash --show-env ``` -------------------------------- ### Example: javasrc2cpg fetch-dependencies argument Source: https://docs.joern.io/frontends/java Use this argument to attempt fetching dependency JARs for additional type information. ```bash --fetch-dependencies ``` -------------------------------- ### Example: javasrc2cpg delombok-java-home argument Source: https://docs.joern.io/frontends/java Optionally override the Java home directory used to run Delombok. Java 17 is recommended. ```bash --delombok-java-home /path/to/home ``` -------------------------------- ### Using the help command for CPG details Source: https://docs.joern.io/quickstart The `help.cpg` command provides a detailed explanation of the `cpg` object and its role as the root of the query language. It also gives examples of common queries. ```joern joern> help.cpg res3: String = """ Upon importing code, a project is created that holds an intermediate representation called `Code Property Graph`. This graph is a composition of low-level program representations such as abstract syntax trees and control flow graphs, but it can be arbitrarily extended to hold any information relevant in your audit, information about HTTP entry points, IO routines, information flows, or locations of vulnerable code. Think of Joern as a CPG editor. In practice, `cpg` is the root object of the query language, that is, all query language constructs can be invoked starting from `cpg`. For exanple, `cpg.method.l` lists all methods, while `cpg.finding.l` lists all findings of potentially vulnerable code.""" ``` -------------------------------- ### Execute Code on Startup with Joern Source: https://docs.joern.io/interpreter Command to run a Joern script and execute individual Scala statements before the script starts using `--runBefore`. ```bash ./joern --script test.sc --param cpgFile=src.path.zip --param outFile=output.log --runBefore 'val bar = 41' --runBefore 'val foo = bar' ``` -------------------------------- ### X42 C Program Example Source: https://docs.joern.io/quickstart This C program demonstrates conditional output to standard error and exit codes. ```c // X42.c #include #include #include int main(int argc, char *argv[]) { if (argc > 1 && strcmp(argv[1], "42") == 0) { fprintf(stderr, "It depends!\n"); exit(42); } printf("What is the meaning of life?\n"); exit(0); } ``` -------------------------------- ### Overview of Top-Level Commands Source: https://docs.joern.io/cpgql/help-directive When executed by itself, the `help` directive displays an overview of all available top-level commands, including their descriptions and examples. Use `help.` for more detailed help. ```text joern> help val res0: Helper = Welcome to the interactive help system. Below you find a table of all available top-level commands. To get more detailed help on a specific command, just type `help.`. Try `help.importCode` to begin with. ┌────────────────┬────────────────────────────────────────────────┬─────────────────────────┐ │command │description │example │ ├────────────────┼────────────────────────────────────────────────┼─────────────────────────┤ │close │Close project by name │close(projectName) │ │cpg │CPG of the active project │cpg.method.l │ │delete │Close and remove project from disk │delete(projectName) │ │exit │Exit the REPL │ │ │importCode │Create new project from code │importCode("example.jar")│ │importCpg │Create new project from existing CPG │importCpg("cpg.bin.zip") │ │open │Open project by name │open("projectName") │ │openForInputPath│Open project for input path │ │ │project │Currently active project │project │ │run │Run analyzer on active CPG │run.securityprofile │ │save │Write all changes to disk │save │ │switchWorkspace │Close current workspace and open a different one│ │ │workspace │Access to the workspace directory │workspace │ └────────────────┴────────────────────────────────────────────────┴─────────────────────────┘ ``` -------------------------------- ### Start Joern Server with Custom Host and Port Source: https://docs.joern.io/server Spawns the Joern server, specifying the hostname and port for the HTTP API. This allows for custom network configurations. ```bash joern --server --server-host localhost --server-port 8081 ``` -------------------------------- ### Launch Joern Interactive Shell Source: https://docs.joern.io/shell Start the Joern interactive shell by executing the 'joern' command in your terminal. ```shell $ joern ``` -------------------------------- ### Example: javasrc2cpg enable-type-recovery argument Source: https://docs.joern.io/frontends/java Enables generic type recovery for improved type analysis. ```bash --enable-type-recovery ``` -------------------------------- ### Example: javasrc2cpg cache-jdk-type-solver argument Source: https://docs.joern.io/frontends/java Enables re-using the JDK type solver between scans to improve performance. ```bash --cache-jdk-type-solver ``` -------------------------------- ### Create CPG and import into Joern Source: https://docs.joern.io/installation Example of creating a CPG for a Linux kernel codebase using c2cpg.sh and then importing the generated CPG into Joern. ```shell ./c2cpg.sh -J-Xmx30G -o linux-full.odb /home/mp/tmp/cpgtesting/linux-kernel/linux-4.1.16 ./joern -J-Xmx100G joern> importCpg("linux-full.odb") ``` -------------------------------- ### Example: javasrc2cpg inference-jar-paths argument Source: https://docs.joern.io/frontends/java Use this argument to specify paths to extra JAR files for type information. ```bash --inference-jar-paths "/path/ex1.jar, /path/ex2.jar" ``` -------------------------------- ### Help for a Specific Top-Level Command Source: https://docs.joern.io/cpgql/help-directive To get detailed help for a specific top-level command, prefix it with `help.`. This returns a string containing the command's description and return value information. ```text joern> help.save res0: String = """ Close and reopen all loaded CPGs. This ensures that changes have been flushed to disk. Returns list of affected projects""" ``` -------------------------------- ### Example of Regex Matching for Method Names Source: https://docs.joern.io/dataflow-semantics Demonstrates using a regex to match method names when the full name is not precisely known, useful for dynamic languages. ```scala val extraFlows = List( FlowSemantic.from( "^path.*\.sanitizer$", // Method full name List((1, 1)), // Flow mappings regex = true // Interpret the method full name as a regex string ) ) val context = new LayerCreatorContext(cpg) val options = new OssDataFlowOptions(semantics = DefaultSemantics().plus(extraFlows)) new OssDataFlow(options).run(context) ``` -------------------------------- ### Build Shippable Joern Plugin Distribution Source: https://docs.joern.io/extensions Command to create a distributable zip file for your Joern plugin, ready for installation. ```bash sbt createDistribution ``` -------------------------------- ### Example: javasrc2cpg type-prop-iterations argument Source: https://docs.joern.io/frontends/java Sets the maximum number of iterations for type propagation. ```bash --type-prop-iterations 2 ``` -------------------------------- ### Example: javasrc2cpg delombok-mode argument Source: https://docs.joern.io/frontends/java Specifies the execution mode for Delombok. Options include 'no-delombok', 'default', 'types-only', and 'run-delombok'. ```bash --delombok-mode no-delombok ``` -------------------------------- ### Example: javasrc2cpg dump-javaparser-asts argument Source: https://docs.joern.io/frontends/java Dumps the javaparser ASTs for input files and exits Joern. Useful for debugging. ```bash --dump-javaparser-asts ``` -------------------------------- ### Add Dependencies in build.sbt Source: https://docs.joern.io/extensions Example of how to add external libraries, such as JGit and ScalaTest, to your plugin's build configuration. ```scala // build.sbt name := "joern-sample-extension" ThisBuild/organization := "io.joern" ThisBuild/scalaVersion := "2.13.0" ... libraryDependencies ++= Seq( // Add your dependencies here "org.eclipse.jgit" % "org.eclipse.jgit" % "5.7.0.202003110725-r", // ... "org.scalatest" %% "scalatest" % "3.1.1" % Test ) ... ``` -------------------------------- ### Example: javasrc2cpg jdk-path argument Source: https://docs.joern.io/frontends/java Specifies the JDK path for resolving built-in Java types. If not set, the current classpath is used. ```bash --jdk-path /path/to/jdk ``` -------------------------------- ### Chaining `filter` Steps Source: https://docs.joern.io/cpgql/filter-steps Shows chaining multiple `filter` steps to apply sequential criteria. This example first filters by name and then by code content. ```scala joern> cpg.call.filter(node => node.name == "exit").filter(node => node.code.contains("42")).code.l res0: List[String] = List("exit(42)") ``` -------------------------------- ### Get Active Joern Project Source: https://docs.joern.io/organizing-projects Use the `project` command to identify the currently active Joern Project in the Joern Shell session. ```scala joern> project res4: io.shiftleft.repl.JoernProject = Project( ProjectFile("/home/user/x42/c", "x42-c"), /home/user/.shiftleft/joern/workspace/x42-c, Some(io.shiftleft.codepropertygraph.Cpg@28ce038d) ) ``` -------------------------------- ### Find nodes post-dominating a call Source: https://docs.joern.io/cpgql/control-flow-steps Use the `postDominatedBy` step to find all nodes by which the preceding node is post-dominated. This example finds nodes post-dominating the `exit(42)` call. ```joern joern> cpg.call.codeExact("exit(42)").postDominatedBy.code.l res0: List[String] = List( "RET", "exit(0)", "0", "printf(\"What is the meaning of life?\\n\")", "\"What is the meaning of life?\\n\"" ) ``` -------------------------------- ### Find nodes controlled by a call Source: https://docs.joern.io/cpgql/control-flow-steps Use the `controls` step to find all nodes that are controlled by a preceding node. This example finds nodes controlled by a call related to `argc` and `strcmp`. ```joern joern> cpg.call.code(".*argc.*strcmp.*").controls.code.l res0: List[String] = List( "fprintf(stderr, \"It depends!\\n"))", "stderr", "\"It depends!\\n\"", "exit(42)", "42" ) ``` -------------------------------- ### C Program with a Dangerous Function Source: https://docs.joern.io/scan This C program demonstrates the use of the 'gets' function, which is known to be dangerous due to potential buffer overflows. It is used as an example for Joern Scan. ```c #include int main () { char str[50]; printf("Enter a string : "); gets(str); printf("You entered: %s", str); return(0); } ``` -------------------------------- ### Chaining Property Filter Steps Source: https://docs.joern.io/cpgql/filter-steps Shows how to chain property filter steps to further refine results. This example filters for CALL nodes named 'exit' and whose CODE property contains '0'. ```scala joern> cpg.call.name("exit").code(".*0.*\").code.l res0: List[String] = List("exit(0)") ``` -------------------------------- ### Find nodes post-dominated by a call Source: https://docs.joern.io/cpgql/control-flow-steps Use the `postDominates` step to find all nodes that are post-dominated by the preceding node. This example finds nodes post-dominated by a call related to `argc` and `strcmp`. ```joern joern> cpg.call.code(".*argc.*strcmp.*").postDominates.code.l res0: List[String] = List( "argv", "1", "argv[1]", "\"42\"", "strcmp(argv[1], \"42\")", "0", "main (int argc,char *argv[])", "argc", "1", "argc > 1", "strcmp(argv[1], \"42\") == 0" ) ``` -------------------------------- ### Find nodes dominating a call Source: https://docs.joern.io/cpgql/control-flow-steps Use the `dominatedBy` step to find all nodes by which the preceding node is dominated. This example finds nodes dominating the `exit(42)` call. ```joern joern> cpg.call.codeExact("exit(42)").dominatedBy.code.l res0: List[String] = List( "main (int argc,char *argv[])", "argc", "1", "argc > 1", "argc > 1 && strcmp(argv[1], \"42\") == 0", "stderr", "\"It depends!\\n\"", "fprintf(stderr, \"It depends!\\n"))", "42" ) ``` -------------------------------- ### Available Starter Steps in CPGQL Traversal Source: https://docs.joern.io/cpgql/help-directive When `help` is used as part of a traversal (e.g., `cpg.help`), it lists the available starter steps from the current node type. This provides context-sensitive guidance for building queries. ```text joern> cpg.help "Available starter steps: ┌─────────────────┬───────────────────────────────────────────────────────────────────────────────────────────────────┐ │step │description │ ├────────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────┤ │.all │All nodes of the graph │ │.argument │All arguments (actual parameters) │ │.arithmetic │All arithmetic operations, including shorthand assignments that perform arithmetic (e.g., '+=') │ │.arrayAccess │All array accesses │ │.assignment │All assignments, including shorthand assignments that perform arithmetic (e.g., '+=') │ ... ``` -------------------------------- ### Execute Traversal and Return Pretty-Printed JSON String Source: https://docs.joern.io/cpgql/execution-directives Use `toJsonPretty` to execute a CPG traversal and get the results as a human-readable, pretty-printed JSON string. This is ideal for debugging and detailed analysis. ```joern joern> cpg.call.name.toJsonPretty res29: String = """[ \"exit\", \"printf\", \"exit\", \"fprintf\", \".indirectIndexAccess\", \"strcmp\", \".equals\", \".greaterThan\", \".logicalAnd\" ]""" ``` -------------------------------- ### Query Call Nodes with Regex Name Source: https://docs.joern.io/cpgql/filter-steps Demonstrates using regular expressions with the `name` property filter step to match 'exit' variations. All provided examples yield the same result for the 'X42' program. ```scala joern> cpg.call.name("exit").code.l res0: List[String] = List("exit(0)", "exit(42)") ``` ```scala joern> cpg.call.name("[eE]xit").code.l res1: List[String] = List("exit(0)", "exit(42)") ``` ```scala joern> cpg.call.name("ex.*\*\*).code.l res2: List[String] = List("exit(0)", "exit(42)") ``` -------------------------------- ### Clone Sample Project Repository Source: https://docs.joern.io/organizing-projects Clone the repository containing the X42 sample program in various languages to use with Joern. ```bash $ git clone https://github.com/ShiftLeftSecurity/x42.git ``` -------------------------------- ### Clone Sample Project Source: https://docs.joern.io/traversal-basics Clone the X42 Java project from GitHub to use as a sample for Joern traversals. ```bash $ git clone https://github.com/ShiftLeftSecurity/x42.git ``` -------------------------------- ### Clone Sample Program Repository Source: https://docs.joern.io/quickstart Clone the X42 sample program repository to begin static code analysis. ```bash git clone https://github.com/ShiftLeftSecurity/x42.git ``` -------------------------------- ### Example of Taint Propagation without Custom Semantics Source: https://docs.joern.io/dataflow-semantics This example demonstrates how taint can propagate imprecisely without custom semantic definitions for external calls. ```python a = "MALICIOUS" foo = Foo() x = foo.bar(a, b) # True positives print(a) print(x) # False positives print(b) print(foo) ``` -------------------------------- ### Joern Scan Query Definition Example Source: https://docs.joern.io/scan An example of how a query is defined within Joern Scan. It includes metadata like name, author, title, description, score, and the graph traversal logic. ```scala def getsUsed(): Query = Query.make( name = "call-to-gets", author = Crew.suchakra, title = "Dangerous function gets() used", description = """ | Avoid `gets` function as it can lead to reads beyond buffer | boundary and cause | buffer overflows. Some secure alternatives are `fgets` and `gets_s`. | """.stripMargin, score = 8, withStrRep({ cpg => cpg.method("gets").callIn }), tags = List(QueryTags.badfn) ) ``` -------------------------------- ### Example: javasrc2cpg no-dummyTypes argument Source: https://docs.joern.io/frontends/java Disables the generation of dummy types during type propagation. ```bash --no-dummyTypes ``` -------------------------------- ### Available Steps for Method Node Source: https://docs.joern.io/cpgql/help-directive When `help` is appended to a specific node type in a traversal (e.g., `cpg.method.help`), it lists the available steps applicable to that node type. This helps in exploring the CPG structure and available query operations. ```text joern> cpg.method.help Available steps for Method: ┌────────────────────┬─────────────────────────────────────────┐ │step │description │ ├────────────────────┼─────────────────────────────────────────┤ │.address │Address of the code (for binary code) │ │.ast │All nodes of the abstract syntax tree │ │.body │Alias for `block` │ │.break │All breaks (`ControlStructure` nodes) │ │.cfgLast │Last control flow graph node │ ... ``` -------------------------------- ### Example: javasrc2cpg keep-type-arguments argument Source: https://docs.joern.io/frontends/java Ensures that full type names of variables retain their type arguments. ```bash --keep-type-arguments ``` -------------------------------- ### Example: javasrc2cpg skip-type-inf-pass argument Source: https://docs.joern.io/frontends/java Skips the type inference pass. Use only for development as results will be significantly degraded. ```bash --skip-type-inf-pass ``` -------------------------------- ### List Files in Source Path Source: https://docs.joern.io/common-issues Use this command to verify if the provided source path exists and is accessible. ```bash ls ``` -------------------------------- ### Sample C Program Source: https://docs.joern.io/cpgql/data-flow-steps A sample C program used to demonstrate data-flow analysis. ```c #include #include #include int main(int argc, char *argv[]) { if (argc > 1 && strcmp(argv[1], "42") == 0) { fprintf(stderr, "It depends!\n"); exit(42); } printf("What is the meaning of life?\n"); exit(0); } ``` -------------------------------- ### Add JVM Dependency via --dep Parameter Source: https://docs.joern.io/shell Add a JVM dependency to the classpath on startup using the --dep parameter. This is the recommended method for Joern 2.0.0 and later. ```shell ./joern --dep com.michaelpollmeier:versionsort:1.0.7 joern> versionsort.VersionHelper.compare("1.0", "0.9") val res0: Int = 1 ``` -------------------------------- ### Get IS_EXTERNAL property values for METHOD nodes Source: https://docs.joern.io/traversal-basics This query retrieves the 'IS_EXTERNAL' property value for all METHOD nodes, not filtering them. ```joern joern> cpg.method.isExternal.toList res11: List[Boolean] = List(true, false, true, ...) ``` -------------------------------- ### List Supported Languages Source: https://docs.joern.io/common-issues Run this command to check all languages supported by Joern/Ocular. ```bash joern-scan --list-languages ``` -------------------------------- ### Import C Code into Joern Project Source: https://docs.joern.io/organizing-projects Use the `importCode` command to create a Joern Project for the C implementation of the X42 program. Ensure the input path is correct to avoid errors. ```scala joern> importCode("./x42/c", "x42-c") Creating project `x42-c` for code at `./x42/c` // ...output trimmed res1: Option[Cpg] = Some(io.shiftleft.codepropertygraph.Cpg@7923e12c) ``` -------------------------------- ### Repeat Traversal Until Specific Call Source: https://docs.joern.io/cpgql/repeat-steps Repeats a traversal until a call with a specific name is encountered. This example stops when an 'exit' call is found. ```scala joern> cpg.method.name("main").repeat(_.astChildren)(_.until(_.isCall.name("exit"))).l ``` -------------------------------- ### Add Dependency and Resolver via Script Source: https://docs.joern.io/shell Configure additional resolvers and dependencies within a script file using '//> using resolver' and '//> using dep' directives. The script is then executed with joern. ```shell //> using resolver https://repo.gradle.org/gradle/libs-releases //> using dep org.gradle:gradle-tooling-api:7.6.1 println(org.gradle.tooling.GradleConnector.newConnector()) ``` ```shell ./joern --script script-with-resolver.sc ``` -------------------------------- ### Running Joern Scan on a C File Source: https://docs.joern.io/scan This command demonstrates how to run Joern Scan on a C source file. It shows the basic invocation and the expected output format for detected issues. ```bash $ joern-scan simple.c Detailed logs at: /tmp/joern-scan-log.txt Result: 8.0 : Dangerous function gets() used: /home/user/code/simple.c:6:main ``` -------------------------------- ### Execute CPGQL Query and Return as List Source: https://docs.joern.io/cpgql/execution-directives Use `toList` to execute a CPGQL query and retrieve all results as a list. This is the most straightforward execution directive. ```java joern> cpg.call.name.toList res0: List[String] = List( "exit", "printf", "exit", "fprintf", ".indirectIndexAccess", "strcmp", ".equals", ".greaterThan", ".logicalAnd" ) ``` -------------------------------- ### Generate CPG and Data Flow Layer for a Sample Function Source: https://docs.joern.io/export Import C code and calculate the data flow layer using `run.ossdataflow`. This is a prerequisite for certain data flow analysis queries. ```scala joern> importCode.c.fromString( """ int myfunc(int b) { int a = 42; if (b > 10) { foo(a) } bar(a); } """ ) ``` ```scala joern> run.ossdataflow ``` -------------------------------- ### Dump AST, CFG, and CPG'14 in dot format from Joern Console Source: https://docs.joern.io/export Dump Abstract Syntax Trees, Control Flow Graphs, and CPG'14 representations in dot format for a given method. ```scala cpg.method($name).dotAst.l ``` ```scala cpg.method($name).dotCfg.l ``` ```scala cpg.method($name).dotCpg14.l ``` -------------------------------- ### Write Query Results to File using Joern Interpreter Source: https://docs.joern.io/cpgql/execution-directives Demonstrates writing the result of a CPGQL query to a text file using standard Java I/O operations within the Joern interpreter. ```scala // first import the namespace for Java I/O joern> import java.io._ import java.io._ // afterwards open a file stream to a new file named `my-query-result.txt` joern> val pw = new PrintWriter(new File("./my-query-result.txt" )) pw: PrintWriter = java.io.PrintWriter@fe4c8fc // execute your query and store the results in a constant joern> val myQueryResult = cpg.call.size myQueryResult: Int = 9 // cast myQueryResult to a string, and write it to the file stream joern> pw.write(myQueryResult.toString()) // close the file streasm joern> pw.close() ``` ```bash $ cat my-query-result.txt 9 ``` -------------------------------- ### Getting the Joern Workspace Path Source: https://docs.joern.io/organizing-projects Retrieve the file system path of the Joern Workspace using the `workspace.getPath` method. This is useful for locating the workspace directory on your machine. ```shell joern> workspace.getPath res1: String = "/home/user/.shiftleft/joern/workspace" ``` -------------------------------- ### Plot AST, CFG, and CPG'14 from Joern Console Source: https://docs.joern.io/export Plot Abstract Syntax Trees, Control Flow Graphs, and CPG'14 representations for a given method. ```scala cpg.method($name).plotDotAst ``` ```scala cpg.method($name).plotDotCfg ``` ```scala cpg.method($name).plotDotCpg14 ``` -------------------------------- ### Find nodes controlling a call Source: https://docs.joern.io/cpgql/control-flow-steps Use the `controlledBy` step to find all nodes on which the preceding node is control-dependent. This example finds nodes controlling the `exit(42)` call. ```joern joern> cpg.call.codeExact("exit(42)").controlledBy.code.l res0: List[String] = List("argc > 1 && strcmp(argv[1], \"42\") == 0") ``` -------------------------------- ### Import Code into Joern Project Source: https://docs.joern.io/traversal-basics Import the X42 program's JAR file into a new Joern project named 'x42'. This command analyzes the code and builds the Code Property Graph. ```scala joern> importCode("./x42/c/", "x42") Creating project `x42` for code at `x42/c/` ... output omitted res0: Option[Cpg] = Some(io.shiftleft.codepropertygraph.Cpg@31ed46c5) ``` -------------------------------- ### Dump Enclosing Function Code for Findings Source: https://docs.joern.io/shell Use the '.dump' method to display the code of the enclosing function for each query result, highlighting the specific finding. Requires 'source-highlight' to be installed. ```scala joern> cpg.method.name("memcpy").callIn.dump ``` -------------------------------- ### Complex Boolean Expressions in `filter` Source: https://docs.joern.io/cpgql/filter-steps Illustrates using complex boolean expressions within a `filter` step. This example combines multiple conditions to find specific CALL nodes. ```scala joern> cpg.call.filter(node => node.name == "exit" && node.code.contains("42")).code.l res0: List[String] = List("exit(42)") ``` ```scala // equivalent in logic to the query above joern> cpg.call.filter(node => true && 1 == 1 && node.name == "exit" && node.code.contains("42")).code.l res0: List[String] = List("exit(42)") ``` -------------------------------- ### Inspect Project Metadata Source: https://docs.joern.io/organizing-projects Use the `cpg.metaData.l` command to view metadata of the currently active Joern project, such as language and version. ```scala joern> cpg.metaData.l res7: List[MetaData] = List( MetaData( id -> 1L, language -> "JAVA", version -> "0.1", overlays -> List("semanticcpg", "dataflow", "tagging"), policyDirectories -> List(), spid -> None ) ) ``` -------------------------------- ### Find nodes dominated by a call Source: https://docs.joern.io/cpgql/control-flow-steps Use the `dominates` step to find all nodes that are dominated by the preceding node. This example finds nodes dominated by a call related to `argc` and `strcmp`. ```joern joern> cpg.call.code(".*argc.*strcmp.*").dominates.code.l res0: List[String] = List( "RET", "exit(0)", "0", "printf(\"What is the meaning of life?\\n\")", "exit(42)", "42", "fprintf(stderr, \"It depends!\\n"))", "\"It depends!\\n\"", "stderr", "\"What is the meaning of life?\\n\"" ) ``` -------------------------------- ### Invoke Python Frontend Directly Source: https://docs.joern.io/frontends Use this command to parse a Python directory and generate an AST using the specific pysrc2cpg frontend. Ensure Joern is staged with `sbt scala stage` if the script is missing. ```bash cd joern-cli/frontends/pysrc2cpg/ sbt scala stage ./pysrc2cpg /some/input/path --output someOutput --venvDir /some/venv/dir ``` -------------------------------- ### Execute Traversal and Return JSON String Source: https://docs.joern.io/cpgql/execution-directives Use `toJson` to execute a CPG traversal and get the results as a compact JSON string. This is useful for quick inspection of traversal output. ```joern joern> cpg.call.name.toJson res28: String = "[\"exit\",\"printf\",\"exit\",\"fprintf\",\".indirectIndexAccess\",\"strcmp\",\".equals\",\".greaterThan\",\".logicalAnd\"]" ``` -------------------------------- ### Import Code into Joern Source: https://docs.joern.io/quickstart Import the X42 C program into Joern to create a Code Property Graph (CPG). This command requires the path to the source code and a project name. ```scala joern> importCode(inputPath="./x42/c", projectName="x42-c") Creating project `x42-c` for code at `x42/c` ... output omitted res1: Option[Cpg] = Some(io.shiftleft.codepropertygraph.Cpg@31ed46c5) ``` -------------------------------- ### Using .to(Traversal) instead of .start Source: https://docs.joern.io/upgrade-guides When migrating from `.start` for collections other than `Node` and `NewNode`, use the standard Scala collection mechanism `.to(Traversal)`. The `.start` step is no longer available for these types. ```scala val someMethod = cpg.method.head someMethod.start.parameter //Traversal[MethodParameterIn] ``` ```scala val methodList: cpg.method.l methodList.to(Traversal) //Traversal[Method] ``` -------------------------------- ### Export entire graph in various formats Source: https://docs.joern.io/export Export the complete graph representation in different formats like neo4jcsv, graphml, graphson, or dot. ```shell ./joern-export --repr=all --format=neo4jcsv ``` ```shell ./joern-export --repr=all --format=graphml ``` ```shell ./joern-export --repr=all --format=graphson ``` ```shell ./joern-export --repr=all --format=dot ``` -------------------------------- ### Execute Traversal and Get MetaData List Source: https://docs.joern.io/traversal-basics Use the 'toList' execution directive to evaluate the traversal and retrieve all METADATA nodes as a list. This demonstrates lazy evaluation and the structure of the MetaData node. ```scala joern> cpg.metaData.toList res3: List[MetaData] = List( MetaData( id -> 1L, hash -> None, language -> "NEWC", overlays -> List("semanticcpg"), version -> "0.1" ) ) ``` -------------------------------- ### Dump all representations into a directory Source: https://docs.joern.io/export Dump all available graph representations (AST, CFG, CPG'14, etc.) into a specified directory using shell commands. ```shell run.dumpast ``` ```shell run.dumpcfg ``` ```shell run.dumpcpg14 ``` -------------------------------- ### Running Joern Scan with All Tags Source: https://docs.joern.io/scan This command executes all available queries by using the 'all' tag. It shows multiple results if different queries match the code. ```bash $ joern-scan simple.c --tags all Detailed logs at: /tmp/joern-scan-log.txt Result: 1.0 : Multiple returns: /home/user/code/simple.c:3:add2 Result: 8.0 : Dangerous function gets() used: /home/user/code/simple.c:17:main ``` -------------------------------- ### Configure Credentials for Authenticated Resolvers Source: https://docs.joern.io/shell Configure username and password for authenticated resolvers in a 'credentials.properties' file. The prefix is arbitrary and used to group credentials. ```properties mycorp.realm=Artifactory Realm mycorp.host=shiftleft.jfrog.io mycorp.username=michael mycorp.password=secret otherone.username=j otherone.password=imj otherone.host=nexus.other.com ``` -------------------------------- ### Import Java JAR into Joern Project Source: https://docs.joern.io/organizing-projects Use the `importCode` command to create a Joern Project for the Java implementation of the X42 program, specifying the JAR file path. ```scala joern> importCode("./x42/java/X42.jar", "x42-java") Creating project `x42-java` for code at `./x42/java/X42.jar` // ...output trimmed res2: Option[Cpg] = Some(io.shiftleft.codepropertygraph.Cpg@5d41bf70) ``` -------------------------------- ### Access Root Object in Joern Source: https://docs.joern.io/traversal-basics Execute a traversal consisting only of the root object 'cpg' to get a reference to the Code Property Graph. The output includes a unique hexadecimal identifier for the graph instance. ```scala joern> cpg res1: Cpg = io.shiftleft.codepropertygraph.Cpg@ab90fdab ``` -------------------------------- ### Execute CPGQL Query and Return First Result Source: https://docs.joern.io/cpgql/execution-directives Use the `head` directive to execute a CPGQL query and retrieve only the first result. ```java joern> cpg.call.name.head res0: List[String] = List( "exit", ) ``` -------------------------------- ### Basic Method Name Traversal Source: https://docs.joern.io/traversal-basics This query retrieves all method names from a Code Property Graph. It starts with the root object 'cpg', traverses to 'method' nodes, accesses their 'name' property, and collects the results into a list. ```scala cpg.method.name.toList ``` -------------------------------- ### Plotting Abstract Syntax Tree Source: https://docs.joern.io/c-syntaxtree Visualize the Abstract Syntax Tree (AST) of a method named 'foo' using the plotDotAst function. This helps in understanding the code's structure. ```scala cpg.method.name("foo").plotDotAst ``` -------------------------------- ### Execute CPGQL Query and Pretty-Print Results Source: https://docs.joern.io/cpgql/execution-directives The `p` directive executes a CPGQL query and pretty-prints the results, providing a detailed, formatted output. ```java joern> cpg.call.p res26: List[String] = List( "(CALL,31): ARGUMENT_INDEX: 3, CODE: exit(0), COLUMN_NUMBER: 2, DISPATCH_TYPE: STATIC_DISPATCH, LINE_NUMBER: 11, METHOD_FULL_NAME: exit, NAME: exit, ORDER: 3, SIGNATURE: TODO assignment signature, TYPE_FULL_NAME: ANY", "(CALL,29): ARGUMENT_INDEX: 2, CODE: printf(\"What is the meaning of life?\\n\"), COLUMN_NUMBER: 2, DISPATCH_TYPE: STATIC_DISPATCH, LINE_NUMBER: 10, METHOD_FULL_NAME: printf, NAME: printf, ORDER: 2, SIGNATURE: TODO assignment signature, TYPE_FULL_NAME: ANY", "(CALL,27): ARGUMENT_INDEX: 2, CODE: exit(42), COLUMN_NUMBER: 4, DISPATCH_TYPE: STATIC_DISPATCH, LINE_NUMBER: 8, METHOD_FULL_NAME: exit, NAME: exit, ORDER: 2, SIGNATURE: TODO assignment signature, TYPE_FULL_NAME: ANY", "(CALL,24): ARGUMENT_INDEX: 1, CODE: fprintf(stderr, \"It depends!\\n\"), COLUMN_NUMBER: 4, DISPATCH_TYPE: STATIC_DISPATCH, LINE_NUMBER: 7, METHOD_FULL_NAME: fprintf, NAME: fprintf, ORDER: 1, SIGNATURE: TODO assignment signature, TYPE_FULL_NAME: ANY", "(CALL,18): ARGUMENT_INDEX: 1, CODE: argv[1], COLUMN_NUMBER: 25, DISPATCH_TYPE: STATIC_DISPATCH, LINE_NUMBER: 6, METHOD_FULL_NAME: .indirectIndexAccess, NAME: .indirectIndexAccess, ORDER: 1, SIGNATURE: TODO assignment signature, TYPE_FULL_NAME: ANY", "(CALL,17): ARGUMENT_INDEX: 1, CODE: strcmp(argv[1], \"42\"), COLUMN_NUMBER: 18, DISPATCH_TYPE: STATIC_DISPATCH, LINE_NUMBER: 6, METHOD_FULL_NAME: strcmp, NAME: strcmp, ORDER: 1, SIGNATURE: TODO assignment signature, TYPE_FULL_NAME: ANY", "(CALL,16): ARGUMENT_INDEX: 2, CODE: strcmp(argv[1], \"42\") == 0, COLUMN_NUMBER: 18, DISPATCH_TYPE: STATIC_DISPATCH, LINE_NUMBER: 6, METHOD_FULL_NAME: .equals, NAME: .equals, ORDER: 2, SIGNATURE: TODO assignment signature, TYPE_FULL_NAME: ANY", "(CALL,13): ARGUMENT_INDEX: 1, CODE: argc > 1, COLUMN_NUMBER: 6, DISPATCH_TYPE: STATIC_DISPATCH, LINE_NUMBER: 6, METHOD_FULL_NAME: .greaterThan, NAME: .greaterThan, ORDER: 1, SIGNATURE: TODO assignment signature, TYPE_FULL_NAME: ANY", "(CALL,12): ARGUMENT_INDEX: 1, CODE: argc > 1 && strcmp(argv[1], \"42\") == 0, COLUMN_NUMBER: 6, DISPATCH_TYPE: STATIC_DISPATCH, LINE_NUMBER: 6, METHOD_FULL_NAME: .logicalAnd, NAME: .logicalAnd, ORDER: 1, SIGNATURE: TODO assignment signature, TYPE_FULL_NAME: ANY" ) ``` -------------------------------- ### Export PDGs for all methods using joern-export Source: https://docs.joern.io/export Parse a directory and export Program Dependence Graphs for all methods to a specified output directory. ```shell joern-parse /src/directory joern-export --repr pdg --out outdir ``` -------------------------------- ### Add Scala Dependency with :: Source: https://docs.joern.io/shell Add a Scala dependency using the '::' notation with the --dep parameter. This is useful for Scala-specific libraries. ```shell ./joern --dep com.michaelpollmeier::colordiff:0.36 colordiff.ColorDiff(List("a", "b"), List("a", "bb")) // color coded diff ``` -------------------------------- ### /query Source: https://docs.joern.io/server Submit a query to the Joern server for execution. ```APIDOC ## POST /query ### Description Submit a query to the Joern server for execution. The server will return a UUID that can be used to retrieve the query results later. ### Method POST ### Endpoint /query ### Parameters #### Request Body - **query** (string) - Required - The query string to be executed. ### Request Example { "query": "val foo = 42" } ### Response #### Success Response (200) - **uuid** (string) - The unique identifier assigned to the query. #### Response Example { "uuid": "some-uuid-string" } ``` -------------------------------- ### Java Instance Method Call AST Representation Source: https://docs.joern.io/frontends/java Illustrates the AST structure for a simple instance method call in Java, including the implicit receiver argument. ```java class Foo { public void bar(String param1, Integer param2, String param3) { s.length() } public void baz() { bar("1", 2, "3") } } ``` ```protobuf CallNode ├── Receiver: this ├── MethodName: bar └── Arguments ├── Argument[0]: this ├── Argument[1]: param1 ├── Argument[2]: param2 └── Argument[3]: param3 ``` -------------------------------- ### Importing C Code Snippet Source: https://docs.joern.io/c-syntaxtree Import a C code snippet into Joern from a string variable. This is the first step before analyzing the code's AST. ```scala val code = """ void foo () { int x = source(); if(x < MAX) { int y = 2*x; sink(y); } } """ importCode.c.fromString(code) ``` -------------------------------- ### Export Raw Code to File Source: https://docs.joern.io/shell Dump the raw code of the enclosing function for each finding to a file using 'dumpRaw'. This skips syntax highlighting, assuming the editor will handle it. ```scala cpg.method.name("memcpy").callIn.dumpRaw #> "/tmp/foo.c" ``` -------------------------------- ### Plot AST for a specific method Source: https://docs.joern.io/export Plot the Abstract Syntax Tree for a method named 'myfunc' after generating the CPG and data flow layer. ```scala joern> cpg.method("myfunc").plotDotAst ``` -------------------------------- ### Generate Full CPG with joern-parse Source: https://docs.joern.io/frontends Use the `joern-parse` command to generate a full CPG for a source directory, specifying the language and passing frontend-specific arguments. ```bash ./joern-parse /some/input/path --language PYTHONSRC --frontend-args --venvDir /some/venv/dir ``` -------------------------------- ### Concise File Output using #> Operator Source: https://docs.joern.io/cpgql/execution-directives Utilizes the Joern Interpreter's `#>` operator for a more concise way to write query results to a file. ```java joern> cpg.call.size.toString() #> "my-query-result.txt" ``` -------------------------------- ### Basic Syntax for Defining Data-Flow Semantics Source: https://docs.joern.io/dataflow-semantics Defines data-flow paths between arguments and the return value for a method. Use -1 for return value and 0 for the receiver. ```text "foo" 1->-1 2->3 ```