X11 connection rejected because of wrong authentication

Inasmuch as using a frame from Emacs running on the laptop on the larger screen of the desktop machine using `make-frame-on-display' is one of life’s pleasures, it was less than a pleasure when it stopped working with a “X11 connection rejected because of wrong authentication” message after an upgrade of one of the machines.

Several upgrades and much thrashing later, the solution by Gregory Grubbs at http://gregorygrubbs.com/development/get-remote-x-working-in-karmic/ works for me, and the script in the fifth comment by Ben Hyde for running emacsclient makes things even easier than I was used to.

My usual technique was to “ssh -X laptop” from the desktop machine to the laptop and then run `make-frame-on-display' in the Emacs running on the laptop so I can check mail on the bigger screen, but it works (or worked) equally well the other way when I want to, say, take my development environment, open buffers and all, away from my desk.

When you use X11 forwarding with ssh (either by using the -X or -Y option or setting ForwardX11 to "yes“), the connection to the local (desktop) X11 display is forwarded to the remote (laptop) side, but ssh creates a “proxy” X server on the remote machine and sets up Xauthority data in ~/.Xauthority with a random authorization cookie. The shell on the remote machine started by ssh sees the proxy X11 display as, e.g., localhost:10. In the already-running Emacs on the laptop, M-x make-frame-on-display ret localhost:10 ret gets Emacs to use the proxy X11 display to put a frame on the desktop machine. At least that’s how it used to work.

The problem is that recent Ubuntu/Xubuntu releases, probably for your own good, use separate Xauthority data for each login. The laptop’s local login has its Xauthority in /var/run/gdm/auth-for-login-random/database (where “login” is your login name and “random” is a random string), with XAUTHORITY set to point to it. The ssh login, however, still uses (and modifies) ~/.Xauthority.

The workaround, or the driving of a truck straight through the security measures, is to merge the Xauthority data added by the ssh login with the Xauthority data seen by the laptop console login. My brute-strength-and-ignorance approach was a straight merge: from a shell on the laptop (remote) machine, run “xauth merge ~/.Xauthority“.

The script by Gregory Grubb is rather more subtle since it doesn’t jigger with the Xauthority data for the local display, only for displays not ending in :0, and the script in the comment by Ben Hyde takes that one step further by using emacsclient to do the merge, so you can do it all from the shell from the ssh login, so you don’t need physical access to the laptop (remote) machine.