Skip to contentSkip to conversation

rule analyzer

DISCUSSION Brian Fegler 1 participant 1 message Oct 18, 2002 SELinux security module

lore
Share & tools
lore
#0 lore raw

ha! I suppose I ought to include the program, I've attached it in this email.

I've included it as an attachment and in the email body.

############################################
#!/usr/bin/perl
use strict;

# Author: Brian Fegler ([email protected])
# Copyright (C) 2002 Brian Fegler
#

#   This program is free software; you can redistribute it and/or modify it
#   under the terms of the GNU General Public License as published by the
#   Free Software Foundation; either version 2, or (at your option) any
#   later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.

$| = 1;

#####################################################
######## Global Values ##############################
#####################################################
my $version = ".1";

my $pfile = "/usr/src/selinux/policy/policy.conf";

#May not use this, keeping in here for now.
#my @keep;
#my @toss;

#List of source and destinations the user is
#interested in
my (@src,@dst,@class,@perm);

#set to one if the user wants to only match exact names #given when doing list compares
my $full_name = 0;

#if set to one there will be a short printout
my $short_print_out = 0;

#if set to one the permissions will be alligned when applicable my $align = 0;
my ($wsrc,$wdst,$wclass) = (0,0,0);

#this sets the width of a tab (useful for changing width of tabs when used) #changed with --tab=INTEGER
my $tab = " ";

#determines how many levels deep to print the rule set my %l = ( 1=>1, 2=>1, 3=>1, 4=>1, );

#Make sure all exits call this incase I ever want the #program to exit in a certain way all the time. sub killme {exit;}
$SIG{INT} = \&killme;
#####################################################
######## End Global Values ##########################
#####################################################

#####################################################
#####Reading in user values #########################
#####################################################
#turn options like -df into -d -f

for(my $i=0; $i<=$#ARGV; $i++){
    if($ARGV[$i] =~ /^-\w{2,}$/){
        my @temp = split("",$ARGV[$i]);   
        shift @temp;                      #get rid of leading -
        $_ = "-$_" foreach(@temp);        #slap a - on each element
        splice(@ARGV,$i,1,@temp);         #put switches back in
        $i+=$#temp;                       #don't read what you just put in
    }
}
foreach(@ARGV) {
    if(/^--help$/){
        &help; killme();
    }elsif(/^-h$/){ 
        &short_help; killme();
    }
    
    elsif(/^--todo$/){ 
        &todo; killme();
    }elsif(/^--version$/){ 
        print "$version\n";
        killme();
    }
    elsif(/^--src=/){
        push @src, split(",",$');
    }elsif(/^--dst=/){
        push @dst, split(",",$');
    }elsif(/^--class=/){
        push @class, split(",",$');
    }elsif(/^--perm=/){
        push @perm, split(",",$');
    }
    
    elsif(/^-f$/ || /^--full-name$/){
        $full_name = 1;
    }
    
    
    elsif(/^--pfile=/){
        $pfile = $';
    }


    #print options
    elsif(/^-s$/ || /^--short$/){
        $short_print_out = 1;
    }elsif(/^-a$/ || /^--alignt$/){
        $align = 1;
    }elsif(/^--tab=(\d{1,2})$/){
        $tab = " " x $1;
    }
    
    elsif(/^--l=(1|2|3|4)$/){
        my $start = $1;
        if($start!=4){ $start++;}
        else{ next;}
        for($start .. 4){
            $l{$_} = 0;
        }
    }
    #don't know if i'll use these
    #i don't thing they benefit speed in any way
    #elsif(/^-keep=/){
    #    push @keep, split(",",$');
    #}elsif(/^-toss=/){
    #    push @toss, split(",",$');
    #}
    
    #used for general purpose debugging
    #current program may or maynot use this
    elsif(/^-edebug=/){
        foreach(split("",$')){
            $ENV{"_d$_"}=1;
        }
    }
    
    else{
        print "$_ is an unrecognized option\n";
        killme();
    }

}#end - foreach(@ARGV)
#####################################################
#####Done reading in user values ####################
#####################################################

#####################################################
### validating input ################################
#####################################################

if(!-r $pfile){
    print STDERR "can't read policy file: $pfile\n";
    killme();
}

#####################################################
### done validating input ###########################
#####################################################

#what gets defined

# using "type .*(,.*);
#as mentioned below, not sure what I'll use this for
my %defined;

#{source}{dest}{class} = LIST
#example: {user_xserver_t}{user_home_t}{dir} = read getattr remove_name ... #example: {user_xserver_t}{user_home_t}{file}= read getattr unlink ... my %rules;

my %transitions;

open(FILE, "<$pfile") or die "couldn't open $pfile: $!\n";

LINE: while(my $line=<FILE>){
    chomp $line;
    if($line =~ /^type /){
        #not sure what'll I'll be using this for
        #just though I'd keep my options open
        my @temp = split(/ /, $line);
        @temp = split(/,|, /, $temp[1]);
        $defined{$temp[0]}=1;
    }
    
    elsif($line =~ /^allow /){

        #TODO
        #try this at different locations in the program
        #to see where the most speed is gained
        #if(@keep and !doesExpMatchList($line,\@keep)){
        #    next LINE;
        #}elsif(@toss and doesExpMatchList($line,\@toss)){
        #    next LINE;
        #}

    
        #used for debugging
        #if($line !~ /kde_t/){next LINE;}
        #if($line !~ /user_gpg/){next LINE;}
        
    
        #i've left the print "$line\n"; in there for future debugging

        #i should try doing a single level hash, this might make
        #   the code a little bit shorter, (cleaner?)
        #this could be tested with out deleting code, i suppose
        #test for speed
    
        if($line =~ /^allow\s*((\w*)|{(.*)})\s*((\w*)|{(.*)})(\s*:\s*)((\w*)|{(.*)})\s*((\w*)|{(.*)})\s*;/){
            #print "1=($1) 2=($2) 3=($3) 4=($4) 5=($5) 6=($6) 7=($7) 8=($8) 9=($9) 10=($10) 11=($11) 12=($12) 13=($13)\n";
            my $one   = $1||$2||$3;
            my $two   = $4||$5||$6;
            #: is 7
            my $three = $8||$9||$10;
            my $four  = $11||$12||$13;
            
            foreach my $src ( getAtoms($one) ){
                foreach my $dst ( getAtoms($two) ){
                    foreach my $class ( getAtoms($three) ){
                        #push @{$rules{$src}{$dst}{$class}}, getAtoms($four);
                        addRule($src,$dst,$class,getAtoms($four));
                    }
                }
            }
        
        }elsif($line =~ /^allow (\w*)\s*(\w*):(\w*) (\*|\~.*);$/){
            #allow * *:* \*
            #allow * *:* ~*
            #push @{$rules{$1}{$2}{$3}}, "*";
            addRule($1,$2,$3,getAtoms($4));
        }elsif($line =~ /^allow \w* \w*;$/){
            #should i do anything with these?
        }elsif($line =~ /^allow /){
            #should i toggle this on or off with a switch?
            #print print "ignoring: $line\n";
            next LINE;
        }

    }#end - elsif($line =~ /^allow /)

    #not sure how I'll implement this.    
    #    elsif($line =~ /^type_trans/){
    #         if($line =~ /^type_transition\s*((\w*)|{(.*)})\s*((\w*)|{(.*)})(\s*:\s*)((\w*)|{(.*)})\s*((\w*)|{(.*)})\s*;/){
    #             #print "1=($1) 2=($2) 3=($3) 4=($4) 5=($5) 6=($6) 7=($7) 8=($8) 9=($9) 10=($10) 11=($11) 12=($12) 13=($13)\n";
    #             my $one   = $1||$2||$3;
    #             my $two   = $4||$5||$6;
    #             #: is 7
    #             my $three = $8||$9||$10;
    #             my $four  = $11||$12||$13;
    #             
    #         }else{    
    #             print "ignoring: $line\n";
    #         }
    #     }
    
    #     elsif($line =~ /^role /){
    #     
    #     }elsif($line =~ /^dontaudit /){
    #     
    #     }elsif($line =~ /^auditallow /){
    #     
    #     }elsif($line =~ /^type_change /){
    #     
    #     }elsif($line =~ /^\s*neverallow /){
    #     
    #     }elsif($line =~ /^user /){
    #     
    #     }elsif($line =~ /^attribute /){
    #     
    #     }
    
    #     else {
    #         if($line !~ /^#|^$/){
    #             print "$line\n";
    #         }
    #     }

}#end - while(my $line=<FILE>)
close(FILE);

#keeping only unique permissions

foreach my $src (keys %rules){
    foreach my $dst (sort keys %{$rules{$src}}){
        foreach my $class (sort keys %{$rules{$src}{$dst}}){
            my %perms;
            PERM: foreach my $perm (@{$rules{$src}{$dst}{$class}}){
                $perms{$perm}=1;
            }
            @{$rules{$src}{$dst}{$class}} = keys %perms;
        }#end - class loop
    }#end - dst loop
}#end - src loop

################################################################
#from here on out are all the different printing options #######
################################################################

if($align){
    my %lists;
    #need to widest width of src, dest and class
    
    #1. collect all of the uniq src, dst and class
    #2. determin the widest src, dst and class
    
    SRC: foreach my $src (sort keys %rules){
        $lists{src}{$src}=1;
        DST: foreach my $dst (sort keys %{$rules{$src}}){
            $lists{dst}{$dst}=1;
            foreach my $class (sort keys %{$rules{$src}{$dst}}) {
                $lists{class}{$class}=1;
            }
        }
    }#end - SRC: 

    #these are global values    
    ($wsrc,$wdst,$wclass) = (longest("src"), longest("dst"), longest("class"));
    
    
    sub longest {
        #used only with in the scope of this block of code
        my ($item) = @_;
        my $longest = 0;
        
        for my $atom (keys %{$lists{$item}}){
            my $length = length $atom;
            if($length > $longest){
                $longest = $length;
            }
        }
        return $longest
    }#end - sbu longest
}#end - if($align)
if($short_print_out){
    #because this print out puts a ":" after the dst
    #i am incrementing $wdst, I don't know if future print outs
    #will need this, so I'm just doing it here
    $wdst++;

    #print join("-",sort keys %rules) . "\n";

    SRC: foreach my $src (sort keys %rules){
        
        if($l{2}==0){ 
            printf "%-${wsrc}s ", $src;
            print "\n"; 
            next SRC; 
        }

        DST: foreach my $dst (sort keys %{$rules{$src}}){

            if($l{3}==0){ 
                printf "%-${wsrc}s ", $src;
                printf "%-${wdst}s ", "$dst:";
                print "\n"; 
                next SRC; 
            }

            CLASS: foreach my $class (sort keys %{$rules{$src}{$dst}}) {
        
                if($l{4}==1){print "allow ";}
                printf "%-${wsrc}s ", $src;
                printf "%-${wdst}s ", "$dst:";
                printf "%-${wclass}s ", $class;                    
                if($l{4}==0){ 
                    print "\n"; 
                    next SRC; 
                }

                print "{ @{$rules{$src}{$dst}{$class}} };\n";
            }
        }
    }#end - SRC: 
    killme();
}#end - if($short_print_out)

#printing out the rules
SRC: foreach my $src (sort keys %rules){

    print "$src\n";
    DST: foreach my $dst (sort keys %{$rules{$src}}){
    
        print "$tab$dst\n";
        CLASS: foreach my $class (sort keys %{$rules{$src}{$dst}}) {
            print "$tab$tab";
            printf "%-12s ", $class;
            if($l{4}==0){ 
                print "\n";
                next CLASS;
            }
            print "{ @{$rules{$src}{$dst}{$class}} }\n";
        }
    }#end - DST: 

    #only print out a new line if you are displaying
    #   at least two levels deep
    #if you aren't displaying at least two levels deep 
    #   you are just displaying the src, so need for a double \n
    print "\n" unless($l{2}==0);

}#end - SRC:

killme();
#

# end of program
#
sub addRule { 
    #INPUT
    #   $scalar: source
    #   $scalar: destination
    #   $scalar: class
    #   $array:  list of permission
    #RETURN
    #   undef
    #DESCRIPTION
    #   determines if this rule should be added to the rule set
    #   if at anyone time it determines that it shouldn't it 
    #       returns with out adding it
    #   if the rule should be added, it'll be done, and the program
    #       will return

    my($src,$dst,$class,@these_perms) = @_;


    if(@src   and !doesExpMatchList($src,\@src)){     return; }
    if(@dst   and !doesExpMatchList($dst,\@dst)){     return; }
    if(@class and !doesExpMatchList($class,\@class)){ return; }


    if(@perm){
        #if no permissions were selected don't bother with this
        my @keep_these_perm;
        PERM: foreach my $perm (@these_perms){
            if(doesExpMatchList($perm,\@perm)){
                push @keep_these_perm, $perm;
            }
        }
        if(!@keep_these_perm){
            return;
        }
        @these_perms = @keep_these_perm;
    }


    if($l{4}){
        push @{$rules{$src}{$dst}{$class}}, @these_perms;
    }elsif($l{3}){
        @{$rules{$src}{$dst}{$class}} = ();
    }elsif($l{2}){
        $rules{$src}{$dst} = undef;
    }elsif($l{1}){
        $rules{$src} = undef;
    }
    
    return;
}#end - sub addRule

sub getAtoms {
#INPUT
# $scalar: a string coming from inside {}'s
# It doesn't matter if there are embedded {}'s
#RETURN
# @array: the list of strings (not including {}'s) found
# within the top {}'s
my $list = shift;
$list =~ s/{|}//g;
return split(" ", $list);
}#end - sub getAtoms

sub doesExpMatchList {
#INPUT
# $scalar: the string you want to look for in the list
# @array: list of reg exps you want to compare the scalar to
# the list will be used as is, (as in it will not be
# converted from a user reg exp to a perl reg expt
#RETURN
# 1 if a match occurred
# 0 if no match found
#DESCRIPTION
# give it a string and a list of regular expressions
# if the string matches any one reg exp return 1
# other wise return 0
# this is CASE INSENSITIVE
#MISC
# Uses the global variable "$full_name" to determine if
# exact matches are required.

my ($string,$l) = @_;

foreach my $try(@{$l}){
if(!$full_name && $string =~ /$try/i){ return 1; } if( $full_name && $string =~ /^$try$/){ return 1; }
}
return 0;
}#end - sub doesExpMatchList

sub intersection {
    #INPUT:
    #   two references to arrays
    #RETURN
    #   1 if any one element in the first array
    #   matches any one element in the second array, using
    #   the list compare that the rest of the program uses
    
    my ($first, $second) = @_;
    
    for my $f (@{$first}){
        if(doesExpMatchList($f, \@{$second})){
            return 1;
        }
    }
}#end - sub intersection

sub todo {
print "
TODO (someday)(in no particular order)

1. List type_transitions.

2. Create multiple, user selectable print functions for the rulesets.
Example: html, condensed, ...?

3. Possibly use a conf file to alter certain parts of any one print function. Examples
A. Never use line breaks, except at the end of a source line. B. Group certain dst's, with no line breaks within a group. C. Condense groups of permissions down to one permission.
file {ioctl read getattr access lock poll write setattr append} file { rw_file_perms }
These could be hardcoded, or user defined.
Don't know if i want to turn this into a \"two file\" script, though.

4. Once kde rules are finished (unrelated to this program) I'd like to use this code (which hopefully will be refined by then), to create a GUI based version of this program. The GUI would most likely read everything into memory and then display, and clear, the results for each query.

5. Force user input to be POSIX compliant, and give dst, pfile, and src single letter aliases.

";
}#end - sub todo

sub short_help {
print "
Displays SELinux rules.

--src=LIST List of sources to display.
--dst=LIST List of destinations to select from.
--class=LIST List of classes to select from.
--perm=LIST List of permissions to select from.

-f,--full-name Match complete names only.
--pfile=FILE Specify a policy file.

-s, --short Condense the print out.
-a, --align Aligns colums when applicable.
--tab=INTEGER Sets width of tabs.
--l=(1|2|3|4) Level of info you want to see.

--todo Show the TODO list.
-h Displays this screen.
--help Displays full version of help.
--version Prints version and exits.

";
}#end - sub short_help

sub help {
print "
NAME
cando - displays what cando what in a given policy.conf file.

DESCRIPTION
The given input file has to be a finished SELinux rule set. No macros will be translated.

Each LIST is made up of one or more comma separated strings. By default the compares of lists are case insensative and any match of any element is successful. \"-f\" or \"--full-name\" requires exact matches.

This help file's nomenclature:
allow source destination:class permissions abbreviated:
allow src dst:class permissions

As of this version ($version), backwards compatability is completely disregared, and not thought of for each subsequent release.

OPTIONS
-a, --align
Aligns colums when applicable.

--dst=LIST
Will keep only rules that interact with any destination in the supplied list.

--class=LIST
Will keep only rules that interact with any class in the supplied list.

-f, --full-name
When comparing a string to a list the full string will have match, including case.

-h
Display short help.

--help
Displays this help screen.

--l=(1|2|3|4)
How much info you want to see. src==1, dst==2, class=3, Perm=4. This is useful if all you want to see is the sources that can exececute bin_t files.
Example: \"cando --dst=bin_t --perm=execute -s --l=1\"

--perm=LIST
List of permissions you'd like to see.

--pfile=FILE
Use a supplied file name instead of the default.
Default: $pfile

-s, --short
Condense the print out.

--scr=LIST
Will keep all rules who's source in in LIST.

--tab=INTEGER
Sets width of tabs.

--todo
Display the TODO list for this program.

--version
Prints version and exits.

EXAMPLES
The following examples are from the default policy.

cando --src=rpm_t
Shows all rules for rpm_tmpfs_t and rpm_t.

cando --src=rpm_t -f
Shows all the rules for rpm_t.

cando --src=rpm_t --dst=tmpfs_t
Shows:
what rpm_tmpfs_t can do to tmpfs_t
what rpm_t can do to tmpfs_t and rpm_tmpfs_t

cando --src=rpm_t --dst=tmpfs_t -f
Shows what rpm_t can do to tmpfs_t.

cando --dst=user_gpg_secret_t
Shows all sources that can do anything to a destination that mathes \"user_gpg_secret_t\".

cando --dst=user_gpg_t
Shows all sources that can do anything with the user_gpg_t type.

cando --dst=gpg --perm=execute -sa
Shows every domain that can execute any \"gpg\" type. The output is shortened (-s), and aligned (-a).

cando --src=httpd --dst=^user
Shows what any httpd domain can do to any domain that starts with user

AUTHOR
Brian Fegler <brianfegler\@bigfoot.com>

";
}

#############################################