Home Backend Development PHP Tutorial ThinkPHP framework security implementation analysis_php example

ThinkPHP framework security implementation analysis_php example

May 16, 2016 pm 07:57 PM
thinkphp framework Safety

ThinkPHP framework is one of the more popular PHP frameworks in China. Although it is not comparable to those foreign frameworks, the advantage is that, well, the Chinese manual is very comprehensive. I have been studying SQL injection recently. When I used the TP framework before, because the underlying layer provided security functions, I didn’t consider security issues much during the development process.

1. I have to say the I function

TP system provides I function for filtering input variables. The meaning of the entire function body is to obtain data in various formats, such as I('get.'), I('post.id'), and then use the htmlspecialchars function (by default) to process it.

If you need to use other methods for security filtering, you can set it from /ThinkPHP/Conf/convention.php:

'DEFAULT_FILTER'    => 'strip_tags',
//也可以设置多种过滤方法
'DEFAULT_FILTER'    => 'strip_tags,stripslashes',
Copy after login

You can find the I function from /ThinkPHP/Common/functions.php, the source code is as follows:

/**
 * 获取输入参数 支持过滤和默认值
 * 使用方法:
 * <code>
 * I('id',0); 获取id参数 自动判断get或者post
 * I('post.name','','htmlspecialchars'); 获取$_POST['name']
 * I('get.'); 获取$_GET
 * </code>
 * @param string $name 变量的名称 支持指定类型
 * @param mixed $default 不存在的时候默认值
 * @param mixed $filter 参数过滤方法
 * @param mixed $datas 要获取的额外数据源
 * @return mixed
 */
function I($name,$default='',$filter=null,$datas=null) {
  static $_PUT  =  null;
  if(strpos($name,'/')){ // 指定修饰符
    list($name,$type)   =  explode('/',$name,2);
  }elseif(C('VAR_AUTO_STRING')){ // 默认强制转换为字符串
    $type  =  's';
  }
  /*根据$name的格式获取数据:先判断参数的来源,然后再根据各种格式获取数据*/
  if(strpos($name,'.')) {list($method,$name) =  explode('.',$name,2);} // 指定参数来源
  else{$method =  'param';}//设定为自动获取
  switch(strtolower($method)) {
    case 'get'   :  $input =& $_GET;break;
    case 'post'  :  $input =& $_POST;break;
    case 'put'   :  /*此处省略*/
    case 'param'  :  /*此处省略*/
    case 'path'  :  /*此处省略*/
  }
  /*对获取的数据进行过滤*/
  if('' // 获取全部变量
    $data    =  $input;
    $filters  =  isset($filter)&#63;$filter:C('DEFAULT_FILTER');
    if($filters) {
      if(is_string($filters)){$filters  =  explode(',',$filters);} //为多种过滤方法提供支持
      foreach($filters as $filter){
        $data  =  array_map_recursive($filter,$data); //循环过滤
      }
    }
  }elseif(isset($input[$name])) { // 取值操作
    $data    =  $input[$name];
    $filters  =  isset($filter)&#63;$filter:C('DEFAULT_FILTER');
    if($filters) {   /*对参数进行过滤,支持正则表达式验证*/
      /*此处省略*/
    }
    if(!empty($type)){ //如果设定了强制转换类型
      switch(strtolower($type)){
        case 'a': $data = (array)$data;break;  // 数组 
        case 'd': $data = (int)$data;break;  // 数字 
        case 'f': $data = (float)$data;break;  // 浮点  
        case 'b': $data = (boolean)$data;break;  // 布尔
        case 's':  // 字符串
        default:$data  =  (string)$data;
      }
    }
  }else{ // 变量默认值
    $data    =  isset($default)&#63;$default:null;
  }
  is_array($data) && array_walk_recursive($data,'think_filter'); //如果$data是数组,那么用think_filter对数组过滤
  return $data;
}
Copy after login

Well, the function is basically divided into three parts:
The first block is to obtain data in various formats.
The second block performs loop encoding on the acquired data, whether it is a two-dimensional array or a three-dimensional array.
The third block, which is the penultimate line, calls think_filter to perform the final step of mysterious processing on the data.

Let’s trace the think_filter function first:

//1536行 版本3.2.3最新添加
function think_filter(&$value){// 过滤查询特殊字符  
  if(preg_match('/^(EXP|NEQ|GT|EGT|LT|ELT|OR|XOR|LIKE|NOTLIKE|NOT BETWEEN|NOTBETWEEN|BETWEEN|NOTIN|NOT IN|IN)$/i',$value)){    
    $value .= ' ';  
  }
}
Copy after login

This function is very simple and can be seen at a glance. It adds a space after some specific keywords.

But this function called think_filter only adds a space. What filtering effect does it play?

We all know that important logical verification, such as verifying whether the user is logged in, whether the user can purchase a certain product, etc., must be verified from the server side. If verified from the front end, it can be easily bypassed. For the same reason, in a program, logical structures such as in/exp are best controlled by the server.

When the data passed to the server is like this: id[0]=in&id[1]=1,2,3, if there is no think_filter function, it will be parsed into 1 in the following table, and it will be regarded as Server-side logic parsing. But if it becomes like Table 2 below, because there is an extra space, it cannot be matched and parsed, thus avoiding the loophole.

$data['id']=array('in'=>'1,2,3') 
//经过think_filter过滤之后,会变成介个样子:
$data['id']=array('in '=>'1,2,3')
Copy after login

2. SQL injection

The relevant files are:/ThinkPHP/Library/Think/Db.class.php (changed to /ThinkPHP/Library/Think/Db/Driver.class.php in 3.2.3) and /ThinkPHP/Library/Think /Model.class.php. The Model.class.php file provides functions directly called by curd and directly provides external interfaces. The functions in Driver.class.php are indirectly called by curd operations.

//此次主要分析如下语句:
M('user')->where($map)->find();  //在user表根据$map的条件检索出一条数据

Copy after login

Briefly talk about TP’s processing ideas:

First instantiate the Model class into a user object, and then call the where function in the user object to process $map, that is, perform some formatting on $map and assign it to the member variable $options of the user object (if there are other For coherent operations, values ​​are first assigned to the corresponding member variables of the user object instead of directly splicing SQL statements. Therefore, when writing coherent operations, there is no need to consider the order of keywords like splicing SQL statements), and then calling the find function.

The find function will call the underlying function - select in the driver class to obtain data. When it comes to the select function, it's another story.

In addition to curd operations, select also handles pdo binding. We only care about curd operations here, so we call buildSelectSql in select to process paging information, and call parseSQL to assemble SQL statements in the established order.

Although all the parameters required to splice SQL statements have been placed in member variables, the format is not uniform. It may be in string format, it may be in array format, or it may be the special query format provided by TP , for example: $data['id']=array('gt','100');, so before splicing, the respective processing functions must be called for unified formatting. I chose parseWhere, a complex example, for analysis.

Regarding security, if you use the I function to obtain data, htmlspecialchars processing will be performed by default, which can effectively resist XSS attacks, but has little impact on SQL injection.

When filtering symbols related to SQL injection, TP’s approach is very clever: first process the user’s input according to normal logic, and then perform safe processing in functions such as parseWhere and parseHaving that are closest to the final SQL statement. This order avoids injection during processing.

Of course, the most common processing method is addslashes. According to the former waves who died on the beach, it is recommended to use mysql_real_escape_string for filtering, but this function can only be used if the database has been connected.

I feel like TP can do some optimization in this area. After all, everyone who has reached this point is connected to the database.

Well, next, the analysis begins:

Let’s talk about a few member variables in the Model object:

// 主键名称
protected $pk   = 'id';
// 字段信息
protected $fields = array();
// 数据信息
protected $data  = array();
// 查询表达式参数
protected $options = array();
// 链操作方法列表
protected $methods = array('strict','order','alias','having','group','lock','distinct','auto','filter','validate','result','token','index','force')
接下来分析where函数:
public function where($where,$parse=null){
  //如果非数组格式,即where('id=%d&name=%s',array($id,$name)),对传递到字符串中的数组调用mysql里的escapeString进行处理
  if(!is_null($parse) && is_string($where)) { 
    if(!is_array($parse)){ $parse = func_get_args();array_shift($parse);}
    $parse = array_map(array($this->db,'escapeString'),$parse);
    $where = vsprintf($where,$parse); //vsprintf() 函数把格式化字符串写入变量中
  }elseif(is_object($where)){
    $where =  get_object_vars($where);
  }
  if(is_string($where) && '' != $where){
    $map  =  array();
    $map['_string']  =  $where;
    $where =  $map;
  }   
  //将$where赋值给$this->where
  if(isset($this->options['where'])){     
    $this->options['where'] =  array_merge($this->options['where'],$where);
  }else{
    $this->options['where'] =  $where;
  }
   
  return $this;
}
Copy after login

where函数的逻辑很简单,如果是where('id=%d&name=%s',array($id,$name))这种格式,那就对$id,$name变量调用mysql里的escapeString进行处理。escapeString的实质是调用mysql_real_escape_string、addslashes等函数进行处理。

最后将分析之后的数组赋值到Model对象的成员函数——$where中供下一步处理。

再分析find函数:

//model.class.php  行721  版本3.2.3
public function find($options=array()) {
  if(is_numeric($options) || is_string($options)){ /*如果传递过来的数据是字符串,不是数组*/
    $where[$this->getPk()] =  $options;
    $options        =  array();
    $options['where']    =  $where; /*提取出查询条件,并赋值*/
  }
  // 根据主键查找记录
  $pk = $this->getPk();
  if (is_array($options) && (count($options) > 0) && is_array($pk)) {
    /*构造复合主键查询条件,此处省略*/
  }
  $options['limit']  =  1;                 // 总是查找一条记录
  $options      =  $this->_parseOptions($options);   // 分析表达式
  if(isset($options['cache'])){
    /*缓存查询,此处省略*/
  }
  $resultSet = $this->db->select($options);
  if(false === $resultSet){  return false;}
  if(empty($resultSet)) {  return null; }      // 查询结果为空    
  if(is_string($resultSet)){  return $resultSet;}  //查询结果为字符串
  // 读取数据后的处理,此处省略简写
  $this->data = $this->_read_data($resultSet[0]);
  return $this->data;
}

Copy after login

$Pk为主键,$options为表达式参数,本函数的作用就是完善成员变量——options数组,然后调用db层的select函数查询数据,处理后返回数据。

跟进_parseOptions函数:

protected function _parseOptions($options=array()) { //分析表达式
  if(is_array($options)){
    $options = array_merge($this->options,$options);
  }
  /*获取表名,此处省略*/
  /*添加数据表别名,此处省略*/
  $options['model']    =  $this->name;// 记录操作的模型名称
  /*对数组查询条件进行字段类型检查,如果在合理范围内,就进行过滤处理;否则抛出异常或者删除掉对应字段*/
  if(isset($options['where']) && is_array($options['where']) && !empty($fields) && !isset($options['join'])){
    foreach ($options['where'] as $key=>$val){
      $key = trim($key);
      if(in_array($key,$fields,true)){  //如果$key在数据库字段内,过滤以及强制类型转换之
        if(is_scalar($val)) { 
        /*is_scalar 检测是否为标量。标量是指integer、float、string、boolean的变量,array则不是标量。*/     
          $this->_parseType($options['where'],$key);
        }
      }elseif(!is_numeric($key) && '_' != substr($key,0,1) && false === strpos($key,'.') && false === strpos($key,'(') && false === strpos($key,'|') && false === strpos($key,'&')){
        // 如果$key不是数字且第一个字符不是_,不存在.(|&等特殊字符
        if(!empty($this->options['strict'])){  //如果是strict模式,抛出异常
          E(L('_ERROR_QUERY_EXPRESS_').':['.$key.'=>'.$val.']');
        }  
        unset($options['where'][$key]); //unset掉对应的值
      }
    }
  } 
  $this->options =  array();      // 查询过后清空sql表达式组装 避免影响下次查询
  $this->_options_filter($options);    // 表达式过滤
  return $options;
}

Copy after login

本函数的结构大概是,先获取了表名,模型名,再对数据进行处理:如果该条数据不在数据库字段内,则做出异常处理或者删除掉该条数据。否则,进行_parseType处理。parseType此处不再跟进,功能为:数据类型检测,强制类型转换包括int,float,bool型的三种数据。

函数运行到此处,就该把处理好的数据传到db层的select函数里了。此时的查询条件$options中的int,float,bool类型的数据都已经进行了强制类型转换,where()函数中的字符串(非数组格式的查询)也进行了addslashes等处理。

继续追踪到select函数,就到了driver对象中了,还是先列举几个有用的成员变量:

// 数据库表达式
protected $exp = array('eq'=>'=','neq'=>'<>','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE','in'=>'IN','notin'=>'NOT IN','not in'=>'NOT IN','between'=>'BETWEEN','not between'=>'NOT BETWEEN','notbetween'=>'NOT BETWEEN');
// 查询表达式
protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%%LOCK%%COMMENT%';
// 当前SQL指令
protected $queryStr  = '';
// 参数绑定
protected $bind     =  array();
select函数:
public function select($options=array()) {
  $this->model =  $options['model'];
  $this->parseBind(!empty($options['bind'])&#63;$options['bind']:array());
  $sql  = $this->buildSelectSql($options);
  $result  = $this->query($sql,!empty($options['fetch_sql']) &#63; true : false);
  return $result;
}

Copy after login

版本3.2.3经过改进之后,select精简了不少。parseBind函数是绑定参数,用于pdo查询,此处不表。

buildSelectSql()函数及其后续调用如下:

public function buildSelectSql($options=array()) {
  if(isset($options['page'])) {
    /*页码计算及处理,此处省略*/
  }
  $sql =  $this->parseSql($this->selectSql,$options);
  return $sql;
}
/* 替换SQL语句中表达式*/
public function parseSql($sql,$options=array()){
  $sql  = str_replace(
    array('%TABLE%','%DISTINCT%','%FIELD%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%','%UNION%','%LOCK%','%COMMENT%','%FORCE%'),
    array(
      $this->parseTable($options['table']),
      $this->parseDistinct(isset($options['distinct'])&#63;$options['distinct']:false),
      $this->parseField(!empty($options['field'])&#63;$options['field']:'*'),
      $this->parseJoin(!empty($options['join'])&#63;$options['join']:''),
      $this->parseWhere(!empty($options['where'])&#63;$options['where']:''),
      $this->parseGroup(!empty($options['group'])&#63;$options['group']:''),
      $this->parseHaving(!empty($options['having'])&#63;$options['having']:''),
      $this->parseOrder(!empty($options['order'])&#63;$options['order']:''),
      $this->parseLimit(!empty($options['limit'])&#63;$options['limit']:''),
      $this->parseUnion(!empty($options['union'])&#63;$options['union']:''),
      $this->parseLock(isset($options['lock'])&#63;$options['lock']:false),
      $this->parseComment(!empty($options['comment'])&#63;$options['comment']:''),
      $this->parseForce(!empty($options['force'])&#63;$options['force']:'')
    ),$sql);
  return $sql;
}

Copy after login

可以看到,在parseSql中用正则表达式拼接了sql语句,但并没有直接的去处理各种插叙你的数据格式,而是在解析变量的过程中调用了多个函数,此处拿parseWhere举例子。

protected function parseWhere($where) {
  $whereStr = '';
  if(is_string($where)) {   // 直接使用字符串条件
    $whereStr = $where;
  }
  else{            // 使用数组表达式
    /*设定逻辑规则,如or and xor等,默认为and,此处省略*/
    $operate=' AND ';
    /*解析特殊格式的表达式并且格式化输出*/
    foreach ($where as $key=>$val){
      if(0===strpos($key,'_')) {  // 解析特殊条件表达式
        $whereStr  .= $this->parseThinkWhere($key,$val);
      }
      else{            // 查询字段的安全过滤
        $multi = is_array($val) && isset($val['_multi']); //判断是否有复合查询
        $key  = trim($key);
        /*处理字段中包含的| &逻辑*/
        if(strpos($key,'|')) { // 支持 name|title|nickname 方式定义查询字段
          /*将|换成or,并格式化输出,此处省略*/
        }
        elseif(strpos($key,'&')){
          /*将&换成and,并格式化输出,此处省略*/
        }
        else{
          $whereStr .= $this->parseWhereItem($this->parseKey($key),$val);
        }
      }
      $whereStr .= $operate;
    }
    $whereStr = substr($whereStr,0,-strlen($operate));
  }
  return empty($whereStr)&#63;'':' WHERE '.$whereStr;
}
// where子单元分析
protected function parseWhereItem($key,$val) {
  $whereStr = '';
  if(is_array($val)){
    if(is_string($val[0])){
      $exp  =  strtolower($val[0]);
      //如果是$map['id']=array('eq',100)一类的结构,那么解析成数据库可执行格式
      if(preg_match('/^(eq|neq|gt|egt|lt|elt)$/',$exp)){
        $whereStr .= $key.' '.$this->exp[$exp].' '.$this->parseValue($val[1]);
      }
      //如果是模糊查找格式
      elseif(preg_match('/^(notlike|like)$/',$exp)){// 模糊查找,$map['name']=array('like','thinkphp%');
        if(is_array($val[1])) { //解析格式如下:$map['b'] =array('notlike',array('%thinkphp%','%tp'),'AND');
          $likeLogic =  isset($val[2])&#63;strtoupper($val[2]):'OR';  //如果没有设定逻辑结构,则默认为OR
          if(in_array($likeLogic,array('AND','OR','XOR'))){
            /* 根据逻辑结构,组合语句,此处省略*/
            $whereStr .= '('.implode(' '.$likeLogic.' ',$like).')';             
          }
        }
        else{
          $whereStr .= $key.' '.$this->exp[$exp].' '.$this->parseValue($val[1]);
        }
      }elseif('bind' == $exp ){ // 使用表达式,pdo数据绑定
        $whereStr .= $key.' = :'.$val[1];
      }elseif('exp' == $exp ){ // 使用表达式 $map['id'] = array('exp',' IN (1,3,8) ');
        $whereStr .= $key.' '.$val[1];
      }elseif(preg_match('/^(notin|not in|in)$/',$exp)){ //IN运算 $map['id'] = array('not in','1,5,8');
        if(isset($val[2]) && 'exp'==$val[2]){
          $whereStr .= $key.' '.$this->exp[$exp].' '.$val[1];
        }else{
          if(is_string($val[1])) {
             $val[1] = explode(',',$val[1]);
          }
          $zone   =  implode(',',$this->parseValue($val[1]));
          $whereStr .= $key.' '.$this->exp[$exp].' ('.$zone.')';
        }
      }elseif(preg_match('/^(notbetween|not between|between)$/',$exp)){ //BETWEEN运算
        $data = is_string($val[1])&#63; explode(',',$val[1]):$val[1];
        $whereStr .= $key.' '.$this->exp[$exp].' '.$this->parseValue($data[0]).' AND '.$this->parseValue($data[1]);
      }else{ //否则抛出异常
        E(L('_EXPRESS_ERROR_').':'.$val[0]);
      }
    }
    else{  //解析如:$map['status&score&title'] =array('1',array('gt','0'),'thinkphp','_multi'=>true);
      $count = count($val);
      $rule = isset($val[$count-1]) &#63; (is_array($val[$count-1]) &#63; strtoupper($val[$count-1][0]) : strtoupper($val[$count-1]) ) : '' ; 
      if(in_array($rule,array('AND','OR','XOR'))){
        $count = $count -1;
      }else{
        $rule  = 'AND';
      }
      for($i=0;$i<$count;$i++){
        $data = is_array($val[$i])&#63;$val[$i][1]:$val[$i];
        if('exp'==strtolower($val[$i][0])) {
          $whereStr .= $key.' '.$data.' '.$rule.' ';
        }else{
          $whereStr .= $this->parseWhereItem($key,$val[$i]).' '.$rule.' ';
        }
      }
      $whereStr = '( '.substr($whereStr,0,-4).' )';
    }
  }
  else {
    //对字符串类型字段采用模糊匹配
    $likeFields  =  $this->config['db_like_fields'];
    if($likeFields && preg_match('/^('.$likeFields.')$/i',$key)) {
      $whereStr .= $key.' LIKE '.$this->parseValue('%'.$val.'%');
    }else {
      $whereStr .= $key.' = '.$this->parseValue($val);
    }
  }
  return $whereStr;
}
protected function parseThinkWhere($key,$val) {   //解析特殊格式的条件
  $whereStr  = '';
  switch($key) {
    case '_string':$whereStr = $val;break;                 // 字符串模式查询条件
    case '_complex':$whereStr = substr($this->parseWhere($val),6);break;  // 复合查询条件
    case '_query':// 字符串模式查询条件
      /*处理逻辑结构,并且格式化输出字符串,此处省略*/
  }
  return '( '.$whereStr.' )';
}

Copy after login

上面的两个函数很长,我们再精简一些来看:parseWhere首先判断查询数据是不是字符串,如果是字符串,直接返回字符串,否则,遍历查询条件的数组,挨个解析。

由于TP支持_string,_complex之类的特殊查询,调用了parseThinkWhere来处理,对于普通查询,就调用了parseWhereItem。

在各自的处理过程中,都调用了parseValue,追踪一下,其实是用了addslashes来过滤,虽然addslashes在非utf-8编码的页面中会造成宽字节注入,但是如果页面和数据库均正确编码的话,还是没什么问题的。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of how to turn off Windows 11 Security Center Detailed explanation of how to turn off Windows 11 Security Center Mar 27, 2024 pm 03:27 PM

In the Windows 11 operating system, the Security Center is an important function that helps users monitor the system security status, defend against malware, and protect personal privacy. However, sometimes users may need to temporarily turn off Security Center, such as when installing certain software or performing system tuning. This article will introduce in detail how to turn off the Windows 11 Security Center to help you operate the system correctly and safely. 1. How to turn off Windows 11 Security Center In Windows 11, turning off the Security Center does not

Detailed explanation of how to turn off real-time protection in Windows Security Center Detailed explanation of how to turn off real-time protection in Windows Security Center Mar 27, 2024 pm 02:30 PM

As one of the operating systems with the largest number of users in the world, Windows operating system has always been favored by users. However, when using Windows systems, users may encounter many security risks, such as virus attacks, malware and other threats. In order to strengthen system security, Windows systems have many built-in security protection mechanisms, one of which is the real-time protection function of Windows Security Center. Today, we will introduce in detail how to turn off real-time protection in Windows Security Center. First, let's

AI's new world challenges: What happened to security and privacy? AI's new world challenges: What happened to security and privacy? Mar 31, 2024 pm 06:46 PM

The rapid development of generative AI has created unprecedented challenges in privacy and security, triggering urgent calls for regulatory intervention. Last week, I had the opportunity to discuss the security-related impacts of AI with some members of Congress and their staff in Washington, D.C. Today's generative AI reminds me of the Internet in the late 1980s, with basic research, latent potential, and academic uses, but it's not yet ready for the public. This time, unchecked vendor ambition, fueled by minor league venture capital and inspired by Twitter echo chambers, is rapidly advancing AI’s “brave new world.” The "public" base model is flawed and unsuitable for consumer and commercial use; privacy abstractions, if present, leak like a sieve; security structures are important because of the attack surface

How should the Java framework security architecture design be balanced with business needs? How should the Java framework security architecture design be balanced with business needs? Jun 04, 2024 pm 02:53 PM

Java framework design enables security by balancing security needs with business needs: identifying key business needs and prioritizing relevant security requirements. Develop flexible security strategies, respond to threats in layers, and make regular adjustments. Consider architectural flexibility, support business evolution, and abstract security functions. Prioritize efficiency and availability, optimize security measures, and improve visibility.

PHP calculates MD5 hash value of string PHP calculates MD5 hash value of string Mar 21, 2024 am 10:51 AM

This article will explain in detail how PHP calculates the MD5 hash value of a string. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Calculating the MD5 hash value of a string in PHP Introduction MD5 (Message Digest 5) is a popular cryptographic hash function used to generate fixed-length hash values, often used to protect data integrity, verify file integrity and Create a digital signature. This article will guide PHP developers on how to use built-in functions to calculate the MD5 hash value of a string. md5() function PHP provides the md5() function to calculate the MD5 hash value of a string. This function receives a string parameter and returns a 32-character hexadecimal hash value.

How to implement PHP security best practices How to implement PHP security best practices May 05, 2024 am 10:51 AM

How to Implement PHP Security Best Practices PHP is one of the most popular backend web programming languages ​​used for creating dynamic and interactive websites. However, PHP code can be vulnerable to various security vulnerabilities. Implementing security best practices is critical to protecting your web applications from these threats. Input validation Input validation is a critical first step in validating user input and preventing malicious input such as SQL injection. PHP provides a variety of input validation functions, such as filter_var() and preg_match(). Example: $username=filter_var($_POST['username'],FILTER_SANIT

Security configuration and hardening of Struts 2 framework Security configuration and hardening of Struts 2 framework May 31, 2024 pm 10:53 PM

To protect your Struts2 application, you can use the following security configurations: Disable unused features Enable content type checking Validate input Enable security tokens Prevent CSRF attacks Use RBAC to restrict role-based access

Implementing Machine Learning Algorithms in C++: Security Considerations and Best Practices Implementing Machine Learning Algorithms in C++: Security Considerations and Best Practices Jun 01, 2024 am 09:26 AM

When implementing machine learning algorithms in C++, security considerations are critical, including data privacy, model tampering, and input validation. Best practices include adopting secure libraries, minimizing permissions, using sandboxes, and continuous monitoring. The practical case demonstrates the use of the Botan library to encrypt and decrypt the CNN model to ensure safe training and prediction.

See all articles