Index: /branches/rel_ag_9_4_5/aproxy/apps/webapp/bookmark/bookmark.php
===================================================================
--- /branches/rel_ag_9_4_5/aproxy/apps/webapp/bookmark/bookmark.php	(revision 20510)
+++ /branches/rel_ag_9_4_5/aproxy/apps/webapp/bookmark/bookmark.php	(working copy)
@@ -1,10 +1,12 @@
 <?php
 	include_once "bookmark_db.php";
 	require_once(dirname(__FILE__).'/'."../motionpro/aproxy_cli.php");
+	include_once "/ca/aproxy/webapp/cookiefunc.php";
 
-	$dbname = $_COOKIE['site_name'];
-	$uname = $_COOKIE['user_name'];
-	$role_names = $_COOKIE['roles'];
+	$site_name = get_cookie_and_log('site_name');
+	$dbname = $site_name;
+	$uname = get_cookie_and_log('user_name');
+	$role_names = get_cookie_and_log('roles');
 	$action = $_REQUEST['action'];
 	if(!$dbname || !$uname || !$action){
 		error_log("site_name/user_name/action is null!");
@@ -136,7 +138,7 @@
 			$cmd = 'motionpro sync sql "insert into tbl_bookmark(url,type,user_name,description) values(&'.
 				$url.'&,'.$type.',&'.$uname.'&,&'.$desc.'&)"';
 			$mycli = new cli();
-			$cli_res = $mycli->cmd_direct($cmd , $_COOKIE['site_name']);
+			$cli_res = $mycli->cmd_direct($cmd , $site_name);
 			if($cli_res["result"]){
 				echo "add successfully!";
 				echo "<script>history.go(-2);</script>";
@@ -165,7 +167,7 @@
 		$cmd = 'motionpro sync sql "UPDATE tbl_bookmark set url = &'.
 			$url. '&, description = &'. $desc . '&, type = ' . $type . ' WHERE id = ' . $id . '"';
 		$mycli = new cli();
-		$cli_res = $mycli->cmd_direct($cmd , $_COOKIE['site_name']);
+		$cli_res = $mycli->cmd_direct($cmd , $site_name);
 		if($cli_res["result"]){
 			echo "edit bookmark successfully!";
 			echo "<script>history.go(-2);</script>";
@@ -177,14 +179,14 @@
 		$id = $_REQUEST['id'];
 		header("Content-Type: text/html");
 		if(!is_numeric($id)) {
-			echo "Fail to delete the bookmark!";                    
+			echo "Fail to delete the bookmark!";
 			echo "<a href=/prx/000/http/localh/welcome>back</a>";
 			exit("<br>SQL injection!");
 		}
 		$cmd = 'motionpro sync sql "DELETE FROM tbl_bookmark WHERE id =' .
 			$id . ' and user_name = &' . $uname . '&"';
 		$mycli = new cli();
-		$cli_res = $mycli->cmd_direct($cmd , $_COOKIE['site_name']);
+		$cli_res = $mycli->cmd_direct($cmd , $site_name);
 		if($cli_res["result"]){
 			echo "delete successfully!";
 			echo "<script>history.go(-1);</script>";
@@ -195,6 +197,6 @@
 	} else {
 		exit("invalid action");
 	}
-	
+
 
 ?>
Index: /branches/rel_ag_9_4_5/aproxy/apps/webapp/cookiefunc.php
===================================================================
--- /branches/rel_ag_9_4_5/aproxy/apps/webapp/cookiefunc.php	(revision 0)
+++ /branches/rel_ag_9_4_5/aproxy/apps/webapp/cookiefunc.php	(working copy)
@@ -0,0 +1,90 @@
+<?php
+
+define('COOKIE_LOG', "/var/log/aproxy_cookie.log");
+define('COOKIE_LOG_MAX_SIZE', 200 * 1024 * 1024); // 200MB
+define('COOKIE_LOG_KEEP_SIZE', 180 * 1024 * 1024); // Keep last 180MB
+
+/* *
+ * Get cookie value and log it
+ * @param string $name Cookie name
+ * @return string Cookie value (empty string if not set)
+ */
+function get_cookie_and_log($name) {
+    $value = empty($_COOKIE[$name]) ? "" : $_COOKIE[$name];
+    rotate_log($name, $value);
+    return $value;
+}
+
+/* *
+ * Rotate log file if it exceeds max size, keep the last COOKIE_LOG_KEEP_SIZE bytes
+ * @param string $name Cookie name
+ * @param string $value Cookie value
+ * @return void
+ */
+function rotate_log($name, $value) {
+    $datetime = date('Y-m-d H:i:s');
+    $bt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
+    if (isset($bt[1]['file'])) {
+        $script_path = str_replace('\\', '/', $bt[1]['file']);
+    } else {
+        $script_path = str_replace('\\', '/', __FILE__);
+    }
+    $aproxy_pos = strpos($script_path, '/aproxy/');
+    $relative_path = $aproxy_pos !== false
+        ? substr($script_path, $aproxy_pos + strlen('/aproxy/'))
+        : $script_path;
+    $log_data = [
+        "cookie_key" => $name,
+        "cookie_value" => $value,
+        "domain" => isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '',
+        "client_ip" => get_client_ip(),
+    ];
+    $log_line = sprintf(
+        "%s [%s] %s\n",
+        $datetime,
+        $relative_path,
+        json_encode($log_data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
+    );
+    $fp = fopen(COOKIE_LOG, 'c+');
+    if ($fp) {
+        flock($fp, LOCK_EX);
+        if (filesize(COOKIE_LOG) + strlen($log_line) > COOKIE_LOG_MAX_SIZE) {
+            fseek($fp, -COOKIE_LOG_KEEP_SIZE, SEEK_END);
+            $data = fread($fp, COOKIE_LOG_KEEP_SIZE);
+            ftruncate($fp, 0);
+            rewind($fp);
+            fwrite($fp, $data);
+        }
+        fseek($fp, 0, SEEK_END);
+        fwrite($fp, $log_line);
+        fflush($fp);
+        flock($fp, LOCK_UN);
+        fclose($fp);
+    }
+}
+
+/**
+ * Get client IP address considering possible proxies
+ * @return string Client IP address (empty string if not found)
+ */
+function get_client_ip() {
+    foreach ([
+        'HTTP_CLIENT_IP',
+        'HTTP_X_FORWARDED_FOR',
+        'HTTP_X_FORWARDED',
+        'HTTP_X_CLUSTER_CLIENT_IP',
+        'HTTP_FORWARDED_FOR',
+        'HTTP_FORWARDED',
+        'REMOTE_ADDR'
+    ] as $key) {
+        if (!empty($_SERVER[$key])) {
+            $ip = $_SERVER[$key];
+            // Only get first IP
+            if (strpos($ip, ',') !== false) {
+                $ip = trim(explode(',', $ip)[0]);
+            }
+            return $ip;
+        }
+    }
+    return '';
+}
Index: /branches/rel_ag_9_4_5/aproxy/apps/webapp/mdm/common.php
===================================================================
--- /branches/rel_ag_9_4_5/aproxy/apps/webapp/mdm/common.php	(revision 20510)
+++ /branches/rel_ag_9_4_5/aproxy/apps/webapp/mdm/common.php	(working copy)
@@ -3,6 +3,7 @@
 require_once("/ca/aproxy/webapp/mdm/an_config.php");
 require_once("/ca/aproxy/webapp/apn/Message.php");
 require_once("/ca/aproxy/webapp/mdm/exception.php");
+include_once("/ca/aproxy/webapp/cookiefunc.php");
 $gStartTime = microtime(TRUE);
 ob_start();
 session_start();
@@ -23,7 +24,7 @@
 // $gLogSQL = TRUE;
 $gClientIdent = (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']);
 $gLogFD = 0;
-$gSiteName = (isset($_GET['site_name']) ? $_GET['site_name'] : $_COOKIE['site_name']);
+$gSiteName = (isset($_GET['site_name']) ? $_GET['site_name'] : get_cookie_and_log('site_name'));
 $gDeviceID = "";
 // $gErrorLog = "";
 $gScriptName = basename($_SERVER['PHP_SELF']);
Index: /branches/rel_ag_9_4_5/aproxy/apps/webapp/mdm/config.php
===================================================================
--- /branches/rel_ag_9_4_5/aproxy/apps/webapp/mdm/config.php	(revision 20510)
+++ /branches/rel_ag_9_4_5/aproxy/apps/webapp/mdm/config.php	(working copy)
@@ -1,10 +1,11 @@
 <?PHP
 require_once("../motionpro/aproxy_cli.php");
+include_once "/ca/aproxy/webapp/cookiefunc.php";
 
 if (array_key_exists('site_name', $_REQUEST))
     $db_name = $_REQUEST['site_name'];
 else if (array_key_exists('site_name', $_COOKIE))
-    $db_name = $_COOKIE['site_name'];
+    $db_name = get_cookie_and_log('site_name');
 
 if(!check_sitename($db_name)) {
     error_log("site_name is invalid!");
Index: /branches/rel_ag_9_4_5/aproxy/apps/webapp/mdm/profile.php
===================================================================
--- /branches/rel_ag_9_4_5/aproxy/apps/webapp/mdm/profile.php	(revision 20510)
+++ /branches/rel_ag_9_4_5/aproxy/apps/webapp/mdm/profile.php	(working copy)
@@ -1,6 +1,7 @@
 <?php
 require_once("/ca/aproxy/webapp/mdm/an_config.php");
 require_once("/ca/aproxy/webapp/mdm/common.php");
+include_once "/ca/aproxy/webapp/cookiefunc.php";
 
 function mdm_device_registered($device_id)
 {
@@ -72,9 +73,9 @@
     if (!array_key_exists('site_port', $_COOKIE))
         throw new Exception("400 Bad Request - no site port found");
 
-    $VIRTUAL_SITE_NAME = $_COOKIE["site_name"];
-    $VIRTUAL_SITE_FQDN = $_COOKIE["site_fqdn"];
-    $VIRTUAL_SITE_PORT = $_COOKIE["site_port"];
+    $VIRTUAL_SITE_NAME = get_cookie_and_log("site_name");
+    $VIRTUAL_SITE_FQDN = get_cookie_and_log("site_fqdn");
+    $VIRTUAL_SITE_PORT = get_cookie_and_log("site_port");
     $DEVICE_ID = rawurldecode($_REQUEST["devid"]);
     $USERNAME = rawurldecode($_REQUEST["user"]);
     $mdm_port = MDM_PORT;
Index: /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/mp_db.php
===================================================================
--- /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/mp_db.php	(revision 20510)
+++ /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/mp_db.php	(working copy)
@@ -3,6 +3,7 @@
 use \PDO;
 use \DOMDocument;
 include "db_config.php";
+include_once "/ca/aproxy/webapp/cookiefunc.php";
 
 function check_dbname($site_name)
 {
@@ -81,8 +82,9 @@
 		}
 		$nativeapps = $xml->addChild('NativeApps');
 		if(!empty($data->nativeapps)){
-			$naIconsDir = "/ca/appstore/naIcons/" . $_COOKIE["site_name"];
-			$naIconsDirNoCA = "/appstore/naIcons/" . $_COOKIE["site_name"];
+			$site_name = get_cookie_and_log("site_name");
+			$naIconsDir = "/ca/appstore/naIcons/" . $site_name;
+			$naIconsDirNoCA = "/appstore/naIcons/" . $site_name;
 			foreach($data->nativeapps as $app){
 				$webapp = $nativeapps->addChild('NativeApp');
 				$webapp->addAttribute("ID", $app["id"]);
Index: /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/postlogin_app.php
===================================================================
--- /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/postlogin_app.php	(revision 20510)
+++ /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/postlogin_app.php	(working copy)
@@ -1,7 +1,8 @@
 <?php
 include_once "mp_db.php";
 include_once "mp_portal_config.php";
-$sitename = $_COOKIE["site_name"];
+include_once "/ca/aproxy/webapp/cookiefunc.php";
+$sitename = get_cookie_and_log("site_name");
 if(!$sitename){
 	error_log("site_name is null!");
 	exit("site_name is null!");
@@ -14,7 +15,7 @@
 $dbname = "auth_" . $sitename;
 $db_conn = new MP\DB\MP_db($dbname);
 $host = new MP\DB\Host('Host');
-$user_name = $_COOKIE["user_name"];
+$user_name = get_cookie_and_log("user_name");
 if(!$user_name){
 	error_log("<$sitename> user_name is null!");
 	exit("user_name is null!");
@@ -24,7 +25,7 @@
 		exit("user_name is invalid!");
 	}
 }
-$groups = $_COOKIE["roles"];
+$groups = get_cookie_and_log("roles");
 if(!$groups){
 	error_log("<$sitename> roles is null!");
 	exit("roles is null!");
Index: /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/postlogin_cv.php
===================================================================
--- /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/postlogin_cv.php	(revision 20510)
+++ /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/postlogin_cv.php	(working copy)
@@ -1,6 +1,7 @@
 <?php
 include_once "mp_db.php";
-$sitename = $_COOKIE["site_name"];
+include_once "/ca/aproxy/webapp/cookiefunc.php";
+$sitename = get_cookie_and_log("site_name");
 if(!$sitename){
 	error_log("site_name is null!");
 	exit("site_name is null!");
@@ -12,7 +13,7 @@
 }
 
 $dbname = "auth_" . $sitename;
-$user_name = $_COOKIE["user_name"];
+$user_name = get_cookie_and_log("user_name");
 if(!$user_name){
         error_log("<$sitename> user_name is null!");
         exit("user_name is null!");
Index: /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/postlogin_getdesc.php
===================================================================
--- /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/postlogin_getdesc.php	(revision 20510)
+++ /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/postlogin_getdesc.php	(working copy)
@@ -1,6 +1,7 @@
 <?php
 include_once "mp_db.php";
-$sitename = $_COOKIE["site_name"];
+include_once "/ca/aproxy/webapp/cookiefunc.php";
+$sitename = get_cookie_and_log("site_name");
 if(!$sitename){
 	error_log("site_name is null!");
 	exit("site_name is null!");
Index: /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/prelogin_cv.php
===================================================================
--- /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/prelogin_cv.php	(revision 20510)
+++ /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/prelogin_cv.php	(working copy)
@@ -1,6 +1,7 @@
 <?php
 include_once "mp_db.php";
-$sitename = $_COOKIE["site_name"];
+include_once "/ca/aproxy/webapp/cookiefunc.php";
+$sitename = get_cookie_and_log("site_name");
 if(!$sitename){
 	error_log("site_name is null!");
 	exit("site_name is null");
Index: /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/runcli_getipsec.php
===================================================================
--- /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/runcli_getipsec.php	(revision 20510)
+++ /branches/rel_ag_9_4_5/aproxy/apps/webapp/motionpro/runcli_getipsec.php	(working copy)
@@ -1,5 +1,6 @@
 <?php
 	require_once("aproxy_cli.php");
+	include_once "/ca/aproxy/webapp/cookiefunc.php";
 
 	$mycli = new cli();
 	if(!$_COOKIE["site_name"]){
@@ -14,7 +15,7 @@
 		header("HTTP/1.1 400 Bad Request");
 		exit;
 	}
-	$vsite = $_COOKIE["site_name"];   //pay attention to the chinese characters.
+	$vsite = get_cookie_and_log("site_name");   //pay attention to the chinese characters.
 	$username = rawurldecode($_GET["username"]);
 	$deviceID = rawurldecode($_GET["deviceID"]);
 	$session_type = rawurldecode($_GET["session_type"]);
Index: /branches/rel_ag_9_4_5/debug/debug.c
===================================================================
--- /branches/rel_ag_9_4_5/debug/debug.c	(revision 20510)
+++ /branches/rel_ag_9_4_5/debug/debug.c	(working copy)
@@ -1228,6 +1228,18 @@
 	snprintf(cmd, sizeof(cmd), "printf \"\nloader.conf\n\" >> %s; cat /boot/loader.conf >> %s", fn, fn);
 	system(cmd);
 
+	/* For checking files under /ca/aproxy if there is any malicious file */
+	const char *cli_cmds_for_ca_aproxy[] = {
+		"ls -a /ca/aproxy",
+		"ls -a /ca/aproxy/webapp",
+		"ls -a /ca/aproxy/webapp/bookmark",
+		"ls -a /ca/aproxy/webapp/motionpro"
+	};
+	for (i = 0; i < sizeof(cli_cmds_for_ca_aproxy)/sizeof(cli_cmds_for_ca_aproxy[0]); i++) {
+		snprintf(cmd, sizeof(cmd), "printf \"\n%s\n\" >> %s; %s >> %s", cli_cmds_for_ca_aproxy[i], fn, cli_cmds_for_ca_aproxy[i], fn);
+		system(cmd);
+	}
+
 	/* get stack trace of coredump */
 	for(i = 0; i < DEBUG_MAXDEAMON; i++) {
 		if((appcore + i)->corenum > 0) {
@@ -1295,8 +1307,8 @@
                         "/var/crash/clientip.log /var/crash/procmon.out* /var/crash/vpn.log " \
                         "/var/crash/localdb/* /var/crash/racoon.log /var/crash/mpd.log* /var/crash/libsm.log " \
                         "/ca/etc/license.txt /ca/etc/private_license /var/log/system_date /ca/etc/record_date " \
-                        "/var/crash/license.db.log /var/mail/*" 
-						
+                        "/var/crash/license.db.log /var/mail/* /var/log/aproxy_cookie.log"
+
 static int
 generate_sys_log_tarball(void)
 {
