[CentOS] UID/GID migration vom C6 to C8

Mon Nov 15 14:48:17 UTC 2021
Simon Matter <simon.matter at invoca.ch>

> Hello.
>
> We have to migrate an old Centos 6 to Centos 8. C6 has UID/GID starting
> at number 500.
> I the Users should possibily keep the existing UID/GID as on the old
> system.
>
> I changed on the Centos 8 system, in /etc/login.defs, the lines
> UID_MIN/SYS_UID_MAX and GID_MIN/SYS_GID_MAX:
>
> #
> # Min/max values for automatic uid selection in useradd
> #
> UID_MIN                   500
> UID_MAX                 60000
> # System accounts
> SYS_UID_MIN               201
> SYS_UID_MAX               499
>
> #
> # Min/max values for automatic gid selection in groupadd
> #
> GID_MIN                   500
> GID_MAX                 60000
> # System accounts
> SYS_GID_MIN               201
> SYS_GID_MAX               499
>
> and extracted all users and groups with UID/GID greater than 499 from
> the old system and inserted in the corresponding files
> (passwd/groups/shadows) on the new system.
>
> So wanted to ask if this is a valid thing to do? Especially regarding
> security of the new system. Can it create problems in the future
> (updates etc.)?
> It is a simple LAMP server.

I was in a similar situation but on a quite large application server with
hundreds of users.
I quickly found that I don't want to fiddle with UID/GID settings so I
decided to change all users on the CentOS 6 host before migrating any
data.
I've created a script which uses `chown' to recursively change UIDs and
GIDs. I don't remember exactly but I think I made it run for every user in
parallel and it finished quite fast considering the fact that it had to
traverse the whole storage consisting of millions of files.
I could then later just rsync everything to the new box without ant
UID/GID conversion.
See below for the script `chuidgid'.

Regards,
Simon

----%<-----
#!/bin/bash

if (( $# < 4 )); then
  echo "Usage: $0 <username> <new uid> <new gid | \"\" = uid> <dir>
[<dir>...]"
  echo "Example: $0 user1 1000 \"\" /tmp /etc /usr /opt /var /home"
  echo
  echo "Important: this needs to run before changing any uid/gid!"
  exit 1
fi

USR="$1"
NEW_UID="$2"
NEW_GID="$3"

shift 3
DIRS=$@

OLD_UID=$(id -u "$USR")
OLD_GID=$(id -g "$USR")

if [[ -z "$NEW_GID" ]]; then
  NEW_GID="$NEW_UID"
fi

echo "modifying user $USR ids ${OLD_UID}:${OLD_GID} ->
${NEW_UID}:${NEW_GID} on $DIRS"

# Note: usermod changes ownership of at least $HOME and
/var/spool/mail/${USR}
groupmod -g "$NEW_GID" "$USR"
usermod -u "$NEW_UID" -g "$USR" "$USR"

chown --changes --silent --no-dereference --preserve-root --recursive
--from=":${OLD_GID}" ":${NEW_GID}" $DIRS
chown --changes --silent --no-dereference --preserve-root --recursive
--from="${OLD_UID}"   "${NEW_UID}" $DIRS
----%<-----