summaryrefslogtreecommitdiff
path: root/ssh-keys.sh
blob: 3004affd18d7ddf0e049ffce86fb22e7108e7876 (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
#!/usr/bin/env bash
## check if ldapsearch is installed

DRY_RUN=false
if [ "$1" == "-n" ]; then
  DRY_RUN=true
fi

sunetEmpl="leif leifj lundberg linus per john"
ignoreList="ndn-eduix nunoc"
if [ -f /opt/cf-replace-ignore ]; then
  ignoreList=$(cat /opt/cf-replace-ignore)
fi

for userHome in /home/*; do
  user=$(basename "$userHome")
  keys_raw=$(/usr/bin/ldapsearch -o nettimeout=5 -o ldif-wrap=no -LLL -x -H "ldaps://ldap.nordu.net" -b "ou=people,dc=nordu,dc=net" "(&(employeeType=employee)(memberof=cn=ndn-sysadmin,ou=groups,dc=nordu,dc=net)(sshPublicKey=*)(uid=$user))" sshPublicKey)
  search_status=$?

  if [ "$search_status" -ne 0 ]; then
    echo "Ldap search failed for $user with status $search_status, ignoring"
    continue
  fi

  keys=$(echo "$keys_raw" | grep '^sshPublicKey' | cut -f 2- -d' ')
  authorized_keys="/home/$user/.ssh/authorized_keys"
  if grep -q "$user" <<< "$sunetEmpl"; then
    # skip SUNET people
    keys=""
  fi
  if grep -q "$user" <<< "$ignoreList"; then
    # skip certain users
    continue
  fi
  if [ -n "$keys" ]; then
    # write authorized_keys
    if $DRY_RUN; then
        echo "$user"
    else
      echo "$keys" > "$authorized_keys"
    fi
   else
   # blank authorized_keys
    if $DRY_RUN; then
      echo "!$user"
    else
      echo "" > "$authorized_keys"
    fi
  fi
done