| 1 | #!/bin/bash |
|---|
| 2 | |
|---|
| 3 | CERT="macports_codesign" |
|---|
| 4 | |
|---|
| 5 | function error() { |
|---|
| 6 | echo error: "$@" |
|---|
| 7 | exit 1 |
|---|
| 8 | } |
|---|
| 9 | |
|---|
| 10 | function cleanup { |
|---|
| 11 | # Remove generated files |
|---|
| 12 | rm -f "$TMPDIR/$CERT.tmpl" "$TMPDIR/$CERT.cer" "$TMPDIR/$CERT.key" > /dev/null 2>&1 |
|---|
| 13 | } |
|---|
| 14 | |
|---|
| 15 | trap cleanup EXIT |
|---|
| 16 | |
|---|
| 17 | # Check if the certificate is already present in the system keychain |
|---|
| 18 | security find-certificate -Z -p -c "$CERT" /Library/Keychains/System.keychain > /dev/null 2>&1 |
|---|
| 19 | if [ $? -eq 0 ]; then |
|---|
| 20 | echo Certificate has already been generated and installed |
|---|
| 21 | exit 0 |
|---|
| 22 | fi |
|---|
| 23 | |
|---|
| 24 | # Create the certificate template |
|---|
| 25 | cat <<EOF >$TMPDIR/$CERT.tmpl |
|---|
| 26 | [ req ] |
|---|
| 27 | default_bits = 2048 # RSA key size |
|---|
| 28 | encrypt_key = no # Protect private key |
|---|
| 29 | default_md = sha512 # MD to use |
|---|
| 30 | prompt = no # Prompt for DN |
|---|
| 31 | distinguished_name = codesign_dn # DN template |
|---|
| 32 | [ codesign_dn ] |
|---|
| 33 | commonName = "$CERT" |
|---|
| 34 | [ codesign_reqext ] |
|---|
| 35 | keyUsage = critical,digitalSignature |
|---|
| 36 | extendedKeyUsage = critical,codeSigning |
|---|
| 37 | EOF |
|---|
| 38 | |
|---|
| 39 | echo Generating and installing macports_codesign certificate |
|---|
| 40 | |
|---|
| 41 | # Generate a new certificate |
|---|
| 42 | openssl req -new -newkey rsa:2048 -x509 -days 3650 -nodes -config "$TMPDIR/$CERT.tmpl" -extensions codesign_reqext -batch -out "$TMPDIR/$CERT.cer" -keyout "$TMPDIR/$CERT.key" > /dev/null 2>&1 |
|---|
| 43 | [ $? -eq 0 ] || error Something went wrong when generating the certificate |
|---|
| 44 | |
|---|
| 45 | # Install the certificate in the system keychain |
|---|
| 46 | sudo security add-trusted-cert -d -r trustRoot -p codeSign -k /Library/Keychains/System.keychain "$TMPDIR/$CERT.cer" > /dev/null 2>&1 |
|---|
| 47 | [ $? -eq 0 ] || error Something went wrong when installing the certificate |
|---|
| 48 | |
|---|
| 49 | # Install the key for the certificate in the system keychain |
|---|
| 50 | sudo security import "$TMPDIR/$CERT.key" -A -k /Library/Keychains/System.keychain > /dev/null 2>&1 |
|---|
| 51 | [ $? -eq 0 ] || error Something went wrong when installing the key |
|---|
| 52 | |
|---|
| 53 | # Kill task_for_pid access control daemon |
|---|
| 54 | sudo pkill -f /usr/libexec/taskgated > /dev/null 2>&1 |
|---|
| 55 | |
|---|
| 56 | # Exit indicating the certificate is now generated and installed |
|---|
| 57 | exit 0 |
|---|