kubelogin icon indicating copy to clipboard operation
kubelogin copied to clipboard

Lock file may conflict with another user on a machine

Open wshihadeh opened this issue 4 years ago • 2 comments

Purpose of the feature (why)

By default, the Lock file is located in /tmp, the first user is left with rights to the lock file, and another user can no longer consume the service and they will not be able to perform tasks.

Your idea (how)

if the user id or username is included in the name of the get-token file, it would me impossible to have conflicts between users

wshihadeh avatar Sep 14 '21 16:09 wshihadeh

should be fixed with PullRequest #780

another possibility is:

diff --git a/pkg/infrastructure/mutex/mutex.go b/pkg/infrastructure/mutex/mutex.go
index 1e45aa6..0a60b73 100644
--- a/pkg/infrastructure/mutex/mutex.go
+++ b/pkg/infrastructure/mutex/mutex.go
@@ -54,7 +54,7 @@ func internalRelease(fm *filemutex.FileMutex, lfn string, log logger.Interface)
 
 // LockFileName get the lock file name from the lock name.
 func LockFileName(name string) string {
-       return path.Join(os.TempDir(), fmt.Sprintf(".kubelogin.%s.lock", name))
+       return path.Join(os.TempDir(), fmt.Sprintf(".%v.kubelogin.%s.lock", os.Getuid(), name))
 }

wer-anders avatar Oct 06 '22 14:10 wer-anders

My setup is using OIDC (Dex) with K8s and AD backend. So when I setup a pair of jump servers I wanted all users that admin the K8s cluster, I ran into this issue.

My work-around for it was to set the ENV (TMPDIR) in the kubeconfig to the users $HOME/temp directory. So the .lock file is under each user.

#!/bin/bash
#
#########################################################################################
# Created by: Brandt Winchell                                                           #
# Date Created: 01-23-2022                                                              #
# Date Modified: 02-06-2023                                                             #
# Version: 0.2.0                                                                        #
# ScriptFunction>                                                                       #
#               Configure local user kubeconfig to use                                  #
#               OIDC (Dex) to authenticate to Kubernetes                                #
#                                                                                       #
# Notes>                                                                                #
#       n/a                                                                             #
#                                                                                       #
# Changelog>                                                                            #
#               0.1.0   Initial creation                                                #
#               0.1.1   Removed dedicated log facility                                  #
#               0.1.2   Remove Krew during reset process, set kubeconfig ENV            #
#                       added bashautocomplete to .bashrc                               #
#               0.2.0   Added logic for multiple kubeconfig context                     #
#########################################################################################

######################
# Static Variables   #
######################

scriptfile="$(basename $0)"
timestamp=`date +%R:%S`
max_age="120" #timelimit for this script to run(seconds)
declare -a arrKubeconfigFiles


######################
# Dynamic Variables  #
######################

kubeconfig_root_dir="${HOME}/.kube"
kubeconfig_file="${kubeconfig_root_dir}/config"
kubeconfig_tempdir="${HOME}/temp/"

## Dictionary of names of each kubeconfig context
declare -a dictcontext=("clst01" "clst50")

## Array of kubeconfig context #1 settings
declare -A clst01=( 
                      ["clusterurl"]="https://k8-clst01.local.net:6443" ["sslinsecure"]="true"
                      ["oidcurl"]="https://k8-clst01-dex-k8sauth.local.net" ["oidctoken"]="lkasdfjasdj097097889"
                      ["oidcuser"]="oidc-k8-clst01"
)

## Array of kubeconfig context #2 settings
declare -A clst50=( 
                      ["clusterurl"]="https://k8-clst50.local.net:6443" ["sslinsecure"]="true"
                      ["oidcurl"]="https://k8-clst50-k8sauth.local.net" ["oidctoken"]="asdnlksjh2309432234"
                      ["oidcuser"]="oidc-k8-clst50"
)


######################
# Functions          #
######################

######################
# function configure end logging process
func_end_logging() {
    echo "`date`: Script $0 ended" 2>&1
    echo "****************************************************************************" 2>&1
}

######################
#function to check if $process is already running, if longer than $max_age, then kill process
func_check_process_running() {
    for pid in $(pidof -x $process); do
        if [ $pid != $$ ]; then
            age_in_seconds="$(ps -o etimes= -p $pid)"
            echo "[$(date)] : $process : Process is already running with pid $pid and has been running for $age_in_seconds" 2>&1
                if [[ "$age_in_seconds" -ge "$max_age" ]]; then
                    echo "$timestamp - Backup process has been running for too long and was cancelled." 2>&1
                    kill -s 9 "$pid" #(Backup was running longer than expected and was killed)
                else #(A previous backup process is currently running and within time limit)
                    echo "$timestamp - This pid $$ has terminated awaiting for the existing pid $pid to finish" 2>&1
                    exit 1
                fi
        fi
    done
}

######################
# function to install krew
func_install_krew() {
    echo "$timestamp - Installing Krew..." 2>&1
    
    (
    set -x; cd "$(mktemp -d)" &&
    os="$(uname | tr '[:upper:]' '[:lower:]')" &&
    arch="$(uname -m | sed -e 's/x86_64/amd64/' -e 's/\(arm\)\(64\)\?.*/\1\2/' -e 's/aarch64$/arm64/')" &&
    krew_ver="krew-${os}_${arch}" &&
    curl -fsSLO "https://github.com/kubernetes-sigs/krew/releases/latest/download/${krew_ver}.tar.gz" &&
    tar zxvf "${krew_ver}.tar.gz" &&
    ./"${krew_ver}" install krew
    )

    func_install_krew_exitcode="$(echo $?)"
    echo "$timestamp - func_install_krew_exitcode: $func_install_krew_exitcode" 2>&1

    if [ $func_install_krew_exitcode != 0 ]; then
        error "$timestamp - Krew installation failed!!!" 2>&1
        exit 1
    else
        echo "$timestamp - Krew has been installed" 2>&1
    fi

}

######################
# function to set Krew PATH and re-source bash
func_krew_path_source_shell() {
    stringinfile='export PATH="${KREW_ROOT:-$HOME/.krew}/bin:$PATH"'
    sed -i -e "s|$stringinfile||;" -e '$a '"${stringinfile}" $HOME/.bashrc
    # exec bash
    source $HOME/.bashrc
}

######################
# function to set Krew PATH and re-source bash
func_bashautocomplete_source_shell() {
    stringinfile='source <(kubectl completion bash)'
    sed -i -e "s|$stringinfile||;" -e '$a '"${stringinfile}" $HOME/.bashrc
    # exec bash
    source $HOME/.bashrc
}

######################
# function to update Krew
func_krew_update() {
    kubectl krew update

    func_krew_update_exitcode="$(echo $?)"
    echo "$timestamp - func_krew_update_exitcode: $func_krew_update_exitcode" 2>&1

    if [ $func_krew_update_exitcode != 0 ]; then
        error "$timestamp - Krew update failed!!!" 2>&1
        exit 2
    else
        echo "$timestamp - Krew has been updated" 2>&1
    fi
}

######################
# function to install oidc-login
func_oidc_login_install() {
    echo "$timestamp - Installing oidc-login..." 2>&1
    
    kubectl krew install oidc-login
    func_oidc_login_install_exitcode="$(echo $?)"
    echo "$timestamp - func_oidc_login_install_exitcode: $func_oidc_login_install_exitcode" 2>&1

    if [ $func_oidc_login_install_exitcode != 0 ]; then
        error "$timestamp - Krew update failed!!!" 2>&1
        exit 3
    else
        echo "$timestamp - Krew oidc-login has been installed" 2>&1
    fi
}

######################
# function to configure kubeconfig
func_kubeconfig_copy() {
    mkdir -p $kubeconfig_root_dir/
    mkdir $kubeconfig_tempdir

    ## Build kubeconfig for each context
    for context in "${dictcontext[@]}"; do
        declare -n z="$context"
        local y=${z[clusterurl]}
        local w=${z[sslinsecure]}
        local v=${z[oidcurl]}
        local u=${z[oidctoken]}
        local t=${z[oidcuser]}
        local s="${kubeconfig_file}_${context}"
    
        mkdir -p "${kubeconfig_tempdir}${context}"
        arrKubeconfigFiles+=$s:
         
        cat <<-EOF | tee $s
        apiVersion: v1
        clusters:
        - cluster:
            server: $y
            insecure-skip-tls-verify: $w
          name: $context
        contexts:
        - context:
            cluster: $context
            namespace: default
            user: oidc
          name: $context
        current-context: $context
        kind: Config
        preferences: {}
        users:
        - name: $t
          user:
            exec:
              apiVersion: client.authentication.k8s.io/v1beta1
              args:
              - oidc-login
              - get-token
              - --oidc-issuer-url=$v
              - --oidc-client-id=oidc-static-client
              - --oidc-client-secret=$u
              - --oidc-extra-scope=groups
              - --oidc-extra-scope=profile
              - --oidc-extra-scope=offline_access
              command: kubectl
              env:
              - name: "TMPDIR"
                value: "${kubeconfig_tempdir}${context}"
              provideClusterInfo: false
EOF
    done

}

######################
# function merge kubeconfig context files
func_merge_kubeconfig() {
    stringify_KUBECONFIG="$(echo ${arrKubeconfigFiles[@]})"
    KUBECONFIG=$stringify_KUBECONFIG kubectl config view --flatten > $kubeconfig_file

}

######################
# fuction set kubeconfig context & user associations
func_assoc_kubeconfig() {
    for context in "${dictcontext[@]}"; do
        declare -n z="$context"
        local t=${z[oidcuser]}

        kubectl config set-context $context --user=$t
    done
}

######################
# function to clear oidc-login cache
func_clear_oidc_login_cache() {
    rm -fR $kubeconfig_root_dir/cache
    rm -fR $kubeconfig_tempdir
    mkdir $kubeconfig_tempdir

    echo "$timestamp - oidc-login cache has been cleared" 2>&1
}

######################
# function to configure kubeconfig
func_configure_kubeconfig() {
    func_install_krew
    func_krew_path_source_shell
    func_krew_update
    func_kubeconfig_copy
    func_oidc_login_install
    func_bashautocomplete_source_shell
    func_merge_kubeconfig
    func_assoc_kubeconfig
    
}

######################
# function to reset oidc-login to default
func_reset_oidc_login() {
    echo "$timestamp - Resetting oidc-login to default" 2>&1

    rm -fR $kubeconfig_root_dir/cache
    rm -f $kubeconfig_file
    rm -fR $kubeconfig_tempdir
    rm -fR ${HOME}/.krew
    func_configure_kubeconfig

}

######################
# Gitsub functions
kubeconfigsub() {

    usage() {
            cat <<-EOF
            ------------------------------------------------------------------------
            GNU kubeconfigsub 0.1.0, interactive kubeconfig controller.
            Usage:
                  - kubeconfigsub [-h]
                  - source kubeconfigsub [-a [init|reset|update|clear]]
            ------------------------------------------------------------------------
            Mandatory arguments to long options are mandatory for short options too.
            ------------------------------------------------------------------------
            MANDATORY:
            -a, --action          [init]   - action to install and initiate kubeconfig
                                  [reset]  - Delete $HOME/.kube/[config | cache] and restore to default
                                  [update] - Update oidc-login plugin to latest version
                                  [clear]  - Delete $HOME/.kube/cache (tokens)
            COMMANDS:
            -h, --help            display this help and exit
            ------------------------------------------------------------------------
            Mail bug reports and suggestions to [email protected]
            ------------------------------------------------------------------------
EOF
    }
    error() { echo -e "\033[1;31mError: $1\033[0m" ;}

    # check supplied args
    is_arg() { 
        [[ -n "$2" && ${2:0:1} != "-" ]] \
        || { error "Argument for $1 is missing..." >&2 \
        && usage \
        && exit 14 ;}
    }
    POSITIONAL=()
    while (( "$#" )); do
        case "$1" in
        ## commands
        -h|--help)        usage && exit 0                                  ;;
        ## mandatory flags with arguments
        -a|--action)      is_arg $1 $2 && action=$2              ; shift 2 ;;

        ## unsupported flags
        -*|--*=) error "Unsupported flag $1" >&2 && usage        ; exit 13 ;;
        ## preserve positional arguments
        *) POSITIONAL+=("$1")                                    ; shift   ;;
        esac
    done
    # set positional arguments in their proper place
    set -- "${POSITIONAL[@]}"

    # check mandatory arguments
    [[ -z "$action" ]] \
    && { error "Missing mandatory arguments..." >&2 \
    && usage \
    && exit 15 ;}

    # check input values
    [[ "$action" =~ (^init$)|(^reset$)|(^update$)|(^clear$) ]] \
    || { error "Incorrect action argument value..." >&2 \
    && usage \
    && exit 16 ;}

    # Sanity checks
    func_check_process_running

    # Change Veristy GW status via systemctl
    if [[ "$action" == 'init' ]]; then
        func_configure_kubeconfig
    fi
    if [[ "$action" == 'reset' ]]; then
        func_reset_oidc_login
    fi
    if [[ "$action" == 'update' ]]; then
        func_krew_update
    fi
    if [[ "$action" == 'clear' ]]; then
        func_clear_oidc_login_cache
    fi
}



######################
# Bypass for help    #
######################
if [[ "${1}" == '-h' ]]; then
    kubeconfigsub "$@"
    exit 0
fi


######################
# Main               #
######################
kubeconfigsub "$@"


#########################################################################################
# End logging statement
func_end_logging

tlb1galaxy avatar Feb 01 '23 22:02 tlb1galaxy