Skip to content

Instantly share code, notes, and snippets.

@airvzxf
Created December 6, 2020 04:51
Show Gist options
  • Save airvzxf/1c1e4ba15d4e169c66255ac15f01673b to your computer and use it in GitHub Desktop.
Save airvzxf/1c1e4ba15d4e169c66255ac15f01673b to your computer and use it in GitHub Desktop.
Perl: Inject inside of every Python function (`def`) a print statement on this way you can see what is executing during runtime.
#!/usr/bin/perl
#
# Strict and warnings are recommended.
use strict;
use warnings;
use Cwd;
use File::Find;
my $base_path = Cwd::cwd . '/';
my $path = $base_path . 'pwndbg/';
my $extension = 'py';
File::Find::find(\&inject_function, $path);
sub inject_function {
my $file = $File::Find::name;
return unless -f $file;
return unless $file =~ /\.$extension$/;
my $file_relative = $file;
$file_relative =~ s/$base_path//;
print "file: $file ---> $file_relative\n";
# INIT - INJECTION: Variables that you need to setup.
my $injection_import = "from pwndbg.color import message\n";
my $injection_print_init = "print(message.warn(\"";
my $injection_print_end = "\"))\n";
# END - INJECTION: Variables that you need to setup.
my $new_content = '';
open(my $FH, "<", $file) or die "Can't open the file: $!";
while (my $line = <$FH>) {
if ($line =~ /(\s*)(def\s+.*:)[ ]+(.*)/) {
my $spaces = " ";
my $original_spaces = $1;
my $def = $2;
my $instruction = $3;
$def =~ s/\"/\\\"/g;
$new_content .= $original_spaces . $def . "\n";
# INIT - INJECTION: Injection that you need to customize.
$new_content .= $original_spaces . $spaces . $injection_import;
$new_content .= $original_spaces . $spaces . $injection_print_init;
$new_content .= $def . " # " . $file_relative;
$new_content .= $injection_print_end;
# END - INJECTION: Injection that you need to customize.
$new_content .= $original_spaces . $spaces . $instruction . "\n";
}
elsif ($line =~ /\s*(def\s+.*:).*/) {
my $def = $1;
$def =~ s/\"/\\\"/g;
$new_content .= $line;
while (my $sub_line = <$FH>) {
if ($sub_line =~ /^(\s+)\S+/) {
my $spaces = $1;
# INIT - INJECTION: Injection that you need to customize.
$new_content .= $spaces . $injection_import;
$new_content .= $spaces . $injection_print_init;
$new_content .= $def . " # " . $file_relative;
$new_content .= $injection_print_end;
# END - INJECTION: Injection that you need to customize.
$new_content .= $sub_line;
last;
}
$new_content .= $sub_line;
next;
}
}
else {
$new_content .= $line;
}
}
close($FH) || die "Couldn't close $file: $!";
open(my $NFH, ">", $file) or die "$0 ---> Can't open $file in write-open mode: $!";
unless (print $NFH $new_content) {
die "Couldn't write to $file: $!";
}
close($NFH) || die "Couldn't close $file: $!";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment