1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
antivirus.php
См. документацию.
1<?
3
10
11/*
12Here is testing code:
13$s=<<<EOT
14
15Place tested html here
16
17EOT;
18CModule::IncludeModule('security');
19$Antivirus = new CSecurityAntiVirus("pre");
20$Antivirus->replace=1;
21$Antivirus->Analyze($s);
22echo htmlspecialcharsbx($s),'<hr><pre>',htmlspecialcharsbx(print_r($Antivirus,1));
23*/
24
26{
27 var $place = "";
28 var $stylewithiframe = false;
29
30 // this properties may be changed after object creation
31 var $maxrating = 20; //рейтинг принятия решений
32 var $useglobalrules = 1; //использовать глобальные правила
33
34 var $replace = 1;//
35 var $replacement = "<!-- deleted by bitrix Antivirus -->"; //на что заменяем, если заменяем..
36
37 //результаты
38 var $resultrules; //массив сработавших правил
40
41 //вспомогательные свойства
42 var $data = ''; //полный код блока, включая ограничивающие теги
43 var $type = ''; //тип блока
44 var $body = ''; // тело блока.
45 var $bodylines = false; // массив строк из body
46 var $bodyWOquotes = '';
47
48 var $atributes = ''; // дополнительные атрибуты (вместе с src)
49
50 var $cnt = 0; //счетчик обработанных блоков
51
52 var $prev = '';
53 var $next = '';
54
55 private $quotes = array();
56
57 function __construct($place = "body")
58 {
59 $this->place = $place;
60 global $BX_SECURITY_AV_ACTION;
61 if($BX_SECURITY_AV_ACTION === "notify_only")
62 $this->replace = false;
63 }
64
65 public static function IsActive()
66 {
67 $bActive = false;
68 foreach(GetModuleEvents("main", "OnPageStart", true) as $event)
69 {
70 if(
71 isset($event["TO_MODULE_ID"]) && $event["TO_MODULE_ID"] === "security"
72 && isset($event["TO_CLASS"]) && $event["TO_CLASS"] === "CSecurityAntiVirus"
73 )
74 {
75 $bActive = true;
76 break;
77 }
78 }
79 return $bActive;
80 }
81
82 public static function SetActive($bActive = false)
83 {
84 if($bActive)
85 {
87 {
88 //Just pre compression
89 RegisterModuleDependences("main", "OnPageStart", "security", "CSecurityAntiVirus", "OnPageStart", -1);
90 RegisterModuleDependences("main", "OnEndBufferContent", "security", "CSecurityAntiVirus", "OnEndBufferContent", 10000);
91 //Right after compression
92 RegisterModuleDependences("main", "OnAfterEpilog", "security", "CSecurityAntiVirus", "OnAfterEpilog", 10001);
93 }
94 }
95 else
96 {
98 {
99 UnRegisterModuleDependences("main", "OnPageStart", "security", "CSecurityAntiVirus", "OnPageStart");
100 UnRegisterModuleDependences("main", "OnEndBufferContent", "security", "CSecurityAntiVirus", "OnEndBufferContent");
101 UnRegisterModuleDependences("main", "OnAfterEpilog", "security", "CSecurityAntiVirus", "OnAfterEpilog");
102 }
103 }
104 }
105
106 public static function GetAuditTypes()
107 {
108 return array(
109 "SECURITY_VIRUS" => "[SECURITY_VIRUS] ".GetMessage("SECURITY_VIRUS"),
110 );
111 }
112
113 public static function OnPageStart()
114 {
115 if (CSecuritySystemInformation::isCliMode())
116 return;
117
118 if (self::isSafetyRequest()) //Check only GET and POST request
119 return;
120
121 global $APPLICATION, $BX_SECURITY_AV_TIMEOUT, $BX_SECURITY_AV_ACTION;
122 $BX_SECURITY_AV_TIMEOUT = COption::GetOptionInt("security", "antivirus_timeout");
123 $BX_SECURITY_AV_ACTION = COption::GetOptionInt("security", "antivirus_action");
124
125 //user white list
126 global $BX_SECURITY_AV_WHITE_LIST, $CACHE_MANAGER;
127 if($CACHE_MANAGER->Read(36000, "b_sec_white_list"))
128 {
129 $BX_SECURITY_AV_WHITE_LIST = $CACHE_MANAGER->Get("b_sec_white_list");
130 }
131 else
132 {
133 $BX_SECURITY_AV_WHITE_LIST = array();
135 while($ar = $res->Fetch())
136 $BX_SECURITY_AV_WHITE_LIST[] = $ar["WHITE_SUBSTR"];
137 $CACHE_MANAGER->Set("b_sec_white_list", $BX_SECURITY_AV_WHITE_LIST);
138 }
139
140 //Init DB in order to be able to register the event in the shutdown function
141
142 //Check if we started output buffering in auto_prepend_file
143 //so we'll have chances to detect virus before prolog
144 if(defined("BX_SECURITY_AV_STARTED"))
145 {
146 $content = ob_get_contents();
147 ob_end_clean();
148 if($content <> '')
149 {
150 $Antivirus = new CSecurityAntiVirus("pre");
151 $Antivirus->Analyze($content);
152 echo $content;
153 }
154 }
155
156 //Initiate monitoring of output that can be after working antivirus.
157 register_shutdown_function(array('CSecurityAntiVirus', 'PHPShutdown'));
158
159 //Check notification from previous hit
160 $fname = $_SERVER["DOCUMENT_ROOT"].BX_PERSONAL_ROOT."/managed_cache/b_sec_virus";
161 if(file_exists($fname))
162 {
163 $rsInfo = VirusTable::getList(["filter" => ["=SENT" => "N"]]);
164
165 if($arInfo = $rsInfo->Fetch())
166 {
167 $connection = Application::getConnection();
168 if($connection->lock("b_sec_virus"))
169 {
170 $SITE_ID = false;
171 do {
172 $SITE_ID = $arInfo["SITE_ID"];
173 if($arInfo["INFO"] <> '')
174 {
175 $arEvent = unserialize(base64_decode($arInfo["INFO"]), ['allowed_classes' => false]);
176 if(is_array($arEvent))
177 {
178 $arEvent["TIMESTAMP_X"] = $arInfo["TIMESTAMP_X"];
179 $arEvent["USER_ID"] = null;
180 $arEvent["GUEST_ID"] = null;
181 EventLogTable::add($arEvent);
182 }
183 }
184 VirusTable::update($arInfo["ID"], ["SENT" => "Y"]);
185
186 } while ($arInfo = $rsInfo->Fetch());
187
188 $date = new \Bitrix\Main\Type\DateTime();
189 $date->add("-{$BX_SECURITY_AV_TIMEOUT} minutes");
190
191 VirusTable::deleteList(["<=TIMESTAMP_X" => $date]);
192
193 CEvent::Send("VIRUS_DETECTED", $SITE_ID? $SITE_ID: SITE_ID, array("EMAIL" => COption::GetOptionString("main", "email_from", "")));
194
195 $connection->unlock("b_sec_virus");
196
197 @unlink($fname);
198 }
199 }
200 }
201 }
202
203 public static function OnEndBufferContent(&$content)
204 {
205 if (self::isSafetyRequest()) //Check only GET and POST request
206 return;
207
208 //Обработка основного вывода
209 $Antivirus = new CSecurityAntiVirus("body");
210 $Antivirus->Analyze($content);
211 }
212
213 public static function OnAfterEpilog()
214 {
215 if (self::isSafetyRequest()) //Check only GET and POST request
216 return;
217
218 //start monitoring of output that can be after working antivirus.
219 ob_start();
220 define("BX_SECURITY_AV_AFTER_EPILOG", true);
221 }
222
223 public static function PHPShutdown()
224 {
225 if(defined("BX_SECURITY_AV_AFTER_EPILOG"))
226 {
227 $content = ob_get_contents();
228 if($content <> '')
229 {
230 ob_end_clean();
231
232 if(mb_substr($content, 0, 6) == "<html>" && preg_match("#</html>\\s*\$#is", $content))
233 {
234 $Antivirus = new CSecurityAntiVirus("body");
235 }
236 else
237 {
238 $Antivirus = new CSecurityAntiVirus("post");
239 }
240
241 $Antivirus->Analyze($content);
242 echo $content;
243 }
244 }
245 }
246
247 public static function GetWhiteList()
248 {
249 $res = WhiteListTable::getList(["order" => "ID"]);
250 return $res;
251 }
252
253 public static function UpdateWhiteList($arWhiteList)
254 {
255 global $CACHE_MANAGER;
256
257 WhiteListTable::deleteList([]);
258 $i = 1;
259 foreach($arWhiteList as $white_str)
260 {
261 $white_str = trim($white_str);
262 if($white_str){
263 WhiteListTable::add(["ID" => $i++, "WHITE_SUBSTR" => $white_str]);
264 }
265 }
266 $CACHE_MANAGER->Clean("b_sec_white_list");
267 }
268
269 // function returns 1, if current block is in white list and needs not processing.
270 function isInWhiteList()
271 {
272 if(mb_strpos($this->atributes, 'src="/bitrix/') !== false)
273 return 1;
274
275 if(preg_match('#src="http[s]?://(api-maps\\.yandex|maps\\.google|apis\\.google|stg\\.odnoklassniki)\\.[a-z]{2,3}/#', $this->atributes))
276 return 2;
277
278 if(mb_strpos($this->body, 'BX_DEBUG_INFO') !== false)
279 return 3;
280
281 if(preg_match('#(google-analytics\\.com/ga\\.js|openstat\\.net/cnt\\.js|autocontext\\.begun\\.ru/autocontext\\.js|counter\\.yadro\\.ru/hit)#', $this->body))
282 return 4;
283
284 if(preg_match('/var\s+(cmt|jsMnu_toolbar_|hint|desktopPage|arStructure|current_selected|arCrmSelected|arKernelCSS|lastUsers|arStore)/', $this->body))
285 return 5;
286
287 if(preg_match('/(arFDDirs|arFDFiles|arPropFieldsList|PROP)\[/', $this->body))
288 return 6;
289
290 if(preg_match('/(addPathRow|MoveProgress|Import|DoNext|JCMenu|AttachFile|CloseDialog|_processData|showComment|ShowWarnings|SWFObject|deliveryCalcProceed|structReload|addForumImagesShow|rsasec_form_bind|BX_YMapAddPolyline|BX_YMapAddPlacemark|CloseWaitWindow|DoChangeExternalSaleId|AjaxSend|readFileChunk|EndDump|createMenu|addProperty)\‍(/', $this->body))
291 return 7;
292
293 if(mb_strpos($this->body, 'window.operation_success = true;') !== false)
294 return 8;
295
296 if(preg_match('/(jsAjaxUtil|jsUtils|jsPopup|elOnline|jsAdminChain|jsEvent|jsAjaxHistory|bxSession|BXHotKeys|oSearchDialog)\./', $this->body))
297 return 9;
298
299 if(preg_match('/new\s+(PopupMenu|JCAdminFilter|JCSmartFilter|JCAdminMenu|BXHint|ViewTabControl|BXHTMLEditor|JCTitleSearch|JCWDTitleSearch|BxInterfaceForm|Date|JCEmployeeSelectControl|JCCatalogBigdataProducts|JCCatalogSection|JCCatalogElement|JCCatalogTopSlider|JCCatalogTopSection|JCCatalogSectionRec|JCCatalogSectionViewed|JCCatalogCompareList|JCCatalogItem|JCSaleGiftProduct|B24\.SearchTitle)/', $this->body))
300 return 10;
301
302 if(mb_strpos($this->body, 'document\.write(\'<link href="/bitrix/templates/') !== false)
303 return 11;
304
305 if(preg_match('/(BX|document\.getElementById)\‍(\'session_time_result\'\‍).innerHTML/', $this->body))
306 return 12;
307
308 if(preg_match('/(structRegisterDD|bx_adv_includeFlash|BXSnippetsTaskbar|BXPropertiesTaskbar|oBXDialogControls|editComment|taskManagerForm|SLtestParamsSetValue|SLshowError|arUsers|arImages|itm_name|form_tbl_dump|bx_template_params|GetAdminList|WDAddUser2Filter|pBXEventDispatcher|orderCallback|disableAddToCompare)/', $this->body))
309 return 13;
310
311 if(preg_match('/(iblock_element_edit|iblock_element_search|posting_admin|fileman_file_view|sale_print|get_message|user_edit)\.php/', $this->body))
312 return 14;
313
314 if(preg_match('/BX\.(WindowManager|reload|message|browser|ready|tooltip|admin|hint_replace|CDebugDialog|adjust|ajax|bind|loadScript|addCustomEvent|timeman|Finder|Access|loadCSS|CrmProductEditor|COpener|file_input|setKernelJS|TreeConditions|PULL|runSitemap|setCSSList|setJSList)/', $this->body))
315 return 15;
316
317 if(preg_match('/window\.parent\.(InitActionProps|Tree|buildNoMenu)/', $this->body))
318 return 16;
319
320 if(preg_match('/document\.forms\.meeting_edit/', $this->body))
321 return 17;
322
323 if(preg_match('/top\.(jsBXAC|bx_req_res|BX|bxiu_simple_res|bxiu_wm_img_res|SetForumAjaxPostTmp|SetVoteAjaxPostTmp|SetReviewsAjaxPostTmp|bxBlogImageError|replaceKeys|FILE_UPLOADER_CALLBACK|setAuthResult)/', $this->body))
324 return 18;
325
326 if(preg_match('/var\s+dates\s+=\s+(new\s+Array|\[\];)/', $this->body))
327 return 19;
328
329 if(preg_match('/(updateURL|bx_incl_area|basketTotalWeight|iNoOnSelectionChange|arGDGroups|phpVars)\s+=/', $this->body))
330 return 20;
331
332 if(preg_match('/^\s*__status\s+=\s+true;\s*$/', $this->body))
333 return 21;
334
335 if(preg_match('/window\.(bx_load_items_res|oPhotoEditIconDialogError|bxph_error|bxph_action|bxphres|bx_req_res|MLSearchResult|arUsedCSS|arComp2Templates|arComp2TemplateProps|arComp2TemplateLists|arComp2Elements|arSnippets|JCCalendarViewMonth|JCCalendarViewWeek|JCCalendarViewDay|_bx_result|_bx_new_event|_bx_plann_mr|_bx_ar_events|_bx_calendar|_bx_plann_events|_bx_existent_event|_ml_items_colls|MLCollections|fmsBtimeout|fmsResult|arSnGroups|BXFM_result|BXFM_NoCopyToDir|oPhotoEditAlbumDialogError|structOptions|__bxst_result|_bx_def_calendar|GLOBAL_arMapObjects|autosave_|oPhotoEditDialogError|bxPlayerOnload|LHE_MESS|MLItems|fmPackTimeout|fmUnpackSuccess|BXFM_archiveExists|BXHtmlEditor)/', $this->body))
336 return 22;
337
338 if(preg_match('/\s*(self|window)\.close\s*\‍(\s*\‍)\s*;*\s*$/', $this->body))
339 return 24;
340
341 if($this->body === 'window.location.reload();')
342 return 25;
343
344 if($this->body === 'window.location = window.location.href;')
345 return 26;
346
347 if(preg_match('/^parent\.window\.(End\‍(\d+\‍)|EndTasks\‍(\‍)|buildNoMenu\‍(\‍));\s*$/', $this->body))
348 return 27;
349
350 if(preg_match('/parent\.window\.|Start\‍(\s*\d+,\s*\d+\s*\‍);\s*$/', $this->body))
351 return 28;
352
353 if(preg_match('/^top\.location\.href\s*=\s*([\'"])[^\'"]*\1;{0,1}$/', $this->body))
354 return 29;
355
356 if(preg_match('/\.setTimeout\‍(\'CheckNew\‍(\‍)\'/', $this->body))
357 return 30;
358
359 if(preg_match('/function\s+twitter_click_\d+\‍(longUrl\‍)/', $this->body))
360 return 31;
361
362 if(preg_match('/(window\.)*parent\.document\.getElementById\‍(["\'](COUNTERS_UPDATED|div_PROPERTY_DEFAULT_VALUE)["\']\‍)\.innerHTML/',$this->body))
363 return 32;
364
365 if(preg_match('/(TasksUsers|IntranetUsers).arEmployees/',$this->body))
366 return 35;
367
368 if(preg_match('/window\.location\s*=\s*[\'"]\/bitrix\/admin\/iblock_bizproc_workflow_edit.php/', $this->body))
369 return 36;
370
371 if(preg_match('/window\.parent\.location\.href\s*=\s*[\'"]\/bitrix\/admin\/sale_order_new.php/', $this->body))
372 return 43;
373
374 if(preg_match('/^window\.open\‍(/', $this->body))
375 return 44;
376
377 if(preg_match('/^\s*window\.__bxResult\[\'\d+\'\]\s*=\s*\{/', $this->body))
378 return 46;
379
380 if(mb_strpos($this->body, 'showFLVPlayer') !== false)
381 return 37;
382
383 if(preg_match('/var\s+formSettingsDialogCRM_(LEAD|DEAL|COMPANY|CONTACT)_SHOW/', $this->body))
384 return 38;
385
386 if(preg_match('/parent\.(FILE_UPLOADER_CALLBACK)/', $this->body))
387 return 39;
388
389 if(preg_match('/bxForm_CRM/', $this->body))
390 return 40;
391
392 if(preg_match('/\$\‍(([\'"])[^\'"]*[\'"]\‍)/', $this->body))
393 return 41;
394
395 if(preg_match('/document\.documentElement\.className/i', $this->body))
396 return 42;
397
398 //site checker
399 if(preg_match('/var\s*fix_mode\s*=/i', $this->body))
400 return 43;
401
402 //Voximplant && powerBi && gtm
403 if($this->type == 'iframe' && preg_match('#\s*src=[\'"]https://(verify\.voximplant\.com|lookerstudio\.google\.com|datastudio\.google\.com|app\.powerbi\.com|www\.googletagmanager\.com)/#i', $this->atributes))
404 return 45;
405
406 if(preg_match('#function\s+bizvalChange#', $this->body))
407 return 46;
408
409 if($this->type === "script")
410 {
411 if(preg_match('#type="application/json"#is', $this->atributes))
412 return 44;
413
414 if(preg_match('#type="application/ld\+json"#is', $this->atributes))
415 return 44;
416
417 if(preg_match('#type="text/x-template"#is', $this->atributes))
418 return 44;
419
420 $filter = new CSecurityXSSDetect(array("action" => "none", "log" => "N"));
421 $this->bodyWOquotes = trim($filter->removeQuotedStrings($this->body, false), " \t\n\r");
422 $this->bodyWOquotes = preg_replace("/\\s*(window\\.top|top|window|window\\.document|document)\\.(strWarning|location\\.href|location|action_warning|__bx_res_sn_filename|title|title[\\d]+\\s*=\\s*title[\\d]+|text[\\d]+\\s*=\\s*text[\\d]+)\\s*=\\s*(|\\s*\\+\\s*)+;{0,1}\\s*/s", "", $this->bodyWOquotes, -1, $count);
423 $this->bodyWOquotes = preg_replace("/\\s*(alert|SelFile)\\s*\\((|[0-9]+|\\s*\\+\\s*)+\\)\\s*;{0,1}\\s*/", "", $this->bodyWOquotes);
424 $this->bodyWOquotes = trim($this->bodyWOquotes, "\n\r\t ");
425 $this->bodyWOquotes = preg_replace("/^\\/\\/[^\n]*\$/", "", $this->bodyWOquotes);
426
427 if($this->bodyWOquotes === "")
428 return 33;
429 }
430
431 //user defined white list
432 global $BX_SECURITY_AV_WHITE_LIST;
433 if(is_array($BX_SECURITY_AV_WHITE_LIST))
434 foreach($BX_SECURITY_AV_WHITE_LIST as $white_substr)
435 if(mb_strpos($this->data, $white_substr) !== false)
436 return 34;
437
438 return 0;
439 }
440
441 //заглушка. Возщвращает рейтинг опасности текущего блока из кеша, или FALSE
442 // кешируются только составляющся рейтинга, вложденная внутренними правилами.
444 {
445 // тут можно вставить кеширование. Для кеширование вычислять и сохранять кеш от $this->data
446 return false;
447 }
448
449 //заглушка. Добавляет рейтинг опасности для текущего блока в кеш.
450 function addtocache()
451 {
452 // тут можно вставить кеширование. Для кеширование вычислять и сохранять кеш от $this->data
453 return true;
454 }
455
456 //механизм для вывода сообщения об обнаруженном подозрительном текущем блоке
457 function dolog()
458 {
459 global $BX_SECURITY_AV_TIMEOUT;
460 if(defined("ANTIVIRUS_CREATE_TRACE"))
461 $this->CreateTrace();
462
463 $uniq_id = md5($this->data);
464 $arLog = VirusTable::getByPrimary($uniq_id)->fetch();
465
466 if($arLog && ($arLog["SENT"] == "Y"))
467 {
468 $date = new \Bitrix\Main\Type\DateTime();
469 $date->add("-{$BX_SECURITY_AV_TIMEOUT} minutes");
470
471 VirusTable::deleteList(["SENT" => "Y", "<TIMESTAMP_X" => $date]);
472
473 $arLog = VirusTable::getByPrimary($uniq_id)->fetch();
474 }
475
476 if(!$arLog)
477 {
478 $ss = $this->data;
479
480 if(defined("ANTIVIRUS_CREATE_TRACE"))
481 foreach($this->resultrules as $k=>$v)
482 $ss .= "\n".$k."=".$v;
483
484 if(defined("SITE_ID") && !defined("ADMIN_SECTION"))
485 {
487 }
488 else
489 {
491 "select" => ["LID"],
492 "filter" => ["=ACTIVE" => "Y"],
493 "order" => ["DEF" => "DESC", "SORT" => "ASC"]
494 ])->fetch();
495
496 $SITE_ID = $arDefSite ? $arDefSite["LID"] : null;
497 }
498
499 $s = serialize(array(
500 "SEVERITY" => "SECURITY",
501 "AUDIT_TYPE_ID" => "SECURITY_VIRUS",
502 "MODULE_ID" => "security",
503 "ITEM_ID" => "UNKNOWN",
504 "REMOTE_ADDR" => $_SERVER["REMOTE_ADDR"],
505 "USER_AGENT" => $_SERVER["HTTP_USER_AGENT"],
506 "REQUEST_URI" => $_SERVER["REQUEST_URI"],
507 "SITE_ID" => defined("SITE_ID")? SITE_ID: false,
508 "USER_ID" => false,
509 "GUEST_ID" => array_key_exists("SESS_GUEST_ID", $_SESSION) && ($_SESSION["SESS_GUEST_ID"] > 0)? $_SESSION["SESS_GUEST_ID"]: false,
510 "DESCRIPTION" => "==".base64_encode($ss),
511 ));
512
513 VirusTable::add([
514 "ID" => $uniq_id,
515 "TIMESTAMP_X" => new \Bitrix\Main\Type\DateTime(),
516 "SITE_ID" => $SITE_ID,
517 "INFO" => base64_encode($s)
518 ]);
519
520 @fclose(@fopen($_SERVER["DOCUMENT_ROOT"].BX_PERSONAL_ROOT."/managed_cache/b_sec_virus","w"));
521 }
522 }
523
524
525 // вызывается каждый раз, когда обработка блока закончена и блок признан нормальным.
526 // функция должна возвратить содержимое блока.
527 function end_okblock()
528 {
529 return $this->data;
530 }
531
532 function end_whiteblock()
533 {
534 return $this->data;
535 }
536
537 // вызывается каждый раз, когда обработка блока закончена и блок признан опасным.
538 // функция должна возвратить содержимое блока.
539 function end_blkblock()
540 {
541 if($this->replace)
542 return $this->replacement;
543 else
544 return $this->data;
545 }
546
547 function CreateTrace()
548 {
549 $cache_id = md5($this->data);
550 $fn = $_SERVER["DOCUMENT_ROOT"]."/bitrix/cache/virus.db/".$cache_id.".vir";
551 if(!file_exists($fn))
552 {
553 CheckDirPath($fn);
554 $f = fopen($fn, "wb");
555
556 fwrite($f, $this->data);
557
558 fwrite($f, "\n------------------------------\n\$_SERVER:\n");
559 foreach($_SERVER as $k=>$v)
560 fwrite($f, $k." = ".$v."\n");
561
562 fwrite($f, "\n------------------------------\n\$this->resultrules:\n");
563 foreach($this->resultrules as $k=>$v)
564 fwrite($f, $k." = ".$v."\n");
565
566 fclose($f);
567
568 @chmod($fn, BX_FILE_PERMISSIONS);
569 }
570 }
571
572 function Analyze(&$content)
573 {
574 static $arLocalCache = array();
575
576 $content_len = strlen($content) * 2;
577 Ini::adjustPcreBacktrackLimit($content_len);
578
579 $this->stylewithiframe = preg_match("/<style.*>\s*iframe/", $content);
580
581 $arData = preg_split("/(<script.*?>.*?<\\/script.*?>|<iframe.*?>.*?<\\/iframe.*?>)/is", $content, -1, PREG_SPLIT_DELIM_CAPTURE);
582
583 $cData = is_array($arData) ? count($arData) : 0;
584
585 if($cData < 2)
586 return;
587
588 $bDataChanged = false;
589 for($iData = 1; $iData < $cData; $iData += 2)
590 {
591 $this->data = $arData[$iData]; //полный код блока, включая ограничивающие теги
592
593 // < 1 2 > 3 4
594 if(!preg_match('/^<(script|iframe)(.*?)>(.*?)(<\\/\\1.*?>)$/is', $this->data, $ret))
595 continue;
596
597 if($iData>1)
598 $this->prev = $arData[$iData-2].$arData[$iData-1];
599 else
600 $this->prev = $arData[$iData-1];
601
602 if($iData < $cData-2)
603 $this->next = $arData[$iData+1].$arData[$iData+2];
604 else
605 $this->next = $arData[$iData+1];
606
607 $this->resultrules = array();
608 $this->bodylines = false;
609 $this->atributes = $ret[2];
610 if(mb_strtolower($ret[1]) == 'script')
611 {
612 $this->body = $this->returnscriptbody($this->data);
613 $this->type = 'script';
614 }
615 else
616 {
617 $this->body = '';
618 $this->type = 'iframe';
619 }
620
621 $this->whitelist_id = $this->isInWhiteList();
622 if(!$this->whitelist_id)
623 {
624 $cache_id = md5($this->data);
625 if(!isset($arLocalCache[$cache_id]))
626 $arLocalCache[$cache_id] = $this->returnblockrating();
627
628 if($arLocalCache[$cache_id] >= $this->maxrating)
629 {
630 $this->dolog();
631 $arData[$iData] = $this->end_blkblock();
632 if($this->replace)
633 $bDataChanged = true;
634 }
635 }
636
637 $this->cnt++;
638 }
639
640 if($bDataChanged)
641 $content = implode('', $arData);
642
643 }
644
645 /*
646 Возвращает рейтинг опасности блока (ифрейм или скрипт)
647 входные параметры класса должны быть заполнеы.
648 */
650 {
651 if($this->type=='iframe')
652 {
653 if(!preg_match("/src=[\'\"]?http/", $this->atributes))
654 return 0;
655 }
656
657 $r = $this->returnfromcache();
658 if($r === false)
659 {
660 $r = 0;
661 //вначале все кешируемые внутренние правила
662 if($this->type=='iframe')
663 {
664 $r += $this->ruleframevisiblity();
665 }
666 elseif($this->type=='script')
667 {
668 $r += $this->rulescriptbasics();
669 $r += $this->rulescriptvbscript();
670 $r += $this->rulescriptwhiterules();
671 $r += $this->rulescriptnamerules();
672 }
673 $r += $this->ruleallsources();
674
675 $this->addtocache($r);
676 }
677
678 // некешируемые наружные правила..
679 $r += $this->rulescriptglobals();
680 $r += $this->rulescriptblocks();
681
682 return $r;
683 }
684
685 // ПРАВИЛА
686 // надбавки и скидки действующие для каждого скрипта (возможно с некоторыми условиями)
688 {
689 return 0;
690 $r = 0;
691 if(!$this->useglobalrules)
692 {
693 return 0;
694 }
695
696 if($this->type=='script' && $this->stylewithiframe
697 )
698 {
699 $val = 4;
700 $r += $val;
701 $this->resultrules['rulescriptglobals_styleiframe'] = $val;
702 }
703
704 if($this->place == "post")
705 {
706 $val = 12;
707 $r += $val;
708 $this->resultrules['rulescriptglobals_blockafterend'] = $val;
709 }
710
711 if($this->place == "pre")
712 {
713 $val = 12;
714 $r += $val;
715 $this->resultrules['rulescriptglobals_blockprestart'] = $val;
716 }
717
718 return $r;
719 }
720
721 //правила, учитывающие окружение скрипта
723 {
724 $r = 0;
725 $strp = preg_replace('/<!\-\-.*?\-\->$/', '', $this->prev);
726 $strn = preg_replace('/^<!\-\-.*?\-\->/', '', $this->next);
727 //удалили окружающие комментарии, если имелись..
728
729 if($this->cnt == 0) //обрабатывается первое попадание...
730 {
731 if(preg_match("/^\s*$/is", $strp))
732 {
733 $val = 1;
734 $r += $val;
735 $this->resultrules['rulescriptblocks_blockinstart'] = $val;
736 }
737 }
738
739 if(preg_match("/^\s*$/is", $strn))
740 {
741 $val = 1;
742 $r += $val;
743 $this->resultrules['rulescriptblocks_endofhtml'] = $val;
744 }
745
746 if(preg_match("/<body[^>]*?>\s*$/is", $strp))
747 {
748 $val = 3;
749 $r += $val;
750 $this->resultrules['rulescriptblocks_postbody'] = $val;
751 }
752
753 if(preg_match("/^\s*<\\/body[^>]*?>/is", $strn))
754 {
755 $val = 3;
756 $r += $val;
757 $this->resultrules['rulescriptblocks_preendofbody'] = $val;
758 }
759
760 if(preg_match("/<\\/html[^>]*?>\s*$/is", $strp))
761 {
762 $val = 10;
763 $r += $val;
764 $this->resultrules['rulescriptblocks_postendofhtml'] = $val;
765 }
766
767 if($this->type == 'iframe')
768 {
769 if(preg_match("/<div[^>]+((visibility\s*:\s*hidden)|(display\s*:\s*none))[^>]*>\s*$/is", $strp))
770 {
771 $val = 11;
772 $r += $val;
773 $this->resultrules['rulescriptblocks_inhideddiv'] = $val;
774 }
775 }
776
777 if(preg_match("/^\s*<noscript/is", $strn))
778 {
779 $val = -3;
780 $r += $val;
781 $this->resultrules['rulescriptblocks_prenoscript'] = $val;
782 }
783
784 return $r;
785 }
786
787 //правила, отлавливающие "невидимость" блока
789 {
790 $r = 0;
791 if(
792 preg_match('/visibility\s*:\s*hidden/is', $this->atributes)
793 || preg_match('/display\s*:\s*none/is', $this->atributes)
794 )
795 {
796 $val = 20;
797 $r += $val;
798 $this->resultrules['ruleframevisiblity_invisible'] = $val;
799 }
800
801 if(
802 preg_match('/width=[\'\"]?[10][\'\"]?/is', $this->atributes)
803 && preg_match('/height=[\'\"]?[10][\'\"]?/is', $this->atributes)
804 )
805 {
806 $val = 20;
807 $r += $val;
808 $this->resultrules['ruleframevisiblity_sizes'] = $val;
809 }
810
811 if(preg_match('/position\s*:\s*absolute/is', $this->atributes))
812 {
813 $val = 2;
814 $r += $val;
815 $this->resultrules['ruleframevisiblity_position'] = $val;
816 }
817 return $r;
818 }
819
820 //правила, отлавливающие потенциально опасныеключевые слова в скрипте
822 {
823 $r = 0;
824 if(preg_match("/<iframe/is", $this->body))
825 {
826 $val = 11;
827 $r += $val;
828 $this->resultrules['rulescriptbasics_iframe'] = $val;
829 }
830
831 if(preg_match("/eval\‍(/is", $this->body))
832 {
833 $val = 7;
834 $r += $val;
835 $this->resultrules['rulescriptbasics_eval'] = $val;
836 }
837
838 if(preg_match("/replace\‍(/is", $this->body))
839 {
840 $val = 4;
841 $r += $val;
842 $this->resultrules['rulescriptbasics_raplace'] = $val;
843 }
844
845 if(preg_match("/unescape\‍(/is", $this->body))
846 {
847 $val = 6;
848 $r += $val;
849 $this->resultrules['rulescriptbasics_unescape'] = $val;
850 }
851
852 if(preg_match("/fromCharCode\‍(/is", $this->body))
853 {
854 $val = 5;
855 $r += $val;
856 $this->resultrules['rulescriptbasics_fromcharcode'] = $val;
857 }
858
859 if(preg_match("/parseInt\‍(/is", $this->body))
860 {
861 $val = 2;
862 $r += $val;
863 $this->resultrules['rulescriptbasics_parseInt'] = $val;
864 }
865
866 if(preg_match("/substr\‍(/is", $this->body))
867 {
868 $val = 1;
869 $r += $val;
870 $this->resultrules['rulescriptbasics_substr'] = $val;
871 }
872
873 if(preg_match("/substring\‍(/is", $this->body))
874 {
875 $val = 1;
876 $r += $val;
877 $this->resultrules['rulescriptbasics_substring'] = $val;
878 }
879
880 if(preg_match("/document\.write\‍(/is", $this->body))
881 {
882 $val = 1;
883 $r += $val;
884 $this->resultrules['rulescriptbasics_documentwrite'] = $val;
885 }
886
887 if(preg_match("/window\.status/is", $this->body))
888 {
889 $val = 3;
890 $r += $val;
891 $this->resultrules['rulescriptbasics_windowstatus'] = $val;
892 }
893
894 if(
895 preg_match('/visibility\s*:\s*hidden/is', $this->body)
896 || preg_match('/display\s*:\s*none/is', $this->body)
897 )
898 {
899 $val = 8;
900 $r += $val;
901 $this->resultrules['rulescriptbasics_invisible'] = $val;
902 }
903
904 return $r;
905 }
906
907 //правила, отлавливающие vbscript
909 {
910 $r = 0;
911 if(preg_match('/vbscript/is', $this->atributes))
912 {
913 $val = 8;
914 $r += $val;
915 $this->resultrules['rulescript_vbscript'] = $val;
916 }
917 return $r;
918 }
919
920 //правила, отлавливающие опасные места загрузки блоков
921 function ruleallsources()
922 {
923 $r = 0;
924 static $bl = array(
925 "/gumblar\.cn/is",
926 "/martuz\.cn/is",
927 "/beladen\.net/is",
928 "/38zu\.cn/is",
929 "/googleanalytlcs\.net/is",
930 "/lousecn\.cn/is",
931 "/fqwerz\.cn/is",
932 "/d99q\.cn/is",
933 "/orgsite\.info/is",
934 "/94\.247\.2\.0/is",
935 "/94\.247\.2\.195/is",
936 "/mmsreader\.com/is",
937 "/google-ana1yticz\.com/is",
938 "/my2\.mobilesect\.info/is",
939 "/thedeadpit\.com/is",
940 "/internetcountercheck\.com/is",
941 "/165\.194\.30\.123/is",
942 "/ruoo\.info/is",
943 "/gogo2me\.net/is",
944 "/live-counter\.net/is",
945 "/klinoneshoes\.info/is",
946 "/protection-livescan\.com/is",
947 "/webexperience13\.com/is",
948 "/q5x\.ru/is",
949 );
950
951 foreach($bl as $url)
952 {
953 if(preg_match($url, $this->atributes))
954 {
955 $val = 12;
956 $r += $val;
957 $this->resultrules['ruleallsources_url'] = $val;
958 return $r;//только одно правило из блока
959 }
960 }
961
962 if(preg_match('/src=.*anal.*google/is', $this->atributes))
963 {
964 $val = 12;
965 $r += $val;
966 $this->resultrules['ruleallsources_url'] = $val;
967 return $r;//только одно правило из блока
968 }
969
970 if(
971 preg_match('/src=.*google.*anal/is', $this->atributes)
972 && !preg_match('/src=.*google\-analytics\.com/is', $this->atributes)
973 )
974 {
975 $val = 12;
976 $r += $val;
977 $this->resultrules['ruleallsources_url'] = $val;
978 return $r;//только одно правило из блока
979 }
980
981 if(preg_match('/src=.*\:\/\/\d+\.\d+\.\d+\.\d+/is', $this->atributes))
982 {
983 $val = 10;
984 $r += $val;
985 $this->resultrules['ruleallsources_ip'] = $val;
986 return $r;//только одно правило из блока
987 }
988
989 if(preg_match('/src=.*\:\d+\//is', $this->atributes))
990 {
991 $val = 10;
992 $r += $val;
993 $this->resultrules['ruleallsources_port'] = $val;
994 return $r;//только одно правило из блока
995 }
996
997 if(preg_match('/src=[\'\"]?http\:\/\//is', $this->atributes))
998 {
999 $val = 9;
1000 $r += $val;
1001 $this->resultrules['ruleallsources_extern'] = $val;
1002 return $r;//только одно правило из блока
1003 }
1004
1005 return $r;
1006 }
1007
1008 //правила, учитываюбщие подозрительные длины строк и объектов
1010 {
1011 if(!$this->bodylines)
1012 $this->bodylines = explode("\n", $this->body);
1013
1014 $r = 0;
1015
1016 if(count($this->bodylines) == 1)
1017 {
1018 $ll = mb_strlen(bin2hex($this->body)) / 2;
1019 if($ll > 500)
1020 {
1021 $val = 9;
1022 $r += $val;
1023 $this->resultrules['rulescriptlenghts_sl'] = $val;
1024 return $r;//только одно правило из блока
1025 }
1026 elseif($ll > 300)
1027 {
1028 $val = 7;
1029 $r += $val;
1030 $this->resultrules['rulescriptlenghts_sl'] = $val;
1031 return $r;//только одно правило из блока
1032 }
1033 elseif($ll > 100)
1034 {
1035 $val = 5;
1036 $r += $val;
1037 $this->resultrules['rulescriptlenghts_sl'] = $val;
1038 return $r;//только одно правило из блока
1039 }
1040 }
1041 else
1042 {
1043 $ll = 0;
1044 $mxl = 0;
1045 foreach($this->bodylines as $str)
1046 {
1047 $ll = mb_strlen(bin2hex($str)) / 2;
1048 if($mxl < $ll)
1049 $mxl = $ll;
1050 }
1051
1052 if($ll > 500)
1053 {
1054 $val = 7;
1055 $r += $val;
1056 $this->resultrules['rulescriptlenghts_ml'] = $val;
1057 return $r;//только одно правило из блока
1058 }
1059 elseif($ll > 300)
1060 {
1061 $val = 5;
1062 $r += $val;
1063 $this->resultrules['rulescriptlenghts_ml'] = $val;
1064 return $r;//только одно правило из блока
1065 }
1066 elseif($ll > 100)
1067 {
1068 $val = 3;
1069 $r += $val;
1070 $this->resultrules['rulescriptlenghts_ml'] = $val;
1071 return $r;//только одно правило из блока
1072 }
1073 }
1074
1075 return $r;
1076 }
1077
1078 // Анализ частотных вхождений символов...
1080 {
1081 if(!$this->bodylines)
1082 $this->bodylines = explode("\n", $this->body);
1083
1084 $all = array("MAXCHAR"=>0, "D"=>0,"H"=>0, "NW"=>0, "B"=>0, "LEN"=>0 );
1085 $maxes = array("MAXCHAR"=>0, "D"=>0,"H"=>0, "NW"=>0, "B"=>0, "LEN"=>0 );
1086
1087 foreach($this->bodylines as $str)
1088 {
1089 $ret = $this->getstatchars($str);
1090
1091 $all['MAXCHAR'] += $ret['MAXCHAR'];
1092 $all['D'] += $ret['D'];
1093 $all['H'] += $ret['H'];
1094 $all['NW'] += $ret['NW'];
1095 $all['B'] += $ret['B'];
1096 $all['LEN'] += $ret['LEN'];
1097
1098 if($ret['LEN'] > 30)
1099 {
1100 $ret['MAXCHAR'] = $ret['MAXCHAR']*100/$ret['LEN'];
1101 $ret['D'] = $ret['D']*100/$ret['LEN'];
1102 $ret['H'] = $ret['H']*100/$ret['LEN'];
1103 $ret['NW'] = $ret['NW']*100/$ret['LEN'];
1104 $ret['B'] = $ret['B']*100/$ret['LEN'];
1105
1106 if($ret['MAXCHAR'] > $maxes['MAXCHAR'])
1107 $maxes['MAXCHAR'] = $ret['MAXCHAR'];
1108 if($ret['D'] > $maxes['D'])
1109 $maxes['D'] = $ret['D'];
1110 if($ret['H'] > $maxes['H'])
1111 $maxes['H'] = $ret['H'];
1112 if($ret['NW'] > $maxes['NW'])
1113 $maxes['NW'] = $ret['NW'];
1114 if($ret['B'] > $maxes['B'])
1115 $maxes['B'] = $ret['B'];
1116 }
1117 }
1118
1119 if($all['LEN'] > 0)
1120 {
1121 $all['MAXCHAR'] = $all['MAXCHAR']*100/$all['LEN'];
1122 $all['D'] = $all['D']*100/$all['LEN'];
1123 $all['H'] = $all['H']*100/$all['LEN'];
1124 $all['NW'] = $all['NW']*100/$all['LEN'];
1125 $all['B'] = $all['B']*100/$all['LEN'];
1126 }
1127
1128 $g3=$g4=$g5=$g6=0; // груповые баллы
1129 $g3s=$g4s=$g5s=$g6s=0; // груповые баллы
1130
1131
1132 if($all['LEN'] > 30)
1133 {
1134 //G3 какой либо символ встречается более чем в ps1% ps1=17 [3]
1135 //G3 какой либо символ встречается более чем в ps2% ps2=19 [5]
1136 //G3 какой либо символ встречается более чем в ps3% ps3=20 [7]
1137
1138 if($all['MAXCHAR'] > 17)
1139 {
1140 $val = 2;
1141 if($g3 < $val)
1142 {
1143 $g3 = $val;
1144 $g3s = "rulescriptfrequensy_maxchar";
1145 }
1146 }
1147
1148 if($all['MAXCHAR'] > 19)
1149 {
1150 $val = 4;
1151 if($g3 < $val)
1152 {
1153 $g3 = $val;
1154 $g3s = "rulescriptfrequensy_maxchar";
1155 }
1156 }
1157
1158 if($all['MAXCHAR'] > 20)
1159 {
1160 $val = 6;
1161 if($g3 < $val)
1162 {
1163 $g3 = $val;
1164 $g3s = "rulescriptfrequensy_maxchar";
1165 }
1166 }
1167
1168 //G4 процентное содержание цифр более чем pc1% pc1= 20 [6]
1169 //G4 процентное содержание цифр более чем pc2% pc2= 25 [8]
1170 //G4 процентное содержание цифр более чем pc3% pc3= 30 [9]
1171 if($all['D'] > 20)
1172 {
1173 $val = 6;
1174 if($g3 < $val)
1175 {
1176 $g4 = $val;
1177 $g4s = "rulescriptfrequensy_D";
1178 }
1179 }
1180
1181 if($all['D'] > 25)
1182 {
1183 $val = 8;
1184 if($g4 < $val)
1185 {
1186 $g4 = $val;
1187 $g4s = "rulescriptfrequensy_D";
1188 }
1189 }
1190
1191 if($all['D'] > 40)
1192 {
1193 $val = 9;
1194 if($g4 < $val)
1195 {
1196 $g4 = $val;
1197 $g4s = "rulescriptfrequensy_D";
1198 }
1199 }
1200
1201 //G4 процентное содержание HEX цифр более чем ph1% ph1=35 [5]
1202 //G4 процентное содержание HEX цифр более чем ph2% ph2=45 [7]
1203 //G4 процентное содержание HEX цифр более чем ph3% ph3=55 [9]
1204
1205 if($all['H'] > 35)
1206 {
1207 $val = 5;
1208 if($g4 < $val)
1209 {
1210 $g4 = $val;
1211 $g4s="rulescriptfrequensy_H";
1212 }
1213 }
1214
1215
1216 if($all['H'] > 40)
1217 {
1218 $val = 7;
1219 if($g3 < $val)
1220 {
1221 $g4 = $val;
1222 $g4s = "rulescriptfrequensy_H";
1223 }
1224 }
1225
1226 if($all['H'] > 55)
1227 {
1228 $val = 9;
1229 if($g4 < $val)
1230 {
1231 $g4 = $val;
1232 $g4s = "rulescriptfrequensy_H";
1233 }
1234 }
1235
1236 //G5 процентное содержание невордслооварных символов pnw1% = 23 [3]
1237 //G5 процентное содержание невордслооварных символов pnw2% = 26 [5]
1238 //G5 процентное содержание невордслооварных символов pnw3% = 30 [7]
1239
1240 if($all['NW'] > 23)
1241 {
1242 $val = 2;
1243 if($g5 < $val)
1244 {
1245 $g5 = $val;
1246 $g5s = "rulescriptfrequensy_NW";
1247 }
1248 }
1249
1250 if($all['NW'] > 26)
1251 {
1252 $val = 4;
1253 if($g5 < $val)
1254 {
1255 $g5 = $val;
1256 $g5s = "rulescriptfrequensy_NW";
1257 }
1258 }
1259
1260 if($all['NW'] > 30)
1261 {
1262 $val = 6;
1263 if($g5 < $val)
1264 {
1265 $g5 = $val;
1266 $g5s = "rulescriptfrequensy_NW";
1267 }
1268 }
1269
1270 //G6 процентное содержание символов с кодом меньше чем 20 (hex) больше чем pb1% 0.1 [7]
1271 //G6 процентное содержание символов с кодом меньше чем 20 (hex) больше чем pb2% 0.5 [8]
1272 //G6 процентное содержание символов с кодом меньше чем 20 (hex) больше чем pb3% 1.0 [9]
1273 if($all['B'] > 0.1)
1274 {
1275 $val = 7;
1276 if($g6 < $val)
1277 {
1278 $g6 = $val;
1279 $g6s = "rulescriptfrequensy_B";
1280 }
1281 }
1282
1283 if($all['B'] > 0.5)
1284 {
1285 $val = 8;
1286 if($g6 < $val)
1287 {
1288 $g6 = $val;
1289 $g6s = "rulescriptfrequensy_B";
1290 }
1291 }
1292
1293 if($all['B'] > 1)
1294 {
1295 $val = 9;
1296 if($g6 < $val)
1297 {
1298 $g6 = $val;
1299 $g6s = "rulescriptfrequensy_B";
1300 }
1301 }
1302 };// if($all['LEN']>30)
1303
1304 //G3 какой либо символ встречается в одной строке (длиной более psslss1 =30символов) более чем в pss1% 20 [3]
1305 //G3 какой либо символ встречается в одной строке (длиной более psslss2 =30символов) более чем в pss2% 24 [5]
1306 //G3 какой либо символ встречается в одной строке (длиной более psslss3 =30символов) более чем в pss3% 28 [6]
1307 if($maxes['MAXCHAR']>20)
1308 {
1309
1310 $val = 3;
1311 if($g3 < $val)
1312 {
1313 $g3 = $val;
1314 $g3s = "rulescriptfrequensystr_MAXCHAR";
1315 }
1316 }
1317
1318 if($maxes['MAXCHAR'] > 24)
1319 {
1320 $val = 5;
1321 if($g3 < $val)
1322 {
1323 $g3 = $val;
1324 $g3s = "rulescriptfrequensystr_MAXCHAR";
1325 }
1326 }
1327
1328 if($maxes['MAXCHAR'] > 28)
1329 {
1330 $val = 6;
1331 if($g3 < $val)
1332 {
1333 $g3 = $val;
1334 $g3s = "rulescriptfrequensystr_MAXCHAR";
1335 }
1336 }
1337
1338 //G4 процентное содержание цифр в одной строке (длиной более psclss1=30 символов) более чем psc1% 50 [4]
1339 //G4 процентное содержание цифр в одной строке (длиной более psclss2=30 символов) более чем psc2% 65 [5]
1340 //G4 процентное содержание цифр в одной строке (длиной более psclss3=30 символов) более чем psc3% 80 [6]
1341
1342 if($maxes['D'] > 50)
1343 {
1344 $val = 4;
1345 if($g4 < $val)
1346 {
1347 $g4 = $val;
1348 $g4s = "rulescriptfrequensystr_D";
1349 }
1350 }
1351
1352 if($maxes['D'] > 65)
1353 {
1354 $val = 5;
1355 if($g4 < $val)
1356 {
1357 $g4 = $val;
1358 $g4s = "rulescriptfrequensystr_D";
1359 }
1360 }
1361
1362 if($maxes['D'] > 80)
1363 {
1364 $val = 6;
1365 if($g4 < $val)
1366 {
1367 $g4 = $val;
1368 $g4s = "rulescriptfrequensystr_D";
1369 }
1370 }
1371
1372 //G4 процентное содержание HEX цифр в одной строке (длиной более pshlss1=30символов) более чем psh1% 30 [4]
1373 //G4 процентное содержание HEX цифр в одной строке (длиной более pshlss2=30символов) более чем psh2% 50 [6]
1374 //G4 процентное содержание HEX цифр в одной строке (длиной более pshlss3=30символов) более чем psh3% 70 [8]
1375
1376 if($maxes['H'] > 40)
1377 {
1378 $val = 3;
1379 if($g4 < $val)
1380 {
1381 $g4 = $val;
1382 $g4s = "rulescriptfrequensystr_H";
1383 }
1384 }
1385
1386 if($maxes['H'] > 55)
1387 {
1388 $val = 5;
1389 if($g4 < $val)
1390 {
1391 $g4 = $val;
1392 $g4s = "rulescriptfrequensystr_H";
1393 }
1394 }
1395
1396 if($maxes['H'] > 70)
1397 {
1398 $val = 7;
1399 if($g4 < $val)
1400 {
1401 $g4 = $val;
1402 $g4s = "rulescriptfrequensystr_H";
1403 }
1404 }
1405
1406 //G5 процентное содержание невордслооварных символов в одной строке (длиной более pshlss3 =30символов) более чем psw1% = 23 [3]
1407 //G5 процентное содержание невордслооварных символов в одной строке (длиной более pshlss3 =30символов) более чем psw2% = 26 [5]
1408 //G5 процентное содержание невордслооварных символов в одной строке (длиной более pshlss3 =30символов) более чем psw3% = 30 [7]
1409
1410 if($maxes['NW'] > 23)
1411 {
1412 $val = 3;
1413 if($g5 < $val)
1414 {
1415 $g5 = $val;
1416 $g5s = "rulescriptfrequensystr_NW";
1417 }
1418 }
1419
1420 if($maxes['NW'] > 26)
1421 {
1422 $val = 5;
1423 if($g5 < $val)
1424 {
1425 $g5 = $val;
1426 $g5s = "rulescriptfrequensystr_NW";
1427 }
1428 }
1429
1430 if($maxes['NW'] > 30)
1431 {
1432 $val = 7;
1433 if($g5 < $val)
1434 {
1435 $g5 = $val;
1436 $g5s = "rulescriptfrequensystr_NW";
1437 }
1438 }
1439
1440 //G6 процентное содержание символов с кодом меньше чем 20 (hex) в одной строке (длиной более psblss1=30 символов) больше чем psb1% 0.1 [7]
1441 //G6 процентное содержание символов с кодом меньше чем 20 (hex) в одной строке (длиной более psblss2=30 символов) больше чем psb2% 0.5 [8]
1442 //G6 процентное содержание символов с кодом меньше чем 20 (hex) в одной строке (длиной более psblss3=30 символов) больше чем psb3% 1.0 [9]
1443
1444 if($maxes['B'] > 0.1)
1445 {
1446 $val = 7;
1447 if($g6 < $val)
1448 {
1449 $g6 = $val;
1450 $g6s = "rulescriptfrequensystr_B";
1451 }
1452 }
1453
1454 if($maxes['B'] > 0.5)
1455 {
1456 $val = 8;
1457 if($g6 < $val)
1458 {
1459 $g6 = $val;
1460 $g6s = "rulescriptfrequensystr_B";
1461 }
1462 }
1463
1464 if($maxes['B'] > 1)
1465 {
1466 $val = 9;
1467 if($g6 < $val)
1468 {
1469 $g6 = $val;
1470 $g6s = "rulescriptfrequensystr_B";
1471 }
1472 }
1473
1474 if(!empty($g3s))
1475 $this->resultrules[$g3s] = $g3;
1476 if(!empty($g4s))
1477 $this->resultrules[$g4s] = $g4;
1478 if(!empty($g5s))
1479 $this->resultrules[$g5s] = $g5;
1480 if(!empty($g6s))
1481 $this->resultrules[$g6s] = $g6;
1482
1483 return ($g3+$g4+$g5+$g6);
1484 }
1485
1486 // признаки, уменьшающие рейтинг опасности скрипта
1488 {
1489 if(!$this->bodylines)
1490 $this->bodylines = explode("\n", $this->body);
1491
1492 $ll = mb_strlen(bin2hex($this->body)) / 2;
1493 $r = 0;
1494 $lstr = count($this->bodylines);
1495
1496 if(!preg_match("/src=/", $this->atributes))
1497 {
1498 if($ll < 100)
1499 {
1500 $val = -6;
1501 $this->resultrules["rulescriptwhiterules_len"] = $val;
1502 $r += $val;
1503 }
1504 elseif($ll < 200)
1505 {
1506 $val = -4;
1507 $this->resultrules["rulescriptwhiterules_len"] = $val;
1508 $r += $val;
1509 }
1510 elseif($ll < 400)
1511 {
1512 $val = -1;
1513 $this->resultrules["rulescriptwhiterules_len"] = $val;
1514 $r += $val;
1515 }
1516
1517 $ok = 0;
1518 $ok2 = 0;
1519 $i = 0;
1520 $lstr=sizeof($this->bodylines);
1521 while((!$ok || !$ok2) && $i<$lstr)
1522 {
1523 if(!$ok && preg_match("/^[\\s\\r\\n]*$/", $this->bodylines[$i]))
1524 {
1525 $val = -6;
1526 $this->resultrules["rulescriptwhiterules_nullines"] = $val;
1527 $r += $val;
1528 $ok = 1;
1529 }
1530
1531 if(!$ok2 && preg_match("/^(( )|(\t))/", $this->bodylines[$i]))
1532 {
1533 $val = -6;
1534 $this->resultrules["rulescriptwhiterules_tabs"] = $val;
1535 $r += $val;
1536 $ok2 = 1;
1537 }
1538
1539 $i++;
1540 }
1541 }
1542
1543 if($lstr > 30)
1544 {
1545 $val = -20;
1546 $this->resultrules["rulescriptwhiterules_lines"] = $val;
1547 $r += $val;
1548 }
1549 elseif($lstr > 15)
1550 {
1551 $val = -14;
1552 $this->resultrules["rulescriptwhiterules_lines"] = $val;
1553 $r += $val;
1554 }
1555 elseif($lstr > 7)
1556 {
1557 $val = -6;
1558 $this->resultrules["rulescriptwhiterules_lines"] = $val;
1559 $r += $val;
1560 }
1561
1562 return $r;
1563 }
1564
1565 //анализ признаков в именах функций и переменных
1567 {
1568
1569 $rr = $this->getnames($this->body);
1570
1571 $cc = 0;
1572 $cn = 0;
1573 $r = 0;
1574
1575 foreach($rr['f'] as $k=>$v)
1576 {
1577 $cc++;
1578 if(!$this->isnormalname($v, $l))
1579 $cn++;
1580 }
1581
1582 $mxl = 0;
1583 foreach($rr['n'] as $k=>$v)
1584 {
1585 $cc++;
1586 if(!$this->isnormalname($v, $l))
1587 $cn++;
1588
1589 if($l > $mxl)
1590 $mxl = $l;
1591 }
1592
1593 if($mxl > 35)
1594 {
1595 $val = 6;
1596 $this->resultrules["rulescriptnamerules_nlen"] = $val;
1597 $r += $val;
1598 }
1599 elseif($mxl > 25)
1600 {
1601 $val = 4;
1602 $this->resultrules["rulescriptnamerules_nlen"] = $val;
1603 $r += $val;
1604 }
1605 elseif($mxl > 15)
1606 {
1607 $val = 2;
1608 $this->resultrules["rulescriptnamerules_nlen"] = $val;
1609 $r += $val;
1610 }
1611
1612 $mxs = 0;
1613 foreach($rr['s'] as $k=>$v)
1614 {
1615 $l = mb_strlen(bin2hex($v)) / 2;
1616 if($l > $mxs)
1617 $mxs = $l;
1618 }
1619
1620 if($mxs > 400)
1621 {
1622 $val = 7;
1623 $this->resultrules["rulescriptnamerules_str"] = $val;
1624 $r += $val;
1625 }
1626 elseif($mxs > 200)
1627 {
1628 $val = 4;
1629 $this->resultrules["rulescriptnamerules_str"] = $val;
1630 $r += $val;
1631 }
1632 elseif($mxs > 100)
1633 {
1634 $val = 2;
1635 $this->resultrules["rulescriptnamerules_str"] = $val;
1636 $r += $val;
1637 }
1638
1639 if($cc > 3)
1640 {
1641 $nspp = 100*$cn/$cc;
1642
1643 if($nspp > 40)
1644 {
1645 $val = 9;
1646 $this->resultrules["rulescriptnamerules_nnormnam"] = $val;
1647 $r += $val;
1648 }
1649 elseif($nspp > 25)
1650 {
1651 $val = 8;
1652 $this->resultrules["rulescriptnamerules_nnormnam"] = $val;
1653 $r += $val;
1654 }
1655 elseif($nspp > 10)
1656 {
1657 $val = 6;
1658 $this->resultrules["rulescriptnamerules_nnormnam"] = $val;
1659 $r += $val;
1660 }
1661 }
1662
1663 return $r;
1664 }
1665
1666 // вспомогательные функции..
1667
1668 // возвращает частотные содержания символов в строке
1670 {
1671 static $arCharClasses = false;
1672 if(!$arCharClasses)
1673 {
1674 $arCharClasses = array(
1675 'D' => array(),
1676 'H' => array(),
1677 'B' => array(),
1678 'NW' => array(),
1679 );
1680
1681 for($i = ord('0'), $end = ord('9'); $i <= $end; $i++)
1682 $arCharClasses['D'][] = $i;
1683
1684 for($i = ord('a'), $end = ord('f'); $i <= $end; $i++)
1685 $arCharClasses['H'][] = $i;
1686
1687 for($i = ord('A'), $end = ord('F'); $i <= $end; $i++)
1688 $arCharClasses['H'][] = $i;
1689
1690 for($i = 0;$i < 32; $i++)
1691 $arCharClasses['B'][] = $i;
1692
1693 $strPunct = "`~!@#$%^&*[]{}();:'\",.\/?\|";
1694 $len = mb_strlen($strPunct);
1695 for($i = 0; $i < $len; $i++)
1696 $arCharClasses['NW'][] = ord(mb_substr($strPunct, $i, 1));
1697 }
1698
1699 $chars = count_chars($str, 1);
1700 $len = array_sum($chars);
1701
1702 unset($chars[9]);
1703 unset($chars[10]);
1704 unset($chars[13]);
1705 unset($chars[32]);
1706 unset($chars[208]);
1707 unset($chars[209]);
1708
1709 $out = array(
1710 'MAXCHAR' => $len && count($chars)? max($chars): 0,
1711 "D" => 0,
1712 "H" => 0,
1713 "B" => 0,
1714 "NW" => 0,
1715 "LEN" => $len,
1716 );
1717
1718 if(count($chars))
1719 {
1720 foreach($arCharClasses as $class => $arChars)
1721 foreach($arChars as $ch)
1722 if(isset($chars[$ch]))
1723 $out[$class] += $chars[$ch];
1724 $out["H"] += $out["D"];
1725 }
1726
1727 return $out;
1728 }
1729
1730 function getnames_cb($m)
1731 {
1732 $this->quotes[] = ($m[2]);
1733 return $m[1].$m[3];
1734 }
1735
1736 function getnames($str)
1737 {
1738 $flt = new CSecurityXSSDetect(array("action" => "none", "log" => "N"));
1739 $flt->removeQuotedStrings($str);
1740 $this->quotes = $flt->getQuotes();
1741
1742 $r = array('f'=>array(), 'n'=>array(), 's'=>array());
1743
1744 if(preg_match_all("/(?<=[^\w\d\_\'\"]|^)([a-z][\w\d\_]*)([^\w\d\_\'\"])/is", $str, $ret))
1745 {
1746 $added = array();
1747 foreach($ret[1] as $k => $v)
1748 {
1749 if(!array_key_exists($v ,$added))
1750 {
1751 if($ret[2][$k] == '(')
1752 $r['f'][] = $v;
1753 else
1754 $r['n'][]=$v;;
1755
1756 $added[$v] = 1;
1757 }
1758 }
1759 }
1760
1761 $r['s'] = $this->quotes;
1762
1763 return $r;
1764 }
1765
1766 function isnormalname($nm, &$l)
1767 {
1768 $lnm = mb_strtolower($nm);
1769 if($lnm == 'ac_fl_runcontent')
1770 return 1;
1771 if($lnm == 'innerhtml')
1772 return 1;
1773
1774 if(preg_match("/[a-z]\d+[a-z]+\d+[a-z]+/is", $nm))
1775 return 0;
1776
1777 static $cache = array();
1778 if(!isset($cache[$nm]))
1779 {
1780 $chars = count_chars($nm, 1);
1781 $l = array_sum($chars);
1782
1783 $cs = 0;
1784 $start = ord('a');
1785 $end = ord('z');
1786 for($i = $start; $i <= $end; $i++)
1787 {
1788 if(isset($chars[$i]))
1789 $cs += $chars[$i];
1790 }
1791
1792 $cz = 0;
1793 $start = ord('A');
1794 $end = ord('Z');
1795 for($i = $start; $i <= $end; $i++)
1796 {
1797 if(isset($chars[$i]))
1798 $cz += $chars[$i];
1799 }
1800
1801 $cc = 0;
1802 $start = ord('0');
1803 $end = ord('9');
1804 for($i = $start; $i <= $end; $i++)
1805 {
1806 if(isset($chars[$i]))
1807 $cc += $chars[$i];
1808 }
1809
1810 if($cs<$cz && $cs>2 && $l>5)
1811 $cache[$nm] = 0;
1812 elseif($cs>$cz && $cz>3 && $l>6)
1813 $cache[$nm] = 0;
1814 elseif($l>0 && $cc*100/$l>50 && $l>5)
1815 $cache[$nm] = 0;
1816 else
1817 $cache[$nm] = 1;
1818 }
1819 return $cache[$nm];
1820 }
1821
1823 {
1824 if(preg_match("/<script.*?>((\s*<!\-\-)|(<!\[CDATA\[))?\s*(.*?)\s*((\/\/\s*\-\->\s*)|(\/\/\s*\]\s*\]\s*))?<\/script.*>/is", $str, $ret))
1825 return $ret[4];
1826 return $str;
1827 }
1828
1829 public static function isSafetyRequest()
1830 {
1831 return (!isset($_SERVER['REQUEST_METHOD']) || !in_array($_SERVER['REQUEST_METHOD'],array('GET','POST')));
1832 }
1833}
$connection
Определения actionsdefinitions.php:38
$count
Определения admin_tab.php:4
global $APPLICATION
Определения include.php:80
Определения ini.php:6
static getList(array $parameters=array())
Определения datamanager.php:431
Определения antivirus.php:26
static UpdateWhiteList($arWhiteList)
Определения antivirus.php:253
rulescriptblocks()
Определения antivirus.php:722
static GetAuditTypes()
Определения antivirus.php:106
$body
Определения antivirus.php:44
isInWhiteList()
Определения antivirus.php:270
getnames_cb($m)
Определения antivirus.php:1730
end_blkblock()
Определения antivirus.php:539
CreateTrace()
Определения antivirus.php:547
isnormalname($nm, &$l)
Определения antivirus.php:1766
static IsActive()
Определения antivirus.php:65
rulescriptglobals()
Определения antivirus.php:687
__construct($place="body")
Определения antivirus.php:57
rulescriptlenghts()
Определения antivirus.php:1009
$atributes
Определения antivirus.php:48
$bodyWOquotes
Определения antivirus.php:46
rulescriptvbscript()
Определения antivirus.php:908
ruleframevisiblity()
Определения antivirus.php:788
$prev
Определения antivirus.php:52
$replacement
Определения antivirus.php:35
static PHPShutdown()
Определения antivirus.php:223
$data
Определения antivirus.php:42
static GetWhiteList()
Определения antivirus.php:247
rulescriptfrequensy()
Определения antivirus.php:1079
ruleallsources()
Определения antivirus.php:921
$cnt
Определения antivirus.php:50
end_whiteblock()
Определения antivirus.php:532
$place
Определения antivirus.php:27
static OnAfterEpilog()
Определения antivirus.php:213
dolog()
Определения antivirus.php:457
Analyze(&$content)
Определения antivirus.php:572
static isSafetyRequest()
Определения antivirus.php:1829
rulescriptnamerules()
Определения antivirus.php:1566
$type
Определения antivirus.php:43
$resultrules
Определения antivirus.php:38
$maxrating
Определения antivirus.php:31
getstatchars(&$str)
Определения antivirus.php:1669
$useglobalrules
Определения antivirus.php:32
rulescriptwhiterules()
Определения antivirus.php:1487
returnscriptbody($str)
Определения antivirus.php:1822
returnfromcache()
Определения antivirus.php:443
$next
Определения antivirus.php:53
$stylewithiframe
Определения antivirus.php:28
static OnPageStart()
Определения antivirus.php:113
static OnEndBufferContent(&$content)
Определения antivirus.php:203
returnblockrating()
Определения antivirus.php:649
getnames($str)
Определения antivirus.php:1736
rulescriptbasics()
Определения antivirus.php:821
addtocache()
Определения antivirus.php:450
$whitelist_id
Определения antivirus.php:39
$replace
Определения antivirus.php:34
end_okblock()
Определения antivirus.php:527
$bodylines
Определения antivirus.php:45
static SetActive($bActive=false)
Определения antivirus.php:82
global $CACHE_MANAGER
Определения clear_component_cache.php:7
$str
Определения commerceml2.php:63
$content
Определения commerceml.php:144
$f
Определения component_props.php:52
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$res
Определения filter_act.php:7
$start
Определения get_search.php:9
else $ch
Определения group_list_element_edit.php:27
$filter
Определения iblock_catalog_list.php:54
$_SERVER["DOCUMENT_ROOT"]
Определения cron_frame.php:9
$l
Определения options.php:783
CheckDirPath($path)
Определения tools.php:2707
RegisterModuleDependences($FROM_MODULE_ID, $MESSAGE_ID, $TO_MODULE_ID, $TO_CLASS="", $TO_METHOD="", $SORT=100, $TO_PATH="", $TO_METHOD_ARG=[])
Определения tools.php:5295
UnRegisterModuleDependences($FROM_MODULE_ID, $MESSAGE_ID, $TO_MODULE_ID, $TO_CLASS="", $TO_METHOD="", $TO_PATH="", $TO_METHOD_ARG=[])
Определения tools.php:5289
GetModuleEvents($MODULE_ID, $MESSAGE_ID, $bReturnArray=false)
Определения tools.php:5177
IncludeModuleLangFile($filepath, $lang=false, $bReturnArray=false)
Определения tools.php:3778
GetMessage($name, $aReplace=null)
Определения tools.php:3397
$event
Определения prolog_after.php:141
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
$ar
Определения options.php:199
$i
Определения factura.php:643
</p ></td >< td valign=top style='border-top:none;border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;padding:0cm 2.0pt 0cm 2.0pt;height:9.0pt'>< p class=Normal align=center style='margin:0cm;margin-bottom:.0001pt;text-align:center;line-height:normal'>< a name=ТекстовоеПоле54 ></a ><?=($taxRate > count( $arTaxList) > 0) ? $taxRate."%"
Определения waybill.php:936
$val
Определения options.php:1793
const SITE_ID
Определения sonet_set_content_view.php:12
$k
Определения template_pdf.php:567
$url
Определения iframe.php:7
$SITE_ID
Определения yandex_run.php:607