命令注入是十分致命的安全漏洞,在编码过程中需要予以重视。防止命令注入有一种方便快捷的方法,就是加转义字符过滤用户敏感输入。

示例代码:

 1 char* CGlobe::RejectCommandInjection(char *strCmd)
 2 {
 3     // 通过加转义字符防止命令注入
 4 
 5     memset(m_strBuf,0,sizeof(m_strBuf));
 6 
 7     int len = strlen(strCmd);
 8     //防止字符串长度溢出
 9     if(len > MAX_LEN/2)
10         len = MAX_LEN/2 - 2;
11     int x,y;
12     for(x=0,y=1;x<len;x++)
13     {
14         switch(strCmd[x])
15         {
16         case ';':
17         case '|':
18         case '>':
19         case '<':
20         case '[':
21         case ']':
22         case '&':
23         case '#':
24         case '{':
25         case '}':
26         case '^':
27         case '(':
28         case ')':
29         case '$':
30             m_strBuf[y++] = '\\';
31             m_strBuf[y++] = strCmd[x];
32             break;
33 
34         default:
35              m_strBuf[y++] = strCmd[x];
36 
37         }
38 
39     }
40     //字符串首尾加单引号
41     m_strBuf[0] = '\'';
42     m_strBuf[y] = '\'';
43 
44     return m_strBuf;
45 
46 
47 }

  不过这种方法并不能完全杜绝命令注入,具体可参考php escapeshellcmd多字节编码漏洞解析及延伸

posted on 2015-09-23 17:05  江左醉风流  阅读(1025)  评论(0编辑  收藏  举报