Saturday, 16 August 2014

PHP & MySQL basic

CREATE DATABASE ijdb;
DROP DATABASE ijdb;

CREATE TABLE joke (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    jokeText TEXT,
    jokeDate DATE NOT NULL
) DEFAULT CHARACTER SET utf8;

SHOW TABLES;
DESCRIBE joke;
DROP TABLE joke;


INSERT INTO joke SET
joketext = "Why did the chicken cross the road? To get to the other side!",
jokedate = "2011-04-01";

INSERT INTO joke
(joketext, jokedate)
VALUES (
"Why did the chicken cross the road? To get to the other side!",
"2011-04-01"
);


SELECT * FROM joke;
SELECT id, jokedate from joke;
SELECT id, LEFT(joketext, 20), jokedate FROM joke; - LEFT , lets us tell MySQL to display a column’s contents up to a specified maximum number of characters.
SELECT COUNT(*) FROM joke; - COUNT , which lets us count the number of results returned.
SELECT COUNT(*) FROM joke WHERE jokedate >= "2011-01-01";
SELECT joketext FROM joke WHERE joketext LIKE "%chicken%";

SELECT joketext FROM joke WHERE
joketext LIKE "%knock%" AND
jokedate >= "2011-04-01" AND
jokedate < "2011-05-01";


UPDATE joke SET jokedate = "2011-04-01"
WHERE joketext LIKE "%chicken%";

DELETE FROM tableName WHERE conditions;
DELETE FROM tableName WHERE conditions;


PHP
-----------
$var1 = 'PHP';
echo "$var1 rules!";    // Outputs 'PHP rules!'
echo '$var1 rules!';    // Outputs '$var1 rules!'
ou can include the name of a variable right inside a text string, and have the value inserted in its place if you surround the string with double quotes instead of single quotes. This process of converting variable names to their values is known as variable interpolation. However, as the last line demonstrates, a string surrounded with single quotes will not interpolate the variable names it contains.



$myarray = array('one', 2, '3');
echo $myarray[0];       // Outputs 'one'
echo $myarray[1];       // Outputs '2'
echo $myarray[2];       // Outputs '3'

$myarray[1] = 'two';    // Assign a new value
$myarray[3] = 'four';   // Create a new element

$myarray[] = 'the fifth element';
echo $myarray[4];       // Outputs 'the fifth element'


$birthdays['Kevin'] = '1978-04-12';
$birthdays['Stephanie'] = '1980-05-16';
$birthdays['David'] = '1983-09-09';



htmlspecialchars($firstname, ENT_QUOTES, 'utf-8')

----------------------------------
For documentation - php.net/date (for eg); dev.mysql.com (click on Developer zone);

-----------------------------------

Connecting to MySQL database from PHP
------------
Need a user account for php. Go to phpMyAdmin, select a database, click on Priviledge. Add user.

<?php

$link = mysqli_connect('localhost', 'ijdbuser', 'mypassword');
if (!$link)
{
$output = "Unable to connect to the database server";
include 'output.html.php';
exit();
}

if (!mysqli_set_charset($link, 'utf8'))
{
$output = "Unable to set  database connection encoding";
include 'output.html.php';
exit();
}

if (!mysqli_select_db($link, 'ijdb'))
{
$output = 'Unable to locate joke database';
include 'output.html.php';
exit();
}

$output = 'Database connection established';
include 'output.html.php';

?>

SQL Join
Select * From joke INNER JOIN author on authorid = author.id

File List

PHP-L3S4-Variables,Operators.pdf
PHP-L3S5-Arrays.pdf
PHP-L3S6-PassingVariablesInLinks.pdf
PHP-L3S8-PassingVariablesInForms.pdf
PHP-L4S3-ConditionalStatements.pdf
PHP-L4S4-Loops.pdf
PHP-L4S7-ControllerAndTemplates.pdf
PHP-L6S5-SendingSqlQueries with PHP.pdf
PHP-L6S6-Handling SELECT Resultset.pdf
PHP-L7S3-Inserting Data Into Database.pdf
PHP-L7S4-Deleting Data from Database.pdf
PHP-L11S4-Types Of Includes.pdf
PHP-L11S6-Variable Scope&Global Access.pdf

sample codes.zip


Monday, 11 August 2014

Linux Baisc Commands

Linux commands are case sensitive.

cat <filename> (print/display the text in file)

$PATH is a variable that tells shell where to look for specific command
echo $PATH

which (show where this command path is)

To run 2 commands together
echo $a;$b
ls;ls 

history (command history that typed in)

ls --help (To get help about a command)

man <command> (display manual)
man -k <command> (search for that command as keyword in other commands)

info (same/more info than man)

whatis <command> (displays brief description of the command)
whereis <command> (displays location of the command)

less (read text files page by page, even it's zipped)

Working with directories

pwd (present working directory)
cd -absolute path or -relative path
cd ~ (bring back to current user's home directory)
cd . and cd ..

ls -l (optional folder name) (displays file list with rights); line starts with - is a file while starting with d is a directory)
ls -R (recursive, list all files within current directory and within sub-directories)
ls -a (list all files including hidden files (those files start with .)
ls -al


mv <source> <destination>
cp <source file> <destination file>
cp -R <source folder> <destination folder>
rm <file name>
rmdir <folder name> (the contents of the folder must be empty first rm *)
rm -rf <name> (force remove recursively)


/etc     - system wide config files
/lib      - linked library files used by binaries in /bin and /usr/bin
/usr/lib -linked library files used by binaries in /bin and /usr/bin
/var/log - log files

syslog   - program that manages storage of logs for daemons on the system
Klog     - logs Kernel specific messages
dmesg   - used to view kernel messages

Checking CPU and Memory
free -tom
top

IP, DNS, etc
/etc/resolv.conf (where current DNS server info is stored)
ifconfig
route
dig

Users and Groups
standard, root, system users

id - info about a user
w - what users logged in are doing
who - who is logged in
sudo - do command with root privledges

/etc/passwd
/etc/group
System accounts usually/generally have low user ID numbers.

useradd - add uer
groupadd - add group
last - show recent logsin
passwd - change passwords
usermod - change aspects of existing user
userdel - delete user
groupdel - delete group
eg. sudo usermod -a -G pineGroup patrick
     sudo usermod -a -G sudo patrick

/etc/passwd  - user info
/etc/shadow  - user passwords
/etc/group  - group info

File Permission and Ownership
user group other (ugo)
chmod ugo -w file (remove write permission from everyone)
chmod go -w file (remove write permission from group, other)
chmod o +x file (add execute permission to other)
chmod 555 file (change the permission using number instead of letters)
sudo chown spowers:pirate gold.txt (change ownership to spowers (user), pirate (group))

If a person has a write access to a folder, he can also delete anything in that folder.
To prevent people from erasing each other's files in public folder like /tmp,
chmod o+t folder (sets sticky bit,only user can delete the file)
chmod 1777 folder (sets sticky bit,only user can delete the file)

Special Directories and Files
ln -s source-file sybolic-file  - Symbolic link 


/tmp  - short term storage, get erased on boot
/var/tmp  -  same, but doesn't get deleted
/var/  - files that change often (mail, logs, etc)


Monday, 23 June 2014

Access Control - Authorization

Physical or logical location can also be used to restrict access to resources. Some files may be available only to users who can log on interactively to a computer. This means the user must be physically at the computer.

Default to No Access -  all access controls should be based on the concept of starting with zero access, and building on top of that.

Authorization Creep - As employees work at a company over time and move from one department to another, they often are assigned more and more access rights and permissions.

Kerberos

Kerberos is an example of a single sign-on system for distributed environments, and is a de facto standard for heterogeneous networks.Kerberos uses symmetric key cryptography and provides end-to-end security. Although it allows the use of passwords for authentication, it was designed specifically to eliminate the need to transmit passwords over the network. Most Kerberos implementations work with shared secret keys.

Main Components in Kerberos
Key Distribution Center (KDC) is the most important component within a Kerberos environment and it holds all users’ and services’ secret keys. It provides an authentication service, as well as key distribution  functionality. The clients and services trust the integrity of the KDC, and this trust is the foundation of Kerberos security.The KDC provides security services to principals, which can be users, applications, or network services. The KDC must have an account for, and share a secret key with, each principal(for users,it's password).

A ticket is generated by the ticket granting service (TGS) on the KDC and given to a principal when that principal, let’s say a user, needs to authenticate to another principal, let’s say a print server. The ticket enables one principal to authenticate to another
principal.

A KDC provides security services for a set of principals. This set is called a realm in Kerberos. The KDC is the trusted authentication server for all users, applications, and services within a realm. One KDC can be responsible for one realm or several realms. Realms are used to allow an administrator to logically group resources and users.

The Kerberos Authentication Process
The user and the KDC share a secret key, while the service and the KDC share a different secret key. The user and the requested service do not share a symmetric key in the beginning. The user trusts the KDC because they share a secret key. They can encrypt and decrypt data they pass between each other, and thus have a protected communication path. Once the user authenticates to the service, they, too, will share a symmetric key (session key) that is used for authentication purposes.

Be sure you understand that a session key is different from a secret key. A secret key is shared between the KDC and a principal and is static in nature. A session key is shared between two principals and is generated when needed and destroyed after the session is completed.



Security Domains - A domain is a set of resources available to a subject. A security domain is where resources within this logical structure (domain) are working under the same security policy and managed by the same group.

Directory Services - A network service is a mechanism that identifies resources (printers, file servers, domain controllers, and peripheral devices) on a network. A network directory service contains information about these different resources, and the subjects that need to access them, and carries out access control activities. Network directory services provide users access to network resources transparently, meaning that users don’t need to know the exact location of the resources or the steps required to access them. The network directory services handle these issues for the user in the background. Some examples of directory services are Lightweight Directory Access Protocol (LDAP), Novell NetWare Directory Service (NDS), and Microsoft Active Directory (AD).

Examples of Single Sign-On Technologies
• Kerberos - Authentication protocol that uses a KDC and tickets, and is based on symmetric key cryptography
• SESAME - Authentication protocol that uses a PAS and PACs, and is based on symmetric and asymmetric cryptography
• Security domains - Resources working under the same security policy and managed by the same group
• Directory services - Technology that allows resources to be named in a standardized manner and access control to be maintained centrally
• Thin clients Terminals that rely upon a central server for access control, processing, and storage

Access Control Models

An access control model is a framework that dictates how subjects access objects. There are three main types of access control models: discretionary, mandatory, and role based.

Discretionary Access Control - A system that uses discretionary access control (DAC) enables the owner of the resource to specify which subjects can access specific resources. This model is called discretionary because the control of access is based on the discretion of the owner.

Nondiscretionary Access Control states that access decisions are not made at the discretion of the user. Nondiscretionary access controls are put into place by an authoritative entity (usually a security administrator) with the goal of protecting the organization’s most critical assets.

Mandatory Access Control - In a mandatory access control (MAC) model, users do not have the discretion of determining who can access objects as in a DAC model. MAC model is much more structured and strict than the DAC model and is based on a security label system. Users are given a security clearance (secret, top secret,confidential, and so on), and data is classified in the same way. The clearance and classification data are stored in the security labels, which are bound to the specific subjects and objects. When the system makes a decision about fulfilling a request to access an object, it is based on the clearance of the subject, the classification of the object, and the
security policy of the system. The rules for how subjects access objects are made by the organization’s security policy, configured by the security administrator, enforced by the operating system, and supported by security technologies.

While MAC systems might seem an answer to all our security prayers, they have very limited user functionality, require a lot of administrative overhead, are very expensive, and are not user-friendly. DAC systems are general-purpose computers, while MAC systems serve a very specific purpose.

Role-Based Access Control
A role-based access control (RBAC) model uses a centrally administrated set of controls to determine how subjects and objects interact. The access control levels can be based upon the necessary operations and tasks a user needs to carry out to fulfill her
responsibilities without an organization. In an RBAC model, a role is defined in terms of the operations and tasks the role
will carry out, whereas a DAC model outlines which subjects can access what objects based upon the individual user identity.

An RBAC model is the best system for a company that has high employee turnover.

Access Control Models
The main characteristics of the three different access control models are important to understand.
• DAC  Data owners decide who has access to resources, and ACLs are used to enforce these access decisions.
• MAC  Operating systems enforce the system’s security policy through the use of security labels.
• RBAC  Access decisions are based on each subject’s role and/or functional position.

Access Control Matrix

An access control matrix is a table of subjects and objects indicating what actions individual subjects can take upon individual objects.

Capability Table specifies the access rights a certain subject possesses pertaining to specific objects. A capability table is different from an ACL because the subject is bound to the capability table, whereas the object is bound to the ACL.

Access Control Lists (ACLs) are used in several operating systems, applications, and router configurations. They are lists of subjects that are authorized to access a specific object, and they define what level of authorization is granted.

Content-Dependent Access Control - with content-dependent access control, access to objects is determined by the content within the object. Eg. email filer, web filter.

Context-Dependent Access Control - Context-dependent access control differs from content-dependent access control in that it makes access decisions based on the context of a collection of information rather than on the sensitivity of the data.A system that is using context-dependent access control “reviews the situation” and then makes a decision. For example, firewalls make context-based access decisions when they collect state information on a packet before allowing it into the network.

Access Control Administration


Access Control - Authentication

Access controls are security features that control how users and systems communicate and interact with other systems and resources. Access is the flow of information between a subject and an object.

Identification describes a method of ensuring that a subject (user, program, or process) is the entity it claims to be. Identification can be provided with the use of a username or account number.

A race condition is when processes carry out their tasks on a shared resource in an incorrect order. A race condition is possible when two or more processes use a shared resource, as in data within a variable. It is important that the processes carry out their functionality in the correct sequence.

Identification and Authentication

Three general factors can be used for authentication: something a person knows, something a person has, and something a person is. They are also commonly called authentication by knowledge, authentication by ownership, and authentication by characteristic.
Strong authentication contains two out of these three methods: something a person knows, has, or is.This is also referred to as two-factor authentication.
Creating or issuing secure identities should include three key aspects: uniqueness, nondescriptive, and issuance.

Identity management solutions and products
•  Directories
•  Web access management
•  Password management
•  Legacy single sign-on
•  Account management
•  Profile update

Directories

The objects within the directory are managed by a directory service. The directory service allows an administrator to configure and manage how identification, authentication, authorization, and access control take place within the network and on individual systems.

A meta-directory gathers the necessary information from multiple sources and stores it in one central directory. A virtual directory plays the same role and can be used instead of a meta-directory. The difference between the two is that the meta-directory physically has the identity data in its directory, whereas a virtual directory does not and points to where the actual data reside.

Web Access Management

Web access management(WAM) software controls what users can access when using a web browser to interact with web-based enterprise assets.
WAM tools usually also provide a single sign-on capability so that once a user is authenticated at a web site, she can access different web-based applications and resources without having to log in multiple times. It does that by sending a cookie to the user's web browser and that cookie indicates she has authenticated properly and the type of access she should be allowed. When a product provides a single sign-on capability in a web environment, the product must keep track of the user’s authentication state and security context as the user moves from one resource to the next.

Account Management 

Account management deals with creating user accounts on all systems, modifying the account privileges when necessary, and decommissioning the accounts when they are no longer needed. by implementing a workflow process.


These different technologies work together to provide an organization with streamlined IdM. Directories are built to contain user and resource information. A metadata directory pulls identity information that resides in different places within the network to allow IdM processes to only have to get the needed data for their tasks from this one location. User management tools allow for automated control of user identities through their lifetimes and can provide provisioning. A password management tool is in place so that productivity is not slowed down by a forgotten password. A single sign-on technology requires internal users to only authenticate once for enterprise access. Web access management tools provide a single sign-on
service to external users and control access to web-based resources.


Access Control and Markup Languages

The Service Provisioning Markup Language (SPML) allows for the exchange of provisioning data between applications, which could reside in one organization or many. SPML allows for all these accounts to be set up and managed simultaneously across
the various systems and applications. SPML is made up of three main entities: the Requesting Authority (RA), which is the entity that is making the request to set up a new account  or  make  changes  to  an  existing  account;  the  Provisioning  Service  Provider (PSP), which is the software that responds to the account requests; and the Provisioning Service Target (PST), which is the entity that carries out the provisioning activities on the requested system.

When there is a need to allow a user to log in one time and gain access to different and separate web-based applications, the actual authentication data have to be shared between the systems maintaining those web applications securely and in a standardized manner. This is the role that the Security Assertion Markup Language (SAML) plays.

Transmission of SAML data can take place over different protocol types, but a common one is Simple Object Access Protocol (SOAP). SOAP is a specification that outlines how information pertaining to web services is exchanged in a structured manner.

The use of web services in this manner also allows for organizations to provide service oriented architecture (SOA) environments. An SOA is a way to provide independent services residing on different systems in different business domains in one consistent manner. For example, if your company has a web portal that allows you to access the company’s CRM, an employee directory, and a help-desk ticketing application, this is most likely being provided through an SOA.

Biometrics

Biometrics verifies an individual’s identity by analyzing a unique personal attribute or behavior, which is one of the most effective and accurate methods of verifying identification. Biometrics is typically broken up into two different categories - physiological( physical attributes unique to a specific individual,eg.fingerprint) and behavioral( characteristic of an individual to confirm his identity,eg.signature dynamics). Physiological is “what you are” and behavioral is “what you do.”

When comparing different biometric systems, many different variables are used, but one of the most important metrics is the crossover error rate (CER). This rating is stated as a percentage and represents the point at which the false rejection rate equals the false acceptance rate. This rating is the most important measurement when determining the system’s accuracy. A biometric system that delivers a CER of 3 will be more accurate than a system that delivers a CER of 4.Crossover error rate (CER) is also called equal error rate (EER).

Signature Dynamics - When a person signs a signature, usually they do so in the same manner and speed each time. Signing a signature produces electrical signals that can be captured by a biometric system. Other behavioral based verifications are Keystroke Dynamics, Voice Print, Facial Scan, Hand Topography.

Password and Password Management

Certain techniques can be implemented to provide another layer of security for passwords and their use. After each successful logon, a message can be presented to a user indicating the date and time of the last successful logon, the location of this logon, and whether there were any unsuccessful logon attempts.

The Token Device

The token device, or password generator, is usually a handheld device that has an LCD display and possibly a keypad. This hardware is separate from the computer the user is attempting to access. The token device and authentication service must be synchronized in some manner to be able to authenticate a user.

Synchronous  
A synchronous token device synchronizes with the authentication service by using time or a counter as the core piece of the authentication process. If the synchronization is time-based, the token device and the authentication service must
hold the same time within their internal clocks. The time value on the token device and a secret key are used to create the one-time password, which is displayed to the user. The user enters this value and a user ID into the computer, which then passes them to the server running the authentication service. The authentication service decrypts this value and compares it to the value it expected. If the two match, the user is authenticated and allowed to use the computer and resources

If the token device and authentication service use counter-synchronization, the user will need to initiate the creation of the one-time password by pushing a button on the token device. This causes the token device and the authentication service to advance to the next authentication value. This value and a base secret are hashed and displayed to the user. The user enters this resulting value along with a user ID to be authenticated. In either  time-  or  counter-based  synchronization,  the  token  device  and  authentication service must share the same secret base key used for encryption and decryption.Also called event-based.

Asynchronous
 A  token  device  using  an  asynchronous  token–generating  method employs a challenge/response scheme to authenticate the user. In this situation, the authentication server sends the user a challenge, a random value, also called a nonce. The user enters this random value into the token device, which encrypts it and returns a value the user uses as a one-time password. The user sends this value, along with a username, to the authentication server. If the authentication server can decrypt the value and it is the same challenge value sent earlier, the user is authenticated.Eg. Like when we add a new payee account in iBanking.

Asynchronous is based on challenge/response mechanisms, while synchronous is based on time or counter-driven mechanisms.This type of system is not vulnerable to electronic eavesdropping, sniffing, or password guessing.One-time passwords can also be generated in software called soft token, in which case a piece of hardware such as a token device is not required.


Cryptographic Keys
A digital signature could be used in place of a password. Passwords are the weakest form of authentication and can be easily sniffed as they travel over a network. Digital signatures are forms of authentication used in environments that require higher security protection than what is provided by passwords.

A digital signature is a technology that uses a private key to encrypt a hash value (message digest). The act of encrypting this hash value with a private key is called digitally signing a message. A digital signature attached to a message proves the message originated from a specific source.

Memory Cards and Smart cards
The main difference between memory cards and smart cards is their capacity to process information. A memory card holds information but cannot process information. A smart card holds information and has the necessary hardware and software to actually process that information. Eg. memory card is a swipe card that must be used for an individual to be able to enter a
building.

Wireshark Notes

Wireshark Notes

segment - layer 4
packet- layer 3
frame - layer 2
tcp stream index to find specific tcp stream
conversation filter could do the same.
Follow TCP stream
Statistic--> conversation = summary of capture files..Can be used to find out toptalkers, etc.
HTTP response times (request-response)

Should take a baseline of the network.

-----------------------

Regular expression
[xy] means anything inside x or y;(?!)means following is case sensitive
"[aA][bB][cC]"" or "(?!)abc"  --> string abc case insensitive

| means or
"(?!)(abc|xyz)? --> abc or xyz case insensitive

. wildcard means any single character
"(?!)(a.c|x..)" --> aSOMETHINGc or xSOMETHINGSOMETHING

{x,y} previous character before bracket can be repeated x to y times
"(?!)(cbt.{5,7}s)"--> cbtnuggets

---------------------------

IO output to see amount of packets/throughput using display filter in the captured file
Expert info -
Extract http-images, ftp files from the trace.

Monday, 28 April 2014

No IP Redirect, No IP Unreachable, No IP proxy-arp, No IP route-cache



no ip redirects--this disables icmp redirect messages. Redirects happen when a router recognizes a packet arriving on an interface and the best route is out that same interface. In that case the router sends an icmp redirect back to the source telling them about a better router on the same subnet. Subsequent packets take the optimal path. If you disable this, the packets would have continued using the sub optimal path (in this scenario).

no ip unreachable--disable icmp type 3 generation. Can wreak havoc if an egress port has a lower mtu. This is because icmp "packet to big fragment needed" is type 3 code 4.

no ip proxy-arp--proxy arp allows the router to respond to any arp request that is out another interface according to the route table. Disabling this makes the router only respond to arps to the interface ip address.

no ip route-cache--process switches ip packets. Mostly useful only with debug ip packet.


Wednesday, 16 April 2014

GNS3 - Distributed Dynamips

Configuring Distributed Dynamips for GNS3

Machine A - mainly run Dynamips. Chose Linux (Ubuntu) as it better handles Dynamips. IP address - 192.168.1.20
Machine B - mainly run GNS3. It uses Machine A's resources for Dynamips. Of course, Machine B can have its own local Dynamips instance to handle additional load if necessary. Chose windows as it is the main device to interact with the engineer. IP address - 192.168.1.224

Machine A Setup

    1.  To install GNS3 in Ubuntu, go to Ubuntu Software Center and search gns3 to install.


    2.  After installation, we can know the location of gns3 and dynamips by using which command.

    3.  Start GNS3 by using sudo /usr/bin/gns3. Go to Preferences and take note of Dynamips Base port number and test the settings to make sure it can run properly.

    4.  Copy the IOS images to the folder - /home/images/ in this case.\

Machine B Setup

  1. Go to GNS3 Preferences->Dynamips and choose a different base port (e.g. 7201). Test the settings if it's successful.


    2.  We might need to change IP/host binding in Hypervisor Manager as below.

    3.  Go to IOS imanges and hypervisors->External hypervisors. Here we need to add Machine A as external hypervisor with default port and Base UDP port.

    4.  We also add Machine B (local machine) as external hypervisor as well with different port and Base UDP.

    5.  Next, we add IOS images from Machine A. Be sure to key in exact path of image on Machine A. Select an external hypervisor as 192.168.1.20 - its IP address.

    6.  We can add IOS images from Machine B if we also want to use this GNS3 machine for dynamips. Select an external hypervisor as 192.168.1.224 - its IP address.

Running the pieces together

    1.  Before we add devices in GNS3, we need to start Dynaimps on Machine B and also Machine A. 

    2.  On Machine B, start Dynaimps by issuing sudo /usr/bin/dynamips -H 7200 as shown below.

    3.  On Machine A, go to GNS3 installation folder - C:\Program Files\GNS3 and edit dynamips-start.cmd to run on 7201. Start dynaimps and Dynamips will run as below.

    4.  In GNS3, add the router and it will ask you which image you want to use. You can choose either images from 192.168.1.20 or 192.168.1.224

    5.  Add the routers using images from both machines and test the inter-connectivity from the routers.

That's it.