Yanyg - Software Engineer

Shell脚本嵌入到二进制代码中

目录

1 描述

最近需要完成一个小的加密工具,有较高安全要求,并要求快速完成,但对加解密性能 不敏感。为简化实现,规划使用Bash Shell封装,调用现有工具GPG完成。使用tarbzip2压缩,使用openssl对tar包执行对称加密,使用objcopy转为二进制对象,与C语言 链接生成可执行二进制程序。C语言使用系统调用unshare NewNamespace保护挂载,在挂载 点内执行openssl解密、解压缩,并执行具体的非对称安全加密任务。为进一步保证安全, 对二进制程序执行移除所有符号。

2 技术点备忘

2.1 openssl加解密

~$ openssl enc -pass pass:123 -e -aes-256-cbc -in test.txt -out test.txt.enc
~$ openssl enc -pass pass:123 -d -aes-256-cbc -in test.txt.enc -out test.txt.new
### We can get more notice with wrong option. e.g.: --help, --xxx
~$ openssl enc --help
unknown option '--help'
options are
-in <file>     input file
-out <file>    output file
-pass <arg>    pass phrase source
-e             encrypt
-d             decrypt
-a/-base64     base64 encode/decode, depending on encryption flag
-k             passphrase is the next argument
-kfile         passphrase is the first line of the file argument
-md            the next argument is the md to use to create a key
                 from a passphrase.  One of md2, md5, sha or sha1
-S             salt in hex is the next argument
-K/-iv         key/iv in hex is the next argument
-[pP]          print the iv/key (then exit if -P)
-bufsize <n>   buffer size
-nopad         disable standard block padding
-engine e      use engine e, possibly a hardware device.
Cipher Types
-aes-128-cbc               -aes-128-cbc-hmac-sha1     -aes-128-cfb
-aes-128-cfb1              -aes-128-cfb8              -aes-128-ctr
-aes-128-ecb               -aes-128-gcm               -aes-128-ofb
-aes-128-xts               -aes-192-cbc               -aes-192-cfb
... ...

2.2 objcopy转换任意文件为二进制目标对象

~$ objcopy -I binary -O elf64-x86-64 -B i386 file.in file.o
~$ readelf -s test.o

Symbol table '.symtab' contains 5 entries:
   Num:    Value          Size Type    Bind   Vis      Ndx Name
     0: 0000000000000000     0 NOTYPE  LOCAL  DEFAULT  UND
     1: 0000000000000000     0 SECTION LOCAL  DEFAULT    1
     2: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT    1 _binary_test_in_start
     3: 0000000000000205     0 NOTYPE  GLOBAL DEFAULT    1 _binary_test_in_end
     4: 0000000000000205     0 NOTYPE  GLOBAL DEFAULT  ABS _binary_test_in_size
#### => We need to define extern char variable with above name
~$ cat eg.c
extern const char _binary_test_in_start;
extern const char _binary_test_in_end;
// #### => The data is positioned bewteen above symbol
... ...
copy_region_to_data(&_binary_test_in_start, &_binary_test_in_end, "test.data");
// #### => DATA RANGE: [&_binary_test_in_start, &_binary_test_in_end)

2.3 strip symbol

~$ strip --strip-all test

2.4 gpg howto

3 其他设计事项

3.1 为保证尽可能多的平台兼容性,使用静态链接

3.2 关键二进制程序静态链接生成,内置到二进制发布包中

3.3 交互式输入密码策略,降低可用性,但更安全

3.4 充分应用非对称加密提高可靠性

4 References