1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
|
/**
* Copyright 2012,2016 Nick Galbreath
* nickg@client9.com
* BSD License -- see COPYING.txt for details
*
* https://libinjection.client9.com/
*
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include <stddef.h>
#include "libinjection.h"
#include "libinjection_sqli.h"
#include "libinjection_sqli_data.h"
#define LIBINJECTION_VERSION "3.9.2"
#define LIBINJECTION_SQLI_TOKEN_SIZE sizeof(((stoken_t*)(0))->val)
#define LIBINJECTION_SQLI_MAX_TOKENS 5
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#define CHAR_NULL '\0'
#define CHAR_SINGLE '\''
#define CHAR_DOUBLE '"'
#define CHAR_TICK '`'
/* faster than calling out to libc isdigit */
#define ISDIGIT(a) ((unsigned)((a) - '0') <= 9)
#if 0
#define FOLD_DEBUG printf("%d \t more=%d pos=%d left=%d\n", __LINE__, more, (int)pos, (int)left);
#else
#define FOLD_DEBUG
#endif
/*
* not making public just yet
*/
typedef enum {
TYPE_NONE = 0
, TYPE_KEYWORD = (int)'k'
, TYPE_UNION = (int)'U'
, TYPE_GROUP = (int)'B'
, TYPE_EXPRESSION = (int)'E'
, TYPE_SQLTYPE = (int)'t'
, TYPE_FUNCTION = (int)'f'
, TYPE_BAREWORD = (int)'n'
, TYPE_NUMBER = (int)'1'
, TYPE_VARIABLE = (int)'v'
, TYPE_STRING = (int)'s'
, TYPE_OPERATOR = (int)'o'
, TYPE_LOGIC_OPERATOR = (int)'&'
, TYPE_COMMENT = (int)'c'
, TYPE_COLLATE = (int)'A'
, TYPE_LEFTPARENS = (int)'('
, TYPE_RIGHTPARENS = (int)')' /* not used? */
, TYPE_LEFTBRACE = (int)'{'
, TYPE_RIGHTBRACE = (int)'}'
, TYPE_DOT = (int)'.'
, TYPE_COMMA = (int)','
, TYPE_COLON = (int)':'
, TYPE_SEMICOLON = (int)';'
, TYPE_TSQL = (int)'T' /* TSQL start */
, TYPE_UNKNOWN = (int)'?'
, TYPE_EVIL = (int)'X' /* unparsable, abort */
, TYPE_FINGERPRINT = (int)'F' /* not really a token */
, TYPE_BACKSLASH = (int)'\\'
} sqli_token_types;
/**
* Initializes parsing state
*
*/
static char flag2delim(int flag)
{
if (flag & FLAG_QUOTE_SINGLE) {
return CHAR_SINGLE;
} else if (flag & FLAG_QUOTE_DOUBLE) {
return CHAR_DOUBLE;
} else {
return CHAR_NULL;
}
}
/* memchr2 finds a string of 2 characters inside another string
* This a specialized version of "memmem" or "memchr".
* 'memmem' doesn't exist on all platforms
*
* Porting notes: this is just a special version of
* astring.find("AB")
*
*/
static const char *
memchr2(const char *haystack, size_t haystack_len, char c0, char c1)
{
const char *cur = haystack;
const char *last = haystack + haystack_len - 1;
if (haystack_len < 2) {
return NULL;
}
while (cur < last) {
/* safe since cur < len - 1 always */
if (cur[0] == c0 && cur[1] == c1) {
return cur;
}
cur += 1;
}
return NULL;
}
/**
* memmem might not exist on some systems
*/
static const char *
my_memmem(const char* haystack, size_t hlen, const char* needle, size_t nlen)
{
const char* cur;
const char* last;
assert(haystack);
assert(needle);
assert(nlen > 1);
last = haystack + hlen - nlen;
for (cur = haystack; cur <= last; ++cur) {
if (cur[0] == needle[0] && memcmp(cur, needle, nlen) == 0) {
return cur;
}
}
return NULL;
}
/** Find largest string containing certain characters.
*
* C Standard library 'strspn' only works for 'c-strings' (null terminated)
* This works on arbitrary length.
*
* Performance notes:
* not critical
*
* Porting notes:
* if accept is 'ABC', then this function would be similar to
* a_regexp.match(a_str, '[ABC]*'),
*/
static size_t
strlenspn(const char *s, size_t len, const char *accept)
{
size_t i;
for (i = 0; i < len; ++i) {
/* likely we can do better by inlining this function
* but this works for now
*/
if (strchr(accept, s[i]) == NULL) {
return i;
}
}
return len;
}
static size_t
strlencspn(const char *s, size_t len, const char *accept)
{
size_t i;
for (i = 0; i < len; ++i) {
/* likely we can do better by inlining this function
* but this works for now
*/
if (strchr(accept, s[i]) != NULL) {
return i;
}
}
return len;
}
static int char_is_white(char ch) {
/* ' ' space is 0x32
'\t 0x09 \011 horizontal tab
'\n' 0x0a \012 new line
'\v' 0x0b \013 vertical tab
'\f' 0x0c \014 new page
'\r' 0x0d \015 carriage return
0x00 \000 null (oracle)
0xa0 \240 is Latin-1
*/
return strchr(" \t\n\v\f\r\240\000", ch) != NULL;
}
/* DANGER DANGER
* This is -very specialized function-
*
* this compares a ALL_UPPER CASE C STRING
* with a *arbitrary memory* + length
*
* Sane people would just make a copy, up-case
* and use a hash table.
*
* Required since libc version uses the current locale
* and is much slower.
*/
static int cstrcasecmp(const char *a, const char *b, size_t n)
{
char cb;
for (; n > 0; a++, b++, n--) {
cb = *b;
if (cb >= 'a' && cb <= 'z') {
cb -= 0x20;
}
if (*a != cb) {
return *a - cb;
} else if (*a == '\0') {
return -1;
}
}
return (*a == 0) ? 0 : 1;
}
/**
* Case sensitive string compare.
* Here only to make code more readable
*/
static int streq(const char *a, const char *b)
{
return strcmp(a, b) == 0;
}
/**
*
*
*
* Porting Notes:
* given a mapping/hash of string to char
* this is just
* typecode = mapping[key.upper()]
*/
static char bsearch_keyword_type(const char *key, size_t len,
const keyword_t * keywords, size_t numb)
{
size_t pos;
size_t left = 0;
size_t right = numb - 1;
while (left < right) {
pos = (left + right) >> 1;
/* arg0 = upper case only, arg1 = mixed case */
if (cstrcasecmp(keywords[pos].word, key, len) < 0) {
left = pos + 1;
} else {
right = pos;
}
}
if ((left == right) && cstrcasecmp(keywords[left].word, key, len) == 0) {
return keywords[left].type;
} else {
return CHAR_NULL;
}
}
static char is_keyword(const char* key, size_t len)
{
return bsearch_keyword_type(key, len, sql_keywords, sql_keywords_sz);
}
/* st_token methods
*
* The following functions manipulates the stoken_t type
*
*
*/
static void st_clear(stoken_t * st)
{
memset(st, 0, sizeof(stoken_t));
}
static void st_assign_char(stoken_t * st, const char stype, size_t pos, size_t len,
const char value)
{
/* done to eliminate unused warning */
(void)len;
st->type = (char) stype;
st->pos = pos;
st->len = 1;
st->val[0] = value;
st->val[1] = CHAR_NULL;
}
static void st_assign(stoken_t * st, const char stype,
size_t pos, size_t len, const char* value)
{
const size_t MSIZE = LIBINJECTION_SQLI_TOKEN_SIZE;
size_t last = len < MSIZE ? len : (MSIZE - 1);
st->type = (char) stype;
st->pos = pos;
st->len = last;
memcpy(st->val, value, last);
st->val[last] = CHAR_NULL;
}
static void st_copy(stoken_t * dest, const stoken_t * src)
{
memcpy(dest, src, sizeof(stoken_t));
}
static int st_is_arithmetic_op(const stoken_t* st)
{
const char ch = st->val[0];
return (st->type == TYPE_OPERATOR && st->len == 1 &&
(ch == '*' || ch == '/' || ch == '-' || ch == '+' || ch == '%'));
}
static int st_is_unary_op(const stoken_t * st)
{
const char* str = st->val;
const size_t len = st->len;
if (st->type != TYPE_OPERATOR) {
return FALSE;
}
switch (len) {
case 1:
return *str == '+' || *str == '-' || *str == '!' || *str == '~';
case 2:
return str[0] == '!' && str[1] == '!';
case 3:
return cstrcasecmp("NOT", str, 3) == 0;
default:
return FALSE;
}
}
/* Parsers
*
*
*/
static size_t parse_white(struct libinjection_sqli_state * sf)
{
return sf->pos + 1;
}
static size_t parse_operator1(struct libinjection_sqli_state * sf)
{
const char *cs = sf->s;
size_t pos = sf->pos;
st_assign_char(sf->current, TYPE_OPERATOR, pos, 1, cs[pos]);
return pos + 1;
}
static size_t parse_other(struct libinjection_sqli_state * sf)
{
const char *cs = sf->s;
size_t pos = sf->pos;
st_assign_char(sf->current, TYPE_UNKNOWN, pos, 1, cs[pos]);
return pos + 1;
}
static size_t parse_char(struct libinjection_sqli_state * sf)
{
const char *cs = sf->s;
size_t pos = sf->pos;
st_assign_char(sf->current, cs[pos], pos, 1, cs[pos]);
return pos + 1;
}
static size_t parse_eol_comment(struct libinjection_sqli_state * sf)
{
const char *cs = sf->s;
const size_t slen = sf->slen;
size_t pos = sf->pos;
const char *endpos =
(const char *) memchr((const void *) (cs + pos), '\n', slen - pos);
if (endpos == NULL) {
st_assign(sf->current, TYPE_COMMENT, pos, slen - pos, cs + pos);
return slen;
} else {
st_assign(sf->current, TYPE_COMMENT, pos, (size_t)(endpos - cs) - pos, cs + pos);
return (size_t)((endpos - cs) + 1);
}
}
/** In ANSI mode, hash is an operator
* In MYSQL mode, it's a EOL comment like '--'
*/
static size_t parse_hash(struct libinjection_sqli_state * sf)
{
sf->stats_comment_hash += 1;
if (sf->flags & FLAG_SQL_MYSQL) {
sf->stats_comment_hash += 1;
return parse_eol_comment(sf);
} else {
st_assign_char(sf->current, TYPE_OPERATOR, sf->pos, 1, '#');
return sf->pos + 1;
}
}
static size_t parse_dash(struct libinjection_sqli_state * sf)
{
const char *cs = sf->s;
const size_t slen = sf->slen;
size_t pos = sf->pos;
/*
* five cases
* 1) --[white] this is always a SQL comment
* 2) --[EOF] this is a comment
* 3) --[notwhite] in MySQL this is NOT a comment but two unary operators
* 4) --[notwhite] everyone else thinks this is a comment
* 5) -[not dash] '-' is a unary operator
*/
if (pos + 2 < slen && cs[pos + 1] == '-' && char_is_white(cs[pos+2]) ) {
return parse_eol_comment(sf);
} else if (pos +2 == slen && cs[pos + 1] == '-') {
return parse_eol_comment(sf);
} else if (pos + 1 < slen && cs[pos + 1] == '-' && (sf->flags & FLAG_SQL_ANSI)) {
/* --[not-white] not-white case:
*
*/
sf->stats_comment_ddx += 1;
return parse_eol_comment(sf);
} else {
st_assign_char(sf->current, TYPE_OPERATOR, pos, 1, '-');
return pos + 1;
}
}
/** This detects MySQL comments, comments that
* start with /x! We just ban these now but
* previously we attempted to parse the inside
*
* For reference:
* the form of /x![anything]x/ or /x!12345[anything] x/
*
* Mysql 3 (maybe 4), allowed this:
* /x!0selectx/ 1;
* where 0 could be any number.
*
* The last version of MySQL 3 was in 2003.
* It is unclear if the MySQL 3 syntax was allowed
* in MySQL 4. The last version of MySQL 4 was in 2008
*
*/
static size_t is_mysql_comment(const char *cs, const size_t len, size_t pos)
{
/* so far...
* cs[pos] == '/' && cs[pos+1] == '*'
*/
if (pos + 2 >= len) {
/* not a mysql comment */
return 0;
}
if (cs[pos + 2] != '!') {
/* not a mysql comment */
return 0;
}
/*
* this is a mysql comment
* got "/x!"
*/
return 1;
}
static size_t parse_slash(struct libinjection_sqli_state * sf)
{
const char* ptr;
size_t clen;
const char *cs = sf->s;
const size_t slen = sf->slen;
size_t pos = sf->pos;
const char* cur = cs + pos;
char ctype = TYPE_COMMENT;
size_t pos1 = pos + 1;
if (pos1 == slen || cs[pos1] != '*') {
return parse_operator1(sf);
}
/*
* skip over initial '/x'
*/
ptr = memchr2(cur + 2, slen - (pos + 2), '*', '/');
/*
* (ptr == NULL) causes false positive in cppcheck 1.61
* casting to type seems to fix it
*/
if (ptr == (const char*) NULL) {
/* till end of line */
clen = slen - pos;
} else {
clen = (size_t)(ptr + 2 - cur);
}
/*
* postgresql allows nested comments which makes
* this is incompatible with parsing so
* if we find a '/x' inside the coment, then
* make a new token.
*
* Also, Mysql's "conditional" comments for version
* are an automatic black ban!
*/
if (memchr2(cur + 2, (size_t)(ptr - (cur + 1)), '/', '*') != NULL) {
ctype = TYPE_EVIL;
} else if (is_mysql_comment(cs, slen, pos)) {
ctype = TYPE_EVIL;
}
st_assign(sf->current, ctype, pos, clen, cs + pos);
return pos + clen;
}
static size_t parse_backslash(struct libinjection_sqli_state * sf)
{
const char *cs = sf->s;
const size_t slen = sf->slen;
size_t pos = sf->pos;
/*
* Weird MySQL alias for NULL, "\N" (capital N only)
*/
if (pos + 1 < slen && cs[pos +1] == 'N') {
st_assign(sf->current, TYPE_NUMBER, pos, 2, cs + pos);
return pos + 2;
} else {
st_assign_char(sf->current, TYPE_BACKSLASH, pos, 1, cs[pos]);
return pos + 1;
}
}
static size_t parse_operator2(struct libinjection_sqli_state * sf)
{
char ch;
const char *cs = sf->s;
const size_t slen = sf->slen;
size_t pos = sf->pos;
if (pos + 1 >= slen) {
return parse_operator1(sf);
}
if (pos + 2 < slen &&
cs[pos] == '<' &&
cs[pos + 1] == '=' &&
cs[pos + 2] == '>') {
/*
* special 3-char operator
*/
st_assign(sf->current, TYPE_OPERATOR, pos, 3, cs + pos);
return pos + 3;
}
ch = sf->lookup(sf, LOOKUP_OPERATOR, cs + pos, 2);
if (ch != CHAR_NULL) {
st_assign(sf->current, ch, pos, 2, cs+pos);
return pos + 2;
}
/*
* not an operator.. what to do with the two
* characters we got?
*/
if (cs[pos] == ':') {
/* ':' is not an operator */
st_assign(sf->current, TYPE_COLON, pos, 1, cs+pos);
return pos + 1;
} else {
/*
* must be a single char operator
*/
return parse_operator1(sf);
}
}
/*
* Ok! " \" " one backslash = escaped!
* " \\" " two backslash = not escaped!
* "\\\" " three backslash = escaped!
*/
static int is_backslash_escaped(const char* end, const char* start)
{
const char* ptr;
for (ptr = end; ptr >= start; ptr--) {
if (*ptr != '\\') {
break;
}
}
/* if number of backslashes is odd, it is escaped */
return (end - ptr) & 1;
}
static size_t is_double_delim_escaped(const char* cur, const char* end)
{
return ((cur + 1) < end) && *(cur+1) == *cur;
}
/* Look forward for doubling of delimiter
*
* case 'foo''bar' --> foo''bar
*
* ending quote isn't duplicated (i.e. escaped)
* since it's the wrong char or EOL
*
*/
static size_t parse_string_core(const char *cs, const size_t len, size_t pos,
stoken_t * st, char delim, size_t offset)
{
/*
* offset is to skip the perhaps first quote char
*/
const char *qpos =
(const char *) memchr((const void *) (cs + pos + offset), delim,
len - pos - offset);
/*
* then keep string open/close info
*/
if (offset > 0) {
/*
* this is real quote
*/
st->str_open = delim;
} else {
/*
* this was a simulated quote
*/
st->str_open = CHAR_NULL;
}
while (TRUE) {
if (qpos == NULL) {
/*
* string ended with no trailing quote
* assign what we have
*/
st_assign(st, TYPE_STRING, pos + offset, len - pos - offset, cs + pos + offset);
st->str_close = CHAR_NULL;
return len;
} else if ( is_backslash_escaped(qpos - 1, cs + pos + offset)) {
/* keep going, move ahead one character */
qpos =
(const char *) memchr((const void *) (qpos + 1), delim,
(size_t)((cs + len) - (qpos + 1)));
continue;
} else if (is_double_delim_escaped(qpos, cs + len)) {
/* keep going, move ahead two characters */
qpos =
(const char *) memchr((const void *) (qpos + 2), delim,
(size_t)((cs + len) - (qpos + 2)));
continue;
} else {
/* hey it's a normal string */
st_assign(st, TYPE_STRING, pos + offset,
(size_t)(qpos - (cs + pos + offset)), cs + pos + offset);
st->str_close = delim;
return (size_t)(qpos - cs + 1);
}
}
}
/**
* Used when first char is a ' or "
*/
static size_t parse_string(struct libinjection_sqli_state * sf)
{
const char *cs = sf->s;
const size_t slen = sf->slen;
size_t pos = sf->pos;
/*
* assert cs[pos] == single or double quote
*/
return parse_string_core(cs, slen, pos, sf->current, cs[pos], 1);
}
/**
* Used when first char is:
* N or n: mysql "National Character set"
* E : psql "Escaped String"
*/
static size_t parse_estring(struct libinjection_sqli_state * sf)
{
const char *cs = sf->s;
const size_t slen = sf->slen;
size_t pos = sf->pos;
if (pos + 2 >= slen || cs[pos+1] != CHAR_SINGLE) {
return parse_word(sf);
}
return parse_string_core(cs, slen, pos, sf->current, CHAR_SINGLE, 2);
}
static size_t parse_ustring(struct libinjection_sqli_state * sf)
{
const char *cs = sf->s;
size_t slen = sf->slen;
size_t pos = sf->pos;
if (pos + 2 < slen && cs[pos+1] == '&' && cs[pos+2] == '\'') {
sf->pos += 2;
pos = parse_string(sf);
sf->current->str_open = 'u';
if (sf->current->str_close == '\'') {
sf->current->str_close = 'u';
}
return pos;
} else {
return parse_word(sf);
}
}
static size_t parse_qstring_core(struct libinjection_sqli_state * sf, size_t offset)
{
char ch;
const char *strend;
const char *cs = sf->s;
size_t slen = sf->slen;
size_t pos = sf->pos + offset;
/* if we are already at end of string..
if current char is not q or Q
if we don't have 2 more chars
if char2 != a single quote
then, just treat as word
*/
if (pos >= slen ||
(cs[pos] != 'q' && cs[pos] != 'Q') ||
pos + 2 >= slen ||
cs[pos + 1] != '\'') {
return parse_word(sf);
}
ch = cs[pos + 2];
/* the ch > 127 is un-needed since
* we assume char is signed
*/
if (ch < 33 /* || ch > 127 */) {
return parse_word(sf);
}
switch (ch) {
case '(' : ch = ')'; break;
case '[' : ch = ']'; break;
case '{' : ch = '}'; break;
case '<' : ch = '>'; break;
}
strend = memchr2(cs + pos + 3, slen - pos - 3, ch, '\'');
if (strend == NULL) {
st_assign(sf->current, TYPE_STRING, pos + 3, slen - pos - 3, cs + pos + 3);
sf->current->str_open = 'q';
sf->current->str_close = CHAR_NULL;
return slen;
} else {
st_assign(sf->current, TYPE_STRING, pos + 3, (size_t)(strend - cs) - pos - 3, cs + pos + 3);
sf->current->str_open = 'q';
sf->current->str_close = 'q';
return (size_t)(strend - cs + 2);
}
}
/*
* Oracle's q string
*/
static size_t parse_qstring(struct libinjection_sqli_state * sf)
{
return parse_qstring_core(sf, 0);
}
/*
* mysql's N'STRING' or
* ... Oracle's nq string
*/
static size_t parse_nqstring(struct libinjection_sqli_state * sf)
{
size_t slen = sf->slen;
size_t pos = sf->pos;
if (pos + 2 < slen && sf->s[pos+1] == CHAR_SINGLE) {
return parse_estring(sf);
}
return parse_qstring_core(sf, 1);
}
/*
* binary literal string
* re: [bB]'[01]*'
*/
static size_t parse_bstring(struct libinjection_sqli_state *sf)
{
size_t wlen;
const char *cs = sf->s;
size_t pos = sf->pos;
size_t slen = sf->slen;
/* need at least 2 more characters
* if next char isn't a single quote, then
* continue as normal word
*/
if (pos + 2 >= slen || cs[pos+1] != '\'') {
return parse_word(sf);
}
wlen = strlenspn(cs + pos + 2, sf->slen - pos - 2, "01");
if (pos + 2 + wlen >= slen || cs[pos + 2 + wlen] != '\'') {
return parse_word(sf);
}
st_assign(sf->current, TYPE_NUMBER, pos, wlen + 3, cs + pos);
return pos + 2 + wlen + 1;
}
/*
* hex literal string
* re: [xX]'[0123456789abcdefABCDEF]*'
* mysql has requirement of having EVEN number of chars,
* but pgsql does not
*/
static size_t parse_xstring(struct libinjection_sqli_state *sf)
{
size_t wlen;
const char *cs = sf->s;
size_t pos = sf->pos;
size_t slen = sf->slen;
/* need at least 2 more characters
* if next char isn't a single quote, then
* continue as normal word
*/
if (pos + 2 >= slen || cs[pos+1] != '\'') {
return parse_word(sf);
}
wlen = strlenspn(cs + pos + 2, sf->slen - pos - 2, "0123456789ABCDEFabcdef");
if (pos + 2 + wlen >= slen || cs[pos + 2 + wlen] != '\'') {
return parse_word(sf);
}
st_assign(sf->current, TYPE_NUMBER, pos, wlen + 3, cs + pos);
return pos + 2 + wlen + 1;
}
/**
* This handles MS SQLSERVER bracket words
* http://stackoverflow.com/questions/3551284/sql-serverwhat-do-brackets-mean-around-column-name
*
*/
static size_t parse_bword(struct libinjection_sqli_state * sf)
{
const char *cs = sf->s;
size_t pos = sf->pos;
const char* endptr = (const char*) memchr(cs + pos, ']', sf->slen - pos);
if (endptr == NULL) {
st_assign(sf->current, TYPE_BAREWORD, pos, sf->slen - pos, cs + pos);
return sf->slen;
} else {
st_assign(sf->current, TYPE_BAREWORD, pos, (size_t)(endptr - cs) - pos + 1, cs + pos);
return (size_t)((endptr - cs) + 1);
}
}
static size_t parse_word(struct libinjection_sqli_state * sf)
{
char ch;
char delim;
size_t i;
const char *cs = sf->s;
size_t pos = sf->pos;
size_t wlen = strlencspn(cs + pos, sf->slen - pos,
" []{}<>:\\?=@!#~+-*/&|^%(),';\t\n\v\f\r\"\240\000");
st_assign(sf->current, TYPE_BAREWORD, pos, wlen, cs + pos);
/* now we need to look inside what we good for "." and "`"
* and see if what is before is a keyword or not
*/
for (i =0; i < sf->current->len; ++i) {
delim = sf->current->val[i];
if (delim == '.' || delim == '`') {
ch = sf->lookup(sf, LOOKUP_WORD, sf->current->val, i);
if (ch != TYPE_NONE && ch != TYPE_BAREWORD) {
/* needed for swig */
st_clear(sf->current);
/*
* we got something like "SELECT.1"
* or SELECT`column`
*/
st_assign(sf->current, ch, pos, i, cs + pos);
return pos + i;
}
}
}
/*
* do normal lookup with word including '.'
*/
if (wlen < LIBINJECTION_SQLI_TOKEN_SIZE) {
ch = sf->lookup(sf, LOOKUP_WORD, sf->current->val, wlen);
if (ch == CHAR_NULL) {
ch = TYPE_BAREWORD;
}
sf->current->type = ch;
}
return pos + wlen;
}
/* MySQL backticks are a cross between string and
* and a bare word.
*
*/
static size_t parse_tick(struct libinjection_sqli_state* sf)
{
size_t pos = parse_string_core(sf->s, sf->slen, sf->pos, sf->current, CHAR_TICK, 1);
/* we could check to see if start and end of
* of string are both "`", i.e. make sure we have
* matching set. `foo` vs. `foo
* but I don't think it matters much
*/
/* check value of string to see if it's a keyword,
* function, operator, etc
*/
char ch = sf->lookup(sf, LOOKUP_WORD, sf->current->val, sf->current->len);
if (ch == TYPE_FUNCTION) {
/* if it's a function, then convert token */
sf->current->type = TYPE_FUNCTION;
} else {
/* otherwise it's a 'n' type -- mysql treats
* everything as a bare word
*/
sf->current->type = TYPE_BAREWORD;
}
return pos;
}
static size_t parse_var(struct libinjection_sqli_state * sf)
{
size_t xlen;
const char *cs = sf->s;
const size_t slen = sf->slen;
size_t pos = sf->pos + 1;
/*
* var_count is only used to reconstruct
* the input. It counts the number of '@'
* seen 0 in the case of NULL, 1 or 2
*/
/*
* move past optional other '@'
*/
if (pos < slen && cs[pos] == '@') {
pos += 1;
sf->current->count = 2;
} else {
sf->current->count = 1;
}
/*
* MySQL allows @@`version`
*/
if (pos < slen) {
if (cs[pos] == '`') {
sf->pos = pos;
pos = parse_tick(sf);
sf->current->type = TYPE_VARIABLE;
return pos;
} else if (cs[pos] == CHAR_SINGLE || cs[pos] == CHAR_DOUBLE) {
sf->pos = pos;
pos = parse_string(sf);
sf->current->type = TYPE_VARIABLE;
return pos;
}
}
xlen = strlencspn(cs + pos, slen - pos,
" <>:\\?=@!#~+-*/&|^%(),';\t\n\v\f\r'`\"");
if (xlen == 0) {
st_assign(sf->current, TYPE_VARIABLE, pos, 0, cs + pos);
return pos;
} else {
st_assign(sf->current, TYPE_VARIABLE, pos, xlen, cs + pos);
return pos + xlen;
}
}
static size_t parse_money(struct libinjection_sqli_state *sf)
{
size_t xlen;
const char* strend;
const char *cs = sf->s;
const size_t slen = sf->slen;
size_t pos = sf->pos;
if (pos + 1 == slen) {
/* end of line */
st_assign_char(sf->current, TYPE_BAREWORD, pos, 1, '$');
return slen;
}
/*
* $1,000.00 or $1.000,00 ok!
* This also parses $....,,,111 but that's ok
*/
xlen = strlenspn(cs + pos + 1, slen - pos - 1, "0123456789.,");
if (xlen == 0) {
if (cs[pos + 1] == '$') {
/* we have $$ .. find ending $$ and make string */
strend = memchr2(cs + pos + 2, slen - pos -2, '$', '$');
if (strend == NULL) {
/* fell off edge */
st_assign(sf->current, TYPE_STRING, pos + 2, slen - (pos + 2), cs + pos + 2);
sf->current->str_open = '$';
sf->current->str_close = CHAR_NULL;
return slen;
} else {
st_assign(sf->current, TYPE_STRING, pos + 2,
(size_t)(strend - (cs + pos + 2)), cs + pos + 2);
sf->current->str_open = '$';
sf->current->str_close = '$';
return (size_t)(strend - cs + 2);
}
} else {
/* ok it's not a number or '$$', but maybe it's pgsql "$ quoted strings" */
xlen = strlenspn(cs + pos + 1, slen - pos - 1, "abcdefghjiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
if (xlen == 0) {
/* hmm it's "$" _something_ .. just add $ and keep going*/
st_assign_char(sf->current, TYPE_BAREWORD, pos, 1, '$');
return pos + 1;
}
/* we have $foobar????? */
/* is it $foobar$ */
if (pos + xlen + 1 == slen || cs[pos+xlen+1] != '$') {
/* not $foobar$, or fell off edge */
st_assign_char(sf->current, TYPE_BAREWORD, pos, 1, '$');
return pos + 1;
}
/* we have $foobar$ ... find it again */
strend = my_memmem(cs+xlen+2, slen - (pos+xlen+2), cs + pos, xlen+2);
if (strend == NULL || ((size_t)(strend - cs) < (pos+xlen+2))) {
/* fell off edge */
st_assign(sf->current, TYPE_STRING, pos+xlen+2, slen - pos - xlen - 2, cs+pos+xlen+2);
sf->current->str_open = '$';
sf->current->str_close = CHAR_NULL;
return slen;
} else {
/* got one */
st_assign(sf->current, TYPE_STRING, pos+xlen+2,
(size_t)(strend - (cs + pos + xlen + 2)), cs+pos+xlen+2);
sf->current->str_open = '$';
sf->current->str_close = '$';
return (size_t)((strend + xlen + 2) - cs);
}
}
} else if (xlen == 1 && cs[pos + 1] == '.') {
/* $. should parsed as a word */
return parse_word(sf);
} else {
st_assign(sf->current, TYPE_NUMBER, pos, 1 + xlen, cs + pos);
return pos + 1 + xlen;
}
}
static size_t parse_number(struct libinjection_sqli_state * sf)
{
size_t xlen;
size_t start;
const char* digits = NULL;
const char *cs = sf->s;
const size_t slen = sf->slen;
size_t pos = sf->pos;
int have_e = 0;
int have_exp = 0;
/* cs[pos] == '0' has 1/10 chance of being true,
* while pos+1< slen is almost always true
*/
if (cs[pos] == '0' && pos + 1 < slen) {
if (cs[pos + 1] == 'X' || cs[pos + 1] == 'x') {
digits = "0123456789ABCDEFabcdef";
} else if (cs[pos + 1] == 'B' || cs[pos + 1] == 'b') {
digits = "01";
}
if (digits) {
xlen = strlenspn(cs + pos + 2, slen - pos - 2, digits);
if (xlen == 0) {
st_assign(sf->current, TYPE_BAREWORD, pos, 2, cs + pos);
return pos + 2;
} else {
st_assign(sf->current, TYPE_NUMBER, pos, 2 + xlen, cs + pos);
return pos + 2 + xlen;
}
}
}
start = pos;
while (pos < slen && ISDIGIT(cs[pos])) {
pos += 1;
}
if (pos < slen && cs[pos] == '.') {
pos += 1;
while (pos < slen && ISDIGIT(cs[pos])) {
pos += 1;
}
if (pos - start == 1) {
/* only one character read so far */
st_assign_char(sf->current, TYPE_DOT, start, 1, '.');
return pos;
}
}
if (pos < slen) {
if (cs[pos] == 'E' || cs[pos] == 'e') {
have_e = 1;
pos += 1;
if (pos < slen && (cs[pos] == '+' || cs[pos] == '-')) {
pos += 1;
}
while (pos < slen && ISDIGIT(cs[pos])) {
have_exp = 1;
pos += 1;
}
}
}
/* oracle's ending float or double suffix
* http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements003.htm#i139891
*/
if (pos < slen && (cs[pos] == 'd' || cs[pos] == 'D' || cs[pos] == 'f' || cs[pos] == 'F')) {
if (pos + 1 == slen) {
/* line ends evaluate "... 1.2f$" as '1.2f' */
pos += 1;
} else if ((char_is_white(cs[pos+1]) || cs[pos+1] == ';')) {
/*
* easy case, evaluate "... 1.2f ... as '1.2f'
*/
pos += 1;
} else if (cs[pos+1] == 'u' || cs[pos+1] == 'U') {
/*
* a bit of a hack but makes '1fUNION' parse as '1f UNION'
*/
pos += 1;
} else {
/* it's like "123FROM" */
/* parse as "123" only */
}
}
if (have_e == 1 && have_exp == 0) {
/* very special form of
* "1234.e"
* "10.10E"
* ".E"
* this is a WORD not a number!! */
st_assign(sf->current, TYPE_BAREWORD, start, pos - start, cs + start);
} else {
st_assign(sf->current, TYPE_NUMBER, start, pos - start, cs + start);
}
return pos;
}
/*
* API to return version. This allows us to increment the version
* without having to regenerated the SWIG (or other binding) in minor
* releases.
*/
const char* libinjection_version()
{
return LIBINJECTION_VERSION;
}
int libinjection_sqli_tokenize(struct libinjection_sqli_state * sf)
{
pt2Function fnptr;
size_t *pos = &sf->pos;
stoken_t *current = sf->current;
const char *s = sf->s;
const size_t slen = sf->slen;
if (slen == 0) {
return FALSE;
}
st_clear(current);
sf->current = current;
/*
* if we are at beginning of string
* and in single-quote or double quote mode
* then pretend the input starts with a quote
*/
if (*pos == 0 && (sf->flags & (FLAG_QUOTE_SINGLE | FLAG_QUOTE_DOUBLE))) {
*pos = parse_string_core(s, slen, 0, current, flag2delim(sf->flags), 0);
sf->stats_tokens += 1;
return TRUE;
}
while (*pos < slen) {
/*
* get current character
*/
const unsigned char ch = (unsigned char) (s[*pos]);
/*
* look up the parser, and call it
*
* Porting Note: this is mapping of char to function
* charparsers[ch]()
*/
fnptr = char_parse_map[ch];
*pos = (*fnptr) (sf);
/*
*
*/
if (current->type != CHAR_NULL) {
sf->stats_tokens += 1;
return TRUE;
}
}
return FALSE;
}
void libinjection_sqli_init(struct libinjection_sqli_state * sf, const char *s, size_t len, int flags)
{
if (flags == 0) {
flags = FLAG_QUOTE_NONE | FLAG_SQL_ANSI;
}
memset(sf, 0, sizeof(struct libinjection_sqli_state));
sf->s = s;
sf->slen = len;
sf->lookup = libinjection_sqli_lookup_word;
sf->userdata = 0;
sf->flags = flags;
sf->current = &(sf->tokenvec[0]);
}
void libinjection_sqli_reset(struct libinjection_sqli_state * sf, int flags)
{
void *userdata = sf->userdata;
ptr_lookup_fn lookup = sf->lookup;;
if (flags == 0) {
flags = FLAG_QUOTE_NONE | FLAG_SQL_ANSI;
}
libinjection_sqli_init(sf, sf->s, sf->slen, flags);
sf->lookup = lookup;
sf->userdata = userdata;
}
void libinjection_sqli_callback(struct libinjection_sqli_state * sf, ptr_lookup_fn fn, void* userdata)
{
if (fn == NULL) {
sf->lookup = libinjection_sqli_lookup_word;
sf->userdata = (void*)(NULL);
} else {
sf->lookup = fn;
sf->userdata = userdata;
}
}
/** See if two tokens can be merged since they are compound SQL phrases.
*
* This takes two tokens, and, if they are the right type,
* merges their values together. Then checks to see if the
* new value is special using the PHRASES mapping.
*
* Example: "UNION" + "ALL" ==> "UNION ALL"
*
* C Security Notes: this is safe to use C-strings (null-terminated)
* since the types involved by definition do not have embedded nulls
* (e.g. there is no keyword with embedded null)
*
* Porting Notes: since this is C, it's oddly complicated.
* This is just: multikeywords[token.value + ' ' + token2.value]
*
*/
static int syntax_merge_words(struct libinjection_sqli_state * sf,stoken_t * a, stoken_t * b)
{
size_t sz1;
size_t sz2;
size_t sz3;
char tmp[LIBINJECTION_SQLI_TOKEN_SIZE];
char ch;
/* first token is of right type? */
if (!
(a->type == TYPE_KEYWORD ||
a->type == TYPE_BAREWORD ||
a->type == TYPE_OPERATOR ||
a->type == TYPE_UNION ||
a->type == TYPE_FUNCTION ||
a->type == TYPE_EXPRESSION ||
a->type == TYPE_TSQL ||
a->type == TYPE_SQLTYPE)) {
return FALSE;
}
if (!
(b->type == TYPE_KEYWORD ||
b->type == TYPE_BAREWORD ||
b->type == TYPE_OPERATOR ||
b->type == TYPE_UNION ||
b->type == TYPE_FUNCTION ||
b->type == TYPE_EXPRESSION ||
b->type == TYPE_TSQL ||
b->type == TYPE_SQLTYPE ||
b->type == TYPE_LOGIC_OPERATOR)) {
return FALSE;
}
sz1 = a->len;
sz2 = b->len;
sz3 = sz1 + sz2 + 1; /* +1 for space in the middle */
if (sz3 >= LIBINJECTION_SQLI_TOKEN_SIZE) { /* make sure there is room for ending null */
return FALSE;
}
/*
* oddly annoying last.val + ' ' + current.val
*/
memcpy(tmp, a->val, sz1);
tmp[sz1] = ' ';
memcpy(tmp + sz1 + 1, b->val, sz2);
tmp[sz3] = CHAR_NULL;
ch = sf->lookup(sf, LOOKUP_WORD, tmp, sz3);
if (ch != CHAR_NULL) {
st_assign(a, ch, a->pos, sz3, tmp);
return TRUE;
} else {
return FALSE;
}
}
int libinjection_sqli_fold(struct libinjection_sqli_state * sf)
{
stoken_t last_comment;
/* POS is the position of where the NEXT token goes */
size_t pos = 0;
/* LEFT is a count of how many tokens that are already
folded or processed (i.e. part of the fingerprint) */
size_t left = 0;
int more = 1;
st_clear(&last_comment);
/* Skip all initial comments, right-parens ( and unary operators
*
*/
sf->current = &(sf->tokenvec[0]);
while (more) {
more = libinjection_sqli_tokenize(sf);
if ( ! (sf->current->type == TYPE_COMMENT ||
sf->current->type == TYPE_LEFTPARENS ||
sf->current->type == TYPE_SQLTYPE ||
st_is_unary_op(sf->current))) {
break;
}
}
if (! more) {
/* If input was only comments, unary or (, then exit */
return 0;
} else {
/* it's some other token */
pos += 1;
}
while (1) {
FOLD_DEBUG;
/* do we have all the max number of tokens? if so do
* some special cases for 5 tokens
*/
if (pos >= LIBINJECTION_SQLI_MAX_TOKENS) {
if (
(
sf->tokenvec[0].type == TYPE_NUMBER &&
(sf->tokenvec[1].type == TYPE_OPERATOR || sf->tokenvec[1].type == TYPE_COMMA) &&
sf->tokenvec[2].type == TYPE_LEFTPARENS &&
sf->tokenvec[3].type == TYPE_NUMBER &&
sf->tokenvec[4].type == TYPE_RIGHTPARENS
) ||
(
sf->tokenvec[0].type == TYPE_BAREWORD &&
sf->tokenvec[1].type == TYPE_OPERATOR &&
sf->tokenvec[2].type == TYPE_LEFTPARENS &&
(sf->tokenvec[3].type == TYPE_BAREWORD || sf->tokenvec[3].type == TYPE_NUMBER) &&
sf->tokenvec[4].type == TYPE_RIGHTPARENS
) ||
(
sf->tokenvec[0].type == TYPE_NUMBER &&
sf->tokenvec[1].type == TYPE_RIGHTPARENS &&
sf->tokenvec[2].type == TYPE_COMMA &&
sf->tokenvec[3].type == TYPE_LEFTPARENS &&
sf->tokenvec[4].type == TYPE_NUMBER
) ||
(
sf->tokenvec[0].type == TYPE_BAREWORD &&
sf->tokenvec[1].type == TYPE_RIGHTPARENS &&
sf->tokenvec[2].type == TYPE_OPERATOR &&
sf->tokenvec[3].type == TYPE_LEFTPARENS &&
sf->tokenvec[4].type == TYPE_BAREWORD
)
)
{
if (pos > LIBINJECTION_SQLI_MAX_TOKENS) {
st_copy(&(sf->tokenvec[1]), &(sf->tokenvec[LIBINJECTION_SQLI_MAX_TOKENS]));
pos = 2;
left = 0;
} else {
pos = 1;
left = 0;
}
}
}
if (! more || left >= LIBINJECTION_SQLI_MAX_TOKENS) {
left = pos;
break;
}
/* get up to two tokens */
while (more && pos <= LIBINJECTION_SQLI_MAX_TOKENS && (pos - left) < 2) {
sf->current = &(sf->tokenvec[pos]);
more = libinjection_sqli_tokenize(sf);
if (more) {
if (sf->current->type == TYPE_COMMENT) {
st_copy(&last_comment, sf->current);
} else {
last_comment.type = CHAR_NULL;
pos += 1;
}
}
}
FOLD_DEBUG;
/* did we get 2 tokens? if not then we are done */
if (pos - left < 2) {
left = pos;
continue;
}
/* FOLD: "ss" -> "s"
* "foo" "bar" is valid SQL
* just ignore second string
*/
if (sf->tokenvec[left].type == TYPE_STRING && sf->tokenvec[left+1].type == TYPE_STRING) {
pos -= 1;
sf->stats_folds += 1;
continue;
} else if (sf->tokenvec[left].type == TYPE_SEMICOLON && sf->tokenvec[left+1].type == TYPE_SEMICOLON) {
/* not sure how various engines handle
* 'select 1;;drop table foo' or
* 'select 1; /x foo x/; drop table foo'
* to prevent surprises, just fold away repeated semicolons
*/
pos -= 1;
sf->stats_folds += 1;
continue;
} else if ((sf->tokenvec[left].type == TYPE_OPERATOR ||
sf->tokenvec[left].type == TYPE_LOGIC_OPERATOR) &&
(st_is_unary_op(&sf->tokenvec[left+1]) ||
sf->tokenvec[left+1].type == TYPE_SQLTYPE)) {
pos -= 1;
sf->stats_folds += 1;
left = 0;
continue;
} else if (sf->tokenvec[left].type == TYPE_LEFTPARENS &&
st_is_unary_op(&sf->tokenvec[left+1])) {
pos -= 1;
sf->stats_folds += 1;
if (left > 0) {
left -= 1;
}
continue;
} else if (syntax_merge_words(sf, &sf->tokenvec[left], &sf->tokenvec[left+1])) {
pos -= 1;
sf->stats_folds += 1;
if (left > 0) {
left -= 1;
}
continue;
} else if (sf->tokenvec[left].type == TYPE_SEMICOLON &&
sf->tokenvec[left+1].type == TYPE_FUNCTION &&
(sf->tokenvec[left+1].val[0] == 'I' ||
sf->tokenvec[left+1].val[0] == 'i' ) &&
(sf->tokenvec[left+1].val[1] == 'F' ||
sf->tokenvec[left+1].val[1] == 'f' )) {
/* IF is normally a function, except in Transact-SQL where it can be used as a
* standalone control flow operator, e.g. ; IF 1=1 ...
* if found after a semicolon, convert from 'f' type to 'T' type
*/
sf->tokenvec[left+1].type = TYPE_TSQL;
/* left += 2; */
continue; /* reparse everything, but we probably can advance left, and pos */
} else if ((sf->tokenvec[left].type == TYPE_BAREWORD || sf->tokenvec[left].type == TYPE_VARIABLE) &&
sf->tokenvec[left+1].type == TYPE_LEFTPARENS && (
/* TSQL functions but common enough to be column names */
cstrcasecmp("USER_ID", sf->tokenvec[left].val, sf->tokenvec[left].len) == 0 ||
cstrcasecmp("USER_NAME", sf->tokenvec[left].val, sf->tokenvec[left].len) == 0 ||
/* Function in MYSQL */
cstrcasecmp("DATABASE", sf->tokenvec[left].val, sf->tokenvec[left].len) == 0 ||
cstrcasecmp("PASSWORD", sf->tokenvec[left].val, sf->tokenvec[left].len) == 0 ||
cstrcasecmp("USER", sf->tokenvec[left].val, sf->tokenvec[left].len) == 0 ||
/* Mysql words that act as a variable and are a function */
/* TSQL current_users is fake-variable */
/* http://msdn.microsoft.com/en-us/library/ms176050.aspx */
cstrcasecmp("CURRENT_USER", sf->tokenvec[left].val, sf->tokenvec[left].len) == 0 ||
cstrcasecmp("CURRENT_DATE", sf->tokenvec[left].val, sf->tokenvec[left].len) == 0 ||
cstrcasecmp("CURRENT_TIME", sf->tokenvec[left].val, sf->tokenvec[left].len) == 0 ||
cstrcasecmp("CURRENT_TIMESTAMP", sf->tokenvec[left].val, sf->tokenvec[left].len) == 0 ||
cstrcasecmp("LOCALTIME", sf->tokenvec[left].val, sf->tokenvec[left].len) == 0 ||
cstrcasecmp("LOCALTIMESTAMP", sf->tokenvec[left].val, sf->tokenvec[left].len) == 0
)) {
/* pos is the same
* other conversions need to go here... for instance
* password CAN be a function, coalesce CAN be a function
*/
sf->tokenvec[left].type = TYPE_FUNCTION;
continue;
} else if (sf->tokenvec[left].type == TYPE_KEYWORD && (
cstrcasecmp("IN", sf->tokenvec[left].val, sf->tokenvec[left].len) == 0 ||
cstrcasecmp("NOT IN", sf->tokenvec[left].val, sf->tokenvec[left].len) == 0
)) {
if (sf->tokenvec[left+1].type == TYPE_LEFTPARENS) {
/* got .... IN ( ... (or 'NOT IN')
* it's an operator
*/
sf->tokenvec[left].type = TYPE_OPERATOR;
} else {
/*
* it's a nothing
*/
sf->tokenvec[left].type = TYPE_BAREWORD;
}
/* "IN" can be used as "IN BOOLEAN MODE" for mysql
* in which case merging of words can be done later
* other wise it acts as an equality operator __ IN (values..)
*
* here we got "IN" "(" so it's an operator.
* also back track to handle "NOT IN"
* might need to do the same with like
* two use cases "foo" LIKE "BAR" (normal operator)
* "foo" = LIKE(1,2)
*/
continue;
} else if ((sf->tokenvec[left].type == TYPE_OPERATOR) && (
cstrcasecmp("LIKE", sf->tokenvec[left].val, sf->tokenvec[left].len) == 0 ||
cstrcasecmp("NOT LIKE", sf->tokenvec[left].val, sf->tokenvec[left].len) == 0)) {
if (sf->tokenvec[left+1].type == TYPE_LEFTPARENS) {
/* SELECT LIKE(...
* it's a function
*/
sf->tokenvec[left].type = TYPE_FUNCTION;
}
} else if (sf->tokenvec[left].type == TYPE_SQLTYPE &&
(sf->tokenvec[left+1].type == TYPE_BAREWORD ||
sf->tokenvec[left+1].type == TYPE_NUMBER ||
sf->tokenvec[left+1].type == TYPE_SQLTYPE ||
sf->tokenvec[left+1].type == TYPE_LEFTPARENS ||
sf->tokenvec[left+1].type == TYPE_FUNCTION ||
sf->tokenvec[left+1].type == TYPE_VARIABLE ||
sf->tokenvec[left+1].type == TYPE_STRING)) {
st_copy(&sf->tokenvec[left], &sf->tokenvec[left+1]);
pos -= 1;
sf->stats_folds += 1;
left = 0;
continue;
} else if (sf->tokenvec[left].type == TYPE_COLLATE &&
sf->tokenvec[left+1].type == TYPE_BAREWORD) {
/*
* there are too many collation types.. so if the bareword has a "_"
* then it's TYPE_SQLTYPE
*/
if (strchr(sf->tokenvec[left+1].val, '_') != NULL) {
sf->tokenvec[left+1].type = TYPE_SQLTYPE;
left = 0;
}
} else if (sf->tokenvec[left].type == TYPE_BACKSLASH) {
if (st_is_arithmetic_op(&(sf->tokenvec[left+1]))) {
/* very weird case in TSQL where '\%1' is parsed as '0 % 1', etc */
sf->tokenvec[left].type = TYPE_NUMBER;
} else {
/* just ignore it.. Again T-SQL seems to parse \1 as "1" */
st_copy(&sf->tokenvec[left], &sf->tokenvec[left+1]);
pos -= 1;
sf->stats_folds += 1;
}
left = 0;
continue;
} else if (sf->tokenvec[left].type == TYPE_LEFTPARENS &&
sf->tokenvec[left+1].type == TYPE_LEFTPARENS) {
pos -= 1;
left = 0;
sf->stats_folds += 1;
continue;
} else if (sf->tokenvec[left].type == TYPE_RIGHTPARENS &&
sf->tokenvec[left+1].type == TYPE_RIGHTPARENS) {
pos -= 1;
left = 0;
sf->stats_folds += 1;
continue;
} else if (sf->tokenvec[left].type == TYPE_LEFTBRACE &&
sf->tokenvec[left+1].type == TYPE_BAREWORD) {
/*
* MySQL Degenerate case --
*
* select { ``.``.id }; -- valid !!!
* select { ``.``.``.id }; -- invalid
* select ``.``.id; -- invalid
* select { ``.id }; -- invalid
*
* so it appears {``.``.id} is a magic case
* I suspect this is "current database, current table, field id"
*
* The folding code can't look at more than 3 tokens, and
* I don't want to make two passes.
*
* Since "{ ``" so rare, we are just going to blacklist it.
*
* Highly likely this will need revisiting!
*
* CREDIT @rsalgado 2013-11-25
*/
if (sf->tokenvec[left+1].len == 0) {
sf->tokenvec[left+1].type = TYPE_EVIL;
return (int)(left+2);
}
/* weird ODBC / MYSQL {foo expr} --> expr
* but for this rule we just strip away the "{ foo" part
*/
left = 0;
pos -= 2;
sf->stats_folds += 2;
continue;
} else if (sf->tokenvec[left+1].type == TYPE_RIGHTBRACE) {
pos -= 1;
left = 0;
sf->stats_folds += 1;
continue;
}
/* all cases of handing 2 tokens is done
and nothing matched. Get one more token
*/
FOLD_DEBUG;
while (more && pos <= LIBINJECTION_SQLI_MAX_TOKENS && pos - left < 3) {
sf->current = &(sf->tokenvec[pos]);
more = libinjection_sqli_tokenize(sf);
if (more) {
if (sf->current->type == TYPE_COMMENT) {
st_copy(&last_comment, sf->current);
} else {
last_comment.type = CHAR_NULL;
pos += 1;
}
}
}
/* do we have three tokens? If not then we are done */
if (pos -left < 3) {
left = pos;
continue;
}
/*
* now look for three token folding
*/
if (sf->tokenvec[left].type == TYPE_NUMBER &&
sf->tokenvec[left+1].type == TYPE_OPERATOR &&
sf->tokenvec[left+2].type == TYPE_NUMBER) {
pos -= 2;
left = 0;
continue;
} else if (sf->tokenvec[left].type == TYPE_OPERATOR &&
sf->tokenvec[left+1].type != TYPE_LEFTPARENS &&
sf->tokenvec[left+2].type == TYPE_OPERATOR) {
left = 0;
pos -= 2;
continue;
} else if (sf->tokenvec[left].type == TYPE_LOGIC_OPERATOR &&
sf->tokenvec[left+2].type == TYPE_LOGIC_OPERATOR) {
pos -= 2;
left = 0;
continue;
} else if (sf->tokenvec[left].type == TYPE_VARIABLE &&
sf->tokenvec[left+1].type == TYPE_OPERATOR &&
(sf->tokenvec[left+2].type == TYPE_VARIABLE ||
sf->tokenvec[left+2].type == TYPE_NUMBER ||
sf->tokenvec[left+2].type == TYPE_BAREWORD)) {
pos -= 2;
left = 0;
continue;
} else if ((sf->tokenvec[left].type == TYPE_BAREWORD ||
sf->tokenvec[left].type == TYPE_NUMBER ) &&
sf->tokenvec[left+1].type == TYPE_OPERATOR &&
(sf->tokenvec[left+2].type == TYPE_NUMBER ||
sf->tokenvec[left+2].type == TYPE_BAREWORD)) {
pos -= 2;
left = 0;
continue;
} else if ((sf->tokenvec[left].type == TYPE_BAREWORD ||
sf->tokenvec[left].type == TYPE_NUMBER ||
sf->tokenvec[left].type == TYPE_VARIABLE ||
sf->tokenvec[left].type == TYPE_STRING) &&
sf->tokenvec[left+1].type == TYPE_OPERATOR &&
streq(sf->tokenvec[left+1].val, "::") &&
sf->tokenvec[left+2].type == TYPE_SQLTYPE) {
pos -= 2;
left = 0;
sf->stats_folds += 2;
continue;
} else if ((sf->tokenvec[left].type == TYPE_BAREWORD ||
sf->tokenvec[left].type == TYPE_NUMBER ||
sf->tokenvec[left].type == TYPE_STRING ||
sf->tokenvec[left].type == TYPE_VARIABLE) &&
sf->tokenvec[left+1].type == TYPE_COMMA &&
(sf->tokenvec[left+2].type == TYPE_NUMBER ||
sf->tokenvec[left+2].type == TYPE_BAREWORD ||
sf->tokenvec[left+2].type == TYPE_STRING ||
sf->tokenvec[left+2].type == TYPE_VARIABLE)) {
pos -= 2;
left = 0;
continue;
} else if ((sf->tokenvec[left].type == TYPE_EXPRESSION ||
sf->tokenvec[left].type == TYPE_GROUP ||
sf->tokenvec[left].type == TYPE_COMMA) &&
st_is_unary_op(&sf->tokenvec[left+1]) &&
sf->tokenvec[left+2].type == TYPE_LEFTPARENS) {
/* got something like SELECT + (, LIMIT + (
* remove unary operator
*/
st_copy(&sf->tokenvec[left+1], &sf->tokenvec[left+2]);
pos -= 1;
left = 0;
continue;
} else if ((sf->tokenvec[left].type == TYPE_KEYWORD ||
sf->tokenvec[left].type == TYPE_EXPRESSION ||
sf->tokenvec[left].type == TYPE_GROUP ) &&
st_is_unary_op(&sf->tokenvec[left+1]) &&
(sf->tokenvec[left+2].type == TYPE_NUMBER ||
sf->tokenvec[left+2].type == TYPE_BAREWORD ||
sf->tokenvec[left+2].type == TYPE_VARIABLE ||
sf->tokenvec[left+2].type == TYPE_STRING ||
sf->tokenvec[left+2].type == TYPE_FUNCTION )) {
/* remove unary operators
* select - 1
*/
st_copy(&sf->tokenvec[left+1], &sf->tokenvec[left+2]);
pos -= 1;
left = 0;
continue;
} else if (sf->tokenvec[left].type == TYPE_COMMA &&
st_is_unary_op(&sf->tokenvec[left+1]) &&
(sf->tokenvec[left+2].type == TYPE_NUMBER ||
sf->tokenvec[left+2].type == TYPE_BAREWORD ||
sf->tokenvec[left+2].type == TYPE_VARIABLE ||
sf->tokenvec[left+2].type == TYPE_STRING)) {
/*
* interesting case turn ", -1" ->> ",1" PLUS we need to back up
* one token if possible to see if more folding can be done
* "1,-1" --> "1"
*/
st_copy(&sf->tokenvec[left+1], &sf->tokenvec[left+2]);
left = 0;
/* pos is >= 3 so this is safe */
assert(pos >= 3);
pos -= 3;
continue;
} else if (sf->tokenvec[left].type == TYPE_COMMA &&
st_is_unary_op(&sf->tokenvec[left+1]) &&
sf->tokenvec[left+2].type == TYPE_FUNCTION) {
/* Separate case from above since you end up with
* 1,-sin(1) --> 1 (1)
* Here, just do
* 1,-sin(1) --> 1,sin(1)
* just remove unary operator
*/
st_copy(&sf->tokenvec[left+1], &sf->tokenvec[left+2]);
pos -= 1;
left = 0;
continue;
} else if ((sf->tokenvec[left].type == TYPE_BAREWORD) &&
(sf->tokenvec[left+1].type == TYPE_DOT) &&
(sf->tokenvec[left+2].type == TYPE_BAREWORD)) {
/* ignore the '.n'
* typically is this databasename.table
*/
assert(pos >= 3);
pos -= 2;
left = 0;
continue;
} else if ((sf->tokenvec[left].type == TYPE_EXPRESSION) &&
(sf->tokenvec[left+1].type == TYPE_DOT) &&
(sf->tokenvec[left+2].type == TYPE_BAREWORD)) {
/* select . `foo` --> select `foo` */
st_copy(&sf->tokenvec[left+1], &sf->tokenvec[left+2]);
pos -= 1;
left = 0;
continue;
} else if ((sf->tokenvec[left].type == TYPE_FUNCTION) &&
(sf->tokenvec[left+1].type == TYPE_LEFTPARENS) &&
(sf->tokenvec[left+2].type != TYPE_RIGHTPARENS)) {
/*
* whats going on here
* Some SQL functions like USER() have 0 args
* if we get User(foo), then User is not a function
* This should be expanded since it eliminated a lot of false
* positives.
*/
if (cstrcasecmp("USER", sf->tokenvec[left].val, sf->tokenvec[left].len) == 0) {
sf->tokenvec[left].type = TYPE_BAREWORD;
}
}
/* no folding -- assume left-most token is
is good, now use the existing 2 tokens --
do not get another
*/
left += 1;
} /* while(1) */
/* if we have 4 or less tokens, and we had a comment token
* at the end, add it back
*/
if (left < LIBINJECTION_SQLI_MAX_TOKENS && last_comment.type == TYPE_COMMENT) {
st_copy(&sf->tokenvec[left], &last_comment);
left += 1;
}
/* sometimes we grab a 6th token to help
determine the type of token 5.
*/
if (left > LIBINJECTION_SQLI_MAX_TOKENS) {
left = LIBINJECTION_SQLI_MAX_TOKENS;
}
return (int)left;
}
/* secondary api: detects SQLi in a string, GIVEN a context.
*
* A context can be:
* * CHAR_NULL (\0), process as is
* * CHAR_SINGLE ('), process pretending input started with a
* single quote.
* * CHAR_DOUBLE ("), process pretending input started with a
* double quote.
*
*/
const char* libinjection_sqli_fingerprint(struct libinjection_sqli_state * sql_state, int flags)
{
int i;
int tlen = 0;
libinjection_sqli_reset(sql_state, flags);
tlen = libinjection_sqli_fold(sql_state);
/* Check for magic PHP backquote comment
* If:
* * last token is of type "bareword"
* * And is quoted in a backtick
* * And isn't closed
* * And it's empty?
* Then convert it to comment
*/
if (tlen > 2 &&
sql_state->tokenvec[tlen-1].type == TYPE_BAREWORD &&
sql_state->tokenvec[tlen-1].str_open == CHAR_TICK &&
sql_state->tokenvec[tlen-1].len == 0 &&
sql_state->tokenvec[tlen-1].str_close == CHAR_NULL) {
sql_state->tokenvec[tlen-1].type = TYPE_COMMENT;
}
for (i = 0; i < tlen; ++i) {
sql_state->fingerprint[i] = sql_state->tokenvec[i].type;
}
/*
* make the fingerprint pattern a c-string (null delimited)
*/
sql_state->fingerprint[tlen] = CHAR_NULL;
/*
* check for 'X' in pattern, and then
* clear out all tokens
*
* this means parsing could not be done
* accurately due to pgsql's double comments
* or other syntax that isn't consistent.
* Should be very rare false positive
*/
if (strchr(sql_state->fingerprint, TYPE_EVIL)) {
/* needed for SWIG */
memset((void*)sql_state->fingerprint, 0, LIBINJECTION_SQLI_MAX_TOKENS + 1);
memset((void*)sql_state->tokenvec[0].val, 0, LIBINJECTION_SQLI_TOKEN_SIZE);
sql_state->fingerprint[0] = TYPE_EVIL;
sql_state->tokenvec[0].type = TYPE_EVIL;
sql_state->tokenvec[0].val[0] = TYPE_EVIL;
sql_state->tokenvec[1].type = CHAR_NULL;
}
return sql_state->fingerprint;
}
int libinjection_sqli_check_fingerprint(struct libinjection_sqli_state* sql_state)
{
return libinjection_sqli_blacklist(sql_state) &&
libinjection_sqli_not_whitelist(sql_state);
}
char libinjection_sqli_lookup_word(struct libinjection_sqli_state *sql_state, int lookup_type,
const char* str, size_t len)
{
if (lookup_type == LOOKUP_FINGERPRINT) {
return libinjection_sqli_check_fingerprint(sql_state) ? 'X' : '\0';
} else {
return bsearch_keyword_type(str, len, sql_keywords, sql_keywords_sz);
}
}
int libinjection_sqli_blacklist(struct libinjection_sqli_state* sql_state)
{
/*
* use minimum of 8 bytes to make sure gcc -fstack-protector
* works correctly
*/
char fp2[8];
char ch;
size_t i;
size_t len = strlen(sql_state->fingerprint);
int patmatch;
if (len < 1) {
sql_state->reason = __LINE__;
return FALSE;
}
/*
to keep everything compatible, convert the
v0 fingerprint pattern to v1
v0: up to 5 chars, mixed case
v1: 1 char is '0', up to 5 more chars, upper case
*/
fp2[0] = '0';
for (i = 0; i < len; ++i) {
ch = sql_state->fingerprint[i];
if (ch >= 'a' && ch <= 'z') {
ch -= 0x20;
}
fp2[i+1] = ch;
}
fp2[i+1] = '\0';
patmatch = is_keyword(fp2, len + 1) == TYPE_FINGERPRINT;
/*
* No match.
*
* Set sql_state->reason to current line number
* only for debugging purposes.
*/
if (!patmatch) {
sql_state->reason = __LINE__;
return FALSE;
}
return TRUE;
}
/*
* return TRUE if SQLi, false is benign
*/
int libinjection_sqli_not_whitelist(struct libinjection_sqli_state* sql_state)
{
/*
* We assume we got a SQLi match
* This next part just helps reduce false positives.
*
*/
char ch;
size_t tlen = strlen(sql_state->fingerprint);
if (tlen > 1 && sql_state->fingerprint[tlen-1] == TYPE_COMMENT) {
/*
* if ending comment is contains 'sp_password' then it's SQLi!
* MS Audit log apparently ignores anything with
* 'sp_password' in it. Unable to find primary reference to
* this "feature" of SQL Server but seems to be known SQLi
* technique
*/
if (my_memmem(sql_state->s, sql_state->slen,
"sp_password", strlen("sp_password"))) {
sql_state->reason = __LINE__;
return TRUE;
}
}
switch (tlen) {
case 2:{
/*
* case 2 are "very small SQLi" which make them
* hard to tell from normal input...
*/
if (sql_state->fingerprint[1] == TYPE_UNION) {
if (sql_state->stats_tokens == 2) {
/* not sure why but 1U comes up in SQLi attack
* likely part of parameter splitting/etc.
* lots of reasons why "1 union" might be normal
* input, so beep only if other SQLi things are present
*/
/* it really is a number and 'union'
* other wise it has folding or comments
*/
sql_state->reason = __LINE__;
return FALSE;
} else {
sql_state->reason = __LINE__;
return TRUE;
}
}
/*
* if 'comment' is '#' ignore.. too many FP
*/
if (sql_state->tokenvec[1].val[0] == '#') {
sql_state->reason = __LINE__;
return FALSE;
}
/*
* for fingerprint like 'nc', only comments of /x are treated
* as SQL... ending comments of "--" and "#" are not SQLi
*/
if (sql_state->tokenvec[0].type == TYPE_BAREWORD &&
sql_state->tokenvec[1].type == TYPE_COMMENT &&
sql_state->tokenvec[1].val[0] != '/') {
sql_state->reason = __LINE__;
return FALSE;
}
/*
* if '1c' ends with '/x' then it's SQLi
*/
if (sql_state->tokenvec[0].type == TYPE_NUMBER &&
sql_state->tokenvec[1].type == TYPE_COMMENT &&
sql_state->tokenvec[1].val[0] == '/') {
return TRUE;
}
/**
* there are some odd base64-looking query string values
* 1234-ABCDEFEhfhihwuefi--
* which evaluate to "1c"... these are not SQLi
* but 1234-- probably is.
* Make sure the "1" in "1c" is actually a true decimal number
*
* Need to check -original- string since the folding step
* may have merged tokens, e.g. "1+FOO" is folded into "1"
*
* Note: evasion: 1*1--
*/
if (sql_state->tokenvec[0].type == TYPE_NUMBER &&
sql_state->tokenvec[1].type == TYPE_COMMENT) {
if (sql_state->stats_tokens > 2) {
/* we have some folding going on, highly likely SQLi */
sql_state->reason = __LINE__;
return TRUE;
}
/*
* we check that next character after the number is either whitespace,
* or '/' or a '-' ==> SQLi.
*/
ch = sql_state->s[sql_state->tokenvec[0].len];
if ( ch <= 32 ) {
/* next char was whitespace,e.g. "1234 --"
* this isn't exactly correct.. ideally we should skip over all whitespace
* but this seems to be ok for now
*/
return TRUE;
}
if (ch == '/' && sql_state->s[sql_state->tokenvec[0].len + 1] == '*') {
return TRUE;
}
if (ch == '-' && sql_state->s[sql_state->tokenvec[0].len + 1] == '-') {
return TRUE;
}
sql_state->reason = __LINE__;
return FALSE;
}
/*
* detect obvious SQLi scans.. many people put '--' in plain text
* so only detect if input ends with '--', e.g. 1-- but not 1-- foo
*/
if ((sql_state->tokenvec[1].len > 2)
&& sql_state->tokenvec[1].val[0] == '-') {
sql_state->reason = __LINE__;
return FALSE;
}
break;
} /* case 2 */
case 3:{
/*
* ...foo' + 'bar...
* no opening quote, no closing quote
* and each string has data
*/
if (streq(sql_state->fingerprint, "sos")
|| streq(sql_state->fingerprint, "s&s")) {
if ((sql_state->tokenvec[0].str_open == CHAR_NULL)
&& (sql_state->tokenvec[2].str_close == CHAR_NULL)
&& (sql_state->tokenvec[0].str_close == sql_state->tokenvec[2].str_open)) {
/*
* if ....foo" + "bar....
*/
sql_state->reason = __LINE__;
return TRUE;
}
if (sql_state->stats_tokens == 3) {
sql_state->reason = __LINE__;
return FALSE;
}
/*
* not SQLi
*/
sql_state->reason = __LINE__;
return FALSE;
} else if (streq(sql_state->fingerprint, "s&n") ||
streq(sql_state->fingerprint, "n&1") ||
streq(sql_state->fingerprint, "1&1") ||
streq(sql_state->fingerprint, "1&v") ||
streq(sql_state->fingerprint, "1&s")) {
/* 'sexy and 17' not SQLi
* 'sexy and 17<18' SQLi
*/
if (sql_state->stats_tokens == 3) {
sql_state->reason = __LINE__;
return FALSE;
}
} else if (sql_state->tokenvec[1].type == TYPE_KEYWORD) {
if ((sql_state->tokenvec[1].len < 5) ||
cstrcasecmp("INTO", sql_state->tokenvec[1].val, 4)) {
/* if it's not "INTO OUTFILE", or "INTO DUMPFILE" (MySQL)
* then treat as safe
*/
sql_state->reason = __LINE__;
return FALSE;
}
}
break;
} /* case 3 */
case 4:
case 5: {
/* nothing right now */
break;
} /* case 5 */
} /* end switch */
return TRUE;
}
/** Main API, detects SQLi in an input.
*
*
*/
static int reparse_as_mysql(struct libinjection_sqli_state * sql_state)
{
return sql_state->stats_comment_ddx ||
sql_state->stats_comment_hash;
}
/*
* This function is mostly use with SWIG
*/
struct libinjection_sqli_token*
libinjection_sqli_get_token(struct libinjection_sqli_state * sql_state, int i)
{
if (i < 0 || i > (int)LIBINJECTION_SQLI_MAX_TOKENS) {
return NULL;
}
return &(sql_state->tokenvec[i]);
}
int libinjection_is_sqli(struct libinjection_sqli_state * sql_state)
{
const char *s = sql_state->s;
size_t slen = sql_state->slen;
/*
* no input? not SQLi
*/
if (slen == 0) {
return FALSE;
}
/*
* test input "as-is"
*/
libinjection_sqli_fingerprint(sql_state, FLAG_QUOTE_NONE | FLAG_SQL_ANSI);
if (sql_state->lookup(sql_state, LOOKUP_FINGERPRINT,
sql_state->fingerprint, strlen(sql_state->fingerprint))) {
return TRUE;
} else if (reparse_as_mysql(sql_state)) {
libinjection_sqli_fingerprint(sql_state, FLAG_QUOTE_NONE | FLAG_SQL_MYSQL);
if (sql_state->lookup(sql_state, LOOKUP_FINGERPRINT,
sql_state->fingerprint, strlen(sql_state->fingerprint))) {
return TRUE;
}
}
/*
* if input has a single_quote, then
* test as if input was actually '
* example: if input if "1' = 1", then pretend it's
* "'1' = 1"
* Porting Notes: example the same as doing
* is_string_sqli(sql_state, "'" + s, slen+1, NULL, fn, arg)
*
*/
if (memchr(s, CHAR_SINGLE, slen)) {
libinjection_sqli_fingerprint(sql_state, FLAG_QUOTE_SINGLE | FLAG_SQL_ANSI);
if (sql_state->lookup(sql_state, LOOKUP_FINGERPRINT,
sql_state->fingerprint, strlen(sql_state->fingerprint))) {
return TRUE;
} else if (reparse_as_mysql(sql_state)) {
libinjection_sqli_fingerprint(sql_state, FLAG_QUOTE_SINGLE | FLAG_SQL_MYSQL);
if (sql_state->lookup(sql_state, LOOKUP_FINGERPRINT,
sql_state->fingerprint, strlen(sql_state->fingerprint))) {
return TRUE;
}
}
}
/*
* same as above but with a double-quote "
*/
if (memchr(s, CHAR_DOUBLE, slen)) {
libinjection_sqli_fingerprint(sql_state, FLAG_QUOTE_DOUBLE | FLAG_SQL_MYSQL);
if (sql_state->lookup(sql_state, LOOKUP_FINGERPRINT,
sql_state->fingerprint, strlen(sql_state->fingerprint))) {
return TRUE;
}
}
/*
* Hurray, input is not SQLi
*/
return FALSE;
}
int libinjection_sqli(const char* input, size_t slen, char fingerprint[])
{
int issqli;
struct libinjection_sqli_state state;
libinjection_sqli_init(&state, input, slen, 0);
issqli = libinjection_is_sqli(&state);
if (issqli) {
strcpy(fingerprint, state.fingerprint);
} else {
fingerprint[0] = '\0';
}
return issqli;
}
|