December 23, 2017

Root me write-up : Perl - Command injection

description of  Perl - Command injection

Retrieve the password stored in .passwd.




first scene of Perl - Command injection

There are .passwd, ch7.pl and setuid-wrapper files.

This challenge seems to read the .passwd file using the permissions of the setuid-wrapper file.

※ Two kinds of SUID(Link).




operation of Perl - Command injection

This program prompts you to enter a file path. Then it outputs the statistical results of the contents of the file.



<setuid-wrapper.c>
#include <stdlib.h>

/* setuid script wrapper */

int main()
{
    system("/challenge/app-script/ch7/ch7.pl");
    return 0;
}


<ch7.pl>
#!/usr/bin/perl

delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
$ENV{'PATH'}='/bin:/usr/bin';

use strict;
use warnings;

main();

sub main {
    my ($file, $line) = @_;

    menu();
    prompt();

    while((my $file = <STDIN>)) {
        chomp $file;

        process_file($file);

        prompt();
    }
}

sub prompt {
    local $| = 1;
    print ">>> ";
}
sub menu {
    print "*************************\n";
    print "* Stat File Service    *\n";
    print "*************************\n";
}

sub check_read_access {
    my $f = shift;

    if(-f $f) {
        my $filemode = (stat($f))[2];

        return ($filemode & 4);
    }

    return 0;
}

sub process_file {
    my $file = shift;
    my $line;
    my ($line_count, $char_count, $word_count) = (0,0,0);

    $file =~ /(.+)/;
    $file = $1;
    if(!open(F, $file)) {
        die "[-] Can't open $file: $!\n";
    }


    while(($line = <F>)) {
        $line_count++;
        $char_count += length $line;
        $word_count += scalar(split/\W+/, $line);
    }

    print "~~~ Statistics for \"$file\" ~~~\n";
    print "Lines: $line_count\n";
    print "Words: $word_count\n";
    print "Chars: $char_count\n";

    close F;
}

The perl script file, ch7.pl, uses <STDIN> to accept user input and store it in $file. Then it opens $file to print simple statistics.

Note that this script uses the open () function. This function has a hidden feature that can use shell commands. Details can be found here(Link). This hidden feature can be used to get a flag.




getting flag of Perl - Command injection

The flag obtained successfully.