cert.sh 14.7 KB
Newer Older
1 2 3 4 5 6
#!/usr/bin/env bash

scriptPath=${0%/*}
. "$scriptPath"/../../libs/bashhelper.sh
. "$scriptPath"/../../libs/shflags

Janek Bevendorff's avatar
Janek Bevendorff committed
7
check_tools "cryfs keyctl openssl"
8 9 10 11

usage() {
    echo "
usage:
Janek Bevendorff's avatar
Janek Bevendorff committed
12
    $(basename "$0") issue|revoke [OPTIONS]
13 14

description:
Janek Bevendorff's avatar
Janek Bevendorff committed
15
    Manage VPN client, server, and ICA certificates.
16 17 18 19 20 21 22 23 24 25 26

"
    exit 1
}

CMD="$1"
shift

# Define command line arguments and parse them.
if [ "$CMD" == "issue" ]; then
    DEFINE_string "cryfs_dir" "" "CryFS base dir containing the encrypted certificates." "d"
Janek Bevendorff's avatar
Janek Bevendorff committed
27
    DEFINE_integer "keyring_id" -1 "Retrieve given CryFS decryption key from kernel keyring" "k"
28 29
    DEFINE_string "root_cn" "" "CN of the root certificate for signing (optional)" "r"
    DEFINE_string "type" "client" "Certificate type (client | server | ca)" "t"
30 31 32
    DEFINE_string "common_name" "" "Common Name (CN) for the certificate (e.g., username)" "c"
    DEFINE_string "full_name" "" "User's full name" "f"
    DEFINE_string "default_subj" "/C=DE/ST=Thuringia/L=Weimar/O=Webis/" "Default Subj fields (optional)" "s"
33
    DEFINE_string "organizational_unit" "" "Organizational Unit (OU) for the certificate (optional)" "u"
34
    DEFINE_string "email" "" "E-Mail address for the certificate" "e"
35
    DEFINE_boolean "no_password" false "Do not encrypt private key" "n"
36
    DEFINE_boolean "overwrite" false "Overwrite existing certificates instead of incrementing filename (use with caution!)" "x"
Janek Bevendorff's avatar
Janek Bevendorff committed
37
    DEFINE_integer "validity" "" "Certificate validity period in days" "v"
38
    DEFINE_string "csr" "" "CSR file (optional)" "i"
39
    DEFINE_string "out" "/dev/stdout" "OpenVPN .ovpn config or PEM file to generate (optional)" "o"
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
elif [ "$CMD" == "revoke" ]; then
    DEFINE_string "cryfs_dir" "" "CryFS base dir containing the encrypted certificates." "d"
    DEFINE_string "root_cn" "" "CN of the root certificate for signing (optional)" "r"
    DEFINE_string "type" "" "Certificate type (client | server | ca)" "t"
    DEFINE_string "cert_cn" "" "CN of the certificate to revoke" "c"
fi

FLAGS_HELP=$(usage)
export FLAGS_HELP
FLAGS "$@" || exit 1  # Parse command line arguments.
eval set -- "${FLAGS_ARGV}"

export MOUNT_DIR
trap "cleanup ${MOUNT_DIR}; exit $?" INT TERM EXIT

CONF="$(dirname $0)/openssl.conf"


# ===========================================================================
#                              helper commands
# ===========================================================================

# Usage: cleanup MOUNT_DIR
cleanup() {
    if [ ! -d "$1" ]; then
        return
    fi
    logInfo "Unmounting CryFS..."
    fusermount -u "$1" &> /dev/null
    rmdir "$1"
}

72 73 74 75 76 77 78 79
# Usage: update_repository BASE_DIR
pull_repository() {
    if [ ! -d "${1}/.git" ]; then
        logError "CryFS directory is not a Git repository!"
        exit 1
    fi

    logInfo "Updating Git repository..."
80
    if ! (cd "$1" && git pull >&2); then
81 82 83 84 85 86 87 88
        logError "Git update failed!"
        exit 1
    fi
}

# Usage: commit_changes BASE_DIR
commit_changes() {
    logInfo "Committing changes to Git..."
89
    if (cd "$1" && git add -A && git commit -m "-" >&2); then
90 91
        logInfo "Changes committed. Please push the repository now (git push)."
    else
92 93 94 95
        logError "Committing changes failed!"
    fi
}

96 97
# Usage: mount_cryfs BASE_DIR MOUNT_DIR
mount_cryfs() {
98 99 100 101 102
    if [ ! -d "$1" ]; then
        logError "CryFS directory '$1' does not exist!"
        exit 1
    fi

103
    logInfo "Mounting CryFS..."
104
    mkdir -p "$2"
105 106 107 108 109 110 111
    echo keyctl pipe $FLAGS_keyring_id >&2
    if [ $FLAGS_keyring_id -ne -1 ]; then
        < <(keyctl pipe $FLAGS_keyring_id 2>&1) cryfs "$1" "$2" >&2
    else
        cryfs "$1" "$2" >&2
    fi
    if [ $? -ne 0 ]; then
112
        logError "Failed to mount CryFS volume!"
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
        cleanup "$2"
        exit 1
    fi
}

# Usage: choose_root_cert MOUNT_DIR
choose_root_cert() {
    echo -e "\n\nPlease choose a root certificate:" >&2
    root_certs=()
    i=0
    for c in $(find "${1}/ca/" -name "*.pem"); do
        if grep -q "PRIVATE KEY" "$c"; then
            root_certs[$i]="$c"
            printf "  [%2d] $(basename $c | sed 's/\.pem$//')\n" $i >&2
            i=$(($i +1))
        fi
    done

    echo -en "\nYour choice: " >&2
    read root_cert_choice
133 134
    local choice_counter=0
    while [ $choice_counter -lt 10 ] && [ "${root_certs[$root_cert_choice]}" == "" ]; do
135 136 137
        logError "Invalid choice, please enter a valid number."
        echo -en "\nYour choice: " >&2
        read root_cert_choice
138
        choice_counter=$((choice_counter + 1))
139
    done
140 141 142 143 144
    if [ $choice_counter -ge 10 ]; then
        logError "Too many failures."
        cleanup "$1"
        exit 1
    fi
145 146 147 148 149 150 151 152 153
    echo "${root_certs[$root_cert_choice]}"
}

# Usage: generate_key OUT_FILE BITS
generate_key() {
    logInfo "Generating private key..."
    openssl genrsa -out "$1" "$2"
}

154
# Usage: generate_csr CONF CERT_TYPE KEY_FILE OUT_FILE DEFAULT_SUBJ ORG_UNIT CLIENT_CN CLIENT_FULL_NAME CLIENT_EMAIL
155 156
generate_csr() {
    logInfo "Generating CSR..."
157 158 159
    openssl req -new -key "$3" -out "$4" -reqexts "v3_req_${2}" \
        -subj "${5}OU=${6}/CN=${7}/emailAddress=${9}" -reqexts "SAN" \
        -config <(cat "$1" <(printf "\n[SAN]\nsubjectAltName = 'DNS:${8}'"))
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
}

# Usage: revoke_cert CONF CERT CA_KEY CA_CERT
revoke_cert() {
    logInfo "Revoking certificate..."
    openssl ca -config "$1" -revoke "$2" -keyfile "$3" -cert "$4"
}

# Usage: generate_crl CONF CRL_OUT CA_KEY CA_CERT
generate_crl() {
    logInfo "Creating / updating CRL..."
    openssl ca -config "$1" -gencrl -out "$2" -keyfile "$3" -cert "$4" -updatedb
    logInfo "CRL '$2' updated."
}

# Usage: sign_csr CONF CSR_IN CERT_OUT CA_KEY CA_CERT CERT_TYPE
sign_csr() {
    local validity=730
    # certificate validity in days
Janek Bevendorff's avatar
Janek Bevendorff committed
179 180 181
    if [ "$FLAGS_validity" -gt 0 ]; then
        validity="$FLAGS_validity"
    elif [ "$6" == "server" ]; then
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
        validity=1825
    elif [ "$6" == "ca" ]; then
        validity=3650
    fi

    openssl ca -config "$1" -in "$2" -out "$3" -keyfile "$4" -cert "$5" -create_serial \
        -days "$validity" -extensions "v3_cert_${6}" -notext -batch -updatedb
}

# Usage: ensure_ca_base_dir DATA_DIR
ensure_ca_base_dir() {
    if [ ! -d "$1" ]; then
        logInfo "Creating CA data dir..."
        mkdir -p "${1}/certs"
        touch "${1}/index.txt"
        echo 1000 > "${1}/crlnumber.txt"
    fi
}

# Usage: CA_CERT
resolve_ca_chain() {
    local cert_file="$1"
    local issuer

    while : ; do
        if [ ! -f "$cert_file" ]; then
            logError "Unable to find certificate for '${issuer}', CA chain may be incomplete!"
            break
        fi

        cat "$cert_file"

        issuer="$(openssl x509 -in "${cert_file}" -noout -issuer | grep -Po '(?<=CN = )[^,]+')"
        local issuer_cert_file="$(dirname "$cert_file")/${issuer}.crt"
        if [ "$(realpath $cert_file)" == "$(realpath $issuer_cert_file)" ]; then
            break
        fi
        cert_file="$issuer_cert_file"
    done
}

223 224 225 226 227
# Usage: TYPE OUT_FILE CERT CA_CERT [KEY] [NO_PASSWORD]
generate_output_file() {
    if [ "$5" != "" ] && [ "$6" -eq 0 ]; then
        local pem="$(cat "$5")"
    elif [ "$5" != "" ]; then
228 229 230 231 232
        local extra_param=""
        if ! tty -s; then
            # non-interactive shell, get password from env
            extra_param="-passout env:PK_PASS"
        fi
233
        echo "Password to encrypt private key in .ovpn config file: " >&2
234
        local pem="$(openssl rsa -aes256 -in $5 $extra_param)"
235
        local counter=0
236 237
        while [ "$pem" == "" ]; do
            logError "Invalid passphrase, please try again."
238
            local pem="$(openssl rsa -aes256 -in $5 $extra_param)"
239 240 241 242 243 244

            counter=$(($counter + 1))
            if [ $counter -ge 10 ]; then
                logError "Too many input failures."
                return 1
            fi
245
        done
246
    fi
247

248
    local out_file="$2"
249

250
    if [ "$1" == "ovpn" ]; then
251 252 253
    cat <<EOL > "$out_file"
client
remote vpn.webis.de
254 255 256
remote vpn1.webis.de
remote vpn2.webis.de
remote vpn3.webis.de
257 258 259 260 261
dev tun
proto udp
port 1194
remote-cert-tls server

262 263 264
# Cipher is set on the server, this is only to avoid warnings
cipher AES-256-GCM

265 266 267 268 269
<key>
$pem
</key>

<cert>
270
$(cat "$3")
271 272 273
</cert>

<ca>
274
$(resolve_ca_chain "$4")
275 276 277
</ca>
EOL

278 279 280 281 282 283 284 285 286 287 288 289 290
        logInfo "OpenVPN config file has been written to '$2'."
    else
        cat <<EOL > "$out_file"
$pem

$(cat "$3")

$(resolve_ca_chain "$4")
EOL

        logInfo "PEM file has been written to '$2'."
    fi

291
    return 0
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
}


# ===========================================================================
#                               issue command
# ===========================================================================
issue() {
    if [ "$FLAGS_cryfs_dir" == "" ]; then
        logError "--cryfs_dir is required"
        exit 1;
    fi
    if [ "$FLAGS_type" != "client" ] && [ "$FLAGS_type" != "server" ] && [ "$FLAGS_type" != "ca" ]; then
        logError "Invalid certificate type: ${FLAGS_type}"
        exit 1
    fi
    if [ "$FLAGS_common_name" == "" ]; then
        logError "--common_name is required"
        exit 1;
    fi
311 312
    if [ "$FLAGS_full_name" == "" ]; then
        logError "--full_name is required"
313 314
        exit 1;
    fi
315 316
    if [ "$FLAGS_email" == "" ]; then
        logError "--email is required"
317 318 319
        exit 1;
    fi

320 321
    pull_repository "${FLAGS_cryfs_dir}"

322 323 324
    MOUNT_DIR="${FLAGS_cryfs_dir}_mount.${RANDOM}"
    mount_cryfs "$FLAGS_cryfs_dir" "$MOUNT_DIR"

325 326
    ROOT_KEY="${MOUNT_DIR}/ca/${FLAGS_root_cn}.pem"
    if [ "$FLAGS_root_cn" == "" ] || [ ! -f "$ROOT_KEY" ]; then
327 328 329 330 331 332 333 334 335 336 337 338 339
        ROOT_KEY="$(choose_root_cert "$MOUNT_DIR")"
        logInfo "Using '$(basename "${ROOT_KEY}" | sed 's/\.pem$//')' as the root certificate..."
    fi
    ROOT_CERT="$(echo -n "$ROOT_KEY" | sed 's/\.pem$/.crt/')"
    export CA_BASE_DIR="$(echo "$ROOT_CERT" | sed 's/\.crt$//')_Data"
    ensure_ca_base_dir "$CA_BASE_DIR"

    BITS=2048

    # use provided CSR or generate new one
    CSR="$FLAGS_csr"
    DELETE_KEY=false
    DELETE_CSR=false
340

341 342
    local cert_filename="$FLAGS_common_name"
    CERT="${MOUNT_DIR}/${FLAGS_type}/${cert_filename}.crt"
343 344 345
    local counter_suffix=0
    while [ $FLAGS_overwrite -eq 1 ] && [ -f "$CERT" ]; do
        counter_suffix=$(($counter_suffix + 1))
346
        CERT="${MOUNT_DIR}/${FLAGS_type}/${cert_filename}_${counter_suffix}.crt"
347 348
    done
    if [ $counter_suffix -gt 0 ]; then
349 350
        logWarn "Certificate file '${FLAGS_type}/${cert_filename}.crt' already exists, saving as '${FLAGS_type}/${cert_filename}_${counter_suffix}.crt'."
        cert_filename="${cert_filename}_${counter_suffix}"
351 352
    fi

353
    if [ "$CSR" == "" ] || [ ! -f "$CSR" ]; then
354
        KEY="${MOUNT_DIR}/${FLAGS_type}/${cert_filename}.pem"
355
        if [ $FLAGS_overwrite -eq 1 ] && [ -f "$KEY" ]; then
356 357 358 359 360 361
            logError "Key file ${KEY} already exists!"
            cleanup "$MOUNT_DIR"
            exit 1
        fi
        generate_key "$KEY" "$BITS"

362
        CSR="${MOUNT_DIR}/${FLAGS_type}/${cert_filename}.csr"
363
        if [ $FLAGS_overwrite -eq 1 ] && [ -f "$CSR" ]; then
364
            logError "CSR file ${CSR} already exists!"
365
            rm -f "$KEY"
366 367 368
            cleanup "$MOUNT_DIR"
            exit 1
        fi
369
        if ! generate_csr "$CONF" "$FLAGS_type" "$KEY" "$CSR" "$FLAGS_default_subj" "$FLAGS_organizational_unit" "$FLAGS_common_name" "$FLAGS_full_name" "$FLAGS_email"; then
370
            logError "CSR generation failed!"
371
            rm -f "$KEY" "$CSR"
372 373 374 375 376 377 378 379 380 381 382 383 384
            cleanup "$MOUNT_DIR"
            exit 1
        fi

        if [ "$FLAGS_type" == "client" ]; then
            DELETE_KEY=true
        fi
        DELETE_CSR=true
    fi

    logInfo "Signing client certificate..."
    if ! sign_csr "$CONF" "$CSR" "$CERT" "$ROOT_KEY" "$ROOT_CERT" "$FLAGS_type"; then
        logError "Signing failed!"
385
        rm -f "$KEY" "$CSR" "$CERT"
386 387 388 389 390 391
        cleanup "$MOUNT_DIR"
        exit 1
    fi

    if [ "$FLAGS_type" == "client" ]; then
        logInfo "Writing .ovpn file..."
392 393 394 395 396 397 398 399 400 401
        local type="ovpn"
    else
        logInfo "Writing PEM file..."
        local type="pem"
    fi
    ROOT_CA_CERT="$(dirname $ROOT_CERT)/Webis_Root_CA.crt"
    if ! generate_output_file "$type" "$FLAGS_out" "$CERT" "$ROOT_CERT" "$KEY" $FLAGS_no_password; then
        rm -f "$KEY" "$CSR" "$CERT"
        cleanup "$MOUNT_DIR"
        exit 1
402 403
    fi
    if $DELETE_KEY; then
Janek Bevendorff's avatar
Janek Bevendorff committed
404
        # delete private key after generating ovpn file
405 406 407 408
        logInfo "Deleting temporary private key..."
        rm "$KEY"
    fi
    if $DELETE_CSR; then
Janek Bevendorff's avatar
Janek Bevendorff committed
409
        # delete CSR after generating ovpn file
410 411 412 413 414 415 416 417
        logInfo "Deleting temporary CSR..."
        rm "$CSR"
    fi

    CRL="$(echo -n "$ROOT_KEY" | sed 's/\.pem$/.crl/')"
    generate_crl "$CONF" "$CRL" "$ROOT_KEY" "$ROOT_CERT"

    cleanup "$MOUNT_DIR"
418
    commit_changes "${FLAGS_cryfs_dir}"
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
}


# ===========================================================================
#                               revoke command
# ===========================================================================

revoke() {
    if [ "$FLAGS_cryfs_dir" == "" ]; then
        logError "--cryfs_dir is required"
        exit 1;
    fi
    if [ "$FLAGS_cert_cn" == "" ]; then
        logError "--cert_cn is required"
        exit 1;
    fi
    if [ "$FLAGS_type" == "" ]; then
        logError "--type is required"
        exit 1;
    fi

440 441
    pull_repository "${FLAGS_cryfs_dir}"

442 443 444
    MOUNT_DIR="${FLAGS_cryfs_dir}_mount.${RANDOM}"
    mount_cryfs "$FLAGS_cryfs_dir" "$MOUNT_DIR"

445 446
    ROOT_KEY="${MOUNT_DIR}/ca/${FLAGS_root_cn}.pem"
    if [ "$FLAGS_root_cn" == "" ] || [ ! -f "$ROOT_KEY" ]; then
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
        ROOT_KEY="$(choose_root_cert "$MOUNT_DIR")"
        logInfo "Using '$(basename "${ROOT_KEY}" | sed 's/\.pem$//')' as the root certificate..."
    fi
    ROOT_CERT="$(echo -n "$ROOT_KEY" | sed 's/\.pem$/.crt/')"
    export CA_BASE_DIR="$(echo "$ROOT_CERT" | sed 's/\.crt$//')_Data"
    ensure_ca_base_dir "$CA_BASE_DIR"

    CERT="${MOUNT_DIR}/${FLAGS_type}/${FLAGS_cert_cn}.crt"
    if [ ! -f "$CERT" ]; then
        logError "Certificate '${CERT}' does not exist."
        cleanup "$MOUNT_DIR"
        exit 1
    fi

    echo -n "Are you sure you want to revoke the ${FLAGS_type} certificate '${FLAGS_cert_cn}'? [y/N] "
    read answer
    if [ "$answer" != "y" ] && [ "$answer" != "Y" ]; then
        logError "Revocation aborted."
        cleanup "$MOUNT_DIR"
        exit 1
    fi
    if ! revoke_cert "$CONF" "$CERT" "$ROOT_KEY" "$ROOT_CERT"; then
        logError "Certificate revocation failed!"
        cleanup "$MOUNT_DIR"
        exit 1
    fi

    CRL="$(echo -n "$ROOT_KEY" | sed 's/\.pem$/.crl/')"
    generate_crl "$CONF" "$CRL" "$ROOT_KEY" "$ROOT_CERT"

    cleanup "$MOUNT_DIR"
478
    commit_changes "${FLAGS_cryfs_dir}"
479 480 481 482 483 484 485 486 487 488 489 490 491
}

# ===========================================================================
#                                 bootstrap
# ===========================================================================

if [ "$CMD" == "issue" ] || [ "$CMD" == "revoke" ]; then
    $CMD "$@"
else
    logError "Invalid command '$CMD'."
    usage
    exit 1
fi