|
#!/bin/bash |
|
set -eo pipefail |
|
|
|
# Threshold number of days for expiration check |
|
DAYS_FOR_EXPIRATION_CHECK=30 |
|
IFS=$'\n' |
|
|
|
today=$(date +"%s") |
|
tenant_id=$(az account show --query tenantId -o tsv) |
|
|
|
# Get all principal IDs assigned roles to the resources under the subscription set in the CLI |
|
# https://docs.microsoft.com/en-us/cli/azure/role/assignment?view=azure-cli-latest#az_role_assignment_list |
|
principal_ids=$(az role assignment list --all --query "[?principalType=='ServicePrincipal'].principalId" -o tsv) |
|
unique_principal_ids=$(echo "$principal_ids" | sort -u) |
|
|
|
function check_expire() { |
|
diff=$((($1 - $2)/86400)) |
|
if [ $diff -lt $DAYS_FOR_EXPIRATION_CHECK ]; then |
|
echo true |
|
else |
|
echo false |
|
fi |
|
} |
|
|
|
for pid in $unique_principal_ids; do |
|
sp=$(az ad sp show --id "$pid" -o json) |
|
app_owner_tenant_id=$(echo "$sp" | jq -r '.appOwnerTenantId') |
|
|
|
# Skip if the service principal is not owned by the tenant or Managed ID (appOwnerTenantId: null) |
|
if [[ "$app_owner_tenant_id" != "$tenant_id" ]]; then |
|
continue |
|
fi |
|
|
|
app_id=$(echo "$sp" | jq -r '.appId') |
|
app=$(az ad app show --id "$app_id" -o json) |
|
app_name=$(echo "$app" | jq -r '.displayName') |
|
|
|
# Check password expiration |
|
len=$(echo "$app" | jq -r '.passwordCredentials' | jq length) |
|
if [[ "$len" -ne 0 ]]; then |
|
for i in $( seq 0 $((len - 1)) ); do |
|
end_date=$(echo "$app" | jq -r .passwordCredentials["$i"].endDate) |
|
end_date_s=$(date -d "$end_date" +"%s") |
|
is_near_expire=$(check_expire "$end_date_s" "$today") |
|
if [[ "$is_near_expire" = 'true' ]]; then |
|
printf "app_id:%s\tapp_display_name:%s\tpassword_expire:%s\n" "$app_id" "$app_name" "$end_date" |
|
fi |
|
done |
|
fi |
|
|
|
# Check key(certificate) expiration |
|
len=$(echo "$app" | jq -r '.keyCredentials' | jq length) |
|
if [[ "$len" -ne 0 ]]; then |
|
for i in $( seq 0 $((len - 1)) ); do |
|
end_date=$(echo "$app" | jq -r .keyCredentials["$i"].endDate) |
|
end_date_s=$(date -d "$end_date" +"%s") |
|
is_near_expire=$(check_expire "$end_date_s" "$today") |
|
if [[ "$is_near_expire" = 'true' ]]; then |
|
printf "app_id:%s\tapp_display_name:%s\tkey_expire:%s\n" "$app_id" "$app_name" "$end_date" |
|
fi |
|
done |
|
fi |
|
done |