Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 0xdevalias/d8b743efb82c0e9406fc69da0d6c6581 to your computer and use it in GitHub Desktop.
Save 0xdevalias/d8b743efb82c0e9406fc69da0d6c6581 to your computer and use it in GitHub Desktop.
Some notes and tools for reverse engineering / deobfuscating / unminifying obfuscated web app code

Deobfuscating / Unminifying Obfuscated Web App / JavaScript Code

Table of Contents

Other files in this gist:

PoC

Tools

Unsorted

  • https://eslint.org/docs/
    • https://eslint.org/docs/latest/extend/custom-rules#the-context-object
      • The context object is the only argument of the create method in a rule.

      • As the name implies, the context object contains information that is relevant to the context of the rule.

    • https://eslint.org/docs/latest/extend/custom-rules#applying-fixes
      • Applying Fixes If you’d like ESLint to attempt to fix the problem you’re reporting, you can do so by specifying the fix function when using context.report(). The fix function receives a single argument, a fixer object, that you can use to apply a fix.

      • Important: The meta.fixable property is mandatory for fixable rules. ESLint will throw an error if a rule that implements fix functions does not export the meta.fixable property.

      • The fixer object has the following methods:

        • insertTextAfter(nodeOrToken, text): Insert text after the given node or token.
        • insertTextAfterRange(range, text): Insert text after the given range.
        • insertTextBefore(nodeOrToken, text): Insert text before the given node or token.
        • insertTextBeforeRange(range, text): Insert text before the given range.
        • remove(nodeOrToken): Remove the given node or token.
        • removeRange(range): Remove text in the given range.
        • replaceText(nodeOrToken, text): Replace the text in the given node or token.
        • replaceTextRange(range, text): Replace the text in the given range.

        A range is a two-item array containing character indices inside the source code. The first item is the start of the range (inclusive) and the second item is the end of the range (exclusive). Every node and token has a range property to identify the source code range they represent.

        The above methods return a fixing object. The fix() function can return the following values:

        • A fixing object.
        • An array which includes fixing objects.
        • An iterable object which enumerates fixing objects. Especially, the fix() function can be a generator.

        If you make a fix() function which returns multiple fixing objects, those fixing objects must not overlap.

    • https://eslint.org/docs/latest/extend/code-path-analysis
      • Code Path Analysis Details

      • ESLint’s rules can use code paths. The code path is execution routes of programs. It forks/joins at such as if statements.

      • Program is expressed with several code paths. A code path is expressed with objects of two kinds: CodePath and CodePathSegment.

      • CodePath expresses whole of one code path. This object exists for each function and the global. This has references of both the initial segment and the final segments of a code path.

      • CodePathSegment is a part of a code path. A code path is expressed with plural CodePathSegment objects, it’s similar to doubly linked list. Difference from doubly linked list is what there are forking and merging (the next/prev are plural).

      • There are seven events related to code paths, and you can define event handlers by adding them alongside node visitors in the object exported from the create() method of your rule.

  • https://prettier.io/
  • https://github.com/beautify-web/js-beautify
    • Beautifier for javascript

    • This little beautifier will reformat and re-indent bookmarklets, ugly JavaScript, unpack scripts packed by Dean Edward’s popular packer, as well as partly deobfuscate scripts processed by the npm package javascript-obfuscator.

    • https://beautifier.io/
  • https://github.com/shapesecurity/unminify
  • https://github.com/lelinhtinh/de4js
  • http://www.jsnice.org/
    • Statistical renaming, type inference and deobfuscation

    • https://www.sri.inf.ethz.ch/research/plml
      • Machine Learning for Code This project combines programming languages and machine learning for building statistical programming engines -- systems built on top of machine learning models of large codebases. These are new kinds of engines which can provide statistically likely solutions to problems that are difficult or impossible to solve with traditional techniques.

      • JSNice JSNice de-obfuscates JavaScript programs. JSNice is a popular system in the JavaScript commmunity used by tens of thousands of programmers, worldwide

  • https://github.com/spaceraccoon/webpack-exploder/
  • https://github.com/goto-bus-stop/webpack-unpack
  • https://github.com/goto-bus-stop/amd-unpack
    • extract modules from a bundled AMD project using define/require functions

  • https://github.com/gchq/CyberChef
  • https://github.com/dandavison/delta
  • https://github.com/Wilfred/difftastic
    • Difftastic is a structural diff tool that compares files based on their syntax.

    • https://difftastic.wilfred.me.uk/introduction.html
      • Difftastic is a structural diff tool that understands syntax. It supports over 30 programming languages and when it works, it's fantastic.

  • https://github.com/prettydiff/prettydiff
    • Beautifier and language aware code comparison tool for many languages. It also minifies and a few other things

    • https://prettydiff.com/#projects-prettydiff
      • When I first became a developer at Travelocity I would sometimes needs to compare code in different environments where some code existed in its original condition and in other cases was minified. Existing diff tools could not solve for that sort of comparison, and at that time existing JavaScript beautifiers had trouble with complex data structures. So I integrated a web-based diff tool with an existing beautifier and minifier. As the features, capabilities, and requests upon the application grew I eventually wrote my own diff algorithm and beautifiers for the various supported languages.

  • https://github.com/Vunovati/astii
    • A JavaScript AST-aware diff and patch toolset

    • When comparing two JavaScript files, standard diff tools compare the two files line-by-line and output the lines on which the files differ. This tool does not compare the characters of the source files directly but their abstract representation - their abstract syntax trees.

    • This enables you to have more meaningfull diffs between files which may be very simmilar but have different source code formatting.

    • When patching, astii patch will regenerate (original --> AST --> generate) the source file and patch it with the provided diff.

  • https://www.blueclosure.com/product/bc-detect
    • BC Detect (DOMinatorPro NG) helps security testers to analyse and automatically discover DOM Based Cross Site Scripting issues thanks to its Hybrid IAST Engine together with the Smart Fuzzer module.

    • https://www.blueclosure.com/page/features
  • https://github.com/kuizuo/js-deobfuscator
  • https://github.com/j4k0xb/unsea
    • unsea Extracts the javascript source code and assets of Node Single Executable Applications.

      Compatible with ELF (Linux), PE (Windows), and Mach-O (MacOS) executables.

      • https://nodejs.org/api/single-executable-applications.html
        • Single executable applications

          This feature allows the distribution of a Node.js application conveniently to a system that does not have Node.js installed.

          Node.js supports the creation of single executable applications by allowing the injection of a blob prepared by Node.js, which can contain a bundled script, into the node binary. During start up, the program checks if anything has been injected. If the blob is found, it executes the script in the blob. Otherwise Node.js operates as it normally does.

          The single executable application feature currently only supports running a single embedded script using the CommonJS module system.

          Users can create a single executable application from their bundled script with the node binary itself and any tool which can inject resources into the binary.

wakaru

webcrack

ast-grep

Restringer

debundle + related

joern

  • https://joern.io/
    • The Bug Hunter's Workbench

    • Query: Uncover attack surface, sloppy coding practices, and variants of known vulnerabilities using an interactive code analysis shell. Joern supports C, C++, LLVM bitcode, x86 binaries (via Ghidra), JVM bytecode (via Soot), and Javascript. Python, Java source code, Kotlin, and PHP support coming soon.

    • Automate: Wrap your queries into custom code scanners and share them with the community or run existing Joern-based scanners in your CI.

    • Integrate: Use Joern as a library to power your own code analysis tools or as a component via the REST API.

    • https://github.com/joernio/joern
      • Open-source code analysis platform for C/C++/Java/Binary/Javascript/Python/Kotlin based on code property graphs.

      • Joern is a platform for analyzing source code, bytecode, and binary executables. It generates code property graphs (CPGs), a graph representation of code for cross-language code analysis. Code property graphs are stored in a custom graph database. This allows code to be mined using search queries formulated in a Scala-based domain-specific query language. Joern is developed with the goal of providing a useful tool for vulnerability discovery and research in static program analysis.

    • https://docs.joern.io/
      • Joern is a platform for robust analysis of source code, bytecode, and binary code. It generates code property graphs, a graph representation of code for cross-language code analysis. Code property graphs are stored in a custom graph database. This allows code to be mined using search queries formulated in a Scala-based domain-specific query language. Joern is developed with the goal of providing a useful tool for vulnerability discovery and research in static program analysis.

      • The core features of Joern are:

        • Robust parsing. Joern allows importing code even if a working build environment cannot be supplied or parts of the code are missing.
        • Code Property Graphs. Joern creates semantic code property graphs from the fuzzy parser output and stores them in an in-memory graph database. SCPGs are a language-agnostic intermediate representation of code designed for query-based code analysis.
        • Taint Analysis. Joern provides a taint-analysis engine that allows the propagation of attacker-controlled data in the code to be analyzed statically.
        • Search Queries. Joern offers a strongly-typed Scala-based extensible query language for code analysis based on Gremlin-Scala. This language can be used to manually formulate search queries for vulnerabilities as well as automatically infer them using machine learning techniques.
        • Extendable via CPG passes. Code property graphs are multi-layered, offering information about code on different levels of abstraction. Joern comes with many default passes, but also allows users to add passes to include additional information in the graph, and extend the query language accordingly.
      • https://docs.joern.io/code-property-graph/
      • https://docs.joern.io/cpgql/data-flow-steps/
      • https://docs.joern.io/export/
        • Joern can create the following graph representations for C/C++ code:

          • Abstract Syntax Trees (AST)
          • Control Flow Graphs (CFG)
          • Control Dependence Graphs (CDG)
          • Data Dependence Graphs (DDG)
          • Program Dependence graphs (PDG)
          • Code Property Graphs (CPG14)
          • Entire graph, i.e. convert to a different graph format (ALL)
  • https://en.wikipedia.org/wiki/Code_property_graph
    • A code property graph of a program is a graph representation of the program obtained by merging its abstract syntax trees (AST), control-flow graphs (CFG) and program dependence graphs (PDG) at statement and predicate nodes. The resulting graph is a property graph, which is the underlying graph model of graph databases such as Neo4j, JanusGraph and OrientDB where data is stored in the nodes and edges as key-value pairs. In effect, code property graphs can be stored in graph databases and queried using graph query languages.

    • Joern CPG. The original code property graph was implemented for C/C++ in 2013 at University of Göttingen as part of the open-source code analysis tool Joern. This original version has been discontinued and superseded by the open-source Joern Project, which provides a formal code property graph specification applicable to multiple programming languages. The project provides code property graph generators for C/C++, Java, Java bytecode, Kotlin, Python, JavaScript, TypeScript, LLVM bitcode, and x86 binaries (via the Ghidra disassembler).

      • https://github.com/joernio/joern
        • Open-source code analysis platform for C/C++/Java/Binary/Javascript/Python/Kotlin based on code property graphs.

        • Joern is a platform for analyzing source code, bytecode, and binary executables. It generates code property graphs (CPGs), a graph representation of code for cross-language code analysis. Code property graphs are stored in a custom graph database. This allows code to be mined using search queries formulated in a Scala-based domain-specific query language. Joern is developed with the goal of providing a useful tool for vulnerability discovery and research in static program analysis.

        • https://joern.io/
        • https://cpg.joern.io/
          • Code Property Graph Specification 1.1

          • This is the specification of the Code Property Graph, a language-agnostic intermediate graph representation of code designed for code querying.

            The code property graph is a directed, edge-labeled, attributed multigraph. This specification provides the graph schema, that is, the types of nodes and edges and their properties, as well as constraints that specify which source and destination nodes are permitted for each edge type.

            The graph schema is structured into multiple layers, each of which provide node, property, and edge type definitions. A layer may depend on multiple other layers and make use of the types it provides.

Blogs / Articles / etc

Libraries / Helpers

Unsorted

Recast + related

  • https://github.com/benjamn/recast
  • https://github.com/facebook/jscodeshift
    • A JavaScript codemod toolkit

    • jscodeshift is a toolkit for running codemods over multiple JavaScript or TypeScript files. It provides:

      • A runner, which executes the provided transform for each file passed to it. It also outputs a summary of how many files have (not) been transformed.
      • A wrapper around recast, providing a different API. Recast is an AST-to-AST transform tool and also tries to preserve the style of original code as much as possible.
    • facebook/jscodeshift#500
      • Bringing jscodeshift up to date

      • The biggest issue is with recast. This library hasn't really had a lot of maintenance for the last couple of years, and there's something like 150+ issues and 40+ pull requests waiting to be merged. It seems like 80% of the issues that are logged against jscodeshift are actually recast issues. In order to fix the jscodeshift's outstanding issues, either recast itself needs to fix them or jscodeshift will need to adopt/create its own fork of recast to solve them. For the past year and a half or so putout's main developer has been maintaining a fork of recast and adding a lot of fixes to it. It might be worthwhile to look at switching to @putout/recast as opposed to the recast upstream. I've also been working on a fork of @putout/recast for evcodeshift that adds a few other things to make evcodeshift transforms more debuggable in vscode.

      • https://github.com/putoutjs/recast
        • https://github.com/putoutjs/printer
        • Prints Babel AST to readable JavaScript. For ESTree use estree-to-babel.

          • Similar to Recast, but twice faster, also simpler and easier in maintenance, since it supports only Babel.
          • As opinionated as Prettier, but has more user-friendly output and works directly with AST.
          • Like ESLint but works directly with Babel AST.
          • Easily extendable with help of Overrides.
    • What can be said about recast can probably also be said to a lesser degree about ast-types

  • https://github.com/codemod-js/codemod
    • codemod rewrites JavaScript and TypeScript using babel plugins

  • https://github.com/unjs/magicast
    • Programmatically modify JavaScript and TypeScript source codes with a simplified, elegant and familiar syntax powered by recast and babel.

estools + related

Babel

semantic / tree-sitter + related

Shift AST

swc

esbuild

  • https://github.com/evanw/esbuild
    • An extremely fast bundler for the web

    • Written in Golang
    • https://esbuild.github.io/
      • https://esbuild.github.io/faq/#upcoming-roadmap
        • I am not planning to include these features in esbuild's core itself:

          • ..snip..
          • An API for custom AST manipulation
          • ..snip..

          I hope that the extensibility points I'm adding to esbuild (plugins and the API) will make esbuild useful to include as part of more customized build workflows, but I'm not intending or expecting these extensibility points to cover all use cases.

          • https://esbuild.github.io/plugins/
          • https://esbuild.github.io/api/
          • https://news.ycombinator.com/item?id=29004200
            • ESBuild does not support any AST transforms directly

              You can add it, via plugins, but its a serious limitation for a project like Next.js which require's these types of transforms

              You also end up with diminishing returns with the more plugins in you add to esbuild, and I imagine its worse with js plugins than it is with go based ones, none the less, you have zero access to it directly

            • It is trivial to write extensions for esbuild. We've written extensive plugins to perform ast transformations that all run, collectively, in under 0.5 seconds. Make a plugin, add acorn and escodegen.

              • This implies that the plugins are doing the AST transformation outside of esbuild itself (likely still running in JS), so wouldn't really benefit from the fact that esbuild is written in golang like I was hoping.
          • evanw/esbuild#2172
            • Forking esbuild to build an AST plugin tool

            • The internal AST is not designed for this use case at all, and it’s not a use case that I’m going to spend time supporting (so I’m not going to spend time documenting exactly how to do it). I recommend using some other tool if you want to do AST-level stuff, especially because keeping a hack like this working over time as esbuild changes might be a big pain for you.

            • If it really want to do this with esbuild, know that the AST is not cleanly abstracted and is only intended for use with esbuild (e.g. uses a lot of internal data structures, has implicit invariants regarding symbols and tree shaking, does some weird things for performance reasons).

Source Maps

Visualisation/etc

Browser Based Code Editors / IDEs

In addition to the links directly below, also make sure to check out the various online REPL/playground tools linked under various other parts of this page too (eg. babel, swc, etc):

  • https://github.com/microsoft/TypeScript-Website/tree/v2/packages/playground
    • This is the JS tooling which powers the https://www.typescriptlang.org/play/

    • It is more or less vanilla DOM-oriented JavaScript with as few dependencies as possible. Originally based on the work by Artem Tyurin but now it's diverged far from that fork.

    • https://github.com/microsoft/TypeScript-Website/tree/v2/packages/sandbox
      • The TypeScript Sandbox is the editor part of the TypeScript Playground. It's effectively an opinionated fork of monaco-typescript with extra extension points so that projects like the TypeScript Playground can exist.

    • https://github.com/microsoft/TypeScript-Playground-Samples
      • Examples of TypeScript Playground Plugins for you to work from

      • This is a series of example plugins, which are extremely well documented and aim to give you samples to build from depending on what you want to build.

        • TS Compiler API: Uses @typescript/vfs to set up a TypeScript project in the browser, and then displays all of the top-level functions as AST nodes in the sidebar.
        • TS Transformers Demo: Uses a custom TypeScript transformer when emitting JavaScript from the current file in the Playground.
        • Using a Web-ish npm Dependency: Uses a dependency which isn't entirely optimised for running in a web page, but doesn't have too big of a dependency tree that it this becomes an issue either
        • Presenting Information Inline: Using a fraction of the extensive Monaco API (monaco is the text editor at the core of the Playground) to showcase what parts of a TypeScript file would be removed by a transpiler to make it a JS file.

CodeMirror

  • https://codemirror.net/
    • CodeMirror is a code editor component for the web. It can be used in websites to implement a text input field with support for many editing features, and has a rich programming interface to allow further extension.

    • CodeMirror is open source under a permissive license (MIT).

    • A full parser package, often with language-specific integration and extension code, exists for the following languages

    • There is also a collection of CodeMirror 5 modes that can be used, and a list of community-maintained language packages. If your language is not listed above, you may still find a solution there.

    • https://codemirror.net/docs/community/
      • Community Packages

      • This page lists CodeMirror-related packages maintained by the wider community.

  • https://github.com/codemirror/dev
    • Development repository for the CodeMirror editor project

    • This is the central repository for CodeMirror. It holds the bug tracker and development scripts.

      If you want to use CodeMirror, install the separate packages from npm, and ignore the contents of this repository. If you want to develop on CodeMirror, this repository provides scripts to install and work with the various packages.

  • https://github.com/uiwjs/react-codemirror

monaco-editor

Obfuscation / Deobfuscation

Variable Name Mangling

Stack Graphs / Scope Graphs

Symbolic / Concolic Execution

  • https://en.wikipedia.org/wiki/Symbolic_execution
    • In computer science, symbolic execution (also symbolic evaluation or symbex) is a means of analyzing a program to determine what inputs cause each part of a program to execute. An interpreter follows the program, assuming symbolic values for inputs rather than obtaining actual inputs as normal execution of the program would. It thus arrives at expressions in terms of those symbols for expressions and variables in the program, and constraints in terms of those symbols for the possible outcomes of each conditional branch. Finally, the possible inputs that trigger a branch can be determined by solving the constraints.

    • https://en.wikipedia.org/wiki/Symbolic_execution#Tools
    • https://en.wikipedia.org/wiki/Symbolic_execution#See_also
      • Abstract interpretation

      • Symbolic simulation

      • Symbolic computation

      • Concolic testing

      • Control-flow graph

      • Dynamic recompilation

  • https://en.wikipedia.org/wiki/Concolic_testing
    • Concolic testing (a portmanteau of concrete and symbolic, also known as dynamic symbolic execution) is a hybrid software verification technique that performs symbolic execution, a classical technique that treats program variables as symbolic variables, along a concrete execution (testing on particular inputs) path. Symbolic execution is used in conjunction with an automated theorem prover or constraint solver based on constraint logic programming to generate new concrete inputs (test cases) with the aim of maximizing code coverage. Its main focus is finding bugs in real-world software, rather than demonstrating program correctness.

    • Implementation of traditional symbolic execution based testing requires the implementation of a full-fledged symbolic interpreter for a programming language. Concolic testing implementors noticed that implementation of full-fledged symbolic execution can be avoided if symbolic execution can be piggy-backed with the normal execution of a program through instrumentation. This idea of simplifying implementation of symbolic execution gave birth to concolic testing.

    • An important reason for the rise of concolic testing (and more generally, symbolic-execution based analysis of programs) in the decade since it was introduced in 2005 is the dramatic improvement in the efficiency and expressive power of SMT Solvers. The key technical developments that lead to the rapid development of SMT solvers include combination of theories, lazy solving, DPLL(T) and the huge improvements in the speed of SAT solvers. SMT solvers that are particularly tuned for concolic testing include Z3, STP, Z3str2, and Boolector.

      • https://en.wikipedia.org/wiki/Satisfiability_modulo_theories
        • In computer science and mathematical logic, satisfiability modulo theories (SMT) is the problem of determining whether a mathematical formula is satisfiable. It generalizes the Boolean satisfiability problem (SAT) to more complex formulas involving real numbers, integers, and/or various data structures such as lists, arrays, bit vectors, and strings. The name is derived from the fact that these expressions are interpreted within ("modulo") a certain formal theory in first-order logic with equality (often disallowing quantifiers). SMT solvers are tools that aim to solve the SMT problem for a practical subset of inputs. SMT solvers such as Z3 and cvc5 have been used as a building block for a wide range of applications across computer science, including in automated theorem proving, program analysis, program verification, and software testing.

      • https://en.wikipedia.org/wiki/Boolean_satisfiability_problem#Algorithms_for_solving_SAT
    • https://en.wikipedia.org/wiki/Concolic_testing#Algorithm
      • Essentially, a concolic testing algorithm operates as follows:

        • Classify a particular set of variables as input variables. These variables will be treated as symbolic variables during symbolic execution. All other variables will be treated as concrete values.
        • Instrument the program so that each operation which may affect a symbolic variable value or a path condition is logged to a trace file, as well as any error that occurs.
        • Choose an arbitrary input to begin with.
        • Execute the program.
        • Symbolically re-execute the program on the trace, generating a set of symbolic constraints (including path conditions).
        • Negate the last path condition not already negated in order to visit a new execution path. If there is no such path condition, the algorithm terminates.
        • Invoke an automated satisfiability solver on the new set of path conditions to generate a new input. If there is no input satisfying the constraints, return to step 6 to try the next execution path.
        • Return to step 4.

        There are a few complications to the above procedure:

        • The algorithm performs a depth-first search over an implicit tree of possible execution paths. In practice programs may have very large or infinite path trees – a common example is testing data structures that have an unbounded size or length. To prevent spending too much time on one small area of the program, the search may be depth-limited (bounded).
        • Symbolic execution and automated theorem provers have limitations on the classes of constraints they can represent and solve. For example, a theorem prover based on linear arithmetic will be unable to cope with the nonlinear path condition xy = 6. Any time that such constraints arise, the symbolic execution may substitute the current concrete value of one of the variables to simplify the problem. An important part of the design of a concolic testing system is selecting a symbolic representation precise enough to represent the constraints of interest.
    • https://en.wikipedia.org/wiki/Concolic_testing#Tools
      • Jalangi is an open-source concolic testing and symbolic execution tool for JavaScript. Jalangi supports integers and strings.
  • https://en.wikipedia.org/wiki/Constraint_logic_programming
    • Constraint logic programming

    • Constraint logic programming is a form of constraint programming, in which logic programming is extended to include concepts from constraint satisfaction. A constraint logic program is a logic program that contains constraints in the body of clauses.

  • https://en.wikipedia.org/wiki/Automated_theorem_proving
    • Automated theorem proving

    • Automated theorem proving (also known as ATP or automated deduction) is a subfield of automated reasoning and mathematical logic dealing with proving mathematical theorems by computer programs.

  • https://github.com/ksluckow/awesome-symbolic-execution
    • Awesome Symbolic Execution A curated list of awesome symbolic execution resources including essential research papers, lectures, videos, and tools.

  • https://angr.io/
    • angr angr is an open-source binary analysis platform for Python. It combines both static and dynamic symbolic ("concolic") analysis, providing tools to solve a variety of tasks.

    • Features:

      • Symbolic Execution: Provides a powerful symbolic execution engine, constraint solving, and instrumentation.
      • Control-Flow Graph Recovery: Provides advanced analysis techniques for control-flow graph recovery.
      • Disassembly & Lifting: Provides convenient methods to disassemble code and lift to an intermediate language.
      • Decompilation: Decompile machine code to angr Intermediate Language (AIL) and C pseudocode.
      • Architecture Support: Supports analysis of several CPU architectures, loading from several executable formats.
      • Extensibility: Provides powerful extensibility for analyses, architectures, platforms, exploration techniques, hooks, and more.
    • https://docs.angr.io/en/latest/
      • Welcome to angr’s documentation!

      • Welcome to angr’s documentation! This documentation is intended to be a guide for learning angr, as well as a reference for the API.

    • https://angr.io/blog/
    • https://github.com/angr
  • https://github.com/Z3Prover/z3
    • The Z3 Theorem Prover

    • https://github.com/Z3Prover/z3/wiki
      • Z3 is an SMT solver and supports the SMTLIB format.

        • https://smtlib.cs.uiowa.edu/
          • SMT-LIB is an international initiative aimed at facilitating research and development in Satisfiability Modulo Theories (SMT).

          • Documents describing the SMT-LIB input/output language for SMT solvers and its semantics;

          • etc
    • https://microsoft.github.io/z3guide/
      • Online Z3 Guide

      • https://github.com/microsoft/z3guide
        • Tutorials and courses for Z3

        • https://microsoft.github.io/z3guide/docs/logic/intro/
          • Introduction Z3 is a state-of-the art theorem prover from Microsoft Research. It can be used to check the satisfiability of logical formulas over one or more theories. Z3 offers a compelling match for software analysis and verification tools, since several common software constructs map directly into supported theories.

            The main objective of the tutorial is to introduce the reader on how to use Z3 effectively for logical modeling and solving. The tutorial provides some general background on logical modeling, but we have to defer a full introduction to first-order logic and decision procedures to text-books in order to develop an in depth understanding of the underlying concepts. To clarify: a deep understanding of logical modeling is not necessarily required to understand this tutorial and modeling with Z3, but it is necessary to understand for writing complex models.

        • https://microsoft.github.io/z3guide/programming/Z3%20JavaScript%20Examples/
          • Z3 JavaScript The Z3 distribution comes with TypeScript (and therefore JavaScript) bindings for Z3. In the following we give a few examples of using Z3 through these bindings. You can run and modify the examples locally in your browser.

  • https://github.com/Samsung/jalangi2
    • Dynamic analysis framework for JavaScript

    • Jalangi2 is a framework for writing dynamic analyses for JavaScript. Jalangi1 is still available at https://github.com/SRA-SiliconValley/jalangi, but we no longer plan to develop it. Jalangi2 does not support the record/replay feature of Jalangi1. In the Jalangi2 distribution you will find several analyses:

      • an analysis to track NaNs.
      • an analysis to check if an undefined is concatenated to a string.
      • Memory analysis: a memory-profiler for JavaScript and HTML5.
      • DLint: a dynamic checker for JavaScript bad coding practices.
      • JITProf: a dynamic JIT-unfriendly code snippet detection tool.
      • analysisCallbackTemplate.js: a template for writing a dynamic analysis.
      • and more ...

      See our tutorial slides for a detailed overview of Jalangi and some client analyses.

    • https://github.com/Samsung/jalangi2#usage
      • Usage

      • Analysis in node.js with on-the-fly instrumentation

      • Analysis in node.js with explicit one-file-at-a-time offline instrumentation

      • Analysis in a browser using a proxy and on-the-fly instrumentation

  • https://github.com/SRA-SiliconValley/jalangi
    • This repository has been archived by the owner on Dec 9, 2017. It is now read-only.

    • We encourage you to switch to Jalangi2 available at https://github.com/Samsung/jalangi2. Jalangi2 is a framework for writing dynamic analyses for JavaScript. Jalangi2 does not support the record/replay feature of Jalangi1. Jalangi1 is still available from this website, but we no longer plan to develop it.

    • Jalangi is a framework for writing heavy-weight dynamic analyses for JavaScript. Jalangi provides two modes for dynamic program analysis: an online mode (a.k.a direct or inbrowser analysis mode)and an offilne mode (a.k.a record-replay analysis mode). In both modes, Jalangi instruments the program-under-analysis to insert callbacks to methods defined in Jalangi. An analysis writer implements these methods to perform custom dynamic program analysis. In the online mode, Jalangi performs analysis during the execution of the program. An analysis in online mode can use shadow memory to attach meta information with every memory location. The offilne mode of Jalangi incorporates two key techniques: 1) selective record-replay, a technique which enables to record and to faithfully replay a user-selected part of the program, and 2) shadow values and shadow execution, which enables easy implementation of heavy-weight dynamic analyses. Shadow values allow an analysis to attach meta information with every value. In the distribution you will find several analyses:

      • concolic testing,
      • an analysis to track origins of nulls and undefined,
      • an analysis to infer likely types of objects fields and functions,
      • an analysis to profile object allocation and usage,
      • a simple form of taint analysis,
      • an experimental pure symbolic execution engine (currently undocumented)
  • https://github.com/ExpoSEJS/ExpoSE
    • ExpoSE

    • A Dynamic Symbolic Execution (DSE) engine for JavaScript. ExpoSE is highly scalable, compatible with recent JavaScript standards, and supports symbolic modelling of strings and regular expressions.

    • ExpoSE is a dynamic symbolic execution engine for JavaScript, developed at Royal Holloway, University of London by Blake Loring, Duncan Mitchell, and Johannes Kinder (now at LMU Munich). ExpoSE supports symbolic execution of Node.js programs and JavaScript in the browser. ExpoSE is based on Jalangi2 and the Z3 SMT solver.

  • https://dl.acm.org/doi/10.1145/2635868.2635913
    • SymJS: automatic symbolic testing of JavaScript web applications (2014)

    • We present SymJS, a comprehensive framework for automatic testing of client-side JavaScript Web applications. The tool contains a symbolic execution engine for JavaScript, and an automatic event explorer for Web pages. Without any user intervention, SymJS can automatically discover and explore Web events, symbolically execute the associated JavaScript code, refine the execution based on dynamic feedbacks, and produce test cases with high coverage. The symbolic engine contains a symbolic virtual machine, a string-numeric solver, and a symbolic executable DOM model. SymJS's innovations include a novel symbolic virtual machine for JavaScript Web, symbolic+dynamic feedback directed event space exploration, and dynamic taint analysis for enhancing event sequence construction. We illustrate the effectiveness of SymJS on standard JavaScript benchmarks and various real-life Web applications. On average SymJS achieves over 90% line coverage for the benchmark programs, significantly outperforming existing methods.

  • https://github.com/javert2/JaVerT2.0
    • JaVerT2.0 - Compositional Symbolic Execution for JavaScript

    • JaVerT: JavaScript Verification Toolchain JaVerT (pronounced [ʒavɛʁ]) is a toolchain for semi-automatic verification of functional correctness properties of JavaScript programs. It is based on separation logic.

    • Deprected - Please use Gillian-JS instead We've built a generalised version of JaVerT2.0 called Gillian, which is currently hosted at https://github.com/GillianPlatform/Gillian

    • https://www.doc.ic.ac.uk/~pg/publications/FragosoSantos2019JaVerT.pdf
      • JaVerT 2.0: Compositional Symbolic Execution for JavaScript (2019)

      • We propose a novel, unified approach to the development of compositional symbolic execution tools, bridging the gap between classical symbolic execution and compositional program reasoning based on separation logic. Using this approach, we build JaVerT 2.0, a symbolic analysis tool for JavaScript that follows the language semantics without simplifications. JaVerT 2.0 supports whole-program symbolic testing, verification, and, for the first time, automatic compositional testing based on bi-abduction. The meta-theory underpinning JaVerT 2.0 is developed modularly, streamlining the proofs and informing the implementation. Our explicit treatment of symbolic execution errors allows us to give meaningful feedback to the developer during wholeprogram symbolic testing and guides the inference of resource of the bi-abductive execution. We evaluate the performance of JaVerT 2.0 on a number of JavaScript data-structure libraries, demonstrating: the scalability of our whole-program symbolic testing; an improvement over the state-of-the-art in JavaScript verification; and the feasibility of automatic compositional testing for JavaScript.

  • https://webblaze.cs.berkeley.edu/2010/kudzu/kudzu.pdf
    • A Symbolic Execution Framework for JavaScript (2010)

    • As AJAX applications gain popularity, client-side JavaScript code is becoming increasingly complex. However, few automated vulnerability analysis tools for JavaScript exist. In this paper, we describe the first system for exploring the execution space of JavaScript code using symbolic execution. To handle JavaScript code’s complex use of string operations, we design a new language of string constraints and implement a solver for it. We build an automatic end-to-end tool, Kudzu, and apply it to the problem of finding client-side code injection vulnerabilities. In experiments on 18 live web applications, Kudzu automatically discovers 2 previously unknown vulnerabilities and 9 more that were previously found only with a manually-constructed test suite.

  • https://www.code-intelligence.com/blog/using-symbolic-execution-fuzzing
    • Why You Should Combine Symbolic Execution and Fuzzing

    • As opposed to traditional fuzzers, which generate inputs without taking code structure into account, symbolic execution tools precisely capture the computation of each value. They use solvers at each branch to generate new inputs and thus to provide the precisely calculated input to cover all parts of code.

    • Symbolic Execution Tools

      • KLEE: KLEE is an open-source code testing instrument that runs on LLVM bitcode, a representation of the program created by the clang compiler. KLEE explores the program and generates test cases to reproduce any crashes it finds.
      • Driller Driller is a concolic execution tool. Concolic execution is a software testing technique that performs symbolic execution (using symbolic input values with sets of expressions, one expression per output variable) with concrete execution (testing on particular inputs) path. The advantage of this approach is that it can achieve high code coverage even in case of complex source code, but still maintain a high degree of scalability and speed.

        Driller uses selective concolic execution to explore only the paths that are found interesting by the fuzzer and to generate inputs for conditions (branches) that a fuzzer cannot satisfy. In other words, it leverages concolic execution to reach deeper program code but uses a feedback-driven/guided fuzzer to alleviate path explosion, which greatly increases the speed of the testing process.

    • Although Driller marked significant research advances in the field of symbolic execution, it is still a highly specialized tool that requires expert knowledge to set up and run and uses up a lot of computational resources. So, how can the industry profit from the latest research?

      Driller and other symbolic or concolic execution tools can be paired with open-source fuzzing tools. Contrary to many traditional fuzzers, modern fuzzers such as AFL++ or libfuzzer do not just generate random inputs. Instead, they use intelligent algorithms to provide inputs that reach deeper into the code structure. Enhancing such fuzzers with concolic execution is highly effective in cases when fuzzing algorithms reach their limits.

      • https://github.com/AFLplusplus/AFLplusplus
        • American Fuzzy Lop plus plus (AFL++)

        • The fuzzer afl++ is afl with community patches, qemu 5.1 upgrade, collision-free coverage, enhanced laf-intel & redqueen, AFLfast++ power schedules, MOpt mutators, unicorn_mode, and a lot more!

        • https://aflplus.plus/
          • AFL++ Overview AFLplusplus is the daughter of the American Fuzzy Lop fuzzer by Michał “lcamtuf” Zalewski and was created initially to incorporate all the best features developed in the years for the fuzzers in the AFL family and not merged in AFL cause it is not updated since November 2017.

      • https://llvm.org/docs/LibFuzzer.html
        • libFuzzer – a library for coverage-guided fuzz testing

        • LibFuzzer is an in-process, coverage-guided, evolutionary fuzzing engine.

          LibFuzzer is linked with the library under test, and feeds fuzzed inputs to the library via a specific fuzzing entrypoint (aka “target function”); the fuzzer then tracks which areas of the code are reached, and generates mutations on the corpus of input data in order to maximize the code coverage. The code coverage information for libFuzzer is provided by LLVM’s SanitizerCoverage instrumentation.

Profiling

Unsorted

  • https://github.com/bytecodealliance/ComponentizeJS
    • ESM -> WebAssembly Component creator, via a SpiderMonkey JS engine embedding

    • Provides a Mozilla SpiderMonkey embedding that takes as input a JavaScript source file and a WebAssembly Component WIT World, and outputs a WebAssembly Component binary with the same interface.

    • https://bytecodealliance.org/articles/making-javascript-run-fast-on-webassembly
      • Making JavaScript run fast on WebAssembly

      • We should be clear here—if you’re running JavaScript in the browser, it still makes the most sense to simply deploy JS. The JS engines within the browsers are highly tuned to run the JS that gets shipped to them.

    • https://github.com/bytecodealliance/wizer
      • The WebAssembly Pre-Initializer Don't wait for your Wasm module to initialize itself, pre-initialize it! Wizer instantiates your WebAssembly module, executes its initialization function, and then snapshots the initialized state out into a new WebAssembly module. Now you can use this new, pre-initialized WebAssembly module to hit the ground running, without making your users wait for that first-time set up code to complete.

        The improvements to start up latency you can expect will depend on how much initialization work your WebAssembly module needs to do before it's ready. Some initial benchmarking shows between 1.35 to 6.00 times faster instantiation and initialization with Wizer, depending on the workload

  • https://wingolog.org/archives/2022/08/18/just-in-time-code-generation-within-webassembly
    • just-in-time code generation within webassembly

  • https://github.com/WebAssembly/wabt
    • The WebAssembly Binary Toolkit

    • WABT (we pronounce it "wabbit") is a suite of tools for WebAssembly, including:

      • wat2wasm: translate from WebAssembly text format to the WebAssembly binary format
      • wasm2wat: the inverse of wat2wasm, translate from the binary format back to the text format (also known as a .wat)
      • wasm-objdump: print information about a wasm binary. Similiar to objdump.
      • wasm-interp: decode and run a WebAssembly binary file using a stack-based interpreter
      • wasm-decompile: decompile a wasm binary into readable C-like syntax.
      • wat-desugar: parse .wat text form as supported by the spec interpreter (s-expressions, flat syntax, or mixed) and print "canonical" flat format
      • wasm2c: convert a WebAssembly binary file to a C source and header
      • wasm-strip: remove sections of a WebAssembly binary file
      • wasm-validate: validate a file in the WebAssembly binary format
      • wast2json: convert a file in the wasm spec test format to a JSON file and associated wasm binary files
      • wasm-stats: output stats for a module
      • spectest-interp: read a Spectest JSON file, and run its tests in the interpreter

      These tools are intended for use in (or for development of) toolchains or other systems that want to manipulate WebAssembly files. Unlike the WebAssembly spec interpreter (which is written to be as simple, declarative and "speccy" as possible), they are written in C/C++ and designed for easier integration into other systems. Unlike Binaryen these tools do not aim to provide an optimization platform or a higher-level compiler target; instead they aim for full fidelity and compliance with the spec (e.g. 1:1 round-trips with no changes to instructions).

  • https://glean.software/
    • Glean System for collecting, deriving and querying facts about source code

    • https://glean.software/docs/introduction/
      • Introduction Glean is a system for working with facts about source code. It is designed for collecting and storing detailed information about code structure, and providing access to the data to power tools and experiences from online IDE features to offline code analysis.

        For example, Glean could answer all the questions you'd expect your IDE to answer, accurately and efficiently on a large-scale codebase. Things like:

        • Where is the definition of this method?
        • Where are all the callers of this function?
        • Who inherits from this class?
        • What are all the declarations in this file?

        But Glean isn't limited to storing particular kinds of data, or answering particular queries. Glean comes with indexers and schemas for some languages which support queries like the examples above, but you can also define your own schemas and store whatever data you like, perhaps augmenting the data that existing indexers collect. So, for example, you could store test coverage data or profiling data.

        Glean's powerful query language means that you can build tools around complex queries of the underlying data. For example, you could search for dead code, write code linters, API migration tools or refactoring tools, all by using Glean queries instead of a compiler API to inspect the code structure.

    • https://github.com/facebookincubator/glean
      • System for collecting, deriving and working with facts about source code.

  • https://github.com/obi1kenobi/trustfall
    • Trustfall — Engine for Querying (Almost) Everything Trustfall is a query engine for querying any kind of data source, from APIs and databases to any kind of files on disk — and even AI models.

    • A query engine for any combination of data sources. Query your files and APIs as if they were databases!

    • https://github.com/obi1kenobi/trustfall#try-trustfall-in-your-browser
      • Try Trustfall in your browser The Trustfall Playground supports running queries against public data sources

    • https://github.com/obi1kenobi/trustfall#10min-tech-talk--demo
      • 10min tech talk + demo Trustfall was featured in the "How to Query (Almost) Everything" talk talk at the HYTRADBOI 2022 conference.

        • https://www.hytradboi.com/2022/how-to-query-almost-everything
        • https://predr.ag/querying/
          • How to Query (Almost) Everything

          • While working at Kensho, I started a query compiler project designed to empower everyone (even non-engineers) to make use of datasets available to them. The query system is responsible for creating a schema covering all available data across all databases, and allows the user to write cross-database queries without needing to know about the location and representation of the various bits of data involved in the query.

          • The project I built at Kensho is now open source on GitHub, under the name GraphQL compiler — in retrospect, a name I somewhat regret since the query language uses GraphQL-compatible syntax but has significant differences in query semantics.

            • https://github.com/kensho-technologies/graphql-compiler
              • graphql-compiler Turn complex GraphQL queries into optimized database queries.

              • GraphQL compiler is a library that simplifies data querying and exploration by exposing one simple query language written using GraphQL syntax to target multiple database backends. It currently supports OrientDB. and multiple SQL database management systems, such as PostgreSQL, MSSQL and MySQL.

          • More recently, I've successfully extended the same ideas beyond querying just databases, and added support for querying APIs, raw files, ML models, or any other data source.

  • AST Query Libs
    • https://github.com/estools/esquery
      • ESQuery ECMAScript AST query library

      • ESQuery is a library for querying the AST output by Esprima for patterns of syntax using a CSS style selector system

    • https://github.com/rse/astq
      • ASTq Abstract Syntax Tree (AST) Query Engine

      • ASTq is an Abstract Syntax Tree (AST) query engine library for JavaScript, i.e., it allows you to query nodes of an arbitary AST-style hierarchical data structure with the help of a powerful XPath-inspired query language. ASTq can operate on arbitrary AST-style data structures through the help of pluggable access adapters.

      • https://github.com/rse/asty-astq
        • ASTy-ASTq Abstract Syntax Tree With Integrated Query Engine

        • ASTy-ASTq, as its name implies, is a combination of the Abstract Syntax Tree (AST) Data Structure library ASTy and the Abstract Syntax Tree (AST) Query Engine Library ASTq. Technically ASTy-ASTq is a super-class of ASTy while it internally integrates ASTq so that each ASTy node has additional compile, execute and query methods available.

      • https://github.com/rse/asty
        • ASTy Abstract Syntax Tree (AST) Data Structure

        • ASTy is a Abstract Syntax Tree (AST) Data Structure library for JavaScript, i.e., it provides a hierarchical data structure for holding the syntax abstraction of an arbitrary formal language. It is usually used in combination with a parser generator like PEG.js (and then especially with its utility class PEGUtil) to carry the results of the parsing step and to provide the vehicle for further processing those results.

My ChatGPT Research / Conversations

These are private chat links, so won't work for others, and are included here only for my reference:

See Also

My Other Related Deepdive Gist's and Projects

Chrome DevTools 'Sources' Extension

Originally articulated here:

  • j4k0xb/webcrack#29
    • add Chrome DevTools extension that allows the web IDE to be used within DevTools

  • pionxzh/wakaru#76
    • add Chrome DevTools extension that allows the web IDE to be used within DevTools

Overview

The following is as I originally wrote it on the above issues, copied here for posterity:

First off, I LOVE the new v2.11.0 update, and the changes to the web IDE to use monaco to support 'references', 'go to declaration', etc.

This issue is about an idea I've had and wanted to work on myself for a while, but haven't got around to it yet. Often when exploring web apps, I make pretty heavy use of Chrome DevTools' 'Search' / 'Sources' / 'Network' / etc tabs, the debugger, and the console / utilities APIs. While there have been some nice improvements to the 'Sources' tab over the years (pretty printing, syntax highlighting, code folding, etc); one area I have really wished it was able to support for a long time now is 'references' / 'go to definition' / similar.

A thought I had in this space is that, while I obviously can't outright replace the 'Sources' tab (which I believe is based on CodeMirror), it should be possible to create a Chrome DevTools Extension that adds a new tab/panel that does similar to the current 'Sources' tab, but using monaco as it's base, and enabling features like 'references' / 'go to definition' / etc within that.

Useful Chrome Extension APIs

Overview of extending DevTools:

Some of the Chrome Extension API's that would be useful/enable this:

Then there are also all of the 'standard' Chrome Extension APIs as well, which can do a lot of cool stuff:

A few of which could be useful for this feature:

And some that are a little more esoteric, but might still be interesting/useful:

Fingerprinting Minified JavaScript Libraries

Table of Contents

See Also

Initial ChatGPT Conversation / Notes

Source: https://chat.openai.com/c/d9b7b64f-aa93-474e-939f-79e376e6d375

Me:

Are there any tools that allow me to identify potentially minified javascript/etc libraries within a webpack or similar bundle?

ChatGPT:

Identifying and fingerprinting minified JavaScript modules within a webpack bundle, regardless of their minification method, can be a challenging task due to the nature of minification and bundling. However, there are approaches and tools you can use to achieve this:

  1. Custom Fingerprinting Script: Given your skills in IT and software engineering, you might consider writing a custom script to analyze the bundles. This script can use heuristics like function and variable name patterns, known code snippets, or specific algorithm implementations to identify libraries. The script can parse the bundle, apply these heuristics, and attempt to match segments of the code with known library patterns.

  2. Entropy Analysis: Minified code typically has higher entropy than non-minified code. By analyzing the entropy of different sections of your bundle, you might be able to identify boundaries between different libraries or modules.

  3. AST Analysis: Abstract Syntax Tree (AST) analysis involves parsing the JavaScript code into a tree structure, which can then be analyzed. You could use AST to look for specific patterns that match known library code structures.

  4. Binary Analysis Tools: Tools like Binwalk, which are traditionally used for analyzing binary files, can sometimes be repurposed for script analysis. They work by scanning files for embedded files and executable code.

  5. Regular Expression Matching: This involves creating regular expressions that match known patterns from popular libraries. While this approach can be time-consuming and may require regular updates, it can be effective for well-known and widely used libraries.

  6. Machine Learning Approaches: With advancements in machine learning, you can train a model to recognize patterns in minified code. This requires a substantial dataset of minified and unminified code to train the model.

  7. Community Databases: Sometimes, the community might maintain databases of fingerprints of popular libraries. These can be used to match against your bundle.

  8. Source Map Reversal: If source maps are available, you can reverse-engineer them to get the original source code, making it easier to identify the libraries.

Remember, the effectiveness of these methods depends on various factors, including the degree of minification, the presence of source maps, and the specific bundling process used. Additionally, given the potential complexity, this might be a time-consuming task, but your background in software engineering and ethical hacking should provide a solid foundation for tackling this challenge.

Me:

Let's work with the following ideas:

Custom Fingerprinting Script: Given your skills in IT and software engineering, you might consider writing a custom script to analyze the bundles. This script can use heuristics like function and variable name patterns, known code snippets, or specific algorithm implementations to identify libraries. The script can parse the bundle, apply these heuristics, and attempt to match segments of the code with known library patterns.

AST Analysis: Abstract Syntax Tree (AST) analysis involves parsing the JavaScript code into a tree structure, which can then be analyzed. You could use AST to look for specific patterns that match known library code structures.

Community Databases: Sometimes, the community might maintain databases of fingerprints of popular libraries. These can be used to match against your bundle.

--

Let's assume that there isn't currently a community database, but that once we figure out an effective way of creating and matching these fingerprints, that we could open source one.

Since we want this to work regardless of whether the library code has been minified or not, we need to take that into account.

How should we approach this?

ChatGPT:

Creating a system to fingerprint JavaScript libraries within a webpack bundle, especially considering the challenges posed by minification, is a multi-step process. The goal is to create a system that can analyze JavaScript code, extract identifiable patterns, and match these against a database of known library fingerprints. Here's a proposed approach:

Establishing a Fingerprinting Methodology

  1. Identify Unique Patterns: Begin by identifying patterns that remain consistent in a library, even after minification. These could include:

    • Unique function signatures.
    • Specific algorithm implementations.
    • Characteristic variable naming schemes that survive minification.
    • Constant values or strings used by the library.
  2. Heuristics for Detection: Develop heuristics to detect these patterns, such as specific function name and parameter combinations, unique method chaining styles, or specific API calls.

Abstract Syntax Tree (AST) Analysis

  1. Parse JavaScript Bundle: Utilize tools like Esprima, Acorn, or Babel to convert JavaScript code into AST, enabling effective analysis of code structure and content.

  2. Pattern Recognition in AST: Implement algorithms for matching parsed code against defined fingerprint criteria, focusing on structural and syntactical patterns and heuristics established earlier. This involves looking for specific node types (like function declarations, variable declarations, etc.) that match the identified patterns.

  3. Handling Minification: Design heuristics and pattern recognition to be resilient to common minification techniques like variable renaming and whitespace removal.

Building and Maintaining the Fingerprint Database

  1. Collecting Fingerprints: Start with popular libraries, analyzing unminified sources to establish baseline fingerprints.

  2. Database Structure and Contributions: Organize the database with library entries, fingerprints, and metadata, and set up a system for validating and integrating community contributions.

Matching Mechanism and Script Integration

  1. Matching Algorithm: Develop an algorithm to compare AST nodes against database fingerprints.

  2. Handling Ambiguities: Design the system to handle cases where a definitive match isn't possible. This could involve ranking potential matches or providing a probability score.

  3. Script Functionality: Ensure the script can process a JavaScript bundle, parse it, and match it against fingerprints. Test the matching algorithm with both minified and unminified versions of known libraries to ensure accuracy.

Handling Minification Variations

  1. Minification Resilience: Ensure your fingerprints are resilient to common minification techniques, like variable renaming and whitespace removal.

  2. Testing Across Minifiers: Test your system with code minified by different tools (e.g., UglifyJS, Terser) to ensure reliability.

User Interface and Accessibility

  1. Ease of Use: Develop a user-friendly interface for both contributing to the database and using the script to identify libraries.

  2. Integration with Development Tools: Consider how your tool could integrate with existing development workflows, such as bundlers or IDEs.

Open Sourcing and Community Engagement

  1. Open Source the Tool: Release the tool and database as open source, encouraging community contributions of new fingerprints and algorithm improvements.

  2. Documentation and Support Channels: Provide thorough documentation and establish channels for community support, feedback, and contributions.

Continuous Improvement and Adaptation

  1. Regular Updates and Algorithm Refinement: Keep the database up-to-date with new library versions and continuously refine matching algorithms based on user feedback and new JavaScript development trends.

  2. Performance Optimization: Optimize for performance, especially when analyzing large bundles, using efficient AST traversal and optimized pattern matching algorithms.

Legal and Ethical Considerations

  1. Respecting Copyright: Ensure that the use of library fingerprints complies with legal and ethical standards, respecting the intellectual property rights of library authors.

This project aligns well with your background in IT and software engineering. The main challenge lies in the nuances of JavaScript minification and the diverse coding patterns across different libraries, but a focused and iterative approach can lead to a robust and useful tool for the community.

Thoughts / comments as I've articulated them elsewhere

On j4k0xb/webcrack

Issue 21: rename short identifiers

When I was exploring this concept in my own deobfuscation PoC project, I was exploring to make the variable names unique + have them add sort of semantic information about their source/scope.

Eg. if it was an arg to a function, it might be arg_1. Or potentially if the function is foo, it might end up as foo_arg_1

It looks like most of the PoC code I was playing with was local/in a pretty messy/hacky state, but I did find a link in it to an online REPL I was playing around with some of it in. Not sure how outdated that code is, but it might be useful:

There were a number of different AST parsers I was playing around with, but I think that this babel code may have been the latest (not sure which one):

Within those files, I believe the functions getNameFromPath, getPrefix (and older commented out functions getTypePrefix, getPrefix


Edit: Came across this in another issue here:

I published my decompiler that I used in the above example. I think it might be a good reference for adding this feature. https://github.com/e9x/krunker-decompiler

Originally posted by @e9x in j4k0xb/webcrack#10 (comment)

And looking at it's libRenameVars code seems to be taking a vaguely similar approach to how I was looking at doing things in my original PoC that I described above:

  • https://github.com/e9x/krunker-decompiler/blob/master/src/libRenameVars.ts
    • getVarPrefix will set a prefix based on the type (eg. func, arg, Class, imported, var)
    • getName generates a new variable name that does not conflict with existing names or reserved keywords
    • generateName generates a new name for a variable considering its scope, type, and the context in which it is used (e.g., whether it's a class, a function variable, etc.). It employs various AST manipulations to ensure the generated name is appropriate and does not conflict with existing names.

A more generalised summary/overview (via ChatGPT):

Certainly, the code implements a sophisticated algorithm for renaming variables in a JavaScript program, adhering to several high-level rules and strategies:

  1. Type-Specific Prefixing:

    • The getVarPrefix function assigns specific prefixes to variable names based on their type (e.g., "func" for function names, "arg" for parameters). This approach helps in identifying the role of a variable just by its name.
  2. Avoiding Reserved Keywords:

    • The script includes a comprehensive list of reserved JavaScript keywords. If a variable's name matches a reserved keyword, it is prefixed with an underscore to prevent syntax errors.
  3. Unique Naming with Context Consideration:

    • The generateName function ensures that each variable gets a unique name that doesn't conflict with other variables in its scope. It also considers the context in which a variable is used. For example, if a variable is part of a class, it may receive a name that reflects this context, using pascalCase or camelCase as appropriate.
  4. Handling Special Cases:

    • The script contains logic to handle special cases, such as variables that are function expressions (isFuncVar) or class instances (isClass). This affects the naming convention applied to these variables.
  5. Randomness with Mersenne Twister:

    • A Mersenne Twister is used to generate random elements for variable names, ensuring that the names are not only unique within the scope of the program but also less predictable.
  6. AST-Based Renaming:

    • The script analyzes the Abstract Syntax Tree (AST) of the program to understand the structure and scope of variables. This analysis guides the renaming process, ensuring that the new names are consistent with the variable's usage and position in the code.
  7. Scope Analysis with ESLint Scope:

    • By leveraging eslint-scope, the script can accurately determine the scope of each variable. This is crucial in avoiding name collisions and ensuring that the renaming respects lexical scoping rules in JavaScript.
  8. Consideration for Exported and Assigned Variables:

    • The script pays special attention to variables that are exported or assigned in specific ways (e.g., through Object.defineProperty). It ensures that these variables receive names that are appropriate for their roles.

In summary, the script uses a combination of type-based naming conventions, context consideration, randomness, AST analysis, and scope analysis to systematically rename variables in a JavaScript program. This approach aims to enhance readability, avoid conflicts, and maintain the logical structure of the program.

Originally posted by @0xdevalias in j4k0xb/webcrack#21 (comment)


And for an even cooler/more extreme version of improving variable naming; I just came across this blog post / project from @jehna that makes use of webcrack + ChatGPT for variable renaming:

  • https://thejunkland.com/blog/using-llms-to-reverse-javascript-minification.html
    • Using LLMs to reverse JavaScript variable name minification This blog introduces a novel way to reverse minified Javascript using large language models (LLMs) like ChatGPT and llama2 while keeping the code semantically intact. The code is open source and available at Github project Humanify.

  • https://github.com/jehna/humanify
    • Un-minify Javascript code using ChatGPT

    • This tool uses large language modeles (like ChatGPT & llama2) and other tools to un-minify Javascript code. Note that LLMs don't perform any structural changes – they only provide hints to rename variables and functions. The heavy lifting is done by Babel on AST level to ensure code stays 1-1 equivalent.

Originally posted by @0xdevalias in j4k0xb/webcrack#21 (comment)


I came across another tool today that seemed to have a start on implementing some 'smart rename' features:

Digging through the code lead me to this:

There's also an issue there that seems to be exploring how to improve 'unmangling variable names' as well:

Which I wrote the following extra thoughts on:

I just finished up writing some thoughts/references for variable renaming on the webcrack repo, that could also be a useful idea for here. (see quotes below)

When I was exploring PoC ideas for my own project previously, I was looking to generate a file similar to the 'module map' that this project is using; but instead of just for the names of modules, I wanted to be able to use it to provide a 'variable name map'. Though because the specific variables used in webpack/etc can change between builds, my thought was that first 'normalising' them to a 'known format' based on their context would make sense to do first.

That could then be letter enhanced/expanded by being able to pre-process these 'variable name mappings' for various open source projects in a way that could then be applied 'automagically' without the end user needing to first create them.

It could also be enhanced by similar techniques such as what the humanify project does, by using LLMs/similar to generate suggested variable name mappings based on the code.

My personal ideal end goal for a feature like that would then allow me to use it within an IDE-like environment, where I can rename variables 'as I explore', knowing that the mappings/etc will be kept up to date.

Originally posted by @0xdevalias in pionxzh/wakaru#34 (comment)

Originally posted by @0xdevalias in j4k0xb/webcrack#21 (comment)


Another link from my reference notes that I forgot to include earlier; my thoughts on how to rename otherwise unknown variables are based on similar concepts that are used in reverse engineering tools such as IDA:

  • https://hex-rays.com/blog/igors-tip-of-the-week-34-dummy-names/
    • In IDA’s disassembly, you may have often observed names that may look strange and cryptic on first sight: sub_73906D75, loc_40721B, off_40A27C and more. In IDA’s terminology, they’re called dummy names. They are used when a name is required by the assembly syntax but there is nothing suitable available

    • https://www.hex-rays.com/products/ida/support/idadoc/609.shtml
      • IDA Help: Names Representation

      • Dummy names are automatically generated by IDA. They are used to denote subroutines, program locations and data. Dummy names have various prefixes depending on the item type and value


And a few more I was looking at recently as well (that is sort of basically smart-rename:

  • https://binary.ninja/2023/09/15/3.5-expanded-universe.html#automatic-variable-naming
    • Automatic Variable Naming One easy way to improve decompilation output is to come up with better default names for variables. There’s a lot of possible defaults you could choose and a number of different strategies are seen throughout different reverse engineering tools. Prior to 3.5, Binary Ninja left variables named based on their origin. Stack variables were var_OFFSET, register-based variables were reg_COUNTER, and global data variables were (data_). While this scheme isn’t changing, we’re being much more intelligent about situations where additional information is available.

      For example, if a variable is passed to a function and a variable name is available, we can now make a much better guess for the variable name. This is most obvious in binaries with type libraries.

    • This isn’t the only style of default names. Binary Ninja also will name loop counters with simpler names like i, or j, k, etc (in the case of nested loops)

  • Vector35/binaryninja-api#2558

Originally posted by @0xdevalias in pionxzh/wakaru#34 (comment)

Originally posted by @0xdevalias in j4k0xb/webcrack#21 (comment)

On pionxzh/wakaru

Issue 34: support un-mangle identifiers

I just finished up writing some thoughts/references for variable renaming on the webcrack repo, that could also be a useful idea for here. (see quotes below)

When I was exploring PoC ideas for my own project previously, I was looking to generate a file similar to the 'module map' that this project is using; but instead of just for the names of modules, I wanted to be able to use it to provide a 'variable name map'. Though because the specific variables used in webpack/etc can change between builds, my thought was that first 'normalising' them to a 'known format' based on their context would make sense to do first.

That could then be later enhanced/expanded by being able to pre-process these 'variable name mappings' for various open source projects in a way that could then be applied 'automagically' without the end user needing to first create them.

It could also be enhanced by similar techniques such as what the humanify project does, by using LLMs/similar to generate suggested variable name mappings based on the code.

My personal ideal end goal for a feature like that would then allow me to use it within an IDE-like environment, where I can rename variables 'as I explore', knowing that the mappings/etc will be kept up to date.


When I was exploring this concept in my own deobfuscation PoC project, I was exploring to make the variable names unique + have them add sort of semantic information about their source/scope.

Eg. if it was an arg to a function, it might be arg_1. Or potentially if the function is foo, it might end up as foo_arg_1

It looks like most of the PoC code I was playing with was local/in a pretty messy/hacky state, but I did find a link in it to an online REPL I was playing around with some of it in. Not sure how outdated that code is, but it might be useful:

There were a number of different AST parsers I was playing around with, but I think that this babel code may have been the latest (not sure which one):

Within those files, I believe the functions getNameFromPath, getPrefix (and older commented out functions getTypePrefix, getPrefix


Edit: Came across this in another issue here:

I published my decompiler that I used in the above example. I think it might be a good reference for adding this feature. https://github.com/e9x/krunker-decompiler

Originally posted by @e9x in j4k0xb/webcrack#10 (comment)

And looking at it's libRenameVars code seems to be taking a vaguely similar approach to how I was looking at doing things in my original PoC that I described above:

  • https://github.com/e9x/krunker-decompiler/blob/master/src/libRenameVars.ts
    • getVarPrefix will set a prefix based on the type (eg. func, arg, Class, imported, var)
    • getName generates a new variable name that does not conflict with existing names or reserved keywords
    • generateName generates a new name for a variable considering its scope, type, and the context in which it is used (e.g., whether it's a class, a function variable, etc.). It employs various AST manipulations to ensure the generated name is appropriate and does not conflict with existing names.

A more generalised summary/overview (via ChatGPT):

Certainly, the code implements a sophisticated algorithm for renaming variables in a JavaScript program, adhering to several high-level rules and strategies:

  1. Type-Specific Prefixing:

    • The getVarPrefix function assigns specific prefixes to variable names based on their type (e.g., "func" for function names, "arg" for parameters). This approach helps in identifying the role of a variable just by its name.
  2. Avoiding Reserved Keywords:

    • The script includes a comprehensive list of reserved JavaScript keywords. If a variable's name matches a reserved keyword, it is prefixed with an underscore to prevent syntax errors.
  3. Unique Naming with Context Consideration:

    • The generateName function ensures that each variable gets a unique name that doesn't conflict with other variables in its scope. It also considers the context in which a variable is used. For example, if a variable is part of a class, it may receive a name that reflects this context, using pascalCase or camelCase as appropriate.
  4. Handling Special Cases:

    • The script contains logic to handle special cases, such as variables that are function expressions (isFuncVar) or class instances (isClass). This affects the naming convention applied to these variables.
  5. Randomness with Mersenne Twister:

    • A Mersenne Twister is used to generate random elements for variable names, ensuring that the names are not only unique within the scope of the program but also less predictable.
  6. AST-Based Renaming:

    • The script analyzes the Abstract Syntax Tree (AST) of the program to understand the structure and scope of variables. This analysis guides the renaming process, ensuring that the new names are consistent with the variable's usage and position in the code.
  7. Scope Analysis with ESLint Scope:

    • By leveraging eslint-scope, the script can accurately determine the scope of each variable. This is crucial in avoiding name collisions and ensuring that the renaming respects lexical scoping rules in JavaScript.
  8. Consideration for Exported and Assigned Variables:

    • The script pays special attention to variables that are exported or assigned in specific ways (e.g., through Object.defineProperty). It ensures that these variables receive names that are appropriate for their roles.

In summary, the script uses a combination of type-based naming conventions, context consideration, randomness, AST analysis, and scope analysis to systematically rename variables in a JavaScript program. This approach aims to enhance readability, avoid conflicts, and maintain the logical structure of the program.

Originally posted by @0xdevalias in j4k0xb/webcrack#21 (comment)


And for an even cooler/more extreme version of improving variable naming; I just came across this blog post / project from @jehna that makes use of webcrack + ChatGPT for variable renaming:

  • https://thejunkland.com/blog/using-llms-to-reverse-javascript-minification.html
    • Using LLMs to reverse JavaScript variable name minification This blog introduces a novel way to reverse minified Javascript using large language models (LLMs) like ChatGPT and llama2 while keeping the code semantically intact. The code is open source and available at Github project Humanify.

  • https://github.com/jehna/humanify
    • Un-minify Javascript code using ChatGPT

    • This tool uses large language modeles (like ChatGPT & llama2) and other tools to un-minify Javascript code. Note that LLMs don't perform any structural changes – they only provide hints to rename variables and functions. The heavy lifting is done by Babel on AST level to ensure code stays 1-1 equivalent.

Originally posted by @0xdevalias in j4k0xb/webcrack#21 (comment)

Originally posted by @0xdevalias in pionxzh/wakaru#34 (comment)

For now, we have smart-rename that can guess the variable name based on the context. I would like to expand it to cover some other generic cases.

Linking to my smart-rename related issues to keep the contextual link here:

Originally posted by @0xdevalias in pionxzh/wakaru#34 (comment)


Another link from my reference notes that I forgot to include earlier; my thoughts on how to rename otherwise unknown variables are based on similar concepts that are used in reverse engineering tools such as IDA:

  • https://hex-rays.com/blog/igors-tip-of-the-week-34-dummy-names/
    • In IDA’s disassembly, you may have often observed names that may look strange and cryptic on first sight: sub_73906D75, loc_40721B, off_40A27C and more. In IDA’s terminology, they’re called dummy names. They are used when a name is required by the assembly syntax but there is nothing suitable available

    • https://www.hex-rays.com/products/ida/support/idadoc/609.shtml
      • IDA Help: Names Representation

      • Dummy names are automatically generated by IDA. They are used to denote subroutines, program locations and data. Dummy names have various prefixes depending on the item type and value

Originally posted by @0xdevalias in j4k0xb/webcrack#21 (comment)


And a few more I was looking at recently as well (that is sort of basically smart-rename:

  • https://binary.ninja/2023/09/15/3.5-expanded-universe.html#automatic-variable-naming
    • Automatic Variable Naming One easy way to improve decompilation output is to come up with better default names for variables. There’s a lot of possible defaults you could choose and a number of different strategies are seen throughout different reverse engineering tools. Prior to 3.5, Binary Ninja left variables named based on their origin. Stack variables were var_OFFSET, register-based variables were reg_COUNTER, and global data variables were (data_). While this scheme isn’t changing, we’re being much more intelligent about situations where additional information is available.

      For example, if a variable is passed to a function and a variable name is available, we can now make a much better guess for the variable name. This is most obvious in binaries with type libraries.

    • This isn’t the only style of default names. Binary Ninja also will name loop counters with simpler names like i, or j, k, etc (in the case of nested loops)

  • Vector35/binaryninja-api#2558

Originally posted by @0xdevalias in pionxzh/wakaru#34 (comment)


Was looking closer at the sourcemap spec today, and the names field jumped out at me as potentially useful:

  • https://tc39.es/source-map-spec/#names
    • names: a list of symbol names used by the mappings entry

  • https://tc39.es/source-map-spec/#mappings
    • mappings: a string with the encoded mapping data (see 4.1 Mappings Structure)

  • https://tc39.es/source-map-spec/#mappings-structure
    • The mappings data is broken down as follows:

      • each group representing a line in the generated file is separated by a semicolon (;)
      • each segment is separated by a comma (,)
      • each segment is made up of 1, 4, or 5 variable length fields.
    • It then goes on to describe the segment's in greater detail, but the specific part I was thinking could be relevant here would be this:
      • If present, the zero-based index into the names list associated with this segment. This field is a base 64 VLQ relative to the previous occurrence of this field unless this is the first occurrence of this field, in which case the whole value is represented.

Obviously if there is a full sourcemap for the webapp, then wakaru isn't really needed anyway.. but what I was thinking of here is that in combination with module detection (see - pionxzh/wakaru#41), if there are sourcemapss available for that original module, then we could potentially extract the original function/variable/etc names from the names field of the sourcemap, and use them in a sort of 'smart-rename with sourcemap' type way.


Another sourcemap related idea I had (which probably deserves it's own issue) is that it would be cool to be able to 'retroactively generate a sourcemap) for a webapp, based on the unminified output from wakaru; such that we could than take that sourcemap, and apply it to the original minified web app source for debugging the live app.

Edit: Created a new issue to track this:

Originally posted by @0xdevalias in pionxzh/wakaru#34 (comment)


It isn't very meaningful to support such a feature when you can access all the source code.

@pionxzh I was specifically talking about it in terms of bundled modules (eg. React, etc), and not the unique web app code of the app itself.

Originally posted by @0xdevalias in pionxzh/wakaru#34 (comment)


You mean like, for popular open-source projects, we can put some sourcemap in our project / read from the chunk, and then reverse map the minified variable and function name back to normal?

@pionxzh Similar to that, but probably not "put the sourcemap in our project" directly; but more process the sourcemaps from popular open-source projects and extract those details to an 'intermediary form'. That 'intermediary form' would be similar to the 'module map' file, as I described earlier in this thread:

When I was exploring PoC ideas for my own project previously, I was looking to generate a file similar to the 'module map' that this project is using; but instead of just for the names of modules, I wanted to be able to use it to provide a 'variable name map'. Though because the specific variables used in webpack/etc can change between builds, my thought was that first 'normalising' them to a 'known format' based on their context would make sense to do first.

That could then be later enhanced/expanded by being able to pre-process these 'variable name mappings' for various open source projects in a way that could then be applied 'automagically' without the end user needing to first create them.

It could also be enhanced by similar techniques such as what the humanify project does, by using LLMs/similar to generate suggested variable name mappings based on the code.

Originally posted by @0xdevalias in pionxzh/wakaru#34 (comment)


A configuration table/profile can be provided to allow users to manually write correspondences. wakaru can simply include the rules of the better known packages.

@StringKe nods, sounds like we are thinking about similar things here :)


Can you specify the content that you would expect to have? and the corresponding behavior

@pionxzh For me personally, I haven't deeply thought through all the use cases in depth, but at a high level I basically want to be able to take a web app that is going to be re-built multiple times, and be able to have a 'config file' similar to the 'module mapping' that wakaru has/had; but that also allows me to specify the variable/function names ('symbols') that are used within it.

The slightly more challenging part is that because the app will be re-built multiple times, the minified variables will change (sometimes every build), so we can't easily use those as the 'key' of the mapping. One idea I had for solving that is potentially by first renaming all of the variables based on a 'stable naming pattern' (eg. func_*, arg_*, const_*, etc; and then could just use a counter/similar based on the 'scope' it's being defined in) that would be generated based on the scope/type of the 'symbol', and would therefore be resilient to the minified variable names changing each build. Those 'stable intermediary names' could then potentially be used for the keys in the variable mapping.

Though then we also need to figure out what level of 'granularity' makes sense to generate those 'stable intermediary names' at; as having a 1:1 mapping of those 'stable name scopes' to JS scopes could potentially end up being really noisy in the mapping file. So maybe using a 'higher abstracted scope' would make more sense (eg. at the module level or similar)

My original hacky implementation of this in my own PoC code was using JS objects/JSON to map an explicit minified variable name to it's 'proper' name; but that broke because the minified names changed between builds. Even by implementing the 'stable naming pattern', if those 'stable names' included a 'counter' in them (eg. func_1, const_8, etc) we still probably wouldn't want to use those stable names directly as the key of an object, as if a new variable was added 'in between' in a later build, that would flow on to 'shifting' the 'counter' for every variable of a matching type afterwards, which would be a lot of effort to manually update in a mapping file. While I haven't thought too deeply about it, I think that by using an array in the mapping file, it should simplify things so that we only need to make a small change to 'fix the mappings' when a new variable is added that 'shifts' everything.

Even by using the array concept in the mappings file, there is still some manual pain/effort involved in trying to keep the mapping 'up to date' in newer builds. That's what lead me into some of the deeper/more esoteric ideas/thinking around 'fingerprinting' that I expand on below.

--

Another area I started looking into (but haven't deeply explored yet) for both figuring out how to map variable names to sections of code in a 'smart' way, and potentially also for module identification (see #41); is in the space of 'structural AST fingerprinting' or 'code similarity' algorithms and similar. (I realise that this is a rather deep/esoteric angle to be looking at this from, and that there are likely going to be far simpler/easier ways to implement the variable mapping/module identification in a 'good enough' way without going to this level of depth; but I'm curious to explore it regardless, to see if any good ideas come out of it)

I haven't gotten too far in my reading yet (got distracted on other things), but the high level of my idea was that maybe we could generate an 'AST fingerprint' that isn't impacted by the variable/function/etc names ('symbols') changing during minification; and then use that as the basis for the 'key' in the 'mappings file'; as that fingerprint could theoretically still identify a 'scope' (which might be a literal JS scope, or might be a higher level abstraction that we decide makes sense; the most abstract being probably at the bundled module level) even if the bundler decides to move some functions around to a different module/etc. Then obviously if we were able to generate those 'resilient fingerprints' to identify code even when it's been minified, that would make perfect sense to apply to module detection/etc (see #41) as well.

Some of the high level ideas / search terms that I was using to start my research in that area was things like:

  • AST fingerprinting
  • Source code similarity fingerprinting
  • Control flow graphs
  • Call flow graphs
  • Program dependence graph
  • etc

Here is a link dump of a bunch of the tabs I have open but haven't got around to reviewing in depth yet, RE: 'AST fingerprinting' / Code Similarity / etc:

Unsorted/Unreviewed Initial Link Dump RE: 'AST fingerprinting' / Code Similarity

--

Another idea I've had, but only lightly explored so far, is looking into how various projects like Terser, Webpack, etc choose their minified variable names in general; but also how they handle 'stable minified variables' between builds (which is something that I know at least Webpack has some concept of). My thought there is that by understanding how they implement their own 'stable minified variables between builds', that we might be able to leverage to either a) do similar, or b) be able to reverse engineer that in a way that might be able to be 'retroactively applied' on top of an existing minified project that didn't use 'stable minified variables', to 'stabilise' them.

Originally posted by @0xdevalias in pionxzh/wakaru#34 (comment)

Issue 41: Module detection

that can help us transform the code and give the extracted module a better name other than module-xxxx.js

This could then also tie in well with some of the ideas for 'unmangling identifiers' that I laid out here:

Theoretically if we can identify a common open source module, we could also have pre-processed that module to extract variable/function names, that we could then potentially apply back to the identified module.

I kind of think of this like 'debug symbols' used in compiled binaries.

Though technically, if you know the module and can get the original source; and you know the webpacked version of that code; you could also generate a sourcemap that lets the user map between the 2 versions of the code.


When I was manually attempting to reverse and identify the modules in #40, a couple of techniques I found useful:

  • searching for Symbol()s
  • searching for React .displayName and similar
  • searching for other arrays of static strings/similar
  • once interesting candidates had been found, searching for them on GitHub code search to try and identify the library/narrow things down

Edit: This might not be useful right now, but just added a new section to one of my gists with some higher level notes/thoughts on fingerprinting modules; that I might expand either directly, or based on how this issue pans out:

While it might be more effort than it's worth, it may also be possible to extract the patterns that wappalyzer was using to identify various libraries; which I made some basic notes on in this revision to the above gist:

Originally posted by @0xdevalias in pionxzh/wakaru#41 (comment)


With regards to module detection/similar for React, these might be interesting/useful:

  • facebook/react#20186
  • facebook/react#27774
  • https://github.com/markerikson/react-prod-sourcemaps
    • A tool to update app sourcemaps with the original code of ReactDOM's production builds

    • This package includes:

      • the actual sourcemaps
      • logic to search an input sourcemap for specific ReactDOM prod artifacts by content hash and replace them with the "original" pre-minified bundle source via the sourcemaps
      • a CLI tool that will load a given input sourcemap file and rewrite it
      • a build tool plugin that will automatically replace react-dom sourcemaps
  • facebook/react#27515 (comment)
    • I don't know how W3Techs counts but the HTTP Archive Almanac 2022 uses Wappalyzer v6.10.26, whose React version detection logic seems to look for (a) a global React.version property or (b) a version number in a script filename that clearly indicates React. Both of these are very uncommon ways to deploy React these days. Even for detecting React as a whole, it uses data attributes no longer used by React or a _reactRootContainer property that is not added when using modern React APIs such as React 18 createRoot (and only looks for that property on divs that are direct children of ).

Originally posted by @0xdevalias in pionxzh/wakaru#41 (comment)


This specific implementation is more related to detecting and injecting into webpack modules at runtime, but it might have some useful ideas/concepts that are applicable at the AST level too:

// ..snip..

export const common = { // Common modules
  React: findByProps('createElement'),
  ReactDOM: findByProps('render', 'hydrate'),

  Flux: findByProps('Store', 'connectStores'),
  FluxDispatcher: findByProps('register', 'wait'),

  i18n: findByProps('Messages', '_requestedLocale'),

  channels: findByProps('getChannelId', 'getVoiceChannelId'),
  constants: findByProps('API_HOST')
};

Originally posted by @0xdevalias in pionxzh/wakaru#41 (comment)

Issue 73: add a 'module graph'

Introducing module graph: Like Webpack and other bundlers, a module graph can help us unminify/rename identifiers and exports from bottom to top.

@pionxzh This sounds like an awesome idea!


Based on 1, the steps gonna be like [unpacked] -> [???] -> [unminify]. This new step will build the module graph, do module scanning, rename the file smartly, and provide this information to unminify.

@pionxzh I've only thought about this a little bit, and it depends on how 'all encompassing' you want the module graph to be, but I think it might even make sense for it (or some other metadata/graph) to capture the mapping from original files -> unmapped as well.

--

For some background context (to help understand some of the things I describe for the graph later on below), the workflow I've been thinking about/following for my own needs would probably be as follows:

  • My original workflow:
    • identify when a new build has been published + the manifest/chunk/etc URLs from that (Ref)
    • download all of the raw script files from the website and save them 'as is' in raw/ (Ref)
    • do a 'first stage' 'light unpack' of the relevant manifest/chunks/etc for this build from raw/ by stripping the hashes from the filenames/etc, run prettier on them, and save in unpacked-stage1; I also manually figure out if any chunks have changed their identifier, and remove any chunks from the old build that no longer exist in the new build (Ref: 1, 2)
  • Additional steps now that I have wakaru:
    • do a 'wakaru unpack' of all of the relevant manifest/chunks/etc in unpacked-stage1/, and save them into unpacked-stage2/
    • do a 'wakaru unminify' of all the modules in unpacked-stage2/, and save them in unminified

While that workflow might be overkill for a lot of people, I like that it allows me to keep the outputs of each of the 'intermediary steps' available, and can cross reference between them if/as needed. I might find that as I start to use this more, that I don't find it useful to keep some of those intermediate steps; but at least for now, that is my workflow.

--

Now with that background context, going back to my thoughts about the graph/etc; I think it would be useful to be able to have a graph/similar that shows:

  • a1-b1-c1-ha-sh/_buildManifest.js contains chunk files ["filefoo-abc123.js", "etc.js"] (Ref)
  • a1-b1-c1-ha-sh/_ssgManifest.js contains chunk files ["ssgbar-abc123.js", "ssg-etc.js"] (Ref)
  • webpack-a2b2c2hash.js contains chunk files ["aaaa-bbbb.js", "etc.js"] (Ref)
  • filefoo-abc123.js contains chunk [1337, ...]
  • chunk 1337
    • contains modules [1, 3, 7, 24]
    • which were renamed to ["module1.js", "aUsefulName.js", "a/path/and/a/reallyUsefulName.js", "module24.js"]

And then the actual 'internal module mapping' stuff of what imports/exports what, etc.

I'm not sure exactly how to map the data, but I would probably start with identifying the main 'types' involved, and what makes sense to know/store about each of them. The following might not be complete, but it's what I came up with from a 'first pass':

  • a 'build'
    • all of the original file names
    • (some of the below may make sense to be nested under this, not sure)
  • build manifest (Ref)
    • original filename
    • build hash
    • renamed to filename
    • chunks (and I think the URL paths that map to them; at least for those related to pages (possibly a next.js thing) (Ref))
  • ssg manifest (Ref)
    • original filename
    • build hash
    • renamed to filename
    • etc? (I haven't actually looked at one of these with real data in it yet)
  • chunk files (of which the webpack.js chunk seems a bit special I think?) (Ref)
    • original filename
    • chunk hash
    • renamed to filename
    • chunk IDs that were included in it
  • chunks/modules
    • original chunk filename/etc?
      • (probably will be the same as the 'chunk files' section above; might be a better way to layout this data, but I thought it probably didn't make sense to nest it under the chunk files structure)
    • chunkID in the bundle
    • moduleIDs in the chunk
  • modules
    • chunkID that originally contained it
    • moduleID from the bundle/chunk
    • filename the module was renamed into
    • imported moduleIDs
    • exports

This 'metadata file' / graph / etc could then potentially also include the stuff I've talked about before (Ref) for being able to 'guide' the variable/function/etc names used during unminification.

--

I haven't thought deeply through the above yet; it might turn out that some of the things I described there might make sense being split into 2 different things; but I wanted to capture it all while it was in my head.


In the module graph, we can have a map for all exported names and top-level variables/functions, which also allows the user to guide the tool to improve the mapping.

Module graph also brings the possibility of cross-module renaming. For example, un-indirect-call shall detect some pattern and rename the minified export name back to the real name.

@pionxzh 👌🏻🎉


I like the idea of "AST fingerprinting". This can also be used in module scanning to replace the current regex implementation.

@pionxzh Definitely. Though I (or you, or someone) need to dig into the concepts a bit more and figure out a practical way to implement it; as currently it's sort of a theory in my mind, but not sure how practical it will be in reality.

Created a new issue for that exploration:

Originally posted by @0xdevalias in pionxzh/wakaru#73 (comment)


I was wanting to visualize the dependencies between my unminified modules, and stumbled across this project:

It mentioned two of it's dependencies, which sound like they could potentially be useful here:


Off the top of my head, I think the 'high level' module-graph within wakaru would probably make the most sense to be linked based on the module ID's, rather than the actual import/exports / module filenames. That way it would be more robust/not need to change as things are renamed/moved around/etc. So these libraries may not be super useful 'as is' for this.


Some useful commands for visualising module dependencies:

# Get the module dependencies as a static .svg image
madge --image graph.svg path/src/app.js

# Get the module dependencies as a graphviz DOT file
madge --dot path/src/app.js > graph.gv

# Get the module dependencies as json
madge --json path/src/app.js > dependencies.json

The graphviz dot output can then be further explored through an interactive tool such as:

If there are missing dependencies, these are worth noting for how to see/improve it:


In addition to the above, a couple of other 'dependency graph' viewers I came across when I was looking for tools for this today:

Originally posted by @0xdevalias in pionxzh/wakaru#73 (comment)


Not 100% sure, but Webpack's stats.json file sounds like it might be relevant here (if not directly, then maybe as a source of inspiration):

Even more tangentially related to this, I've pondered how much we could 're-construct' the files necessary to use tools like bundle analyzer, without having access to the original source (or if there would even be any benefit to trying to do so):

My gut feel is that we probably can figure out most of what we need for it; we probably just can't give accurate sizes for the original pre-minified code, etc; and the module names/etc might not be mappable to their originals unless we have module identification type features (see pionxzh/wakaru#41)

Originally posted by @0xdevalias in 0xdevalias/chatgpt-source-watch#9 (comment)

Originally posted by @0xdevalias in pionxzh/wakaru#121 (comment)

Originally posted by @0xdevalias in pionxzh/wakaru#73 (comment)


The Stack Graph / Scope Graph links/references I shared in pionxzh/wakaru#34 (comment) may be relevant to this issue as well.

Originally posted by @0xdevalias in pionxzh/wakaru#73 (comment)

Issue 74: explore 'AST fingerprinting' for module/function identification (eg. to assist smart / stable renames, etc)

Have been spending some more time in binary reverse engineering land lately, and (re-)stumbled across this tool (Diaphora). While it's focus is on binary reverse engineering, some of the features it mentioned sounded like they would be interesting/useful to look deeper into for this 'AST Fingerprinting' sort of idea, eg.

  • Porting symbol names and comments
  • Similarity ratio calculation
  • Call graph matching calculation
  • Dozens of heuristics based on graph theory, assembler, bytes, functions' features, etc...
  • Pseudo-code based heuristics

There might be some ideas/patterns/algorithms/similar that we could use from there for implementing AST fingerprinting on JS code.


  • http://diaphora.re/
    • Diaphora A Free and Open Source Program Diffing Tool

    • Diaphora (διαφορά, Greek for 'difference') version 3.0 is the most advanced program diffing tool (working as an IDA plugin) available as of today (2023). It was released first during SyScan 2015 and has been actively maintained since this year: it has been ported to every single minor version of IDA since 6.8 to 8.3.

      Diaphora supports versions of IDA >= 7.4 because the code only runs in Python 3.X (Python 3.11 was the last version being tested).

    • https://github.com/joxeankoret/diaphora
      • Diaphora, the most advanced Free and Open Source program diffing tool.

      • Diaphora has many of the most common program diffing (bindiffing) features you might expect, like:

        • Diffing assembler.
        • Diffing control flow graphs.
        • Porting symbol names and comments.
        • Adding manual matches.
        • Similarity ratio calculation.
        • Batch automation.
        • Call graph matching calculation.
        • Dozens of heuristics based on graph theory, assembler, bytes, functions' features, etc...

        However, Diaphora has also many features that are unique, not available in any other public tool. The following is a non extensive list of unique features:

        • Ability to port structs, enums, unions and typedefs.
        • Potentially fixed vulnerabilities detection for patch diffing sessions.
        • Support for compilation units (finding and diffing compilation units).
        • Microcode support.
        • Parallel diffing.
        • Pseudo-code based heuristics.
        • Pseudo-code patches generation.
        • Diffing pseudo-codes (with syntax highlighting!).
        • Scripting support (for both the exporting and diffing processes).
  • https://github.com/FernandoDoming/r2diaphora
    • r2diaphora r2diaphora is a port of Diaphora to radare2 and MariaDB. It also uses r2ghidra as decompiler by default, with support for other decompilers such as pdc.

    • Port of the binary diffing library, diaphora, for radare2 and mariadb

Originally posted by @0xdevalias in pionxzh/wakaru#74 (comment)


The Stack Graph / Scope Graph links/references I shared in pionxzh/wakaru#34 (comment) may be relevant to this issue as well.

Originally posted by @0xdevalias in pionxzh/wakaru#74 (comment)


Some more 'prior art' from the binary reverse engineering world:

  • https://hex-rays.com/products/ida/tech/flirt/in_depth/
    • IDA F.L.I.R.T. Technology: In-Depth

    • One major stumbling block in the disassembly of programs written in modern high level languages is the time required to isolate library functions.

    • To assist IDA users we attempted to create an algorithm to recognize the standard library functions.

    • The idea To address those issues, we created a database of all the functions from all libraries we wanted to recognize. IDA now checks, at each byte of the program being disassembled, whether this byte can mark the start of a standard library function.

      The information required by the recognition algorithm is kept in a signature file. Each function is represented by a pattern. Patterns are first 32 bytes of a function where all variant bytes are marked.

      ..snip..

    • Sequences of bytes are kept in the nodes of the tree.

    • When two functions have the same first 32 bytes, they are stored in the same leaf of the tree. To resolve that situation, we calculate the CRC16 of the bytes starting from position 33 until till the first variant byte. The CRC is stored in the signature file. The number of bytes used to calculate that CRC also needs to be saved, as it differs from function to function.

    • etc

While the exact specifics of that method won't be relevant here (since we're operating on JS, and not raw bytes); some of the more general concepts might be.

Interestingly, that ends up being a more refined version of some binary offset finding code I wrote for another project:

Originally posted by @0xdevalias in pionxzh/wakaru#74 (comment)


I've been thinking about this topic and found this repo when searching for if someone had done it before and/or for a debundler to build it on top of.

@anka-213 Curious (if you're open to/able to share), what your use case for this sort of thing would be?


The basic idea I was imagining was:

  1. First perform some basic normalization of the code
  2. Rename all local variables according to some deterministic scheme

This approach doesn't do any kind of fuzzy matching, but as long as the normalization works well enough and the output doesn't vary in too many ways that are difficult to normalize away depending on e.g. bundler config, it should be fairly reliable.

@anka-213 This basically aligns with one of the ways of how I was thinking it would probably work at a high level as well; though I think the key/crux of it would be figuring out the normalisation (including stabilising or not including variable/function identifiers that churn) in a way that is resilient to all the 'optimisations' a bundler/minifier might choose to make.

That may mean that it would need to run on 'partially unminified' code, though in the ideal case, it should be able to work with as little 'pre-processing' of the minified code as possible; as this module identification would be used as part of the unminification process (for certain aspects).


The approach is kind of similar to how the content addressed programming language Unison does their hashing.

@anka-213 Just had a read through that blog, and it sounds like a really interesting approach!


If we want to allow more fine-grained fingerprinting we could use some kind of De Bruijn index instead for the local variables, so local snippets would have the same variable names regardless of their context. This wouldn't produce valid JS code, but that doesn't matter since the result is only used for hashing, not for output.

@anka-213 I only quickly skimmed the wiki pages for De Bruijn index / De Bruijn notation, so I might not be grasping it fully, but from what I saw, it seems like you could probably model it in a way that would fit the semantics to produce valid JS variable names/code still.


Another method (that I can't remember if I've ever written out in full here) is somewhat based on the more manual approach I was taking at one point:

that can help us transform the code and give the extracted module a better name other than module-xxxx.js

This could then also tie in well with some of the ideas for 'unmangling identifiers' that I laid out here:

Theoretically if we can identify a common open source module, we could also have pre-processed that module to extract variable/function names, that we could then potentially apply back to the identified module.

I kind of think of this like 'debug symbols' used in compiled binaries.

Though technically, if you know the module and can get the original source; and you know the webpacked version of that code; you could also generate a sourcemap that lets the user map between the 2 versions of the code.


When I was manually attempting to reverse and identify the modules in #40, a couple of techniques I found useful:

  • searching for Symbol()s
  • searching for React .displayName and similar
  • searching for other arrays of static strings/similar
  • once interesting candidates had been found, searching for them on GitHub code search to try and identify the library/narrow things down

Edit: This might not be useful right now, but just added a new section to one of my gists with some higher level notes/thoughts on fingerprinting modules; that I might expand either directly, or based on how this issue pans out:

While it might be more effort than it's worth, it may also be possible to extract the patterns that wappalyzer was using to identify various libraries; which I made some basic notes on in this revision to the above gist:

Originally posted by @0xdevalias in pionxzh/wakaru#41 (comment)

Specifically, identifying the types of things that are usually not minified/mangled by a bundler/minifier (Symbol()s, React's .displayName, static strings, etc; and using those parts as the 'source' for the fingerprint/similar. In a way, I guess this could also be considered a type of normalisation.

One benefit of this approach, is that those same 'key identifiers' can be used with GitHub Code search or similar tools to help narrow down and identify an otherwise unknown module/library. This could even probably be partially automated using the GitHub API; and then provide an easy way for users to contribute the relevant details/hash/etc for an identified module back to the 'core database' (in a similar way to how nmap allows users to submit service fingerprints (Ref: 1, 2)

Here is some further 'prior art' from a tool that seems to use this sort of method to target the functions it wants to interact with:

This specific implementation is more related to detecting and injecting into webpack modules at runtime, but it might have some useful ideas/concepts that are applicable at the AST level too:

// ..snip..

export const common = { // Common modules
  React: findByProps('createElement'),
  ReactDOM: findByProps('render', 'hydrate'),

  Flux: findByProps('Store', 'connectStores'),
  FluxDispatcher: findByProps('register', 'wait'),

  i18n: findByProps('Messages', '_requestedLocale'),

  channels: findByProps('getChannelId', 'getVoiceChannelId'),
  constants: findByProps('API_HOST')
};

Originally posted by @0xdevalias in pionxzh/wakaru#41 (comment)


This is potentially more of a generalised/'naive' approach to the problem, but it would also be interesting to see if/how well an embedding model tuned for code would do at solving this sort of problem space:


Also, here's the latest version of my open tabs 'reading list' in this space of things, in case any of it is relevant/interesting/useful here:

Unsorted/Unreviewed Link Dump RE: 'AST fingerprinting' / Code Similarity (v2)
  • https://en.wikipedia.org/wiki/Content_similarity_detection
    • Content similarity detection

  • https://arxiv.org/abs/2306.16171
    • A systematic literature review on source code similarity measurement and clone detection: techniques, applications, and challenges (2023)

    • Measuring and evaluating source code similarity is a fundamental software engineering activity that embraces a broad range of applications, including but not limited to code recommendation, duplicate code, plagiarism, malware, and smell detection. This paper proposes a systematic literature review and meta-analysis on code similarity measurement and evaluation techniques to shed light on the existing approaches and their characteristics in different applications. We initially found over 10000 articles by querying four digital libraries and ended up with 136 primary studies in the field. The studies were classified according to their methodology, programming languages, datasets, tools, and applications. A deep investigation reveals 80 software tools, working with eight different techniques on five application domains. Nearly 49% of the tools work on Java programs and 37% support C and C++, while there is no support for many programming languages. A noteworthy point was the existence of 12 datasets related to source code similarity measurement and duplicate codes, of which only eight datasets were publicly accessible. The lack of reliable datasets, empirical evaluations, hybrid methods, and focuses on multi-paradigm languages are the main challenges in the field. Emerging applications of code similarity measurement concentrate on the development phase in addition to the maintenance.

  • https://link.springer.com/article/10.1007/s10664-017-9564-7
    • A comparison of code similarity analysers (2017)

    • Copying and pasting of source code is a common activity in software engineering. Often, the code is not copied as it is and it may be modified for various purposes; e.g. refactoring, bug fixing, or even software plagiarism. These code modifications could affect the performance of code similarity analysers including code clone and plagiarism detectors to some certain degree. We are interested in two types of code modification in this study: pervasive modifications, i.e. transformations that may have a global effect, and local modifications, i.e. code changes that are contained in a single method or code block. We evaluate 30 code similarity detection techniques and tools using five experimental scenarios for Java source code. These are (1) pervasively modified code, created with tools for source code and bytecode obfuscation, and boiler-plate code, (2) source code normalisation through compilation and decompilation using different decompilers, (3) reuse of optimal configurations over different data sets, (4) tool evaluation using ranked-based measures, and (5) local + global code modifications. Our experimental results show that in the presence of pervasive modifications, some of the general textual similarity measures can offer similar performance to specialised code similarity tools, whilst in the presence of boiler-plate code, highly specialised source code similarity detection techniques and tools outperform textual similarity measures. Our study strongly validates the use of compilation/decompilation as a normalisation technique. Its use reduced false classifications to zero for three of the tools. Moreover, we demonstrate that optimal configurations are very sensitive to a specific data set. After directly applying optimal configurations derived from one data set to another, the tools perform poorly on the new data set. The code similarity analysers are thoroughly evaluated not only based on several well-known pair-based and query-based error measures but also on each specific type of pervasive code modification. This broad, thorough study is the largest in existence and potentially an invaluable guide for future users of similarity detection in source code.

  • https://www.researchgate.net/publication/2840981_Winnowing_Local_Algorithms_for_Document_Fingerprinting
    • Winnowing: Local Algorithms for Document Fingerprinting (2003)

    • Digital content is for copying: quotation, revision, plagiarism, and file sharing all create copies. Document fingerprinting is concerned with accurately identifying copying, including small partial copies, within large sets of documents. We introduce the class of local document fingerprinting algorithms, which seems to capture an essential property of any fingerprinting technique guaranteed to detect copies. We prove a novel lower bound on the performance of any local algorithm. We also develop winnowing, an efficient local fingerprinting algorithm, and show that winnowing's performance is within 33% of the lower bound. Finally, we also give experimental results on Web data, and report experience with Moss, a widely-used plagiarism detection service.

    • https://theory.stanford.edu/~aiken/publications/papers/sigmod03.pdf
  • https://www.researchgate.net/publication/375651686_Source_Code_Plagiarism_Detection_with_Pre-Trained_Model_Embeddings_and_Automated_Machine_Learning
  • https://www.researchgate.net/publication/262322336_A_Source_Code_Similarity_System_for_Plagiarism_Detection
    • A Source Code Similarity System for Plagiarism Detection (2013)

    • Source code plagiarism is an easy to do task, but very difficult to detect without proper tool support. Various source code similarity detection systems have been developed to help detect source code plagiarism. Those systems need to recognize a number of lexical and structural source code modifications. For example, by some structural modifications (e.g. modification of control structures, modification of data structures or structural redesign of source code) the source code can be changed in such a way that it almost looks genuine. Most of the existing source code similarity detection systems can be confused when these structural modifications have been applied to the original source code. To be considered effective, a source code similarity detection system must address these issues. To address them, we designed and developed the source code similarity system for plagiarism detection. To demonstrate that the proposed system has the desired effectiveness, we performed a well-known conformism test. The proposed system showed promising results as compared with the JPlag system in detecting source code similarity when various lexical or structural modifications are applied to plagiarized code. As a confirmation of these results, an independent samples t-test revealed that there was a statistically significant difference between average values of F-measures for the test sets that we used and for the experiments that we have done in the practically usable range of cut-off threshold values of 35–70%.

  • https://www.mdpi.com/2076-3417/10/21/7519
    • A Source Code Similarity Based on Siamese Neural Network (2020)

    • Finding similar code snippets is a fundamental task in the field of software engineering. Several approaches have been proposed for this task by using statistical language model which focuses on syntax and structure of codes rather than deep semantic information underlying codes. In this paper, a Siamese Neural Network is proposed that maps codes into continuous space vectors and try to capture their semantic meaning. Firstly, an unsupervised pre-trained method that models code snippets as a weighted series of word vectors. The weights of the series are fitted by the Term Frequency-Inverse Document Frequency (TF-IDF). Then, a Siamese Neural Network trained model is constructed to learn semantic vector representation of code snippets. Finally, the cosine similarity is provided to measure the similarity score between pairs of code snippets. Moreover, we have implemented our approach on a dataset of functionally similar code. The experimental results show that our method improves some performance over single word embedding method.

  • https://www.researchgate.net/publication/337196468_Detecting_Source_Code_Similarity_Using_Compression
    • Detecting Source Code Similarity Using Compression (2019)

    • Different forms of plagiarism make a fair assessment of student assignments more difficult. Source code plagiarisms pose a significant challenge especially for automated assessment systems aimed for students' programming solutions. Different automated assessment systems employ different text or source code similarity detection tools, and all of these tools have their advantages and disadvantages. In this paper, we revitalize the idea of similarity detection based on string complexity and compression. We slightly adapt an existing, third-party, approach, implement it and evaluate its potential on synthetically generated cases and on a small set of real student solutions. On synthetic cases, we showed that average deviation (in absolute values) from the expected similarity is less than 1% (0.94%). On the real-life examples of student programming solutions we compare our results with those of two established tools. The average difference is around 18.1% and 11.6%, while the average difference between those two tools is 10.8%. However, the results of all three tools follow the same trend. Finally, a deviation to some extent is expected as observed tools apply different approaches that are sensitive to other factors of similarities. Gained results additionally demonstrate open challenges in the field.

    • https://ceur-ws.org/Vol-2508/paper-pri.pdf
  • https://www.nature.com/articles/s41598-023-42769-9
    • Binary code similarity analysis based on naming function and common vector space (2023)

    • Binary code similarity analysis is widely used in the field of vulnerability search where source code may not be available to detect whether two binary functions are similar or not. Based on deep learning and natural processing techniques, several approaches have been proposed to perform cross-platform binary code similarity analysis using control flow graphs. However, existing schemes suffer from the shortcomings of large differences in instruction syntaxes across different target platforms, inability to align control flow graph nodes, and less introduction of high-level semantics of stability, which pose challenges for identifying similar computations between binary functions of different platforms generated from the same source code. We argue that extracting stable, platform-independent semantics can improve model accuracy, and a cross-platform binary function similarity comparison model N_Match is proposed. The model elevates different platform instructions to the same semantic space to shield their underlying platform instruction differences, uses graph embedding technology to learn the stability semantics of neighbors, extracts high-level knowledge of naming function to alleviate the differences brought about by cross-platform and cross-optimization levels, and combines the stable graph structure as well as the stable, platform-independent API knowledge of naming function to represent the final semantics of functions. The experimental results show that the model accuracy of N_Match outperforms the baseline model in terms of cross-platform, cross-optimization level, and industrial scenarios. In the vulnerability search experiment, N_Match significantly improves hit@N, the mAP exceeds the current graph embedding model by 66%. In addition, we also give several interesting observations from the experiments. The code and model are publicly available at https://www.github.com/CSecurityZhongYuan/Binary-Name_Match

  • https://arxiv.org/abs/2305.03843
    • REINFOREST: Reinforcing Semantic Code Similarity for Cross-Lingual Code Search Models (2023)

    • This paper introduces a novel code-to-code search technique that enhances the performance of Large Language Models (LLMs) by including both static and dynamic features as well as utilizing both similar and dissimilar examples during training. We present the first-ever code search method that encodes dynamic runtime information during training without the need to execute either the corpus under search or the search query at inference time and the first code search technique that trains on both positive and negative reference samples. To validate the efficacy of our approach, we perform a set of studies demonstrating the capability of enhanced LLMs to perform cross-language code-to-code search. Our evaluation demonstrates that the effectiveness of our approach is consistent across various model architectures and programming languages. We outperform the state-of-the-art cross-language search tool by up to 44.7%. Moreover, our ablation studies reveal that even a single positive and negative reference sample in the training process results in substantial performance improvements demonstrating both similar and dissimilar references are important parts of code search. Importantly, we show that enhanced well-crafted, fine-tuned models consistently outperform enhanced larger modern LLMs without fine tuning, even when enhancing the largest available LLMs highlighting the importance for open-sourced models. To ensure the reproducibility and extensibility of our research, we present an open-sourced implementation of our tool and training procedures called REINFOREST.

  • https://www.usenix.org/conference/usenixsecurity21/presentation/ahmadi
    • Finding Bugs Using Your Own Code: Detecting Functionally-similar yet Inconsistent Code (2021)

    • Probabilistic classification has shown success in detecting known types of software bugs. However, the works following this approach tend to require a large amount of specimens to train their models. We present a new machine learning-based bug detection technique that does not require any external code or samples for training. Instead, our technique learns from the very codebase on which the bug detection is performed, and therefore, obviates the need for the cumbersome task of gathering and cleansing training samples (e.g., buggy code of certain kinds). The key idea behind our technique is a novel two-step clustering process applied on a given codebase. This clustering process identifies code snippets in a project that are functionally-similar yet appear in inconsistent forms. Such inconsistencies are found to cause a wide range of bugs, anything from missing checks to unsafe type conversions. Unlike previous works, our technique is generic and not specific to one type of inconsistency or bug. We prototyped our technique and evaluated it using 5 popular open source software, including QEMU and OpenSSL. With a minimal amount of manual analysis on the inconsistencies detected by our tool, we discovered 22 new unique bugs, despite the fact that many of these programs are constantly undergoing bug scans and new bugs in them are believed to be rare.

    • https://www.usenix.org/system/files/sec21summer_ahmadi.pdf
  • https://theory.stanford.edu/~aiken/moss/
    • MOSS: A1 System for Detecting Software Similarity

  • https://github.com/fanghon/antiplag
    • antiplag similarity checking software for program codes, documents, and pictures The software mainly checks and compares the similarities between electronic assignments submitted by students. It can detect the similarities between electronic assignments submitted by students and can analyze the content of multiple programming languages ​​​​(such as java, c/c++, python, etc.) and multiple formats (txt, doc, docx, pdf, etc.) Comparative analysis of text and image similarities in multiple formats (png, jpg, gif, bmp, etc.) between English and simplified and traditional Chinese documents, and output codes, texts, and images with high similarity, thereby helping to detect plagiarism between students. the behavior of.

  • https://github.com/dodona-edu/dolos
    • Dolos Dolos is a source code plagiarism detection tool for programming exercises. Dolos helps teachers in discovering students sharing solutions, even if they are modified. By providing interactive visualizations, Dolos can also be used to sensitize students to prevent plagiarism.

    • https://dolos.ugent.be/
    • https://dolos.ugent.be/about/algorithm.html
      • How Dolos works Conceptually, the plagiarism detection pipeline of Dolos can be split into four successive steps:

        • Tokenization
        • Fingerprinting
        • Indexing
        • Reporting
      • Tokenization To be immune against masking plagiarism by techniques such as renaming variables and functions, Dolos doesn't directly process the source code under investigation. It starts by performing a tokenization step using Tree-sitter. Tree-sitter can generate syntax trees for many programming languages, converts source code to a more structured form, and masks specific naming of variables and functions.

      • Fingerprinting To measure similarities between (converted) files, Dolos tries to find common sequences of tokens. More specifically, it uses subsequences of fixed length called k-grams. To efficiently make these comparisons and reduce the memory usage, all k-grams are hashed using a rolling hash function (the one used by Rabin-Karp in their string matching algorithm). The length k of k-grams can be with the -k option.

        To further reduce the memory usage, only a subset of all hashes are stored. The selection of hashes is done by the Winnowing algorithm as described by (Schleimer, Wilkerson and Aiken). In short: only the hash with the smallest numerical value is kept for each window. The window length (in k-grams) can be altered with the -w option.

        The remaining hashes are the fingerprints of the analyzed files. Internally, these are stored as simple integers.

      • Indexing Because Dolos needs to compare all files with each other, it is more efficient to first create an index containing the fingerprints of all files. For each of the fingerprints encountered in any of the files, we store the file and the corresponding line number where we encountered that fingerprint.

        As soon as a fingerprint is stored in the index twice, this is recorded as a match between the two files because they share at least one k-gram.

      • Reporting Dolos finally collects all fingerprints that occur in more than one file and aggregates the results into a report.

        This report contains all file pairs that have at least one common fingerprint, together with some metrics:

        • similarity: the fraction of shared fingerprints between the two files
        • total overlap: the absolute value of shared fingerprints, useful for larger projects
        • longest fragment: the length (in fingerprints) of the longest subsequence of fingerprints matching between the two files, useful when not the whole source code is copied
    • https://dolos.ugent.be/about/languages.html
    • https://dolos.ugent.be/about/publications.html
      • Publications Dolos is developed by Team Dodona at Ghent University in Belgium. Our research is published in the following journals and conferences.

  • https://github.com/danielplohmann/mcrit
    • MinHash-based Code Relationship & Investigation Toolkit (MCRIT) MCRIT is a framework created to simplify the application of the MinHash algorithm in the context of code similarity. It can be used to rapidly implement "shinglers", i.e. methods which encode properties of disassembled functions, to then be used for similarity estimation via the MinHash algorithm. It is tailored to work with disassembly reports emitted by SMDA.

  • https://github.com/BK-SCOSS/scoss
    • scoss A Source Code Similarity System - SCOSS

  • https://github.com/island255/source2binary_dataset_construction
    • Source2binary Dataset Construction This is the repository for the paper "One to One or One to many? What function inline brings to binary similarity analysis".

  • https://github.com/JackHCC/Pcode-Similarity
    • Pcode-Similarity Algorithm for calculating similarity between function and library function.

  • https://github.com/JackHCC/Awesome-Binary-Code-Similarity-Detection-2021
    • Awesome Binary code similarity detection 2021 Awesome list for Binary Code Similarity Detection in 2021

  • https://github.com/Jaso1024/Semantic-Code-Embeddings
    • SCALE: Semantic Code Analysis via Learned Embeddings (2023) 3rd best paper on Artificial Intelligence track | presented at the 2023 International Conference on AI, Blockchain, Cloud Computing and Data Analytics This repository holds the code and supplementary materials for SCALE: Semantic Code Analysis via Learned Embeddings. This research explores the efficacy of contrastive learning alongside large language models as a paradigm for developing a model capable of creating code embeddings indicative of code on a functional level. Existing pre-trained models in NLP have demonstrated impressive success, surpassing previous benchmarks in various language-related tasks. However, when it comes to the field of code understanding, these models still face notable limitations. Code isomorphism, which deals with determining functional similarity between pieces of code, presents a challenging problem for NLP models. In this paper, we explore two approaches to code isomorphism. Our first approach, dubbed SCALE-FT, formulates the problem as a binary classification task, where we feed pairs of code snippets to a Large Language Model (LLM), using the embeddings to predict whether the given code segments are equivalent. The second approach, SCALE-CLR, adopts the SimCLR framework to generate embeddings for individual code snippets. By processing code samples with an LLM and observing the corresponding embeddings, we assess the similarity of two code snippets. These approaches enable us to leverage function-based code embeddings for various downstream tasks, such as code-optimization, code-comment alignment, and code classification. Our experiments on the CodeNet Python800 benchmark demonstrate promising results for both approaches. Notably, our SCALE-FT using Babbage-001 (GPT-3) achieves state-of-the-art performance, surpassing various benchmark models such as GPT-3.5 Turbo and GPT-4. Additionally, Salesforce's 350-million parameter CodeGen, when trained with the SCALE-FT framework, surpasses GPT-3.5 and GPT-4.

  • https://github.com/Aida-yy/binary-sim
  • https://github.com/jorge-martinez-gil/crosslingual-clone-detection
    • Transcending Language Barriers in Software Engineering with Crosslingual Code Clone Detection (2024) Systematic study to determine the best methods to assess the similarity between code snippets in different programming languages

You can also find the first link dump of content in the collapsible in the first post on this issue.

Originally posted by @0xdevalias in pionxzh/wakaru#74 (comment)

On jehna/humanify

Issue 97: More deterministic renames across different versions of the same code

Currently, LLMs often guess variable names differently across various versions of the same JavaScript code. This inconsistency complicates versioning, tracking changes, and merging code for anyone regularly analyzing or modifying applications, extensions, etc.

My suggestion is to create a mapping file that lists generated variable names alongside their LLM-generated alternatives, updated continuously. This would serve as a lookup table for the LLM, helping maintain consistency and reducing variations in the final output. Admittedly, I haven't fully explored the feasibility of this concept, but I believe it would strengthen reverse-engineering processes.

_Originally posted by @neoOpus in jehna/humanify#97


My suggestion is to create a mapping file that lists generated variable names alongside their LLM-generated alternatives

@neoOpus This is similar to an area I have spent a fair bit of time thinking about/prototyping tooling around in the past. One of the bigger issues that you're likely to find here is that with bundlers like webpack/etc, when they minimise the variable names, they won't necessarily choose the same minified variable name for the same code each time. So to make a 'lookup table' type concept work, you first need to be able to stabilise the 'reference key' for each of those variables, even if the bundler chose something different to represent it.

You can find some of my initial hacky prototypes scattered in this repo:

My thoughts/notes on this are scattered around a few places, but these may be some useful/interesting places to start:

You can see an example of a larger scale project where I was trying to stabilise the minified variable names to reduce the 'noise' in large scale source diffing here:

Originally posted by @0xdevalias in jehna/humanify#97 (comment)


Currently, LLMs often guess variable names differently across various versions of the same JavaScript code. This inconsistency complicates versioning, tracking changes, and merging code for anyone regularly analyzing or modifying applications, extensions, etc.

Just to clarify that I'm on the same page here, is the issue that:

  • You have multiple versions of a webapp/website that change over time
  • You un-minify all of them
  • You need to compare their differencies, and it's proving difficult as Humanify does not generate same names for same minified code

This is an interesting problem. I'd love to research some ways to implement this. Especially AST fingerprinting seems promising, thank you @0xdevalias for your links.

Originally posted by @jehna in jehna/humanify#97 (comment)


One issue related to fingerprinting is that most of the stuff in a modern webapp bundle is dependencies. And most of the dependencies probably have public source code. So in theory it would be possible to build a huge database of open source code fingerprints that would match a specific version of a specific code, and to have a tool that deterministically reverses the code to its actual original source.

In theory we could use a similar method to build a local database of already-humanified code, which would make the reverse process more deterministic on subsequent runs.

Originally posted by @jehna in jehna/humanify#97 (comment)


I would like to share an idea I’ve been considering, even though I’m still in the process of researching this topic. I hope it proves to be useful!

My suggestion is to break the code down into smaller, modular functions, which seems to be a practice your script might already be implementing. One approach to enhance this is to replace all variable names with generic placeholders (like a, b, c, d) or numerical identifiers (such as 0001, 0002, 0003) by order of apparency. (I honestly don't know how this can be done but maybe via RegEx or just asking LLM to do it).

Anyway, this would allow for a standardized, minified version of the code. After creating this stripped down and abstracted version, we could calculate a hash of the code as a string. This hash would serve as a unique identifier to track changes portions of the code from different versions of the project and prevent duplicate entries as well as a reference to where to store the future generated variable names. The resulting data could be stored in an appropriate format, such as CSV, NoSQL, or JSON, based on your requirements for speed, scalability, and ease of access.

Next, we could analyze this stored data from a designated project location or a maybe specified subfolder (into .humanifjs). Here, we could leverage language models (LLMs) to generate meaningful variable names based on the context of the functions. This would create a "reference" that can assist in future analyses of the code.

When new versions of the obfuscated code are generated (which will have different variable names), we can apply a similar process to compare them with previously processed versions. By using diff techniques, we can identify changes and maintain a collection of these sub-chunks of code, which would help reduce discrepancies. In most cases, we should see a high degree of similarity unless a particular function’s logic has altered. We can then reassign the previously generated variable names (instead of the original variable names or having to generate different ones) to the new code chunks by feeding them as choices for the LLM or assigning them directly programmatically to reduce the need to consume more tokens for the same chunks.

Additionally, to enhance this process, we could explore various optimizations in how the LLM generates and assigns these variable names, as well as how we handle the storage and retrieval of the chunks.

I look forward to your thoughts on this approach and any suggestions you may have for improving it further!

What would make this work better is to make it able to work take advantage of diff (compare) technics to make some sort of sub-chuncks then keeping them available to reduce the discrepancy, maybe also optimize the generation... I hope this makes sense.

And as you stated here

One issue related to fingerprinting is that most of the stuff in a modern webapp bundle is dependencies. And most of the dependencies probably have public source code. So in theory it would be possible to build a huge database of open source code fingerprints that would match a specific version of a specific code, and to have a tool that deterministically reverses the code to its actual original source.

In theory we could use a similar method to build a local database of already-humanified code, which would make the reverse process more deterministic on subsequent runs.

This would be optimal indeed as it will allow to leverage the collective work to get the best results.

PS: I don't have a good machine right now to do some testing myself, nor an API key that allows me to do them properly.

Originally posted by @neoOpus in jehna/humanify#97 (comment)


One issue related to fingerprinting is that most of the stuff in a modern webapp bundle is dependencies. And most of the dependencies probably have public source code. So in theory it would be possible to build a huge database of open source code fingerprints that would match a specific version of a specific code, and to have a tool that deterministically reverses the code to its actual original source.

@jehna Agreed. This was one of the ideas that first led me down the 'fingerprinting' path. Though instead of 'deterministically reversing the code to the original source' in its entirety (which may also be useful), my plan was first to be able to detect dependencies and mark them as such (as most of the time I don't care to look too deeply at them), and then secondly to just be able to extract the 'canonical variable/function names' from that original source and be able to apply them to my unminified version (similar to how humanify currently uses AI for this step); as that way I know that even if there is some little difference in the actual included code, I won't lose that by replacing it with the original source. These issues on wakaru are largely based on this area of things:

While it's a very minimal/naive attempt, and definitely not the most robust way to approach things, a while back I implemented a really basic 'file fingerprint' method, mostly to assist in figuring out when a chunk had been renamed (but was otherwise largely the same chunk as before), that I just pushed to poc-ast-tools (https://github.com/0xdevalias/poc-ast-tools/commit/b0ef60f8608385c40de2644b3346b1834eb477a0):

When I was implementing it, I was thinking about embeddings, but didn't want to have to send large files to the OpenAI embeddings API; and wanted a quick/simple local approximation of it.

Expanding on this concept to the more general code fingerprinting problem; I would probably look at breaking things down to at least an individual module level, as I believe usually modules tend to coincide with original source files; and maybe even break things down even further to a function level if needed. I would also probably be normalising the code to remove any function/variable identifiers first; and to remove the impact of whitespace differences/etc.

While it's not applied to generating a fingerprint, you can see how I've used some of these techniques in my approach to creating a 'diff minimiser' for identifying newly changed code between builds, while ignoring the 'minification noise / churn':


In theory we could use a similar method to build a local database of already-humanified code, which would make the reverse process more deterministic on subsequent runs.

@jehna Oh true.. yeah, that definitely makes sense. Kind of like a local cache.


One approach to enhance this is to replace all variable names with generic placeholders (like a, b, c, d) or numerical identifiers (such as 0001, 0002, 0003) by order of apparency. (I honestly don't know how this can be done but maybe via RegEx or just asking LLM to do it).

@neoOpus This would be handled by parsing the code into an AST, and then manipulating that AST to rename the variables.

You can see various hacky PoC versions of this with various parsers in my poc-ast-tools repo (I don't remember which is the best/most canonical as I haven't looked at it all for ages), eg:

Which you can see some of the early hacky mapping attempts I was making in these files:

That was the point where I realised I really needed something more robust (such as a proper fingerprint that would survive code minification) to use as the key.


We can then reassign the previously generated variable names (instead of the original variable names or having to generate different ones) to the new code chunks by feeding them as choices for the LLM or assigning them directly programmatically to reduce the need to consume more tokens for the same chunks.

@neoOpus Re-applying the old variable names to the new code wouldn't need an LLM at all, as that part is handled in the AST processing code within humanify:

  • https://thejunkland.com/blog/using-llms-to-reverse-javascript-minification#:~:text=Don%27t%20let%20AI%20touch%20the%20code
    • Don't let AI touch the code Now while LLMs are very good at rephrasing and summarizing, they are not very good at coding (yet). They have inherent randomness, which makes them unsuitable for performing the actual renaming and modification of the code.

      Fortunately renaming a Javascript variable within its scope is a solved problem with traditional tools like Babel. Babel first parses the code into an abstract syntax tree (AST, a machine representation of the code), which is easy to modify using well behaving algorithms.

      This is much better than letting the LLM modify the code on a text level; it ensures that only very specific transformations are carried out so the code's functionality does not change after the renaming. The code is guaranteed to have the original functionality and to be runnable by the computer.


I would like to share an idea I’ve been considering, even though I’m still in the process of researching this topic. I hope it proves to be useful!

@neoOpus At a high level, it seems that the thinking/aspects you've outlined here are more or less in line with what I've discussed previously in the resources I linked to in my first comment above.


PS: I don't have a good machine right now to do some testing myself, nor an API key that allows me to do them properly.

@neoOpus IMO, the bulk of the 'harder parts' of implementing this aren't really LLM related, and shouldn't require a powerful machine. The areas I would suggest most looking into around this are how AST parsing/manipulation works; and then how to create a robust/stable fingerprinting method.

IMO, figuring the ideal method of fingerprinting is probably the largest / potentially hardest 'unknown' in all of this currently (at least to me, since while I started to gather resources for it, I haven't had the time to deep dive into reading/analysing them all):

Off the top of my head, I would probably look at breaking things down to at least an individual module level, as I believe usually modules tend to coincide with original source files; and maybe even break things down even further to a function level if needed; and then generate fingerprints for them.

I would also potentially consider looking at the module/function 'entry/exit' points (eg. imports/exports); or maybe even the entire 'shape' of the module import graph itself.

I would also probably be normalising the code to remove any function/variable identifiers and to remove the impact of whitespace differences/etc; before generating any fingerprints on it.

Another potential method I considered for the fingerprints is identifying the types of elements that tend to remain stable even when minified, and using those as part of the fingerprint. As that is one of the manual methods I used to be able to identify a number of the modules listed here:

Originally posted by @0xdevalias in jehna/humanify#97 (comment)

@milahu
Copy link

milahu commented Feb 15, 2024

eslint rule to rewrite absolute imports to relative imports: path/no-absolute-imports

this is needed to make a webapp work on github pages, where we need relative import paths

see also How to convert absolute imports to relative imports with Rollup.js?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment