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/hgTracks/pubsTracks.c src/hg/hgTracks/pubsTracks.c index a5e8e15..a104feb 100644 --- src/hg/hgTracks/pubsTracks.c +++ src/hg/hgTracks/pubsTracks.c @@ -63,31 +63,32 @@ /* assignment of pubs classes to colors */ static struct hash* pubsClassColors = NULL; static void pubsParseClassColors() /* parse class colors from hgFixed.pubsClassColors into the hash pubsClassColors */ { if (pubsClassColors!=NULL) return; pubsClassColors = hashNew(0); struct sqlConnection *conn = hAllocConn("hgFixed"); if (!sqlTableExists(conn, "pubsClassColors")) { return; } -char *query = NOSQLINJ "SELECT class, rgbColor FROM pubsClassColors"; +char query[1024]; +sqlSafef(query, sizeof query, "SELECT class, rgbColor FROM pubsClassColors"); struct sqlResult *sr = sqlGetResult(conn, query); char **row = NULL; while ((row = sqlNextRow(sr)) != NULL) { char *class = row[0]; char *colStr = row[1]; // copied from genePredItemClassColor - is there no function for this? // convert comma sep rgb string to array char *rgbVals[5]; chopString(colStr, ",", rgbVals, sizeof(rgbVals)); struct rgbColor *rgb; AllocVar(rgb); rgb->r = (sqlUnsigned(rgbVals[0])); rgb->g = (sqlUnsigned(rgbVals[1])); rgb->b = (sqlUnsigned(rgbVals[2])); @@ -227,41 +228,30 @@ return; } char *articleTable = trackDbSettingClosestToHome(tg->tdb, "pubsArticleTable"); if(isEmpty(articleTable)) return; if (lf->extra != NULL) return; struct sqlConnection *conn = hAllocConn(database); struct pubsExtra* extra = pubsMakeExtra(tg, articleTable, conn, lf); lf->extra = extra; hFreeConn(&conn); } -static void sqlDyStringPrintfWithSep(struct dyString *ds, char* sep, char *format, ...) -/* Printf to end of dyString. Prefix with sep if dyString is not empty. */ -{ -if (ds->stringSize!=0) - dyStringAppend(ds, sep); -va_list args; -va_start(args, format); -vaSqlDyStringPrintfFrag(ds, format, args); -va_end(args); -} - struct hash* searchForKeywords(struct sqlConnection* conn, char *articleTable, char *keywords) /* return hash with the articleIds that contain a given keyword in the abstract/title/authors */ { if (isEmpty(keywords)) return NULL; char query[12000]; sqlSafef(query, sizeof(query), "SELECT articleId FROM %s WHERE " "MATCH (citation, title, authors, abstract) AGAINST ('%s' IN BOOLEAN MODE)", articleTable, keywords); //printf("query %s", query); struct slName *artIds = sqlQuickList(conn, query); if (artIds==NULL || slCount(artIds)==0) return NULL; // convert list to hash @@ -304,52 +294,60 @@ char **row; struct linkedFeatures *lfList = NULL; struct trackDb *tdb = tg->tdb; int scoreMin = atoi(trackDbSettingClosestToHomeOrDefault(tdb, "scoreMin", "0")); int scoreMax = atoi(trackDbSettingClosestToHomeOrDefault(tdb, "scoreMax", "1000")); boolean useItemRgb = bedItemRgb(tdb); char *extra = NULL; struct dyString *extraDy = dyStringNew(0); struct hash *articleIds = searchForKeywords(conn, articleTable, keywords); if (!sameWord(tg->table, "pubsBlat")) // new table schema: filter fields are on main bed table { if (isNotEmpty(yearFilter)) - sqlDyStringPrintfWithSep(extraDy, " AND ", " year >= '%s'", yearFilter); + { + if (dyStringLen(extraDy) > 0) + sqlDyStringPrintf(extraDy, " AND "); + sqlDyStringPrintf(extraDy, " year >= '%s'", yearFilter); + } if (isNotEmpty(publFilter)) - sqlDyStringPrintfWithSep(extraDy, " AND ", " publisher = '%s'", publFilter); + { + if (dyStringLen(extraDy) > 0) + sqlDyStringPrintf(extraDy, " AND "); + sqlDyStringPrintf(extraDy, " publisher = '%s'", publFilter); + } } else // old table schema, filter by doing a join on article table { if(isNotEmpty(yearFilter)) - sqlDyStringPrintfFrag(extraDy, "name IN (SELECT articleId FROM %s WHERE year>='%s')", articleTable, \ + sqlDyStringPrintf(extraDy, "name IN (SELECT articleId FROM %s WHERE year>='%s')", articleTable, \ yearFilter); } if (extraDy->stringSize > 0) extra = extraDy->string; else extra = NULL; int rowOffset = 0; struct sqlResult *sr = hExtendedRangeQuery(conn, tg->table, chromName, winStart, winEnd, extra, FALSE, NULL, &rowOffset); - freeDyString(&extraDy); + dyStringFree(&extraDy); while ((row = sqlNextRow(sr)) != NULL) { struct bed *bed = bedLoad12(row+rowOffset); if (articleIds==NULL || hashFindVal(articleIds, bed->name)) slAddHead(&lfList, bedMungToLinkedFeatures(&bed, tdb, 12, scoreMin, scoreMax, useItemRgb)); } sqlFreeResult(&sr); slReverse(&lfList); slSort(&lfList, linkedFeaturesCmp); tg->items = lfList; } hFreeConn(&conn); } @@ -445,40 +443,40 @@ /* make sure that mapItem is the bed->name field, not the itemName */ struct bed *bed = item; genericMapItem(tg, hvg, item, bed->name, bed->name, start, end, x, y, width, height); } static struct hash* pubsLookupSequences(struct track *tg, struct sqlConnection* conn, char *articleId, bool getSnippet) /* create a hash with a mapping annotId -> snippet or annotId -> shortSeq for an articleId*/ { struct dyString *dy = dyStringNew(LARGEBUF); char *sequenceTable = trackDbRequiredSetting(tg->tdb, "pubsSequenceTable"); // work around sql injection fix problem, suggested by galt sqlDyStringPrintf(dy, "SELECT annotId, "); if (getSnippet) - dyStringAppend(dy, "replace(replace(snippet, \"<B>\", \"\\n>>> \"), \"</B>\", \" <<<\\n\")" ); + sqlDyStringPrintf(dy, "replace(replace(snippet, \"<B>\", \"\\n>>> \"), \"</B>\", \" <<<\\n\")" ); else - dyStringAppend(dy, "concat(substr(sequence,1,4),\"...\",substr(sequence,-4))" ); + sqlDyStringPrintf(dy, "concat(substr(sequence,1,4),\"...\",substr(sequence,-4))" ); sqlDyStringPrintf(dy, " FROM %s WHERE articleId='%s' ", sequenceTable, articleId); // end sql injection fix struct hash *seqIdHash = sqlQuickHash(conn, dy->string); //freeMem(sequenceTable); // trackDbRequiredSetting returns a value in a hash, so do not free - freeDyString(&dy); + dyStringFree(&dy); return seqIdHash; } static char *pubsArticleDispId(struct track *tg, struct sqlConnection *conn, char *articleId) /* given an articleId, lookup author and year and create <author><year> label for it */ { char *dispLabel = NULL; char *articleTable = pubsArticleTable(tg); char query[LARGEBUF]; sqlSafef(query, sizeof(query), "SELECT firstAuthor, year FROM %s WHERE articleId = '%s'", articleTable, articleId); struct sqlResult *sr = sqlGetResult(conn, query); if (sr!=NULL) { char **row = NULL; @@ -500,31 +498,31 @@ // get articleId to filter on char *articleId = cartOptionalString(cart, PUBSFILTERNAME); if (articleId==NULL) return; struct sqlConnection *conn = hAllocConn(database); char *dispLabel = pubsArticleDispId(tg, conn, articleId); struct hash *idToSnip = pubsLookupSequences(tg, conn, articleId, TRUE); struct hash *idToSeq = pubsLookupSequences(tg, conn, articleId, FALSE); // change track label tg->longLabel = catTwoStrings("Individual matches for article ", dispLabel); // filter and load items for this articleId char where[256]; -safef(where, sizeof(where), " articleId=%s ", articleId); +sqlSafef(where, sizeof(where), " articleId='%s' ", articleId); int rowOffset = 0; struct sqlResult *sr = NULL; sr = hRangeQuery(conn, tg->table, chromName, winStart, winEnd, where, &rowOffset); struct linkedFeatures *lfList = NULL; char **row = NULL; while ((row = sqlNextRow(sr)) != NULL) { struct psl *psl = pslLoad(row+rowOffset); slAddHead(&lfList, lfFromPsl(psl, TRUE)); char *shortSeq = hashFindVal(idToSeq, lfList->name); char *snip = hashFindVal(idToSnip, lfList->name); struct pubsExtra *extra = needMem(sizeof(struct pubsExtra)); extra->mouseOver=snip;