3 # Signature-du-Terroir module to handle /proc/<pid>
7 Start a command that will stall on reading STDIN, eg, grep, cat, dd, perl, python, ruby, bash.
8 Or enter the PID of an existing, running, task.
10 Use /proc/<pid>/{exe, maps} to collect information, eg, all loaded libraries, the file paths,
11 inode numbers, and mem addresses. Then use dbugfs to read out the inode numbers. The results can be
12 hashed with sha512sum (recommended) or returned raw.
15 reset() : Empty cache, next call to get_info() will run the command
16 get_info(command) : Run command and read all info, if command differs from current_command
17 get_info(PID) : Read all info from running process PID, if command differs from current pid
20 current_command : Command (path) for which the current values are relevant
21 address_list : The start, end, and offset addresses for each file (path) loaded (/proc/<pid>/maps). Ie, each address_list[path] is a list of address lists.
22 map_list : Information for /proc/<pid>/maps - [path]={'permissions', 'device', 'inode'}
23 path_list : All files (paths) loaded for the current command (/proc/<pid>/maps).
24 mapsfile : The first file path in /proc/<pid>/maps, ie, the file with the command
25 file_system : Device, /dev/..., on which mapsfile is stored
26 exe : The path to which /proc/<pid>/exe links
28 Methods returning contents of /proc/<pid>/maps as text tables
29 paths (command, key_list) : A table of all paths with one or more of ['permissions', 'device', 'inode'] (inode is default)
31 The following methods return the SHA512 hash. They use the prefix to start the hash
32 Files are read using the inode numbers with debugfs (sudo only)
33 inodeSHA (command, file, prefix): The file contents based on the inode number in /proc/<pid>/maps, if 'file' is '', the mapsfile is used.
34 mapsSHA (command, prefix) : All files in /proc/<pid>/maps, based on inode number
36 For debugging purposes:
37 fileSHA (command, prefix) : Simple file read from disk using mapsfile
38 exeSHA (command, prefix) : File read using the exe link
40 The following methods return the WHOLE, binary file content
41 Files are read using the inode numbers with debugfs (sudo only)
42 inode (command, file): The file based on the inode number in /proc/<pid>/maps
43 maps (command) : All files in /proc/<pid>/maps, based on inode number
45 For debugging purposes:
46 file (command) : Simple file read from disk using mapsfile
47 exe (command) : File read using the exe link
50 > python3 proc_PID.py [path1 ....]
51 Will run for each path:
65 # Basic support routines
66 def create_process (command
):
67 devnull
= open('/dev/null', 'w');
68 return subprocess
.Popen(command
.split(), stdin
= subprocess
.PIPE
, stdout
= devnull
, stderr
= subprocess
.PIPE
, shell
=False, universal_newlines
=False);
70 def kill_process (process
):
71 process
.stdin
.close();
72 errormess
= process
.stderr
.read();
73 if len(errormess
) > 0: print(str(errormess
), file=sys
.stderr
);
84 # Determine the file system on which a file is stored (using df)
85 def get_filesystem(path
):
86 command
= 'df -h '+path
+' |tail -1';
87 process
= subprocess
.Popen(command
, stdin
= None, stdout
= subprocess
.PIPE
, stderr
= sys
.stderr
, shell
=True, universal_newlines
=True);
88 df_output
= process
.stdout
.read();
89 return df_output
.split()[0];
91 def get_debugfs_command (path
, inode
):
93 print("ERROR: must be root to read disk blocks\n", file=sys
.stderr
);
95 file_system
= get_filesystem(path
);
96 return "/sbin/debugfs -f - "+file_system
+" -R 'cat <"+str(inode
)+">'";
105 global current_command
;
112 current_command
= '';
114 # Start command and read info from /proc/<pid>/
115 # Do nothing if the command is identical to previous one
116 def getinfo (command
): # -> pid
123 global current_command
;
125 if command
== current_command
:
129 current_command
= command
;
131 # Do not create a process if it already exists
132 kill_process
= False;
133 if isinstance(command
, int):
135 elif re
.search(r
'[^0-9]', command
) == None:
138 process
= create_process(command
);
140 # Wait a quarter of a second to allow the loading of the command to finish
143 dir = '/proc/'+str(pid
);
144 exe
= os
.readlink(dir+'/exe');
146 # Get all mapped memory and files
147 with
open(dir+'/maps', 'r') as file:
149 record_list
= l
.split();
150 if len(record_list
) == 6 and int(record_list
[4]) > 0:
151 (addresses
, permissions
, offset
, device
, inode
, path
) = record_list
;
152 if path
not in path_list
:
153 path_list
.append(path
);
154 map_list
[path
] = {'permissions':permissions
, 'device':device
, 'inode':inode
};
155 address_list
[path
] = [];
156 (address1
, address2
) = addresses
.split('-');
157 address_list
[path
].append({'start':address1
, 'end':address2
, 'offset':offset
});
158 if kill_process
: kill_process(process
);
159 mapsfile
= path_list
[0];
160 file_system
= get_filesystem(mapsfile
);
163 # Print out running proc stats
164 def paths (command
, key_list
= 'inode'): # 'key'/['key1', 'key2', ...] -> text-table
168 if isinstance(key_list
, str):
169 key_list
= [key_list
];
170 # Construct a line for each path,
172 for path
in path_list
:
175 line
+= '\t'+map_list
[path
][key
];
177 result_table
+= line
;
180 # Methods that return the raw file contents (could be LARGE)
184 with
open(mapsfile
, 'rb') as file:
186 if type(l
).__name
__ == 'str':
187 l
= bytes(l
, encoding
='utf8');
194 with
open(exe
, 'rb') as file:
196 if type(l
).__name
__ == 'str':
197 l
= bytes(l
, encoding
='utf8');
199 kill_process(process
);
202 def inode (command
, path
):
205 # Get file contents on inode number
207 inode
= map_list
[path
]['inode'];
208 debugfs
= subprocess
.Popen(get_debugfs_command(path
, inode
), stdin
= None, stdout
= subprocess
.PIPE
, stderr
= sys
.stderr
, shell
=True, universal_newlines
=False);
209 # read out the file contents
210 for l
in debugfs
.stdout
:
211 if type(l
).__name
__ == 'str':
212 l
= bytes(l
, encoding
='utf8');
220 # Get file contents on inode number
222 for file in path_list
:
223 inode
= map_list
[file]['inode'];
224 debugfs
= subprocess
.Popen(get_debugfs_command(path
, inode
), stdin
= None, stdout
= subprocess
.PIPE
, stderr
= sys
.stderr
, shell
=True, universal_newlines
=False);
225 # read out the file contents
226 for l
in debugfs
.stdout
:
227 if type(l
).__name
__ == 'str':
228 l
= bytes(l
, encoding
='utf8');
233 # Methods that return the SHA512sum
234 def fileSHA (command
, prefix
=''):
236 filehash
= hashlib
.sha512(bytes(prefix
, encoding
='ascii'));
237 with
open(mapsfile
, 'rb') as file:
239 if type(l
).__name
__ == 'str':
240 l
= bytes(l
, encoding
='utf8');
242 return str(filehash
.hexdigest());
244 def exeSHA (command
, prefix
=''):
246 exehash
= hashlib
.sha512(bytes(prefix
, encoding
='ascii'));
247 with
open(exe
, 'rb') as file:
249 if type(l
).__name
__ == 'str':
250 l
= bytes(l
, encoding
='utf8');
252 return str(exehash
.hexdigest());
254 def inodeSHA (command
, path
='', prefix
=''):
256 if len(path
) == 0: path
= mapsfile
;
258 # Get file contents on inode number
259 mapshash
= hashlib
.sha512(bytes(prefix
, encoding
='ascii'));
260 inode
= map_list
[path
]['inode'];
261 debugfs
= subprocess
.Popen(get_debugfs_command(path
, inode
), stdin
= None, stdout
= subprocess
.PIPE
, stderr
= sys
.stderr
, shell
=True, universal_newlines
=False);
262 # read out the file contents
263 for l
in debugfs
.stdout
:
264 if type(l
).__name
__ == 'str':
265 l
= bytes(l
, encoding
='utf8');
268 return str(mapshash
.hexdigest());
270 def mapsSHA (command
, prefix
=''):
273 # Get file contents on inode number
274 mapshash
= hashlib
.sha512(bytes(prefix
, encoding
='ascii'));
275 for path
in path_list
:
276 inode
= map_list
[path
]['inode'];
277 debugfs
= subprocess
.Popen(get_debugfs_command(path
, inode
), stdin
= None, stdout
= subprocess
.PIPE
, stderr
= sys
.stderr
, shell
=True, universal_newlines
=False);
278 # read out the file contents
279 for l
in debugfs
.stdout
:
280 if type(l
).__name
__ == 'str':
281 l
= bytes(l
, encoding
='utf8');
284 return str(mapshash
.hexdigest());
286 if __name__
== "__main__":
287 if len(sys
.argv
) == 1:
290 for command
in sys
.argv
[1:]:
291 result
= fileSHA(command
);
292 print(mapsfile
+(len("/proc/<pid>/inode") - len(mapsfile
))*' ', result
);
293 result
= exeSHA(command
);
294 print("/proc/<pid>/exe"+(len("/proc/<pid>/inode") - len("/proc/<pid>/exe"))*' ', result
);
296 result
= inodeSHA(command
);
297 print("/proc/<pid>/inode"+(len(mapsfile
) - len("/proc/<pid>/inode"))*' ', result
);
298 result
= mapsSHA(command
);
299 print("/proc/<pid>/maps"+(len("/proc/<pid>/inode") - len("/proc/<pid>/all"))*' ', result
);
302 result
= paths(command
);