SHC 是 Shell Script Compiler 的縮寫,顧名思義就是 shell 腳本編譯器。經過 SHC 處理後的腳本,一般使用者只會看到一個二進位執行檔,讀不出原始內容,因此如果你想保護代碼(例如腳本裡寫死了金鑰),SHC 是個選項。
不過要先有心理準備:並非絕對安全。有經驗的人可以透過逆向工程把 SHC 加密過的腳本還原出來,它只能算「提高門檻」,不能當成真正的加密方案。
# wget https://www.datsi.fi.upm.es/~frosal/sources/shc-3.8.7.tgz # tar xvfz shc-3.8.7.tgz # cd shc-3.8.7 # make
驗證是否安裝成功:
$ ./shc -v shc parse(-f): No source file specified shc Usage: shc [-e date] [-m addr] [-i iopt] [-x cmnd] [-l lopt] [-rvDTCAh] -f script
#!/bin/bash echo -n "How many random numbers do you want to generate? " read max for (( start = 1; start <= $max; start++ )) do echo -e $RANDOM done
$ ./shc -f random.sh $ ll random.sh* -rwxr-xr-x 1 lesca lesca 153 2012-05-16 06:34 random.sh* -rwx--x--x 1 lesca lesca 10512 2012-05-16 06:34 random.sh.x* -rw-r--r-- 1 lesca lesca 10145 2012-05-16 06:34 random.sh.x.c
三個檔案的分工如下:
用 file 指令確認:
random.sh: Bourne-Again shell script text executable
random.sh.x: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV),
dynamically linked (uses shared libs), for GNU/Linux 2.6.15, stripped
random.sh.x.c: ASCII C program text
執行加密後的版本:
$ ./random.sh.x How many random numbers do you want to generate? 3 15146 20741 17825
SHC 可以指定程式的有效期,過期後任何使用者執行都會收到錯誤訊息。用 -e 搭配 dd/mm/yyyy 格式開啟:
$ ./shc -e 31/12/2011 -f random.sh $ ./random.sh.x ./random.sh.x: has expired! Please contact your provider
搭配 -m 可以自訂提示訊息:
$ ./shc -e 31/12/2011 -m "Contact admin@lesca.me for new version of this script" -f random.sh $ ./random.sh.x ./random.sh.x: has expired! Contact admin@lesca.me for new version of this script
通常 -r 與 -T 一起使用,用來產生可重複發布且可追蹤的版本:
$ ./shc -v -r -T -f random.sh shc shll=bash shc [-i]=-c shc [-x]=exec '%s' "$@" shc [-l]= shc opts= shc: cc random.sh.x.c -o random.sh.x shc: strip random.sh.x shc: chmod go-r random.sh.x $ ./random.sh.x How many random numbers do you want to generate? 3 1311 19637 14891
交付時只給 .x 檔就好,.c 與原始腳本請留在自己手上。另外,SHC 產物會依賴特定 glibc 版本,跨機型發布前務必實測;若你的目標是保護敏感金鑰,更穩妥的做法是把金鑰移到環境變數或外部配置檔,而不是硬寫在腳本裡。