How to configure xhost to be persistent across reboots in Linux

Introduction

The xhost command is the Linux X-Windows server access control program. Depending on the arguments used, xhost grants or denies user/host access (connections) to the local X-server, thereby allowing or denying users/hosts the ability to display X-Windows-based applications e.g. xclock, graphical installers etc. The purpose of this post is to describe how to configure xhost to be persistent across Linux server reboot, thereby ensuring that users/hosts may continue to display X-Windows applications without privileged user intervention.

Steps to configure xhost persistently

Users/hosts attempting to display/redirect X-Windows applications to a recently rebooted server that is not specifically configured to permit access to it’s X-server will receive the following (partial) error, until such time the System Administrator runs the xhost command:

...
Xlib: connection to "host01.example.com:0.0" refused by server
Xlib: No protocol specified
...

To configure xhost to be persistent across Linux server reboot, perform the following steps.
1. Determine the list of trusted/untrusted hosts (hostnames or IP addresses) that you wish to grant/deny access to the X-server.
2. As a privileged user (root), append the following lines to file /etc/profile file – substitute hostnames for those you identified in Step 1.

...
if [ "$DISPLAY" != "" ]
then
 xhost +host01.example.com +host02.example.com +host03.example.com +host04.example.com
 xhost -host05.example.com
fi
#eof

In the example above, the system is configured to grant hosts host01, host02, host03 and host04 the ability to connect (i.e. display/redirect their X display) to it’s X-server, but to restrict host host05.

Note that hostnames must be resolvable i.e. they must be present in either /etc/hosts or in DNS. The above also assumes the use of bash (/bin/bash), bourne (/bin/sh), korn (/bin/ksh) shells. Furthermore, when added to the /etc/profile file, the xhost+ command is only executed and set when a user is logged into and remains logged into the system graphically.

For security, When the user logs out, the xhost setting is reset. For the xhost setting to remain persistent, a user must remain logged into the system graphically.

3. With the above in place, execute/source the /etc/profile file as root (you may need to chmod the file to be executable (i.e. # chmod u+x /etc/profile) and/or re-login to the system graphically as root, where something similar to the following ought to be observed.

[root@host01 ~]# /etc/profile
host01.example.com being added to access control list
host02.example.com being added to access control list
host03.example.com being added to access control list
host04.example.com being added to access control list
host05.example.com being removed from access control list

The list of authorized/unauthorized hosts will be displayed each time one log into the server.

Related Post