【转】使用SHC加密bash脚本程序以及解密

转自https://www.xiaohuai.com/4949

SHC代表shell script compiler,即shell脚本编译器。通过SHC编译过的脚本程序对普通用户而言是不读的,因此如果你想保护你的代码(例如含有密钥),则可以考虑SHC;然而有些人可以通过反向编译的方式破解SHC加密过的脚本。

1.下载并编译SHC

1
2
3
4
5
wget http://www.datsi.fi.upm.es/~frosal/sources/shc-3.8.9.tgz
tar zxf shc-3.8.9.tgz
cd shc-3.8.9
mkdir -p /usr/local/man/man1
make install

2.建立一个测试bash脚本

1
2
3
4
5
6
7
8
9
#!/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

这个脚本的意思输出几个随机数,你执行的时候输入2,就输出2个,输入3就输出3个。

3.使用SHC加密bash脚本

1
$ ./shc -f random.sh

之后我们可以看到多出两个文件:

1
2
3
4
$ 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

random.sh 是原始的未加密的bash脚本
random.sh.x 是加密的二进制格式的bash脚本
random.sh.x.c 是random.sh的C源代码。该文件是从random.sh转换而来的,SHC就是通过将bash脚本转为C语言再编译之进行加密的。

4.执行加密的bash脚本

1
2
3
4
5
$ ./random.sh.x
How many random numbers do you want to generate? 3
15146
20741
17825

二、SHC的其他功能

一些常用参数

1
2
3
4
5
-e date (指定过期时间)
-m message  (指定过期提示的信息)
-f  script_name (指定要编译的shell路径)
-r  relax security  (在不同操作系统执行)
-v  Verbose compilation (输出编译的详细情况)

1.设置脚本使用期限
我们可以通过SHC指定程序的有效期,过期后程序将失效,任何尝试运行的用户将收到错误消息。SHC使用-e dd/mm/yyyy来开启该功能:

1
$ ./shc -e 31/12/2011 -f random.sh

如果程序过期了,将会得到以下消息:

1
2
3
$ ./random.sh.x
./random.sh.x: has expired!
Please contact your provider

结合-m “message”选项,我们可以指定发生错误时输出的消息:

1
2
3
4
$ ./shc -e 31/12/2011 -m &quot;Contact admin@lesca.me for new version of this script&quot; -f random.sh
$ ./random.sh.x
./random.sh.x: has expired!
Contact admin@lesca.me for new version of this script

2.创建可重复发布的加密脚本
-r: 允许该脚本在同操作系统的不同硬件平台上运行
-T: 允许让ltrace, strace那样的程序追踪脚本运行
-v: 输出详细信息
通常-r与-T一起使用,用于创建可重复发布且可追踪的加密脚本,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ ./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

解密:
git地址:https://github.com/yanncam/UnSHc

将unshc wget或者上传到任意目录
然后可执行如下命令查看帮助

1
./unshc.sh -h

执行下面的命令进行解密(此过程可能耗时有点长,需耐心等待)

1
2
3
wget https://www.xiaohuai.com/down/unshc.sh
chmod +x unshc.sh
./unshc.sh script.sh.x -o script_decrypted.sh

script.sh.x文件为经过加密的二进制文件
script_decrypted.sh文件为解密后shell脚本