#!/usr/bin/perl -w
#
# $Id: unconfined 4424 2005-05-03 22:22:18Z sarnold $
#
# ----------------------------------------------------------------------
#    PROPRIETARY DATA of IMMUNIX INC.
#    Copyright (c) 2004, IMMUNIX (All rights reserved)
#
#    This document contains trade secret data which is the property
#    of IMMUNIX Inc.  This document is submitted to recipient in
#    confidence. Information contained herein may not be used, copied
#    or disclosed in whole or in part except as permitted by written
#    agreement signed by an officer of IMMUNIX, Inc.
# ----------------------------------------------------------------------
#
#  unconfined -
#    audit local system for processes listening on network connections
#    that are not currently running with a profile.

use Getopt::Long;

use Locale::gettext;
use POSIX;

setlocale(LC_MESSAGES, "");
textdomain("subdomain-utils");


# options variables
my $paranoid = '';
my $help     = '';

GetOptions(
  'paranoid' => \$paranoid,
  'help|h'   => \$help,
);

# tell 'em how to use it...
&usage && exit if $help;

sub usage {
  printf (gettext("Usage: %s [ --paranoid ]\n"), $0);
  exit 0;
}

my $subdomainfs;
if(open(MOUNTS, "/proc/mounts")) {
  while(<MOUNTS>) {
    chomp;
    $subdomainfs = $1 if m/^\S+\s+(\S+)\s+subdomainfs\s+/;
  }
  close(MOUNTS);
}

die gettext("Can't find the location of subdomainfs\n") unless $subdomainfs;

my @pids;
if($paranoid) {
  opendir(PROC, "/proc") or die gettext("Can't read /proc\n");
  @pids = grep { /^\d+$/ } readdir(PROC);
  closedir(PROC);
} else {
  if(open(NETSTAT, "/bin/netstat -nlp |")) {
    while(<NETSTAT>) {
      chomp;
      push @pids, $5 if /^(tcp|udp)\s+\d+\s+\d+\s+\S+\:(\d+)\s+\S+\:(\*|\d+)\s+(LISTEN|\s+)\s+(\d+)\/(\S+)/;
    }
    close(NETSTAT);
  }
}

for my $pid (sort { $a <=> $b } @pids) {
  my $prog = readlink "/proc/$pid/exe" or next;
  my $attr;
  if(open(CURRENT, "/proc/$pid/attr/current")) {
    while(<CURRENT>) {
      chomp;
      $attr = $_ if(/^\// || /^null/);
    }
    close(CURRENT);
  }
  if(not $attr) {
    if($prog =~ m/^(\/usr\/bin\/python|\/usr\/bin\/perl|\/bin\/bash)$/) {
      #my $scriptname = (split(/\0/, `cat /proc/$pid/cmdline`))[1];
      my $cmdline = `cat /proc/$pid/cmdline`;
      $cmdline =~ s/\0/ /g;
      $cmdline =~ s/\s+$//;
      chomp $cmdline;
      print "$pid $prog ($cmdline) " . gettext("not confined\n");
    } else {
      print "$pid $prog " . gettext("not confined\n");
    }
  } else {
    if($prog =~ m/^(\/usr\/bin\/python|\/usr\/bin\/perl|\/bin\/bash)$/) {
      #my $scriptname = (split(/\0/, `cat /proc/$pid/cmdline`))[1];
      my $cmdline = `cat /proc/$pid/cmdline`;
      $cmdline =~ s/\0/ /g;
      $cmdline =~ s/\s+$//;
      chomp $cmdline;
      print "$pid $prog ($cmdline) " . gettext("confined by") . " '$attr'\n";
    } else {
      print "$pid $prog " . gettext("confined by") . " '$attr'\n";
    }
  }
}
