-
Notifications
You must be signed in to change notification settings - Fork 2
/
phssh_connector.py
1358 lines (1100 loc) · 54.2 KB
/
phssh_connector.py
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
# File: phssh_connector.py
#
# Copyright (c) 2016-2024 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific language governing permissions
# and limitations under the License.
#
#
# Phantom App imports
import os
import socket
import sys
import time
from socket import gaierror as SocketError
import paramiko
import phantom.app as phantom
import phantom.rules as ph_rules
import simplejson as json
from paramiko.ssh_exception import AuthenticationException, BadHostKeyException
from phantom.action_result import ActionResult
from phantom.base_connector import BaseConnector
from phantom.vault import Vault as Vault
# Import local
from phssh_consts import *
try:
from urllib.parse import unquote
except Exception:
from urllib import unquote
os.sys.path.insert(0, "{}/paramikossh".format(os.path.dirname(os.path.abspath(__file__))))
class SshConnector(BaseConnector):
def __init__(self):
super(SshConnector, self).__init__()
self._ssh_client = None
self._shell_channel = None
self.OS_TYPE = OS_LINUX
def _get_error_message_from_exception(self, e):
""" This method is used to get appropriate error message from the exception.
:param e: Exception object
:return: error message
"""
error_code = SSH_CODE_UNAVAILABLE_ERR
error_msg = SSH_MSG_UNAVAILABLE_ERR
self.error_print(error_msg, dump_object=e)
try:
if e.args:
if len(e.args) > 1:
error_code = e.args[0]
error_msg = e.args[1]
elif len(e.args) == 1:
error_code = SSH_CODE_UNAVAILABLE_ERR
error_msg = e.args[0]
except Exception:
pass
return "Error Code: {0}. Error Message: {1}".format(error_code, error_msg)
def _validate_integer(self, action_result, parameter, key, allow_zero=False):
""" This method is to check if the provided input parameter value
is a non-zero positive integer and returns the integer value of the parameter itself.
:param action_result: Action result or BaseConnector object
:param parameter: input parameter
:param key: input parameter message key
:allow_zero: whether zero should be considered as valid value or not
:return: integer value of the parameter or None in case of failure
"""
if parameter is not None:
try:
if not float(parameter).is_integer():
return action_result.set_status(phantom.APP_ERROR, SSH_VALID_INT_MSG.format(param=key)), None
parameter = int(parameter)
except Exception:
return action_result.set_status(phantom.APP_ERROR, SSH_VALID_INT_MSG.format(param=key)), None
if parameter < 0:
return action_result.set_status(phantom.APP_ERROR, SSH_NON_NEG_INT_MSG.format(param=key)), None
if not allow_zero and parameter == 0:
return action_result.set_status(phantom.APP_ERROR, SSH_NON_NEG_NON_ZERO_INT_MSG.format(param=key)), None
return phantom.APP_SUCCESS, parameter
def initialize(self):
config = self.get_config()
self._state = self.load_state()
self._username = config[SSH_JSON_USERNAME]
self._password = config.get(SSH_JSON_PASSWORD)
self._root = config.get(SSH_JSON_ROOT, False)
self._rsa_key_file = config.get(SSH_JSON_RSA_KEY)
self._pseudo_terminal = config.get(SSH_JSON_PSEUDO_TERMINAL, False)
self._disable_sha2 = config.get(SSH_JSON_DISABLE_SHA2, False)
# integer validation for 'timeout' config parameter
timeout = config.get(SSH_JSON_TIMEOUT)
ret_val, self._timeout = self._validate_integer(self, timeout, SSH_JSON_TIMEOUT)
if phantom.is_fail(ret_val):
return self.get_status()
# Fetching the Python major version
try:
self._python_version = int(sys.version_info[0])
except Exception:
return self.set_status(phantom.APP_ERROR, SSH_FETCHING_PYTHON_VERSION_MSG_ERR)
return phantom.APP_SUCCESS
def _start_connection(self, action_result, server):
self.debug_print("PARAMIKO VERSION. {}".format(paramiko.__version__))
if self._rsa_key_file is None and self._password is None:
return action_result.set_status(phantom.APP_ERROR, SSH_PWD_OR_RSA_KEY_NOT_SPECIFIED_MSG_ERR)
if self._rsa_key_file:
try:
if os.path.exists(self._rsa_key_file):
key = paramiko.RSAKey.from_private_key_file(self._rsa_key_file)
else:
ssh_file_path1 = "/home/phantom-worker/.ssh/{}".format(self._rsa_key_file)
ssh_file_path2 = "/home/phanru/.ssh/{}".format(self._rsa_key_file)
if os.path.exists(ssh_file_path1):
key = paramiko.RSAKey.from_private_key_file(ssh_file_path1)
elif os.path.exists(ssh_file_path2):
key = paramiko.RSAKey.from_private_key_file(ssh_file_path2)
else:
raise Exception('No such file or directory')
self._password = None
except Exception as e:
err = self._get_error_message_from_exception(e)
return action_result.set_status(phantom.APP_ERROR, "{}. {}".format(SSH_CONNECTIVITY_FAILED_ERR, err))
else:
key = None
self._ssh_client = paramiko.SSHClient()
self._ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.save_progress(phantom.APP_PROG_CONNECTING_TO_ELLIPSES, server)
try:
if self._disable_sha2:
self.debug_print("Disabling SHA2 algorithms")
self._ssh_client.connect(hostname=server, username=self._username, pkey=key,
password=self._password, allow_agent=False, look_for_keys=True,
timeout=FIRST_RECV_TIMEOUT, disabled_algorithms=dict(pubkeys=["rsa-sha2-512", "rsa-sha2-256"]))
else:
self._ssh_client.connect(hostname=server, username=self._username, pkey=key,
password=self._password, allow_agent=False, look_for_keys=True,
timeout=FIRST_RECV_TIMEOUT)
except AuthenticationException:
return action_result.set_status(phantom.APP_ERROR, SSH_AUTHENTICATION_FAILED_MSG_ERR)
except BadHostKeyException as e:
err = self._get_error_message_from_exception(e)
error_msg = "{}. {}".format(SSH_BAD_HOST_KEY_MSG_ERR, err)
return action_result.set_status(phantom.APP_ERROR, error_msg)
except SocketError:
error_msg = "{}. {}".format(SSH_CONNECTIVITY_FAILED_ERR, SSH_FAILED_TO_RESOLVE_MSG_ERR.format(server=server))
return action_result.set_status(phantom.APP_ERROR, error_msg)
except Exception as e:
err = self._get_error_message_from_exception(e)
return action_result.set_status(phantom.APP_ERROR, "{}. {}".format(SSH_CONNECTIVITY_FAILED_ERR, err))
return phantom.APP_SUCCESS
def _send_command(self, command, action_result, passwd="", timeout=0, suppress=False):
"""
Args:
action_result: object used to store the status
command: command to send
passwd: password, if command needs to be run with root
timeout: how long to wait before terminating program
suppress: don't send message / heartbeat back to phantom
"""
try:
output = ""
self.debug_print("Calling 'get_transport' via SSH client")
trans = self._ssh_client.get_transport()
self.debug_print("Creating session")
self._shell_channel = trans.open_session()
self._shell_channel.set_combine_stderr(True)
if self._pseudo_terminal:
self._shell_channel.get_pty()
self.debug_print("Calling 'exec_command' for command: {}".format(command))
self._shell_channel.settimeout(SEND_TIMEOUT)
self._shell_channel.exec_command(command)
self.debug_print("Calling 'get_output' method for processing the output")
ret_val, data, exit_status = self._get_output(action_result, timeout, passwd, suppress)
output += data
self.debug_print("Cleaning the output")
output = self._clean_stdout(output, passwd)
if phantom.is_fail(action_result.get_status()):
return action_result.get_status(), output, exit_status
except Exception as e:
err = self._get_error_message_from_exception(e)
return action_result.set_status(phantom.APP_ERROR, "{}. {}".format(SSH_SHELL_SEND_COMMAND_ERR.format(command), err)), None, None
self.debug_print("Command executed successfully")
return action_result.set_status(phantom.APP_SUCCESS, SSH_SUCCESS_CMD_EXEC), output, exit_status
def _get_output(self, action_result, timeout, passwd, suppress):
sendpw = True
output = ""
i = 1
stime = int(time.time())
if not suppress:
self.save_progress("Executing command")
try:
while True:
ctime = int(time.time())
if (timeout and ctime - stime >= timeout):
err = 'Error: Timeout after {} seconds'.format(timeout)
return action_result.set_status(phantom.APP_ERROR, err), output, 1
elif (self._shell_channel.recv_ready()):
output += self._shell_channel.recv(8192).decode('utf-8')
# This is pretty messy but it's just the way it is I guess
if (sendpw and passwd):
try:
self._shell_channel.send("{}\n".format(passwd))
if not self._pseudo_terminal:
output += "\n"
except socket.error:
pass
sendpw = False
# Exit status AND nothing left in output
elif (self._shell_channel.exit_status_ready() and not self._shell_channel.recv_ready()):
break
else:
time.sleep(1)
if not suppress:
self.send_progress("Executing command" + "." * i)
i = i % 5 + 1
except Exception as e:
err = self._get_error_message_from_exception(e)
return action_result.set_status(phantom.APP_ERROR, err), "", None
return action_result.set_status(phantom.APP_SUCCESS), output, self._shell_channel.recv_exit_status()
def _clean_stdout(self, stdout, passwd):
if stdout is None:
return None
try:
lines = []
for index, line in enumerate(stdout.splitlines()):
if (passwd and passwd in line) or ("[sudo] password for" in line):
if passwd and passwd in line:
self.debug_print("Password found at index: {}".format(index))
continue
lines.append(line)
except Exception:
return None
return '\n'.join(lines)
def _output_for_exit_status(self, action_result, exit_status,
output_on_err, output_on_succ):
# Shell returned an error
if exit_status:
action_result.set_status(phantom.APP_ERROR, output_on_err)
d = {"output": output_on_err}
else:
action_result.set_status(phantom.APP_SUCCESS, SSH_SUCCESS_CMD_SUCCESS)
d = {"output": output_on_succ}
action_result.add_data(d)
action_result.update_summary({"exit_status": exit_status})
# result.add_data({"exit_status": exit_status})
return action_result
def _test_connectivity(self, param):
self.save_progress("Testing SSH Connection")
action_result = self.add_action_result(ActionResult(dict(param)))
try:
endpoint = self.get_config()[SSH_JSON_DEVICE]
except Exception:
return action_result.set_status(phantom.APP_ERROR, SSH_HOSTNAME_OR_IP_NOT_SPECIFIED_MSG_ERR)
status_code = self._start_connection(action_result, endpoint)
if phantom.is_fail(status_code):
self.save_progress(SSH_CONNECTIVITY_TEST_ERR)
return action_result.get_status()
self.save_progress(SSH_CONNECTIVITY_ESTABLISHED)
self.save_progress("Executing 'uname' command...")
# Get Linux Distribution
cmd = "uname -a"
status_code, stdout, exit_status = self._send_command(cmd, action_result, suppress=True, timeout=self._timeout)
# Couldn't send command
if phantom.is_fail(status_code):
return status_code
# Some version of mac
if (exit_status == 0 and stdout.split()[0] == "Darwin"):
self.OS_TYPE = OS_MAC
self.debug_print("ssh uname {}".format(stdout))
self.save_progress(SSH_SUCCESS_CONNECTIVITY_TEST)
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_ssh_execute_command(self, param):
self.debug_print("Starting 'execute program' action function")
action_result = ActionResult(dict(param))
self.add_action_result(action_result)
endpoint = param[SSH_JSON_ENDPOINT]
self.debug_print("Calling 'start_connection'..")
status_code = self._start_connection(action_result, endpoint)
if phantom.is_fail(status_code):
return action_result.get_status()
self.debug_print(SSH_CONNECTIVITY_ESTABLISHED)
# As it turns out, even if the data type is "numeric" in the json
# the data will end up being a string after you receive it
# integer validation for 'timeout' action parameter
timeout = param.get(SSH_JSON_TIMEOUT)
if timeout is not None:
ret_val, timeout = self._validate_integer(action_result, timeout, SSH_JSON_TIMEOUT, False)
if phantom.is_fail(ret_val):
timeout = self._timeout
self.debug_print("Invalid value provided in the timeout parameter of the execute program action. {}".format(
SSH_ASSET_TIMEOUT_MSG))
else:
timeout = self._timeout
self.debug_print("No value found in the timeout parameter of the execute program action. {}".format(SSH_ASSET_TIMEOUT_MSG))
script_file = param.get(SSH_JSON_SCRIPT_FILE)
if script_file:
try:
with open(script_file, 'r') as f:
cmd = f.read()
except Exception as e:
err = self._get_error_message_from_exception(e)
err_msg = "{}. {}".format(SSH_UNABLE_TO_READ_SCRIPT_FILE_MSG_ERR.format(script_file=script_file), err)
return action_result.set_status(phantom.APP_ERROR, err_msg)
else:
cmd = param.get(SSH_JSON_CMD)
if not cmd:
return action_result.set_status(phantom.APP_ERROR, SSH_COMMAND_OR_SCRIPT_FILE_NOT_PROVIDED_MSG_ERR)
# Command needs to be run as root
if (not self._root and cmd.split()[0] == "sudo"):
passwd = self._password
if passwd is None:
return action_result.set_status(phantom.APP_ERROR, SSH_NEED_PW_FOR_ROOT_ERR)
else:
passwd = ""
self.debug_print("Sending command for execution")
status_code, stdout, exit_status = self._send_command(cmd, action_result, passwd=passwd, timeout=timeout)
# If command failed to send
if phantom.is_fail(status_code):
action_result.add_data({"output": stdout})
return action_result.get_status()
action_result = self._output_for_exit_status(action_result, exit_status,
stdout, stdout)
self.debug_print("'exec_command' action executed successfully")
return action_result.get_status()
def _handle_ssh_reboot_server(self, param):
action_result = ActionResult(dict(param))
self.add_action_result(action_result)
endpoint = param[SSH_JSON_ENDPOINT]
status_code = self._start_connection(action_result, endpoint)
if phantom.is_fail(status_code):
return action_result.get_status()
self.debug_print(SSH_CONNECTIVITY_ESTABLISHED)
cmd = "sudo -S shutdown -r now"
passwd = self._password
root = self._root
if root:
passwd = None
if not root and passwd is None:
return action_result.set_status(phantom.APP_ERROR, SSH_NEED_PW_FOR_ROOT_ERR)
status_code, stdout, exit_status = self._send_command(cmd, action_result, passwd=passwd, timeout=self._timeout)
# If command failed to send
if phantom.is_fail(status_code):
return action_result.get_status()
# no exit status code is returned, in case the server is successfully rebooted
if exit_status == -1:
action_result.set_status(phantom.APP_SUCCESS, "Exit status: {}. {}".format(exit_status, SSH_VERIFY_LAST_REBOOT_TIME_MSG))
d = {"output": stdout}
# Shell returned an error
elif exit_status:
action_result.set_status(phantom.APP_ERROR, stdout)
d = {"output": stdout}
else:
action_result.set_status(phantom.APP_SUCCESS, SSH_SUCCESS_CMD_SUCCESS)
d = {"output": SSH_SHELL_NO_ERR}
action_result.add_data(d)
action_result.update_summary({"exit_status": exit_status})
return action_result.get_status()
def _handle_ssh_shutdown_server(self, param):
action_result = ActionResult(dict(param))
self.add_action_result(action_result)
endpoint = param[SSH_JSON_ENDPOINT]
status_code = self._start_connection(action_result, endpoint)
if phantom.is_fail(status_code):
return action_result.get_status()
self.debug_print(SSH_CONNECTIVITY_ESTABLISHED)
cmd = "sudo -S shutdown -h now"
passwd = self._password
root = self._root
if root:
passwd = None
if not root and passwd is None:
return action_result.set_status(phantom.APP_ERROR, SSH_NEED_PW_FOR_ROOT_ERR)
status_code, stdout, exit_status = self._send_command(cmd, action_result, passwd=passwd, timeout=self._timeout)
# If command failed to send
if phantom.is_fail(status_code):
return action_result.get_status()
# verifying whether the endpoint has successfully shutdown or not
time.sleep(15)
status_code = self._start_connection(action_result, endpoint)
if phantom.is_fail(status_code):
d = {"output": SSH_SHELL_NO_ERR}
action_result.add_data(d)
action_result.update_summary({"exit_status": exit_status})
return action_result.set_status(phantom.APP_SUCCESS, "{}. {}".format(SSH_ENDPOINT_SHUTDOWN_MSG, SSH_SUCCESS_CMD_SUCCESS))
action_result = self._output_for_exit_status(action_result, exit_status,
stdout, SSH_SHELL_NO_ERR)
return action_result.get_status()
def _handle_ssh_list_processes(self, param):
action_result = ActionResult(dict(param))
self.add_action_result(action_result)
endpoint = param[SSH_JSON_ENDPOINT]
status_code = self._start_connection(action_result, endpoint)
if phantom.is_fail(status_code):
return action_result.get_status()
self.debug_print(SSH_CONNECTIVITY_ESTABLISHED)
# excl_root = param.get(SSH_JSON_EXCL_ROOT, False)
# ps on mac will always show the full username, ps on linux will
# only show usernames of <= 8 characters unless otherwise specified
fuser = "" if self.OS_TYPE == OS_MAC else ":32"
cmd = "ps c -Ao user{},uid,pid,ppid,stime,command".format(fuser)
status_code, stdout, exit_status = self._send_command(cmd, action_result, timeout=self._timeout)
if phantom.is_fail(status_code):
return action_result.get_status()
action_result = self._parse_processes(action_result, stdout, cmd)
# action_result.update_summary({"exit_status": exit_status})
return action_result.get_status()
def _parse_processes(self, action_result, stdout, cmd):
"""
STDOUT:
USER UID PID PPID STIME CMD
"""
try:
ll = [] # List to store dictionaries
headers = stdout.splitlines()[0].split()
rows = stdout.splitlines()
for row in rows[1:]:
r = row.split()
d = {} # Used to store results
for i in range(0, len(headers)):
if (i == len(headers) - 1):
d[headers[i].lower()] = ' '.join(r[i:])
else:
d[headers[i].lower()] = r[i]
ll.append(d.copy())
action_result.add_data({"processes": ll})
action_result.update_summary({"total_processes": len(ll)})
# result.set_status(phantom.APP_SUCCESS, SSH_SUCCESS_CMD_SUCCESS)
action_result.set_status(phantom.APP_SUCCESS)
except Exception:
action_result.set_status(phantom.APP_ERROR, SSH_UNABLE_TO_PARSE_OUTPUT_OF_CMD.format(cmd))
return action_result
def _handle_ssh_kill_process(self, param):
action_result = ActionResult(dict(param))
self.add_action_result(action_result)
endpoint = param[SSH_JSON_ENDPOINT]
status_code = self._start_connection(action_result, endpoint)
if phantom.is_fail(status_code):
return action_result.get_status()
self.debug_print(SSH_CONNECTIVITY_ESTABLISHED)
pid = param[SSH_JSON_PID]
# integer validation for 'pid' action parameter
ret_val, pid = self._validate_integer(action_result, pid, SSH_JSON_PID, True)
if phantom.is_fail(ret_val):
return action_result.get_status()
passwd = self._password
root = self._root
if root:
passwd = None
if not root and passwd is None:
return action_result.set_status(phantom.APP_ERROR, SSH_NEED_PW_FOR_ROOT_ERR)
cmd = "sudo -S kill -SIGKILL {}".format(pid)
status_code, stdout, exit_status = self._send_command(cmd, action_result, passwd=passwd, timeout=self._timeout)
if phantom.is_fail(status_code):
return action_result.get_status()
action_result = self._output_for_exit_status(action_result, exit_status,
stdout, SSH_PID_TERMINATED_MSG.format(pid=pid))
return action_result.get_status()
def _handle_ssh_logout_user(self, param):
action_result = ActionResult(dict(param))
self.add_action_result(action_result)
endpoint = param[SSH_JSON_ENDPOINT]
status_code = self._start_connection(action_result, endpoint)
if phantom.is_fail(status_code):
return action_result.get_status()
self.debug_print(SSH_CONNECTIVITY_ESTABLISHED)
user_name = param[SSH_JSON_USER]
passwd = self._password
root = self._root
if root:
passwd = None
if not root and passwd is None:
return action_result.set_status(phantom.APP_ERROR, SSH_NEED_PW_FOR_ROOT_ERR)
cmd = "sudo -S pkill -SIGKILL -u {}".format(user_name)
status_code, stdout, exit_status = self._send_command(cmd, action_result, passwd=passwd, timeout=self._timeout)
if phantom.is_fail(status_code):
return action_result.get_status()
action_result = self._output_for_exit_status(action_result, exit_status,
stdout, SSH_LOGOFF_USER_MSG.format(username=user_name))
return action_result.get_status()
def _handle_ssh_list_conn(self, param):
action_result = ActionResult(dict(param))
self.add_action_result(action_result)
endpoint = param[SSH_JSON_ENDPOINT]
status_code = self._start_connection(action_result, endpoint)
if phantom.is_fail(status_code):
return action_result.get_status()
self.debug_print(SSH_CONNECTIVITY_ESTABLISHED)
passwd = self._password
root = self._root
if not root and passwd is None:
return action_result.set_status(phantom.APP_ERROR, SSH_NEED_PW_FOR_ROOT_ERR)
local_addr = param.get(SSH_JSON_LOCAL_ADDR, "")
local_port = param.get(SSH_JSON_LOCAL_PORT, "")
# integer validation for 'local_port' action parameter
if local_port:
ret_val, local_port = self._validate_integer(action_result, local_port, SSH_JSON_LOCAL_PORT)
if phantom.is_fail(ret_val):
return action_result.get_status()
local_port = str(local_port)
remote_addr = param.get(SSH_JSON_REMOTE_ADDR, "")
remote_port = param.get(SSH_JSON_REMOTE_PORT, "")
# integer validation for 'remote_port' action parameter
if remote_port:
ret_val, remote_port = self._validate_integer(action_result, remote_port, SSH_JSON_REMOTE_PORT)
if phantom.is_fail(ret_val):
return action_result.get_status()
remote_port = str(remote_port)
# Macs have BSD netstat which doesn't give enough information
if (self.OS_TYPE == OS_MAC):
return self._list_connections_mac(param, action_result, passwd,
local_addr, local_port, remote_addr, remote_port)
cmd = 'sudo -S netstat -etnp'
status_code, stdout, exit_status = self._send_command(cmd, action_result, passwd=passwd, timeout=self._timeout)
if phantom.is_fail(status_code):
return action_result.get_status()
action_result.update_summary({"exit_status": exit_status})
if exit_status:
action_result.add_data({"output": stdout})
if not stdout:
return action_result.set_status(phantom.APP_ERROR, "{}. {}".format(SSH_NO_SHELL_OUTPUT_MSG_ERR, SSH_IS_NETSTAT_INSTALLED_MSG))
return action_result.set_status(phantom.APP_ERROR, "{}. {}".format(
SSH_SHELL_OUTPUT_MSG_ERR.format(stdout=stdout), SSH_IS_NETSTAT_INSTALLED_MSG))
action_result = self._parse_connections(action_result, stdout, cmd,
local_addr, local_port, remote_addr, remote_port)
return action_result.get_status()
def _parse_connections(self, action_result, stdout, cmd, la, lp, ra, rp):
""" Process output for connections
PROTO Rec-Q Send-Q Local_Address Foreign_Address State User Inode Pid/Program_Name
"""
try:
ll = [] # List to store dictionaries
rows = stdout.splitlines()
# if (len(rows) <= 1):
# return None
for row in rows[2:]: # Don't parse first two lines
r = row.split()
d = {}
d["protocol"] = r[0]
d["rec_q"] = r[1]
d["send_q"] = r[2]
try:
s = r[3].split(':')
d["local_port"] = s[-1]
if (lp and d["local_port"] != lp):
continue
del s[-1]
d["local_ip"] = ":".join(s)
if (la and d["local_ip"] != la):
continue
except Exception: # Some error parsing
d["local_port"] = ""
d["local_ip"] = ""
try:
s = r[4].split(':')
d["remote_port"] = s[-1]
if (rp and d["remote_port"] != rp):
continue
del s[-1]
d["remote_ip"] = ":".join(s)
if (ra and d["remote_ip"] != ra):
continue
except Exception: # Some error parsing
d["remote_port"] = ""
d["remote_ip"] = ""
d["state"] = r[5]
d["uid"] = r[6]
d["inode"] = r[7]
try:
if (r[8] == "-"):
d["pid"] = ""
d["cmd"] = ""
else:
s = r[8].split('/')
d["pid"] = s[0]
del s[0]
d["cmd"] = "/".join(s)
except Exception:
d["pid"] = ""
d["cmd"] = ""
ll.append(d.copy())
action_result.add_data({"connections": ll})
action_result.set_status(phantom.APP_SUCCESS, SSH_SUCCESS_CMD_SUCCESS)
except Exception:
action_result.set_status(phantom.APP_ERROR, SSH_UNABLE_TO_PARSE_OUTPUT_OF_CMD.format(cmd))
return action_result
def _list_connections_mac(self, param, action_result, passwd,
local_addr, local_port, remote_addr, remote_port):
cmd = "sudo -S lsof -nP -i"
status_code, stdout, exit_status = self._send_command(cmd, action_result, passwd=passwd, timeout=self._timeout)
if phantom.is_fail(status_code):
return action_result.get_status()
action_result.update_summary({"exit_status": exit_status})
if exit_status:
action_result.add_data({"output": stdout})
if not stdout:
return action_result.set_status(phantom.APP_ERROR, SSH_NO_SHELL_OUTPUT_MSG_ERR)
return action_result.set_status(phantom.APP_ERROR, SSH_SHELL_OUTPUT_MSG_ERR.format(stdout=stdout))
action_result = self._parse_connections_mac(action_result, stdout, cmd,
local_addr, local_port, remote_addr, remote_port)
return action_result.get_status()
def _parse_connections_mac(self, action_result, stdout, cmd, la, lp, ra, rp):
""" Process output for connections
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME (STATE)?
"""
try:
ll = [] # List to store dictionaries
rows = stdout.splitlines()
if len(rows) <= 1:
return None
for row in rows[1:]: # Skip the first line
r = row.split()
d = {}
d['cmd'] = r[0]
d['pid'] = r[1]
d['uid'] = r[2]
d['fd'] = r[3]
d['type'] = r[4]
d['device'] = r[5]
d['sizeoff'] = r[6]
d['protocol'] = r[7]
n = r[8].split('->')
if len(n) == 2:
# Get Local
s = n[0].split(':')
d['local_port'] = s[-1]
if lp and d['local_port'] != lp:
continue
del s[-1]
d['local_ip'] = ':'.join(s)
if la and d['local_ip'] != la:
continue
# Get Remote
s = n[1].split(':')
d['remote_port'] = s[-1]
if rp and d['remote_port'] != rp:
continue
del s[-1]
d['remote_ip'] = ':'.join(s)
if ra and d['remote_ip'] != ra:
continue
else:
# If there is no remote connection (as many things will display),
# and they are being filtered, don't add
if (rp or ra):
continue
s = n[0].split(':')
d['local_port'] = s[-1]
if (lp and d['local_port'] != lp):
continue
del s[-1]
d['local_ip'] = ':'.join(s)
if (la and d['local_ip'] != la):
continue
d['remote_port'] = ""
d['remote_ip'] = ""
try:
d['state'] = r[9][1:-1] # Ignore paranthesis
except Exception:
d['state'] = ""
ll.append(d.copy())
action_result.add_data({"connections": ll})
action_result.set_status(phantom.APP_SUCCESS, SSH_SUCCESS_CMD_SUCCESS)
except Exception:
action_result.set_status(phantom.APP_ERROR, SSH_UNABLE_TO_PARSE_OUTPUT_OF_CMD.format(cmd))
return action_result
def _handle_ssh_list_fw_rules(self, param):
action_result = ActionResult(dict(param))
self.add_action_result(action_result)
endpoint = param[SSH_JSON_ENDPOINT]
status_code = self._start_connection(action_result, endpoint)
if phantom.is_fail(status_code):
return action_result.get_status()
self.debug_print(SSH_CONNECTIVITY_ESTABLISHED)
if (self.OS_TYPE == OS_MAC):
return action_result.set_status(phantom.APP_ERROR, SSH_FIREWALL_CMDS_NOT_SUPPORTED_ERR)
passwd = self._password
root = self._root
if root:
passwd = None
if not root and passwd is None:
return action_result.set_status(phantom.APP_ERROR, SSH_NEED_PW_FOR_ROOT_ERR)
prot = param.get(SSH_JSON_PROTOCOL, "")
port = param.get(SSH_JSON_PORT, "")
# integer validation of 'port' action parameter
if port:
ret_val, port = self._validate_integer(action_result, port, SSH_JSON_PORT)
if phantom.is_fail(ret_val):
return action_result.get_status()
port = str(port)
chain = param.get(SSH_JSON_CHAIN, "")
cmd = 'sudo -S iptables -L {} --line-numbers -n'.format(chain)
status_code, stdout, exit_status = self._send_command(cmd, action_result, passwd=passwd, timeout=self._timeout)
if phantom.is_fail(status_code):
return action_result.get_status()
action_result.update_summary({"exit_status": exit_status})
if exit_status:
action_result.add_data({"output": stdout})
if not stdout:
return action_result.set_status(phantom.APP_ERROR, SSH_NO_SHELL_OUTPUT_MSG_ERR)
return action_result.set_status(phantom.APP_ERROR, SSH_SHELL_OUTPUT_MSG_ERR.format(stdout=stdout))
action_result = self._filter_fw_rules(action_result, stdout, cmd, prot, port)
return action_result.get_status()
def _filter_fw_rules(self, action_result, stdout, cmd, prot, port):
try:
ll = []
cur_chain = ""
d = {}
rows = stdout.splitlines()
i = 0
while (i < len(rows)):
cur_chain = rows[i].split()[1] # Name of chain
i += 2 # Skip header row
while (i < len(rows)):
if (rows[i] == ""):
i += 1
break # New Chain
row = rows[i].split()
if (len(row) >= 6): # This is hopefully always true
d["chain"] = cur_chain
d["num"] = row[0]
d["target"] = row[1]
if (prot and row[2] != prot):
i += 1
continue
d["protocol"] = row[2]
d["source"] = row[4]
d["destination"] = row[5]
try: # the rest can contain port numbers, comments, and other things
the_rest = " ".join(row[6:])
except Exception:
the_rest = ""
if (port and port not in the_rest):
i += 1
continue
d["options"] = the_rest
ll.append(d.copy())
i += 1
action_result.add_data({"rules": ll})
action_result.set_status(phantom.APP_SUCCESS, SSH_SUCCESS_CMD_SUCCESS)
except Exception:
action_result.set_status(phantom.APP_ERROR, SSH_UNABLE_TO_PARSE_OUTPUT_OF_CMD.format(cmd))
return action_result
def _handle_ssh_block_ip(self, param):
action_result = ActionResult(dict(param))
self.add_action_result(action_result)
endpoint = param[SSH_JSON_ENDPOINT]
status_code = self._start_connection(action_result, endpoint)
if phantom.is_fail(status_code):
return action_result.get_status()
self.debug_print(SSH_CONNECTIVITY_ESTABLISHED)
if (self.OS_TYPE == OS_MAC):
return action_result.set_status(phantom.APP_ERROR, SSH_FIREWALL_CMDS_NOT_SUPPORTED_ERR)
no_ip = True
no_port = True
passwd = self._password
root = self._root
if root:
passwd = None
if not root and passwd is None:
return action_result.set_status(phantom.APP_ERROR, SSH_NEED_PW_FOR_ROOT_ERR)
protocol = param[SSH_JSON_PROTOCOL]
direction = "INPUT" if param[SSH_JSON_DIRECTION].lower() == "in" else "OUTPUT"
remote_ip = param.get(SSH_JSON_REMOTE_IP)
if remote_ip:
if direction == "INPUT":
remote_ip = "-s {}".format(remote_ip)
else:
remote_ip = "-d {}".format(remote_ip)
no_ip = False
else:
remote_ip = ""
remote_port = param.get(SSH_JSON_REMOTE_PORT)
# integer validation of 'remote_port' action parameter
ret_val, remote_port = self._validate_integer(action_result, remote_port, SSH_JSON_REMOTE_PORT, True)
if phantom.is_fail(ret_val):
return action_result.get_status()
if remote_port:
if direction == "INPUT":
port = "--destination-port {}".format(remote_port)
else:
port = "-dport {}".format(remote_port)
no_port = False
else:
port = ""
user_comment = param.get(SSH_JSON_COMMENT)
if user_comment:
comment = "-m comment --comment '{} -- Added by Phantom'".format(user_comment)
else:
comment = "-m comment --comment 'Added by Phantom'"
if (no_ip and no_port):
return action_result.set_status(phantom.APP_ERROR, SSH_REMOTE_IP_OR_PORT_NOT_SPECIFIED_MSG_ERR)
cmd = "sudo -S iptables -I {} -p {} {} {} -j DROP {}".format(direction,
protocol, remote_ip,
port, comment)
status_code, stdout, exit_status = self._send_command(cmd, action_result, passwd=passwd, timeout=self._timeout)
if phantom.is_fail(status_code):
return action_result.get_status()
if exit_status:
action_result.add_data({"output": stdout})
if not stdout:
return action_result.set_status(phantom.APP_ERROR, SSH_NO_SHELL_OUTPUT_MSG_ERR)
return action_result.set_status(phantom.APP_ERROR, SSH_SHELL_OUTPUT_MSG_ERR.format(stdout=stdout))
action_result = self._save_iptables(action_result, passwd)
return action_result.get_status()
def _handle_ssh_delete_fw_rule(self, param):
""" Should this be changed to only delete rules
created by Phantom?
"""
action_result = ActionResult(dict(param))
self.add_action_result(action_result)