KVM/Qemu VMs with a multi-screen Spice console – VIII – VM and user specific restrictions for remote-viewer connections – iptables and sudo

The Spice console allows users to access the graphical desktop of a Qemu based virtual machines [VM]. The performance with both data encryption and data compression is excellent, audio is no problem and the required data transfer rates to client-applications as “remote-viewer” are within reasonable limits for a (switched) LAN. In virtualization scenarios where you can organize tasks according to a scheme “one user per VM” Spice is actually an attractive tool – and even professional virtualization environments a “Proxmoxx” and “oVirt” make use of it.

In this series we look at basic setups in self-administered Intranet environments. So far we had some ups and downs regarding the tool remote-viewer. If you want to use it in a desktop virtualization environment it is an almost perfect tool. We also found it to be a very convenient and efficient remote client-tool in an Intranet when we combined it with SSH and internal data compression of the Spice protocol. See:

KVM/Qemu VMs with a multi-screen Spice console – V – remote access via remote-viewer, a network port and a SSH-tunnel
KVM/Qemu VMs with a multi-screen Spice console – IV – remote access via SSH, remote-viewer and a Unix socket
KVM/Qemu VMs with a multi-screen Spice console – III – local access with remote-viewer via a Unix socket

SSH gave us all options we needed to take care of various security issues in remote access scenarios. The KVM/Qemu server could control the interaction of remote-users with VMs by applying user-specific SSH restrictions to port-forwarding. We could establish rules to bind the Spice access to a specific VM to a specific user.

Regarding the last point the combination of remote-viewer, TLS and SASL came as a solid disappointment. TLS worked perfectly. But we had problems with SASL; see:

KVM/Qemu VMs with a multi-screen Spice console – VII – remote-viewer, qemu and SASL authentication
KVM/Qemu VMs with a multi-screen Spice console – VI – remote access with remote-viewer and TLS encryption

We got SASL authentication working in two different ways. The frustrating result of our efforts, however, was that we could not confine the access to the Spice-console of a specific VM to exactly one user.

In the end we found that it might even be better to use TLS and a VM-specific Spice password set in the VM’s XML-domain file. The problem then still is that users could share the password for a specific VM. So, we still could not ensure a scenario “one VM – one UID, only”.

In this article we, therefore, look at measures on remote client-systems to allow a TLS connection to a specific VM on the KVM/Qemu host for exactly one user. We use two different Linux tools – namely iptables and sudo – to achieve this. The recipes given below are interesting in themselves and can be applied to other scenarios where the admin wants to restrict outgoing TCP-connection on a user specific level.

Why do we care about user-specific control for Spice at all?

Assume a situation
in a small Linux oriented office where you run a bunch of VMs for special purposes on a central KVM-server.
You provide e.g. a VM (VM1) with Windows 10 ( 🙁 ) for book-keeping with a program your tax advisor understands. A user “Charlie” with a defined UID should use the VM’s Spice console, but basically only he (and his boss in the evening hours).
You have a second VM (VM2) with a Web-server for development and test purposes. Only user “Maggie” shall have access to the Spice console of VM2 on Mondays and Tuesdays and a user “Anne” on Wednesdays and Thursdays and no one else.
And then there is yet another VM (VM3) which only user “Ralph” shall access via Spice to create documents of a confidential analysis for a governmental organization.
There are multiple Linux client PCs available in the office; any of the user can use and login to any free Linux workstations. None of the user has root rights on the clients and the server.

We have thus defined a scenario of the type

One VM + Spice console    < = >    one user or a group of selected users.

Can you cover such a situation with remote-viewer, TLS and server-based SASL, only?
The answer of my last article was: NO. At least not by simple means. (By the way: It is not the fault of SASL. Remote-viewer, simply and unfortunately, does not provide any system-based data for the realm or for the remote-system which SASL could evaluate. The user has too much freedom …)

Do we need measures on the client-systems?

It is interesting that even Opensuse’s “Virtualization Guide” writes about some required measures on the client (restricting access to specific client-certificates for selected users) when discussing the security for libvirt and vnc as tools to access the graphical desktop of a VM. We have not come to libvirt-based tools in this series, yet, but this is already some indication that restrictions of desktop access to KVM/Qemu based VMs may sometimes require measures on the client. So, let us turn to the client-systems … Of course, we assume that such clients have a Linux OS, in my case a Opensuse Leap 15.2.

Schematic drawing

The following schematic drawing reflects the situation we want to control:
We want to make it impossible user “mybro” to access the Spice console of a VM1. Only “myself” should be able to use VM1’s Spice console via a TLS connection. The other way round: Only user “mybro” shall be allowed to connect to the the Spice console of VM2 with remote-viewer. Cross-connections are forbidden; each user gets access to one defined VM only.

We use the same systems as in the last articles: A KVM/Qemu server host “MySRV” (IP: with a Leap 15.2 OS on it, a test-VM1 “debianx” with a Kali-OS on it and a client-system “MyLAP” (a laptop with a Leap 15.2 OS; IP: On MyLap we have a user “myself” and a user “mybro”. VM1 (“debianx”) gets the (TLS-) port 20002 on the server, and VM2 (“leaptest”) the (TLS-) port 20004.

We shall perform the experiments in this article with a Qemu set up without SASL, but each VM configured for an individual password. (As we already know it will only means a small difference in the form of the authentication dialog. We will not be asked for a username.) The scenario can easily be changed to SASL authentication.

Strategies to allow Spice access to a VM’s desktop only for a specific user

There are three major strategies we can follow:

Strategy 1: We could think about a specific TLS client certificate for a connection to a VM and to make it accessible only to the user in question. Such a
strategy would require that client certificates are supported by Qemu and Spice.

Strategy 2: We could use iptables and add user-specific rules for outgoing data to certain TLS-ports on the server. As user-related rules can only be set for the “output chain” we cannot set any such user-specific filters for our problem on the server.

Strategy 3: We take the choice of the target port on the server away from the user as well as any free access to the remote-viewer command namely by changing file permissions, setting up special sudo rules and/or enforcing him/her to run a shell script which starts remote-viewer with a pre-defined target port for him/her.

The strategies (if working) can be combined. Even if the firewall of strategy 2 failed the user would only get access to a specific VM by restrictions of strategy 3. But all these things are a bit complicated and they all depend on the user not being able to get root rights, the firewall being set up at every system-startup and the sudo rules being tight. This is crucial; our KVM/Qemu server with TLS and SASL could only block connections from certain IPs, but not really users.

We could extend strategy 3 to a network namespace – but it won’t help too much as we then would again need to apply routing and related firewall rules. Or to sudo rules. We could also think about using different networks for different VMs and thus a port-IP-VM-relation – but we would still depend on user-specific firewall rules on the clients.

Strategy 1: What about Spice and TLS client certificates?

Here I come with bad news:
If you activate the option “default_tls_x509_verify = 1” in “/etc/livirt/qemu.conf” it is simply ignored. One can guess it from a lack of required parameters in the qemu-command created by virt-manager. Even if and when you provide client certificates in the required directories on the server and the client. In contrast to VNC-settings there is no option like “spice_tls_x509_verify = 1” available. If you set it by yourself, it is silently ignored.

So, client-certificates will be of no help with Spice and remote-viewer. The situation my be different for the libvirt-dependent “virt-viewer” tool. But this is the topic of a future blog post.

Strategy 2: netfilter/iptables to the rescue

I assume that you have some tool in place on your Linux systems to configure your own iptables-rules. Professionals may write their own scripts. Independent of your interface to netfilter/iptables, it is obvious that working with firewall rules in a productive environment is a risky business. Therefore:

Disclaimer: I take no responsibility whatever for the consequences of the approach describes below and its application to your computers. The iptables-rules have to be tested carefully before making them productive and their setup on Linux hosts must be supervised by an expert.

In my network environments I still cling to the tool “fwbuilder” because it gives you a good graphical overview for most purposes and it allows for more complex configurations than e.g. frontends to firewalld or ufw. So, let me show you how to set up a basic set of user-specific iptables rules with fwbuilder and then have a closer look at the contents of the created statements of the firewall script.

fwbuilder allows you to set up “users” with a defined UID in the object catalog for “services”:

This may seem strange; but the meaning is the following:

  1. Using a “user” as a “service” will trigger the creation of a rule for the OUTPUT chain which matches the user of outgoing connection
    packets against an owner with a defined UID and then triggers a reaction.
  2. To cover the reaction in fwbuilder we “branch off” into a specific rule-set for the user. On the iptables level this corresponds to a user-defined rule-chain as a reaction target.
  3. The filter-rules for data packets in the user-defined chain themselves then lead to certain final reactions in the sense of “allow” or “deny”.

In pseudo-code: IF a user matches an UID THEN apply a set of filter rules with their own final reactions.

In Fwbuilder a set of filter-rules is usually put into an object called “policy”. The following image shows some rules of the main “policy” on “MyLap”:

You see that rules 4 and 5 include users “myself” and “mybro”; the rules branch off to policies “Spice_VM_1” and “Spice_VM_2”, respectively.

Rule 6 blocks a whole bunch of TCP-ports used for VMs on the KVM/Qemu server for any other user than “myself” and “mybro”.

Policy “Spice_VM_1” contains one rule, only:

This rule specifies a certain interface and the IP of the target host “mysrv”. We allow access to port 20002 – corresponding to the TLS port defined for our test VM “debianx” (VM1). Something analogous holds for our second user “mybro”. He gets access to another virtual machine “VM2” which we have bound to port 20004 on the KVM-server for external TLS connections.

Now, let us look at the iptables statements generated by fwbuilder:

    # ================ Table 'filter', automatic rules
    # accept established sessions
    # backup ssh access from a admin host 
    $IPTABLES -A INPUT  -p tcp -m tcp  -s  --dport 22  -m state --state NEW,ESTABLISHED -j  ACCEPT 
    $IPTABLES -A OUTPUT  -p tcp -m tcp  -d  --sport 22  -m state --state ESTABLISHED,RELATED -j ACCEPT

    # ================ Table 'filter', rule set Spice_VM_1
    # Rule Spice_VM_1 0 (eth0)
    echo "Rule Spice_VM_1 0 (eth0)"
    $IPTABLES -N Spice_VM_1
    $IPTABLES -N Cid40091X30615.0
    $IPTABLES -A Spice_VM_1 -o eth0  -p tcp -m tcp  -d   --dport 20002  -m state --state NEW  -j Cid40091X30615.0
    $IPTABLES -A Cid40091X30615.0  -s   -j ACCEPT
    $IPTABLES -A Cid40091X30615.0  -s   -j ACCEPT
    # ================ Table 'filter', rule set Spice_VM_2
    # Rule Spice_VM_2 0 (eth0)
    echo "Rule Spice_VM_2 0 (eth0)"
    $IPTABLES -N Spice_VM_2
    $IPTABLES -N Cid40661X30615.0
    $IPTABLES -A Spice_VM_2 -o eth0  -p tcp -m tcp  -d   --dport 20004  -m state --state NEW  -j Cid40661X30615.0
    $IPTABLES -A Cid40661X30615.0  -s   -j ACCEPT
    $IPTABLES -A Cid40661X30615.0  -s 
    # ================ Table 'filter', rule set Main_Policy
    # Rule Main_Policy 0 (eth0)
    echo "Rule Main_Policy 0 (eth0)"
    # Antispoofing
    $IPTABLES -N In_Main_Policy_0
    $IPTABLES -A INPUT -i eth0   -s   -j In_Main_Policy_0
    $IPTABLES -A INPUT -i eth0   -s   -j In_Main_Policy_0
    $IPTABLES -A FORWARD -i eth0   -s   -j In_Main_Policy_0
    $IPTABLES -A FORWARD -i eth0   -s   -j In_Main_Policy_0
    $IPTABLES -A In_Main_Policy_0  -j LOG  --log-level info --log-prefix "RULE 0 -- DENY "
    $IPTABLES -A In_Main_Policy_0  -j DROP
    # Rule Main_Policy 1 (lo)
    echo "Rule Main_Policy 1 (lo)"
    $IPTABLES -A INPUT -i lo   -m state --state NEW  -j ACCEPT
    $IPTABLES -A OUTPUT -o lo   -m state --state NEW  -j ACCEPT
    # Rule Main_Policy 2 (global)
    echo "Rule Main_Policy 2 (global)"
    #  ICMP, DNS, DHCP 
    $IPTABLES -A OUTPUT -p icmp  -m icmp  --icmp-type 3  -m state --state NEW  -j ACCEPT
    $IPTABLES -A OUTPUT -p icmp  -m icmp  --icmp-type 0/0   -m state --state NEW  -j ACCEPT
    $IPTABLES -A OUTPUT -p icmp  -m icmp  --icmp-type 8/0   -m state --state NEW  -j ACCEPT
    $IPTABLES -A OUTPUT -p icmp  -m icmp  --icmp-type 11/0   -m state --state NEW  -j ACCEPT
    $IPTABLES -A OUTPUT -p icmp  -m icmp  --icmp-type 11/1   -m state --state NEW  -j ACCEPT
    $IPTABLES -A OUTPUT -p tcp -m tcp  --dport 53  -m state --state NEW  -j ACCEPT
    $IPTABLES -A OUTPUT -p udp -m udp  -m multiport  --dports 68,67,53  -m state --state NEW  -j ACCEPT
    # Rule Main_Policy 3 (global)
    echo "Rule Main_Policy 3 (global)"
    $IPTABLES -A OUTPUT -p udp -m udp  --dport 123  -m state --state NEW  -j ACCEPT
    # Rule Main_Policy 4 (global)
    echo "Rule Main_Policy 4 (global)"
    $IPTABLES -A OUTPUT -m owner --uid-owner 1021  -j Spice_VM_1
    # Rule Main_Policy 5 (global)
    echo "Rule Main_Policy 5 (global)"
    $IPTABLES -A OUTPUT -m owner --uid-owner 1022  -j Spice_VM_2
    # Rule Main_Policy 6 (global)
    echo "Rule Main_Policy 6 (global)"
    $IPTABLES -N Out_Main_Policy_6
    $IPTABLES -A OUTPUT -p tcp -m tcp  --dport 20001:20010  -j Out_Main_Policy_6
    $IPTABLES -A Out_Main_Policy_6  -j LOG  --log-level info --log-prefix "RULE 6 -- DENY "
    $IPTABLES -A Out_Main_Policy_6  -j DROP

These are simple rules which the experienced reader will have no difficulty to interpret. (The reader also sees that I have multiple IPs on eth0, but this does not affect our present topic).

I leave the test to you. You should see that user “myself” can access VM1 (debianx) whilst user “mybro” and any other users cannot. User “mybro” instead can access VM2 on the server.

Important note:

Do not forget to write a small systemd service which starts your firewall automatically during the startup of your client-system.

I have written about his topic somewhere else in this blog already. believe me its easy.

Strategy 3: Using sudo

Working with “sudo” and manipulating the file “/etc/sudoers” is somewhat risky. Therefore:

Disclaimer: I take no responsibility whatever for the consequences of the sudo approach describe below and its application to your computers. The sudoer rules have to be tested carefully before the are used in a production environment and their setup must be supervised by an expert.

The settings below work for an Opensuse Leap system – partially due to the default settings there.

A standard problem with sudoer rules for graphical applications is the handling of the access to the X11
display if you need to start programs as another user (e.g. root). (Things may be even worse with Wayland; but I have no experience with it). To keep things simple it is a worthwhile investment to think a bit about the precise nature of your sudo-objective.

In our case we want enforce a user-specific usage of the command remote-viewer. More precisely:

  1. We want to disallow the usage of remote-viewer for most users. And even selected users shall not be able to call or invoke remote-viewer directly and freely.
  2. We want to enforce user-specific arguments to the command “remote-viewer”, if executed by certain selected users.
  3. If possible we do not want to run any remote-tool with root-rights at all.
  4. We want to keep our user-specific firewall rules in place and not to create new ones.
  5. X11-display access shall be possible.

The answer to this challenge is a bit tricky. It first looks like you need to write a separate script (accessible to root) which evaluates UIDs or SUD_UIDs and then calls remote-viewer with appropriate arguments.

But you will then be confronted with problems to access the X11-display of the user issuing the script. In addition rule 3 above forces you to start the required remote-viewer command in the end as a specific user via “sudo -u USER” or “su -c ‘…’ USER”. This in turn forces you to allow “USER” to execute the remote-viewer command anyway according to a specific sudo (!) rule for USER. Therefore, he/she must be able to read and execute the remote-viewer command. But then he/she could execute it outside freely without sudo – and again use any arguments he/she likes. It took me a while to find a way out.

The right approach is to find a rule working for the user in question, first, before you turn to a script as a mediator. On the other side: The user must NOT be allowed to use “remote-viewer” freely – neither by user or group access rights. This seeming contradiction is solved by the following steps on our client-system; we describe the rules below for user “myself”. You must execute most of the commands as root:

  • Step 1: Create a special group, e.g. named “spicegrp”. Do NOT make user “myself” a member of this group!
  • Step 2: Change the ownership and access rights of “/usr/bin/remote-viewer” according to
    • chown root.spicegrp /usr/bin/remote-viewer
    • chmod 750 /usr/bin/remote-viewer
  • Step 3: Check that remote-viewer can no longer be executed by user “myself”.
  • Step 4: Start editing the file “/etc/sudoers” with visudo.
  • Step 5: Add the following lines and turn some existing lines into comments:
    Defaults env_reset
    Defaults:myself env_keep += "DISPLAY"
    #Defaults targetpw   # ask for the password of the target user i.e. root
    #ALL   ALL=(ALL) ALL
    myself ALL=(myself:spicegrp) /usr/bin/remote-viewer -- spice\://mysrv.anraconc.de?tls-port=20002
    # myself ALL=(myself:spicegrp) NOPASSWD: /usr/bin/remote-viewer -- spice\://mysrv.anraconc.de?tls-port=20002
    # mybro ALL=(mybro:spicegrp) NOPASSWD: /usr/bin/remote-viewer -- spice\://mysrv.anraconc.de?tls-port=20004

This is all we basically need for the user myself. An extension to
user “mybro” should be clear. See the commented line for mybro.

The sudoer statements – also the commented ones – deserve some short explanation:
We reset the environment, but we keep some language settings for sudoer users. More important: We keep the “DISPLAY” variable of the environment of sudoer user “myself”. Meaning, it will be available when commands are executed with his/her UID. Hereby, we avoid major X11 trouble. The two commented lines in the middle correspond to the the objective that sudoer users should provide their own passwords instead of the root password to execute the commands in the prescribed form.

And then comes some sudo vodoo:

We only define a rule for the user “myself”: We allow him/her to execute the command remote-viewer with his own UID, but with a different group. This gives him access to “/usr/bin/remote-viewer” under “sudo” conditions ( only !). But, in no way else on a shell’s command line, as he/her no longer has access rights to “/usr/bin/remote-viewer” and is no member of “spicegrp”!

The other part of the magic is that the sudoer-mechanism checks the precise form by which the user in question (here: myself) executes the command. It compares the command exactly to the form given in the rule line including the command’s arguments!

myself ALL=(myself:spicegrp) /usr/bin/remote-viewer -- spice\://mysrv.anraconc.de?tls-port=20002

The command and the arguments to it are together handled as one string for comparison!
Thus we have a user “myself” who can only use remote-viewer with “sudo” and he/she is forced to provide a specific argument. And when he issues the command the firewall rules defined in the first part of this post should open doors to the VM as the execution is done with his/her UID!

What will the required sudo command for a successful access to the VM1 (debianx) at TLS-port 20002 on server MySRV look like:

sudo -u myself -g spicegrp remote-viewer — spice://mysrv.anraconc.de?tls-port=20002

You took notice of the argument for the group?

Test for a sudoer user

Let us test our theory (sorry for the German system messages, tried to translate them):

myself@mylap:~> remote-viewer -- spice://mysrv.anraconc.de?tls-port=20002
-bash: /usr/bin/remote-viewer: Keine Berechtigung
myself@mylap:~> # Keine Berechtigung = No access right
myself@mylap:~> # Now with sudo - but wrong port 20004
myself@mylap:~> sudo -u myself -g spicegrp remote-viewer -- spice://mysrv.anraconc.de?tls-port=20004
[sudo] Passwort für myself: 
Leider darf der Benutzer myself »/usr/bin/remote-viewer -- spice://mysrv.anraconc.de?tls-port=20004« als myself:spicegrp auf mylap.anraconc.de nicht ausführen.
myself@mylap:~> # Translation: Sorry, but user myself is not allowed to execute »/usr/bin/remote-viewer -- spice://beta.rux.anraconb.de?tls-port=20004« as myself:spicegrp on mylap.anraconc.de.
myself@mylap:~> # Now with sudo - but the right port 20002
myself@mylap:~> sudo -u myself -g spicegrp remote-viewer -- spice://mysrv.anraconc.de?tls-port=20002

And now we get the familiar dialog to authenticate :

Our firewall obviously has let us through. And – after filling in the VM-specific password (we work without SASL here; see above), we get:

I leave
it to the reader extend the whole thing to two users and to test all combinations out.

Making things a bit easier for the users

An authorized user has to type a lot of things to make the sudo command work. One thing, you can think about, is to not require a password for the sudo command. (Personally, I would not do this; a password is a last security barrier in case of configuration mistakes. But, in principle it is possible to work without a password in this specific case – after you have checked out and tested all security implications). The entry in the “/etc/sudoers” file then would look like

myself ALL=(myself:spicegrp) NOPASSWD: /usr/bin/remote-viewer -- spice\://mysrv.anraconc.de?tls-port=20002

Another reduction of typing work comes through a script which readers can read and execute, but not change. The script could make all the relevant decisions for a user. A very simplified version would in my test scenario contain statements like:

if  test $SUDO_UID
        if test  $UID -ne $SUDO_UID
                echo "error - you are not allowed to run this command as another user"
if  test $UID -eq $Myself_UID
        echo "Hello Ralph"
        msg="You are entering the Spice console of VM \"debianx\" - happy working"
        echo $msg
        sudo -u "#$UID" -g spicegrp /usr/bin/remote-viewer -- spice://$host?tls-port=$myself_port
elif  test $UID -eq $Mybro_UID
        echo "Hello Brother"
        msg4="You are entering the Spice console of VM \"leaptest\" - happy working"
        echo $msg4
        sudo -u "#$UID" -g spicegrp /usr/bin/remote-viewer -- spice://$host?tls-port=$mybro_port
        echo "Sorry, you are not allowed to access VMs"

Note that the script would ask for a password before executing the sudo statement enclosed – if you had defined a password request in the sudoer file.
If you absolutely wanted to obfuscate the information contained in this script you could again use the trick with sudo and the special group spicegrp. You would the add lines

myself ALL=(myself:spicegrp) /usr/bin/rviewer
myself ALL=(mybro:spicegrp) /usr/bin/rviewer

to the “/etc/sudoers”-file

Important note:

You must not forget to check the fie permission of the file “/usr/bin/remote-viewer” after SW-updates or upgrades of your system.

I would recommend to start a small scheduled job or a service to check the rights settings frequently.


Remote-viewer connections to VMs cannot be controlled on a user level by the KVM/Qemu server if we just used TLS and SASL. We can set up a VM specific password. But external connections to a VM specific TLS port can only be blocked for external systems and IPs on the server.
However, on Linux client-systems iptables helps us to allow access to the Spice console of a specific VM for a selected user, only. This can be achieved by setting up user specific iptables rules on client-systems. This post has shown you how to create such rules for the OUTPUT chain with fwbuilder. We must set up a systemd service to implement these rules automatically at system (and network) startup.

To restrict users on Linux client systems even more we applied the sudo mechanism in a very specific way: we enforced the usage of certain arguments to the remote-viewer command for specific users. I think the method I discussed is safe; if you find a caveat please send me a mail.

Both strategies can and should be applied in Intranets where we want to provide remote-viewer and the Spice consoles of Qemu VMs as real working instruments.

KVM/Qemu VMs with a multi-screen Spice console – VII – remote-viewer, qemu and SASL authentication

I continue with my exploration of remote access methods to the Spice console of a VM run on a KVM/Qemu-server with Opensuse Leap 15.2 as OS.

KVM/Qemu VMs with a multi-screen Spice console – VI – remote access with remote-viewer and TLS encryption
KVM/Qemu VMs with a multi-screen Spice console – V – remote access via remote-viewer, a network port and a SSH-tunnel
KVM/Qemu VMs with a multi-screen Spice console – IV – remote access via SSH, remote-viewer and a Unix socket
KVM/Qemu VMs with a multi-screen Spice console – III – local access with remote-viewer via a Unix socket
KVM/Qemu VMs with a multi-screen Spice console – II – local access with remote-viewer via a network port
KVM/Qemu VMs with a multi-screen Spice console – I – Overview over local and remote access methods

The topic of my last post was the combination of remote-viewer with “TLS” encryption. We configured libvirt such that virt-manager or virsh started the qemu-process for our test-VM with support for TLS/SSL. But: Remote-viewer itself does not use any libvirt-layer; regarding connections to a VM-specific network port, it is the qemu-emulator-process of the VM which does the encryption business for us on the server’s side – not libvirt.

In comparison to SSH-based methods discussed earlier a major disadvantage of the TLS-solution was the lack of any authentication on the server. The TLS-port for Spice on the server was open for anybody in our Intranet – not a nice situation for a “one seat” tool as Spice. We could, of course, have restricted access to certain client-systems by a firewall and by setting a general or a VM-specific password for the Spice console(s); but still there would not be any user-specific restrictions in place.

As a first improvement we would like to establish some server-side authentication as a condition for access to a Spice console. With SSH this was a peace of cake – and we could in addition set user-specific options for the SSH daemon to combine authentication with a user-specific access to the Spice console of a selected VM, only. Something similar is much harder to achieve with TLS – as long as we cling to libvirt-tools for starting VMs and remote-viewer as a client. I have not succeeded with it by simple means. Actually, I will need another article to describe some measures for real user specific restrictions – on the remote-client and, unfortunately, without reaching the same clear association of a user’s authentication on the server with the access to a specific VM. But one step after the other.

In this article I am going to discuss the combination of

remote-viewer, Qemu, TLS and SASL.

We first take a look at a most simple SASL authentication mechanisms based on a sasldb2-file which contains the credentials. One could also directly involve a Kerberos system by just changing some settings in prepared configuration
files. But Kerberos is beyond the scope of this series. Instead I want to show you how to configure the invocation of the saslauthd daemon as a general bridge to whatever authentication method you prefer in your network or on the server for special services. For reasons of simplicity we pick the local PAM machinery on the server as an example, but MySQL, LDAP or LDAP combined with Kerberos would be other options.

We are going to see that these two simple approaches to SASL based authentication – though working – come with a big disadvantage regarding Spice: The authentication is unfortunately global for all VMs. We won’t get a restriction to the Spice console of a specific VM with remote-viewer and SASL. And we do not really restrict the access to the console of a specific VM to a defined UID on the server.

But, let us first focus on the problem of getting SASL active in combination with remote-viewer. We work again with our test-VM “debianx” with a Kali system on it, a laptop MyLAP as a remote client-system with OS Leap 15.2 and a KVM/Qemu server, also with Opensuse Leap 15.2 as OS (see the previous articles of this series).

Schematic overview

The following drawing gives you an overview about the involved components on the KVM/Qemu server and on the remote client-system.

This is more or less the graphics from my last article with additional elements. I have indicated that both remote-viewer and the Qemu-hypervisor must be configured to use SASL in addition to OpenSSL. This in turn means that these components must support SASL and its challenge/response mechanisms. On the server-side we need a SASL compatible backend for keeping credential data and performing authentication against them. Some Qemu-configuration options allow for a direct and seamless access of certain backends – as sasldb2 or Kerberos. However, the “saslauthd” daemon with its manifold of connectors to different internal or external backends can be used as a mediator, too.

Note that we would create severe security holes if SASL related credentials or other authentication data were transferred between the client-system and the server without encryption. SASL is basically independent of OpenSSL-libraries. It provides its own methods (“mechanisms”) for data exchange – some with encryption, but some without. And saslauthd works with clear text data, only.

Therefore, any client-application using SASL is well advised to check that a TLS-tunnel really is in place if the used or available SASL mechanisms imply plain text transfer of challenge/response data. It is the sole responsibility of the applications to evaluate the circumstances. And remote-viewer indeed seems to take care ….

TLS was not really enforced by our settings … so far

I am lazy and I use libvirt tools to start qemu-based VMs. The TLS configuration is, therefore, in a way a global one for all VMs. It activates (potential) TLS support for the Spice console whether the VM in the end really offers a special TLS-port or not. In this case the global configuration has no consequences in the sense of TLS enforcement; we must still define a VM-specific TLS-port to really enable TLS for a chosen VM. And as long as a standard network port is defined for the VM and opened on the KVM/Qemu-server the usage of TLS is not enforced. A good reason for remote-viewer to be careful with regard to SASL.


We have to install packages for SASL on the server and also on the client. Opensuse provides SASL in form of “cyrus-sasl“. Required packages for our
tests are:
cyrus-sasl, cyrus-sasl-digestmd5, cyrus-sasl-plain, cyrus-sasl-saslauthd, cyrus-sasl-scram, libgsasl-lang, libgsasl7, libsasl2-3, libsas2-3-32bit, perl-Authen-SASL.

Some of these packages provide specific SASL “mechanisms” for the exchange of challenge/response data.

Basic preparations for Qemu and SASL on the KVM/Qemu-server

In previous articles we learned that remote-viewer accesses the Spice console of a VM directly via Qemu (and not libvirt). So we must prepare the start of a qemu-process for our VM such that parameters enable the use of SASL. As with TLS we use the file “/etc/libvirt/qemu.conf” for the configuration. For our present purposes we activate the following options:

spice_tls = 1
spice_tls_x509_cert_dir = "/etc/pki/libvirt-spice"
spice_sasl = 1

You are already familiar with the TLS-related options. The only new point is the activation of SASL as the authentication mechanism for the Spice console. Folks who start qemu processes manually or with the help of scripts should read
for the relevant options to add to the “/usr/bin/qemu-system-x86_64”-command. Spice related parameters may look similar to what I get in may case, namely

/usr/bin/qemu-system-x86_64 ….. -spice tls-port=20002,addr=,sasl,disable-ticketing,x509-dir=/etc/pki/libvirt-spice,tls-channel=default,image-compression=auto_glz,seamless-migration=on ……

Note the location of the x509-directory; we got already acquainted with it it in the last article: It is used by qemu to read in TLS/SSL-certificates and key information which we must place there in advance, e.g for the CA and the server. If we started VMs directly with “qemu”-comands on a CLI we could change this directory individually for VMs. Using virt-manager or virsh forces us to define one x509 directory for all VMs, instead. Keep this in mind.

The commenting text in the file “/etc/libvirt/qemu.conf” tells you already that additional configuration steps are required in a file just below “/etc/sasl2/“. This directory gathers SASL configuration files for various services that make use of SASL.

On a Leap 15.2 system no special default configuration file for “qemu” is provided at “/etc/sasl2/”, but for “libvirt”. For our present purposes we just copy the existing file “/etc/sasl2/libvirt.conf” to a new file “/etc/sasl2/qemu.conf“. Why “qemu.conf”? Well, this is the instruction given in Opensuse’s virtualization documentation – and it seems completely logical. This may lead you to the assumption that the “service” in question always has to be qualified as “qemu” in relation to SASL. We shall later see that this assumption is wrong when we invoke the “saslauthd”-daemon …

For our first tests we activate the following two options, only, in the file “/etc/sasl2/qemu.conf” by un-commenting respective lines, out-commenting others and a minimum of editing:

mech_list:  plain scram-sha-256 
# mech_list:  plain scram-sha-256 digest-md5
sasldb_path: /var/spice/sasl/passwd.db

With the “mech_list” we obviously define a list of SASL mechanisms. We shall see how we specify which of these mechanism remote-viewer should use in a minute.

The mechanisms “plain” and “scram-sha-256” lead to an exchange of (salted) challenge/response data in clear text. They offer no real security for man-in-the-middle attacks in our Intranet. So, these mechanisms must be used in combination with a TLS tunnel, only. For possible attack-vectors see e.g.

The good message is: Remote-viewer will block the access to the Spice console of a VM if the connection is not secured by TLS/SSL!

Note the out-commented line with a crypto-mechanism specified in addition, namely “digest-md5“. We shall use this line for tests of situations where a standard connection without TLS is established or might be established as a fallback. We shall see that remote-viewer will pick “digest-md5” automatically if TLS is not guaranteed and if the mechanism is available.

However, “digest-md5” must itself be regarded as insecure due to its weak cryptography. In a productive environment you should simply forget it – and best eliminate it from your configuration! Let remote-viewer check for sufficient TLS conditions – and let it refuse access to the target VM if necessary.

The parameter sasldb_path specifies the path to sasldb2-files which should contain the credentials. In my settings the reader recognizes the directory below which I placed a folder for a pure Unix socket in local access scenarios (the previous articles). You may, however, specify whatever directory you like on your system. But be aware of required access rights; see below.

How to fill sasldb2 with credentials? What access rights are required?

Some basic information about the usage of sasldb2-files is given e.g. at

According to the test settings above we place our sasldb-files into a folder “/var/spice/sasl/” (see below). Before you blindly experiment with adding users, consider some hints regarding the entries:

SASL distinguishes between users of the same name for different systems or application environments. Users have to be qualified with a user-name and a realm in the form


Regarding the “user“:
It does not matter what usernames we choose; we can use fictitious users – they need not exist as valid users on the KVM/Qemu server (or the client-system) at all. However, as remote-viewer normally “suggests” the present username in a dialog for authentication (see below) it may be clever to add users with these suggested names – just to save some time with typing. In my test environment I work as user “myself” on the client “MyLAP”, but sometimes also as user “uvmb” on the server “MySRV”. So, I should have valid entries for both users.

Regarding the “realm“:
For a simple sasldb you can basically define as a realm whatever you want – but the user who wants to authenticate has to know what to provide. So he/she should be able to associate it with some meaning, e.g. the VM’s name. The “realm” is, unfortunately, NOT set or defined automatically later by the remote-viewer client and is in no way related to the contents of TLS certificates or target domain names presented during the authentication process. It can be freely set by the user in an SASL authentication dialog presented by remote-viewer: The user there can fill in anything after “username@…”. To become authenticated, however, what he/she fills in must match an entry in the sasldb-file.

Thus, we could define a fantasy user “tom@waits” with a password “the-piano-has-been-drinking”; it would work – as long as the remote-viewer user has all this information and provides it properly in the authentication dialog.

There is, however, one more rule to keep in mind during your experiments:

If the user provides just a username without any realm in the SASL authentication dialog then the hostname will be added automatically
on the server-side. And the hostname is the one in “/etc/hostname” on the server.

(The qemu-end of the SASL authentication does not seem to differentiate in cases where we use multiple IPs and different FQDN entries at a DNS server or in /etc/hosts for the host.)

In my test case the hostname is “myserv.anraconc.de”. But be careful: You may have the short-name (“mysrv”) standing in “/etc/hostname” on your Opensuse Leap 15.2 system! You should have a proper entry “myself@hostname” in your sasldb. If in doubt enter entries with both the short form and the FQDN of your KVM-host.

As root we now prepare a folder “/var/spice/sasl/” on the server (we have a folder “/var/spice/” already from previous efforts) and add some users with the help of the “saslpasswd2“-command :

mysrv:/var/spice # mkdir /var/spice/sasl
mysrv:/var/spice # chown root.qemu /var/spice/sasl
mysrv:/var/spice # chmod 750 /var/spice/sasl
mysrv:/var/spice # saslpasswd2  -a qemu myself@mysrv.anraconc.de -f /var/spice/sasl/passwd.db
Again (for verification): 
mysrv:/var/spice # saslpasswd2  -a qemu myself -f /var/spice/sasl/passwd.db
mysrv:/var/spice # saslpasswd2  -a qemu uvmb@mysrv.anraconc.de -f /var/spice/sasl/passwd.db
mysrv:/var/spice # saslpasswd2  -a qemu uvmb -f /var/spice/sasl/passwd.db
mysrv:/var/spice # saslpasswd2  -a qemu xen -f /var/spice/sasl/passwd.db
mysrv:/var/spice # saslpasswd2  -a qemu xen@xensrv -f /var/spice/sasl/passwd.db

Afterward, you will find two new files in “/var/spice/sasl”:

mysrv:/var/spice/sasl # la 
mysrv:/var/spice/sasl # la
total 28
drwxr-x--- 2 root qemu  4096 Apr 18 18:09 .
drwxr-xr-x 3 root root  4096 Apr 18 18:07 ..
-rw------- 1 root root    16 Apr 18 18:09 passwd.db.dir
-rw------- 1 root root 23384 Apr 18 18:09 passwd.db.pag
mysrv:/var/spice/sasl # 

Note the rights: The passwd-files can only be read by root. Why? Well, such a SASL file contains the credentials in clear text! It must be protected!

But, with these settings we would again run into a problem, which we have already seen in previous articles: The user of the qemu-processes is “qemu” on Leap 15.2-systems – at least when qemu-processes are started by libvirt-tools! This user “qemu” must be allowed to read critical files, in our present situation the “passwd.db”-files. Therefore, we change the group to “qemu” and the access rights to “640”:

mysrv:/var/spice/sasl # chown root.qemu pass*
mysrv:/var/spice/sasl # chmod 640 pass*
mysrv:/var/spice/sasl # la
total 28
drwxr-x--- 2 root qemu  4096 Apr 18 18:09 .
drwxr-xr-x 3 root root  4096 Apr 18 18:07 ..
-rw-r----- 1 root qemu    16 Apr 18 18:09 passwd.db.dir
-rw-r----- 1 root qemu 16384 Apr 18 18:09 passwd.db.pag
mysrv:/var/spice/sasl # 

Warning: Please check that the qemu-group contains the user “qemu”, ONLY !

To check which users are enlisted in our backend we use the command “sasldblistusers2“.

mysrv:/var/spice/sasl # sasldblistusers2 -f /var/spice/sasl/passwd.db 
xen@xensrv: userPassword
xen@mysrv: userPassword
uvmb@mysrv: userPassword
uvmb@mysrv.anraconc.de: userPassword
myself@mysrv: userPassword
myself@mysrv.anraconc.de: userPassword
mysrv:/var/spice/sasl # 

You see that users provided without a system realm automatically got the present system’s name attached!

If we wanted to delete a user we would use:

mysrv:/var/spice/sasl # saslpasswd2  -d xen@xen -f /var/spice/sasl/passwd.db
mysrv:/var/spice/sasl # sasldblistusers2 -f /var/spice/sasl/passwd.db 
xen@mysrv: userPassword
uvmb@mysrv: userPassword
uvmb@mysrv.anraconc.de: userPassword
myself@mysrv: userPassword
de: userPassword
mysrv:/var/spice/sasl # 

For tests you should vary the passwords of usernames defined for different systems.

Indications of basic security problems

As long as a standard TCP port is defined for Spice fallback-situations may occur without any announcement. But remote-viewer checks whether the tunnel really is TLS secured or not. If not, it will automatically try to choose a SASL mechanism with encryption – as e.g. digest-md5 – if such a mechanism is available to the qemu-process on the server. If such a mechanism is not available remote-viewer will block the access to the Spice console:

A typical indication that something is wrong is a decline to enter a username in the dialog window for authentication opened by remote-viewer.

Problematic SASL mechanisms of course are PLAIN and all SCRAM-mechanisms. A noteworthy fact about remote-viewer is:

remote-viewer will try to use a SASL mechanism with encryption even if you have explicitly specified something else!

Problematic situation arise for a remote-viewer command (executed locally or on a real remote client) which contains the specification of a standard non-TLS port and a TLS-port – e.g.:

remote-viewer spice://myserv.anraconc.de:20001?tls-port=20002

for a VM with a Spice configuration that includes a standard non-TLS port and “defaultMode” set to “insecure” or “any”. The same is true for:

remote-viewer spice://myserv.anraconc.de:20001?tls-port=20002&sasl=plain

If remote-viewer in its background dialog with the server does not find a “worthy” mechanism it will give you an error hint:

Failed to start SASL negotiation: -4 (SASL(-4): no mechanism available: No worthy mechs found)

Spice configuration to be used with plain text SASL mechanisms

To be on the safe side we configure Spice in the XML-definition file for a VM as follows:

   <graphics type='spice' tlsPort='20002' autoport='no' listen='' keymap='de' defaultMode='secure' >
      <listen type='address' address=''/>
      <image compression='auto_glz'/>
      <gl enable='no'/>

The difference in comparison to specifications in previous articles is that we do not specify a standard “port” at all – but still have “autoport=’no’” in place AND set “defaultMode=’secure'”.

How do we specify a SASL mechanism when starting remote-viewer?

The general form is as simple as this

remote-viewer spice://FQDN??tls-port=NR_OF_TLS_PORT&sasl=MECHANISM 

where “FQDN” refers to the address of the server, “NR_OF_TLS_PORT” to the tlsPort settings for Spice in the VM’s configuration and “MECHANISM” to one of the SASL mechanisms in the list of the “/etc/sasl2/qemu.config”-file.

Remote test

We are confident and test our present settings. We restart libvirtd on the server. A privileged user “uvma” starts the test VM there for us. Then we login into the remote system – in my case as user “myself” into “MyLAP”. On a terminal we enter:

myself@mylap:~> remote-viewer spice://mysrv.anraconc.de?tls-port=20002&sasl=plain

We then get an authentication dialog:

We enter the password defined in the credentials file – in my case for “myself@mysrv.anraconc.de” and not for “myself@mysrv” (!!) – and there we go:

After a login we can work with the desktop of the VM as described in previous articles and open up more screens.

Tests for realm dependence of the authentication

We are now able to test the dependency of the authentication on the “realm”; we just type in the “username@realm” which we want to test and provide the related password. Try also cases without providing a “realm”. I leave it to you to perform such tests.

Afterward it should be clear that the FQDN shown in the authentication dialog is important for the validity of the TLS server certificate – but it has nothing to do with the SASL realms!

A dis-functionality: Freezing Spice windows if the Spice session is taken by another user

Now you could try to do the same shortly after and locally on the server “mysrv” – i.e. you try to steal the “seat” in front of the Spice console. In previous articles we have seen that the Spice windows of the user, from which the seat was taken, were just closed without any warning. This was not the case on my systems with TLS and SASL. Instead and unfortunately the Spice window of the original user froze; he/she could not enter anything anymore. One could not even close it explicitly without killing the job.

Otherwise the handling of an active Spice session is as we are used to.

What do we get for situations with TLS not fully enforced?

Just for testing purposes we change the security situation by adding a standard port to the Spice configuration and set the defaultMode in the VM’s XML-configuration to ‘any’:

   <graphics type='spice' port='20001' tlsPort='20002' autoport='no' listen='' keymap='de' defaultMode='any' >

Then a dubious situation as provoked by

myself@mylap:~> remote-viewer spice://mysrv.anraconc.de:20001?tls-port=20002&sasl=plain

The TLS-option is ignored in this case and this in turn leads to a decline to enter a user@realm in the first field of the dialog:

accompanied by a warning on the terminal window :

(remote-viewer:21318): GSpice-CRITICAL **: 17:33:36.750: Failed to start SASL negotiation: -4 (SASL(-4): no mechanism available: No worthy mechs found)

However, if you now change the “mech_list” for SASL in “/etc/sasl2/qemu.config” such that it includes “digest-md5”, then

myself@mylap:~> remote-viewer spice://mysrv.anraconc.de:20001?tls-port=20002

would work. And also – somewhat unexpected – the following works:

myself@mylap:~> remote-viewer spice://mysrv.anraconc.de:20001?tls-port=20002&sasl=plain

Wireshark, however, reveals that the specified sasl-mechanism is ignored and digest-md5 is taken in this case:

Well, this is a bit confusing as remote-viewer does not inform the user about the measures taken. My advice is to prepare for clarity: If you want to work with SASL then disable the standard non-TLS port for Spice and do not include weak SASL crypto-mechanisms in the mech-list at all. It is better that remote-viewer
stops the conversation ….

Failure for local access to the Spice console from virt-manager

There is a problem with our qemu-setting that enforces SASL and virt-manager. Afterwards we can no longer access the Spice console locally on the KVM/Qemu-server with the built-in Spice client of virt-manager. We get a screen that wants a password from us – but no user and realm:

You can fill in whatever you want of known passwords for root, qemu and other users which you may have filled in into your sasldb. (You could have added an entry for “root@mysrv.anraconc.de” with some password, because virt-manager runs with user root). It is not going to work.

There seems to be a basic problem; we get a log message as

2021-04-30T17:05:20.745776Z qemu-system-x86_64: warning: Spice: red-stream.c:1039:red_sasl_start_auth: sasl context setup failed -7 (invalid parameter supplied)

The funny thing is that another libvirt-dependent tool, namely “virt-viewer” works correctly with SASL. You can test it locally on the KVM/Qemu-server, e.g. for the following situation:

  • Allow for a standard Spice port without TLS (in our test case 20001; in our series we have not yet come to the point where we use libvirt-tools remotely together with TLS 🙂 ).
  • Let Spice listen on all on all network devices (including
  • Activate SASL for qemu (via settings in “/etc/libvirt/qemu.conf”; see above).
  • Allow for a SASL mechanism with encryption.

If you then enter e.g. the command

mysrv:~ # virt-viewer -c qemu:///system

(e.g. as user root) an authentication dialog opens, where we can fill in a username (“root” is suggested) plus a realm, if we want, and a valid password for the combination.

Enter a valid password for some entry (e.g. for root@mysrv.anraconc.de”) in the sasldb and the Spice console comes up as usual. So – there is some dis-functionality in virt-viewer, when SASL is activated for qemu (and not a libvirt port or local libvirt Unix socket).

Switching to the saslauthd daemon

“/etc/sasl2/qemu.config” was copied from a libvirt-oriented file. We can, of course, specify other SASL rules for the service “qemu”. In particular we can invoke a “saslauthd” daemon. We achieve this by changing the settings in “/etc/sasl2/qemu.config” to:

mech_list:  plain scram-sha-256
pwcheck_method: saslauthd

Please out-comment other lines. Why did I only specify clear text mechanisms? Well, saslauthd simply does not work with crypto-mechanisms! It is not designed for it. It is invoked locally on our KVM server where it listens on a Unix socket after having been started:

mysrv:~ # netstat -ax | grep sasl
unix  2      [ ACC ]     STREAM     LISTENING     603842   /run/sasl2//mux

To get that far there are a few more things to do, of course: We must configure saslauthd and start the related service. The basic configuration of “saslauthd” on a Leap 15.2 system is done
via settings in the file “/etc/sysconfig/saslauthd“.

For a simple scenario, which uses the standard PAM mechanisms on the server, we can leave the default settings there as they are:


What is the expected effect? Well, afterward, we should be able to authenticate ourselves with credentials (usernames and passwords) already defined for valid accounts on the server (e.g. in “/etc/passwd” and “/etc/shadow”). Note:

No login shell is required for our special Spice users!

So, we can create some (harmless) user accounts on the server to test the Spice/SASL authentication (with some preset complicated passwords).

Before testing we should not forget to start the daemon by “systemctl start saslauthd” or “rcsaslauthd start“. But before we do this there is one more step required ….

PAM configuration to support authentication for Spice by saslauthd

PAM works for services – and what PAM should do for a service has to be defined. The configuration files are placed in “/etc/pam.d/“. Naively, I had expected that we would need a “qemu” configuration file there. Well this is wrong. I could see it from resulting error messages in “/var/log/messages”

... saslauthd[25571]:                 : auth failure: [user=myself] [service=spice] [realm=] [mech=pam] [reason=PAM auth error]

The “service” to be configured is “spice” ! Ok, the machine gets what it wants. I created a simple file “/etc/pam.d/spice” with the following standard contents:

auth     requisite      pam_nologin.so
auth     include        common-auth
account  include        common-account
password include        common-password
session  required       pam_loginuid.so
session  include        common-session

This is enough to support our SASL operations; some lines as e.g. for the password could even have been omitted for our present objectives. Note hat a “realm” does not make much sense if we work with a local PAM for Linux password files on a Linux host, only, and no external backend.

Test of salsauthd

Stop your VM if it were running. Restart libvirtd, start saslauthd, start the VM.
You can pre-test your saslauthd configuration for the service “spice” with existing user accounts on the server with the command

mysrv:~ # testsaslauthd  -s spice -u uvmb -p ******** 
0: OK "Success."

You must of course replace “uvmb” without a username defined on your server and the “******” with the related password. .

Now you can try it for a remote-viewer session. The same authentication dialog we got before for our sasldb-experiment should appear. You then only enter a username (no realm) into the filed for the username. Should work without any problems.

Major deficits of the SASL-authentication for remote-viewer

During his/her tests of the authentication with sasldb2 the reader has certainly realized the following point:

Any valid combination of a username, a related realm and a password authorizes us to get access to the Spice console of our test-VM.

There is no unique relation between a UID on the remote-client or on the server and the “username@realm” combination. And there is no real relation of a username/user with a specific VM. Therefore, the situation is actually worse:

A user providing a valid “username@realm” (existing in sasldb2) has access to the Spice consoles of all VMs running on the server!

Activating SASL in the general way we did it for the startup of all qemu-processes
establishes an authentication and authorization mechanism for the Spice consoles of all VMs on a KVM server – if the user knows the relevant TLS-ports or just checks out ports systematically.

Obviously, the logic for our present setup is that we authenticate a general Spice user via SASL on the server. We cannot establish a relation between the Spice related SASL “username@realm” and a specific VM. The present version of remote-viewer does not provide other data (as an rhost) which we could e.g. use in some cleverly crafted PAM rules for special modules. (You can see the information provided from log-entries for your VM and wrong authentications)

In my opinion an authorization should be specific for a user (or a group of selected users) and a specific target service. And it should be such that the server alone can control the service access. For a bunch of VMs on the KVM/Qemu-server we would assume that we could establish a specific user authentication for the Spice console of a specific VM and no other VMs.

So, it is very unfortunate that “realm” delivered by remote-viewer can freely be set by the user and that it is independent of the TLS parameters and/or data of the remote-host. Thus, there is no way to force the user on the client-system to enter a VM-specific user@realm combination. And any other user sharing one valid username/password combination known to him opens up access to all Spice consoles for other users – if no additional measures were taken.

If you wonder how a coupling of certificate data to the realm would have helped: We could have achieved a relation between a realm and a VM, if we had coupled the VM to a sub-domain for a wildcard certificate on the server and to a specific IP on the server – and if the realm were taken from the “common name” (i.e. the FQDN) in the certificate. Then we had just needed a specific username@ realm entry in the sasldb – and we would have gotten a VM-specific authentication. In the case of saslauthd the delivery of information about the remote host would have helped. I leave it to the user to figure that out. Its fruitless thinking anyway, …

Actually, setting a password int VM’s XML file would have given us a VM-specific authentication. Unfortunately, we are not allowed to combine the setting of a VM-specific password in the XML-file in addition to SASL-authentication. The VM can not be started by virt-manager or virsh then. So, it is a bit of a mess with SASL and remote-viewer …

Are there valid counter arguments?
Well, you could argue that we could hinder access to specific VMs by blocking ports on the server for certain client-systems. Well, and what for situations where multiple users are allowed to login to any client-machine in an office?
And you could argue: But the user has certainly to login into the VM as well? Yeah, but there is the problem with Spice – if someone legitimately had already opened a a session on the VM via a Spice console this session could be taken from him/her in the present open status by an other user authenticated via SASL for some other entry in the sasldb. Security is something else …


To activate SASL for some general authentication to get access to the Spice console of a chosen VM is simple. However, the SASL authentication does not allow us

  • to restrict the access to the Spice console of a specific VM to a specific username@realm combination.
  • to restrict the access to the Spice console to a specific UID on either the remote client or the KVM-server.

So, TLS in combination with SASL is to a certain degree a disappointment. A VM-specific password has more advantages. Note, that for present versions of “qemu” it is not displayed anymore in the output of “ps aux | grep qemu”.

The combination of TLS and SASL with remote-viewer is not really useful for situations where we want Intranet users to
work with VMs via Spice sessions – each of them with a (user-) specific VM or some (user-) specific VMs, only.

If you wanted to make Spice sessions available to a selected user only for specific VMs we thus end up with the question: How can we become more restrictive?

In the next article

KVM/Qemu VMs with a multi-screen Spice console – VIII – VM and user specific restrictions for remote-viewer connections – iptables and sudo

I will therefore discuss the application of user specific iptables- and sudo-rules on remote client-systems. Not ideal – but a step forward.

KVM/Qemu VMs with a multi-screen Spice console – VI – remote access with remote-viewer and TLS encryption

In my series on various methods to access a Spice console of a VM I have already covered two remote scenarios in an Intranet based on remote-viewer and SSH:

  • Scenario 1: remote-viewer is run on the KVM/Qemu server and accesses the Qemu-hypervisor over a Unix socket. The user at the remote client-system opens a “ssh -X” or “ssh -XC” session to the server, starts remote-viewer there and uses the graphical output data via the client’s X-server. Audio requires a reverse SSH tunnel for Pulseaudio ( “ssh -X -R 44713:localhost:4713” ).
  • Scenario 2: remote-viewer is started on the remote client-system. A Spice and VM-specific TCP-port (TCP socket) on the server is used for the transfer of video + audio data. Security can be achieved by establishing a SSH tunnel with port-forwarding and further user-related SSH-restrictions.

KVM/Qemu VMs with a multi-screen Spice console – V – remote access via remote-viewer, a network port and a SSH-tunnel
KVM/Qemu VMs with a multi-screen Spice console – IV – remote access via SSH, remote-viewer and a Unix socket
KVM/Qemu VMs with a multi-screen Spice console – III – local access with remote-viewer via a Unix socket
KVM/Qemu VMs with a multi-screen Spice console – II – local access with remote-viewer via a network port
KVM/Qemu VMs with a multi-screen Spice console – I – Overview over local and remote access methods

Security regarding an encrypted data transfer, user authentication and port or socket access was achieved via SSH in both scenarios, plus ACLs in case of the first scenario. A critical point in both scenarios was data compression. SSH compression (=gzip) had a palpable negative impact on the responsiveness of the VM’s desktop in the Spice windows. However, data compression offered via Spice options did not diminish the performance – at least it could not be felt.

In this article we have a look at yet another scenario for remote-viewer: Spice is this time combined with TLS encryption. However, in this post, we use TLS for data encryption, only, and not yet for client-authentication. Client authentication methods in combination with TLS and remote-viewer will be the topic of the next article.

We use the same systems as in the last articles: A KVM/Qemu server host “MySRV” with a Leap 15.2 OS on it, a test-VM “debianx” with a Kali-OS on it and a client-system “MyLAP” (a laptop with a Leap 15.2 OS). On the KVM/Qemu host our meanwhile familiar user “uvma” is used to start the VM “debianx” for us with the help of virt-manager. On the client-system “MyLAP”, instead, a user “myself” will start remote-viewer.

Schematic drawing

The following sketch shows what we want to achieve:

Qemu-hypervisor shall use a TLS server-key and a X509-server-certificate to encrypt all application data transferred in our Intranet between the server and the remote-viewer application on the client-system. This should include all data channels of the Spice protocol.

TLS CA, server certificates and RSA-keys

A sound TLS setup requires at least a CA, a CA-certificate, a server-certificate for the KVM/Qemu-server and a file with the private key of an asymmetric (RSA) key-pair. This brings us to the question: What tools can we use on a Leap-system to create such certificates for our private network?

On a Linux system there are, of course the OpenSSL libraries together with the so called “certtool“, a CLI-tool. You get the latter on Leap 15.2 by installing the “gnutls” RPM from the Leap15.2-Update repository. A documentation for the creation of CA, server and client TLS certificates and related key-pairs with certtool is given on the following web-pages:

Personally, I prefer a graphical tool to keep an overview about my own CAs and related server-certificates. As Opensuse never replaced their YaST CA-tool after they changed to Ruby as the programming platform for YaST we have to look elsewhere.

A very good tool which provides a lot of options is “XCA“. You find it in the package “xca” on a Leap 15.2 system. It is intuitive to use, offers a lot of options and its “help” documentation is very good – if you already know something about the differences and requirements of certificates. It offers suitable templates for CA-, server- and client-certificates. For a step-by-step description of how to create certificates see section 14 in the help functionality. Other tutorials for certificate creation with “xca” can be found in th following PDFs
http://help.mguard.com/ pdf /en / mguard8/ AppNotes/ AH EN X.509 CERT XCA 108396 en 00
http://evardsson.github.io/ s3c3/ Generating, signing and exporting keys and certificates with XCA

Another older tool, which I still use, is TinyCA. The following image shows a test example (I have no such net nor server as displayed).

Its templates are simpler than those of “xca”; the options are also a bit more limited, but sufficient for private purposes. Opensuse provides a RPM “tinyca2” in its standard repositories. I have written some blog posts about it; see: TinyCA2 as a replacement for YaST’s CA-tools on Opensuse Leap servers with TLS/SSL – I and two later posts.
Please, be aware of the fact that you need to apply additional patches to get SHA-256 and SHA-512 capabilities. See the named post about it. You should be able with my descriptions to create a server certificate for your KVM/Qemu-host. Also see TinyCA2 as a replacement for YaST’s CA-tools on Opensuse Leap servers with TLS/SSL – II for a description into which directory the CA-certificate files should be placed on a Leap 15.x OS.

For the rest of the present article I assume
the following:
You have created a CA, a CA-certificate, a X509-compatible server-certificate and a RSA based private key for the server. You do this on whatever system you use for the administration of your CA. You have also exported the certificate data and the key into files with the “pem“-format and copied them (scp) to a save place under the control of root on your KVM/Qemu server host. In the end you should have the following files there:

  • ca-cert.pem
  • server-cert.pem
  • server-key.pem

Note that these specific file-names are important for the later Qemu-configuration. You should rename your files accordingly or make copies with these names. Note that the server-key file contains a private key – this file must be protected against unauthorized access during all steps of the configuration process and after.

Note also that the server-certificate should be set up with the FQDN of our KVM/Qemu-server: This is “mysrv.anraconc.de” for our test situation.

You must also place a copy of the CA-cert file onto the client-system(s) from which the Spice user later connects to the KVM-server. The “CA-cert”-file must in addition be known there as coming from a trustworthy CA. See a separate section below for the required measures on an Opensuse Leap system.

If you already had a CA and had already issued certificates in the past – can we reuse them? The answer is: Yes, you could. Personally, however, I prefer to issue a special dedicated server-certificate and keys for Qemu. One of the reasons is that the Qemu process must be able to read the server-key-file and it is run for a special user “qemu” and not root. But I do not want “qemu” to be able to read other server-keys used by completely other processes as e.g. for a web- or mysql-server.

Configuration of Qemu on the KVM-host for TLS connections

You remember from previous articles of this series that remote-viewer talks directly to the Qemu-hypervisor; it does not involve any libvirt layer. It is therefore no surprise that we need to configure Qemu itself such that it uses TLS. But which is the right configuration file to take? And where do we place our certificates and keys?

On a Leap 15.2 system we normally use the libvirt machinery to create and start Qemu-based VMs and the related Qemu-processes. Then we need to tell libvirt how to start a Qemu-process with the required correct options. The config-file to take in this case is “/etc/libvirt/qemu.conf” (see the 2nd article of this series).

[If you, by the way, are interested in the qemu-options and in particular the TLS options which can be used if and when you start a qemu-process manually see the qemu documentation, e.g. here and here.]

The named “qemu.conf”-file on our Leap based KVM/Qemu-server has multiple sections regarding TLS. The first main section covers the directories used for certificate and key-files. There you also find the file-names mentioned above. Later on you find an option to change the directory for Spice related certificates. We use this option.

For the time being we set the following parameters and un-comment the related lines:

# The following tells Qemu to use TLS for the encr<yption of Spice cahnnels 
spice_tls = 1  

# We need to specify a directory where we place the certifactes and key to be used  
spice_tls_x509_cert_dir = "/etc/pki/libvirt-spice"

That is all we need for this article. (As mentioned in a previous post: On systems with apparmor active one should also activate “security_default_confined = 1”. But this no special TLS option).

Afterwards we have to copy our certificate- and key-files to “/etc/pki/libvirt-spice/“.

It is obligatory to use the filenames given above. A VM would not start otherwise and Qemu would complain non-existing or unusable files.

What file access rights are required?
The certificates should only include public keys, so here we could grant others the “r”-right. The situation is different with the file “server-key.pem“. It contains the server’s private key – and probably in unencrypted form if we did not protect it by password.

Therefore, we need to restrict the read rights for this file. And here we are confronted with a small glitch in the Opensuse configuration – the apparmor settings allow the privileged libvirt-user who is allowed to start virsh or virt-manager to read the files – but not “qemu”. A simple solution is

mysrv:~ # cd /etc/pki/libvirt-spice/
mysrv:/etc/pki/libvirt-spice # chmod 440 *
mysrv:/etc/pki/libvirt-spice # chown root.qemu * 
mysrv:/etc/pki/libvirt-spice # la
total 20
drwxr-xr-x 2 root root 4096 Apr 11 11:44 .
drwxr-xr-x 8 root root 4096 Feb 27 15:11 ..
-r--r----- 1 root qemu 2504 Feb 27 15:14 ca-cert.pem
-r--r----- 1 root qemu 2504 Apr 11 09:49 server-cert.pem
-r--r----- 1 root qemu 3243 Apr 11 09:49 server-key.pem
mysrv:/etc/pki/libvirt-spice # 

But from now on you should be careful during your experiments and check what members the group “qemu” has – on a Leap system it should only contain the user “qemu”, nobody else!

The question remains whether you need the CA-cert-file for any other purposes on the KVM server. If so, please follow the advice given in the section for using the ca-cert-file on the client-system and apply them in an analogous way on the server.

You should restart the libvirtd-daemon to activate the changed options for the start of Qemu-based VMs via virsh or virt-manager in the future.

Configuring Qemu to use TLS is NOT the same as configuring libvirt to use TLS!

Just a warning:
Readers who work totally libvirt-centered and use virt-viewer instead remote-viewer should at this point of reading become very clear about the fact that configuring Qemu for using TLS with Spice is something else than configuring libvirtd to use TLS for external connections. The Opensuse documentation at
doc.opensuse.org/ documentation/ leap/ virtualization/ html/ book-virt/ cha-libvirt-connect.html
refers to the latter. The settings to activate TLS for libvirtd and libvirt-tools use a different directory scheme and different file-names in comparison to what we did above. Also the required file access to certificates and private keys can be limited to root for pure libvitr-based tools – but not in our scenario.

Configuring the VM to use TLS with Spice

So far Qemu is prepared to support TLS on the KVM-server – if and when the use of TLS is requested. We, therefore, still have to define that TLS should be used for connections to the Spice console of our specific test-VM “debianx”.

Actually, we have to define a special network port for this purpose. In the XML-configuration file for the VM we change the Spice settings :

    <graphics type='spice' port='20001' tlsPort='20002' autoport='no' keymap='de' defaultMode='any' >
      <listen type='address' address=''/>
      <image compression='auto_glz'/>
      <gl enable='no'/>
    <sound model='ich6'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
      <model type='virtio' heads='2' primary='yes'>
        <acceleration accel3d='yes'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'

The first change in comparison to previous settings consists of a new attribute “tlsPort
(Off topic: I use the same audio and video settings as before.)


The “tlsPort” – just as the the standard “port” – is specific for the VM.
For another VM you must define another “tlsPort”.

The second change is the removal of the attribute “defaultMode”. This allows us later to switch between TLS-secure and “insecure” access methods as we like. Remember that we always can make a insecure” connection (regrding a lack of TLS) secure at any time by building a SSH tunnel.

Some reader may ask why we did not set the default mode to “secure” and deleted the “port”-attribute. Well, if we were in a position in which we had tested the TLS configuration already and wanted to use TLS only in the future (and not SSH, for example) then we could make these changes, yes. But I keep the option of using a SSH-tunnel open. TLS is anyway the preferred option if the associated port is specified by the Spice client (here remote-viewer).

The reader certainly has noticed that I activated Spice image data compression. We made a good experience with it the other day.

How to deal with the CA-certificate on the Leap 15.2 client-system? Where to place it?

OpenSSL will validate the whole CA-chain when confronted with a server-certificate. It needs the CA-certificate for it. In addition it should trust the related public key – as the CA-root-certificate is self-signed. This means that we have to make the certificate of our private CA known to the client-system(s) – here MyLAP – on which we want to start a Spice client requesting a TLS encrypted connection from the KVM/Qemu-server.

Opensuse Leap systems are a bit picky about were to place the CA-certificates. To say it clearly: “/etc/ssl/certs” is the wrong place!

Any certificates unknown to Leap 15.2 will not survive a reboot there. They won’t even survive a call of the “update-ca-certificate“-program, which would make the CA-certificate known to other programs as a usable and trustworthy one. So, placing the “ca-cert.pem”-file of our private CA into “/etc/ssl/certs” will lead to severe problems: It won’t be found or won’t be accepted during the start of remote-viewer on a client-system as MyLAP.


The right place for the certificate of our private CA on a Leap-system is “/etc/pki/trust/anchors/“.

You should copy it there. By the way: You should use the name given to your CA initially – not necessarily the special file name used for Qemu on the KVM/Qmu server. In my case it is something like “anraconc-CA”, thus “anraconc-CA.pem”.

So, we perfom the following copy-process

CaSRV:~ # scp /root/.TinyCA/anraconc-CA/cacert.pem root@MyLAP:/etc/pki/trust/anchors/anraconc-CA.pem

On MyLAP we then enter

mylap:/etc/pki/trust/anchors # la 
-r--r--r-- 1 root root  2540 Apr 11 11:11 anraconc-CA.pem
mylap:/etc/pki/trust/anchors # update-ca-certificates
mylap:/etc/pki/trust/anchors # la /var/lib/ca-certificates/openssl | grep anrac
lrwxrwxrwx 1 root root    15 Apr 11 12:13 610c65bd.0 -> anraconc-CA.pem
-r--r--r-- 1 root root  2540 Apr 11 12:13 anraconc-CA.pem
lrwxrwxrwx 1 root root    15 Apr 11 12:13 bfb4c341.0 -> anraconb-CA.pem

“update-ca-certificates” makes the CA-certificate system-wide. The look into “/var/lib/ca-certificates/openssl” just was a check for this.
That is all we have to do regarding certificates on the client.

Test of the TLS encrypted remote connection to the Spice console

We first open our firewalls for connection from MyLAP to port 20002 on MySRV. On our KVM/Qemu-host we then start the libvirtd-daemon again to cover all
changes to Qemu and the VM. Afterward our privileged user “uvma” starts the VM “debianx” for us on the server. This should work without any problems – there should not be any errors regarding the TLS options and TLS files.

Then we have a brief look at https://libvirt.org/uri.html and https://www.spice-space.org/spice-user-manual.html to get an idea how we have to formulate our remote-viewer parameters for TLS:

myself@mylap:~> remote-viewer spice://mysrv.anraconc.de?tls-port=20002

(remote-viewer:29853): GSpice-WARNING **: 15:29:34.201: Warning no automount-inhibiting implementation available

with results that look very similar to what we have done in the last article. I omit the proof by screenshots as we would get no new information from them.

But did you notice a major difference besides the special way of specifying the TLS-port to use ?
We have to use the FQDN of the server!
Exactly in the form it was filled as the “common name” into the server-certificate! If we just used “mysrv” this would lead to an error message of OpenSSL – despite the fact that the short name can be resolved by a DNS server.
Note also that something like “remote-viewer spice://mysrv.anraconc.de:20002” will NOT work.

The required form of the command for remote-viewer with TLS is :

remote-viewer spice://FQDN_OF_KVM_HOST?tls-port=VM_SPECIFIC_PORT_NR

You should also test that the variant

myself@mylap:~> remote-viewer --spice-ca-file=/etc/pki/trust/anchors/anraconc-CA.pem  spice://mysrv.anraconc.de?tls-port=20002

works flawlessly.

Checking for encryption

A look at netstat on the server proves a connection to port 20002:

mysrv:~ # netstat -an | grep 20002
tcp        0      0 *               LISTEN     
tcp        0      0      ESTABLISHED
tcp        0      0      ESTABLISHED
tcp        0      0      ESTABLISHED
tcp        0      0      ESTABLISHED
tcp        0      0      ESTABLISHED
tcp        0      0      ESTABLISHED
tcp        0      0      ESTABLISHED
tcp        0      0      ESTABLISHED
tcp        0      0      ESTABLISHED
tcp        0      0      ESTABLISHED
mysrv:~ # 

While this only shows that a connection to the right port is established. However, an additional look with wireshark shows you the TLS version (which it gets from protocol headers):

We see that TLS V1.3 is indeed used to encrypt the application data crossing port 20002.

Data transfer rates and responsiveness

The data transfer rates for the present scenario overall are very similar to the ones measured for the SSH-scenarios with Spice data compression. Maybe a tiny bit higher for TLS. But there are too many impact factors to really say this. The responsiveness of the window manager and single applications are excellent – as with the SSH scenario of the last article. I leave it to the reader to test it out on his own.

Does TLS encryption to the VM work locally, too?

An interesting question is whether we can have
encryption locally on the KVM/Qemu-server, too. The answer is: Yes, but you still have to provide the FQDN of the server; the network request will nevertheless be handled over the “lo”-device. This at least enables you to test your VM settings locally. But local encryption could also be interesting in some multi-user scenarios.

Using different options for the defaultMode and the Spice data channels

Allowed values for the “defaultMode” attribute in the Spice configuration of the VM are “secure”, “insecure” and “any”. With “any” you can switch between encrypted and unencrypted access at any time by closing the Spice windows and opening them again with different settings for the remote-viewer. You should check which port is taken by looking at the output of e.g. netstat. Using “secure” will enforce TLS-encryption; if no sufficient certificates were in place the VM would not even start then.

An important feature regarding TLS is that you may define which Spice data channel should/must be encrypted. You find more information about this at https://libvirt.org/formatdomain.html#graphical-framebuffers. I quote from the documentation there:

When SPICE has both a normal and TLS secured TCP port configured, it can be desirable to restrict what channels can be run on each port. This is achieved by adding one or more elements inside the main element and setting the mode attribute to either secure or insecure. Setting the mode attribute overrides the default value as set by the defaultMode attribute. (Note that specifying any as mode discards the entry as the channel would inherit the default mode anyways.) Valid channel names include main, display, inputs, cursor, playback, record (all since 0.8.6 ); smartcard ( since 0.8.8 ); and usbredir ( since 0.9.12 ).

The example given in the libvirt documentation is:

<graphics type='spice' port='-1' tlsPort='-1' autoport='yes'>
  <channel name='main' mode='secure'/>
  <channel name='record' mode='insecure'/>
  <image compression='auto_glz'/>
  <streaming mode='filter'/>
  <clipboard copypaste='no'/>
  <mouse mode='client'/>
  <filetransfer enable='no'/>
  <gl enable='yes' rendernode='/dev/dri/by-path/pci-0000:00:02.0-render'/>

Off topic: You see that there are more options for Spice – e.g. the streaming parameter, which can be used for video-streaming. In a quiet minute the interested reader should have a look into the Spice documentation at
to get more information.

What about other security elements?

It is nice that we now are able to use a TLS encrypted connection for remote-viewer. But a noticeable disadvantage in comparison to the SSH-tunnel scenario of my last article is that we must keep the Spice TLS-port open and accessible on the server. In addition: Basic security measures on a server should also include some form of user authentication – and the access to the Spice console of a VM should be restricted to selected users. With the TLS-elements discussed above alone we cannot achieve this. So, you have to wait for yet another blog article.

In the meantime you can and should at least set a password for the Spice console:

<graphics type='spice' port='20001' tlsPort='20002' autoport='no' keymap='de' defaultMode='any' password='my_verysecret_pwd' >

See the 2nd article of this series about it.


It is relatively easy to
configure a KVM/Qemu-server such that it encrypts Spice data with TLS. We tested this with a remote-viewer instance started on a client-system somewhere in our Intranet. A basic requirement is of course the creation of a private CA and certificates/keys. Tools like TinyCA or XCA help us with this.
As remote-viewer directly talks to the Qemu-emulator we had to configure libvirtd to enable dependent tools like “virsh” and “virt-manager” to start qemu-processes with the required parameters for TLS. This could be done via a few settings in the file “/etc/libvirt/qemu.conf”.
This type of qemu-configuration differs from activating TLS for a remote access to libvirt-based tools themselves. As a consequence the private server-key to be used by the Qemu process must be made readable for the “qemu”-user.
The TLS setup for remote-viewer and Spice neither allowed for user authentication on the server nor for user-specific restrictions so far. In the next article

KVM/Qemu VMs with a multi-screen Spice console – VII – remote-viewer, qemu and SASL authentication

we shall, therefore, have a look at methods for user authentication combined with TLS.


Qmu, Spice und TLS



Spice + defaultMode

OpenSSL to check for a valid TLS certificate on a network port