คำถาม: จะเข้ารหัส Bash Shell Script บน Linux ยังไง? สคริปต์มีรหัสผ่าน อยากป้องกันไม่ให้คนที่มีสิทธิ์รัน (execute) อ่านโค้ดและเห็นรหัสผ่าน มีวิธีเข้ารหัได้ไหม?
คำตอบ: ก่อนอื่น ต้องบอกเลยว่า ไม่ควรเข้ารหัส Shell Script ควรเขียนเอกสารให้ชัดเจน ถ้ามีข้อมูลสensitive อย่างรหัสผ่าน ควรหาวิธีเขียนสคริปต์แบบไม่ต้องเก็บรหัสผ่านไว้ในโค้ด
แต่หากยังต้องการเข้ารหัส สามารถใช้ SHC (Shell Script Compiler) ได้ โปรดทราบว่าไฟล์ไบนารีที่ SHC สร้าง ไม่ได้เข้ารหัสจริงๆ ใครที่เข้าใจหลักการทำงานสามารถดึงสคริปต์ต้นฉบับคืนมาได้
1. ดาวน์โหลดและติดตั้ง 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
2. สร้าง Shell Script ตัวอย่าง
สร้าง random.sh สุ่มตัวเลข:
$ vi random.sh #!/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 $ ./random.sh How many random numbers do you want to generate? 3 24682 1678 491
3. เข้ารหัส Shell Script ด้วย SHC
$ ./shc -f random.sh
จะได้ไฟล์ 2 ไฟล์:
$ ls -l random.sh* -rwxrw-r--. 1 ramesh ramesh 149 Mar 27 01:09 random.sh -rwx-wx--x. 1 ramesh ramesh 11752 Mar 27 01:12 random.sh.x -rw-rw-r--. 1 ramesh ramesh 10174 Mar 27 01:12 random.sh.x.c
random.sh: สคริปต์ต้นฉบับrandom.sh.x: ไฟล์ไบนารีที่เข้ารหัสแล้วrandom.sh.x.c: โค้ด C ที่แปลงจากสคริปต์ คอมไพล์เป็นrandom.sh.x
$ file random.sh random.sh: Bourne-Again shell script text executable $ file random.sh.x random.sh.x: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, for GNU/Linux 2.6.18, stripped $ file random.sh.x.c random.sh.x.c: ASCII C program text
4. รันสคริปต์ที่เข้ารหัสแล้ว
$ ./random.sh.x How many random numbers do you want to generate? 3 7489 10494 29627
หมายเหตุ: ไบนารียังต้องพึ่ง Shell (shebang line เช่น /bin/bash) เพื่อรัน
5. กำหนดวันหมดอายุ (Expiration Date)
ใช้ -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@thegeekstuff.com for new version" -f random.sh $ ./random.sh.x ./random.sh.x: has expired! Contact admin@thegeekstuff.com for new version of this script
6. สร้าง Encrypted Script ที่กระจายได้ (Redistributable)
ตัวเลือกเพิ่มเติม:
-r: ลดความปลอดภัย เพื่อรันบนระบบ OS เดียวกันได้-T: อนุญาตให้ trace ด้วย strace, ltrace-v: แสดงรายละเอียด
$ ./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 28954 1410 15234
สรุป: ไม่ควรเข้ารหัส Shell Script แต่ถ้าต้องการใช้ SHC ให้จำไว้ว่า ยังสามารถดึงโค้ดต้นฉบับคืนได้ หากผู้รู้จักวิธี