修改Zend引擎实现PHP源码加密的原理及实践_PHP
PHP文件的源码都是明文,这对于某些商业用途来说,并不适合。
因此考虑使用加密的手段保护源码。
实在不耐烦等待zend出编译器,而且编译和加密本质上不是一回事儿。自己动手、开始修改。
一、基本原理
考虑截获PHP读取源文件的接口。一开始,我考虑从Apache和PHP之间的接口处 处理,参见apache的src/modules/php4/mod_php4.c (这个是PHP用static方式编译进apache,make install 后的文件),在send_php()函数中截获文件指针,采用临时文件的方式,解密后替换文件指针。这种方 法经过测试实践,证明是可行的。但是,必须使用两次文件操作,效率低下,而且对于DSO方式不可采用。
由此,重新考虑截获PHP读取文件并装载至缓存的过程,经过费力的寻找,发现在Zend引擎中zend-scanner.c是做此处理的。开始对此文件修改。
二、实现方法示意
采用libmcrypt作为加 密模块,现在采用的是DES方法ECB模式加密,
下面是文件加密的源代码:
/* ecb.c-------------------cut here-----------*/
/* encrypt for php source code version 0.99 beta
we are using libmcrypt to encrypt codes, please
install it first.
compile command line:
gcc -O6 -lmcrypt -lm -o encryptphp ecb.c
please set LD_LIBRARY_PATH before use.
GNU copyleft, designed by wangsu , miweicong */
#define MCRYPT_BACKWARDS_COMPATIBLE 1
#define PHP_CACHESIZE 8192
#include
#include
#include
#include
#include
#include
#include
main(int argc, char** argv)
{
int td, i,j,inputfilesize,filelength;
char filename[255];
char password[12];
FILE* ifp;
int readfd;
char *key;
void *block_buffer;
void *file_buffer;
int keysize;
int decode=0;
int realbufsize=0;
struct stat *filestat;
if(argc == 3) {
strcpy(password,argv[1]);
strcpy(filename,argv[2]);
} else if(argc == 4 && !strcmp(argv[1],"-d")){
strcpy(password,argv[2]);
strcpy(filename,argv[3]);
decode=1;
printf("Entering decode mode ... n");
} else {
printf("Usage: encryptphp [-d] password filenamen");
exit(1);
}
keysize=mcrypt_get_key_size(DES);
key=calloc(1, mcrypt_get_key_size(DES));
gen_key_sha1( key, NULL, 0, keysize, password, strlen(password));
td=init_mcrypt_ecb(DES, key, keysize);
if((readfd=open(filename,O_RDONLY,S_IRUSR|S_IWUSR|S_IRGRP))==-1){
printf("FATAL: Can't open file to read");
exit(3);
}
filestat=malloc(sizeof(stat));
fstat(readfd,filestat);
inputfilesize=filestat- >st_size;
printf("filesize is %d n",inputfilesize);
filelength=inputfilesize;
inputfilesize=((int)(floor(inputfilesize/PHP_CACHESIZE))+1)*PHP_CACHESIZE;
if((file_buffer=malloc(inputfilesize))==NULL){
printf("FATAL: can't malloc file buffer.n");
exit(2);
}
if((block_buffer=malloc(PHP_CACHESIZE))==NULL){
printf("FATAL: can't malloc encrypt block buffer.n");
exit(2);
}
j=0;
while(realbufsize=read (readfd,block_buffer, PHP_CACHESIZE)){
printf(".");
if(!decode){
if(realbufsizefor(i=realbufsize;i((char *)block_buffer)[i]=' ';
}
}
mcrypt_ecb (td, block_buffer, PHP_CACHESIZE);
} else {
mdecrypt_ecb (td, block_buffer, realbufsize);
}
memcpy(file_buffer+j*PHP_CACHESIZE,block_buffer,PHP_CACHESIZE);
j++;
}
close(readfd);
if((ifp=fopen(filename,"wb"))==NULL){
printf("FATAL: file access error.n");
exit(3);
}
fwrite ( file_buffer, inputfilesize, 1, ifp);
free(block_buffer);
free(file_buffer);
free(filestat);
fclose(ifp);
printf("n");
return 0;
}
/*--- end of ecb.c ------------------------------------*/
因为ECB模式是块长度确定的块加密,这里填充了一 些空字符。
然后,修改php代码中 Zend/zend-scanner.c 如下:
(我的php版本是4.01pl2, SUNsparc/solaris 2.7, gcc 2.95;)
文件前加入:
#define MCRYPT_BACKWARDS_COMPATIBLE 1
#include
然后,注释掉大约3510行前后的YY_INPUT的定义。
然后, 修改大约5150行前后的yy_get_next_buffer()函数:
函数头加上定义:
void *tempbuf;
char *key;
char debugstr[255];
int td,keysize;
int x,y;
FILE *fp;
然后 ,注释掉
YY_INPUT( (&yy_current_buffer- >yy_ch_buf[number_to_move]),
yy_n_chars, num_to_read );
这一句。
改为:
tempbuf=malloc(num_to_read);
if((yy_n_chars=fread(tempbuf,1,num_to_read,yyin))!=0){
/*decode*/
#define password "PHPphp111222"
#define debug 0
keysize=mcrypt_get_key_size(DES);
key=calloc(1, mcrypt_get_key_size(DES));
gen_key_sha1( key, NULL, 0, keysize, password, strlen(password));
td=init_mcrypt_ecb(DES, key, keysize);
mdecrypt_ecb(td, tempbuf, yy_n_chars);
memcpy((&yy_current_buffer- >yy_ch_buf[number_to_move]),tempbuf,yy_n_chars);
if(debug){
fp=fopen("/tmp/logs","wb");
fwrite("nstartn",7,1,fp);
fwrite(tempbuf,1,yy_n_chars,fp);
fwrite("nenditn",7,1,fp);
fclose(fp);
}
}
free(tempbuf);
然后,编译php,按正常方法安装即可,因为我对于libtool不太熟悉,因此我选择static方式,并在 configure时加入了--with-mcrypt,这样我就不用自己手工修改Makefile
三、测试及结果
编译php,apache后,用ecb.c编译出来的encryptphp加密了几个文件,分别为 这是因为块的ECB加密方式决定了必须使用定长块,所以,请 诸位同好指点采用何种流加密方式可以兼顾到zend每次读取8192字节的缓存处理方式。(其他平台上 zend每次读取的块长度可能有所不同)
四、说明
我的机器是SUN Ultra1, solaris 2.7, gcc 2.95 , apache 1.3.12,
php 4.01pl2, libmcrypt 2.2.4
我的C水平很差,请大家见谅。这里只是原理说明。
感谢老米飞刀等提供的协助。
源码遵从GNU,需要注意,libmcrypt提供的某些加密方式不是free的。

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools
