#!/bin/bash
# Copyright (C) 2003, 2004 Red Hat, Inc.
# Written by Ingo Molnar and Ulrich Drepper
if [ "$#" != "1" ]; then
  echo "usage: lsexec [ <PID> | process name | --all ]"
  exit 1
fi
if ! test -f /etc/redhat-release; then
  echo "this script is written for RHEL or Fedora Core"
  exit 1
fi

cd /proc

printit() {
    if [ -r $1/maps ]; then
     echo -n $(basename $(readlink $1/exe))
     printf ", PID %6d" $1
     printf ", UID %s: " `ps -ef | awk 'PID == $2 { print $1 }' "PID=$1"`
     if [ -r $1/exe ]; then
       if eu-readelf -h $1/exe|egrep -q 'Type:[[:space:]]*EXEC'; then
         echo -n -e 'no PIE, '
       else
         if eu-readelf -d $1/exe|egrep -q '  DEBUG[[:space:]]*$'; then
           echo -n -e 'PIE, '
	   if eu-readelf -d $1/exe|fgrep -q TEXTREL; then
	     echo -n -e 'TEXTREL, '
	   fi
	  else
	   echo -n -e 'DSO, '
          fi
       fi
       if eu-readelf -l $1/exe|fgrep -q 'GNU_RELRO'; then
	 if eu-readelf -d $1/exe|fgrep -q '_BIND_NOW'; then
           echo -n -e 'full RELRO, '
         else
           echo -n -e 'partial RELRO, '
         fi
       else
         echo -n -e 'no RELRO, '
       fi
     fi
     lastpg=$(sed -n '/^[[:xdigit:]]*-[[:xdigit:]]* rw.. \([[:xdigit:]]*\) 00:00 0$/p' $1/maps|
	      tail -n 1)
     if echo "$lastpg" | egrep -v -q ' rwx. '; then
       lastpg=""
     fi
     if [ -z "$lastpg" ] || [ -z "$(echo $lastpg||cut -d ' ' -f3|tr -d 0)" ]; then
       echo -e 'execshield enabled'
     else
      echo -e 'execshield disabled'
      for N in `awk '{print $6}' $1/maps  | egrep '\.so|bin/' | grep '^/' | sort -u`; do
        NE=$(eu-readelf -l $N | fgrep STACK | fgrep 'RW ')
        if [ "$NE" = "" ]; then
          echo " => $N disables exec-shield!"
        fi
      done
     fi
    fi
}

if [ -d $1 ]; then
  printit $1
  exit 0
fi

if [ "$1" = "--all" ]; then
   for N in [1-9]*; do
     if [ $N != $$ ] && readlink $N/exe > /dev/null 2>&1; then
       printit $N
     fi
   done
   exit 0
fi

for N in `/sbin/pidof $1`; do
 if [ -d $N ]; then
  printit $N
 fi
done
