Scala executes your comments as code, whoops!

Recently I came across an article about Java executing code in comments by being tricked to decode unicode characters. This means you can include a Line-Feed (LF) or Carriage-Return (CR) in a comment and have the line after it be executed at runtime.

The same trick works for Scala. I tested on 2.12.6 with the following:

$ cat print.scala
object Test {
  def main(args: Array[String]) = {
    // \u000a System.out.println("Hello World!");
    // \u000d System.out.println("Hello World!");

    // \u000d println("hi")
  }
}

$ scala print.scala
Hello World!
Hello World!
hi
          

This trick seems like an arbitrary code execution bug, but with a twist in that the bug doesn't come around until runtime and would typically come about from a sloppy copy/paste job from an untrusted source. Careful code review should catch this as oddly commented out code, but as pointed out when reporting this to Lightbend you could prefix the \u000a with enough spaces to move the code off screen. (In non-line wrapping editors).

Running scalafmt over this example code would highlight the executed code (at the cost of a bug in chopping off part of the unicode expression).

object Test {
  def main(args: Array[String]) = {
    // \u000
    System.out.println("Hello World!");

    // \u000
    println("hi")
  }
}
        

I looked at the following languages to see if they exposed the same flaw, but none seem to.

Python

$ cat print.py
# \u000d print "hi"
Ruby
$ cat print.rb
# \u000d puts "hi"
Rust
$ cat print.rs
fn main() {
  // \u000d \n println!("Hello World!");
}
Go
$ cat print1.go
package main

func main() {
  // \u000d fmt.Println("hi")
}

Posted on 2018-05-11 | View this discussion on Reddit