Friday, January 22, 2016

How to reset the password in an LXC container

Question: I created an LXC container, but I cannot log in to the container as I forgot the default user's password and the root password. How can I reset the password on an LXC container?
When you create an LXC container, it will have the default username/password set up. The default username/password will vary depending on which LXC template was used to create the container. For example, Debian LXC will have the default username/password set to root/root. Fedora LXC will have the root password set as expired, so it can be set on the first login. Ubuntu LXC will have ubuntu/ubuntu as the default username/password. For any pre-built container images downloaded from third-party repositories, their default username/password will also be image-specific.
If you do not know the default username/password of your LXC container, there is an easy way to find the default username and reset its password.
First of all, make sure to stop the LXC container before proceeding.
$ sudo lxc-stop -n

Find the Default User of an LXC Container

To find the default username created in an LXC container, open the /etc/passwd of the container, which can be found at /var/lib/lxc//rootfs/etc/passwd of the LXC host. In the passwd file of the container, look for "login-enabled" users, which have "/bin/bash" (or something similar) listed as their login shell. Any of such usernames can be the default username of the container. For example, in the screenshot below, the usernames "ubuntu" or "sdn" are login-enabled.

Any username which has "/usr/sbin/nologin" or "/bin/false" as its login shell is login-disabled.

Reset the User Password in an LXC Container

To reset the password of any login-enabled username, you can modify /etc/shadow file of the container, which can be fount at /var/lib/lxc//rootfs/etc/shadow of the LXC host. In Linux, the /etc/shadow file stores one-way encrypted passwords (password hashes) of user accounts. Each line in /etc/shadow is formatted as strings concatenated with ":" delimeter. The first two strings represent a username and its encrypted password.

If the password field is set to '!' or '*', it means the user account is locked for access or completely disabled for login.
To reset the password of any login-enabled username, all you have to do is to remove the password hash of the username and leave the ":" delimeter only. For example, for username "sdn", change:
Similarly, to reset the root password, simply delete the password hash of the root.
With the password field set to empty, you will be able to login to the user account without any password from the console. Now start the container, and verify password-less console login.
Don't forget to set a new password using passwd after successful login.

No comments:

Post a Comment