44ccfacbe3a3d4b300f80d48651c77837a4b571e galt Tue Apr 26 11:12:02 2022 -0700 SQL INJECTION Prevention Version 2 - this improves our methods by making subclauses of SQL that get passed around be both easy and correct to use. The way that was achieved was by getting rid of the obscure and not well used functions sqlSafefFrag and sqlDyStringPrintfFrag and replacing them with the plain versions of those functions, since these are not needed anymore. The new version checks for NOSQLINJ in unquoted %-s which is used to include SQL clauses, and will give an error the NOSQLINJ clause is not present, and this will automatically require the correct behavior by developers. sqlDyStringPrint is a very useful function, however because it was not enforced, users could use various other dyString functions and they operated without any awareness or checking for SQL correct use. Now those dyString functions are prohibited and it will produce an error if you try to use a dyString function on a SQL string, which is simply detected by the presence of the NOSQLINJ prefix. diff --git src/hg/hgText/hgText.c src/hg/hgText/hgText.c index e0d5652..81cca64 100644 --- src/hg/hgText/hgText.c +++ src/hg/hgText/hgText.c @@ -974,31 +974,31 @@ /* separate tables in db into positional and nonpositional lists, * with db added as a prefix to each name. */ { struct hash *posTableHash = newHash(7); struct hashEl *posTableList; struct hash *nonposTableHash = newHash(7); struct hashEl *nonposTableList; struct sqlResult *sr; char **row; char query[256]; char name[128]; char chrom[32]; char post[64]; char fullName[128]; -strcpy(query, NOSQLINJ "SHOW TABLES"); +sqlSafef(query, sizeof query, "SHOW TABLES"); sr = sqlGetResult(conn, query); while((row = sqlNextRow(sr)) != NULL) { if (excludeTable(row[0])) continue; /* if table name is of the form, chr*_random_* or chr*_*: */ if ( (sscanf(row[0], "chr%32[^_]_random_%64s", chrom, post) == 2) || (sscanf(row[0], "chr%32[^_]_hla_hap1_%64s", chrom, post) == 2) || (sscanf(row[0], "chr%32[^_]_hla_hap2_%64s", chrom, post) == 2) || (sscanf(row[0], "chr%32[^_]_%64s", chrom, post) == 2)) { snprintf(name, sizeof(name), "chrN_%s", post); // If a chrN_ table is already in the (positional) hash, // don't bother looking up its fields. @@ -1651,32 +1651,32 @@ } dyStringAppend(clause, ")"); if (numLeftParen != numRightParen) webAbort("Error", "Unequal number of left parentheses (%d) and right parentheses (%d) in free-form query expression", numLeftParen, numRightParen); slFreeList(&tokList); } char *constrainFields(char *tableId) /* If the user specified constraints, append SQL conditions (suitable * for a WHERE clause) to q. */ { struct cgiVar *current; -struct dyString *freeClause = newDyString(512); -struct dyString *andClause = newDyString(512); +struct dyString *freeClause = dyStringNew(512); +struct dyString *andClause = dyStringNew(512); struct dyString *clause; char *fieldName; char *rawQuery; char *rQLogOp; char *dd, *cmp, *pat; char varName[128]; char *ret; int tableIndex = 0; if (tableId == NULL) { tableId = ""; tableIndex = 0; } if (sameString(tableId,"2")) @@ -1735,32 +1735,32 @@ if ((rQLogOp != NULL) && (! sameString("AND", rQLogOp))) rQLogOp = "OR"; if (freeClause->stringSize > 0 && andClause->stringSize > 0) dyStringPrintf(freeClause, " %s ", rQLogOp); if (freeClause->stringSize > 0) { dyStringAppend(freeClause, andClause->string); } else { dyStringAppend(freeClause, andClause->string); } ret = cloneString(freeClause->string); -freeDyString(&freeClause); -freeDyString(&andClause); +dyStringFree(&freeClause); +dyStringFree(&andClause); return ret; } void cgiToCharFilter(char *dd, char *pat, enum charFilterType *retCft, char **retVals, boolean *retInv) /* Given a "does/doesn't" and a (list of) literal chars from CGI, fill in * retCft, retVals and retInv to make a filter. */ { char *vals, *ptrs[32]; int numWords; int i; assert(retCft != NULL); assert(retVals != NULL); @@ -1956,31 +1956,31 @@ void preserveConstraints(char *fullTblName, char *db, char *tableId) /* Add CGI variables for filtering constraints, so they will be passed to * the next page. Also parse the constraints and do a null query with them * in order to catch any syntax errors sooner rather than later. */ { struct cgiVar *current; char *constraints = constrainFields(tableId); char varName[128]; if ((constraints != NULL) && (constraints[0] != 0) && (! sameString(customTrackPseudoDb, db))) { struct sqlConnection *conn = hAllocOrConnect(db); struct sqlResult *sr; - struct dyString *query = newDyString(512); + struct dyString *query = dyStringNew(512); // Null query will cause errAbort if there's a syntax error, no-op if OK. sqlDyStringPrintf(query, "SELECT 1 FROM %s WHERE 0 AND %s", fullTblName, constraints); sr = sqlGetResult(conn, query->string); dyStringFree(&query); sqlFreeResult(&sr); hFreeOrDisconnect(&conn); } if (tableId == NULL) tableId = ""; for (current = cgiVarList(); current != NULL; current = current->next) { /* Look for pattern variable associated with each field. */ snprintf(varName, sizeof(varName), "pat%s_", tableId); @@ -2946,31 +2946,31 @@ } } sqlFreeResult(&sr); } return(gotInfo); } void showItemCountFirstFew(struct sqlConnection *conn, int n) /* Show the item count and first n items of table. */ { char *track = getTrackName(); struct slName *tableList = hSplitTableNames(track); struct slName *tPtr = NULL; struct sqlResult *sr = NULL; -struct dyString *query = newDyString(256); +struct dyString *query = dyStringNew(256); char **row = NULL; char *table = getTableName(); int count = 0; int numberColumns = 0; int i = 0; #define NEEDED_UNTIL_GB_CDNA_INFO_CHANGE #ifdef NEEDED_UNTIL_GB_CDNA_INFO_CHANGE if (sameString(table, "mrna")) { struct slName *slNew = newSlName(table); slFreeList(&tableList); tableList = slNew; } #endif /* NEEDED_UNTIL_GB_CDNA_INFO_CHANGE */ @@ -3140,32 +3140,32 @@ else bedList = bedFilterListInRange(ct->bedList, bf, chrom, winStart, winEnd); bedFilterBatch(&bedList); gotResults = printTabbedBed(bedList, chosenFields, FALSE); bedFreeList(&bedList); if (! gotResults) printf("\n# No results returned from query.\n\n"); } void doTabSeparated(boolean allFields) { struct slName *chromList, *chromPtr; struct sqlConnection *conn; struct sqlResult *sr; -struct dyString *query = newDyString(512); -struct dyString *fieldSpec = newDyString(256); +struct dyString *query = dyStringNew(512); +struct dyString *fieldSpec = dyStringNew(256); struct hTableInfo *hti = NULL; char *table = getTableName(); char *db = getTableDb(); char *constraints; boolean gotResults; checkUserKeys(); saveChooseTableState(); saveChooseFieldsState(); saveOutputOptionsState(); saveIntersectOptionsState(); if (sameString(customTrackPseudoDb, db)) { doTabSeparatedCT(allFields); @@ -4056,31 +4056,31 @@ cgiMakeHiddenVar("table", getTableVar()); preserveConstraints(fullTableName, db, NULL); cgiContinueHiddenVar("position"); //#*** Really need to save this off to a local file! cgiContinueHiddenVar("tbUserKeys"); printf("<H4> Fields of %s: </H4>\n", getTableName()); descTable(TRUE); puts("</FORM>"); } void doGetStatsNonpositional() /* Print out statistics about nonpositional query results. */ { struct sqlConnection *conn; -struct dyString *query = newDyString(256); +struct dyString *query = dyStringNew(256); char *constraints; char *table = getTableName(); char *db = getTableDb(); int numRows; saveOutputOptionsState(); webStart(cart, "Table Browser: %s %s: %s", hOrganism(database),freezeName, statsPhase); checkTableExists(fullTableName); printf("<FORM ACTION=\"%s\" NAME=\"mainForm\" METHOD=\"%s\">\n\n", hgTextName(), httpFormMethod); cartSaveSession(cart); cgiMakeHiddenVar("db", database); cgiMakeHiddenVar("table", getTableVar()); @@ -4098,33 +4098,33 @@ puts("<HR>"); puts("<A HREF=\"/goldenPath/help/hgTextHelp.html#Stats\">" "<B>Help</B></A><P>"); printf("<H4> Your query on %s: </H4>\n", table); constraints = constrainFields(NULL); if ((constraints != NULL) && (constraints[0] == 0)) constraints = NULL; if (constraints != NULL) printf("Constraints on %s: %s<P>\n", table, constraints); else printf("No constraints selected on fields of %s.<P>\n", table); dyStringClear(query); -sqlDyStringPrintf(query, "select count(*) from %s%s%-s", table, - (constraints ? " where " : ""), - (constraints ? constraints : "")); +sqlDyStringPrintf(query, "select count(*) from %s", table); +if (constraints) + sqlDyStringPrintf(query, " where %-s", constraints); conn = hAllocOrConnect(db); numRows = sqlQuickNum(conn, query->string); hFreeOrDisconnect(&conn); printf("Number of rows in %s%s: %d<P>\n", table, constraints ? " matching constraints" : "", numRows); descForm(); webEnd(); } struct slName *getOrderedChromList() /* Put the _random's at the end, and break them into two lines. */ /* Also, put the alpha-name chroms after the numeric-name chroms. */ { struct slName *randList = NULL, *nonrList = NULL; @@ -4791,31 +4791,31 @@ int v1 = ptToInt(hel1->val); int v2 = ptToInt(hel2->val); int dif; dif = v2 - v1; if (dif == 0) dif = strcmp(hel1->name, hel2->name); return(dif); } void doGetHistogram() /* Print out a histogram for the text value of some field. */ { struct sqlConnection *conn; struct sqlResult *sr; -struct dyString *query = newDyString(256); +struct dyString *query = dyStringNew(256); struct hash *freqHash = newHash(16); struct hashEl *els, *el; struct slName *chromList, *chromPtr; struct hash *nameHash = newHash(18); struct slName *wildNames = NULL, *wild=NULL; char **row; char *words[5]; char *constraints; char *table = getTableName(); char *db = getTableDb(); char *keyStr = getUserKeys(); char *word; struct hTableInfo *hti = getHti(db, table); char *phase = cgiString("phase"); char *field;