Skip to content

Instantly share code, notes, and snippets.

@Yxogenium
Last active June 4, 2017 11:27
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Yxogenium/801dbd4cf5d9e5151be1e7e60e5f7653 to your computer and use it in GitHub Desktop.

Chrooting RPi partition using systemd-nspawn

By chrooting a partition, you may issue any user command on a mounted partition as if you had booted on this partition. systemd-nspawn is a systemd-specific command providing better isolation than the traditional chroot command (see the archlinux wiki for a more in-depth description).

Prerequisites

pkcon install qemu qemu-user-static

(no need to install qemu-user as qemu-user-static supersedes it, nor qemu-user-binfmt, as binfmt files are already provided by the installed package).

Mounting and chrooting

On Fedora, partitions are automounted with exec (check the output of lsblk and mount).

RPI_MNT="/run/media/USER/__"
## OR ##
pmount -e /dev/sdb4 rpi # Note the -e for exec
RPI_MNT="/media/rpi"

You may now chroot to the mounted partition. However, to be able to run ARM executables you need to copy qemu-arm-static binaries to the target partion.

cp "/usr/bin/qemu-arm-static" "$RPI_MNT/usr/bin"
systemd-nspawn -D "$RPI_MNT" qemu-arm-static /bin/bash

(Nb: Apparently, simply systemd-nspawn -D "$RPI_MNT" works)

Changing root password

On my system passwd and chpasswd lead to core dumps. I eventually managed to modify the password directly in /etc/shadow.

To do so, you'll first need the SHA-512 hash of your password as provided by crypt(3). The following Python script will do the trick:

#!/usr/bin/env python3
import crypt
import getpass

def main():
    print("This will return a SHA-512 hashed and salted version of the password.")
    pwd = getpass.getpass('Password: ')
    
    if getpass.getpass("Verifying: ") == pwd:
        print(crypt.crypt(pwd, crypt.mksalt(crypt.METHOD_SHA512)))
    else:
        raise ValueError("Passwords don't match")

if __name__ == '__main__':
    main()

You may now paste the string (something like $6$7ZnZp9lP.tCHzB5Z$IZg8WSTb.wVC/72gltImh1i241x42eRjIwyjQmPeD25gH.rscLITF6fN2dnkB.Kn2lqhGykUw1jSSt47pOzej.) between the first and second colon of the file /etc/shadow after root:

root:$6$7ZnZp9lP.tCHzB5Z$IZg8WSTb.wVC/72gltImh1i241x42eRjIwyjQmPeD25gH.rscLITF6fN2dnkB.Kn2lqhGykUw1jSSt47pOzej.:17206:0:99999:7:::

(Note the file will probably open read-only. In vi, you should therefore exit using :x! to save the changes)

I also enabled ssh : systemctl enable sshd. Putting the sdcard in the Raspberry Pi, I was able to ssh into it and login using the root password I chose.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment