From 271d7009cf623b3befc91b4829761741f8423554 Mon Sep 17 00:00:00 2001 From: MasterofJOKers Date: Sat, 25 Feb 2023 17:13:12 +0100 Subject: [PATCH] Add get-lxc-idmap-config script This script handles uid/gid ranges for creating unprivileged containers as root. --- lxc/get-lxc-idmap-config | 80 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100755 lxc/get-lxc-idmap-config diff --git a/lxc/get-lxc-idmap-config b/lxc/get-lxc-idmap-config new file mode 100755 index 0000000..30f2766 --- /dev/null +++ b/lxc/get-lxc-idmap-config @@ -0,0 +1,80 @@ +#!/bin/sh +# Manage uid/gid maps for containers +# +# This script manages uids/gids assigned to certain containers or groups of containers. It uses /etc/subuid and +# /etc/subgid by default to save the information. All the ranges are owned by root as we don't want to support creation +# of containers by unprivileged users, but rather want to create unprivileged containers as root user. + +USER_ID=0 +FIRST_ID=1000000 +DEFAULT_COUNT=65536 +FILENAME="/etc/sub_____id" + +get_filename () ( + TYPE="${1}" + echo "${FILENAME}" | sed "s/_____/${TYPE}/" +) + +find_range () ( + TYPE="${1}" + NAME="${2}" + FILENAME="$(get_filename ${TYPE})" + + grep -A 1 "^# ${NAME}$" "${FILENAME}" -A 1 | tail -n 1 +) + +get_last_range () ( + TYPE="${1}" + grep "^${USER_ID}:" "$(get_filename ${TYPE})" | tail -n 1 +) + +get_new_range () ( + TYPE="${1}" + LAST_RANGE=$(get_last_range "${TYPE}") + if [ "${LAST_RANGE}" = "" ]; then + NEW_ID=$FIRST_ID; + else + LAST_ID=$(echo "${LAST_RANGE}" | cut -d : -f 2) + LAST_COUNT=$(echo "${LAST_RANGE}" | cut -d : -f 3) + NEW_ID=$(( $LAST_ID + $LAST_COUNT )) + fi + echo "${USER_ID}:${NEW_ID}:${DEFAULT_COUNT}" +) + +append_range () ( + TYPE="${1}" + FILENAME="$(get_filename ${TYPE})" + NAME="${2}" + RANGE="${3}" + printf "# ${NAME}\n${RANGE}\n" >> "${FILENAME}" +) + +usage () { + echo "usage: get-lxc-idmap-config " + exit 1 +} + + +TYPE="${1}" +if [ "${TYPE}" = "" || "${TYPE}" == "--help" || "${TYPE}" == "-h" ]; then + usage +fi + +NAME="${2}" +if [ "${NAME}" = "" ]; then + usage +fi + +RANGE=$(find_range "${TYPE}" "${NAME}") + +if [ "${RANGE}" = "" ]; then + RANGE=$(get_new_range "${TYPE}") + if [ "${RANGE}" = "" ]; then + exit 1 + fi + append_range "${TYPE}" "${NAME}" "${RANGE}" +fi + +RANGE_START=$(echo ${RANGE} | cut -d : -f 2) +RANGE_COUNT=$(echo ${RANGE} | cut -d : -f 3) +printf "lxc.idmap = %s 0 %s %s\n" "${TYPE}" "${RANGE_START}" "$(( ${RANGE_COUNT} - 1))"