aboutsummaryrefslogtreecommitdiff
path: root/add-authorized-keys
blob: 212c277aeef1ebb75fb3471161b584a3e80c8233 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/bin/bash

### Add RSA keys to the authorized_keys file of a given user

### Copyright (C) 2015, 2022 Rafael Laboissière
###
### This program is free software; you can redistribute it and/or modify it under
### the terms of the GNU General Public License as published by the Free Software
### Foundation; either version 3 of the License, or (at your option) any later
### version.
###
### This program is distributed in the hope that it will be useful, but WITHOUT
### ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
### FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
### details.
###
### You should have received a copy of the GNU General Public License along with
### this program; if not, see <http://www.gnu.org/licenses/>.

### Get the program name
prog=${0##*/}

usage () {
    local status=$1
    echo "Usage: $prog [-h] [-r] user file" >&$(($status + 1))
    echo "Options:" >&$(($status + 1))
    echo "  -h  show this usage notice" >&$(($status + 1))
    echo "  -r  force read-only access" >&$(($status + 1))
    echo "Arguments:" >&$(($status + 1))
    echo "  user  the Git user to act upon" >&$(($status + 1))
    echo "  file  the RSA public key to be added" >&$(($status + 1))
    exit $status
}

### Default value
readonly=no

### Parse arguments
args=$(getopt rh $*)

eval set -- "$args"

while true ; do
    case "$1" in
        -h) usage 0 ; exit ;;
        -r) readonly=yes ; shift ;;
        --) shift ; break ;;
    esac
done

### Ensure that the correct number of arguments are given
if [ $# != 2 ] ; then
    usage 1
fi

### Get Git user name and check its sanity
user=$1

ret=false
id -u $user >/dev/null 2>&1 && ret=true

if [ $ret = false ] ; then
    echo "$prog:E: User $user does not exist.  Add it first." 1>&2
    exit 1
fi

### Get RSA file name and check its sanity
rsaid=$2

type="OpenSSH RSA public key"
if [ "$(file --brief $rsaid)" != "$type" ] ; then
    echo "$prog:E: File $rsaid is not of type '$type'." 1>&2
    exit 1
fi

### Install the key(s)
tmp=$(mktemp)
cleanup(){
    rm -f $tmp
}
trap "cleanup" 1 2 3 13 15
if [ "$readonly" = yes ] ; then
    echo -n "command=\"read-only\" " > $tmp
fi
cat $rsaid >> $tmp

home=$(getent passwd $user | cut -f6 -d:)
cat $tmp >> $home/.ssh/authorized_keys
cleanup