106

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.

Masroor
  • 17,842
  • 29
    \renewcommand – egreg Feb 13 '20 at 10:28
  • 11
    Can you define 'dangerous' here? The obvious one is \write18 followed by other \write operations ... – Joseph Wright Feb 13 '20 at 10:30
  • 1
    In LaTeX \protect is there to overcome the dangerous – New to latex Feb 13 '20 at 10:41
  • 49
    \dagger is a dangerous thing – David Carlisle Feb 13 '20 at 10:43
  • 2
    \def\z{\z}\z will make the process loop forever. – David Carlisle Feb 13 '20 at 10:48
  • 1
    Why \dagger is dangerous thing sir – New to latex Feb 13 '20 at 10:49
  • 5
    @DavidCarlisle surely \ddagger is more dangerous?! However I'd agree that the things that are generally dangerous for computers is the ability to write arbitrary things to arbitrary files... – rbrignall Feb 13 '20 at 10:55
  • 2
    @Newtolatex it's a joke, sorry:-) https://en.wikipedia.org/wiki/Dagger – David Carlisle Feb 13 '20 at 10:58
  • 1
    \mycmd for testing something. It stays there and then, when testing something different much later, naturally again with \mycmd, everything crashes – Raoul Kessels Feb 13 '20 at 13:08
  • 1
    \outer can bite! As can \catcode – Steven B. Segletes Feb 13 '20 at 14:55
  • 1
    @DavidCarlisle You mean \dagger produces a dangerous picture :). But that picture is merely a paper tiger. – Masroor Feb 13 '20 at 14:56
  • 5
    For 1 and 2 you might want to look at some questions under the [tag:security] tag (https://tex.stackexchange.com/q/10418/134574 and https://tex.stackexchange.com/q/358642/134574 for example), and the answer basically is: if you compile \write18{rm -rf /*} with --shell-escape (and Linux) you'll get what you asked for. 3 depends: you can make TeX loop forever with \def~{~}~, but it won't consume that much resources. With Lua you may get better (bad) results. 4 can be made into a list: the limit is your creativity and TeX knowledge :-) – Phelype Oleinik Feb 13 '20 at 15:05
  • 5
    Either --shell-escape or --enable-write18 is dangerous. – Display Name Feb 13 '20 at 15:28
  • \patchcmd (etoolkit package) scares me silly, since you can't see the results. I have found that the most powerful commands are also the most dangerous, so \documentclass and \usepackage qualify. – John Kormylo Feb 13 '20 at 17:52
  • @JohnKormylo \patchcmd (from etoolbox) is pretty well-behaved: it either patches what you asked it to patch, or it does nothing at all. \patchcmd is no more dangerous than \def or \renewcommand. It's even less so, as it only redefines in specific conditions. Of course, what you patch (or (re)define) is up to you, and Here Be Dragons :-) – Phelype Oleinik Feb 13 '20 at 23:49
  • @PhelypeOleinik - But with \def and \newcommand, you can see the final code. With \patchmd you take it on faith that the patch went where you wanted it to go. – John Kormylo Feb 14 '20 at 02:45
  • 1
    @JohnKormylo \patchcmd\cmd{<find>}{<replace>}{Patch worked}{Patch failed} and then \show\cmd is usually enough. But I agree, seeing the full code in the definition is way easier – Phelype Oleinik Feb 14 '20 at 03:26
  • \makeatletter also may come into this list... – MadyYuvi Feb 14 '20 at 07:15

5 Answers5

105

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}
egreg
  • 1,121,712
  • 1
    In cat.4, what happens if I compile the code, then delete the line \renewcommand and recompile the code without that line? – manooooh Feb 14 '20 at 01:58
  • 7
    @manooooh Other errors – egreg Feb 14 '20 at 08:48
  • 1
    @Quuxplusone I added “scripting program” – egreg Feb 14 '20 at 17:37
  • Is there a "denial of service" subcategory of cat 3, on non-LuaTeX, where the malicious code tries to allocate too much memory, and so you get a weird out-of-memory error message instead of a typeset document? (What other resources might be exhaustible? File descriptors? Kernel threads/processes — can you make a TeX "fork bomb"?) – Quuxplusone Feb 14 '20 at 17:50
  • 1
    @Quuxplusone Sorry, that's outside my expertise. On non-LuaTeX engines you can't change the memory allocation during the run: it is fixed at launch time. On the other hand, with -shell-escape you can fork as many processes as you want. – egreg Feb 14 '20 at 17:55
  • 3
    About category 4, redefining a primitive: One of my favorites is: \documentclass{article}\begin{document}\def\else{Ha! Ha!}\end{document} You get: ! LaTeX Error: \begin{document} ended by \end{document}. – Ulrich Diez Feb 14 '20 at 18:56
  • 1
    @UlrichDiez I like redefining \fi in the preamble, which makes LaTeX stop at \begin{document} saying Missing \begin{document}. – egreg Feb 14 '20 at 20:22
  • 1
    @UlrichDiez Unfortunately, the robusting of \end makes your nice error message only appear after some other errors. – egreg Feb 14 '20 at 20:28
  • I don't speak latex much; what does \def\fool{\fool}\fool mean, and in particular, how is it that it does not waste memory, while I believe I see two recursive calls? – Mathieu CAROFF Mar 04 '20 at 14:57
  • @MathieuCAROFF The first part \def\fool{\fool} just defines \fool to have replacement text \fool. It does nothing else. The problem is when \fool is executed: it is replaced by \fool, which is replaced by \fool,… No memory is wasted, because a macro disappears from memory as soon as it is expanded; so the loop cannot stop for memory exhaustion. It just goes on forever. – egreg Mar 04 '20 at 15:01
  • But what exactly happens when you call \renewcommand? What makes it so dangerous? – Jakob W. Mar 05 '20 at 09:46
  • @JakobS It is dangerous if you \renewcommand something you don't know about. A knife is not so dangerous if used correctly… – egreg Mar 05 '20 at 10:13
48

If you have a LaTeX-allergy, then all LaTeX is dangerous. ;-)

To be more serious:

You might be interested in these documents:


A platform independent computer virus
by Keith Allen McMillan
URL: http://vxheaven.0l.wtf/lib/vkm00.html
URL: ftp://ftp.cerias.purdue.edu/pub/doc/viruses/KeithMcMillan-PlatformIndependantVirus.ps

Summary:

In this master-thesis the author elaborates on his research regarding the question whether a platform-independent virus can be implemented in LaTeX.
The author defines viruses as follows: A computer virus is a fragment of a computer program whereof the user of the program is not aware. When the program is executed, the viral fragment takes control and performs the actions it is programmed to perform. Purposes of viruses:

  1. Propagation on the infected computer-system by copying themselves or causing other programs to copy them.
  2. Protecting themselves from detection.
  3. An optional "payload". The "payload" can be malicious action.

The author distinguishes viruses from rabbits—the latter are not fragments but they are entire programs—and worms. Worms are self-contained self-replicating computer programs whose spreading is not focused on the files of the infected computer-system but whose spreading is focused on a network-environment, i.e., making copies of themselves on as many machines as possible.

Towards the end of the master-thesis, the author outlines how to program a virus in LaTeX which can without modification run and spread on a variety of computer platforms as long as these platforms support LaTeX and GNU emacs. In order to prevent unleashing such a virus, the actual code used in his research is not presented. The LaTeX/GNU emacs virus outlined does not have a payload and does only infect LaTeX-files with filename-extension .tex in the current directory where the \documentstyle-directive contains a comment %DoNotInfectMe by placing itself behind that directive.

The author explains that

  • GNU emacs is used for providing the virus with a file containing a list of target-files/.tex-files in the current directory that can be infected.
  • LaTeX is used for processing those macros that do the work of infection.
  • The author outlines how to structure the LaTeX code executed by the virus and the LaTeX macros that constitute the routines of the virus.

Don’t take LaTeX files from strangers
by Steven Checkoway, Hovav Shacham, and Eric Rescorla
URL: https://www.usenix.org/system/files/login/articles/73506-checkoway.pdf
URL: https://hovav.net/ucsd/dist/tex-login.pdf

Quote from the abstract:

TeX, LaTeX, and BibTeX files are a common method of collaboration for computer science professionals. It is widely assumed by users that LaTeX files are safe; that is, that no significant harm can come of running LaTeX on an arbitrary computer. Unfortunately, this is not the case: In this article we describe how to exploit LaTeX to build a virus that spreads between documents on the MiKTeX distribution on Windows XP as well as how to use malicious documents to steal data from web-based LaTeX previewer services.


Are Text-Only Data Formats Safe? Or, Use This LaTeX Class File to Pwn Your Computer
by Steven Checkoway, Hovav Shacham, and Eric Rescorla
URL: https://hovav.net/ucsd/dist/texhack.pdf

Quote from the abstract:

We show that malicious TeX, BIBTeX, and METAPOST files can lead to arbitrary code execution, viral infection, denial of service, and data exfiltration, through thefile I/O capabilities exposed by TeX’s Turing-complete macro language. This calls into doubt the conventional wisdom view that text-only data formats that do not access the network are likely safe. We build a TeX virus that spreads between documents on the MiKTeX distribution on Windows XP; we demonstrate data exfiltration attacks on web-based LaTeX previewer services.


Hacking with LaTeX
by Sebastian Neef
URL: https://0day.work/hacking-with-latex/

The author elaborates on the capability of (La)TeX to create/write and read text files via \input/\read/\write and on \write18. \input/\read/\write could be used for reading/copying/overwriting sensitive files. \write18 can be used for doing harm by exexuting programs.


LaTeX Malicious PDF Generation
by admin
URL: http://blog.9bplus.com/latex-malicious-pdf-generation/

The author outlines that LaTeX is used for creating pdf-files and that there are LaTeX packages like the package movie15 which can be used for integrating .swf-files (Shockwave Flash Files) into .pdf-files. .swf-files in turn can be malicious.
(Remark by me, Ulrich Diez: The "danger" lies in the fact that like many other pdf-creation-tools LaTeX can be used for integrating objects/items into .pdf-files. Integrated objects/items in turn do not necessarily need to be created by means of LaTeX, and can be malicious.)


Summa summarum:

With many of the things explained in these elaborates, the danger does neither come per se from using LaTeX, nor has something to do with producing LaTeX-code with inherent malignancy, but the danger comes from applying LaTeX/LaTeX-code to resources (.swf-files, scripts that get executed by the pdf-viewer, etc) that are not trustworthy/that are compromised.



Someone might (ab)use (La)TeX's capability of writing external files for producing huge garbage-files again and again until the SD-card/the SSD is damaged due to the amount of writing-cycles.



Besides this you can use (La)TeX for writing things in cryptic ways.
When writing my answer to the question "Macro for mass hyper-reference?" I took the opportunity to show some of them.
I leave judging whether this is dangerous to others.
In any case you can write in cryptic ways (where one doesn't immediately see what the code does) directives for creating garbage-files or carrying out \write18-calls.



\outer is a good candidate for generating unintended results.

Making a command \outer after having added it to a hook can cause trouble when it comes to appending to that hook:

The minimal example

\documentclass{article}

\AtEndDocument{\one} \outer \def\one{one} \AtEndDocument{\two} \def\two{two}

\begin{document} \end{document}

delivers

Runaway text?
! Forbidden control sequence found while scanning text of \toks@.
<inserted text> 
                }
l.6 \AtEndDocument{\two}

\outer-tokens inside \if..\else..\fi also trigger error-messages:

The minimal example

\documentclass{article}

\outer\def\macro{}

\begin{document} \iffalse\macro\fi \end{document}

delivers

! Incomplete \iffalse; all text was ignored after line 6.
<inserted text> 
                \fi 
l.6 \iffalse\macro
                  \fi
? 


By the way:

All this does not answer the question whether there is a (single) command in LaTeX that is dangerous.

So I don't understand why this answer of mine gets so many "likes" although it does not really answer the question. ;->

(But using LaTeX's macro-capabilities, you can create macros that can be used as single commands which trigger the execution of a lot of code/of a lot of directives/instructions which have an effect which can probably be considered dangerous.)

Ulrich Diez
  • 28,770
  • 4
    Question: Are those links infected? – manooooh Feb 14 '20 at 02:00
  • 6
    Can you make a small summary of each of the internet links? – AndréC Feb 14 '20 at 07:00
  • 7
    For those who are allergic to LaTeX, I recomment NiTriLe – Tristan Feb 14 '20 at 14:33
  • 2
    @Tristan All the readers of this forum already are in contact with LaTeX. Can NiTriLe alleviate unwanted sequelae/aftereffects? ;-) – Ulrich Diez Feb 14 '20 at 18:32
  • 1
    @manooooh I can't tell you. ;-) (By the way I nowadays tend to use virtual machines that are disposed of in "data-nirvana" after the session.) – Ulrich Diez Feb 14 '20 at 18:40
  • 1
    @UlrichDiez LaTeX allergies are contact-based. While antihistamines and steroids may be necessary to treat any existing reaction, using a NiTriLe layer on top of LaTeX may achieve the desired outcome. – Tristan Feb 17 '20 at 14:38
26

In my opinion the most dangerous command is \globaldefs1. Don't try! ;-)

\documentclass{article}
%\globaldefs1
\begin{document}
\section{Test}
\end{document}

It changes the way definitions work in LaTeX fundamentally. Definitions become global by default. That is, it undermines the way LaTeX works: groups are no longer efficient. As a consequence, everything goes berserk. Of course, if you really know what you are doing, you can use it. Ironically, you may only use it locally.

Of course, as every cat knows, \catcode can also be used to do maximal damage. It can be used in sneaky ways, which must be the reason why it is called cat code .

  • 4
    Since we should not try it, could you elaborate? – Sigur Feb 13 '20 at 23:48
  • 5
    \globaldefs-1 doesn't break as bad, but it's equally fun when it does :-) – Phelype Oleinik Feb 13 '20 at 23:51
  • @sigur I changes the way definitions work in LaTeX fundamentally. Definitions become global by default. That is, it undermines the way LaTeX works: groups are no longer efficient. As a consequence, everything goes berserk. –  Feb 13 '20 at 23:54
  • @PhelypeOleinik Yes, that’s another good example, both of which I consider more dangerous than \renewcommand. The latter does generically only isolated damage. –  Feb 13 '20 at 23:58
  • 1
    Of course, as every cat knows, \catcode can also be used to do maximal damage. It is also sneaky, which is why it is called code –  Feb 14 '20 at 00:01
23

In old times on DOS file systems, a really bad command to use in LaTeX was

\include{chapter.tex}

That looks innocuous, but the spurious extension causes it to open chapter.tex.aux for writing and truncate it, and the old DOS file systems abbreviated the name to be replaced with an empty file as chapter.tex.

At some point of time emTeX, then the prevalent TeX system, refused to open a file named in that manner, but not before many documents had been lost by the unwary.

2

filecontents with the option overwrite. I saw the following in a tex file:

\begin{filecontents*}[overwrite]{filename.tex}
...
\end{filecontents*}

There was a file with the same name as filename.tex in the same directory. I would have lost the original file if I had not changed the name of the file in the filecontents environment.

Andre
  • 969