aboutsummaryrefslogtreecommitdiff
path: root/ssl/uca/uca
blob: 625f684e5cdc1ab19ab7c8c05a7820f3f056cb2b (plain) (blame)
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
#!/bin/bash -e

# configuration variables (change at will)
CONFIG="/etc/ssl/openssl.cnf"
CERT_SUFFIX=".cert.pem"
KEY_SUFFIX=".key.pem"
REQ_SUFFIX=".req.pem"

# global variables set through parameters
CA=${CA:-root}
CA_CERT="${CA}${CERT_SUFFIX}"
CA_KEY="${CA}${KEY_SUFFIX}"
CA_SERIAL="${CA}.srl"

# print usage
print_usage() {
    cat <<- EOF
    uca - a certificate authority of micro complexity
    
    uca setup
    uca issue cert

    Environment Variables:
    CA name of certificate authority
EOF
}

# generate new certificate authority
new_ca() {
    local ca_req="${CA}${REQ_SUFFIX}"

    openssl genpkey -algorithm RSA -out "$CA_KEY" -pkeyopt rsa_keygen_bits:4096 #-aes-256-cbc
    openssl req -new -key "$CA_KEY" -out "$ca_req"
    openssl x509 -req -in "$ca_req" -extfile "$CONFIG" -extensions v3_ca -days 3650 -signkey "$CA_KEY" -out "$CA_CERT"

    echo "01" > "$CA_SERIAL"

    rm -f "$reqfile"
}

# issue new certificate
# $1 name of new certificate
issue() {
    local keyfile="${1}${KEY_SUFFIX}"
    local reqfile="${1}${REQ_SUFFIX}"
    local certfile="${1}${CERT_SUFFIX}"

    echo $certfile

    openssl genpkey -algorithm RSA -out "$keyfile" -pkeyopt rsa_keygen_bits:4096
    openssl req -new -key "$keyfile" -out "$reqfile"
    openssl x509 -req -in "$reqfile" -extfile "$CONFIG" -extensions usr_cert -CA "$CA_CERT" -CAkey "$CA_KEY" -CAserial "$CA_SERIAL" -out "$certfile"

    rm -f "$reqfile"
}


case "$1" in
    setup)
        new_ca
        exit 0
        ;;

    issue)
        if [ -e "$CA_CERT" ] && [ -e "$CA_KEY" ]; then
            echo $2
            issue $2
            exit 0
        else 
            echo "no root certificate and key found"
            exit 1
        fi
        ;;

    *)
        print_usage
        exit 0
esac