...
1#!/bin/bash
2
3# Copyright 2023 Google LLC.
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# https://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16set -eux
17
18PASSWORD="1234"
19WORK_DIR=$(mktemp -d)
20KEYCHAIN="BuildTest.keychain"
21KEYCHAIN_TEST_BINARY=$(echo "$PWD/$(find . -iname keychain.test)")
22
23pushd "${WORK_DIR}"
24
25openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -sha256 -days 5 -nodes -subj "/C=US/ST=WA/L=Kirkland/O=Temp/OU=CI/CN=TestIssuer/emailAddress=dev@example.com"
26openssl pkcs12 -inkey key.pem -in cert.pem -export -out cred.p12 -passin pass:${PASSWORD} -passout pass:${PASSWORD}
27
28security create-keychain -p ${PASSWORD} ${KEYCHAIN}
29
30# Disable password prompt timeout
31security set-keychain-setting ${KEYCHAIN}
32
33# Put custom keychain on keychain path
34security list-keychains -d user -s ${KEYCHAIN}
35
36security default-keychain -s "${KEYCHAIN}"
37
38security import cred.p12 -P ${PASSWORD} -k ${KEYCHAIN} -A
39security unlock-keychain -p ${PASSWORD} ${KEYCHAIN}
40
41# Sign the test binary
42codesign -s - "${KEYCHAIN_TEST_BINARY}"
43
44# Grab CD Hash of the keychain test binary
45KEYCHAIN_TEST_BINARY_CD_HASH=$(codesign --display --verbose=4 "${KEYCHAIN_TEST_BINARY}" 2>&1 | grep 'CDHash=\(.*\)' | cut -d '=' -f 2)
46
47# Need to specify in ACL that the test binary can access the test toolchain
48# This is because the `-A` param to allow all applications access to the private key on the import
49# command is apparently not enough...
50#
51# This method was found by comparing the diff of `$ security dump-keychain -a` before and after always
52# allowing the test binary access
53security set-key-partition-list -S "cdhash:${KEYCHAIN_TEST_BINARY_CD_HASH}" -k ${PASSWORD} ${KEYCHAIN}
54
55popd
View as plain text