Polyglot Programming HacKSU
$ ./lecture --topic polyglot

POLYGLOT
PROGRAMMING

one file  ·  many languages  ·  one runtime won't tell you
$ python demo.c
Hello from Python!
$ gcc demo.c -o demo && ./demo
Hello from C!
$ diff <(python demo.c) <(./demo)
same file on disk - two completely different execution paths
01 - Definition HacKSU

What is a Polyglot File?

A polyglot file is a single file that is simultaneously valid in two or more languages or formats - each parser reads the same bytes and produces correct, meaningful output.

Core insight

  • Not a bug - exploits formal grammar rules
  • Every language has regions it ignores
  • Hide language B inside language A's ignored regions
  • 100% valid in both languages simultaneously
  • The bytes never change - only the parser does

What we'll cover today

  • HTMLCSSJavaScript - already in every webpage
  • JPEGZIP - binary format tricks
  • CPython - the preprocessor trick
  • BashPython - the exec trick
  • PythonJavaScript - polycompiler library
02 - Parser Mechanics HacKSU

How Do Parsers See the World?

Every language has regions it ignores. Polyglots hide language B inside language A's ignored regions - and vice versa.

Comments

  • #  Python, Bash, Ruby, Perl
  • //  C, C++, Java, JavaScript
  • /* */ C, CSS, Java
  • <!-- --> HTML, XML
  • --  SQL, Lua, Haskell

Skip Regions

  • #if 0 … #endif in C
  • """...""" string literals (Python)
  • /* ... */ block comments
  • heredocs in Bash / Ruby
  • Shebang lines  #!/usr/bin/env

File Format Rules

  • JPEG reads from the start
  • ZIP reads from the end
  • PDF has flexible internal structure
  • Magic bytes checked in first N bytes
  • Trailing data is often ignored
The rule: If parser A ignores region R, and region R is valid in parser B, you can hide language-B code inside R - and vice versa.
03 - HTML + CSS + JavaScript HacKSU

The Web Is Already Polyglot

Every .html file is a polyglot - three parsers, one file, by design.

<!DOCTYPE html>
<html>

  <!-- HTML PARSER reads the structure -->

  <style>
    /* CSS PARSER handles styles */
    body {
      background: #0d0d0d;
      color: var(--green);
      font-family: monospace;
    }
  </style>

  <script>
    // JAVASCRIPT ENGINE runs logic
    document.addEventListener('DOMContentLoaded', () => {
      console.log("three parsers, one file");
    });
  </script>

  <p>Hello, polyglot world!</p>

</html>

HTML Parser

Reads tags, builds the DOM tree. Treats <style> and <script> contents as opaque blobs and hands them off.

CSS Parser

Only processes what's inside <style> tags. The surrounding HTML is completely invisible to it.

JS Engine

Only runs what's inside <script> tags. Has no awareness of HTML or CSS syntax around it.

03b - More Examples HacKSU

More Polyglot Examples

HTML + Python

"""<!--
<!DOCTYPE html>
<html>
  <h1>Hello from the browser!</h1>
</html>
<!--"""

print("Hello from Python!")
# -->

Python: triple-quoted string hides HTML.
Browser: <!-- --> hides Python code.

Shell + Python (shebang trick)

#!/bin/sh
"exec" "python3" "$0" "$@"

import os, sys, platform
print(f"[python {sys.version_info.major}.{sys.version_info.minor}]")
print(f"  OS:    {platform.system()}")
print(f"  Shell: {os.environ.get('SHELL', 'unknown')}")

From examples/bash_python.sh - "exec" is a quoted word in bash but adjacent string literals in Python.

Python + JavaScript

1 // (lambda: exec("nums=[1,2,3,4,5]\nprint('Python:',list(map(lambda x:x**2,nums)))", globals()) or 1)()
lambda: eval("const nums=[1,2,3,4,5]; console.log('JS:', nums.map(x=>x**2));")

The polycompiler output format. Exploits // as floor division (Python) vs line comment (JS), and lambda: as expression prefix (Python) vs labeled statement (JS).

C + Python

#if 0
x = """
#endif
#include <stdio.h>
int main(void) {
    printf("[ C ]  Fibonacci: ");
    /* ... loop ... */
}
#if 0
"""
print("[ Python ]  Fibonacci: ", end="")
# ... loop ...
#endif

From examples/demo.c - the main demo.

04 - Binary Polyglots HacKSU

Binary Polyglots - Images

File format parsers have their own ignored regions. A single file can be a valid JPEG and a valid ZIP archive simultaneously.

┌──────────────────────────────────────┐ │ polyglot.jpg (on disk) │ ├──────────────────────────────────────┤ │ FF D8 FF E0 ... ← JPEG magic bytes │ │ [JPEG image data ................] │ │ [JPEG image data ................] │ │ FF D9 ← JPEG end marker │ ├──────────────────────────────────────┤ │ PK\x03\x04 ... ← ZIP local header │ │ [ZIP file entries ................] │ │ PK\x05\x06 ... ← end-of-central- │ │ directory │ └──────────────────────────────────────┘
Image viewer: reads from the start → sees valid JPEG ✓
ZIP tool:    reads from the end  → sees valid ZIP ✓
Neither parser notices the other's data.

Why it works

  • JPEG spec: parse forward from magic bytes
  • ZIP spec: find end-of-central-dir from the back
  • JPEG ignores all data after FF D9
  • ZIP ignores bytes before its local headers

Real-world examples

  • CTF forensics - classic puzzle type
  • GIFAR - GIF+JAR (Java applet in image)
  • PDF+ZIP - common in competitions
  • Malware - evade file-type content filters
Try it: cat image.jpg archive.zip > polyglot.jpg
Open in an image viewer, then run unzip polyglot.jpg
05 - The C + Python Trick HacKSU

The C + Python Mechanism

We exploit two features: C's #if 0 … #endif preprocessor directive and Python's """…""" triple-quoted strings.

C PREPROCESSOR
#if 0    ← skip until matching #endif
#endif   ← resume normal compilation
#include <stdio.h>
int main(void) {
  printf("[ C ] Fibonacci: ");
  int a = 0, b = 1;
  for (int i = 0; i < 8; i++) { ... }
}
#if 0    ← skip again
#endif
PYTHON INTERPRETER
#if 0    ← Python comment, ignored
x = """  ← triple-quoted string begins
"""     ← string ends, x assigned
print("[ Python ] Fibonacci: ", end="")
a, b = 0, 1
for _ in range(8): ...
#endif   ← Python comment, ignored
C never sees the print() call.  Python never executes the printf(). Both are 100% correct in their own language.
06 - Live Demo: demo.c HacKSU

Demo: examples/demo.c

#if 0
# Run as Python:  python demo.c
# Compile as C:   gcc demo.c -o demo && ./demo
x = """
#endif

#include <stdio.h>

int main(void) {
    printf("[ C ]  Fibonacci: ");
    int a = 0, b = 1;
    for (int i = 0; i < 8; i++) {
        printf("%d ", a);
        int t = a + b; a = b; b = t;
    }
    printf("\n");
    return 0;
}

#if 0
"""
print("[ Python ]  Fibonacci: ", end="")
a, b = 0, 1
for _ in range(8):
    print(a, end=" ")
    a, b = b, a + b
print()

#endif

Run as Python

$ python demo.c
[ Python ] Fibonacci: 0 1 1 2 3 5 8 13

Compile + run as C

$ gcc demo.c -o demo && ./demo
[ C ] Fibonacci: 0 1 1 2 3 5 8 13
Same bytes on disk. Two completely different execution paths. Zero modification between runs.
07 - Bash + Python HacKSU

Bash + Python: The Exec Trick

Uses the difference between quoted words in bash and adjacent string literals in Python.

#!/bin/sh
# Polyglot: valid Bash AND valid Python
# Run as bash:   bash bash_python.sh
# Run as Python: python3 bash_python.sh

"exec" "python3" "$0" "$@"

import os, sys, platform

print(f"[python {sys.version_info.major}.{sys.version_info.minor}]")
print(f"  OS:    {platform.system()} {platform.release()}")
print(f"  Shell: {os.environ.get('SHELL', 'unknown')}")
print(f"  File:  {__file__}")
print()
print("Bash hit 'exec python3' and handed off.")
print("Everything above never ran as bash.")

Bash sees line 6:

"exec" → the exec shell builtin
"python3" "$0" "$@" → its arguments

Shell is replaced by Python running this file. Bash never reaches line 8+.

Python sees line 6:

"exec" "python3" "$0" "$@"
→ four adjacent string literals
→ concatenated: "execpython3$0$@"
→ expression statement, result discarded

No exec happens. Python runs the import + print below.

Key: Python's $0 and $@ are literal strings - no shell expansion. Bash's quoting preserves the builtin name.
07b - Three Languages, One File HacKSU

Bash + Python + C

Combine both tricks: the exec trick for Bash and the #if 0 trick for C. Same file - three runtimes, all valid.

#if 0
"exec" "python3" "$0" "$@"
x = """
#endif

#include <stdio.h>
int main(void) {
    printf("[ C ]  Fibonacci: ");
    int a = 0, b = 1;
    for (int i = 0; i < 8; i++) {
        printf("%d ", a);
        int t = a+b; a = b; b = t;
    }
    printf("\n");
    return 0;
}

#if 0
"""
print("[ Python ]  Fibonacci: ", end="")
a, b = 0, 1
for _ in range(8):
    print(a, end=" ")
    a, b = b, a + b
print()
#endif

Bash sees it

  • #if 0 - comment, ignored
  • "exec" "python3" ... - runs exec, bash replaced by Python
  • Never reaches anything below

Python sees it

  • #if 0 - comment, ignored
  • "exec" "python3" ... - string expression, discarded
  • x = """...""" - C code hidden in a string
  • Fibonacci loop executes

C sees it

  • #if 0 - preprocessor skips exec + x = """
  • #include, main() - compiled normally
  • Second #if 0 skips the Python code
bash triple.c  ·  python3 triple.c  ·  gcc triple.c -o t && ./t
08 - polycompiler HacKSU

polycompiler - Python + JavaScript

An experimental npm package (304 ★) by evanzhoudev that merges Python and JS into one file runnable by both runtimes.  github.com/evanzhoudev/polycompiler

Install + use

npm install -g polycompiler

# Merge your files
polycompiler script.py script.js out.py.js

# Run with either runtime
python3 out.py.js
node    out.py.js

Output format

1 // (lambda: exec("PYTHON CODE", globals()) or 1)()
lambda: eval("JS CODE")

Two lines. That's the whole trick.

The // operator duality

  • Python: // is floor division - line 1 evaluates
  • JavaScript: // is a line comment - line 1 is skipped

The lambda: label duality

  • Python: lambda: creates an uncalled lambda - discarded
  • JavaScript: lambda: is a labeled statement - eval() runs

Limitation

Node.js only executes files with .py.js extension - it refuses other extensions. The output file must be named *.py.js.

08b - polycompiler: live trace HacKSU

How the Two Lines Work

1 // (lambda: exec("nums=[1,2,3,4,5]\nprint('Python:',list(map(lambda x:x**2,nums)))", globals()) or 1)()
lambda: eval("const nums=[1,2,3,4,5]; console.log('JS:    ', nums.map(x => x**2));")
PYTHON READS IT
1
//    ← floor division operator
(lambda: exec("...", globals()) or 1)()
    ↑ lambda is called immediately
     exec() runs the Python code string
     "or 1" ensures result is truthy
     1 // result → integer, discarded
lambda: eval("...")
    ↑ lambda created but never called
     eval() never runs → JS code ignored
JAVASCRIPT READS IT
1
//    ← LINE COMMENT starts here
    ↑ entire rest of line 1 is ignored
     Python code never seen by JS
lambda:
     ↑ LABELED STATEMENT (rare JS syntax)
     "lambda" is just a label name
eval("const nums=[1,2,3,4,5]; console.log(...)")
    ↑ this runs! JS code executes
Demo: python3 examples/python_js.py.js  ·  node examples/python_js.py.js
09 - Why It Matters HacKSU

Why Does This Matter?

Security & CTF

  • CTF challenges hide flags in polyglot files
  • PDF+JS polyglots used in real malware
  • GIFAR bypassed same-origin policy (CVE patched)
  • JPEG+PHP bypasses file upload filters
  • PHAR archives used in PHP deserialization attacks

Parser Literacy

  • Forces deep understanding of grammar rules
  • Exposes hidden assumptions in specs
  • Great compiler/interpreter exercise
  • Reveals why # means different things in C vs Python
  • Builds intuition for format validation bugs

Art & Creativity

  • Quines - programs that print themselves
  • Multi-language quines in competitions
  • Code golf & esoteric programming
  • Images that are also runnable programs
  • The IOCCC (Obfuscated C Contest)

Famous real-world polyglots

  • PHAR polyglots - PHP archive upload bypasses
  • PDF+ZIP - standard CTF forensics puzzle
  • MP4+ZIP - video files that unzip cleanly
  • Polyglot quines - self-printing in 5+ languages
10 - Try It Yourself HacKSU

Try It Yourself

Exercise 1 - Run the demos

# C + Python polyglot
python examples/demo.c
gcc examples/demo.c -o demo && ./demo

# Bash + Python polyglot
bash    examples/bash_python.sh
python3 examples/bash_python.sh

Exercise 2 - Extend demo.c

Add a function that prints your name in both the C and Python sections. Both versions must still compile and run correctly.

Exercise 3 - Binary polyglot

Create a JPEG+ZIP polyglot:

cat photo.jpg archive.zip > poly.jpg

Verify: image viewer still shows the photo.
Verify: unzip poly.jpg extracts files.

Exercise 4 - polycompiler

npm install -g polycompiler

# Write hello.py (print "Hello from Python")
# Write hello.js (console.log("Hello from JS"))
# Compile into one file, run with both
Bonus challenge: Can you make a valid Python + HTML polyglot? What structure would you use? Hint: think about what Python ignores at the top of a file.
12 - Build It Live HacKSU

Build Your Own Polyglot

Fill in the blanks - the structure is already there:

#if 0
x = """
#endif

/* ── YOUR C CODE HERE ──────────────────────────── */

#include <stdio.h>

int main(void) {
    /* TODO: printf("Hello from C!\n"); */


    return 0;
}

/* ─────────────────────────────────────────────── */

#if 0
"""
# ── YOUR PYTHON CODE HERE ──────────────────────

# TODO: print("Hello from Python!")


#endif

Goal

  • Save as my_polyglot.c
  • When run with Python, print Hello from Python!
  • When compiled with GCC, print Hello from C!

Test it

python my_polyglot.c

gcc my_polyglot.c -o mine && ./mine

Hints

  • Python ignores #if 0 - it's just a # comment
  • C ignores everything between #if 0 and #endif
  • x = """...""" hides C code as a Python string
  • Don't change the skeleton - only fill the TODO lines
Stretch: Add a second function that prints your name in both languages.
EOF HacKSU

QUESTIONS?

one file  ·  many languages  ·  infinite curiosity
linkedin  linkedin.com/in/austin-sternberg
github.com/evanzhoudev/polycompiler - Python+JS polyglot tool
angr / CTF platforms - practice binary polyglot forensics
IOCCC - international obfuscated C competition
$ cd polyglot && python examples/demo.c
LinkedIn QR code
scan to connect