Polyglot is a way of programming such that the same source code can run on more than one compilers simultaneously. Sometimes people make it more difficult by requiring the code to behave exactly the same on each programming language.

HITCON CTF 2014 last weekend has a similar challenge where we needed to write a Python2/Python3/Ruby/C/Haskell polyglot code that does the same thing as bash command cat flag.

I couldn’t solve the problem during the competition and later on was quite amazed of how simple the solutions were. Below is the solution from the player t0mcr00se:

b = 3;
a = 2 // 3 –b; c = “””/.inspect.length; <<eos
* 2 /* 5
where (//) x y = x + y
(/*) x y = x + y
{-
– */;
main() { system(“cat flag”); }
/*
“””
import os; os.system(“cat flag”)
“””
eos
system(“cat flag”)
__END__
# -}
main = do { a <- readFile “flag”; putStr a }
– */ // “””

Another one from Ricky Zhou :

hash
# pragma = (/*) ; 1 /* a =a; a ## b = b
main = 1 ## readFile(“flag”) >>= putStr {–
#*/</code>
#if 0
x = ‘puts `cat flag`’ and ‘__import__(“os”).system(“cat flag”)’
eval(x)
#endif
#ifdef __GNUC__
#define True = 1; int main() { system(“cat flag\n”); }
True
#endif
#define Y -}</p>
<p>

It’s fairly easy to modify t0mcr00se’s code to a “Hello World” polyglot just for fun:

b = 3;
a = 2 // 3 –b; c = “””/.inspect.length; <<eos
* 2 /* 5
where (//) x y = x + y
(/*) x y = x + y
{-
– */;
main() { printf(“Hello World!\n”); }
/*
“””
print ‘Hello World!’
“””
eos
print “Hello World!\n”
__END__
# -}
main = do {  putStr “Hello World!\n” }
– */ // “””</p>
<p>