Pages

Thursday, March 3, 2011

Linux Commands to get you started

'man'
  • Command mode accessible through ESC
  • /<search string>  - use 'n' to continue search
  • 'b' to go up a page
'info'
  • Control-S used to search
  • 'control-s' to continue the search
  • Control-G to end that task
  • Set up cursor on index points and hit enter to be taken to that section
  • Use 'l' to return to previous position with relation to indexed point
'man -k <keyword>' looks for keyword one-line synoposis entries
'apropos <keyword>' identical to above

'vi'
  • vi editor, command mode accessible through ESC
  • 'dd' - deletes a line
  • '/' search, similar to man pages
  • :wq - write and quit
  • :q! - quit without writing
'rm <file>' remove a file
'rm -i <file>' , interact flag for rm - prompt for confirmation on file deletion
'mkdir <name>' , create a directory
'rmdir <name>', remove an empty directory

'ls' - list the contents of current location
'ls -a' - list the contents of current location including all files beginning with a period (.)
'ls -l' - long listing format, includes DAC layout, along with other properties.

'cp' - copy
'mv' - rename/move

Terms to be aware of:  Absolute path - begins with a '/'
Relative path: - relative to the current directory inwhich the command is executed

Special files for easy configuration.

.bash_profile, easily modify the path to search for programs!
.bashrc , easily modify aliases surrounding common commands you may use.
example:  alias rm='rm -i'

source <file> , ie: source .bashrc
implement changes/take effect the current changes made, without exit/relogging.

nroff input for man pages is kept in /usr/share/man/manX, compressed with gzip to save space.  'man' knows how to uncompress on the fly.

Formatted versions of the manuals are kept in /var/cache/man/catX.  Should the directory be writable, man will also deposit the formatted pages as they are created, generating a cache of commonly read man pages.

'manpath' will display the path 'man' utilizes when searching for manual pages as per your request.  The system wide default can be configured in /etc/man.config (on some distributions)  The PAGER environment variable controls the way inwhich the listing of the man pages is utilized, typically using 'less'.

Monday, February 21, 2011

Properties of Real Numbers

Commutative Properties

  • a + b = b + a
  • Example: 7 + 3 = 3 + 7
  • When we add two numbers, order doesn't matter.

  • ab = ba
  • Example: 3 * 5 = 5 * 3
  • When we multiply two numbers, order doesn't matter.

Associative Properties
  • (a + b) + c = a + (b + c)
  • Example: (2 + 4) + 8 = 2 + (4 + 8)
  • When we add three numbers, it does not matter which two we add first.

  • (ab)c = a(bc)
  • Example: (3 * 7) * 5 = 3 * (7 * 5)
  • When we multiple three numbers, it does not matter which two we multiple first.

Distributive Property
  • a(b + c) = ab + ac
  • Example: 2 * (3 + 5) = 2 * 3 + 2 * 5
  • When we multiply a number by a sum of two numbers, we get the same result as multiplying the number by each of the terms and then adding the products.
  • (b + c)a = ab + ac
  • Example: (4 + 5) * 2 = 2 * 4 + 2 * 5

Monday, February 7, 2011

Patterns of PI

When plotting graphs using radians I often found it tedious to have to try and memorize the formulas for degrees based on Pi.  However, it is not necessary to do so, if you can understand the fundamental concepts and are receptive to the continuing patterns throughout, charting graphs based on PI can be easy.

Watch the patterns !

π/2 , π, 3π/2, 2π, 5π/2, 3π, 7π/2, 4π, 9π/2, 5π, 11π/2, 6π, 13π/2, 7π, 15π/2, 8π

90, 180, 270, 360, 450, 540, 630, 720, 810, 900, 990, 1080, 1170, 1260, 1350, 1440 respectively. (degrees)

 Now let's incorporate that pattern into a similar pattern, this one including the special angles 30 and 60.

π/6, π/3, π/2, 2π/3, 5π/6, π, 7π/6, 4π/3, 3π/2, 5π/3, 11π/6, 2π, 13π/6, 7π/3, 5π/2, 8π/3, 17π/6, 3π

30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360, 390, 420, 450, 480, 510, 540 respectively. (degrees)

Sunday, February 6, 2011

Brief History of Electronics / PC

1642
  • Blaise Pascal introduces Pascaline Digital Adding Machine
1822
  • Charles Babbage introduces the Difference Engine & later the Analytical Engine, a true general-purpose computing machine
1906
  • Lee DeForest patents the Vacuum Tube Triode, used as an electronic switch in the first electronic computer
1936
  • Konrad Zuse begins work on a series of computers, considered the first electric binary computers, using electromechnical switches and relays
  • Alan Turing publishes "On Computable Numbers" a paper in which he conceives an imaginary computer called the Turing Machine, considered one of the foundations of modern computing
1937
  • John V. Atanasoff begins work on the Atanasoff-Berry Computer officially credited as first electronic computer
1945
  • John von Neumann writes "First Draft of a Report on the EDVAC" which outlines the architecture of the modern stored-program computer
1946
  • John Mauchly & J. Presper Eckert introduce ENIAC - an electronic computing machine.
1947
  • William Shockley, Walter Brattain & John Bardeen successfully test the point-contact transistor, setting off the semiconductor revolution.
1949
  • Maurice Wilkes assembles the EDSAC, the first practical stored-program computer.
1953
  • IBM ships it's first electronic computer the 701.
1954
  • Gordon Teal (Texas Instruments) perfects the silicon-based transistor, bring a tremendous reduction in costs.
1955
  • Bell Laboratories announces the first fully transistorized computer, the TRADIC.
1956
  • MIT researchers build the TX-0, the first general-purpose, programmable computer built with transistors.
  • IBM - ushers in the era of magnetic disk storage, with shipment of a 305 RAMAC to Zellerbach Paper in San Francisco.
1958
  • Jack Kilby (Texas Instruments) creates the first integrated circuit to prove that resistors and capacitators can exist on the same piece of semiconductor material.
1959
  • IBM releases its 7000 series mainframes and are the company's first transistorized computer.
  • Robert Noyce creates practical integrated circuit.  Allowing printing of conducting channels directly on the silicon surface.
  • Bell Laboratories designs it's Dataphone, the first commercial modem, converting digital computer data to analog signals for transmission across it's long distance network.
1965
  • Digital Equipment Corporation (DEC) introduces the PDP-8, the first commercially successful minicomputer.
1969
  • Department of Defense establishes four nodes on the ARPA network, in what will become the internet.
  • The Unix operating system is conceived and implemented at AT&T's Bell Laboratories by Ken Thompson, Dennis Ritchies, Douglas McIlroy and Joe Ossanna.
1971
  • Intel advertises first microprocessor, intel 4004
  • Scientific American - advertises the KENBAK-1 for $750.00 USD, one of the first personal computers.
  • Unix is released, entirely written in Assembly language.
1972
  • Intel debuts the 8008 microprocessor
1973
  • Robert Metcalfe (Xerox) devises the ethernet method of network connection.
  • The Micral - the earliest non-kit personal computer based on a microprocessor, the Intel 8008.
  • Dennis Ritchie rewrites Unix in the C programming language, except for the kernel and I/O.
1974
  • Xerox designs the Alto.  The first workstation with a built in mouse for input.
1975
  • Telenet, the first commercial packet-switching network and civilian equivalent of ARPA net.
  • Popular Electronics features the Altair 8800 which is based on Intel's 8080 microprocessor.
1976
  • Steve Wozniak designs the Apple I, a single-board computer
  • Shugart Associates introduce the 5 1/4" floppy disk
1977
  • Tandy Radioshack introduce the TRS-80
  • Commodore introduces the PET (Personal Electronic Transactor)
1979
  • Motorola introduces the 68000 microprocessor
1980
  • Seagate Technology creates the first hard disk drive for microcomputers, the ST-506.
1981
  • Xerox introduces the first personal computer with a graphical interface, called the Star.
  • IBM introduces it's P.C (considered the Grandfather of modern P.C's)
  • Sony debuts & ships the first 3 1/2" floppy disk drive.
  • Phillips & Sony introduce the CD-DA (Compact Disc Digital Audio) format.
  • Chase Bishop designs the first model of an electronic device and project "Interface Manager" (birth of Windows)
1983
  • Apple releases Lisa.
  • Richard Stallman announces and begins the GNU project.
  • Microsoft announces Windows.
1984
  • Apple launches Macintosh, with a mouse driven GUI
1985
  • IBM releases PC-AT (Advanced Technology) 3x faster than original P.C
  • s and is based on the Intel 286 chip.  The AT introduces the 16-Bit ISA Bus & is the computer on which all modern P.C's are based.
  • Microsoft introduces an operating environment named Windows 1.0 as an add-on to MS-DOS.
1986
  • Compaq announces desktop 386 first computer on the market to use Intel's 32-Bit 386 chip.
1987
  • IBM introduces PS/2 machines, making 3 1/2" floppy disk drives & VGA video standard for P.C's.  PS/2 introduces microchannel architecture (MCA) bus, the first Plug N' Play bus for PC's.
  • Andrew S. Tanenbaum releases MINIX, a Unix-like computer operating system based on microkernel architecture.
  • Windows 2.0 is released.
1988
  • Compaq and other P.C clone makers develop Enhanced Industry Standard Architecture (EISA) which unlike MCA, retains backward compatibility with the existing ISA Bus.
1989
  • Intel releases the 486 (P4) microprocessor and also introduces the 486 motherboard chipsets.
  • Richard Stallman writes and releases the GNU GPL.
1990
  • Tim Berners-Lee (CERN) develops Hypertext Markup Language (HTML) and with it, the WWW is born.
1991
  • Linus Torvalds develops the Linux kernel.
1993
  • Intel releases the Pentium (P5) processor with numbers having been changed to names due to trademarks.  Intel also releases "Complete" motherboards.
... and the list goes on !

Numbers and Number Systems

Natural Numbers
  • {1, 2, 3, ....}
Whole Numbers
  • {0, 1, 2, 3, ...}
Integers
  • Either signed or unsigned, denoted by \mathbb{Z} referring to the set of all integers
Decimal (Base 10) Digits 0 - 9
  • Utilizes the digits 0 - 9
Rational Numbers
  • Terminating decimals, or repeating decimals (P / Q) Where P & Q are both integers, and Q != 0.
  • 1/1 = 1 is a rational number, 2/1 is a rational number.
Irrational Numbers
  • Neither terminate nor repeat, ie:  π (Pi)
Real numbers
  • Rational Numbers + Irrational Numbers
Binary
  • Base 2
  • Converting Whole numbers to binary is easy.
  • Steps are as follows:
  1. Divide by 2, remainder represents LSB (Least Significant Bit)
  2. Continue to divide by two, until division by 2 is not possible. 
  3. The final remainder will represent the MSB (Most Significant Bit)
  4. Written MSB on left, LSB on right.
Example: 25(base ten) : 25 / 2 = 12 r. 1[LSB], 12 / 2 = 6, r. 0, 6 / 2 = 3 r.0, 3/2 = 1 r.1, 1/2 = 0. r 1[MSB]
Written: 11001
  • Like all systems utilizes place value.  Ie:  10110 = (1 * 2^4) + (0 * 2^3) + (1 *2^2) + (1 * 2^1) + (0 * 2^0) = 22

Hexadecimal
  • Base 16
  • Utilizes digits 0 - 9
  • Expands, to include A, B, C, D, E, F - A representing 10, continuing respectively
  • Utilizes the same place value system as used in our number systems across the board, however with a base of 16.
  • Example: 2BD = (2 * 16^2) + (11 * 16^1) + (2 * 16^0)
  • Converting Whole numbers to hexadecimal is identical to converting whole numbers to binary except a divisor of 16 is used.   Example:  589 / 16 = 36 r. 13, 36 / 16 = 2 r. 4, 2 / 16 = 0 r. 2 , written: 24D
  • Converting hexadecimal to binary, divide the Hex Digits into 4 bit patterns (nibbles), 24D for example = 0010 / 0100 / 1101 -> 001001001101
  • Each hex digit = nibble, 2 Hex digits = 1 byte

Friday, February 4, 2011

Beginner's Guide to Reverse Code Engineering

There may come a moment in every man's life, where one has the urge to understand the obfuscated functionality of a program they run on their Windows machine. There exist many reasons for wanting to understand how a closed-source precompiled binary works, but the most important would be for knowledge.
This guide was designed for beginner's who have very little to no experience in reversing, so the guide will be fairly straightforward. I suggest learning about C, x86 Assembly, the PE Specification, and of course, how to use a debugger.
Tools
The tools required for reversing will span far beyond the scope of this article however, you will be introduced to several vital tools:
  • Ollydebug - the olly debugger, a scripted and powerful tool which will aid us for dynamic analysis of a closed-source program.
  • PEiD - A useful tool for detecting packers, compilers and PE information.
  • PE Explorer - Used for PE analysis, includes a disassembler
  • IDA Pro - A static disassembler, very vital for understanding how assemblies work.
Sample Program
We'll be using a canned program called a crackme to get you acquainted with RCE. The crackme is called Zyrel's Simple KeygenMe#2 and the basic goals are to create a KeyGen.
Sometimes, we can use existing code to write a keygen, other times we must reverse the algorithm used to compute the serials. Since this is a beginner tutorial, you don't have to worry about reversing those algorithms.
PE Analysis
Start the program. You'll notice the Name and Key field. This should be pretty obvious. Typing in junk into those fields and clicking register will either a) cause the program to crash (a bug) or b) do nothing.

Load the program into PEiD. You can see standard PE segments, an entry point which is within .text and a "nothing found" on the bottom field. This just means that the program was written in standard C/C++, gcc probably. Also, note there is no packer installed (although this is not always the case).
Static Analysis
Open PE Explorer, let's see if we can determine anything from there. As we can see from the disassembler, nothing clear is shown for us (just remember, keep PE Explorer around, it will become more useful as the programs we're reversing become more complex).

Start IDA Pro, we will use it for static analysis of the program routines. Okay, I usually set auto-comments, stack values, and 9 opcode values. First, let's examine the strings window. Allow for C style strings (NULL terminated). You can see the strings used for the fields, title of the program and, most importantly, the strings used for notifying us of success (if we entered the right serial key):

.rdata:0043F084 00000037 C Seriale corretto, programma correttamente registrato.!
This looks like what we want. So this string is read once we type in the correct key. Double click on it. This will move you to the .rdata segment which contains the string. Select the string XREF. As you can see, this string is referenced only once in the code. Probably by the routine which tells us whether or not we have succeeded.


We can see that 00401D3B is branched off from a jnz (jump if not zero) instruction @ 00401D35. A cmp instruction @ 00401D2E checks that [ebp + 218] is equal to 0. As we can see, strcmp is called @ 00401D12, which compares two strings at [esp] and [esp + 4]. There is a high probability that the two strings are your input Key field (judging by a call to GetDlgItemTextA), and the computed string value. Perfect, this means we just have to fish for the key at runtime.
You may also go further up the function to determine which routine is used to compute the serial. This is not necessary as the only goal of the crackme is to create a keygen.
Label what you require and use IDA to export a .map file.
Dynamic Analysis
Once you have Ollydbg going, install the GODUP plugin. Load the crackme inside Olly, you'll notice that Olly will stop at the module entry point. Go to the GODUP plugin and load your .map file. This file will make use of the comments and function names generated by IDA, it will make it easier for us to orientate ourselves within code.
Go to instruction 00401D35, our jnz instruction indicated by IDA. Place a breakpoint on that instruction and run the program. Type in anything for the name field, and type in anything for the Key. The program should stop at 00401D35. The key is probably wrong, therefore cmp will check the output of strcmp (at ebp - 0x218), and set the EFL z-flag to 0 - jnz will jump to subroutine 00401E0F; we do not want this. Set the z-flag to 1, so the jump never occurs and our MessageBox says "Complimenti":


So, I've set EFL Z-Flag to 1, so the jump never takes place. Press F9 and you'll see that the Congrats message box tells us that we've found the serial. Also note:
strcmp() is passed [ebp - 0x20c] and a pointer stored in [ebp - 0x210]. These pointers are the generated key and typed-in key, respectively. Strcmp will obviously return -1, indicating that the strings do not match, this value will be stored in [ebp - 0x218]. cmp will then check that [ebp - 0x218] is 0 (which is the successful return value of strcmp()), if it is 0xffffffff, the serial and input serial do not match, therefore the MessageBoxA is never called.
As you can see, [esp] contains a pointer to the actual serial key and [esp + 4] contains our input key.
Patching
Next, we must patch the program in order to write the key generator for this keygenme. We can either:
  • Reverse the algorithm
  • Patch the program
I will show you how to patch the program, as this algorithm is rather straightforward, you should have no trouble writing it from scratch.
Okay, so the game plan is to remove instructions which we do not need and replace them with our own. I think the best way to do this would be:
NOP the cmp instruction at 00401D2E, which will give us 7 bytes of space.
NOP the jnz instruction at 00401D35, which will give us 6 bytes of space.
Also, NOP these four instructions:
.text:00401D3B 29C C7 44 24 0C 00 00 00 00 mov dword ptr [esp+0Ch], 0
.text:00401D43 29C C7 44 24 08 78 F0 43 00 mov dword ptr [esp+8], offset Caption ; "Complimenti"
.text:00401D4B 29C C7 44 24 04 84 F0 43 00 mov dword ptr [esp+4], offset Text ; "Seriale corretto, programma correttamen"...
.text:00401D53 29C C7 04 24 00 00 00 00 mov dword ptr [esp], 0 ; hWnd







Make sure you don't overwrite the Call to MessageBoxA, as we'll be using it to pass the serial key as a parameter:




Now that the junk has been NOP'd out, let's begin by passing our values onto the stack. MessageBoxA requires the following parameters:
int WINAPI MessageBoxA(
__in_opt HWND hWnd,
__in_opt LPCTSTR lpText,
__in_opt LPCTSTR lpCaption,
__in UINT uType
);

So, uType can be NULL, lpCaption can be NULL, lpText must be a pointer to our generated serial buffer, and our HWND (window handle) may be NULL:

[esp] hWnd
[esp + 4] lpText
[esp + 8] lpCaption
[esp + 12] uType
Alright, now we must craft the instructions which will manipulate the stack and push the proper parameters. Be careful with this part: do not expand or shrink the size of the stack, do not modify any registers except eax (because MessageBox will return a value through eax) and do not overwrite any other instruction except the NOP pool we have.
So, what instructions do we need? well, the stack has already been adjust for the compiler (instruction sub @ 401cfc), so we don't need to push anything, instead, we just modify the values on the stack to suit MessageBoxA:
mov eax, [esp] ; Load pointer at top of the stack to eax register
mov DWORD PTR [esp], 0 ; Zero out our hWin parameter
mov DWORD PTR [esp + 8], 0 ; Set the Caption parameter to NULL
mov [esp + 4], eax ; Write our serial key pointer to as our lpText parameter
mov DWORD PTR [esp + c], 0 ; Set uType to NULL
So, your instructions should look like this:



Also, check that your stack parameters align with the requirements of MessageBoxA.




When you run the program, you will see a message box pops up with the serial key, regardless of what key you enter into the Key field!


Okay, so the final thing would be to commit changes to the program, you can do that by selecting the modified code and writing changes to exe.




Okay, this concludes the tutorial, I hope you learned something new. Try to understand as much as possible about this program, understand how the algorithm works, see if you can reverse it yourself.
My next tutorial will be about memory dumping and unpacking. Have fun!

Monday, January 31, 2011

SELinux - Users, Policies, Security Contexts, Roles

I introduced SELinux and it's generalized form in my previous blog post, and as promised wanted to touch base on more of the underlying functionality and setup of SELinux on standard 2.6 Kernels.

SELinux being that of a FLASK (Flux Advanced Security Kernel) implementation encompasses a wide array of MAC oriented policies, including but not limited to type enforcement, role-based access control and multilevel security, all of which were prototyped in the Fluke operating system.

First things first, recalling that a subject is typically a process or thread with its own set of security attributes and an object being that of typically constructs such as files, directories, TCP/UDP ports, shared memory segments also with its own set of security attributes, it's important to understand the association of three fundamental SELinux related attributes :

  1. Users
  2. Policies
  3. Security Contexts
 Without regard for the order inwhich they are listed above, it's easier to understand by demonstration of the security contexts, just how each SELinux attribute interacts with one another.

Before exploring the details of security contexts, it's important to note that many users are unfamiliar with the GNU 'ls' formatting structure, when for example using the 'l' option (long listing) combined with 'a', ie:

Take note of the trailing bit !  The additional trailing bit, is to mark the presence of an additional access method on the object.  A space representing the opposite scenario.

A '+' represents an ACL (Access Control List) association with the object, a '.' represents SElinux.

Back to SELinux !
 

"SELinux adds the -Z switch to the shell commands ls, ps, and some others, allowing the security context of the files or process to be seen." (Wikipedia)




The above screen shot outlines the security contexts of .bash_history, as prescribed by SELinux.  The security context consists of four fields: user, role, type and level.  All fields are required, except for the level.

User Field 
  • 'unconfined_u' in our example
  • Conventionally all default SELinux Users end with a "_u" except for root.
  • Consider this component a way of grouping 'roles'
  • Three typical users seen on a system are : user_u/unconfined_u, system_u and root
  • "user_u"/"unconfined_u" is the default SELinux User for a logged in user on a system
  • "system_u" is the default User for processes started during the boot up process
  • "root" is the SELinux user that you get when you login at the console as "root"
  • SELinux user differs from a convential Linux user in that a SELinux user "attribute" is binded to your login, regardless of let's say issuing a 'su' command.  In easier to understand terms, take for example linux user 'infolock', with an SELinux user associated attributed of "unconfined_u" as shown above.  "infolock" issues 'su' , yet, is still labelled "unconfined_u" by SELinux, and still under the "restrictions" of the security policies set forth by SELinux related to unconfined_u User.   SELinux login, handles the mapping of SELinux related users and standard linux uids.   Issuing 'semange login -l' will display the correlation in SELinux Login.

  • The first column denotes the typical linux uid and the second column being that of the SELinux user identity.  The last column is the MLS/MCS (Multi Level Security/Multi Category System) Range, discussed later in this post.
  • To better understand the mapping of linux uids to SELinux user identities, execute the following command 'semanage user -l' which outputs the definitions of the SELinux user identities.









Role Field

  • "This field is only really relevant on processes or domains. The role field on a file is always object_r, and really has no meaning other than as a place holder. On a process you would usually see a role like system_r or sysadm_r. Roles are used to group security types. So you can specify in policy which roles are able to execute which types. This is the basis of "Roles Based Access Control" (RBAC) in SELinux. RBAC is not really used in targeted policy, but becomes more important in Strict and MLS policy. MLS Policy also contains sysadm_r, staff_r, and secadm_r. Roles by convention end with a "_r". "(Fedora Project, wiki)
  • Roles are predefined in SELinux policy
  • SELinux Roles determine which process domains / object types can be accessed. All processes under SELinux run under a domain. A domain specifies what can be performed by processes while a type specifies who can access an object.

Type Field

  • "The 3rd component of the security context is the Type component, for example /usr/sbin/httpd is labeled with a type of “httpd_exec_t".
    In my opinion this is the most important field in the SELinux security context. This is the heart of SELinux Type Enforcement. Most of the policy rules in SELinux revolve around what subject types have what access to which object types. By convention this component always ends in a "_t". "(Fedora, Wiki)
Level Field

  • "The 4th component is the MLS, or Multilevel security, field which is not supported in RHEL4 or Fedora Core 4. It is first showing up with Fedora Core 5, although it has been in SELinux in the previous versions, it was never turned on.
    This component is used in all policies shipped with Fedora Core 5. On strict and targeted policies we refer to this as the MCS (Multi Category System) Field. Unfortunately this field can contain a ":". The syntax of this field can look something like s0-s15:c1,c2. But I will put off talking about this syntax until a later date. Most files by default are labeled s0, sometimes referred to as SystemLow. Fortunately SELinux provides a translation library (libsetrans) that replaces the codes in this field with a more human readable form. So something like s0:c1,c2 might be show up to the user as PatientRecord,CompanyConfidential. On a targeted or strict policy machine s0 translates to "", so almost all files will not even show the fourth field." (Fedora, Wiki)
     
Armed with your new understanding of SELinux and it's associated attributes (secutiy contexts, types, roles, levels and the likes) it's time to re-examine the commands we issued in the first blog post, to enable SELinux access to userdir apache settings.

Prior to executing the following commands :

#setsebool -P httpd_enable_homedirs 1
 &
#chcon -R -t httpd_sys_content_t ~user/public_html


We were still receiving 403 errors, when trying to access local documents via userdir directories.  So what have we done, through the execution of the two commands to change it ?

First !  setsebool ,

To change parts of the SELinux policy at runtime without having to reload a new policy, we manipulate the boolean values of specific daemons with respect to the SELinux policy.

"booleans - Policy booleans enable runtime customization of SELinux policy." (boolean(8))

in the 'setsebool' command above, we are using the option -P, which specifies that the value we are manipulating remain persistent across reboots. 

The boolean in this case is "httpd_enable_homedirs".   Allowing httpd to read home directories.  To determine what the current boolean settings are on your particular machine, provided you have SELinux installed and enforcing a policy run any of the following commands:

$getsebool -a
#semanage boolean -l
$getsebool httpd_enable_homedirs

The boolean value of 1 signifying 'on' and 0 signalling 'off'.

Next comes, chcon,

The chcon command changes the SELinux context for files. Keep in mind changes made with the chcon command do not survive a file system relabel, or the execution of the /sbin/restorecon command.  Essentially what we are doing here, is recursively (-R) changing the SELinux type (-t) association of all security contexts contained in '~user/public_html' to httpd_sys_content_t , which depending on the type of policy currently enforced, can be manipulated once again.

So there you have it, the truth about SELinux, how to properly configure Apache to work with USERDIRS and SELinux, and a bit of information related to the configuring of SELinux on the whole.

Hope it helped.

Expect more to come on the topic of SELinux.  Enjoyed writing this article.

~infolock

Sunday, January 30, 2011

For your viewing pleasure.....



Go confidently in the direction of your dreams.Live the life you have imagined.

~infolock

Apache USERDIR Access rights via SELinux (Fedora Core 12)

Today I set up Apache on my Fedora Core 12 x86_64 machine. To avoid the read of the underlying logic behind SELinux, feel free to browse this blogpost, noting only lines editted in bold.

The following article will detail the process of establishing your userdir setup on Fedora, without disabling SELinux.  Essentially rendering /~username/public_html directories available for localhost web development.  Good luck!

Initially, I ran:
$rpm -q httpd
to determine wether or not I had such services bundled with my installation.

The result:
httpd-2.2.15-1.fc12.2.x86_64

Perfect !  Time to set up permissions !

It's a hassle having to manage to /var/www/html as the directory default, when you don't want to have to develop via 'root'  so here are the steps I followed to setup USERDIR settings with special privileges for SELinux.

SELinux, as some of you may not know stands for 'Security-Enhanced Linux' and is a "security architecture integrated into the 2.6.x kernel using the Linux Security Modules (LSM)." ( Red Hat Enterprise Linux 5 Deployment Guide, ref-G)  It's development was a joint effort between the National Security Agency of the United States and Redhat.

To determine whether or not SELinux is enabled on your system, issue the following command:
$cat /etc/selinux/config

The SELINUX variable may be set to one of three options ('modes'):
  1. disabled
  2. permissive
  3. enforcing
As described below:


disabled
  • completely disabling the SELinux kernel and application code
permissive
  • enabling the SELinux code, with minimal restriction on access, however calls / requests are audited.
enforcing
  • enabling the SELinux code, enforcing access denials as well as audits.
You may have noticed another variable contained in the config file :

SELINUXTYPE

This post will not dive into the details of such configuration options with respect to SELinux, but I will touch base on the issue at a later date.  For more information regarding the variable SELINUXTYPE's configuration, reference either the man pages or search for SELinux policy types.

Back to the basics !

"Security-Enhanced Linux is a Flux Advanced Security Kernel (FLASK) implementation integrated in some versions of the Linux kernel with a number of utilities designed to demonstrate the value of mandatory access controls to the Linux community and how such controls could be added to Linux. Such a kernel contains architectural components prototyped in the Fluke operating system. These provide general support for enforcing many kinds of mandatory access control policies, including those based on the concepts of type enforcement, role-based access control, and multilevel security. FLASK, in turn, was based on DTOS, a Mach-derived Distributed Trusted Operating System, as well as Trusted Mach, a research project from Trusted Information Systems that was influential in the design and implementation of DTOS." (Wikipedia)

To better understand the technology behind SELinux, one must first grasp the concepts of DAC (Discretionary Access Control).  The typical access layer found on linux distributions.

Essentially DAC "is a kind of access control defined by the Trusted Computer System Evaluation Criteria[1] "as a means of restricting access to objects based on the identity of subjects and/or groups to which they belong.". (Wikipedia)

To further help you understand, the following is a result of :
$ ls -al /var/www



The object 'usage' has the following permissions:
drwx:r-x:r-x


  • The 'd' specifying 'directory.
  • The following three characters (rwx) representing the access privileges for the owner, in this case 'webalizer'.  Read, Write, and eXecute respectively. 
  • Following that, we see, (r-x).  These permissions correspond to the assigned group of which the object is associated.  In this case 'root'.  We see that such a group, has the following permissions:  Read and eXecute.
  • The three trailing permission bits are associated with 'others' but can be thought of as 'everyone' , whom are granted both Read and eXecute permissions.  

"The term DAC is commonly used in contexts that assume that every object has an owner that controls the permissions to access the object, probably because many systems do implement DAC using the concept of an owner. But the TCSEC definition does not say anything about owners, so technically an access control system doesn't have to have a concept of owner to meet the TCSEC definition of DAC.
Users (owners) have under this DAC implementation the ability to make policy decisions and/or assign security attributes. A straightforward example is the traditional Unix permissions with its system of users, groups and read-write-execute permissions for objects (ie. files and directories)." (Wikipedia)
So that is DAC !  Now you know, but just when you thought you had that digested, there is more.

Bring in MAC !

No, not Macintosh.  Mandatory Access Control of course !

Before I begin with the formal introductions, it may be best to familiarize yourself with the following definitions.  As you will soon see, they tie in nicely when deciphering the logic behind access control.


subject a.k.a initiator
  • usually a process or thread with its own set of security attributes
object a.k.a target
  • typically constructs such as files, directories, TCP/UDP ports, shared memory segments also with its own set of security attributes
Onto the introductions ...

 "Whenever a subject attempts to access an object, an authorization rule enforced by the operating system kernel examines these security attributes and decides whether the access can take place. Any operation by any subject on any object will be tested against the set of authorization rules (aka policy) to determine if the operation is allowed." (Wikipedia)

In contrast to DAC which allows users to manage authorization rules and or assign security attributes, MAC is governed by a "central" security policy administrator, who controls the implementation of organization-wide security policies, of which can not be manipulated by users. 

It would seem at this point from analysis, that the two are somewhat polar opposites of one another.  Why on earth would you need to know about MAC if a typical distribution delivers DAC!  Well, SELinux, the overall focus of this blog post builds an access layer on top of DAC, guess it's classification if you want to call it that.  That's right MAC.


"On the other hand, systems can be said to implement both MAC and DAC simultaneously, where DAC refers to one category of access controls that subjects can transfer among each other, and MAC refers to a second category of access controls that imposes constraints upon the first." (Wikipedia)

"From a puristic perspective, SELinux provides a hybrid of concepts and capabilities drawn from mandatory access controls, mandatory integrity controls, role-based access control (RBAC), and type enforcement architecture. Third-party tools enable one to build a variety of security policies." (Wikipedia)


A generalized breakdown of the SELinux "architecture" is as follows, when investigating the process of object access requests:

  1. Subject attempts to access object.
  2. Subject must first pass DAC authentication.
  3. Upon clearance of DAC, MAC steps in.
  4. The subject sends an action request to the SELinux Security Server, a.k.a. the policy enforcement server.
  5. The policy enforcement server references the SELinux Policy Database via AVC (Access Vector Cache) or Security Context Matrix to verify policy permissions on the requested object.
  6. The server will either grant permission to the object based on policy or deny and log the attempt.
Now that most of the formal introductions with respect to SELinux, FLASK, MAC and DAC are out of the way, it's time to get back to the goal of the topic!

Having identified SELinux was setup and enforcing the access control policies in co ordinance with the kernel, it was no longer a mystery after having configured my httpd.conf file like so:

#vim /etc/httpd/conf/httpd.conf



Take note of the commented text apparent in the clause about enabling UserDir permissions!

The following commands, were then to follow:

#chmod 711 /home/user
  • Don't forget to replace 'user' with the name of the account you would like to develop on !
Create the public_html directory in your /home/user directory.

$mkdir public_html

Set the permissions !

$chmod 755 public_html

For those with SELinux disabled, this would be all that would be required.  You should be able to successfully navigate your browse to "localhost/~user/" and pull the default (index.html file) from the directory, provided you have created it !

But for those of us with SELinux enabled and enforcing the policy rules, a few more steps remain!


#setsebool -P httpd_enable_homedirs 1


#chcon -R -t httpd_sys_content_t ~user/public_html
  • Don't forget to replace 'user' with the account you used in the above steps!
A rather gentle restart of the services via :

#service httpd restart

And you should be on your way to developing local sites via your userdir!

Now that's great and all, but after having read a short novel about the logic behind SELinux, I have failed to answer a question on many of your minds.  That being, what exactly did the two commands above, have to do with configuring SELinux ?

Check out my next blog post, where I'll detail the users, policies and security contexts of SELinux, which will help clarify just what permission bits were set, and help you build a solid foundation of SELinux on the whole.

Hope it helped!  Keep the information free !



~infolock