oauth2-qbittorrent-mod/root/etc/s6-overlay/s6-rc.d/init-oauth2-qbittorrent-config/run

46 lines
2 KiB
Text
Raw Normal View History

2024-01-15 23:59:14 -07:00
#!/usr/bin/with-contenv bash
# shellcheck shell=bash
## Override the webui username & password with a custom one for this session,
## to effectively make localhost requests the only valid kind. This was originally
## intended to pass directly to oauth2-proxy, but the qbittorrent auth process
## requires making a request to /api/v2/auth/login, which isn't really possible.
# Generate password and hash into an array in the format of [BASE64_SALT, PASSWORD, BASE64_HASH]
mapfile \
-d ':' \
-t generated \
< <(
python3 \
-c "from hashlib import pbkdf2_hmac; import os, base64, string, random; salt = os.urandom(16); password = ''.join(random.choices(string.ascii_uppercase+string.ascii_lowercase+string.digits, k=64)); print(f'{base64.standard_b64encode(salt).decode()}:{base64.standard_b64encode(pbkdf2_hmac(\"sha512\", password.encode(), salt, 100000)).decode()}', end='')"
)
# Detect if the qbittorrent config file has the LocalHostAuth key already (it doesn't by default)
grep -qF 'WebUI\LocalHostAuth' /config/qBittorrent/qBittorrent.conf
LOCALHOSTAUTH_MISSING=$?
# Modify the qbittorrent config file to
# 1. Replace the username & password entry (username is always DO_NOT_CHANGE)
# 2. Enable localhost whitelisting to allow oauth2-proxy to bypass auth
awk \
-v "salt=${generated[0]}" \
-v "hash=${generated[1]}" \
-v "localhostauth_missing=$LOCALHOSTAUTH_MISSING" \
'/^WebUI\\Password_PBKDF2=/ { \
printf "WebUI\\Password_PBKDF2=\"@ByteArray(%s:%s)\"\n",salt,hash; \
next; \
}; \
/^WebUI\\Username=/ { \
print "WebUI\\Username=DO_NOT_CHANGE"; \
next; \
}; \
/^WebUI\\LocalHostAuth=/ { \
print "WebUI\\LocalHostAuth=false"; \
next; \
} \
/^\[Preferences]/ { \
print;
if (localhostauth_missing == 1) print "WebUI\\LocalHostAuth=false"; \
next;
} \
{ print; }' \
/config/qBittorrent/qBittorrent.conf \
> tmp && mv tmp /config/qBittorrent/qBittorrent.conf