瀏覽代碼

db_postgres: Fix heap use after free error in db_postgres module

The result structure for a query holds a pointer returned by
PQfname. When sql_do_query executes the query it gets this
database result structure returned but the PQfname pointer
has already been free'd by a call to db_postgres_free_query
from within db_postgres_store_result.

sql_do_query then tries to copy the free'd string into another
result structure resulting in a heap use after free.

The fix here copies the PQfname result.

Fix by Chris Double
Carsten Bock 10 年之前
父節點
當前提交
74c84c7cd5
共有 2 個文件被更改,包括 8 次插入6 次删除
  1. 0 4
      modules/db_postgres/km_pg_con.c
  2. 8 2
      modules/db_postgres/km_res.c

+ 0 - 4
modules/db_postgres/km_pg_con.c

@@ -71,10 +71,6 @@ struct pg_con* db_postgres_new_connection(struct db_id* id)
 	memset(ptr, 0, sizeof(struct pg_con));
 	ptr->ref = 1;
 
-	memset(keywords, 0, (sizeof(char*) * 10));
-	memset(values, 0, (sizeof(char*) * 10));
-	memset(to, 0, (sizeof(char) * 16));
-
 	if (id->port) {
 		ports = int2str(id->port, 0);
 		keywords[i] = "port";

+ 8 - 2
modules/db_postgres/km_res.c

@@ -126,8 +126,14 @@ int db_postgres_get_columns(const db1_con_t* _h, db1_res_t* _r)
 				RES_NAMES(_r)[col]);
 
 		/* The pointer that is here returned is part of the result structure. */
-		RES_NAMES(_r)[col]->s = PQfname(CON_RESULT(_h), col);
-		RES_NAMES(_r)[col]->len = strlen(PQfname(CON_RESULT(_h), col));
+		RES_NAMES(_r)[col]->s = pkg_malloc(strlen(PQfname(CON_RESULT(_h), col))+1);
+		if (! RES_NAMES(_r)[col]->s) {
+			LM_ERR("no private memory left\n");
+			db_free_columns(_r);
+			return -4;
+		}
+		strcpy(RES_NAMES(_r)[col]->s, PQfname(CON_RESULT(_h), col));
+		RES_NAMES(_r)[col]->len = strlen(RES_NAMES(_r)[col]->s);
 
 		LM_DBG("RES_NAMES(%p)[%d]=[%.*s]\n", RES_NAMES(_r)[col], col,
 				RES_NAMES(_r)[col]->len, RES_NAMES(_r)[col]->s);