Sunday, 1 November 2015

Reset root password by accessing file system on Guest OS from Physical host - CentOS

Everyone know as how to reset your forgotten root password on Linux - (http://goo.gl/6j9u2k), but in this article since I'm using Guest OS on KVM hypervisor, I would demonstrate as how to mount the root file system and reset password.

Details:

Hostname: kvm1
Diskname: vm1
path:     /var/lib/libvirt/images/vm1.img 

- Firstly, you need to shutdown your VM, doing it which it's running can cause disk corruption.
#virsh shutdown vm1

- Check your VM is in shut off state
#virsh list --all

- Get an unused loop device
#losetup -f
/dev/loop0

- Map VM image to your loop device
#losetup /dev/loop0 /var/lib/libvirt/images/vm1.img

- Print your partition table of the image file which is been mapped to the loop device and identify the correct partition where your root file system mounted upon.
#fdisk -l /dev/loop0

Disk /dev/loop0: 10.7 GB, 10737418240 bytes
255 heads, 63 sectors/track, 1305 cylinders, total 20971520 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000907df

      Device Boot      Start         End      Blocks   Id  System
/dev/loop0p1   *        2048     1050623      524288   83  Linux
/dev/loop0p2         1050624     3147775     1048576   82  Linux swap / Solaris
/dev/loop0p3         3147776    20971519     8911872   83  Linux

- In order to mount the VM's partitions, you need to create partition mappings
#kpartx -av /dev/loop0
Disk /dev/loop0: 10.7 GB, 10737418240 bytes
255 heads, 63 sectors/track, 1305 cylinders, total 20971520 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000907df

      Device Boot      Start         End      Blocks   Id  System
/dev/loop0p1   *        2048     1050623      524288   83  Linux
/dev/loop0p2         1050624     3147775     1048576   82  Linux swap / Solaris
/dev/loop0p3         3147776    20971519     8911872   83  Linux

- Here my root file system was on /dev/vda3 which is associated with 
/dev/loop0p3 which would be mounted.
#mount /dev/mapper/loop0p3 /mnt

- remove password field from root user in /etc/shadow 
#vim /mnt/etc/shadow

Note: If your system has been enabled with SELinux, it is very much required to autorelabel else you will be unable to login. Check below snap.




#touch /mnt/.autorelabel

- Once done, remove your mappings and start the VM. 
#umount /mnt
#kpartx -dv /dev/loop0
#losetup -d /dev/loop0

- Start your VM 
#virsh start vm1

- In your console, when you login with 'root' without providing any password.

No comments:

Post a Comment