EXERCISE 1 — Why find the column count, and the two methods ============================================================ WHY A UNION ATTACK MUST FIRST DETERMINE THE COLUMN COUNT: - UNION combines the rows of two SELECTs into one result set. SQL REQUIRES that both SELECTs return the SAME NUMBER OF COLUMNS (and compatible types). If the counts differ, the database raises an error and the union fails — you get nothing. - So before you can append your own SELECT, you must know how many columns the ORIGINAL query returns, so your injected UNION SELECT lists exactly that many. Step one of every union attack is finding this number. METHOD A — ORDER BY probing (query has 3 columns): Increase the ORDER BY index until it errors; the last working value = count. ' ORDER BY 1-- -> OK (sort by column 1 exists) ' ORDER BY 2-- -> OK ' ORDER BY 3-- -> OK ' ORDER BY 4-- -> ERROR ("Unknown column 4 in 'order clause'") The query orders by column position, so ORDER BY 4 fails because there is no 4th column. Last success was 3 -> THE QUERY HAS 3 COLUMNS. (Advantage: works even before you can craft a valid UNION, and a single failing index pinpoints the count.) METHOD B — UNION SELECT NULL probing (same query): Add NULLs until the UNION succeeds; the count that works = column count. ' UNION SELECT NULL-- -> ERROR (1 col vs 3 -> mismatch) ' UNION SELECT NULL,NULL-- -> ERROR (2 vs 3) ' UNION SELECT NULL,NULL,NULL-- -> SUCCESS (3 vs 3) -> 3 COLUMNS When the injected SELECT's column count matches, the union is valid and the page renders (possibly with an extra blank/NULL row). WHY NULL IS USED IN METHOD B: - NULL is TYPE-COMPATIBLE WITH EVERY column type (string, int, date, etc.). The other UNION requirement is that columns be type-compatible position by position; if you used, say, 'abc' or 1 in a position whose original column is a different type, you might get a TYPE error and not know whether the failure was due to COUNT or TYPE. - By filling every position with NULL, you remove the type variable entirely, so the ONLY thing that can make the union fail is the COLUMN COUNT. This ISOLATES the count question — a clean, unambiguous probe. (Once the count is known, you switch to placing real string markers per position to find a displayable TEXT column — Exercise 2.) ONE-LINE TAKEAWAY: UNION needs equal column counts, so first find the count: ORDER BY n until it errors, or UNION SELECT NULL,... until it works — NULL isolating count from type.