[Tex/LaTex] Are there any dangerous commands in LaTeX

Securitytex-core

I encountered this question: What is the most dangerous command in SQL?. And a similar one came to my mind,

Are there any dangerous commands in LaTeX?

By dangerous we may mean any or all of these scenarios:

  1. When a particular command is used inadvertently by someone in a file, the command may harm one's system or files.
  2. A command may be put in a file with malicious intent, then the file is given to someone, and when that file is compiled in the remote system, a harm will occur.
  3. A command in a file will cause the compilation process of the file to consume prohibitively high resources.
  4. A command will cause LaTeX or TeX to malfunction and produce unintended results.

When you answer, please include relevant examples, with explanations
of how exactly it will cause harm.

Best Answer

Category 1

\newwrite\out
\immediate\openout\out=\jobname
\immediate\write\out{Fool!}
\bye

This will overwrite the TeX file.

TeX will obey your instructions even if they're foolish. However, it will refuse to write file above the current working directory (under the standard settings of the most common distributions).

Obviously, if the current directory is / and you run TeX with superuser privileges, you can overwrite anything on your system; but this is true of every scripting language interpreter that's able to write out files, so not a specific thing of TeX.

Category 2

If you run TeX with -shell-escape enabled and sufficient privileges, you can execute any program, including rm -f /. So be careful when enabling -shell-escape. Some packages, notably minted require -shell-escape. Examine the input file you receive from other people before processing it.

Category 3

TeX engines different from LuaTeX only allocate a maximum amount of memory.

It's easy to make TeX loop forever without wasting resources with

\def\fool{\fool}\fool

On the other hand, complicated graphics with LuaTeX, that has dynamic allocation of memory, can lead to consuming vast amount of resources.

Category 4

Redefine a primitive in a wrong way and you'll be welcomed by puzzling error messages such as

! A <box> was supposed to be here.
<to be read again> 
                   -
l.9 \end{document}

which is produced by

\documentclass{article}

\renewcommand{\box}[1]{-#1-}

\begin{document}

\box{abc}

\end{document}

The most dangerous command is \renewcommand (or \def). Another instance is the following

\documentclass{article}
\renewcommand{\fi}{whatever}
\begin{document}
\end{document}

that makes LaTeX stop with the very puzzling error message

! LaTeX Error: Missing \begin{document}.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.3 \begin{document}