CVE-2014-3774 (published 2014-08-07T11:13Z)

Multiple cross-site scripting (XSS) vulnerabilities in items.php in TeamPass before 2.1.20 allow remote attackers to inject arbitrary web script or HTML via the group parameter, which is not properly handled in a (1) hid_cat or (2) open_folder form element, or (3) id parameter, which is not properly handled in the open_id form element.

Severity: MEDIUM
CVSS v2 base score: 4.3 (AV:N/AC:M/Au:N/C:N/I:P/A:N)

Weakness information:
cwe_id: CWE-79
cwe_name: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
extended_description: 
            Cross-site scripting (XSS) vulnerabilities occur when:
            
               Untrusted data enters a web application, typically from a web request.
               The web application dynamically generates a web page that contains this untrusted data.
               During page generation, the application does not prevent the data from containing content that is executable by a web browser, such as JavaScript, HTML tags, HTML attributes, mouse events, Flash, ActiveX, etc.
               A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
               Since the script comes from a web page that was sent by the web server, the victim's web browser executes the malicious script in the context of the web server's domain.
               This effectively violates the intention of the web browser's same-origin policy, which states that scripts in one domain should not be able to access resources or run code in a different domain.
            
            There are three main kinds of XSS:
            
               
                  Type 1: Reflected XSS (or Non-Persistent) - 
         			The server reads data directly from the HTTP request and reflects it back in the HTTP response. Reflected XSS exploits occur when an attacker causes a victim to supply dangerous content to a vulnerable web application, which is then reflected back to the victim and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to the victim. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces a victim to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content back to the victim, the content is executed by the victim's browser.
               
                  Type 2: Stored XSS (or Persistent) - 
               The application stores dangerous data in a database, message forum, visitor log, or other trusted data store. At a later time, the dangerous data is subsequently read back into the application and included in dynamic content. From an attacker's perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user. For example, the attacker might inject XSS into a log message, which might not be handled properly when an administrator views the logs.
            
               
                  Type 0: DOM-Based XSS - 
               In DOM-based XSS, the client performs the injection of XSS into the page; in the other types, the server performs the injection. DOM-based XSS generally involves server-controlled, trusted script that is sent to the client, such as Javascript that performs sanity checks on a form before the user submits it. If the server-supplied script processes user-supplied data and then injects it back into the web page (such as with dynamic HTML), then DOM-based XSS is possible.
            
            
            Once the malicious script is injected, the attacker can perform a variety of malicious activities. The attacker could transfer private information, such as cookies that may include session information, from the victim's machine to the attacker. The attacker could send malicious requests to a web site on behalf of the victim, which could be especially dangerous to the site if the victim has administrator privileges to manage that site. Phishing attacks could be used to emulate trusted web sites and trick the victim into entering a password, allowing the attacker to compromise the victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking."
            In many cases, the attack can be launched without the victim even being aware of it. Even with careful users, attackers frequently use a variety of methods to encode the malicious portion of the attack, such as URL encoding or Unicode, so the request looks less suspicious.
         
         

Fix information:
repo_url: https://github.com/nilsteampassnet/TeamPass
commit_details: repo_url: https://github.com/nilsteampassnet/TeamPass
author: nils@teampass.net
author_date: 2014-05-03 08:06:26+02:00
msg: Security/API (beta) improvements
repository: repo_url: https://github.com/nilsteampassnet/TeamPass
repo_name: nilsteampassnet/TeamPass
description: Collaborative Passwords Manager
repo_language: PHP
owner: nilsteampassnet
file_changes: filename: admin.php
change_type: ModificationType.MODIFY
diff: @@ -42,8 +42,6 @@ echo '
             <h3>Some instructions</h3>
             <span class="ui-icon ui-icon-wrench" style="float: left; margin-right: .3em;">&nbsp;</span>
                 Access to <a target="_blank" href="http://www.teampass.net" style="font-weight:bold;font-style:italic;">TeamPass website</a><br />
-            <span class="ui-icon ui-icon-wrench" style="float: left; margin-right: .3em;">&nbsp;</span>
-                For any kind of Help and Support, please use the <a target="_blank" href="http://www.teampass.net/forum" style="font-weight:bold;font-style:italic;">Forum</a><br />
             <span class="ui-icon ui-icon-wrench" style="float: left; margin-right: .3em;">&nbsp;</span>
                 You discovered a Bug or you have an improvement Proposal, please use the <a target="_blank" href="https://github.com/nilsteampassnet/TeamPass/issues" style="font-weight:bold;font-style:italic;">Github channel</a>. <i>If you are not sure, always use the Forum before to obtain a confirmation. This will prevent having to much open tickets at Github</i>.<br />
             <div style="text-align:center;margin-top:10px;">

programming_language: PHP
filename: admin.settings_api.php
change_type: ModificationType.MODIFY
diff: @@ -230,7 +230,7 @@ function newIPDB()
 
 function ip_update(id, value, ip)
 {
-    $("#api_db_type").val("admin_action_api_save_key");
+    $("#api_db_type").val("admin_action_api_save_ip");
     $("#api_db_id").val(id);
     $("#api_db_action").val("update");
     $("#div_key").show();
@@ -261,6 +261,7 @@ $(function() {
 					$("#api_db_message").html("'.$txt['error_too_long'].'");
 					exit;
 				}
+
                 $("#div_loading").show();
                 var $this = $(this);
             	// send query

programming_language: PHP
filename: config.php
change_type: ModificationType.DELETE
diff: @@ -1,9 +0,0 @@
-<?php
-
-// Set Teampass path
-$teampass_path = "E:/xampp/htdocs/Teampass";
-// Set Teampass config file
-$teampass_config_file = $teampass_path."/includes/settings.php";
-// Set Teampass secure keys file path
-$teampass_sk_file = "/space/private/teampass/sk.php";
-?>

programming_language: unknown
filename: functions.php
change_type: ModificationType.MODIFY
diff: @@ -1,4 +1,19 @@
 <?php
+/**
+ *
+ * @file          configapi.php
+ * @author        Nils Laumaillé
+ * @version       2.1.20
+ * @copyright     (c) 2009-2014 Nils Laumaillé
+ * @licensing     GNU AFFERO GPL 3.0
+ * @link		  http://www.teampass.net
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+$teampass_config_file = "../includes/settings.php";
 
 function teampass_api_enabled() {
 	$bdd = teampass_connect();
@@ -9,7 +24,7 @@ function teampass_api_enabled() {
 function teampass_whitelist() {
     $bdd = teampass_connect();
 	$apiip_pool = teampass_get_ips();
-	if (count($apiip_pool) > 0 && !array_search($_SERVER['REMOTE_ADDR'], $apiip_pool)) {
+	if (count($apiip_pool) > 0 && array_search($_SERVER['REMOTE_ADDR'], $apiip_pool) === false) {
 		rest_error('IPWHITELIST');
 	}
 }
@@ -169,36 +184,19 @@ function rest_get () {
 
 		if ($GLOBALS['request'][0] == "read") {
 			if($GLOBALS['request'][1] == "category") {
-				$array_category = explode(';',$GLOBALS['request'][2]);
-
-				foreach($array_category as $category) {
-					if(!preg_match_all("/^([\w\:\'\-\sàáâãäåçèéêëìíîïðòóôõöùúûüýÿ]+)$/i", $category,$result)) {
-						rest_error('CATEGORY_MALFORMED');
-					}
-				}
-
-				if(count($array_category) > 1 && count($array_category) < 5) {
-					for ($i = count($array_category); $i > 0; $i--) {
-						$slot = $i - 1;
-						if (!$slot) {
-							$category_query .= "select id from ".$GLOBALS['pre']."nested_tree where title LIKE '".$array_category[$slot]."' AND parent_id = 0";
-						} else {
-							$category_query .= "select id from ".$GLOBALS['pre']."nested_tree where title LIKE '".$array_category[$slot]."' AND parent_id = (";
-						}
-					}
-					for ($i = 1; $i < count($array_category); $i++) { $category_query .= ")"; }
-				} elseif (count($array_category) == 1) {
-					$category_query = "select id from ".$GLOBALS['pre']."nested_tree where title LIKE '".$array_category[0]."' AND parent_id = 0";
+				// get ids
+				if (strpos($GLOBALS['request'][2],",") > 0) {
+					$condition = "id_tree IN (".$GLOBALS['request'][2].")";
 				} else {
-					rest_error ('NO_CATEGORY');
+					$condition = "id_tree = '".$GLOBALS['request'][2]."'";
 				}
-				$response = $bdd->query("select id,label,login,pw from ".$GLOBALS['pre']."items where id_tree = (".$category_query.")");
+				$response = $bdd->query("select id,label,login,pw from ".$GLOBALS['pre']."items where ".$condition);
 				while ($data = $response->fetch())
 				{
 					$id = $data['id'];
 					$json[$id]['label'] = utf8_encode($data['label']);
 					$json[$id]['login'] = utf8_encode($data['login']);
-//					$json[$id]['pw'] = teampass_decrypt_pw($data['pw'],SALT,$rand_key);
+					$json[$id]['pw'] = teampass_decrypt_pw($data['pw'],SALT,$rand_key);
 				}
 			} elseif($GLOBALS['request'][1] == "item") {
 				$array_category = explode(';',$GLOBALS['request'][2]);
@@ -325,6 +323,4 @@ function teampass_decrypt_pw($encrypted, $salt, $rand_key, $itcount = 2072)
     $encrypted = substr($encrypted, 0, -64);
     if ($mac !== hash_hmac('sha256', $encrypted, $salt)) return null;
     return substr(rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, 'ctr', $iv), "\0\4"), strlen($rand_key));
-}
-
-?>
+}
\ No newline at end of file

programming_language: PHP
filename: index.php
change_type: ModificationType.MODIFY
diff: @@ -1,6 +1,19 @@
 <?php
+/**
+ *
+ * @file          indexapi.php
+ * @author        Nils Laumaill
+ * @version       2.1.20
+ * @copyright     (c) 2009-2014 Nils Laumaill
+ * @licensing     GNU AFFERO GPL 3.0
+ * @link		  http://www.teampass.net
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ */
 
-require_once('config.php');
+//require_once('config.php');
 require_once('functions.php');
 
 header('Content-Type: application/json');

programming_language: PHP
filename: include.php
change_type: ModificationType.MODIFY
diff: @@ -39,4 +39,4 @@ $mngPages = array(
     'manage_views' => 'views.php',
     'manage_main' => 'admin.php',
     'manage_settings' => 'admin.settings.php'
-);
+);
\ No newline at end of file

programming_language: PHP
filename: items.load.php
change_type: ModificationType.MODIFY
diff: @@ -2617,6 +2617,7 @@ function prepareOneTimeView()
         function(data) {
             //check if format error
             if (data[0].error == "") {
+				$("#div_dialog_message").dialog({minHeight:500,minWidth:750});
                 $("#div_dialog_message").dialog('open');
                 $("#div_dialog_message_text").html(data[0].url);
             } else {

programming_language: JavaScript
filename: items.php
change_type: ModificationType.MODIFY
diff: @@ -96,13 +96,13 @@ echo '
 <input type="hidden" id="pf_selected" />';
 // Hidden objects for Item search
 if (isset($_GET['group']) && isset($_GET['id'])) {
-    echo '<input type="hidden" name="open_folder" id="open_folder" value="'.$_GET['group'].'" />';
-    echo '<input type="hidden" name="open_id" id="open_id" value="'.$_GET['id'].'" />';
-    echo '<input type="hidden" name="recherche_group_pf" id="recherche_group_pf" value="', in_array($_GET['group'], $_SESSION['personal_visible_groups']) ? '1' : '', '" />';
+    echo '<input type="hidden" name="open_folder" id="open_folder" value="'.htmlspecialchars($_GET['group']).'" />';
+    echo '<input type="hidden" name="open_id" id="open_id" value="'.htmlspecialchars($_GET['id']).'" />';
+    echo '<input type="hidden" name="recherche_group_pf" id="recherche_group_pf" value="', in_array(htmlspecialchars($_GET['group']), $_SESSION['personal_visible_groups']) ? '1' : '', '" />';
 } elseif (isset($_GET['group']) && !isset($_GET['id'])) {
-    echo '<input type="hidden" name="open_folder" id="open_folder" value="'.$_GET['group'].'" />';
+    echo '<input type="hidden" name="open_folder" id="open_folder" value="'.htmlspecialchars($_GET['group']).'" />';
     echo '<input type="hidden" name="open_id" id="open_id" value="" />';
-    echo '<input type="hidden" name="recherche_group_pf" id="recherche_group_pf" value="', in_array($_GET['group'], $_SESSION['personal_visible_groups']) ? '1' : '', '" />';
+    echo '<input type="hidden" name="recherche_group_pf" id="recherche_group_pf" value="', in_array(htmlspecialchars($_GET['group']), $_SESSION['personal_visible_groups']) ? '1' : '', '" />';
 } else {
     echo '<input type="hidden" name="open_folder" id="open_folder" value="" />';
     echo '<input type="hidden" name="open_id" id="open_id" value="" />';
@@ -230,7 +230,7 @@ foreach ($folders as $folder) {
         	}
             // Prepare folder
             $folderTxt = '
-                    <li class="jstreeopen" id="li_'.$folder->id.'">';
+                    <li class="jstreeopen" id="li_'.$folder->id.'" title="ID ['.$folder->id.']">';
             if (in_array($folder->id, $_SESSION['groupes_visibles'])) {
                 $folderTxt .= '
                             <a id="fld_'.$folder->id.'" class="folder" onclick="ListerItems(\''.$folder->id.'\', \'\', 0);">'.$fldTitle.' (<span class="items_count" id="itcount_'.$folder->id.'">'.$itemsNb.'</span>';
@@ -358,7 +358,7 @@ echo '
                 <tr>
                     <td valign="top" class="td_title"><span class="ui-icon ui-icon-carat-1-e" style="float: left; margin-right: .3em;">&nbsp;</span>'.$txt['label'].' :</td>
                     <td>
-                        <input type="hidden" id="hid_label" value="', isset($dataItem) ? $dataItem['label'] : '', '" />
+                        <input type="hidden" id="hid_label" value="', isset($dataItem) ? htmlspecialchars($dataItem['label']) : '', '" />
                         <div id="id_label" style="display:inline;"></div>
                     </td>
                 </tr>';
@@ -367,7 +367,7 @@ echo '
                 <tr>
                     <td valign="top" class="td_title"><span class="ui-icon ui-icon-carat-1-e" style="float: left; margin-right: .3em;">&nbsp;</span>'.$txt['description'].' :</td>
                     <td>
-                        <div id="id_desc" style="font-style:italic;display:inline;"></div><input type="hidden" id="hid_desc" value="', isset($dataItem) ? $dataItem['description'] : '', '" />
+                        <div id="id_desc" style="font-style:italic;display:inline;"></div><input type="hidden" id="hid_desc" value="', isset($dataItem) ? htmlspecialchars($dataItem['description']) : '', '" />
                     </td>
                 </tr>';
 // Line for PW
@@ -455,7 +455,7 @@ if (isset($_SESSION['settings']['item_extra_fields']) && $_SESSION['settings']['
                     <tr class="tr_fields itemCatName_'.$itemCatName.'">
                         <td valign="top" class="td_title">&nbsp;&nbsp;<span class="ui-icon ui-icon-carat-1-e" style="float: left; margin: 0 .3em 0 15px; font-size:9px;">&nbsp;</span><i>'.$field[1].'</i> :</td>
                         <td>
-                            <div id="id_field_'.$field[0].'" style="display:inline;" class="fields_div"></div><input type="hidden" id="hid_field_'.$field[0].'" class="fields" />
+                            <div id="id_field_'.$field[0].'" style="display:inline;" class="fields_div"></div><input type="hidden" id="hid_field_'.htmlspecialchars($field[0]).'" class="fields" />
                         </td>
                     </tr>';
         }

programming_language: PHP
filename: otv.php
change_type: ModificationType.MODIFY
diff: @@ -70,6 +70,13 @@ if (
 
             // get data
             $pw = decrypt($dataItem['pw']);
+
+        	// get key for original pw
+        	$originalKey = $db->queryFirst('SELECT rand_key FROM `'.$pre.'keys` WHERE `table` LIKE "items" AND `id` ='.intval($_GET['item_id']));
+        	// unsalt previous pw
+        	$pw = substr(decrypt($dataItem['pw']), strlen($originalKey['rand_key']));
+
+
             $label = $dataItem['label'];
             $email = $dataItem['email'];
             $url = $dataItem['url'];

programming_language: PHP
filename: admin.queries.php
change_type: ModificationType.MODIFY
diff: @@ -919,6 +919,7 @@ switch ($_POST['type']) {
 				'api',
 				array(
 				    'label'     => $_POST['label'],
+					'value'     => $_POST['key'],
 				    'timestamp' => time()
 				),
 				"id='".intval($_POST['id'])."'"

programming_language: PHP
filename: datatable.item_edition.php
change_type: ModificationType.MODIFY
diff: @@ -31,6 +31,7 @@ $db->connect();
 
 //Columns name
 $aColumns = array('e.timestamp', 'u.login', 'i.label', 'u.name', 'u.lastname');
+$aSortTypes = array('ASC', 'DESC');
 
 //init SQL variables
 $sOrder = $sLimit = $sWhere = "";
@@ -39,19 +40,30 @@ $sOrder = $sLimit = $sWhere = "";
 //Paging
 $sLimit = "";
 if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
-    $sLimit = "LIMIT ". $_GET['iDisplayStart'] .", ". $_GET['iDisplayLength'] ;
+    $sLimit = "LIMIT ". filter_var($_GET['iDisplayStart'], FILTER_SANITIZE_NUMBER_INT) .", ". filter_var($_GET['iDisplayLength'], FILTER_SANITIZE_NUMBER_INT)."";
 }
 
 //Ordering
 
-if (isset($_GET['iSortCol_0'])) {
+if (isset($_GET['iSortCol_0']) && in_array($_GET['iSortCol_0'], $aSortTypes)) {
     $sOrder = "ORDER BY  ";
-    for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
+/*
+for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
         if ($_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true") {
             $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
             ".mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
         }
     }
+*/
+	for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
+		if (
+			$_GET[ 'bSortable_'.filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT)] == "true" &&
+			preg_match("#^(asc|desc)\$#i", $_GET['sSortDir_'.$i])
+		) {
+			$sOrder .= "".$aColumns[ filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT) ]." "
+			.mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
+		}
+	}
 
     $sOrder = substr_replace($sOrder, "", -2);
     if ($sOrder == "ORDER BY") {

programming_language: PHP
filename: datatable.kb.php
change_type: ModificationType.MODIFY
diff: @@ -31,6 +31,7 @@ $db->connect();
 
 //Columns name
 $aColumns = array('id', 'category_id', 'label', 'description', 'author_id');
+$aSortTypes = array('ASC', 'DESC');
 
 //init SQL variables
 $sWhere = $sOrder = $sLimit = "";
@@ -39,20 +40,22 @@ $sWhere = $sOrder = $sLimit = "";
 //Paging
 $sLimit = "";
 if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
-    $sLimit = "LIMIT ". mysql_real_escape_string($_GET['iDisplayStart']) .", "
-            . mysql_real_escape_string($_GET['iDisplayLength']) ;
+    $sLimit = "LIMIT ". filter_var($_GET['iDisplayStart'], FILTER_SANITIZE_NUMBER_INT) .", ". filter_var($_GET['iDisplayLength'], FILTER_SANITIZE_NUMBER_INT)."";
 }
 
 //Ordering
 
-if (isset($_GET['iSortCol_0'])) {
+if (isset($_GET['iSortCol_0']) && in_array($_GET['iSortCol_0'], $aSortTypes)) {
     $sOrder = "ORDER BY  ";
-    for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
-        if ($_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true") {
-            $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
-                    ".mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
-        }
-    }
+	for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
+		if (
+			$_GET[ 'bSortable_'.filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT)] == "true" &&
+			preg_match("#^(asc|desc)\$#i", $_GET['sSortDir_'.$i])
+		) {
+			$sOrder .= "".$aColumns[ filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT) ]." "
+			.mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
+		}
+	}
 
     $sOrder = substr_replace($sOrder, "", -2);
     if ($sOrder == "ORDER BY") {

programming_language: PHP
filename: datatable.logs.php
change_type: ModificationType.MODIFY
diff: @@ -33,6 +33,7 @@ $db->connect();
 if (isset($_GET['action']) && $_GET['action'] == "connections") {
     //Columns name
     $aColumns = array('l.date', 'l.label', 'l.qui', 'u.login');
+	$aSortTypes = array('ASC', 'DESC');
 
     //init SQL variables
     $sWhere = $sOrder = $sLimit = "";
@@ -41,20 +42,22 @@ if (isset($_GET['action']) && $_GET['action'] == "connections") {
     //Paging
     $sLimit = "";
     if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
-        $sLimit = "LIMIT ". mysql_real_escape_string($_GET['iDisplayStart']) .", "
-                . mysql_real_escape_string($_GET['iDisplayLength']) ;
+        $sLimit = "LIMIT ". filter_var($_GET['iDisplayStart'], FILTER_SANITIZE_NUMBER_INT) .", ". filter_var($_GET['iDisplayLength'], FILTER_SANITIZE_NUMBER_INT)."";
     }
 
     //Ordering
 
-    if (isset($_GET['iSortCol_0'])) {
+    if (isset($_GET['iSortCol_0']) && in_array($_GET['iSortCol_0'], $aSortTypes)) {
         $sOrder = "ORDER BY  ";
-        for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
-            if ($_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true") {
-                $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
-                    ".mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
-            }
-        }
+    	for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
+    		if (
+    			$_GET[ 'bSortable_'.filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT)] == "true" &&
+    			preg_match("#^(asc|desc)\$#i", $_GET['sSortDir_'.$i])
+    		) {
+    			$sOrder .= "".$aColumns[ filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT) ]." "
+    			.mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
+    		}
+    	}
 
         $sOrder = substr_replace($sOrder, "", -2);
         if ($sOrder == "ORDER BY") {

programming_language: PHP
filename: datatable.users_logged.php
change_type: ModificationType.MODIFY
diff: @@ -33,6 +33,7 @@ $db->connect();
 
 //Columns name
 $aColumns = array('login', 'name', 'lastname', 'timestamp', 'last_connexion');
+$aSortTypes = array('ASC', 'DESC');
 
 //init SQL variables
 $sOrder = $sLimit = "";
@@ -41,20 +42,22 @@ $sOrder = $sLimit = "";
 //Paging
 $sLimit = "";
 if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
-    $sLimit = "LIMIT ". mysql_real_escape_string($_GET['iDisplayStart']) .", "
-            . mysql_real_escape_string($_GET['iDisplayLength']);
+    $sLimit = "LIMIT ". filter_var($_GET['iDisplayStart'], FILTER_SANITIZE_NUMBER_INT) .", ". filter_var($_GET['iDisplayLength'], FILTER_SANITIZE_NUMBER_INT)."";
 }
 
 //Ordering
 
-if (isset($_GET['iSortCol_0'])) {
+if (isset($_GET['iSortCol_0']) && in_array($_GET['iSortCol_0'], $aSortTypes)) {
     $sOrder = "ORDER BY  ";
-    for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
-        if ($_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true") {
-            $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
-            ".mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
-        }
-    }
+	for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
+		if (
+			$_GET[ 'bSortable_'.filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT)] == "true" &&
+			preg_match("#^(asc|desc)\$#i", $_GET['sSortDir_'.$i])
+		) {
+			$sOrder .= "".$aColumns[ filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT) ]." "
+			.mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
+		}
+	}
 
     $sOrder = substr_replace($sOrder, "", -2);
     if ($sOrder == "ORDER BY") {

programming_language: PHP
filename: find.queries.php
change_type: ModificationType.MODIFY
diff: @@ -84,7 +84,6 @@ if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
 if (isset($_GET['iSortCol_0']) && in_array($_GET['iSortCol_0'], $aSortTypes)) {
     $sOrder = "ORDER BY  ";
     for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
-
         if (
             $_GET[ 'bSortable_'.filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT)] == "true" &&
             preg_match("#^(asc|desc)\$#i", $_GET['sSortDir_'.$i])

programming_language: PHP
filename: items.queries.php
change_type: ModificationType.MODIFY
diff: @@ -1249,7 +1249,7 @@ if (isset($_POST['type'])) {
                     $arrData['link'] = "&nbsp;<a href='".$dataItem['url']."' target='_blank'><img src='includes/images/arrow_skip.png' style='border:0px;' title='".$txt['open_url_link']."'></a>";
                 }
 
-                $arrData['description'] = preg_replace('/(?<!\\r)\\n+(?!\\r)/', '', strip_tags($dataItem['description'], $allowedTags));
+                $arrData['description'] = preg_replace('/(?<!\\r)\\n+(?!\\r)/', '', strip_tags($dataItem['description'], $k['allowedTags']));
                 $arrData['login'] = str_replace('"', '&quot;', $dataItem['login']);
                 $arrData['id_restricted_to'] = $listeRestriction;
                 $arrData['id_restricted_to_roles'] = count($listRestrictionRoles) > 0 ? implode(";", $listRestrictionRoles).";" : "";

programming_language: PHP
filename: users.queries.php
change_type: ModificationType.MODIFY
diff: @@ -373,8 +373,8 @@ if (!empty($_POST['type'])) {
                     'type' => 'user_mngt',
                     'date' => time(),
                     'label' => 'at_user_email_changed:'.$data[0],
-                    'qui' => $_SESSION['user_id'],
-                    'field_1' => $_POST['id']
+                    'qui' => intval($_SESSION['user_id']),
+                    'field_1' => intval($_POST['id'])
                    )
             );
         	echo '[{"error" : "no"}]';

programming_language: PHP
repo_url: https://github.com/nilsteampassnet/TeamPass
commit_details: repo_url: https://github.com/nilsteampassnet/TeamPass
author: nils@teampass.net
author_date: 2014-04-26 11:52:49+02:00
msg: Several security improvements
New feature: one time item view for anonymous user
repository: repo_url: https://github.com/nilsteampassnet/TeamPass
repo_name: nilsteampassnet/TeamPass
description: Collaborative Passwords Manager
repo_language: PHP
owner: nilsteampassnet
file_changes: filename: changelog.md
change_type: ModificationType.MODIFY
diff: @@ -20,6 +20,7 @@
  #544 - DataTables warning: JSON data from server could not be parsed
  Fork from slimm609 - Encrypted Sessions and CSRFGuard enabled
  Issues with folder creation in "personal folder"
+ New: one time view page for anonymous user
 
 2.1.19
  #413 - fix for PHP Parse error: syntax error, unexpected '['

programming_language: Markdown
filename: include.php
change_type: ModificationType.MODIFY
diff: @@ -22,11 +22,14 @@ $k['office_file_ext'] = array('xls', 'xlsx', 'docx', 'doc', 'csv', 'ppt', 'pptx'
 $k['admin_full_right'] = true;
 $k['admin_no_info'] = false;
 $k['copyright'] = " &copy; 2009 - 2014";
+$k['otv_expiration_period'] = 604800; // 1 week
+$k['allowedTags'] = "<b><i><sup><sub><em><strong><u><br><br /><a><strike><ul><blockquote><blockquote><img><li><h1><h2><h3><h4><h5><ol><small><font>";
 
 @define('ERR_NOT_ALLOWED', "1000");
 @define('ERR_NOT_EXIST', "1001");
 @define('ERR_SESS_EXPIRED', "1002");
 @define('ERR_NO_MCRYPT', "1003");
+@define('ERR_VALID_SESSION', "1004");
 
 // Management Pages
 $mngPages = array(

programming_language: PHP
filename: english.php
change_type: ModificationType.MODIFY
diff: @@ -6,6 +6,8 @@ if (!isset($_SESSION['settings']['cpassman_url'])) {
     $TeamPass_url = $_SESSION['settings']['cpassman_url'];
 }
 
+$txt['one_time_item_view'] = "One time view link";
+$txt['one_time_view_item_url_box'] = "Share the One-Time URL with a person of Trust <br><br>#URL#<br><br>Remember that this link will only be visible one time until the #DAY#";
 $txt['url_copied_clipboard'] = "URL copied in clipboard";
 $txt['url_copy'] = "Copy URL in clipboard";
 

programming_language: PHP
filename: index.php
change_type: ModificationType.MODIFY
diff: @@ -10,7 +10,7 @@ session_start();
  *
  * @file          index.php
  * @author        Nils Laumaillé
- * @version       2.1.19
+ * @version       2.1.20
  * @copyright     (c) 2009-2014 Nils Laumaillé
  * @licensing     GNU AFFERO GPL 3.0
  * @link          http://www.teampass.net
@@ -51,15 +51,12 @@ $db->connect();
 
 //load main functions needed
 require_once 'sources/main.functions.php';
+// Load CORE
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/core.php';
 
 /* DEFINE WHAT LANGUAGE TO USE */
 if (!isset($_SESSION['user_id']) && !isset($_POST['language'])) {
     //get default language
-    /*$dataLanguage =
-        $db->fetchRow(
-            "SELECT valeur FROM ".$pre."misc
-            WHERE type = 'admin' AND intitule = 'default_language'"
-        );*/
     $dataLanguage = $db->queryGetRow(
         "misc",
         array(
@@ -91,12 +88,16 @@ if (!isset($_SESSION['user_id']) && !isset($_POST['language'])) {
     }
 }
 // Load user languages files
-require_once $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
-if (isset($_GET['page']) && $_GET['page'] == "kb") {
-    require_once $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'_kb.php';
+if (in_array($_SESSION['user_language'], $languagesList)) {
+	require_once $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
+	if (isset($_GET['page']) && $_GET['page'] == "kb") {
+		require_once $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'_kb.php';
+	}
+} else {
+	$_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+	include 'error.php';
 }
-// Load CORE
-require_once $_SESSION['settings']['cpassman_dir'].'/sources/core.php';
+
 // Load links, css and javascripts
 @require_once $_SESSION['settings']['cpassman_dir'].'/load.php';
 ?>
@@ -208,7 +209,8 @@ if (isset($_SESSION['login'])) {
         </div>';
 }
 // Display language menu
-echo '
+if (!isset($_GET['otv'])) {
+	echo '
         <div style="float:right;">
             <dl id="flags" class="dropdown">
                 <dt><img src="includes/images/flags/'.$_SESSION['user_language_flag'].'" alt="" /></dt>
@@ -218,7 +220,9 @@ echo '
                     </ul>
                 </dd>
             </dl>
-        </div>
+        </div>';
+}
+echo '
     </div>';
 
 /* LAST SEEN */
@@ -299,7 +303,9 @@ if (isset($_SESSION['autoriser']) && $_SESSION['autoriser'] == true && isset($_G
             <br />
             <button title="'.$txt['history'].'" id="menu_button_history" class="" onclick="OpenDialog(\'div_item_history\', \'false\')"><img src="includes/images/report.png" id="div_history" alt="" /></button>
             <br />
-            <button title="'.$txt['share'].'" id="menu_button_share" class="" onclick="OpenDialog(\'div_item_share\', \'false\')"><img src="includes/images/share.png" id="div_share" alt="" /></button>';
+            <button title="'.$txt['share'].'" id="menu_button_share" class="" onclick="OpenDialog(\'div_item_share\', \'false\')"><img src="includes/images/share.png" id="div_share" alt="" /></button>
+			<br />
+            <button title="'.$txt['one_time_item_view'].'" id="menu_button_otv" class="" onclick="prepareOneTimeView()"><img src="includes/images/globe-share.png" id="div_otv" alt="" /></button>';
     if (isset($_SESSION['settings']['enable_email_notification_on_item_shown']) && $_SESSION['settings']['enable_email_notification_on_item_shown'] == 1) {
         echo '
             <br />
@@ -458,9 +464,14 @@ if (isset($_SESSION['validite_pw']) && $_SESSION['validite_pw'] == true && !empt
     include 'error.php';
 } elseif ((!isset($_SESSION['validite_pw']) || empty($_SESSION['validite_pw']) || empty($_SESSION['user_id'])) && isset($_GET['otv']) && $_GET['otv'] == "true") {
     // case where one-shot viewer
-    if (isset($_GET['session']) && !empty($_GET['session'])) {
-        include 'otv.php?session='.$_GET['session'];
-    } else {
+	if (
+		isset($_GET['code']) && !empty($_GET['code'])
+		&& isset($_GET['item_id']) && !empty($_GET['item_id'])
+		&& isset($_GET['stamp']) && !empty($_GET['stamp'])
+		&& isset($_GET['otv_id'])
+	) {
+		include 'otv.php';
+	} else {
         $_SESSION['error']['code'] = ERR_VALID_SESSION;
         $_SESSION['initial_url'] = substr($_SERVER["REQUEST_URI"], strpos($_SERVER["REQUEST_URI"], "index.php?"));
         include 'error.php';

programming_language: PHP
filename: items.load.php
change_type: ModificationType.MODIFY
diff: @@ -162,7 +162,7 @@ function ListerItems(groupe_id, restricted, start)
         if ($(".tr_fields") != undefined) $(".tr_fields, .newItemCat, .editItemCat").hide();
 
         //Disable menu buttons
-        $('#menu_button_edit_item,#menu_button_del_item,#menu_button_add_fav,#menu_button_del_fav,#menu_button_show_pw,#menu_button_copy_pw,#menu_button_copy_login,#menu_button_copy_link,#menu_button_copy_item,#menu_button_notify,#menu_button_history,#menu_button_share').attr('disabled', 'disabled');
+        $('#menu_button_edit_item,#menu_button_del_item,#menu_button_add_fav,#menu_button_del_fav,#menu_button_show_pw,#menu_button_copy_pw,#menu_button_copy_login,#menu_button_copy_link,#menu_button_copy_item,#menu_button_notify,#menu_button_history,#menu_button_share,#menu_button_otv').attr('disabled', 'disabled');
 
         // clear existing clips
         //ZeroClipboard.destroy();
@@ -197,7 +197,7 @@ function ListerItems(groupe_id, restricted, start)
                 } else if (data.error == "not_authorized") {
                     //warn user
                     $("#hid_cat").val("");
-                    $("#menu_button_copy_item, #menu_button_add_group, #menu_button_edit_group, #menu_button_del_group, #menu_button_add_item, #menu_button_edit_item, #menu_button_del_item, #menu_button_history, #menu_button_share").attr('disabled', 'disabled');
+                    $("#menu_button_copy_item, #menu_button_add_group, #menu_button_edit_group, #menu_button_del_group, #menu_button_add_item, #menu_button_edit_item, #menu_button_del_item, #menu_button_history, #menu_button_share, #menu_button_otv").attr('disabled', 'disabled');
                     $("#item_details_nok").show();
                     $("#item_details_ok, #item_details_no_personal_saltkey").hide();
                     $("#items_list_loader").hide();
@@ -1115,9 +1115,9 @@ function AfficherDetailsItem(id, salt_key_required, expired_item, restricted, di
 
                         // disable share button for personal folder
                         if ($("#recherche_group_pf").val() == 1) {
-            		        $("#menu_button_share").attr('disabled', 'disabled');
+            		        $("#menu_button_share, #menu_button_otv").attr('disabled', 'disabled');
             		    } else {
-            		    	$("#menu_button_share").prop("disabled", false);
+            		    	$("#menu_button_share, #menu_button_otv").prop("disabled", false);
             		    }
 
                         //Manage to deleted information
@@ -2600,4 +2600,30 @@ function aes_decrypt(text)
 {
     return Aes.Ctr.decrypt(text, "<?php echo $_SESSION['key'];?>", 256);
 }
+
+/*
+* Launch the redirection to OTV page
+*/
+function prepareOneTimeView()
+{
+    //Send query
+    $.post(
+        "sources/items.queries.php",
+        {
+            type    : "generate_OTV_url",
+            id      : $("#id_item").val(),
+            key     : "<?php echo $_SESSION['key'];?>"
+        },
+        function(data) {
+            //check if format error
+            if (data[0].error == "") {
+                $("#div_dialog_message").dialog('open');
+                $("#div_dialog_message_text").html(data[0].url);
+            } else {
+                $("#item_history_log_error").html(data[0].error).show();
+            }
+        },
+        "json"
+   );
+}
 </script>

programming_language: JavaScript
filename: items.php
change_type: ModificationType.MODIFY
diff: @@ -14,9 +14,9 @@
  */
 
 if (
-    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
-    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
-    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 ||
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) ||
+    !isset($_SESSION['key']) || empty($_SESSION['key']))
 {
     die('Hacking attempt...');
 }
@@ -74,11 +74,11 @@ foreach ($rows as $reccord) {
 $selectVisibleFoldersOptions = $selectVisibleNonPersonalFoldersOptions = "";
 // Hidden things
 echo '
-<input type="hidden" name="hid_cat" id="hid_cat" value="', isset($_GET['group']) ? $_GET['group'] : "", '" />
+<input type="hidden" name="hid_cat" id="hid_cat" value="', isset($_GET['group']) ? htmlspecialchars($_GET['group']) : "", '" />
 <input type="hidden" id="complexite_groupe" />
 <input type="hidden" name="selected_items" id="selected_items" />
 <input type="hidden" name="input_liste_utilisateurs" id="input_liste_utilisateurs" value="'.$usersString.'" />
-<input type="hidden" name="input_list_roles" id="input_list_roles" value="'.htmlentities($listRoles, ENT_QUOTES, 'UTF-8').'" />
+<input type="hidden" name="input_list_roles" id="input_list_roles" value="'.htmlspecialchars(htmlentities($listRoles, ENT_QUOTES, 'UTF-8')).'" />
 <input type="hidden" id="bloquer_creation_complexite" />
 <input type="hidden" id="bloquer_modification_complexite" />
 <input type="hidden" id="error_detected" />
@@ -87,7 +87,7 @@ echo '
 <input type="hidden" id="richtext_on" value="1" />
 <input type="hidden" id="query_next_start" value="0" />
 <input type="hidden" id="display_categories" value="0" />
-<input type="hidden" id="nb_items_to_display_once" value="', isset($_SESSION['settings']['nb_items_by_query']) ? $_SESSION['settings']['nb_items_by_query'] : 'auto', '" />
+<input type="hidden" id="nb_items_to_display_once" value="', isset($_SESSION['settings']['nb_items_by_query']) ? htmlspecialchars($_SESSION['settings']['nb_items_by_query']) : 'auto', '" />
 <input type="hidden" id="user_is_read_only" value="', isset($_SESSION['user_read_only']) && $_SESSION['user_read_only'] == 1 ? '1' : '', '" />
 <input type="hidden" id="request_ongoing" />
 <input type="hidden" id="request_lastItem" />
@@ -118,7 +118,7 @@ if (isset($_COOKIE['jstree_select']) && !empty($_COOKIE['jstree_select'])) {
     $firstGroup = "";
 }
 echo '
-<input type="hidden" name="jstree_group_selected" id="jstree_group_selected" value="'.$firstGroup.'" />';
+<input type="hidden" name="jstree_group_selected" id="jstree_group_selected" value="'.htmlspecialchars($firstGroup).'" />';
 
 echo '
 <div id="div_items">';

programming_language: PHP
filename: otv.php
change_type: ModificationType.ADD
diff: @@ -0,0 +1,103 @@
+<?php
+/**
+ * @file          otv.php
+ * @author        Nils Laumaill
+ * @version       2.1.20
+ * @copyright     (c) 2009-2014 Nils Laumaill
+ * @licensing     GNU AFFERO GPL 3.0
+ * @link          http://www.teampass.net
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+require_once('sources/sessions.php');
+@session_start();
+if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
+    die('Hacking attempt...');
+}
+
+$html = "";
+if (
+    filter_var($_GET['code'], FILTER_SANITIZE_STRING) != ""
+    && filter_var($_GET['item_id'], FILTER_SANITIZE_STRING) >= 0
+    && filter_var($_GET['stamp'], FILTER_SANITIZE_STRING) >= 0
+    && filter_var($_GET['otv_id'], FILTER_SANITIZE_STRING) >= 0
+) {
+    //Include files
+    require_once $_SESSION['settings']['cpassman_dir'].'/includes/settings.php';
+    require_once $_SESSION['settings']['cpassman_dir'].'/includes/include.php';
+    require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';
+
+    // connect to DB
+    $db = new SplClassLoader('Database\Core', '../includes/libraries');
+    $db->register();
+    $db = new Database\Core\DbCore($server, $user, $pass, $database, $pre);
+    $db->connect();
+
+    // Include main functions used by TeamPass
+    require_once 'sources/main.functions.php';
+
+    // check session validity
+    $data = $db->queryGetRow(
+        "otv",
+        array(
+            "timestamp",
+            "code",
+            "item_id"
+        ),
+        array(
+            "id" => intval($_GET['otv_id'])
+        )
+    );
+    if (
+        $data[0] == $_GET['stamp']
+        && $data[1] == $_GET['code']
+        && $data[2] == $_GET['item_id']
+    ) {
+        // otv is too old
+        if ($data[0] < (time() - $k['otv_expiration_period']) ) {
+            $html = "Link is too old!";
+        } else {
+            $dataItem = $db->queryFirst(
+                "SELECT *
+                FROM ".$pre."items as i
+                INNER JOIN ".$pre."log_items as l ON (l.id_item = i.id)
+                WHERE i.id=".intval($_GET['item_id'])."
+                AND l.action = 'at_creation'"
+            );
+
+            // get data
+            $pw = decrypt($dataItem['pw']);
+            $label = $dataItem['label'];
+            $email = $dataItem['email'];
+            $url = $dataItem['url'];
+            $description = preg_replace('/(?<!\\r)\\n+(?!\\r)/', '', strip_tags($dataItem['description'], $k['allowedTags']));
+            $login = str_replace('"', '&quot;', $dataItem['login']);
+
+            // display data
+            $html = "<div style='margin:30px;'>".
+            	"<div style='font-size:20px;font-weight:bold;'>Welcome to One-Time item view page.</div>".
+            	"<div style='font-style:italic;'>Here are the details of the Item that has been shared to you</div>".
+            	"<div style='margin-top:10px;'><table>".
+				"<tr><td>Label:</td><td>" . $label . "</td</tr>".
+            	"<tr><td>Password:</td><td>" . $pw . "</td</tr>".
+            	"<tr><td>Description:</td><td>" . $description . "</td</tr>".
+            	"<tr><td>login:</td><td>" . $login . "</td</tr>".
+            	"<tr><td>URL:</td><td>" . $url ."</td</tr>".
+            	"</table></div>".
+            	"<div style='margin-top:30px;'>Copy carefully the data you need. This page is only visible once.</div>".
+            	"</div>";
+
+        	// delete entry
+        	//$db->query("DELETE FROM ".$pre."otv WHERE id = '".intval($_GET['item_id'])."'");
+        }
+    } else {
+        $html = "Not a valid page!";
+    }
+} else {
+    $html = "Not a valid page!";
+}
+
+echo $html;
\ No newline at end of file

programming_language: PHP
filename: find.queries.php
change_type: ModificationType.MODIFY
diff: @@ -32,6 +32,7 @@ $db->connect();
 
 //Columns name
 $aColumns = array('id', 'label', 'description', 'tags', 'id_tree', 'folder', 'login');
+$aSortTypes = array('ASC', 'DESC');
 
 //init SQL variables
 $sOrder = $sLimit = "";
@@ -80,9 +81,10 @@ if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
 }
 
 //Ordering
-if (isset($_GET['iSortCol_0'])) {
+if (isset($_GET['iSortCol_0']) && in_array($_GET['iSortCol_0'], $aSortTypes)) {
     $sOrder = "ORDER BY  ";
     for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
+
         if (
             $_GET[ 'bSortable_'.filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT)] == "true" &&
             preg_match("#^(asc|desc)\$#i", $_GET['sSortDir_'.$i])
@@ -96,8 +98,11 @@ if (isset($_GET['iSortCol_0'])) {
     if ($sOrder == "ORDER BY") {
             $sOrder = "";
     }
+} else if (!in_array($_GET['iSortCol_0'], $aSortTypes)) {
+	// possible attack - stop
+	echo '[{}]';
 }
-//echo $sOrder;
+
 /*
  * Filtering
  * NOTE this does not match the built-in DataTables filtering which does it

programming_language: PHP
filename: items.queries.php
change_type: ModificationType.MODIFY
diff: @@ -52,8 +52,6 @@ $pwComplexity = array(0 => array(0, $txt['complex_level0']),
     90 => array(90, $txt['complex_level6'])
    );
 
-$allowedTags = '<b><i><sup><sub><em><strong><u><br><br /><a><strike><ul><blockquote><blockquote><img><li><h1><h2><h3><h4><h5><ol><small><font>';
-
 //Class loader
 require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';
 
@@ -2676,6 +2674,66 @@ if (isset($_POST['type'])) {
                 echo '{ "modified" : "0" }';
             }
             break;
+
+        /*
+        * CASE
+        * Check if Item has been changed since loaded
+        */
+        case "generate_OTV_url":
+            // Check KEY
+            if ($_POST['key'] != $_SESSION['key']) {
+                echo '[ { "error" : "key_not_conform" } ]';
+                break;
+            }
+
+            // delete all existing old otv codes
+            $rows = $db->fetchAllArray("SELECT id FROM ".$pre."otv WHERE timestamp < ".(time() - $k['otv_expiration_period']));
+            foreach ($rows as $reccord) {
+                $db->queryDelete(
+                    'otv',
+                    array(
+                        'id' => $reccord['id']
+                       )
+                );
+            }
+
+            // generate session
+            $pwgen = new SplClassLoader('Encryption\PwGen', '../includes/libraries');
+            $pwgen->register();
+            $pwgen = new Encryption\PwGen\pwgen();
+            $pwgen->setLength(20);
+            $pwgen->setSecure(true);
+            $otv_code = $pwgen->generate();
+
+            $newID = $db->queryInsert(
+                "otv",
+                array(
+                	'id' => null,
+                    'item_id' => intval($_POST['id']),
+                    'timestamp' => time(),
+                    'originator' => intval($_SESSION['user_id']),
+                    'code' => $otv_code
+                   )
+            );
+
+            $otv_session = array(
+                "code"      => $otv_code,
+                "item_id"   => $_POST['id'],
+                "stamp" => time(),
+                "otv_id"    => $newID
+            );
+
+            $url = $_SESSION['settings']['cpassman_url']."/index.php?otv=true&".http_build_query($otv_session);
+        	$exp_date = date($_SESSION['settings']['date_format']." ".$_SESSION['settings']['time_format'], time() + $k['otv_expiration_period']);
+
+        	echo '[{ "error" : "" , "url" : "'.addslashes(
+            	str_replace(
+            		array("#URL#", "#DAY#"),
+            		array($url, $exp_date),
+            		$txt['one_time_view_item_url_box']
+            	)
+            ).'" }]';
+            break;
     }
 }
 // Build the QUERY in case of GET

programming_language: PHP